@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303

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 (407) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +284 -0
  3. package/dist/acp/agent.d.ts +48 -0
  4. package/dist/acp/agent.js +414 -0
  5. package/dist/acp/errors.d.ts +3 -0
  6. package/dist/acp/errors.js +11 -0
  7. package/dist/acp/event-mapper.d.ts +28 -0
  8. package/dist/acp/event-mapper.js +274 -0
  9. package/dist/acp/index.d.ts +9 -0
  10. package/dist/acp/index.js +21 -0
  11. package/dist/acp/runtime.d.ts +5 -0
  12. package/dist/acp/runtime.js +91 -0
  13. package/dist/acp/server.d.ts +4 -0
  14. package/dist/acp/server.js +35 -0
  15. package/dist/acp/skills.d.ts +6 -0
  16. package/dist/acp/skills.js +30 -0
  17. package/dist/acp.d.ts +2 -0
  18. package/dist/acp.js +1 -0
  19. package/dist/agent-connections/messaging-processor.d.ts +17 -0
  20. package/dist/agent-connections/messaging-processor.js +131 -0
  21. package/dist/agent-connections/ownership.d.ts +24 -0
  22. package/dist/agent-connections/ownership.js +96 -0
  23. package/dist/agent-connections/registry.d.ts +20 -0
  24. package/dist/agent-connections/registry.js +167 -0
  25. package/dist/agent-connections/session-advertisement.d.ts +27 -0
  26. package/dist/agent-connections/session-advertisement.js +86 -0
  27. package/dist/agent-connections/signal-provider.d.ts +141 -0
  28. package/dist/agent-connections/signal-provider.js +35 -0
  29. package/dist/agent-connections/state-processor.d.ts +23 -0
  30. package/dist/agent-connections/state-processor.js +270 -0
  31. package/dist/agent-connections/thread-state.d.ts +41 -0
  32. package/dist/agent-connections/thread-state.js +157 -0
  33. package/dist/agent-connections/tools.d.ts +133 -0
  34. package/dist/agent-connections/tools.js +616 -0
  35. package/dist/agent-connections/types.d.ts +99 -0
  36. package/dist/agent-connections/types.js +4 -0
  37. package/dist/agent-connections/untrusted-text.d.ts +5 -0
  38. package/dist/agent-connections/untrusted-text.js +19 -0
  39. package/dist/agents/background-completion-events.d.ts +16 -0
  40. package/dist/agents/background-completion-events.js +16 -0
  41. package/dist/agents/background-completion.d.ts +22 -0
  42. package/dist/agents/background-completion.js +73 -0
  43. package/dist/agents/context-audit.d.ts +84 -0
  44. package/dist/agents/context-audit.js +115 -0
  45. package/dist/agents/credential-resolver.d.ts +74 -0
  46. package/dist/agents/credential-resolver.js +142 -0
  47. package/dist/agents/custom-provider-source.d.ts +35 -0
  48. package/dist/agents/custom-provider-source.js +22 -0
  49. package/dist/agents/fastembed-subprocess.d.ts +52 -0
  50. package/dist/agents/fastembed-subprocess.js +282 -0
  51. package/dist/agents/instructions.d.ts +42 -0
  52. package/dist/agents/instructions.js +69 -0
  53. package/dist/agents/mastracode-gateway.d.ts +85 -0
  54. package/dist/agents/mastracode-gateway.js +500 -0
  55. package/dist/agents/memory.d.ts +36 -0
  56. package/dist/agents/memory.js +248 -0
  57. package/dist/agents/model.d.ts +158 -0
  58. package/dist/agents/model.js +382 -0
  59. package/dist/agents/modes/build.d.ts +12 -0
  60. package/dist/agents/modes/build.js +33 -0
  61. package/dist/agents/modes/explore.d.ts +10 -0
  62. package/dist/agents/modes/explore.js +25 -0
  63. package/dist/agents/modes/plan.d.ts +8 -0
  64. package/dist/agents/modes/plan.js +43 -0
  65. package/dist/agents/prompts/agent-instructions.d.ts +122 -0
  66. package/dist/agents/prompts/agent-instructions.js +617 -0
  67. package/dist/agents/prompts/build.d.ts +12 -0
  68. package/dist/agents/prompts/build.js +73 -0
  69. package/dist/agents/prompts/fast.d.ts +5 -0
  70. package/dist/agents/prompts/fast.js +23 -0
  71. package/dist/agents/prompts/index.d.ts +61 -0
  72. package/dist/agents/prompts/index.js +141 -0
  73. package/dist/agents/prompts/model.d.ts +5 -0
  74. package/dist/agents/prompts/model.js +20 -0
  75. package/dist/agents/prompts/plan.d.ts +11 -0
  76. package/dist/agents/prompts/plan.js +132 -0
  77. package/dist/agents/prompts/tool-guidance.d.ts +18 -0
  78. package/dist/agents/prompts/tool-guidance.js +158 -0
  79. package/dist/agents/sandbox-filesystem.d.ts +232 -0
  80. package/dist/agents/sandbox-filesystem.js +851 -0
  81. package/dist/agents/subagents/execute.d.ts +3 -0
  82. package/dist/agents/subagents/execute.js +24 -0
  83. package/dist/agents/subagents/explore.d.ts +3 -0
  84. package/dist/agents/subagents/explore.js +15 -0
  85. package/dist/agents/subagents/index.d.ts +6 -0
  86. package/dist/agents/subagents/index.js +15 -0
  87. package/dist/agents/subagents/plan.d.ts +3 -0
  88. package/dist/agents/subagents/plan.js +15 -0
  89. package/dist/agents/thread-caveman-state.d.ts +17 -0
  90. package/dist/agents/thread-caveman-state.js +104 -0
  91. package/dist/agents/tool-availability.d.ts +17 -0
  92. package/dist/agents/tool-availability.js +134 -0
  93. package/dist/agents/tools.d.ts +37 -0
  94. package/dist/agents/tools.js +154 -0
  95. package/dist/agents/workflow-builder-agent.d.ts +2 -0
  96. package/dist/agents/workflow-builder-agent.js +79 -0
  97. package/dist/agents/workspace.d.ts +35 -0
  98. package/dist/agents/workspace.js +207 -0
  99. package/dist/analytics.d.ts +18 -0
  100. package/dist/analytics.js +159 -0
  101. package/dist/auth/account-rotation-processor.d.ts +210 -0
  102. package/dist/auth/account-rotation-processor.js +662 -0
  103. package/dist/auth/account-routing-context.d.ts +17 -0
  104. package/dist/auth/account-routing-context.js +38 -0
  105. package/dist/auth/authorization-input.d.ts +16 -0
  106. package/dist/auth/authorization-input.js +39 -0
  107. package/dist/auth/device-code.d.ts +93 -0
  108. package/dist/auth/device-code.js +126 -0
  109. package/dist/auth/index.d.ts +13 -0
  110. package/dist/auth/index.js +9 -0
  111. package/dist/auth/pkce.d.ts +13 -0
  112. package/dist/auth/pkce.js +29 -0
  113. package/dist/auth/provider-auth-error.d.ts +24 -0
  114. package/dist/auth/provider-auth-error.js +44 -0
  115. package/dist/auth/providers/anthropic.d.ts +40 -0
  116. package/dist/auth/providers/anthropic.js +117 -0
  117. package/dist/auth/providers/github-copilot.d.ts +154 -0
  118. package/dist/auth/providers/github-copilot.js +359 -0
  119. package/dist/auth/providers/kimi-coding.d.ts +38 -0
  120. package/dist/auth/providers/kimi-coding.js +225 -0
  121. package/dist/auth/providers/openai-codex.d.ts +141 -0
  122. package/dist/auth/providers/openai-codex.js +531 -0
  123. package/dist/auth/providers/xai.d.ts +64 -0
  124. package/dist/auth/providers/xai.js +223 -0
  125. package/dist/auth/storage.d.ts +222 -0
  126. package/dist/auth/storage.js +805 -0
  127. package/dist/auth/types.d.ts +164 -0
  128. package/dist/auth/types.js +1 -0
  129. package/dist/clipboard/index.d.ts +26 -0
  130. package/dist/clipboard/index.js +224 -0
  131. package/dist/constants.d.ts +29 -0
  132. package/dist/constants.js +34 -0
  133. package/dist/error-classification.d.ts +10 -0
  134. package/dist/error-classification.js +19 -0
  135. package/dist/evals/context-builder.d.ts +41 -0
  136. package/dist/evals/context-builder.js +156 -0
  137. package/dist/evals/index.d.ts +4 -0
  138. package/dist/evals/index.js +5 -0
  139. package/dist/evals/scorers/classify-command.d.ts +30 -0
  140. package/dist/evals/scorers/classify-command.js +61 -0
  141. package/dist/evals/scorers/efficiency.d.ts +44 -0
  142. package/dist/evals/scorers/efficiency.js +256 -0
  143. package/dist/evals/scorers/extract-tools.d.ts +25 -0
  144. package/dist/evals/scorers/extract-tools.js +57 -0
  145. package/dist/evals/scorers/index.d.ts +3 -0
  146. package/dist/evals/scorers/index.js +3 -0
  147. package/dist/evals/scorers/outcome.d.ts +49 -0
  148. package/dist/evals/scorers/outcome.js +360 -0
  149. package/dist/experimental-agent.d.ts +19 -0
  150. package/dist/experimental-agent.js +45 -0
  151. package/dist/factory/client.d.ts +44 -0
  152. package/dist/factory/client.js +110 -0
  153. package/dist/factory/remote-controller.d.ts +34 -0
  154. package/dist/factory/remote-controller.js +40 -0
  155. package/dist/factory/remote-session.d.ts +210 -0
  156. package/dist/factory/remote-session.js +415 -0
  157. package/dist/goal-manager.d.ts +114 -0
  158. package/dist/goal-manager.js +351 -0
  159. package/dist/goal-signal.d.ts +14 -0
  160. package/dist/goal-signal.js +14 -0
  161. package/dist/headless/cli.d.ts +55 -0
  162. package/dist/headless/cli.js +261 -0
  163. package/dist/headless/flags.d.ts +33 -0
  164. package/dist/headless/flags.js +207 -0
  165. package/dist/headless/format.d.ts +41 -0
  166. package/dist/headless/format.js +94 -0
  167. package/dist/headless/index.d.ts +25 -0
  168. package/dist/headless/index.js +6 -0
  169. package/dist/headless/policy.d.ts +17 -0
  170. package/dist/headless/policy.js +39 -0
  171. package/dist/headless/run-mc.d.ts +7 -0
  172. package/dist/headless/run-mc.js +438 -0
  173. package/dist/headless/types.d.ts +175 -0
  174. package/dist/headless/types.js +16 -0
  175. package/dist/hooks/config.d.ts +11 -0
  176. package/dist/hooks/config.js +77 -0
  177. package/dist/hooks/executor.d.ts +13 -0
  178. package/dist/hooks/executor.js +128 -0
  179. package/dist/hooks/index.d.ts +6 -0
  180. package/dist/hooks/index.js +5 -0
  181. package/dist/hooks/manager.d.ts +75 -0
  182. package/dist/hooks/manager.js +289 -0
  183. package/dist/hooks/types.d.ts +180 -0
  184. package/dist/hooks/types.js +5 -0
  185. package/dist/index.d.ts +537 -0
  186. package/dist/index.js +1399 -0
  187. package/dist/ipc/ipc-reporter.d.ts +14 -0
  188. package/dist/ipc/ipc-reporter.js +18 -0
  189. package/dist/knowledge-inspector.d.ts +139 -0
  190. package/dist/knowledge-inspector.js +533 -0
  191. package/dist/knowledge-scope-id.d.ts +7 -0
  192. package/dist/knowledge-scope-id.js +10 -0
  193. package/dist/knowledge-scope.d.ts +41 -0
  194. package/dist/knowledge-scope.js +85 -0
  195. package/dist/lsp/client.d.ts +56 -0
  196. package/dist/lsp/client.js +248 -0
  197. package/dist/lsp/index.d.ts +4 -0
  198. package/dist/lsp/index.js +4 -0
  199. package/dist/lsp/language.d.ts +9 -0
  200. package/dist/lsp/language.js +41 -0
  201. package/dist/lsp/manager.d.ts +34 -0
  202. package/dist/lsp/manager.js +79 -0
  203. package/dist/lsp/server.d.ts +27 -0
  204. package/dist/lsp/server.js +158 -0
  205. package/dist/lsp/workspace.d.ts +9 -0
  206. package/dist/lsp/workspace.js +52 -0
  207. package/dist/mcp/config.d.ts +77 -0
  208. package/dist/mcp/config.js +313 -0
  209. package/dist/mcp/index.d.ts +6 -0
  210. package/dist/mcp/index.js +3 -0
  211. package/dist/mcp/manager.d.ts +104 -0
  212. package/dist/mcp/manager.js +693 -0
  213. package/dist/mcp/state.d.ts +35 -0
  214. package/dist/mcp/state.js +94 -0
  215. package/dist/mcp/types.d.ts +139 -0
  216. package/dist/mcp/types.js +1 -0
  217. package/dist/onboarding/custom-packs.d.ts +7 -0
  218. package/dist/onboarding/custom-packs.js +17 -0
  219. package/dist/onboarding/custom-providers.d.ts +4 -0
  220. package/dist/onboarding/custom-providers.js +27 -0
  221. package/dist/onboarding/index.d.ts +5 -0
  222. package/dist/onboarding/index.js +3 -0
  223. package/dist/onboarding/om-settings.d.ts +47 -0
  224. package/dist/onboarding/om-settings.js +80 -0
  225. package/dist/onboarding/pack-activation.d.ts +43 -0
  226. package/dist/onboarding/pack-activation.js +105 -0
  227. package/dist/onboarding/packs.d.ts +106 -0
  228. package/dist/onboarding/packs.js +283 -0
  229. package/dist/onboarding/settings.d.ts +563 -0
  230. package/dist/onboarding/settings.js +1110 -0
  231. package/dist/permissions.d.ts +55 -0
  232. package/dist/permissions.js +139 -0
  233. package/dist/platform/index.d.ts +74 -0
  234. package/dist/platform/index.js +199 -0
  235. package/dist/plugin.d.ts +156 -0
  236. package/dist/plugin.js +27 -0
  237. package/dist/plugins/dependencies.d.ts +9 -0
  238. package/dist/plugins/dependencies.js +84 -0
  239. package/dist/plugins/install.d.ts +21 -0
  240. package/dist/plugins/install.js +187 -0
  241. package/dist/plugins/loader.d.ts +25 -0
  242. package/dist/plugins/loader.js +264 -0
  243. package/dist/plugins/manager.d.ts +115 -0
  244. package/dist/plugins/manager.js +507 -0
  245. package/dist/plugins/manifest.d.ts +14 -0
  246. package/dist/plugins/manifest.js +47 -0
  247. package/dist/plugins/package-link.d.ts +3 -0
  248. package/dist/plugins/package-link.js +58 -0
  249. package/dist/plugins/paths.d.ts +10 -0
  250. package/dist/plugins/paths.js +22 -0
  251. package/dist/plugins/registry.d.ts +8 -0
  252. package/dist/plugins/registry.js +109 -0
  253. package/dist/plugins/scaffold.d.ts +10 -0
  254. package/dist/plugins/scaffold.js +115 -0
  255. package/dist/plugins/signal-lane.d.ts +59 -0
  256. package/dist/plugins/signal-lane.js +163 -0
  257. package/dist/plugins/types.d.ts +95 -0
  258. package/dist/plugins/types.js +1 -0
  259. package/dist/process-memory-diagnostics.d.ts +136 -0
  260. package/dist/process-memory-diagnostics.js +497 -0
  261. package/dist/processors/plan-rejection-abort.d.ts +16 -0
  262. package/dist/processors/plan-rejection-abort.js +62 -0
  263. package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
  264. package/dist/providers/amazon-bedrock-gateway.js +142 -0
  265. package/dist/providers/amazon-bedrock.d.ts +28 -0
  266. package/dist/providers/amazon-bedrock.js +99 -0
  267. package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
  268. package/dist/providers/anthropic-prompt-cache.js +8 -0
  269. package/dist/providers/anthropic-thinking.d.ts +5 -0
  270. package/dist/providers/anthropic-thinking.js +22 -0
  271. package/dist/providers/claude-max.d.ts +67 -0
  272. package/dist/providers/claude-max.js +232 -0
  273. package/dist/providers/github-copilot-gateway.d.ts +35 -0
  274. package/dist/providers/github-copilot-gateway.js +58 -0
  275. package/dist/providers/github-copilot.d.ts +60 -0
  276. package/dist/providers/github-copilot.js +320 -0
  277. package/dist/providers/google-thinking.d.ts +31 -0
  278. package/dist/providers/google-thinking.js +64 -0
  279. package/dist/providers/google-vertex-gateway.d.ts +23 -0
  280. package/dist/providers/google-vertex-gateway.js +49 -0
  281. package/dist/providers/google-vertex.d.ts +6 -0
  282. package/dist/providers/google-vertex.js +51 -0
  283. package/dist/providers/kimi-coding.d.ts +14 -0
  284. package/dist/providers/kimi-coding.js +80 -0
  285. package/dist/providers/model-ids.d.ts +53 -0
  286. package/dist/providers/model-ids.js +132 -0
  287. package/dist/providers/openai-codex.d.ts +114 -0
  288. package/dist/providers/openai-codex.js +427 -0
  289. package/dist/providers/provider-thinking.d.ts +23 -0
  290. package/dist/providers/provider-thinking.js +61 -0
  291. package/dist/providers/thinking-request.d.ts +14 -0
  292. package/dist/providers/thinking-request.js +87 -0
  293. package/dist/providers/xai.d.ts +33 -0
  294. package/dist/providers/xai.js +72 -0
  295. package/dist/schedules/index.d.ts +10 -0
  296. package/dist/schedules/index.js +6 -0
  297. package/dist/schedules/interval.d.ts +49 -0
  298. package/dist/schedules/interval.js +212 -0
  299. package/dist/schedules/prompt.d.ts +36 -0
  300. package/dist/schedules/prompt.js +36 -0
  301. package/dist/schedules/run-script.d.ts +8 -0
  302. package/dist/schedules/run-script.js +80 -0
  303. package/dist/schedules/scheduler.d.ts +101 -0
  304. package/dist/schedules/scheduler.js +167 -0
  305. package/dist/schedules/tools.d.ts +57 -0
  306. package/dist/schedules/tools.js +217 -0
  307. package/dist/schema.d.ts +499 -0
  308. package/dist/schema.js +131 -0
  309. package/dist/theme-palette.d.ts +17 -0
  310. package/dist/theme-palette.js +18 -0
  311. package/dist/thinking-catalog.d.ts +4 -0
  312. package/dist/thinking-catalog.js +13 -0
  313. package/dist/thinking.d.ts +37 -0
  314. package/dist/thinking.js +134 -0
  315. package/dist/tool-names.d.ts +77 -0
  316. package/dist/tool-names.js +53 -0
  317. package/dist/tools/index.d.ts +6 -0
  318. package/dist/tools/index.js +3 -0
  319. package/dist/tools/request-sandbox-access.d.ts +6 -0
  320. package/dist/tools/request-sandbox-access.js +80 -0
  321. package/dist/tools/utils.d.ts +20 -0
  322. package/dist/tools/utils.js +31 -0
  323. package/dist/tools/web-search.d.ts +116 -0
  324. package/dist/tools/web-search.js +158 -0
  325. package/dist/tools/workflows/create-workflow.d.ts +7 -0
  326. package/dist/tools/workflows/create-workflow.js +82 -0
  327. package/dist/tools/workflows/delete-workflow.d.ts +7 -0
  328. package/dist/tools/workflows/delete-workflow.js +18 -0
  329. package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
  330. package/dist/tools/workflows/ephemeral-memory.js +41 -0
  331. package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
  332. package/dist/tools/workflows/extract-json-schema.js +19 -0
  333. package/dist/tools/workflows/get-workflow.d.ts +11 -0
  334. package/dist/tools/workflows/get-workflow.js +31 -0
  335. package/dist/tools/workflows/list-available-agents.d.ts +8 -0
  336. package/dist/tools/workflows/list-available-agents.js +29 -0
  337. package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
  338. package/dist/tools/workflows/list-available-classifiers.js +53 -0
  339. package/dist/tools/workflows/list-available-tools.d.ts +9 -0
  340. package/dist/tools/workflows/list-available-tools.js +37 -0
  341. package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
  342. package/dist/tools/workflows/list-available-workflows.js +29 -0
  343. package/dist/tools/workflows/list-workflows.d.ts +9 -0
  344. package/dist/tools/workflows/list-workflows.js +30 -0
  345. package/dist/tools/workflows/run-workflow.d.ts +9 -0
  346. package/dist/tools/workflows/run-workflow.js +49 -0
  347. package/dist/tools/workflows/save-workflow.d.ts +1125 -0
  348. package/dist/tools/workflows/save-workflow.js +25 -0
  349. package/dist/tools/workflows/tool-ids.d.ts +16 -0
  350. package/dist/tools/workflows/tool-ids.js +17 -0
  351. package/dist/utils/binaries.d.ts +7 -0
  352. package/dist/utils/binaries.js +97 -0
  353. package/dist/utils/debug-log.d.ts +12 -0
  354. package/dist/utils/debug-log.js +56 -0
  355. package/dist/utils/discarding-scores-storage.d.ts +33 -0
  356. package/dist/utils/discarding-scores-storage.js +51 -0
  357. package/dist/utils/errors.d.ts +36 -0
  358. package/dist/utils/errors.js +215 -0
  359. package/dist/utils/gateway-sync.d.ts +26 -0
  360. package/dist/utils/gateway-sync.js +58 -0
  361. package/dist/utils/local-observability.d.ts +19 -0
  362. package/dist/utils/local-observability.js +54 -0
  363. package/dist/utils/maintenance-lock.d.ts +42 -0
  364. package/dist/utils/maintenance-lock.js +196 -0
  365. package/dist/utils/notification-dispatch.d.ts +74 -0
  366. package/dist/utils/notification-dispatch.js +128 -0
  367. package/dist/utils/open-url.d.ts +10 -0
  368. package/dist/utils/open-url.js +27 -0
  369. package/dist/utils/path-security.d.ts +2 -0
  370. package/dist/utils/path-security.js +7 -0
  371. package/dist/utils/plan-diff.d.ts +25 -0
  372. package/dist/utils/plan-diff.js +59 -0
  373. package/dist/utils/plans.d.ts +61 -0
  374. package/dist/utils/plans.js +120 -0
  375. package/dist/utils/project.d.ts +160 -0
  376. package/dist/utils/project.js +361 -0
  377. package/dist/utils/prune-cli.d.ts +24 -0
  378. package/dist/utils/prune-cli.js +124 -0
  379. package/dist/utils/signals-pubsub.d.ts +103 -0
  380. package/dist/utils/signals-pubsub.js +409 -0
  381. package/dist/utils/slash-command-loader.d.ts +52 -0
  382. package/dist/utils/slash-command-loader.js +139 -0
  383. package/dist/utils/slash-command-processor.d.ts +14 -0
  384. package/dist/utils/slash-command-processor.js +106 -0
  385. package/dist/utils/stdin-pipe.d.ts +33 -0
  386. package/dist/utils/stdin-pipe.js +93 -0
  387. package/dist/utils/storage-factory.d.ts +50 -0
  388. package/dist/utils/storage-factory.js +118 -0
  389. package/dist/utils/storage-maintenance.d.ts +121 -0
  390. package/dist/utils/storage-maintenance.js +352 -0
  391. package/dist/utils/thread-lock.d.ts +26 -0
  392. package/dist/utils/thread-lock.js +109 -0
  393. package/dist/utils/token-estimator.d.ts +3 -0
  394. package/dist/utils/token-estimator.js +19 -0
  395. package/dist/utils/update-check.d.ts +151 -0
  396. package/dist/utils/update-check.js +430 -0
  397. package/dist/utils/wake-session.d.ts +44 -0
  398. package/dist/utils/wake-session.js +83 -0
  399. package/dist/voice/stt-registry.d.ts +67 -0
  400. package/dist/voice/stt-registry.js +144 -0
  401. package/dist/voice/transcribe.d.ts +10 -0
  402. package/dist/voice/transcribe.js +75 -0
  403. package/dist/workflows/register-primitives.d.ts +52 -0
  404. package/dist/workflows/register-primitives.js +40 -0
  405. package/dist/workflows/service.d.ts +64 -0
  406. package/dist/workflows/service.js +50 -0
  407. package/package.json +117 -0
@@ -0,0 +1,805 @@
1
+ import { getAppDataDir } from "../utils/project.js";
2
+ import { anthropicOAuthProvider } from "./providers/anthropic.js";
3
+ import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
4
+ import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
5
+ import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
6
+ import { xaiOAuthProvider } from "./providers/xai.js";
7
+ import { dirname, join } from "path";
8
+ import { createHash } from "crypto";
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
10
+ // src/auth/storage.ts
11
+ /**
12
+ * Credential storage for API keys and OAuth tokens.
13
+ * Handles loading, saving, and refreshing credentials from auth.json.
14
+ */
15
+ /**
16
+ * API keys this process exported to environment variables, keyed by variable name.
17
+ * `previous` is the value the variable held before the first export, so removing the
18
+ * key can restore it. Module-level because `process.env` is shared by every instance.
19
+ */
20
+ const exportedApiKeys = /* @__PURE__ */ new Map();
21
+ function exportApiKey(envVar, provider, key) {
22
+ const exported = exportedApiKeys.get(envVar);
23
+ const previous = exported && process.env[envVar] === exported.key ? exported.previous : process.env[envVar];
24
+ exportedApiKeys.set(envVar, {
25
+ provider,
26
+ key,
27
+ previous
28
+ });
29
+ process.env[envVar] = key;
30
+ }
31
+ /**
32
+ * Best/default models for each OAuth provider.
33
+ * Used when auto-selecting a model after login.
34
+ */
35
+ const PROVIDER_DEFAULT_MODELS = {
36
+ anthropic: "anthropic/claude-fable-5",
37
+ "openai-codex": "openai/gpt-5.6-sol",
38
+ "github-copilot": "github-copilot/gpt-4.1",
39
+ "kimi-for-coding": "kimi-code-plan-cn/kimi-for-coding",
40
+ xai: "xai/grok-4.5"
41
+ };
42
+ const oauthProviderRegistry = /* @__PURE__ */ new Map([
43
+ [anthropicOAuthProvider.id, anthropicOAuthProvider],
44
+ [openaiCodexOAuthProvider.id, openaiCodexOAuthProvider],
45
+ [githubCopilotOAuthProvider.id, githubCopilotOAuthProvider],
46
+ [kimiCodingOAuthProvider.id, kimiCodingOAuthProvider],
47
+ [xaiOAuthProvider.id, xaiOAuthProvider]
48
+ ]);
49
+ /**
50
+ * Get an OAuth provider by ID
51
+ */
52
+ function getOAuthProvider(id) {
53
+ return oauthProviderRegistry.get(id);
54
+ }
55
+ /**
56
+ * Get all registered OAuth providers
57
+ */
58
+ function getOAuthProviders() {
59
+ return Array.from(oauthProviderRegistry.values());
60
+ }
61
+ /**
62
+ * Mint an account instance id: `${providerId}:${randomUUID()}`.
63
+ *
64
+ * Assigned once, when the account is created, and never derived from
65
+ * credentials. Deriving it from the refresh token (the pre-A13 scheme) looked
66
+ * stable but was not: `persistRefreshedCredential` keeps an entry's key while
67
+ * writing rotated tokens onto it, so every refresh left the id describing a
68
+ * credential the account no longer had — and re-adding that same subscription
69
+ * then failed to match its own entry and registered a second one for it.
70
+ */
71
+ function mintAccountId(providerId) {
72
+ return `${providerId}:${globalThis.crypto.randomUUID()}`;
73
+ }
74
+ /**
75
+ * The pre-A13 id scheme: `${providerId}:${sha256(refresh).slice(0,8)}`.
76
+ *
77
+ * No longer used to assign ids, but still needed to recognize registries
78
+ * written before A13 — both to match a re-authorized account onto its existing
79
+ * entry, and to recognize entries whose fields the A13 migration must backfill.
80
+ */
81
+ function legacyAccountIdFor(providerId, refreshToken) {
82
+ return `${providerId}:${createHash("sha256").update(refreshToken).digest("hex").slice(0, 8)}`;
83
+ }
84
+ /**
85
+ * Stable identity for the *subscription* behind an account, when the provider
86
+ * exposes one (an account id, an email — anything that survives a refresh and
87
+ * a re-authorization). Used to decide whether an added account is one we
88
+ * already have. Providers whose credentials carry no such identifier return
89
+ * undefined; for those, a re-authorization is indistinguishable from a new
90
+ * account without spending a request.
91
+ */
92
+ function providerIdentity(provider, creds) {
93
+ try {
94
+ const identity = provider?.getAccountIdentity?.(creds);
95
+ return typeof identity === "string" && identity.length > 0 ? identity : void 0;
96
+ } catch {
97
+ return;
98
+ }
99
+ }
100
+ function isOAuthAccountRecord(value) {
101
+ if (!value || typeof value !== "object") return false;
102
+ const v = value;
103
+ return v.type === "oauth-account" && typeof v.id === "string" && typeof v.label === "string" && typeof v.addedAt === "string" && typeof v.active === "boolean" && typeof v.refresh === "string" && typeof v.access === "string" && typeof v.expires === "number";
104
+ }
105
+ /** The credential fields of an account record — everything but registry identity. */
106
+ function credentialFieldsOf(record) {
107
+ const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, identity: _identity, ...creds } = record;
108
+ return creds;
109
+ }
110
+ /**
111
+ * Credential storage backed by a JSON file.
112
+ */
113
+ var AuthStorage = class {
114
+ authPath;
115
+ data = {};
116
+ refreshPromises = /* @__PURE__ */ new Map();
117
+ constructor(authPath = join(getAppDataDir(), "auth.json")) {
118
+ this.authPath = authPath;
119
+ this.reload();
120
+ }
121
+ /**
122
+ * Reload credentials from disk.
123
+ */
124
+ reload() {
125
+ if (!existsSync(this.authPath)) {
126
+ this.data = {};
127
+ return;
128
+ }
129
+ try {
130
+ this.data = JSON.parse(readFileSync(this.authPath, "utf-8"));
131
+ } catch {
132
+ this.data = {};
133
+ }
134
+ this.migrate();
135
+ }
136
+ /**
137
+ * Bring auth.json up to the multi-account registry format. Runs on every
138
+ * load; saves only when something actually changed.
139
+ *
140
+ * 1. A legacy OAuth slot with no registry gets one adopted active entry
141
+ * (the slot's tokens stay put — the entry mirrors them).
142
+ * 2. When the slot's refresh token differs from the active entry's, an
143
+ * external writer (older build, another worktree) owns the slot — the
144
+ * slot wins and its tokens are adopted onto the active entry.
145
+ * 3. A registry with no active entry (hand-edited) self-heals to its first
146
+ * entry; malformed `accounts:` values are skipped, never fatal.
147
+ * 4. A registry whose legacy slot disappeared (partial write, an external
148
+ * hand-edit) self-heals by mirroring the active entry's tokens back into
149
+ * the slot, so `isLoggedIn()`/`getOAuthCredential()` keep agreeing with
150
+ * `listAccounts()`. `remove()`/`logout()` clear the registry with the
151
+ * slot, so they never leave the shape this heals.
152
+ */
153
+ migrate() {
154
+ let changed = false;
155
+ for (const key of Object.keys(this.data)) {
156
+ const slot = this.data[key];
157
+ if (!slot || slot.type !== "oauth") continue;
158
+ const providerId = key;
159
+ const entries = this.accountEntries(providerId);
160
+ if (entries.length === 0) {
161
+ this.adoptSlot(providerId, slot);
162
+ changed = true;
163
+ continue;
164
+ }
165
+ const active = entries.find((entry) => entry.active);
166
+ if (!active) {
167
+ this.data[this.accountKeyFor(entries[0].id)] = {
168
+ ...entries[0],
169
+ active: true
170
+ };
171
+ changed = true;
172
+ continue;
173
+ }
174
+ if (active.refresh !== slot.refresh) {
175
+ const matching = entries.find((entry) => entry.id !== active.id && entry.refresh === slot.refresh);
176
+ if (matching) {
177
+ const { type: _t, ...slotCreds } = slot;
178
+ this.data[this.accountKeyFor(matching.id)] = {
179
+ ...matching,
180
+ ...slotCreds,
181
+ type: "oauth-account",
182
+ active: true
183
+ };
184
+ this.data[this.accountKeyFor(active.id)] = {
185
+ ...active,
186
+ active: false
187
+ };
188
+ changed = true;
189
+ } else {
190
+ const { type: _type, ...slotCreds } = slot;
191
+ this.data[this.accountKeyFor(active.id)] = {
192
+ ...active,
193
+ ...slotCreds,
194
+ type: "oauth-account"
195
+ };
196
+ changed = true;
197
+ }
198
+ }
199
+ }
200
+ const registeredProviders = /* @__PURE__ */ new Set();
201
+ for (const key of Object.keys(this.data)) {
202
+ if (!key.startsWith("accounts:")) continue;
203
+ const providerId = key.slice(9).split(":")[0];
204
+ if (providerId) registeredProviders.add(providerId);
205
+ }
206
+ for (const providerId of registeredProviders) {
207
+ if (this.data[providerId]?.type === "oauth") continue;
208
+ const entries = this.accountEntries(providerId);
209
+ if (entries.length === 0) continue;
210
+ let active = entries.find((entry) => entry.active);
211
+ if (!active) {
212
+ active = entries[0];
213
+ this.data[this.accountKeyFor(active.id)] = {
214
+ ...active,
215
+ active: true
216
+ };
217
+ }
218
+ this.data[providerId] = {
219
+ type: "oauth",
220
+ ...credentialFieldsOf(active)
221
+ };
222
+ changed = true;
223
+ }
224
+ for (const providerId of registeredProviders) {
225
+ const provider = getOAuthProvider(providerId);
226
+ if (!provider?.getAccountIdentity) continue;
227
+ for (const entry of this.accountEntries(providerId)) {
228
+ if (entry.identity) continue;
229
+ const identity = providerIdentity(provider, entry);
230
+ if (!identity) continue;
231
+ this.data[this.accountKeyFor(entry.id)] = {
232
+ ...entry,
233
+ identity
234
+ };
235
+ changed = true;
236
+ }
237
+ }
238
+ if (changed) this.save();
239
+ }
240
+ /**
241
+ * Save credentials to disk.
242
+ */
243
+ save() {
244
+ const dir = dirname(this.authPath);
245
+ if (!existsSync(dir)) mkdirSync(dir, {
246
+ recursive: true,
247
+ mode: 448
248
+ });
249
+ const tempPath = `${this.authPath}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;
250
+ try {
251
+ writeFileSync(tempPath, JSON.stringify(this.data, null, 2), {
252
+ encoding: "utf-8",
253
+ mode: 384
254
+ });
255
+ chmodSync(tempPath, 384);
256
+ renameSync(tempPath, this.authPath);
257
+ } finally {
258
+ rmSync(tempPath, { force: true });
259
+ }
260
+ }
261
+ /**
262
+ * Get credential for a provider. Registry entries (type 'oauth-account')
263
+ * live under `accounts:` keys and never surface here.
264
+ */
265
+ get(provider) {
266
+ const cred = this.data[provider];
267
+ return cred !== void 0 && cred.type !== "oauth-account" ? cred : void 0;
268
+ }
269
+ /**
270
+ * Set credential for a provider.
271
+ */
272
+ set(provider, credential) {
273
+ this.reload();
274
+ this.data[provider] = credential;
275
+ this.save();
276
+ }
277
+ /**
278
+ * Remove credential for a provider, including its account registry.
279
+ * Clearing only the slot would leave the registry behind, and the next
280
+ * load's migration would heal the slot back from it — resurrecting the
281
+ * provider the caller just signed out.
282
+ */
283
+ remove(provider) {
284
+ this.reload();
285
+ delete this.data[provider];
286
+ const prefix = this.accountPrefixFor(provider);
287
+ for (const key of Object.keys(this.data)) if (key.startsWith(prefix)) delete this.data[key];
288
+ this.save();
289
+ }
290
+ /**
291
+ * List all providers with credentials.
292
+ */
293
+ list() {
294
+ return Object.keys(this.data);
295
+ }
296
+ /**
297
+ * Check if credentials exist for a provider.
298
+ */
299
+ has(provider) {
300
+ return provider in this.data;
301
+ }
302
+ /**
303
+ * Check if logged in via OAuth for a provider.
304
+ */
305
+ isLoggedIn(provider) {
306
+ return this.data[provider]?.type === "oauth";
307
+ }
308
+ /**
309
+ * Check if a stored API key exists for a provider.
310
+ * Keys are stored under `apikey:<provider>` in auth.json.
311
+ */
312
+ hasStoredApiKey(provider) {
313
+ const cred = this.data[`apikey:${provider}`];
314
+ return cred?.type === "api_key" && cred.key.length > 0;
315
+ }
316
+ /**
317
+ * Get a stored API key for a provider, if any.
318
+ */
319
+ getStoredApiKey(provider) {
320
+ const cred = this.data[`apikey:${provider}`];
321
+ return cred?.type === "api_key" && cred.key.length > 0 ? cred.key : void 0;
322
+ }
323
+ /**
324
+ * Store an API key for a provider.
325
+ * Also sets the corresponding environment variable so model resolution can find it.
326
+ */
327
+ setStoredApiKey(provider, key, envVar) {
328
+ this.set(`apikey:${provider}`, {
329
+ type: "api_key",
330
+ key
331
+ });
332
+ if (envVar) exportApiKey(envVar, provider, key);
333
+ }
334
+ /**
335
+ * Remove a stored API key for a provider.
336
+ * Also undoes the environment variable export done by {@link setStoredApiKey} or
337
+ * {@link loadStoredApiKeysIntoEnv}: the variable gets back the value it had before
338
+ * (for example the key the process was started with), or is unset if it had none.
339
+ * A variable changed since the export is left alone.
340
+ */
341
+ removeStoredApiKey(provider) {
342
+ this.remove(`apikey:${provider}`);
343
+ for (const [envVar, exported] of exportedApiKeys) {
344
+ if (exported.provider !== provider) continue;
345
+ exportedApiKeys.delete(envVar);
346
+ if (process.env[envVar] !== exported.key) continue;
347
+ if (exported.previous === void 0) delete process.env[envVar];
348
+ else process.env[envVar] = exported.previous;
349
+ }
350
+ }
351
+ /**
352
+ * Load all stored API keys into process.env.
353
+ * Called at startup so model resolution can find stored keys.
354
+ * Only sets env vars that aren't already set (env vars take precedence).
355
+ */
356
+ loadStoredApiKeysIntoEnv(providerEnvVars) {
357
+ for (const [key, cred] of Object.entries(this.data)) {
358
+ if (!key.startsWith("apikey:") || cred.type !== "api_key" || !cred.key) continue;
359
+ const provider = key.substring(7);
360
+ const envVar = providerEnvVars[provider];
361
+ if (envVar && !process.env[envVar]) exportApiKey(envVar, provider, cred.key);
362
+ }
363
+ }
364
+ /**
365
+ * Login to an OAuth provider. Resolves to the registered account record.
366
+ * Pass `activate: false` to add the account without making it active (the
367
+ * first account for a provider is always activated — a provider with
368
+ * accounts must have an active one).
369
+ */
370
+ async login(providerId, callbacks, opts) {
371
+ const provider = getOAuthProvider(providerId);
372
+ if (!provider) throw new Error(`Unknown OAuth provider: ${providerId}`);
373
+ const credentials = await provider.login(callbacks);
374
+ return this.addAccount(providerId, credentials, opts);
375
+ }
376
+ /**
377
+ * Logout from a provider: remove the legacy slot and every registered account.
378
+ */
379
+ logout(provider) {
380
+ this.remove(provider);
381
+ }
382
+ accountPrefixFor(providerId) {
383
+ return `accounts:${providerId}:`;
384
+ }
385
+ accountKeyFor(id) {
386
+ return `accounts:${id}`;
387
+ }
388
+ /** Registry entries for a provider in JSON insertion order (malformed values skipped). */
389
+ accountEntries(providerId) {
390
+ const prefix = this.accountPrefixFor(providerId);
391
+ const out = [];
392
+ for (const [key, value] of Object.entries(this.data)) if (key.startsWith(prefix) && isOAuthAccountRecord(value)) out.push(value);
393
+ return out;
394
+ }
395
+ /** Adopt a legacy slot credential as the registry's first active entry. */
396
+ adoptSlot(providerId, slot) {
397
+ const id = mintAccountId(providerId);
398
+ const provider = getOAuthProvider(providerId);
399
+ const identity = providerIdentity(provider, slot);
400
+ const record = {
401
+ ...slot,
402
+ type: "oauth-account",
403
+ id,
404
+ ...identity ? { identity } : {},
405
+ label: `${provider?.name ?? providerId} account 1`,
406
+ addedAt: (/* @__PURE__ */ new Date()).toISOString(),
407
+ active: true
408
+ };
409
+ this.data[this.accountKeyFor(id)] = record;
410
+ return record;
411
+ }
412
+ /**
413
+ * Registered OAuth accounts for a provider, in insertion order. Copies —
414
+ * callers cannot corrupt unsaved storage state by mutating a record.
415
+ */
416
+ listAccounts(providerId) {
417
+ return this.accountEntries(providerId).map((entry) => ({ ...entry }));
418
+ }
419
+ /**
420
+ * The provider's active registry entry, if a registry exists. A copy.
421
+ */
422
+ getActiveAccount(providerId) {
423
+ const active = this.accountEntries(providerId).find((entry) => entry.active);
424
+ return active ? { ...active } : void 0;
425
+ }
426
+ /**
427
+ * Register OAuth credentials as an account for a provider, making it active
428
+ * unless `activate: false` is passed.
429
+ *
430
+ * With `replaceAccountId` (re-authentication of a picked account), the
431
+ * target entry's tokens are replaced in place — id re-keyed to the new
432
+ * refresh-token hash, label/position/addedAt preserved — because providers
433
+ * rotate refresh tokens per authorization, so the picked account's old id
434
+ * never matches the new token hash. Re-authentication keeps the target's
435
+ * active state: an inactive account stays inactive and the currently active
436
+ * account keeps the legacy slot. Otherwise, when the new credentials
437
+ * hash to an existing entry's id (same refresh token), that entry is
438
+ * updated in place; a genuinely new account is appended and activated.
439
+ *
440
+ * `activate: false` only applies to the plain add path: the new/updated entry
441
+ * keeps the active state it had, and the previously active account stays
442
+ * active. The first account of a provider is activated regardless.
443
+ */
444
+ async addAccount(providerId, creds, opts) {
445
+ this.reload();
446
+ const entries = this.accountEntries(providerId);
447
+ if (opts?.replaceAccountId) {
448
+ const target = entries.find((entry) => entry.id === opts.replaceAccountId);
449
+ if (!target) throw new Error(`No account ${opts.replaceAccountId} for provider ${providerId}`);
450
+ const identity = providerIdentity(getOAuthProvider(providerId), creds) ?? target.identity;
451
+ const legacyId = legacyAccountIdFor(providerId, creds.refresh);
452
+ const collided = entries.find((entry) => entry.id !== target.id && (identity !== void 0 && entry.identity === identity || entry.id === legacyId || entry.refresh === creds.refresh));
453
+ const replacement = {
454
+ ...target,
455
+ ...collided ? credentialFieldsOf(collided) : {},
456
+ ...creds,
457
+ type: "oauth-account",
458
+ ...identity ? { identity } : {},
459
+ label: opts.label ?? target.label
460
+ };
461
+ const rebuilt = {};
462
+ for (const [key, value] of Object.entries(this.data)) if (key === this.accountKeyFor(target.id)) rebuilt[key] = collided?.active ? {
463
+ ...replacement,
464
+ active: true
465
+ } : replacement;
466
+ else if (collided && key === this.accountKeyFor(collided.id)) continue;
467
+ else rebuilt[key] = value;
468
+ this.data = rebuilt;
469
+ if (target.active === true || collided?.active === true || entries.some((entry) => entry.active && entry.id !== target.id) === false) {
470
+ const activated = this.activateInMemory(providerId, target.id);
471
+ if (!activated) throw new Error(`Failed to activate account ${target.id} for provider ${providerId}`);
472
+ this.save();
473
+ return activated;
474
+ }
475
+ const replacementEntry = this.accountEntries(providerId).find((entry) => entry.id === target.id);
476
+ if (!replacementEntry) throw new Error(`Failed to store account ${target.id} for provider ${providerId}`);
477
+ this.save();
478
+ return replacementEntry;
479
+ }
480
+ const provider = getOAuthProvider(providerId);
481
+ const identity = providerIdentity(provider, creds);
482
+ const label = opts?.label ?? await provider?.getAccountLabel?.(creds) ?? null;
483
+ this.reload();
484
+ const freshEntries = this.accountEntries(providerId);
485
+ const legacyId = legacyAccountIdFor(providerId, creds.refresh);
486
+ const existing = (identity ? freshEntries.find((entry) => entry.identity === identity) : void 0) ?? freshEntries.find((entry) => entry.id === legacyId) ?? freshEntries.find((entry) => entry.refresh === creds.refresh);
487
+ const id = existing?.id ?? mintAccountId(providerId);
488
+ if (existing) this.data[this.accountKeyFor(id)] = {
489
+ ...existing,
490
+ ...creds,
491
+ type: "oauth-account",
492
+ id,
493
+ ...identity ? { identity } : {},
494
+ active: existing.active
495
+ };
496
+ else {
497
+ const resolvedLabel = label ?? `${provider?.name ?? providerId} account ${freshEntries.length + 1}`;
498
+ this.data[this.accountKeyFor(id)] = {
499
+ type: "oauth-account",
500
+ id,
501
+ ...identity ? { identity } : {},
502
+ label: resolvedLabel,
503
+ addedAt: (/* @__PURE__ */ new Date()).toISOString(),
504
+ active: false,
505
+ ...creds
506
+ };
507
+ }
508
+ if (opts?.activate === false && freshEntries.length > 0 && !existing?.active) {
509
+ this.save();
510
+ return { ...this.data[this.accountKeyFor(id)] };
511
+ }
512
+ const activated = this.activateInMemory(providerId, id);
513
+ if (!activated) throw new Error(`Failed to activate account ${id} for provider ${providerId}`);
514
+ this.save();
515
+ return activated;
516
+ }
517
+ /**
518
+ * Activate an account: move the active tokens out of the legacy slot back
519
+ * into the previously active entry, and the target's tokens into the slot
520
+ * (never copy — one home per token set). With no `instanceId`, rotate to
521
+ * the next entry in insertion order, wrapping once to the front; returns
522
+ * undefined when there is no other entry to rotate to.
523
+ */
524
+ activateAccount(providerId, instanceId) {
525
+ this.reload();
526
+ const activated = this.activateInMemory(providerId, instanceId);
527
+ if (activated) this.save();
528
+ return activated;
529
+ }
530
+ /**
531
+ * Activate an account in memory only — the caller owns reload/save. Move the
532
+ * active tokens out of the legacy slot back into the previously active
533
+ * entry, and the target's tokens into the slot (never copy — one home per
534
+ * token set). With no `instanceId`, rotate to the next entry in insertion
535
+ * order, wrapping once to the front; returns undefined when there is no
536
+ * other entry to rotate to.
537
+ */
538
+ activateInMemory(providerId, instanceId) {
539
+ const entries = this.accountEntries(providerId);
540
+ if (entries.length === 0) return void 0;
541
+ let target;
542
+ if (instanceId !== void 0) {
543
+ target = entries.find((entry) => entry.id === instanceId);
544
+ if (!target) return void 0;
545
+ } else {
546
+ if (entries.length <= 1) return void 0;
547
+ const currentIdx = entries.findIndex((entry) => entry.active);
548
+ target = (currentIdx >= 0 ? [...entries.slice(currentIdx + 1), ...entries.slice(0, currentIdx)] : [...entries])[0];
549
+ }
550
+ if (!target) return void 0;
551
+ const slot = this.data[providerId];
552
+ const current = entries.find((entry) => entry.active && entry.id !== target.id);
553
+ if (current && slot?.type === "oauth") {
554
+ const { type: _type, ...slotCreds } = slot;
555
+ this.data[this.accountKeyFor(current.id)] = {
556
+ ...current,
557
+ ...slotCreds,
558
+ type: "oauth-account",
559
+ active: false
560
+ };
561
+ }
562
+ this.data[providerId] = {
563
+ ...credentialFieldsOf(target),
564
+ type: "oauth"
565
+ };
566
+ this.data[this.accountKeyFor(target.id)] = {
567
+ ...target,
568
+ active: true
569
+ };
570
+ for (const entry of entries) {
571
+ if (entry.id === target.id || entry.id === current?.id) continue;
572
+ if (entry.active) this.data[this.accountKeyFor(entry.id)] = {
573
+ ...entry,
574
+ active: false
575
+ };
576
+ }
577
+ return {
578
+ ...target,
579
+ active: true
580
+ };
581
+ }
582
+ /**
583
+ * Remove an account from the registry. If it was active, the next entry in
584
+ * insertion order is activated; when it was the last one, the legacy slot
585
+ * is removed too (full sign-out for that provider).
586
+ */
587
+ removeAccount(providerId, instanceId) {
588
+ this.reload();
589
+ const entries = this.accountEntries(providerId);
590
+ const target = entries.find((entry) => entry.id === instanceId);
591
+ if (!target) return;
592
+ const wasActive = target.active;
593
+ delete this.data[this.accountKeyFor(instanceId)];
594
+ if (wasActive) {
595
+ const next = entries[entries.indexOf(target) + 1] ?? entries.find((entry) => entry.id !== instanceId);
596
+ if (next) {
597
+ this.data[providerId] = {
598
+ type: "oauth",
599
+ ...credentialFieldsOf(next)
600
+ };
601
+ this.data[this.accountKeyFor(next.id)] = {
602
+ ...next,
603
+ active: true
604
+ };
605
+ for (const entry of entries) {
606
+ if (entry.id === next.id || entry.id === instanceId) continue;
607
+ if (entry.active) this.data[this.accountKeyFor(entry.id)] = {
608
+ ...entry,
609
+ active: false
610
+ };
611
+ }
612
+ } else delete this.data[providerId];
613
+ }
614
+ this.save();
615
+ }
616
+ /**
617
+ * Rename an account's label.
618
+ */
619
+ renameAccount(providerId, instanceId, label) {
620
+ this.reload();
621
+ const key = this.accountKeyFor(instanceId);
622
+ const entry = this.data[key];
623
+ if (!isOAuthAccountRecord(entry)) return;
624
+ this.data[key] = {
625
+ ...entry,
626
+ label
627
+ };
628
+ this.save();
629
+ }
630
+ /**
631
+ * Persist refreshed credentials for the account that initiated the refresh.
632
+ * The legacy slot is updated only if that account is still active when the
633
+ * refresh completes; otherwise a delayed refresh could overwrite a newer
634
+ * activation.
635
+ */
636
+ persistRefreshedCredential(providerId, instanceId, creds) {
637
+ this.reload();
638
+ if (instanceId) {
639
+ const key = this.accountKeyFor(instanceId);
640
+ const entry = this.data[key];
641
+ if (!isOAuthAccountRecord(entry)) return;
642
+ this.data[key] = {
643
+ ...entry,
644
+ ...creds,
645
+ type: "oauth-account"
646
+ };
647
+ if (entry.active) {
648
+ const slot = this.data[providerId];
649
+ this.data[providerId] = slot?.type === "oauth" ? {
650
+ ...slot,
651
+ ...creds,
652
+ type: "oauth"
653
+ } : {
654
+ type: "oauth",
655
+ ...creds
656
+ };
657
+ }
658
+ } else {
659
+ const slot = this.data[providerId];
660
+ this.data[providerId] = slot?.type === "oauth" ? {
661
+ ...slot,
662
+ ...creds,
663
+ type: "oauth"
664
+ } : {
665
+ type: "oauth",
666
+ ...creds
667
+ };
668
+ }
669
+ this.save();
670
+ }
671
+ /**
672
+ * Refresh one account instance through the per-instance dedupe map. Used
673
+ * for sibling refreshes during the rotation walk, so a concurrent
674
+ * `getApiKey` that reloads storage mid-walk (after the candidate was
675
+ * activated but before its refresh resolves) joins the same refresh
676
+ * instead of double-spending a single-use refresh token.
677
+ */
678
+ async refreshInstance(providerId, instanceId, creds) {
679
+ const provider = getOAuthProvider(providerId);
680
+ if (!provider) return void 0;
681
+ const refreshKey = `${providerId}:${instanceId}`;
682
+ const pending = this.refreshPromises.get(refreshKey);
683
+ if (pending) return pending;
684
+ const refresh = (async () => {
685
+ try {
686
+ const fresh = await provider.refreshToken(creds);
687
+ this.persistRefreshedCredential(providerId, instanceId, fresh);
688
+ return fresh;
689
+ } catch {
690
+ return;
691
+ }
692
+ })();
693
+ this.refreshPromises.set(refreshKey, refresh);
694
+ try {
695
+ return await refresh;
696
+ } finally {
697
+ this.refreshPromises.delete(refreshKey);
698
+ }
699
+ }
700
+ /**
701
+ * Get a ready-to-use OAuth credential snapshot, auto-refreshing if needed.
702
+ * A failed refresh leaves the active account unchanged and returns undefined;
703
+ * the account-rotation processor owns switching so it can persist a visible
704
+ * account-switch notice with the request that triggered the change.
705
+ */
706
+ async getOAuthCredential(providerId, accountInstanceId) {
707
+ this.reload();
708
+ const activeEntry = this.getActiveAccount(providerId);
709
+ const selectedEntry = accountInstanceId ? this.accountEntries(providerId).find((entry) => entry.id === accountInstanceId) : activeEntry;
710
+ const slot = this.data[providerId];
711
+ let credential;
712
+ if (selectedEntry) {
713
+ const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...accountCredential } = selectedEntry;
714
+ credential = accountCredential;
715
+ if (selectedEntry.active && slot?.type === "oauth" && slot.refresh === selectedEntry.refresh) {
716
+ const { type: _slotType, ...slotCredential } = slot;
717
+ credential = {
718
+ ...credential,
719
+ ...slotCredential
720
+ };
721
+ }
722
+ } else if (!accountInstanceId && slot?.type === "oauth") credential = slot;
723
+ if (!credential) return void 0;
724
+ const provider = getOAuthProvider(providerId);
725
+ if (!provider) return void 0;
726
+ const selectedInstanceId = selectedEntry?.id;
727
+ const toSnapshot = (credentials) => ({
728
+ type: "oauth",
729
+ ...credentials,
730
+ accountInstanceId: selectedInstanceId
731
+ });
732
+ if (Date.now() < credential.expires) return toSnapshot(credential);
733
+ if (selectedInstanceId) {
734
+ const refreshed = await this.refreshInstance(providerId, selectedInstanceId, credential);
735
+ return refreshed ? toSnapshot(refreshed) : void 0;
736
+ }
737
+ const pendingRefresh = this.refreshPromises.get(providerId);
738
+ const refresh = pendingRefresh ?? (async () => {
739
+ try {
740
+ const fresh = await provider.refreshToken(credential);
741
+ this.persistRefreshedCredential(providerId, void 0, fresh);
742
+ return fresh;
743
+ } catch {
744
+ return;
745
+ }
746
+ })();
747
+ if (!pendingRefresh) this.refreshPromises.set(providerId, refresh);
748
+ try {
749
+ const refreshed = await refresh;
750
+ return refreshed ? toSnapshot(refreshed) : void 0;
751
+ } finally {
752
+ if (!pendingRefresh) this.refreshPromises.delete(providerId);
753
+ }
754
+ }
755
+ /** Get API key for a provider, refreshing OAuth tokens if needed. */
756
+ async getApiKey(providerId, accountInstanceId) {
757
+ this.reload();
758
+ const cred = this.data[providerId];
759
+ if (accountInstanceId === void 0 && cred?.type === "api_key") return cred.key;
760
+ const oauth = await this.getOAuthCredential(providerId, accountInstanceId);
761
+ const provider = oauth ? getOAuthProvider(providerId) : void 0;
762
+ return oauth && provider ? provider.getApiKey(oauth) : void 0;
763
+ }
764
+ /**
765
+ * Force one refresh of the active OAuth account's tokens, regardless of
766
+ * expiry. The account-rotation error processor calls this when a provider
767
+ * rejects a not-yet-expired token (401/403) — server-side clock skew and
768
+ * refresh-token races surface that way. Returns the fresh access token, or
769
+ * undefined when the refresh fails or there is no OAuth credential.
770
+ * Shares the per-instance refresh dedupe with `getApiKey`.
771
+ */
772
+ async forceRefreshActiveAccount(providerId, accountInstanceId) {
773
+ this.reload();
774
+ const activeEntry = this.getActiveAccount(providerId);
775
+ const selectedEntry = accountInstanceId ? this.accountEntries(providerId).find((entry) => entry.id === accountInstanceId) : activeEntry;
776
+ const slot = this.get(providerId);
777
+ let cred;
778
+ if (selectedEntry) {
779
+ const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...accountCredential } = selectedEntry;
780
+ cred = accountCredential;
781
+ } else if (!accountInstanceId && slot?.type === "oauth") cred = slot;
782
+ if (!cred) return void 0;
783
+ const provider = getOAuthProvider(providerId);
784
+ if (!provider) return void 0;
785
+ const refreshKey = selectedEntry ? `${providerId}:${selectedEntry.id}` : providerId;
786
+ const pending = this.refreshPromises.get(refreshKey);
787
+ const refresh = pending ?? (async () => {
788
+ try {
789
+ const fresh = await provider.refreshToken(cred);
790
+ this.persistRefreshedCredential(providerId, selectedEntry?.id, fresh);
791
+ return fresh;
792
+ } catch {
793
+ return;
794
+ }
795
+ })();
796
+ if (!pending) this.refreshPromises.set(refreshKey, refresh);
797
+ try {
798
+ const creds = await refresh;
799
+ return creds ? provider.getApiKey(creds) : void 0;
800
+ } finally {
801
+ if (!pending) this.refreshPromises.delete(refreshKey);
802
+ }
803
+ }
804
+ };
805
+ export { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders };