@mastra/platform-workspace 0.0.0-aggregate-trace-20261015182851

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.
@@ -0,0 +1,597 @@
1
+ import type { RequestContext } from '@mastra/core/di';
2
+ import type { CommandResult, ExecuteCommandOptions, InstructionsOption, MastraSandboxOptions, ProcessInfo, ProviderStatus, SandboxCloneOptions, SandboxInfo, SandboxStartResult, SpawnProcessOptions } from '@mastra/core/workspace';
3
+ import { MastraSandbox, ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';
4
+ import type { PlatformClientOptions } from './client.js';
5
+ import type { DirectExecWebSocketFactory } from './direct-exec.js';
6
+ import type { E2BExecRunner } from './e2b-exec.js';
7
+ import type { PrivateNetFetch } from './private-net-exec.js';
8
+ import type { SandboxTemplateBuilder } from './template.js';
9
+ export type PlatformSandboxNetworkIsolation = 'ISOLATED' | 'PRIVATE';
10
+ export type PlatformSandboxTemplate = SandboxTemplateBuilder | (() => SandboxTemplateBuilder | undefined | Promise<SandboxTemplateBuilder | undefined>);
11
+ /**
12
+ * In-process `sandboxId → instanceUrl` map that lets
13
+ * {@link PlatformSandbox.executeCommand} dial the in-sandbox sidecar over
14
+ * Railway's private network instead of paying for a lease + WebSocket
15
+ * round-trip through Railway's public control plane.
16
+ *
17
+ * The workspace proxy discovers each sandbox's IPv6 during
18
+ * `POST /v1/:provider/projects/:pid/sandbox` and returns it as `instanceUrl` on the
19
+ * create + get responses (see the platform inline-discovery issue). The
20
+ * `PlatformSandbox` client copies that field into this registry from both
21
+ * {@link PlatformSandbox.start} branches (fresh provision + reattach), evicts
22
+ * on {@link PlatformSandbox.destroy}, and evicts again on any observed
23
+ * transport failure so the next exec falls back to the lease path cleanly.
24
+ *
25
+ * See:
26
+ * - `.scratch/factory-deploy/issue-runtime-sandbox-address-discovery.md`
27
+ * - `.scratch/factory-deploy/issue-platform-sandbox-exec-via-private-network.md`
28
+ */
29
+ export interface SandboxAddressRegistry {
30
+ set(sandboxId: string, instanceUrl: string): void;
31
+ get(sandboxId: string): string | undefined;
32
+ delete(sandboxId: string): void;
33
+ }
34
+ export interface PlatformSandboxOptions extends Omit<MastraSandboxOptions, 'processes'>, PlatformClientOptions {
35
+ id?: string;
36
+ environmentId?: string;
37
+ sandboxId?: string;
38
+ /**
39
+ * What `start()` does when `sandboxId` is set but the platform reports that
40
+ * sandbox is gone (404, 410, or a destroyed record).
41
+ *
42
+ * - `'best-effort'` (default): provision a replacement sandbox.
43
+ * - `'required'`: throw a `SandboxError` with code `SANDBOX_REATTACH_FAILED`
44
+ * instead of provisioning, so the caller can surface the lost VM.
45
+ */
46
+ reattach?: 'best-effort' | 'required';
47
+ /** Boot-only fallback checkpoint for a fresh sandbox whose primary recovery key has no state. */
48
+ seedCheckpointName?: string;
49
+ /**
50
+ * Template builder or a lazy resolver for one. The resolver runs only when
51
+ * start() must provision a fresh sandbox. Platform content-addresses the
52
+ * serialized definition and starts or reuses its provider build without
53
+ * blocking sandbox creation. With E2B, cpuCount() and memoryMB() default to 2
54
+ * CPUs and 1,024 MB; the latest setters determine the template identity and
55
+ * stale fallback is restricted to builds with the same effective resources.
56
+ * A provider-base fallback may use provider-default resources while the exact
57
+ * build is pending; inspect templatePending to detect that case. Railway
58
+ * ignores the resource setters. `setEnvs(values, { ephemeral: true })`
59
+ * supplies build-only values outside the serialized definition, content
60
+ * identity, and persistent template record. Resolver failures also fall back
61
+ * to the provider default and are retried on the next fresh provision.
62
+ */
63
+ template?: PlatformSandboxTemplate;
64
+ idleTimeoutMinutes?: number;
65
+ networkIsolation?: PlatformSandboxNetworkIsolation;
66
+ env?: Record<string, string>;
67
+ timeout?: number;
68
+ instructions?: InstructionsOption;
69
+ /**
70
+ * Injected WebSocket factory used by the direct-exec code path. Defaults to
71
+ * the global `WebSocket` (available on Node 22+, this package's minimum) and
72
+ * only exists so tests can drive the exec state machine deterministically
73
+ * without a real network socket.
74
+ */
75
+ webSocketFactory?: DirectExecWebSocketFactory;
76
+ /** Injected E2B direct-exec implementation used by tests. */
77
+ e2bExecRunner?: E2BExecRunner;
78
+ /**
79
+ * Injected fetch implementation used by the private-network exec code path
80
+ * to dial the in-sandbox sidecar. Defaults to `globalThis.fetch` and only
81
+ * exists so tests can drive that transport without a real HTTP server.
82
+ * Note: this is separate from the `fetch` on {@link PlatformClientOptions},
83
+ * which is used for calls to the workspace proxy.
84
+ */
85
+ privateNetFetch?: PrivateNetFetch;
86
+ /**
87
+ * Registry that maps `sandboxId → instanceUrl` for the private-network
88
+ * exec path. When set, {@link PlatformSandbox.start} populates it from the
89
+ * `instanceUrl` field workspace-proxy returns on create + get responses,
90
+ * and {@link PlatformSandbox.executeCommand} looks it up before every exec
91
+ * and tries the private-network transport first, falling back to the lease
92
+ * path on any transport failure (and invalidating the registry entry so
93
+ * the next call goes to the lease path cleanly). When absent, all execs
94
+ * go straight to the lease path — this is the pre-existing behavior and
95
+ * the expected mode outside the shipyard runtime. See
96
+ * {@link SandboxAddressRegistry}.
97
+ */
98
+ addressRegistry?: SandboxAddressRegistry;
99
+ }
100
+ /**
101
+ * Observability handle for a template that was requested but is still being
102
+ * built by the platform. Present on {@link CreateSandboxResponse} and echoed
103
+ * as {@link PlatformSandbox.templatePending} when the sandbox booted from
104
+ * a prior member of the same template family or from the provider's base
105
+ * template while the exact template continues to build in the background.
106
+ * Absent when the sandbox booted on the exact template.
107
+ *
108
+ * `PlatformSandbox` does not act on this: freshness is reconciled by the
109
+ * caller's own `onStart` runtime setup (e.g. `git fetch && checkout`), not
110
+ * by replaying template operations inside the running sandbox.
111
+ */
112
+ export interface SandboxTemplatePending {
113
+ templateId: string;
114
+ retryAfterMs: number;
115
+ }
116
+ /**
117
+ * Diagnostic error thrown when the direct-exec WebSocket transport fails
118
+ * twice in a row (opening handshake refused or socket closed mid-stream
119
+ * without an `exit` frame). Distinguishes "the sandbox transport is broken"
120
+ * from "your command failed" so callers can decide whether to retry at a
121
+ * higher level (e.g. reprovision the sandbox) or surface the error.
122
+ *
123
+ * `opened` is `true` when the WebSocket completed its handshake at least
124
+ * once before closing; `false` when Railway refused the upgrade outright.
125
+ */
126
+ export declare class SandboxExecTransportError extends Error {
127
+ readonly sandboxId: string | undefined;
128
+ readonly command: string;
129
+ readonly attempts: number;
130
+ readonly opened: boolean;
131
+ readonly closeCode: number | undefined;
132
+ readonly closeReason: string | undefined;
133
+ readonly wsEndpoint: string;
134
+ constructor(message: string, diagnostics: {
135
+ sandboxId?: string;
136
+ command: string;
137
+ attempts: number;
138
+ opened: boolean;
139
+ closeCode?: number;
140
+ closeReason?: string;
141
+ wsEndpoint: string;
142
+ });
143
+ }
144
+ /**
145
+ * Outcome of {@link PlatformSandbox.captureCheckpoint}. Mirrors the shape of
146
+ * the OSS `@mastra/railway` `RailwaySandbox.captureCheckpoint()` return so a
147
+ * caller (e.g. the factory fleet) can branch on `status`/`reason` uniformly
148
+ * across providers without knowing which one is underneath.
149
+ *
150
+ * `captured` and `coalesced` both represent a successful capture the caller
151
+ * can persist against — they carry the checkpoint name inline so callers
152
+ * don't have to reach back into the sandbox instance to learn what was
153
+ * written. `skipped` carries a machine-readable `reason` so the discriminant
154
+ * set stays extensible.
155
+ *
156
+ * Note: the platform proxy's own `skipped` (returned when the upstream
157
+ * sandbox is already destroyed) is mapped to `sandbox-not-running` here to
158
+ * keep the discriminant identical to the OSS provider. The diagnostic
159
+ * distinction (pre-flight vs post-hoc discovery) is preserved in log lines,
160
+ * not the return type — see {@link PlatformSandbox.captureCheckpoint}.
161
+ */
162
+ export type CaptureCheckpointResult = {
163
+ status: 'captured';
164
+ checkpointName: string;
165
+ } | {
166
+ status: 'coalesced';
167
+ checkpointName: string;
168
+ } | {
169
+ status: 'skipped';
170
+ reason: 'no-checkpoint-name-configured' | 'sandbox-not-running';
171
+ };
172
+ /**
173
+ * Thrown when `/exec-lease` returns 410 Gone — the sandbox has been destroyed
174
+ * (Railway destroy, quota reclamation, etc.). The client cannot recover from
175
+ * this on its own because it does not own the binding store; only the fleet
176
+ * layer can clear the stale sandbox id and provision a fresh one. Callers
177
+ * (typically `SandboxFleet`) must catch this and reprovision-and-replay.
178
+ *
179
+ * When this is thrown the cached `_lease` and `_sandboxId` on the sandbox
180
+ * instance are cleared, so the next `ensureRunning()` on a reused instance
181
+ * will re-provision cleanly.
182
+ */
183
+ export declare class SandboxDestroyedError extends Error {
184
+ readonly sandboxId: string | undefined;
185
+ readonly command: string;
186
+ readonly attempts: number;
187
+ constructor(message: string, diagnostics: {
188
+ sandboxId?: string;
189
+ command: string;
190
+ attempts: number;
191
+ });
192
+ }
193
+ declare class PlatformProcessManager extends SandboxProcessManager<PlatformSandbox> {
194
+ private spawnCounter;
195
+ /**
196
+ * Spawn a process on the remote sandbox.
197
+ *
198
+ * `command` is interpreted as a shell string by the remote shell, matching
199
+ * the {@link MastraSandbox} contract. See {@link PlatformSandbox.executeCommand}
200
+ * for the untrusted-input caveat: never pass untrusted values as `command`.
201
+ */
202
+ spawn(command: string, options?: SpawnProcessOptions): Promise<ProcessHandle>;
203
+ list(): Promise<ProcessInfo[]>;
204
+ }
205
+ export declare class PlatformSandbox extends MastraSandbox {
206
+ readonly id: string;
207
+ readonly name = "PlatformSandbox";
208
+ readonly provider = "platform";
209
+ status: ProviderStatus;
210
+ readonly processes: PlatformProcessManager;
211
+ /**
212
+ * Populated from the platform's create/reattach response when the sandbox
213
+ * booted from a prior member of the same template family or the provider
214
+ * base template while the requested exact template continues to build in
215
+ * the background.
216
+ * `undefined` when the sandbox booted on the exact template (or when no
217
+ * template was requested). Observability-only; consumers reconcile freshness
218
+ * in their own runtime setup and reprovision to pick up the ready template
219
+ * on a later start.
220
+ */
221
+ templatePending?: SandboxTemplatePending;
222
+ /**
223
+ * The platform's id for the provisioned sandbox, as returned by the create
224
+ * or reattach response. Persist this to reattach later via the `sandboxId`
225
+ * option. Undefined until the sandbox has been started in this process; a
226
+ * `sandboxId` passed to the constructor is only a hint for `start()` and is
227
+ * not reported here until the proxy confirms it.
228
+ */
229
+ get sandboxId(): string | undefined;
230
+ private readonly _client;
231
+ private readonly _usesProviderRoutes;
232
+ private readonly _environmentId;
233
+ private _sandboxId?;
234
+ private readonly _reattach;
235
+ private readonly _seedCheckpointName?;
236
+ private _templateDefinition?;
237
+ private _templateBuildEnvs?;
238
+ private readonly _template?;
239
+ private _templateResolutionInFlight?;
240
+ private readonly _idleTimeoutMinutes?;
241
+ private readonly _networkIsolation?;
242
+ private readonly _env;
243
+ private readonly _timeout?;
244
+ private readonly _instructionsOverride?;
245
+ private _createdAt;
246
+ private readonly _webSocketFactory?;
247
+ private readonly _e2bExecRunner;
248
+ private readonly _privateNetFetch?;
249
+ /**
250
+ * Registry that maps `sandboxId → instanceUrl` for the private-network
251
+ * exec path. Injected by the composition site via
252
+ * {@link PlatformSandboxOptions.addressRegistry} and populated by this
253
+ * class itself in `start()` when the workspace-proxy's create/reattach
254
+ * response includes an `instanceUrl` field. The registry IS the cache —
255
+ * there is no per-instance mirror on `PlatformSandbox`, so every exec is
256
+ * a `Map.get()` (in the default in-process impl) against the live view.
257
+ * When absent, executes go straight to the lease path with no extra
258
+ * round-trip.
259
+ */
260
+ private readonly _addressRegistry?;
261
+ /**
262
+ * Cached exec lease for this sandbox. `null` before the first exec and
263
+ * after {@link destroy}. Refreshed when `expiresAt - LEASE_REFRESH_MARGIN_MS < now`
264
+ * (see {@link _ensureLease}); a lease without a disclosed `expiresAt`
265
+ * is refreshed on every call.
266
+ */
267
+ private _lease;
268
+ /**
269
+ * In-flight mint request; concurrent `_ensureLease` callers on a cold or
270
+ * near-expiry cache all await this single promise so we don't burn N
271
+ * `POST /exec-lease` round-trips when the sandbox is doing N parallel execs.
272
+ * Cleared (regardless of success or failure) when the request settles.
273
+ */
274
+ private _leaseInFlight;
275
+ /**
276
+ * True when this sandbox was constructed with a caller-supplied `id` (the
277
+ * recovery key the proxy hashes into an on-provider checkpoint name).
278
+ * `captureCheckpoint()` needs this to distinguish "no checkpoint intent"
279
+ * (auto-generated random id — capture would land under a name no future
280
+ * boot would look for) from "capture on demand". Cloned sandboxes route
281
+ * `checkpointName` through `id`, so both entry points set this the same
282
+ * way.
283
+ */
284
+ private readonly _hasRecoveryKey;
285
+ /**
286
+ * In-flight `captureCheckpoint()` request. Concurrent callers on the same
287
+ * instance coalesce onto this single promise so we don't burn N `POST
288
+ * /checkpoint` round-trips when the fleet fires several turn-end captures
289
+ * before the first one resolves. Cleared when the request settles.
290
+ */
291
+ private _captureInFlight;
292
+ /**
293
+ * Generation token for the sidecar probe. Incremented on every `start()`
294
+ * and on teardown. The probe captures this value when it begins; if the
295
+ * generation has changed by the time the probe succeeds, the probe skips
296
+ * the `set()` to avoid re-populating a deleted or superseded sandbox entry.
297
+ */
298
+ private _probeGeneration;
299
+ /**
300
+ * In-flight sidecar probe promise. Concurrent `executeCommand` callers that
301
+ * arrive before the registry is populated all await this single promise so
302
+ * we don't fire N independent lease requests during the sidecar boot window.
303
+ * Once the probe resolves (success or timeout), callers check the registry
304
+ * and proceed — either via private-net (probe succeeded) or via lease (probe
305
+ * failed/timed out, but now coalesced via `_leaseInFlight`).
306
+ */
307
+ private _transportReadyPromise;
308
+ /**
309
+ * The sidecar address of the most recent `start()`, kept so a timed-out
310
+ * probe can be restarted by a later exec ({@link _awaitTransportReady})
311
+ * instead of pinning the sandbox to the lease path for its lifetime.
312
+ */
313
+ private _probeTarget;
314
+ constructor(options?: PlatformSandboxOptions);
315
+ private generateId;
316
+ private _failIfReattachRequired;
317
+ private _request;
318
+ /**
319
+ * Construct a sibling {@link PlatformSandbox} that inherits this sandbox's
320
+ * credentials and defaults (access token, project, environment, network
321
+ * isolation, timeout, instructions, env, idle timeout) with per-instance
322
+ * overrides from `options`.
323
+ *
324
+ * Performs no I/O and does not require this sandbox to be started — the
325
+ * returned sandbox is not started and provisions (or reattaches, when
326
+ * `sandboxId` is set) on its own `start()`. Use it when one configured
327
+ * sandbox acts as the template for a fleet of independent sandboxes
328
+ * (e.g. one per project).
329
+ */
330
+ clone(options?: SandboxCloneOptions): PlatformSandbox;
331
+ /**
332
+ * Start the sandbox: reattach to a known provider `sandboxId` when one is
333
+ * set and still live, otherwise provision a fresh sandbox via the proxy.
334
+ *
335
+ * Concurrent-caller coalescing lives in the `MastraSandbox` base class
336
+ * (constructor-wrapped `start()`): joined callers share one attempt and
337
+ * observe its result; the in-flight slot is cleared on settle so a failed
338
+ * attempt is not a permanent latch.
339
+ *
340
+ * Reports `outcome: 'connected'` on reattach and `outcome: 'created'` on provision.
341
+ * Note: a `POST /sandbox` seeded from an id-keyed checkpoint is still a
342
+ * fresh VM and reports `outcome: 'created'`.
343
+ */
344
+ start(): Promise<SandboxStartResult>;
345
+ private _prepareLazyTemplate;
346
+ private _resolveTemplate;
347
+ /**
348
+ * One timing summary per completed `start()` — the whole
349
+ * `PlatformSandbox`-visible boot in a single greppable line.
350
+ *
351
+ * `requestMs` is the proxy round-trip (`GET /sandbox/:id` on reattach,
352
+ * `POST /sandbox` including transient-5xx retries on provision) — a black
353
+ * box from this side that rolls up Railway RPC, sidecar launch, and the
354
+ * proxy's discovery exec. Sidecar probe cost is intentionally NOT here: the
355
+ * probe is fire-and-forget and outlives `start()` by design, so its
356
+ * duration lands on the `platform-workspace probe ok` line instead.
357
+ */
358
+ private _logStartComplete;
359
+ /**
360
+ * Copy `response.instanceUrl` into the injected {@link SandboxAddressRegistry}
361
+ * when both are present. Called from both {@link start} branches (fresh
362
+ * provision + reattach) with the workspace-proxy response for this sandbox.
363
+ *
364
+ * The proxy discovers the IPv6 during `Sandbox.create()` and stores it in
365
+ * `environment_sandboxes.instance_url`; both the create response and
366
+ * `GET /sandbox/:id` echo the same field. The runtime does not do any
367
+ * discovery of its own — it only mirrors the field into an in-process map
368
+ * so {@link executeCommand} can `Map.get()` before every exec without an
369
+ * HTTP round-trip.
370
+ *
371
+ * `null`/absent `instanceUrl` (proxy discovery failed, or an older proxy
372
+ * that predates the field) evicts any stale registry address and leaves
373
+ * executes on the lease path.
374
+ */
375
+ private _populateAddressFromResponse;
376
+ /**
377
+ * Fire-and-forget probe that polls the sidecar's `/health` endpoint until
378
+ * it responds, then populates the address registry. Runs detached from
379
+ * `start()` so sandbox provision latency is unchanged; early execs simply
380
+ * fall back to the lease path until the probe succeeds.
381
+ *
382
+ * If the sidecar never comes up within {@link SIDECAR_PROBE_TIMEOUT_MS},
383
+ * the registry stays unpopulated, `_transportReadyPromise` is cleared,
384
+ * and a later {@link _awaitTransportReady} call restarts the probe
385
+ * instead of pinning this sandbox to the lease path.
386
+ *
387
+ * @param generation - The probe generation captured at call time. If this
388
+ * no longer matches `_probeGeneration` when the probe succeeds, the probe
389
+ * was superseded by a teardown or a new `start()`, so we skip the `set()`.
390
+ */
391
+ private _probeSidecarThenRegister;
392
+ /**
393
+ * Wait for the transport to become ready (sidecar probe succeeds) or time
394
+ * out. Concurrent callers all await the same probe promise, coalescing the
395
+ * cold-start storm into a single warmup attempt.
396
+ *
397
+ * If no probe is in flight (no registry, or registry already populated),
398
+ * this returns immediately. After the wait (success or timeout), callers
399
+ * check the registry and proceed — either via private-net or lease. The
400
+ * lease path is still coalesced via `_leaseInFlight`, so even if the probe
401
+ * times out, we only mint one lease for all concurrent execs.
402
+ */
403
+ private _awaitTransportReady;
404
+ /**
405
+ * Stop this process's use of the sandbox without touching the remote one.
406
+ *
407
+ * Nothing is sent to workspace-proxy. The VM keeps running and idles out
408
+ * under the environment's own idle policy, the recovery checkpoint stays,
409
+ * and `_sandboxId` is kept so a later `start()` on this instance, or on a
410
+ * new instance constructed with the same `id` or `sandboxId`, reattaches
411
+ * instead of provisioning. `Mastra.shutdown()` stops every registered
412
+ * workspace on SIGINT; releasing the VM here would destroy every live
413
+ * session on a host restart. Use {@link destroy} to release the VM and
414
+ * its checkpoint.
415
+ *
416
+ * Any in-flight capture is awaited first so the checkpoint reflects the
417
+ * latest disk state the caller asked for.
418
+ */
419
+ stop(): Promise<void>;
420
+ /**
421
+ * Destroy the sandbox **and release its recovery checkpoint**.
422
+ *
423
+ * Semantic parity with `@mastra/railway` `RailwaySandbox.destroy()`:
424
+ * cancels any in-flight capture (the checkpoint is about to be deleted
425
+ * — no reason to burn a capture on state we're releasing), asks the
426
+ * proxy to delete the checkpoint, then releases the VM. Both remote
427
+ * operations are best-effort logged failures — a stray checkpoint or a
428
+ * transient proxy error must not leave the caller with a half-torn-down
429
+ * sandbox they can't safely retry.
430
+ *
431
+ * Railway requires a caller-supplied recovery `id` before it can have a
432
+ * checkpoint to delete. On E2B the sandbox itself is the persistent thing
433
+ * (idle sandboxes pause and resume in place), so destroy only kills the
434
+ * VM; any snapshot a caller captured on purpose is the caller's to manage.
435
+ */
436
+ destroy(): Promise<void>;
437
+ /**
438
+ * Release the remote sandbox VM and clear the local state pointing at it.
439
+ *
440
+ * Body of {@link destroy}, called after the checkpoint has been released.
441
+ * The proxy's DELETE route releases the VM (on E2B that kills it), so
442
+ * only destroy() may reach here; stop() never does.
443
+ */
444
+ private _teardownSandbox;
445
+ /** Persist the configured recovery checkpoint when available. */
446
+ snapshot(): Promise<void>;
447
+ /** Snapshots persist real checkpoints that can seed future sandboxes. */
448
+ readonly supportsCheckpoints: boolean;
449
+ /**
450
+ * Capture the sandbox's checkpoint on demand, outside any refresh timer the
451
+ * workspace-proxy owns internally.
452
+ *
453
+ * Intended for callers (e.g. a factory-side scheduler) that want to refresh
454
+ * the recovery checkpoint at semantic moments — turn end, session-idle,
455
+ * pre-teardown — rather than only just before the upstream's idle destroy.
456
+ *
457
+ * Mirrors the OSS `@mastra/railway` `RailwaySandbox.captureCheckpoint()`
458
+ * shape so factory can call `sandbox.captureCheckpoint()` uniformly and
459
+ * branch on `status`/`reason` without knowing which provider is underneath.
460
+ * Both `captured` and `coalesced` carry the checkpoint name inline so the
461
+ * caller can persist a session→checkpoint binding atomically with the
462
+ * awaited capture.
463
+ *
464
+ * Skip semantics:
465
+ * - No caller-supplied `id`: returns `{ status: 'skipped', reason:
466
+ * 'no-checkpoint-name-configured' }`. An auto-generated random id is
467
+ * never a meaningful recovery key (no future boot would look for a
468
+ * checkpoint under it), so capturing would silently produce dead data.
469
+ * - Not started (no `_sandboxId`): returns `{ status: 'skipped', reason:
470
+ * 'sandbox-not-running' }` without a round-trip.
471
+ * - Upstream 410 (workspace-proxy or Railway reports the sandbox is
472
+ * already destroyed): returns the same `sandbox-not-running` skip so
473
+ * the discriminant matches the pre-flight case. Local state
474
+ * (`_sandboxId`, `_lease`, sidecar address) is cleared as a side
475
+ * effect so the next `start()` provisions fresh instead of reattaching
476
+ * to a dead id. The diagnostic distinction (pre-flight vs post-hoc)
477
+ * is preserved in log level: debug for the expected pre-flight skip,
478
+ * warn for the surprise upstream destroy.
479
+ *
480
+ * Concurrent callers on the same instance coalesce onto a single in-flight
481
+ * `POST /checkpoint` so N simultaneous turn-end fires (e.g. several tabs)
482
+ * do not each round-trip the proxy. Both the originator and joiners
483
+ * receive `{ status: 'coalesced', ... }` for the joined result — the
484
+ * outer contract does not distinguish who started the request, only that
485
+ * one upstream capture was made.
486
+ *
487
+ * Never throws for expected outcomes. Transport failures (5xx, 4xx other
488
+ * than 410) propagate as {@link PlatformApiError}; a 410 is normalized
489
+ * to a skip as described above.
490
+ */
491
+ captureCheckpoint(): Promise<CaptureCheckpointResult>;
492
+ /**
493
+ * The single `POST /checkpoint` attempt behind {@link captureCheckpoint}.
494
+ *
495
+ * Split out so the coalescing wrapper can install a shared in-flight
496
+ * promise without inlining the transport + response-mapping logic.
497
+ * Joined callers observe `{ status: 'coalesced', ... }` — the initiator
498
+ * sees the underlying `captured` / `coalesced` / `skipped` result the
499
+ * proxy returned. Both are legitimate: the OSS mirror uses the same
500
+ * "initiator sees the truth, joiners see coalesced" split.
501
+ */
502
+ private _doCaptureCheckpoint;
503
+ /**
504
+ * Clear local state that would otherwise let the caller keep exec'ing
505
+ * against a sandbox the upstream has already destroyed. Mirrors what
506
+ * `destroy()` does minus the outbound DELETE — the sandbox is already
507
+ * gone, so all that remains is to stop pointing at it.
508
+ *
509
+ * Also resets `status` to `'pending'` so a subsequent `_start()` on this
510
+ * reused instance re-runs provisioning instead of short-circuiting on
511
+ * the cached `'running'` state (see `MastraSandbox._start`).
512
+ */
513
+ private _clearDestroyedState;
514
+ /**
515
+ * Execute a command on the remote sandbox.
516
+ *
517
+ * `command` is a **shell string**: it is concatenated verbatim into the
518
+ * command line sent to the remote shell, which lets callers use pipes,
519
+ * redirects, and chaining (`ls -la | grep foo`). This matches the contract
520
+ * of {@link MastraSandbox} and the local sandbox implementation.
521
+ *
522
+ * `args`, when provided, are always shell-quoted so they cannot inject
523
+ * additional shell syntax.
524
+ *
525
+ * Security: callers MUST NOT pass untrusted input as `command`. If any part
526
+ * of the invocation is derived from an untrusted source, pass it through
527
+ * `args` (which is safely quoted) or shell-quote it yourself before
528
+ * inclusion. Untrusted `command` values allow arbitrary shell syntax
529
+ * execution on the remote sandbox.
530
+ */
531
+ executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult>;
532
+ /**
533
+ * Run a single exec against the direct-exec transport, with one in-flight
534
+ * retry on WebSocket transport failure (socket closed without an `exit`
535
+ * frame and the exec did not time out). The retry mints a fresh lease
536
+ * — the failure could be a stale JWT — and reopens a new WebSocket.
537
+ *
538
+ * Error taxonomy:
539
+ * - **410 on `/exec-lease`** (either attempt) → the sandbox is gone.
540
+ * Nulls the cached `_lease` and `_sandboxId` and throws
541
+ * {@link SandboxDestroyedError}. Callers (typically `SandboxFleet`) must
542
+ * catch this, clear the stale binding, and reprovision + replay.
543
+ * - **Persistent transport failure** (both WS attempts close without an
544
+ * `exit` frame against a live sandbox) → {@link SandboxExecTransportError}
545
+ * with WebSocket close diagnostics.
546
+ * - **Other `PlatformApiError`s** (404/500/501) propagate directly.
547
+ * - **Real command result** (exit code from Railway's exit frame, or
548
+ * `timedOut: true`) returns normally.
549
+ *
550
+ * Returns a result with a real `exitCode` OR `timedOut: true`. Never
551
+ * returns `{ exitCode: null, timedOut: false }` — that case throws.
552
+ */
553
+ /**
554
+ * Drop undefined values so the result matches the Record<string, string>
555
+ * shape the exec transports expect (`ExecuteCommandOptions.env` is
556
+ * NodeJS.ProcessEnv). The sandbox's own env is already merged in by
557
+ * `executeCommand` before a transport sees these options. Returns undefined
558
+ * when there is nothing to send.
559
+ */
560
+ private _execEnv;
561
+ private _runDirectExec;
562
+ /**
563
+ * Try to run the exec against the in-sandbox sidecar over Railway's private
564
+ * network. Returns the result on success (including non-zero exit codes and
565
+ * timeouts — those are real command results, not failures). Returns
566
+ * `undefined` when the caller should fall back to the lease path:
567
+ *
568
+ * - Transport failure (connection refused, mid-stream drop, no `exit`
569
+ * frame). The registry entry is evicted so subsequent execs skip the
570
+ * private-net dial until the sidecar re-registers.
571
+ * - Sidecar answered with a non-2xx HTTP status. Registry is left intact —
572
+ * the address is still valid; something else is wrong (bad request,
573
+ * sidecar bug). Only this specific exec falls back.
574
+ */
575
+ private _tryExecViaPrivateNetwork;
576
+ /**
577
+ * Evict this sandbox's entry from the address registry after an observed
578
+ * transport failure. The entry stays gone until the next start() re-reads
579
+ * `instanceUrl` from a workspace-proxy response — until then, execs skip
580
+ * the private-net dial and go straight to the lease path.
581
+ */
582
+ private _invalidateAddress;
583
+ /**
584
+ * Return a cached exec lease, minting a fresh one when the cache is empty
585
+ * or the JWT is within {@link LEASE_REFRESH_MARGIN_MS} of `expiresAt`.
586
+ *
587
+ * Callers are expected to be on the "sandbox is running" path; we don't
588
+ * re-check `_sandboxId` here because `executeCommand` already gated on it.
589
+ */
590
+ private _ensureLease;
591
+ getInfo(): Promise<SandboxInfo>;
592
+ getInstructions(opts?: {
593
+ requestContext?: RequestContext;
594
+ }): string;
595
+ }
596
+ export {};
597
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EACV,aAAa,EAC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