@mastra/code-sdk 1.21.0-alpha.6 → 1.21.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (584) hide show
  1. package/dist/acp/agent.js +0 -2
  2. package/dist/acp/errors.js +0 -2
  3. package/dist/acp/event-mapper.js +0 -2
  4. package/dist/acp/index.js +0 -2
  5. package/dist/acp/runtime.js +0 -2
  6. package/dist/acp/server.js +0 -2
  7. package/dist/acp/skills.js +0 -2
  8. package/dist/agent-connections/messaging-processor.js +0 -2
  9. package/dist/agent-connections/ownership.js +0 -2
  10. package/dist/agent-connections/registry.js +0 -2
  11. package/dist/agent-connections/session-advertisement.js +0 -2
  12. package/dist/agent-connections/signal-provider.js +0 -2
  13. package/dist/agent-connections/state-processor.js +0 -2
  14. package/dist/agent-connections/thread-state.js +0 -2
  15. package/dist/agent-connections/tools.js +0 -2
  16. package/dist/agent-connections/types.js +0 -2
  17. package/dist/agent-connections/untrusted-text.js +0 -2
  18. package/dist/agents/background-completion-events.js +0 -2
  19. package/dist/agents/background-completion.js +0 -2
  20. package/dist/agents/context-audit.js +0 -2
  21. package/dist/agents/credential-resolver.js +0 -2
  22. package/dist/agents/custom-provider-source.js +0 -2
  23. package/dist/agents/fastembed-subprocess.d.ts +21 -0
  24. package/dist/agents/fastembed-subprocess.js +88 -8
  25. package/dist/agents/instructions.js +0 -2
  26. package/dist/agents/mastracode-gateway.d.ts +3 -1
  27. package/dist/agents/mastracode-gateway.js +11 -5
  28. package/dist/agents/memory.js +0 -2
  29. package/dist/agents/model.js +15 -8
  30. package/dist/agents/modes/build.js +0 -2
  31. package/dist/agents/modes/explore.js +0 -2
  32. package/dist/agents/modes/plan.js +0 -2
  33. package/dist/agents/prompts/agent-instructions.js +0 -2
  34. package/dist/agents/prompts/build.js +0 -2
  35. package/dist/agents/prompts/fast.js +0 -2
  36. package/dist/agents/prompts/index.js +0 -2
  37. package/dist/agents/prompts/model.js +0 -2
  38. package/dist/agents/prompts/plan.js +0 -2
  39. package/dist/agents/prompts/tool-guidance.js +0 -2
  40. package/dist/agents/sandbox-filesystem.js +0 -2
  41. package/dist/agents/subagents/execute.js +0 -2
  42. package/dist/agents/subagents/explore.js +0 -2
  43. package/dist/agents/subagents/index.js +0 -2
  44. package/dist/agents/subagents/plan.js +0 -2
  45. package/dist/agents/thread-caveman-state.js +0 -2
  46. package/dist/agents/tool-availability.js +0 -2
  47. package/dist/agents/tools.js +0 -2
  48. package/dist/agents/workflow-builder-agent.js +0 -2
  49. package/dist/agents/workspace.js +0 -2
  50. package/dist/analytics.js +0 -2
  51. package/dist/auth/account-rotation-processor.js +3 -5
  52. package/dist/auth/account-routing-context.js +0 -2
  53. package/dist/auth/authorization-input.js +0 -2
  54. package/dist/auth/device-code.js +0 -2
  55. package/dist/auth/pkce.js +0 -2
  56. package/dist/auth/provider-auth-error.js +0 -2
  57. package/dist/auth/providers/anthropic.js +0 -2
  58. package/dist/auth/providers/github-copilot.js +0 -2
  59. package/dist/auth/providers/kimi-coding.js +0 -2
  60. package/dist/auth/providers/openai-codex.js +0 -2
  61. package/dist/auth/providers/xai.js +0 -2
  62. package/dist/auth/storage.js +0 -2
  63. package/dist/clipboard/index.js +0 -2
  64. package/dist/constants.js +0 -2
  65. package/dist/error-classification.js +0 -2
  66. package/dist/evals/context-builder.js +0 -2
  67. package/dist/evals/scorers/classify-command.js +0 -2
  68. package/dist/evals/scorers/efficiency.js +0 -2
  69. package/dist/evals/scorers/extract-tools.js +0 -2
  70. package/dist/evals/scorers/outcome.js +0 -2
  71. package/dist/experimental-agent.js +0 -2
  72. package/dist/factory/client.js +0 -2
  73. package/dist/factory/remote-controller.js +0 -2
  74. package/dist/factory/remote-session.js +0 -2
  75. package/dist/goal-manager.js +0 -2
  76. package/dist/goal-signal.js +0 -2
  77. package/dist/headless/cli.js +5 -2
  78. package/dist/headless/flags.js +0 -2
  79. package/dist/headless/format.js +0 -2
  80. package/dist/headless/policy.js +0 -2
  81. package/dist/headless/run-mc.js +7 -4
  82. package/dist/headless/types.js +0 -2
  83. package/dist/hooks/config.js +0 -2
  84. package/dist/hooks/executor.js +0 -2
  85. package/dist/hooks/manager.js +0 -2
  86. package/dist/hooks/types.js +0 -2
  87. package/dist/index.js +5 -5
  88. package/dist/ipc/ipc-reporter.js +0 -2
  89. package/dist/knowledge-inspector.js +0 -2
  90. package/dist/knowledge-scope-id.js +0 -2
  91. package/dist/knowledge-scope.js +0 -2
  92. package/dist/lsp/client.js +0 -2
  93. package/dist/lsp/language.js +0 -2
  94. package/dist/lsp/manager.js +0 -2
  95. package/dist/lsp/server.js +0 -2
  96. package/dist/lsp/workspace.js +0 -2
  97. package/dist/mcp/config.js +0 -2
  98. package/dist/mcp/manager.js +0 -2
  99. package/dist/mcp/state.js +0 -2
  100. package/dist/onboarding/custom-packs.js +0 -2
  101. package/dist/onboarding/custom-providers.js +0 -2
  102. package/dist/onboarding/om-settings.js +0 -2
  103. package/dist/onboarding/pack-activation.js +0 -2
  104. package/dist/onboarding/packs.js +0 -2
  105. package/dist/onboarding/settings.js +0 -2
  106. package/dist/permissions.js +0 -2
  107. package/dist/platform/index.js +0 -2
  108. package/dist/plugin.js +0 -2
  109. package/dist/plugins/dependencies.js +0 -2
  110. package/dist/plugins/install.js +0 -2
  111. package/dist/plugins/loader.js +0 -2
  112. package/dist/plugins/manager.js +0 -2
  113. package/dist/plugins/manifest.js +0 -2
  114. package/dist/plugins/package-link.js +0 -2
  115. package/dist/plugins/paths.js +0 -2
  116. package/dist/plugins/registry.js +0 -2
  117. package/dist/plugins/scaffold.js +0 -2
  118. package/dist/plugins/signal-lane.js +0 -2
  119. package/dist/process-memory-diagnostics.js +0 -2
  120. package/dist/processors/plan-rejection-abort.js +0 -2
  121. package/dist/providers/amazon-bedrock-gateway.js +0 -2
  122. package/dist/providers/amazon-bedrock.js +0 -2
  123. package/dist/providers/anthropic-prompt-cache.js +0 -2
  124. package/dist/providers/anthropic-thinking.js +0 -2
  125. package/dist/providers/claude-max.js +0 -2
  126. package/dist/providers/github-copilot-gateway.js +0 -2
  127. package/dist/providers/github-copilot.js +0 -2
  128. package/dist/providers/google-thinking.js +0 -2
  129. package/dist/providers/google-vertex-gateway.js +0 -2
  130. package/dist/providers/google-vertex.js +0 -2
  131. package/dist/providers/kimi-coding.js +0 -2
  132. package/dist/providers/model-ids.d.ts +22 -0
  133. package/dist/providers/model-ids.js +55 -3
  134. package/dist/providers/openai-codex.d.ts +5 -1
  135. package/dist/providers/openai-codex.js +7 -6
  136. package/dist/providers/provider-thinking.js +0 -2
  137. package/dist/providers/thinking-request.js +0 -2
  138. package/dist/providers/xai.js +0 -2
  139. package/dist/schedules/interval.js +0 -2
  140. package/dist/schedules/prompt.js +0 -2
  141. package/dist/schedules/run-script.js +0 -2
  142. package/dist/schedules/scheduler.js +0 -2
  143. package/dist/schedules/tools.js +0 -2
  144. package/dist/schema.js +0 -2
  145. package/dist/theme-palette.js +0 -2
  146. package/dist/thinking-catalog.d.ts +2 -2
  147. package/dist/thinking-catalog.js +5 -4
  148. package/dist/thinking.js +0 -2
  149. package/dist/tool-names.js +0 -2
  150. package/dist/tools/request-sandbox-access.js +0 -2
  151. package/dist/tools/utils.js +0 -2
  152. package/dist/tools/web-search.js +0 -2
  153. package/dist/tools/workflows/create-workflow.js +0 -2
  154. package/dist/tools/workflows/delete-workflow.js +0 -2
  155. package/dist/tools/workflows/ephemeral-memory.js +0 -2
  156. package/dist/tools/workflows/extract-json-schema.js +0 -2
  157. package/dist/tools/workflows/get-workflow.js +0 -2
  158. package/dist/tools/workflows/list-available-agents.js +0 -2
  159. package/dist/tools/workflows/list-available-classifiers.js +0 -2
  160. package/dist/tools/workflows/list-available-tools.js +0 -2
  161. package/dist/tools/workflows/list-available-workflows.js +0 -2
  162. package/dist/tools/workflows/list-workflows.js +0 -2
  163. package/dist/tools/workflows/run-workflow.js +0 -2
  164. package/dist/tools/workflows/save-workflow.js +0 -2
  165. package/dist/tools/workflows/tool-ids.js +0 -2
  166. package/dist/utils/binaries.js +0 -2
  167. package/dist/utils/debug-log.js +0 -2
  168. package/dist/utils/discarding-scores-storage.js +0 -2
  169. package/dist/utils/errors.js +0 -2
  170. package/dist/utils/gateway-sync.js +0 -2
  171. package/dist/utils/local-observability.js +0 -2
  172. package/dist/utils/maintenance-lock.js +0 -2
  173. package/dist/utils/notification-dispatch.js +0 -2
  174. package/dist/utils/open-url.js +0 -2
  175. package/dist/utils/path-security.js +0 -2
  176. package/dist/utils/plan-diff.js +0 -2
  177. package/dist/utils/plans.js +0 -2
  178. package/dist/utils/project.js +0 -2
  179. package/dist/utils/prune-cli.js +0 -2
  180. package/dist/utils/signals-pubsub.js +0 -2
  181. package/dist/utils/slash-command-loader.js +0 -2
  182. package/dist/utils/slash-command-processor.js +0 -2
  183. package/dist/utils/stdin-pipe.js +0 -2
  184. package/dist/utils/storage-factory.js +0 -2
  185. package/dist/utils/storage-maintenance.js +0 -2
  186. package/dist/utils/thread-lock.js +0 -2
  187. package/dist/utils/token-estimator.js +0 -2
  188. package/dist/utils/update-check.js +0 -2
  189. package/dist/utils/wake-session.js +0 -2
  190. package/dist/voice/stt-registry.js +0 -2
  191. package/dist/voice/transcribe.js +0 -2
  192. package/dist/workflows/register-primitives.js +0 -2
  193. package/dist/workflows/service.js +0 -2
  194. package/package.json +24 -23
  195. package/dist/acp/agent.d.ts.map +0 -1
  196. package/dist/acp/agent.js.map +0 -1
  197. package/dist/acp/errors.d.ts.map +0 -1
  198. package/dist/acp/errors.js.map +0 -1
  199. package/dist/acp/event-mapper.d.ts.map +0 -1
  200. package/dist/acp/event-mapper.js.map +0 -1
  201. package/dist/acp/index.d.ts.map +0 -1
  202. package/dist/acp/index.js.map +0 -1
  203. package/dist/acp/runtime.d.ts.map +0 -1
  204. package/dist/acp/runtime.js.map +0 -1
  205. package/dist/acp/server.d.ts.map +0 -1
  206. package/dist/acp/server.js.map +0 -1
  207. package/dist/acp/skills.d.ts.map +0 -1
  208. package/dist/acp/skills.js.map +0 -1
  209. package/dist/acp.d.ts.map +0 -1
  210. package/dist/agent-connections/messaging-processor.d.ts.map +0 -1
  211. package/dist/agent-connections/messaging-processor.js.map +0 -1
  212. package/dist/agent-connections/ownership.d.ts.map +0 -1
  213. package/dist/agent-connections/ownership.js.map +0 -1
  214. package/dist/agent-connections/registry.d.ts.map +0 -1
  215. package/dist/agent-connections/registry.js.map +0 -1
  216. package/dist/agent-connections/session-advertisement.d.ts.map +0 -1
  217. package/dist/agent-connections/session-advertisement.js.map +0 -1
  218. package/dist/agent-connections/signal-provider.d.ts.map +0 -1
  219. package/dist/agent-connections/signal-provider.js.map +0 -1
  220. package/dist/agent-connections/state-processor.d.ts.map +0 -1
  221. package/dist/agent-connections/state-processor.js.map +0 -1
  222. package/dist/agent-connections/thread-state.d.ts.map +0 -1
  223. package/dist/agent-connections/thread-state.js.map +0 -1
  224. package/dist/agent-connections/tools.d.ts.map +0 -1
  225. package/dist/agent-connections/tools.js.map +0 -1
  226. package/dist/agent-connections/types.d.ts.map +0 -1
  227. package/dist/agent-connections/types.js.map +0 -1
  228. package/dist/agent-connections/untrusted-text.d.ts.map +0 -1
  229. package/dist/agent-connections/untrusted-text.js.map +0 -1
  230. package/dist/agents/background-completion-events.d.ts.map +0 -1
  231. package/dist/agents/background-completion-events.js.map +0 -1
  232. package/dist/agents/background-completion.d.ts.map +0 -1
  233. package/dist/agents/background-completion.js.map +0 -1
  234. package/dist/agents/context-audit.d.ts.map +0 -1
  235. package/dist/agents/context-audit.js.map +0 -1
  236. package/dist/agents/credential-resolver.d.ts.map +0 -1
  237. package/dist/agents/credential-resolver.js.map +0 -1
  238. package/dist/agents/custom-provider-source.d.ts.map +0 -1
  239. package/dist/agents/custom-provider-source.js.map +0 -1
  240. package/dist/agents/fastembed-subprocess.d.ts.map +0 -1
  241. package/dist/agents/fastembed-subprocess.js.map +0 -1
  242. package/dist/agents/instructions.d.ts.map +0 -1
  243. package/dist/agents/instructions.js.map +0 -1
  244. package/dist/agents/mastracode-gateway.d.ts.map +0 -1
  245. package/dist/agents/mastracode-gateway.js.map +0 -1
  246. package/dist/agents/memory.d.ts.map +0 -1
  247. package/dist/agents/memory.js.map +0 -1
  248. package/dist/agents/model.d.ts.map +0 -1
  249. package/dist/agents/model.js.map +0 -1
  250. package/dist/agents/modes/build.d.ts.map +0 -1
  251. package/dist/agents/modes/build.js.map +0 -1
  252. package/dist/agents/modes/explore.d.ts.map +0 -1
  253. package/dist/agents/modes/explore.js.map +0 -1
  254. package/dist/agents/modes/plan.d.ts.map +0 -1
  255. package/dist/agents/modes/plan.js.map +0 -1
  256. package/dist/agents/prompts/agent-instructions.d.ts.map +0 -1
  257. package/dist/agents/prompts/agent-instructions.js.map +0 -1
  258. package/dist/agents/prompts/build.d.ts.map +0 -1
  259. package/dist/agents/prompts/build.js.map +0 -1
  260. package/dist/agents/prompts/fast.d.ts.map +0 -1
  261. package/dist/agents/prompts/fast.js.map +0 -1
  262. package/dist/agents/prompts/index.d.ts.map +0 -1
  263. package/dist/agents/prompts/index.js.map +0 -1
  264. package/dist/agents/prompts/model.d.ts.map +0 -1
  265. package/dist/agents/prompts/model.js.map +0 -1
  266. package/dist/agents/prompts/plan.d.ts.map +0 -1
  267. package/dist/agents/prompts/plan.js.map +0 -1
  268. package/dist/agents/prompts/tool-guidance.d.ts.map +0 -1
  269. package/dist/agents/prompts/tool-guidance.js.map +0 -1
  270. package/dist/agents/sandbox-filesystem.d.ts.map +0 -1
  271. package/dist/agents/sandbox-filesystem.js.map +0 -1
  272. package/dist/agents/subagents/execute.d.ts.map +0 -1
  273. package/dist/agents/subagents/execute.js.map +0 -1
  274. package/dist/agents/subagents/explore.d.ts.map +0 -1
  275. package/dist/agents/subagents/explore.js.map +0 -1
  276. package/dist/agents/subagents/index.d.ts.map +0 -1
  277. package/dist/agents/subagents/index.js.map +0 -1
  278. package/dist/agents/subagents/plan.d.ts.map +0 -1
  279. package/dist/agents/subagents/plan.js.map +0 -1
  280. package/dist/agents/thread-caveman-state.d.ts.map +0 -1
  281. package/dist/agents/thread-caveman-state.js.map +0 -1
  282. package/dist/agents/tool-availability.d.ts.map +0 -1
  283. package/dist/agents/tool-availability.js.map +0 -1
  284. package/dist/agents/tools.d.ts.map +0 -1
  285. package/dist/agents/tools.js.map +0 -1
  286. package/dist/agents/workflow-builder-agent.d.ts.map +0 -1
  287. package/dist/agents/workflow-builder-agent.js.map +0 -1
  288. package/dist/agents/workspace.d.ts.map +0 -1
  289. package/dist/agents/workspace.js.map +0 -1
  290. package/dist/analytics.d.ts.map +0 -1
  291. package/dist/analytics.js.map +0 -1
  292. package/dist/auth/account-rotation-processor.d.ts.map +0 -1
  293. package/dist/auth/account-rotation-processor.js.map +0 -1
  294. package/dist/auth/account-routing-context.d.ts.map +0 -1
  295. package/dist/auth/account-routing-context.js.map +0 -1
  296. package/dist/auth/authorization-input.d.ts.map +0 -1
  297. package/dist/auth/authorization-input.js.map +0 -1
  298. package/dist/auth/device-code.d.ts.map +0 -1
  299. package/dist/auth/device-code.js.map +0 -1
  300. package/dist/auth/index.d.ts.map +0 -1
  301. package/dist/auth/pkce.d.ts.map +0 -1
  302. package/dist/auth/pkce.js.map +0 -1
  303. package/dist/auth/provider-auth-error.d.ts.map +0 -1
  304. package/dist/auth/provider-auth-error.js.map +0 -1
  305. package/dist/auth/providers/anthropic.d.ts.map +0 -1
  306. package/dist/auth/providers/anthropic.js.map +0 -1
  307. package/dist/auth/providers/github-copilot.d.ts.map +0 -1
  308. package/dist/auth/providers/github-copilot.js.map +0 -1
  309. package/dist/auth/providers/kimi-coding.d.ts.map +0 -1
  310. package/dist/auth/providers/kimi-coding.js.map +0 -1
  311. package/dist/auth/providers/openai-codex.d.ts.map +0 -1
  312. package/dist/auth/providers/openai-codex.js.map +0 -1
  313. package/dist/auth/providers/xai.d.ts.map +0 -1
  314. package/dist/auth/providers/xai.js.map +0 -1
  315. package/dist/auth/storage.d.ts.map +0 -1
  316. package/dist/auth/storage.js.map +0 -1
  317. package/dist/auth/types.d.ts.map +0 -1
  318. package/dist/clipboard/index.d.ts.map +0 -1
  319. package/dist/clipboard/index.js.map +0 -1
  320. package/dist/constants.d.ts.map +0 -1
  321. package/dist/constants.js.map +0 -1
  322. package/dist/error-classification.d.ts.map +0 -1
  323. package/dist/error-classification.js.map +0 -1
  324. package/dist/evals/context-builder.d.ts.map +0 -1
  325. package/dist/evals/context-builder.js.map +0 -1
  326. package/dist/evals/index.d.ts.map +0 -1
  327. package/dist/evals/scorers/classify-command.d.ts.map +0 -1
  328. package/dist/evals/scorers/classify-command.js.map +0 -1
  329. package/dist/evals/scorers/efficiency.d.ts.map +0 -1
  330. package/dist/evals/scorers/efficiency.js.map +0 -1
  331. package/dist/evals/scorers/extract-tools.d.ts.map +0 -1
  332. package/dist/evals/scorers/extract-tools.js.map +0 -1
  333. package/dist/evals/scorers/index.d.ts.map +0 -1
  334. package/dist/evals/scorers/outcome.d.ts.map +0 -1
  335. package/dist/evals/scorers/outcome.js.map +0 -1
  336. package/dist/experimental-agent.d.ts.map +0 -1
  337. package/dist/experimental-agent.js.map +0 -1
  338. package/dist/factory/client.d.ts.map +0 -1
  339. package/dist/factory/client.js.map +0 -1
  340. package/dist/factory/remote-controller.d.ts.map +0 -1
  341. package/dist/factory/remote-controller.js.map +0 -1
  342. package/dist/factory/remote-session.d.ts.map +0 -1
  343. package/dist/factory/remote-session.js.map +0 -1
  344. package/dist/goal-manager.d.ts.map +0 -1
  345. package/dist/goal-manager.js.map +0 -1
  346. package/dist/goal-signal.d.ts.map +0 -1
  347. package/dist/goal-signal.js.map +0 -1
  348. package/dist/headless/cli.d.ts.map +0 -1
  349. package/dist/headless/cli.js.map +0 -1
  350. package/dist/headless/flags.d.ts.map +0 -1
  351. package/dist/headless/flags.js.map +0 -1
  352. package/dist/headless/format.d.ts.map +0 -1
  353. package/dist/headless/format.js.map +0 -1
  354. package/dist/headless/index.d.ts.map +0 -1
  355. package/dist/headless/policy.d.ts.map +0 -1
  356. package/dist/headless/policy.js.map +0 -1
  357. package/dist/headless/run-mc.d.ts.map +0 -1
  358. package/dist/headless/run-mc.js.map +0 -1
  359. package/dist/headless/types.d.ts.map +0 -1
  360. package/dist/headless/types.js.map +0 -1
  361. package/dist/hooks/config.d.ts.map +0 -1
  362. package/dist/hooks/config.js.map +0 -1
  363. package/dist/hooks/executor.d.ts.map +0 -1
  364. package/dist/hooks/executor.js.map +0 -1
  365. package/dist/hooks/index.d.ts.map +0 -1
  366. package/dist/hooks/manager.d.ts.map +0 -1
  367. package/dist/hooks/manager.js.map +0 -1
  368. package/dist/hooks/types.d.ts.map +0 -1
  369. package/dist/hooks/types.js.map +0 -1
  370. package/dist/index.d.ts.map +0 -1
  371. package/dist/index.js.map +0 -1
  372. package/dist/ipc/ipc-reporter.d.ts.map +0 -1
  373. package/dist/ipc/ipc-reporter.js.map +0 -1
  374. package/dist/knowledge-inspector.d.ts.map +0 -1
  375. package/dist/knowledge-inspector.js.map +0 -1
  376. package/dist/knowledge-scope-id.d.ts.map +0 -1
  377. package/dist/knowledge-scope-id.js.map +0 -1
  378. package/dist/knowledge-scope.d.ts.map +0 -1
  379. package/dist/knowledge-scope.js.map +0 -1
  380. package/dist/lsp/client.d.ts.map +0 -1
  381. package/dist/lsp/client.js.map +0 -1
  382. package/dist/lsp/index.d.ts.map +0 -1
  383. package/dist/lsp/language.d.ts.map +0 -1
  384. package/dist/lsp/language.js.map +0 -1
  385. package/dist/lsp/manager.d.ts.map +0 -1
  386. package/dist/lsp/manager.js.map +0 -1
  387. package/dist/lsp/server.d.ts.map +0 -1
  388. package/dist/lsp/server.js.map +0 -1
  389. package/dist/lsp/workspace.d.ts.map +0 -1
  390. package/dist/lsp/workspace.js.map +0 -1
  391. package/dist/mcp/config.d.ts.map +0 -1
  392. package/dist/mcp/config.js.map +0 -1
  393. package/dist/mcp/index.d.ts.map +0 -1
  394. package/dist/mcp/manager.d.ts.map +0 -1
  395. package/dist/mcp/manager.js.map +0 -1
  396. package/dist/mcp/state.d.ts.map +0 -1
  397. package/dist/mcp/state.js.map +0 -1
  398. package/dist/mcp/types.d.ts.map +0 -1
  399. package/dist/onboarding/custom-packs.d.ts.map +0 -1
  400. package/dist/onboarding/custom-packs.js.map +0 -1
  401. package/dist/onboarding/custom-providers.d.ts.map +0 -1
  402. package/dist/onboarding/custom-providers.js.map +0 -1
  403. package/dist/onboarding/index.d.ts.map +0 -1
  404. package/dist/onboarding/om-settings.d.ts.map +0 -1
  405. package/dist/onboarding/om-settings.js.map +0 -1
  406. package/dist/onboarding/pack-activation.d.ts.map +0 -1
  407. package/dist/onboarding/pack-activation.js.map +0 -1
  408. package/dist/onboarding/packs.d.ts.map +0 -1
  409. package/dist/onboarding/packs.js.map +0 -1
  410. package/dist/onboarding/settings.d.ts.map +0 -1
  411. package/dist/onboarding/settings.js.map +0 -1
  412. package/dist/permissions.d.ts.map +0 -1
  413. package/dist/permissions.js.map +0 -1
  414. package/dist/platform/index.d.ts.map +0 -1
  415. package/dist/platform/index.js.map +0 -1
  416. package/dist/plugin.d.ts.map +0 -1
  417. package/dist/plugin.js.map +0 -1
  418. package/dist/plugins/dependencies.d.ts.map +0 -1
  419. package/dist/plugins/dependencies.js.map +0 -1
  420. package/dist/plugins/install.d.ts.map +0 -1
  421. package/dist/plugins/install.js.map +0 -1
  422. package/dist/plugins/loader.d.ts.map +0 -1
  423. package/dist/plugins/loader.js.map +0 -1
  424. package/dist/plugins/manager.d.ts.map +0 -1
  425. package/dist/plugins/manager.js.map +0 -1
  426. package/dist/plugins/manifest.d.ts.map +0 -1
  427. package/dist/plugins/manifest.js.map +0 -1
  428. package/dist/plugins/package-link.d.ts.map +0 -1
  429. package/dist/plugins/package-link.js.map +0 -1
  430. package/dist/plugins/paths.d.ts.map +0 -1
  431. package/dist/plugins/paths.js.map +0 -1
  432. package/dist/plugins/registry.d.ts.map +0 -1
  433. package/dist/plugins/registry.js.map +0 -1
  434. package/dist/plugins/scaffold.d.ts.map +0 -1
  435. package/dist/plugins/scaffold.js.map +0 -1
  436. package/dist/plugins/signal-lane.d.ts.map +0 -1
  437. package/dist/plugins/signal-lane.js.map +0 -1
  438. package/dist/plugins/types.d.ts.map +0 -1
  439. package/dist/process-memory-diagnostics.d.ts.map +0 -1
  440. package/dist/process-memory-diagnostics.js.map +0 -1
  441. package/dist/processors/plan-rejection-abort.d.ts.map +0 -1
  442. package/dist/processors/plan-rejection-abort.js.map +0 -1
  443. package/dist/providers/amazon-bedrock-gateway.d.ts.map +0 -1
  444. package/dist/providers/amazon-bedrock-gateway.js.map +0 -1
  445. package/dist/providers/amazon-bedrock.d.ts.map +0 -1
  446. package/dist/providers/amazon-bedrock.js.map +0 -1
  447. package/dist/providers/anthropic-prompt-cache.d.ts.map +0 -1
  448. package/dist/providers/anthropic-prompt-cache.js.map +0 -1
  449. package/dist/providers/anthropic-thinking.d.ts.map +0 -1
  450. package/dist/providers/anthropic-thinking.js.map +0 -1
  451. package/dist/providers/claude-max.d.ts.map +0 -1
  452. package/dist/providers/claude-max.js.map +0 -1
  453. package/dist/providers/github-copilot-gateway.d.ts.map +0 -1
  454. package/dist/providers/github-copilot-gateway.js.map +0 -1
  455. package/dist/providers/github-copilot.d.ts.map +0 -1
  456. package/dist/providers/github-copilot.js.map +0 -1
  457. package/dist/providers/google-thinking.d.ts.map +0 -1
  458. package/dist/providers/google-thinking.js.map +0 -1
  459. package/dist/providers/google-vertex-gateway.d.ts.map +0 -1
  460. package/dist/providers/google-vertex-gateway.js.map +0 -1
  461. package/dist/providers/google-vertex.d.ts.map +0 -1
  462. package/dist/providers/google-vertex.js.map +0 -1
  463. package/dist/providers/kimi-coding.d.ts.map +0 -1
  464. package/dist/providers/kimi-coding.js.map +0 -1
  465. package/dist/providers/model-ids.d.ts.map +0 -1
  466. package/dist/providers/model-ids.js.map +0 -1
  467. package/dist/providers/openai-codex.d.ts.map +0 -1
  468. package/dist/providers/openai-codex.js.map +0 -1
  469. package/dist/providers/provider-thinking.d.ts.map +0 -1
  470. package/dist/providers/provider-thinking.js.map +0 -1
  471. package/dist/providers/thinking-request.d.ts.map +0 -1
  472. package/dist/providers/thinking-request.js.map +0 -1
  473. package/dist/providers/xai.d.ts.map +0 -1
  474. package/dist/providers/xai.js.map +0 -1
  475. package/dist/schedules/index.d.ts.map +0 -1
  476. package/dist/schedules/interval.d.ts.map +0 -1
  477. package/dist/schedules/interval.js.map +0 -1
  478. package/dist/schedules/prompt.d.ts.map +0 -1
  479. package/dist/schedules/prompt.js.map +0 -1
  480. package/dist/schedules/run-script.d.ts.map +0 -1
  481. package/dist/schedules/run-script.js.map +0 -1
  482. package/dist/schedules/scheduler.d.ts.map +0 -1
  483. package/dist/schedules/scheduler.js.map +0 -1
  484. package/dist/schedules/tools.d.ts.map +0 -1
  485. package/dist/schedules/tools.js.map +0 -1
  486. package/dist/schema.d.ts.map +0 -1
  487. package/dist/schema.js.map +0 -1
  488. package/dist/theme-palette.d.ts.map +0 -1
  489. package/dist/theme-palette.js.map +0 -1
  490. package/dist/thinking-catalog.d.ts.map +0 -1
  491. package/dist/thinking-catalog.js.map +0 -1
  492. package/dist/thinking.d.ts.map +0 -1
  493. package/dist/thinking.js.map +0 -1
  494. package/dist/tool-names.d.ts.map +0 -1
  495. package/dist/tool-names.js.map +0 -1
  496. package/dist/tools/index.d.ts.map +0 -1
  497. package/dist/tools/request-sandbox-access.d.ts.map +0 -1
  498. package/dist/tools/request-sandbox-access.js.map +0 -1
  499. package/dist/tools/utils.d.ts.map +0 -1
  500. package/dist/tools/utils.js.map +0 -1
  501. package/dist/tools/web-search.d.ts.map +0 -1
  502. package/dist/tools/web-search.js.map +0 -1
  503. package/dist/tools/workflows/create-workflow.d.ts.map +0 -1
  504. package/dist/tools/workflows/create-workflow.js.map +0 -1
  505. package/dist/tools/workflows/delete-workflow.d.ts.map +0 -1
  506. package/dist/tools/workflows/delete-workflow.js.map +0 -1
  507. package/dist/tools/workflows/ephemeral-memory.d.ts.map +0 -1
  508. package/dist/tools/workflows/ephemeral-memory.js.map +0 -1
  509. package/dist/tools/workflows/extract-json-schema.d.ts.map +0 -1
  510. package/dist/tools/workflows/extract-json-schema.js.map +0 -1
  511. package/dist/tools/workflows/get-workflow.d.ts.map +0 -1
  512. package/dist/tools/workflows/get-workflow.js.map +0 -1
  513. package/dist/tools/workflows/list-available-agents.d.ts.map +0 -1
  514. package/dist/tools/workflows/list-available-agents.js.map +0 -1
  515. package/dist/tools/workflows/list-available-classifiers.d.ts.map +0 -1
  516. package/dist/tools/workflows/list-available-classifiers.js.map +0 -1
  517. package/dist/tools/workflows/list-available-tools.d.ts.map +0 -1
  518. package/dist/tools/workflows/list-available-tools.js.map +0 -1
  519. package/dist/tools/workflows/list-available-workflows.d.ts.map +0 -1
  520. package/dist/tools/workflows/list-available-workflows.js.map +0 -1
  521. package/dist/tools/workflows/list-workflows.d.ts.map +0 -1
  522. package/dist/tools/workflows/list-workflows.js.map +0 -1
  523. package/dist/tools/workflows/run-workflow.d.ts.map +0 -1
  524. package/dist/tools/workflows/run-workflow.js.map +0 -1
  525. package/dist/tools/workflows/save-workflow.d.ts.map +0 -1
  526. package/dist/tools/workflows/save-workflow.js.map +0 -1
  527. package/dist/tools/workflows/tool-ids.d.ts.map +0 -1
  528. package/dist/tools/workflows/tool-ids.js.map +0 -1
  529. package/dist/utils/binaries.d.ts.map +0 -1
  530. package/dist/utils/binaries.js.map +0 -1
  531. package/dist/utils/debug-log.d.ts.map +0 -1
  532. package/dist/utils/debug-log.js.map +0 -1
  533. package/dist/utils/discarding-scores-storage.d.ts.map +0 -1
  534. package/dist/utils/discarding-scores-storage.js.map +0 -1
  535. package/dist/utils/errors.d.ts.map +0 -1
  536. package/dist/utils/errors.js.map +0 -1
  537. package/dist/utils/gateway-sync.d.ts.map +0 -1
  538. package/dist/utils/gateway-sync.js.map +0 -1
  539. package/dist/utils/local-observability.d.ts.map +0 -1
  540. package/dist/utils/local-observability.js.map +0 -1
  541. package/dist/utils/maintenance-lock.d.ts.map +0 -1
  542. package/dist/utils/maintenance-lock.js.map +0 -1
  543. package/dist/utils/notification-dispatch.d.ts.map +0 -1
  544. package/dist/utils/notification-dispatch.js.map +0 -1
  545. package/dist/utils/open-url.d.ts.map +0 -1
  546. package/dist/utils/open-url.js.map +0 -1
  547. package/dist/utils/path-security.d.ts.map +0 -1
  548. package/dist/utils/path-security.js.map +0 -1
  549. package/dist/utils/plan-diff.d.ts.map +0 -1
  550. package/dist/utils/plan-diff.js.map +0 -1
  551. package/dist/utils/plans.d.ts.map +0 -1
  552. package/dist/utils/plans.js.map +0 -1
  553. package/dist/utils/project.d.ts.map +0 -1
  554. package/dist/utils/project.js.map +0 -1
  555. package/dist/utils/prune-cli.d.ts.map +0 -1
  556. package/dist/utils/prune-cli.js.map +0 -1
  557. package/dist/utils/signals-pubsub.d.ts.map +0 -1
  558. package/dist/utils/signals-pubsub.js.map +0 -1
  559. package/dist/utils/slash-command-loader.d.ts.map +0 -1
  560. package/dist/utils/slash-command-loader.js.map +0 -1
  561. package/dist/utils/slash-command-processor.d.ts.map +0 -1
  562. package/dist/utils/slash-command-processor.js.map +0 -1
  563. package/dist/utils/stdin-pipe.d.ts.map +0 -1
  564. package/dist/utils/stdin-pipe.js.map +0 -1
  565. package/dist/utils/storage-factory.d.ts.map +0 -1
  566. package/dist/utils/storage-factory.js.map +0 -1
  567. package/dist/utils/storage-maintenance.d.ts.map +0 -1
  568. package/dist/utils/storage-maintenance.js.map +0 -1
  569. package/dist/utils/thread-lock.d.ts.map +0 -1
  570. package/dist/utils/thread-lock.js.map +0 -1
  571. package/dist/utils/token-estimator.d.ts.map +0 -1
  572. package/dist/utils/token-estimator.js.map +0 -1
  573. package/dist/utils/update-check.d.ts.map +0 -1
  574. package/dist/utils/update-check.js.map +0 -1
  575. package/dist/utils/wake-session.d.ts.map +0 -1
  576. package/dist/utils/wake-session.js.map +0 -1
  577. package/dist/voice/stt-registry.d.ts.map +0 -1
  578. package/dist/voice/stt-registry.js.map +0 -1
  579. package/dist/voice/transcribe.d.ts.map +0 -1
  580. package/dist/voice/transcribe.js.map +0 -1
  581. package/dist/workflows/register-primitives.d.ts.map +0 -1
  582. package/dist/workflows/register-primitives.js.map +0 -1
  583. package/dist/workflows/service.d.ts.map +0 -1
  584. package/dist/workflows/service.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"account-rotation-processor.js","names":[],"sources":["../../src/auth/account-rotation-processor.ts"],"sourcesContent":["/**\n * Error-driven rotation across a provider's OAuth account registry.\n *\n * When the active account cannot serve a request (rate limit, quota\n * exhaustion, dead token, persistent outage), the next account in insertion\n * order is selected for the request and the request retried. OAuth fetch\n * wrappers read that request-scoped selection on every HTTP attempt, so\n * concurrent runs can't swap each other's credentials. Every switch is\n * persisted as a non-transient `data-mastracode-account-switch` part so it\n * shows in the transcript and survives history reload.\n *\n * Two classes, two lanes — the split is load-bearing. The processor runner\n * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when\n * running `processAPIError`, so a processor registered in the input lane that\n * also implemented `processAPIError` would run BEFORE\n * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries\n * had a chance. `AccountRotationProcessor` therefore implements\n * `processAPIError` only and is registered in `errorProcessors` after\n * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements\n * `processInput` only and is registered in `inputProcessors`.\n */\nimport { TripWire } from '@mastra/core/agent';\nimport { classifyProviderError } from '@mastra/core/error';\nimport type { ProviderFailureKind } from '@mastra/core/error';\nimport type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { resolveCredentialStore } from '../agents/credential-resolver.js';\nimport { resolveModel, resolveRequestThinkingLevel } from '../agents/model.js';\nimport { getCredentialProviderId, normalizeLegacyModelId } from '../providers/model-ids.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport {\n getRequestAccountSelection,\n isRequestAccountRoutingExhausted,\n markRequestAccountRoutingExhausted,\n setRequestAccountSelection,\n} from './account-routing-context.js';\nimport { ProviderAuthRequiredError, PROVIDER_AUTH_REQUIRED_ERROR } from './provider-auth-error.js';\nimport { getOAuthProviders } from './storage.js';\nimport type { CredentialStore, OAuthAccountRecord } from './types.js';\n\nexport const ACCOUNT_SWITCH_PART_TYPE = 'data-mastracode-account-switch';\n\n/** Labels and instance ids only — never token material (do-not list). */\nexport interface AccountSwitchPartData {\n provider: string;\n from: { id: string; label: string } | null;\n to: { id: string; label: string } | null;\n reason:\n | 'rate-limit'\n | 'quota-exhausted'\n | 'auth-failed'\n | 'pool-exhausted'\n | 'persistent-outage'\n | 'preferred-routing';\n at: string;\n /**\n * Set on a `to: null` part when a route pinned to a single account reported\n * that account unusable. The provider's other subscriptions were never\n * consulted (A12), so \"all accounts unavailable\" would misreport what\n * happened.\n */\n exclusive?: boolean;\n}\n\n/** The store surface rotation needs; `AuthStorage` satisfies it structurally. */\nexport type RotationCredentialStore = CredentialStore & {\n /**\n * Force one refresh of the active account's tokens regardless of expiry\n * (401/403 path — a rejected-but-unexpired token usually means clock skew\n * or a refresh race). `AuthStorage` provides it for its active account;\n * deployed per-tenant stores provide it for their single credential.\n */\n forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;\n};\n\n/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */\nconst KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map(provider => provider.id));\n\n/** Hostname suffixes → provider ids, for `APICallError.url`. */\nconst PROVIDER_HOST_PATTERNS: Array<[RegExp, string]> = [\n [/(^|\\.)api\\.anthropic\\.com$/i, 'anthropic'],\n [/(^|\\.)api\\.kimi\\.com$/i, 'kimi-for-coding'],\n [/(^|\\.)api\\.x\\.ai$/i, 'xai'],\n [/(^|\\.)chatgpt\\.com$/i, 'openai-codex'],\n [/(^|\\.)backend-api\\.codex\\.ai$/i, 'openai-codex'],\n [/(^|\\.)githubcopilot\\.com$/i, 'github-copilot'],\n [/(^|\\.)api\\.github\\.com$/i, 'github-copilot'],\n];\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'EPIPE',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_MESSAGE_PATTERN =\n /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;\n\nconst MAX_CAUSE_DEPTH = 4;\n\n/** Persisted data-part type for a model-route hop. */\nexport const MODEL_FALLBACK_PART_TYPE = 'data-mastracode-model-fallback' as const;\n\n/** Non-secret transcript payload for a model-route hop. */\nexport interface ModelFallbackPartData {\n from: { entryId: string; label: string };\n to: { entryId: string; label: string };\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\n/** Session-state key set when account rotation advances the model route. */\nexport const MODEL_FALLBACK_STATE_KEY = 'mastracodePendingModelFallback' as const;\n\n/** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */\nexport interface PendingModelFallback {\n fromEntryId: string;\n toEntryId: string;\n toModelId: string;\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport type RotationClassification =\n | { kind: 'rotate'; reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' }\n | { kind: 'hop' }\n | { kind: 'stream-cut' }\n | { kind: 'never' };\n\n/**\n * Same-account retries for a stream the provider cut after accepting the\n * request. Each one can cost a full stream (900 s on the ChatGPT Codex route),\n * so the budget is small. This is the whole budget: Mastra Code's\n * `StreamErrorRetryProcessor` leaves these errors to this processor.\n */\nexport const MAX_STREAM_CUT_RETRIES = 2;\n\nconst ROTATION_BY_PROVIDER_KIND: Partial<Record<ProviderFailureKind, RotationClassification>> = {\n auth: { kind: 'rotate', reason: 'auth-failed' },\n quota: { kind: 'rotate', reason: 'quota-exhausted' },\n rate_limited: { kind: 'rotate', reason: 'rate-limit' },\n unavailable: { kind: 'hop' },\n};\n\nfunction rotationFromStatus(status: number | undefined): RotationClassification | undefined {\n if (status === 429) return { kind: 'rotate', reason: 'rate-limit' };\n if (status === 402) return { kind: 'rotate', reason: 'quota-exhausted' };\n if (status === 401 || status === 403) return { kind: 'rotate', reason: 'auth-failed' };\n if (status !== undefined && status >= 500 && status < 600) return { kind: 'hop' };\n return undefined;\n}\n\nfunction isErrorWithCode(error: unknown): error is { code?: unknown } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n const { statusCode, status } = current as { statusCode?: unknown; status?: unknown };\n if (typeof statusCode === 'number') return statusCode;\n if (typeof status === 'number') return status;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\nfunction isProviderAuthRequiredError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n current instanceof ProviderAuthRequiredError ||\n (current instanceof Error && current.name === PROVIDER_AUTH_REQUIRED_ERROR)\n ) {\n return true;\n }\n if (typeof current !== 'object') break;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\nfunction isNetworkErrorLike(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n isErrorWithCode(current) &&\n typeof current.code === 'string' &&\n NETWORK_ERROR_CODES.has(current.code.toUpperCase())\n ) {\n return true;\n }\n if (current instanceof Error) {\n if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;\n current = current.cause;\n } else if (typeof current === 'object') {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return false;\n}\n\n/** The code the ChatGPT Codex backend puts on the error frame it sends when it ends a stream at 900 s. */\nconst STREAM_DURATION_LIMIT_CODE = 'request_timeout';\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/** The `error.code` of a stream error frame: the raw frame, or the frame `@ai-sdk/openai` keeps as `data`. */\nfunction streamErrorFrameCode(value: Record<string, unknown>): unknown {\n const data = asRecord(value.data);\n const frame = value.type === 'error' ? value : data?.type === 'error' ? data : undefined;\n return asRecord(frame?.error)?.code;\n}\n\n/**\n * Whether the provider accepted the request and then the response stream died:\n * the AI SDK reports a body that fails after a 2xx response as\n * \"Failed to process successful response\" with the 2xx status, and the ChatGPT\n * Codex backend ends streams at 900 s, sometimes with a `request_timeout` error\n * frame first. Either way the account and the provider answered, so this is\n * not an outage, and another account would be cut the same way.\n *\n * `@ai-sdk/openai` raises that frame with `code: 'request_timeout'` and a\n * derived `statusCode: 504`, so callers must check this before any 5xx rule.\n * Mastra Code's transient retry matchers call it first so that account\n * rotation is the only processor that retries these errors.\n */\nexport function isStreamCutAfterResponse(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n const record = asRecord(current);\n if (!record) break;\n const { statusCode, status, code } = record;\n const httpStatus = typeof statusCode === 'number' ? statusCode : status;\n if (typeof httpStatus === 'number' && httpStatus >= 200 && httpStatus < 300) return true;\n if (code === STREAM_DURATION_LIMIT_CODE || streamErrorFrameCode(record) === STREAM_DURATION_LIMIT_CODE) return true;\n current = record.cause;\n }\n return false;\n}\n\n/**\n * The locked Q7 taxonomy. Rate limits and exhausted quotas rotate immediately\n * (429 is not covered by any transient matcher, so it arrives here on first\n * occurrence); auth failures and `ProviderAuthRequiredError` rotate after one\n * forced refresh; 5xx/network hop only when the transient retry budget is\n * already spent (they reach this processor because `StreamErrorRetryProcessor`\n * declined); everything else never touches the registry.\n */\nexport function classifyRotationError(error: unknown): RotationClassification {\n if (isProviderAuthRequiredError(error)) {\n return { kind: 'rotate', reason: 'auth-failed' };\n }\n // Before the status, wording and network checks: the duration-limit frame\n // carries a derived 504, and a cut body's socket-error cause reads as\n // network-like. Each of those would hop.\n if (isStreamCutAfterResponse(error)) return { kind: 'stream-cut' };\n const status = readErrorStatus(error);\n const byStatus = rotationFromStatus(status);\n if (byStatus) return byStatus;\n // Wording only speaks for a statusless or 400 failure, where providers put quota and rate-limit text.\n const byKind =\n status === undefined || status === 400 ? ROTATION_BY_PROVIDER_KIND[classifyProviderError(error)] : undefined;\n return byKind ?? (isNetworkErrorLike(error) ? { kind: 'hop' } : { kind: 'never' });\n}\n\n/** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */\nexport function providerFromModelId(modelId: string): string | undefined {\n const segments = normalizeLegacyModelId(modelId)\n .replace(/^mastracode\\//, '')\n .split('/');\n const providerId = segments[0] ? getCredentialProviderId(segments[0]) : undefined;\n return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : undefined;\n}\n\nfunction providerFromHost(hostname: string): string | undefined {\n for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) {\n if (pattern.test(hostname)) return providerId;\n }\n return undefined;\n}\n\n/**\n * Identify the provider an error came from: the request URL's hostname\n * (`APICallError.url`, cause chain included), falling back to the router\n * model id. Unknown → undefined (caller treats as never-rotate).\n */\nexport function providerFromError(error: unknown): string | undefined {\n const causeChain: object[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n causeChain.push(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A request URL identifies the provider that actually handled the failed\n // call. Check every supported URL field throughout the cause chain before\n // falling back to router model metadata, which may describe the original\n // session model rather than the active cascade entry.\n for (const item of causeChain) {\n const urls = [\n (item as { url?: unknown }).url,\n (item as { requestURL?: unknown }).requestURL,\n (item as { requestUrl?: unknown }).requestUrl,\n ];\n for (const url of urls) {\n if (typeof url !== 'string') continue;\n try {\n const providerId = providerFromHost(new URL(url).hostname);\n if (providerId) return providerId;\n } catch {\n // Not a parseable URL — try the other fields and causes.\n }\n }\n }\n\n for (const item of causeChain) {\n const modelId = (item as { modelId?: unknown }).modelId;\n if (typeof modelId !== 'string') continue;\n const providerId = providerFromModelId(modelId);\n if (providerId) return providerId;\n }\n return undefined;\n}\n\nfunction getTriedInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.triedInstances;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.triedInstances = created;\n return created;\n}\n\nfunction getForcedRefreshInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.forcedAuthRefresh;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.forcedAuthRefresh = created;\n return created;\n}\n\n/** Friendly names for the part/notice copy (display only — never auth data). */\nexport const PROVIDER_DISPLAY_NAMES: Record<string, string> = {\n anthropic: 'Anthropic',\n 'kimi-for-coding': 'Kimi',\n 'openai-codex': 'Codex',\n 'github-copilot': 'GitHub Copilot',\n xai: 'xAI',\n};\n\nconst REASON_TEXT: Record<AccountSwitchPartData['reason'], string> = {\n 'rate-limit': 'rate limit',\n 'quota-exhausted': 'quota exhausted',\n 'auth-failed': 'auth failed',\n 'pool-exhausted': 'pool exhausted',\n 'persistent-outage': 'persistent outage',\n 'preferred-routing': 'subscription routing',\n};\n\n/** Validates untrusted `reason` values (e.g. persisted message parts). */\nexport function isAccountSwitchReason(value: unknown): value is AccountSwitchPartData['reason'] {\n // Own-property check: `in` would accept prototype names like 'toString',\n // which would then interpolate the inherited function into the notice text.\n return typeof value === 'string' && Object.prototype.hasOwnProperty.call(REASON_TEXT, value);\n}\n\n/**\n * One-line transcript copy for a switch part. Shared by the live `info`\n * controller event (the TUI shows controller `info` events as transcript\n * lines, and no message event carries data parts mid-run) and by the TUI's\n * history rendering of the persisted part — one formatter, identical text.\n */\nexport function accountSwitchNoticeText(data: AccountSwitchPartData): string {\n const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;\n const reason = REASON_TEXT[data.reason];\n if (data.to === null) {\n // A12: a targeted route reports *its* account, not the pool — the other\n // subscriptions were never tried, so \"all accounts unavailable\" would be\n // wrong and would read as if the pool had been walked.\n if (data.exclusive) {\n return `Pinned ${provider} account unavailable (${reason})`;\n }\n return `All ${provider} accounts unavailable (${reason})`;\n }\n const from = data.from?.label ?? 'unknown';\n return `Switched ${provider} account: ${from} → ${data.to.label} (${reason})`;\n}\n\n/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */\nexport function modelFallbackNoticeText(data: ModelFallbackPartData): string {\n const reason = REASON_TEXT[data.reason] ?? data.reason;\n return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;\n}\n\n/**\n * Whether a persisted model-fallback reason is one this build understands.\n * `REASON_TEXT` also covers the account-switch reasons, so the notice text\n * alone would happily render a foreign value such as `rate-limit` as a\n * model-fallback reason; history parsed from another build's part must be\n * rejected instead.\n */\nexport function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'] {\n return value === 'pool-exhausted' || value === 'persistent-outage';\n}\n\nasync function emitAccountSwitchPart(\n args: Pick<ProcessAPIErrorArgs, 'writer' | 'requestContext'> | Pick<ProcessInputArgs, 'writer' | 'requestContext'>,\n data: AccountSwitchPartData,\n): Promise<void> {\n // Non-transient on purpose (contrast the transient tool-progress parts):\n // switches must persist into the assistant message and render from history.\n await args.writer?.custom({\n type: ACCOUNT_SWITCH_PART_TYPE,\n data,\n });\n // Data parts surface in the TUI only on history reload; emit the same line\n // as a controller `info` event so the switch is visible live (precedent:\n // emitTransientRetry emits controller events from the retry matcher).\n const controllerContext = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controllerContext?.emitEvent?.({ type: 'info', message: accountSwitchNoticeText(data) });\n}\n\n/**\n * Provider of the model the controller session is currently running — the\n * fallback identification path for errors that carry neither a request URL\n * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper\n * before any HTTP request exists).\n */\nfunction providerFromSession(\n args: Pick<ProcessAPIErrorArgs, 'requestContext'> | Pick<ProcessInputArgs, 'requestContext'>,\n): string | undefined {\n const controller = args.requestContext?.get('controller') as { session?: { modelId?: unknown } } | undefined;\n const modelId = controller?.session?.modelId;\n return typeof modelId === 'string' ? providerFromModelId(modelId) : undefined;\n}\n\n/**\n * Rotates the active OAuth account on classified API errors.\n *\n * Registered in `errorProcessors` AFTER `StreamErrorRetryProcessor` — a\n * transient error reaching this processor means the transient budget is\n * spent, which is exactly the hop condition. Implements `processAPIError`\n * ONLY (see the file header for the runner-order rationale).\n */\n/** Cached per-request model route cascade. */\ninterface ModelRouteCascade {\n entries: Array<{ id: string; label: string; modelId: string; accountId?: string }>;\n position: number;\n}\n\ninterface AccountRoute {\n entryId: string;\n modelId: string;\n providerId: string;\n accountId?: string;\n}\n\ntype RoutingProcessorArgs = Pick<ProcessAPIErrorArgs, 'requestContext' | 'state' | 'writer'> | ProcessInputArgs;\n\nexport type RoutingControllerContext = {\n session?: { modelId?: unknown; modeId?: unknown };\n threadId?: unknown;\n getState?: () => Record<string, unknown>;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n getThreadSetting?: (key: string) => Promise<unknown>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n isThreadActive?: () => boolean;\n};\n\nfunction getRoutingController(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n): RoutingControllerContext | undefined {\n return args.requestContext?.get('controller') as RoutingControllerContext | undefined;\n}\n\n/** A targeted route is exclusive; an entry without accountId uses automatic pool rotation. */\nfunction getRouteTargetAccountId(route: AccountRoute | null): string | undefined {\n return route?.accountId;\n}\n\nfunction getRequestActiveAccount(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n store: CredentialStore,\n providerId: string,\n) {\n if (isRequestAccountRoutingExhausted(args.requestContext, providerId)) return undefined;\n const selectedId = getRequestAccountSelection(args.requestContext, providerId);\n if (selectedId) return store.listAccounts?.(providerId).find(account => account.id === selectedId);\n return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find(account => account.active);\n}\n\nfunction resolveAccountRoute(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n explicit?: { id: string; modelId: string; accountId?: string },\n): AccountRoute | null {\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n typeof pending.toModelId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const routeEntries = Array.isArray((state?.modelRoute as { entries?: unknown } | undefined)?.entries)\n ? ((state?.modelRoute as { entries: Array<{ id?: unknown; modelId?: unknown; accountId?: unknown }> }).entries ??\n [])\n : [];\n const entry = explicit\n ? explicit\n : pendingMatchesThread\n ? routeEntries.find(candidate => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId)\n : routeEntries.find(candidate => candidate.modelId === controller?.session?.modelId);\n if (!entry || typeof entry.id !== 'string' || typeof entry.modelId !== 'string') return null;\n const providerId = providerFromModelId(entry.modelId);\n if (!providerId) return null;\n return {\n entryId: entry.id,\n modelId: entry.modelId,\n providerId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n };\n}\n\n/**\n * A14: `Automatic` rotation starts *at* the persisted active account and walks\n * insertion order from there, wrapping once. The active account is the cursor\n * rotation last left at, so a turn that starts at index 0 regardless would\n * re-activate and re-try an account the previous turn already moved past —\n * which is the whole job the removed sticky-exclusion set was doing badly.\n * With no persisted active account the order is plain insertion order.\n */\nfunction orderAccountsFromActive(accounts: OAuthAccountRecord[], activeId: string | undefined) {\n const index = activeId === undefined ? -1 : accounts.findIndex(account => account.id === activeId);\n if (index <= 0) return accounts;\n return [...accounts.slice(index), ...accounts.slice(0, index)];\n}\n\nasync function applyPreferredAccountRoute(\n args: RoutingProcessorArgs,\n store: CredentialStore,\n route: AccountRoute,\n): Promise<boolean> {\n store.reload();\n const preferredId = getRouteTargetAccountId(route);\n const accounts = store.listAccounts?.(route.providerId) ?? [];\n if (accounts.length === 0 && preferredId === undefined) return false;\n const tried = getTriedInstances(args.state);\n const unavailable = new Set(accounts.filter(account => tried.has(account.id)).map(account => account.id));\n const active = getRequestActiveAccount(args, store, route.providerId) ?? store.getActiveAccount?.(route.providerId);\n const selected = // A12: a targeted route may use only the account it names. `Automatic`\n // keeps insertion order with full pool rotation (A10), starting from the\n // account the cursor already points at (A14).\n (\n preferredId\n ? accounts.filter(account => account.id === preferredId)\n : orderAccountsFromActive(accounts, active?.id)\n ).find(account => !unavailable.has(account.id));\n\n for (const accountId of unavailable) tried.add(accountId);\n if (!selected) {\n markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n\n if (active?.id === selected.id) {\n setRequestAccountSelection(args.requestContext, route.providerId, selected.id);\n return false;\n }\n // Activate before recording the request-scoped selection: a failed\n // activation must not leave the selection claiming an account that never\n // became the provider's active credential.\n const activated = store.activateAccount ? store.activateAccount(route.providerId, selected.id) : selected;\n if (!activated) {\n // Only a targeted route is out of options here. The exhausted marker is\n // request-wide and fails every credential read closed, so setting it for\n // `Automatic` would stop error recovery from retrying on a survivor.\n if (preferredId !== undefined) markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n setRequestAccountSelection(args.requestContext, route.providerId, activated.id);\n\n // Applying an explicit account choice is routine, not a failover notice.\n if (preferredId === undefined) {\n await emitAccountSwitchPart(args, {\n provider: route.providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: activated.id, label: activated.label },\n reason: 'preferred-routing',\n at: new Date().toISOString(),\n });\n }\n return true;\n}\n\nexport class AccountRotationProcessor implements Processor {\n readonly id = 'mastracode-account-rotation' as const;\n\n constructor(\n private readonly options: {\n credentialStore: RotationCredentialStore;\n maxProcessorRetries: number;\n settingsPath?: string;\n /** The host has no modes, so per-mode thinking defaults never apply. */\n modeless?: boolean;\n /** Same host thinking default `getDynamicModel` uses, so a hop resolves at the same level. */\n resolveDefaultThinkingLevel?: (ctx: {\n requestContext: RequestContext;\n }) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;\n },\n ) {}\n\n async processAPIError(args: ProcessAPIErrorArgs): Promise<{ retry: boolean }> {\n const { error, state } = args;\n\n // Core runs error processors even after the shared retry budget is spent\n // and silently discards `retry: true` then (llm-execution-step.ts\n // canRetryError) — rotating the cursor or emitting a switch part for a\n // retry that will never run would lie to both auth.json and the\n // transcript. With a fallback chain configured, a bare `retry: false`\n // here would silently advance the route for an error we never classified, so the\n // chain gate surfaces the error instead.\n if (args.retryCount >= this.options.maxProcessorRetries) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // Classify before attributing: an error from a provider outside the OAuth\n // registry (API-key/router providers are valid route entries) still hops on\n // rotate/hop classes — there is just no account cursor to advance.\n const classification = classifyRotationError(error);\n // Q14: 400/unknown errors never rotate and never advance routes. With a chain\n // active, core's fallback array would still advance on a bare\n // `retry: false` (it advances on any thrown non-TripWire error), so the\n // gate converts that into a surfaced error instead of a silent hop.\n if (classification.kind === 'never') {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // A stream cut after the provider accepted the request (e.g. the ChatGPT\n // Codex 900 s limit) says nothing about the account: retry it on the same\n // account a few times, and when that runs out surface the error itself\n // rather than marking every account unavailable as a persistent outage.\n if (classification.kind === 'stream-cut') {\n // The budget belongs to one model step: `state` lives for the whole request, and a\n // step's retries keep its step number, while the next step starts with a fresh budget.\n const budget = state.streamCutRetries as { step: number; count: number } | undefined;\n const cuts = budget?.step === args.stepNumber ? budget.count : 0;\n if (cuts >= MAX_STREAM_CUT_RETRIES) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n state.streamCutRetries = { step: args.stepNumber, count: cuts + 1 };\n // The retry replays the request from scratch (Q10), as a rotation does.\n args.rotateResponseMessageId?.();\n const controller = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controller?.emitEvent?.({\n type: 'info',\n message: `The provider ended the response stream early (it may have hit a stream duration limit). Retrying (${cuts + 1}/${MAX_STREAM_CUT_RETRIES}).`,\n });\n return { retry: true };\n }\n\n const cascade = await this.getModelRouteCascade(args);\n const currentEntry = cascade?.entries[cascade.position];\n const providerId =\n providerFromError(error) ??\n (currentEntry ? providerFromModelId(currentEntry.modelId) : undefined) ??\n (cascade ? undefined : providerFromSession(args));\n if (!providerId) {\n await this.emitModelFallbackPart(args, classification.kind === 'hop' ? 'persistent-outage' : 'pool-exhausted');\n return { retry: false };\n }\n\n // Deployed requests resolve the tenant-scoped store; local mode keeps the\n // host storage. Reading the host registry here would rotate or announce\n // host accounts for a tenant request. Annotated as the rotation surface:\n // `resolveCredentialStore` returns a plain CredentialStore, and the 401\n // path below uses the optional `forceRefreshActiveAccount` when the host\n // provides it.\n const store: RotationCredentialStore = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n store.reload();\n const accounts = store.listAccounts?.(providerId) ?? [];\n const active = getRequestActiveAccount(args, store, providerId);\n const route = currentEntry ? resolveAccountRoute(args, currentEntry) : resolveAccountRoute(args);\n\n // Q7 bucket 2: force one refresh of the active instance before rotating.\n // A 401 usually means a fresh-but-rejected token; the forced refresh\n // covers server-side clock skew and refresh-token races. Success retries\n // the same account — no rotation, no part. With no active account (e.g.\n // `ProviderAuthRequiredError` from an empty registry) a refresh can never\n // succeed, so skip it and fall through to the retry:false surface below,\n // which rethrows the original auth error instead of a generic pool\n // exhaustion message. Stores without an account registry (deployed\n // per-tenant stores) hold one credential per provider, so they refresh\n // that credential instead.\n const hasAccountRegistry = typeof store.listAccounts === 'function';\n if (\n classification.kind === 'rotate' &&\n classification.reason === 'auth-failed' &&\n (active || !hasAccountRegistry)\n ) {\n const forced = getForcedRefreshInstances(state);\n const refreshKey = `${providerId}:${active?.id ?? 'active'}`;\n if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === 'function') {\n forced.add(refreshKey);\n const token = await store.forceRefreshActiveAccount(providerId, active?.id);\n if (token !== undefined) {\n return { retry: true };\n }\n }\n }\n\n // A12: only a pin on the provider that actually failed makes this failure\n // exclusive. `route.providerId` is derived from the route's model while\n // `providerId` comes from the failed request's URL, which during a cascade\n // can still describe the session model rather than the entry being retried;\n // when they differ the pin belongs to an unrelated route, so the provider\n // that failed keeps its normal pool handling.\n const targetAccountId = route?.providerId === providerId ? getRouteTargetAccountId(route) : undefined;\n\n if (classification.kind === 'hop') {\n return this.declarePoolUnavailable(args, providerId, 'persistent-outage', targetAccountId !== undefined);\n }\n\n // A12: a targeted route never activates a sibling subscription. A\n // rotate-classified failure on the account the route selected proceeds to\n // the model route instead — the request hops, it does not spill\n // onto another subscription's quota. A targeted route has nothing to\n // rotate to at any pool size. A stale id for an account the user removed\n // reads the same way: fail closed rather than silently land on a sibling.\n if (targetAccountId !== undefined) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted', true);\n }\n\n // Count only this provider's instances: `tried` spans the whole request\n // (a cascade can visit several providers), so comparing its raw size to\n // this provider's account count would falsely report exhaustion when an\n // earlier provider in the same request already used up accounts.\n const tried = getTriedInstances(state);\n if (active) tried.add(active.id);\n // The tried-set is request-global and shared across providers after a\n // route hop, so exhaustion must count only this provider's ids.\n const triedForProvider = accounts.filter(account => tried.has(account.id)).length;\n if (triedForProvider >= accounts.length) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n // If the selected account was removed elsewhere, even a single survivor\n // is still untried. Resume from the freshly loaded global cursor.\n const candidates = active ? accounts : orderAccountsFromActive(accounts, store.getActiveAccount?.(providerId)?.id);\n const nextCandidate = candidates.find(account => !tried.has(account.id));\n\n const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : undefined;\n if (!next) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n setRequestAccountSelection(args.requestContext, providerId, next.id);\n tried.add(next.id);\n\n // The retry replays the request from scratch (Q10): rotate the assistant\n // message id so the retried response starts a fresh message instead of\n // appending to the partially streamed one.\n args.rotateResponseMessageId?.();\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: next.id, label: next.label },\n reason: classification.reason,\n at: new Date().toISOString(),\n });\n\n return { retry: true };\n }\n\n /**\n * Resolve the request's host-supplied model route once and cache the reachable\n * prefix in processor state. Resolution mirrors getDynamicModel so a hop is\n * never announced for an entry core cannot reach.\n */\n private async getModelRouteCascade(args: ProcessAPIErrorArgs): Promise<ModelRouteCascade | null> {\n if (args.state.modelRouteCascade !== undefined) {\n return (args.state.modelRouteCascade as ModelRouteCascade | null) ?? null;\n }\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const route = (\n state?.modelRoute as\n | { entries?: Array<{ id?: unknown; label?: unknown; modelId?: unknown; accountId?: unknown }> }\n | undefined\n )?.entries;\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const startIndex = pendingMatchesThread\n ? route?.findIndex(entry => entry.id === pending.toEntryId)\n : route?.findIndex(entry => entry.modelId === controller?.session?.modelId);\n if (!route || startIndex === undefined || startIndex < 0 || route.length - startIndex < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(\n {\n state: { thinkingLevel: state?.thinkingLevel },\n ...(!this.options.modeless && {\n session: { modeId: typeof controller?.session?.modeId === 'string' ? controller.session.modeId : 'build' },\n }),\n },\n this.options.settingsPath,\n args.requestContext && !isThinkingLevelSetting(state?.thinkingLevel)\n ? await this.options.resolveDefaultThinkingLevel?.({ requestContext: args.requestContext })\n : undefined,\n );\n const entries: ModelRouteCascade['entries'] = [];\n for (const entry of route.slice(startIndex)) {\n if (\n typeof entry.id !== 'string' ||\n entry.id.length === 0 ||\n typeof entry.modelId !== 'string' ||\n entry.modelId.length === 0\n ) {\n break;\n }\n if (entries.length > 0) {\n try {\n resolveModel(entry.modelId, {\n thinkingLevel,\n remapForCodexOAuth: true,\n requestContext: args.requestContext,\n });\n } catch {\n break;\n }\n }\n entries.push({\n id: entry.id,\n label: typeof entry.label === 'string' && entry.label.length > 0 ? entry.label : entry.id,\n modelId: entry.modelId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n });\n }\n if (entries.length < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n const cascade: ModelRouteCascade = { entries, position: 0 };\n args.state.modelRouteCascade = cascade;\n return cascade;\n }\n\n /**\n * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's\n * fallback array advances on ANY thrown error except TripWire\n * (llm-execution-step.ts), so when the session route has another entry and the\n * current entry is non-last, a bare `retry: false` would silently hop on an\n * error class the user excluded from hop triggers. TripWire is the only\n * no-advance escape: the runner rethrows it and the fallback loop declines\n * to advance. No chain (or already on the last entry) → return and let the\n * plain `retry: false` surface the error exactly as before.\n */\n private async gateChainHop(args: ProcessAPIErrorArgs, error: unknown): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n if (cascade.position >= cascade.entries.length - 1) return;\n const reason = error instanceof Error ? error.message : String(error);\n throw new TripWire(reason, {}, this.id);\n }\n\n /** Announce and persist the next model-route hop before core advances. */\n private async emitModelFallbackPart(\n args: ProcessAPIErrorArgs,\n reason: 'pool-exhausted' | 'persistent-outage',\n ): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n\n const from = cascade.entries[cascade.position];\n const to = cascade.entries[cascade.position + 1];\n if (!from || !to) return;\n\n const controller = args.requestContext?.get('controller') as\n | {\n threadId?: unknown;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n emitEvent?: (event: { type: 'info'; message: string }) => void;\n }\n | undefined;\n const at = new Date().toISOString();\n const threadId = typeof controller?.threadId === 'string' ? controller.threadId : undefined;\n const pending = {\n fromEntryId: from.id,\n toEntryId: to.id,\n toModelId: to.modelId,\n ...(threadId ? { threadId } : {}),\n reason,\n at,\n } satisfies PendingModelFallback;\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: pending });\n const data: ModelFallbackPartData = {\n from: { entryId: from.id, label: from.label },\n to: { entryId: to.id, label: to.label },\n reason,\n at,\n };\n try {\n await args.writer?.custom({ type: MODEL_FALLBACK_PART_TYPE, data });\n } catch (error) {\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: undefined });\n throw error;\n }\n await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });\n args.state.startNoticeEmitted = false;\n const targetRoute = resolveAccountRoute(args, to);\n if (targetRoute) {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n await applyPreferredAccountRoute(args, store, targetRoute).catch(() => undefined);\n }\n controller?.emitEvent?.({ type: 'info', message: modelFallbackNoticeText(data) });\n cascade.position++;\n }\n\n /**\n * Pool done for this request: every instance recorded in the tried-set and\n * a `to: null` part emitted. Returns `retry: false` so core's fallback\n * array can hop to the next route entry (announced by `emitModelFallbackPart`).\n * Silent on the account part when the provider has no registry at all —\n * there are no accounts to declare unavailable, but the hop still applies.\n */\n private async declarePoolUnavailable(\n args: ProcessAPIErrorArgs,\n providerId: string,\n reason: 'pool-exhausted' | 'persistent-outage',\n exclusive = false,\n ): Promise<{ retry: boolean }> {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length === 0) {\n // No account registry (API-key-only provider): nothing rotated, but the\n // hop still happens — announce the model fallback before core advances.\n await this.emitModelFallbackPart(args, reason);\n return { retry: false };\n }\n\n const tried = getTriedInstances(args.state);\n for (const account of accounts) tried.add(account.id);\n\n const active = getRequestActiveAccount(args, store, providerId);\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: null,\n reason,\n at: new Date().toISOString(),\n ...(exclusive ? { exclusive: true } : {}),\n });\n\n await this.emitModelFallbackPart(args, reason);\n\n return { retry: false };\n }\n}\n\n/**\n * Applies the pack's preferred account route once per request, before the\n * first model call. Without a route it only reloads the credential store so\n * the request sees accounts changed by other processes.\n *\n * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It\n * lives in `inputProcessors`; the runner walks input processors first when\n * running `processAPIError`, so adding the method here would classify and\n * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.\n */\nexport class AccountStartNoticeProcessor implements Processor {\n readonly id = 'mastracode-account-start-notice' as const;\n\n constructor(private readonly options: { credentialStore: CredentialStore }) {}\n\n async processInput(args: ProcessInputArgs): Promise<ProcessInputResult> {\n if (args.state.startNoticeEmitted) return args.messageList;\n\n // Deployed requests resolve the tenant-scoped store so host accounts are\n // never listed, activated, or announced for a tenant run. Local mode keeps\n // the constructor's storage.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n\n const route = resolveAccountRoute(args);\n if (!route) {\n store.reload();\n return args.messageList;\n }\n\n // A14: a route whose accounts are all unavailable is not a pre-emptive\n // abort. `applyPreferredAccountRoute` marks the provider on the request so\n // credential reads fail closed rather than falling through to the active\n // account, and the request then runs and fails at the provider — which is\n // what lets the error lane classify it and hand the turn to the route's\n // configured fallback chain. The removed persisted set threw here instead,\n // before any socket opened, so the chain was never reached.\n const switched = await applyPreferredAccountRoute(args, store, route);\n if (switched || getRouteTargetAccountId(route) !== undefined) {\n args.state.startNoticeEmitted = true;\n }\n return args.messageList;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAa,2BAA2B;;AAoCxC,MAAM,qBAAqB,IAAI,IAAI,kBAAkB,CAAC,CAAC,KAAI,aAAY,SAAS,EAAE,CAAC;;AAGnF,MAAM,yBAAkD;CACtD,CAAC,+BAA+B,WAAW;CAC3C,CAAC,0BAA0B,iBAAiB;CAC5C,CAAC,sBAAsB,KA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,MAAM;GAChC,UAAU;GACV,MAAM,SAAS;IAAE,IAAI,OAAO;IAAI,OAAO,OAAO;GAAM,IAAI;GACxD,IAAI;GACJ;GACA,qBAAI,IAAI,KAAK,EAAA,CAAE,YAAY;GAC3B,GAAI,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;EACzC,CAAC;EAED,MAAM,KAAK,sBAAsB,MAAM,MAAM;EAE7C,OAAO,EAAE,OAAO,MAAM;CACxB;AACF;;;;;;;;;;;AAYA,IAAa,8BAAb,MAA8D;CAG/B;CAF7B,KAAc;CAEd,YAAY,SAAgE;EAA/C,KAAA,UAAA;CAAgD;CAE7E,MAAM,aAAa,MAAqD;EACtE,IAAI,KAAK,MAAM,oBAAoB,OAAO,KAAK;EAK/C,MAAM,QAAQ,uBAAuB,KAAK,cAAc,KAAK,KAAK,QAAQ;EAE1E,MAAM,QAAQ,oBAAoB,IAAI;EACtC,IAAI,CAAC,OAAO;GACV,MAAM,OAAO;GACb,OAAO,KAAK;EACd;EAUA,IAAI,MADmB,2BAA2B,MAAM,OAAO,KAAK,KACpD,wBAAwB,KAAK,MAAM,KAAA,GACjD,KAAK,MAAM,qBAAqB;EAElC,OAAO,KAAK;CACd;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"account-routing-context.d.ts","sourceRoot":"","sources":["../../src/auth/account-routing-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,wFAAwF;AACxF,MAAM,MAAM,oBAAoB,GAAG;IAAE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC;AAWjE,wBAAgB,0BAA0B,CAAC,cAAc,EAAE,oBAAoB,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,sBAE9G;AAED,wBAAgB,0BAA0B,CACxC,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,EAClB,iBAAiB,EAAE,MAAM,GACxB,IAAI,CAMN;AASD;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAChD,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,GACjB,IAAI,CAKN;AAED,wFAAwF;AACxF,wBAAgB,gCAAgC,CAC9C,cAAc,EAAE,oBAAoB,GAAG,SAAS,EAChD,UAAU,EAAE,MAAM,GACjB,OAAO,CAET"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"account-routing-context.js","names":[],"sources":["../../src/auth/account-routing-context.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\n\n/** The read-only view of a request context that credential and account lookups need. */\nexport type RequestContextReader = { get(key: string): unknown };\n\nconst ACCOUNT_ROUTING_SELECTIONS_KEY = 'mastracodeAccountRoutingSelections';\n\ntype AccountRoutingSelections = Record<string, string>;\n\nfunction getSelections(requestContext?: RequestContextReader): AccountRoutingSelections | undefined {\n const value = requestContext?.get(ACCOUNT_ROUTING_SELECTIONS_KEY);\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as AccountRoutingSelections) : undefined;\n}\n\nexport function getRequestAccountSelection(requestContext: RequestContextReader | undefined, providerId: string) {\n return getSelections(requestContext)?.[providerId];\n}\n\nexport function setRequestAccountSelection(\n requestContext: RequestContext | undefined,\n providerId: string,\n accountInstanceId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n requestContext.set(ACCOUNT_ROUTING_SELECTIONS_KEY, {\n ...getSelections(requestContext),\n [providerId]: accountInstanceId,\n });\n}\n\nconst ACCOUNT_ROUTING_EXHAUSTED_KEY = 'mastracodeAccountRoutingExhaustedProviders';\n\nfunction getExhaustedProviders(requestContext?: RequestContextReader): string[] {\n const value = requestContext?.get(ACCOUNT_ROUTING_EXHAUSTED_KEY);\n return Array.isArray(value) ? (value as string[]) : [];\n}\n\n/**\n * Record that routing found no usable account for this provider on this\n * request. Kept separate from the account selection: a sentinel *id* would be\n * handed to credential lookup, where an unknown id makes `get()` fall back to\n * the provider's active account — the very account routing just rejected.\n */\nexport function markRequestAccountRoutingExhausted(\n requestContext: RequestContext | undefined,\n providerId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n const exhausted = getExhaustedProviders(requestContext);\n if (exhausted.includes(providerId)) return;\n requestContext.set(ACCOUNT_ROUTING_EXHAUSTED_KEY, [...exhausted, providerId]);\n}\n\n/** Whether routing already rejected every account for this provider on this request. */\nexport function isRequestAccountRoutingExhausted(\n requestContext: RequestContextReader | undefined,\n providerId: string,\n): boolean {\n return getExhaustedProviders(requestContext).includes(providerId);\n}\n"],"mappings":";AAKA,MAAM,iCAAiC;AAIvC,SAAS,cAAc,gBAA6E;CAClG,MAAM,QAAQ,gBAAgB,IAAI,8BAA8B;CAChE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAqC,KAAA;AAC7G;AAEA,SAAgB,2BAA2B,gBAAkD,YAAoB;CAC/G,OAAO,cAAc,cAAc,CAAC,GAAG;AACzC;AAEA,SAAgB,2BACd,gBACA,YACA,mBACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,eAAe,IAAI,gCAAgC;EACjD,GAAG,cAAc,cAAc;GAC9B,aAAa;CAChB,CAAC;AACH;AAEA,MAAM,gCAAgC;AAEtC,SAAS,sBAAsB,gBAAiD;CAC9E,MAAM,QAAQ,gBAAgB,IAAI,6BAA6B;CAC/D,OAAO,MAAM,QAAQ,KAAK,IAAK,QAAqB,CAAC;AACvD;;;;;;;AAQA,SAAgB,mCACd,gBACA,YACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,MAAM,YAAY,sBAAsB,cAAc;CACtD,IAAI,UAAU,SAAS,UAAU,GAAG;CACpC,eAAe,IAAI,+BAA+B,CAAC,GAAG,WAAW,UAAU,CAAC;AAC9E;;AAGA,SAAgB,iCACd,gBACA,YACS;CACT,OAAO,sBAAsB,cAAc,CAAC,CAAC,SAAS,UAAU;AAClE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorization-input.d.ts","sourceRoot":"","sources":["../../src/auth/authorization-input.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CA4BA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorization-input.js","names":[],"sources":["../../src/auth/authorization-input.ts"],"sourcesContent":["/**\n * Forgiving parser for user-pasted OAuth authorization input.\n *\n * Accepts, in order of preference:\n * - a full redirect URL (`https://.../callback?code=...&state=...`)\n * - the `code#state` form shown on Anthropic's hosted callback page\n * - a raw query string (`code=...&state=...`)\n * - a bare authorization code\n *\n * Ported from pi-mono's `parseAuthorizationInput`.\n */\nexport function parseAuthorizationInput(input: string): {\n code?: string;\n state?: string;\n} {\n const value = input.trim();\n if (!value) return {};\n\n try {\n const url = new URL(value);\n return {\n code: url.searchParams.get('code') ?? undefined,\n state: url.searchParams.get('state') ?? undefined,\n };\n } catch {\n // not a URL\n }\n\n if (value.includes('#')) {\n const [code, state] = value.split('#', 2);\n return { code, state };\n }\n\n if (value.includes('code=')) {\n const params = new URLSearchParams(value);\n return {\n code: params.get('code') ?? undefined,\n state: params.get('state') ?? undefined,\n };\n }\n\n return { code: value };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,wBAAwB,OAGtC;CACA,MAAM,QAAQ,MAAM,KAAK;CACzB,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,OAAO;GACL,MAAM,IAAI,aAAa,IAAI,MAAM,KAAK,KAAA;GACtC,OAAO,IAAI,aAAa,IAAI,OAAO,KAAK,KAAA;EAC1C;CACF,QAAQ,CAER;CAEA,IAAI,MAAM,SAAS,GAAG,GAAG;EACvB,MAA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O,CAAC,CAAC,CAAC,CAwBb"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"device-code.js","names":[],"sources":["../../src/auth/device-code.ts"],"sourcesContent":["/**\n * Generic RFC 8628 (OAuth 2.0 Device Authorization Grant) polling helpers.\n *\n * Ported from pi-mono's device-code utility, restructured as a single-step\n * API so the same poll semantics can be driven two ways:\n * - `pollDeviceCodeUntilComplete()` — blocking loop for TUI flows.\n * - `stepDeviceCodePoll()` — exactly one upstream poll per call, with a\n * JSON-serializable `DeviceCodePollState` so web routes can persist the\n * state between HTTP requests (any replica can continue the poll).\n *\n * Inspired by pi-mono:\n * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/device-code.ts\n */\n\nconst DEFAULT_INTERVAL_SECONDS = 5;\nconst INITIAL_POLL_INTERVAL_MULTIPLIER = 1.2;\nconst SLOW_DOWN_POLL_INTERVAL_MULTIPLIER = 1.4;\nconst SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;\n\n/**\n * Serializable poll-loop state. Safe to round-trip through JSON (e.g. a\n * `pending jsonb` column) so device-code polling can span HTTP requests.\n */\nexport interface DeviceCodePollState {\n /** ms epoch after which the device authorization is considered expired. */\n deadlineAt: number;\n /** Current base poll interval in ms (grows on slow_down responses). */\n intervalMs: number;\n /** Number of slow_down responses observed so far. */\n slowDownResponses: number;\n}\n\nexport function createDeviceCodePollState(options: {\n /** Poll interval suggested by the server, in seconds. Defaults to 5 (RFC 8628). */\n intervalSeconds?: number;\n /** Lifetime of the device code, in seconds. */\n expiresInSeconds: number;\n /** Override \"now\" for tests. */\n now?: number;\n}): DeviceCodePollState {\n const now = options.now ?? Date.now();\n const intervalSeconds =\n typeof options.intervalSeconds === 'number' && options.intervalSeconds > 0\n ? options.intervalSeconds\n : DEFAULT_INTERVAL_SECONDS;\n return {\n deadlineAt: now + options.expiresInSeconds * 1000,\n intervalMs: Math.max(1000, Math.floor(intervalSeconds * 1000)),\n slowDownResponses: 0,\n };\n}\n\n/**\n * Classified result of one upstream token-endpoint poll. Providers implement\n * the HTTP request and map their response shape onto this union.\n */\nexport type DeviceCodePollOutcome<T> =\n | { status: 'complete'; result: T }\n | { status: 'pending'; intervalSeconds?: number }\n | { status: 'slow_down'; intervalSeconds?: number }\n | { status: 'failed'; error: string };\n\nexport type DeviceCodeStepResult<T> =\n | { status: 'complete'; result: T; state: DeviceCodePollState }\n | { status: 'pending'; nextPollMs: number; state: DeviceCodePollState }\n | { status: 'slow_down'; nextPollMs: number; state: DeviceCodePollState }\n | { status: 'failed'; error: string; state: DeviceCodePollState };\n\nfunction timeoutMessage(state: DeviceCodePollState): string {\n if (state.slowDownResponses > 0) {\n // Repeated slow_down responses followed by a timeout usually means the\n // local clock is behind the server's (common in WSL/VMs after sleep).\n return 'Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.';\n }\n return 'Device flow timed out';\n}\n\n/**\n * Delay to wait before the next poll, honoring slow_down growth and clamped\n * to the remaining lifetime of the device code.\n */\nexport function nextPollDelayMs(state: DeviceCodePollState, now: number = Date.now()): number {\n const multiplier =\n state.slowDownResponses > 0 ? SLOW_DOWN_POLL_INTERVAL_MULTIPLIER : INITIAL_POLL_INTERVAL_MULTIPLIER;\n const remainingMs = Math.max(0, state.deadlineAt - now);\n return Math.min(Math.ceil(state.intervalMs * multiplier), remainingMs);\n}\n\n/**\n * Perform exactly one upstream poll and fold the outcome into the poll state.\n * Never throws for flow-level conditions — timeouts and provider errors are\n * reported as `{ status: 'failed' }` so callers can persist/report them.\n */\nexport async function stepDeviceCodePoll<T>(\n state: DeviceCodePollState,\n pollOnce: () => Promise<DeviceCodePollOutcome<T>>,\n now: number = Date.now(),\n): Promise<DeviceCodeStepResult<T>> {\n if (now >= state.deadlineAt) {\n return { status: 'failed', error: timeoutMessage(state), state };\n }\n\n const outcome = await pollOnce();\n\n switch (outcome.status) {\n case 'complete':\n return { status: 'complete', result: outcome.result, state };\n case 'failed':\n return { status: 'failed', error: outcome.error, state };\n case 'slow_down': {\n const next: DeviceCodePollState = {\n ...state,\n slowDownResponses: state.slowDownResponses + 1,\n // RFC 8628 section 3.5: grow the interval by 5 seconds, unless the\n // server told us the interval to use.\n intervalMs:\n typeof outcome.intervalSeconds === 'number' && outcome.intervalSeconds > 0\n ? outcome.intervalSeconds * 1000\n : Math.max(1000, state.intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS),\n };\n return { status: 'slow_down', nextPollMs: nextPollDelayMs(next, now), state: next };\n }\n case 'pending': {\n const next: DeviceCodePollState =\n typeof outcome.intervalSeconds === 'number' && outcome.intervalSeconds > 0\n ? { ...state, intervalMs: Math.max(1000, outcome.intervalSeconds * 1000) }\n : state;\n return { status: 'pending', nextPollMs: nextPollDelayMs(next, now), state: next };\n }\n }\n}\n\n/** Sleep that can be interrupted by an AbortSignal. */\nexport function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error('Login cancelled'));\n return;\n }\n\n let timeout: ReturnType<typeof setTimeout>;\n const onAbort = () => {\n clearTimeout(timeout);\n reject(new Error('Login cancelled'));\n };\n\n timeout = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Blocking poll loop for TUI flows: waits the appropriate interval between\n * polls, honors slow_down growth, aborts on the signal, and throws on\n * failure/timeout (with a clock-drift hint after slow_down responses).\n */\nexport async function pollDeviceCodeUntilComplete<T>(options: {\n state: DeviceCodePollState;\n pollOnce: () => Promise<DeviceCodePollOutcome<T>>;\n signal?: AbortSignal;\n /** Override the sleep implementation for tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n}): Promise<T> {\n let state = options.state;\n const sleep = options.sleep ?? abortableSleep;\n\n while (true) {\n if (options.signal?.aborted) {\n throw new Error('Login cancelled');\n }\n if (Date.now() >= state.deadlineAt) {\n throw new Error(timeoutMessage(state));\n }\n\n await sleep(nextPollDelayMs(state), options.signal);\n\n const step = await stepDeviceCodePoll(state, options.pollOnce);\n state = step.state;\n\n if (step.status === 'complete') {\n return step.result;\n }\n if (step.status === 'failed') {\n throw new Error(step.error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,kCAAkC;AAexC,SAAgB,0BAA0B,SAOlB;CACtB,MAAM,MAAM,QAAQ,OAAO,KAAK,IAAI;CACpC,MAAM,kBACJ,OAAO,QAAQ,oBAAoB,YAAY,QAAQ,kBAAkB,IACrE,QAAQ,kBACR;CACN,OAAO;EACL,YAAY,MAAM,QAAQ,mBAAmB;EAC7C,YAAY,KAAK,IAAI,KAAM,KAAK,MAAM,kBAAkB,GAAI,CAAC;EAC7D,mBAAmB;CACrB;AACF;AAkBA,SAAS,eAAe,OAAoC;CAC1D,IAAI,MAAM,oBAAoB,GAG5B,OAAO;CAET,OAAO;AACT;;;;;AAMA,SAAgB,gBAAgB,OAA4B,MAAc,KAAK,IAAI,GAAW;CAC5F,MAAM,aACJ,MAAM,oBAAoB,IAAI,qCAAqC;CACrE,MAAM,cAAc,KAAK,IAAI,GAAG,MAAM,aAAa,GAAG;CACtD,OAAO,KAAK,IAAI,KAAK,KAAK,MAAM,aAAa,UAAU,GAAG,WAAW;AACvE;;;;;;AAOA,eAAsB,mBACpB,OACA,UACA,MAAc,KAAK,IAAI,GACW;CAClC,IAAI,OAAO,MAAM,YACf,OAAO;EAAE,QAAQ;EAAU,OAAO,eAAe,KAAK;EAAG;CAAM;CAGjE,MAAM,UAAU,MAAM,SAAS;CAE/B,QAAQ,QAAQ,QAAhB;EACE,KAAK,YACH,OAAO;GAAE,QAAQ;GAAY,QAAQ,QAAQ;GAAQ;EAAM;EAC7D,KAAK,UACH,OAAO;GAAE,QAAQ;GAAU,OAAO,QAAQ;GAAO;EAAM;EACzD,KAAK,aAA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MAAM,OAAO,MAAM,mBAAmB,OAAO,QAAQ,QAAQ;EAC7D,QAAQ,KAAK;EAEb,IAAI,KAAK,WAAW,YAClB,OAAO,KAAK;EAEd,IAAI,KAAK,WAAW,UAClB,MAAM,IAAI,MAAM,KAAK,KAAK;CAE9B;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,iCAAiC,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pkce.d.ts","sourceRoot":"","sources":["../../src/auth/pkce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH;;;GAGG;AACH,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAC5C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC,CAaD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pkce.js","names":[],"sources":["../../src/auth/pkce.ts"],"sourcesContent":["/**\n * PKCE utilities using Web Crypto API.\n * Works in both Node.js 20+ and browsers.\n */\n\n/**\n * Encode bytes as base64url string.\n */\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\n/**\n * Generate PKCE code verifier and challenge.\n * Uses Web Crypto API for cross-platform compatibility.\n */\nexport async function generatePKCE(): Promise<{\n verifier: string;\n challenge: string;\n}> {\n // Generate random verifier\n const verifierBytes = new Uint8Array(32);\n crypto.getRandomValues(verifierBytes);\n const verifier = base64urlEncode(verifierBytes);\n\n // Compute SHA-256 challenge\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const challenge = base64urlEncode(new Uint8Array(hashBuffer));\n\n return { verifier, challenge };\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,gBAAgB,OAA2B;CAClD,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OACjB,UAAU,OAAO,aAAa,IAAI;CAEpC,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,MAAM,EAAE;AAC9E;;;;;AAMA,eAAsB,eAGnB;CAED,MAAM,gCAAgB,IAAI,WAAW,EAAE;CACvC,OAAO,gBAAgB,aAAa;CACpC,MAAM,WAAW,gBAAgB,aAAa;CAI9C,MAAM,OAAO,IADO,YACD,CAAC,CAAC,OAAO,QAAQ;CACpC,MAAM,aAAa,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;CAG7D,OAAO;EAAE;EAAU,WAFD,gBAAgB,IAAI,WAAW,UAAU,CAEhC;CAAE;AAC/B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-auth-error.d.ts","sourceRoot":"","sources":["../../src/auth/provider-auth-error.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,8BAA8B,CAAC;AAExE;;;;;GAKG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,+BAAgC;IAE7C,MAAM,CAAC,WAAW,CAAC,YAAY,EAAE,MAAM,GAAG,yBAAyB,CAElE;IAED,MAAM,CAAC,aAAa,CAAC,YAAY,EAAE,MAAM,GAAG,yBAAyB,CAEpE;CACF;AAiBD;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,QAAQ,EAAE,QAAQ,EAClB,EAAE,YAAY,EAAE,UAAU,EAAE,EAAE;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACzE,OAAO,CAAC,QAAQ,CAAC,CAKnB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-auth-error.js","names":[],"sources":["../../src/auth/provider-auth-error.ts"],"sourcesContent":["/** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */\nexport const PROVIDER_AUTH_REQUIRED_ERROR = 'ProviderAuthRequiredError';\n\n/**\n * A provider credential is missing or no longer usable. The message states the\n * fact only — how the user re-authenticates is the host's call (`/login` in the\n * TUI, Settings → Models in the factory web UI), so no host advertises a\n * command another host doesn't have.\n */\nexport class ProviderAuthRequiredError extends Error {\n readonly name = PROVIDER_AUTH_REQUIRED_ERROR;\n\n static notSignedIn(providerName: string): ProviderAuthRequiredError {\n return new ProviderAuthRequiredError(`Not logged in to ${providerName}.`);\n }\n\n static signInExpired(providerName: string): ProviderAuthRequiredError {\n return new ProviderAuthRequiredError(`${providerName} sign-in expired.`);\n }\n}\n\nfunction providerErrorMessage(body: string): string | undefined {\n try {\n const parsed = JSON.parse(body) as { message?: unknown; error?: unknown };\n const error = parsed.error;\n if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') return error;\n if (typeof parsed.message === 'string') return parsed.message;\n } catch {\n // Not JSON — fall through to the raw text.\n }\n return body.trim() || undefined;\n}\n\n/**\n * A stored OAuth token the provider rejects (revoked, signed out elsewhere) is\n * the same user-facing state as a missing one, so a 401 becomes\n * `ProviderAuthRequiredError`. `status` and `requestUrl` stay on the error:\n * account rotation reads them to force a refresh and attribute the provider.\n */\nexport async function rejectUnauthorizedResponse(\n response: Response,\n { providerName, requestUrl }: { providerName: string; requestUrl: string },\n): Promise<Response> {\n if (response.status !== 401) return response;\n const detail = providerErrorMessage(await response.text().catch(() => ''));\n const message = `${providerName} rejected the stored sign-in${detail ? `: ${detail}` : '.'}`;\n throw Object.assign(new ProviderAuthRequiredError(message), { status: 401, requestUrl });\n}\n"],"mappings":";;AACA,MAAa,+BAA+B;;;;;;;AAQ5C,IAAa,4BAAb,MAAa,kCAAkC,MAAM;CACnD,OAAgB;CAEhB,OAAO,YAAY,cAAiD;EAClE,OAAO,IAAI,0BAA0B,oBAAoB,aAAa,EAAE;CAC1E;CAEA,OAAO,cAAc,cAAiD;EACpE,OAAO,IAAI,0BAA0B,GAAG,aAAa,kBAAkB;CACzE;AACF;AAEA,SAAS,qBAAqB,MAAkC;CAC9D,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAC9B,MAAM,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,SAAS,OAAO,MAAM,YAAY,UAChG,OAAO,MAAM;EAEf,IAAI,OAAO,UAAU,UAAU,OAAO;EACtC,IAAI,OAAO,OAAO,YAAY,UAAU,OAAO,OAAO;CACxD,QAAQ,CAER;CACA,OAAO,KAAK,KAAK,KAAK,KAAA;AACxB;;;;;;;AAQA,eAAsB,2BACpB,UACA,EAAE,cAAc,cACG;CACnB,IAAI,SAAS,WAAW,KAAK,OAAO;CACpC,MAAM,SAAS,qBAAqB,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE,CAAC;CACzE,MAAM,UAAU,GAAG,aAAa,8BAA8B,SAAS,KAAK,WAAW;CACvF,MAAM,OAAO,OAAO,IAAI,0BAA0B,OAAO,GAAG;EAAE,QAAQ;EAAK;CAAW,CAAC;AACzF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/providers/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAuB,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAYjG,MAAM,WAAW,mBAAmB;IAClC,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,mBAAmB,CAAC,CAexE;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA8CvG;AAED;;GAEG;AACH,wBAAsB,cAAc,CAClC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,EAChC,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,GAClC,OAAO,CAAC,gBAAgB,CAAC,CAU3B;AAED;;GAEG;AACH,wBAAsB,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2B3F;AAED,eAAO,MAAM,sBAAsB,EAAE,sBAkBpC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic.js","names":[],"sources":["../../../src/auth/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * Inspired by pi-mono's OAuth implementation:\n * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/anthropic.ts\n *\n * The flow is a paste-code PKCE flow: the redirect lands on Anthropic's hosted\n * callback page which displays `code#state` for the user to paste back. That\n * makes it deployable without any inbound connection to the server, so the\n * primitives are split into `startAnthropicLogin()` / `completeAnthropicLogin()`\n * which can span separate HTTP requests (only the PKCE verifier needs to be\n * persisted in between).\n */\n\nimport { parseAuthorizationInput } from '../authorization-input.js';\nimport { generatePKCE } from '../pkce.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode('OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl');\nconst AUTHORIZE_URL = 'https://claude.ai/oauth/authorize';\n// pi-mono uses `https://platform.claude.com/v1/oauth/token` with extra scopes\n// (user:sessions:claude_code, user:mcp_servers, user:file_upload); we keep the\n// console.anthropic.com endpoints that are known to work for our scope set.\nconst TOKEN_URL = 'https://console.anthropic.com/v1/oauth/token';\nconst REDIRECT_URI = 'https://console.anthropic.com/oauth/code/callback';\nconst SCOPES = 'org:create_api_key user:profile user:inference';\n\nexport interface AnthropicLoginStart {\n /** Authorization URL for the user to open. */\n url: string;\n /** PKCE code verifier — persist it to complete the login later. */\n verifier: string;\n}\n\n/**\n * Start an Anthropic login: generate PKCE state and build the authorization URL.\n */\nexport async function startAnthropicLogin(): Promise<AnthropicLoginStart> {\n const { verifier, challenge } = await generatePKCE();\n\n const authParams = new URLSearchParams({\n code: 'true',\n client_id: CLIENT_ID,\n response_type: 'code',\n redirect_uri: REDIRECT_URI,\n scope: SCOPES,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state: verifier,\n });\n\n return { url: `${AUTHORIZE_URL}?${authParams.toString()}`, verifier };\n}\n\n/**\n * Complete an Anthropic login: parse the pasted authorization input\n * (full URL, `code#state`, or query string), validate its state, and exchange\n * it for tokens using the verifier from `startAnthropicLogin()`.\n */\nexport async function completeAnthropicLogin(input: string, verifier: string): Promise<OAuthCredentials> {\n const { code, state } = parseAuthorizationInput(input);\n if (!code) {\n throw new Error('Missing authorization code');\n }\n if (!state || state !== verifier) {\n throw new Error('Invalid authorization state');\n }\n\n const tokenResponse = await fetch(TOKEN_URL, {\n method: 'POST',\n // Bound the OAuth exchange so an unresponsive upstream cannot pin the\n // caller (and, in the shipyard server, the containing project lock)\n // indefinitely. See 2025-07-23 shipyard latency incident.\n signal: AbortSignal.timeout(15_000),\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code,\n state,\n redirect_uri: REDIRECT_URI,\n code_verifier: verifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n throw new Error(`Token exchange failed: ${tokenResponse.status}`);\n }\n\n const tokenData = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n // Calculate expiry time (current time + expires_in seconds - 5 min buffer)\n const expiresAt = Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000;\n\n return {\n refresh: tokenData.refresh_token,\n access: tokenData.access_token,\n expires: expiresAt,\n };\n}\n\n/**\n * Login with Anthropic OAuth (paste-code flow), blocking on the prompt callback.\n */\nexport async function loginAnthropic(\n onAuthUrl: (url: string) => void,\n onPromptCode: () => Promise<string>,\n): Promise<OAuthCredentials> {\n const { url, verifier } = await startAnthropicLogin();\n\n // Notify caller with URL to open\n onAuthUrl(url);\n\n // Wait for user to paste authorization code (format: code#state)\n const authCode = await onPromptCode();\n\n return completeAnthropicLogin(authCode, verifier);\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nexport async function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredentials> {\n const response = await fetch(TOKEN_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(15_000),\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'refresh_token',\n client_id: CLIENT_ID,\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Anthropic token refresh failed: ${response.status}`);\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n return {\n refresh: data.refresh_token,\n access: data.access_token,\n expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n };\n}\n\nexport const anthropicOAuthProvider: OAuthProviderInterface = {\n id: 'anthropic',\n name: 'Anthropic (Claude Pro/Max)',\n\n async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n return loginAnthropic(\n url => callbacks.onAuth({ url }),\n () => callbacks.onPrompt({ message: 'Paste the authorization code:' }),\n );\n },\n\n async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n return refreshAnthropicToken(credentials.refresh);\n },\n\n getApiKey(credentials: OAuthCredentials): string {\n return credentials.access;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,UAAU,MAAc,KAAK,CAAC;AACpC,MAAM,YAAY,OAAO,kDAAkD;AAC3E,MAAM,gBAAgB;AAItB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,SAAS;;;;AAYf,eAAsB,sBAAoD;CACxE,MAAM,EAAE,UAAU,cAAc,MAAM,aAAa;CAEnD,MAAM,aAAa,IAAI,gBAAgB;EACrC,MAAM;EACN,WAAW;EACX,eAAe;EACf,cAAc;EACd,OAAO;EACP,gBAAgB;EAChB,uBAAuB;EACvB,OAAO;CACT,CAAC;CAED,OAAO;EAAE,KAAK,GAAG,cAAc,GAAG,WAAW,SAAS;EAAK;CAAS;AACtE;;;;;;AAOA,eAAsB,uBAAuB,OAAe,UAA6C;CACvG,MAAM,EAAE,MAAM,UAAU,wBAAwB,KAAK;CACrD,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,4BAA4B;CAE9C,IAAI,CAAC,SAAS,UAAU,UACtB,MAAM,IAAI,MAAM,6BAA6B;CAG/C,MAAM,gBAAgB,MAAM,MAAM,WAAW;EAC3C,QAAQ;EAIR,QAAQ,YAAY,QAAQ,IAAM;EAClC,SAAS,EACP,gBAAgB,mBAClB;EACA,MAAM,KAAK,UAAU;GACnB,YAAY;GACZ,WAAW;GACX;GACA;GACA,cAAc;GACd,eAAe;EACjB,CAAC;CACH,CAAC;CAED,IAAI,CAAC,cAAc,IACjB,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ;CAGlE,MAAM,YAAa,MAAM,cAAc,KAAK;CAO5C,MAAM,YAAY,KAAK,IAAI,IAAI,UAAU,aAAa,MAAO;CAE7D,OAAO;EACL,SAAS,UAAU;EACnB,QAAQ,UAAU;EAClB,SAAS;CAC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kB,EAAE,MAAM,EAAE,CAAC;IAC7B,gGAAgG;IAChG,iBAAiB,EAAE,OAAO,CAAC;IAC3B,wDAAwD;IACxD,cAAc,EAAE,OAAO,CAAC;IACxB,iDAAiD;IACjD,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA6D/B;AAED,eAAO,MAAM,0BAA0B,EAAE,sBAgDxC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-copilot.js","names":[],"sources":["../../../src/auth/providers/github-copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth flow\n *\n * Inspired by:\n * - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts\n * - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/copilot.ts\n *\n * Storage layout in AuthStorage:\n * - `refresh` holds the long-lived GitHub OAuth access token (used to mint Copilot tokens).\n * - `access` holds the short-lived Copilot bearer token (~30 minutes).\n * - `expires` is the Copilot bearer expiry (ms epoch, with a 5-minute safety buffer).\n * - `enterpriseUrl` is the GitHub Enterprise hostname, or undefined for github.com.\n */\n\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nexport type GitHubCopilotCredentials = OAuthCredentials & {\n enterpriseUrl?: string;\n};\n\nconst decode = (s: string): string => atob(s);\n// Copilot's public client ID, encoded to mirror the upstream references.\nconst CLIENT_ID = decode('SXYxLmI1MDdhMDhjODdlY2ZlOTg=');\n\nexport const COPILOT_USER_AGENT = 'GitHubCopilotChat/0.35.0';\n\n/** Headers that Copilot endpoints expect from a VS Code-like client. */\nexport const COPILOT_HEADERS = {\n 'User-Agent': COPILOT_USER_AGENT,\n 'Editor-Version': 'vscode/1.107.0',\n 'Editor-Plugin-Version': 'copilot-chat/0.35.0',\n 'Copilot-Integration-Id': 'vscode-chat',\n} as const;\n\nconst INITIAL_POLL_INTERVAL_MULTIPLIER = 1.2;\nconst SLOW_DOWN_POLL_INTERVAL_MULTIPLIER = 1.4;\nconst OAUTH_REQUEST_TIMEOUT_MS = 15_000;\n\nfunction requestSignal(signal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);\n return signal ? AbortSignal.any([timeout, signal]) : timeout;\n}\n\ntype DeviceCodeResponse = {\n device_code: string;\n user_code: string;\n verification_uri: string;\n interval: number;\n expires_in: number;\n};\n\ntype DeviceTokenSuccessResponse = {\n access_token: string;\n token_type?: string;\n scope?: string;\n};\n\ntype DeviceTokenErrorResponse = {\n error: string;\n error_description?: string;\n interval?: number;\n};\n\n/**\n * Normalize a user-entered Enterprise URL/domain into a hostname (e.g. `company.ghe.com`).\n * Returns null for an empty input or an unparseable URL.\n */\nexport function normalizeDomain(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed) return null;\n try {\n const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://${trimmed}`);\n return url.hostname || null;\n } catch {\n return null;\n }\n}\n\nfunction getUrls(domain: string): {\n deviceCodeUrl: string;\n accessTokenUrl: string;\n copilotTokenUrl: string;\n} {\n return {\n deviceCodeUrl: `https://${domain}/login/device/code`,\n accessTokenUrl: `https://${domain}/login/oauth/access_token`,\n copilotTokenUrl: `https://api.${domain}/copilot_internal/v2/token`,\n };\n}\n\n/**\n * Parse the `proxy-ep` segment from a Copilot bearer token and convert to its API base URL.\n * Token shape: `tid=...;exp=...;proxy-ep=proxy.individual.githubcopilot.com;...`\n */\nfunction getBaseUrlFromToken(token: string): string | null {\n const match = token.match(/proxy-ep=([^;]+)/);\n if (!match) return null;\n const proxyHost = match[1]!;\n const apiHost = proxyHost.replace(/^proxy\\./, 'api.');\n return `https://${apiHost}`;\n}\n\n/**\n * Resolve the Copilot API base URL.\n * Prefers the `proxy-ep` parsed from the bearer token, then falls back to enterprise/individual defaults.\n */\nexport function getGitHubCopilotBaseUrl(token?: string, enterpriseDomain?: string): string {\n if (token) {\n const fromToken = getBaseUrlFromToken(token);\n if (fromToken) return fromToken;\n }\n if (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n return 'https://api.individual.githubcopilot.com';\n}\n\nasync function fetchJson(url: string, init: RequestInit, signal?: AbortSignal): Promise<unknown> {\n const response = await fetch(url, { ...init, signal: requestSignal(signal) });\n if (!response.ok) {\n throw new Error(`${response.status} ${response.statusText}`.trim());\n }\n return response.json();\n}\n\nasync function startDeviceFlow(domain: string, signal?: AbortSignal): Promise<DeviceCodeResponse> {\n const urls = getUrls(domain);\n const data = await fetchJson(\n urls.deviceCodeUrl,\n {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': COPILOT_USER_AGENT,\n },\n body: new URLSearchParams({\n client_id: CLIENT_ID,\n scope: 'read:user',\n }),\n },\n signal,\n );\n\n if (!data || typeof data !== 'object') {\n throw new Error('Invalid device code response');\n }\n\n const obj = data as Record<string, unknown>;\n const deviceCode = obj.device_code;\n const userCode = obj.user_code;\n const verificationUri = obj.verification_uri;\n const interval = obj.interval;\n const expiresIn = obj.expires_in;\n\n if (\n typeof deviceCode !== 'string' ||\n typeof userCode !== 'string' ||\n typeof verificationUri !== 'string' ||\n typeof interval !== 'number' ||\n typeof expiresIn !== 'number'\n ) {\n throw new Error('Invalid device code response fields');\n }\n\n return {\n device_code: deviceCode,\n user_code: userCode,\n verification_uri: verificationUri,\n interval,\n expires_in: expiresIn,\n };\n}\n\n/** Sleep that can be interrupted by an AbortSignal. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error('Login cancelled'));\n return;\n }\n\n let timeout: ReturnType<typeof setTimeout>;\n const onAbort = () => {\n clearTimeout(timeout);\n reject(new Error('Login cancelled'));\n };\n\n timeout = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Serializable pending state for a Copilot device-code login. Safe to persist\n * (e.g. a `pending jsonb` column) so polling can span HTTP requests/replicas.\n */\nexport interface CopilotDeviceLoginPending {\n /** GitHub host performing the flow (`github.com` or an Enterprise hostname). */\n domain: string;\n /** Enterprise hostname, or undefined for github.com. Recorded on the final credentials. */\n enterpriseDomain?: string;\n deviceCode: string;\n userCode: string;\n /** Verification URL for the user to open. */\n url: string;\n instructions: string;\n /** Current base poll interval in ms (grows on slow_down). */\n intervalMs: number;\n /** Safety margin applied to intervalMs when computing the next wait. */\n intervalMultiplier: number;\n /** Number of slow_down responses seen (used for the clock-drift hint). */\n slowDownCount: number;\n /** ms epoch after which the device authorization expires. */\n deadlineAt: number;\n}\n\nexport type CopilotDevicePollResult =\n | { status: 'complete'; credentials: GitHubCopilotCredentials }\n | { status: 'pending'; pending: CopilotDeviceLoginPending; nextPollMs: number }\n | { status: 'failed'; error: string };\n\n/** Delay to wait before the next upstream poll for a pending Copilot device login. */\nexport function copilotNextPollDelayMs(pending: CopilotDeviceLoginPending): number {\n return Math.ceil(pending.intervalMs * pending.intervalMultiplier);\n}\n\n/**\n * Start a Copilot device-code login: request a user code and return the\n * serializable pending state for subsequent polls. Wait `copilotNextPollDelayMs`\n * before the first poll.\n */\nexport async function startGitHubCopilotDeviceLogin(\n enterpriseDomain?: string,\n options?: { signal?: AbortSignal },\n): Promise<CopilotDeviceLoginPending> {\n const domain = enterpriseDomain || 'github.com';\n const device = await startDeviceFlow(domain, options?.signal);\n\n return {\n domain,\n ...(enterpriseDomain ? { enterpriseDomain } : {}),\n deviceCode: device.device_code,\n userCode: device.user_code,\n url: device.verification_uri,\n instructions: `Enter code: ${device.user_code}`,\n intervalMs: Math.max(1000, Math.floor(device.interval * 1000)),\n intervalMultiplier: INITIAL_POLL_INTERVAL_MULTIPLIER,\n slowDownCount: 0,\n deadlineAt: Date.now() + device.expires_in * 1000,\n };\n}\n\n/**\n * Perform exactly one upstream poll for a pending Copilot device login.\n * On success, exchanges the GitHub OAuth token for a Copilot bearer token and\n * returns full credentials. Never throws for flow-level conditions; network\n * errors from fetch still propagate.\n */\nexport async function pollGitHubCopilotDeviceLogin(\n pending: CopilotDeviceLoginPending,\n options?: { signal?: AbortSignal; onProgress?: (message: string) => void },\n): Promise<CopilotDevicePollResult> {\n if (Date.now() >= pending.deadlineAt) {\n if (pending.slowDownCount > 0) {\n return {\n status: 'failed',\n error:\n 'Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.',\n };\n }\n return { status: 'failed', error: 'Device flow timed out' };\n }\n\n const urls = getUrls(pending.domain);\n const raw = await fetchJson(\n urls.accessTokenUrl,\n {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': COPILOT_USER_AGENT,\n },\n body: new URLSearchParams({\n client_id: CLIENT_ID,\n device_code: pending.deviceCode,\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n }),\n },\n options?.signal,\n );\n\n if (raw && typeof raw === 'object' && typeof (raw as DeviceTokenSuccessResponse).access_token === 'string') {\n const githubAccessToken = (raw as DeviceTokenSuccessResponse).access_token;\n options?.onProgress?.('Fetching Copilot token...');\n const credentials = await refreshGitHubCopilotToken(githubAccessToken, pending.enterpriseDomain, options?.signal);\n return { status: 'complete', credentials };\n }\n\n if (raw && typeof raw === 'object' && typeof (raw as DeviceTokenErrorResponse).error === 'string') {\n const { error, error_description: description, interval } = raw as DeviceTokenErrorResponse;\n\n if (error === 'slow_down') {\n const next: CopilotDeviceLoginPending = {\n ...pending,\n slowDownCount: pending.slowDownCount + 1,\n intervalMs:\n typeof interval === 'number' && interval > 0 ? interval * 1000 : Math.max(1000, pending.intervalMs + 5000),\n intervalMultiplier: SLOW_DOWN_POLL_INTERVAL_MULTIPLIER,\n };\n return { status: 'pending', pending: next, nextPollMs: copilotNextPollDelayMs(next) };\n }\n\n if (error !== 'authorization_pending') {\n const descriptionSuffix = description ? `: ${description}` : '';\n return { status: 'failed', error: `Device flow failed: ${error}${descriptionSuffix}` };\n }\n }\n\n // authorization_pending or an unrecognized-but-OK response: keep polling.\n return { status: 'pending', pending, nextPollMs: copilotNextPollDelayMs(pending) };\n}\n\n/**\n * Refresh the short-lived Copilot bearer token using the long-lived GitHub OAuth token.\n *\n * `refreshToken` here is the GitHub OAuth access token; the Copilot endpoint returns a\n * fresh bearer token (`token`) and absolute expiry (`expires_at`, seconds since epoch).\n */\nexport async function refreshGitHubCopilotToken(\n refreshToken: string,\n enterpriseDomain?: string,\n signal?: AbortSignal,\n): Promise<GitHubCopilotCredentials> {\n const domain = enterpriseDomain || 'github.com';\n const urls = getUrls(domain);\n\n const raw = await fetchJson(\n urls.copilotTokenUrl,\n {\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${refreshToken}`,\n ...COPILOT_HEADERS,\n },\n },\n signal,\n );\n\n if (!raw || typeof raw !== 'object') {\n throw new Error('Invalid Copilot token response');\n }\n\n const obj = raw as Record<string, unknown>;\n const token = obj.token;\n const expiresAt = obj.expires_at;\n\n if (typeof token !== 'string' || typeof expiresAt !== 'number') {\n throw new Error('Invalid Copilot token response fields');\n }\n\n const credentials: GitHubCopilotCredentials = {\n refresh: refreshToken,\n access: token,\n // expires_at is seconds; subtract 5 minutes so we refresh before actual expiry.\n expires: expiresAt * 1000 - 5 * 60 * 1000,\n };\n if (enterpriseDomain) {\n credentials.enterpriseUrl = enterpriseDomain;\n }\n return credentials;\n}\n\n/**\n * Login with GitHub Copilot OAuth (device-code flow).\n *\n * Prompts for an optional GitHub Enterprise URL/domain, performs the device-code flow,\n * then exchanges the GitHub OAuth token for a Copilot bearer token.\n */\nexport async function loginGitHubCopilot(options: {\n onAuth: (url: string, instructions?: string) => void;\n onPrompt: (prompt: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise<string>;\n onProgress?: (message: string) => void;\n signal?: AbortSignal;\n}): Promise<GitHubCopilotCredentials> {\n const input = await options.onPrompt({\n message: 'GitHub Enterprise URL/domain (blank for github.com)',\n placeholder: 'company.ghe.com',\n allowEmpty: true,\n });\n\n if (options.signal?.aborted) {\n throw new Error('Login cancelled');\n }\n\n const trimmed = input.trim();\n const enterpriseDomain = normalizeDomain(input);\n if (trimmed && !enterpriseDomain) {\n throw new Error('Invalid GitHub Enterprise URL/domain');\n }\n let pending = await startGitHubCopilotDeviceLogin(enterpriseDomain ?? undefined, { signal: options.signal });\n options.onAuth(pending.url, pending.instructions);\n\n while (true) {\n if (options.signal?.aborted) {\n throw new Error('Login cancelled');\n }\n\n // Wait before polling (safety margin over the server interval), clamped to the deadline.\n const remainingMs = Math.max(pending.deadlineAt - Date.now(), 0);\n await abortableSleep(Math.min(copilotNextPollDelayMs(pending), remainingMs), options.signal);\n\n const result = await pollGitHubCopilotDeviceLogin(pending, {\n signal: options.signal,\n onProgress: options.onProgress,\n });\n if (result.status === 'complete') {\n return result.credentials;\n }\n if (result.status === 'failed') {\n throw new Error(result.error);\n }\n pending = result.pending;\n }\n}\n\n/**\n * Filtered, normalized entry from the Copilot `/models` API.\n *\n * The full API payload includes a lot of capability metadata; we only keep the bits\n * we need to expose models in `listAvailableModels()` and route requests sensibly.\n */\nexport type CopilotModelEntry = {\n /** Stable model id (e.g. `claude-sonnet-4.5`, `gpt-4.1`). */\n id: string;\n /** Human-readable display name (e.g. `Claude Sonnet 4.5`). */\n name: string;\n /** Vendor field from the API (e.g. `Anthropic`, `OpenAI`). */\n vendor: string;\n /**\n * Endpoints the model exposes (e.g. `/chat/completions`, `/responses`, `/v1/messages`).\n * Empty when the API didn't return `supported_endpoints` for this entry.\n */\n supportedEndpoints: string[];\n /** True when `supported_endpoints` includes `/v1/messages` (Anthropic-shaped Copilot model). */\n isAnthropicShaped: boolean;\n /** True when `capabilities.supports.vision` is true. */\n supportsVision: boolean;\n /** True when the model supports tool calling. */\n supportsToolCalls: boolean;\n};\n\n/**\n * Fetch the Copilot model list available to the current subscription.\n *\n * Hits `${baseURL}/models` with the Copilot bearer token, filters to\n * `model_picker_enabled === true && policy.state !== 'disabled'`, and returns\n * a normalized list. Mirrors opencode's filtering rules.\n *\n * Inspired by:\n * - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/models.ts\n */\nexport async function fetchCopilotModels(opts: {\n baseUrl: string;\n bearerToken: string;\n signal?: AbortSignal;\n}): Promise<CopilotModelEntry[]> {\n const url = `${opts.baseUrl.replace(/\\/$/, '')}/models`;\n const response = await fetch(url, {\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${opts.bearerToken}`,\n ...COPILOT_HEADERS,\n },\n signal: requestSignal(opts.signal),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch Copilot models: ${response.status} ${response.statusText}`.trim());\n }\n\n const json = await response.json().catch(() => null);\n if (!json || typeof json !== 'object' || !Array.isArray((json as { data?: unknown }).data)) {\n throw new Error('Invalid Copilot models response: missing `data` array');\n }\n\n const data = (json as { data: unknown[] }).data;\n const result: CopilotModelEntry[] = [];\n\n for (const item of data) {\n if (!item || typeof item !== 'object') continue;\n const obj = item as Record<string, unknown>;\n\n if (obj.model_picker_enabled !== true) continue;\n\n const policy = obj.policy as Record<string, unknown> | undefined;\n if (policy && policy.state === 'disabled') continue;\n\n const id = obj.id;\n if (typeof id !== 'string' || !id) continue;\n\n const name = typeof obj.name === 'string' ? obj.name : id;\n const vendor = typeof obj.vendor === 'string' ? obj.vendor : '';\n\n const capabilities = obj.capabilities as Record<string, unknown> | undefined;\n const supports = capabilities?.supports as Record<string, unknown> | undefined;\n const supportsVision = supports?.vision === true;\n const supportsToolCalls = supports?.tool_calls === true;\n\n const rawEndpoints = obj.supported_endpoints;\n const supportedEndpoints = Array.isArray(rawEndpoints)\n ? rawEndpoints.filter((e): e is string => typeof e === 'string')\n : [];\n const isAnthropicShaped = supportedEndpoints.includes('/v1/messages');\n\n result.push({\n id,\n name,\n vendor,\n supportedEndpoints,\n isAnthropicShaped,\n supportsVision,\n supportsToolCalls,\n });\n }\n\n return result;\n}\n\nexport const githubCopilotOAuthProvider: OAuthProviderInterface = {\n id: 'github-copilot',\n name: 'GitHub Copilot',\n\n async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n return loginGitHubCopilot({\n onAuth: (url, instructions) => callbacks.onAuth({ url, instructions }),\n onPrompt: callbacks.onPrompt,\n onProgress: callbacks.onProgress,\n signal: callbacks.signal,\n });\n },\n\n async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const creds = credentials as GitHubCopilotCredentials;\n return refreshGitHubCopilotToken(creds.refresh, creds.enterpriseUrl);\n },\n\n getApiKey(credentials: OAuthCredentials): string {\n return credentials.access;\n },\n\n /**\n * The stored refresh token is the long-lived GitHub OAuth token — use it to\n * resolve the account's GitHub login for the account manager. Enterprise\n * tokens don't work against api.github.com, which just falls through to the\n * label prompt/default.\n */\n async getAccountLabel(credentials: OAuthCredentials): Promise<string | undefined> {\n // Enterprise credentials authenticate against the enterprise host, not\n // GitHub.com — sending that token to api.github.com would disclose it.\n // Enterprise accounts fall through to the label prompt/default instead.\n if ((credentials as GitHubCopilotCredentials).enterpriseUrl) return undefined;\n try {\n const response = await fetch('https://api.github.com/user', {\n headers: {\n Authorization: `Bearer ${credentials.refresh}`,\n Accept: 'application/vnd.github+json',\n },\n signal: requestSignal(),\n });\n if (!response.ok) return undefined;\n const user = (await response.json()) as { login?: unknown };\n return typeof user.login === 'string' && user.login.length > 0 ? user.login : undefined;\n } catch {\n return undefined;\n }\n },\n};\n"],"mappings":";AAoBA,MAAM,UAAU,MAAsB,KAAK,CAAC;AAE5C,MAAM,YAAY,OAAO,8BAA8B;AAEvD,MAAa,q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C,OAAO,EAAE,4BAA4B,EACrC,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACjC,OAAO,CAAC,0BAA0B,CAAC,CASrC;AAED,wBAAsB,eAAe,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAS/F;AAED,wBAAsB,sBAAsB,CAC1C,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAClD,OAAO,CAAC,gBAAgB,CAAC,CAoC3B;AAED,eAAO,MAAM,uBAAuB,EAAE,sBASrC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../../src/auth/providers/kimi-coding.ts"],"sourcesContent":["import { arch, hostname, platform, release } from 'node:os';\nimport { getCurrentVersion } from '../../utils/update-check.js';\nimport {\n abortableSleep,\n createDeviceCodePollState,\n pollDeviceCodeUntilComplete,\n stepDeviceCodePoll,\n} from '../device-code.js';\nimport type { DeviceCodePollOutcome, DeviceCodePollState } from '../device-code.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098';\nconst OAUTH_HOST = 'https://auth.kimi.com';\nconst DEVICE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst DEFAULT_EXPIRES_IN_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\nconst REQUEST_TIMEOUT_MS = 30_000;\nconst REFRESH_MAX_RETRIES = 3;\n\nfunction asciiHeaderValue(value: string): string {\n const sanitized = value.replace(/[^\\x20-\\x7E]/g, '').trim();\n return sanitized || 'unknown';\n}\n\nconst KIMI_DEVICE_DETAILS = {\n 'X-Msh-Platform': 'mastracode',\n 'X-Msh-Version': asciiHeaderValue(getCurrentVersion()),\n 'X-Msh-Device-Name': asciiHeaderValue(hostname()),\n 'X-Msh-Device-Model': asciiHeaderValue(`${platform()} ${arch()}`),\n 'X-Msh-Os-Version': asciiHeaderValue(release()),\n};\n\nexport function createKimiCodingDeviceId(): string {\n return globalThis.crypto.randomUUID().replaceAll('-', '');\n}\n\nexport function isKimiCodingDeviceId(value: unknown): value is string {\n return typeof value === 'string' && DEVICE_ID_PATTERN.test(value);\n}\n\nexport function getKimiCodingDeviceHeaders(deviceId: string): Record<string, string> {\n if (!isKimiCodingDeviceId(deviceId)) {\n throw new Error('Kimi For Coding credentials have an invalid device ID. Please reconnect the account.');\n }\n return { ...KIMI_DEVICE_DETAILS, 'X-Msh-Device-Id': deviceId };\n}\n\nfunction requestSignal(signal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);\n return signal ? AbortSignal.any([timeout, signal]) : timeout;\n}\n\nfunction trustedHttpUrl(value: unknown): string | null {\n if (typeof value !== 'string' || !value) return null;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' ? url.href : null;\n } catch {\n return null;\n }\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n try {\n const value = (await response.json()) as unknown;\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nfunction credentialsFromTokenResponse(value: unknown, operation: string, deviceId: string): OAuthCredentials {\n const data = (value ?? {}) as Record<string, unknown>;\n const access = data.access_token;\n const refresh = data.refresh_token;\n const expiresIn = data.expires_in;\n if (\n typeof access !== 'string' ||\n !access ||\n typeof refresh !== 'string' ||\n !refresh ||\n typeof expiresIn !== 'number' ||\n !Number.isFinite(expiresIn) ||\n expiresIn <= 0\n ) {\n throw new Error(`Kimi For Coding token ${operation} response missing fields`);\n }\n return { access, refresh, expires: Date.now() + expiresIn * 1000, deviceId };\n}\n\nexport interface KimiCodingDeviceLoginPending {\n clientId: string;\n deviceId: string;\n deviceCode: string;\n userCode: string;\n url: string;\n instructions: string;\n state: DeviceCodePollState;\n}\n\nexport type KimiCodingDevicePollResult =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending: KimiCodingDeviceLoginPending }\n | { status: 'failed'; error: string };\n\nexport async function startKimiCodingDeviceLogin(options?: {\n signal?: AbortSignal;\n}): Promise<KimiCodingDeviceLoginPending> {\n const clientId = CLIENT_ID;\n const deviceId = createKimiCodingDeviceId();\n const response = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({ client_id: clientId }).toString(),\n signal: requestSignal(options?.signal),\n });\n if (!response.ok) {\n throw new Error(`Kimi For Coding device authorization failed: ${response.status}`);\n }\n\n const data = await readJson(response);\n const deviceCode = data?.device_code;\n const userCode = data?.user_code;\n const verificationUri = trustedHttpUrl(data?.verification_uri);\n const verificationUriComplete = trustedHttpUrl(data?.verification_uri_complete);\n if (\n typeof deviceCode !== 'string' ||\n !deviceCode ||\n typeof userCode !== 'string' ||\n !userCode ||\n !verificationUri ||\n !verificationUriComplete\n ) {\n throw new Error('Invalid Kimi For Coding device authorization response');\n }\n\n const interval = data?.interval;\n const expiresIn = data?.expires_in;\n return {\n clientId,\n deviceId,\n deviceCode,\n userCode,\n url: verificationUriComplete,\n instructions: `Enter code: ${userCode}`,\n state: createDeviceCodePollState({\n intervalSeconds:\n typeof interval === 'number' && Number.isFinite(interval) && interval > 0\n ? interval\n : DEFAULT_POLL_INTERVAL_SECONDS,\n expiresInSeconds:\n typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0\n ? expiresIn\n : DEFAULT_EXPIRES_IN_SECONDS,\n }),\n };\n}\n\nasync function pollKimiCodingTokenOnce(\n pending: KimiCodingDeviceLoginPending,\n signal?: AbortSignal,\n): Promise<DeviceCodePollOutcome<OAuthCredentials>> {\n const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(pending.deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: pending.clientId,\n device_code: pending.deviceCode,\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n }).toString(),\n signal: requestSignal(signal),\n });\n const data = await readJson(response);\n if (response.ok && typeof data?.access_token === 'string') {\n try {\n return { status: 'complete', result: credentialsFromTokenResponse(data, 'poll', pending.deviceId) };\n } catch (error) {\n return { status: 'failed', error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n const error = data?.error;\n if (error === 'authorization_pending') return { status: 'pending' };\n if (error === 'slow_down') {\n return {\n status: 'slow_down',\n intervalSeconds: typeof data?.interval === 'number' && data.interval > 0 ? data.interval : undefined,\n };\n }\n if (error === 'expired_token') {\n return { status: 'failed', error: 'Kimi For Coding authorization expired. Please restart login.' };\n }\n if (error === 'access_denied') return { status: 'failed', error: 'Kimi For Coding login was denied.' };\n return {\n status: 'failed',\n error: `Kimi For Coding token request failed: ${response.status}`,\n };\n}\n\nexport async function pollKimiCodingDeviceLogin(\n pending: KimiCodingDeviceLoginPending,\n options?: { signal?: AbortSignal },\n): Promise<KimiCodingDevicePollResult> {\n const step = await stepDeviceCodePoll(pending.state, () => pollKimiCodingTokenOnce(pending, options?.signal));\n if (step.status === 'complete') return { status: 'complete', credentials: step.result };\n if (step.status === 'failed') return { status: 'failed', error: step.error };\n return {\n status: 'pending',\n nextPollMs: step.nextPollMs,\n pending: { ...pending, state: step.state },\n };\n}\n\nexport async function loginKimiCoding(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const pending = await startKimiCodingDeviceLogin({ signal: callbacks.signal });\n callbacks.onAuth({ url: pending.url, instructions: pending.instructions, userCode: pending.userCode });\n callbacks.onProgress?.('Waiting for Kimi For Coding device authorization...');\n return pollDeviceCodeUntilComplete({\n state: pending.state,\n pollOnce: () => pollKimiCodingTokenOnce(pending, callbacks.signal),\n signal: callbacks.signal,\n });\n}\n\nexport async function refreshKimiCodingToken(\n refreshToken: string,\n options: { signal?: AbortSignal; deviceId: string },\n): Promise<OAuthCredentials> {\n const clientId = CLIENT_ID;\n const deviceHeaders = getKimiCodingDeviceHeaders(options.deviceId);\n let lastError: Error | undefined;\n for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {\n if (attempt > 0) await abortableSleep(1000 * 2 ** (attempt - 1), options.signal);\n let response: Response;\n try {\n response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...deviceHeaders,\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }).toString(),\n signal: requestSignal(options.signal),\n });\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt === REFRESH_MAX_RETRIES) throw lastError;\n continue;\n }\n const data = await readJson(response);\n if (response.ok) return credentialsFromTokenResponse(data, 'refresh', options.deviceId);\n\n const error = typeof data?.error === 'string' ? ` ${data.error}` : '';\n lastError = new Error(`Kimi For Coding token refresh failed: ${response.status}${error}`);\n const retryable = response.status === 429 || response.status >= 500;\n if (!retryable || attempt === REFRESH_MAX_RETRIES) throw lastError;\n }\n throw lastError ?? new Error('Kimi For Coding token refresh failed');\n}\n\nexport const kimiCodingOAuthProvider: OAuthProviderInterface = {\n id: 'kimi-for-coding',\n name: 'Kimi For Coding',\n login: loginKimiCoding,\n refreshToken: credentials =>\n refreshKimiCodingToken(credentials.refresh, {\n deviceId: typeof credentials.deviceId === 'string' ? credentials.deviceId : '',\n }),\n getApiKey: credentials => credentials.access,\n};\n"],"mappings":";;;;AAWA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;AAC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C;IACnD,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;CAC7B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2H5B;AAED,eAAO,MAAM,SAAS;;;;;;;;CAQrB,CAAC;AAEF;;GAEG;AACH,wBAAsB,uBAAuB,CAC3C,YAAY,EAAE,MAAM,EACpB,iBAAiB,CAAC,EAAE,MAAM,EAC1B,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAe3B;AAED,eAAO,MAAM,wBAAwB,EAAE,sBA2CtC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"openai-codex.js","names":[],"sources":["../../../src/auth/providers/openai-codex.ts"],"sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * Inspired by pi-mono's OAuth implementation:\n * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/openai-codex.ts\n *\n * NOTE: This module uses Node.js http for the OAuth callback.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds (web-ui)\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nlet _httpPromise: Promise<typeof import('node:http')> | null = null;\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nlet _http: typeof import('node:http') | null = null;\ntype HttpServer = {\n off: (event: 'error' | 'listening', listener: (...args: any[]) => void) => HttpServer;\n once: (event: 'error' | 'listening', listener: (...args: any[]) => void) => HttpServer;\n listen: (port: number, hostname: string) => HttpServer;\n close: () => void;\n};\nif (typeof process !== 'undefined' && (process.versions?.node || process.versions?.bun)) {\n _httpPromise = import('node:http').then(m => {\n _http = m;\n return m;\n });\n}\n\nimport { parseAuthorizationInput } from '../authorization-input.js';\nimport { generatePKCE } from '../pkce.js';\nimport type { AuthMode, OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProviderInterface } from '../types.js';\n\nexport const OPENAI_CODEX_AUTH_MODES: ReadonlyArray<AuthMode> = [\n {\n id: 'browser',\n name: 'Browser (local callback)',\n description: 'Opens the browser and waits for the OAuth callback on localhost.',\n },\n {\n id: 'device',\n name: 'Device code (headless)',\n description: 'Shows a code to enter at openai.com — for SSH, remote, or no-browser environments.',\n },\n];\n\nconst CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';\nconst ISSUER = 'https://auth.openai.com';\nconst AUTHORIZE_URL = `${ISSUER}/oauth/authorize`;\nconst TOKEN_URL = `${ISSUER}/oauth/token`;\nconst DEVICE_USER_CODE_URL = `${ISSUER}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${ISSUER}/api/accounts/deviceauth/token`;\nconst DEVICE_AUTHORIZE_URL = `${ISSUER}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${ISSUER}/deviceauth/callback`;\nconst DEFAULT_CALLBACK_PORT = 1455;\nconst FALLBACK_CALLBACK_PORT = 1457;\nconst DEFAULT_TOKEN_EXPIRES_IN_SECONDS = 3600;\nconst DEVICE_AUTH_TIMEOUT_MS = 15 * 60 * 1000;\nconst OAUTH_REQUEST_TIMEOUT_MS = 15_000;\nconst SCOPE = 'openid profile email offline_access api.connectors.read api.connectors.invoke';\nconst JWT_CLAIM_PATH = 'https://api.openai.com/auth';\n\nconst SUCCESS_HTML = `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Authentication successful</title>\n</head>\n<body>\n <p>Authentication successful. Return to your terminal to continue.</p>\n</body>\n</html>`;\n\ntype TokenSuccess = {\n type: 'success';\n access: string;\n refresh: string;\n expires: number;\n idToken?: string;\n};\ntype TokenFailure = { type: 'failed' };\ntype TokenResult = TokenSuccess | TokenFailure;\n\ntype JwtPayload = {\n chatgpt_account_id?: string;\n email?: string;\n [JWT_CLAIM_PATH]?: {\n chatgpt_account_id?: string;\n email?: string;\n };\n [key: string]: unknown;\n};\n\nfunction requestSignal(signal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);\n return signal ? AbortSignal.any([timeout, signal]) : timeout;\n}\n\nasync function createState(): Promise<string> {\n if (typeof process === 'undefined' || !(process.versions?.node || process.versions?.bun)) {\n throw new Error('OpenAI Codex OAuth is only available in Node.js environments');\n }\n return Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(16))).toString('hex');\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n const payload = parts[1] ?? '';\n const padded = payload\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .padEnd(Math.ceil(payload.length / 4) * 4, '=');\n const decoded = atob(padded);\n return JSON.parse(decoded) as JwtPayload;\n } catch {\n return null;\n }\n}\n\nfunction extractAccountIdFromClaims(payload: JwtPayload | null | undefined): string | null {\n if (!payload) return null;\n const accountId = payload.chatgpt_account_id ?? payload[JWT_CLAIM_PATH]?.chatgpt_account_id;\n return typeof accountId === 'string' && accountId.length > 0 ? accountId : null;\n}\n\nfunction getAccountId(tokens: { idToken?: string; access: string }, fallback?: string): string | undefined {\n const fromIdToken = tokens.idToken ? extractAccountIdFromClaims(decodeJwt(tokens.idToken)) : null;\n if (fromIdToken) return fromIdToken;\n\n const fromAccessToken = extractAccountIdFromClaims(decodeJwt(tokens.access));\n if (fromAccessToken) return fromAccessToken;\n\n return fallback;\n}\n\nfunction requireAccountId(tokens: { idToken?: string; access: string }, fallback?: string): string {\n const accountId = getAccountId(tokens, fallback);\n if (!accountId) {\n throw new Error('Failed to extract ChatGPT account id from OpenAI Codex token');\n }\n return accountId;\n}\n\nfunction extractEmailFromClaims(payload: JwtPayload): string | null {\n const email = payload.email ?? payload[JWT_CLAIM_PATH]?.email;\n return typeof email === 'string' && email.length > 0 ? email : null;\n}\n\nfunction getEmailFromTokens(tokens: { idToken?: string; access: string }): string | undefined {\n const fromIdToken = tokens.idToken ? extractEmailFromClaims(decodeJwt(tokens.idToken) ?? {}) : null;\n if (fromIdToken) return fromIdToken;\n const fromAccessToken = extractEmailFromClaims(decodeJwt(tokens.access) ?? {});\n return fromAccessToken ?? undefined;\n}\n\ntype TokenResponseJson = {\n id_token?: string;\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n};\n\nfunction tokenResponseToResult(json: TokenResponseJson, logPrefix: string): TokenResult {\n if (!json.access_token || !json.refresh_token) {\n console.error(\n `[openai-codex] ${logPrefix} response missing required fields (access_token=${Boolean(json.access_token)}, refresh_token=${Boolean(json.refresh_token)})`,\n );\n return { type: 'failed' };\n }\n\n return {\n type: 'success',\n access: json.access_token,\n refresh: json.refresh_token,\n expires: Date.now() + (json.expires_in ?? DEFAULT_TOKEN_EXPIRES_IN_SECONDS) * 1000,\n idToken: json.id_token,\n };\n}\n\nasync function exchangeAuthorizationCode(\n code: string,\n verifier: string,\n redirectUri: string,\n signal?: AbortSignal,\n): Promise<TokenResult> {\n const response = await fetch(TOKEN_URL, {\n method: 'POST',\n signal: requestSignal(signal),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code,\n code_verifier: verifier,\n redirect_uri: redirectUri,\n }),\n });\n\n if (!response.ok) {\n console.error('[openai-codex] code->token failed:', response.status);\n return { type: 'failed' };\n }\n\n return tokenResponseToResult((await response.json()) as TokenResponseJson, 'token');\n}\n\nasync function refreshAccessToken(refreshToken: string): Promise<TokenResult> {\n try {\n const response = await fetch(TOKEN_URL, {\n method: 'POST',\n signal: requestSignal(),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: CLIENT_ID,\n }),\n });\n\n if (!response.ok) {\n console.error('[openai-codex] Token refresh failed:', response.status);\n return { type: 'failed' };\n }\n\n return tokenResponseToResult((await response.json()) as TokenResponseJson, 'Token refresh');\n } catch {\n console.error('[openai-codex] Token refresh request failed');\n return { type: 'failed' };\n }\n}\n\nasync function createAuthorizationFlow(\n redirectUri: string,\n state: string,\n originator: string = 'mastracode',\n): Promise<{ verifier: string; url: string }> {\n const { verifier, challenge } = await generatePKCE();\n\n const url = new URL(AUTHORIZE_URL);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('client_id', CLIENT_ID);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('scope', SCOPE);\n url.searchParams.set('code_challenge', challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n url.searchParams.set('state', state);\n url.searchParams.set('id_token_add_organizations', 'true');\n url.searchParams.set('codex_cli_simplified_flow', 'true');\n url.searchParams.set('originator', originator);\n\n return { verifier, url: url.toString() };\n}\n\ntype OAuthServerInfo = {\n redirectUri: string;\n warning?: string;\n close: () => void;\n cancelWait: () => void;\n waitForCode: () => Promise<{ code: string } | null>;\n};\n\ntype CallbackPorts = {\n defaultPort: number;\n fallbackPort: number;\n};\n\nconst CODEX_CALLBACK_PORTS: CallbackPorts = {\n defaultPort: DEFAULT_CALLBACK_PORT,\n fallbackPort: FALLBACK_CALLBACK_PORT,\n};\n\nasync function requestCancel(port: number): Promise<void> {\n try {\n await fetch(`http://127.0.0.1:${port}/cancel`, { signal: AbortSignal.timeout(200) });\n } catch {\n // The existing listener might not be a Codex auth server.\n }\n}\n\nfunction listen(server: HttpServer, port: number): Promise<boolean> {\n return new Promise(resolve => {\n const onError = () => {\n server.off('listening', onListening);\n resolve(false);\n };\n const onListening = () => {\n server.off('error', onError);\n resolve(true);\n };\n\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, '127.0.0.1');\n });\n}\n\nasync function bindOAuthServer(server: HttpServer, ports: CallbackPorts): Promise<number | null> {\n await requestCancel(ports.defaultPort);\n if (await listen(server, ports.defaultPort)) return ports.defaultPort;\n if (await listen(server, ports.fallbackPort)) return ports.fallbackPort;\n\n return null;\n}\n\nasync function getHttpModule() {\n if (!_http && _httpPromise) {\n _http = await _httpPromise;\n }\n if (!_http) {\n throw new Error('OpenAI Codex OAuth is only available in Node.js environments');\n }\n return _http;\n}\n\nasync function startLocalOAuthServer(\n state: string,\n ports: CallbackPorts = CODEX_CALLBACK_PORTS,\n): Promise<OAuthServerInfo> {\n const http = await getHttpModule();\n let lastCode: string | null = null;\n let cancelled = false;\n const server = http.createServer((req, res) => {\n try {\n const url = new URL(req.url || '', 'http://localhost');\n if (url.pathname === '/cancel') {\n cancelled = true;\n res.statusCode = 200;\n res.end('Cancelled');\n return;\n }\n if (url.pathname !== '/auth/callback') {\n res.statusCode = 404;\n res.end('Not found');\n return;\n }\n if (url.searchParams.get('state') !== state) {\n res.statusCode = 400;\n res.end('State mismatch');\n return;\n }\n const code = url.searchParams.get('code');\n if (!code) {\n res.statusCode = 400;\n res.end('Missing authorization code');\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.end(SUCCESS_HTML);\n lastCode = code;\n } catch {\n res.statusCode = 500;\n res.end('Internal error');\n }\n });\n\n return new Promise(resolve => {\n bindOAuthServer(server, ports).then(port => {\n if (!port) {\n resolve({\n redirectUri: `http://localhost:${ports.fallbackPort}/auth/callback`,\n warning: `OpenAI Codex OAuth requires localhost port ${ports.defaultPort} or ${ports.fallbackPort}, but both are in use. Automatic browser callback will not work until one is freed.`,\n close: () => {\n try {\n server.close();\n } catch {\n // ignore\n }\n },\n cancelWait: () => {},\n waitForCode: async () => null,\n });\n return;\n }\n\n resolve({\n redirectUri: `http://localhost:${port}/auth/callback`,\n close: () => server.close(),\n cancelWait: () => {\n cancelled = true;\n },\n waitForCode: async () => {\n const sleep = () => new Promise(r => setTimeout(r, 100));\n for (let i = 0; i < 600; i += 1) {\n if (lastCode) return { code: lastCode };\n if (cancelled) return null;\n await sleep();\n }\n return null;\n },\n });\n });\n });\n}\n\n/**\n * Serializable pending state for a Codex device-code login. Safe to persist\n * (e.g. a `pending jsonb` column) so polling can span HTTP requests — the\n * device token response carries the `code_verifier`, so no PKCE state needs\n * to be kept client-side.\n */\nexport interface CodexDeviceLoginPending {\n deviceAuthId: string;\n userCode: string;\n /** Verification URL for the user to open. */\n url: string;\n instructions: string;\n /** Poll interval in ms suggested by the server. */\n intervalMs: number;\n /** ms epoch after which the device authorization expires. */\n deadlineAt: number;\n}\n\nexport type CodexDevicePollResult =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number }\n | { status: 'failed'; error: string };\n\n/**\n * Start a Codex device-code login: request a user code and return the\n * serializable pending state for subsequent polls.\n */\nexport async function startCodexDeviceLogin(options?: { signal?: AbortSignal }): Promise<CodexDeviceLoginPending> {\n const response = await fetch(DEVICE_USER_CODE_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'mastracode',\n },\n body: JSON.stringify({ client_id: CLIENT_ID, originator: 'mastracode' }),\n signal: requestSignal(options?.signal),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate OpenAI Codex device authorization: ${response.status}`);\n }\n\n const deviceData = (await response.json()) as {\n device_auth_id?: string;\n user_code?: string;\n usercode?: string;\n interval?: string | number;\n };\n\n const userCode = deviceData.user_code ?? deviceData.usercode;\n\n if (!deviceData.device_auth_id || !userCode) {\n throw new Error('OpenAI Codex device authorization response missing required fields');\n }\n\n const intervalSeconds =\n typeof deviceData.interval === 'number' ? deviceData.interval : Number.parseInt(deviceData.interval ?? '', 10) || 5;\n\n return {\n deviceAuthId: deviceData.device_auth_id,\n userCode,\n url: DEVICE_AUTHORIZE_URL,\n instructions: `Enter code: ${userCode}`,\n intervalMs: Math.max(intervalSeconds, 1) * 1000,\n deadlineAt: Date.now() + DEVICE_AUTH_TIMEOUT_MS,\n };\n}\n\n/**\n * Perform exactly one upstream poll for a pending Codex device login.\n * The Codex device endpoint signals \"still pending\" via HTTP 403/404 (it is\n * not an RFC 8628 error-JSON endpoint); on success it returns the\n * authorization code plus server-held PKCE verifier, which we exchange\n * immediately for credentials. Never throws for flow-level conditions.\n */\nexport async function pollCodexDeviceLogin(\n pending: CodexDeviceLoginPending,\n options?: { signal?: AbortSignal },\n): Promise<CodexDevicePollResult> {\n if (Date.now() >= pending.deadlineAt) {\n return { status: 'failed', error: 'OpenAI Codex device authorization timed out after 15 minutes' };\n }\n\n const pollResponse = await fetch(DEVICE_TOKEN_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'mastracode',\n },\n body: JSON.stringify({\n device_auth_id: pending.deviceAuthId,\n user_code: pending.userCode,\n }),\n signal: requestSignal(options?.signal),\n });\n\n if (pollResponse.ok) {\n const data = (await pollResponse.json()) as {\n authorization_code?: string;\n code_verifier?: string;\n };\n\n if (!data.authorization_code || !data.code_verifier) {\n return { status: 'failed', error: 'OpenAI Codex device token response missing required fields' };\n }\n\n const tokenResult = await exchangeAuthorizationCode(\n data.authorization_code,\n data.code_verifier,\n DEVICE_REDIRECT_URI,\n options?.signal,\n );\n if (tokenResult.type !== 'success') {\n return { status: 'failed', error: 'Token exchange failed' };\n }\n\n let accountId: string;\n try {\n accountId = requireAccountId(tokenResult);\n } catch (error) {\n return { status: 'failed', error: error instanceof Error ? error.message : String(error) };\n }\n\n return {\n status: 'complete',\n credentials: {\n access: tokenResult.access,\n refresh: tokenResult.refresh,\n expires: tokenResult.expires,\n accountId,\n email: getEmailFromTokens(tokenResult),\n },\n };\n }\n\n if (pollResponse.status !== 403 && pollResponse.status !== 404) {\n return {\n status: 'failed',\n error: `OpenAI Codex device authorization failed: ${pollResponse.status}`,\n };\n }\n\n return { status: 'pending', nextPollMs: pending.intervalMs };\n}\n\nasync function loginOpenAICodexDevice(options: {\n onAuth: (info: { url: string; instructions?: string }) => void;\n onProgress?: (message: string) => void;\n signal?: AbortSignal;\n sleep?: (ms: number) => Promise<void>;\n}): Promise<OAuthCredentials> {\n const pending = await startCodexDeviceLogin({ signal: options.signal });\n const sleep = options.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n options.onAuth({\n url: pending.url,\n instructions: pending.instructions,\n });\n\n await sleep(pending.intervalMs);\n\n while (true) {\n if (options.signal?.aborted) {\n throw new Error('Login cancelled');\n }\n\n const result = await pollCodexDeviceLogin(pending, { signal: options.signal });\n if (result.status === 'complete') {\n return result.credentials;\n }\n if (result.status === 'failed') {\n throw new Error(result.error);\n }\n\n options.onProgress?.('Waiting for OpenAI Codex device authorization...');\n await sleep(result.nextPollMs);\n }\n}\n\n/**\n * Login with OpenAI Codex OAuth\n *\n * @param options.onAuth - Called with URL and instructions when auth starts\n * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)\n * @param options.onProgress - Optional progress messages\n * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.\n * Races with browser callback - whichever completes first wins.\n * Useful for showing paste input immediately alongside browser flow.\n * @param options.originator - OAuth originator parameter (defaults to \"mastracode\")\n */\nexport async function loginOpenAICodex(options: {\n onAuth: (info: { url: string; instructions?: string }) => void;\n onPrompt: (prompt: OAuthPrompt) => Promise<string>;\n onProgress?: (message: string) => void;\n onManualCodeInput?: () => Promise<string>;\n signal?: AbortSignal;\n originator?: string;\n mode?: 'browser' | 'device';\n}): Promise<OAuthCredentials> {\n const envMode =\n typeof process !== 'undefined' && process.env?.MASTRACODE_OPENAI_CODEX_AUTH_MODE === 'device'\n ? 'device'\n : undefined;\n const mode = options.mode ?? envMode ?? 'browser';\n if (mode === 'device') {\n return loginOpenAICodexDevice({\n onAuth: options.onAuth,\n onProgress: options.onProgress,\n signal: options.signal,\n });\n }\n\n const state = await createState();\n const server = await startLocalOAuthServer(state);\n if (server.warning) {\n options.onProgress?.(server.warning);\n }\n const { verifier, url } = await createAuthorizationFlow(\n server.redirectUri,\n state,\n options.originator ?? 'mastracode',\n );\n\n options.onAuth({\n url,\n instructions: server.warning\n ? `${server.warning} You can still paste the authorization code or full redirect URL manually.`\n : 'A browser window should open. Complete login to finish.',\n });\n\n let code: string | undefined;\n try {\n if (options.onManualCodeInput) {\n // Race between browser callback and manual input\n let manualCode: string | undefined;\n let manualError: Error | undefined;\n const manualPromise = options\n .onManualCodeInput()\n .then(input => {\n manualCode = input;\n server.cancelWait();\n })\n .catch(err => {\n manualError = err instanceof Error ? err : new Error(String(err));\n server.cancelWait();\n });\n\n const result = await server.waitForCode();\n\n // If manual input was cancelled, throw that error\n if (manualError) {\n throw manualError;\n }\n\n if (result?.code) {\n // Browser callback won\n code = result.code;\n } else if (manualCode) {\n // Manual input won (or callback timed out and user had entered code)\n const parsed = parseAuthorizationInput(manualCode);\n if (parsed.state && parsed.state !== state) {\n throw new Error('State mismatch');\n }\n code = parsed.code;\n }\n\n // If still no code, wait for manual promise to complete and try that\n if (!code) {\n await manualPromise;\n if (manualError) {\n throw manualError;\n }\n if (manualCode) {\n const parsed = parseAuthorizationInput(manualCode);\n if (parsed.state && parsed.state !== state) {\n throw new Error('State mismatch');\n }\n code = parsed.code;\n }\n }\n } else {\n // Original flow: wait for callback, then prompt if needed\n const result = await server.waitForCode();\n if (result?.code) {\n code = result.code;\n }\n }\n\n // Fallback to onPrompt if still no code\n if (!code) {\n const input = await options.onPrompt({\n message: 'Paste the authorization code (or full redirect URL):',\n });\n const parsed = parseAuthorizationInput(input);\n if (parsed.state && parsed.state !== state) {\n throw new Error('State mismatch');\n }\n code = parsed.code;\n }\n\n if (!code) {\n throw new Error('Missing authorization code');\n }\n\n const tokenResult = await exchangeAuthorizationCode(code, verifier, server.redirectUri, options.signal);\n if (tokenResult.type !== 'success') {\n throw new Error('Token exchange failed');\n }\n\n const accountId = requireAccountId(tokenResult);\n\n return {\n access: tokenResult.access,\n refresh: tokenResult.refresh,\n expires: tokenResult.expires,\n accountId,\n email: getEmailFromTokens(tokenResult),\n };\n } finally {\n server.close();\n }\n}\n\nexport const __testing = {\n createAuthorizationFlow,\n decodeJwt,\n extractAccountIdFromClaims,\n getAccountId,\n loginOpenAICodexDevice,\n requireAccountId,\n startLocalOAuthServer,\n};\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nexport async function refreshOpenAICodexToken(\n refreshToken: string,\n previousAccountId?: string,\n previousEmail?: string,\n): Promise<OAuthCredentials> {\n const result = await refreshAccessToken(refreshToken);\n if (result.type !== 'success') {\n throw new Error('Failed to refresh OpenAI Codex token');\n }\n\n const accountId = requireAccountId(result, previousAccountId);\n\n return {\n access: result.access,\n refresh: result.refresh,\n expires: result.expires,\n accountId,\n email: getEmailFromTokens(result) ?? previousEmail,\n };\n}\n\nexport const openaiCodexOAuthProvider: OAuthProviderInterface = {\n id: 'openai-codex',\n name: 'ChatGPT Plus/Pro (Codex Subscription)',\n usesCallbackServer: true,\n authModes: OPENAI_CODEX_AUTH_MODES,\n\n async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const mode = callbacks.authMode === 'device' || callbacks.authMode === 'browser' ? callbacks.authMode : undefined;\n return loginOpenAICodex({\n onAuth: callbacks.onAuth,\n onPrompt: callbacks.onPrompt,\n onProgress: callbacks.onProgress,\n onManualCodeInput: callbacks.onManualCodeInput,\n signal: callbacks.signal,\n mode,\n });\n },\n\n async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n return refreshOpenAICodexToken(\n credentials.refresh,\n credentials.accountId as string | undefined,\n credentials.email as string | undefined,\n );\n },\n\n getApiKey(credentials: OAuthCredentials): string {\n return credentials.access;\n },\n\n getAccountLabel(credentials: OAuthCredentials): Promise<string | undefined> {\n const email = credentials.email;\n return Promise.resolve(typeof email === 'string' && email.length > 0 ? email : undefined);\n },\n\n /**\n * The ChatGPT account/workspace id from the token, when present — stable\n * across refreshes and re-authorizations of one subscription.\n */\n getAccountIdentity(credentials: OAuthCredentials): string | undefined {\n const accountId = credentials.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,CAAC;IACrB,6EAA6E;IAC7E,KAAK,EAAE,mBAAmB,CAAC;CAC5B;AAED,MAAM,MAAM,mBAAmB,GAC3B;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,WAAW,EAAE,gBAAgB,CAAA;CAAE,GACrD;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,qBAAqB,CAAA;CAAE,GACzE;IAAE,MAAM,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAExC;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAgC5G;AAsDD;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACjC,OAAO,CAAC,mBAAmB,CAAC,CAgB9B;AAED;;GAEG;AACH,wBAAsB,QAAQ,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAWxF;AAED;;GAEG;AACH,wBAAsB,eAAe,CACnC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,gBAAgB,CAAC,CAgB3B;AAgBD,eAAO,MAAM,gBAAgB,EAAE,sBA2B9B,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"xai.js","names":[],"sources":["../../../src/auth/providers/xai.ts"],"sourcesContent":["/**\n * xAI OAuth flow (Grok)\n *\n * Ported from pi-mono's xAI OAuth implementation:\n * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/xai.ts\n *\n * xAI uses a standard RFC 8628 device authorization grant, so the flow needs\n * no inbound connection to the server. The primitives are split into\n * `startXAIDeviceLogin()` / `pollXAIDeviceLogin()` so web routes can persist\n * the JSON-serializable pending state between HTTP requests; the blocking\n * `loginXAI()` wraps them for TUI use.\n */\n\nimport { createDeviceCodePollState, pollDeviceCodeUntilComplete, stepDeviceCodePoll } from '../device-code.js';\nimport type { DeviceCodePollOutcome, DeviceCodePollState } from '../device-code.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828';\nconst DEVICE_CODE_URL = 'https://auth.x.ai/oauth2/device/code';\nconst TOKEN_URL = 'https://auth.x.ai/oauth2/token';\nconst SCOPE = 'openid profile email offline_access grok-cli:access api:access';\nconst DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\nconst DEFAULT_TOKEN_EXPIRES_IN_SECONDS = 3600;\nconst REQUEST_TIMEOUT_MS = 30_000;\n// Refresh 5 minutes before actual expiry (same skew as Anthropic).\nconst REFRESH_SKEW_MS = 5 * 60 * 1000;\n\nasync function postForm(url: string, params: Record<string, string>, signal?: AbortSignal): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);\n return fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(params).toString(),\n signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal,\n });\n}\n\n/** The verification URI is opened by the user; only accept https URLs. */\nfunction validateVerificationUri(raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new Error('xAI device authorization returned an invalid verification_uri');\n }\n if (parsed.protocol !== 'https:') {\n throw new Error('xAI device authorization returned a non-https verification_uri');\n }\n return parsed.toString();\n}\n\nfunction credentialsFromTokenResponse(\n data: unknown,\n previousRefreshToken?: string,\n previousIdToken?: string,\n): OAuthCredentials {\n const record = (data ?? {}) as Record<string, unknown>;\n const access = record.access_token;\n if (typeof access !== 'string' || access.length === 0) {\n throw new Error('xAI token response missing access_token');\n }\n\n // xAI may not rotate the refresh token on refresh; keep the previous one.\n const refresh =\n typeof record.refresh_token === 'string' && record.refresh_token.length > 0\n ? record.refresh_token\n : previousRefreshToken;\n if (!refresh) {\n throw new Error('xAI token response missing refresh_token');\n }\n\n const expiresIn =\n typeof record.expires_in === 'number' && record.expires_in > 0\n ? record.expires_in\n : DEFAULT_TOKEN_EXPIRES_IN_SECONDS;\n\n return {\n access,\n refresh,\n expires: Date.now() + expiresIn * 1000 - REFRESH_SKEW_MS,\n // Kept so the account label can resolve the email claim later; xAI's\n // refresh responses re-issue it, and the previous one is carried forward\n // when they don't.\n idToken: typeof record.id_token === 'string' && record.id_token.length > 0 ? record.id_token : previousIdToken,\n };\n}\n\n/**\n * Serializable pending state for an xAI device-code login. Safe to persist\n * (e.g. a `pending jsonb` column) so polling can span HTTP requests.\n */\nexport interface XAIDeviceLoginPending {\n deviceCode: string;\n userCode: string;\n /** Verification URL for the user to open (https-only, validated). */\n url: string;\n instructions: string;\n /** RFC 8628 poll-loop state (interval growth, deadline, slow_down count). */\n state: DeviceCodePollState;\n}\n\nexport type XAIDevicePollResult =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending: XAIDeviceLoginPending }\n | { status: 'failed'; error: string };\n\n/**\n * Start an xAI device-code login: request a user code and return the\n * serializable pending state for subsequent polls.\n */\nexport async function startXAIDeviceLogin(options?: { signal?: AbortSignal }): Promise<XAIDeviceLoginPending> {\n const response = await postForm(DEVICE_CODE_URL, { client_id: CLIENT_ID, scope: SCOPE }, options?.signal);\n\n if (!response.ok) {\n throw new Error(`Failed to initiate xAI device authorization: ${response.status}`);\n }\n\n const data = (await response.json()) as {\n device_code?: string;\n user_code?: string;\n verification_uri?: string;\n verification_uri_complete?: string;\n interval?: number;\n expires_in?: number;\n };\n\n if (!data.device_code || !data.user_code || !data.verification_uri) {\n throw new Error('xAI device authorization response missing required fields');\n }\n\n const url = validateVerificationUri(data.verification_uri_complete ?? data.verification_uri);\n\n return {\n deviceCode: data.device_code,\n userCode: data.user_code,\n url,\n instructions: `Enter code: ${data.user_code}`,\n state: createDeviceCodePollState({\n intervalSeconds: data.interval,\n expiresInSeconds: typeof data.expires_in === 'number' && data.expires_in > 0 ? data.expires_in : 600,\n }),\n };\n}\n\nasync function pollXAITokenOnce(\n pending: XAIDeviceLoginPending,\n signal?: AbortSignal,\n): Promise<DeviceCodePollOutcome<OAuthCredentials>> {\n const response = await postForm(\n TOKEN_URL,\n {\n grant_type: DEVICE_CODE_GRANT_TYPE,\n device_code: pending.deviceCode,\n client_id: CLIENT_ID,\n },\n signal,\n );\n\n if (response.ok) {\n const data = (await response.json()) as unknown;\n try {\n return { status: 'complete', result: credentialsFromTokenResponse(data) };\n } catch (error) {\n return { status: 'failed', error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n const text = await response.text().catch(() => '');\n let body: { error?: string; interval?: number } = {};\n try {\n body = JSON.parse(text) as { error?: string; interval?: number };\n } catch {\n // Non-JSON upstream bodies are intentionally omitted from user-visible errors.\n }\n\n switch (body.error) {\n case 'authorization_pending':\n return { status: 'pending', intervalSeconds: body.interval };\n case 'slow_down':\n return { status: 'slow_down', intervalSeconds: body.interval };\n case 'access_denied':\n case 'authorization_denied':\n return { status: 'failed', error: 'xAI authorization was denied' };\n case 'expired_token':\n return { status: 'failed', error: 'xAI device code expired before authorization completed' };\n default:\n // Status only: `body.error` is untrusted upstream text (RFC 6749 does not\n // constrain it), so echoing it would render provider-controlled content\n // in the TUI. The known flow codes above are handled explicitly.\n return {\n status: 'failed',\n error: `xAI device authorization failed: ${response.status}`,\n };\n }\n}\n\n/**\n * Perform exactly one upstream poll for a pending xAI device login.\n * Returns the updated pending state so callers (e.g. web routes) can persist\n * slow_down interval growth between polls. Never throws for flow-level\n * conditions.\n */\nexport async function pollXAIDeviceLogin(\n pending: XAIDeviceLoginPending,\n options?: { signal?: AbortSignal },\n): Promise<XAIDevicePollResult> {\n const step = await stepDeviceCodePoll(pending.state, () => pollXAITokenOnce(pending, options?.signal));\n\n switch (step.status) {\n case 'complete':\n return { status: 'complete', credentials: step.result };\n case 'failed':\n return { status: 'failed', error: step.error };\n case 'pending':\n case 'slow_down':\n return {\n status: 'pending',\n nextPollMs: step.nextPollMs,\n pending: { ...pending, state: step.state },\n };\n }\n}\n\n/**\n * Login with xAI OAuth (device-code flow), blocking until authorized.\n */\nexport async function loginXAI(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const pending = await startXAIDeviceLogin({ signal: callbacks.signal });\n\n callbacks.onAuth({ url: pending.url, instructions: pending.instructions, userCode: pending.userCode });\n callbacks.onProgress?.('Waiting for xAI device authorization...');\n\n return pollDeviceCodeUntilComplete({\n state: pending.state,\n pollOnce: () => pollXAITokenOnce(pending, callbacks.signal),\n signal: callbacks.signal,\n });\n}\n\n/**\n * Refresh xAI OAuth token\n */\nexport async function refreshXAIToken(\n refreshToken: string,\n signal?: AbortSignal,\n previousIdToken?: string,\n): Promise<OAuthCredentials> {\n const response = await postForm(\n TOKEN_URL,\n {\n grant_type: 'refresh_token',\n client_id: CLIENT_ID,\n refresh_token: refreshToken,\n },\n signal,\n );\n\n if (!response.ok) {\n throw new Error(`xAI token refresh failed: ${response.status}`);\n }\n\n return credentialsFromTokenResponse((await response.json()) as unknown, refreshToken, previousIdToken);\n}\n\n/** Decode the email claim out of an id_token JWT payload (no verification). */\nfunction emailFromIdToken(idToken: string | undefined): string | undefined {\n if (typeof idToken !== 'string') return undefined;\n const parts = idToken.split('.');\n if (parts.length !== 3) return undefined;\n try {\n const padded = (parts[1] ?? '').replace(/-/g, '+').replace(/_/g, '/');\n const json = JSON.parse(Buffer.from(padded, 'base64').toString('utf8')) as { email?: unknown };\n return typeof json.email === 'string' && json.email.length > 0 ? json.email : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport const xaiOAuthProvider: OAuthProviderInterface = {\n id: 'xai',\n name: 'xAI (Grok)',\n\n async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n return loginXAI(callbacks);\n },\n\n async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n return refreshXAIToken(credentials.refresh, undefined, credentials.idToken as string | undefined);\n },\n\n getApiKey(credentials: OAuthCredentials): string {\n return credentials.access;\n },\n\n getAccountLabel(credentials: OAuthCredentials): Promise<string | undefined> {\n return Promise.resolve(emailFromIdToken(credentials.idToken as string | undefined));\n },\n\n /**\n * The account's email, read from the id token — one subscription per email,\n * so this distinguishes two xAI accounts from a re-authorization of one.\n */\n getAccountIdentity(credentials: OAuthCredentials): string | undefined {\n return emailFromIdToken(credentials.idToken as string | undefined);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,MAAM,yBAAyB;AAC/B,MAAM,mCAAmC;AACzC,MAAM,qBAAqB;AAE3B,MAAM,kBAAkB;AAExB,eAAe,SAAS,KAAa,QAAgC,QAAyC;CAC5G,MAAM,gBAAgB,YAAY,QAAQ,kBAAkB;CAC5D,OAAO,MAAM,KAAK;EAChB,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB,MAAM,CAAC,CAAC,SAAS;EAC3C,QAAQ,SAAS,YAAY,IAAI,CAAC,QAAQ,aAAa,CAAC,IAAI;CAC9D,CAAC;AACH;;AAGA,SAAS,wBAAwB,KAAqB;CACpD,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,GAAG;CACtB,QAAQ;EACN,MAAM,IAAI,MAAM,+DAA+D;CACjF;CACA,IAAI,OAAO,aAAa,UACtB,MAAM,IAAI,MAAM,gEAAgE;CAElF,OAAO,OAAO,SAAS;AACzB;AAEA,SAAS,6BACP,MACA,sBACA,iBACkB;CAClB,MAAM,SAAU,QAAQ,CAAC;CACzB,MAAM,SAAS,OAAO;CACtB,IAAI,OAAO,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