@earendil-works/pi-ai 1.4.0 → 1.5.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 (318) hide show
  1. package/README.md +58 -39
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +282 -87
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  6. package/dist/api/azure-openai-responses.js +1 -7
  7. package/dist/api/azure-openai-responses.js.map +1 -1
  8. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  9. package/dist/api/bedrock-converse-stream.js +127 -103
  10. package/dist/api/bedrock-converse-stream.js.map +1 -1
  11. package/dist/api/bedrock-converse-stream.lazy.d.ts +7 -0
  12. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -1
  13. package/dist/api/bedrock-converse-stream.lazy.js +18 -5
  14. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
  15. package/dist/api/constrained-sampling.d.ts +13 -1
  16. package/dist/api/constrained-sampling.d.ts.map +1 -1
  17. package/dist/api/constrained-sampling.js +38 -18
  18. package/dist/api/constrained-sampling.js.map +1 -1
  19. package/dist/api/google-generative-ai.d.ts.map +1 -1
  20. package/dist/api/google-generative-ai.js +0 -6
  21. package/dist/api/google-generative-ai.js.map +1 -1
  22. package/dist/api/google-shared.d.ts +2 -1
  23. package/dist/api/google-shared.d.ts.map +1 -1
  24. package/dist/api/google-shared.js +57 -2
  25. package/dist/api/google-shared.js.map +1 -1
  26. package/dist/api/google-vertex.d.ts.map +1 -1
  27. package/dist/api/google-vertex.js +0 -6
  28. package/dist/api/google-vertex.js.map +1 -1
  29. package/dist/api/lazy.d.ts +1 -1
  30. package/dist/api/lazy.d.ts.map +1 -1
  31. package/dist/api/lazy.js +9 -8
  32. package/dist/api/lazy.js.map +1 -1
  33. package/dist/api/mistral-conversations.d.ts.map +1 -1
  34. package/dist/api/mistral-conversations.js +17 -44
  35. package/dist/api/mistral-conversations.js.map +1 -1
  36. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  37. package/dist/api/openai-codex-responses.js +7 -8
  38. package/dist/api/openai-codex-responses.js.map +1 -1
  39. package/dist/api/openai-completions.d.ts +2 -1
  40. package/dist/api/openai-completions.d.ts.map +1 -1
  41. package/dist/api/openai-completions.js +55 -59
  42. package/dist/api/openai-completions.js.map +1 -1
  43. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  44. package/dist/api/openai-responses-shared.js +58 -57
  45. package/dist/api/openai-responses-shared.js.map +1 -1
  46. package/dist/api/openai-responses.d.ts.map +1 -1
  47. package/dist/api/openai-responses.js +4 -8
  48. package/dist/api/openai-responses.js.map +1 -1
  49. package/dist/api/openrouter-images.js +1 -0
  50. package/dist/api/openrouter-images.js.map +1 -1
  51. package/dist/api/pi-messages.d.ts +2 -0
  52. package/dist/api/pi-messages.d.ts.map +1 -1
  53. package/dist/api/pi-messages.js +24 -9
  54. package/dist/api/pi-messages.js.map +1 -1
  55. package/dist/api/simple-options.d.ts +1 -0
  56. package/dist/api/simple-options.d.ts.map +1 -1
  57. package/dist/api/simple-options.js +16 -2
  58. package/dist/api/simple-options.js.map +1 -1
  59. package/dist/api/strict-tool-limits.d.ts +13 -0
  60. package/dist/api/strict-tool-limits.d.ts.map +1 -0
  61. package/dist/api/strict-tool-limits.js +50 -0
  62. package/dist/api/strict-tool-limits.js.map +1 -0
  63. package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
  64. package/dist/auth/oauth/github-copilot.js +4 -11
  65. package/dist/auth/oauth/github-copilot.js.map +1 -1
  66. package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  67. package/dist/auth/oauth/kimi-coding.js +4 -22
  68. package/dist/auth/oauth/kimi-coding.js.map +1 -1
  69. package/dist/auth/oauth/load.d.ts.map +1 -1
  70. package/dist/auth/oauth/load.js +5 -2
  71. package/dist/auth/oauth/load.js.map +1 -1
  72. package/dist/auth/oauth/meta.d.ts.map +1 -1
  73. package/dist/auth/oauth/meta.js +1 -14
  74. package/dist/auth/oauth/meta.js.map +1 -1
  75. package/dist/auth/oauth/radius.d.ts.map +1 -1
  76. package/dist/auth/oauth/radius.js +9 -3
  77. package/dist/auth/oauth/radius.js.map +1 -1
  78. package/dist/auth/oauth/trusted-url.d.ts +7 -0
  79. package/dist/auth/oauth/trusted-url.d.ts.map +1 -0
  80. package/dist/auth/oauth/trusted-url.js +12 -0
  81. package/dist/auth/oauth/trusted-url.js.map +1 -0
  82. package/dist/auth/types.d.ts +4 -0
  83. package/dist/auth/types.d.ts.map +1 -1
  84. package/dist/auth/types.js.map +1 -1
  85. package/dist/cache-warming.d.ts +53 -0
  86. package/dist/cache-warming.d.ts.map +1 -0
  87. package/dist/cache-warming.js +82 -0
  88. package/dist/cache-warming.js.map +1 -0
  89. package/dist/cli.js +6 -2
  90. package/dist/cli.js.map +1 -1
  91. package/dist/compat/extension-oauth-types.d.ts +4 -0
  92. package/dist/compat/extension-oauth-types.d.ts.map +1 -1
  93. package/dist/compat/extension-oauth-types.js.map +1 -1
  94. package/dist/env-api-keys.d.ts.map +1 -1
  95. package/dist/env-api-keys.js +1 -0
  96. package/dist/env-api-keys.js.map +1 -1
  97. package/dist/index.d.ts +3 -3
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +3 -2
  100. package/dist/index.js.map +1 -1
  101. package/dist/lazy-bedrock-provider.d.ts +10 -0
  102. package/dist/lazy-bedrock-provider.d.ts.map +1 -0
  103. package/dist/lazy-bedrock-provider.js +13 -0
  104. package/dist/lazy-bedrock-provider.js.map +1 -0
  105. package/dist/lazy-oauth.d.ts +10 -0
  106. package/dist/lazy-oauth.d.ts.map +1 -0
  107. package/dist/lazy-oauth.js +23 -0
  108. package/dist/lazy-oauth.js.map +1 -0
  109. package/dist/models.d.ts +7 -0
  110. package/dist/models.d.ts.map +1 -1
  111. package/dist/models.generated.d.ts +4 -0
  112. package/dist/models.generated.d.ts.map +1 -1
  113. package/dist/models.generated.js +5 -1
  114. package/dist/models.generated.js.map +1 -1
  115. package/dist/models.js +20 -11
  116. package/dist/models.js.map +1 -1
  117. package/dist/providers/all.d.ts.map +1 -1
  118. package/dist/providers/all.js +2 -0
  119. package/dist/providers/all.js.map +1 -1
  120. package/dist/providers/amazon-bedrock.models.js +1 -1
  121. package/dist/providers/amazon-bedrock.models.js.map +1 -1
  122. package/dist/providers/ant-ling.models.js +1 -1
  123. package/dist/providers/ant-ling.models.js.map +1 -1
  124. package/dist/providers/anthropic.models.js +1 -1
  125. package/dist/providers/anthropic.models.js.map +1 -1
  126. package/dist/providers/azure.models.js +1 -1
  127. package/dist/providers/azure.models.js.map +1 -1
  128. package/dist/providers/baseten.models.js +1 -1
  129. package/dist/providers/baseten.models.js.map +1 -1
  130. package/dist/providers/cerebras.models.js +1 -1
  131. package/dist/providers/cerebras.models.js.map +1 -1
  132. package/dist/providers/cloudflare-ai-gateway.models.js +1 -1
  133. package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
  134. package/dist/providers/cloudflare-workers-ai.models.js +1 -1
  135. package/dist/providers/cloudflare-workers-ai.models.js.map +1 -1
  136. package/dist/providers/compat-schema.d.ts +444 -456
  137. package/dist/providers/compat-schema.d.ts.map +1 -1
  138. package/dist/providers/compat-schema.js +166 -112
  139. package/dist/providers/compat-schema.js.map +1 -1
  140. package/dist/providers/data/.manifest.json +1 -1
  141. package/dist/providers/data/amazon-bedrock.json +1 -1
  142. package/dist/providers/data/anthropic.json +1 -1
  143. package/dist/providers/data/azure.json +1 -1
  144. package/dist/providers/data/baseten.json +1 -1
  145. package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  146. package/dist/providers/data/cloudflare-workers-ai.json +1 -1
  147. package/dist/providers/data/fireworks.json +1 -1
  148. package/dist/providers/data/github-copilot.json +1 -1
  149. package/dist/providers/data/google-vertex.json +1 -1
  150. package/dist/providers/data/google.json +1 -1
  151. package/dist/providers/data/huggingface.json +1 -1
  152. package/dist/providers/data/kimi-coding.json +1 -1
  153. package/dist/providers/data/mistral.json +1 -1
  154. package/dist/providers/data/moonshotai-cn.json +1 -1
  155. package/dist/providers/data/moonshotai.json +1 -1
  156. package/dist/providers/data/nvidia.json +1 -1
  157. package/dist/providers/data/openai-codex.json +1 -1
  158. package/dist/providers/data/openai.json +1 -1
  159. package/dist/providers/data/opencode-go.json +1 -1
  160. package/dist/providers/data/opencode.json +1 -1
  161. package/dist/providers/data/openrouter.json +1 -1
  162. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  163. package/dist/providers/data/qwen-token-plan-individual-cn.json +1 -0
  164. package/dist/providers/data/qwen-token-plan-individual.json +1 -1
  165. package/dist/providers/data/qwen-token-plan.json +1 -1
  166. package/dist/providers/data/radius.json +1 -1
  167. package/dist/providers/data/together.json +1 -1
  168. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  169. package/dist/providers/data/xai.json +1 -1
  170. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  171. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  172. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  173. package/dist/providers/data/xiaomi.json +1 -1
  174. package/dist/providers/data/zai-coding-cn.json +1 -1
  175. package/dist/providers/data/zai.json +1 -1
  176. package/dist/providers/deepseek.models.js +1 -1
  177. package/dist/providers/deepseek.models.js.map +1 -1
  178. package/dist/providers/faux.d.ts.map +1 -1
  179. package/dist/providers/faux.js +7 -2
  180. package/dist/providers/faux.js.map +1 -1
  181. package/dist/providers/fireworks.models.js +1 -1
  182. package/dist/providers/fireworks.models.js.map +1 -1
  183. package/dist/providers/github-copilot.d.ts +3 -1
  184. package/dist/providers/github-copilot.d.ts.map +1 -1
  185. package/dist/providers/github-copilot.js +13 -2
  186. package/dist/providers/github-copilot.js.map +1 -1
  187. package/dist/providers/github-copilot.models.js +1 -1
  188. package/dist/providers/github-copilot.models.js.map +1 -1
  189. package/dist/providers/google-vertex.models.js +1 -1
  190. package/dist/providers/google-vertex.models.js.map +1 -1
  191. package/dist/providers/google.models.js +1 -1
  192. package/dist/providers/google.models.js.map +1 -1
  193. package/dist/providers/groq.models.js +1 -1
  194. package/dist/providers/groq.models.js.map +1 -1
  195. package/dist/providers/huggingface.models.js +1 -1
  196. package/dist/providers/huggingface.models.js.map +1 -1
  197. package/dist/providers/kimi-coding.models.js +1 -1
  198. package/dist/providers/kimi-coding.models.js.map +1 -1
  199. package/dist/providers/meta.models.js +1 -1
  200. package/dist/providers/meta.models.js.map +1 -1
  201. package/dist/providers/minimax-cn.models.js +1 -1
  202. package/dist/providers/minimax-cn.models.js.map +1 -1
  203. package/dist/providers/minimax.models.js +1 -1
  204. package/dist/providers/minimax.models.js.map +1 -1
  205. package/dist/providers/mistral.models.js +1 -1
  206. package/dist/providers/mistral.models.js.map +1 -1
  207. package/dist/providers/model-schema.d.ts +65 -65
  208. package/dist/providers/model-schema.d.ts.map +1 -1
  209. package/dist/providers/model-schema.js +41 -30
  210. package/dist/providers/model-schema.js.map +1 -1
  211. package/dist/providers/moonshotai-cn.models.js +1 -1
  212. package/dist/providers/moonshotai-cn.models.js.map +1 -1
  213. package/dist/providers/moonshotai.models.js +1 -1
  214. package/dist/providers/moonshotai.models.js.map +1 -1
  215. package/dist/providers/nvidia.models.js +1 -1
  216. package/dist/providers/nvidia.models.js.map +1 -1
  217. package/dist/providers/openai-codex.js +1 -1
  218. package/dist/providers/openai-codex.js.map +1 -1
  219. package/dist/providers/openai-codex.models.js +1 -1
  220. package/dist/providers/openai-codex.models.js.map +1 -1
  221. package/dist/providers/openai.models.js +1 -1
  222. package/dist/providers/openai.models.js.map +1 -1
  223. package/dist/providers/opencode-go.models.js +1 -1
  224. package/dist/providers/opencode-go.models.js.map +1 -1
  225. package/dist/providers/opencode.js +1 -1
  226. package/dist/providers/opencode.js.map +1 -1
  227. package/dist/providers/opencode.models.js +1 -1
  228. package/dist/providers/opencode.models.js.map +1 -1
  229. package/dist/providers/openrouter.models.js +1 -1
  230. package/dist/providers/openrouter.models.js.map +1 -1
  231. package/dist/providers/qwen-token-plan-cn.models.js +1 -1
  232. package/dist/providers/qwen-token-plan-cn.models.js.map +1 -1
  233. package/dist/providers/qwen-token-plan-individual-cn.d.ts +3 -0
  234. package/dist/providers/qwen-token-plan-individual-cn.d.ts.map +1 -0
  235. package/dist/providers/qwen-token-plan-individual-cn.js +15 -0
  236. package/dist/providers/qwen-token-plan-individual-cn.js.map +1 -0
  237. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts +6 -0
  238. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts.map +1 -0
  239. package/dist/providers/qwen-token-plan-individual-cn.models.js +8 -0
  240. package/dist/providers/qwen-token-plan-individual-cn.models.js.map +1 -0
  241. package/dist/providers/qwen-token-plan-individual.models.js +1 -1
  242. package/dist/providers/qwen-token-plan-individual.models.js.map +1 -1
  243. package/dist/providers/qwen-token-plan.models.js +1 -1
  244. package/dist/providers/qwen-token-plan.models.js.map +1 -1
  245. package/dist/providers/radius-config.d.ts.map +1 -1
  246. package/dist/providers/radius-config.js +2 -1
  247. package/dist/providers/radius-config.js.map +1 -1
  248. package/dist/providers/radius.models.js +1 -1
  249. package/dist/providers/radius.models.js.map +1 -1
  250. package/dist/providers/schema-builders.d.ts +10 -0
  251. package/dist/providers/schema-builders.d.ts.map +1 -0
  252. package/dist/providers/schema-builders.js +18 -0
  253. package/dist/providers/schema-builders.js.map +1 -0
  254. package/dist/providers/together.models.js +1 -1
  255. package/dist/providers/together.models.js.map +1 -1
  256. package/dist/providers/typesafe.models.js +1 -1
  257. package/dist/providers/typesafe.models.js.map +1 -1
  258. package/dist/providers/vercel-ai-gateway.models.js +1 -1
  259. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  260. package/dist/providers/xai.models.js +1 -1
  261. package/dist/providers/xai.models.js.map +1 -1
  262. package/dist/providers/xiaomi-token-plan-ams.models.js +1 -1
  263. package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -1
  264. package/dist/providers/xiaomi-token-plan-cn.models.js +1 -1
  265. package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -1
  266. package/dist/providers/xiaomi-token-plan-sgp.models.js +1 -1
  267. package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -1
  268. package/dist/providers/xiaomi.models.js +1 -1
  269. package/dist/providers/xiaomi.models.js.map +1 -1
  270. package/dist/providers/zai-coding-cn.models.js +1 -1
  271. package/dist/providers/zai-coding-cn.models.js.map +1 -1
  272. package/dist/providers/zai.models.js +1 -1
  273. package/dist/providers/zai.models.js.map +1 -1
  274. package/dist/telemetry.d.ts.map +1 -1
  275. package/dist/telemetry.js +2 -1
  276. package/dist/telemetry.js.map +1 -1
  277. package/dist/types.d.ts +20 -3
  278. package/dist/types.d.ts.map +1 -1
  279. package/dist/types.js.map +1 -1
  280. package/dist/utils/error-body.d.ts +8 -0
  281. package/dist/utils/error-body.d.ts.map +1 -1
  282. package/dist/utils/error-body.js +30 -2
  283. package/dist/utils/error-body.js.map +1 -1
  284. package/dist/utils/openrouter-cost.d.ts +24 -0
  285. package/dist/utils/openrouter-cost.d.ts.map +1 -0
  286. package/dist/utils/openrouter-cost.js +34 -0
  287. package/dist/utils/openrouter-cost.js.map +1 -0
  288. package/dist/utils/overflow.d.ts.map +1 -1
  289. package/dist/utils/overflow.js +2 -0
  290. package/dist/utils/overflow.js.map +1 -1
  291. package/dist/utils/retry.d.ts.map +1 -1
  292. package/dist/utils/retry.js +6 -0
  293. package/dist/utils/retry.js.map +1 -1
  294. package/dist/utils/streaming-json.d.ts +84 -0
  295. package/dist/utils/streaming-json.d.ts.map +1 -0
  296. package/dist/utils/streaming-json.js +513 -0
  297. package/dist/utils/streaming-json.js.map +1 -0
  298. package/dist/utils/{typebox-helpers.d.ts → string-enum.d.ts} +5 -5
  299. package/dist/utils/string-enum.d.ts.map +1 -0
  300. package/dist/utils/{typebox-helpers.js → string-enum.js} +5 -6
  301. package/dist/utils/string-enum.js.map +1 -0
  302. package/dist/utils/text.d.ts +7 -0
  303. package/dist/utils/text.d.ts.map +1 -1
  304. package/dist/utils/text.js +9 -0
  305. package/dist/utils/text.js.map +1 -1
  306. package/dist/utils/transcript.d.ts +1 -1
  307. package/dist/utils/transcript.js +1 -1
  308. package/dist/utils/transcript.js.map +1 -1
  309. package/dist/utils/validation.d.ts +5 -3
  310. package/dist/utils/validation.d.ts.map +1 -1
  311. package/dist/utils/validation.js +27 -277
  312. package/dist/utils/validation.js.map +1 -1
  313. package/dist/utils/version.d.ts +1 -1
  314. package/dist/utils/version.js +1 -1
  315. package/dist/utils/version.js.map +1 -1
  316. package/package.json +19 -10
  317. package/dist/utils/typebox-helpers.d.ts.map +0 -1
  318. package/dist/utils/typebox-helpers.js.map +0 -1
@@ -12,6 +12,7 @@ import { normalizeRadiusGatewayUrl } from "../../providers/radius-config.js";
12
12
  import { startOAuthCallbackServer } from "./callback-server.js";
13
13
  import { pollOAuthDeviceCodeFlow } from "./device-code.js";
14
14
  import { generatePKCE } from "./pkce.js";
15
+ import { trustedHttpUrl } from "./trusted-url.js";
15
16
  const CALLBACK_HOST = "127.0.0.1";
16
17
  const CALLBACK_PORT = 1456;
17
18
  const CALLBACK_PATH = "/oauth/callback";
@@ -31,10 +32,11 @@ async function loadRadiusOAuthDiscovery(gateway, signal) {
31
32
  throw new Error(`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`);
32
33
  }
33
34
  const discovery = (await response.json());
34
- if (typeof discovery.authorizationEndpoint !== "string") {
35
+ const authorizationEndpoint = trustedHttpUrl(discovery.authorizationEndpoint);
36
+ if (!authorizationEndpoint) {
35
37
  throw new Error(`Invalid Radius OAuth config from ${gateway}`);
36
38
  }
37
- return { authorizationEndpoint: discovery.authorizationEndpoint };
39
+ return { authorizationEndpoint };
38
40
  }
39
41
  class OAuthResponseError extends Error {
40
42
  status;
@@ -162,10 +164,14 @@ async function requestDeviceAuthorization(gateway, signal) {
162
164
  if (!data.device_code || !data.user_code || !data.verification_uri || !data.expires_in) {
163
165
  throw new Error("Radius OAuth device authorization response is missing required fields");
164
166
  }
167
+ const verificationUri = trustedHttpUrl(data.verification_uri);
168
+ if (!verificationUri) {
169
+ throw new Error("Untrusted verification_uri in Radius OAuth device authorization response");
170
+ }
165
171
  return {
166
172
  device_code: data.device_code,
167
173
  user_code: data.user_code,
168
- verification_uri: data.verification_uri,
174
+ verification_uri: verificationUri,
169
175
  expires_in: data.expires_in,
170
176
  interval: data.interval,
171
177
  };
@@ -1 +1 @@
1
- {"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,iBAAiB,CAAC;AACxC,MAAM,YAAY,GAAG,UAAU,aAAa,IAAI,aAAa,GAAG,aAAa,EAAE,CAAC;AAChF,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,oBAAoB,GAAG,SAAS,CAAC;AACvC,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAC/C,MAAM,eAAe,GAAG,YAAY,CAAC;AACrC,MAAM,WAAW,GAAG,wBAAwB,CAAC;AAC7C,MAAM,4BAA4B,GAAG,8CAA8C,CAAC;AAcpF,KAAK,UAAU,wBAAwB,CAAC,OAAe,EAAE,MAAmB;IAC3E,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE;QAC3D,OAAO,EAAE,EAAE,MAAM,EAAE,kBAAkB,EAAE;Q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;aACD,CAAC,CAAC;YAEH,IAAI,WAAW,KAAK,wBAAwB,EAAE,CAAC;gBAC9C,OAAO,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YAClD,CAAC;YACD,IAAI,WAAW,KAAK,oBAAoB,EAAE,CAAC;gBAC1C,MAAM,SAAS,GAAG,MAAM,wBAAwB,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;gBAC9E,OAAO,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,qBAAqB,EAAE,WAAW,CAAC,CAAC;YAChF,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,WAAW,OAAO,CAAC,IAAI,oBAAoB,WAAW,EAAE,CAAC,CAAC;QAC3E,CAAC;QAED,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM;YAC/B,MAAM,SAAS,GAAG,MAAM,iBAAiB,CACxC,OAAO,EACP,IAAI,eAAe,CAAC;gBACnB,UAAU,EAAE,eAAe;gBAC3B,SAAS,EAAE,eAAe;gBAC1B,aAAa,EAAE,UAAU,CAAC,OAAO;aACjC,CAAC,EACF,MAAM,CACN,CAAC;YACF,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,UAAU;YACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;QACtC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Radius gateway OAuth flow.\n *\n * Radius is a pi-messages gateway. OAuth client APIs live on the configured\n * gateway; only the interactive browser authorization endpoint is discovered.\n * Model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http (via callback-server.ts) for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { normalizeRadiusGatewayUrl } from \"../../providers/radius-config.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\nconst OAUTH_CLIENT_ID = \"pi-gateway\";\nconst OAUTH_SCOPE = \"gateway offline_access\";\nconst OAUTH_DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\n\ntype RadiusOAuthDiscovery = {\n\tauthorizationEndpoint: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthDiscovery(gateway: string, signal: AbortSignal): Promise<RadiusOAuthDiscovery> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t\tsignal,\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\tconst discovery = (await response.json()) as Partial<RadiusOAuthDiscovery>;\n\tif (typeof discovery.authorizationEndpoint !== \"string\") {\n\t\tthrow new Error(`Invalid Radius OAuth config from ${gateway}`);\n\t}\n\treturn { authorizationEndpoint: discovery.authorizationEndpoint };\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\tgateway: string,\n\tbody: URLSearchParams,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/token\", gateway), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\nasync function loginWithBrowser(\n\tgateway: string,\n\tauthorizationEndpoint: string,\n\tinteraction: ProviderAuthInteraction,\n): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: OAUTH_CLIENT_ID,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: OAUTH_SCOPE,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Radius\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate,\n\t\tcomplete: (code) =>\n\t\t\trequestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\t\tcode,\n\t\t\t\t\tcode_verifier: verifier,\n\t\t\t\t}),\n\t\t\t\tinteraction.signal,\n\t\t\t),\n\t\tsignal: interaction.signal,\n\t});\n\tinteraction.notify({ type: \"progress\", message: `Listening for OAuth callback on ${REDIRECT_URI}` });\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst credential = await callback.wait();\n\t\tif (!credential) throw new Error(\"OAuth callback did not complete.\");\n\t\treturn credential;\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(gateway: string, signal: AbortSignal): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/device\", gateway), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: OAUTH_CLIENT_ID, scope: OAUTH_SCOPE }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.verification_uri || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: data.verification_uri,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(gateway: string, interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(gateway, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: interaction.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: OAUTH_DEVICE_CODE_GRANT_TYPE,\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tinteraction.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nexport interface RadiusOAuthOptions {\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuth(options: RadiusOAuthOptions): OAuthAuth {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tname: options.name,\n\n\t\tasync login(interaction): Promise<OAuthCredential> {\n\t\t\tconst loginMethod = await interaction.prompt({\n\t\t\t\ttype: \"select\",\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\treturn loginWithDeviceCode(gateway, interaction);\n\t\t\t}\n\t\t\tif (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tconst discovery = await loadRadiusOAuthDiscovery(gateway, interaction.signal);\n\t\t\t\treturn loginWithBrowser(gateway, discovery.authorizationEndpoint, interaction);\n\t\t\t}\n\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn refreshed;\n\t\t},\n\n\t\tasync toAuth(credential) {\n\t\t\treturn { apiKey: credential.access };\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,iBAAiB,CAAC;AACxC,MAAM,YAAY,GAAG,UAAU,aAAa,IAAI,aAAa,GAAG,aAAa,EAAE,CAAC;AAChF,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,oBAAoB,GAAG,SAAS,CAAC;AACvC,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAC/C,MAAM,eAAe,GAAG,YAAY,CAAC;AACrC,MAAM,WAAW,GAAG,wBAAwB,CAAC;AAC7C,MAAM,4BAA4B,GAAG,8CAA8C,CAAC;AAcpF,KAAK,UAAU,wBAAwB,CAAC,OAAe,EAAE,MAAmB;IAC3E,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE;QAC3D,OAAO,EAAE,E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;gBACd,OAAO,EAAE,cAAc,OAAO,CAAC,IAAI,GAAG;gBACtC,OAAO,EAAE;oBACR,EAAE,EAAE,EAAE,oBAAoB,EAAE,KAAK,EAAE,oCAAoC,EAAE;oBACzE;wBACC,EAAE,EAAE,wBAAwB;wBAC5B,KAAK,EAAE,gEAAgE;qBACvE;iBACD;aACD,CAAC,CAAC;YAEH,IAAI,WAAW,KAAK,wBAAwB,EAAE,CAAC;gBAC9C,OAAO,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YAClD,CAAC;YACD,IAAI,WAAW,KAAK,oBAAoB,EAAE,CAAC;gBAC1C,MAAM,SAAS,GAAG,MAAM,wBAAwB,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;gBAC9E,OAAO,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,qBAAqB,EAAE,WAAW,CAAC,CAAC;YAChF,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,WAAW,OAAO,CAAC,IAAI,oBAAoB,WAAW,EAAE,CAAC,CAAC;QAC3E,CAAC;QAED,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM;YAC/B,MAAM,SAAS,GAAG,MAAM,iBAAiB,CACxC,OAAO,EACP,IAAI,eAAe,CAAC;gBACnB,UAAU,EAAE,eAAe;gBAC3B,SAAS,EAAE,eAAe;gBAC1B,aAAa,EAAE,UAAU,CAAC,OAAO;aACjC,CAAC,EACF,MAAM,CACN,CAAC;YACF,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,UAAU;YACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;QACtC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Radius gateway OAuth flow.\n *\n * Radius is a pi-messages gateway. OAuth client APIs live on the configured\n * gateway; only the interactive browser authorization endpoint is discovered.\n * Model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http (via callback-server.ts) for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { normalizeRadiusGatewayUrl } from \"../../providers/radius-config.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport { trustedHttpUrl } from \"./trusted-url.ts\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\nconst OAUTH_CLIENT_ID = \"pi-gateway\";\nconst OAUTH_SCOPE = \"gateway offline_access\";\nconst OAUTH_DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\n\ntype RadiusOAuthDiscovery = {\n\tauthorizationEndpoint: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthDiscovery(gateway: string, signal: AbortSignal): Promise<RadiusOAuthDiscovery> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t\tsignal,\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\tconst discovery = (await response.json()) as Partial<RadiusOAuthDiscovery>;\n\tconst authorizationEndpoint = trustedHttpUrl(discovery.authorizationEndpoint);\n\tif (!authorizationEndpoint) {\n\t\tthrow new Error(`Invalid Radius OAuth config from ${gateway}`);\n\t}\n\treturn { authorizationEndpoint };\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\tgateway: string,\n\tbody: URLSearchParams,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/token\", gateway), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\nasync function loginWithBrowser(\n\tgateway: string,\n\tauthorizationEndpoint: string,\n\tinteraction: ProviderAuthInteraction,\n): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: OAUTH_CLIENT_ID,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: OAUTH_SCOPE,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Radius\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate,\n\t\tcomplete: (code) =>\n\t\t\trequestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\t\tcode,\n\t\t\t\t\tcode_verifier: verifier,\n\t\t\t\t}),\n\t\t\t\tinteraction.signal,\n\t\t\t),\n\t\tsignal: interaction.signal,\n\t});\n\tinteraction.notify({ type: \"progress\", message: `Listening for OAuth callback on ${REDIRECT_URI}` });\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst credential = await callback.wait();\n\t\tif (!credential) throw new Error(\"OAuth callback did not complete.\");\n\t\treturn credential;\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(gateway: string, signal: AbortSignal): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/device\", gateway), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: OAUTH_CLIENT_ID, scope: OAUTH_SCOPE }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.verification_uri || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\tconst verificationUri = trustedHttpUrl(data.verification_uri);\n\tif (!verificationUri) {\n\t\tthrow new Error(\"Untrusted verification_uri in Radius OAuth device authorization response\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: verificationUri,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(gateway: string, interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(gateway, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: interaction.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: OAUTH_DEVICE_CODE_GRANT_TYPE,\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tinteraction.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nexport interface RadiusOAuthOptions {\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuth(options: RadiusOAuthOptions): OAuthAuth {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tname: options.name,\n\n\t\tasync login(interaction): Promise<OAuthCredential> {\n\t\t\tconst loginMethod = await interaction.prompt({\n\t\t\t\ttype: \"select\",\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\treturn loginWithDeviceCode(gateway, interaction);\n\t\t\t}\n\t\t\tif (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tconst discovery = await loadRadiusOAuthDiscovery(gateway, interaction.signal);\n\t\t\t\treturn loginWithBrowser(gateway, discovery.authorizationEndpoint, interaction);\n\t\t\t}\n\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn refreshed;\n\t\t},\n\n\t\tasync toAuth(credential) {\n\t\t\treturn { apiKey: credential.access };\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the
3
+ * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing
4
+ * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.
5
+ */
6
+ export declare function trustedHttpUrl(value: unknown): string | null;
7
+ //# sourceMappingURL=trusted-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trusted-url.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/trusted-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAI5D"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the
3
+ * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing
4
+ * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.
5
+ */
6
+ export function trustedHttpUrl(value) {
7
+ if (typeof value !== "string" || !URL.canParse(value))
8
+ return null;
9
+ const url = new URL(value);
10
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
11
+ }
12
+ //# sourceMappingURL=trusted-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trusted-url.js","sourceRoot":"","sources":["../../../src/auth/oauth/trusted-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACnE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC","sourcesContent":["/**\n * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the\n * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing\n * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.\n */\nexport function trustedHttpUrl(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !URL.canParse(value)) return null;\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" || url.protocol === \"http:\" ? url.href : null;\n}\n"]}
@@ -141,6 +141,10 @@ export type AuthEvent = {
141
141
  type: "device_code";
142
142
  userCode: string;
143
143
  verificationUri: string;
144
+ /** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */
145
+ openBrowserOnConfirm?: boolean;
146
+ /** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */
147
+ copyCodeOnConfirm?: boolean;
144
148
  intervalSeconds?: number;
145
149
  expiresInSeconds?: number;
146
150
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,WAAW,CAAC;CAClB;AAED,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,yCAAyC;AACzC,MAAM,WAAW,eAAgB,SAAQ,gBAAgB;IACxD,IAAI,EAAE,OAAO,CAAC;CACd;AAED,gFAAgF;AAChF,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAE5D,qEAAqE;AACrE,MAAM,WAAW,cAAc;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;CACzB;AAED,uEAAuE;AACvE,MAAM,WAAW,oBAAoB;IACpC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,eAAe;IAC/B;;;OAGG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;IAE1F;;;O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C;IAEb,oFAAoF;IACpF,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,KAAK,CAAC,WAAW,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9F;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAEpF;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App-supplied context for `Models.login`. */\nexport interface LoginOptions {\n\t/**\n\t * Returns the stable ID of this app installation, e.g. sent to OpenAI as its\n\t * agent host ID. Called only by login flows that need it, so apps can create\n\t * the ID on first use and must return the same ID on every later call.\n\t */\n\tgetDeviceId?: () => string;\n\t/**\n\t * Name this app introduces itself with during login, e.g. OpenAI's agent name hint and\n\t * Codex originator. Defaults to pi's own name.\n\t */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App-supplied context for `Models.login`. */\nexport interface LoginOptions {\n\t/**\n\t * Returns the stable ID of this app installation, e.g. sent to OpenAI as its\n\t * agent host ID. Called only by login flows that need it, so apps can create\n\t * the ID on first use and must return the same ID on every later call.\n\t */\n\tgetDeviceId?: () => string;\n\t/**\n\t * Name this app introduces itself with during login, e.g. OpenAI's agent name hint and\n\t * Codex originator. Defaults to pi's own name.\n\t */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import type { Api, Model, SimpleStreamOptions } from "./types.ts";
2
+ /** Whether a refresh is sent ("warm") or warming ends until the next real request ("stop"). */
3
+ export type CacheWarmingAction = "warm" | "stop";
4
+ /** "streaming" while the agent run that sent the request is still active; "idle" after it settled. */
5
+ export type CacheWarmingPhase = "streaming" | "idle";
6
+ /** Inputs and outcome of one warm-or-stop decision. */
7
+ export interface CacheWarmingDecision {
8
+ phase: CacheWarmingPhase;
9
+ /** Price of this refresh: a cache read of the prompt plus one output token. */
10
+ warmCost: number;
11
+ /** Extra price of the next real request if the cache entry is lost. */
12
+ missCost: number;
13
+ /** Estimated chance that a real request arrives before the entry expires. */
14
+ continuationProbability: number;
15
+ /** `continuationProbability * missCost - warmCost`. */
16
+ expectedSavings: number;
17
+ /** False when the prompt size or the model's prices are unknown. */
18
+ economicsAvailable: boolean;
19
+ /** "warm" when `expectedSavings` is at least `CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS`. */
20
+ action: CacheWarmingAction;
21
+ }
22
+ /** Streaming warming never continues past this long after the real request that started it. */
23
+ export declare const CACHE_WARMING_MAX_AGE_MS: number;
24
+ /** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */
25
+ export declare const CACHE_WARMING_MAX_IDLE_AGE_MS: number;
26
+ /** A refresh is sent only when it is expected to save at least this many dollars. */
27
+ export declare const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;
28
+ /**
29
+ * Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own
30
+ * usage; per-session estimates were not better than this constant.
31
+ */
32
+ export declare const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;
33
+ /** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
34
+ export declare function getCacheWarmingDelayMs(ttlMs: number): number | undefined;
35
+ /**
36
+ * Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the
37
+ * request used. Undefined when the model has no lifetime for that tier or caching is off.
38
+ */
39
+ export declare function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined;
40
+ /**
41
+ * Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based
42
+ * thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a
43
+ * different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.
44
+ */
45
+ export declare function isCacheWarmingReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean;
46
+ /**
47
+ * The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the
48
+ * conversation's provider thread state (the refresh repeats the last request).
49
+ */
50
+ export declare function getCacheWarmingRequestOptions<T extends SimpleStreamOptions>(options: T, signal: AbortSignal): T;
51
+ /** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */
52
+ export declare function evaluateCacheWarming(model: Model<Api>, promptTokens: number, phase: CacheWarmingPhase): CacheWarmingDecision;
53
+ //# sourceMappingURL=cache-warming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-warming.d.ts","sourceRoot":"","sources":["../src/cache-warming.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,mBAAmB,EAAS,MAAM,YAAY,CAAC;AAGzE,+FAA+F;AAC/F,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,MAAM,CAAC;AAEjD,sGAAsG;AACtG,MAAM,MAAM,iBAAiB,GAAG,WAAW,GAAG,MAAM,CAAC;AAErD,uDAAuD;AACvD,MAAM,WAAW,oBAAoB;IACpC,KAAK,EAAE,iBAAiB,CAAC;IACzB,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,uBAAuB,EAAE,MAAM,CAAC;IAChC,uDAAuD;IACvD,eAAe,EAAE,MAAM,CAAC;IACxB,oEAAoE;IACpE,kBAAkB,EAAE,OAAO,CAAC;IAC5B,0FAA0F;IAC1F,MAAM,EAAE,kBAAkB,CAAC;CAC3B;AAED,+FAA+F;AAC/F,eAAO,MAAM,wBAAwB,QAAc,CAAC;AAEpD,wGAAwG;AACxG,eAAO,MAAM,6BAA6B,QAAc,CAAC;AAEzD,qFAAqF;AACrF,eAAO,MAAM,sCAAsC,OAAO,CAAC;AAE3D;;;GAGG;AACH,eAAO,MAAM,2CAA2C,OAAO,CAAC;AAEhE,iFAAiF;AACjF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGxE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,mBAAmB,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOnH;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,mBAAmB,GAAG,SAAS,GAAG,OAAO,CAG7G;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,CAAC,SAAS,mBAAmB,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,CAAC,CAE/G;AAED,8GAA8G;AAC9G,wBAAgB,oBAAoB,CACnC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,iBAAiB,GACtB,oBAAoB,CAoBtB"}
@@ -0,0 +1,82 @@
1
+ // Prompt cache warming policy shared by pi's hosts: when a refresh is due, whether a request can be replayed, and
2
+ // whether a refresh pays for itself. Hosts own the scheduling; this module owns the numbers.
3
+ import { calculateCost } from "./models.js";
4
+ import { getProviderEnvValue } from "./utils/provider-env.js";
5
+ /** Streaming warming never continues past this long after the real request that started it. */
6
+ export const CACHE_WARMING_MAX_AGE_MS = 60 * 60_000;
7
+ /** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */
8
+ export const CACHE_WARMING_MAX_IDLE_AGE_MS = 30 * 60_000;
9
+ /** A refresh is sent only when it is expected to save at least this many dollars. */
10
+ export const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;
11
+ /**
12
+ * Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own
13
+ * usage; per-session estimates were not better than this constant.
14
+ */
15
+ export const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;
16
+ /** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
17
+ export function getCacheWarmingDelayMs(ttlMs) {
18
+ if (ttlMs <= 10_000)
19
+ return undefined;
20
+ return Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));
21
+ }
22
+ /**
23
+ * Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the
24
+ * request used. Undefined when the model has no lifetime for that tier or caching is off.
25
+ */
26
+ export function getPromptCacheTtlMs(model, options) {
27
+ const retention = options?.cacheRetention ??
28
+ (getProviderEnvValue("PI_CACHE_RETENTION", options?.env) === "long" ? "long" : "short");
29
+ if (retention === "none")
30
+ return undefined;
31
+ const seconds = model.promptCache?.[retention];
32
+ return seconds === undefined ? undefined : seconds * 1000;
33
+ }
34
+ /**
35
+ * Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based
36
+ * thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a
37
+ * different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.
38
+ */
39
+ export function isCacheWarmingReplayable(model, options) {
40
+ if (!options?.reasoning || model.api !== "anthropic-messages")
41
+ return true;
42
+ return model.compat?.forceAdaptiveThinking === true;
43
+ }
44
+ /**
45
+ * The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the
46
+ * conversation's provider thread state (the refresh repeats the last request).
47
+ */
48
+ export function getCacheWarmingRequestOptions(options, signal) {
49
+ return { ...options, maxTokens: 1, disableContinuation: true, maxRetries: 0, signal };
50
+ }
51
+ /** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */
52
+ export function evaluateCacheWarming(model, promptTokens, phase) {
53
+ const cacheHitCost = price(model, { cacheRead: promptTokens });
54
+ const cacheMissCost = price(model, model.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens });
55
+ const warmCost = price(model, { cacheRead: promptTokens, output: 1 });
56
+ const missCost = Math.max(0, cacheMissCost - cacheHitCost);
57
+ const continuationProbability = phase === "idle" ? CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY : 1;
58
+ const economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);
59
+ const expectedSavings = continuationProbability * missCost - warmCost;
60
+ return {
61
+ phase,
62
+ warmCost,
63
+ missCost,
64
+ continuationProbability,
65
+ expectedSavings,
66
+ economicsAvailable,
67
+ action: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? "warm" : "stop",
68
+ };
69
+ }
70
+ function price(model, tokens) {
71
+ const usage = {
72
+ input: 0,
73
+ output: 0,
74
+ cacheRead: 0,
75
+ cacheWrite: 0,
76
+ totalTokens: 0,
77
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
78
+ ...tokens,
79
+ };
80
+ return calculateCost(model, usage).total;
81
+ }
82
+ //# sourceMappingURL=cache-warming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-warming.js","sourceRoot":"","sources":["../src/cache-warming.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,6FAA6F;AAC7F,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAyB9D,+FAA+F;AAC/F,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,GAAG,MAAM,CAAC;AAEpD,wGAAwG;AACxG,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,MAAM,CAAC;AAEzD,qFAAqF;AACrF,MAAM,CAAC,MAAM,sCAAsC,GAAG,IAAI,CAAC;AAE3D;;;GAGG;AACH,MAAM,CAAC,MAAM,2CAA2C,GAAG,IAAI,CAAC;AAEhE,iFAAiF;AACjF,MAAM,UAAU,sBAAsB,CAAC,KAAa;IACnD,IAAI,KAAK,IAAI,MAAM;QAAE,OAAO,SAAS,CAAC;IACtC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,GAAG,EAAE,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAA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AAE,YAAY,EAAE,CAClF,CAAC;IACF,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;IACtE,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,aAAa,GAAG,YAAY,CAAC,CAAC;IAC3D,MAAM,uBAAuB,GAAG,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,2CAA2C,CAAC,CAAC,CAAC,CAAC,CAAC;IACnG,MAAM,kBAAkB,GAAG,YAAY,GAAG,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,IAAI,aAAa,GAAG,CAAC,CAAC,CAAC;IACvF,MAAM,eAAe,GAAG,uBAAuB,GAAG,QAAQ,GAAG,QAAQ,CAAC;IACtE,OAAO;QACN,KAAK;QACL,QAAQ;QACR,QAAQ;QACR,uBAAuB;QACvB,eAAe;QACf,kBAAkB;QAClB,MAAM,EAAE,eAAe,IAAI,sCAAsC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;KACnF,CAAC;AACH,CAAC;AAED,SAAS,KAAK,CACb,KAAiB,EACjB,MAA6E;IAE7E,MAAM,KAAK,GAAU;QACpB,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;QACpE,GAAG,MAAM;KACT,CAAC;IACF,OAAO,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC;AAC1C,CAAC","sourcesContent":["// Prompt cache warming policy shared by pi's hosts: when a refresh is due, whether a request can be replayed, and\n// whether a refresh pays for itself. Hosts own the scheduling; this module owns the numbers.\nimport { calculateCost } from \"./models.ts\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"./types.ts\";\nimport { getProviderEnvValue } from \"./utils/provider-env.ts\";\n\n/** Whether a refresh is sent (\"warm\") or warming ends until the next real request (\"stop\"). */\nexport type CacheWarmingAction = \"warm\" | \"stop\";\n\n/** \"streaming\" while the agent run that sent the request is still active; \"idle\" after it settled. */\nexport type CacheWarmingPhase = \"streaming\" | \"idle\";\n\n/** Inputs and outcome of one warm-or-stop decision. */\nexport interface CacheWarmingDecision {\n\tphase: CacheWarmingPhase;\n\t/** Price of this refresh: a cache read of the prompt plus one output token. */\n\twarmCost: number;\n\t/** Extra price of the next real request if the cache entry is lost. */\n\tmissCost: number;\n\t/** Estimated chance that a real request arrives before the entry expires. */\n\tcontinuationProbability: number;\n\t/** `continuationProbability * missCost - warmCost`. */\n\texpectedSavings: number;\n\t/** False when the prompt size or the model's prices are unknown. */\n\teconomicsAvailable: boolean;\n\t/** \"warm\" when `expectedSavings` is at least `CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS`. */\n\taction: CacheWarmingAction;\n}\n\n/** Streaming warming never continues past this long after the real request that started it. */\nexport const CACHE_WARMING_MAX_AGE_MS = 60 * 60_000;\n\n/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */\nexport const CACHE_WARMING_MAX_IDLE_AGE_MS = 30 * 60_000;\n\n/** A refresh is sent only when it is expected to save at least this many dollars. */\nexport const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;\n\n/**\n * Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own\n * usage; per-session estimates were not better than this constant.\n */\nexport const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;\n\n/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */\nexport function getCacheWarmingDelayMs(ttlMs: number): number | undefined {\n\tif (ttlMs <= 10_000) return undefined;\n\treturn Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));\n}\n\n/**\n * Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the\n * request used. Undefined when the model has no lifetime for that tier or caching is off.\n */\nexport function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined {\n\tconst retention =\n\t\toptions?.cacheRetention ??\n\t\t(getProviderEnvValue(\"PI_CACHE_RETENTION\", options?.env) === \"long\" ? \"long\" : \"short\");\n\tif (retention === \"none\") return undefined;\n\tconst seconds = model.promptCache?.[retention];\n\treturn seconds === undefined ? undefined : seconds * 1000;\n}\n\n/**\n * Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based\n * thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a\n * different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.\n */\nexport function isCacheWarmingReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean {\n\tif (!options?.reasoning || model.api !== \"anthropic-messages\") return true;\n\treturn (model as Model<\"anthropic-messages\">).compat?.forceAdaptiveThinking === true;\n}\n\n/**\n * The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the\n * conversation's provider thread state (the refresh repeats the last request).\n */\nexport function getCacheWarmingRequestOptions<T extends SimpleStreamOptions>(options: T, signal: AbortSignal): T {\n\treturn { ...options, maxTokens: 1, disableContinuation: true, maxRetries: 0, signal };\n}\n\n/** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */\nexport function evaluateCacheWarming(\n\tmodel: Model<Api>,\n\tpromptTokens: number,\n\tphase: CacheWarmingPhase,\n): CacheWarmingDecision {\n\tconst cacheHitCost = price(model, { cacheRead: promptTokens });\n\tconst cacheMissCost = price(\n\t\tmodel,\n\t\tmodel.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens },\n\t);\n\tconst warmCost = price(model, { cacheRead: promptTokens, output: 1 });\n\tconst missCost = Math.max(0, cacheMissCost - cacheHitCost);\n\tconst continuationProbability = phase === \"idle\" ? CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY : 1;\n\tconst economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);\n\tconst expectedSavings = continuationProbability * missCost - warmCost;\n\treturn {\n\t\tphase,\n\t\twarmCost,\n\t\tmissCost,\n\t\tcontinuationProbability,\n\t\texpectedSavings,\n\t\teconomicsAvailable,\n\t\taction: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? \"warm\" : \"stop\",\n\t};\n}\n\nfunction price(\n\tmodel: Model<Api>,\n\ttokens: Partial<Pick<Usage, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\">>,\n): number {\n\tconst usage: Usage = {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t...tokens,\n\t};\n\treturn calculateCost(model, usage).total;\n}\n"]}
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { randomUUID } from "node:crypto";
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { createInterface } from "node:readline";
5
5
  import { builtinProviders } from "./providers/all.js";
6
6
  const AUTH_FILE = "auth.json";
@@ -19,7 +19,11 @@ function loadAuth() {
19
19
  }
20
20
  }
21
21
  function saveAuth(auth) {
22
- writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
22
+ // OAuth tokens: readable by the user only. `mode` applies when the file is created; chmod covers a file an older
23
+ // version created, before the new tokens are in it.
24
+ if (existsSync(AUTH_FILE))
25
+ chmodSync(AUTH_FILE, 0o600);
26
+ writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), { encoding: "utf-8", mode: 0o600 });
23
27
  }
24
28
  async function answerPrompt(rl, authPrompt) {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,CAAC,CAAC;gBACzD,CAAC;gBACD,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,EAAE,EAAE,mBAAmB,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;gBAClG,UAAU,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;YACnC,CAAC;oBAAS,CAAC;gBACV,EAAE,CAAC,KAAK,EAAE,CAAC;YACZ,CAAC;QACF,CAAC;QACD,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC;YAC9E,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QACxB,OAAO;IACR,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { AuthPrompt, OAuthCredential, Provider } from \"./index.ts\";\nimport { builtinProviders } from \"./providers/all.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = builtinProviders().filter(\n\t(provider): provider is Provider & { auth: { oauth: NonNullable<Provider[\"auth\"][\"oauth\"]> } } =>\n\t\tprovider.auth.oauth !== undefined,\n);\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, OAuthCredential> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\")) as Record<string, OAuthCredential>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, OAuthCredential>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function answerPrompt(rl: ReturnType<typeof createInterface>, authPrompt: AuthPrompt): Promise<string> {\n\tif (authPrompt.type === \"select\") {\n\t\tconsole.log(`\\n${authPrompt.message}`);\n\t\tfor (let index = 0; index < authPrompt.options.length; index++) {\n\t\t\tconsole.log(` ${index + 1}. ${authPrompt.options[index].label}`);\n\t\t}\n\t\tconst choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;\n\t\tconst selected = authPrompt.options[choice];\n\t\tif (!selected) throw new Error(\"Invalid selection\");\n\t\treturn selected.id;\n\t}\n\treturn prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : \"\"}: `);\n}\n\nasync function login(providerId: string): Promise<void> {\n\tconst provider = PROVIDERS.find((entry) => entry.id === providerId);\n\tif (!provider) throw new Error(`Unknown provider: ${providerId}`);\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\t// This dev CLI does not persist an installation ID; apps should reuse one across logins.\n\t\tconst credential = await provider.auth.oauth.login(\n\t\t\t{\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\tprompt: (authPrompt) => answerPrompt(rl, authPrompt),\n\t\t\t\tnotify: (event) => {\n\t\t\t\t\tswitch (event.type) {\n\t\t\t\t\t\tcase \"auth_url\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.url}`);\n\t\t\t\t\t\t\tif (event.instructions) console.log(event.instructions);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"device_code\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.verificationUri}`);\n\t\t\t\t\t\t\tconsole.log(`Enter code: ${event.userCode}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"info\":\n\t\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\t\tconsole.log(event.message);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ getDeviceId: randomUUID },\n\t\t);\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = credential;\n\t\tsaveAuth(auth);\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\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join(\"\\n\");\n\t\tconsole.log(\n\t\t\t`Usage: npx @earendil-works/pi-ai <command> [provider]\\n\\nCommands:\\n login [provider] Login to an OAuth provider\\n list List available providers\\n\\nProviders:\\n${providerList}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (command === \"list\") {\n\t\tfor (const provider of PROVIDERS) console.log(`${provider.id.padEnd(20)} ${provider.name}`);\n\t\treturn;\n\t}\n\tif (command === \"login\") {\n\t\tlet providerId = args[1];\n\t\tif (!providerId) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tfor (let index = 0; index < PROVIDERS.length; index++) {\n\t\t\t\t\tconsole.log(` ${index + 1}. ${PROVIDERS[index].name}`);\n\t\t\t\t}\n\t\t\t\tconst index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;\n\t\t\t\tproviderId = PROVIDERS[index]?.id;\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t}\n\t\tif (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {\n\t\t\tthrow new Error(`Unknown provider: ${providerId ?? \"\"}`);\n\t\t}\n\t\tawait login(providerId);\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(\"Error:\", error instanceof Error ? error.message : String(error));\n\tprocess.exit(1);\n});\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,SAAS,GAAG,WAAW,CAAC;AAC9B,MAAM,SAAS,GAAG,gBAAgB,EAAE,CAAC,MAAM,CAC1C,CAAC,QAAQ,EAAsF,EAAE,CAChG,QAAQ,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,CAClC,CAAC;AAEF,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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ED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { chmodSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { AuthPrompt, OAuthCredential, Provider } from \"./index.ts\";\nimport { builtinProviders } from \"./providers/all.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = builtinProviders().filter(\n\t(provider): provider is Provider & { auth: { oauth: NonNullable<Provider[\"auth\"][\"oauth\"]> } } =>\n\t\tprovider.auth.oauth !== undefined,\n);\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, OAuthCredential> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\")) as Record<string, OAuthCredential>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, OAuthCredential>): void {\n\t// OAuth tokens: readable by the user only. `mode` applies when the file is created; chmod covers a file an older\n\t// version created, before the new tokens are in it.\n\tif (existsSync(AUTH_FILE)) chmodSync(AUTH_FILE, 0o600);\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), { encoding: \"utf-8\", mode: 0o600 });\n}\n\nasync function answerPrompt(rl: ReturnType<typeof createInterface>, authPrompt: AuthPrompt): Promise<string> {\n\tif (authPrompt.type === \"select\") {\n\t\tconsole.log(`\\n${authPrompt.message}`);\n\t\tfor (let index = 0; index < authPrompt.options.length; index++) {\n\t\t\tconsole.log(` ${index + 1}. ${authPrompt.options[index].label}`);\n\t\t}\n\t\tconst choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;\n\t\tconst selected = authPrompt.options[choice];\n\t\tif (!selected) throw new Error(\"Invalid selection\");\n\t\treturn selected.id;\n\t}\n\treturn prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : \"\"}: `);\n}\n\nasync function login(providerId: string): Promise<void> {\n\tconst provider = PROVIDERS.find((entry) => entry.id === providerId);\n\tif (!provider) throw new Error(`Unknown provider: ${providerId}`);\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\t// This dev CLI does not persist an installation ID; apps should reuse one across logins.\n\t\tconst credential = await provider.auth.oauth.login(\n\t\t\t{\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\tprompt: (authPrompt) => answerPrompt(rl, authPrompt),\n\t\t\t\tnotify: (event) => {\n\t\t\t\t\tswitch (event.type) {\n\t\t\t\t\t\tcase \"auth_url\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.url}`);\n\t\t\t\t\t\t\tif (event.instructions) console.log(event.instructions);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"device_code\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.verificationUri}`);\n\t\t\t\t\t\t\tconsole.log(`Enter code: ${event.userCode}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"info\":\n\t\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\t\tconsole.log(event.message);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ getDeviceId: randomUUID },\n\t\t);\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = credential;\n\t\tsaveAuth(auth);\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\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join(\"\\n\");\n\t\tconsole.log(\n\t\t\t`Usage: npx @earendil-works/pi-ai <command> [provider]\\n\\nCommands:\\n login [provider] Login to an OAuth provider\\n list List available providers\\n\\nProviders:\\n${providerList}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (command === \"list\") {\n\t\tfor (const provider of PROVIDERS) console.log(`${provider.id.padEnd(20)} ${provider.name}`);\n\t\treturn;\n\t}\n\tif (command === \"login\") {\n\t\tlet providerId = args[1];\n\t\tif (!providerId) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tfor (let index = 0; index < PROVIDERS.length; index++) {\n\t\t\t\t\tconsole.log(` ${index + 1}. ${PROVIDERS[index].name}`);\n\t\t\t\t}\n\t\t\t\tconst index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;\n\t\t\t\tproviderId = PROVIDERS[index]?.id;\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t}\n\t\tif (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {\n\t\t\tthrow new Error(`Unknown provider: ${providerId ?? \"\"}`);\n\t\t}\n\t\tawait login(providerId);\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(\"Error:\", error instanceof Error ? error.message : String(error));\n\tprocess.exit(1);\n});\n"]}
@@ -14,6 +14,10 @@ export interface OAuthAuthInfo {
14
14
  export interface OAuthDeviceCodeInfo {
15
15
  userCode: string;
16
16
  verificationUri: string;
17
+ /** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */
18
+ openBrowserOnConfirm?: boolean;
19
+ /** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */
20
+ copyCodeOnConfirm?: boolean;
17
21
  intervalSeconds?: number;
18
22
  expiresInSeconds?: number;
19
23
  }
@@ -1 +1 @@
1
- {"version":3,"file":"extension-oauth-types.d.ts","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,uDAAuD;AACvD,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC7B;AAED,+EAA+E;AAC/E,MAAM,WAAW,mBAAmB;IACnC,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;IAClC,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,UAAU,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjE,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
1
+ {"version":3,"file":"extension-oauth-types.d.ts","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,uDAAuD;AACvD,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,uGAAuG;IACvG,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,iGAAiG;IACjG,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC7B;AAED,+EAA+E;AAC/E,MAAM,WAAW,mBAAmB;IACnC,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;IAClC,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,UAAU,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjE,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"extension-oauth-types.js","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OAuthCredentials } from \"../auth/types.ts\";\n\n/** Legacy extension OAuth prompt. */\nexport interface OAuthPrompt {\n\tmessage: string;\n\tplaceholder?: string;\n\tallowEmpty?: boolean;\n}\n\n/** Legacy extension OAuth authorization link. */\nexport interface OAuthAuthInfo {\n\turl: string;\n\tinstructions?: string;\n}\n\n/** Legacy extension OAuth device-code notification. */\nexport interface OAuthDeviceCodeInfo {\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n}\n\nexport interface OAuthSelectOption {\n\tid: string;\n\tlabel: string;\n}\n\nexport interface OAuthSelectPrompt {\n\tmessage: string;\n\toptions: OAuthSelectOption[];\n}\n\n/** Callback surface retained only for coding-agent extension compatibility. */\nexport interface OAuthLoginCallbacks {\n\tonAuth(info: OAuthAuthInfo): void;\n\tonDeviceCode(info: OAuthDeviceCodeInfo): void;\n\tonPrompt(prompt: OAuthPrompt): Promise<string>;\n\tonProgress?(message: string): void;\n\tonManualCodeInput?(): Promise<string>;\n\tonSelect(prompt: OAuthSelectPrompt): Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}\n\nexport type { OAuthCredentials };\n"]}
1
+ {"version":3,"file":"extension-oauth-types.js","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OAuthCredentials } from \"../auth/types.ts\";\n\n/** Legacy extension OAuth prompt. */\nexport interface OAuthPrompt {\n\tmessage: string;\n\tplaceholder?: string;\n\tallowEmpty?: boolean;\n}\n\n/** Legacy extension OAuth authorization link. */\nexport interface OAuthAuthInfo {\n\turl: string;\n\tinstructions?: string;\n}\n\n/** Legacy extension OAuth device-code notification. */\nexport interface OAuthDeviceCodeInfo {\n\tuserCode: string;\n\tverificationUri: string;\n\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\topenBrowserOnConfirm?: boolean;\n\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\tcopyCodeOnConfirm?: boolean;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n}\n\nexport interface OAuthSelectOption {\n\tid: string;\n\tlabel: string;\n}\n\nexport interface OAuthSelectPrompt {\n\tmessage: string;\n\toptions: OAuthSelectOption[];\n}\n\n/** Callback surface retained only for coding-agent extension compatibility. */\nexport interface OAuthLoginCallbacks {\n\tonAuth(info: OAuthAuthInfo): void;\n\tonDeviceCode(info: OAuthDeviceCodeInfo): void;\n\tonPrompt(prompt: OAuthPrompt): Promise<string>;\n\tonProgress?(message: string): void;\n\tonManualCodeInput?(): Promise<string>;\n\tonSelect(prompt: OAuthSelectPrompt): Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}\n\nexport type { OAuthCredentials };\n"]}
@@ -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;AAG7D,eAAO,MAAM,wBAAwB,yBAAyB,CAAC;AAC/D,eAAO,MAAM,yBAAyB,0BAA0B,CAAC;AACjE,eAAO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,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"}
@@ -79,6 +79,7 @@ function getApiKeyEnvVars(provider) {
79
79
  "qwen-token-plan": "QWEN_TOKEN_PLAN_API_KEY",
80
80
  "qwen-token-plan-cn": "QWEN_TOKEN_PLAN_CN_API_KEY",
81
81
  "qwen-token-plan-individual": "QWEN_TOKEN_PLAN_API_KEY",
82
+ "qwen-token-plan-individual-cn": "QWEN_TOKEN_PLAN_CN_API_KEY",
82
83
  openai: "OPENAI_API_KEY",
83
84
  azure: "AZURE_OPENAI_API_KEY",
84
85
  nvidia: "NVIDIA_API_KEY",