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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +284 -0
  3. package/dist/acp/agent.d.ts +48 -0
  4. package/dist/acp/agent.js +414 -0
  5. package/dist/acp/errors.d.ts +3 -0
  6. package/dist/acp/errors.js +11 -0
  7. package/dist/acp/event-mapper.d.ts +28 -0
  8. package/dist/acp/event-mapper.js +274 -0
  9. package/dist/acp/index.d.ts +9 -0
  10. package/dist/acp/index.js +21 -0
  11. package/dist/acp/runtime.d.ts +5 -0
  12. package/dist/acp/runtime.js +91 -0
  13. package/dist/acp/server.d.ts +4 -0
  14. package/dist/acp/server.js +35 -0
  15. package/dist/acp/skills.d.ts +6 -0
  16. package/dist/acp/skills.js +30 -0
  17. package/dist/acp.d.ts +2 -0
  18. package/dist/acp.js +1 -0
  19. package/dist/agent-connections/messaging-processor.d.ts +17 -0
  20. package/dist/agent-connections/messaging-processor.js +131 -0
  21. package/dist/agent-connections/ownership.d.ts +24 -0
  22. package/dist/agent-connections/ownership.js +96 -0
  23. package/dist/agent-connections/registry.d.ts +20 -0
  24. package/dist/agent-connections/registry.js +167 -0
  25. package/dist/agent-connections/session-advertisement.d.ts +27 -0
  26. package/dist/agent-connections/session-advertisement.js +86 -0
  27. package/dist/agent-connections/signal-provider.d.ts +141 -0
  28. package/dist/agent-connections/signal-provider.js +35 -0
  29. package/dist/agent-connections/state-processor.d.ts +23 -0
  30. package/dist/agent-connections/state-processor.js +270 -0
  31. package/dist/agent-connections/thread-state.d.ts +41 -0
  32. package/dist/agent-connections/thread-state.js +157 -0
  33. package/dist/agent-connections/tools.d.ts +133 -0
  34. package/dist/agent-connections/tools.js +616 -0
  35. package/dist/agent-connections/types.d.ts +99 -0
  36. package/dist/agent-connections/types.js +4 -0
  37. package/dist/agent-connections/untrusted-text.d.ts +5 -0
  38. package/dist/agent-connections/untrusted-text.js +19 -0
  39. package/dist/agents/background-completion-events.d.ts +16 -0
  40. package/dist/agents/background-completion-events.js +16 -0
  41. package/dist/agents/background-completion.d.ts +22 -0
  42. package/dist/agents/background-completion.js +73 -0
  43. package/dist/agents/context-audit.d.ts +84 -0
  44. package/dist/agents/context-audit.js +115 -0
  45. package/dist/agents/credential-resolver.d.ts +74 -0
  46. package/dist/agents/credential-resolver.js +142 -0
  47. package/dist/agents/custom-provider-source.d.ts +35 -0
  48. package/dist/agents/custom-provider-source.js +22 -0
  49. package/dist/agents/fastembed-subprocess.d.ts +52 -0
  50. package/dist/agents/fastembed-subprocess.js +282 -0
  51. package/dist/agents/instructions.d.ts +42 -0
  52. package/dist/agents/instructions.js +69 -0
  53. package/dist/agents/mastracode-gateway.d.ts +85 -0
  54. package/dist/agents/mastracode-gateway.js +500 -0
  55. package/dist/agents/memory.d.ts +36 -0
  56. package/dist/agents/memory.js +248 -0
  57. package/dist/agents/model.d.ts +158 -0
  58. package/dist/agents/model.js +382 -0
  59. package/dist/agents/modes/build.d.ts +12 -0
  60. package/dist/agents/modes/build.js +33 -0
  61. package/dist/agents/modes/explore.d.ts +10 -0
  62. package/dist/agents/modes/explore.js +25 -0
  63. package/dist/agents/modes/plan.d.ts +8 -0
  64. package/dist/agents/modes/plan.js +43 -0
  65. package/dist/agents/prompts/agent-instructions.d.ts +122 -0
  66. package/dist/agents/prompts/agent-instructions.js +617 -0
  67. package/dist/agents/prompts/build.d.ts +12 -0
  68. package/dist/agents/prompts/build.js +73 -0
  69. package/dist/agents/prompts/fast.d.ts +5 -0
  70. package/dist/agents/prompts/fast.js +23 -0
  71. package/dist/agents/prompts/index.d.ts +61 -0
  72. package/dist/agents/prompts/index.js +141 -0
  73. package/dist/agents/prompts/model.d.ts +5 -0
  74. package/dist/agents/prompts/model.js +20 -0
  75. package/dist/agents/prompts/plan.d.ts +11 -0
  76. package/dist/agents/prompts/plan.js +132 -0
  77. package/dist/agents/prompts/tool-guidance.d.ts +18 -0
  78. package/dist/agents/prompts/tool-guidance.js +158 -0
  79. package/dist/agents/sandbox-filesystem.d.ts +232 -0
  80. package/dist/agents/sandbox-filesystem.js +851 -0
  81. package/dist/agents/subagents/execute.d.ts +3 -0
  82. package/dist/agents/subagents/execute.js +24 -0
  83. package/dist/agents/subagents/explore.d.ts +3 -0
  84. package/dist/agents/subagents/explore.js +15 -0
  85. package/dist/agents/subagents/index.d.ts +6 -0
  86. package/dist/agents/subagents/index.js +15 -0
  87. package/dist/agents/subagents/plan.d.ts +3 -0
  88. package/dist/agents/subagents/plan.js +15 -0
  89. package/dist/agents/thread-caveman-state.d.ts +17 -0
  90. package/dist/agents/thread-caveman-state.js +104 -0
  91. package/dist/agents/tool-availability.d.ts +17 -0
  92. package/dist/agents/tool-availability.js +134 -0
  93. package/dist/agents/tools.d.ts +37 -0
  94. package/dist/agents/tools.js +154 -0
  95. package/dist/agents/workflow-builder-agent.d.ts +2 -0
  96. package/dist/agents/workflow-builder-agent.js +79 -0
  97. package/dist/agents/workspace.d.ts +35 -0
  98. package/dist/agents/workspace.js +207 -0
  99. package/dist/analytics.d.ts +18 -0
  100. package/dist/analytics.js +159 -0
  101. package/dist/auth/account-rotation-processor.d.ts +210 -0
  102. package/dist/auth/account-rotation-processor.js +662 -0
  103. package/dist/auth/account-routing-context.d.ts +17 -0
  104. package/dist/auth/account-routing-context.js +38 -0
  105. package/dist/auth/authorization-input.d.ts +16 -0
  106. package/dist/auth/authorization-input.js +39 -0
  107. package/dist/auth/device-code.d.ts +93 -0
  108. package/dist/auth/device-code.js +126 -0
  109. package/dist/auth/index.d.ts +13 -0
  110. package/dist/auth/index.js +9 -0
  111. package/dist/auth/pkce.d.ts +13 -0
  112. package/dist/auth/pkce.js +29 -0
  113. package/dist/auth/provider-auth-error.d.ts +24 -0
  114. package/dist/auth/provider-auth-error.js +44 -0
  115. package/dist/auth/providers/anthropic.d.ts +40 -0
  116. package/dist/auth/providers/anthropic.js +117 -0
  117. package/dist/auth/providers/github-copilot.d.ts +154 -0
  118. package/dist/auth/providers/github-copilot.js +359 -0
  119. package/dist/auth/providers/kimi-coding.d.ts +38 -0
  120. package/dist/auth/providers/kimi-coding.js +225 -0
  121. package/dist/auth/providers/openai-codex.d.ts +141 -0
  122. package/dist/auth/providers/openai-codex.js +531 -0
  123. package/dist/auth/providers/xai.d.ts +64 -0
  124. package/dist/auth/providers/xai.js +223 -0
  125. package/dist/auth/storage.d.ts +222 -0
  126. package/dist/auth/storage.js +805 -0
  127. package/dist/auth/types.d.ts +164 -0
  128. package/dist/auth/types.js +1 -0
  129. package/dist/clipboard/index.d.ts +26 -0
  130. package/dist/clipboard/index.js +224 -0
  131. package/dist/constants.d.ts +29 -0
  132. package/dist/constants.js +34 -0
  133. package/dist/error-classification.d.ts +10 -0
  134. package/dist/error-classification.js +19 -0
  135. package/dist/evals/context-builder.d.ts +41 -0
  136. package/dist/evals/context-builder.js +156 -0
  137. package/dist/evals/index.d.ts +4 -0
  138. package/dist/evals/index.js +5 -0
  139. package/dist/evals/scorers/classify-command.d.ts +30 -0
  140. package/dist/evals/scorers/classify-command.js +61 -0
  141. package/dist/evals/scorers/efficiency.d.ts +44 -0
  142. package/dist/evals/scorers/efficiency.js +256 -0
  143. package/dist/evals/scorers/extract-tools.d.ts +25 -0
  144. package/dist/evals/scorers/extract-tools.js +57 -0
  145. package/dist/evals/scorers/index.d.ts +3 -0
  146. package/dist/evals/scorers/index.js +3 -0
  147. package/dist/evals/scorers/outcome.d.ts +49 -0
  148. package/dist/evals/scorers/outcome.js +360 -0
  149. package/dist/experimental-agent.d.ts +19 -0
  150. package/dist/experimental-agent.js +45 -0
  151. package/dist/factory/client.d.ts +44 -0
  152. package/dist/factory/client.js +110 -0
  153. package/dist/factory/remote-controller.d.ts +34 -0
  154. package/dist/factory/remote-controller.js +40 -0
  155. package/dist/factory/remote-session.d.ts +210 -0
  156. package/dist/factory/remote-session.js +415 -0
  157. package/dist/goal-manager.d.ts +114 -0
  158. package/dist/goal-manager.js +351 -0
  159. package/dist/goal-signal.d.ts +14 -0
  160. package/dist/goal-signal.js +14 -0
  161. package/dist/headless/cli.d.ts +55 -0
  162. package/dist/headless/cli.js +261 -0
  163. package/dist/headless/flags.d.ts +33 -0
  164. package/dist/headless/flags.js +207 -0
  165. package/dist/headless/format.d.ts +41 -0
  166. package/dist/headless/format.js +94 -0
  167. package/dist/headless/index.d.ts +25 -0
  168. package/dist/headless/index.js +6 -0
  169. package/dist/headless/policy.d.ts +17 -0
  170. package/dist/headless/policy.js +39 -0
  171. package/dist/headless/run-mc.d.ts +7 -0
  172. package/dist/headless/run-mc.js +438 -0
  173. package/dist/headless/types.d.ts +175 -0
  174. package/dist/headless/types.js +16 -0
  175. package/dist/hooks/config.d.ts +11 -0
  176. package/dist/hooks/config.js +77 -0
  177. package/dist/hooks/executor.d.ts +13 -0
  178. package/dist/hooks/executor.js +128 -0
  179. package/dist/hooks/index.d.ts +6 -0
  180. package/dist/hooks/index.js +5 -0
  181. package/dist/hooks/manager.d.ts +75 -0
  182. package/dist/hooks/manager.js +289 -0
  183. package/dist/hooks/types.d.ts +180 -0
  184. package/dist/hooks/types.js +5 -0
  185. package/dist/index.d.ts +537 -0
  186. package/dist/index.js +1399 -0
  187. package/dist/ipc/ipc-reporter.d.ts +14 -0
  188. package/dist/ipc/ipc-reporter.js +18 -0
  189. package/dist/knowledge-inspector.d.ts +139 -0
  190. package/dist/knowledge-inspector.js +533 -0
  191. package/dist/knowledge-scope-id.d.ts +7 -0
  192. package/dist/knowledge-scope-id.js +10 -0
  193. package/dist/knowledge-scope.d.ts +41 -0
  194. package/dist/knowledge-scope.js +85 -0
  195. package/dist/lsp/client.d.ts +56 -0
  196. package/dist/lsp/client.js +248 -0
  197. package/dist/lsp/index.d.ts +4 -0
  198. package/dist/lsp/index.js +4 -0
  199. package/dist/lsp/language.d.ts +9 -0
  200. package/dist/lsp/language.js +41 -0
  201. package/dist/lsp/manager.d.ts +34 -0
  202. package/dist/lsp/manager.js +79 -0
  203. package/dist/lsp/server.d.ts +27 -0
  204. package/dist/lsp/server.js +158 -0
  205. package/dist/lsp/workspace.d.ts +9 -0
  206. package/dist/lsp/workspace.js +52 -0
  207. package/dist/mcp/config.d.ts +77 -0
  208. package/dist/mcp/config.js +313 -0
  209. package/dist/mcp/index.d.ts +6 -0
  210. package/dist/mcp/index.js +3 -0
  211. package/dist/mcp/manager.d.ts +104 -0
  212. package/dist/mcp/manager.js +693 -0
  213. package/dist/mcp/state.d.ts +35 -0
  214. package/dist/mcp/state.js +94 -0
  215. package/dist/mcp/types.d.ts +139 -0
  216. package/dist/mcp/types.js +1 -0
  217. package/dist/onboarding/custom-packs.d.ts +7 -0
  218. package/dist/onboarding/custom-packs.js +17 -0
  219. package/dist/onboarding/custom-providers.d.ts +4 -0
  220. package/dist/onboarding/custom-providers.js +27 -0
  221. package/dist/onboarding/index.d.ts +5 -0
  222. package/dist/onboarding/index.js +3 -0
  223. package/dist/onboarding/om-settings.d.ts +47 -0
  224. package/dist/onboarding/om-settings.js +80 -0
  225. package/dist/onboarding/pack-activation.d.ts +43 -0
  226. package/dist/onboarding/pack-activation.js +105 -0
  227. package/dist/onboarding/packs.d.ts +106 -0
  228. package/dist/onboarding/packs.js +283 -0
  229. package/dist/onboarding/settings.d.ts +563 -0
  230. package/dist/onboarding/settings.js +1110 -0
  231. package/dist/permissions.d.ts +55 -0
  232. package/dist/permissions.js +139 -0
  233. package/dist/platform/index.d.ts +74 -0
  234. package/dist/platform/index.js +199 -0
  235. package/dist/plugin.d.ts +156 -0
  236. package/dist/plugin.js +27 -0
  237. package/dist/plugins/dependencies.d.ts +9 -0
  238. package/dist/plugins/dependencies.js +84 -0
  239. package/dist/plugins/install.d.ts +21 -0
  240. package/dist/plugins/install.js +187 -0
  241. package/dist/plugins/loader.d.ts +25 -0
  242. package/dist/plugins/loader.js +264 -0
  243. package/dist/plugins/manager.d.ts +115 -0
  244. package/dist/plugins/manager.js +507 -0
  245. package/dist/plugins/manifest.d.ts +14 -0
  246. package/dist/plugins/manifest.js +47 -0
  247. package/dist/plugins/package-link.d.ts +3 -0
  248. package/dist/plugins/package-link.js +58 -0
  249. package/dist/plugins/paths.d.ts +10 -0
  250. package/dist/plugins/paths.js +22 -0
  251. package/dist/plugins/registry.d.ts +8 -0
  252. package/dist/plugins/registry.js +109 -0
  253. package/dist/plugins/scaffold.d.ts +10 -0
  254. package/dist/plugins/scaffold.js +115 -0
  255. package/dist/plugins/signal-lane.d.ts +59 -0
  256. package/dist/plugins/signal-lane.js +163 -0
  257. package/dist/plugins/types.d.ts +95 -0
  258. package/dist/plugins/types.js +1 -0
  259. package/dist/process-memory-diagnostics.d.ts +136 -0
  260. package/dist/process-memory-diagnostics.js +497 -0
  261. package/dist/processors/plan-rejection-abort.d.ts +16 -0
  262. package/dist/processors/plan-rejection-abort.js +62 -0
  263. package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
  264. package/dist/providers/amazon-bedrock-gateway.js +142 -0
  265. package/dist/providers/amazon-bedrock.d.ts +28 -0
  266. package/dist/providers/amazon-bedrock.js +99 -0
  267. package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
  268. package/dist/providers/anthropic-prompt-cache.js +8 -0
  269. package/dist/providers/anthropic-thinking.d.ts +5 -0
  270. package/dist/providers/anthropic-thinking.js +22 -0
  271. package/dist/providers/claude-max.d.ts +67 -0
  272. package/dist/providers/claude-max.js +232 -0
  273. package/dist/providers/github-copilot-gateway.d.ts +35 -0
  274. package/dist/providers/github-copilot-gateway.js +58 -0
  275. package/dist/providers/github-copilot.d.ts +60 -0
  276. package/dist/providers/github-copilot.js +320 -0
  277. package/dist/providers/google-thinking.d.ts +31 -0
  278. package/dist/providers/google-thinking.js +64 -0
  279. package/dist/providers/google-vertex-gateway.d.ts +23 -0
  280. package/dist/providers/google-vertex-gateway.js +49 -0
  281. package/dist/providers/google-vertex.d.ts +6 -0
  282. package/dist/providers/google-vertex.js +51 -0
  283. package/dist/providers/kimi-coding.d.ts +14 -0
  284. package/dist/providers/kimi-coding.js +80 -0
  285. package/dist/providers/model-ids.d.ts +53 -0
  286. package/dist/providers/model-ids.js +132 -0
  287. package/dist/providers/openai-codex.d.ts +114 -0
  288. package/dist/providers/openai-codex.js +427 -0
  289. package/dist/providers/provider-thinking.d.ts +23 -0
  290. package/dist/providers/provider-thinking.js +61 -0
  291. package/dist/providers/thinking-request.d.ts +14 -0
  292. package/dist/providers/thinking-request.js +87 -0
  293. package/dist/providers/xai.d.ts +33 -0
  294. package/dist/providers/xai.js +72 -0
  295. package/dist/schedules/index.d.ts +10 -0
  296. package/dist/schedules/index.js +6 -0
  297. package/dist/schedules/interval.d.ts +49 -0
  298. package/dist/schedules/interval.js +212 -0
  299. package/dist/schedules/prompt.d.ts +36 -0
  300. package/dist/schedules/prompt.js +36 -0
  301. package/dist/schedules/run-script.d.ts +8 -0
  302. package/dist/schedules/run-script.js +80 -0
  303. package/dist/schedules/scheduler.d.ts +101 -0
  304. package/dist/schedules/scheduler.js +167 -0
  305. package/dist/schedules/tools.d.ts +57 -0
  306. package/dist/schedules/tools.js +217 -0
  307. package/dist/schema.d.ts +499 -0
  308. package/dist/schema.js +131 -0
  309. package/dist/theme-palette.d.ts +17 -0
  310. package/dist/theme-palette.js +18 -0
  311. package/dist/thinking-catalog.d.ts +4 -0
  312. package/dist/thinking-catalog.js +13 -0
  313. package/dist/thinking.d.ts +37 -0
  314. package/dist/thinking.js +134 -0
  315. package/dist/tool-names.d.ts +77 -0
  316. package/dist/tool-names.js +53 -0
  317. package/dist/tools/index.d.ts +6 -0
  318. package/dist/tools/index.js +3 -0
  319. package/dist/tools/request-sandbox-access.d.ts +6 -0
  320. package/dist/tools/request-sandbox-access.js +80 -0
  321. package/dist/tools/utils.d.ts +20 -0
  322. package/dist/tools/utils.js +31 -0
  323. package/dist/tools/web-search.d.ts +116 -0
  324. package/dist/tools/web-search.js +158 -0
  325. package/dist/tools/workflows/create-workflow.d.ts +7 -0
  326. package/dist/tools/workflows/create-workflow.js +82 -0
  327. package/dist/tools/workflows/delete-workflow.d.ts +7 -0
  328. package/dist/tools/workflows/delete-workflow.js +18 -0
  329. package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
  330. package/dist/tools/workflows/ephemeral-memory.js +41 -0
  331. package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
  332. package/dist/tools/workflows/extract-json-schema.js +19 -0
  333. package/dist/tools/workflows/get-workflow.d.ts +11 -0
  334. package/dist/tools/workflows/get-workflow.js +31 -0
  335. package/dist/tools/workflows/list-available-agents.d.ts +8 -0
  336. package/dist/tools/workflows/list-available-agents.js +29 -0
  337. package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
  338. package/dist/tools/workflows/list-available-classifiers.js +53 -0
  339. package/dist/tools/workflows/list-available-tools.d.ts +9 -0
  340. package/dist/tools/workflows/list-available-tools.js +37 -0
  341. package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
  342. package/dist/tools/workflows/list-available-workflows.js +29 -0
  343. package/dist/tools/workflows/list-workflows.d.ts +9 -0
  344. package/dist/tools/workflows/list-workflows.js +30 -0
  345. package/dist/tools/workflows/run-workflow.d.ts +9 -0
  346. package/dist/tools/workflows/run-workflow.js +49 -0
  347. package/dist/tools/workflows/save-workflow.d.ts +1125 -0
  348. package/dist/tools/workflows/save-workflow.js +25 -0
  349. package/dist/tools/workflows/tool-ids.d.ts +16 -0
  350. package/dist/tools/workflows/tool-ids.js +17 -0
  351. package/dist/utils/binaries.d.ts +7 -0
  352. package/dist/utils/binaries.js +97 -0
  353. package/dist/utils/debug-log.d.ts +12 -0
  354. package/dist/utils/debug-log.js +56 -0
  355. package/dist/utils/discarding-scores-storage.d.ts +33 -0
  356. package/dist/utils/discarding-scores-storage.js +51 -0
  357. package/dist/utils/errors.d.ts +36 -0
  358. package/dist/utils/errors.js +215 -0
  359. package/dist/utils/gateway-sync.d.ts +26 -0
  360. package/dist/utils/gateway-sync.js +58 -0
  361. package/dist/utils/local-observability.d.ts +19 -0
  362. package/dist/utils/local-observability.js +54 -0
  363. package/dist/utils/maintenance-lock.d.ts +42 -0
  364. package/dist/utils/maintenance-lock.js +196 -0
  365. package/dist/utils/notification-dispatch.d.ts +74 -0
  366. package/dist/utils/notification-dispatch.js +128 -0
  367. package/dist/utils/open-url.d.ts +10 -0
  368. package/dist/utils/open-url.js +27 -0
  369. package/dist/utils/path-security.d.ts +2 -0
  370. package/dist/utils/path-security.js +7 -0
  371. package/dist/utils/plan-diff.d.ts +25 -0
  372. package/dist/utils/plan-diff.js +59 -0
  373. package/dist/utils/plans.d.ts +61 -0
  374. package/dist/utils/plans.js +120 -0
  375. package/dist/utils/project.d.ts +160 -0
  376. package/dist/utils/project.js +361 -0
  377. package/dist/utils/prune-cli.d.ts +24 -0
  378. package/dist/utils/prune-cli.js +124 -0
  379. package/dist/utils/signals-pubsub.d.ts +103 -0
  380. package/dist/utils/signals-pubsub.js +409 -0
  381. package/dist/utils/slash-command-loader.d.ts +52 -0
  382. package/dist/utils/slash-command-loader.js +139 -0
  383. package/dist/utils/slash-command-processor.d.ts +14 -0
  384. package/dist/utils/slash-command-processor.js +106 -0
  385. package/dist/utils/stdin-pipe.d.ts +33 -0
  386. package/dist/utils/stdin-pipe.js +93 -0
  387. package/dist/utils/storage-factory.d.ts +50 -0
  388. package/dist/utils/storage-factory.js +118 -0
  389. package/dist/utils/storage-maintenance.d.ts +121 -0
  390. package/dist/utils/storage-maintenance.js +352 -0
  391. package/dist/utils/thread-lock.d.ts +26 -0
  392. package/dist/utils/thread-lock.js +109 -0
  393. package/dist/utils/token-estimator.d.ts +3 -0
  394. package/dist/utils/token-estimator.js +19 -0
  395. package/dist/utils/update-check.d.ts +151 -0
  396. package/dist/utils/update-check.js +430 -0
  397. package/dist/utils/wake-session.d.ts +44 -0
  398. package/dist/utils/wake-session.js +83 -0
  399. package/dist/voice/stt-registry.d.ts +67 -0
  400. package/dist/voice/stt-registry.js +144 -0
  401. package/dist/voice/transcribe.d.ts +10 -0
  402. package/dist/voice/transcribe.js +75 -0
  403. package/dist/workflows/register-primitives.d.ts +52 -0
  404. package/dist/workflows/register-primitives.js +40 -0
  405. package/dist/workflows/service.d.ts +64 -0
  406. package/dist/workflows/service.js +50 -0
  407. package/package.json +117 -0
@@ -0,0 +1,49 @@
1
+ /**
2
+ * MastraCode Outcome Scorer (Code-based, Agent type, always-on)
3
+ *
4
+ * Grades the objective outcome of a coding session by checking hard facts:
5
+ * - Did the build/typecheck pass?
6
+ * - Did tests pass?
7
+ * - What was the tool error rate?
8
+ * - Did the agent get stuck in a loop?
9
+ * - Was there a regression (build passed earlier, failed later)?
10
+ * - Did the agent use ask_user unnecessarily? (autonomy)
11
+ *
12
+ * This scorer is always-on (no sampling) because it's cheap — it only
13
+ * reads exit codes and error states from tool results already in the messages.
14
+ *
15
+ * Scoring philosophy (from Anthropic's eval guidance):
16
+ * "Grade outcomes, not paths" — we check what happened, not how.
17
+ * Partial credit: a session that passes build but fails tests scores
18
+ * higher than one that fails build entirely.
19
+ *
20
+ * Dimensions that don't apply to a session (e.g. build for a docs-only task)
21
+ * are excluded from the weighted average, so sessions aren't penalized for
22
+ * irrelevant criteria.
23
+ */
24
+ type DimensionResult = {
25
+ score: number;
26
+ detail: string;
27
+ applicable: boolean;
28
+ };
29
+ export declare function createOutcomeScorer(): import("@mastra/core/evals").MastraScorer<"mastracode-outcome", import("@mastra/core/evals").ScorerRunInputForAgent, import("@mastra/core/evals").ScorerRunOutputForAgent, Record<"preprocessStepResult", {
30
+ empty: true;
31
+ build: DimensionResult;
32
+ tests: DimensionResult;
33
+ toolErrors: DimensionResult;
34
+ loops: DimensionResult;
35
+ regression: DimensionResult;
36
+ autonomy: DimensionResult;
37
+ totalCalls: number;
38
+ } | {
39
+ empty: false;
40
+ build: DimensionResult;
41
+ tests: DimensionResult;
42
+ toolErrors: DimensionResult;
43
+ loops: DimensionResult;
44
+ regression: DimensionResult;
45
+ autonomy: DimensionResult;
46
+ totalCalls: number;
47
+ }> & Record<"generateScoreStepResult", number> & Record<"generateReasonStepResult", string>>;
48
+ export {};
49
+ //# sourceMappingURL=outcome.d.ts.map
@@ -0,0 +1,360 @@
1
+ import { getExitCode, isBuildCommand, isSuccessResult, isTestCommand } from "./classify-command.js";
2
+ import { extractToolCalls } from "./extract-tools.js";
3
+ import { createScorer, filterRun } from "@mastra/core/evals";
4
+ // src/evals/scorers/outcome.ts
5
+ /**
6
+ * Dimension weights. Used to compute the weighted average of applicable dimensions.
7
+ * Dimensions that don't apply (e.g. no build ran) are excluded from the average.
8
+ */
9
+ const WEIGHTS = {
10
+ build: .3,
11
+ tests: .25,
12
+ toolErrors: .2,
13
+ loops: .1,
14
+ regression: .1,
15
+ autonomy: .05
16
+ };
17
+ /**
18
+ * Scoring thresholds and multipliers.
19
+ */
20
+ const THRESHOLDS = {
21
+ /** Multiplier for tool error rate penalty. Score = max(0, 1 - rate × this). */
22
+ toolErrorPenaltyMultiplier: 1,
23
+ /** How many consecutive identical calls (or same-error repeats) before it's a "loop". */
24
+ loopMinRepetitions: 3,
25
+ /** Score penalty per detected loop. */
26
+ loopPenaltyPerOccurrence: .3,
27
+ /** Score deducted per ask_user call. */
28
+ autonomyPenaltyPerAsk: .25,
29
+ /** Score when a command ran but exit code is ambiguous. */
30
+ ambiguousExitScore: .75,
31
+ /** Minimum tool calls required to produce a meaningful score. */
32
+ minToolCalls: 1,
33
+ /** Tool names whose errors are expected/benign (not penalized). */
34
+ benignErrorTools: [
35
+ "search_content",
36
+ "find_files",
37
+ "lsp_inspect"
38
+ ]
39
+ };
40
+ /**
41
+ * Check if the primary verb of an execute_command is a build/typecheck command.
42
+ * Splits compound commands (&&, ;) and checks the first segment.
43
+ */
44
+ /** Extract command string from tool call args, then delegate to shared classifier. */
45
+ function isBuildArgs(args) {
46
+ return isBuildCommand(String(args.command ?? ""));
47
+ }
48
+ function isTestArgs(args) {
49
+ return isTestCommand(String(args.command ?? ""));
50
+ }
51
+ function isForegroundCommand(result) {
52
+ return result.args.background !== true;
53
+ }
54
+ /**
55
+ * Score build/typecheck outcome (final state).
56
+ */
57
+ function scoreBuild(execResults) {
58
+ const builds = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && isBuildArgs(r.args));
59
+ if (builds.length === 0) return {
60
+ score: 0,
61
+ detail: "No build/typecheck ran",
62
+ applicable: false
63
+ };
64
+ const last = builds[builds.length - 1];
65
+ if (last.isError) return {
66
+ score: 0,
67
+ detail: "Build/typecheck tool errored",
68
+ applicable: true
69
+ };
70
+ const exitCode = getExitCode(last.result);
71
+ if (exitCode !== null && exitCode !== 0) return {
72
+ score: 0,
73
+ detail: `Build failed (exit ${exitCode})`,
74
+ applicable: true
75
+ };
76
+ if (typeof last.result === "string") return {
77
+ score: 1,
78
+ detail: "Build/typecheck passed",
79
+ applicable: true
80
+ };
81
+ const text = JSON.stringify(last.result ?? "");
82
+ if (/error TS\d+|Cannot find module|is not assignable/i.test(text)) return {
83
+ score: 0,
84
+ detail: "Build failed (TypeScript errors in output)",
85
+ applicable: true
86
+ };
87
+ if (isSuccessResult(last.result)) return {
88
+ score: 1,
89
+ detail: "Build/typecheck passed",
90
+ applicable: true
91
+ };
92
+ return {
93
+ score: THRESHOLDS.ambiguousExitScore,
94
+ detail: "Build ran, outcome unclear",
95
+ applicable: true
96
+ };
97
+ }
98
+ /**
99
+ * Score test outcome (final state).
100
+ */
101
+ function scoreTests(execResults) {
102
+ const tests = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && isTestArgs(r.args));
103
+ if (tests.length === 0) return {
104
+ score: 0,
105
+ detail: "No tests ran",
106
+ applicable: false
107
+ };
108
+ const last = tests[tests.length - 1];
109
+ if (last.isError) return {
110
+ score: 0,
111
+ detail: "Test command errored",
112
+ applicable: true
113
+ };
114
+ const exitCode = getExitCode(last.result);
115
+ if (exitCode !== null && exitCode !== 0) return {
116
+ score: 0,
117
+ detail: `Tests failed (exit ${exitCode})`,
118
+ applicable: true
119
+ };
120
+ if (typeof last.result === "string") return {
121
+ score: 1,
122
+ detail: "Tests passed",
123
+ applicable: true
124
+ };
125
+ const text = JSON.stringify(last.result ?? "");
126
+ if (/\bFAIL\b|failed|✗|✘/i.test(text)) return {
127
+ score: 0,
128
+ detail: "Tests failed (inferred)",
129
+ applicable: true
130
+ };
131
+ if (/\d+ (?:tests? )?passed|✓|PASS/i.test(text) && !/\bfail(?:ed|ure)?\b|\berror\b/i.test(text)) return {
132
+ score: 1,
133
+ detail: "Tests passed (inferred)",
134
+ applicable: true
135
+ };
136
+ if (isSuccessResult(last.result)) return {
137
+ score: 1,
138
+ detail: "Tests passed",
139
+ applicable: true
140
+ };
141
+ return {
142
+ score: THRESHOLDS.ambiguousExitScore,
143
+ detail: "Tests ran, outcome unclear",
144
+ applicable: true
145
+ };
146
+ }
147
+ /**
148
+ * Score tool error rate, excluding benign errors from expected-to-fail tools.
149
+ */
150
+ function scoreToolErrors(results) {
151
+ if (results.length === 0) return {
152
+ score: 1,
153
+ detail: "No tool calls",
154
+ applicable: false
155
+ };
156
+ const nonBenign = results.filter((r) => !THRESHOLDS.benignErrorTools.includes(r.toolName));
157
+ if (nonBenign.length === 0) return {
158
+ score: 1,
159
+ detail: "All tool calls are benign-error tools",
160
+ applicable: true
161
+ };
162
+ const errors = nonBenign.filter((r) => r.isError);
163
+ const rate = errors.length / nonBenign.length;
164
+ if (rate === 0) return {
165
+ score: 1,
166
+ detail: "No tool errors",
167
+ applicable: true
168
+ };
169
+ return {
170
+ score: Math.max(0, 1 - rate * THRESHOLDS.toolErrorPenaltyMultiplier),
171
+ detail: `${errors.length}/${nonBenign.length} tools errored (${(rate * 100).toFixed(0)}%)`,
172
+ applicable: true
173
+ };
174
+ }
175
+ /**
176
+ * Detect stuck loops: same tool + same args appearing 3+ times consecutively,
177
+ * or same tool + same args erroring 3+ times total.
178
+ */
179
+ function scoreStuckLoops(results) {
180
+ if (results.length < 3) return {
181
+ score: 1,
182
+ detail: "Too few calls for loop detection",
183
+ applicable: true
184
+ };
185
+ const fingerprint = (r) => `${r.toolName}:${JSON.stringify(r.args)}`;
186
+ let maxConsecutive = 1;
187
+ let currentRun = 1;
188
+ for (let i = 1; i < results.length; i++) if (fingerprint(results[i]) === fingerprint(results[i - 1])) {
189
+ currentRun++;
190
+ maxConsecutive = Math.max(maxConsecutive, currentRun);
191
+ } else currentRun = 1;
192
+ const errorCounts = /* @__PURE__ */ new Map();
193
+ for (const r of results) {
194
+ if (!r.isError) continue;
195
+ const fp = fingerprint(r);
196
+ errorCounts.set(fp, (errorCounts.get(fp) ?? 0) + 1);
197
+ }
198
+ const maxErrorRepeat = Math.max(0, ...[...errorCounts.values()]);
199
+ const minReps = THRESHOLDS.loopMinRepetitions;
200
+ const loopSeverity = Math.max(maxConsecutive >= minReps ? maxConsecutive - (minReps - 1) : 0, maxErrorRepeat >= minReps ? maxErrorRepeat - (minReps - 1) : 0);
201
+ if (loopSeverity === 0) return {
202
+ score: 1,
203
+ detail: "No stuck loops",
204
+ applicable: true
205
+ };
206
+ const score = Math.max(0, 1 - loopSeverity * THRESHOLDS.loopPenaltyPerOccurrence);
207
+ const details = [];
208
+ if (maxConsecutive >= minReps) details.push(`${maxConsecutive} consecutive identical calls`);
209
+ if (maxErrorRepeat >= minReps) details.push(`same error repeated ${maxErrorRepeat}x`);
210
+ return {
211
+ score,
212
+ detail: details.join("; "),
213
+ applicable: true
214
+ };
215
+ }
216
+ /**
217
+ * Detect regressions: build/test passed at some point, then failed later.
218
+ * Gives partial credit if the agent recovered (final state passes).
219
+ */
220
+ function scoreRegression(execResults) {
221
+ const regressions = [];
222
+ for (const [label, filter] of [["Build", isBuildArgs], ["Tests", isTestArgs]]) {
223
+ const cmds = execResults.filter((r) => r.toolName === "execute_command" && isForegroundCommand(r) && filter(r.args));
224
+ if (cmds.length < 2) continue;
225
+ let sawPass = false;
226
+ let sawRegression = false;
227
+ for (const cmd of cmds) {
228
+ const exitCode = getExitCode(cmd.result);
229
+ const passed = isSuccessResult(cmd.result, cmd.isError);
230
+ const failed = cmd.isError || exitCode !== null && exitCode !== 0;
231
+ if (passed) {
232
+ if (sawRegression) {
233
+ regressions.push({
234
+ label,
235
+ recovered: true
236
+ });
237
+ sawRegression = false;
238
+ }
239
+ sawPass = true;
240
+ }
241
+ if (sawPass && failed) sawRegression = true;
242
+ }
243
+ if (sawRegression) regressions.push({
244
+ label,
245
+ recovered: false
246
+ });
247
+ }
248
+ if (regressions.length === 0) return {
249
+ score: 1,
250
+ detail: "No regressions",
251
+ applicable: true
252
+ };
253
+ const persistentCount = regressions.filter((r) => !r.recovered).length;
254
+ const recoveredCount = regressions.filter((r) => r.recovered).length;
255
+ return {
256
+ score: Math.max(0, 1 - persistentCount * .5 - recoveredCount * .1),
257
+ detail: regressions.map((r) => `${r.label} ${r.recovered ? "regressed then recovered" : "regressed (persisted)"}`).join("; "),
258
+ applicable: true
259
+ };
260
+ }
261
+ /**
262
+ * Score autonomy: penalize ask_user calls.
263
+ * 0 calls = 1.0, each call reduces by 0.25 (up to a floor of 0).
264
+ */
265
+ function scoreAutonomy(results) {
266
+ const count = results.filter((r) => r.toolName === "ask_user").length;
267
+ if (count === 0) return {
268
+ score: 1,
269
+ detail: "No ask_user calls (fully autonomous)",
270
+ applicable: true
271
+ };
272
+ return {
273
+ score: Math.max(0, 1 - count * THRESHOLDS.autonomyPenaltyPerAsk),
274
+ detail: `${count} ask_user call${count > 1 ? "s" : ""}`,
275
+ applicable: true
276
+ };
277
+ }
278
+ /**
279
+ * Compute weighted average of only applicable dimensions.
280
+ * Returns null if no dimensions are applicable.
281
+ */
282
+ function weightedAverage(dimensions, weights) {
283
+ let totalWeight = 0;
284
+ let weightedSum = 0;
285
+ for (const [key, result] of Object.entries(dimensions)) {
286
+ if (!result.applicable) continue;
287
+ const weight = weights[key] ?? 0;
288
+ totalWeight += weight;
289
+ weightedSum += result.score * weight;
290
+ }
291
+ if (totalWeight === 0) return null;
292
+ return weightedSum / totalWeight;
293
+ }
294
+ function createOutcomeScorer() {
295
+ return createScorer({
296
+ id: "mastracode-outcome",
297
+ name: "MastraCode Outcome",
298
+ description: "Grades coding session outcomes: build/test pass, tool errors, stuck loops, regressions, autonomy. Always-on.",
299
+ type: "agent",
300
+ prepareRun: filterRun({ partTypes: ["tool-invocation", "text"] })
301
+ }).preprocess(async ({ run }) => {
302
+ const messages = run.output ?? [];
303
+ const allResults = extractToolCalls(messages);
304
+ const totalCalls = allResults.length;
305
+ if (totalCalls < THRESHOLDS.minToolCalls) {
306
+ const empty = {
307
+ score: 0,
308
+ detail: "No tool calls",
309
+ applicable: false
310
+ };
311
+ return {
312
+ empty: true,
313
+ build: empty,
314
+ tests: empty,
315
+ toolErrors: empty,
316
+ loops: empty,
317
+ regression: empty,
318
+ autonomy: empty,
319
+ totalCalls
320
+ };
321
+ }
322
+ const execResults = allResults.filter((r) => r.toolName === "execute_command");
323
+ return {
324
+ empty: false,
325
+ build: scoreBuild(execResults),
326
+ tests: scoreTests(execResults),
327
+ toolErrors: scoreToolErrors(allResults),
328
+ loops: scoreStuckLoops(allResults),
329
+ regression: scoreRegression(execResults),
330
+ autonomy: scoreAutonomy(allResults),
331
+ totalCalls
332
+ };
333
+ }).generateScore(({ results }) => {
334
+ const p = results.preprocessStepResult;
335
+ if (p.empty) return 0;
336
+ const score = weightedAverage({
337
+ build: p.build,
338
+ tests: p.tests,
339
+ toolErrors: p.toolErrors,
340
+ loops: p.loops,
341
+ regression: p.regression,
342
+ autonomy: p.autonomy
343
+ }, WEIGHTS);
344
+ return score === null ? 0 : Math.round(score * 100) / 100;
345
+ }).generateReason(({ results, score }) => {
346
+ const p = results.preprocessStepResult;
347
+ if (p.empty) return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;
348
+ const pct = (w) => `${(w * 100).toFixed(0)}%`;
349
+ const dimLine = (name, weight, r) => r.applicable ? `${name} (${pct(weight)}): ${r.detail} [${r.score}]` : `${name}: ${r.detail} [N/A — excluded from average]`;
350
+ const parts = [`Score: ${score} (${p.totalCalls} tool calls total)`];
351
+ parts.push(dimLine("Build", WEIGHTS.build, p.build));
352
+ parts.push(dimLine("Tests", WEIGHTS.tests, p.tests));
353
+ parts.push(dimLine("Tool errors", WEIGHTS.toolErrors, p.toolErrors));
354
+ parts.push(dimLine("Loops", WEIGHTS.loops, p.loops));
355
+ parts.push(dimLine("Regression", WEIGHTS.regression, p.regression));
356
+ parts.push(dimLine("Autonomy", WEIGHTS.autonomy, p.autonomy));
357
+ return parts.join("\n");
358
+ });
359
+ }
360
+ export { createOutcomeScorer };
@@ -0,0 +1,19 @@
1
+ import type { Agent } from '@mastra/core/agent';
2
+ import type { Mastra } from '@mastra/core/mastra';
3
+ import type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';
4
+ export interface ExperimentalAgentEnvironment {
5
+ MASTRACODE_EXPERIMENTAL_AGENT?: string;
6
+ }
7
+ export declare function parseExperimentalAgentEnvironment(env?: ExperimentalAgentEnvironment): ExperimentalAgent | null;
8
+ export declare function resolveExperimentalAgent(settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>, env?: ExperimentalAgentEnvironment): ExperimentalAgent | null;
9
+ /**
10
+ * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing
11
+ * its runs on a resumable stream; `on` or unset keeps the core default. Any other
12
+ * value, including an empty string, throws so a typo can't silently leave streams on.
13
+ */
14
+ export declare function resolveAgentStreamsOff(env?: {
15
+ MASTRACODE_AGENT_STREAMS?: string;
16
+ }): boolean;
17
+ export declare function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent;
18
+ export declare function validateExperimentalAgent(agent: Agent, mastra: Mastra | undefined, report?: (message: string) => void): void;
19
+ //# sourceMappingURL=experimental-agent.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { parseExperimentalAgentSetting } from "./onboarding/settings.js";
2
+ import { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from "@mastra/core/agent/durable";
3
+ // src/experimental-agent.ts
4
+ const ACCEPTED_VALUES = "\"durable\", \"evented\", or unset";
5
+ function parseExperimentalAgentEnvironment(env = process.env) {
6
+ const value = env.MASTRACODE_EXPERIMENTAL_AGENT;
7
+ if (value === void 0 || value === "") return null;
8
+ if (value === "durable" || value === "evented") return value;
9
+ throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);
10
+ }
11
+ function resolveExperimentalAgent(settings, env = process.env) {
12
+ const environmentSelection = parseExperimentalAgentEnvironment(env);
13
+ if (environmentSelection) return environmentSelection;
14
+ return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);
15
+ }
16
+ /**
17
+ * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing
18
+ * its runs on a resumable stream; `on` or unset keeps the core default. Any other
19
+ * value, including an empty string, throws so a typo can't silently leave streams on.
20
+ */
21
+ function resolveAgentStreamsOff(env = process.env) {
22
+ const value = env.MASTRACODE_AGENT_STREAMS;
23
+ if (value === void 0 || value === "on") return false;
24
+ if (value === "off") return true;
25
+ throw new Error(`Invalid MASTRACODE_AGENT_STREAMS value ${JSON.stringify(value)}. Expected "on", "off", or unset.`);
26
+ }
27
+ function wrapExperimentalAgent(agent, selection) {
28
+ if (selection === "durable") return createDurableAgent({ agent });
29
+ if (selection === "evented") return createEventedAgent({ agent });
30
+ return agent;
31
+ }
32
+ function validateExperimentalAgent(agent, mastra, report = console.info) {
33
+ const evented = isEventedAgent(agent);
34
+ if (!evented && !isDurableAgent(agent)) return;
35
+ const selection = evented ? "evented" : "durable";
36
+ if (selection === "evented" && (!mastra || agent.getMastraInstance() !== mastra)) throw new Error("Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.");
37
+ const workflowsStore = mastra?.getStorage()?.stores?.workflows;
38
+ if (!workflowsStore) throw new Error(`Experimental agent "${selection}" requires a configured workflow storage domain.`);
39
+ if (selection === "evented" && workflowsStore.supportsConcurrentUpdates?.() !== true) throw new Error("Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).");
40
+ const engineType = agent.getWorkflow().engineType;
41
+ const expectedEngine = selection === "evented" ? "evented" : "default";
42
+ if (engineType !== expectedEngine) throw new Error(`Experimental agent "${selection}" resolved workflow engine ${JSON.stringify(engineType)} instead of "${expectedEngine}".`);
43
+ report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);
44
+ }
45
+ export { parseExperimentalAgentEnvironment, resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent };
@@ -0,0 +1,44 @@
1
+ import { MastraClient } from '@mastra/client-js';
2
+ import type { PlatformSession } from '../platform/index.js';
3
+ /** The agent controller every Factory serves its coding sessions under. */
4
+ export declare const FACTORY_CONTROLLER_ID = "code";
5
+ export interface FactoryAddress {
6
+ url: string;
7
+ session: PlatformSession;
8
+ }
9
+ export interface FactoryRepository {
10
+ projectRepositoryId: string;
11
+ slug: string;
12
+ branch?: string;
13
+ }
14
+ export interface FactoryProject {
15
+ id: string;
16
+ name: string;
17
+ repositories: FactoryRepository[];
18
+ }
19
+ export interface FactoryUserSession {
20
+ sessionId: string;
21
+ projectRepositoryId: string;
22
+ title?: string;
23
+ branch: string;
24
+ updatedAt: string;
25
+ }
26
+ export declare function factoryHeaders({ session }: FactoryAddress): Record<string, string>;
27
+ /**
28
+ * List the org's Factory projects with their linked repositories. Current servers return the repositories with the
29
+ * project list; an older server, which does not, is asked once per project.
30
+ */
31
+ export declare function listFactoryProjects(address: FactoryAddress): Promise<FactoryProject[]>;
32
+ /**
33
+ * Create a Factory user session. Factory assigns the session ID and its
34
+ * `user/session-<id>` branch, cut from the repository's default branch.
35
+ */
36
+ export declare function createFactoryUserSession(address: FactoryAddress, projectRepositoryId: string, title?: string): Promise<FactoryUserSession>;
37
+ /**
38
+ * Platform access tokens expire while a long-lived TUI is open. On a 401,
39
+ * refresh the session and replay the request once with the new token; a
40
+ * rejected request never ran, so the replay cannot duplicate a command.
41
+ */
42
+ export declare function refreshingFetch(address: FactoryAddress, refresh?: () => Promise<PlatformSession | null>, baseFetch?: typeof fetch): typeof fetch;
43
+ export declare function createFactoryClient(address: FactoryAddress): MastraClient;
44
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,110 @@
1
+ import { getPlatformSession } from "../platform/index.js";
2
+ import { MastraClient } from "@mastra/client-js";
3
+ // src/factory/client.ts
4
+ /** The agent controller every Factory serves its coding sessions under. */
5
+ const FACTORY_CONTROLLER_ID = "code";
6
+ const ORGANIZATION_ID_HEADER = "X-Mastra-Organization-Id";
7
+ function factoryHeaders({ session }) {
8
+ return {
9
+ Authorization: `Bearer ${session.token}`,
10
+ [ORGANIZATION_ID_HEADER]: session.orgId
11
+ };
12
+ }
13
+ async function factoryFetch(address, path, init) {
14
+ const res = await refreshingFetch(address)(`${address.url.replace(/\/$/, "")}${path}`, {
15
+ method: init?.method ?? "GET",
16
+ headers: {
17
+ Accept: "application/json",
18
+ ...init?.body !== void 0 ? { "content-type": "application/json" } : {}
19
+ },
20
+ body: init?.body !== void 0 ? JSON.stringify(init.body) : void 0
21
+ });
22
+ if (!res.ok) {
23
+ const body = await res.json().catch(() => ({}));
24
+ throw new Error(`Factory request ${path} failed (${res.status})${body.message || body.error ? `: ${body.message ?? body.error}` : ""}`);
25
+ }
26
+ return await res.json();
27
+ }
28
+ function toFactoryRepository(projectName, repository) {
29
+ return {
30
+ projectRepositoryId: repository.projectRepositoryId,
31
+ slug: repository.slug ?? projectName,
32
+ branch: repository.branch ?? repository.defaultBranch ?? void 0
33
+ };
34
+ }
35
+ /**
36
+ * List the org's Factory projects with their linked repositories. Current servers return the repositories with the
37
+ * project list; an older server, which does not, is asked once per project.
38
+ */
39
+ async function listFactoryProjects(address) {
40
+ const { projects } = await factoryFetch(address, "/web/factory/projects");
41
+ return Promise.all(projects.map(async (project) => {
42
+ const repositories = project.repositories ?? await listProjectRepositories(address, project.id);
43
+ return {
44
+ id: project.id,
45
+ name: project.name,
46
+ repositories: repositories.map((repository) => toFactoryRepository(project.name, repository))
47
+ };
48
+ }));
49
+ }
50
+ async function listProjectRepositories(address, projectId) {
51
+ const { connections } = await factoryFetch(address, `/web/factory/projects/${encodeURIComponent(projectId)}/source-control-connections`);
52
+ return connections.flatMap((connection) => connection.repositories.map((link) => ({
53
+ projectRepositoryId: link.id,
54
+ slug: link.repository?.slug ?? null,
55
+ defaultBranch: link.repository?.defaultBranch ?? null,
56
+ branch: link.branch
57
+ })));
58
+ }
59
+ /**
60
+ * Create a Factory user session. Factory assigns the session ID and its
61
+ * `user/session-<id>` branch, cut from the repository's default branch.
62
+ */
63
+ async function createFactoryUserSession(address, projectRepositoryId, title) {
64
+ const { session } = await factoryFetch(address, `/web/source-control/projects/${encodeURIComponent(projectRepositoryId)}/sessions`, {
65
+ method: "POST",
66
+ body: title ? { title } : {}
67
+ });
68
+ return {
69
+ ...session,
70
+ title: session.title ?? void 0
71
+ };
72
+ }
73
+ /**
74
+ * Platform access tokens expire while a long-lived TUI is open. On a 401,
75
+ * refresh the session and replay the request once with the new token; a
76
+ * rejected request never ran, so the replay cannot duplicate a command.
77
+ */
78
+ function refreshingFetch(address, refresh = getPlatformSession, baseFetch = fetch) {
79
+ const withAuth = (init) => {
80
+ const headers = new Headers(init?.headers);
81
+ for (const [key, value] of Object.entries(factoryHeaders(address))) headers.set(key, value);
82
+ return {
83
+ ...init,
84
+ headers
85
+ };
86
+ };
87
+ let refreshing;
88
+ return async (input, init) => {
89
+ const sentToken = address.session.token;
90
+ const res = await baseFetch(input, withAuth(init));
91
+ if (res.status !== 401) return res;
92
+ if (address.session.token === sentToken) {
93
+ refreshing ??= refresh().finally(() => {
94
+ refreshing = void 0;
95
+ });
96
+ const session = await refreshing;
97
+ if (!session || session.token === sentToken) return res;
98
+ address.session = session;
99
+ }
100
+ return baseFetch(input, withAuth(init));
101
+ };
102
+ }
103
+ function createFactoryClient(address) {
104
+ return new MastraClient({
105
+ baseUrl: address.url.replace(/\/$/, ""),
106
+ retries: 0,
107
+ fetch: refreshingFetch(address)
108
+ });
109
+ }
110
+ export { FACTORY_CONTROLLER_ID, createFactoryClient, createFactoryUserSession, factoryHeaders, listFactoryProjects, refreshingFetch };
@@ -0,0 +1,34 @@
1
+ import type { AvailableModel, ModelAuthStatus } from '@mastra/core/agent-controller';
2
+ import type { FactoryAddress } from './client.js';
3
+ import { createFactoryClient } from './client.js';
4
+ export interface RemoteMode {
5
+ id: string;
6
+ name?: string;
7
+ description?: string;
8
+ default?: boolean;
9
+ defaultModelId?: string;
10
+ metadata?: Record<string, unknown>;
11
+ }
12
+ type ControllerHandle = ReturnType<ReturnType<typeof createFactoryClient>['getAgentController']>;
13
+ /**
14
+ * The Factory-side counterpart to the local agent controller. Modes, models, and
15
+ * provider auth come from the Factory, never from local settings or auth storage.
16
+ */
17
+ export declare class RemoteController {
18
+ #private;
19
+ readonly id = "code";
20
+ constructor(address: FactoryAddress, remote?: ControllerHandle);
21
+ /** Load the mode list; `listModes()` is synchronous so it must be primed. */
22
+ connect(): Promise<void>;
23
+ listModes(): RemoteMode[];
24
+ listAvailableModels(): Promise<AvailableModel[]>;
25
+ invalidateAvailableModelsCache(): void;
26
+ /** Auth is the Factory's: report what it reports, or assume ok and let the run surface errors. */
27
+ getCurrentModelAuthStatus(session: {
28
+ model: {
29
+ get(): string;
30
+ };
31
+ }): Promise<ModelAuthStatus>;
32
+ }
33
+ export {};
34
+ //# sourceMappingURL=remote-controller.d.ts.map