@vite-hub/sandbox 0.1.0 → 0.3.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 (54) hide show
  1. package/README.md +118 -53
  2. package/dist/abortable-CR01hzfi.js +57 -0
  3. package/dist/cloudflare-Cog_r2Me.js +910 -0
  4. package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
  5. package/dist/cloudflare-failure-CFQhalfh.js +50 -0
  6. package/dist/container-CqfD8yuE.js +868 -0
  7. package/dist/{crabbox-BFCdf41h.js → crabbox-sbV3Zjuo.js} +10 -6
  8. package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
  9. package/dist/error-diagnostics-BJtLRL9w.js +536 -0
  10. package/dist/{file-listing-DECFTdSl.js → file-listing-CHtRrfo1.js} +1 -1
  11. package/dist/{file-lock-CxyVl4Cv.js → file-lock-D0-XPogS.js} +3 -2
  12. package/dist/{index-CXej1Bt0.d.ts → index-DsoQAUb7.d.ts} +94 -19
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +15 -10
  15. package/dist/internal/cloudflare.d.ts +173 -1
  16. package/dist/internal/cloudflare.js +4 -12
  17. package/dist/internal/host-toolchain.d.ts +1 -1
  18. package/dist/internal/host-toolchain.js +6 -7
  19. package/dist/internal/vercel.d.ts +1 -1
  20. package/dist/internal/vercel.js +3 -11
  21. package/dist/invariant-DolT9EEx.js +22 -0
  22. package/dist/module-types-B0LQ5H2S.js +7 -0
  23. package/dist/module-types-DCeJbS9Z.d.ts +110 -0
  24. package/dist/process-sweep-CMaujWE5.js +33 -0
  25. package/dist/provider-resolution-C6AQzuFG.js +133 -0
  26. package/dist/{remote-1Jz2oUMK.js → remote-70ZVZZlq.js} +32 -14
  27. package/dist/runtime-type-Deo4qzxN.js +9 -0
  28. package/dist/{session-DD0S1PDC.js → session-e0lyzjJ3.js} +2 -1
  29. package/dist/size-7AkVwGZb.js +118 -0
  30. package/dist/ssh.d.ts +8 -0
  31. package/dist/ssh.js +107 -40
  32. package/dist/task/index.d.ts +19 -17
  33. package/dist/task/index.js +92 -201
  34. package/dist/task/runtime/provider-loader.d.ts +7 -9
  35. package/dist/task/runtime/provider-loader.js +2 -5
  36. package/dist/task/runtime/providers/cloudflare.d.ts +5 -19
  37. package/dist/task/runtime/providers/cloudflare.js +7 -6
  38. package/dist/task/runtime/providers/vercel.d.ts +3 -3
  39. package/dist/task/runtime/providers/vercel.js +35 -4
  40. package/dist/task/runtime/state.d.ts +4 -1
  41. package/dist/task/runtime/state.js +11 -2
  42. package/dist/task/vite.d.ts +143 -17
  43. package/dist/task/vite.js +723 -400
  44. package/dist/{toolchain-BUVXtQ2m.js → toolchain-BIVGMRty.js} +12 -11
  45. package/dist/{trusted-host-DNMJ-Oig.js → trusted-host-kxkpaQcs.js} +21 -179
  46. package/dist/{vercel-Jtxa9TJx.js → vercel-BGGrNpza.js} +107 -34
  47. package/package.json +15 -12
  48. package/dist/cloudflare-DO0h3Ncf.js +0 -281
  49. package/dist/cloudflare-env-BBJaBbuQ.js +0 -39
  50. package/dist/error-diagnostics-BSysPv-D.js +0 -166
  51. package/dist/error-diagnostics-dGQqfgLt.js +0 -99
  52. package/dist/module-types-BfyRBaiP.js +0 -7
  53. package/dist/module-types-Cis4hrF1.d.ts +0 -95
  54. package/dist/runtime-type-DrmrW5m5.js +0 -42
@@ -1,7 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
2
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
3
3
  import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
4
- import { i as abortable, n as isRuntimeString, r as runtimeRecord } from "./runtime-type-DrmrW5m5.js";
4
+ import { t as abortable } from "./abortable-CR01hzfi.js";
5
+ import { t as runtimeRecord } from "./runtime-type-Deo4qzxN.js";
5
6
  import { createHash, randomUUID } from "node:crypto";
6
7
  import { maxSatisfying, minVersion, rcompare, valid, validRange } from "semver";
7
8
  //#region src/internal/toolchain.ts
@@ -127,11 +128,11 @@ function projectNodePin(manifest, files) {
127
128
  }
128
129
  function projectPackageManagerPin(manifest) {
129
130
  if (manifest?.packageManager !== void 0) {
130
- if (!isRuntimeString(manifest.packageManager)) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: "[vitehub] package.json packageManager must be a name@version string." });
131
+ if (typeof manifest.packageManager !== "string") throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: "[vitehub] package.json packageManager must be a name@version string." });
131
132
  return parsePackageManager(manifest.packageManager, "package.json#packageManager");
132
133
  }
133
134
  const declared = runtimeRecord(manifest?.devEngines)?.packageManager;
134
- const entry = (Array.isArray(declared) ? declared : declared ? [declared] : []).map(runtimeRecord).find((value) => isRuntimeString(value?.name));
135
+ const entry = (Array.isArray(declared) ? declared : declared ? [declared] : []).map(runtimeRecord).find((value) => typeof value?.name === "string");
135
136
  if (!entry) return;
136
137
  const source = "package.json#devEngines.packageManager";
137
138
  if (!isVersionText(entry.version)) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: `[vitehub] ${source} must declare a version for ${String(entry.name)}.` });
@@ -210,14 +211,14 @@ async function nodeReleases(base, signal) {
210
211
  if (cached && cached.expires > Date.now()) return await cached.value;
211
212
  const value = fetchBytes(url, "Node.js release index", signal).then((bytes) => {
212
213
  const parsed = JSON.parse(new TextDecoder().decode(bytes));
213
- if (!Array.isArray(parsed)) throw new TypeError("index.json is not a list");
214
+ if (!Array.isArray(parsed)) throw sandboxErrorDiagnostics.SANDBOX_R0155({ message: `[vitehub] Sandbox toolchain could not download Node.js release index from ${url}: the file is not a list.` });
214
215
  return parsed.flatMap((entry) => {
215
216
  const record = runtimeRecord(entry);
216
- const version = isRuntimeString(record?.version) ? valid(record.version) : null;
217
+ const version = typeof record?.version === "string" ? valid(record.version) : null;
217
218
  if (!version) return [];
218
219
  return [{
219
- ...Array.isArray(record?.files) ? { files: record.files.filter(isRuntimeString) } : {},
220
- lts: isRuntimeString(record?.lts) ? record.lts : false,
220
+ ...Array.isArray(record?.files) ? { files: record.files.filter((file) => typeof file === "string") } : {},
221
+ lts: typeof record?.lts === "string" ? record.lts : false,
221
222
  version
222
223
  }];
223
224
  }).sort((left, right) => rcompare(left.version, right.version));
@@ -256,9 +257,9 @@ async function resolvePackageManagerVersion(pin, signal) {
256
257
  async function packageVersionMetadata(name, version, signal) {
257
258
  const document = runtimeRecord(JSON.parse(new TextDecoder().decode(await fetchBytes(`${registryUrl()}/${encodePackageName(name)}/${encodeURIComponent(version)}`, `${name}@${version} registry metadata`, signal))));
258
259
  const dist = runtimeRecord(document?.dist);
259
- const declared = isRuntimeString(document?.bin) ? { [name.split("/").at(-1)]: document.bin } : Object.fromEntries(Object.entries(runtimeRecord(document?.bin) ?? {}).flatMap(([command, path]) => isRuntimeString(path) ? [[command, path]] : []));
260
+ const declared = typeof document?.bin === "string" ? { [name.split("/").at(-1)]: document.bin } : Object.fromEntries(Object.entries(runtimeRecord(document?.bin) ?? {}).flatMap(([command, path]) => typeof path === "string" ? [[command, path]] : []));
260
261
  const bin = Object.fromEntries(Object.entries(declared).map(([command, path]) => [command, path.replace(/^(?:\.\/)+/, "")]));
261
- if (!isRuntimeString(dist?.tarball) || !isRuntimeString(dist.integrity) || !dist.integrity.startsWith("sha512-")) throw sandboxErrorDiagnostics.SANDBOX_R0152({ message: `[vitehub] ${name}@${version} registry metadata has no sha512 integrity.` });
262
+ if (typeof dist?.tarball !== "string" || typeof dist.integrity !== "string" || !dist.integrity.startsWith("sha512-")) throw sandboxErrorDiagnostics.SANDBOX_R0152({ message: `[vitehub] ${name}@${version} registry metadata has no sha512 integrity.` });
262
263
  if (!Object.keys(bin).length || Object.entries(bin).some(([command, path]) => !/^[A-Za-z0-9._-]+$/.test(command) || !safeRelativePath(path))) throw sandboxErrorDiagnostics.SANDBOX_R0152({ message: `[vitehub] ${name}@${version} registry metadata has no usable bin entries.` });
263
264
  return {
264
265
  bin,
@@ -502,7 +503,7 @@ function versionFile(text) {
502
503
  return text?.split(/\r?\n/).map((value) => value.replace(/#.*$/, "").trim()).find(Boolean) || void 0;
503
504
  }
504
505
  function isVersionText(value) {
505
- return isRuntimeString(value) && Boolean(value.trim()) && !/[\0\n\r]/.test(value);
506
+ return typeof value === "string" && Boolean(value.trim()) && !/[\0\n\r]/.test(value);
506
507
  }
507
508
  function isPackageManagerName(value) {
508
509
  return value !== void 0 && packageManagerNames.has(value);
@@ -1,162 +1,16 @@
1
1
  import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
2
- import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
3
- import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, n as collectSandboxRequirementOutput, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-DD0S1PDC.js";
4
- import { t as acquireFileLock } from "./file-lock-CxyVl4Cv.js";
2
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
3
+ import { t as stopMarkedProcesses } from "./process-sweep-CMaujWE5.js";
4
+ import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, n as collectSandboxRequirementOutput, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-e0lyzjJ3.js";
5
+ import { t as acquireFileLock } from "./file-lock-D0-XPogS.js";
5
6
  import { createHash, randomUUID } from "node:crypto";
6
- import { access, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, statfs, symlink, writeFile } from "node:fs/promises";
7
+ import { access, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
7
8
  import { basename, delimiter, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
8
- import { defineDiagnostics } from "nostics";
9
9
  import { execFile, spawn } from "node:child_process";
10
- import { tmpdir } from "node:os";
11
10
  import { promisify } from "node:util";
12
- import { chmodSync, constants, rmSync, writeFileSync } from "node:fs";
13
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { constants } from "node:fs";
14
13
  import { Readable, Writable } from "node:stream";
15
- //#region src/internal/session-memory.ts
16
- const diagnostics = defineDiagnostics({
17
- docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
18
- codes: {
19
- SANDBOX_R0157: { why: ({ message }) => message },
20
- SANDBOX_R0158: { why: ({ message }) => message }
21
- }
22
- });
23
- function validateTrustedHostResources(resources) {
24
- if (process.platform !== "linux" || !isAbsolute(resources.cgroupParent)) throw diagnostics.SANDBOX_R0157({ message: "Sandbox memory limits require Linux and an absolute delegated cgroupParent." });
25
- for (const [key, value] of Object.entries({
26
- memoryMaxBytes: resources.memoryMaxBytes,
27
- memoryHighBytes: resources.memoryHighBytes ?? resources.memoryMaxBytes,
28
- memorySwapMaxBytes: resources.memorySwapMaxBytes ?? 0
29
- })) if (!Number.isSafeInteger(value) || value < 0 || key !== "memorySwapMaxBytes" && value === 0) throw diagnostics.SANDBOX_R0157({ message: `Sandbox ${key} must be a safe integer byte limit.` });
30
- if ((resources.memoryHighBytes ?? resources.memoryMaxBytes) > resources.memoryMaxBytes) throw diagnostics.SANDBOX_R0157({ message: "Sandbox memoryHighBytes must not exceed memoryMaxBytes." });
31
- }
32
- async function createSessionMemory(resources) {
33
- validateTrustedHostResources(resources);
34
- const parent = resources.cgroupParent;
35
- if ((await statfs(parent)).type !== 1667723888) throw diagnostics.SANDBOX_R0157({ message: "Sandbox cgroupParent must be on a cgroup v2 filesystem." });
36
- if (!(await readFile(join(parent, "cgroup.controllers"), "utf8")).trim().split(/\s+/).includes("memory")) throw diagnostics.SANDBOX_R0157({ message: "Sandbox cgroupParent does not delegate the memory controller." });
37
- await writeFile(join(parent, "cgroup.subtree_control"), "+memory");
38
- const path = join(parent, `vitehub-sandbox-${randomUUID()}`);
39
- await mkdir(path);
40
- try {
41
- await writeFile(join(path, "memory.max"), String(resources.memoryMaxBytes));
42
- if (resources.memoryHighBytes !== void 0) await writeFile(join(path, "memory.high"), String(resources.memoryHighBytes));
43
- await writeFile(join(path, "memory.swap.max"), String(resources.memorySwapMaxBytes ?? 0));
44
- await writeFile(join(path, "memory.oom.group"), "1");
45
- await access(join(path, "cgroup.procs"), constants.W_OK);
46
- await access(join(path, "cgroup.kill"), constants.W_OK);
47
- } catch (error) {
48
- await rmdir(path);
49
- throw error;
50
- }
51
- let closed = false;
52
- let healthError;
53
- const healthMarker = join(tmpdir(), `vitehub-sandbox-oom-${randomUUID()}`);
54
- const inspectHealth = async () => {
55
- if (closed || healthError) return;
56
- const localEvents = await readFile(join(path, "memory.events.local"), "utf8");
57
- const localOom = Number(/^oom (\d+)/m.exec(localEvents)?.[1] ?? 0);
58
- if (localOom > 0) {
59
- const events = await readFile(join(path, "memory.events"), "utf8");
60
- const kills = Number(/^oom_kill (\d+)/m.exec(events)?.[1] ?? 0);
61
- const peak = await readFile(join(path, "memory.peak"), "utf8").then((contents) => contents.trim()).catch((error) => error.code === "ENOENT" ? "unavailable" : Promise.reject(error));
62
- healthError = diagnostics.SANDBOX_R0158({ message: `Sandbox memory limit exceeded: local allocation OOM recorded; limit=${resources.memoryMaxBytes} bytes, peak=${peak} bytes, local_oom=${localOom}, observed_oom_kill=${kills}. Kill count does not identify the OOM cause and may exclude descendants on memory_localevents mounts. Open a new session after reducing the workload or changing its budget.` });
63
- const cleanupErrors = [];
64
- try {
65
- await writeFile(healthMarker, "1");
66
- } catch (error) {
67
- cleanupErrors.push(error);
68
- }
69
- try {
70
- await writeFile(join(path, "cgroup.kill"), "1");
71
- } catch (error) {
72
- cleanupErrors.push(error);
73
- }
74
- if (cleanupErrors.length) healthError.message += ` Cleanup details: ${cleanupErrors.map((error) => error instanceof Error ? error.message : String(error)).join("; ")}.`;
75
- }
76
- };
77
- const monitor = setInterval(() => {
78
- inspectHealth().catch((error) => {
79
- if (!healthError) healthError = error instanceof Error ? error : new Error(String(error));
80
- });
81
- }, 25);
82
- monitor.unref?.();
83
- return {
84
- async assertHealthy() {
85
- if (closed) throw diagnostics.SANDBOX_R0157({ message: "Sandbox resource group is closed." });
86
- await inspectHealth();
87
- if (healthError) throw healthError;
88
- },
89
- spawn(command, options) {
90
- const environment = Object.entries(options.env ?? process.env).filter((entry) => entry[1] !== void 0);
91
- const environmentFile = join(tmpdir(), `vitehub-sandbox-env-${randomUUID()}`);
92
- try {
93
- writeFileSync(environmentFile, JSON.stringify(Object.fromEntries(environment)), { mode: 384 });
94
- chmodSync(environmentFile, 384);
95
- const child = spawn(process.execPath, [
96
- "--input-type=commonjs",
97
- "-e",
98
- `const fs = require("node:fs");
99
- const [group, marker, environmentFile, command] = process.argv.slice(1);
100
- const env = JSON.parse(fs.readFileSync(environmentFile, "utf8"));
101
- const args = ["/bin/sh", "-c", command];
102
- fs.writeFileSync(group + "/cgroup.procs", String(process.pid));
103
- if (fs.existsSync(marker) || !/^oom 0$/m.test(fs.readFileSync(group + "/memory.events.local", "utf8"))) process.exit(125);
104
- process.execve("/bin/sh", args, env);`,
105
- path,
106
- healthMarker,
107
- environmentFile,
108
- command
109
- ], {
110
- ...options,
111
- env: {}
112
- });
113
- child?.once("close", () => {
114
- try {
115
- rmSync(environmentFile, { force: true });
116
- } catch {}
117
- });
118
- return child;
119
- } catch (error) {
120
- try {
121
- rmSync(environmentFile, { force: true });
122
- } catch {}
123
- throw error;
124
- }
125
- },
126
- async kill() {
127
- if (!closed) await writeFile(join(path, "cgroup.kill"), "1");
128
- },
129
- async close() {
130
- if (closed) return;
131
- clearInterval(monitor);
132
- await writeFile(join(path, "cgroup.kill"), "1");
133
- await waitForCgroupEmpty(path);
134
- await removeDescendantCgroups(path);
135
- await rmdir(path);
136
- await rm(healthMarker, { force: true }).catch(() => void 0);
137
- closed = true;
138
- }
139
- };
140
- }
141
- async function waitForCgroupEmpty(path) {
142
- const deadline = performance.now() + 1e4;
143
- while (true) {
144
- const events = await readFile(join(path, "cgroup.events"), "utf8");
145
- const populated = /^populated (\d+)/m.exec(events)?.[1];
146
- if (populated === void 0 || populated === "0") return;
147
- if (performance.now() >= deadline) throw diagnostics.SANDBOX_R0157({ message: `Timed out waiting for Sandbox cgroup ${path} to become empty; it remains populated. Retry session close after its descendants exit.` });
148
- await setTimeout$1(25);
149
- }
150
- }
151
- async function removeDescendantCgroups(path) {
152
- for (const entry of await readdir(path, { withFileTypes: true })) {
153
- if (!entry.isDirectory()) continue;
154
- const child = join(path, entry.name);
155
- await removeDescendantCgroups(child);
156
- await rmdir(child);
157
- }
158
- }
159
- //#endregion
160
14
  //#region src/internal/trusted-host.ts
161
15
  const baseEnvironmentKeys = [
162
16
  "ComSpec",
@@ -200,19 +54,15 @@ function createTrustedHostRuntime(options = {}) {
200
54
  return markBuiltInSandboxRuntime({
201
55
  name: "trusted-host",
202
56
  async prepare(input) {
203
- const resources = options.resources ? Object.freeze({ ...options.resources }) : void 0;
204
- if (resources) validateTrustedHostResources(resources);
205
57
  const { cwd, stateRoot } = await resolveTrustedHostInput(input, options);
206
58
  preparedInputs.set(input, {
207
59
  cwd,
208
- stateRoot,
209
- resources
60
+ stateRoot
210
61
  });
211
62
  return {
212
63
  cache: { state: "disposable" },
213
64
  environment: { env: {} },
214
65
  executionAuthority: trustedHostExecutionAuthority,
215
- ...resources ? { resources } : {},
216
66
  home: stateRoot ? { state: input.plan.state.map((state) => ({
217
67
  identity: createHash("sha256").update(JSON.stringify([
218
68
  stateRoot,
@@ -238,18 +88,12 @@ function createTrustedHostRuntime(options = {}) {
238
88
  };
239
89
  },
240
90
  async open(input, openOptions) {
241
- const prepared = preparedInputs.get(input);
242
- const resolved = prepared ?? await resolveTrustedHostInput(input, options);
243
- const resources = prepared ? prepared.resources : options.resources ? Object.freeze({ ...options.resources }) : void 0;
91
+ const resolved = preparedInputs.get(input) ?? await resolveTrustedHostInput(input, options);
244
92
  let initializedSession;
245
93
  const runtimeSession = await createSession({
246
94
  ...input,
247
95
  ...resolved.cwd ? { cwd: resolved.cwd } : {}
248
- }, {
249
- ...options,
250
- resources,
251
- stateRoot: resolved.stateRoot
252
- }, {
96
+ }, { stateRoot: resolved.stateRoot }, {
253
97
  abortSignal: openOptions?.signal,
254
98
  ...openOptions?.initialize ? { async initialize(session) {
255
99
  initializedSession = createSandboxSession(session, openOptions, resolved.cwd ? join(session.defaultWorkingDirectory, "workspace") : void 0);
@@ -313,7 +157,6 @@ async function createSession(input, options, createOptions) {
313
157
  }).catch(() => void 0)));
314
158
  await releases();
315
159
  },
316
- resources: options.resources,
317
160
  root,
318
161
  sessionId: createOptions.sessionId,
319
162
  workspace: input.cwd
@@ -488,11 +331,11 @@ async function resolveEnvironment(home, values) {
488
331
  for (const [name, resolveValue] of Object.entries(values)) env[name] = await resolveValue();
489
332
  return env;
490
333
  }
334
+ const sessionEnvironmentKey = "VITEHUB_SANDBOX_SESSION";
491
335
  async function createTrustedHostSession(options) {
492
336
  const workspace = join(options.root, "workspace");
493
337
  if (options.workspace) await symlink(options.workspace, workspace, "dir");
494
338
  else await mkdir(workspace, { recursive: true });
495
- const memory = options.resources ? await createSessionMemory(options.resources) : void 0;
496
339
  let destroyPromise;
497
340
  let closing = false;
498
341
  const processes = /* @__PURE__ */ new Set();
@@ -509,7 +352,6 @@ async function createTrustedHostSession(options) {
509
352
  closing = true;
510
353
  const cleanup = async () => {
511
354
  await this.stop();
512
- await memory?.close();
513
355
  try {
514
356
  await rm(options.root, {
515
357
  force: true,
@@ -588,9 +430,8 @@ async function createTrustedHostSession(options) {
588
430
  assertCommandEnvironment(runOptions.env);
589
431
  const cwd = await physicalSessionPath(options.root, runOptions.workingDirectory ?? this.defaultWorkingDirectory);
590
432
  runOptions.abortSignal?.throwIfAborted();
591
- await memory?.assertHealthy();
592
- if (closing) throw new Error("Trusted host Sandbox session is closing.");
593
- const child = (memory ? memory.spawn : spawn)(runOptions.command, {
433
+ if (closing) throw sandboxErrorDiagnostics.SANDBOX_TRUSTED_HOST_CLOSING();
434
+ const child = spawn(runOptions.command, {
594
435
  cwd,
595
436
  detached: process.platform !== "win32",
596
437
  env: {
@@ -598,9 +439,10 @@ async function createTrustedHostSession(options) {
598
439
  ...runOptions.env,
599
440
  INIT_CWD: cwd,
600
441
  OLDPWD: cwd,
601
- PWD: cwd
442
+ PWD: cwd,
443
+ [sessionEnvironmentKey]: options.root
602
444
  },
603
- shell: !memory
445
+ shell: true
604
446
  });
605
447
  processes.add(child);
606
448
  if (child.pid && process.platform !== "win32") processGroups.add(child.pid);
@@ -608,7 +450,7 @@ async function createTrustedHostSession(options) {
608
450
  processes.delete(child);
609
451
  if (child.pid && process.platform !== "win32" && !processGroupExists(child.pid)) processGroups.delete(child.pid);
610
452
  });
611
- return processHandle(child, runOptions.abortSignal, () => memory?.assertHealthy());
453
+ return processHandle(child, runOptions.abortSignal);
612
454
  },
613
455
  async stop() {
614
456
  const active = [...processes];
@@ -624,7 +466,6 @@ async function createTrustedHostSession(options) {
624
466
  }
625
467
  for (const pid of processGroups) signalProcessGroup(pid, "SIGKILL");
626
468
  if (process.platform === "win32") for (const child of active) signalProcessTree(child, "SIGKILL");
627
- await memory?.kill();
628
469
  let timedOut = false;
629
470
  let timeout;
630
471
  try {
@@ -637,7 +478,8 @@ async function createTrustedHostSession(options) {
637
478
  } finally {
638
479
  if (timeout) clearTimeout(timeout);
639
480
  }
640
- if (timedOut) throw new Error("Timed out waiting for trusted-host processes to exit after SIGKILL.");
481
+ if (timedOut) throw sandboxErrorDiagnostics.SANDBOX_TRUSTED_HOST_KILL_TIMED_OUT();
482
+ await stopMarkedProcesses(sessionEnvironmentKey, options.root);
641
483
  processes.clear();
642
484
  processGroups.clear();
643
485
  },
@@ -782,7 +624,7 @@ function rootRelativeFragment(path) {
782
624
  async function collect(stream) {
783
625
  return await new Response(stream).text();
784
626
  }
785
- function processHandle(child, abortSignal, afterExit) {
627
+ function processHandle(child, abortSignal) {
786
628
  let abortReason;
787
629
  let forceKillTimer;
788
630
  const abort = () => {
@@ -799,7 +641,7 @@ function processHandle(child, abortSignal, afterExit) {
799
641
  abortSignal?.removeEventListener("abort", abort);
800
642
  if (forceKillTimer) clearTimeout(forceKillTimer);
801
643
  if (abortReason) reject(abortReason);
802
- else Promise.resolve().then(afterExit).then(() => resolvePromise({ exitCode: code ?? 1 }), reject);
644
+ else resolvePromise({ exitCode: code ?? 1 });
803
645
  });
804
646
  });
805
647
  wait.catch(() => void 0);
@@ -1,16 +1,29 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
2
  import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
3
- import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
3
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
4
4
  import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
5
- import { t as listCommandFiles } from "./file-listing-DECFTdSl.js";
6
- import { i as resolveRemoteEnvironment, n as openRemoteSandbox, o as snapshotStream, r as remoteSandboxPlan, t as collectProcessOutput } from "./remote-1Jz2oUMK.js";
5
+ import { t as listCommandFiles } from "./file-listing-CHtRrfo1.js";
6
+ import { i as resolveRemoteEnvironment, n as openRemoteSandbox, r as remoteSandboxPlan, t as collectProcessOutput } from "./remote-70ZVZZlq.js";
7
+ import { n as killOnAbort } from "./abortable-CR01hzfi.js";
7
8
  import { randomUUID } from "node:crypto";
8
9
  import { posix } from "node:path";
9
10
  //#region src/vercel.ts
10
- var vercel_exports = /* @__PURE__ */ __exportAll({ createVercelRuntime: () => createVercelRuntime });
11
- const vercelSandboxPackage = "@vercel/sandbox";
11
+ var vercel_exports = /* @__PURE__ */ __exportAll({
12
+ createVercelRuntime: () => createVercelRuntime,
13
+ loadVercelSandbox: () => loadVercelSandbox
14
+ });
15
+ /** The signals that the Vercel Sandbox SDK sends by name. Other signals use their number. */
16
+ const vercelSignalNames = [
17
+ "SIGHUP",
18
+ "SIGINT",
19
+ "SIGQUIT",
20
+ "SIGKILL",
21
+ "SIGTERM",
22
+ "SIGCONT",
23
+ "SIGSTOP"
24
+ ];
12
25
  function createVercelRuntime(options = {}) {
13
- const runtime = options.runtime ?? "node24";
26
+ const runtime = options.source?.type === "snapshot" ? options.runtime : options.runtime ?? "node24";
14
27
  const executionAuthority = vercelExecutionAuthority(options.networkPolicy);
15
28
  return markBuiltInSandboxRuntime({
16
29
  name: "vercel",
@@ -24,7 +37,7 @@ function createVercelRuntime(options = {}) {
24
37
  const workspace = options.source ? "/vercel/sandbox" : "/workspace";
25
38
  const env = await resolveRemoteEnvironment(input, { workspace });
26
39
  const instance = await (options.create ?? await loadVercelSandbox())({
27
- runtime,
40
+ ...runtime ? { runtime } : {},
28
41
  persistent: false,
29
42
  signal: openOptions?.signal,
30
43
  timeout: options.timeout ?? 3e5,
@@ -87,10 +100,7 @@ function ownNetworkPolicyMember(value, key) {
87
100
  }
88
101
  async function loadVercelSandbox() {
89
102
  try {
90
- const { Sandbox } = await import(
91
- /* @vite-ignore */
92
- vercelSandboxPackage
93
- );
103
+ const { Sandbox } = await import("@vercel/sandbox");
94
104
  return async (options) => await Sandbox.create(options);
95
105
  } catch (error) {
96
106
  throw sandboxErrorDiagnostics.SANDBOX_R0142({ message: `[vitehub] The vercel Sandbox runtime requires @vercel/sandbox: ${error instanceof Error ? error.message : error}` });
@@ -101,10 +111,10 @@ function isMissingFile(error) {
101
111
  }
102
112
  function createVercelSession(id, instance, baseEnv, ports, workspace) {
103
113
  let destroyPromise;
104
- const run = async (options) => {
114
+ const startCommand = (options) => {
105
115
  options.abortSignal?.throwIfAborted();
106
- const process = await instance.runCommand({
107
- args: ["-lc", options.command],
116
+ return instance.runCommand({
117
+ args: ["-c", options.command],
108
118
  cmd: "sh",
109
119
  cwd: options.workingDirectory ?? workspace,
110
120
  detached: true,
@@ -112,12 +122,16 @@ function createVercelSession(id, instance, baseEnv, ports, workspace) {
112
122
  ...baseEnv,
113
123
  ...options.env
114
124
  },
115
- signal: options.abortSignal
125
+ signal: options.abortSignal,
126
+ ...options.stdin ? { stdin: true } : {}
116
127
  });
128
+ };
129
+ const run = async (options) => {
130
+ const process = await startCommand(options);
117
131
  let abort;
118
132
  const aborted = new Promise((_, reject) => {
119
133
  abort = () => {
120
- process.kill().catch(() => void 0);
134
+ process.kill("SIGKILL").catch(() => void 0);
121
135
  reject(options.abortSignal.reason);
122
136
  };
123
137
  options.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -235,18 +249,8 @@ function createVercelSession(id, instance, baseEnv, ports, workspace) {
235
249
  },
236
250
  run,
237
251
  async spawn(options) {
238
- options.abortSignal?.throwIfAborted();
239
- return vercelProcess(await instance.runCommand({
240
- args: ["-lc", options.command],
241
- cmd: "sh",
242
- cwd: options.workingDirectory ?? workspace,
243
- detached: true,
244
- env: {
245
- ...baseEnv,
246
- ...options.env
247
- },
248
- signal: options.abortSignal
249
- }));
252
+ const process = await startCommand(options);
253
+ return killOnAbort(vercelProcess(process, options.stdin), options.abortSignal);
250
254
  },
251
255
  async stop() {},
252
256
  async writeBinaryFile({ abortSignal, content, path }) {
@@ -262,18 +266,87 @@ function createVercelSession(id, instance, baseEnv, ports, workspace) {
262
266
  }
263
267
  };
264
268
  }
265
- function vercelProcess(process) {
269
+ function vercelProcess(process, stdin) {
266
270
  const wait = process.wait();
267
271
  return {
268
- stderr: snapshotStream(async () => await process.stderr()),
269
- stdout: snapshotStream(async () => await process.stdout()),
270
- async kill() {
271
- await process.kill();
272
+ ...streamLogs(process),
273
+ ...stdin ? { stdin: new WritableStream({
274
+ abort: async () => await process.closeStdin(),
275
+ close: async () => await process.closeStdin(),
276
+ write: async (chunk) => await process.writeStdin(chunk)
277
+ }) } : {},
278
+ async kill(signal) {
279
+ await process.kill(vercelSignal(signal));
272
280
  },
273
281
  async wait() {
274
282
  return await wait;
275
283
  }
276
284
  };
277
285
  }
286
+ /** Bounds each channel independently so an unread channel cannot stall its sibling. */
287
+ function streamLogs(command) {
288
+ const bufferLimit = 1048576;
289
+ const encoder = new TextEncoder();
290
+ const abort = new AbortController();
291
+ const iterator = command.logs({ signal: abort.signal })[Symbol.asyncIterator]();
292
+ const open = /* @__PURE__ */ new Map();
293
+ let stopped = false;
294
+ const stop = async () => {
295
+ if (stopped) return;
296
+ stopped = true;
297
+ abort.abort();
298
+ try {
299
+ await iterator.return?.();
300
+ } catch {}
301
+ };
302
+ const stream = (name) => new ReadableStream({
303
+ cancel() {
304
+ open.delete(name);
305
+ if (open.size === 0) return stop();
306
+ },
307
+ start(controller) {
308
+ open.set(name, controller);
309
+ }
310
+ }, new ByteLengthQueuingStrategy({ highWaterMark: bufferLimit }));
311
+ const output = {
312
+ stderr: stream("stderr"),
313
+ stdout: stream("stdout")
314
+ };
315
+ (async () => {
316
+ try {
317
+ while (open.size > 0) {
318
+ const entry = await iterator.next();
319
+ if (entry.done) break;
320
+ const line = entry.value;
321
+ const controller = open.get(line.stream);
322
+ if (!controller || line.data.length === 0) continue;
323
+ const chunk = new Uint8Array(Math.min(line.data.length * 3, controller.desiredSize ?? 0));
324
+ const { read, written } = encoder.encodeInto(line.data, chunk);
325
+ if (read < line.data.length) {
326
+ controller.error(sandboxErrorDiagnostics.SANDBOX_R0159({ message: `Vercel ${line.stream} exceeded the ${bufferLimit}-byte output buffer limit. Consume both streams concurrently or cancel unused output.` }));
327
+ open.delete(line.stream);
328
+ } else controller.enqueue(written === chunk.byteLength ? chunk : chunk.slice(0, written));
329
+ }
330
+ for (const controller of open.values()) controller.close();
331
+ } catch (error) {
332
+ for (const controller of open.values()) controller.error(error);
333
+ } finally {
334
+ open.clear();
335
+ await stop();
336
+ }
337
+ })();
338
+ return output;
339
+ }
340
+ function vercelSignal(signal) {
341
+ if (signal === void 0) return void 0;
342
+ if (/^\d+$/.test(signal)) return Number(signal);
343
+ const name = `SIG${signal.toUpperCase().replace(/^SIG/, "")}`;
344
+ const known = vercelSignalNames.find((value) => value === name);
345
+ if (!known) throw sandboxErrorDiagnostics.SANDBOX_R0165({
346
+ runtime: "Vercel",
347
+ signal: String(signal)
348
+ });
349
+ return known;
350
+ }
278
351
  //#endregion
279
- export { vercel_exports as n, createVercelRuntime as t };
352
+ export { loadVercelSandbox as n, vercel_exports as r, createVercelRuntime as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/sandbox",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Portable, isolated Sandboxes for ViteHub Agents, and Sandbox Tasks that run named package projects in them.",
5
5
  "keywords": [
6
6
  "agent",
@@ -109,22 +109,26 @@
109
109
  }
110
110
  },
111
111
  "dependencies": {
112
- "@vite-hub/runtime": "0.1.0",
113
- "esbuild": "^0.28.2",
112
+ "@vite-hub/runtime": "0.3.0",
114
113
  "local-pkg": "^1.2.1",
115
114
  "mlly": "^1.8.2",
116
- "nostics": "1.3.0",
115
+ "nostics": "1.4.0",
117
116
  "pathe": "^2.0.3",
117
+ "picomatch": "^4.0.7",
118
118
  "semver": "^7.8.5",
119
119
  "unimport": "^6.5.0",
120
120
  "yaml": "^2.9.1"
121
121
  },
122
122
  "devDependencies": {
123
- "@cloudflare/sandbox": "^0.12.10",
123
+ "@cloudflare/sandbox": "^1.0.3",
124
124
  "@types/node": "^24.19.1",
125
+ "@types/picomatch": "^4.0.3",
125
126
  "@types/semver": "^7.8.0",
126
127
  "@types/ssh2": "^1.15.6",
127
- "@vercel/sandbox": "^3.5.1",
128
+ "@vercel/sandbox": "^3.9.1 || ^4.0.0",
129
+ "@vite-hub/internal": "0.0.1",
130
+ "esbuild": "^0.28.2",
131
+ "miniflare": "4.20260730.0",
128
132
  "ofetch": "^1.5.1",
129
133
  "publint": "^0.3.25",
130
134
  "rollup": "^4.64.0",
@@ -133,13 +137,12 @@
133
137
  "vite": "^8.2.2",
134
138
  "vite-plus": "^0.3.3",
135
139
  "vitest": "^4.1.11",
136
- "zod": "^4.6.7",
137
- "@vite-hub/internal": "0.0.1"
140
+ "zod": "^4.6.7"
138
141
  },
139
142
  "peerDependencies": {
140
- "@cloudflare/sandbox": "^0.12.10",
143
+ "@cloudflare/sandbox": "^1.0.3",
141
144
  "ssh2": "^1.17.0",
142
- "@vercel/sandbox": "^3.5.1",
145
+ "@vercel/sandbox": "^3.9.1 || ^4.0.0",
143
146
  "typescript": "^5.8.0 || ^6.0.0",
144
147
  "vite": ">=8.0.0"
145
148
  },
@@ -161,12 +164,12 @@
161
164
  }
162
165
  },
163
166
  "engines": {
164
- "node": ">=24.0.0"
167
+ "node": ">=22.18.0"
165
168
  },
166
169
  "scripts": {
167
170
  "build": "vp pack",
168
171
  "dev": "vp pack --watch",
169
172
  "typecheck": "vp run --cache -t @vite-hub/sandbox#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
170
- "test": "vp run -t @vite-hub/sandbox#build && vp test"
173
+ "test": "vp run --cache -t @vite-hub/sandbox#build && vp test"
171
174
  }
172
175
  }