@mastra/factory 0.11.1 → 0.12.0-alpha.0

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 (112) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/factory.d.ts +2 -22
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +15 -58
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/integrations/base.d.ts +5 -13
  9. package/dist/integrations/base.d.ts.map +1 -1
  10. package/dist/integrations/github/config.d.ts +4 -4
  11. package/dist/integrations/github/config.d.ts.map +1 -1
  12. package/dist/integrations/github/config.js +3 -3
  13. package/dist/integrations/github/config.js.map +1 -1
  14. package/dist/integrations/github/integration.d.ts.map +1 -1
  15. package/dist/integrations/github/integration.js +2 -4
  16. package/dist/integrations/github/integration.js.map +1 -1
  17. package/dist/integrations/github/reconcile-worker.d.ts +0 -5
  18. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +0 -7
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/routes.d.ts +6 -5
  22. package/dist/integrations/github/routes.d.ts.map +1 -1
  23. package/dist/integrations/github/routes.js +36 -263
  24. package/dist/integrations/github/routes.js.map +1 -1
  25. package/dist/integrations/github/sandbox-release.d.ts +17 -47
  26. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  27. package/dist/integrations/github/sandbox-release.js +24 -103
  28. package/dist/integrations/github/sandbox-release.js.map +1 -1
  29. package/dist/integrations/github/sandbox.d.ts +25 -139
  30. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox.js +24 -212
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/github/webhook.d.ts.map +1 -1
  34. package/dist/integrations/github/webhook.js +1 -2
  35. package/dist/integrations/github/webhook.js.map +1 -1
  36. package/dist/integrations/platform/github/event-worker.d.ts +0 -2
  37. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  38. package/dist/integrations/platform/github/event-worker.js +0 -7
  39. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  40. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  41. package/dist/integrations/platform/github/integration.js +5 -7
  42. package/dist/integrations/platform/github/integration.js.map +1 -1
  43. package/dist/routes/config.d.ts.map +1 -1
  44. package/dist/routes/config.js +3 -1
  45. package/dist/routes/config.js.map +1 -1
  46. package/dist/routes/fs.d.ts +4 -6
  47. package/dist/routes/fs.d.ts.map +1 -1
  48. package/dist/routes/fs.js +28 -34
  49. package/dist/routes/fs.js.map +1 -1
  50. package/dist/routes/skills.d.ts.map +1 -1
  51. package/dist/routes/skills.js +6 -3
  52. package/dist/routes/skills.js.map +1 -1
  53. package/dist/routes/surface.d.ts +4 -9
  54. package/dist/routes/surface.d.ts.map +1 -1
  55. package/dist/routes/surface.js +3 -5
  56. package/dist/routes/surface.js.map +1 -1
  57. package/dist/sandbox/materialization.d.ts +36 -0
  58. package/dist/sandbox/materialization.d.ts.map +1 -0
  59. package/dist/sandbox/materialization.js +18 -0
  60. package/dist/sandbox/materialization.js.map +1 -0
  61. package/dist/sandbox/session-retirement.d.ts +8 -6
  62. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  63. package/dist/sandbox/session-retirement.js +28 -123
  64. package/dist/sandbox/session-retirement.js.map +1 -1
  65. package/dist/sandbox/session-sandbox.d.ts +117 -0
  66. package/dist/sandbox/session-sandbox.d.ts.map +1 -0
  67. package/dist/sandbox/session-sandbox.js +132 -0
  68. package/dist/sandbox/session-sandbox.js.map +1 -0
  69. package/dist/sandbox/workdir.d.ts +30 -0
  70. package/dist/sandbox/workdir.d.ts.map +1 -0
  71. package/dist/sandbox/workdir.js +48 -0
  72. package/dist/sandbox/workdir.js.map +1 -0
  73. package/dist/session/filesystem-capture.d.ts +2 -1
  74. package/dist/session/filesystem-capture.d.ts.map +1 -1
  75. package/dist/session/filesystem-capture.js +45 -4
  76. package/dist/session/filesystem-capture.js.map +1 -1
  77. package/dist/session/first-exec-capture.d.ts +1 -0
  78. package/dist/session/first-exec-capture.d.ts.map +1 -1
  79. package/dist/session/first-exec-capture.js +1 -1
  80. package/dist/session/first-exec-capture.js.map +1 -1
  81. package/dist/storage/domains/integrations/base.d.ts +1 -1
  82. package/dist/storage/domains/integrations/base.js +1 -1
  83. package/dist/storage/domains/integrations/base.js.map +1 -1
  84. package/dist/storage/domains/source-control/base.d.ts +0 -144
  85. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  86. package/dist/storage/domains/source-control/base.js +3 -290
  87. package/dist/storage/domains/source-control/base.js.map +1 -1
  88. package/dist/storage/domains/source-control/inmemory.d.ts +1 -63
  89. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  90. package/dist/storage/domains/source-control/inmemory.js +0 -89
  91. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  92. package/dist/workspace.d.ts +5 -37
  93. package/dist/workspace.d.ts.map +1 -1
  94. package/dist/workspace.js +107 -245
  95. package/dist/workspace.js.map +1 -1
  96. package/package.json +4 -4
  97. package/dist/sandbox/base-checkpoint-triggers.d.ts +0 -77
  98. package/dist/sandbox/base-checkpoint-triggers.d.ts.map +0 -1
  99. package/dist/sandbox/base-checkpoint-triggers.js +0 -137
  100. package/dist/sandbox/base-checkpoint-triggers.js.map +0 -1
  101. package/dist/sandbox/base-checkpoint.d.ts +0 -59
  102. package/dist/sandbox/base-checkpoint.d.ts.map +0 -1
  103. package/dist/sandbox/base-checkpoint.js +0 -145
  104. package/dist/sandbox/base-checkpoint.js.map +0 -1
  105. package/dist/sandbox/fleet.d.ts +0 -258
  106. package/dist/sandbox/fleet.d.ts.map +0 -1
  107. package/dist/sandbox/fleet.js +0 -356
  108. package/dist/sandbox/fleet.js.map +0 -1
  109. package/dist/sandbox/reattach.d.ts +0 -3
  110. package/dist/sandbox/reattach.d.ts.map +0 -1
  111. package/dist/sandbox/reattach.js +0 -16
  112. package/dist/sandbox/reattach.js.map +0 -1
@@ -1,356 +0,0 @@
1
- import { timedPhase } from "../timing.js";
2
- import path from "path";
3
- //#region src/sandbox/fleet.ts
4
- /**
5
- * Project sandbox fleet: provisioning, reattach, teardown, and budgeting.
6
- *
7
- * Server-hosted projects never run on the web host itself. Each project gets
8
- * its own isolated sandbox (a `WorkspaceSandbox`, e.g. a Railway VM) `clone()`d
9
- * from the machine the factory was configured with. This module owns everything
10
- * about that fleet — which provider is active, where checkouts live inside a
11
- * sandbox, the idle window, the per-replica budget, and the
12
- * provision/reattach/teardown lifecycle — but knows nothing about what runs
13
- * inside a sandbox (git materialization lives with its feature, e.g. the
14
- * GitHub integration's `sandbox.ts`).
15
- *
16
- * The fleet is constructed once at boot with the machine config (or none, when
17
- * sandboxes are disabled) and handed to consumers — no global registry.
18
- * Persistence of the provider's reattach id is delegated to the caller via
19
- * {@link SandboxBindingStore}, so the fleet stays storage-agnostic. Tests can
20
- * swap the low-level construction via {@link SandboxFleet.setFactory}.
21
- */
22
- /** Invoke a progress callback without letting it break the actual work. */
23
- function reportProgress(onProgress, event) {
24
- if (!onProgress) return;
25
- try {
26
- onProgress(event);
27
- } catch {}
28
- }
29
- /** Raised when provisioning would exceed the per-replica sandbox budget. */
30
- var SandboxBudgetError = class extends Error {
31
- max;
32
- code = "sandbox-budget-exceeded";
33
- constructor(max) {
34
- super(`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.`);
35
- this.max = max;
36
- this.name = "SandboxBudgetError";
37
- }
38
- };
39
- /**
40
- * Stable identity for one binding's in-flight provision work, used to coalesce
41
- * concurrent `ensureSandbox` calls. Prefer `checkpointName` — it is a pure
42
- * function of the owning session and is set before the first provision, which
43
- * is exactly when the herd forms (the stored `sandboxId` is still null then).
44
- * Fall back to the stored provider id, and skip coalescing entirely for
45
- * bindings with neither: keying those on a shared constant would wrongly
46
- * funnel *different* bindings onto one sandbox.
47
- */
48
- function coalesceKey(store) {
49
- if (store.checkpointName) return `checkpoint:${store.checkpointName}`;
50
- if (store.sandboxId) return `sandbox:${store.sandboxId}`;
51
- }
52
- /**
53
- * Adapt a cloned `WorkspaceSandbox` to the minimal surface this module needs.
54
- * Lifecycle goes through the `_`-prefixed wrappers when present (they add
55
- * status tracking and concurrency safety on `MastraSandbox` subclasses),
56
- * falling back to the plain methods for interface-only implementations.
57
- */
58
- function toMaterializationSandbox(sandbox, initialEnvironment = {}) {
59
- if (typeof sandbox.executeCommand !== "function") throw new Error(`Sandbox provider '${sandbox.provider}' does not implement executeCommand() — cannot materialize repos.`);
60
- const lifecycle = sandbox;
61
- const environment = { ...initialEnvironment };
62
- return {
63
- id: sandbox.id,
64
- name: sandbox.name,
65
- provider: sandbox.provider,
66
- getInstructions: (opts) => sandbox.getInstructions?.(opts) ?? "",
67
- processes: sandbox.processes,
68
- mounts: sandbox.mounts,
69
- start: async () => {
70
- await (lifecycle._start ?? sandbox.start)?.call(sandbox);
71
- },
72
- getInfo: async () => await sandbox.getInfo?.() ?? {},
73
- executeCommand: (command, args, options) => sandbox.executeCommand(command, args, {
74
- ...options,
75
- env: {
76
- ...environment,
77
- ...options?.env
78
- }
79
- }),
80
- setEnvironmentVariable: (name, value) => {
81
- environment[name] = value;
82
- },
83
- stop: async () => {
84
- await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);
85
- },
86
- supportsCheckpoints: sandbox.supportsCheckpoints === true,
87
- ...sandbox.snapshot ? { snapshot: sandbox.snapshot.bind(sandbox) } : {}
88
- };
89
- }
90
- /**
91
- * Provider details reported after startup. Railway exposes its native sandbox
92
- * id and the checkpoint it actually restored through `getInfo().metadata`.
93
- */
94
- async function readProviderSandboxDetails(sandbox) {
95
- const info = await sandbox.getInfo();
96
- const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;
97
- const restoredCheckpointName = info.metadata?.restoredCheckpointName;
98
- return {
99
- sandboxId: typeof id === "string" ? id : sandbox.id,
100
- restoredCheckpointName: typeof restoredCheckpointName === "string" ? restoredCheckpointName : void 0
101
- };
102
- }
103
- /** Keep each path piece a single safe segment (no separators or traversal). */
104
- function sanitizeSegment(segment) {
105
- return segment.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^\.+/, "") || "repo";
106
- }
107
- /** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
108
- function resolveContainedLocalWorkdir(root, ...segments) {
109
- const resolvedRoot = path.resolve(root);
110
- const resolved = path.resolve(resolvedRoot, ...segments);
111
- if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;
112
- throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);
113
- }
114
- /**
115
- * The sandbox fleet for one deployment. Constructed once at boot — with a
116
- * config when a sandbox machine was configured, or without one when sandboxes
117
- * are disabled (every provisioning entry point then throws and
118
- * {@link enabled} reports `false` so features stay off).
119
- */
120
- var SandboxFleet = class {
121
- #config;
122
- #factory;
123
- #liveCount = 0;
124
- /** In-flight `ensureSandbox` work, keyed per binding so concurrent callers coalesce. */
125
- #inflight = /* @__PURE__ */ new Map();
126
- constructor(config) {
127
- this.#config = config;
128
- }
129
- /**
130
- * True when a sandbox machine was configured. The factory validates the
131
- * machine implements `clone()` at boot, so a configured fleet is usable —
132
- * sandbox-backed projects stay off only when the slot was omitted.
133
- */
134
- get enabled() {
135
- return this.#config !== void 0;
136
- }
137
- /**
138
- * Name of the active sandbox provider — the configured machine's `provider`
139
- * discriminator (`'railway'`, `'local'`, …), or `'none'` when the fleet was
140
- * constructed without a config. Diagnostic only; feature gating goes
141
- * through {@link enabled}.
142
- */
143
- get provider() {
144
- return this.#config?.machine.provider ?? "none";
145
- }
146
- /**
147
- * Usage instructions from the configured template machine, for surfacing in
148
- * tool descriptions before any per-session sandbox has materialized.
149
- * Empty string when no machine is configured or it exposes none.
150
- */
151
- getInstructions() {
152
- return this.#config?.machine.getInstructions?.() ?? "";
153
- }
154
- /**
155
- * Idle teardown window for provisioned sandboxes, in minutes; defaults to 30.
156
- * Read back from the machine's own config when it exposes one
157
- * (Railway's `idleTimeoutMinutes`) — the knob lives on the sandbox, the
158
- * fleet only needs it to schedule GC and stamp sandbox clones. Advisory:
159
- * providers without idle GC ignore it, and a re-open detects a torn-down VM
160
- * and re-provisions cleanly.
161
- */
162
- get idleMinutes() {
163
- const minutes = (this.#config?.machine)?.idleTimeoutMinutes;
164
- return typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 ? minutes : 30;
165
- }
166
- /**
167
- * Per-replica cap on concurrently *provisioned* sandboxes. 0 means unlimited.
168
- * This is a lightweight per-process budget to keep a single replica from
169
- * exhausting provider quota — it is not a global, cross-replica scheduler
170
- * (that is a deferred follow-up).
171
- */
172
- get maxSandboxes() {
173
- return this.#config?.maxSandboxes ?? 0;
174
- }
175
- /**
176
- * Count of sandboxes this fleet has freshly provisioned and not yet torn
177
- * down. Reattaches to existing VMs do not count (they reuse an already-billed
178
- * sandbox). Used to enforce {@link maxSandboxes}.
179
- */
180
- get liveCount() {
181
- return this.#liveCount;
182
- }
183
- /** For tests: reset the live-sandbox counter to a known state. */
184
- __resetLiveCount(value = 0) {
185
- this.#liveCount = value;
186
- }
187
- /** Override the sandbox factory (tests). */
188
- setFactory(factory) {
189
- this.#factory = factory;
190
- }
191
- /** Reset to the default machine-cloning factory. */
192
- resetFactory() {
193
- this.#factory = void 0;
194
- }
195
- /**
196
- * Compute the in-sandbox working directory for a repo: a nested
197
- * `<base>/<owner>/<name>` layout under the factory-resolved checkout base.
198
- * Nesting keeps same-name repos apart (`acme/api` vs `other/api`) — cloud
199
- * sandboxes are one-per-project so it's merely tidy there, but local
200
- * checkouts share one host root where it prevents collisions. Server-side
201
- * only; never derived from client input.
202
- */
203
- computeWorkdir(repoFullName) {
204
- if (!this.#config) throw new Error("No sandbox configured");
205
- const [owner, name] = repoFullName.split("/", 2);
206
- return `${this.#config.workdirBase}/${sanitizeSegment(owner || "unknown")}/${sanitizeSegment(name || "repo")}`;
207
- }
208
- /**
209
- * Compute the host working directory for a local GitHub session checkout.
210
- * This is server-derived only: repo pieces are sanitized and the trusted
211
- * session id is kept as a single path segment under the configured local root.
212
- */
213
- computeLocalSessionWorkdir(repoFullName, sessionId) {
214
- if (!this.#config) throw new Error("No sandbox configured");
215
- if (this.#config.machine.provider !== "local") throw new Error("Local session workdirs require the local sandbox provider");
216
- const localRoot = this.#config.machine.workingDirectory;
217
- if (typeof localRoot !== "string" || localRoot.length === 0) throw new Error("Local sandbox working directory is not configured");
218
- const [owner, name] = repoFullName.split("/", 2);
219
- return resolveContainedLocalWorkdir(localRoot, "github-sessions", sanitizeSegment(owner || "unknown"), sanitizeSegment(name || "repo"), sanitizeSegment(sessionId));
220
- }
221
- /**
222
- * Build a (not-yet-started) sandbox: the test-provided factory when set,
223
- * otherwise a per-project clone of the configured machine. The stored id is
224
- * passed both as the logical `id` (providers that reattach by construction
225
- * id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so
226
- * reattach works across the provider matrix.
227
- *
228
- * `env` is deliberately NOT forwarded to the provider clone: remote
229
- * providers bake creation-time env into the VM for its whole lifetime
230
- * (`POST /sandbox`), which would persist credentials like `GH_TOKEN` inside
231
- * a VM that can outlive the session and be reused by another user via the
232
- * sandbox pool. Instead the env lives only on the adapter, which merges it
233
- * into every `executeCommand` — commands see the (refreshable) token, but
234
- * the VM itself never stores it.
235
- */
236
- #build(opts) {
237
- if (this.#factory) return this.#factory(opts);
238
- if (!this.#config) throw new Error("No sandbox configured");
239
- return toMaterializationSandbox(this.#config.machine.clone({
240
- ...opts.providerSandboxId ? {
241
- id: opts.providerSandboxId,
242
- sandboxId: opts.providerSandboxId
243
- } : {},
244
- ...opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {},
245
- ...opts.idleTimeoutMinutes !== void 0 ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {},
246
- ...opts.checkpointName ? { checkpointName: opts.checkpointName } : {},
247
- ...opts.seedCheckpointName ? { seedCheckpointName: opts.seedCheckpointName } : {},
248
- ...opts.actingUserId ? { actingUserId: opts.actingUserId } : {}
249
- }), opts.env);
250
- }
251
- async ensureSandbox(store, envOrProgress, progressOrOptions, maybeOptions = {}) {
252
- const env = typeof envOrProgress === "function" ? void 0 : envOrProgress;
253
- const onProgress = typeof envOrProgress === "function" ? envOrProgress : progressOrOptions;
254
- const options = typeof envOrProgress === "function" ? progressOrOptions ?? {} : maybeOptions;
255
- const key = coalesceKey(store);
256
- if (!key) return this.#ensureSandboxUncoalesced(store, env, onProgress, options);
257
- const existing = this.#inflight.get(key);
258
- if (existing) return existing;
259
- const promise = this.#ensureSandboxUncoalesced(store, env, onProgress, options).finally(() => {
260
- if (this.#inflight.get(key) === promise) this.#inflight.delete(key);
261
- });
262
- this.#inflight.set(key, promise);
263
- return promise;
264
- }
265
- /** The single provision/reattach attempt behind {@link ensureSandbox}. */
266
- async #ensureSandboxUncoalesced(store, env, onProgress, options) {
267
- const idleTimeoutMinutes = this.idleMinutes;
268
- const checkpointName = store.checkpointName;
269
- if (store.sandboxId) {
270
- reportProgress(onProgress, {
271
- phase: "reattaching",
272
- message: "Reconnecting to your sandbox…"
273
- });
274
- const reattached = this.#build({
275
- providerSandboxId: store.sandboxId,
276
- idleTimeoutMinutes,
277
- ...checkpointName ? { checkpointName } : {},
278
- ...env ? { env } : {},
279
- ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {},
280
- ...options.actingUserId ? { actingUserId: options.actingUserId } : {}
281
- });
282
- try {
283
- await timedPhase("sandbox.reattach", () => reattached.start());
284
- reattached.seedCheckpointNameUsed = void 0;
285
- return reattached;
286
- } catch {
287
- await store.setSandboxId(null);
288
- }
289
- }
290
- const max = this.maxSandboxes;
291
- if (max > 0 && this.#liveCount >= max) throw new SandboxBudgetError(max);
292
- reportProgress(onProgress, {
293
- phase: "provisioning",
294
- message: "Provisioning a new sandbox…"
295
- });
296
- const sandbox = this.#build({
297
- idleTimeoutMinutes,
298
- ...checkpointName ? { checkpointName } : {},
299
- ...store.seedCheckpointName ? { seedCheckpointName: store.seedCheckpointName } : {},
300
- ...env ? { env } : {},
301
- ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {},
302
- ...options.actingUserId ? { actingUserId: options.actingUserId } : {}
303
- });
304
- await timedPhase("sandbox.provision", () => sandbox.start());
305
- this.#liveCount += 1;
306
- try {
307
- const provider = await readProviderSandboxDetails(sandbox);
308
- if (provider.sandboxId) await store.setSandboxId(provider.sandboxId);
309
- if (store.seedCheckpointName && provider.restoredCheckpointName === store.seedCheckpointName) sandbox.seedCheckpointNameUsed = store.seedCheckpointName;
310
- return sandbox;
311
- } catch (error) {
312
- if (this.#liveCount > 0) this.#liveCount -= 1;
313
- try {
314
- await sandbox.stop?.();
315
- } catch {}
316
- throw error;
317
- }
318
- }
319
- /**
320
- * Tear down a sandbox binding: stop the live VM (best-effort) and clear the
321
- * persisted state through the binding store so the next open re-provisions
322
- * cleanly. Decrements the per-replica live-sandbox counter.
323
- *
324
- * @param store the binding to tear down
325
- * @param sandbox an already-reattached live sandbox to stop, when available
326
- */
327
- async teardownSandbox(store, sandbox) {
328
- if (sandbox?.stop) try {
329
- await sandbox.stop();
330
- } catch {}
331
- if (store.sandboxId) {
332
- if (this.#liveCount > 0) this.#liveCount -= 1;
333
- await store.clear();
334
- }
335
- }
336
- /**
337
- * Reattach to an already-provisioned sandbox by its provider id and start it.
338
- * Used by the workspace seam when opening a project that was already
339
- * materialized (sandbox id + workdir carried on controller state), so no DB
340
- * round-trip is needed.
341
- */
342
- async reattachSandbox(providerSandboxId, options = {}) {
343
- const sandbox = this.#build({
344
- providerSandboxId,
345
- idleTimeoutMinutes: this.idleMinutes,
346
- ...options.workingDirectory ? { workingDirectory: options.workingDirectory } : {},
347
- ...options.actingUserId ? { actingUserId: options.actingUserId } : {}
348
- });
349
- await sandbox.start();
350
- return sandbox;
351
- }
352
- };
353
- //#endregion
354
- export { SandboxBudgetError, SandboxFleet, reportProgress, resolveContainedLocalWorkdir };
355
-
356
- //# sourceMappingURL=fleet.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fleet.js","names":["#config","#inflight","#liveCount","#factory","#ensureSandboxUncoalesced","#build"],"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\nimport { timedPhase } from '../timing.js';\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 /** Human-readable provider name, forwarded from the underlying sandbox. */\n readonly name?: string;\n /** Provider type discriminator, forwarded from the underlying sandbox. */\n readonly provider?: string;\n /** Sandbox usage instructions surfaced in tool descriptions. */\n getInstructions?(opts?: { requestContext?: unknown }): string;\n /** Long-running process capability, when the provider supports it. */\n readonly processes?: WorkspaceSandbox['processes'];\n /** Mount capability, when the provider supports it. */\n readonly mounts?: WorkspaceSandbox['mounts'];\n start(): Promise<void>;\n getInfo(): Promise<{ metadata?: Record<string, unknown> }>;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; env?: Record<string, string | undefined> },\n ): Promise<SandboxCommandResult>;\n /** Update an environment variable for future commands in this sandbox. */\n setEnvironmentVariable?(name: string, value: string): void;\n /** Tear down the underlying VM. Optional: providers without it are no-ops. */\n stop?(): Promise<void>;\n /** True when the provider persists real checkpoints (snapshot is not a no-op). */\n readonly supportsCheckpoints?: boolean;\n /** Persist the sandbox's current state under its bound checkpoint name. */\n snapshot?(): Promise<void>;\n /** Boot-only fallback checkpoint requested for this fresh provision. */\n seedCheckpointNameUsed?: string;\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 /**\n * Environment variables for commands run in the sandbox. Adapter-level\n * only: merged into every `executeCommand`, never baked into the provider\n * VM (see `SandboxFleet.#build`).\n */\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 * Boot-only fallback checkpoint used when `checkpointName` has no stored\n * state yet (e.g. the repo base checkpoint for a brand-new session).\n * Snapshots keep writing to `checkpointName`.\n */\n seedCheckpointName?: string;\n /** Opaque user subject attributed to provider API requests. */\n actingUserId?: 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 /** Opaque user subject attributed to provider API requests. */\n actingUserId?: 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 /** Boot-only fallback checkpoint (e.g. repo base checkpoint) for first provision. */\n readonly seedCheckpointName?: 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 * Stable identity for one binding's in-flight provision work, used to coalesce\n * concurrent `ensureSandbox` calls. Prefer `checkpointName` — it is a pure\n * function of the owning session and is set before the first provision, which\n * is exactly when the herd forms (the stored `sandboxId` is still null then).\n * Fall back to the stored provider id, and skip coalescing entirely for\n * bindings with neither: keying those on a shared constant would wrongly\n * funnel *different* bindings onto one sandbox.\n */\nfunction coalesceKey(store: SandboxBindingStore): string | undefined {\n if (store.checkpointName) return `checkpoint:${store.checkpointName}`;\n if (store.sandboxId) return `sandbox:${store.sandboxId}`;\n return undefined;\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(\n sandbox: WorkspaceSandbox,\n initialEnvironment: Record<string, string> = {},\n): 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 const environment = { ...initialEnvironment };\n return {\n id: sandbox.id,\n name: sandbox.name,\n provider: sandbox.provider,\n getInstructions: opts =>\n sandbox.getInstructions?.(opts as Parameters<NonNullable<WorkspaceSandbox['getInstructions']>>[0]) ?? '',\n processes: sandbox.processes,\n mounts: sandbox.mounts,\n start: async () => {\n await (lifecycle._start ?? sandbox.start)?.call(sandbox);\n },\n getInfo: async () => (await sandbox.getInfo?.()) ?? {},\n executeCommand: (command, args, options) =>\n sandbox.executeCommand!(command, args, {\n ...options,\n env: { ...environment, ...options?.env },\n }),\n setEnvironmentVariable: (name, value) => {\n environment[name] = value;\n },\n stop: async () => {\n await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);\n },\n supportsCheckpoints: sandbox.supportsCheckpoints === true,\n ...(sandbox.snapshot ? { snapshot: sandbox.snapshot.bind(sandbox) } : {}),\n };\n}\n\n/**\n * Provider details reported after startup. Railway exposes its native sandbox\n * id and the checkpoint it actually restored through `getInfo().metadata`.\n */\nasync function readProviderSandboxDetails(\n sandbox: MaterializationSandbox,\n): Promise<{ sandboxId: string | undefined; restoredCheckpointName: string | undefined }> {\n const info = await sandbox.getInfo();\n const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;\n const restoredCheckpointName = info.metadata?.restoredCheckpointName;\n return {\n sandboxId: typeof id === 'string' ? id : sandbox.id,\n restoredCheckpointName: typeof restoredCheckpointName === 'string' ? restoredCheckpointName : undefined,\n };\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 /** In-flight `ensureSandbox` work, keyed per binding so concurrent callers coalesce. */\n readonly #inflight = new Map<string, Promise<MaterializationSandbox>>();\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 * Usage instructions from the configured template machine, for surfacing in\n * tool descriptions before any per-session sandbox has materialized.\n * Empty string when no machine is configured or it exposes none.\n */\n getInstructions(): string {\n return this.#config?.machine.getInstructions?.() ?? '';\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 * `env` is deliberately NOT forwarded to the provider clone: remote\n * providers bake creation-time env into the VM for its whole lifetime\n * (`POST /sandbox`), which would persist credentials like `GH_TOKEN` inside\n * a VM that can outlive the session and be reused by another user via the\n * sandbox pool. Instead the env lives only on the adapter, which merges it\n * into every `executeCommand` — commands see the (refreshable) token, but\n * the VM itself never stores it.\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.workingDirectory ? { workingDirectory: opts.workingDirectory } : {}),\n ...(opts.idleTimeoutMinutes !== undefined ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {}),\n ...(opts.checkpointName ? { checkpointName: opts.checkpointName } : {}),\n ...(opts.seedCheckpointName ? { seedCheckpointName: opts.seedCheckpointName } : {}),\n ...(opts.actingUserId ? { actingUserId: opts.actingUserId } : {}),\n });\n return toMaterializationSandbox(clone, opts.env);\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 * Concurrent calls for the same binding coalesce onto one in-flight\n * provision/reattach and share its sandbox handle — N simultaneous requests\n * for one cold session (e.g. several browser tabs polling right after boot)\n * must not each fire their own `POST /sandbox` against the provider.\n * Failures are not cached: once the shared attempt settles, the next call\n * starts fresh.\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\n const key = coalesceKey(store);\n if (!key) return this.#ensureSandboxUncoalesced(store, env, onProgress, options);\n\n const existing = this.#inflight.get(key);\n if (existing) return existing;\n\n const promise = this.#ensureSandboxUncoalesced(store, env, onProgress, options).finally(() => {\n // Only clear when this is still the entry we own.\n if (this.#inflight.get(key) === promise) this.#inflight.delete(key);\n });\n this.#inflight.set(key, promise);\n return promise;\n }\n\n /** The single provision/reattach attempt behind {@link ensureSandbox}. */\n async #ensureSandboxUncoalesced(\n store: SandboxBindingStore,\n env: Record<string, string> | undefined,\n onProgress: ProgressFn | undefined,\n options: EnsureSandboxOptions,\n ): Promise<MaterializationSandbox> {\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 ...(options.actingUserId ? { actingUserId: options.actingUserId } : {}),\n });\n try {\n await timedPhase('sandbox.reattach', () => reattached.start());\n reattached.seedCheckpointNameUsed = undefined;\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 // Boot-only fallback seed (repo base checkpoint) — only meaningful on a\n // fresh provision; snapshots keep writing to `checkpointName`.\n ...(store.seedCheckpointName ? { seedCheckpointName: store.seedCheckpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n ...(options.actingUserId ? { actingUserId: options.actingUserId } : {}),\n });\n await timedPhase('sandbox.provision', () => sandbox.start());\n this.#liveCount += 1;\n\n try {\n const provider = await readProviderSandboxDetails(sandbox);\n if (provider.sandboxId) {\n await store.setSandboxId(provider.sandboxId);\n }\n\n if (store.seedCheckpointName && provider.restoredCheckpointName === store.seedCheckpointName) {\n sandbox.seedCheckpointNameUsed = store.seedCheckpointName;\n }\n return sandbox;\n } catch (error) {\n if (this.#liveCount > 0) this.#liveCount -= 1;\n try {\n await sandbox.stop?.();\n } catch {\n // Preserve the provider-detail or persistence error that made the sandbox unusable.\n }\n throw error;\n }\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 ...(options.actingUserId ? { actingUserId: options.actingUserId } : {}),\n });\n await sandbox.start();\n return sandbox;\n }\n}\n"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,OAA4B,SAAiD;EACjG,IAAI,SAAS,MACX,IAAI;GACF,MAAM,QAAQ,KAAK;EACrB,QAAQ,CAER;EAEF,IAAI,MAAM,WAAW;GACnB,IAAI,KAAKA,aAAa,GAAG,KAAKA,cAAc;GAC5C,MAAM,MAAM,MAAM;EACpB;CACF;;;;;;;CAQA,MAAM,gBACJ,mBACA,UAAgC,CAAC,GACA;EACjC,MAAM,UAAU,KAAKG,OAAO;GAC1B;GACA,oBAAoB,KAAK;GACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;GACjF,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACvE,CAAC;EACD,MAAM,QAAQ,MAAM;EACpB,OAAO;CACT;AACF"}
@@ -1,3 +0,0 @@
1
- import type { SandboxFleet } from './fleet.js';
2
- export declare function registerSandboxReattach(fleet: SandboxFleet): void;
3
- //# sourceMappingURL=reattach.d.ts.map
@@ -1 +0,0 @@
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"}
@@ -1,16 +0,0 @@
1
- import { registerSandboxReattach as registerSandboxReattach$1 } from "@mastra/code-sdk/agents/sandbox-reattach";
2
- //#region src/sandbox/reattach.ts
3
- /**
4
- * Wires the core workspace sandbox seam to the factory's sandbox fleet.
5
- * Core's `getDynamicWorkspace` reattaches project sandboxes through
6
- * `@mastra/code-sdk/agents/sandbox-reattach`, but only the factory owns the
7
- * fleet — so `MastraFactory.prepare()` registers the implementation here once
8
- * the fleet is constructed.
9
- */
10
- function registerSandboxReattach(fleet) {
11
- registerSandboxReattach$1((providerSandboxId, options) => fleet.reattachSandbox(providerSandboxId, options));
12
- }
13
- //#endregion
14
- export { registerSandboxReattach };
15
-
16
- //# sourceMappingURL=reattach.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"reattach.js","names":[],"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, options) => fleet.reattachSandbox(providerSandboxId, options));\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,wBAAwB,OAA2B;CACjE,2BAAgB,mBAAmB,YAAY,MAAM,gBAAgB,mBAAmB,OAAO,CAAC;AAClG"}