@mastra/factory 0.0.0 → 0.1.0-alpha.2

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 (287) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE.md +30 -0
  3. package/dist/auth.d.ts +181 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +370 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/capabilities/connection.d.ts +9 -0
  8. package/dist/capabilities/connection.d.ts.map +1 -0
  9. package/dist/capabilities/connection.js +1 -0
  10. package/dist/capabilities/connection.js.map +1 -0
  11. package/dist/capabilities/intake.d.ts +93 -0
  12. package/dist/capabilities/intake.d.ts.map +1 -0
  13. package/dist/capabilities/intake.js +1 -0
  14. package/dist/capabilities/intake.js.map +1 -0
  15. package/dist/capabilities/version-control.d.ts +239 -0
  16. package/dist/capabilities/version-control.d.ts.map +1 -0
  17. package/dist/capabilities/version-control.js +1 -0
  18. package/dist/capabilities/version-control.js.map +1 -0
  19. package/dist/factory.d.ts +145 -0
  20. package/dist/factory.d.ts.map +1 -0
  21. package/dist/factory.js +38208 -0
  22. package/dist/factory.js.map +1 -0
  23. package/dist/index.d.ts +3 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +38208 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/integrations/base.d.ts +197 -0
  28. package/dist/integrations/base.d.ts.map +1 -0
  29. package/dist/integrations/base.js +1 -0
  30. package/dist/integrations/base.js.map +1 -0
  31. package/dist/integrations/github/config.d.ts +60 -0
  32. package/dist/integrations/github/config.d.ts.map +1 -0
  33. package/dist/integrations/github/config.js +28 -0
  34. package/dist/integrations/github/config.js.map +1 -0
  35. package/dist/integrations/github/factory-session.d.ts +12 -0
  36. package/dist/integrations/github/factory-session.d.ts.map +1 -0
  37. package/dist/integrations/github/factory-session.js +41 -0
  38. package/dist/integrations/github/factory-session.js.map +1 -0
  39. package/dist/integrations/github/integration.d.ts +191 -0
  40. package/dist/integrations/github/integration.d.ts.map +1 -0
  41. package/dist/integrations/github/integration.js +2999 -0
  42. package/dist/integrations/github/integration.js.map +1 -0
  43. package/dist/integrations/github/issue-triage.d.ts +27 -0
  44. package/dist/integrations/github/issue-triage.d.ts.map +1 -0
  45. package/dist/integrations/github/issue-triage.js +82 -0
  46. package/dist/integrations/github/issue-triage.js.map +1 -0
  47. package/dist/integrations/github/project-lock.d.ts +78 -0
  48. package/dist/integrations/github/project-lock.d.ts.map +1 -0
  49. package/dist/integrations/github/project-lock.js +70 -0
  50. package/dist/integrations/github/project-lock.js.map +1 -0
  51. package/dist/integrations/github/provenance.d.ts +27 -0
  52. package/dist/integrations/github/provenance.d.ts.map +1 -0
  53. package/dist/integrations/github/provenance.js +104 -0
  54. package/dist/integrations/github/provenance.js.map +1 -0
  55. package/dist/integrations/github/routes.d.ts +72 -0
  56. package/dist/integrations/github/routes.d.ts.map +1 -0
  57. package/dist/integrations/github/routes.js +1832 -0
  58. package/dist/integrations/github/routes.js.map +1 -0
  59. package/dist/integrations/github/sandbox.d.ts +268 -0
  60. package/dist/integrations/github/sandbox.d.ts.map +1 -0
  61. package/dist/integrations/github/sandbox.js +381 -0
  62. package/dist/integrations/github/sandbox.js.map +1 -0
  63. package/dist/integrations/github/session-subscriptions.d.ts +23 -0
  64. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
  65. package/dist/integrations/github/session-subscriptions.js +190 -0
  66. package/dist/integrations/github/session-subscriptions.js.map +1 -0
  67. package/dist/integrations/github/subscriptions.d.ts +54 -0
  68. package/dist/integrations/github/subscriptions.d.ts.map +1 -0
  69. package/dist/integrations/github/subscriptions.js +70 -0
  70. package/dist/integrations/github/subscriptions.js.map +1 -0
  71. package/dist/integrations/github/webhook.d.ts +87 -0
  72. package/dist/integrations/github/webhook.d.ts.map +1 -0
  73. package/dist/integrations/github/webhook.js +381 -0
  74. package/dist/integrations/github/webhook.js.map +1 -0
  75. package/dist/integrations/linear/agent-tools.d.ts +34 -0
  76. package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
  77. package/dist/integrations/linear/agent-tools.js +108 -0
  78. package/dist/integrations/linear/agent-tools.js.map +1 -0
  79. package/dist/integrations/linear/integration.d.ts +233 -0
  80. package/dist/integrations/linear/integration.d.ts.map +1 -0
  81. package/dist/integrations/linear/integration.js +962 -0
  82. package/dist/integrations/linear/integration.js.map +1 -0
  83. package/dist/integrations/linear/routes.d.ts +61 -0
  84. package/dist/integrations/linear/routes.d.ts.map +1 -0
  85. package/dist/integrations/linear/routes.js +242 -0
  86. package/dist/integrations/linear/routes.js.map +1 -0
  87. package/dist/integrations/linear/storage.d.ts +65 -0
  88. package/dist/integrations/linear/storage.d.ts.map +1 -0
  89. package/dist/integrations/linear/storage.js +1 -0
  90. package/dist/integrations/linear/storage.js.map +1 -0
  91. package/dist/integrations/platform/api-client.d.ts +24 -0
  92. package/dist/integrations/platform/api-client.d.ts.map +1 -0
  93. package/dist/integrations/platform/api-client.js +153 -0
  94. package/dist/integrations/platform/api-client.js.map +1 -0
  95. package/dist/integrations/platform/github/event-worker.d.ts +42 -0
  96. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
  97. package/dist/integrations/platform/github/event-worker.js +577 -0
  98. package/dist/integrations/platform/github/event-worker.js.map +1 -0
  99. package/dist/integrations/platform/github/integration.d.ts +36 -0
  100. package/dist/integrations/platform/github/integration.d.ts.map +1 -0
  101. package/dist/integrations/platform/github/integration.js +3242 -0
  102. package/dist/integrations/platform/github/integration.js.map +1 -0
  103. package/dist/integrations/platform/linear/integration.d.ts +46 -0
  104. package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
  105. package/dist/integrations/platform/linear/integration.js +891 -0
  106. package/dist/integrations/platform/linear/integration.js.map +1 -0
  107. package/dist/integrations/workos/integration.d.ts +39 -0
  108. package/dist/integrations/workos/integration.d.ts.map +1 -0
  109. package/dist/integrations/workos/integration.js +96 -0
  110. package/dist/integrations/workos/integration.js.map +1 -0
  111. package/dist/routes/config.d.ts +220 -0
  112. package/dist/routes/config.d.ts.map +1 -0
  113. package/dist/routes/config.js +770 -0
  114. package/dist/routes/config.js.map +1 -0
  115. package/dist/routes/fs.d.ts +105 -0
  116. package/dist/routes/fs.d.ts.map +1 -0
  117. package/dist/routes/fs.js +294 -0
  118. package/dist/routes/fs.js.map +1 -0
  119. package/dist/routes/intake.d.ts +23 -0
  120. package/dist/routes/intake.d.ts.map +1 -0
  121. package/dist/routes/intake.js +179 -0
  122. package/dist/routes/intake.js.map +1 -0
  123. package/dist/routes/oauth.d.ts +43 -0
  124. package/dist/routes/oauth.d.ts.map +1 -0
  125. package/dist/routes/oauth.js +25058 -0
  126. package/dist/routes/oauth.js.map +1 -0
  127. package/dist/routes/projects.d.ts +19 -0
  128. package/dist/routes/projects.d.ts.map +1 -0
  129. package/dist/routes/projects.js +395 -0
  130. package/dist/routes/projects.js.map +1 -0
  131. package/dist/routes/provider-credentials.d.ts +81 -0
  132. package/dist/routes/provider-credentials.d.ts.map +1 -0
  133. package/dist/routes/provider-credentials.js +68 -0
  134. package/dist/routes/provider-credentials.js.map +1 -0
  135. package/dist/routes/route.d.ts +48 -0
  136. package/dist/routes/route.d.ts.map +1 -0
  137. package/dist/routes/route.js +11 -0
  138. package/dist/routes/route.js.map +1 -0
  139. package/dist/routes/skills.d.ts +30 -0
  140. package/dist/routes/skills.d.ts.map +1 -0
  141. package/dist/routes/skills.js +181 -0
  142. package/dist/routes/skills.js.map +1 -0
  143. package/dist/routes/surface.d.ts +83 -0
  144. package/dist/routes/surface.d.ts.map +1 -0
  145. package/dist/routes/surface.js +28504 -0
  146. package/dist/routes/surface.js.map +1 -0
  147. package/dist/routes/tenant-credentials.d.ts +74 -0
  148. package/dist/routes/tenant-credentials.d.ts.map +1 -0
  149. package/dist/routes/tenant-credentials.js +181 -0
  150. package/dist/routes/tenant-credentials.js.map +1 -0
  151. package/dist/routes/work-items.d.ts +40 -0
  152. package/dist/routes/work-items.d.ts.map +1 -0
  153. package/dist/routes/work-items.js +902 -0
  154. package/dist/routes/work-items.js.map +1 -0
  155. package/dist/rules/binding-context.d.ts +5 -0
  156. package/dist/rules/binding-context.d.ts.map +1 -0
  157. package/dist/rules/binding-context.js +40 -0
  158. package/dist/rules/binding-context.js.map +1 -0
  159. package/dist/rules/defaults.d.ts +9 -0
  160. package/dist/rules/defaults.d.ts.map +1 -0
  161. package/dist/rules/defaults.js +328 -0
  162. package/dist/rules/defaults.js.map +1 -0
  163. package/dist/rules/dispatcher.d.ts +40 -0
  164. package/dist/rules/dispatcher.d.ts.map +1 -0
  165. package/dist/rules/dispatcher.js +695 -0
  166. package/dist/rules/dispatcher.js.map +1 -0
  167. package/dist/rules/github-service.d.ts +27 -0
  168. package/dist/rules/github-service.d.ts.map +1 -0
  169. package/dist/rules/github-service.js +460 -0
  170. package/dist/rules/github-service.js.map +1 -0
  171. package/dist/rules/index.d.ts +7 -0
  172. package/dist/rules/index.d.ts.map +1 -0
  173. package/dist/rules/index.js +577 -0
  174. package/dist/rules/index.js.map +1 -0
  175. package/dist/rules/linear-service.d.ts +27 -0
  176. package/dist/rules/linear-service.d.ts.map +1 -0
  177. package/dist/rules/linear-service.js +343 -0
  178. package/dist/rules/linear-service.js.map +1 -0
  179. package/dist/rules/processor.d.ts +54 -0
  180. package/dist/rules/processor.d.ts.map +1 -0
  181. package/dist/rules/processor.js +629 -0
  182. package/dist/rules/processor.js.map +1 -0
  183. package/dist/rules/resolve.d.ts +17 -0
  184. package/dist/rules/resolve.d.ts.map +1 -0
  185. package/dist/rules/resolve.js +27 -0
  186. package/dist/rules/resolve.js.map +1 -0
  187. package/dist/rules/start-coordinator.d.ts +58 -0
  188. package/dist/rules/start-coordinator.d.ts.map +1 -0
  189. package/dist/rules/start-coordinator.js +136 -0
  190. package/dist/rules/start-coordinator.js.map +1 -0
  191. package/dist/rules/tools.d.ts +10 -0
  192. package/dist/rules/tools.d.ts.map +1 -0
  193. package/dist/rules/tools.js +93 -0
  194. package/dist/rules/tools.js.map +1 -0
  195. package/dist/rules/transition-service.d.ts +32 -0
  196. package/dist/rules/transition-service.d.ts.map +1 -0
  197. package/dist/rules/transition-service.js +474 -0
  198. package/dist/rules/transition-service.js.map +1 -0
  199. package/dist/rules/types.d.ts +220 -0
  200. package/dist/rules/types.d.ts.map +1 -0
  201. package/dist/rules/types.js +33 -0
  202. package/dist/rules/types.js.map +1 -0
  203. package/dist/rules/validation.d.ts +11 -0
  204. package/dist/rules/validation.d.ts.map +1 -0
  205. package/dist/rules/validation.js +310 -0
  206. package/dist/rules/validation.js.map +1 -0
  207. package/dist/sandbox/fleet.d.ts +208 -0
  208. package/dist/sandbox/fleet.d.ts.map +1 -0
  209. package/dist/sandbox/fleet.js +259 -0
  210. package/dist/sandbox/fleet.js.map +1 -0
  211. package/dist/sandbox/reattach.d.ts +3 -0
  212. package/dist/sandbox/reattach.d.ts.map +1 -0
  213. package/dist/sandbox/reattach.js +9 -0
  214. package/dist/sandbox/reattach.js.map +1 -0
  215. package/dist/server-error.d.ts +12 -0
  216. package/dist/server-error.d.ts.map +1 -0
  217. package/dist/server-error.js +20 -0
  218. package/dist/server-error.js.map +1 -0
  219. package/dist/skills/service.d.ts +48 -0
  220. package/dist/skills/service.d.ts.map +1 -0
  221. package/dist/skills/service.js +45 -0
  222. package/dist/skills/service.js.map +1 -0
  223. package/dist/spa-static.d.ts +34 -0
  224. package/dist/spa-static.d.ts.map +1 -0
  225. package/dist/spa-static.js +73 -0
  226. package/dist/spa-static.js.map +1 -0
  227. package/dist/state-signing.d.ts +48 -0
  228. package/dist/state-signing.d.ts.map +1 -0
  229. package/dist/state-signing.js +48 -0
  230. package/dist/state-signing.js.map +1 -0
  231. package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
  232. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
  233. package/dist/storage/domains/audit/agent-audit.js +65 -0
  234. package/dist/storage/domains/audit/agent-audit.js.map +1 -0
  235. package/dist/storage/domains/audit/base.d.ts +140 -0
  236. package/dist/storage/domains/audit/base.d.ts.map +1 -0
  237. package/dist/storage/domains/audit/base.js +127 -0
  238. package/dist/storage/domains/audit/base.js.map +1 -0
  239. package/dist/storage/domains/audit/domain.d.ts +69 -0
  240. package/dist/storage/domains/audit/domain.d.ts.map +1 -0
  241. package/dist/storage/domains/audit/domain.js +165 -0
  242. package/dist/storage/domains/audit/domain.js.map +1 -0
  243. package/dist/storage/domains/credentials/base.d.ts +134 -0
  244. package/dist/storage/domains/credentials/base.d.ts.map +1 -0
  245. package/dist/storage/domains/credentials/base.js +257 -0
  246. package/dist/storage/domains/credentials/base.js.map +1 -0
  247. package/dist/storage/domains/intake/base.d.ts +38 -0
  248. package/dist/storage/domains/intake/base.d.ts.map +1 -0
  249. package/dist/storage/domains/intake/base.js +62 -0
  250. package/dist/storage/domains/intake/base.js.map +1 -0
  251. package/dist/storage/domains/integrations/base.d.ts +126 -0
  252. package/dist/storage/domains/integrations/base.d.ts.map +1 -0
  253. package/dist/storage/domains/integrations/base.js +252 -0
  254. package/dist/storage/domains/integrations/base.js.map +1 -0
  255. package/dist/storage/domains/model-packs/base.d.ts +49 -0
  256. package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
  257. package/dist/storage/domains/model-packs/base.js +95 -0
  258. package/dist/storage/domains/model-packs/base.js.map +1 -0
  259. package/dist/storage/domains/projects/base.d.ts +55 -0
  260. package/dist/storage/domains/projects/base.d.ts.map +1 -0
  261. package/dist/storage/domains/projects/base.js +99 -0
  262. package/dist/storage/domains/projects/base.js.map +1 -0
  263. package/dist/storage/domains/queue-health/base.d.ts +52 -0
  264. package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
  265. package/dist/storage/domains/queue-health/base.js +87 -0
  266. package/dist/storage/domains/queue-health/base.js.map +1 -0
  267. package/dist/storage/domains/source-control/base.d.ts +288 -0
  268. package/dist/storage/domains/source-control/base.d.ts.map +1 -0
  269. package/dist/storage/domains/source-control/base.js +722 -0
  270. package/dist/storage/domains/source-control/base.js.map +1 -0
  271. package/dist/storage/domains/source-control/inmemory.d.ts +158 -0
  272. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
  273. package/dist/storage/domains/source-control/inmemory.js +348 -0
  274. package/dist/storage/domains/source-control/inmemory.js.map +1 -0
  275. package/dist/storage/domains/work-items/base.d.ts +412 -0
  276. package/dist/storage/domains/work-items/base.d.ts.map +1 -0
  277. package/dist/storage/domains/work-items/base.js +1174 -0
  278. package/dist/storage/domains/work-items/base.js.map +1 -0
  279. package/dist/storage/domains/work-items/metrics.d.ts +101 -0
  280. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
  281. package/dist/storage/domains/work-items/metrics.js +203 -0
  282. package/dist/storage/domains/work-items/metrics.js.map +1 -0
  283. package/dist/workspace.d.ts +20 -0
  284. package/dist/workspace.d.ts.map +1 -0
  285. package/dist/workspace.js +364 -0
  286. package/dist/workspace.js.map +1 -0
  287. package/package.json +19 -19
@@ -0,0 +1,259 @@
1
+ // src/sandbox/fleet.ts
2
+ import path from "path";
3
+ function reportProgress(onProgress, event) {
4
+ if (!onProgress) return;
5
+ try {
6
+ onProgress(event);
7
+ } catch {
8
+ }
9
+ }
10
+ var SandboxBudgetError = class extends Error {
11
+ constructor(max) {
12
+ super(
13
+ `Sandbox budget exceeded: this server already has ${max} active sandbox(es), the configured per-replica maximum. Close an existing repository's sandbox and try again.`
14
+ );
15
+ this.max = max;
16
+ this.name = "SandboxBudgetError";
17
+ }
18
+ max;
19
+ code = "sandbox-budget-exceeded";
20
+ };
21
+ function toMaterializationSandbox(sandbox) {
22
+ if (typeof sandbox.executeCommand !== "function") {
23
+ throw new Error(
24
+ `Sandbox provider '${sandbox.provider}' does not implement executeCommand() \u2014 cannot materialize repos.`
25
+ );
26
+ }
27
+ const lifecycle = sandbox;
28
+ return {
29
+ id: sandbox.id,
30
+ start: async () => {
31
+ await (lifecycle._start ?? sandbox.start)?.call(sandbox);
32
+ },
33
+ getInfo: async () => await sandbox.getInfo?.() ?? {},
34
+ executeCommand: (command, args, options) => sandbox.executeCommand(command, args, options),
35
+ stop: async () => {
36
+ await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);
37
+ }
38
+ };
39
+ }
40
+ async function readProviderSandboxId(sandbox) {
41
+ const info = await sandbox.getInfo();
42
+ const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;
43
+ return typeof id === "string" ? id : sandbox.id;
44
+ }
45
+ function sanitizeSegment(segment) {
46
+ const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^\.+/, "");
47
+ return cleaned || "repo";
48
+ }
49
+ function resolveContainedLocalWorkdir(root, ...segments) {
50
+ const resolvedRoot = path.resolve(root);
51
+ const resolved = path.resolve(resolvedRoot, ...segments);
52
+ if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;
53
+ throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);
54
+ }
55
+ var SandboxFleet = class {
56
+ #config;
57
+ #factory;
58
+ #liveCount = 0;
59
+ constructor(config) {
60
+ this.#config = config;
61
+ }
62
+ /**
63
+ * True when a sandbox machine was configured. The factory validates the
64
+ * machine implements `clone()` at boot, so a configured fleet is usable —
65
+ * sandbox-backed projects stay off only when the slot was omitted.
66
+ */
67
+ get enabled() {
68
+ return this.#config !== void 0;
69
+ }
70
+ /**
71
+ * Name of the active sandbox provider — the configured machine's `provider`
72
+ * discriminator (`'railway'`, `'local'`, …), or `'none'` when the fleet was
73
+ * constructed without a config. Diagnostic only; feature gating goes
74
+ * through {@link enabled}.
75
+ */
76
+ get provider() {
77
+ return this.#config?.machine.provider ?? "none";
78
+ }
79
+ /**
80
+ * Idle teardown window for provisioned sandboxes, in minutes; defaults to 30.
81
+ * Read back from the machine's own config when it exposes one
82
+ * (Railway's `idleTimeoutMinutes`) — the knob lives on the sandbox, the
83
+ * fleet only needs it to schedule GC and stamp sandbox clones. Advisory:
84
+ * providers without idle GC ignore it, and a re-open detects a torn-down VM
85
+ * and re-provisions cleanly.
86
+ */
87
+ get idleMinutes() {
88
+ const machine = this.#config?.machine;
89
+ const minutes = machine?.idleTimeoutMinutes;
90
+ return typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 ? minutes : 30;
91
+ }
92
+ /**
93
+ * Per-replica cap on concurrently *provisioned* sandboxes. 0 means unlimited.
94
+ * This is a lightweight per-process budget to keep a single replica from
95
+ * exhausting provider quota — it is not a global, cross-replica scheduler
96
+ * (that is a deferred follow-up).
97
+ */
98
+ get maxSandboxes() {
99
+ return this.#config?.maxSandboxes ?? 0;
100
+ }
101
+ /**
102
+ * Count of sandboxes this fleet has freshly provisioned and not yet torn
103
+ * down. Reattaches to existing VMs do not count (they reuse an already-billed
104
+ * sandbox). Used to enforce {@link maxSandboxes}.
105
+ */
106
+ get liveCount() {
107
+ return this.#liveCount;
108
+ }
109
+ /** For tests: reset the live-sandbox counter to a known state. */
110
+ __resetLiveCount(value = 0) {
111
+ this.#liveCount = value;
112
+ }
113
+ /** Override the sandbox factory (tests). */
114
+ setFactory(factory) {
115
+ this.#factory = factory;
116
+ }
117
+ /** Reset to the default machine-cloning factory. */
118
+ resetFactory() {
119
+ this.#factory = void 0;
120
+ }
121
+ /**
122
+ * Compute the in-sandbox working directory for a repo: a nested
123
+ * `<base>/<owner>/<name>` layout under the factory-resolved checkout base.
124
+ * Nesting keeps same-name repos apart (`acme/api` vs `other/api`) — cloud
125
+ * sandboxes are one-per-project so it's merely tidy there, but local
126
+ * checkouts share one host root where it prevents collisions. Server-side
127
+ * only; never derived from client input.
128
+ */
129
+ computeWorkdir(repoFullName) {
130
+ if (!this.#config) throw new Error("No sandbox configured");
131
+ const [owner, name] = repoFullName.split("/", 2);
132
+ return `${this.#config.workdirBase}/${sanitizeSegment(owner || "unknown")}/${sanitizeSegment(name || "repo")}`;
133
+ }
134
+ /**
135
+ * Compute the host working directory for a local GitHub session checkout.
136
+ * This is server-derived only: repo pieces are sanitized and the trusted
137
+ * session id is kept as a single path segment under the configured local root.
138
+ */
139
+ computeLocalSessionWorkdir(repoFullName, sessionId) {
140
+ if (!this.#config) throw new Error("No sandbox configured");
141
+ if (this.#config.machine.provider !== "local") {
142
+ throw new Error("Local session workdirs require the local sandbox provider");
143
+ }
144
+ const localRoot = this.#config.machine.workingDirectory;
145
+ if (typeof localRoot !== "string" || localRoot.length === 0) {
146
+ throw new Error("Local sandbox working directory is not configured");
147
+ }
148
+ const [owner, name] = repoFullName.split("/", 2);
149
+ return resolveContainedLocalWorkdir(
150
+ localRoot,
151
+ "github-sessions",
152
+ sanitizeSegment(owner || "unknown"),
153
+ sanitizeSegment(name || "repo"),
154
+ sanitizeSegment(sessionId)
155
+ );
156
+ }
157
+ /**
158
+ * Build a (not-yet-started) sandbox: the test-provided factory when set,
159
+ * otherwise a per-project clone of the configured machine. The stored id is
160
+ * passed both as the logical `id` (providers that reattach by construction
161
+ * id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so
162
+ * reattach works across the provider matrix.
163
+ */
164
+ #build(opts) {
165
+ if (this.#factory) return this.#factory(opts);
166
+ if (!this.#config) throw new Error("No sandbox configured");
167
+ const clone = this.#config.machine.clone({
168
+ ...opts.providerSandboxId ? { id: opts.providerSandboxId, sandboxId: opts.providerSandboxId } : {},
169
+ ...opts.env ? { env: opts.env } : {},
170
+ ...opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {},
171
+ ...opts.idleTimeoutMinutes !== void 0 ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {},
172
+ ...opts.checkpointName ? { checkpointName: opts.checkpointName } : {}
173
+ });
174
+ return toMaterializationSandbox(clone);
175
+ }
176
+ async ensureSandbox(store, envOrProgress, progressOrOptions, maybeOptions = {}) {
177
+ const env = typeof envOrProgress === "function" ? void 0 : envOrProgress;
178
+ const onProgress = typeof envOrProgress === "function" ? envOrProgress : progressOrOptions;
179
+ const options = typeof envOrProgress === "function" ? progressOrOptions ?? {} : maybeOptions;
180
+ const idleTimeoutMinutes = this.idleMinutes;
181
+ const checkpointName = store.checkpointName;
182
+ if (store.sandboxId) {
183
+ reportProgress(onProgress, { phase: "reattaching", message: "Reconnecting to your sandbox\u2026" });
184
+ const reattached = this.#build({
185
+ providerSandboxId: store.sandboxId,
186
+ idleTimeoutMinutes,
187
+ ...checkpointName ? { checkpointName } : {},
188
+ ...env ? { env } : {},
189
+ ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}
190
+ });
191
+ try {
192
+ await reattached.start();
193
+ return reattached;
194
+ } catch {
195
+ await store.setSandboxId(null);
196
+ }
197
+ }
198
+ const max = this.maxSandboxes;
199
+ if (max > 0 && this.#liveCount >= max) {
200
+ throw new SandboxBudgetError(max);
201
+ }
202
+ reportProgress(onProgress, { phase: "provisioning", message: "Provisioning a new sandbox\u2026" });
203
+ const sandbox = this.#build({
204
+ idleTimeoutMinutes,
205
+ ...checkpointName ? { checkpointName } : {},
206
+ ...env ? { env } : {},
207
+ ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}
208
+ });
209
+ await sandbox.start();
210
+ this.#liveCount += 1;
211
+ const providerSandboxId = await readProviderSandboxId(sandbox);
212
+ if (providerSandboxId) {
213
+ await store.setSandboxId(providerSandboxId);
214
+ }
215
+ return sandbox;
216
+ }
217
+ /**
218
+ * Tear down a sandbox binding: stop the live VM (best-effort) and clear the
219
+ * persisted state through the binding store so the next open re-provisions
220
+ * cleanly. Decrements the per-replica live-sandbox counter.
221
+ *
222
+ * @param store the binding to tear down
223
+ * @param sandbox an already-reattached live sandbox to stop, when available
224
+ */
225
+ async teardownSandbox(store, sandbox) {
226
+ if (sandbox?.stop) {
227
+ try {
228
+ await sandbox.stop();
229
+ } catch {
230
+ }
231
+ }
232
+ if (store.sandboxId) {
233
+ if (this.#liveCount > 0) this.#liveCount -= 1;
234
+ await store.clear();
235
+ }
236
+ }
237
+ /**
238
+ * Reattach to an already-provisioned sandbox by its provider id and start it.
239
+ * Used by the workspace seam when opening a project that was already
240
+ * materialized (sandbox id + workdir carried on controller state), so no DB
241
+ * round-trip is needed.
242
+ */
243
+ async reattachSandbox(providerSandboxId, options = {}) {
244
+ const sandbox = this.#build({
245
+ providerSandboxId,
246
+ idleTimeoutMinutes: this.idleMinutes,
247
+ ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}
248
+ });
249
+ await sandbox.start();
250
+ return sandbox;
251
+ }
252
+ };
253
+ export {
254
+ SandboxBudgetError,
255
+ SandboxFleet,
256
+ reportProgress,
257
+ resolveContainedLocalWorkdir
258
+ };
259
+ //# sourceMappingURL=fleet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/sandbox/fleet.ts"],"sourcesContent":["/**\n * Project sandbox fleet: provisioning, reattach, teardown, and budgeting.\n *\n * Server-hosted projects never run on the web host itself. Each project gets\n * its own isolated sandbox (a `WorkspaceSandbox`, e.g. a Railway VM) `clone()`d\n * from the machine the factory was configured with. This module owns everything\n * about that fleet — which provider is active, where checkouts live inside a\n * sandbox, the idle window, the per-replica budget, and the\n * provision/reattach/teardown lifecycle — but knows nothing about what runs\n * inside a sandbox (git materialization lives with its feature, e.g. the\n * GitHub integration's `sandbox.ts`).\n *\n * The fleet is constructed once at boot with the machine config (or none, when\n * sandboxes are disabled) and handed to consumers — no global registry.\n * Persistence of the provider's reattach id is delegated to the caller via\n * {@link SandboxBindingStore}, so the fleet stays storage-agnostic. Tests can\n * swap the low-level construction via {@link SandboxFleet.setFactory}.\n */\n\nimport path from 'node:path';\n\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\n/** Minimal command result shape sandbox consumers depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Minimal live-sandbox surface fleet consumers need: an id, a way to start it,\n * a way to learn the provider's reattach id, and command execution.\n */\nexport interface MaterializationSandbox {\n readonly id: string;\n start(): Promise<void>;\n getInfo(): Promise<{ metadata?: Record<string, unknown> }>;\n executeCommand(command: string, args?: string[], options?: { timeout?: number }): Promise<SandboxCommandResult>;\n /** Tear down the underlying VM. Optional: providers without it are no-ops. */\n stop?(): Promise<void>;\n}\n\n/** Options for building (or reattaching) one sandbox. */\nexport interface SandboxCreateOptions {\n /** Reattach to this existing provider VM instead of provisioning a new one. */\n providerSandboxId?: string;\n /** Environment variables baked into the sandbox. */\n env?: Record<string, string>;\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n /** Idle teardown window (minutes). The provider stops the VM after this idle period. */\n idleTimeoutMinutes?: number;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n checkpointName?: string;\n}\n\n/**\n * A coarse-grained step of the sandbox-preparation flow, reported as it happens\n * so the UI can show the user what the server is doing instead of a static\n * \"Preparing…\" toast. `phase` is a stable machine token; `message` is\n * user-facing copy.\n */\nexport interface PrepareProgress {\n phase: 'reattaching' | 'provisioning' | 'preparing-workspace' | 'cloning' | 'pulling' | 'finalizing' | 'done';\n message: string;\n}\n\n/** Callback invoked with each preparation step. Best-effort; never throws. */\nexport type ProgressFn = (event: PrepareProgress) => void;\n\n/** Invoke a progress callback without letting it break the actual work. */\nexport function reportProgress(onProgress: ProgressFn | undefined, event: PrepareProgress): void {\n if (!onProgress) return;\n try {\n onProgress(event);\n } catch {\n // Progress reporting must never break the actual work.\n }\n}\n\n/**\n * Factory that builds a (not-yet-started) sandbox. When `providerSandboxId` is\n * provided the sandbox should reattach to that existing VM instead of\n * provisioning a new one.\n */\nexport type SandboxFactory = (opts: SandboxCreateOptions) => MaterializationSandbox;\n\n/** Raised when provisioning would exceed the per-replica sandbox budget. */\nexport class SandboxBudgetError extends Error {\n readonly code = 'sandbox-budget-exceeded' as const;\n constructor(readonly max: number) {\n super(\n `Sandbox budget exceeded: this server already has ${max} active sandbox(es), ` +\n `the configured per-replica maximum. Close an existing repository's sandbox and try again.`,\n );\n this.name = 'SandboxBudgetError';\n }\n}\n\n/** Optional knobs for provisioning/reattaching one sandbox. */\nexport interface EnsureSandboxOptions {\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n}\n\n/**\n * Where a feature persists its sandbox binding. The fleet reads the stored\n * reattach id and writes updates through this seam so it stays agnostic of\n * the owning table (GitHub projects today, anything else tomorrow).\n */\nexport interface SandboxBindingStore {\n /** Stored provider reattach id from a previous provisioning, if any. */\n readonly sandboxId: string | null;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n readonly checkpointName?: string;\n /** Persist a freshly provisioned provider id, or clear a stale one with `null`. */\n setSandboxId(id: string | null): Promise<void>;\n /** Clear all stored sandbox state (reattach id + materialization mark) on teardown. */\n clear(): Promise<void>;\n}\n\n/**\n * Adapt a cloned `WorkspaceSandbox` to the minimal surface this module needs.\n * Lifecycle goes through the `_`-prefixed wrappers when present (they add\n * status tracking and concurrency safety on `MastraSandbox` subclasses),\n * falling back to the plain methods for interface-only implementations.\n */\nfunction toMaterializationSandbox(sandbox: WorkspaceSandbox): MaterializationSandbox {\n if (typeof sandbox.executeCommand !== 'function') {\n throw new Error(\n `Sandbox provider '${sandbox.provider}' does not implement executeCommand() — cannot materialize repos.`,\n );\n }\n const lifecycle = sandbox as { _start?(): Promise<void>; _stop?(): Promise<void> };\n return {\n id: sandbox.id,\n start: async () => {\n await (lifecycle._start ?? sandbox.start)?.call(sandbox);\n },\n getInfo: async () => (await sandbox.getInfo?.()) ?? {},\n executeCommand: (command, args, options) => sandbox.executeCommand!(command, args, options),\n stop: async () => {\n await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);\n },\n };\n}\n\n/**\n * The provider's reattach id for a started sandbox. For Railway this is the\n * underlying `railwaySandboxId` in `getInfo().metadata`. Providers without a\n * provider-native id (e.g. local) reattach by construction id, so fall back\n * to the sandbox's own logical id.\n */\nasync function readProviderSandboxId(sandbox: MaterializationSandbox): Promise<string | undefined> {\n const info = await sandbox.getInfo();\n const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;\n return typeof id === 'string' ? id : sandbox.id;\n}\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nfunction sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n\n/**\n * Factory-resolved sandbox runtime the fleet is constructed with: the machine\n * projects clone their per-project sandboxes from, plus the knobs the factory\n * resolved around it.\n */\nexport interface SandboxFleetConfig {\n /**\n * Template machine (validated by the factory to implement `clone()`).\n * Never started — acts purely as the credential/default holder that\n * per-project sandboxes are cloned from.\n */\n machine: WorkspaceSandbox;\n /** In-sandbox base directory repos check out under (no trailing slash). */\n workdirBase: string;\n /** Per-replica cap on concurrently provisioned sandboxes. 0 = unlimited. */\n maxSandboxes?: number;\n}\n\n/**\n * The sandbox fleet for one deployment. Constructed once at boot — with a\n * config when a sandbox machine was configured, or without one when sandboxes\n * are disabled (every provisioning entry point then throws and\n * {@link enabled} reports `false` so features stay off).\n */\nexport class SandboxFleet {\n readonly #config: SandboxFleetConfig | undefined;\n #factory: SandboxFactory | undefined;\n #liveCount = 0;\n\n constructor(config?: SandboxFleetConfig) {\n this.#config = config;\n }\n\n /**\n * True when a sandbox machine was configured. The factory validates the\n * machine implements `clone()` at boot, so a configured fleet is usable —\n * sandbox-backed projects stay off only when the slot was omitted.\n */\n get enabled(): boolean {\n return this.#config !== undefined;\n }\n\n /**\n * Name of the active sandbox provider — the configured machine's `provider`\n * discriminator (`'railway'`, `'local'`, …), or `'none'` when the fleet was\n * constructed without a config. Diagnostic only; feature gating goes\n * through {@link enabled}.\n */\n get provider(): string {\n return this.#config?.machine.provider ?? 'none';\n }\n\n /**\n * Idle teardown window for provisioned sandboxes, in minutes; defaults to 30.\n * Read back from the machine's own config when it exposes one\n * (Railway's `idleTimeoutMinutes`) — the knob lives on the sandbox, the\n * fleet only needs it to schedule GC and stamp sandbox clones. Advisory:\n * providers without idle GC ignore it, and a re-open detects a torn-down VM\n * and re-provisions cleanly.\n */\n get idleMinutes(): number {\n const machine = this.#config?.machine as { idleTimeoutMinutes?: unknown } | undefined;\n const minutes = machine?.idleTimeoutMinutes;\n return typeof minutes === 'number' && Number.isFinite(minutes) && minutes > 0 ? minutes : 30;\n }\n\n /**\n * Per-replica cap on concurrently *provisioned* sandboxes. 0 means unlimited.\n * This is a lightweight per-process budget to keep a single replica from\n * exhausting provider quota — it is not a global, cross-replica scheduler\n * (that is a deferred follow-up).\n */\n get maxSandboxes(): number {\n return this.#config?.maxSandboxes ?? 0;\n }\n\n /**\n * Count of sandboxes this fleet has freshly provisioned and not yet torn\n * down. Reattaches to existing VMs do not count (they reuse an already-billed\n * sandbox). Used to enforce {@link maxSandboxes}.\n */\n get liveCount(): number {\n return this.#liveCount;\n }\n\n /** For tests: reset the live-sandbox counter to a known state. */\n __resetLiveCount(value = 0): void {\n this.#liveCount = value;\n }\n\n /** Override the sandbox factory (tests). */\n setFactory(factory: SandboxFactory): void {\n this.#factory = factory;\n }\n\n /** Reset to the default machine-cloning factory. */\n resetFactory(): void {\n this.#factory = undefined;\n }\n\n /**\n * Compute the in-sandbox working directory for a repo: a nested\n * `<base>/<owner>/<name>` layout under the factory-resolved checkout base.\n * Nesting keeps same-name repos apart (`acme/api` vs `other/api`) — cloud\n * sandboxes are one-per-project so it's merely tidy there, but local\n * checkouts share one host root where it prevents collisions. Server-side\n * only; never derived from client input.\n */\n computeWorkdir(repoFullName: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n const [owner, name] = repoFullName.split('/', 2);\n return `${this.#config.workdirBase}/${sanitizeSegment(owner || 'unknown')}/${sanitizeSegment(name || 'repo')}`;\n }\n\n /**\n * Compute the host working directory for a local GitHub session checkout.\n * This is server-derived only: repo pieces are sanitized and the trusted\n * session id is kept as a single path segment under the configured local root.\n */\n computeLocalSessionWorkdir(repoFullName: string, sessionId: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n if (this.#config.machine.provider !== 'local') {\n throw new Error('Local session workdirs require the local sandbox provider');\n }\n\n const localRoot = (this.#config.machine as { workingDirectory?: unknown }).workingDirectory;\n if (typeof localRoot !== 'string' || localRoot.length === 0) {\n throw new Error('Local sandbox working directory is not configured');\n }\n\n const [owner, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(\n localRoot,\n 'github-sessions',\n sanitizeSegment(owner || 'unknown'),\n sanitizeSegment(name || 'repo'),\n sanitizeSegment(sessionId),\n );\n }\n\n /**\n * Build a (not-yet-started) sandbox: the test-provided factory when set,\n * otherwise a per-project clone of the configured machine. The stored id is\n * passed both as the logical `id` (providers that reattach by construction\n * id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so\n * reattach works across the provider matrix.\n */\n #build(opts: SandboxCreateOptions): MaterializationSandbox {\n if (this.#factory) return this.#factory(opts);\n if (!this.#config) throw new Error('No sandbox configured');\n const clone = this.#config.machine.clone!({\n ...(opts.providerSandboxId ? { id: opts.providerSandboxId, sandboxId: opts.providerSandboxId } : {}),\n ...(opts.env ? { env: opts.env } : {}),\n ...(opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {}),\n ...(opts.idleTimeoutMinutes !== undefined ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {}),\n ...(opts.checkpointName ? { checkpointName: opts.checkpointName } : {}),\n });\n return toMaterializationSandbox(clone);\n }\n\n /**\n * Provision a new sandbox (persisting its provider id on first open) or\n * reattach to the stored one. Returns a started, live sandbox.\n */\n async ensureSandbox(store: SandboxBindingStore, onProgress?: ProgressFn): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n env?: Record<string, string>,\n onProgress?: ProgressFn,\n options?: EnsureSandboxOptions,\n ): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n envOrProgress?: Record<string, string> | ProgressFn,\n progressOrOptions?: ProgressFn | EnsureSandboxOptions,\n maybeOptions: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const env = typeof envOrProgress === 'function' ? undefined : envOrProgress;\n const onProgress =\n typeof envOrProgress === 'function' ? envOrProgress : (progressOrOptions as ProgressFn | undefined);\n const options =\n typeof envOrProgress === 'function'\n ? ((progressOrOptions as EnsureSandboxOptions | undefined) ?? {})\n : maybeOptions;\n const idleTimeoutMinutes = this.idleMinutes;\n const checkpointName = store.checkpointName;\n\n // Reattach path: if we have a stored sandbox id, try to reattach. The VM may\n // have been torn down by the provider's idle GC (or otherwise died), in which\n // case `start()` fails. Recover by clearing the stale id and provisioning a\n // fresh sandbox so the next open succeeds instead of being permanently wedged.\n if (store.sandboxId) {\n reportProgress(onProgress, { phase: 'reattaching', message: 'Reconnecting to your sandbox…' });\n const reattached = this.#build({\n providerSandboxId: store.sandboxId,\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n try {\n await reattached.start();\n return reattached;\n } catch {\n await store.setSandboxId(null);\n // fall through to fresh provision below\n }\n }\n\n // Fresh provision: enforce the per-replica budget before spending quota.\n const max = this.maxSandboxes;\n if (max > 0 && this.#liveCount >= max) {\n throw new SandboxBudgetError(max);\n }\n\n reportProgress(onProgress, { phase: 'provisioning', message: 'Provisioning a new sandbox…' });\n const sandbox = this.#build({\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n this.#liveCount += 1;\n\n const providerSandboxId = await readProviderSandboxId(sandbox);\n if (providerSandboxId) {\n await store.setSandboxId(providerSandboxId);\n }\n\n return sandbox;\n }\n\n /**\n * Tear down a sandbox binding: stop the live VM (best-effort) and clear the\n * persisted state through the binding store so the next open re-provisions\n * cleanly. Decrements the per-replica live-sandbox counter.\n *\n * @param store the binding to tear down\n * @param sandbox an already-reattached live sandbox to stop, when available\n */\n async teardownSandbox(store: SandboxBindingStore, sandbox?: MaterializationSandbox): Promise<void> {\n if (sandbox?.stop) {\n try {\n await sandbox.stop();\n } catch {\n // Best-effort: the VM may already be gone (idle GC). Still clear the binding.\n }\n }\n if (store.sandboxId) {\n if (this.#liveCount > 0) this.#liveCount -= 1;\n await store.clear();\n }\n }\n\n /**\n * Reattach to an already-provisioned sandbox by its provider id and start it.\n * Used by the workspace seam when opening a project that was already\n * materialized (sandbox id + workdir carried on controller state), so no DB\n * round-trip is needed.\n */\n async reattachSandbox(\n providerSandboxId: string,\n options: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const sandbox = this.#build({\n providerSandboxId,\n idleTimeoutMinutes: this.idleMinutes,\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n return sandbox;\n }\n}\n"],"mappings":";AAmBA,OAAO,UAAU;AAqDV,SAAS,eAAe,YAAoC,OAA8B;AAC/F,MAAI,CAAC,WAAY;AACjB,MAAI;AACF,eAAW,KAAK;AAAA,EAClB,QAAQ;AAAA,EAER;AACF;AAUO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAE5C,YAAqB,KAAa;AAChC;AAAA,MACE,oDAAoD,GAAG;AAAA,IAEzD;AAJmB;AAKnB,SAAK,OAAO;AAAA,EACd;AAAA,EANqB;AAAA,EADZ,OAAO;AAQlB;AA8BA,SAAS,yBAAyB,SAAmD;AACnF,MAAI,OAAO,QAAQ,mBAAmB,YAAY;AAChD,UAAM,IAAI;AAAA,MACR,qBAAqB,QAAQ,QAAQ;AAAA,IACvC;AAAA,EACF;AACA,QAAM,YAAY;AAClB,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,OAAO,YAAY;AACjB,aAAO,UAAU,UAAU,QAAQ,QAAQ,KAAK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mBACA,UAAgC,CAAC,GACA;AACjC,UAAM,UAAU,KAAK,OAAO;AAAA,MAC1B;AAAA,MACA,oBAAoB,KAAK;AAAA,MACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;AAAA,IACnF,CAAC;AACD,UAAM,QAAQ,MAAM;AACpB,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,3 @@
1
+ import type { SandboxFleet } from './fleet.js';
2
+ export declare function registerSandboxReattach(fleet: SandboxFleet): void;
3
+ //# sourceMappingURL=reattach.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reattach.d.ts","sourceRoot":"","sources":["../../src/sandbox/reattach.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAEjE"}
@@ -0,0 +1,9 @@
1
+ // src/sandbox/reattach.ts
2
+ import { registerSandboxReattach as registerOnCore } from "@mastra/code-sdk/agents/sandbox-reattach";
3
+ function registerSandboxReattach(fleet) {
4
+ registerOnCore((providerSandboxId) => fleet.reattachSandbox(providerSandboxId));
5
+ }
6
+ export {
7
+ registerSandboxReattach
8
+ };
9
+ //# sourceMappingURL=reattach.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/sandbox/reattach.ts"],"sourcesContent":["/**\n * Wires the core workspace sandbox seam to the factory's sandbox fleet.\n * Core's `getDynamicWorkspace` reattaches project sandboxes through\n * `@mastra/code-sdk/agents/sandbox-reattach`, but only the factory owns the\n * fleet — so `MastraFactory.prepare()` registers the implementation here once\n * the fleet is constructed.\n */\nimport { registerSandboxReattach as registerOnCore } from '@mastra/code-sdk/agents/sandbox-reattach';\nimport type { SandboxFleet } from './fleet.js';\n\nexport function registerSandboxReattach(fleet: SandboxFleet): void {\n registerOnCore(providerSandboxId => fleet.reattachSandbox(providerSandboxId));\n}\n"],"mappings":";AAOA,SAAS,2BAA2B,sBAAsB;AAGnD,SAAS,wBAAwB,OAA2B;AACjE,iBAAe,uBAAqB,MAAM,gBAAgB,iBAAiB,CAAC;AAC9E;","names":[]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Server-wide error handler for the MastraCode web surface.
3
+ *
4
+ * Installed as `server.onError`, which the deployer applies to the top-level
5
+ * Hono app AND the custom-route sub-app (`/web/*`, `/auth/*`) — without it,
6
+ * unexpected route errors surface as an opaque `Internal Server Error` with no
7
+ * server-side trace.
8
+ */
9
+ import type { Context } from 'hono';
10
+ /** Handle a route error: log full detail server-side, return structured JSON. */
11
+ export declare function handleServerError(err: Error, c: Context): Response;
12
+ //# sourceMappingURL=server-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-error.d.ts","sourceRoot":"","sources":["../src/server-error.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAGpC,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,GAAG,QAAQ,CAiBlE"}
@@ -0,0 +1,20 @@
1
+ // src/server-error.ts
2
+ import { HTTPException } from "hono/http-exception";
3
+ function handleServerError(err, c) {
4
+ if (err instanceof HTTPException) {
5
+ return c.json({ error: err.message }, err.status);
6
+ }
7
+ const detail = err instanceof Error ? err.stack ?? err.message : String(err);
8
+ console.error(`[MastraCode Web] ${c.req.method} ${c.req.path} failed: ${detail}`);
9
+ return c.json(
10
+ {
11
+ error: "internal_error",
12
+ message: err instanceof Error ? err.message : String(err)
13
+ },
14
+ 500
15
+ );
16
+ }
17
+ export {
18
+ handleServerError
19
+ };
20
+ //# sourceMappingURL=server-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server-error.ts"],"sourcesContent":["/**\n * Server-wide error handler for the MastraCode web surface.\n *\n * Installed as `server.onError`, which the deployer applies to the top-level\n * Hono app AND the custom-route sub-app (`/web/*`, `/auth/*`) — without it,\n * unexpected route errors surface as an opaque `Internal Server Error` with no\n * server-side trace.\n */\n\nimport type { Context } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\n\n/** Handle a route error: log full detail server-side, return structured JSON. */\nexport function handleServerError(err: Error, c: Context): Response {\n // Deliberate HTTP errors (auth middleware, body limits, handlers) keep their\n // status + message; they are expected flows, not server faults.\n if (err instanceof HTTPException) {\n return c.json({ error: err.message }, err.status);\n }\n\n const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);\n console.error(`[MastraCode Web] ${c.req.method} ${c.req.path} failed: ${detail}`);\n\n return c.json(\n {\n error: 'internal_error',\n message: err instanceof Error ? err.message : String(err),\n },\n 500,\n );\n}\n"],"mappings":";AAUA,SAAS,qBAAqB;AAGvB,SAAS,kBAAkB,KAAY,GAAsB;AAGlE,MAAI,eAAe,eAAe;AAChC,WAAO,EAAE,KAAK,EAAE,OAAO,IAAI,QAAQ,GAAG,IAAI,MAAM;AAAA,EAClD;AAEA,QAAM,SAAS,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,OAAO,GAAG;AAC7E,UAAQ,MAAM,oBAAoB,EAAE,IAAI,MAAM,IAAI,EAAE,IAAI,IAAI,YAAY,MAAM,EAAE;AAEhF,SAAO,EAAE;AAAA,IACP;AAAA,MACE,OAAO;AAAA,MACP,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IAC1D;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,48 @@
1
+ import type { MastraCodeState } from '@mastra/code-sdk/schema';
2
+ import type { SendAgentSignalResult } from '@mastra/core/agent';
3
+ import type { AgentController } from '@mastra/core/agent-controller';
4
+ import type { RequestContext } from '@mastra/core/request-context';
5
+ import type { Workspace } from '@mastra/core/workspace';
6
+ export interface SkillInvocationInput {
7
+ resourceId: string;
8
+ scope?: string;
9
+ name: string;
10
+ arguments?: string;
11
+ }
12
+ export interface SkillSession {
13
+ getWorkspace(): Workspace;
14
+ sendMessage(input: {
15
+ content: string;
16
+ }): Promise<unknown>;
17
+ sendNotificationSignal(input: {
18
+ source: string;
19
+ kind: string;
20
+ summary: string;
21
+ priority?: 'low' | 'medium' | 'high' | 'urgent';
22
+ payload?: unknown;
23
+ dedupeKey?: string;
24
+ sourceId?: string;
25
+ }, options?: {
26
+ ifActive?: {
27
+ behavior?: 'deliver' | 'persist';
28
+ };
29
+ ifIdle?: {
30
+ behavior?: 'persist' | 'wake';
31
+ };
32
+ requestContext?: RequestContext;
33
+ }): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;
34
+ }
35
+ export declare class SkillInvocationError extends Error {
36
+ readonly code: 'session_not_found' | 'skill_not_found';
37
+ constructor(code: SkillInvocationError['code'], message: string);
38
+ }
39
+ export declare function resolveSkillInvocation(controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>, input: SkillInvocationInput): Promise<{
40
+ session: SkillSession;
41
+ skillName: string;
42
+ message: string;
43
+ }>;
44
+ export declare function dispatchSkillInvocation(controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>, input: SkillInvocationInput): Promise<{
45
+ skillName: string;
46
+ message: string;
47
+ }>;
48
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/skills/service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,MAAM,CAAC;IAC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YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAkBxE;AAED,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,sBAAsB,CAAC,EAC1E,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAIjD"}
@@ -0,0 +1,45 @@
1
+ // src/skills/service.ts
2
+ import { formatSkillActivation } from "@mastra/core/workspace";
3
+ var SkillInvocationError = class extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "SkillInvocationError";
8
+ this.code = code;
9
+ }
10
+ };
11
+ function escapeSkillBoundary(value) {
12
+ return value.replaceAll("</skill>", "&lt;/skill&gt;");
13
+ }
14
+ async function resolveSkillInvocation(controller, input) {
15
+ const session = await controller.getSessionByResource(input.resourceId, input.scope);
16
+ if (!session) throw new SkillInvocationError("session_not_found", "Agent controller session not found.");
17
+ const skills = session.getWorkspace().skills;
18
+ await skills?.maybeRefresh();
19
+ const skill = await skills?.get(input.name);
20
+ if (!skill || skill["user-invocable"] === false) {
21
+ throw new SkillInvocationError("skill_not_found", `Skill not found: ${input.name}.`);
22
+ }
23
+ const args = input.arguments?.trim();
24
+ const content = `${formatSkillActivation(skill)}${args ? `
25
+
26
+ ARGUMENTS: ${args}` : ""}`.trim();
27
+ return {
28
+ session,
29
+ skillName: skill.name,
30
+ message: `<skill name="${skill.name}">
31
+ ${escapeSkillBoundary(content)}
32
+ </skill>`
33
+ };
34
+ }
35
+ async function dispatchSkillInvocation(controller, input) {
36
+ const resolved = await resolveSkillInvocation(controller, input);
37
+ await resolved.session.sendMessage({ content: resolved.message });
38
+ return { skillName: resolved.skillName, message: resolved.message };
39
+ }
40
+ export {
41
+ SkillInvocationError,
42
+ dispatchSkillInvocation,
43
+ resolveSkillInvocation
44
+ };
45
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/skills/service.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { SendAgentSignalResult } from '@mastra/core/agent';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\nimport type { Workspace } from '@mastra/core/workspace';\n\nexport interface SkillInvocationInput {\n resourceId: string;\n scope?: string;\n name: string;\n arguments?: string;\n}\n\nexport interface SkillSession {\n getWorkspace(): Workspace;\n sendMessage(input: { content: string }): Promise<unknown>;\n sendNotificationSignal(\n input: {\n source: string;\n kind: string;\n summary: string;\n priority?: 'low' | 'medium' | 'high' | 'urgent';\n payload?: unknown;\n dedupeKey?: string;\n sourceId?: string;\n },\n options?: {\n ifActive?: { behavior?: 'deliver' | 'persist' };\n ifIdle?: { behavior?: 'persist' | 'wake' };\n requestContext?: RequestContext;\n },\n ): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;\n}\n\nexport class SkillInvocationError extends Error {\n readonly code: 'session_not_found' | 'skill_not_found';\n\n constructor(code: SkillInvocationError['code'], message: string) {\n super(message);\n this.name = 'SkillInvocationError';\n this.code = code;\n }\n}\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nexport async function resolveSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ session: SkillSession; skillName: string; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n\n const skills = session.getWorkspace().skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(input.name);\n if (!skill || skill['user-invocable'] === false) {\n throw new SkillInvocationError('skill_not_found', `Skill not found: ${input.name}.`);\n }\n\n const args = input.arguments?.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return {\n session,\n skillName: skill.name,\n message: `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`,\n };\n}\n\nexport async function dispatchSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ skillName: string; message: string }> {\n const resolved = await resolveSkillInvocation(controller, input);\n await resolved.session.sendMessage({ content: resolved.message });\n return { skillName: resolved.skillName, message: resolved.message };\n}\n"],"mappings":";AAIA,SAAS,6BAA6B;AA+B/B,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EAET,YAAY,MAAoC,SAAiB;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,oBAAoB,OAAuB;AAClD,SAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;AAEA,eAAsB,uBACpB,YACA,OACwE;AACxE,QAAM,UAAW,MAAM,WAAW,qBAAqB,MAAM,YAAY,MAAM,KAAK;AACpF,MAAI,CAAC,QAAS,OAAM,IAAI,qBAAqB,qBAAqB,qCAAqC;AAEvG,QAAM,SAAS,QAAQ,aAAa,EAAE;AACtC,QAAM,QAAQ,aAAa;AAC3B,QAAM,QAAQ,MAAM,QAAQ,IAAI,MAAM,IAAI;AAC1C,MAAI,CAAC,SAAS,MAAM,gBAAgB,MAAM,OAAO;AAC/C,UAAM,IAAI,qBAAqB,mBAAmB,oBAAoB,MAAM,IAAI,GAAG;AAAA,EACrF;AAEA,QAAM,OAAO,MAAM,WAAW,KAAK;AACnC,QAAM,UAAU,GAAG,sBAAsB,KAAK,CAAC,GAAG,OAAO;AAAA;AAAA,aAAkB,IAAI,KAAK,EAAE,GAAG,KAAK;AAC9F,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,SAAS,gBAAgB,MAAM,IAAI;AAAA,EAAO,oBAAoB,OAAO,CAAC;AAAA;AAAA,EACxE;AACF;AAEA,eAAsB,wBACpB,YACA,OACiD;AACjD,QAAM,WAAW,MAAM,uBAAuB,YAAY,KAAK;AAC/D,QAAM,SAAS,QAAQ,YAAY,EAAE,SAAS,SAAS,QAAQ,CAAC;AAChE,SAAO,EAAE,WAAW,SAAS,WAAW,SAAS,SAAS,QAAQ;AACpE;","names":[]}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Same-origin SPA serving for production.
3
+ *
4
+ * In dev the SPA is served by Vite (:5173) which proxies API paths to the
5
+ * server (:4111) — this module is effectively idle there. In production the
6
+ * built SPA (vite output) is served by the API server itself at `/`, so the
7
+ * app is a single origin and no CORS / separate static host is required.
8
+ *
9
+ * The middleware is mounted via the Mastra entry's `server.middleware`, which
10
+ * the deployer applies before routes: real file hits and SPA navigations are
11
+ * answered here, everything else falls through to the API routes.
12
+ */
13
+ import type { Context } from 'hono';
14
+ /**
15
+ * Locate the built SPA (a dir containing `index.html`). Checked in order:
16
+ * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.
17
+ * 2. `ui/` next to the bundled server module — vite builds into
18
+ * `src/mastra/public/ui` and `mastra build` copies `public/` into
19
+ * `.mastra/output/`, so the build output is self-contained.
20
+ * 3. `src/mastra/public/ui` under cwd — the vite outDir when running from
21
+ * the package root before `mastra build`.
22
+ * Returns `undefined` when no build is found (e.g. plain `mastra dev` without
23
+ * a prior vite build), in which case the middleware is simply not mounted.
24
+ */
25
+ export declare function resolveUiDistDir(): string | undefined;
26
+ /**
27
+ * Hono middleware serving the built SPA from `uiDist`:
28
+ * - exact file hits (js/css/assets) are served directly,
29
+ * - GET navigations to non-server paths fall back to `index.html` (SPA
30
+ * client-side routing),
31
+ * - `/api`, `/web`, `/auth` and non-GET requests always pass through.
32
+ */
33
+ export declare function createSpaStaticMiddleware(uiDist: string): (c: Context, next: () => Promise<void>) => Promise<Response | void>;
34
+ //# sourceMappingURL=spa-static.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spa-static.d.ts","sourceRoot":"","sources":["../src/spa-static.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA0BpC;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAUrD;AAmBD;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,IACxC,GAAG,OAAO,EAAE,MAAM,MAAM,OAAO,CAAC,IAAI,CAAC,KAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAuB/E"}
@@ -0,0 +1,73 @@
1
+ // src/spa-static.ts
2
+ import { existsSync } from "fs";
3
+ import { readFile, stat } from "fs/promises";
4
+ import { dirname, extname, join, normalize, resolve, sep } from "path";
5
+ import { fileURLToPath } from "url";
6
+ var MIME = {
7
+ ".html": "text/html; charset=utf-8",
8
+ ".js": "text/javascript; charset=utf-8",
9
+ ".mjs": "text/javascript; charset=utf-8",
10
+ ".css": "text/css; charset=utf-8",
11
+ ".json": "application/json",
12
+ ".map": "application/json",
13
+ ".svg": "image/svg+xml",
14
+ ".png": "image/png",
15
+ ".jpg": "image/jpeg",
16
+ ".jpeg": "image/jpeg",
17
+ ".gif": "image/gif",
18
+ ".webp": "image/webp",
19
+ ".ico": "image/x-icon",
20
+ ".txt": "text/plain; charset=utf-8",
21
+ ".woff": "font/woff",
22
+ ".woff2": "font/woff2",
23
+ ".ttf": "font/ttf",
24
+ ".wasm": "application/wasm"
25
+ };
26
+ var SERVER_PREFIXES = ["/api", "/web", "/auth"];
27
+ function resolveUiDistDir() {
28
+ const candidates = [
29
+ process.env.MASTRACODE_UI_DIST,
30
+ join(dirname(fileURLToPath(import.meta.url)), "ui"),
31
+ resolve(process.cwd(), "src/mastra/public/ui")
32
+ ];
33
+ for (const candidate of candidates) {
34
+ if (candidate && existsSync(join(candidate, "index.html"))) return resolve(candidate);
35
+ }
36
+ return void 0;
37
+ }
38
+ async function isFile(path) {
39
+ try {
40
+ return (await stat(path)).isFile();
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ async function serveFile(c, filePath, immutable) {
46
+ const data = await readFile(filePath);
47
+ c.header("Content-Type", MIME[extname(filePath).toLowerCase()] ?? "application/octet-stream");
48
+ c.header("Cache-Control", immutable ? "public, max-age=31536000, immutable" : "no-cache");
49
+ return c.body(new Uint8Array(data));
50
+ }
51
+ function createSpaStaticMiddleware(uiDist) {
52
+ return async (c, next) => {
53
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") return next();
54
+ const path = c.req.path;
55
+ if (SERVER_PREFIXES.some((prefix) => path === prefix || path.startsWith(`${prefix}/`))) return next();
56
+ const relative = normalize(decodeURIComponent(path)).replace(/^[/\\]+/, "");
57
+ const filePath = resolve(uiDist, relative);
58
+ const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;
59
+ if (filePath.startsWith(uiDistPrefix) && relative !== "" && await isFile(filePath)) {
60
+ return serveFile(c, filePath, relative.startsWith("assets/"));
61
+ }
62
+ const accept = c.req.header("Accept") ?? "";
63
+ if (path === "/" || accept.includes("text/html")) {
64
+ return serveFile(c, join(uiDist, "index.html"), false);
65
+ }
66
+ return next();
67
+ };
68
+ }
69
+ export {
70
+ createSpaStaticMiddleware,
71
+ resolveUiDistDir
72
+ };
73
+ //# sourceMappingURL=spa-static.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/spa-static.ts"],"sourcesContent":["/**\n * Same-origin SPA serving for production.\n *\n * In dev the SPA is served by Vite (:5173) which proxies API paths to the\n * server (:4111) — this module is effectively idle there. In production the\n * built SPA (vite output) is served by the API server itself at `/`, so the\n * app is a single origin and no CORS / separate static host is required.\n *\n * The middleware is mounted via the Mastra entry's `server.middleware`, which\n * the deployer applies before routes: real file hits and SPA navigations are\n * answered here, everything else falls through to the API routes.\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, normalize, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Context } from 'hono';\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json',\n '.map': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.txt': 'text/plain; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.wasm': 'application/wasm',\n};\n\n/** Server-owned path prefixes the SPA middleware must never answer for. */\nconst SERVER_PREFIXES = ['/api', '/web', '/auth'];\n\n/**\n * Locate the built SPA (a dir containing `index.html`). Checked in order:\n * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.\n * 2. `ui/` next to the bundled server module — vite builds into\n * `src/mastra/public/ui` and `mastra build` copies `public/` into\n * `.mastra/output/`, so the build output is self-contained.\n * 3. `src/mastra/public/ui` under cwd — the vite outDir when running from\n * the package root before `mastra build`.\n * Returns `undefined` when no build is found (e.g. plain `mastra dev` without\n * a prior vite build), in which case the middleware is simply not mounted.\n */\nexport function resolveUiDistDir(): string | undefined {\n const candidates = [\n process.env.MASTRACODE_UI_DIST,\n join(dirname(fileURLToPath(import.meta.url)), 'ui'),\n resolve(process.cwd(), 'src/mastra/public/ui'),\n ];\n for (const candidate of candidates) {\n if (candidate && existsSync(join(candidate, 'index.html'))) return resolve(candidate);\n }\n return undefined;\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nasync function serveFile(c: Context, filePath: string, immutable: boolean): Promise<Response> {\n const data = await readFile(filePath);\n c.header('Content-Type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream');\n // Vite emits content-hashed filenames under assets/ — cache those forever;\n // index.html (and anything unhashed) must revalidate so deploys roll out.\n c.header('Cache-Control', immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return c.body(new Uint8Array(data));\n}\n\n/**\n * Hono middleware serving the built SPA from `uiDist`:\n * - exact file hits (js/css/assets) are served directly,\n * - GET navigations to non-server paths fall back to `index.html` (SPA\n * client-side routing),\n * - `/api`, `/web`, `/auth` and non-GET requests always pass through.\n */\nexport function createSpaStaticMiddleware(uiDist: string) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();\n const path = c.req.path;\n if (SERVER_PREFIXES.some(prefix => path === prefix || path.startsWith(`${prefix}/`))) return next();\n\n // Resolve the request path inside uiDist, rejecting traversal escapes.\n const relative = normalize(decodeURIComponent(path)).replace(/^[/\\\\]+/, '');\n const filePath = resolve(uiDist, relative);\n // Use a trailing separator so a sibling like \"ui.key\" can't slip past the\n // prefix check (same pattern as fs-routes.ts isWithinRoot).\n const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;\n if (filePath.startsWith(uiDistPrefix) && relative !== '' && (await isFile(filePath))) {\n return serveFile(c, filePath, relative.startsWith('assets/'));\n }\n\n // SPA fallback: serve index.html for root and html navigations.\n const accept = c.req.header('Accept') ?? '';\n if (path === '/' || accept.includes('text/html')) {\n return serveFile(c, join(uiDist, 'index.html'), false);\n }\n\n return next();\n };\n}\n"],"mappings":";AAaA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,YAAY;AAC/B,SAAS,SAAS,SAAS,MAAM,WAAW,SAAS,WAAW;AAChE,SAAS,qBAAqB;AAI9B,IAAM,OAA+B;AAAA,EACnC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,Q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