@vite-hub/sandbox 0.0.3 → 0.1.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 (60) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +388 -22
  3. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  4. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  5. package/dist/crabbox-BFCdf41h.js +1106 -0
  6. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  7. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  8. package/dist/file-listing-DECFTdSl.js +26 -0
  9. package/dist/file-lock-CxyVl4Cv.js +73 -0
  10. package/dist/index-CXej1Bt0.d.ts +519 -0
  11. package/dist/index.d.ts +2 -65
  12. package/dist/index.js +277 -1172
  13. package/dist/internal/cloudflare.d.ts +4 -0
  14. package/dist/internal/cloudflare.js +16 -0
  15. package/dist/internal/host-toolchain.d.ts +22 -0
  16. package/dist/internal/host-toolchain.js +97 -0
  17. package/dist/internal/vercel.d.ts +4 -0
  18. package/dist/internal/vercel.js +16 -0
  19. package/dist/module-types-BfyRBaiP.js +7 -0
  20. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  21. package/dist/remote-1Jz2oUMK.js +247 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  23. package/dist/runtime-DHp6ImeP.js +32 -0
  24. package/dist/runtime-type-DrmrW5m5.js +42 -0
  25. package/dist/session-DD0S1PDC.js +337 -0
  26. package/dist/shell-quote-Q3u3plif.js +6 -0
  27. package/dist/ssh.d.ts +55 -0
  28. package/dist/ssh.js +219 -0
  29. package/dist/task/index.d.ts +67 -0
  30. package/dist/task/index.js +1523 -0
  31. package/dist/task/runtime/empty-registry.d.ts +6 -0
  32. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  33. package/dist/task/runtime/provider-loader.d.ts +20 -0
  34. package/dist/task/runtime/provider-loader.js +19 -0
  35. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  36. package/dist/task/runtime/providers/cloudflare.js +26 -0
  37. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  38. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  39. package/dist/task/runtime/state.d.ts +24 -0
  40. package/dist/task/runtime/state.js +73 -0
  41. package/dist/task/vite.d.ts +360 -0
  42. package/dist/task/vite.js +3643 -0
  43. package/dist/toolchain-BUVXtQ2m.js +527 -0
  44. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  45. package/dist/vercel-Jtxa9TJx.js +279 -0
  46. package/package.json +103 -39
  47. package/dist/cloudflare-env-2NctU8i7.js +0 -12
  48. package/dist/module-types-DfXe133f.d.ts +0 -91
  49. package/dist/module-types-Dj1MFmHT.js +0 -7
  50. package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
  51. package/dist/runtime/empty-registry.d.ts +0 -6
  52. package/dist/runtime/provider-loader.d.ts +0 -2
  53. package/dist/runtime/provider-loader.js +0 -15
  54. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  55. package/dist/runtime/providers/cloudflare.js +0 -25
  56. package/dist/runtime/providers/vercel.d.ts +0 -112
  57. package/dist/runtime/state.d.ts +0 -17
  58. package/dist/runtime/state.js +0 -21
  59. package/dist/vite.d.ts +0 -24
  60. package/dist/vite.js +0 -2367
@@ -0,0 +1,872 @@
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";
5
+ 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 { basename, delimiter, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
8
+ import { defineDiagnostics } from "nostics";
9
+ import { execFile, spawn } from "node:child_process";
10
+ import { tmpdir } from "node:os";
11
+ import { promisify } from "node:util";
12
+ import { chmodSync, constants, rmSync, writeFileSync } from "node:fs";
13
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
+ 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
+ //#region src/internal/trusted-host.ts
161
+ const baseEnvironmentKeys = [
162
+ "ComSpec",
163
+ "LANG",
164
+ "LC_ALL",
165
+ "LOGNAME",
166
+ "Path",
167
+ "PATH",
168
+ "PATHEXT",
169
+ "SHELL",
170
+ "SystemRoot",
171
+ "TEMP",
172
+ "TERM",
173
+ "TMP",
174
+ "TMPDIR",
175
+ "USER"
176
+ ];
177
+ const runtimeEnvironmentKeys = /* @__PURE__ */ new Set([
178
+ "CODEX_HOME",
179
+ "HOME",
180
+ "INIT_CWD",
181
+ "OLDPWD",
182
+ "PWD",
183
+ "XDG_CACHE_HOME",
184
+ "XDG_CONFIG_HOME",
185
+ "XDG_STATE_HOME"
186
+ ]);
187
+ const trustedHostExecutionAuthority = {
188
+ credentials: "unknown",
189
+ environment: "selected",
190
+ filesystem: {
191
+ access: "read-write",
192
+ scope: "host"
193
+ },
194
+ isolation: "none",
195
+ network: "unrestricted",
196
+ processes: "arbitrary"
197
+ };
198
+ function createTrustedHostRuntime(options = {}) {
199
+ const preparedInputs = /* @__PURE__ */ new WeakMap();
200
+ return markBuiltInSandboxRuntime({
201
+ name: "trusted-host",
202
+ async prepare(input) {
203
+ const resources = options.resources ? Object.freeze({ ...options.resources }) : void 0;
204
+ if (resources) validateTrustedHostResources(resources);
205
+ const { cwd, stateRoot } = await resolveTrustedHostInput(input, options);
206
+ preparedInputs.set(input, {
207
+ cwd,
208
+ stateRoot,
209
+ resources
210
+ });
211
+ return {
212
+ cache: { state: "disposable" },
213
+ environment: { env: {} },
214
+ executionAuthority: trustedHostExecutionAuthority,
215
+ ...resources ? { resources } : {},
216
+ home: stateRoot ? { state: input.plan.state.map((state) => ({
217
+ identity: createHash("sha256").update(JSON.stringify([
218
+ stateRoot,
219
+ state.key,
220
+ state.path
221
+ ])).digest("hex"),
222
+ path: state.path
223
+ })) } : void 0,
224
+ identity: input.identity,
225
+ requirements: sandboxRequirementPlan(input.requirements),
226
+ runtime: "trusted-host",
227
+ workspace: cwd ? {
228
+ path: cwd,
229
+ state: "authoritative",
230
+ workDir: "workspace"
231
+ } : input.checkout ? {
232
+ state: "disposable",
233
+ workDir: "."
234
+ } : {
235
+ state: "disposable",
236
+ workDir: "."
237
+ }
238
+ };
239
+ },
240
+ 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;
244
+ let initializedSession;
245
+ const runtimeSession = await createSession({
246
+ ...input,
247
+ ...resolved.cwd ? { cwd: resolved.cwd } : {}
248
+ }, {
249
+ ...options,
250
+ resources,
251
+ stateRoot: resolved.stateRoot
252
+ }, {
253
+ abortSignal: openOptions?.signal,
254
+ ...openOptions?.initialize ? { async initialize(session) {
255
+ initializedSession = createSandboxSession(session, openOptions, resolved.cwd ? join(session.defaultWorkingDirectory, "workspace") : void 0);
256
+ await openOptions.initialize(initializedSession, { signal: openOptions.signal });
257
+ } } : {},
258
+ sessionId: openOptions?.id
259
+ });
260
+ return initializedSession ?? createSandboxSession(runtimeSession, openOptions, resolved.cwd ? join(runtimeSession.defaultWorkingDirectory, "workspace") : void 0);
261
+ }
262
+ });
263
+ }
264
+ async function resolveTrustedHostInput(input, options) {
265
+ const requestedCwd = input.cwd ? resolve(input.cwd) : void 0;
266
+ if (requestedCwd) await assertDirectory(requestedCwd, "workspace");
267
+ const cwd = requestedCwd ? await realpath(requestedCwd) : void 0;
268
+ const configuredStateRoot = options.stateRoot;
269
+ if (input.plan.state.length && (!configuredStateRoot || !isAbsolute(configuredStateRoot))) throw sandboxErrorDiagnostics.SANDBOX_R0130({ message: "[vitehub] The trusted-host runtime requires stateRoot to be an absolute path when sandbox.home.state is declared." });
270
+ const stateRoot = configuredStateRoot ? await canonicalFuturePath(configuredStateRoot) : void 0;
271
+ if (input.plan.state.length && stateRoot && dirname(stateRoot) === stateRoot) throw sandboxErrorDiagnostics.SANDBOX_R0131({ message: "[vitehub] Sandbox stateRoot must be a dedicated directory, not the filesystem root." });
272
+ if (cwd && input.plan.state.length && stateRoot) {
273
+ if (pathsOverlap(cwd, stateRoot)) throw sandboxErrorDiagnostics.SANDBOX_R0132({ message: "[vitehub] Sandbox stateRoot must be outside the authoritative workspace." });
274
+ }
275
+ return {
276
+ cwd,
277
+ stateRoot
278
+ };
279
+ }
280
+ async function createSession(input, options, createOptions) {
281
+ const releases = await acquireStateLeases(input.plan.state, options.stateRoot, createOptions.abortSignal);
282
+ let root;
283
+ let session;
284
+ const initializedState = [];
285
+ let initializationFailed = false;
286
+ try {
287
+ root = await realpath(await mkdtemp(join(tmpdir(), "vitehub-sandbox-")));
288
+ const home = join(root, "home");
289
+ await mkdir(home, { mode: 448 });
290
+ const states = await prepareState(input.plan.state, options.stateRoot);
291
+ const files = await resolveFiles(input.plan.files);
292
+ const env = await resolveEnvironment(home, input.plan.env);
293
+ await materializeState(home, states, initializedState);
294
+ await materializeFiles(home, files);
295
+ const checkout = input.checkout ? join(root, "workspace") : void 0;
296
+ if (input.checkout && checkout) await materializeGitCheckout(input.checkout, checkout, {
297
+ abortSignal: createOptions.abortSignal,
298
+ async run(args) {
299
+ return { stdout: (await promisify(execFile)("git", [...args], {
300
+ env,
301
+ signal: createOptions.abortSignal
302
+ })).stdout };
303
+ }
304
+ });
305
+ const toolchain = input.toolchain ? await provisionTrustedHostToolchain(input.toolchain, checkout ?? input.cwd ?? root, options.stateRoot, env, createOptions.abortSignal) : void 0;
306
+ session = await createTrustedHostSession({
307
+ env,
308
+ home,
309
+ async release() {
310
+ if (initializationFailed) await Promise.all(initializedState.map((path) => rm(path, {
311
+ force: true,
312
+ recursive: true
313
+ }).catch(() => void 0)));
314
+ await releases();
315
+ },
316
+ resources: options.resources,
317
+ root,
318
+ sessionId: createOptions.sessionId,
319
+ workspace: input.cwd
320
+ });
321
+ session.toolchain = toolchain;
322
+ await validateRequirements(input.requirements, env, checkout ?? input.cwd ?? root, createOptions.abortSignal, sandboxRequirementSecrets([
323
+ ...Object.keys(input.plan.env).map((name) => env[name]),
324
+ ...files.map((file) => file.contents),
325
+ ...states.flatMap((state) => state.seed.map((file) => file.contents))
326
+ ]), input.plan.state.length === 0);
327
+ await createOptions.initialize?.(session);
328
+ return session;
329
+ } catch (error) {
330
+ if (session) {
331
+ initializationFailed = true;
332
+ try {
333
+ await session.destroy?.();
334
+ } catch {
335
+ retrySessionDestroy(session);
336
+ }
337
+ } else {
338
+ await Promise.all(initializedState.map((path) => rm(path, {
339
+ force: true,
340
+ recursive: true
341
+ }).catch(() => void 0)));
342
+ if (root) await rm(root, {
343
+ force: true,
344
+ recursive: true
345
+ }).catch(() => void 0);
346
+ await releases();
347
+ }
348
+ throw error;
349
+ }
350
+ }
351
+ async function retrySessionDestroy(session) {
352
+ while (true) {
353
+ await new Promise((resolvePromise) => {
354
+ setTimeout(resolvePromise, 250).unref?.();
355
+ });
356
+ try {
357
+ await session.destroy?.();
358
+ return;
359
+ } catch {}
360
+ }
361
+ }
362
+ async function provisionTrustedHostToolchain(toolchain, directory, stateRoot, env, abortSignal) {
363
+ const { hostToolchainCacheRoot, provisionHostToolchain, toolchainPath } = await import("./internal/host-toolchain.js");
364
+ const provisioned = await provisionHostToolchain(toolchain, directory, {
365
+ abortSignal,
366
+ cacheRoot: hostToolchainCacheRoot(stateRoot),
367
+ env
368
+ });
369
+ env.PATH = toolchainPath(provisioned, env.PATH);
370
+ return provisioned;
371
+ }
372
+ async function prepareState(states, stateRoot) {
373
+ if (!states.length) return [];
374
+ const prepared = [];
375
+ for (const state of states) {
376
+ const persistent = statePath(stateRoot, state.key);
377
+ const existing = await stat(persistent).catch((error) => {
378
+ if (error.code === "ENOENT") return void 0;
379
+ throw error;
380
+ });
381
+ if (existing && !existing.isDirectory()) throw sandboxErrorDiagnostics.SANDBOX_R0133({ message: `[vitehub] Sandbox state is not a directory: ${state.key}` });
382
+ prepared.push({
383
+ initialize: !existing,
384
+ path: state.path,
385
+ persistent,
386
+ projections: state.projections,
387
+ seed: existing ? [] : await resolveFiles(state.seed)
388
+ });
389
+ }
390
+ return prepared;
391
+ }
392
+ async function materializeState(home, states, initialized) {
393
+ for (const state of states) {
394
+ if (state.initialize) {
395
+ const staging = `${state.persistent}.init-${randomUUID()}`;
396
+ try {
397
+ await mkdir(staging, { mode: 448 });
398
+ await materializeFiles(staging, state.seed);
399
+ await rename(staging, state.persistent);
400
+ initialized.push(state.persistent);
401
+ } finally {
402
+ await rm(staging, {
403
+ force: true,
404
+ recursive: true
405
+ }).catch(() => void 0);
406
+ }
407
+ }
408
+ await reconcileProjections(state);
409
+ await chmod(state.persistent, 448);
410
+ const target = join(home, ...state.path.split("/"));
411
+ await mkdir(dirname(target), {
412
+ mode: 448,
413
+ recursive: true
414
+ });
415
+ await symlink(state.persistent, target, "dir");
416
+ }
417
+ }
418
+ async function reconcileProjections(state) {
419
+ const manifest = `${state.persistent}.projections`;
420
+ const previous = await readFile(manifest, "utf8").then((value) => {
421
+ const parsed = JSON.parse(value);
422
+ if (!Array.isArray(parsed) || parsed.some((path) => typeof path !== "string")) throw sandboxErrorDiagnostics.SANDBOX_R0134({ message: `[vitehub] Sandbox projection manifest is invalid: ${state.path}` });
423
+ return parsed;
424
+ }, (error) => {
425
+ if (error.code === "ENOENT") return [];
426
+ throw error;
427
+ });
428
+ const persistent = await realpath(state.persistent);
429
+ for (const path of state.projections) {
430
+ const parent = await canonicalFuturePath(dirname(join(state.persistent, ...path.split("/"))));
431
+ const relativeParent = relative(persistent, parent);
432
+ if (relativeParent === ".." || relativeParent.startsWith(`..${sep}`) || isAbsolute(relativeParent)) throw sandboxErrorDiagnostics.SANDBOX_R0135({ message: `[vitehub] Sandbox projected path escapes writable state: ${state.path}/${path}` });
433
+ }
434
+ const current = new Set(state.projections);
435
+ for (const path of previous) {
436
+ if (current.has(path)) continue;
437
+ const target = join(state.persistent, ...path.split("/"));
438
+ const parent = await realpath(dirname(target)).catch((error) => {
439
+ if (error.code === "ENOENT") return void 0;
440
+ throw error;
441
+ });
442
+ if (!parent) continue;
443
+ const relativeParent = relative(persistent, parent);
444
+ if (relativeParent === ".." || relativeParent.startsWith(`..${sep}`) || isAbsolute(relativeParent)) throw sandboxErrorDiagnostics.SANDBOX_R0136({ message: `[vitehub] Sandbox projected path escapes writable state: ${state.path}/${path}` });
445
+ await rm(target, {
446
+ force: true,
447
+ recursive: true
448
+ });
449
+ }
450
+ await writePrivateFile(manifest, new TextEncoder().encode(JSON.stringify(state.projections)));
451
+ }
452
+ async function resolveFiles(files) {
453
+ return await Promise.all(Object.entries(files).map(async ([path, input]) => ({
454
+ contents: await input.resolve(),
455
+ path
456
+ })));
457
+ }
458
+ async function materializeFiles(root, files) {
459
+ for (const file of files) await writePrivateFile(join(root, ...file.path.split("/")), file.contents);
460
+ }
461
+ async function writePrivateFile(path, contents) {
462
+ const directory = dirname(path);
463
+ await mkdir(directory, {
464
+ mode: 448,
465
+ recursive: true
466
+ });
467
+ const temporary = join(directory, `.vitehub-${randomUUID()}`);
468
+ try {
469
+ await writeFile(temporary, contents, { mode: 384 });
470
+ await rm(path, {
471
+ force: true,
472
+ recursive: true
473
+ });
474
+ await rename(temporary, path);
475
+ await chmod(path, 384);
476
+ } finally {
477
+ await rm(temporary, { force: true }).catch(() => void 0);
478
+ }
479
+ }
480
+ async function resolveEnvironment(home, values) {
481
+ const env = Object.fromEntries(baseEnvironmentKeys.map((name) => [name, process.env[name]]).filter((entry) => entry[1] !== void 0));
482
+ Object.assign(env, {
483
+ HOME: home,
484
+ XDG_CACHE_HOME: join(home, ".cache"),
485
+ XDG_CONFIG_HOME: join(home, ".config"),
486
+ XDG_STATE_HOME: join(home, ".local", "state")
487
+ });
488
+ for (const [name, resolveValue] of Object.entries(values)) env[name] = await resolveValue();
489
+ return env;
490
+ }
491
+ async function createTrustedHostSession(options) {
492
+ const workspace = join(options.root, "workspace");
493
+ if (options.workspace) await symlink(options.workspace, workspace, "dir");
494
+ else await mkdir(workspace, { recursive: true });
495
+ const memory = options.resources ? await createSessionMemory(options.resources) : void 0;
496
+ let destroyPromise;
497
+ let closing = false;
498
+ const processes = /* @__PURE__ */ new Set();
499
+ const processGroups = /* @__PURE__ */ new Set();
500
+ return {
501
+ defaultWorkingDirectory: options.workspace ? options.root : workspace,
502
+ env: options.env,
503
+ home: options.home,
504
+ id: options.sessionId || randomUUID(),
505
+ ports: [0],
506
+ processes,
507
+ root: options.root,
508
+ async destroy() {
509
+ closing = true;
510
+ const cleanup = async () => {
511
+ await this.stop();
512
+ await memory?.close();
513
+ try {
514
+ await rm(options.root, {
515
+ force: true,
516
+ recursive: true
517
+ });
518
+ } finally {
519
+ await options.release();
520
+ }
521
+ };
522
+ const attempt = destroyPromise ?? cleanup();
523
+ if (!destroyPromise) destroyPromise = attempt;
524
+ try {
525
+ await attempt;
526
+ } catch (error) {
527
+ if (destroyPromise === attempt) destroyPromise = void 0;
528
+ throw error;
529
+ }
530
+ },
531
+ async getPortUrl({ port, protocol = "http" }) {
532
+ return `${protocol}://127.0.0.1:${port}`;
533
+ },
534
+ async existsFile({ path }) {
535
+ return await lstat(resolveSessionPath(options.root, path)).then(() => true, (error) => {
536
+ if (error.code === "ENOENT") return false;
537
+ throw error;
538
+ });
539
+ },
540
+ async listFiles({ path, recursive = false }) {
541
+ const root = resolveSessionPath(options.root, path);
542
+ const entries = [];
543
+ await visit(root, path);
544
+ return entries.sort((left, right) => left.path.localeCompare(right.path));
545
+ async function visit(directory, logicalDirectory) {
546
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
547
+ const physicalPath = join(directory, entry.name);
548
+ const logicalPath = posix.join(logicalDirectory, entry.name);
549
+ const item = await lstat(physicalPath);
550
+ entries.push({
551
+ path: logicalPath,
552
+ size: entry.isFile() ? item.size : void 0,
553
+ type: entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "file"
554
+ });
555
+ if (recursive && entry.isDirectory()) await visit(physicalPath, logicalPath);
556
+ }
557
+ }
558
+ },
559
+ async makeDirectory({ path, recursive = false }) {
560
+ await mkdir(resolveSessionPath(options.root, path), { recursive });
561
+ },
562
+ async moveFile({ destination, source }) {
563
+ const target = resolveSessionPath(options.root, destination);
564
+ await mkdir(dirname(target), { recursive: true });
565
+ await rename(resolveSessionPath(options.root, source), target);
566
+ },
567
+ async readBinaryFile({ path }) {
568
+ return await readFile(resolveSessionPath(options.root, path)).catch((error) => {
569
+ if (error.code === "ENOENT") return null;
570
+ throw error;
571
+ });
572
+ },
573
+ async run(runOptions) {
574
+ const child = await this.spawn(runOptions);
575
+ const [stdout, stderr, { exitCode }] = await Promise.all([
576
+ collect(child.stdout),
577
+ collect(child.stderr),
578
+ child.wait()
579
+ ]);
580
+ return {
581
+ exitCode,
582
+ stderr,
583
+ stdout
584
+ };
585
+ },
586
+ async spawn(runOptions) {
587
+ runOptions.abortSignal?.throwIfAborted();
588
+ assertCommandEnvironment(runOptions.env);
589
+ const cwd = await physicalSessionPath(options.root, runOptions.workingDirectory ?? this.defaultWorkingDirectory);
590
+ 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, {
594
+ cwd,
595
+ detached: process.platform !== "win32",
596
+ env: {
597
+ ...options.env,
598
+ ...runOptions.env,
599
+ INIT_CWD: cwd,
600
+ OLDPWD: cwd,
601
+ PWD: cwd
602
+ },
603
+ shell: !memory
604
+ });
605
+ processes.add(child);
606
+ if (child.pid && process.platform !== "win32") processGroups.add(child.pid);
607
+ child.once("close", () => {
608
+ processes.delete(child);
609
+ if (child.pid && process.platform !== "win32" && !processGroupExists(child.pid)) processGroups.delete(child.pid);
610
+ });
611
+ return processHandle(child, runOptions.abortSignal, () => memory?.assertHealthy());
612
+ },
613
+ async stop() {
614
+ const active = [...processes];
615
+ for (const pid of processGroups) signalProcessGroup(pid, "SIGTERM");
616
+ if (process.platform === "win32") for (const child of active) signalProcessTree(child, "SIGTERM");
617
+ let graceTimeout;
618
+ try {
619
+ await Promise.race([Promise.all(active.map(waitForExit)), new Promise((resolvePromise) => {
620
+ graceTimeout = setTimeout(resolvePromise, 250);
621
+ })]);
622
+ } finally {
623
+ if (graceTimeout) clearTimeout(graceTimeout);
624
+ }
625
+ for (const pid of processGroups) signalProcessGroup(pid, "SIGKILL");
626
+ if (process.platform === "win32") for (const child of active) signalProcessTree(child, "SIGKILL");
627
+ await memory?.kill();
628
+ let timedOut = false;
629
+ let timeout;
630
+ try {
631
+ await Promise.race([Promise.all(active.map(waitForExit)), new Promise((resolvePromise) => {
632
+ timeout = setTimeout(() => {
633
+ timedOut = true;
634
+ resolvePromise();
635
+ }, 1e4);
636
+ })]);
637
+ } finally {
638
+ if (timeout) clearTimeout(timeout);
639
+ }
640
+ if (timedOut) throw new Error("Timed out waiting for trusted-host processes to exit after SIGKILL.");
641
+ processes.clear();
642
+ processGroups.clear();
643
+ },
644
+ async removeFile({ path, recursive = false }) {
645
+ const target = resolveSessionPath(options.root, path);
646
+ if (recursive) {
647
+ await rm(target, {
648
+ force: true,
649
+ recursive: true
650
+ });
651
+ return;
652
+ }
653
+ const item = await lstat(target).catch((error) => {
654
+ if (error.code === "ENOENT") return void 0;
655
+ throw error;
656
+ });
657
+ if (!item) return;
658
+ if (item.isDirectory() && !item.isSymbolicLink()) await rmdir(target);
659
+ else await rm(target, { force: true });
660
+ },
661
+ async writeBinaryFile({ content, path }) {
662
+ const target = resolveSessionPath(options.root, path);
663
+ await mkdir(dirname(target), { recursive: true });
664
+ await writeFile(target, content);
665
+ }
666
+ };
667
+ }
668
+ function assertCommandEnvironment(env) {
669
+ const name = Object.keys(env || {}).find((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name));
670
+ if (name) throw sandboxErrorDiagnostics.SANDBOX_R0112({ message: `[vitehub] Invalid Sandbox environment variable: ${name}` });
671
+ const reservedName = Object.keys(env || {}).find((name) => runtimeEnvironmentKeys.has(name));
672
+ if (reservedName) throw sandboxErrorDiagnostics.SANDBOX_R0137({ message: `[vitehub] Sandbox commands cannot override ${reservedName}.` });
673
+ }
674
+ async function validateRequirements(requirements, env, cwd, abortSignal, secrets, includeDiagnosticOutput) {
675
+ for (const requirement of requirements) {
676
+ const executable = await findExecutable(requirement.command, env.PATH || env.Path, env.PATHEXT, cwd);
677
+ if (!executable) throw sandboxRequirementError(requirement, { message: `${requirement.command} is not on PATH.` }, secrets, requirement.timeout, includeDiagnosticOutput);
678
+ if (!requirement.args.length) continue;
679
+ const timeout = requirement.timeout ?? 1e4;
680
+ let result;
681
+ try {
682
+ const handle = processHandle(spawn(executable, requirement.args, {
683
+ cwd,
684
+ detached: process.platform !== "win32",
685
+ env,
686
+ shell: isWindowsCommandShim(executable)
687
+ }), sandboxRequirementSignal({
688
+ ...requirement,
689
+ timeout
690
+ }, abortSignal));
691
+ const [stderr, stdout, { exitCode }] = await Promise.all([
692
+ collectSandboxRequirementOutput(handle.stderr, secrets),
693
+ collectSandboxRequirementOutput(handle.stdout, secrets),
694
+ handle.wait()
695
+ ]);
696
+ result = {
697
+ exitCode,
698
+ stderr,
699
+ stdout
700
+ };
701
+ } catch (cause) {
702
+ if (abortSignal?.aborted) throw abortSignal.reason;
703
+ throw sandboxRequirementError(requirement, cause, secrets, timeout, includeDiagnosticOutput);
704
+ }
705
+ if (result.exitCode !== 0) throw sandboxRequirementError(requirement, result, secrets, timeout, includeDiagnosticOutput);
706
+ }
707
+ }
708
+ async function acquireStateLeases(states, stateRoot, abortSignal) {
709
+ if (!states.length) return async () => {};
710
+ await ensureStateRoot(stateRoot);
711
+ const paths = [...new Set(states.map((state) => statePath(stateRoot, state.key)))].sort();
712
+ const releases = [];
713
+ try {
714
+ for (const path of paths) releases.push(await acquireFileLock(`${path}.lock`, abortSignal));
715
+ } catch (error) {
716
+ for (const release of releases.reverse()) await release();
717
+ throw error;
718
+ }
719
+ return async () => {
720
+ for (const release of releases.reverse()) await release();
721
+ };
722
+ }
723
+ function statePath(root, key) {
724
+ return join(resolve(root), createHash("sha256").update(key).digest("hex"));
725
+ }
726
+ async function assertDirectory(path, label) {
727
+ if (!(await stat(path).catch(() => void 0))?.isDirectory()) throw sandboxErrorDiagnostics.SANDBOX_R0138({ message: `[vitehub] Sandbox ${label} directory does not exist: ${path}` });
728
+ }
729
+ async function canonicalFuturePath(path) {
730
+ const missing = [];
731
+ let candidate = resolve(path);
732
+ while (true) try {
733
+ return join(await realpath(candidate), ...missing.toReversed());
734
+ } catch (error) {
735
+ if (error.code !== "ENOENT") throw error;
736
+ const parent = dirname(candidate);
737
+ if (parent === candidate) throw error;
738
+ missing.push(basename(candidate));
739
+ candidate = parent;
740
+ }
741
+ }
742
+ async function ensureStateRoot(path) {
743
+ await mkdir(path, {
744
+ mode: 448,
745
+ recursive: true
746
+ });
747
+ const canonical = await realpath(path);
748
+ if (resolve(canonical) !== resolve(path)) throw sandboxErrorDiagnostics.SANDBOX_R0139({ message: "[vitehub] Sandbox stateRoot changed while the Sandbox was materializing." });
749
+ await assertDirectory(canonical, "stateRoot");
750
+ }
751
+ async function findExecutable(command, path, pathExt, cwd) {
752
+ const names = [command, ...(pathExt || "").split(";").map((extension) => extension.trim()).filter(Boolean).flatMap((extension) => {
753
+ return command.toLowerCase().endsWith(extension.toLowerCase()) ? [] : [`${command}${extension}`];
754
+ })];
755
+ const candidates = command.includes("/") || command.includes("\\") || isAbsolute(command) ? names.map((name) => resolve(cwd ?? process.cwd(), name)) : (path || "").split(delimiter).filter(Boolean).flatMap((directory) => names.map((name) => isAbsolute(directory) ? join(directory, name) : resolve(cwd ?? process.cwd(), directory, name)));
756
+ for (const candidate of candidates) if (await access(candidate, constants.X_OK).then(() => true, () => false)) return candidate;
757
+ }
758
+ function isWindowsCommandShim(path) {
759
+ return process.platform === "win32" && /\.(?:bat|cmd)$/i.test(path);
760
+ }
761
+ function resolveSessionPath(root, path = "") {
762
+ const candidate = isRootedPath(path) ? isAbsolute(path) && isInside(root, resolve(path)) ? resolve(path) : resolve(root, rootRelativeFragment(path)) : resolve(root, path);
763
+ if (!isInside(root, candidate)) throw sandboxErrorDiagnostics.SANDBOX_R0140({ message: `[vitehub] Trusted host Sandbox path escapes the session root: ${path}` });
764
+ return candidate;
765
+ }
766
+ async function physicalSessionPath(root, path = "") {
767
+ return await realpath(resolveSessionPath(root, path));
768
+ }
769
+ function isInside(root, path) {
770
+ const next = relative(resolve(root), resolve(path));
771
+ return !next || !next.startsWith("..") && !isAbsolute(next);
772
+ }
773
+ function pathsOverlap(first, second) {
774
+ return isInside(first, second) || isInside(second, first);
775
+ }
776
+ function isRootedPath(path) {
777
+ return isAbsolute(path) || /^[A-Za-z]:/.test(path) || /^[\\/]{2}/.test(path);
778
+ }
779
+ function rootRelativeFragment(path) {
780
+ return path.replace(/^[A-Za-z]:[\\/]*/, "").replace(/^[\\/]+/, "").replace(/\\/g, "/");
781
+ }
782
+ async function collect(stream) {
783
+ return await new Response(stream).text();
784
+ }
785
+ function processHandle(child, abortSignal, afterExit) {
786
+ let abortReason;
787
+ let forceKillTimer;
788
+ const abort = () => {
789
+ if (abortReason) return;
790
+ abortReason = abortSignal?.reason || sandboxErrorDiagnostics.SANDBOX_R0141({ message: "Sandbox command aborted." });
791
+ signalProcessTree(child, "SIGTERM");
792
+ forceKillTimer = setTimeout(() => signalProcessTree(child, "SIGKILL"), 250);
793
+ forceKillTimer.unref?.();
794
+ };
795
+ abortSignal?.addEventListener("abort", abort, { once: true });
796
+ const wait = new Promise((resolvePromise, reject) => {
797
+ child.once("error", reject);
798
+ child.once("close", (code) => {
799
+ abortSignal?.removeEventListener("abort", abort);
800
+ if (forceKillTimer) clearTimeout(forceKillTimer);
801
+ if (abortReason) reject(abortReason);
802
+ else Promise.resolve().then(afterExit).then(() => resolvePromise({ exitCode: code ?? 1 }), reject);
803
+ });
804
+ });
805
+ wait.catch(() => void 0);
806
+ if (abortSignal?.aborted) abort();
807
+ let stdin;
808
+ return {
809
+ pid: child.pid,
810
+ stderr: Readable.toWeb(child.stderr),
811
+ get stdin() {
812
+ return stdin ??= Writable.toWeb(child.stdin);
813
+ },
814
+ stdout: Readable.toWeb(child.stdout),
815
+ wait: () => wait,
816
+ async kill(signal) {
817
+ signalProcessTree(child, normalizeSignal(signal));
818
+ const settled = wait.catch(() => void 0);
819
+ if (signal !== void 0) {
820
+ await settled;
821
+ return;
822
+ }
823
+ let timer;
824
+ try {
825
+ const gracePeriod = new Promise((resolvePromise) => {
826
+ timer = setTimeout(resolvePromise, 250);
827
+ });
828
+ await Promise.race([gracePeriod, settled.then(() => {
829
+ if (child.pid && process.platform !== "win32" && processGroupExists(child.pid)) return gracePeriod;
830
+ })]);
831
+ signalProcessTree(child, "SIGKILL");
832
+ await settled;
833
+ } finally {
834
+ clearTimeout(timer);
835
+ }
836
+ }
837
+ };
838
+ }
839
+ function normalizeSignal(signal = "TERM") {
840
+ const normalized = signal.toUpperCase();
841
+ return normalized.startsWith("SIG") ? normalized : `SIG${normalized}`;
842
+ }
843
+ function signalProcessTree(child, signal) {
844
+ if (child.pid && process.platform !== "win32") {
845
+ signalProcessGroup(child.pid, signal);
846
+ return;
847
+ }
848
+ if (child.exitCode !== null || child.signalCode !== null) return;
849
+ child.kill(signal);
850
+ }
851
+ function signalProcessGroup(pid, signal) {
852
+ try {
853
+ process.kill(-pid, signal);
854
+ } catch (error) {
855
+ if (error.code !== "ESRCH") throw error;
856
+ }
857
+ }
858
+ function processGroupExists(pid) {
859
+ try {
860
+ process.kill(-pid, 0);
861
+ return true;
862
+ } catch (error) {
863
+ if (error.code === "ESRCH") return false;
864
+ throw error;
865
+ }
866
+ }
867
+ function waitForExit(child) {
868
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
869
+ return new Promise((resolvePromise) => child.once("close", () => resolvePromise()));
870
+ }
871
+ //#endregion
872
+ export { createTrustedHostRuntime };