@mastra/e2b 0.10.0-alpha.3 → 0.10.0-alpha.4

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @mastra/e2b
2
2
 
3
+ ## 0.10.0-alpha.4
4
+
5
+ ### Minor Changes
6
+
7
+ - Added deterministic reattach to E2B sandboxes by provider sandbox ID. Pass the persisted E2B sandbox ID via the new `sandboxId` option (or `clone({ sandboxId })`) and `start()` connects to that exact sandbox — resuming it if paused — instead of discovering by logical id metadata. Only a typed "sandbox gone" error falls back to the usual lookup-or-create path; auth, quota, rate-limit, timeout, and network errors now propagate instead of silently creating a duplicate sandbox. The resolved provider ID is exposed via the new `sandbox.sandboxId` property so it can be persisted across restarts. ([#22316](https://github.com/mastra-ai/mastra/pull/22316))
8
+
9
+ ```ts
10
+ const sandbox = new E2BSandbox({ id: 'my-workspace', sandboxId: persistedId });
11
+ await sandbox.start();
12
+ await save(sandbox.sandboxId); // persist for the next process
13
+ ```
14
+
15
+ Fixes https://github.com/mastra-ai/mastra/issues/22300
16
+
17
+ ### Patch Changes
18
+
19
+ - Starting a sandbox now reports whether it created a fresh sandbox or reconnected to an existing one, so an `onStart` handler can run first-time setup only when it's actually needed: ([#21984](https://github.com/mastra-ai/mastra/pull/21984))
20
+
21
+ ```typescript
22
+ new E2BSandbox({
23
+ id: 'session-1',
24
+ onStart: async ({ outcome }) => {
25
+ if (outcome === 'created') await cloneRepo();
26
+ },
27
+ });
28
+ ```
29
+
30
+ - Updated dependencies [[`4ff3ee2`](https://github.com/mastra-ai/mastra/commit/4ff3ee2bff7ed07528b4817f8f49639031c72a4d), [`c24754c`](https://github.com/mastra-ai/mastra/commit/c24754c1fb6fe144e5051e536e98c8a18b0214ac), [`45dd6ee`](https://github.com/mastra-ai/mastra/commit/45dd6ee089bd7df0d0c98a10098e483fd388e04a), [`32d3583`](https://github.com/mastra-ai/mastra/commit/32d358332cb8ac2306b83b73cf3536e74dbd435e), [`aca2869`](https://github.com/mastra-ai/mastra/commit/aca2869b2031982f3c4a2f52525c9be7cf123ef8)]:
31
+ - @mastra/core@1.62.0-alpha.11
32
+
3
33
  ## 0.10.0-alpha.3
4
34
 
5
35
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -650,6 +650,7 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
650
650
  network;
651
651
  lifecycle;
652
652
  connectionOpts;
653
+ _preferredSandboxId;
653
654
  _instructionsOverride;
654
655
  _constructorOptions;
655
656
  /** Resolved template ID after building (if needed) */
@@ -674,6 +675,7 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
674
675
  ...options.apiKey && { apiKey: options.apiKey },
675
676
  ...options.accessToken && { accessToken: options.accessToken }
676
677
  };
678
+ this._preferredSandboxId = options.sandboxId;
677
679
  this._instructionsOverride = options.instructions;
678
680
  this._constructorOptions = { ...options };
679
681
  this._templatePreparePromise = this.resolveTemplate().catch((err) => {
@@ -692,13 +694,16 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
692
694
  * independent sandboxes (e.g. one per project).
693
695
  *
694
696
  * `options.idleTimeoutMinutes` maps to the E2B sandbox `timeout` (ms);
695
- * `options.sandboxId` is ignored because E2B reconnects by logical `id`.
697
+ * `options.sandboxId` reattaches the clone to that exact E2B sandbox on
698
+ * `start()`. The parent's own preferred provider sandbox ID is never
699
+ * inherited — physical identity is per-instance.
696
700
  */
697
701
  clone(options = {}) {
698
- const { id: _id, ...base } = this._constructorOptions;
702
+ const { id: _id, sandboxId: _sandboxId, ...base } = this._constructorOptions;
699
703
  return new E2BSandbox({
700
704
  ...base,
701
705
  ...options.id !== void 0 && { id: options.id },
706
+ ...options.sandboxId !== void 0 && { sandboxId: options.sandboxId },
702
707
  ...options.env !== void 0 && { env: options.env },
703
708
  ...options.idleTimeoutMinutes !== void 0 && { timeout: options.idleTimeoutMinutes * 6e4 }
704
709
  });
@@ -730,25 +735,43 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
730
735
  return this._sandbox;
731
736
  }
732
737
  /**
733
- * Start the E2B sandbox.
734
- * Handles template preparation, existing sandbox reconnection, and new sandbox creation.
738
+ * The E2B provider sandbox ID resolved after connect or create.
735
739
  *
736
- * Status management and mount processing are handled by the base class.
740
+ * Persist this to reattach deterministically later via the `sandboxId`
741
+ * option (or `clone({ sandboxId })`). Undefined until the sandbox has been
742
+ * started (attached) in this process.
737
743
  */
738
- async start() {
739
- if (this._sandbox) return;
740
- const [existingSandbox, templateId] = await Promise.all([this.findExistingSandbox(), this._templatePreparePromise || this.resolveTemplate()]);
741
- if (existingSandbox) {
742
- this._sandbox = existingSandbox;
743
- this._createdAt = /* @__PURE__ */ new Date();
744
- this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);
745
- const expectedPaths = Array.from(this.mounts.entries.keys());
746
- this.logger.debug(`${LOG_PREFIX} Running mount reconciliation...`);
747
- await this.reconcileMounts(expectedPaths);
748
- this.logger.debug(`${LOG_PREFIX} Mount reconciliation complete`);
749
- return;
750
- }
751
- let resolvedTemplateId = templateId;
744
+ get sandboxId() {
745
+ return this._sandbox?.sandboxId;
746
+ }
747
+ /**
748
+ * Acquisition primitives (base-orchestrated start): the base derives
749
+ * `outcome: 'created'` only when a brand-new sandbox VM was created;
750
+ * reconnecting (including resuming a paused sandbox) is `outcome: 'connected'`.
751
+ *
752
+ * `find` returns an already-connected E2B handle: `Sandbox.connect`
753
+ * resumes paused sandboxes, and its failures are deliberately swallowed
754
+ * (unusable handle → create fresh) — that forgiveness is this provider's
755
+ * policy, so it lives here rather than in `connect`. The exception is the
756
+ * `sandboxId` reattach inside {@link acquireExistingSandbox}, which is
757
+ * fail-closed: only a "sandbox gone" error falls through to discovery.
758
+ */
759
+ async find() {
760
+ if (this._sandbox) return this._sandbox;
761
+ return await this.acquireExistingSandbox() ?? void 0;
762
+ }
763
+ async connect(existingSandbox) {
764
+ if (existingSandbox === this._sandbox) return;
765
+ this._sandbox = existingSandbox;
766
+ this._createdAt = /* @__PURE__ */ new Date();
767
+ this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);
768
+ const expectedPaths = Array.from(this.mounts.entries.keys());
769
+ this.logger.debug(`${LOG_PREFIX} Running mount reconciliation...`);
770
+ await this.reconcileMounts(expectedPaths);
771
+ this.logger.debug(`${LOG_PREFIX} Mount reconciliation complete`);
772
+ }
773
+ async create() {
774
+ let resolvedTemplateId = await (this._templatePreparePromise || this.resolveTemplate());
752
775
  if (!resolvedTemplateId) {
753
776
  this.logger.debug(`${LOG_PREFIX} Template preparation failed earlier, retrying...`);
754
777
  resolvedTemplateId = await this.resolveTemplate();
@@ -768,7 +791,7 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
768
791
  } catch (createError) {
769
792
  const errorStr = String(createError);
770
793
  if (errorStr.includes("404") && errorStr.includes("not found") && !this.templateSpec) {
771
- this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${templateId}`);
794
+ this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${resolvedTemplateId}`);
772
795
  this._resolvedTemplateId = void 0;
773
796
  const rebuiltTemplateId = await this.buildDefaultTemplate();
774
797
  this.logger.debug(`${LOG_PREFIX} Retrying sandbox creation with rebuilt template: ${rebuiltTemplateId}`);
@@ -849,7 +872,10 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
849
872
  path,
850
873
  filesystem: entry.filesystem?.provider ?? entry.config?.type ?? "unknown"
851
874
  })),
852
- metadata: { ...this.metadata }
875
+ metadata: {
876
+ ...this.metadata,
877
+ ...this._sandbox && { sandboxId: this._sandbox.sandboxId }
878
+ }
853
879
  };
854
880
  }
855
881
  /**
@@ -1127,6 +1153,52 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
1127
1153
  return null;
1128
1154
  }
1129
1155
  /**
1156
+ * Acquire an existing sandbox: try the preferred provider sandbox ID first
1157
+ * (deterministic reattach), then fall back to logical-id metadata discovery.
1158
+ */
1159
+ async acquireExistingSandbox() {
1160
+ if (this._preferredSandboxId) {
1161
+ const preferred = await this.connectToPreferredSandbox(this._preferredSandboxId);
1162
+ if (preferred) return preferred;
1163
+ }
1164
+ return this.findExistingSandbox();
1165
+ }
1166
+ /**
1167
+ * Deterministically reattach to a sandbox by its E2B provider ID.
1168
+ *
1169
+ * Fail-closed: only a typed "sandbox gone" error (not found / killed /
1170
+ * not running) returns null so the caller can fall through to logical-id
1171
+ * discovery or creation. Any other error (auth, quota, rate limit,
1172
+ * timeout, network) propagates so a duplicate sandbox is never created.
1173
+ *
1174
+ * Ownership is validated before connecting: a sandbox tagged with a
1175
+ * different `mastra-sandbox-id` is refused (without resuming it).
1176
+ * Sandboxes without the tag (created outside Mastra) are attachable.
1177
+ */
1178
+ async connectToPreferredSandbox(preferredSandboxId) {
1179
+ let info;
1180
+ try {
1181
+ info = await e2b.Sandbox.getInfo(preferredSandboxId, this.connectionOpts);
1182
+ } catch (e) {
1183
+ if (this.isSandboxDeadError(e)) {
1184
+ this.logger.debug(`${LOG_PREFIX} Preferred sandbox ${preferredSandboxId} is gone, falling back to logical-id discovery:`, e);
1185
+ return null;
1186
+ }
1187
+ throw e;
1188
+ }
1189
+ const owner = info.metadata?.["mastra-sandbox-id"];
1190
+ if (owner !== void 0 && owner !== this.id) throw new Error(`${LOG_PREFIX} Provider sandbox ${preferredSandboxId} belongs to logical sandbox id "${owner}", refusing to attach it to "${this.id}"`);
1191
+ try {
1192
+ return await e2b.Sandbox.connect(preferredSandboxId, this.connectionOpts);
1193
+ } catch (e) {
1194
+ if (this.isSandboxDeadError(e)) {
1195
+ this.logger.debug(`${LOG_PREFIX} Preferred sandbox ${preferredSandboxId} vanished before connect, falling back:`, e);
1196
+ return null;
1197
+ }
1198
+ throw e;
1199
+ }
1200
+ }
1201
+ /**
1130
1202
  * Find an existing sandbox with matching mastra-sandbox-id metadata.
1131
1203
  * Returns the connected sandbox if found, null otherwise.
1132
1204
  * Connecting to a paused sandbox resumes it.