@mastra/factory 0.0.0-fix-thread-subscription-multi-instance-redis-streams-20260730204150

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 (313) hide show
  1. package/CHANGELOG.md +695 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +27 -0
  4. package/dist/auth.d.ts +181 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +505 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/capabilities/connection.d.ts +9 -0
  9. package/dist/capabilities/connection.d.ts.map +1 -0
  10. package/dist/capabilities/connection.js +1 -0
  11. package/dist/capabilities/intake.d.ts +140 -0
  12. package/dist/capabilities/intake.d.ts.map +1 -0
  13. package/dist/capabilities/intake.js +1 -0
  14. package/dist/capabilities/version-control.d.ts +245 -0
  15. package/dist/capabilities/version-control.d.ts.map +1 -0
  16. package/dist/capabilities/version-control.js +1 -0
  17. package/dist/factory.d.ts +156 -0
  18. package/dist/factory.d.ts.map +1 -0
  19. package/dist/factory.js +483 -0
  20. package/dist/factory.js.map +1 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +7 -0
  24. package/dist/integrations/base.d.ts +210 -0
  25. package/dist/integrations/base.d.ts.map +1 -0
  26. package/dist/integrations/base.js +1 -0
  27. package/dist/integrations/github/config.d.ts +60 -0
  28. package/dist/integrations/github/config.d.ts.map +1 -0
  29. package/dist/integrations/github/config.js +42 -0
  30. package/dist/integrations/github/config.js.map +1 -0
  31. package/dist/integrations/github/factory-session.d.ts +12 -0
  32. package/dist/integrations/github/factory-session.d.ts.map +1 -0
  33. package/dist/integrations/github/factory-session.js +37 -0
  34. package/dist/integrations/github/factory-session.js.map +1 -0
  35. package/dist/integrations/github/integration.d.ts +191 -0
  36. package/dist/integrations/github/integration.d.ts.map +1 -0
  37. package/dist/integrations/github/integration.js +1077 -0
  38. package/dist/integrations/github/integration.js.map +1 -0
  39. package/dist/integrations/github/issue-triage.d.ts +27 -0
  40. package/dist/integrations/github/issue-triage.d.ts.map +1 -0
  41. package/dist/integrations/github/issue-triage.js +82 -0
  42. package/dist/integrations/github/issue-triage.js.map +1 -0
  43. package/dist/integrations/github/pat.d.ts +38 -0
  44. package/dist/integrations/github/pat.d.ts.map +1 -0
  45. package/dist/integrations/github/pat.js +59 -0
  46. package/dist/integrations/github/pat.js.map +1 -0
  47. package/dist/integrations/github/provenance.d.ts +27 -0
  48. package/dist/integrations/github/provenance.d.ts.map +1 -0
  49. package/dist/integrations/github/provenance.js +75 -0
  50. package/dist/integrations/github/provenance.js.map +1 -0
  51. package/dist/integrations/github/routes.d.ts +69 -0
  52. package/dist/integrations/github/routes.d.ts.map +1 -0
  53. package/dist/integrations/github/routes.js +1324 -0
  54. package/dist/integrations/github/routes.js.map +1 -0
  55. package/dist/integrations/github/rules.d.ts +78 -0
  56. package/dist/integrations/github/rules.d.ts.map +1 -0
  57. package/dist/integrations/github/rules.js +362 -0
  58. package/dist/integrations/github/rules.js.map +1 -0
  59. package/dist/integrations/github/sandbox-release.d.ts +38 -0
  60. package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
  61. package/dist/integrations/github/sandbox-release.js +74 -0
  62. package/dist/integrations/github/sandbox-release.js.map +1 -0
  63. package/dist/integrations/github/sandbox.d.ts +281 -0
  64. package/dist/integrations/github/sandbox.d.ts.map +1 -0
  65. package/dist/integrations/github/sandbox.js +547 -0
  66. package/dist/integrations/github/sandbox.js.map +1 -0
  67. package/dist/integrations/github/session-subscriptions.d.ts +26 -0
  68. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
  69. package/dist/integrations/github/session-subscriptions.js +192 -0
  70. package/dist/integrations/github/session-subscriptions.js.map +1 -0
  71. package/dist/integrations/github/subscriptions.d.ts +54 -0
  72. package/dist/integrations/github/subscriptions.d.ts.map +1 -0
  73. package/dist/integrations/github/subscriptions.js +62 -0
  74. package/dist/integrations/github/subscriptions.js.map +1 -0
  75. package/dist/integrations/github/token-refresh.d.ts +12 -0
  76. package/dist/integrations/github/token-refresh.d.ts.map +1 -0
  77. package/dist/integrations/github/token-refresh.js +24 -0
  78. package/dist/integrations/github/token-refresh.js.map +1 -0
  79. package/dist/integrations/github/webhook.d.ts +87 -0
  80. package/dist/integrations/github/webhook.d.ts.map +1 -0
  81. package/dist/integrations/github/webhook.js +397 -0
  82. package/dist/integrations/github/webhook.js.map +1 -0
  83. package/dist/integrations/linear/agent-tools.d.ts +34 -0
  84. package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
  85. package/dist/integrations/linear/agent-tools.js +85 -0
  86. package/dist/integrations/linear/agent-tools.js.map +1 -0
  87. package/dist/integrations/linear/integration.d.ts +233 -0
  88. package/dist/integrations/linear/integration.d.ts.map +1 -0
  89. package/dist/integrations/linear/integration.js +672 -0
  90. package/dist/integrations/linear/integration.js.map +1 -0
  91. package/dist/integrations/linear/routes.d.ts +61 -0
  92. package/dist/integrations/linear/routes.d.ts.map +1 -0
  93. package/dist/integrations/linear/routes.js +239 -0
  94. package/dist/integrations/linear/routes.js.map +1 -0
  95. package/dist/integrations/linear/rules.d.ts +42 -0
  96. package/dist/integrations/linear/rules.d.ts.map +1 -0
  97. package/dist/integrations/linear/rules.js +133 -0
  98. package/dist/integrations/linear/rules.js.map +1 -0
  99. package/dist/integrations/linear/storage.d.ts +65 -0
  100. package/dist/integrations/linear/storage.d.ts.map +1 -0
  101. package/dist/integrations/linear/storage.js +1 -0
  102. package/dist/integrations/platform/api-client.d.ts +26 -0
  103. package/dist/integrations/platform/api-client.d.ts.map +1 -0
  104. package/dist/integrations/platform/api-client.js +156 -0
  105. package/dist/integrations/platform/api-client.js.map +1 -0
  106. package/dist/integrations/platform/github/event-worker.d.ts +49 -0
  107. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
  108. package/dist/integrations/platform/github/event-worker.js +348 -0
  109. package/dist/integrations/platform/github/event-worker.js.map +1 -0
  110. package/dist/integrations/platform/github/integration.d.ts +50 -0
  111. package/dist/integrations/platform/github/integration.d.ts.map +1 -0
  112. package/dist/integrations/platform/github/integration.js +961 -0
  113. package/dist/integrations/platform/github/integration.js.map +1 -0
  114. package/dist/integrations/platform/linear/integration.d.ts +46 -0
  115. package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
  116. package/dist/integrations/platform/linear/integration.js +483 -0
  117. package/dist/integrations/platform/linear/integration.js.map +1 -0
  118. package/dist/integrations/workos/integration.d.ts +39 -0
  119. package/dist/integrations/workos/integration.d.ts.map +1 -0
  120. package/dist/integrations/workos/integration.js +91 -0
  121. package/dist/integrations/workos/integration.js.map +1 -0
  122. package/dist/routes/config.d.ts +235 -0
  123. package/dist/routes/config.d.ts.map +1 -0
  124. package/dist/routes/config.js +972 -0
  125. package/dist/routes/config.js.map +1 -0
  126. package/dist/routes/custom-provider-source.d.ts +52 -0
  127. package/dist/routes/custom-provider-source.d.ts.map +1 -0
  128. package/dist/routes/custom-provider-source.js +124 -0
  129. package/dist/routes/custom-provider-source.js.map +1 -0
  130. package/dist/routes/fs.d.ts +151 -0
  131. package/dist/routes/fs.d.ts.map +1 -0
  132. package/dist/routes/fs.js +708 -0
  133. package/dist/routes/fs.js.map +1 -0
  134. package/dist/routes/intake.d.ts +23 -0
  135. package/dist/routes/intake.d.ts.map +1 -0
  136. package/dist/routes/intake.js +179 -0
  137. package/dist/routes/intake.js.map +1 -0
  138. package/dist/routes/oauth.d.ts +43 -0
  139. package/dist/routes/oauth.d.ts.map +1 -0
  140. package/dist/routes/oauth.js +463 -0
  141. package/dist/routes/oauth.js.map +1 -0
  142. package/dist/routes/projects.d.ts +19 -0
  143. package/dist/routes/projects.d.ts.map +1 -0
  144. package/dist/routes/projects.js +461 -0
  145. package/dist/routes/projects.js.map +1 -0
  146. package/dist/routes/provider-credentials.d.ts +81 -0
  147. package/dist/routes/provider-credentials.d.ts.map +1 -0
  148. package/dist/routes/provider-credentials.js +86 -0
  149. package/dist/routes/provider-credentials.js.map +1 -0
  150. package/dist/routes/route.d.ts +48 -0
  151. package/dist/routes/route.d.ts.map +1 -0
  152. package/dist/routes/route.js +15 -0
  153. package/dist/routes/route.js.map +1 -0
  154. package/dist/routes/skills.d.ts +30 -0
  155. package/dist/routes/skills.d.ts.map +1 -0
  156. package/dist/routes/skills.js +168 -0
  157. package/dist/routes/skills.js.map +1 -0
  158. package/dist/routes/surface.d.ts +91 -0
  159. package/dist/routes/surface.d.ts.map +1 -0
  160. package/dist/routes/surface.js +260 -0
  161. package/dist/routes/surface.js.map +1 -0
  162. package/dist/routes/tenant-credentials.d.ts +74 -0
  163. package/dist/routes/tenant-credentials.d.ts.map +1 -0
  164. package/dist/routes/tenant-credentials.js +156 -0
  165. package/dist/routes/tenant-credentials.js.map +1 -0
  166. package/dist/routes/work-items.d.ts +40 -0
  167. package/dist/routes/work-items.d.ts.map +1 -0
  168. package/dist/routes/work-items.js +695 -0
  169. package/dist/routes/work-items.js.map +1 -0
  170. package/dist/rules/binding-context.d.ts +5 -0
  171. package/dist/rules/binding-context.d.ts.map +1 -0
  172. package/dist/rules/binding-context.js +28 -0
  173. package/dist/rules/binding-context.js.map +1 -0
  174. package/dist/rules/defaults.d.ts +9 -0
  175. package/dist/rules/defaults.d.ts.map +1 -0
  176. package/dist/rules/defaults.js +260 -0
  177. package/dist/rules/defaults.js.map +1 -0
  178. package/dist/rules/dispatcher.d.ts +42 -0
  179. package/dist/rules/dispatcher.d.ts.map +1 -0
  180. package/dist/rules/dispatcher.js +518 -0
  181. package/dist/rules/dispatcher.js.map +1 -0
  182. package/dist/rules/index.d.ts +7 -0
  183. package/dist/rules/index.d.ts.map +1 -0
  184. package/dist/rules/index.js +5 -0
  185. package/dist/rules/processor.d.ts +54 -0
  186. package/dist/rules/processor.d.ts.map +1 -0
  187. package/dist/rules/processor.js +378 -0
  188. package/dist/rules/processor.js.map +1 -0
  189. package/dist/rules/resolve.d.ts +17 -0
  190. package/dist/rules/resolve.d.ts.map +1 -0
  191. package/dist/rules/resolve.js +30 -0
  192. package/dist/rules/resolve.js.map +1 -0
  193. package/dist/rules/start-coordinator.d.ts +60 -0
  194. package/dist/rules/start-coordinator.d.ts.map +1 -0
  195. package/dist/rules/start-coordinator.js +194 -0
  196. package/dist/rules/start-coordinator.js.map +1 -0
  197. package/dist/rules/tools.d.ts +10 -0
  198. package/dist/rules/tools.d.ts.map +1 -0
  199. package/dist/rules/tools.js +58 -0
  200. package/dist/rules/tools.js.map +1 -0
  201. package/dist/rules/transition-service.d.ts +49 -0
  202. package/dist/rules/transition-service.d.ts.map +1 -0
  203. package/dist/rules/transition-service.js +232 -0
  204. package/dist/rules/transition-service.js.map +1 -0
  205. package/dist/rules/types.d.ts +234 -0
  206. package/dist/rules/types.d.ts.map +1 -0
  207. package/dist/rules/types.js +38 -0
  208. package/dist/rules/types.js.map +1 -0
  209. package/dist/rules/validation.d.ts +11 -0
  210. package/dist/rules/validation.d.ts.map +1 -0
  211. package/dist/rules/validation.js +308 -0
  212. package/dist/rules/validation.js.map +1 -0
  213. package/dist/sandbox/fleet.d.ts +222 -0
  214. package/dist/sandbox/fleet.d.ts.map +1 -0
  215. package/dist/sandbox/fleet.js +322 -0
  216. package/dist/sandbox/fleet.js.map +1 -0
  217. package/dist/sandbox/reattach.d.ts +3 -0
  218. package/dist/sandbox/reattach.d.ts.map +1 -0
  219. package/dist/sandbox/reattach.js +16 -0
  220. package/dist/sandbox/reattach.js.map +1 -0
  221. package/dist/server-error.d.ts +12 -0
  222. package/dist/server-error.d.ts.map +1 -0
  223. package/dist/server-error.js +16 -0
  224. package/dist/server-error.js.map +1 -0
  225. package/dist/skills/service.d.ts +48 -0
  226. package/dist/skills/service.d.ts.map +1 -0
  227. package/dist/skills/service.js +40 -0
  228. package/dist/skills/service.js.map +1 -0
  229. package/dist/spa-static.d.ts +33 -0
  230. package/dist/spa-static.d.ts.map +1 -0
  231. package/dist/spa-static.js +104 -0
  232. package/dist/spa-static.js.map +1 -0
  233. package/dist/state-signing.d.ts +59 -0
  234. package/dist/state-signing.d.ts.map +1 -0
  235. package/dist/state-signing.js +83 -0
  236. package/dist/state-signing.js.map +1 -0
  237. package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
  238. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
  239. package/dist/storage/domains/audit/agent-audit.js +66 -0
  240. package/dist/storage/domains/audit/agent-audit.js.map +1 -0
  241. package/dist/storage/domains/audit/base.d.ts +140 -0
  242. package/dist/storage/domains/audit/base.d.ts.map +1 -0
  243. package/dist/storage/domains/audit/base.js +184 -0
  244. package/dist/storage/domains/audit/base.js.map +1 -0
  245. package/dist/storage/domains/audit/domain.d.ts +69 -0
  246. package/dist/storage/domains/audit/domain.d.ts.map +1 -0
  247. package/dist/storage/domains/audit/domain.js +167 -0
  248. package/dist/storage/domains/audit/domain.js.map +1 -0
  249. package/dist/storage/domains/channel-identity/base.d.ts +96 -0
  250. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
  251. package/dist/storage/domains/channel-identity/base.js +149 -0
  252. package/dist/storage/domains/channel-identity/base.js.map +1 -0
  253. package/dist/storage/domains/credentials/base.d.ts +134 -0
  254. package/dist/storage/domains/credentials/base.d.ts.map +1 -0
  255. package/dist/storage/domains/credentials/base.js +273 -0
  256. package/dist/storage/domains/credentials/base.js.map +1 -0
  257. package/dist/storage/domains/custom-providers/base.d.ts +57 -0
  258. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -0
  259. package/dist/storage/domains/custom-providers/base.js +145 -0
  260. package/dist/storage/domains/custom-providers/base.js.map +1 -0
  261. package/dist/storage/domains/intake/base.d.ts +38 -0
  262. package/dist/storage/domains/intake/base.d.ts.map +1 -0
  263. package/dist/storage/domains/intake/base.js +80 -0
  264. package/dist/storage/domains/intake/base.js.map +1 -0
  265. package/dist/storage/domains/integrations/base.d.ts +126 -0
  266. package/dist/storage/domains/integrations/base.d.ts.map +1 -0
  267. package/dist/storage/domains/integrations/base.js +317 -0
  268. package/dist/storage/domains/integrations/base.js.map +1 -0
  269. package/dist/storage/domains/memory-settings/base.d.ts +62 -0
  270. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -0
  271. package/dist/storage/domains/memory-settings/base.js +126 -0
  272. package/dist/storage/domains/memory-settings/base.js.map +1 -0
  273. package/dist/storage/domains/model-packs/base.d.ts +49 -0
  274. package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
  275. package/dist/storage/domains/model-packs/base.js +96 -0
  276. package/dist/storage/domains/model-packs/base.js.map +1 -0
  277. package/dist/storage/domains/projects/base.d.ts +58 -0
  278. package/dist/storage/domains/projects/base.d.ts.map +1 -0
  279. package/dist/storage/domains/projects/base.js +111 -0
  280. package/dist/storage/domains/projects/base.js.map +1 -0
  281. package/dist/storage/domains/queue-health/base.d.ts +52 -0
  282. package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
  283. package/dist/storage/domains/queue-health/base.js +122 -0
  284. package/dist/storage/domains/queue-health/base.js.map +1 -0
  285. package/dist/storage/domains/source-control/base.d.ts +358 -0
  286. package/dist/storage/domains/source-control/base.d.ts.map +1 -0
  287. package/dist/storage/domains/source-control/base.js +908 -0
  288. package/dist/storage/domains/source-control/base.js.map +1 -0
  289. package/dist/storage/domains/source-control/inmemory.d.ts +175 -0
  290. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
  291. package/dist/storage/domains/source-control/inmemory.js +377 -0
  292. package/dist/storage/domains/source-control/inmemory.js.map +1 -0
  293. package/dist/storage/domains/work-items/base.d.ts +412 -0
  294. package/dist/storage/domains/work-items/base.d.ts.map +1 -0
  295. package/dist/storage/domains/work-items/base.js +1309 -0
  296. package/dist/storage/domains/work-items/base.js.map +1 -0
  297. package/dist/storage/domains/work-items/metrics.d.ts +101 -0
  298. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
  299. package/dist/storage/domains/work-items/metrics.js +221 -0
  300. package/dist/storage/domains/work-items/metrics.js.map +1 -0
  301. package/dist/timing.d.ts +15 -0
  302. package/dist/timing.d.ts.map +1 -0
  303. package/dist/timing.js +34 -0
  304. package/dist/timing.js.map +1 -0
  305. package/dist/workspace.d.ts +24 -0
  306. package/dist/workspace.d.ts.map +1 -0
  307. package/dist/workspace.js +286 -0
  308. package/dist/workspace.js.map +1 -0
  309. package/factory-skills/configure-factory-rules/SKILL.md +67 -0
  310. package/factory-skills/factory-plan/SKILL.md +61 -0
  311. package/factory-skills/factory-review/SKILL.md +155 -0
  312. package/factory-skills/factory-triage/SKILL.md +77 -0
  313. package/package.json +81 -0
@@ -0,0 +1,483 @@
1
+ import { timedPhase } from "./timing.js";
2
+ import { buildAuthRoutes, createFactoryAuthGate, createFactoryRouteAuth, getFactoryAuthOrgId, getFactoryAuthUserId } from "./auth.js";
3
+ import { recordFactoryPullRequestProvenance } from "./integrations/github/provenance.js";
4
+ import { SandboxFleet } from "./sandbox/fleet.js";
5
+ import { releaseWorkItemSandboxes } from "./integrations/github/sandbox-release.js";
6
+ import { assertFactoryRules } from "./rules/validation.js";
7
+ import { PlatformGithubIntegration } from "./integrations/platform/github/integration.js";
8
+ import { PlatformLinearIntegration } from "./integrations/platform/linear/integration.js";
9
+ import { createCustomProvidersPrimer, registerCustomProvidersSource } from "./routes/custom-provider-source.js";
10
+ import { ProjectRoutes } from "./routes/projects.js";
11
+ import { FactoryTransitionService } from "./rules/transition-service.js";
12
+ import { ModelCredentialsStorage } from "./storage/domains/credentials/base.js";
13
+ import { createTenantCredentialPrimer, primeTenantCredentials, registerTenantCredentialResolver } from "./routes/tenant-credentials.js";
14
+ import { QueueHealthStorage } from "./storage/domains/queue-health/base.js";
15
+ import { WorkItemsStorage } from "./storage/domains/work-items/base.js";
16
+ import { assembleFactoryApiRoutes, buildIntegrationContext } from "./routes/surface.js";
17
+ import { builtInFactoryRules } from "./rules/defaults.js";
18
+ import { FactoryDecisionDispatcher } from "./rules/dispatcher.js";
19
+ import { FactoryPhaseStateProcessor } from "./rules/processor.js";
20
+ import { createFactoryTransitionTools } from "./rules/tools.js";
21
+ import { registerSandboxReattach } from "./sandbox/reattach.js";
22
+ import { handleServerError } from "./server-error.js";
23
+ import { createSpaStaticMiddleware, resolveUiDistDir } from "./spa-static.js";
24
+ import { createStateSigner } from "./state-signing.js";
25
+ import { observeAgentGitAction } from "./storage/domains/audit/agent-audit.js";
26
+ import { AuditStorage } from "./storage/domains/audit/base.js";
27
+ import { AuditDomain } from "./storage/domains/audit/domain.js";
28
+ import { ChannelIdentityStorage } from "./storage/domains/channel-identity/base.js";
29
+ import { CustomProvidersStorage } from "./storage/domains/custom-providers/base.js";
30
+ import { IntakeStorage } from "./storage/domains/intake/base.js";
31
+ import { IntegrationStorage } from "./storage/domains/integrations/base.js";
32
+ import { MemorySettingsStorage } from "./storage/domains/memory-settings/base.js";
33
+ import { ModelPacksStorage } from "./storage/domains/model-packs/base.js";
34
+ import { FactoryProjectsStorage } from "./storage/domains/projects/base.js";
35
+ import { SourceControlStorage } from "./storage/domains/source-control/base.js";
36
+ import { createWorkspaceFactory } from "./workspace.js";
37
+ import { hasAuthInit } from "@mastra/core/server";
38
+ import { MastraAuthStudio } from "@mastra/auth-studio";
39
+ import { prepareAgentControllerMount } from "@mastra/code-sdk";
40
+ import { LocalSandbox } from "@mastra/core/workspace";
41
+ //#region src/factory.ts
42
+ /**
43
+ * `MastraFactory` — the single entry point to the whole Mastra Software Factory.
44
+ *
45
+ * The consumer's deploy entry constructs deployment-specific config instances
46
+ * (auth adapter, pubsub) and passes them here explicitly. The only provider
47
+ * defaults constructed here are Platform GitHub and Linear integrations when
48
+ * Platform credentials exist and the caller did not provide those integrations.
49
+ *
50
+ * `prepare()` resolves feature readiness, threads every dependency explicitly,
51
+ * assembles the web routes/middleware, and returns the constructor args for
52
+ * `new Mastra(...)`. The literal `export const mastra = new Mastra(...)` must
53
+ * stay in the entry file — the deployer's `checkConfigExport` Babel plugin
54
+ * only marks the config valid when it finds that literal in the entry AST —
55
+ * so the factory produces args instead of the instance. `finalize()` runs the
56
+ * post-construct boot (controller init + workers).
57
+ *
58
+ * Integration readiness is derived from each instance's declared capabilities
59
+ * and the storage domains those capabilities require.
60
+ */
61
+ const CONTROLLER_ID = "code";
62
+ function hasPlatformSecretKey() {
63
+ return Boolean(process.env.MASTRA_PLATFORM_SECRET_KEY?.trim());
64
+ }
65
+ /**
66
+ * The template sandbox's own working directory, when it exposes one as a
67
+ * string (core `LocalSandbox` does; remote providers generally don't).
68
+ * Used as the default checkout base so a local template rooted at a host
69
+ * directory checks repos out under that same root.
70
+ */
71
+ function templateWorkingDirectory(sandbox) {
72
+ const wd = sandbox.workingDirectory;
73
+ return typeof wd === "string" && wd.length > 0 ? wd : void 0;
74
+ }
75
+ function resolveSandboxWorkdirBase(machine, configuredWorkdir) {
76
+ const machineWorkdir = templateWorkingDirectory(machine);
77
+ return ((configuredWorkdir === "/workspace" && machineWorkdir ? machineWorkdir : configuredWorkdir ?? machineWorkdir) ?? "/workspace").replace(/\/+$/, "");
78
+ }
79
+ /**
80
+ * Default auth provider — `MastraAuthStudio`, which proxies identity to the
81
+ * shared Mastra platform API. `MastraAuthStudio` resolves `MASTRA_SHARED_API_URL`,
82
+ * `MASTRA_ORGANIZATION_ID`, and `MASTRA_COOKIE_DOMAIN` from env on its own —
83
+ * this helper only derives a cookie-domain fallback from the factory's
84
+ * `publicUrl`.
85
+ *
86
+ * Cookie-domain resolution (Studio picks the first that wins):
87
+ * 1. explicit `MASTRA_COOKIE_DOMAIN` env, if set;
88
+ * 2. `.mastra.ai` when `sharedApiUrl` is on `.mastra.ai`;
89
+ * 3. this parent-domain fallback derived from `publicUrl` — so a deploy on
90
+ * `https://foo.mastra.cloud` mints cookies with `Domain=.mastra.cloud`
91
+ * without the caller wiring the env var by hand.
92
+ * 4. otherwise host-only (no `Domain=`), which is correct for `localhost`.
93
+ */
94
+ function buildDefaultStudioAuth(publicUrl) {
95
+ return new MastraAuthStudio({ cookieDomain: parentDomainFromPublicUrl(publicUrl) });
96
+ }
97
+ /**
98
+ * Derive a parent cookie domain from `publicUrl` by stripping the leftmost
99
+ * label — the same shape platform-API's env injection uses (see
100
+ * `platform/servers/api/src/lib/studio-env-vars.ts`: `.${routingDomain.replace(/^[^.]+\./, '')}`).
101
+ *
102
+ * Rather than a generic `strip-left-label` heuristic — which either emits
103
+ * cookies scoped to a public suffix (`sub.example.co.uk` → `.example.co.uk`
104
+ * requires PSL data to be safe) or misclassifies numeric hostnames like
105
+ * `3scale.example.com` as IPv4 — we only derive a parent domain when the
106
+ * host sits under one of the platform's known registrable domains. Anything
107
+ * else (custom domains, arbitrary tenant hostnames, IPs, `localhost`)
108
+ * falls through to host-only cookies. Callers that need a different scope
109
+ * pass `MASTRA_COOKIE_DOMAIN` explicitly (Studio honors that first).
110
+ */
111
+ const KNOWN_PLATFORM_COOKIE_PARENTS = ["mastra.cloud", "mastra.ai"];
112
+ function isIpLiteral(hostname) {
113
+ if (hostname.includes(":")) return true;
114
+ return /^\d+(?:\.\d+){3}$/.test(hostname);
115
+ }
116
+ function parentDomainFromPublicUrl(publicUrl) {
117
+ let hostname;
118
+ try {
119
+ hostname = new URL(publicUrl).hostname.toLowerCase();
120
+ } catch {
121
+ return;
122
+ }
123
+ if (hostname === "localhost" || isIpLiteral(hostname)) return void 0;
124
+ for (const parent of KNOWN_PLATFORM_COOKIE_PARENTS) {
125
+ if (hostname === parent) return void 0;
126
+ if (hostname.endsWith(`.${parent}`)) return `.${parent}`;
127
+ }
128
+ }
129
+ var MastraFactory = class {
130
+ #config;
131
+ #prepared;
132
+ #dispatcher;
133
+ #factoryProcessor;
134
+ #preparing = false;
135
+ constructor(config) {
136
+ if (!config?.storage) throw new Error("MastraFactory: 'storage' is required. Pass a FactoryStorage backend — e.g. new PgFactoryStorage({ connectionString }) from '@mastra/pg' for deployments, or new LibSQLFactoryStorage({ url }) from '@mastra/libsql' for local dev.");
137
+ this.#config = config;
138
+ }
139
+ /**
140
+ * Resolve feature readiness, wire every dependency explicitly, and assemble
141
+ * everything needed to construct the server-owned Mastra. Returns the args
142
+ * for the `new Mastra(...)` literal that must live in the entry file.
143
+ */
144
+ async prepare() {
145
+ if (this.#preparing) throw new Error("MastraFactory.prepare() called twice");
146
+ this.#preparing = true;
147
+ const publicOrigin = (this.#config.publicUrl ?? "http://localhost:4111").replace(/\/+$/, "");
148
+ const allowedOrigins = (this.#config.allowedOrigins ?? []).map((o) => o.replace(/\/+$/, "")).filter(Boolean);
149
+ const storage = this.#config.storage;
150
+ const vector = this.#config.vector;
151
+ const pubsub = this.#config.pubsub;
152
+ const configuredAuth = this.#config.auth;
153
+ const auth = configuredAuth === null ? void 0 : configuredAuth ?? buildDefaultStudioAuth(publicOrigin);
154
+ const routeAuth = createFactoryRouteAuth(auth);
155
+ const integrations = [...this.#config.integrations ?? []];
156
+ if (hasPlatformSecretKey()) {
157
+ if (!integrations.some((integration) => integration.id === "github")) integrations.push(new PlatformGithubIntegration({ runIssueTriage: this.#config.platform?.runIssueTriage }));
158
+ if (!integrations.some((integration) => integration.id === "linear")) integrations.push(new PlatformLinearIntegration());
159
+ }
160
+ const integrationIds = /* @__PURE__ */ new Set();
161
+ for (const integration of integrations) {
162
+ if (integrationIds.has(integration.id)) throw new Error(`MastraFactory: duplicate integration id '${integration.id}' in 'integrations'.`);
163
+ integrationIds.add(integration.id);
164
+ }
165
+ const rules = this.#config.rules ?? builtInFactoryRules();
166
+ assertFactoryRules(rules);
167
+ const intakeStorage = storage.registerDomain(new IntakeStorage());
168
+ const auditStorage = storage.registerDomain(new AuditStorage());
169
+ const workItemsStorage = storage.registerDomain(new WorkItemsStorage());
170
+ const modelCredentialsStorage = storage.registerDomain(new ModelCredentialsStorage());
171
+ const modelPacksStorage = storage.registerDomain(new ModelPacksStorage());
172
+ const memorySettingsStorage = storage.registerDomain(new MemorySettingsStorage());
173
+ const customProvidersStorage = storage.registerDomain(new CustomProvidersStorage());
174
+ const queueHealthStorage = storage.registerDomain(new QueueHealthStorage());
175
+ const integrationStorage = storage.registerDomain(new IntegrationStorage());
176
+ const factoryProjectsStorage = storage.registerDomain(new FactoryProjectsStorage());
177
+ const sourceControlStorage = storage.registerDomain(new SourceControlStorage());
178
+ const domains = {
179
+ intake: intakeStorage,
180
+ modelCredentials: modelCredentialsStorage,
181
+ modelPacks: modelPacksStorage,
182
+ memorySettings: memorySettingsStorage,
183
+ customProviders: customProvidersStorage,
184
+ projects: factoryProjectsStorage,
185
+ queueHealth: queueHealthStorage,
186
+ workItems: workItemsStorage,
187
+ channelIdentity: storage.registerDomain(new ChannelIdentityStorage())
188
+ };
189
+ const projectRoutes = new ProjectRoutes({
190
+ auth: routeAuth,
191
+ projects: factoryProjectsStorage,
192
+ sourceControl: sourceControlStorage,
193
+ versionControlIntegrationIds: integrations.filter((integration) => integration.versionControl).map((integration) => integration.id)
194
+ });
195
+ const auditDomain = new AuditDomain({
196
+ auth: routeAuth,
197
+ audit: auditStorage,
198
+ projects: factoryProjectsStorage,
199
+ sinks: integrations,
200
+ agentTenant: (requestContext) => {
201
+ const user = requestContext.get("user");
202
+ return {
203
+ orgId: getFactoryAuthOrgId(user),
204
+ userId: getFactoryAuthUserId(user)
205
+ };
206
+ }
207
+ });
208
+ const sandboxConfig = this.#config.sandbox;
209
+ const machine = sandboxConfig?.machine;
210
+ if (machine && typeof machine.clone !== "function") throw new Error(`MastraFactory: the configured sandbox machine (provider '${machine.provider}') does not implement clone(). Project repositories each get their own sandbox cloned from the configured machine. Pass a machine that implements clone() — e.g. RailwaySandbox (@mastra/railway) or LocalSandbox (@mastra/core/workspace) — or omit 'sandbox' to disable sandboxes.`);
211
+ const fleet = new SandboxFleet(machine ? {
212
+ machine,
213
+ workdirBase: resolveSandboxWorkdirBase(machine, sandboxConfig?.workdir),
214
+ maxSandboxes: sandboxConfig?.maxSandboxes
215
+ } : void 0);
216
+ registerSandboxReattach(fleet);
217
+ const stateSigner = createStateSigner(this.#config.stateSecret);
218
+ if (auth && hasAuthInit(auth)) await timedPhase("prepare.auth.init", () => auth.init({
219
+ database: storage.authDatabase?.(),
220
+ publicUrl: publicOrigin,
221
+ allowedOrigins
222
+ }));
223
+ await timedPhase("prepare.storage.init", () => storage.init());
224
+ if (auth) registerTenantCredentialResolver(modelCredentialsStorage);
225
+ registerCustomProvidersSource({
226
+ storage: customProvidersStorage,
227
+ authEnabled: Boolean(auth)
228
+ });
229
+ for (const integration of integrations) {
230
+ integration.initialize?.({
231
+ storage: integrationStorage.forIntegration(integration.id),
232
+ projects: factoryProjectsStorage,
233
+ auth: routeAuth
234
+ });
235
+ if (integration.versionControl) integration.versionControl.initialize({ storage: sourceControlStorage.forIntegration(integration.id) });
236
+ }
237
+ const integrationRegistrations = integrations.map((integration) => {
238
+ const requiredDomains = [
239
+ "integrations",
240
+ ...integration.versionControl ? ["source-control"] : [],
241
+ ...integration.channels ? ["channel-identity"] : []
242
+ ];
243
+ return {
244
+ integration,
245
+ ready: requiredDomains.every((domain) => storage.isDomainReady(domain)),
246
+ ensureReady: async () => {
247
+ for (const domain of requiredDomains) await storage.ensureDomainReady(domain);
248
+ }
249
+ };
250
+ });
251
+ const intakeReady = integrations.some((integration) => integration.intake !== void 0) && storage.isDomainReady("intake");
252
+ const factoryReady = storage.isDomainReady("projects") && storage.isDomainReady("work-items");
253
+ const githubIntegration = integrations.find((integration) => integration.id === "github");
254
+ const workItemsReady = storage.isDomainReady("work-items");
255
+ const releaseTerminalSandboxes = machine && !(machine instanceof LocalSandbox) && workItemsReady && storage.isDomainReady("source-control") ? async ({ orgId, workItemId }) => releaseWorkItemSandboxes({
256
+ workItems: workItemsStorage,
257
+ sourceControl: sourceControlStorage.forIntegration("github"),
258
+ fleet,
259
+ orgId,
260
+ workItemId
261
+ }) : void 0;
262
+ const transitionService = workItemsReady ? new FactoryTransitionService({
263
+ rules,
264
+ storage: workItemsStorage,
265
+ ...releaseTerminalSandboxes ? { onTerminalStage: releaseTerminalSandboxes } : {}
266
+ }) : void 0;
267
+ const factoryProcessor = workItemsReady ? new FactoryPhaseStateProcessor({
268
+ rules,
269
+ storage: workItemsStorage,
270
+ ...transitionService ? { transitionService } : {},
271
+ ...githubIntegration ? { recordPullRequestProvenance: (input) => recordFactoryPullRequestProvenance(githubIntegration, sourceControlStorage.forIntegration("github"), integrationStorage.forIntegration("github"), input) } : {},
272
+ messageReader: { listMessages: async (input) => {
273
+ const memory = await storage.getMastraStorage().getStore("memory");
274
+ return memory ? memory.listMessages(input) : {
275
+ messages: [],
276
+ hasMore: false
277
+ };
278
+ } }
279
+ }) : void 0;
280
+ for (const { integration } of integrationRegistrations) if (integration.requiresStableStateSigner && !stateSigner.stable) throw new Error(`MastraFactory: integration '${integration.id}' signs OAuth state and requires a replica-stable state secret, but none is configured. Set 'stateSecret' on the factory config.`);
281
+ const mastraStorageBackend = (() => {
282
+ for (let proto = Object.getPrototypeOf(storage); proto; proto = Object.getPrototypeOf(proto)) {
283
+ if (proto.constructor?.name === "PgFactoryStorage") return "pg";
284
+ if (proto.constructor?.name === "LibSQLFactoryStorage") return "libsql";
285
+ }
286
+ })();
287
+ const toolIntegrations = integrationRegistrations.filter(({ integration }) => integration.agentTools || integration.sessionTools);
288
+ const prepared = await timedPhase("prepare.controllerMount", () => prepareAgentControllerMount({
289
+ controllerId: CONTROLLER_ID,
290
+ workspace: createWorkspaceFactory({
291
+ ...this.#config.sandbox ? { sandbox: this.#config.sandbox } : {},
292
+ ...githubIntegration ? { github: githubIntegration } : {},
293
+ ...workItemsStorage ? { workItems: workItemsStorage } : {},
294
+ fleet
295
+ }),
296
+ disableGithubSignals: true,
297
+ disableSettingsOmSeed: true,
298
+ storage: storage.getMastraStorage(),
299
+ ...mastraStorageBackend ? { storageBackend: mastraStorageBackend } : {},
300
+ ...factoryProcessor ? { inputProcessors: [factoryProcessor] } : {},
301
+ ...vector ? { vector } : {},
302
+ ...toolIntegrations.length > 0 || workItemsStorage && transitionService ? { extraTools: async ({ requestContext }) => {
303
+ const tools = {};
304
+ const toolOwners = /* @__PURE__ */ new Map();
305
+ const mergeTools = (ownerId, contributed) => {
306
+ for (const [name, tool] of Object.entries(contributed)) {
307
+ const owner = toolOwners.get(name);
308
+ if (owner) throw new Error(`MastraFactory: integration tool '${name}' from '${ownerId}' conflicts with '${owner}'.`);
309
+ toolOwners.set(name, ownerId);
310
+ tools[name] = tool;
311
+ }
312
+ };
313
+ if (workItemsStorage && transitionService) mergeTools("factory", await createFactoryTransitionTools({
314
+ requestContext,
315
+ storage: workItemsStorage,
316
+ transitionService
317
+ }));
318
+ for (const { integration, ready, ensureReady } of toolIntegrations) {
319
+ if (!ready && ensureReady) try {
320
+ await ensureReady();
321
+ } catch {
322
+ continue;
323
+ }
324
+ if (integration.agentTools) mergeTools(integration.id, await integration.agentTools({ requestContext }));
325
+ if (integration.sessionTools) mergeTools(integration.id, integration.sessionTools({ requestContext }));
326
+ }
327
+ return tools;
328
+ } } : {},
329
+ postToolObserver: async (toolContext) => {
330
+ const requestContext = toolContext.context?.requestContext;
331
+ if (requestContext) await observeAgentGitAction({
332
+ audit: auditDomain,
333
+ toolContext: {
334
+ ...toolContext,
335
+ context: requestContext
336
+ }
337
+ });
338
+ await Promise.all(integrations.map(async (integration) => {
339
+ if (!integration.postToolObserver) return;
340
+ try {
341
+ await integration.postToolObserver({
342
+ toolContext,
343
+ requestContext
344
+ });
345
+ } catch (error) {
346
+ console.warn(`[factory] Integration '${integration.id}' post-tool observer failed:`, error);
347
+ }
348
+ }));
349
+ },
350
+ ...pubsub ? {
351
+ pubsub,
352
+ crossProcessPubSub: true
353
+ } : {},
354
+ buildApiRoutes: ({ controller, authStorage }) => [
355
+ ...auth ? buildAuthRoutes(auth, { publicUrl: publicOrigin }) : [],
356
+ ...assembleFactoryApiRoutes({
357
+ controllerId: CONTROLLER_ID,
358
+ controller,
359
+ auth: routeAuth,
360
+ authStorage,
361
+ audit: auditDomain,
362
+ publicOrigin,
363
+ stateSigner,
364
+ fleet,
365
+ factoryStorage: storage,
366
+ integrationStorage,
367
+ sourceControlStorage,
368
+ domains,
369
+ integrations: integrationRegistrations,
370
+ intakeReady,
371
+ factoryReady,
372
+ rules,
373
+ factoryTransitionService: transitionService,
374
+ onFactoryRuntime: ({ transitionService: runtimeTransitionService, prepareBinding }) => {
375
+ this.#dispatcher ??= new FactoryDecisionDispatcher({
376
+ controller,
377
+ transitionService: runtimeTransitionService,
378
+ storage: storage.getDomain("work-items"),
379
+ reconcileToolResults: () => factoryProcessor?.reconcileAllBoundThreads() ?? Promise.resolve(),
380
+ prepareBinding,
381
+ primeCredentials: (tenant) => primeTenantCredentials({
382
+ tenant,
383
+ credentials: modelCredentialsStorage
384
+ })
385
+ });
386
+ }
387
+ }),
388
+ ...projectRoutes.routes(),
389
+ ...auditDomain.routes()
390
+ ],
391
+ buildServerConfig: () => {
392
+ const cors = allowedOrigins.length ? { cors: {
393
+ origin: allowedOrigins,
394
+ credentials: true
395
+ } } : {};
396
+ const onError = { onError: handleServerError };
397
+ const uiDist = resolveUiDistDir();
398
+ const spa = uiDist ? [createSpaStaticMiddleware(uiDist)] : [];
399
+ if (!auth) return {
400
+ middleware: [createCustomProvidersPrimer({
401
+ auth: routeAuth,
402
+ storage: customProvidersStorage,
403
+ authEnabled: false
404
+ }), ...spa],
405
+ ...cors,
406
+ ...onError
407
+ };
408
+ return {
409
+ auth,
410
+ middleware: [
411
+ createFactoryAuthGate(auth),
412
+ createTenantCredentialPrimer({
413
+ auth: routeAuth,
414
+ credentials: modelCredentialsStorage
415
+ }),
416
+ createCustomProvidersPrimer({
417
+ auth: routeAuth,
418
+ storage: customProvidersStorage,
419
+ authEnabled: Boolean(auth)
420
+ }),
421
+ ...spa
422
+ ],
423
+ ...cors,
424
+ ...onError
425
+ };
426
+ }
427
+ }));
428
+ this.#prepared = prepared;
429
+ this.#factoryProcessor = factoryProcessor;
430
+ const channelRegistrations = integrationRegistrations.filter(({ integration, ready }) => ready && integration.channels);
431
+ if (channelRegistrations.length > 1) throw new Error(`MastraFactory: integrations [${channelRegistrations.map(({ integration }) => integration.id).join(", ")}] all provide channels, but only one may. Remove all but one.`);
432
+ for (const { integration } of channelRegistrations) prepared.base.controller.setChannels(integration.channels(buildIntegrationContext({
433
+ controller: prepared.base.controller,
434
+ publicOrigin,
435
+ auth: routeAuth,
436
+ stateSigner,
437
+ fleet,
438
+ factoryStorage: storage,
439
+ integrationStorage,
440
+ sourceControlStorage,
441
+ rules,
442
+ factoryReady,
443
+ domains
444
+ }, integration.id)));
445
+ const integrationWorkers = integrationRegistrations.filter(({ integration, ready }) => ready && integration.workers).flatMap(({ integration }) => integration.workers(buildIntegrationContext({
446
+ controller: prepared.base.controller,
447
+ publicOrigin,
448
+ auth: routeAuth,
449
+ stateSigner,
450
+ fleet,
451
+ factoryStorage: storage,
452
+ integrationStorage,
453
+ sourceControlStorage,
454
+ rules,
455
+ factoryReady,
456
+ domains
457
+ }, integration.id)));
458
+ return {
459
+ ...prepared.mastraArgs,
460
+ ...auth ? { studio: { auth } } : {},
461
+ ...integrationWorkers.length > 0 ? { workers: integrationWorkers } : {}
462
+ };
463
+ }
464
+ /**
465
+ * Post-construct boot: initialize the controller (which inherits the
466
+ * constructed Mastra's storage) and start its workers. Call AFTER the entry
467
+ * has run `new Mastra(prepare()'s args)`.
468
+ */
469
+ async finalize() {
470
+ if (!this.#prepared) throw new Error("MastraFactory.finalize() called before prepare()");
471
+ await timedPhase("finalize.controller", () => this.#prepared.finalize());
472
+ await timedPhase("finalize.reconcileBoundThreads", () => this.#factoryProcessor?.reconcileAllBoundThreads() ?? Promise.resolve());
473
+ this.#dispatcher?.start();
474
+ }
475
+ /** Stop Factory-owned background dispatch before the host process shuts down. */
476
+ async shutdown() {
477
+ await this.#dispatcher?.stop();
478
+ }
479
+ };
480
+ //#endregion
481
+ export { MastraFactory };
482
+
483
+ //# sourceMappingURL=factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.js","names":["#config","#preparing","#dispatcher","#prepared","#factoryProcessor"],"sources":["../src/factory.ts"],"sourcesContent":["/**\n * `MastraFactory` — the single entry point to the whole Mastra Software Factory.\n *\n * The consumer's deploy entry constructs deployment-specific config instances\n * (auth adapter, pubsub) and passes them here explicitly. The only provider\n * defaults constructed here are Platform GitHub and Linear integrations when\n * Platform credentials exist and the caller did not provide those integrations.\n *\n * `prepare()` resolves feature readiness, threads every dependency explicitly,\n * assembles the web routes/middleware, and returns the constructor args for\n * `new Mastra(...)`. The literal `export const mastra = new Mastra(...)` must\n * stay in the entry file — the deployer's `checkConfigExport` Babel plugin\n * only marks the config valid when it finds that literal in the entry AST —\n * so the factory produces args instead of the instance. `finalize()` runs the\n * post-construct boot (controller init + workers).\n *\n * Integration readiness is derived from each instance's declared capabilities\n * and the storage domains those capabilities require.\n */\n\nimport { MastraAuthStudio } from '@mastra/auth-studio';\nimport { prepareAgentControllerMount } from '@mastra/code-sdk';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { hasAuthInit } from '@mastra/core/server';\nimport type { IMastraAuthProvider } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { LocalSandbox } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { FactoryAuthUser } from './auth.js';\nimport {\n buildAuthRoutes,\n createFactoryAuthGate,\n createFactoryRouteAuth,\n getFactoryAuthOrgId,\n getFactoryAuthUserId,\n} from './auth.js';\nimport type { FactoryIntegration, IntegrationPostToolContext, IntegrationTools } from './integrations/base.js';\nimport type { GithubIntegration } from './integrations/github/integration.js';\nimport type { GithubIssueTriageInput, GithubIssueTriageResult } from './integrations/github/issue-triage.js';\nimport { recordFactoryPullRequestProvenance } from './integrations/github/provenance.js';\nimport { releaseWorkItemSandboxes } from './integrations/github/sandbox-release.js';\nimport { PlatformGithubIntegration } from './integrations/platform/github/integration.js';\nimport { PlatformLinearIntegration } from './integrations/platform/linear/integration.js';\nimport { createCustomProvidersPrimer, registerCustomProvidersSource } from './routes/custom-provider-source.js';\nimport { ProjectRoutes } from './routes/projects.js';\nimport { assembleFactoryApiRoutes, buildIntegrationContext } from './routes/surface.js';\nimport type { FactoryApiRoutesDeps } from './routes/surface.js';\nimport {\n createTenantCredentialPrimer,\n primeTenantCredentials,\n registerTenantCredentialResolver,\n} from './routes/tenant-credentials.js';\nimport { builtInFactoryRules } from './rules/defaults.js';\nimport { FactoryDecisionDispatcher } from './rules/dispatcher.js';\nimport { FactoryPhaseStateProcessor } from './rules/processor.js';\nimport { createFactoryTransitionTools } from './rules/tools.js';\nimport { FactoryTransitionService } from './rules/transition-service.js';\nimport type { FactoryRules } from './rules/types.js';\nimport { assertFactoryRules } from './rules/validation.js';\nimport { SandboxFleet } from './sandbox/fleet.js';\nimport { registerSandboxReattach } from './sandbox/reattach.js';\nimport { handleServerError } from './server-error.js';\nimport { createSpaStaticMiddleware, resolveUiDistDir } from './spa-static.js';\nimport { createStateSigner } from './state-signing.js';\nimport { observeAgentGitAction } from './storage/domains/audit/agent-audit.js';\nimport { AuditStorage } from './storage/domains/audit/base.js';\nimport { AuditDomain } from './storage/domains/audit/domain.js';\nimport { ChannelIdentityStorage } from './storage/domains/channel-identity/base.js';\nimport { ModelCredentialsStorage } from './storage/domains/credentials/base.js';\nimport { CustomProvidersStorage } from './storage/domains/custom-providers/base.js';\nimport { IntakeStorage } from './storage/domains/intake/base.js';\nimport { IntegrationStorage } from './storage/domains/integrations/base.js';\nimport { MemorySettingsStorage } from './storage/domains/memory-settings/base.js';\nimport { ModelPacksStorage } from './storage/domains/model-packs/base.js';\nimport { FactoryProjectsStorage } from './storage/domains/projects/base.js';\nimport { QueueHealthStorage } from './storage/domains/queue-health/base.js';\nimport { SourceControlStorage } from './storage/domains/source-control/base.js';\nimport { WorkItemsStorage } from './storage/domains/work-items/base.js';\nimport { timedPhase } from './timing.js';\nimport { createWorkspaceFactory } from './workspace.js';\n\ntype BuildApiRoutesDeps = Pick<FactoryApiRoutesDeps, 'controller' | 'authStorage'>;\n\n/** Constructor args for the `new Mastra(...)` literal in the deploy entry. */\nexport type MastraArgs = NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n\nexport interface MastraFactoryConfig {\n /**\n * Auth provider instance — `MastraAuthStudio` (`@mastra/auth-studio`),\n * `MastraAuthWorkos` (`@mastra/auth-workos`), `MastraAuthBetterAuth`\n * (`@mastra/auth-better-auth`), or any custom `MastraAuthProvider`. Whatever\n * instance is passed is the active provider; a passed instance is always\n * honored as-is.\n *\n * Omitted → the factory defaults to `MastraAuthStudio`, proxying auth\n * through the shared Mastra platform API. `MastraAuthStudio` resolves its\n * own env (`MASTRA_SHARED_API_URL`, `MASTRA_ORGANIZATION_ID`,\n * `MASTRA_COOKIE_DOMAIN`).\n *\n * Pass `null` to disable auth entirely (open server, local-dev behavior)\n * without falling back to the default.\n */\n auth?: IMastraAuthProvider | null;\n /**\n * REQUIRED. Factory storage backend powering BOTH agent storage (threads,\n * messages, memory, OM — via `getMastraStorage()`) and the app tables\n * (projects/source-control/audit/intake — via the generic ops surface). Pass a\n * `PgFactoryStorage` (`@mastra/pg`) for deployments or a\n * `LibSQLFactoryStorage` (`@mastra/libsql`) for local dev — one backend,\n * one connection, every feature on.\n */\n storage: FactoryStorage;\n /**\n * Vector store instance for recall search — `PgVector` (`@mastra/pg`) on\n * the same database as `storage`. Omitted → the SDK mount's default vector\n * store resolution applies.\n */\n vector?: MastraVector;\n /**\n * Distributed event bus instance (e.g. `new RedisStreamsPubSub({ url })`).\n * When set, streams/workflows/signals ride it across processes and the\n * controller drops file-based thread locks in favor of pubsub-coordinated\n * leases. Omitted → in-process default.\n */\n pubsub?: PubSub;\n /**\n * Browser-facing origin used to build integration OAuth/install callback\n * URLs and to derive the auth redirect URI. On the platform the SPA is\n * hosted separately, so this MUST be the public API origin.\n * Default: `http://localhost:4111` (the local Factory server, which also\n * serves the UI).\n */\n publicUrl?: string;\n /**\n * Allowed cross-origin SPA origins. The SPA may be served from a separate\n * static host, so credentialed requests must be explicitly allowed.\n */\n allowedOrigins?: string[];\n /** Sandbox configuration. Omitted → repository sandboxes are disabled. */\n sandbox?: MastraFactorySandboxConfig;\n /**\n * Deployment-stable secret for signing integration OAuth `state` values.\n * Omitted → a per-process random secret, which is fine for single-process\n * local development but rejected for integrations that declare\n * `requiresStableStateSigner`.\n */\n stateSecret?: string;\n /**\n * Registered capability providers. The factory registers the pieces each\n * `FactoryIntegration` instance provides — HTTP routes, storage domains,\n * agent/session tools, intake, source control, and diagnostics — into the\n * system. When Platform credentials are configured, missing `github` and\n * `linear` integrations default to their Platform-backed implementations.\n */\n integrations?: FactoryIntegration[];\n /**\n * Authoritative Factory board, tool-result, and GitHub-event rules. Construct\n * with `defaultFactoryRules({ version, overrides })` so deployment policy has\n * an explicit version and exact handler leaves replace rather than compose.\n * Omitted → conservative built-in rules for the current deployment.\n */\n rules?: FactoryRules;\n\n /**\n * Platform-specific overrides. When the Platform-backed GitHub integration\n * is active, it derives a `runIssueTriage` runner from the mounted\n * controller automatically. An explicit `runIssueTriage` here takes\n * precedence over the controller-derived default.\n */\n platform?: {\n runIssueTriage?: (input: GithubIssueTriageInput) => Promise<GithubIssueTriageResult>;\n };\n}\n\nexport interface MastraFactorySandboxConfig {\n /**\n * Template machine — `RailwaySandbox` (`@mastra/railway`), core\n * `LocalSandbox` (`@mastra/core/workspace`), or any `WorkspaceSandbox` that\n * implements `clone()`. Each project-repository execution environment gets\n * its own sandbox cloned from this machine; the machine itself is never\n * started. `prepare()` fails fast when the instance lacks `clone()`.\n */\n machine: WorkspaceSandbox;\n /**\n * In-sandbox base directory repos check out under (nested `owner/name` per\n * repo). Default: the machine's own `workingDirectory` when it exposes one\n * (core `LocalSandbox` does), else `/workspace`.\n */\n workdir?: string;\n /**\n * Per-replica cap on concurrently provisioned sandboxes. `0`/omitted means\n * unlimited. A lightweight per-process budget, not a cross-replica scheduler.\n */\n maxSandboxes?: number;\n}\n\nconst CONTROLLER_ID = 'code';\n\nfunction hasPlatformSecretKey(): boolean {\n return Boolean(process.env.MASTRA_PLATFORM_SECRET_KEY?.trim());\n}\n\n/**\n * The template sandbox's own working directory, when it exposes one as a\n * string (core `LocalSandbox` does; remote providers generally don't).\n * Used as the default checkout base so a local template rooted at a host\n * directory checks repos out under that same root.\n */\nfunction templateWorkingDirectory(sandbox: WorkspaceSandbox): string | undefined {\n const wd = (sandbox as { workingDirectory?: unknown }).workingDirectory;\n return typeof wd === 'string' && wd.length > 0 ? wd : undefined;\n}\n\nfunction resolveSandboxWorkdirBase(machine: WorkspaceSandbox, configuredWorkdir?: string): string {\n const machineWorkdir = templateWorkingDirectory(machine);\n const workdir =\n configuredWorkdir === '/workspace' && machineWorkdir ? machineWorkdir : (configuredWorkdir ?? machineWorkdir);\n return (workdir ?? '/workspace').replace(/\\/+$/, '');\n}\n\n/**\n * Default auth provider — `MastraAuthStudio`, which proxies identity to the\n * shared Mastra platform API. `MastraAuthStudio` resolves `MASTRA_SHARED_API_URL`,\n * `MASTRA_ORGANIZATION_ID`, and `MASTRA_COOKIE_DOMAIN` from env on its own —\n * this helper only derives a cookie-domain fallback from the factory's\n * `publicUrl`.\n *\n * Cookie-domain resolution (Studio picks the first that wins):\n * 1. explicit `MASTRA_COOKIE_DOMAIN` env, if set;\n * 2. `.mastra.ai` when `sharedApiUrl` is on `.mastra.ai`;\n * 3. this parent-domain fallback derived from `publicUrl` — so a deploy on\n * `https://foo.mastra.cloud` mints cookies with `Domain=.mastra.cloud`\n * without the caller wiring the env var by hand.\n * 4. otherwise host-only (no `Domain=`), which is correct for `localhost`.\n */\nfunction buildDefaultStudioAuth(publicUrl: string): IMastraAuthProvider {\n return new MastraAuthStudio({\n cookieDomain: parentDomainFromPublicUrl(publicUrl),\n });\n}\n\n/**\n * Derive a parent cookie domain from `publicUrl` by stripping the leftmost\n * label — the same shape platform-API's env injection uses (see\n * `platform/servers/api/src/lib/studio-env-vars.ts`: `.${routingDomain.replace(/^[^.]+\\./, '')}`).\n *\n * Rather than a generic `strip-left-label` heuristic — which either emits\n * cookies scoped to a public suffix (`sub.example.co.uk` → `.example.co.uk`\n * requires PSL data to be safe) or misclassifies numeric hostnames like\n * `3scale.example.com` as IPv4 — we only derive a parent domain when the\n * host sits under one of the platform's known registrable domains. Anything\n * else (custom domains, arbitrary tenant hostnames, IPs, `localhost`)\n * falls through to host-only cookies. Callers that need a different scope\n * pass `MASTRA_COOKIE_DOMAIN` explicitly (Studio honors that first).\n */\nconst KNOWN_PLATFORM_COOKIE_PARENTS = ['mastra.cloud', 'mastra.ai'] as const;\n\nfunction isIpLiteral(hostname: string): boolean {\n // IPv6 addresses in URLs are bracketed; `URL.hostname` strips the brackets\n // but the address itself still contains `:`. IPv4 is four dot-separated\n // numeric octets — trust the parser to have already validated shape.\n if (hostname.includes(':')) return true;\n return /^\\d+(?:\\.\\d+){3}$/.test(hostname);\n}\n\nfunction parentDomainFromPublicUrl(publicUrl: string): string | undefined {\n let hostname: string;\n try {\n hostname = new URL(publicUrl).hostname.toLowerCase();\n } catch {\n return undefined;\n }\n if (hostname === 'localhost' || isIpLiteral(hostname)) return undefined;\n for (const parent of KNOWN_PLATFORM_COOKIE_PARENTS) {\n // Exact match → we're already on the parent, host-only is correct.\n // Subdomain match → mint the parent-scoped cookie.\n if (hostname === parent) return undefined;\n if (hostname.endsWith(`.${parent}`)) return `.${parent}`;\n }\n return undefined;\n}\n\nexport class MastraFactory {\n readonly #config: MastraFactoryConfig;\n #prepared: Awaited<ReturnType<typeof prepareAgentControllerMount>> | undefined;\n #dispatcher: FactoryDecisionDispatcher | undefined;\n #factoryProcessor: FactoryPhaseStateProcessor | undefined;\n #preparing = false;\n\n constructor(config: MastraFactoryConfig) {\n if (!config?.storage) {\n throw new Error(\n \"MastraFactory: 'storage' is required. Pass a FactoryStorage backend — e.g. \" +\n \"new PgFactoryStorage({ connectionString }) from '@mastra/pg' for deployments, or \" +\n \"new LibSQLFactoryStorage({ url }) from '@mastra/libsql' for local dev.\",\n );\n }\n this.#config = config;\n }\n\n /**\n * Resolve feature readiness, wire every dependency explicitly, and assemble\n * everything needed to construct the server-owned Mastra. Returns the args\n * for the `new Mastra(...)` literal that must live in the entry file.\n */\n async prepare(): Promise<MastraArgs> {\n // Guard set synchronously (before the first await) so overlapping calls —\n // not just strictly sequential ones — can't double-seed the runtime\n // registry or double-run one-time adapter init.\n if (this.#preparing) throw new Error('MastraFactory.prepare() called twice');\n this.#preparing = true;\n\n const publicOrigin = (this.#config.publicUrl ?? 'http://localhost:4111').replace(/\\/+$/, '');\n const allowedOrigins = (this.#config.allowedOrigins ?? []).map(o => o.replace(/\\/+$/, '')).filter(Boolean);\n const storage = this.#config.storage;\n const vector = this.#config.vector;\n const pubsub = this.#config.pubsub;\n // Default auth: honor an explicitly-passed provider (including `null` to\n // disable auth) as-is; otherwise fall back to `MastraAuthStudio`\n // (platform-proxied identity). The default derives its cookie domain\n // from `publicUrl` — deploys on `<sub>.mastra.cloud` mint parent-domain\n // cookies without the caller wiring `MASTRA_COOKIE_DOMAIN` explicitly.\n const configuredAuth = this.#config.auth;\n const auth: IMastraAuthProvider | undefined =\n configuredAuth === null ? undefined : (configuredAuth ?? buildDefaultStudioAuth(publicOrigin));\n // One RouteAuth seam per boot, closed over the resolved provider. Every\n // factory route module receives this handle — no service locator.\n const routeAuth = createFactoryRouteAuth(auth);\n\n // Explicit integrations win. Platform credentials fill only missing GitHub\n // and Linear slots so callers can override either provider independently.\n const integrations = [...(this.#config.integrations ?? [])];\n if (hasPlatformSecretKey()) {\n if (!integrations.some(integration => integration.id === 'github')) {\n integrations.push(\n new PlatformGithubIntegration({\n runIssueTriage: this.#config.platform?.runIssueTriage,\n }),\n );\n }\n if (!integrations.some(integration => integration.id === 'linear')) {\n integrations.push(new PlatformLinearIntegration());\n }\n }\n\n // Validate ids up front so a copy-paste duplicate fails loud instead of one\n // instance silently shadowing the other.\n const integrationIds = new Set<string>();\n for (const integration of integrations) {\n if (integrationIds.has(integration.id)) {\n throw new Error(`MastraFactory: duplicate integration id '${integration.id}' in 'integrations'.`);\n }\n integrationIds.add(integration.id);\n }\n const rules = this.#config.rules ?? builtInFactoryRules();\n assertFactoryRules(rules);\n\n // FactoryStorage owns every app-table domain and initializes them through\n // the same lifecycle as the backend connection.\n const intakeStorage = storage.registerDomain(new IntakeStorage());\n const auditStorage = storage.registerDomain(new AuditStorage());\n const workItemsStorage = storage.registerDomain(new WorkItemsStorage());\n const modelCredentialsStorage = storage.registerDomain(new ModelCredentialsStorage());\n const modelPacksStorage = storage.registerDomain(new ModelPacksStorage());\n const memorySettingsStorage = storage.registerDomain(new MemorySettingsStorage());\n const customProvidersStorage = storage.registerDomain(new CustomProvidersStorage());\n const queueHealthStorage = storage.registerDomain(new QueueHealthStorage());\n // Generic integration storage (connections/subscriptions/settings) — the\n // default persistence surface for integrations without a bespoke domain.\n const integrationStorage = storage.registerDomain(new IntegrationStorage());\n const factoryProjectsStorage = storage.registerDomain(new FactoryProjectsStorage());\n const sourceControlStorage = storage.registerDomain(new SourceControlStorage());\n // Reverse index from a platform sender (Slack/Discord/...) to a Mastra\n // tenant, so inbound channel events can resolve the sender's model creds.\n const channelIdentityStorage = storage.registerDomain(new ChannelIdentityStorage());\n // Every app-table domain handle the route builders and integrations need,\n // threaded explicitly (no service locator).\n const domains = {\n intake: intakeStorage,\n modelCredentials: modelCredentialsStorage,\n modelPacks: modelPacksStorage,\n memorySettings: memorySettingsStorage,\n customProviders: customProvidersStorage,\n projects: factoryProjectsStorage,\n queueHealth: queueHealthStorage,\n workItems: workItemsStorage,\n channelIdentity: channelIdentityStorage,\n };\n const projectRoutes = new ProjectRoutes({\n auth: routeAuth,\n projects: factoryProjectsStorage,\n sourceControl: sourceControlStorage,\n versionControlIntegrationIds: integrations\n .filter(integration => integration.versionControl)\n .map(integration => integration.id),\n });\n const auditDomain = new AuditDomain({\n auth: routeAuth,\n audit: auditStorage,\n projects: factoryProjectsStorage,\n sinks: integrations,\n agentTenant: requestContext => {\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n return { orgId: getFactoryAuthOrgId(user), userId: getFactoryAuthUserId(user) };\n },\n });\n\n // Repository execution needs one sandbox per project-repository link,\n // cloned from the configured machine. A machine without `clone()` would\n // only fail on first use, so fail fast at boot instead.\n const sandboxConfig = this.#config.sandbox;\n const machine = sandboxConfig?.machine;\n if (machine && typeof machine.clone !== 'function') {\n throw new Error(\n `MastraFactory: the configured sandbox machine (provider '${machine.provider}') does not implement clone(). ` +\n `Project repositories each get their own sandbox cloned from the configured machine. ` +\n `Pass a machine that implements clone() — e.g. RailwaySandbox (@mastra/railway) or ` +\n `LocalSandbox (@mastra/core/workspace) — or omit 'sandbox' to disable sandboxes.`,\n );\n }\n\n // One sandbox fleet per boot: constructed with the machine config when\n // sandboxes are configured, disabled otherwise. Handed to integrations\n // through the IntegrationContext — no global registry.\n const fleet = new SandboxFleet(\n machine\n ? {\n machine,\n workdirBase: resolveSandboxWorkdirBase(machine, sandboxConfig?.workdir),\n maxSandboxes: sandboxConfig?.maxSandboxes,\n }\n : undefined,\n );\n // Core's `getDynamicWorkspace` reattaches project sandboxes through the\n // SDK seam; only this factory owns the fleet, so register it here.\n registerSandboxReattach(fleet);\n\n // One shared OAuth state signer per boot. The deploy entry supplies a\n // replica-stable secret when needed; otherwise local development gets a\n // per-process random signer (`stable: false`).\n const stateSigner = createStateSigner(this.#config.stateSecret);\n\n // One-time provider initialization with factory-level context (e.g.\n // better-auth builds its default instance on the backend's auth\n // database, WorkOS derives its redirect URI from the public URL).\n // Failures surface here, at prepare() — a misconfigured provider must\n // not boot.\n if (auth && hasAuthInit(auth)) {\n await timedPhase('prepare.auth.init', () =>\n auth.init({ database: storage.authDatabase?.(), publicUrl: publicOrigin, allowedOrigins }),\n );\n }\n\n // Single init path: backend connection failure is a hard boot error;\n // registered app domains initialize fail-soft inside FactoryStorage.\n await timedPhase('prepare.storage.init', () => storage.init());\n\n // Per-tenant model credentials: once the credentials domain is up, model\n // resolution goes through the caller's own store and the SDK stops\n // mirroring stored API keys into process.env.\n //\n // Only register when a real auth adapter gates callers. In local /\n // auth-disabled mode there is no authenticated tenant, so registering would\n // force every model call through an empty tenant store (fail-closed, no env\n // fallback) and break chat with \"Not logged in\". Leaving it unregistered\n // lets the SDK fall back to the file-backed AuthStorage (auth.json) — the\n // same store the local /login and Settings pages read and write.\n if (auth) {\n registerTenantCredentialResolver(modelCredentialsStorage);\n }\n\n // Custom providers: DB-backed in both modes (org rows in tenant mode, the\n // sentinel `local` org in no-auth mode). Once registered, model resolution\n // and the gateway catalog never read settings.json custom providers.\n registerCustomProvidersSource({ storage: customProvidersStorage, authEnabled: Boolean(auth) });\n\n for (const integration of integrations) {\n integration.initialize?.({\n storage: integrationStorage.forIntegration(integration.id),\n projects: factoryProjectsStorage,\n auth: routeAuth,\n });\n if (integration.versionControl) {\n integration.versionControl.initialize({\n storage: sourceControlStorage.forIntegration(integration.id),\n });\n }\n }\n\n // Every integration uses generic integration storage. Version-control\n // providers additionally require the source-control storage domain. Readiness\n // is derived solely from capability presence, never from provider ids.\n const integrationRegistrations = integrations.map(integration => {\n const requiredDomains = [\n 'integrations',\n ...(integration.versionControl ? ['source-control'] : []),\n // Channels resolve an inbound sender to a tenant through the reverse\n // index; without it every message would dispatch tenant-less.\n ...(integration.channels ? ['channel-identity'] : []),\n ];\n return {\n integration,\n ready: requiredDomains.every(domain => storage.isDomainReady(domain)),\n ensureReady: async () => {\n for (const domain of requiredDomains) await storage.ensureDomainReady(domain);\n },\n };\n });\n const intakeReady =\n integrations.some(integration => integration.intake !== undefined) && storage.isDomainReady('intake');\n const factoryReady = storage.isDomainReady('projects') && storage.isDomainReady('work-items');\n const githubIntegration = integrations.find(integration => integration.id === 'github') as\n | GithubIntegration\n | undefined;\n const workItemsReady = storage.isDomainReady('work-items');\n // Terminal work items release their session sandboxes back to the reuse\n // pool so the next session for the same repository/user claims a warm VM\n // instead of provisioning fresh. Remote providers only: local \"sandboxes\"\n // are the host machine with per-session workdirs — nothing to pool.\n const releaseTerminalSandboxes =\n machine && !(machine instanceof LocalSandbox) && workItemsReady && storage.isDomainReady('source-control')\n ? async ({ orgId, workItemId }: { orgId: string; workItemId: string }) =>\n releaseWorkItemSandboxes({\n workItems: workItemsStorage,\n sourceControl: sourceControlStorage.forIntegration('github'),\n fleet,\n orgId,\n workItemId,\n })\n : undefined;\n const transitionService = workItemsReady\n ? new FactoryTransitionService({\n rules,\n storage: workItemsStorage,\n ...(releaseTerminalSandboxes ? { onTerminalStage: releaseTerminalSandboxes } : {}),\n })\n : undefined;\n const factoryProcessor = workItemsReady\n ? new FactoryPhaseStateProcessor({\n rules,\n storage: workItemsStorage,\n ...(transitionService ? { transitionService } : {}),\n ...(githubIntegration\n ? {\n recordPullRequestProvenance: (input: Parameters<typeof recordFactoryPullRequestProvenance>[3]) =>\n recordFactoryPullRequestProvenance(\n githubIntegration,\n sourceControlStorage.forIntegration('github'),\n integrationStorage.forIntegration('github'),\n input,\n ),\n }\n : {}),\n messageReader: {\n listMessages: async input => {\n const memory = await storage.getMastraStorage().getStore('memory');\n return memory ? memory.listMessages(input) : { messages: [], hasMore: false };\n },\n },\n })\n : undefined;\n\n // Boot assertion: an active integration that signs OAuth `state` needs a\n // replica-stable signer — a per-process random secret silently breaks the\n // OAuth callback on any replica that didn't sign the state. Fail loud now\n // instead. (The built-ins also assert this inside their readiness gates.)\n for (const { integration } of integrationRegistrations) {\n if (integration.requiresStableStateSigner && !stateSigner.stable) {\n throw new Error(\n `MastraFactory: integration '${integration.id}' signs OAuth state and requires a ` +\n `replica-stable state secret, but none is configured. Set 'stateSecret' on the factory config.`,\n );\n }\n }\n\n // The SDK needs to know which backend the injected Mastra store uses\n // (its own `instanceof` detection breaks when the dependency graph holds\n // duplicate package copies). Resolve it by walking the FactoryStorage\n // prototype chain by class name — the factory can't import the concrete\n // classes since '@mastra/pg' / '@mastra/libsql' are the user's choice.\n const mastraStorageBackend = (() => {\n for (let proto = Object.getPrototypeOf(storage); proto; proto = Object.getPrototypeOf(proto)) {\n if (proto.constructor?.name === 'PgFactoryStorage') return 'pg' as const;\n if (proto.constructor?.name === 'LibSQLFactoryStorage') return 'libsql' as const;\n }\n return undefined;\n })();\n\n // Integrations contributing tools to agent sessions: org-scoped\n // `agentTools` (resolved per request) + session-scoped `sessionTools`.\n const toolIntegrations = integrationRegistrations.filter(\n ({ integration }) => integration.agentTools || integration.sessionTools,\n );\n\n // Build the real production controller (agents, modes, tools, memory, OM,\n // MCP, providers) — identical to the terminal app. Agent state lives in\n // the storage backend's Mastra store alongside the Factory app tables —\n // one shared database for all users, separated by `resourceId` scoping.\n const prepared = await timedPhase('prepare.controllerMount', () =>\n prepareAgentControllerMount({\n controllerId: CONTROLLER_ID,\n workspace: createWorkspaceFactory({\n ...(this.#config.sandbox ? { sandbox: this.#config.sandbox } : {}),\n ...(githubIntegration ? { github: githubIntegration } : {}),\n ...(workItemsStorage ? { workItems: workItemsStorage } : {}),\n fleet,\n }),\n disableGithubSignals: true,\n // Memory settings live in the factory's `memory-settings` app table (per\n // org/user), so the host machine's TUI settings.json must not seed them.\n disableSettingsOmSeed: true,\n storage: storage.getMastraStorage(),\n ...(mastraStorageBackend ? { storageBackend: mastraStorageBackend } : {}),\n ...(factoryProcessor ? { inputProcessors: [factoryProcessor] } : {}),\n ...(vector ? { vector } : {}),\n ...(toolIntegrations.length > 0 || (workItemsStorage && transitionService)\n ? {\n extraTools: async ({ requestContext }: { requestContext: RequestContext }) => {\n const tools: IntegrationTools = {};\n const toolOwners = new Map<string, string>();\n const mergeTools = (ownerId: string, contributed: IntegrationTools) => {\n for (const [name, tool] of Object.entries(contributed)) {\n const owner = toolOwners.get(name);\n if (owner) {\n throw new Error(\n `MastraFactory: integration tool '${name}' from '${ownerId}' conflicts with '${owner}'.`,\n );\n }\n toolOwners.set(name, ownerId);\n tools[name] = tool;\n }\n };\n if (workItemsStorage && transitionService) {\n mergeTools(\n 'factory',\n await createFactoryTransitionTools({\n requestContext,\n storage: workItemsStorage,\n transitionService,\n }),\n );\n }\n for (const { integration, ready, ensureReady } of toolIntegrations) {\n if (!ready && ensureReady) {\n try {\n await ensureReady();\n } catch {\n continue;\n }\n }\n if (integration.agentTools) {\n mergeTools(integration.id, await integration.agentTools({ requestContext }));\n }\n if (integration.sessionTools) {\n mergeTools(integration.id, integration.sessionTools({ requestContext }));\n }\n }\n return tools;\n },\n }\n : {}),\n postToolObserver: async (toolContext: IntegrationPostToolContext) => {\n const requestContext = (toolContext.context as { requestContext?: RequestContext } | undefined)\n ?.requestContext;\n if (requestContext) {\n await observeAgentGitAction({\n audit: auditDomain,\n toolContext: { ...toolContext, context: requestContext },\n });\n }\n await Promise.all(\n integrations.map(async integration => {\n if (!integration.postToolObserver) return;\n try {\n await integration.postToolObserver({ toolContext, requestContext });\n } catch (error) {\n console.warn(`[factory] Integration '${integration.id}' post-tool observer failed:`, error);\n }\n }),\n );\n },\n ...(pubsub ? { pubsub, crossProcessPubSub: true } : {}),\n buildApiRoutes: ({ controller, authStorage }: BuildApiRoutesDeps) => [\n // Public `/auth/*` routes (login/callback/logout/me). Folded in as\n // `apiRoutes` (not plain Hono routes) because the entry can't touch the\n // Hono app the deployer generates. `requiresAuth: false`; the gate\n // skips `/auth/*`.\n ...(auth ? buildAuthRoutes(auth, { publicUrl: publicOrigin }) : []),\n // Custom `/web/*` routes (fs / config / integrations / factory / audit).\n ...assembleFactoryApiRoutes({\n controllerId: CONTROLLER_ID,\n controller,\n auth: routeAuth,\n authStorage,\n audit: auditDomain,\n publicOrigin,\n stateSigner,\n fleet,\n factoryStorage: storage,\n integrationStorage,\n sourceControlStorage,\n domains,\n integrations: integrationRegistrations,\n intakeReady,\n factoryReady,\n rules,\n factoryTransitionService: transitionService,\n onFactoryRuntime: ({ transitionService: runtimeTransitionService, prepareBinding }) => {\n this.#dispatcher ??= new FactoryDecisionDispatcher({\n controller,\n transitionService: runtimeTransitionService,\n storage: storage.getDomain<WorkItemsStorage>('work-items'),\n reconcileToolResults: () => factoryProcessor?.reconcileAllBoundThreads() ?? Promise.resolve(),\n prepareBinding,\n primeCredentials: tenant => primeTenantCredentials({ tenant, credentials: modelCredentialsStorage }),\n });\n },\n }),\n ...projectRoutes.routes(),\n ...auditDomain.routes(),\n ],\n buildServerConfig: () => {\n const cors = allowedOrigins.length ? { cors: { origin: allowedOrigins, credentials: true } } : {};\n // Log route errors with method/path/stack and answer with structured\n // JSON instead of an opaque `Internal Server Error`. Applied by the\n // deployer to both the top-level app and the custom-route sub-app.\n const onError = { onError: handleServerError };\n // Same-origin SPA: when a vite build is present (see resolveUiDistDir),\n // serve it at `/` from this server. Mounted last so the auth gate (when\n // enabled) covers it; it always passes `/api`, `/web`, `/auth` through.\n const uiDist = resolveUiDistDir();\n const spa = uiDist ? [createSpaStaticMiddleware(uiDist)] : [];\n if (!auth) {\n // Auth disabled: no gate. Still prime the sentinel-local custom\n // provider snapshot so model calls see DB rows, then SPA + CORS.\n return {\n middleware: [\n createCustomProvidersPrimer({ auth: routeAuth, storage: customProvidersStorage, authEnabled: false }),\n ...spa,\n ],\n ...cors,\n ...onError,\n };\n }\n\n // Ordered middleware. The deployer applies these AFTER its context\n // middleware sets `c.set('mastra', mastra)` and BEFORE routes, so:\n // 1. gate — validates the auth session, stashes the user, and 401s /\n // redirects unauthenticated requests. Skips public `/auth/*`.\n // 2. primers — hydrate the caller's model-credential and custom\n // provider snapshots so the request's first model call\n // resolves tenant credentials and custom providers.\n // 3. spa — serves the built UI for everything the server doesn't own.\n // `auth` also lands on `server.auth` so the core auth middleware (and\n // Studio's dual-auth routing — see `studio.auth` on the returned args)\n // authenticates core `/api/*` routes with the same provider.\n return {\n auth,\n middleware: [\n createFactoryAuthGate(auth),\n createTenantCredentialPrimer({ auth: routeAuth, credentials: modelCredentialsStorage }),\n createCustomProvidersPrimer({\n auth: routeAuth,\n storage: customProvidersStorage,\n authEnabled: Boolean(auth),\n }),\n ...spa,\n ],\n ...cors,\n ...onError,\n };\n },\n }),\n );\n\n this.#prepared = prepared;\n this.#factoryProcessor = factoryProcessor;\n\n // Chat-platform channels (Slack, Discord, …) contributed by integrations,\n // attached to the mounted controller so inbound platform messages reach\n // the same agents the web UI drives. READY integrations only — readiness\n // means the `channel-identity` domain's `init()` succeeded, so its link\n // table is queryable. Without it a sender can't be resolved to a tenant,\n // and attaching anyway would dispatch runs on default credentials.\n const channelRegistrations = integrationRegistrations.filter(\n ({ integration, ready }) => ready && integration.channels,\n );\n // `setChannels` replaces rather than merges, so a second provider would\n // silently never receive a message. Fail loud instead.\n if (channelRegistrations.length > 1) {\n throw new Error(\n `MastraFactory: integrations [${channelRegistrations\n .map(({ integration }) => integration.id)\n .join(', ')}] all provide channels, but only one may. Remove all but one.`,\n );\n }\n for (const { integration } of channelRegistrations) {\n prepared.base.controller.setChannels(\n integration.channels!(\n buildIntegrationContext(\n {\n controller: prepared.base.controller,\n publicOrigin,\n auth: routeAuth,\n stateSigner,\n fleet,\n factoryStorage: storage,\n integrationStorage,\n sourceControlStorage,\n rules,\n factoryReady,\n domains,\n },\n integration.id,\n ),\n ),\n );\n }\n\n // Integration lifecycle workers (e.g. polling an upstream without\n // webhooks): collected from READY integrations only, folded into the\n // constructor args so `new Mastra(...)` merges them with the default\n // workers and `finalize()`'s `startWorkers()` starts them alongside the\n // built-ins. Never passed for the disabled/not-ready case — a worker for\n // an unavailable integration must not run.\n const integrationWorkers = integrationRegistrations\n .filter(({ integration, ready }) => ready && integration.workers)\n .flatMap(({ integration }) =>\n integration.workers!(\n buildIntegrationContext(\n {\n controller: prepared.base.controller,\n publicOrigin,\n auth: routeAuth,\n stateSigner,\n fleet,\n factoryStorage: storage,\n integrationStorage,\n sourceControlStorage,\n rules,\n factoryReady,\n domains,\n },\n integration.id,\n ),\n ),\n );\n\n return {\n ...prepared.mastraArgs,\n // Same provider on `studio.auth` as on `server.auth` (buildServerConfig):\n // deployed factories must authenticate BOTH plain API callers and Studio\n // requests (`x-mastra-client-type: studio` routes to `studio.auth`).\n ...(auth ? { studio: { auth } } : {}),\n ...(integrationWorkers.length > 0 ? { workers: integrationWorkers } : {}),\n };\n }\n\n /**\n * Post-construct boot: initialize the controller (which inherits the\n * constructed Mastra's storage) and start its workers. Call AFTER the entry\n * has run `new Mastra(prepare()'s args)`.\n */\n async finalize(): Promise<void> {\n if (!this.#prepared) {\n throw new Error('MastraFactory.finalize() called before prepare()');\n }\n await timedPhase('finalize.controller', () => this.#prepared!.finalize());\n await timedPhase(\n 'finalize.reconcileBoundThreads',\n () => this.#factoryProcessor?.reconcileAllBoundThreads() ?? Promise.resolve(),\n );\n this.#dispatcher?.start();\n }\n\n /** Stop Factory-owned background dispatch before the host process shuts down. */\n async shutdown(): Promise<void> {\n await this.#dispatcher?.stop();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuMA,MAAM,gBAAgB;AAEtB,SAAS,uBAAgC;CACvC,OAAO,QAAQ,QAAQ,IAAI,4BAA4B,KAAK,CAAC;AAC/D;;;;;;;AAQA,SAAS,yBAAyB,SAA+C;CAC/E,MAAM,KAAM,QAA2C;CACvD,OAAO,OAAO,OAAO,YAAY,GAAG,SAAS,IAAI,KAAK,KAAA;AACxD;AAEA,SAAS,0BAA0B,SAA2B,mBAAoC;CAChG,MAAM,iBAAiB,yBAAyB,OAAO;CAGvD,SADE,sBAAsB,gBAAgB,iBAAiB,iBAAkB,qBAAqB,mBAC7E,aAAA,CAAc,QAAQ,QAAQ,EAAE;AACrD;;;;;;;;;;;;;;;;AAiBA,SAAS,uBAAuB,WAAwC;CACtE,OAAO,IAAI,iBAAiB,EAC1B,cAAc,0BAA0B,SAAS,EACnD,CAAC;AACH;;;;;;;;;;;;;;;AAgBA,MAAM,gCAAgC,CAAC,gBAAgB,WAAW;AAElE,SAAS,YAAY,UAA2B;CAI9C,IAAI,SAAS,SAAS,GAAG,GAAG,OAAO;CACnC,OAAO,oBAAoB,KAAK,QAAQ;AAC1C;AAEA,SAAS,0BAA0B,WAAuC;CACxE,IAAI;CACJ,IAAI;EACF,WAAW,IAAI,IA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C5B,SAAS,KAAK,WAAW,YACvB,YAAY,SACV,wBACE;GACE,YAAY,SAAS,KAAK;GAC1B;GACA,MAAM;GACN;GACA;GACA,gBAAgB;GAChB;GACA;GACA;GACA;GACA;EACF,GACA,YAAY,EACd,CACF,CACF;EASF,MAAM,qBAAqB,yBACxB,QAAQ,EAAE,aAAa,YAAY,SAAS,YAAY,OAAO,CAAC,CAChE,SAAS,EAAE,kBACV,YAAY,QACV,wBACE;GACE,YAAY,SAAS,KAAK;GAC1B;GACA,MAAM;GACN;GACA;GACA,gBAAgB;GAChB;GACA;GACA;GACA;GACA;EACF,GACA,YAAY,EACd,CACF,CACF;EAEF,OAAO;GACL,GAAG,SAAS;GAIZ,GAAI,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC;GACnC,GAAI,mBAAmB,SAAS,IAAI,EAAE,SAAS,mBAAmB,IAAI,CAAC;EACzE;CACF;;;;;;CAOA,MAAM,WAA0B;EAC9B,IAAI,CAAC,KAAKD,WACR,MAAM,IAAI,MAAM,kDAAkD;EAEpE,MAAM,WAAW,6BAA6B,KAAKA,UAAW,SAAS,CAAC;EACxE,MAAM,WACJ,wCACM,KAAKC,mBAAmB,yBAAyB,KAAK,QAAQ,QAAQ,CAC9E;EACA,KAAKF,aAAa,MAAM;CAC1B;;CAGA,MAAM,WAA0B;EAC9B,MAAM,KAAKA,aAAa,KAAK;CAC/B;AACF"}
@@ -0,0 +1,14 @@
1
+ export { MastraFactory } from './factory.js';
2
+ export type { MastraArgs, MastraFactoryConfig } from './factory.js';
3
+ export { ChannelIdentityStorage } from './storage/domains/channel-identity/base.js';
4
+ export type { ChannelAccountLink, ChannelAccountLinkEntry, ChannelAccountLinkKey, ChannelAccountLinkNames, } from './storage/domains/channel-identity/base.js';
5
+ export { FactoryProjectsStorage } from './storage/domains/projects/base.js';
6
+ export type { FactoryProject } from './storage/domains/projects/base.js';
7
+ export { WorkItemsStorage } from './storage/domains/work-items/base.js';
8
+ export type { CreateWorkItemInput, WorkItemRow } from './storage/domains/work-items/base.js';
9
+ export { createStateSigner } from './state-signing.js';
10
+ export type { StateSigner, StateTenant } from './state-signing.js';
11
+ export { createFactoryRouteAuth } from './auth.js';
12
+ export type { RouteAuth } from './routes/route.js';
13
+ export type { FactoryIntegration, IntegrationContext, IntegrationHooks, IntegrationTools, } from './integrations/base.js';
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,YAAY,EACV,kBAAkB,EAClB,uBAAuB,EACvB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,YAAY,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,YAAY,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACnD,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAInD,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { createFactoryRouteAuth } from "./auth.js";
2
+ import { WorkItemsStorage } from "./storage/domains/work-items/base.js";
3
+ import { createStateSigner } from "./state-signing.js";
4
+ import { ChannelIdentityStorage } from "./storage/domains/channel-identity/base.js";
5
+ import { FactoryProjectsStorage } from "./storage/domains/projects/base.js";
6
+ import { MastraFactory } from "./factory.js";
7
+ export { ChannelIdentityStorage, FactoryProjectsStorage, MastraFactory, WorkItemsStorage, createFactoryRouteAuth, createStateSigner };