@finalai/sandbox-router-e2b 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -4
- package/dist/modules/desktop.d.mts +13 -0
- package/dist/modules/desktop.mjs +279 -0
- package/dist/modules/desktop.mjs.map +7 -0
- package/dist/modules/e2b.mjs +302 -56
- package/dist/modules/e2b.mjs.map +2 -2
- package/dist/modules/limits.mjs +6 -1
- package/dist/modules/limits.mjs.map +2 -2
- package/dist/modules/process-history.d.mts +16 -0
- package/dist/modules/process-history.mjs +38 -3
- package/dist/modules/process-history.mjs.map +2 -2
- package/dist/modules/template.d.mts +1 -0
- package/dist/modules/template.mjs +19 -0
- package/dist/modules/template.mjs.map +2 -2
- package/package.json +2 -2
package/dist/modules/e2b.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import {
|
|
2
|
-
AtEnd,
|
|
3
2
|
attempt,
|
|
4
3
|
canonicalJson,
|
|
5
4
|
defineProvider,
|
|
@@ -9,6 +8,7 @@ import {
|
|
|
9
8
|
failFromStatus,
|
|
10
9
|
FileKind,
|
|
11
10
|
fitWithinLimits,
|
|
11
|
+
IdleAction,
|
|
12
12
|
imageKey,
|
|
13
13
|
ImageStrategy,
|
|
14
14
|
ok,
|
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
shellQuote,
|
|
22
22
|
SPECIFICATION_VERSION
|
|
23
23
|
} from "@finalai/sandbox-router/provider";
|
|
24
|
+
import { MaxAction } from "@finalai/sandbox-router";
|
|
24
25
|
import {
|
|
25
26
|
ALL_TRAFFIC,
|
|
26
27
|
AuthenticationError,
|
|
@@ -38,12 +39,13 @@ import {
|
|
|
38
39
|
TimeoutError
|
|
39
40
|
} from "e2b";
|
|
40
41
|
import * as z from "zod";
|
|
42
|
+
import { createDesktop } from "./desktop.mjs";
|
|
41
43
|
import { E2B_CAPABILITIES, E2B_REGIONS, e2bLimits } from "./limits.mjs";
|
|
42
44
|
import {
|
|
43
45
|
createProcessRegistry,
|
|
44
46
|
processKey
|
|
45
47
|
} from "./process-history.mjs";
|
|
46
|
-
import { DEFAULT_TEMPLATE, templateOf } from "./template.mjs";
|
|
48
|
+
import { buildsBase, DEFAULT_TEMPLATE, templateOf } from "./template.mjs";
|
|
47
49
|
const e2bOptionsSchema = z.object({
|
|
48
50
|
// Start from this E2B template (name or id) instead of the default. Its size is the
|
|
49
51
|
// template's own.
|
|
@@ -56,6 +58,7 @@ const TEMPLATE_SIZE = { cpu: 2, memoryMib: 512 };
|
|
|
56
58
|
const TIMEOUT_KEY = "sandbox_router_timeout_s";
|
|
57
59
|
const RESERVED_KEYS = /* @__PURE__ */ new Set([TIMEOUT_KEY]);
|
|
58
60
|
const ENVD_PORT = 49983;
|
|
61
|
+
const TRAFFIC_TOKEN_HEADER = "e2b-traffic-access-token";
|
|
59
62
|
const classify = (cause) => {
|
|
60
63
|
const message = cause instanceof Error ? cause.message : String(cause);
|
|
61
64
|
if (cause instanceof NotFoundError)
|
|
@@ -121,11 +124,57 @@ const entryOf = (entry) => ({
|
|
|
121
124
|
modifiedAt: entry.modifiedTime?.toISOString() ?? null,
|
|
122
125
|
mode: entry.mode & 4095
|
|
123
126
|
});
|
|
124
|
-
const networkOf = (network) => {
|
|
125
|
-
|
|
126
|
-
if (network.egress === EgressMode.
|
|
127
|
+
const networkOf = (network, ports) => {
|
|
128
|
+
const allowPublicTraffic = ports.some((port) => port.public);
|
|
129
|
+
if (network.egress === EgressMode.AllowAll) return { network: { allowPublicTraffic } };
|
|
130
|
+
if (network.egress === EgressMode.DenyAll)
|
|
131
|
+
return { allowInternetAccess: false, network: { allowPublicTraffic } };
|
|
127
132
|
const allowOut = [...network.egress.allowDomains ?? [], ...network.egress.allowCidrs ?? []];
|
|
128
|
-
return { network: { allowOut, denyOut: [ALL_TRAFFIC] } };
|
|
133
|
+
return { network: { allowOut, denyOut: [ALL_TRAFFIC], allowPublicTraffic } };
|
|
134
|
+
};
|
|
135
|
+
const lifecycleOf = (lifecycle) => {
|
|
136
|
+
const pause = lifecycle.max == null && (lifecycle.idle?.action === IdleAction.Pause || lifecycle.autoResume === true);
|
|
137
|
+
return {
|
|
138
|
+
onTimeout: pause ? "pause" : "kill",
|
|
139
|
+
...lifecycle.autoResume == null ? {} : { autoResume: lifecycle.autoResume }
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
const lifecycleProblem = (lifecycle) => {
|
|
143
|
+
if (lifecycle.max?.action === MaxAction.Stop)
|
|
144
|
+
return {
|
|
145
|
+
field: "lifecycle.max.action",
|
|
146
|
+
reason: "E2B deletes or pauses a sandbox at the end of its lifetime; it cannot stop one"
|
|
147
|
+
};
|
|
148
|
+
if (lifecycle.autoResume === true && lifecycle.max != null)
|
|
149
|
+
return {
|
|
150
|
+
field: "lifecycle.autoResume",
|
|
151
|
+
reason: "E2B wakes only sandboxes that pause at the end of their lifetime, not ones it deletes"
|
|
152
|
+
};
|
|
153
|
+
if (lifecycle.max === null && lifecycleOf(lifecycle).onTimeout === "kill")
|
|
154
|
+
return {
|
|
155
|
+
field: "lifecycle.max",
|
|
156
|
+
reason: "E2B deletes every sandbox at the end of its lifetime (24 hours at most) unless it pauses then, which needs an idle pause or autoResume"
|
|
157
|
+
};
|
|
158
|
+
return null;
|
|
159
|
+
};
|
|
160
|
+
const isShellCommand = (info) => {
|
|
161
|
+
const flag = info.args.indexOf("-c");
|
|
162
|
+
return flag !== -1 && flag === info.args.length - 2;
|
|
163
|
+
};
|
|
164
|
+
const commandOf = (info) => isShellCommand(info) ? info.args.at(-1) ?? info.cmd : [info.cmd, ...info.args].join(" ");
|
|
165
|
+
const CIDR = /^[0-9a-f:.]+\/\d+$|^[0-9.]+$/i;
|
|
166
|
+
const networkFromInfo = (info) => {
|
|
167
|
+
const allowOut = info.network?.allowOut ?? [];
|
|
168
|
+
const denyOut = info.network?.denyOut ?? [];
|
|
169
|
+
const deniesAll = info.allowInternetAccess === false || denyOut.includes(ALL_TRAFFIC);
|
|
170
|
+
if (!deniesAll) return { egress: EgressMode.AllowAll };
|
|
171
|
+
if (allowOut.length === 0) return { egress: EgressMode.DenyAll };
|
|
172
|
+
return {
|
|
173
|
+
egress: {
|
|
174
|
+
allowDomains: allowOut.filter((entry) => !CIDR.test(entry)),
|
|
175
|
+
allowCidrs: allowOut.filter((entry) => CIDR.test(entry))
|
|
176
|
+
}
|
|
177
|
+
};
|
|
129
178
|
};
|
|
130
179
|
const networkUpdateOf = (network) => {
|
|
131
180
|
if (network.egress === EgressMode.AllowAll) return {};
|
|
@@ -174,14 +223,39 @@ const e2b = (credentials, options = {}) => {
|
|
|
174
223
|
const sizedTemplates = /* @__PURE__ */ new Set();
|
|
175
224
|
const limits = e2bLimits;
|
|
176
225
|
const maxOutputBytes = limits.maxOutputBytes;
|
|
177
|
-
const
|
|
178
|
-
const
|
|
226
|
+
const maxLifetimeOf = (info) => timeouts.has(info.sandboxId) ? timeouts.get(info.sandboxId) ?? null : Number(info.metadata[TIMEOUT_KEY]) || null;
|
|
227
|
+
const lifecycleFromInfo = (info) => {
|
|
228
|
+
const native = info.lifecycle;
|
|
229
|
+
if (native == null) return null;
|
|
230
|
+
const maxS = maxLifetimeOf(info) ?? Math.max(1, Math.round((info.endAt.getTime() - info.startedAt.getTime()) / 1e3));
|
|
231
|
+
return {
|
|
232
|
+
idle: null,
|
|
233
|
+
max: native.onTimeout === "kill" ? { afterS: maxS, action: MaxAction.Delete } : null,
|
|
234
|
+
autoResume: native.autoResume
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
const vendorSandbox = (info) => ({
|
|
238
|
+
...sandboxOf(info),
|
|
239
|
+
lifecycle: lifecycleFromInfo(info)
|
|
240
|
+
});
|
|
241
|
+
const connectTimeoutMs = (info) => {
|
|
242
|
+
const maxS = maxLifetimeOf(info);
|
|
243
|
+
if (info.state === "paused" || maxS == null) return (maxS ?? defaultTimeoutS) * 1e3;
|
|
244
|
+
return Math.max(1e3, info.endAt.getTime() - Date.now());
|
|
245
|
+
};
|
|
246
|
+
const sandboxFor = async (id, wake) => {
|
|
179
247
|
const cached = connected.get(id);
|
|
180
|
-
if (cached != null) return ok(cached);
|
|
248
|
+
if (cached != null && wake !== false) return ok(cached);
|
|
181
249
|
const info = await call(() => Sandbox.getInfo(id, api));
|
|
182
250
|
if (!info.ok) return info;
|
|
251
|
+
if (cached != null && info.value.state !== "paused") return ok(cached);
|
|
252
|
+
if (info.value.state === "paused" && !(wake ?? info.value.lifecycle?.autoResume ?? false))
|
|
253
|
+
return fail(
|
|
254
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
255
|
+
`the ${PROVIDER} sandbox is paused; resume it first`
|
|
256
|
+
);
|
|
183
257
|
const sandbox = await call(
|
|
184
|
-
() => Sandbox.connect(id, { ...api, timeoutMs:
|
|
258
|
+
() => Sandbox.connect(id, { ...api, timeoutMs: connectTimeoutMs(info.value) })
|
|
185
259
|
);
|
|
186
260
|
if (sandbox.ok) connected.set(id, sandbox.value);
|
|
187
261
|
return sandbox;
|
|
@@ -283,14 +357,60 @@ const e2b = (credentials, options = {}) => {
|
|
|
283
357
|
}
|
|
284
358
|
};
|
|
285
359
|
};
|
|
360
|
+
const portUrl = async (id, port, urlOptions = {}) => {
|
|
361
|
+
const info = await call(() => Sandbox.getInfo(id, api));
|
|
362
|
+
if (!info.ok) return info;
|
|
363
|
+
const url = `https://${port}-${id}.${info.value.sandboxDomain ?? domain}`;
|
|
364
|
+
if (info.value.network?.allowPublicTraffic !== false)
|
|
365
|
+
return ok({ url, auth: PortAuth.Public, token: null, expiresAt: null });
|
|
366
|
+
if (urlOptions.ttlS != null)
|
|
367
|
+
return fail(
|
|
368
|
+
SandboxRouterErrorCode.UnsupportedByProvider,
|
|
369
|
+
"E2B traffic access tokens cannot be given a lifetime"
|
|
370
|
+
);
|
|
371
|
+
const sandbox = await sandboxFor(id);
|
|
372
|
+
if (!sandbox.ok) return sandbox;
|
|
373
|
+
const token = sandbox.value.trafficAccessToken;
|
|
374
|
+
if (token == null)
|
|
375
|
+
return fail(
|
|
376
|
+
SandboxRouterErrorCode.InvalidResponse,
|
|
377
|
+
`${PROVIDER} returned no traffic access token`
|
|
378
|
+
);
|
|
379
|
+
return ok({
|
|
380
|
+
url,
|
|
381
|
+
auth: PortAuth.Header,
|
|
382
|
+
token,
|
|
383
|
+
header: TRAFFIC_TOKEN_HEADER,
|
|
384
|
+
expiresAt: null
|
|
385
|
+
});
|
|
386
|
+
};
|
|
387
|
+
const desktop = createDesktop({
|
|
388
|
+
sandboxFor: (id) => sandboxFor(id),
|
|
389
|
+
portAccess: async (id, port) => {
|
|
390
|
+
const access = await portUrl(id, port);
|
|
391
|
+
return access.ok ? ok({ url: access.value.url, token: access.value.token }) : access;
|
|
392
|
+
},
|
|
393
|
+
call
|
|
394
|
+
});
|
|
286
395
|
const fit = (spec) => {
|
|
287
396
|
const base = fitWithinLimits({ limits, spec });
|
|
288
|
-
if (spec.
|
|
397
|
+
if (spec.lifecycle.idle != null)
|
|
289
398
|
base.ignored.push({
|
|
290
|
-
field: "
|
|
399
|
+
field: "lifecycle.idle",
|
|
291
400
|
reason: "E2B ends sandboxes at a fixed lifetime, not after idle time"
|
|
292
401
|
});
|
|
402
|
+
const problem = lifecycleProblem(spec.lifecycle);
|
|
403
|
+
if (problem != null) base.rejected.push(problem);
|
|
404
|
+
if (spec.ports.some((port) => port.public) && spec.ports.some((port) => !port.public))
|
|
405
|
+
base.ignored.push({
|
|
406
|
+
field: "ports",
|
|
407
|
+
reason: "E2B makes every port public when one is"
|
|
408
|
+
});
|
|
409
|
+
if (spec.cpuLimit != null && spec.cpuLimit > spec.cpu || spec.memoryLimitMib != null && spec.memoryLimitMib > spec.memoryMib)
|
|
410
|
+
base.rejected.push({ field: "cpuLimit", reason: "E2B sandboxes have a fixed size" });
|
|
293
411
|
if (spec.gpu != null) base.rejected.push({ field: "gpu", reason: "E2B has no GPUs" });
|
|
412
|
+
if (spec.volumes.length > 0)
|
|
413
|
+
base.rejected.push({ field: "volumes", reason: "volumes are not offered on E2B" });
|
|
294
414
|
return base;
|
|
295
415
|
};
|
|
296
416
|
return defineProvider({
|
|
@@ -316,7 +436,14 @@ const e2b = (credentials, options = {}) => {
|
|
|
316
436
|
template = resized.value;
|
|
317
437
|
sized = source === DEFAULT_TEMPLATE || context.artifact != null;
|
|
318
438
|
}
|
|
319
|
-
const
|
|
439
|
+
const problem = lifecycleProblem(spec.lifecycle);
|
|
440
|
+
if (problem != null)
|
|
441
|
+
return fail(SandboxRouterErrorCode.UnsupportedByProvider, problem.reason);
|
|
442
|
+
const maxS = spec.lifecycle.max?.afterS;
|
|
443
|
+
const lifetimeS = maxS ?? defaultTimeoutS;
|
|
444
|
+
const native = lifecycleOf(spec.lifecycle);
|
|
445
|
+
if (spec.volumes.length > 0)
|
|
446
|
+
return fail(SandboxRouterErrorCode.UnsupportedByProvider, "volumes are not offered on E2B");
|
|
320
447
|
const idempotencyKey = `sandbox-router-${(await sha256Hex(
|
|
321
448
|
canonicalJson({ name: context.name, spec, labels: context.labels, template })
|
|
322
449
|
)).slice(0, 48)}`;
|
|
@@ -325,14 +452,14 @@ const e2b = (credentials, options = {}) => {
|
|
|
325
452
|
...api,
|
|
326
453
|
signal: context.signal,
|
|
327
454
|
idempotencyKey,
|
|
328
|
-
metadata: {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
lifecycle: {
|
|
332
|
-
onTimeout: spec.atEnd === AtEnd.Pause ? "pause" : "kill",
|
|
333
|
-
autoResume: false
|
|
455
|
+
metadata: {
|
|
456
|
+
...context.labels,
|
|
457
|
+
...maxS == null ? {} : { [TIMEOUT_KEY]: String(maxS) }
|
|
334
458
|
},
|
|
335
|
-
...
|
|
459
|
+
envs: { ...spec.image?.env, ...spec.env },
|
|
460
|
+
timeoutMs: lifetimeS * 1e3,
|
|
461
|
+
lifecycle: native,
|
|
462
|
+
...networkOf(spec.network, spec.ports)
|
|
336
463
|
})
|
|
337
464
|
);
|
|
338
465
|
if (!created.ok) return created;
|
|
@@ -341,7 +468,7 @@ const e2b = (credentials, options = {}) => {
|
|
|
341
468
|
if (!sized) {
|
|
342
469
|
const info = await call(() => Sandbox.getInfo(sandbox.sandboxId, api));
|
|
343
470
|
if (!info.ok) return info;
|
|
344
|
-
return ok(
|
|
471
|
+
return ok(vendorSandbox(info.value));
|
|
345
472
|
}
|
|
346
473
|
return ok({
|
|
347
474
|
providerSandboxId: sandbox.sandboxId,
|
|
@@ -351,14 +478,19 @@ const e2b = (credentials, options = {}) => {
|
|
|
351
478
|
nativeError: null,
|
|
352
479
|
labels: context.labels,
|
|
353
480
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
354
|
-
granted: { cpu: granted.cpu, memoryMib: granted.memoryMib, diskGib: null }
|
|
481
|
+
granted: { cpu: granted.cpu, memoryMib: granted.memoryMib, diskGib: null },
|
|
482
|
+
lifecycle: {
|
|
483
|
+
idle: null,
|
|
484
|
+
max: native.onTimeout === "kill" ? { afterS: lifetimeS, action: MaxAction.Delete } : null,
|
|
485
|
+
autoResume: native.autoResume ?? false
|
|
486
|
+
}
|
|
355
487
|
});
|
|
356
488
|
},
|
|
357
489
|
get: async (id) => {
|
|
358
490
|
const info = await call(() => Sandbox.getInfo(id, api));
|
|
359
491
|
if (!info.ok)
|
|
360
492
|
return info.error.code === SandboxRouterErrorCode.NotFound || info.error.code === SandboxRouterErrorCode.InvalidRequest ? ok(null) : info;
|
|
361
|
-
return ok(
|
|
493
|
+
return ok(vendorSandbox(info.value));
|
|
362
494
|
},
|
|
363
495
|
list: async ({ labels }) => call(async () => {
|
|
364
496
|
const paginator = Sandbox.list({
|
|
@@ -370,7 +502,7 @@ const e2b = (credentials, options = {}) => {
|
|
|
370
502
|
while (paginator.hasNext)
|
|
371
503
|
for (const info of await paginator.nextItems())
|
|
372
504
|
if (Object.entries(labels).every(([key, value]) => info.metadata[key] === value))
|
|
373
|
-
found.push(
|
|
505
|
+
found.push(vendorSandbox(info));
|
|
374
506
|
return found;
|
|
375
507
|
}),
|
|
376
508
|
delete: async (id) => {
|
|
@@ -397,7 +529,7 @@ const e2b = (credentials, options = {}) => {
|
|
|
397
529
|
const info = await call(() => Sandbox.getInfo(id, api));
|
|
398
530
|
if (!info.ok) return info;
|
|
399
531
|
const resumed = await call(
|
|
400
|
-
() => Sandbox.connect(id, { ...api, timeoutMs:
|
|
532
|
+
() => Sandbox.connect(id, { ...api, timeoutMs: connectTimeoutMs(info.value) })
|
|
401
533
|
);
|
|
402
534
|
if (!resumed.ok) return resumed;
|
|
403
535
|
connected.set(id, resumed.value);
|
|
@@ -405,20 +537,78 @@ const e2b = (credentials, options = {}) => {
|
|
|
405
537
|
pausedKeeping.delete(id);
|
|
406
538
|
return ok({ coldRestart });
|
|
407
539
|
},
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
540
|
+
// Replaces the policy. E2B can change a sandbox's lifetime; whether it pauses or is deleted
|
|
541
|
+
// at the end, and whether it wakes, is fixed at create. Idle policies are ignored, as at
|
|
542
|
+
// create.
|
|
543
|
+
setLifecycle: async (id, lifecycle) => {
|
|
544
|
+
const problem = lifecycleProblem(lifecycle);
|
|
545
|
+
if (problem != null)
|
|
546
|
+
return fail(SandboxRouterErrorCode.UnsupportedByProvider, problem.reason);
|
|
547
|
+
const info = await call(() => Sandbox.getInfo(id, api));
|
|
548
|
+
if (!info.ok) return info;
|
|
549
|
+
const native = info.value.lifecycle;
|
|
550
|
+
const wanted = lifecycleOf(lifecycle);
|
|
551
|
+
if (native != null && (native.onTimeout !== wanted.onTimeout || native.autoResume !== (wanted.autoResume ?? false)))
|
|
552
|
+
return fail(
|
|
553
|
+
SandboxRouterErrorCode.UnsupportedByProvider,
|
|
554
|
+
"E2B fixes pausing and waking at the end of a lifetime when the sandbox is created"
|
|
555
|
+
);
|
|
556
|
+
const { max } = lifecycle;
|
|
557
|
+
if (max === null) {
|
|
558
|
+
timeouts.set(id, null);
|
|
559
|
+
return ok(void 0);
|
|
560
|
+
}
|
|
561
|
+
const timeoutMs = max == null ? defaultTimeoutS * 1e3 : Math.max(1e3, max.afterS * 1e3 - (Date.now() - info.value.startedAt.getTime()));
|
|
562
|
+
const set = await call(() => Sandbox.setTimeout(id, timeoutMs, api));
|
|
412
563
|
if (!set.ok) return set;
|
|
413
|
-
timeouts.set(id,
|
|
564
|
+
timeouts.set(id, max?.afterS ?? null);
|
|
414
565
|
return ok(void 0);
|
|
415
566
|
},
|
|
416
|
-
|
|
567
|
+
// E2B does not version network policies.
|
|
568
|
+
setNetwork: async (id, network, networkOptions = {}) => {
|
|
569
|
+
if (networkOptions.expectedRevision != null)
|
|
570
|
+
return fail(
|
|
571
|
+
SandboxRouterErrorCode.UnsupportedByProvider,
|
|
572
|
+
"E2B network policies have no revisions"
|
|
573
|
+
);
|
|
417
574
|
const updated = await call(() => Sandbox.updateNetwork(id, networkUpdateOf(network), api));
|
|
418
575
|
return updated.ok ? ok(void 0) : updated;
|
|
419
576
|
},
|
|
577
|
+
getNetwork: async (id) => {
|
|
578
|
+
const info = await call(() => Sandbox.getInfo(id, api));
|
|
579
|
+
if (!info.ok) return info;
|
|
580
|
+
return ok({ network: networkFromInfo(info.value), revision: null });
|
|
581
|
+
},
|
|
582
|
+
// E2B samples every few seconds; points are averaged into `bucketS` buckets.
|
|
583
|
+
metrics: async (id, { from, to, bucketS }) => {
|
|
584
|
+
const samples = await call(
|
|
585
|
+
() => Sandbox.getMetrics(id, { ...api, start: new Date(from), end: new Date(to) })
|
|
586
|
+
);
|
|
587
|
+
if (!samples.ok) return samples;
|
|
588
|
+
const bucketMs = Math.max(1, bucketS) * 1e3;
|
|
589
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
590
|
+
for (const sample of samples.value) {
|
|
591
|
+
const at = Math.floor(sample.timestamp.getTime() / bucketMs) * bucketMs;
|
|
592
|
+
const bucket = buckets.get(at) ?? { cpu: 0, memory: 0, memoryLimit: 0, count: 0 };
|
|
593
|
+
bucket.cpu += sample.cpuUsedPct;
|
|
594
|
+
bucket.memory += sample.memUsed;
|
|
595
|
+
bucket.memoryLimit += sample.memTotal;
|
|
596
|
+
bucket.count += 1;
|
|
597
|
+
buckets.set(at, bucket);
|
|
598
|
+
}
|
|
599
|
+
return ok(
|
|
600
|
+
[...buckets.entries()].sort(([a], [b]) => a - b).map(([at, bucket]) => ({
|
|
601
|
+
at: new Date(at).toISOString(),
|
|
602
|
+
cpuPercent: bucket.cpu / bucket.count,
|
|
603
|
+
memoryLimitBytes: Math.round(bucket.memoryLimit / bucket.count),
|
|
604
|
+
memoryBytes: Math.round(bucket.memory / bucket.count),
|
|
605
|
+
rxBytes: null,
|
|
606
|
+
txBytes: null
|
|
607
|
+
}))
|
|
608
|
+
);
|
|
609
|
+
},
|
|
420
610
|
exec: async (id, command, execOptions) => {
|
|
421
|
-
const sandbox = await sandboxFor(id);
|
|
611
|
+
const sandbox = await sandboxFor(id, execOptions.autoResume);
|
|
422
612
|
if (!sandbox.ok) return sandbox;
|
|
423
613
|
const sink = outputSink();
|
|
424
614
|
const stdin = execOptions.stdin === true;
|
|
@@ -440,7 +630,10 @@ const e2b = (credentials, options = {}) => {
|
|
|
440
630
|
const handle = started.value;
|
|
441
631
|
const record = processes.create(processKey(id, String(handle.pid)), {
|
|
442
632
|
maxOutputBytes,
|
|
443
|
-
onOutputCap: () => void handle.kill().catch(() => false)
|
|
633
|
+
onOutputCap: () => void handle.kill().catch(() => false),
|
|
634
|
+
command,
|
|
635
|
+
cwd: execOptions.cwd ?? null,
|
|
636
|
+
user: execOptions.user ?? null
|
|
444
637
|
});
|
|
445
638
|
record.queue.started(String(handle.pid), handle.pid);
|
|
446
639
|
sink.bind(record);
|
|
@@ -562,7 +755,7 @@ const e2b = (credentials, options = {}) => {
|
|
|
562
755
|
},
|
|
563
756
|
files: {
|
|
564
757
|
read: async (id, path, range = {}) => {
|
|
565
|
-
const sandbox = await sandboxFor(id);
|
|
758
|
+
const sandbox = await sandboxFor(id, range.autoResume);
|
|
566
759
|
if (!sandbox.ok) return sandbox;
|
|
567
760
|
return call(async () => {
|
|
568
761
|
const stream = await sandbox.value.files.read(path, { format: "stream" });
|
|
@@ -596,8 +789,17 @@ const e2b = (credentials, options = {}) => {
|
|
|
596
789
|
write: async (id, path, bytes, writeOptions = {}) => {
|
|
597
790
|
const sandbox = await sandboxFor(id);
|
|
598
791
|
if (!sandbox.ok) return sandbox;
|
|
599
|
-
const
|
|
792
|
+
const target = writeOptions.append === true ? `${path.slice(0, path.lastIndexOf("/") + 1)}.sandbox-router-append-${crypto.randomUUID()}` : path;
|
|
793
|
+
const written = await call(() => sandbox.value.files.write(target, bytes.slice()));
|
|
600
794
|
if (!written.ok) return written;
|
|
795
|
+
if (target !== path) {
|
|
796
|
+
const appended = await call(
|
|
797
|
+
() => sandbox.value.commands.run(
|
|
798
|
+
`cat ${shellQuote(target)} >> ${shellQuote(path)}; status=$?; rm -f ${shellQuote(target)}; exit $status`
|
|
799
|
+
)
|
|
800
|
+
);
|
|
801
|
+
if (!appended.ok) return appended;
|
|
802
|
+
}
|
|
601
803
|
if (writeOptions.mode == null) return ok(void 0);
|
|
602
804
|
const mode = (writeOptions.mode & 4095).toString(8);
|
|
603
805
|
const changed = await call(
|
|
@@ -605,8 +807,8 @@ const e2b = (credentials, options = {}) => {
|
|
|
605
807
|
);
|
|
606
808
|
return changed.ok ? ok(void 0) : changed;
|
|
607
809
|
},
|
|
608
|
-
list: async (id, path) => {
|
|
609
|
-
const sandbox = await sandboxFor(id);
|
|
810
|
+
list: async (id, path, listOptions = {}) => {
|
|
811
|
+
const sandbox = await sandboxFor(id, listOptions.autoResume);
|
|
610
812
|
if (!sandbox.ok) return sandbox;
|
|
611
813
|
const entries = await call(() => sandbox.value.files.list(path, { depth: 1 }));
|
|
612
814
|
return entries.ok ? ok(entries.value.map(entryOf)) : entries;
|
|
@@ -628,32 +830,70 @@ const e2b = (credentials, options = {}) => {
|
|
|
628
830
|
const removed = await call(() => sandbox.value.files.remove(path));
|
|
629
831
|
return removed.ok || removed.error.code === SandboxRouterErrorCode.NotFound ? ok(void 0) : removed;
|
|
630
832
|
},
|
|
631
|
-
stat: async (id, path) => {
|
|
632
|
-
const sandbox = await sandboxFor(id);
|
|
833
|
+
stat: async (id, path, statOptions = {}) => {
|
|
834
|
+
const sandbox = await sandboxFor(id, statOptions.autoResume);
|
|
633
835
|
if (!sandbox.ok) return sandbox;
|
|
634
836
|
const info = await call(() => sandbox.value.files.getInfo(path));
|
|
635
837
|
if (!info.ok) return info.error.code === SandboxRouterErrorCode.NotFound ? ok(null) : info;
|
|
636
838
|
return ok(entryOf(info.value));
|
|
637
839
|
}
|
|
638
840
|
},
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
841
|
+
...desktop,
|
|
842
|
+
processes: {
|
|
843
|
+
// E2B lists running processes; ones this provider started and that ended recently are
|
|
844
|
+
// added from its own records.
|
|
845
|
+
list: async (id, listOptions = {}) => {
|
|
846
|
+
const sandbox = await sandboxFor(id, listOptions.autoResume);
|
|
847
|
+
if (!sandbox.ok) return sandbox;
|
|
848
|
+
const running = await call(() => sandbox.value.commands.list());
|
|
849
|
+
if (!running.ok) return running;
|
|
850
|
+
const known = processes.list(id);
|
|
851
|
+
const byId = new Map(known.map((entry) => [entry.processId, entry]));
|
|
852
|
+
const live = new Set(running.value.map((info) => String(info.pid)));
|
|
853
|
+
const summaries = running.value.map((info) => {
|
|
854
|
+
const entry = byId.get(String(info.pid));
|
|
855
|
+
const shell = isShellCommand(info);
|
|
856
|
+
return {
|
|
857
|
+
processId: String(info.pid),
|
|
858
|
+
command: entry?.command ?? commandOf(info),
|
|
859
|
+
// Commands run through a shell have no argument list of their own.
|
|
860
|
+
args: entry != null || shell ? null : info.args,
|
|
861
|
+
cwd: info.cwd ?? entry?.cwd ?? null,
|
|
862
|
+
user: entry?.user ?? null,
|
|
863
|
+
pid: info.pid,
|
|
864
|
+
running: true,
|
|
865
|
+
exitCode: null,
|
|
866
|
+
startedAt: entry?.startedAt ?? null,
|
|
867
|
+
endedAt: null
|
|
868
|
+
};
|
|
653
869
|
});
|
|
870
|
+
for (const entry of known)
|
|
871
|
+
if (!live.has(entry.processId))
|
|
872
|
+
summaries.push({
|
|
873
|
+
processId: entry.processId,
|
|
874
|
+
command: entry.command,
|
|
875
|
+
args: null,
|
|
876
|
+
cwd: entry.cwd,
|
|
877
|
+
user: entry.user,
|
|
878
|
+
pid: Number(entry.processId),
|
|
879
|
+
running: false,
|
|
880
|
+
exitCode: entry.exitCode,
|
|
881
|
+
startedAt: entry.startedAt,
|
|
882
|
+
endedAt: entry.endedAt
|
|
883
|
+
});
|
|
884
|
+
return ok(summaries);
|
|
654
885
|
}
|
|
655
886
|
},
|
|
656
|
-
|
|
887
|
+
ports: {
|
|
888
|
+
url: portUrl
|
|
889
|
+
},
|
|
890
|
+
// E2B snapshots carry no metadata, so labels could never be listed by.
|
|
891
|
+
snapshot: async (id, snapshotOptions) => {
|
|
892
|
+
if (Object.keys(snapshotOptions.labels ?? {}).length > 0)
|
|
893
|
+
return fail(
|
|
894
|
+
SandboxRouterErrorCode.UnsupportedByProvider,
|
|
895
|
+
"E2B snapshots cannot carry labels"
|
|
896
|
+
);
|
|
657
897
|
const taken = await call(() => Sandbox.createSnapshot(id, api));
|
|
658
898
|
return taken.ok ? ok({ snapshotId: taken.value.snapshotId }) : taken;
|
|
659
899
|
},
|
|
@@ -662,7 +902,7 @@ const e2b = (credentials, options = {}) => {
|
|
|
662
902
|
return deleted.ok || deleted.error.code === SandboxRouterErrorCode.NotFound ? ok(void 0) : deleted;
|
|
663
903
|
},
|
|
664
904
|
image: {
|
|
665
|
-
strategy: () => ImageStrategy.Build,
|
|
905
|
+
strategy: (spec) => buildsBase(spec) ? ImageStrategy.Build : null,
|
|
666
906
|
build: async (spec, buildContext) => {
|
|
667
907
|
const key = await call(() => imageKey(spec));
|
|
668
908
|
if (!key.ok) return key;
|
|
@@ -724,7 +964,13 @@ const e2b = (credentials, options = {}) => {
|
|
|
724
964
|
}
|
|
725
965
|
})
|
|
726
966
|
},
|
|
727
|
-
|
|
967
|
+
// The envd access token reaches everything in the sandbox and lasts as long as it does.
|
|
968
|
+
connect: async (id, connectOptions = {}) => {
|
|
969
|
+
if (connectOptions.scopes != null || connectOptions.ttlS != null)
|
|
970
|
+
return fail(
|
|
971
|
+
SandboxRouterErrorCode.UnsupportedByProvider,
|
|
972
|
+
"E2B access tokens cannot be scoped or given a lifetime"
|
|
973
|
+
);
|
|
728
974
|
let response;
|
|
729
975
|
try {
|
|
730
976
|
response = await doFetch(`https://api.${domain}/sandboxes/${encodeURIComponent(id)}`, {
|