@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
package/dist/index.js ADDED
@@ -0,0 +1,1399 @@
1
+ import { createSessionThreadAdvertisement } from "./agent-connections/session-advertisement.js";
2
+ import { AgentConnectionsSignalProvider } from "./agent-connections/signal-provider.js";
3
+ import { createBackgroundCompletionEvents } from "./agents/background-completion-events.js";
4
+ import { createBackgroundCompletionCallbacks } from "./agents/background-completion.js";
5
+ import { hasCredentialStoreProvider, setCredentialLogger, withCredentialTenantPreparation } from "./agents/credential-resolver.js";
6
+ import { getDynamicInstructions } from "./agents/instructions.js";
7
+ import { getDynamicMemory } from "./agents/memory.js";
8
+ import { canUseProvider, createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from "./agents/model.js";
9
+ import { buildMode } from "./agents/modes/build.js";
10
+ import { fastMode } from "./agents/modes/explore.js";
11
+ import { createPlanMode } from "./agents/modes/plan.js";
12
+ import { createGitRefReminderReader, createGitRefReminderReaderAsync, instructionSourcePaths, loadSessionInstructions, loadSessionInstructionsAsync, sessionInstructionRoots } from "./agents/prompts/agent-instructions.js";
13
+ import { builtinSubagents, resolveSubagentsSetting } from "./agents/subagents/index.js";
14
+ import { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from "./agents/thread-caveman-state.js";
15
+ import { createDynamicTools, createToolHooks } from "./agents/tools.js";
16
+ import { getDynamicWorkspace, getGoalJudgeTools } from "./agents/workspace.js";
17
+ import { AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_STATE_KEY, isStreamCutAfterResponse } from "./auth/account-rotation-processor.js";
18
+ import { isKimiCodingDeviceId } from "./auth/providers/kimi-coding.js";
19
+ import { AuthStorage } from "./auth/storage.js";
20
+ import { CODE_AGENT_ID, DEFAULT_OM_MODEL_ID, validateConfigDirName } from "./constants.js";
21
+ import { resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent } from "./experimental-agent.js";
22
+ import "./hooks/index.js";
23
+ import { KnowledgeInspectorError, createKnowledgeInspector } from "./knowledge-inspector.js";
24
+ import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
25
+ import "./mcp/index.js";
26
+ import { getAvailableOmPacks, resolveAutoOMModelId } from "./onboarding/packs.js";
27
+ import { MASTRA_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, loadSettings, resolveOmRoleModel, saveSettings } from "./onboarding/settings.js";
28
+ import { getToolCategory } from "./permissions.js";
29
+ import { PluginManager } from "./plugins/manager.js";
30
+ import { PluginSignalLane } from "./plugins/signal-lane.js";
31
+ import { PlanRejectionAbortProcessor } from "./processors/plan-rejection-abort.js";
32
+ import { createAmazonBedrockGateway } from "./providers/amazon-bedrock-gateway.js";
33
+ import { setAuthStorage } from "./providers/claude-max.js";
34
+ import { createGitHubCopilotGateway } from "./providers/github-copilot-gateway.js";
35
+ import { HookManager } from "./hooks/manager.js";
36
+ import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
37
+ import { createGoogleVertexGateway } from "./providers/google-vertex-gateway.js";
38
+ import { createMcpManager } from "./mcp/manager.js";
39
+ import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
40
+ import { parseCodexModelSelection } from "./providers/model-ids.js";
41
+ import { setAuthStorage as setAuthStorage$3 } from "./providers/openai-codex.js";
42
+ import { setAuthStorage as setAuthStorage$4 } from "./providers/xai.js";
43
+ import "./schedules/index.js";
44
+ import { stateSchema } from "./schema.js";
45
+ import { assembleSchedulePrompt } from "./schedules/prompt.js";
46
+ import { ThreadScheduler, scheduleSignalAttributes, shortScheduleId } from "./schedules/scheduler.js";
47
+ import { runScript } from "./schedules/run-script.js";
48
+ import { createScheduleTools } from "./schedules/tools.js";
49
+ import { mastraBrand } from "./theme-palette.js";
50
+ import { isThinkingLevelSetting } from "./thinking.js";
51
+ import { DiscardingScoresStorage } from "./utils/discarding-scores-storage.js";
52
+ import { syncGateways } from "./utils/gateway-sync.js";
53
+ import { openLocalObservabilityStore } from "./utils/local-observability.js";
54
+ import { registerSessionAndWaitForMaintenance, unregisterSession } from "./utils/maintenance-lock.js";
55
+ import { createResourceNotificationDispatcher, shouldHoldNotificationDelivery } from "./utils/notification-dispatch.js";
56
+ import { detectProject, getObservabilityDatabasePath, getResourceIdOverride, getStorageConfig } from "./utils/project.js";
57
+ import { createSignalsPubSub } from "./utils/signals-pubsub.js";
58
+ import { createStorage, createVectorStore } from "./utils/storage-factory.js";
59
+ import { DEFAULT_RETENTION, createStorageMaintenance, resolveLocalDbFiles } from "./utils/storage-maintenance.js";
60
+ import { acquireThreadLock, releaseThreadLock } from "./utils/thread-lock.js";
61
+ import { FOREIGN_THREAD, findWakeSession, sessionLeaseScopes } from "./utils/wake-session.js";
62
+ import { registerWorkflowBuilderPrimitives } from "./workflows/register-primitives.js";
63
+ import { autoApprovePolicy, denyPolicy, permissionModeToPolicy } from "./headless/policy.js";
64
+ import { runMC } from "./headless/run-mc.js";
65
+ import { formatHuman, formatJsonl, renderJsonResult, renderTextResult } from "./headless/format.js";
66
+ import { hasHeadlessFlag, runMCCli } from "./headless/cli.js";
67
+ import "./headless/index.js";
68
+ import path from "path";
69
+ import { createHash, randomUUID } from "crypto";
70
+ import { statSync } from "fs";
71
+ import { homedir, hostname } from "os";
72
+ import { ModelRouterEmbeddingModel, PROVIDER_REGISTRY, findGatewayForModel, getGatewayId } from "@mastra/core/llm";
73
+ import { readFile } from "fs/promises";
74
+ import { AgentController, migratePersistedModelSelection } from "@mastra/core/agent-controller";
75
+ import { createCodingAgent } from "@mastra/core/coding-agent";
76
+ import { classifyProviderError, getErrorFromUnknown } from "@mastra/core/error";
77
+ import { Knowledge, knowledgeMemoryScopes } from "@mastra/core/knowledge";
78
+ import { Mastra } from "@mastra/core/mastra";
79
+ import { defaultNotificationDeliveryDecision, readNotificationRoutingRequirement } from "@mastra/core/notifications";
80
+ import { AgentsMDInjector, CyberRefusalHandler, ProviderHistoryCompat, StreamErrorRetryProcessor, createBackgroundWorkSignalProcessor, isBadRequestError } from "@mastra/core/processors";
81
+ import { RequestContext } from "@mastra/core/request-context";
82
+ import { TaskSignalProvider } from "@mastra/core/signals";
83
+ import { MastraCompositeStore } from "@mastra/core/storage";
84
+ import { DEFAULT_GOAL_JUDGE_PROMPT } from "@mastra/core/tools";
85
+ import { GithubSignals } from "@mastra/github-signals";
86
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
87
+ import { MastraPlatformExporter, MastraStorageExporter, Observability, SensitiveDataFilter } from "@mastra/observability";
88
+ // src/index.ts
89
+ const MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 10;
90
+ const MASTRACODE_MAX_PROCESSOR_RETRIES = 64;
91
+ const MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 500;
92
+ const MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 3e4;
93
+ const TRANSIENT_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "EPIPE"]);
94
+ const TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;
95
+ const isTransientServerStatus = (status) => status >= 500 && status < 600;
96
+ /**
97
+ * Matcher for transient connection failures. Cause-chain traversal is handled
98
+ * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each
99
+ * matcher at every level of the cause chain.
100
+ */
101
+ /**
102
+ * Read the session state fields the AgentsMDInjector callbacks need from the
103
+ * controller request context (set by hosts like the factory review flow).
104
+ */
105
+ function getInjectorSessionState(requestContext) {
106
+ return (requestContext?.get("controller"))?.getState();
107
+ }
108
+ function isTransientConnectionError(error) {
109
+ if (!error) return false;
110
+ const code = typeof error === "object" && "code" in error ? error.code : void 0;
111
+ if (typeof code === "string" && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;
112
+ const message = error instanceof Error ? error.message : void 0;
113
+ if (typeof message === "string" && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;
114
+ return false;
115
+ }
116
+ function isTransientServerError(error) {
117
+ if (!error) return false;
118
+ const kind = classifyProviderError(error);
119
+ if (kind === "context_overflow") return false;
120
+ const errorObj = typeof error === "object" ? error : void 0;
121
+ if (typeof errorObj?.status === "number" && isTransientServerStatus(errorObj.status) || typeof errorObj?.statusCode === "number" && isTransientServerStatus(errorObj.statusCode)) return true;
122
+ return kind === "unavailable";
123
+ }
124
+ function getTransientRetryDelay(retryCount) {
125
+ return Math.min(MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount), MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS);
126
+ }
127
+ function emitTransientRetry(error, retryCount, delayMs, requestContext) {
128
+ (requestContext?.get("controller"))?.emitEvent?.({
129
+ type: "error",
130
+ error: getErrorFromUnknown(error, { supportSerialization: false }),
131
+ retryable: true,
132
+ retryDelay: delayMs,
133
+ retryAttempt: retryCount + 1,
134
+ maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES
135
+ });
136
+ }
137
+ /** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */
138
+ function shortHash(input) {
139
+ return createHash("sha256").update(input).digest("hex").slice(0, 12);
140
+ }
141
+ function applyModeDefaultsToModes(modes, modeDefaults) {
142
+ return modes.map((mode) => {
143
+ const savedModel = modeDefaults[mode.id];
144
+ if (!savedModel) return mode;
145
+ return {
146
+ ...mode,
147
+ defaultModelId: savedModel
148
+ };
149
+ });
150
+ }
151
+ function addPluginToolsToModeAllowlists(modes, pluginToolNames) {
152
+ if (pluginToolNames.length === 0) return modes;
153
+ return modes.map((mode) => {
154
+ if (!mode.availableTools) return mode;
155
+ return {
156
+ ...mode,
157
+ availableTools: Array.from(/* @__PURE__ */ new Set([...mode.availableTools, ...pluginToolNames]))
158
+ };
159
+ });
160
+ }
161
+ function createAuthStorage() {
162
+ const authStorage = new AuthStorage();
163
+ setAuthStorage(authStorage);
164
+ setAuthStorage$3(authStorage);
165
+ setAuthStorage$1(authStorage);
166
+ setAuthStorage$2(authStorage);
167
+ setAuthStorage$4(authStorage);
168
+ return authStorage;
169
+ }
170
+ /**
171
+ * Resolve cloud observability credentials for the MastraPlatformExporter.
172
+ * Priority: per-resource settings > MASTRACODE_* environment variables > undefined (no exporter).
173
+ *
174
+ * The env vars are deliberately namespaced `MASTRACODE_*`, not `MASTRA_*`: the
175
+ * cwd `.env` is loaded into `process.env`, so reading `MASTRA_PROJECT_ID` /
176
+ * `MASTRA_CLOUD_ACCESS_TOKEN` would export Mastra Code's own traces into
177
+ * whatever Mastra project the user happens to be working in (and crash on
178
+ * project ids the exporter rejects).
179
+ */
180
+ function resolveCloudObservabilityConfig(settings, authStorage, resourceId, env = process.env) {
181
+ const resourceConfig = settings.observability.resources[resourceId];
182
+ if (resourceConfig) {
183
+ const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);
184
+ if (token) return {
185
+ accessToken: token,
186
+ projectId: resourceConfig.projectId
187
+ };
188
+ }
189
+ const accessToken = env.MASTRACODE_CLOUD_ACCESS_TOKEN?.trim();
190
+ if (!accessToken) return void 0;
191
+ return {
192
+ accessToken,
193
+ projectId: env.MASTRACODE_PROJECT_ID?.trim() || void 0
194
+ };
195
+ }
196
+ /**
197
+ * Base factory: builds every shared MastraCode resource (storage, observability,
198
+ * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but
199
+ * does NOT call `init()` or create a session. The controller is returned inert so
200
+ * the composition layer can decide its Mastra ownership and session model.
201
+ *
202
+ * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).
203
+ */
204
+ /**
205
+ * `instanceof` checks against Mastra classes are unreliable here: published
206
+ * packages pin exact `@mastra/core` versions, so a user's dependency graph can
207
+ * contain multiple copies of core (and peer-keyed copies of `@mastra/libsql` /
208
+ * `@mastra/pg`). A store built against one copy fails `instanceof` against
209
+ * another — the injected instance then silently fell through to the
210
+ * StorageConfig path and crashed on `config.url`. These structural checks work
211
+ * across duplicated copies.
212
+ */
213
+ function isInjectedStorageInstance(storage) {
214
+ if (!storage) return false;
215
+ if (storage instanceof MastraCompositeStore) return true;
216
+ const candidate = storage;
217
+ return typeof candidate.init === "function" && typeof candidate.__registerMastra === "function";
218
+ }
219
+ /** Cross-copy-safe class check: walks the prototype chain by constructor name. */
220
+ function hasAncestorClassNamed(value, className) {
221
+ for (let proto = Object.getPrototypeOf(value); proto; proto = Object.getPrototypeOf(proto)) if (proto.constructor?.name === className) return true;
222
+ return false;
223
+ }
224
+ function resolveInjectedStorageBackend(storage, configuredBackend) {
225
+ if (configuredBackend) return configuredBackend;
226
+ if (storage instanceof LibSQLStore || hasAncestorClassNamed(storage, "LibSQLStore")) return "libsql";
227
+ if (hasAncestorClassNamed(storage, "PostgresStore")) return "pg";
228
+ throw new Error("storageBackend is required when injecting a custom storage instance.");
229
+ }
230
+ /** Whether the model router would resolve `modelId` through a gateway outside `sdkGatewayIds`. */
231
+ function routesToOtherGateway(modelId, gateways, sdkGatewayIds) {
232
+ try {
233
+ return !sdkGatewayIds.has(getGatewayId(findGatewayForModel(modelId, gateways)));
234
+ } catch (error) {
235
+ if (error?.id === "MODEL_ROUTER_NO_GATEWAY_FOUND") return false;
236
+ throw error;
237
+ }
238
+ }
239
+ async function createMastraCodeAgentController(config) {
240
+ const cwd = config?.cwd ?? process.cwd();
241
+ const homeDir = config?.homeDir ?? config?.initialState?.homeDir;
242
+ const configDir = config?.configDir ?? ".mastracode";
243
+ const modeless = config?.modes === false;
244
+ let activeSession;
245
+ const liveSessions = /* @__PURE__ */ new Set();
246
+ const sessionRouter = {
247
+ getSession: (sessionId) => controller.getSession(sessionId),
248
+ listLiveSessions: () => liveSessions
249
+ };
250
+ let pluginRuntimeController;
251
+ if (configDir !== ".mastracode") validateConfigDirName(configDir);
252
+ if (!config?.disableEnvFile) try {
253
+ process.loadEnvFile(path.join(cwd, ".env"));
254
+ } catch {}
255
+ const authStorage = createAuthStorage();
256
+ const globalSettings = loadSettings(config?.settingsPath);
257
+ const experimentalAgent = resolveExperimentalAgent(globalSettings);
258
+ const agentStreamsOff = resolveAgentStreamsOff();
259
+ const backgroundToolsEnabled = globalSettings.backgroundTools?.enabled ?? false;
260
+ const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);
261
+ const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;
262
+ if (storedGatewayKey) authStorage.loadStoredApiKeysIntoEnv({ [MASTRA_GATEWAY_PROVIDER]: "MASTRA_GATEWAY_API_KEY" });
263
+ if (storedGatewayUrl) process.env["MASTRA_GATEWAY_URL"] ??= storedGatewayUrl;
264
+ if (!hasCredentialStoreProvider()) try {
265
+ const registry = PROVIDER_REGISTRY;
266
+ const providerEnvVars = {};
267
+ for (const [provider, cfg] of Object.entries(registry)) {
268
+ const envVars = cfg?.apiKeyEnvVar;
269
+ providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;
270
+ }
271
+ providerEnvVars[MASTRA_GATEWAY_PROVIDER] ??= "MASTRA_GATEWAY_API_KEY";
272
+ authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);
273
+ } catch {
274
+ authStorage.loadStoredApiKeysIntoEnv({
275
+ [MASTRA_GATEWAY_PROVIDER]: "MASTRA_GATEWAY_API_KEY",
276
+ anthropic: "ANTHROPIC_API_KEY",
277
+ openai: "OPENAI_API_KEY",
278
+ google: "GOOGLE_GENERATIVE_AI_API_KEY",
279
+ cerebras: "CEREBRAS_API_KEY",
280
+ deepseek: "DEEPSEEK_API_KEY"
281
+ });
282
+ }
283
+ const mgApiKey = process.env["MASTRA_GATEWAY_API_KEY"] ?? storedGatewayKey;
284
+ const mastraGatewayBaseUrl = (process.env["MASTRA_GATEWAY_URL"] ?? storedGatewayUrl ?? "https://gateway-api.mastra.ai").replace(/\/+$/, "").replace(/\/v1$/, "");
285
+ const mastraCodeGateway = createMastraCodeGateway({
286
+ mastraGatewayBaseUrl,
287
+ mastraGatewayApiKey: mgApiKey,
288
+ routeThroughMastraGateway: false,
289
+ settingsPath: config?.settingsPath
290
+ });
291
+ const amazonBedrockGateway = createAmazonBedrockGateway();
292
+ const googleVertexGateway = createGoogleVertexGateway();
293
+ const githubCopilotGateway = createGitHubCopilotGateway();
294
+ const embedder = config?.memory === void 0 && typeof config?.embedder === "string" ? new ModelRouterEmbeddingModel(config.embedder) : config?.embedder;
295
+ const project = detectProject(cwd);
296
+ const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);
297
+ if (resourceIdOverride) {
298
+ project.resourceId = resourceIdOverride;
299
+ project.resourceIdOverride = true;
300
+ }
301
+ const cloudObservabilityConfig = resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId);
302
+ const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;
303
+ const ownerId = `mastracode-${shortHash(`${hostname()}\0${project.rootPath}`)}`;
304
+ const useCrossAgentSignals = config?.crossAgentSignals ?? globalSettings.signals?.experimentalCrossAgentSignals ?? false;
305
+ const configuredPubSub = config?.pubsub;
306
+ const useUnixSocketPubSub = (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== "win32";
307
+ const ownSignalsPubSub = !configuredPubSub && useUnixSocketPubSub ? createSignalsPubSub(project.resourceId, { sharedAgentDiscovery: useCrossAgentSignals }) : void 0;
308
+ const signalsPubSub = configuredPubSub ?? ownSignalsPubSub;
309
+ const crossProcessPubSub = config?.crossProcessPubSub ?? Boolean(ownSignalsPubSub);
310
+ if (crossProcessPubSub && !signalsPubSub) throw new Error("crossProcessPubSub requires a pubsub instance");
311
+ const useScheduleTools = config?.scheduleTools ?? globalSettings.signals?.experimentalScheduleTools ?? false;
312
+ const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : void 0;
313
+ const storageConfig = injectedStorage ? void 0 : config?.storage ?? getStorageConfig(project.rootPath, globalSettings.storage, configDir);
314
+ if (!injectedStorage) await registerSessionAndWaitForMaintenance({ onWait: (pid) => console.error(`Waiting for storage maintenance (mastracode prune${pid === -1 ? "" : `, PID ${pid}`}) to finish. Press Ctrl+C to give up.`) });
315
+ let storageResult;
316
+ if (injectedStorage) storageResult = {
317
+ storage: injectedStorage,
318
+ backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend)
319
+ };
320
+ else try {
321
+ storageResult = await createStorage(storageConfig);
322
+ } catch (error) {
323
+ unregisterSession();
324
+ throw error;
325
+ }
326
+ const storageWarning = storageResult.warning;
327
+ let observabilityDomain;
328
+ let observabilityWarning;
329
+ if (globalSettings.observability.localTracing) try {
330
+ const { store: observabilityDuckDB } = await openLocalObservabilityStore(getObservabilityDatabasePath());
331
+ observabilityDomain = observabilityDuckDB.observability;
332
+ } catch (err) {
333
+ const message = err instanceof Error ? err.message : String(err);
334
+ if (/lock|locked|busy/i.test(message)) observabilityWarning = "Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.";
335
+ else observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;
336
+ }
337
+ const storage = new MastraCompositeStore({
338
+ id: "mastra-code-storage",
339
+ default: storageResult.storage,
340
+ domains: {
341
+ observability: observabilityDomain ?? false,
342
+ ...config?.disableScoreStorage ?? true ? { scores: new DiscardingScoresStorage() } : {}
343
+ }
344
+ });
345
+ const observability = new Observability({ configs: { default: {
346
+ serviceName: "mastracode",
347
+ requestContextKeys: [
348
+ "controller.threadId",
349
+ "controller.resourceId",
350
+ "controller.session.modeId",
351
+ "controller.controllerId",
352
+ "controller.state.projectName",
353
+ "controller.state.gitBranch",
354
+ "controller.session.modelId",
355
+ "controller.state.subagentModelId",
356
+ "controller.state.yolo",
357
+ "controller.state.thinkingLevel",
358
+ "controller.state.smartEditing",
359
+ "controller.state.omScope",
360
+ "om.observer.selectionMode",
361
+ "om.observer.effectiveModelId",
362
+ "om.reflector.selectionMode",
363
+ "om.reflector.effectiveModelId",
364
+ "controller.state.observationThreshold",
365
+ "controller.state.reflectionThreshold"
366
+ ],
367
+ exporters: [...observabilityDomain ? [new MastraStorageExporter({ strategy: "event-sourced" })] : [], new MastraPlatformExporter({
368
+ ...cloudObservabilityConfig,
369
+ resolveFromEnv: false
370
+ })],
371
+ spanOutputProcessors: [new SensitiveDataFilter()]
372
+ } } });
373
+ const vector = config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : void 0);
374
+ const storageMaintenance = createStorageMaintenance({
375
+ storage: storageResult.storage,
376
+ backend: storageResult.backend,
377
+ retention: DEFAULT_RETENTION,
378
+ localDbFiles: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],
379
+ closeVector: vector instanceof LibSQLVector ? () => vector.close() : void 0
380
+ });
381
+ const knowledgeOption = config?.knowledge ?? (globalSettings.signals?.experimentalKnowledge ? true : void 0);
382
+ const knowledgeEntry = !knowledgeOption || knowledgeOption === true || knowledgeOption instanceof Knowledge ? void 0 : knowledgeOption;
383
+ const entryKey = knowledgeEntry?.key.trim();
384
+ if (knowledgeEntry && !entryKey) throw new Error("knowledge.key must be a non-empty string.");
385
+ const knowledge = knowledgeOption === true ? new Knowledge({
386
+ id: "mastracode",
387
+ name: "MastraCode Knowledge",
388
+ storage,
389
+ scopes: knowledgeMemoryScopes(),
390
+ tools: true,
391
+ pinnedContext: true
392
+ }) : knowledgeOption instanceof Knowledge ? knowledgeOption : knowledgeEntry?.instance;
393
+ const knowledgeKey = entryKey ?? knowledge?.id ?? "default";
394
+ const knowledgeHostScopes = [...config?.scopes ?? [], ...knowledgeOption === true && !(config?.scopes ?? []).length ? [`org:${LOCAL_KNOWLEDGE_ORG_ID}`] : []];
395
+ const dynamicMemory = config?.memory === void 0 ? getDynamicMemory(storage, vector, config?.settingsPath, {
396
+ disableSettingsOmSeed: config?.disableSettingsOmSeed,
397
+ embedder,
398
+ embedderOptions: config?.embedderOptions
399
+ }) : void 0;
400
+ const memory = config?.memory === false ? void 0 : config?.memory ?? (dynamicMemory && Object.assign(withCredentialTenantPreparation(dynamicMemory), { settled: dynamicMemory.settled }));
401
+ const mcpManager = config?.disableMcp ? void 0 : createMcpManager(project.rootPath, configDir, config?.mcpServers, globalSettings.mcp);
402
+ const hookManager = config?.disableHooks ? void 0 : new HookManager(project.rootPath, "session-init", configDir, homeDir, project.isWorktree ? {
403
+ path: project.rootPath,
404
+ branch: project.gitBranch,
405
+ mainRepoPath: project.mainRepoPath
406
+ } : void 0);
407
+ const pluginManager = config?.disablePlugins ? void 0 : config?.pluginManager ?? new PluginManager({
408
+ projectRoot: project.rootPath,
409
+ configDir,
410
+ homeDir
411
+ });
412
+ pluginManager?.setRuntime({
413
+ getController: () => pluginRuntimeController,
414
+ getActiveSession: () => activeSession,
415
+ getStorage: () => ({
416
+ storage,
417
+ storageBackend: storageResult.backend,
418
+ vector
419
+ })
420
+ });
421
+ const loadedPlugins = pluginManager ? await pluginManager.reload() : [];
422
+ const pluginTools = pluginManager?.getPluginTools() ?? {};
423
+ const ownsNotificationDispatch = !configuredPubSub;
424
+ const dispatchLeasePubSub = ownsNotificationDispatch && !ownSignalsPubSub && process.platform !== "win32" ? createSignalsPubSub(project.resourceId) : void 0;
425
+ const notificationDispatchLeases = ownsNotificationDispatch ? (ownSignalsPubSub ?? dispatchLeasePubSub)?.getLeaseProvider() : void 0;
426
+ const notificationDispatcher = createResourceNotificationDispatcher({
427
+ getMastra: () => controller.getMastra(),
428
+ getSessionScopes: async () => (await Promise.all([...liveSessions].map(async (session) => {
429
+ const resourceId = session.identity.getResourceId();
430
+ return (await sessionLeaseScopes(session)).map((scope) => ({
431
+ resourceId,
432
+ scope
433
+ }));
434
+ }))).flat(),
435
+ leases: notificationDispatchLeases,
436
+ owner: `${ownerId}:${process.pid}:${randomUUID()}`,
437
+ onError: (error) => console.warn("Notification dispatch failed:", error)
438
+ });
439
+ const resolveWakeOwner = async (target, leases) => {
440
+ const owner = await findWakeSession(controller, liveSessions, target, leases);
441
+ if (owner || !config?.resumeWakeSession) return owner;
442
+ await config.resumeWakeSession(target);
443
+ const resumed = await findWakeSession(controller, liveSessions, target, leases);
444
+ if (!resumed) throw new Error(`No session owns resource ${target.resourceId} to run its wake on thread ${target.threadId}.`);
445
+ return resumed;
446
+ };
447
+ const getWakeStreamOptions = async ({ resourceId, threadId, owner }) => {
448
+ const wake = owner ?? await findWakeSession(controller, liveSessions, {
449
+ resourceId,
450
+ threadId
451
+ });
452
+ if (!wake || wake === FOREIGN_THREAD) return void 0;
453
+ const { session } = wake;
454
+ const targetThread = await session.thread.getById({ threadId });
455
+ const metadata = targetThread?.resourceId === resourceId ? targetThread.metadata : void 0;
456
+ const modes = controller.listModes();
457
+ const savedModeId = metadata?.currentModeId;
458
+ const defaultMode = modes.find((mode) => mode.default) ?? modes[0];
459
+ const modeId = typeof savedModeId === "string" && modes.some((mode) => mode.id === savedModeId) ? savedModeId : defaultMode?.id ?? session.mode.get();
460
+ const persistedModelId = metadata ? await migratePersistedModelSelection({
461
+ getMetadata: async () => (await session.thread.getById({ threadId }))?.metadata ?? {},
462
+ modeId,
463
+ set: (key, value) => session.thread.setSettingOn({
464
+ threadId,
465
+ key,
466
+ value
467
+ }),
468
+ threadId,
469
+ validModeIds: modes.map((mode) => mode.id)
470
+ }) : void 0;
471
+ const defaultModeModelId = modes.find((mode) => mode.id === modeId)?.defaultModelId;
472
+ const modelId = persistedModelId ?? defaultModeModelId ?? session.model.get() ?? "";
473
+ const baseState = { ...session.state.get() };
474
+ delete baseState.modelRoute;
475
+ delete baseState.mastracodePendingModelFallback;
476
+ const persistedSandboxPaths = metadata?.sandboxAllowedPaths;
477
+ baseState.sandboxAllowedPaths = Array.isArray(persistedSandboxPaths) && persistedSandboxPaths.every((path) => typeof path === "string") ? persistedSandboxPaths : [];
478
+ const persistedStateKeys = [
479
+ "thinkingLevel",
480
+ "notifications",
481
+ "modelRoute",
482
+ MODEL_FALLBACK_STATE_KEY
483
+ ];
484
+ for (const key of persistedStateKeys) {
485
+ const value = metadata?.[key];
486
+ if (value !== void 0) baseState[key] = value;
487
+ }
488
+ if (session.thread.getId() !== threadId) baseState.permissionRules = metadata?.permissionRules ?? config?.initialState?.permissionRules ?? {
489
+ categories: {},
490
+ tools: {}
491
+ };
492
+ let notificationState = baseState;
493
+ const getNotificationState = () => ({ ...notificationState });
494
+ const setNotificationState = async (updates) => {
495
+ notificationState = {
496
+ ...notificationState,
497
+ ...updates
498
+ };
499
+ if (session.thread.getId() === threadId) await session.state.set(updates);
500
+ };
501
+ const updateNotificationState = async (updater) => {
502
+ const update = await updater(getNotificationState());
503
+ if (update.updates) await setNotificationState(update.updates);
504
+ for (const event of update.events ?? []) if (session.thread.getId() === threadId) session.emit(event);
505
+ return update.result;
506
+ };
507
+ const requestContext = new RequestContext();
508
+ const agentControllerContext = {
509
+ controllerId: controller.id,
510
+ state: getNotificationState(),
511
+ getState: getNotificationState,
512
+ setState: setNotificationState,
513
+ updateState: updateNotificationState,
514
+ getThreadSetting: (key) => session.thread.getSettingOn({
515
+ threadId,
516
+ key
517
+ }),
518
+ setThreadSetting: (setting) => session.thread.setSettingOn({
519
+ threadId,
520
+ key: setting.key,
521
+ value: setting.value
522
+ }),
523
+ isThreadActive: () => session.thread.getId() === threadId,
524
+ threadId,
525
+ resourceId,
526
+ sessionId: session.identity.getId(),
527
+ session: {
528
+ id: session.identity.getId(),
529
+ ownerId: session.identity.getOwnerId(),
530
+ modeId,
531
+ modelId,
532
+ state: {
533
+ get: getNotificationState,
534
+ set: setNotificationState,
535
+ update: updateNotificationState
536
+ }
537
+ },
538
+ workspace: session.getWorkspace(),
539
+ emitEvent: (event) => {
540
+ if (session.thread.getId() === threadId) session.emit(event);
541
+ },
542
+ getSubagentModelId: (params) => {
543
+ const agentType = params?.agentType;
544
+ const perType = agentType ? metadata?.[`subagentModelId_${agentType}`] : void 0;
545
+ const global = metadata?.subagentModelId;
546
+ if (typeof perType === "string") return perType;
547
+ if (typeof global === "string") return global;
548
+ return session.thread.getId() === threadId ? session.subagents.model.get(params ?? {}) : null;
549
+ }
550
+ };
551
+ requestContext.set("controller", agentControllerContext);
552
+ await config?.prepareWakeRequestContext?.({
553
+ requestContext,
554
+ resourceId,
555
+ threadId
556
+ });
557
+ return {
558
+ memory: {
559
+ thread: threadId,
560
+ resource: resourceId
561
+ },
562
+ requestContext,
563
+ maxSteps: 1e3,
564
+ savePerStep: false,
565
+ requireToolApproval: notificationState.yolo === true ? false : ({ toolName }) => session.resolveToolApproval(toolName, requestContext) !== "allow",
566
+ toolCallConcurrency: { strategy: "called" },
567
+ modelSettings: { temperature: 1 }
568
+ };
569
+ };
570
+ const threadScheduler = new ThreadScheduler({
571
+ assemblePrompt: (schedule) => assembleSchedulePrompt(schedule, {
572
+ cwd: project.rootPath,
573
+ runScript,
574
+ readFile: (absPath) => readFile(absPath, "utf8")
575
+ }),
576
+ deliver: async (schedule, assembled) => {
577
+ const target = {
578
+ resourceId: schedule.resourceId,
579
+ threadId: schedule.threadId
580
+ };
581
+ const owner = await resolveWakeOwner(target);
582
+ const streamOptions = owner && owner !== FOREIGN_THREAD ? await getWakeStreamOptions({
583
+ ...target,
584
+ owner
585
+ }) : void 0;
586
+ const accepted = await codeAgent.sendSignal({
587
+ type: "user",
588
+ tagName: "user",
589
+ contents: assembled.prompt,
590
+ attributes: scheduleSignalAttributes(schedule, assembled)
591
+ }, {
592
+ ...target,
593
+ ifActive: { behavior: "deliver" },
594
+ ifIdle: {
595
+ behavior: "wake",
596
+ ...streamOptions ? { streamOptions } : {},
597
+ ...owner === FOREIGN_THREAD ? { requireClaimedOwner: true } : {}
598
+ }
599
+ }).accepted;
600
+ if (accepted.action === "blocked" || accepted.action === "discard") throw new Error(`the agent did not accept the prompt (${accepted.action})`);
601
+ },
602
+ onError: (error, schedule) => {
603
+ console.warn(`Schedule ${shortScheduleId(schedule.id)} failed to fire:`, error);
604
+ }
605
+ });
606
+ const scheduleTools = useScheduleTools ? createScheduleTools({
607
+ scheduler: threadScheduler,
608
+ fileOptions: () => ({
609
+ cwd: project.rootPath,
610
+ homeDir: homedir(),
611
+ fileExists: (absPath) => {
612
+ try {
613
+ return statSync(absPath).isFile();
614
+ } catch {
615
+ return false;
616
+ }
617
+ }
618
+ })
619
+ }) : void 0;
620
+ const githubSignals = globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals ? new GithubSignals({
621
+ cwd: project.rootPath,
622
+ pollIntervalMs: globalSettings.signals.githubPollIntervalMs,
623
+ gitcrawlCommand: process.env.MASTRACODE_GITCRAWL_BIN ?? process.env.GITCRAWL_BIN ?? process.env.MASTRACODE_GITCRAWL_COMMAND ?? process.env.GITCRAWL_COMMAND,
624
+ getNotificationStreamOptions: getWakeStreamOptions
625
+ }) : void 0;
626
+ const mastraCodeInputProcessors = [
627
+ ...Array.isArray(config?.inputProcessors) ? config.inputProcessors : [],
628
+ new PlanRejectionAbortProcessor(),
629
+ ...backgroundToolsEnabled ? [createBackgroundWorkSignalProcessor()] : [],
630
+ new AgentsMDInjector({
631
+ isEnabled: ({ requestContext }) => {
632
+ const state = getInjectorSessionState(requestContext);
633
+ return state?.untrustedCheckout !== true || typeof state?.baseRef === "string";
634
+ },
635
+ getBasePath: ({ requestContext }) => getInjectorSessionState(requestContext)?.projectPath ?? project.rootPath,
636
+ getReader: ({ requestContext }) => {
637
+ const state = getInjectorSessionState(requestContext);
638
+ if (state?.untrustedCheckout !== true || typeof state?.baseRef !== "string") return void 0;
639
+ const projectPath = state?.projectPath ?? project.rootPath;
640
+ const [primary] = sessionInstructionRoots(projectPath, state.instructionRoots);
641
+ const reader = "supportsAsyncInstructionReaders" in AgentsMDInjector ? createGitRefReminderReaderAsync(primary, state.baseRef) : createGitRefReminderReader(primary, state.baseRef);
642
+ if (primary === projectPath) return reader;
643
+ const outsidePrimary = (filePath) => {
644
+ const inProject = path.relative(projectPath, filePath);
645
+ const inPrimary = path.relative(primary, filePath);
646
+ const under = (rel) => rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
647
+ return under(inProject) && !under(inPrimary);
648
+ };
649
+ return {
650
+ ...reader,
651
+ pathExists: (filePath) => !outsidePrimary(filePath) && reader.pathExists(filePath),
652
+ isDirectory: (filePath) => !outsidePrimary(filePath) && reader.isDirectory(filePath),
653
+ readFile: (filePath) => {
654
+ if (outsidePrimary(filePath)) throw new Error(`Not found at ref ${state.baseRef}: ${filePath}`);
655
+ return reader.readFile(filePath);
656
+ }
657
+ };
658
+ },
659
+ getIgnoredInstructionPaths: ({ requestContext }) => {
660
+ const state = getInjectorSessionState(requestContext);
661
+ const projectPath = state?.projectPath ?? project.rootPath;
662
+ const untrusted = state?.untrustedCheckout === true && typeof state?.baseRef === "string";
663
+ const roots = sessionInstructionRoots(projectPath, state?.instructionRoots);
664
+ const options = {
665
+ workingDir: projectPath,
666
+ instructionRoots: state?.instructionRoots,
667
+ untrustedCheckout: untrusted,
668
+ baseRef: untrusted ? state?.baseRef : void 0
669
+ };
670
+ if (!("supportsAsyncInstructionReaders" in AgentsMDInjector)) return instructionSourcePaths(loadSessionInstructions(options), roots);
671
+ return loadSessionInstructionsAsync(options).then((sources) => instructionSourcePaths(sources, roots));
672
+ }
673
+ })
674
+ ];
675
+ const disabledBuiltinTools = new Set(config?.disableBuiltinTools ?? []);
676
+ const taskSignalProvider = new TaskSignalProvider();
677
+ if (disabledBuiltinTools.size > 0) {
678
+ const taskTools = Object.entries(taskSignalProvider.getTools?.() ?? {});
679
+ const enabledTaskTools = Object.fromEntries(taskTools.filter(([id]) => !disabledBuiltinTools.has(id)));
680
+ taskSignalProvider.getTools = () => enabledTaskTools;
681
+ }
682
+ const agentConnectionsSignalProvider = useCrossAgentSignals ? new AgentConnectionsSignalProvider(config?.agentConnections) : void 0;
683
+ const NO_PLUGIN_PROCESSORS = {
684
+ input: [],
685
+ output: []
686
+ };
687
+ let pluginProcessorReadWarned = false;
688
+ const pluginSignalLane = pluginManager ? new PluginSignalLane({
689
+ reservedProviderIds: [
690
+ taskSignalProvider.id,
691
+ ...agentConnectionsSignalProvider ? [agentConnectionsSignalProvider.id] : [],
692
+ ...githubSignals ? [githubSignals.id] : []
693
+ ],
694
+ onError: (message, error, pluginId) => pluginManager.reportPluginError({
695
+ pluginId,
696
+ message: error === void 0 ? message : `${message} ${error instanceof Error ? error.message : String(error)}`
697
+ })
698
+ }) : void 0;
699
+ let unsubscribePluginReload;
700
+ /**
701
+ * Plugin processors are read through a function so that enabling, disabling or
702
+ * updating a plugin takes effect on the next request rather than requiring a
703
+ * new agent. This runs before every LLM call, and also outside the request
704
+ * path when the Agent catalogues its configured processors — where a throw is
705
+ * swallowed into a debug log. So it only reads already-resolved state: no
706
+ * filesystem, no network, no construction, and it never throws.
707
+ */
708
+ const readPluginProcessors = () => {
709
+ try {
710
+ return pluginManager?.getPluginProcessors() ?? NO_PLUGIN_PROCESSORS;
711
+ } catch (error) {
712
+ if (!pluginProcessorReadWarned) {
713
+ pluginProcessorReadWarned = true;
714
+ console.warn("Failed to read plugin processors:", error);
715
+ }
716
+ return NO_PLUGIN_PROCESSORS;
717
+ }
718
+ };
719
+ const resolveTenantSessionModel = withCredentialTenantPreparation(async (ctx) => {
720
+ const controller = ctx.requestContext.get("controller");
721
+ const hasSessionLevel = isThinkingLevelSetting(controller?.state?.thinkingLevel);
722
+ return getDynamicModel(ctx, config?.settingsPath, {
723
+ modeless,
724
+ defaultThinkingLevel: hasSessionLevel ? void 0 : await config?.resolveDefaultThinkingLevel?.(ctx)
725
+ });
726
+ });
727
+ const baseCodeAgent = createCodingAgent({
728
+ id: CODE_AGENT_ID,
729
+ name: "Code Agent",
730
+ ...agentStreamsOff ? { durable: false } : {},
731
+ workspace: void 0,
732
+ ...knowledge ? {
733
+ knowledge,
734
+ scopes: ({ scopes, requestContext }) => {
735
+ const controller = requestContext.get("controller");
736
+ const session = resolveKnowledgeSessionScopes(controller?.state, knowledgeHostScopes);
737
+ return session.resolved ? [...scopes, ...session.scopes] : scopes;
738
+ }
739
+ } : {},
740
+ instructions: async ({ requestContext }) => {
741
+ const configured = config?.hostInstructions;
742
+ const hostInstructions = typeof configured === "function" ? await configured({ requestContext }) : configured;
743
+ return getDynamicInstructions({
744
+ requestContext,
745
+ hostInstructions,
746
+ coAuthor: config?.coAuthor,
747
+ hasSubagents: subagents.length > 0,
748
+ disabledBuiltinTools: config?.disableBuiltinTools,
749
+ planApprovalStartsGoal: config?.planApprovalStartsGoal,
750
+ plansDir: config?.plansDir,
751
+ disabledTools: config?.disabledTools
752
+ });
753
+ },
754
+ model: async (ctx) => ctx.requestContext.get("controller") ? resolveTenantSessionModel(ctx) : getDynamicModel(ctx, config?.settingsPath, { modeless }),
755
+ notifications: { deliveryPolicy: { decide: async (input) => {
756
+ const decision = defaultNotificationDeliveryDecision(input);
757
+ if (!input.record.resourceId) return decision;
758
+ const target = {
759
+ resourceId: input.record.resourceId,
760
+ threadId: input.record.threadId
761
+ };
762
+ const owner = decision.action === "deliver" || decision.action === "summarize" ? await resolveWakeOwner(target, notificationDispatchLeases) : await findWakeSession(controller, liveSessions, target, notificationDispatchLeases);
763
+ if (owner === FOREIGN_THREAD || owner === void 0) {
764
+ const wakesAtFirstSend = decision.action === "deliver" || decision.action === "queue";
765
+ const routedToOwner = readNotificationRoutingRequirement(input.record.metadata)?.requireClaimedOwner;
766
+ if (!wakesAtFirstSend || routedToOwner) return {
767
+ ...decision,
768
+ hold: true
769
+ };
770
+ return {
771
+ action: "defer",
772
+ deliverAt: input.now,
773
+ reason: decision.reason,
774
+ hold: true
775
+ };
776
+ }
777
+ const streamOptions = await getWakeStreamOptions({
778
+ resourceId: input.record.resourceId,
779
+ threadId: input.record.threadId,
780
+ owner
781
+ });
782
+ const withOptions = streamOptions ? {
783
+ ...decision,
784
+ streamOptions
785
+ } : decision;
786
+ if (!ownsNotificationDispatch) return withOptions;
787
+ return shouldHoldNotificationDelivery({
788
+ resourceId: input.record.resourceId,
789
+ scope: owner.scope,
790
+ ownedHere: true,
791
+ dispatcher: notificationDispatcher
792
+ }) ? {
793
+ ...withOptions,
794
+ hold: true
795
+ } : withOptions;
796
+ } } },
797
+ tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools, backgroundToolsEnabled, scheduleTools),
798
+ hooks: createToolHooks(hookManager, config?.postToolObserver),
799
+ ...config?.scorers ? { scorers: config.scorers } : {},
800
+ signals: [
801
+ taskSignalProvider,
802
+ ...agentConnectionsSignalProvider ? [agentConnectionsSignalProvider] : [],
803
+ ...githubSignals ? [githubSignals] : []
804
+ ],
805
+ goal: {
806
+ judge: withCredentialTenantPreparation((ctx) => getGoalJudgeModel(ctx, config?.settingsPath)),
807
+ maxRuns: globalSettings.models.goalMaxTurns ?? 50,
808
+ maxSteps: 1e3,
809
+ prompt: DEFAULT_GOAL_JUDGE_PROMPT,
810
+ tools: getGoalJudgeTools
811
+ },
812
+ inputProcessors: ({ requestContext }) => {
813
+ const resolveProcessors = (configured) => [
814
+ ...configured,
815
+ ...mastraCodeInputProcessors,
816
+ new AccountStartNoticeProcessor({ credentialStore: authStorage }),
817
+ ...readPluginProcessors().input.map((entry) => entry.value),
818
+ ...pluginSignalLane?.getInputProcessors() ?? []
819
+ ];
820
+ if (typeof config?.inputProcessors !== "function") return resolveProcessors([]);
821
+ const configured = config.inputProcessors({ requestContext });
822
+ return configured instanceof Promise ? configured.then(resolveProcessors) : resolveProcessors(configured);
823
+ },
824
+ outputProcessors: ({ requestContext }) => {
825
+ const resolveProcessors = (configured) => [
826
+ new CyberRefusalHandler(),
827
+ ...configured,
828
+ ...readPluginProcessors().output.map((entry) => entry.value),
829
+ ...pluginSignalLane?.getOutputProcessors() ?? []
830
+ ];
831
+ if (typeof config?.outputProcessors !== "function") return resolveProcessors(config?.outputProcessors ?? []);
832
+ const configured = config.outputProcessors({ requestContext });
833
+ return configured instanceof Promise ? configured.then(resolveProcessors) : resolveProcessors(configured);
834
+ },
835
+ errorProcessors: [
836
+ new ProviderHistoryCompat(),
837
+ new CyberRefusalHandler(),
838
+ new StreamErrorRetryProcessor({ matchers: [
839
+ {
840
+ match: isStreamCutAfterResponse,
841
+ maxRetries: 0
842
+ },
843
+ {
844
+ match: isBadRequestError,
845
+ maxRetries: 1,
846
+ delayMs: 2e3
847
+ },
848
+ {
849
+ match: isTransientConnectionError,
850
+ maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,
851
+ delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),
852
+ onRetry: ({ error, retryCount, delayMs, requestContext }) => emitTransientRetry(error, retryCount, delayMs, requestContext)
853
+ },
854
+ {
855
+ match: isTransientServerError,
856
+ maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,
857
+ delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),
858
+ onRetry: ({ error, retryCount, delayMs, requestContext }) => emitTransientRetry(error, retryCount, delayMs, requestContext)
859
+ }
860
+ ] }),
861
+ new AccountRotationProcessor({
862
+ credentialStore: authStorage,
863
+ maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES,
864
+ settingsPath: config?.settingsPath,
865
+ modeless,
866
+ resolveDefaultThinkingLevel: config?.resolveDefaultThinkingLevel
867
+ })
868
+ ],
869
+ maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES
870
+ });
871
+ const codeAgent = wrapExperimentalAgent(baseCodeAgent, experimentalAgent);
872
+ const planMode = createPlanMode(!disabledBuiltinTools.has("submit_plan"));
873
+ const defaultModes = [
874
+ {
875
+ ...buildMode,
876
+ metadata: {
877
+ ...buildMode.metadata,
878
+ color: mastraBrand.green
879
+ }
880
+ },
881
+ {
882
+ ...planMode,
883
+ metadata: {
884
+ ...planMode.metadata,
885
+ color: mastraBrand.purple
886
+ }
887
+ },
888
+ {
889
+ ...fastMode,
890
+ metadata: {
891
+ ...fastMode.metadata,
892
+ color: mastraBrand.orange
893
+ }
894
+ }
895
+ ];
896
+ const intervalHandlers = config?.intervalHandlers ?? [{
897
+ id: "gateway-sync",
898
+ intervalMs: 3e5,
899
+ immediate: false,
900
+ handler: () => syncGateways()
901
+ }];
902
+ const anthropicCred = authStorage.get("anthropic");
903
+ const openaiCred = authStorage.get("openai-codex");
904
+ const githubCopilotCred = authStorage.get("github-copilot");
905
+ const kimiCodingCred = authStorage.get("kimi-for-coding");
906
+ const startupAccess = {
907
+ anthropic: anthropicCred?.type === "oauth" ? "oauth" : anthropicCred?.type === "api_key" && anthropicCred.key.trim().length > 0 ? "apikey" : false,
908
+ openai: openaiCred?.type === "oauth" ? "oauth" : openaiCred?.type === "api_key" && openaiCred.key.trim().length > 0 ? "apikey" : false,
909
+ cerebras: process.env.CEREBRAS_API_KEY ? "apikey" : false,
910
+ google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? "apikey" : false,
911
+ deepseek: process.env.DEEPSEEK_API_KEY ? "apikey" : false,
912
+ "github-copilot": githubCopilotCred?.type === "oauth" ? "oauth" : false,
913
+ "kimi-for-coding": kimiCodingCred?.type === "oauth" && isKimiCodingDeviceId(kimiCodingCred.deviceId) ? "oauth" : kimiCodingCred?.type === "api_key" && kimiCodingCred.key.trim().length > 0 || Boolean(process.env.KIMI_API_KEY?.trim()) ? "apikey" : false
914
+ };
915
+ if (mgApiKey) {
916
+ if (!startupAccess.anthropic) startupAccess.anthropic = "apikey";
917
+ if (!startupAccess.openai) startupAccess.openai = "apikey";
918
+ }
919
+ try {
920
+ const registry = PROVIDER_REGISTRY;
921
+ for (const [provider, config] of Object.entries(registry)) {
922
+ if (startupAccess[provider] === "oauth" || startupAccess[provider] === "apikey") continue;
923
+ if (provider === "anthropic" || provider === "openai") continue;
924
+ const envVars = config?.apiKeyEnvVar;
925
+ if ((Array.isArray(envVars) ? envVars : envVars ? [envVars] : []).some((envVar) => process.env[envVar])) startupAccess[provider] = "apikey";
926
+ }
927
+ } catch {}
928
+ const builtinOmPacks = getAvailableOmPacks(startupAccess);
929
+ const effectiveDefaults = globalSettings.models.modeDefaults;
930
+ const effectiveObserverModel = resolveOmRoleModel(globalSettings, "observer", builtinOmPacks);
931
+ const effectiveReflectorModel = resolveOmRoleModel(globalSettings, "reflector", builtinOmPacks);
932
+ const observerModelSelection = globalSettings.models.observerModelSelection;
933
+ const reflectorModelSelection = globalSettings.models.reflectorModelSelection;
934
+ const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? void 0;
935
+ const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? void 0;
936
+ const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? void 0;
937
+ const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? "auto";
938
+ const modes = addPluginToolsToModeAllowlists(applyModeDefaultsToModes(config?.modes === false ? [buildMode] : config?.modes ?? defaultModes, effectiveDefaults), Object.keys(pluginTools));
939
+ const defaultModeId = modes.find((mode) => mode.metadata?.default === true)?.id ?? modes.find((mode) => mode.id === "build")?.id ?? modes[0]?.id;
940
+ if (!defaultModeId) throw new Error("MastraCode requires at least one mode");
941
+ const subagentModeMap = {
942
+ explore: "fast",
943
+ plan: "plan",
944
+ execute: "build"
945
+ };
946
+ const disabledTools = new Set(config?.disabledTools);
947
+ const subagents = (config?.subagents ?? []).map((definition) => ({
948
+ ...definition,
949
+ ...builtinSubagents.includes(definition) && { defaultModelId: modes.find((mode) => mode.id === subagentModeMap[definition.id])?.defaultModelId ?? modes.find((mode) => mode.id === defaultModeId)?.defaultModelId },
950
+ allowedControllerTools: definition.allowedControllerTools?.filter((name) => !disabledTools.has(name)),
951
+ allowedWorkspaceTools: definition.allowedWorkspaceTools?.filter((name) => !disabledTools.has(name)),
952
+ ...definition.tools && { tools: Object.fromEntries(Object.entries(definition.tools).filter(([name]) => !disabledTools.has(name))) }
953
+ }));
954
+ const globalInitialState = {};
955
+ if (!config?.disableSettingsOmSeed) {
956
+ if (observerModelSelection === "auto") globalInitialState.observerModelSelection = "auto";
957
+ else if (effectiveObserverModel) {
958
+ globalInitialState.observerModelId = effectiveObserverModel;
959
+ globalInitialState.observerModelSelection = effectiveObserverModel;
960
+ } else globalInitialState.observerModelSelection = "auto";
961
+ if (reflectorModelSelection === "auto") globalInitialState.reflectorModelSelection = "auto";
962
+ else if (effectiveReflectorModel) {
963
+ globalInitialState.reflectorModelId = effectiveReflectorModel;
964
+ globalInitialState.reflectorModelSelection = effectiveReflectorModel;
965
+ } else globalInitialState.reflectorModelSelection = "auto";
966
+ if (effectiveObservationThreshold !== void 0) globalInitialState.observationThreshold = effectiveObservationThreshold;
967
+ if (effectiveReflectionThreshold !== void 0) globalInitialState.reflectionThreshold = effectiveReflectionThreshold;
968
+ if (effectiveCavemanObservations !== void 0) globalInitialState.cavemanObservations = effectiveCavemanObservations;
969
+ if (effectiveObserveAttachments !== void 0) globalInitialState.observeAttachments = effectiveObserveAttachments;
970
+ }
971
+ if (globalSettings.preferences.yolo !== null) globalInitialState.yolo = globalSettings.preferences.yolo;
972
+ if (config?.omScope) globalInitialState.omScope = config.omScope;
973
+ for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) if (key === "default" || key === "_default") globalInitialState.subagentModelId = modelId;
974
+ else globalInitialState[`subagentModelId_${key}`] = modelId;
975
+ const typedStateSchema = stateSchema;
976
+ const backgroundCompletionEvents = backgroundToolsEnabled ? createBackgroundCompletionEvents() : void 0;
977
+ const defaultWorkspace = (args) => getDynamicWorkspace({
978
+ ...args,
979
+ backgroundToolsEnabled,
980
+ plansDir: config?.plansDir
981
+ });
982
+ let controller;
983
+ controller = new AgentController({
984
+ id: "mastra-code",
985
+ resourceId: project.resourceId,
986
+ storage,
987
+ ...backgroundToolsEnabled ? { backgroundTasks: {
988
+ enabled: true,
989
+ recoverStaleTasksOnStart: false,
990
+ notifyAgentOnFinish: false,
991
+ ...createBackgroundCompletionCallbacks(() => sessionRouter, backgroundCompletionEvents)
992
+ } } : {},
993
+ observability,
994
+ memory,
995
+ pubsub: signalsPubSub,
996
+ stateSchema: typedStateSchema,
997
+ omConfig: {
998
+ observerModel: "auto",
999
+ defaultObserverModelId: DEFAULT_OM_MODEL_ID,
1000
+ reflectorModel: "auto",
1001
+ defaultReflectorModelId: DEFAULT_OM_MODEL_ID,
1002
+ resolveAutoModelId: ({ currentModelId }) => resolveAutoOMModelId(currentModelId, canUseProvider)
1003
+ },
1004
+ agent: codeAgent,
1005
+ subagents,
1006
+ ...config?.disableBuiltinTools?.length ? { disableBuiltinTools: config.disableBuiltinTools } : {},
1007
+ resolveSubagentModel: (modelId, { requestContext }) => routesToOtherGateway(modelId, Object.values(controller.getMastra()?.listGateways() ?? {}), /* @__PURE__ */ new Set([
1008
+ mastraCodeGateway.id,
1009
+ amazonBedrockGateway.id,
1010
+ googleVertexGateway.id,
1011
+ githubCopilotGateway.id,
1012
+ "models.dev"
1013
+ ])) ? modelId : resolveModel(modelId, { requestContext }),
1014
+ gateways: [
1015
+ amazonBedrockGateway,
1016
+ googleVertexGateway,
1017
+ githubCopilotGateway,
1018
+ mastraCodeGateway
1019
+ ],
1020
+ workspace: config?.workspace ?? defaultWorkspace,
1021
+ browser: config?.browser,
1022
+ idGenerator: config?.idGenerator,
1023
+ toolCategoryResolver: getToolCategory,
1024
+ initialState: {
1025
+ projectPath: project.rootPath,
1026
+ projectName: project.name,
1027
+ gitBranch: project.gitBranch,
1028
+ pluginSkillPaths: loadedPlugins.flatMap((plugin) => plugin.status === "active" ? plugin.skillPaths ?? [] : []),
1029
+ pluginCommandPaths: loadedPlugins.flatMap((plugin) => plugin.status === "active" ? plugin.commandPaths ?? [] : []),
1030
+ pluginInstructions: loadedPlugins.flatMap((plugin) => plugin.status === "active" && plugin.instructions ? [plugin.instructions] : []),
1031
+ yolo: true,
1032
+ ...globalInitialState,
1033
+ ...config?.initialState,
1034
+ configDir
1035
+ },
1036
+ modes,
1037
+ intervalHandlers,
1038
+ modelUseCountProvider: () => loadSettings().modelUseCounts,
1039
+ modelUseCountTracker: (modelId) => {
1040
+ try {
1041
+ const settings = loadSettings();
1042
+ const { modelId: canonicalModelId } = parseCodexModelSelection(modelId);
1043
+ settings.modelUseCounts[canonicalModelId] = (settings.modelUseCounts[canonicalModelId] ?? 0) + 1;
1044
+ saveSettings(settings);
1045
+ } catch (error) {
1046
+ console.error("Failed to persist model usage count", error);
1047
+ }
1048
+ },
1049
+ threadLock: crossProcessPubSub ? void 0 : {
1050
+ acquire: acquireThreadLock,
1051
+ release: releaseThreadLock
1052
+ }
1053
+ });
1054
+ controller.onSessionCreated((session) => {
1055
+ liveSessions.add(session);
1056
+ });
1057
+ controller.onSessionDeleted((session) => {
1058
+ liveSessions.delete(session);
1059
+ });
1060
+ const sessionPeerCleanup = /* @__PURE__ */ new WeakMap();
1061
+ if (useCrossAgentSignals) {
1062
+ controller.onSessionCreated(async (session) => {
1063
+ const advertisement = createSessionThreadAdvertisement({
1064
+ session,
1065
+ controller,
1066
+ projectName: project.name
1067
+ });
1068
+ sessionPeerCleanup.set(session, () => advertisement.close());
1069
+ const initialThreadId = session.thread.getId();
1070
+ if (initialThreadId) await Promise.race([advertisement.claim(initialThreadId), new Promise((resolve) => {
1071
+ setTimeout(resolve, 5e3).unref?.();
1072
+ })]);
1073
+ }, { blocking: true });
1074
+ controller.onSessionDeleted((session) => {
1075
+ sessionPeerCleanup.get(session)?.();
1076
+ sessionPeerCleanup.delete(session);
1077
+ });
1078
+ }
1079
+ pluginRuntimeController = controller;
1080
+ if (pluginSignalLane && pluginManager) {
1081
+ pluginSignalLane.sync(pluginManager.getPluginSignalProviders());
1082
+ unsubscribePluginReload = pluginManager.onReload(() => pluginSignalLane.sync(pluginManager.getPluginSignalProviders()));
1083
+ }
1084
+ return {
1085
+ controller,
1086
+ storage,
1087
+ storageMaintenance,
1088
+ createKnowledgeInspector: (session, knowledgeKey) => createKnowledgeInspector({
1089
+ knowledge: knowledgeKey ?? knowledge,
1090
+ mastra: controller.getMastra(),
1091
+ session,
1092
+ hostScopes: knowledgeHostScopes
1093
+ }),
1094
+ observability,
1095
+ observabilityExports: Boolean(observabilityDomain || cloudObservabilityConfig),
1096
+ memory,
1097
+ knowledge,
1098
+ knowledgeKey,
1099
+ mcpManager,
1100
+ hookManager,
1101
+ pluginManager,
1102
+ loadedPlugins,
1103
+ pluginTools,
1104
+ signalsPubSub,
1105
+ authStorage,
1106
+ resolveModel,
1107
+ storageWarning,
1108
+ observabilityWarning,
1109
+ builtinOmPacks,
1110
+ effectiveDefaults,
1111
+ githubSignals,
1112
+ backgroundToolsEnabled,
1113
+ backgroundCompletionEvents,
1114
+ sessionId,
1115
+ ownerId,
1116
+ projectPath: project.rootPath,
1117
+ codeAgent,
1118
+ setActiveSession: (session) => {
1119
+ activeSession = session;
1120
+ },
1121
+ /**
1122
+ * Starts the signal providers contributed by plugins. Called by the
1123
+ * composition layer once the controller is inited, because that is when a
1124
+ * Mastra instance exists — a provider without one has no storage, and
1125
+ * nothing else will hand it one: the Agent propagates Mastra only to the
1126
+ * providers in its own `signals` array, which these deliberately are not in.
1127
+ */
1128
+ startPluginSignalProviders: () => {
1129
+ const mastra = controller.getMastra();
1130
+ if (!pluginSignalLane || !mastra) return;
1131
+ pluginSignalLane.setMastra(mastra, codeAgent);
1132
+ },
1133
+ /**
1134
+ * Stops every plugin-contributed signal provider and stops listening for
1135
+ * plugin reloads. The inverse of `startPluginSignalProviders`, for an
1136
+ * embedder that is done with this controller: a `pluginManager` shared
1137
+ * across controllers (`MastraCodeConfig.pluginManager`) outlives any one of
1138
+ * them, so without this its providers keep polling and its reload listener
1139
+ * keeps firing for a controller that is gone.
1140
+ */
1141
+ stopPluginSignalProviders: () => {
1142
+ unsubscribePluginReload?.();
1143
+ unsubscribePluginReload = void 0;
1144
+ pluginSignalLane?.stopAll();
1145
+ },
1146
+ /** Process-local `/schedules` scheduler. Call `stop()` on shutdown. */
1147
+ threadScheduler,
1148
+ /**
1149
+ * Starts delivering the due notifications of this controller's sessions'
1150
+ * resources from this process. Called by the composition layer once the
1151
+ * controller is inited. A no-op when the embedder configured its own
1152
+ * PubSub, whose shared dispatch schedule keeps delivering everything.
1153
+ */
1154
+ startNotificationDispatch: () => {
1155
+ if (ownsNotificationDispatch) notificationDispatcher.start();
1156
+ },
1157
+ /**
1158
+ * Stops advertising every live session's threads and releases their
1159
+ * ownership claims. Call first on shutdown: a claim otherwise stays held
1160
+ * (and renewed) through the rest of teardown, so a restarted process cannot
1161
+ * claim the thread — and peers cannot reach it — until this one exits.
1162
+ */
1163
+ releaseThreadClaims: () => {
1164
+ for (const session of liveSessions) {
1165
+ sessionPeerCleanup.get(session)?.();
1166
+ sessionPeerCleanup.delete(session);
1167
+ }
1168
+ },
1169
+ /** Stops this process's notification dispatch and releases its leases. Call on shutdown. */
1170
+ stopNotificationDispatch: async () => {
1171
+ await notificationDispatcher.stop();
1172
+ await dispatchLeasePubSub?.close();
1173
+ },
1174
+ /**
1175
+ * Hands Mastra to the statically configured input processors.
1176
+ *
1177
+ * The Agent does this itself, but only for processors configured as a
1178
+ * plain array (`Array.isArray` in `__registerMastra`). This lane is a
1179
+ * function so plugins can contribute to it, which takes those processors
1180
+ * out of that branch — including any an embedder passed as
1181
+ * `config.inputProcessors`, some of which need Mastra to work at all
1182
+ * (`CostGuardProcessor` reads observability storage there). Doing it here
1183
+ * keeps that unchanged.
1184
+ *
1185
+ * Plugin processors are deliberately not included: they come and go with
1186
+ * their plugin, and the registry keeps the first instance registered under
1187
+ * an id forever, which would leave a retired instance behind. Plugins
1188
+ * reach Mastra through `getController()` on the plugin context instead.
1189
+ */
1190
+ registerConfiguredProcessorsWithMastra: () => {
1191
+ const mastra = controller.getMastra();
1192
+ if (!mastra) return;
1193
+ for (const processor of mastraCodeInputProcessors) {
1194
+ mastra.addProcessor(processor);
1195
+ mastra.addProcessorConfiguration(processor, CODE_AGENT_ID, "input");
1196
+ }
1197
+ }
1198
+ };
1199
+ }
1200
+ /**
1201
+ * Wires the session-scoped concerns MastraCode layers on top of a Session:
1202
+ * hookManager thread-id sync, GitHub PR polling for the current thread, and
1203
+ * per-thread persistence of the mastracode-only `/om` settings.
1204
+ *
1205
+ * Used by {@link bootLocalAgentController} for the single local session. A server can
1206
+ * call this for any session it mints if it wants the same background wiring.
1207
+ */
1208
+ async function wireSessionConcerns(base, session) {
1209
+ const { hookManager, githubSignals } = base;
1210
+ base.setActiveSession(session);
1211
+ if (hookManager) session.subscribe((event) => {
1212
+ if (event.type === "thread_changed") hookManager.setSessionId(event.threadId);
1213
+ else if (event.type === "thread_created") hookManager.setSessionId(event.thread.id);
1214
+ });
1215
+ if (githubSignals) {
1216
+ const startGithubPollingForCurrentThread = async (threadId) => {
1217
+ if (!threadId) return;
1218
+ githubSignals.stopAllPolling();
1219
+ try {
1220
+ const thread = (await session.thread.list({ allResources: true })).find((item) => item.id === threadId);
1221
+ await githubSignals.startPollingForThread({
1222
+ threadId,
1223
+ resourceId: thread?.resourceId ?? session.identity.getResourceId()
1224
+ }, { pollImmediately: true });
1225
+ } catch (error) {
1226
+ console.warn("Failed to start GitHub PR polling:", error);
1227
+ }
1228
+ };
1229
+ session.subscribe((event) => {
1230
+ if (event.type === "thread_changed") startGithubPollingForCurrentThread(event.threadId);
1231
+ else if (event.type === "thread_created") startGithubPollingForCurrentThread(event.thread.id);
1232
+ });
1233
+ startGithubPollingForCurrentThread(session.thread.getId());
1234
+ }
1235
+ const omThreadStateSession = session;
1236
+ attachOMThreadStatePersistence(omThreadStateSession);
1237
+ await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {});
1238
+ }
1239
+ /**
1240
+ * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its
1241
+ * own internal Mastra via `init()`, and mint the single eager session that all
1242
+ * work in this process runs through. The AgentController owns no session of its own.
1243
+ */
1244
+ async function bootLocalAgentController(config) {
1245
+ const base = await createMastraCodeAgentController(config);
1246
+ const { controller, sessionId, ownerId, projectPath, codeAgent, mcpManager } = base;
1247
+ await controller.init();
1248
+ validateExperimentalAgent(codeAgent, controller.getMastra());
1249
+ const mastra = controller.getMastra();
1250
+ registerSelectedKnowledge(mastra, base.knowledgeKey, base.knowledge);
1251
+ if (mastra) await registerWorkflowBuilderPrimitives(mastra, {
1252
+ projectPath,
1253
+ codeAgent,
1254
+ mcpManager
1255
+ });
1256
+ await mastra?.startWorkers();
1257
+ base.registerConfiguredProcessorsWithMastra();
1258
+ base.startPluginSignalProviders();
1259
+ base.startNotificationDispatch();
1260
+ const session = await controller.createSession({
1261
+ id: sessionId,
1262
+ ownerId,
1263
+ createInitialThread: config?.createInitialThread
1264
+ });
1265
+ await wireSessionConcerns(base, session);
1266
+ let knowledgeInspector;
1267
+ let knowledgeInspectorUnavailableReason;
1268
+ if (!base.knowledge) knowledgeInspectorUnavailableReason = "Knowledge is off. Turn it on in /settings, or pass `knowledge` to createMastraCode.";
1269
+ else try {
1270
+ knowledgeInspector = await base.createKnowledgeInspector(session);
1271
+ if (!knowledgeInspector) knowledgeInspectorUnavailableReason = "Knowledge inspection requires a configured Knowledge runtime.";
1272
+ } catch (error) {
1273
+ knowledgeInspectorUnavailableReason = `Knowledge is unavailable: ${error instanceof Error ? error.message : String(error)}`;
1274
+ }
1275
+ return {
1276
+ ...base,
1277
+ session,
1278
+ knowledgeInspector,
1279
+ knowledgeInspectorUnavailableReason
1280
+ };
1281
+ }
1282
+ /**
1283
+ * Registers the selected Knowledge on a Mastra built outside `mastraArgs` (the
1284
+ * controller's internal Mastra, or a caller-owned one) so keyed lookups resolve
1285
+ * it and an instance without its own storage inherits the Mastra's.
1286
+ */
1287
+ function registerSelectedKnowledge(mastra, key, knowledge) {
1288
+ if (!mastra || !knowledge) return;
1289
+ const existing = mastra.listKnowledge()[key];
1290
+ if (existing === knowledge) return;
1291
+ if (existing) throw new Error(`This Mastra already registers a different Knowledge instance under "${key}".`);
1292
+ mastra.addKnowledge(knowledge, key);
1293
+ }
1294
+ /**
1295
+ * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a
1296
+ * server-owned Mastra, THEN init it. Registering before `init()` is what makes
1297
+ * the controller inherit the server's Mastra (storage, agents, gateways) instead of
1298
+ * spinning up its own internal one — there is a single shared Mastra.
1299
+ *
1300
+ * No eager session is minted: each client (browser or terminal) creates/resumes
1301
+ * its own isolated session via `controller.createSession({ resourceId })`, so one
1302
+ * server can drive many concurrent users.
1303
+ *
1304
+ * Pass an existing `mastra` to mount onto a Mastra that already hosts other
1305
+ * primitives; otherwise a Mastra is created that owns the controller's storage so
1306
+ * durability is configured in one place.
1307
+ */
1308
+ async function mountAgentControllerOnMastra(config) {
1309
+ const prepared = await prepareAgentControllerMount(config);
1310
+ if (config?.mastra) {
1311
+ prepared.base.controller.__registerMastra(config.mastra);
1312
+ registerSelectedKnowledge(config.mastra, prepared.base.knowledgeKey, prepared.base.knowledge);
1313
+ await prepared.finalize();
1314
+ return {
1315
+ ...prepared.base,
1316
+ mastra: config.mastra
1317
+ };
1318
+ }
1319
+ const mastra = new Mastra(prepared.mastraArgs);
1320
+ await prepared.finalize();
1321
+ return {
1322
+ ...prepared.base,
1323
+ mastra
1324
+ };
1325
+ }
1326
+ /**
1327
+ * Assemble everything needed to construct the server-owned Mastra WITHOUT
1328
+ * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can
1329
+ * run the `new Mastra(...)` literal in its own module. The deployer's
1330
+ * `checkConfigExport` Babel plugin only marks the config valid when it finds a
1331
+ * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the
1332
+ * construction inside this helper would trip the "Invalid Mastra config" warning.
1333
+ *
1334
+ * Returns the constructor args plus a `finalize()` that runs the post-construct
1335
+ * boot (`controller.init()` + `startWorkers()`). The controller is registered on
1336
+ * the Mastra via the `agentControllers` arg at construction time.
1337
+ */
1338
+ async function prepareAgentControllerMount(config) {
1339
+ const base = await createMastraCodeAgentController(config);
1340
+ const { controller, storage, authStorage, projectPath, codeAgent, mcpManager, backgroundToolsEnabled, backgroundCompletionEvents } = base;
1341
+ const controllerId = config?.controllerId ?? controller.id;
1342
+ const apiRoutes = config?.buildApiRoutes?.({
1343
+ controller,
1344
+ authStorage
1345
+ });
1346
+ const extraServerConfig = config?.buildServerConfig?.({
1347
+ controller,
1348
+ authStorage
1349
+ });
1350
+ const weOwnTheMastra = !config?.mastra;
1351
+ const serverConfig = {
1352
+ ...extraServerConfig,
1353
+ ...apiRoutes?.length ? { apiRoutes } : {}
1354
+ };
1355
+ const mastraArgs = {
1356
+ agentControllers: { [controllerId]: controller },
1357
+ storage,
1358
+ ...base.observabilityExports ? { observability: base.observability } : {},
1359
+ ...backgroundToolsEnabled ? { backgroundTasks: {
1360
+ enabled: true,
1361
+ recoverStaleTasksOnStart: false,
1362
+ notifyAgentOnFinish: false,
1363
+ ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents)
1364
+ } } : {},
1365
+ ...base.knowledge ? { knowledge: { [base.knowledgeKey]: base.knowledge } } : {},
1366
+ ...base.signalsPubSub ? { pubsub: base.signalsPubSub } : {},
1367
+ ...Object.keys(serverConfig).length ? { server: serverConfig } : {}
1368
+ };
1369
+ const finalize = async () => {
1370
+ await controller.init();
1371
+ validateExperimentalAgent(codeAgent, controller.getMastra());
1372
+ setCredentialLogger(controller.getMastra()?.getLogger());
1373
+ if (weOwnTheMastra) {
1374
+ const mastra = controller.getMastra();
1375
+ if (mastra) await registerWorkflowBuilderPrimitives(mastra, {
1376
+ projectPath,
1377
+ codeAgent,
1378
+ mcpManager
1379
+ });
1380
+ }
1381
+ await controller.getMastra()?.startWorkers();
1382
+ base.registerConfiguredProcessorsWithMastra();
1383
+ base.startPluginSignalProviders();
1384
+ base.startNotificationDispatch();
1385
+ };
1386
+ return {
1387
+ base,
1388
+ mastraArgs,
1389
+ finalize
1390
+ };
1391
+ }
1392
+ /**
1393
+ * Back-compat alias. Historically `createMastraCode` built and booted a local
1394
+ * controller with a single session; that behavior now lives in
1395
+ * {@link bootLocalAgentController}. New code should call the explicit factory for its
1396
+ * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).
1397
+ */
1398
+ const createMastraCode = bootLocalAgentController;
1399
+ export { KnowledgeInspectorError, LOCAL_KNOWLEDGE_ORG_ID, autoApprovePolicy, bootLocalAgentController, builtinSubagents, createAuthStorage, createKnowledgeInspector, createMastraCode, createMastraCodeAgentController, denyPolicy, formatHuman, formatJsonl, hasHeadlessFlag, mountAgentControllerOnMastra, permissionModeToPolicy, prepareAgentControllerMount, renderJsonResult, renderTextResult, resolveCloudObservabilityConfig, resolveSubagentsSetting, runMC, runMCCli, wireSessionConcerns };