@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,662 @@
1
+ import { resolveCredentialStore } from "../agents/credential-resolver.js";
2
+ import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
3
+ import { findRouteModelIndex, getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
4
+ import { isThinkingLevelSetting } from "../thinking.js";
5
+ import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
6
+ import { ProviderAuthRequiredError } from "./provider-auth-error.js";
7
+ import { getOAuthProviders } from "./storage.js";
8
+ import { TripWire } from "@mastra/core/agent";
9
+ import { classifyProviderError } from "@mastra/core/error";
10
+ // src/auth/account-rotation-processor.ts
11
+ /**
12
+ * Error-driven rotation across a provider's OAuth account registry.
13
+ *
14
+ * When the active account cannot serve a request (rate limit, quota
15
+ * exhaustion, dead token, persistent outage), the next account in insertion
16
+ * order is selected for the request and the request retried. OAuth fetch
17
+ * wrappers read that request-scoped selection on every HTTP attempt, so
18
+ * concurrent runs can't swap each other's credentials. Every switch is
19
+ * persisted as a non-transient `data-mastracode-account-switch` part so it
20
+ * shows in the transcript and survives history reload.
21
+ *
22
+ * Two classes, two lanes — the split is load-bearing. The processor runner
23
+ * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when
24
+ * running `processAPIError`, so a processor registered in the input lane that
25
+ * also implemented `processAPIError` would run BEFORE
26
+ * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries
27
+ * had a chance. `AccountRotationProcessor` therefore implements
28
+ * `processAPIError` only and is registered in `errorProcessors` after
29
+ * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements
30
+ * `processInput` only and is registered in `inputProcessors`.
31
+ */
32
+ const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
33
+ /** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */
34
+ const KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map((provider) => provider.id));
35
+ /** Hostname suffixes → provider ids, for `APICallError.url`. */
36
+ const PROVIDER_HOST_PATTERNS = [
37
+ [/(^|\.)api\.anthropic\.com$/i, "anthropic"],
38
+ [/(^|\.)api\.kimi\.com$/i, "kimi-for-coding"],
39
+ [/(^|\.)api\.x\.ai$/i, "xai"],
40
+ [/(^|\.)chatgpt\.com$/i, "openai-codex"],
41
+ [/(^|\.)backend-api\.codex\.ai$/i, "openai-codex"],
42
+ [/(^|\.)githubcopilot\.com$/i, "github-copilot"],
43
+ [/(^|\.)api\.github\.com$/i, "github-copilot"]
44
+ ];
45
+ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
46
+ "ECONNRESET",
47
+ "EPIPE",
48
+ "ECONNREFUSED",
49
+ "ENOTFOUND",
50
+ "ETIMEDOUT",
51
+ "EAI_AGAIN",
52
+ "UND_ERR_CONNECT_TIMEOUT",
53
+ "UND_ERR_SOCKET"
54
+ ]);
55
+ const NETWORK_MESSAGE_PATTERN = /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;
56
+ const MAX_CAUSE_DEPTH = 4;
57
+ /** Persisted data-part type for a model-route hop. */
58
+ const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
59
+ /** Session-state key set when account rotation advances the model route. */
60
+ const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
61
+ /**
62
+ * Same-account retries for a stream the provider cut after accepting the
63
+ * request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
64
+ * so the budget is small. This is the whole budget: Mastra Code's
65
+ * `StreamErrorRetryProcessor` leaves these errors to this processor.
66
+ */
67
+ const MAX_STREAM_CUT_RETRIES = 2;
68
+ const ROTATION_BY_PROVIDER_KIND = {
69
+ auth: {
70
+ kind: "rotate",
71
+ reason: "auth-failed"
72
+ },
73
+ quota: {
74
+ kind: "rotate",
75
+ reason: "quota-exhausted"
76
+ },
77
+ rate_limited: {
78
+ kind: "rotate",
79
+ reason: "rate-limit"
80
+ },
81
+ unavailable: { kind: "hop" }
82
+ };
83
+ function rotationFromStatus(status) {
84
+ if (status === 429) return {
85
+ kind: "rotate",
86
+ reason: "rate-limit"
87
+ };
88
+ if (status === 402) return {
89
+ kind: "rotate",
90
+ reason: "quota-exhausted"
91
+ };
92
+ if (status === 401 || status === 403) return {
93
+ kind: "rotate",
94
+ reason: "auth-failed"
95
+ };
96
+ if (status !== void 0 && status >= 500 && status < 600) return { kind: "hop" };
97
+ }
98
+ function isErrorWithCode(error) {
99
+ return typeof error === "object" && error !== null && "code" in error;
100
+ }
101
+ function readErrorStatus(error) {
102
+ let current = error;
103
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
104
+ if (typeof current !== "object") break;
105
+ const { statusCode, status } = current;
106
+ if (typeof statusCode === "number") return statusCode;
107
+ if (typeof status === "number") return status;
108
+ current = current.cause;
109
+ }
110
+ }
111
+ function isProviderAuthRequiredError(error) {
112
+ let current = error;
113
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
114
+ if (current instanceof ProviderAuthRequiredError || current instanceof Error && current.name === "ProviderAuthRequiredError") return true;
115
+ if (typeof current !== "object") break;
116
+ current = current.cause;
117
+ }
118
+ return false;
119
+ }
120
+ function isNetworkErrorLike(error) {
121
+ let current = error;
122
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
123
+ if (isErrorWithCode(current) && typeof current.code === "string" && NETWORK_ERROR_CODES.has(current.code.toUpperCase())) return true;
124
+ if (current instanceof Error) {
125
+ if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;
126
+ current = current.cause;
127
+ } else if (typeof current === "object") current = current.cause;
128
+ else break;
129
+ }
130
+ return false;
131
+ }
132
+ /** The code the ChatGPT Codex backend puts on the error frame it sends when it ends a stream at 900 s. */
133
+ const STREAM_DURATION_LIMIT_CODE = "request_timeout";
134
+ function asRecord(value) {
135
+ return typeof value === "object" && value !== null ? value : void 0;
136
+ }
137
+ /** The `error.code` of a stream error frame: the raw frame, or the frame `@ai-sdk/openai` keeps as `data`. */
138
+ function streamErrorFrameCode(value) {
139
+ const data = asRecord(value.data);
140
+ return asRecord((value.type === "error" ? value : data?.type === "error" ? data : void 0)?.error)?.code;
141
+ }
142
+ /**
143
+ * Whether the provider accepted the request and then the response stream died:
144
+ * the AI SDK reports a body that fails after a 2xx response as
145
+ * "Failed to process successful response" with the 2xx status, and the ChatGPT
146
+ * Codex backend ends streams at 900 s, sometimes with a `request_timeout` error
147
+ * frame first. Either way the account and the provider answered, so this is
148
+ * not an outage, and another account would be cut the same way.
149
+ *
150
+ * `@ai-sdk/openai` raises that frame with `code: 'request_timeout'` and a
151
+ * derived `statusCode: 504`, so callers must check this before any 5xx rule.
152
+ * Mastra Code's transient retry matchers call it first so that account
153
+ * rotation is the only processor that retries these errors.
154
+ */
155
+ function isStreamCutAfterResponse(error) {
156
+ let current = error;
157
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
158
+ const record = asRecord(current);
159
+ if (!record) break;
160
+ const { statusCode, status, code } = record;
161
+ const httpStatus = typeof statusCode === "number" ? statusCode : status;
162
+ if (typeof httpStatus === "number" && httpStatus >= 200 && httpStatus < 300) return true;
163
+ if (code === STREAM_DURATION_LIMIT_CODE || streamErrorFrameCode(record) === STREAM_DURATION_LIMIT_CODE) return true;
164
+ current = record.cause;
165
+ }
166
+ return false;
167
+ }
168
+ /**
169
+ * The locked Q7 taxonomy. Rate limits and exhausted quotas rotate immediately
170
+ * (429 is not covered by any transient matcher, so it arrives here on first
171
+ * occurrence); auth failures and `ProviderAuthRequiredError` rotate after one
172
+ * forced refresh; 5xx/network hop only when the transient retry budget is
173
+ * already spent (they reach this processor because `StreamErrorRetryProcessor`
174
+ * declined); everything else never touches the registry.
175
+ */
176
+ function classifyRotationError(error) {
177
+ if (isProviderAuthRequiredError(error)) return {
178
+ kind: "rotate",
179
+ reason: "auth-failed"
180
+ };
181
+ if (isStreamCutAfterResponse(error)) return { kind: "stream-cut" };
182
+ const status = readErrorStatus(error);
183
+ const byStatus = rotationFromStatus(status);
184
+ if (byStatus) return byStatus;
185
+ return (status === void 0 || status === 400 ? ROTATION_BY_PROVIDER_KIND[classifyProviderError(error)] : void 0) ?? (isNetworkErrorLike(error) ? { kind: "hop" } : { kind: "never" });
186
+ }
187
+ /** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */
188
+ function providerFromModelId(modelId) {
189
+ const segments = normalizeLegacyModelId(modelId).replace(/^mastracode\//, "").split("/");
190
+ const providerId = segments[0] ? getCredentialProviderId(segments[0]) : void 0;
191
+ return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : void 0;
192
+ }
193
+ function providerFromHost(hostname) {
194
+ for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) if (pattern.test(hostname)) return providerId;
195
+ }
196
+ /**
197
+ * Identify the provider an error came from: the request URL's hostname
198
+ * (`APICallError.url`, cause chain included), falling back to the router
199
+ * model id. Unknown → undefined (caller treats as never-rotate).
200
+ */
201
+ function providerFromError(error) {
202
+ const causeChain = [];
203
+ let current = error;
204
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
205
+ if (typeof current !== "object") break;
206
+ causeChain.push(current);
207
+ current = current.cause;
208
+ }
209
+ for (const item of causeChain) {
210
+ const urls = [
211
+ item.url,
212
+ item.requestURL,
213
+ item.requestUrl
214
+ ];
215
+ for (const url of urls) {
216
+ if (typeof url !== "string") continue;
217
+ try {
218
+ const providerId = providerFromHost(new URL(url).hostname);
219
+ if (providerId) return providerId;
220
+ } catch {}
221
+ }
222
+ }
223
+ for (const item of causeChain) {
224
+ const modelId = item.modelId;
225
+ if (typeof modelId !== "string") continue;
226
+ const providerId = providerFromModelId(modelId);
227
+ if (providerId) return providerId;
228
+ }
229
+ }
230
+ function getTriedInstances(state) {
231
+ const existing = state.triedInstances;
232
+ if (existing instanceof Set) return existing;
233
+ const created = /* @__PURE__ */ new Set();
234
+ state.triedInstances = created;
235
+ return created;
236
+ }
237
+ function getForcedRefreshInstances(state) {
238
+ const existing = state.forcedAuthRefresh;
239
+ if (existing instanceof Set) return existing;
240
+ const created = /* @__PURE__ */ new Set();
241
+ state.forcedAuthRefresh = created;
242
+ return created;
243
+ }
244
+ /** Friendly names for the part/notice copy (display only — never auth data). */
245
+ const PROVIDER_DISPLAY_NAMES = {
246
+ anthropic: "Anthropic",
247
+ "kimi-for-coding": "Kimi",
248
+ "openai-codex": "Codex",
249
+ "github-copilot": "GitHub Copilot",
250
+ xai: "xAI"
251
+ };
252
+ const REASON_TEXT = {
253
+ "rate-limit": "rate limit",
254
+ "quota-exhausted": "quota exhausted",
255
+ "auth-failed": "auth failed",
256
+ "pool-exhausted": "pool exhausted",
257
+ "persistent-outage": "persistent outage",
258
+ "preferred-routing": "subscription routing"
259
+ };
260
+ /** Validates untrusted `reason` values (e.g. persisted message parts). */
261
+ function isAccountSwitchReason(value) {
262
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(REASON_TEXT, value);
263
+ }
264
+ /**
265
+ * One-line transcript copy for a switch part. Shared by the live `info`
266
+ * controller event (the TUI shows controller `info` events as transcript
267
+ * lines, and no message event carries data parts mid-run) and by the TUI's
268
+ * history rendering of the persisted part — one formatter, identical text.
269
+ */
270
+ function accountSwitchNoticeText(data) {
271
+ const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;
272
+ const reason = REASON_TEXT[data.reason];
273
+ if (data.to === null) {
274
+ if (data.exclusive) return `Pinned ${provider} account unavailable (${reason})`;
275
+ return `All ${provider} accounts unavailable (${reason})`;
276
+ }
277
+ return `Switched ${provider} account: ${data.from?.label ?? "unknown"} → ${data.to.label} (${reason})`;
278
+ }
279
+ /** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
280
+ function modelFallbackNoticeText(data) {
281
+ const reason = REASON_TEXT[data.reason] ?? data.reason;
282
+ return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;
283
+ }
284
+ /**
285
+ * Whether a persisted model-fallback reason is one this build understands.
286
+ * `REASON_TEXT` also covers the account-switch reasons, so the notice text
287
+ * alone would happily render a foreign value such as `rate-limit` as a
288
+ * model-fallback reason; history parsed from another build's part must be
289
+ * rejected instead.
290
+ */
291
+ function isModelFallbackReason(value) {
292
+ return value === "pool-exhausted" || value === "persistent-outage";
293
+ }
294
+ async function emitAccountSwitchPart(args, data) {
295
+ await args.writer?.custom({
296
+ type: ACCOUNT_SWITCH_PART_TYPE,
297
+ data
298
+ });
299
+ (args.requestContext?.get("controller"))?.emitEvent?.({
300
+ type: "info",
301
+ message: accountSwitchNoticeText(data)
302
+ });
303
+ }
304
+ /**
305
+ * Provider of the model the controller session is currently running — the
306
+ * fallback identification path for errors that carry neither a request URL
307
+ * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper
308
+ * before any HTTP request exists).
309
+ */
310
+ function providerFromSession(args) {
311
+ const modelId = (args.requestContext?.get("controller"))?.session?.modelId;
312
+ return typeof modelId === "string" ? providerFromModelId(modelId) : void 0;
313
+ }
314
+ function getRoutingController(args) {
315
+ return args.requestContext?.get("controller");
316
+ }
317
+ /** A targeted route is exclusive; an entry without accountId uses automatic pool rotation. */
318
+ function getRouteTargetAccountId(route) {
319
+ return route?.accountId;
320
+ }
321
+ function getRequestActiveAccount(args, store, providerId) {
322
+ if (isRequestAccountRoutingExhausted(args.requestContext, providerId)) return void 0;
323
+ const selectedId = getRequestAccountSelection(args.requestContext, providerId);
324
+ if (selectedId) return store.listAccounts?.(providerId).find((account) => account.id === selectedId);
325
+ return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find((account) => account.active);
326
+ }
327
+ function resolveAccountRoute(args, explicit) {
328
+ const controller = getRoutingController(args);
329
+ const state = controller?.getState?.();
330
+ const pending = state?.mastracodePendingModelFallback;
331
+ const pendingMatchesThread = pending && typeof pending.toEntryId === "string" && typeof pending.toModelId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId);
332
+ const routeEntries = Array.isArray((state?.modelRoute)?.entries) ? (state?.modelRoute).entries ?? [] : [];
333
+ const entry = explicit ? explicit : pendingMatchesThread ? routeEntries.find((candidate) => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId) : routeEntries[findRouteModelIndex(routeEntries, controller?.session?.modelId)];
334
+ if (!entry || typeof entry.id !== "string" || typeof entry.modelId !== "string") return null;
335
+ const providerId = providerFromModelId(entry.modelId);
336
+ if (!providerId) return null;
337
+ return {
338
+ entryId: entry.id,
339
+ modelId: entry.modelId,
340
+ providerId,
341
+ ...typeof entry.accountId === "string" ? { accountId: entry.accountId } : {}
342
+ };
343
+ }
344
+ /**
345
+ * A14: `Automatic` rotation starts *at* the persisted active account and walks
346
+ * insertion order from there, wrapping once. The active account is the cursor
347
+ * rotation last left at, so a turn that starts at index 0 regardless would
348
+ * re-activate and re-try an account the previous turn already moved past —
349
+ * which is the whole job the removed sticky-exclusion set was doing badly.
350
+ * With no persisted active account the order is plain insertion order.
351
+ */
352
+ function orderAccountsFromActive(accounts, activeId) {
353
+ const index = activeId === void 0 ? -1 : accounts.findIndex((account) => account.id === activeId);
354
+ if (index <= 0) return accounts;
355
+ return [...accounts.slice(index), ...accounts.slice(0, index)];
356
+ }
357
+ async function applyPreferredAccountRoute(args, store, route) {
358
+ store.reload();
359
+ const preferredId = getRouteTargetAccountId(route);
360
+ const accounts = store.listAccounts?.(route.providerId) ?? [];
361
+ if (accounts.length === 0 && preferredId === void 0) return false;
362
+ const tried = getTriedInstances(args.state);
363
+ const unavailable = new Set(accounts.filter((account) => tried.has(account.id)).map((account) => account.id));
364
+ const active = getRequestActiveAccount(args, store, route.providerId) ?? store.getActiveAccount?.(route.providerId);
365
+ const selected = (preferredId ? accounts.filter((account) => account.id === preferredId) : orderAccountsFromActive(accounts, active?.id)).find((account) => !unavailable.has(account.id));
366
+ for (const accountId of unavailable) tried.add(accountId);
367
+ if (!selected) {
368
+ markRequestAccountRoutingExhausted(args.requestContext, route.providerId);
369
+ return false;
370
+ }
371
+ if (active?.id === selected.id) {
372
+ setRequestAccountSelection(args.requestContext, route.providerId, selected.id);
373
+ return false;
374
+ }
375
+ const activated = store.activateAccount ? store.activateAccount(route.providerId, selected.id) : selected;
376
+ if (!activated) {
377
+ if (preferredId !== void 0) markRequestAccountRoutingExhausted(args.requestContext, route.providerId);
378
+ return false;
379
+ }
380
+ setRequestAccountSelection(args.requestContext, route.providerId, activated.id);
381
+ if (preferredId === void 0) await emitAccountSwitchPart(args, {
382
+ provider: route.providerId,
383
+ from: active ? {
384
+ id: active.id,
385
+ label: active.label
386
+ } : null,
387
+ to: {
388
+ id: activated.id,
389
+ label: activated.label
390
+ },
391
+ reason: "preferred-routing",
392
+ at: (/* @__PURE__ */ new Date()).toISOString()
393
+ });
394
+ return true;
395
+ }
396
+ var AccountRotationProcessor = class {
397
+ options;
398
+ id = "mastracode-account-rotation";
399
+ constructor(options) {
400
+ this.options = options;
401
+ }
402
+ async processAPIError(args) {
403
+ const { error, state } = args;
404
+ if (args.retryCount >= this.options.maxProcessorRetries) {
405
+ await this.gateChainHop(args, error);
406
+ return { retry: false };
407
+ }
408
+ const classification = classifyRotationError(error);
409
+ if (classification.kind === "never") {
410
+ await this.gateChainHop(args, error);
411
+ return { retry: false };
412
+ }
413
+ if (classification.kind === "stream-cut") {
414
+ const budget = state.streamCutRetries;
415
+ const cuts = budget?.step === args.stepNumber ? budget.count : 0;
416
+ if (cuts >= 2) {
417
+ await this.gateChainHop(args, error);
418
+ return { retry: false };
419
+ }
420
+ state.streamCutRetries = {
421
+ step: args.stepNumber,
422
+ count: cuts + 1
423
+ };
424
+ args.rotateResponseMessageId?.();
425
+ (args.requestContext?.get("controller"))?.emitEvent?.({
426
+ type: "info",
427
+ message: `The provider ended the response stream early (it may have hit a stream duration limit). Retrying (${cuts + 1}/2).`
428
+ });
429
+ return { retry: true };
430
+ }
431
+ const cascade = await this.getModelRouteCascade(args);
432
+ const currentEntry = cascade?.entries[cascade.position];
433
+ const providerId = providerFromError(error) ?? (currentEntry ? providerFromModelId(currentEntry.modelId) : void 0) ?? (cascade ? void 0 : providerFromSession(args));
434
+ if (!providerId) {
435
+ await this.emitModelFallbackPart(args, classification.kind === "hop" ? "persistent-outage" : "pool-exhausted");
436
+ return { retry: false };
437
+ }
438
+ const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;
439
+ store.reload();
440
+ const accounts = store.listAccounts?.(providerId) ?? [];
441
+ const active = getRequestActiveAccount(args, store, providerId);
442
+ const route = currentEntry ? resolveAccountRoute(args, currentEntry) : resolveAccountRoute(args);
443
+ const hasAccountRegistry = typeof store.listAccounts === "function";
444
+ if (classification.kind === "rotate" && classification.reason === "auth-failed" && (active || !hasAccountRegistry)) {
445
+ const forced = getForcedRefreshInstances(state);
446
+ const refreshKey = `${providerId}:${active?.id ?? "active"}`;
447
+ if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === "function") {
448
+ forced.add(refreshKey);
449
+ if (await store.forceRefreshActiveAccount(providerId, active?.id) !== void 0) return { retry: true };
450
+ }
451
+ }
452
+ const targetAccountId = route?.providerId === providerId ? getRouteTargetAccountId(route) : void 0;
453
+ if (classification.kind === "hop") return this.declarePoolUnavailable(args, providerId, "persistent-outage", targetAccountId !== void 0);
454
+ if (targetAccountId !== void 0) return this.declarePoolUnavailable(args, providerId, "pool-exhausted", true);
455
+ const tried = getTriedInstances(state);
456
+ if (active) tried.add(active.id);
457
+ if (accounts.filter((account) => tried.has(account.id)).length >= accounts.length) return this.declarePoolUnavailable(args, providerId, "pool-exhausted");
458
+ const nextCandidate = (active ? accounts : orderAccountsFromActive(accounts, store.getActiveAccount?.(providerId)?.id)).find((account) => !tried.has(account.id));
459
+ const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : void 0;
460
+ if (!next) return this.declarePoolUnavailable(args, providerId, "pool-exhausted");
461
+ setRequestAccountSelection(args.requestContext, providerId, next.id);
462
+ tried.add(next.id);
463
+ args.rotateResponseMessageId?.();
464
+ await emitAccountSwitchPart(args, {
465
+ provider: providerId,
466
+ from: active ? {
467
+ id: active.id,
468
+ label: active.label
469
+ } : null,
470
+ to: {
471
+ id: next.id,
472
+ label: next.label
473
+ },
474
+ reason: classification.reason,
475
+ at: (/* @__PURE__ */ new Date()).toISOString()
476
+ });
477
+ return { retry: true };
478
+ }
479
+ /**
480
+ * Resolve the request's host-supplied model route once and cache the reachable
481
+ * prefix in processor state. Resolution mirrors getDynamicModel so a hop is
482
+ * never announced for an entry core cannot reach.
483
+ */
484
+ async getModelRouteCascade(args) {
485
+ if (args.state.modelRouteCascade !== void 0) return args.state.modelRouteCascade ?? null;
486
+ const controller = getRoutingController(args);
487
+ const state = controller?.getState?.();
488
+ const route = (state?.modelRoute)?.entries;
489
+ const pending = state?.mastracodePendingModelFallback;
490
+ const startIndex = pending && typeof pending.toEntryId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? route?.findIndex((entry) => entry.id === pending.toEntryId) : route && findRouteModelIndex(route, controller?.session?.modelId);
491
+ if (!route || startIndex === void 0 || startIndex < 0 || route.length - startIndex < 2) {
492
+ args.state.modelRouteCascade = null;
493
+ return null;
494
+ }
495
+ const thinkingLevel = resolveRequestThinkingLevel({
496
+ state: { thinkingLevel: state?.thinkingLevel },
497
+ ...!this.options.modeless && { session: { modeId: typeof controller?.session?.modeId === "string" ? controller.session.modeId : "build" } }
498
+ }, this.options.settingsPath, args.requestContext && !isThinkingLevelSetting(state?.thinkingLevel) ? await this.options.resolveDefaultThinkingLevel?.({ requestContext: args.requestContext }) : void 0);
499
+ const entries = [];
500
+ for (const entry of route.slice(startIndex)) {
501
+ if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.modelId !== "string" || entry.modelId.length === 0) break;
502
+ if (entries.length > 0) try {
503
+ resolveModel(entry.modelId, {
504
+ thinkingLevel,
505
+ remapForCodexOAuth: true,
506
+ requestContext: args.requestContext
507
+ });
508
+ } catch {
509
+ break;
510
+ }
511
+ entries.push({
512
+ id: entry.id,
513
+ label: typeof entry.label === "string" && entry.label.length > 0 ? entry.label : entry.id,
514
+ modelId: entry.modelId,
515
+ ...typeof entry.accountId === "string" ? { accountId: entry.accountId } : {}
516
+ });
517
+ }
518
+ if (entries.length < 2) {
519
+ args.state.modelRouteCascade = null;
520
+ return null;
521
+ }
522
+ const cascade = {
523
+ entries,
524
+ position: 0
525
+ };
526
+ args.state.modelRouteCascade = cascade;
527
+ return cascade;
528
+ }
529
+ /**
530
+ * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
531
+ * fallback array advances on ANY thrown error except TripWire
532
+ * (llm-execution-step.ts), so when the session route has another entry and the
533
+ * current entry is non-last, a bare `retry: false` would silently hop on an
534
+ * error class the user excluded from hop triggers. TripWire is the only
535
+ * no-advance escape: the runner rethrows it and the fallback loop declines
536
+ * to advance. No chain (or already on the last entry) → return and let the
537
+ * plain `retry: false` surface the error exactly as before.
538
+ */
539
+ async gateChainHop(args, error) {
540
+ const cascade = await this.getModelRouteCascade(args);
541
+ if (!cascade) return;
542
+ if (cascade.position >= cascade.entries.length - 1) return;
543
+ const reason = error instanceof Error ? error.message : String(error);
544
+ throw new TripWire(reason, {}, this.id);
545
+ }
546
+ /** Announce and persist the next model-route hop before core advances. */
547
+ async emitModelFallbackPart(args, reason) {
548
+ const cascade = await this.getModelRouteCascade(args);
549
+ if (!cascade) return;
550
+ const from = cascade.entries[cascade.position];
551
+ const to = cascade.entries[cascade.position + 1];
552
+ if (!from || !to) return;
553
+ const controller = args.requestContext?.get("controller");
554
+ const at = (/* @__PURE__ */ new Date()).toISOString();
555
+ const threadId = typeof controller?.threadId === "string" ? controller.threadId : void 0;
556
+ const pending = {
557
+ fromEntryId: from.id,
558
+ toEntryId: to.id,
559
+ toModelId: to.modelId,
560
+ ...threadId ? { threadId } : {},
561
+ reason,
562
+ at
563
+ };
564
+ await controller?.setThreadSetting?.({
565
+ key: MODEL_FALLBACK_STATE_KEY,
566
+ value: pending
567
+ });
568
+ const data = {
569
+ from: {
570
+ entryId: from.id,
571
+ label: from.label
572
+ },
573
+ to: {
574
+ entryId: to.id,
575
+ label: to.label
576
+ },
577
+ reason,
578
+ at
579
+ };
580
+ try {
581
+ await args.writer?.custom({
582
+ type: MODEL_FALLBACK_PART_TYPE,
583
+ data
584
+ });
585
+ } catch (error) {
586
+ await controller?.setThreadSetting?.({
587
+ key: MODEL_FALLBACK_STATE_KEY,
588
+ value: void 0
589
+ });
590
+ throw error;
591
+ }
592
+ await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
593
+ args.state.startNoticeEmitted = false;
594
+ const targetRoute = resolveAccountRoute(args, to);
595
+ if (targetRoute) await applyPreferredAccountRoute(args, resolveCredentialStore(args.requestContext) ?? this.options.credentialStore, targetRoute).catch(() => void 0);
596
+ controller?.emitEvent?.({
597
+ type: "info",
598
+ message: modelFallbackNoticeText(data)
599
+ });
600
+ cascade.position++;
601
+ }
602
+ /**
603
+ * Pool done for this request: every instance recorded in the tried-set and
604
+ * a `to: null` part emitted. Returns `retry: false` so core's fallback
605
+ * array can hop to the next route entry (announced by `emitModelFallbackPart`).
606
+ * Silent on the account part when the provider has no registry at all —
607
+ * there are no accounts to declare unavailable, but the hop still applies.
608
+ */
609
+ async declarePoolUnavailable(args, providerId, reason, exclusive = false) {
610
+ const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;
611
+ const accounts = store.listAccounts?.(providerId) ?? [];
612
+ if (accounts.length === 0) {
613
+ await this.emitModelFallbackPart(args, reason);
614
+ return { retry: false };
615
+ }
616
+ const tried = getTriedInstances(args.state);
617
+ for (const account of accounts) tried.add(account.id);
618
+ const active = getRequestActiveAccount(args, store, providerId);
619
+ await emitAccountSwitchPart(args, {
620
+ provider: providerId,
621
+ from: active ? {
622
+ id: active.id,
623
+ label: active.label
624
+ } : null,
625
+ to: null,
626
+ reason,
627
+ at: (/* @__PURE__ */ new Date()).toISOString(),
628
+ ...exclusive ? { exclusive: true } : {}
629
+ });
630
+ await this.emitModelFallbackPart(args, reason);
631
+ return { retry: false };
632
+ }
633
+ };
634
+ /**
635
+ * Applies the pack's preferred account route once per request, before the
636
+ * first model call. Without a route it only reloads the credential store so
637
+ * the request sees accounts changed by other processes.
638
+ *
639
+ * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It
640
+ * lives in `inputProcessors`; the runner walks input processors first when
641
+ * running `processAPIError`, so adding the method here would classify and
642
+ * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.
643
+ */
644
+ var AccountStartNoticeProcessor = class {
645
+ options;
646
+ id = "mastracode-account-start-notice";
647
+ constructor(options) {
648
+ this.options = options;
649
+ }
650
+ async processInput(args) {
651
+ if (args.state.startNoticeEmitted) return args.messageList;
652
+ const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;
653
+ const route = resolveAccountRoute(args);
654
+ if (!route) {
655
+ store.reload();
656
+ return args.messageList;
657
+ }
658
+ if (await applyPreferredAccountRoute(args, store, route) || getRouteTargetAccountId(route) !== void 0) args.state.startNoticeEmitted = true;
659
+ return args.messageList;
660
+ }
661
+ };
662
+ export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, modelFallbackNoticeText, providerFromError, providerFromModelId };
@@ -0,0 +1,17 @@
1
+ import type { RequestContext } from '@mastra/core/request-context';
2
+ /** The read-only view of a request context that credential and account lookups need. */
3
+ export type RequestContextReader = {
4
+ get(key: string): unknown;
5
+ };
6
+ export declare function getRequestAccountSelection(requestContext: RequestContextReader | undefined, providerId: string): string | undefined;
7
+ export declare function setRequestAccountSelection(requestContext: RequestContext | undefined, providerId: string, accountInstanceId: string): void;
8
+ /**
9
+ * Record that routing found no usable account for this provider on this
10
+ * request. Kept separate from the account selection: a sentinel *id* would be
11
+ * handed to credential lookup, where an unknown id makes `get()` fall back to
12
+ * the provider's active account — the very account routing just rejected.
13
+ */
14
+ export declare function markRequestAccountRoutingExhausted(requestContext: RequestContext | undefined, providerId: string): void;
15
+ /** Whether routing already rejected every account for this provider on this request. */
16
+ export declare function isRequestAccountRoutingExhausted(requestContext: RequestContextReader | undefined, providerId: string): boolean;
17
+ //# sourceMappingURL=account-routing-context.d.ts.map