@eum-agent/sandbox 0.0.0-stage → 1.0.1

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 (4) hide show
  1. package/dist/index.js +1929 -0
  2. package/package.json +52 -3
  3. package/ui/ui.js +1331 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,1929 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { z } from "zod";
5
+ import { isAbsolute, normalize, parse, posix, win32 } from "node:path";
6
+ //#region src/path-semantics.ts
7
+ /** Host path syntax used by runtime callers; URI and wire paths do not use this module. */
8
+ /** Chooses path operations from an explicit host fact, independently of the test runner. */
9
+ function pathsFor(platform = process.platform) {
10
+ return platform === "win32" ? win32 : posix;
11
+ }
12
+ /** Accepts POSIX roots or complete Windows drive/UNC roots; rejects NUL and implicit drives. */
13
+ function isCompleteAbsolute(path, paths = pathsFor()) {
14
+ if (path.includes("\0")) return false;
15
+ if (paths !== win32) return paths.isAbsolute(path);
16
+ if (/^[a-z]:[\\/]/i.test(path)) return true;
17
+ const unc = /^[/\\]{2}([^/\\]+)[/\\]([^/\\]+)(?:[/\\]|$)/.exec(path);
18
+ return unc !== null && ![
19
+ ".",
20
+ "..",
21
+ "?"
22
+ ].includes(unc[1] ?? "") && ![".", ".."].includes(unc[2] ?? "");
23
+ }
24
+ /**
25
+ * Contains canonical absolute paths by exact normalized segments.
26
+ * Windows drive syntax is normalized; object names never undergo case folding.
27
+ * This lexical check does not replace real-path resolution or safe file opening.
28
+ */
29
+ function containsPath(root, path, paths = pathsFor()) {
30
+ if (!isCompleteAbsolute(root, paths) || !isCompleteAbsolute(path, paths)) return false;
31
+ const parts = (value) => {
32
+ const normalized = paths.normalize(value);
33
+ const root = paths.parse(normalized).root;
34
+ return {
35
+ root: paths === win32 ? root.replace(/^[a-z]:/i, (drive) => drive.toUpperCase()) : root,
36
+ segments: normalized.slice(root.length).split(paths.sep).filter(Boolean)
37
+ };
38
+ };
39
+ const base = parts(root);
40
+ const target = parts(path);
41
+ return base.root === target.root && base.segments.length <= target.segments.length && base.segments.every((segment, index) => segment === target.segments[index]);
42
+ }
43
+ //#endregion
44
+ //#region src/paths.ts
45
+ const MAX_LINK_HOPS = 40;
46
+ /** Resolves existing physical objects and follows dangling links without assuming absence. */
47
+ function resolveThroughExisting(path, host) {
48
+ const paths = pathsFor(host.process.platform);
49
+ if (path.includes("\0") || host.process.platform === "win32" && (/^[a-z]:/i.test(path) || /^[\\/]/.test(path)) && !isCompleteAbsolute(path, paths)) throw new Error(`path must name a complete absolute root: ${path}`);
50
+ const { basename, dirname, resolve } = paths;
51
+ return resolveWithHops(path, 0);
52
+ /** `resolveThroughExisting`, carrying the links already followed on the way
53
+ * here. A cycle stops when that count reaches `MAX_LINK_HOPS`. */
54
+ function resolveWithHops(path, hops) {
55
+ let candidate = resolve(host.process.cwd(), path);
56
+ const rest = [];
57
+ while (true) {
58
+ const real = realPathOf(candidate, hops);
59
+ if (real !== void 0) return rest.length === 0 ? real : resolve(real, ...rest);
60
+ const parent = dirname(candidate);
61
+ if (parent === candidate) throw new Error(`could not resolve existing path root: ${candidate}`);
62
+ rest.unshift(basename(candidate));
63
+ candidate = parent;
64
+ }
65
+ }
66
+ /**
67
+ * `path` with every symlink on it followed, or `undefined` when nothing is
68
+ * there under that name.
69
+ *
70
+ * `host.fs.realpathSync` reports two different situations with one error — a path
71
+ * that does not exist, and a symlink whose target does not exist — and the
72
+ * second must not be read as the first. Reading it as "nothing here" ends the
73
+ * upward walk at the link's parent and answers with the link's own name,
74
+ * which is a name in whatever directory the link happens to sit in while the
75
+ * bytes would land wherever it points. So the link is followed by hand: its
76
+ * target is taken as written, resolved against its parent's real path, and
77
+ * put through the same walk.
78
+ */
79
+ function realPathOf(path, hops) {
80
+ try {
81
+ return host.fs.realpathSync(path);
82
+ } catch (error) {
83
+ if (error.code !== "ENOENT") throw error;
84
+ }
85
+ if (hops >= MAX_LINK_HOPS) throw new Error("too many symbolic links in path");
86
+ let target;
87
+ try {
88
+ if (!host.fs.lstatSync(path).isSymbolicLink()) throw new Error(`could not resolve existing path: ${path}`);
89
+ target = host.fs.readlinkSync(path);
90
+ } catch (error) {
91
+ if (error.code === "ENOENT") return void 0;
92
+ throw error;
93
+ }
94
+ const parent = dirname(path);
95
+ const base = parent === path ? parent : resolveWithHops(parent, hops + 1);
96
+ return resolveWithHops(resolve(base, target), hops + 1);
97
+ }
98
+ }
99
+ function isWithin(root, path, paths = pathsFor()) {
100
+ return containsPath(root, path, paths);
101
+ }
102
+ //#endregion
103
+ //#region src/readable.ts
104
+ /** Manual read roots are resolved independently of owner-provided preset permissions. */
105
+ /**
106
+ * The list as a plan uses it: real paths, in order, without the entries that
107
+ * are not on this machine.
108
+ *
109
+ * Resolved through symlinks because everything a plan compares against is a
110
+ * real path, and because `/private/etc` and `/etc` have to end up as one
111
+ * entry rather than two rules that disagree. A missing entry is skipped
112
+ * rather than refused; a missing manual root contributes no permission.
113
+ */
114
+ function resolveReadablePaths(paths, host) {
115
+ const resolved = [];
116
+ for (const path of paths) {
117
+ if (!isAbsolute(path)) continue;
118
+ if (!host.fs.existsSync(path)) continue;
119
+ resolved.push(host.fs.realpathSync(path));
120
+ }
121
+ return dedupe(resolved);
122
+ }
123
+ /**
124
+ * Why this path cannot join the readable list, or `undefined` when it can.
125
+ *
126
+ * The same check serves the management method and the `allowed-always` half
127
+ * of a permission: a person widening the list from
128
+ * a settings page and a person answering "allow and remember" are granting
129
+ * the same thing, so one of them being able to name the token directory and
130
+ * the other not would be the hole. Phrased like the fence's own refusals, in
131
+ * the same direction as `workspace add-dir`'s.
132
+ */
133
+ function readablePathRefusal(path, protectedPaths, host) {
134
+ if (!isAbsolute(path)) return `readable path must be absolute: ${path}`;
135
+ const real = resolveThroughExisting(path, host);
136
+ const sealedRoot = (protectedPaths.sealed ?? []).find((dir) => isWithin(dir, real));
137
+ if (sealedRoot !== void 0) return `${path} is inside yaoguang's own state directory (${sealedRoot}), which no readable path can cover`;
138
+ }
139
+ /** Insertion order, first occurrence wins — the order a person wrote the
140
+ * list in is the order they read it back in. */
141
+ function dedupe(paths) {
142
+ return [...new Set(paths)];
143
+ }
144
+ //#endregion
145
+ //#region src/targets.ts
146
+ /** Canonical loopback host forms share machine-wide TCP port grants. */
147
+ function isLocalHost(host) {
148
+ return [
149
+ "localhost",
150
+ "127.0.0.1",
151
+ "::1"
152
+ ].includes(host);
153
+ }
154
+ /** Validates exact argv and a complete physical working directory. */
155
+ function commandTarget(target, host) {
156
+ if (!isCompleteAbsolute(target.cwd, pathsFor(host.process.platform)) || !target.argv.length || !target.argv[0] || target.argv.some((arg) => arg.includes("\0"))) throw new Error("invalid-authorization: invalid command argv or cwd");
157
+ return {
158
+ argv: [...target.argv],
159
+ cwd: resolveThroughExisting(target.cwd, host)
160
+ };
161
+ }
162
+ //#endregion
163
+ //#region src/authorize.ts
164
+ /** External hosts are purpose declarations, never address restrictions for shell processes. */
165
+ const NETWORK_WARNING = "External access permits any outside address; declared hosts are not enforced. Remembered resource permissions apply globally. Local connections and listening use independent policies; the resident gateway stays blocked.";
166
+ /** Seatbelt enforces a listening port, but cannot enforce a loopback binding address. */
167
+ const LISTEN_WARNING = "Listening is authorized by TCP port. Bind the service to 127.0.0.1 or ::1 yourself; wildcard bindings (0.0.0.0 / ::) may expose it to the LAN. Seatbelt cannot enforce this address restriction.";
168
+ /** Returns one reentrant decision; lasting grants are committed together before granting execution. */
169
+ function createAuthorize(deps) {
170
+ const host = deps.host;
171
+ const ask = deps.approval;
172
+ return function authorize(ctx, permissions, reason, execution, mode = "sandboxed", fallbackReason) {
173
+ if (!deps.available()) return {
174
+ kind: "refused",
175
+ reason: "policy",
176
+ message: "Authorization strategy is unavailable. Nothing ran."
177
+ };
178
+ let command;
179
+ try {
180
+ command = commandTarget({
181
+ argv: [...execution.argv],
182
+ cwd: execution.cwd
183
+ }, host);
184
+ } catch (error) {
185
+ return {
186
+ kind: "refused",
187
+ reason: "policy",
188
+ message: String(error)
189
+ };
190
+ }
191
+ const policies = deps.policies();
192
+ const files = mode === "direct" ? [] : [...(permissions.read ?? []).map((path) => ({
193
+ kind: "file",
194
+ path: resolveThroughExisting(path, host),
195
+ operations: ["read"]
196
+ })), ...(permissions.write ?? []).map((path) => ({
197
+ kind: "file",
198
+ path: resolveThroughExisting(path, host),
199
+ operations: ["write"]
200
+ }))];
201
+ const locals = mode === "direct" ? [] : [...(permissions.connect ?? []).map((item) => ({
202
+ kind: "host",
203
+ ...item,
204
+ operations: ["connect"]
205
+ })), ...(permissions.listen ?? []).map((item) => ({
206
+ kind: "host",
207
+ ...item,
208
+ operations: ["listen"]
209
+ }))];
210
+ if (permissions.receipt !== void 0) try {
211
+ if (mode !== "sandboxed" || !deps.receipts) throw new Error("receipt-unavailable");
212
+ deps.receipts.inspect(ctx, {
213
+ receiptId: permissions.receipt,
214
+ inputs: files
215
+ });
216
+ } catch (error) {
217
+ return {
218
+ kind: "refused",
219
+ reason: "policy",
220
+ message: error instanceof Error ? error.message : "receipt-unavailable"
221
+ };
222
+ }
223
+ try {
224
+ for (const input of locals) deps.validateTarget(input);
225
+ } catch (error) {
226
+ return {
227
+ kind: "refused",
228
+ reason: "policy",
229
+ message: String(error)
230
+ };
231
+ }
232
+ if (mode === "sandboxed" && (permissions.connect ?? []).some((item) => item.port !== "any" && deps.protectedPorts().includes(item.port))) return {
233
+ kind: "refused",
234
+ reason: "policy",
235
+ message: "The resident gateway connection is protected."
236
+ };
237
+ const wantsExternal = mode === "sandboxed" && (permissions.network?.length ?? 0) > 0;
238
+ if (mode === "sandboxed" && (wantsExternal && policies.external === "deny" || (permissions.connect?.length ?? 0) > 0 && policies.connect === "deny" || (permissions.listen?.length ?? 0) > 0 && policies.listen === "deny")) return {
239
+ kind: "refused",
240
+ reason: "policy",
241
+ message: "The requested sandbox network capability is denied by its policy."
242
+ };
243
+ const toolInputs = (permissions.receipt !== void 0 ? [] : files).filter((input) => input.kind === "file" && !deps.access.holds(ctx.address, ctx.sessionId, input.path, input.operations[0]) && !(input.operations[0] === "read" && deps.access.holds(ctx.address, ctx.sessionId, input.path, "write")));
244
+ if (!deps.access.holdsCommand(command)) toolInputs.unshift({
245
+ kind: "command",
246
+ ...command
247
+ });
248
+ const networkInputs = locals.filter((input) => input.kind === "host" && policies[input.operations[0]] === "ask" && !deps.access.holdsHost(input.host, input.port, input.operations[0]));
249
+ const external = wantsExternal && policies.external === "ask" && !deps.access.holdsNetwork(ctx.address, ctx.sessionId);
250
+ const defaultPolicy = deps.defaultPolicy();
251
+ if (toolInputs.length && defaultPolicy === "deny") return {
252
+ kind: "refused",
253
+ reason: "policy",
254
+ message: "The default authorization policy refuses this command or file access."
255
+ };
256
+ const inputs = [...defaultPolicy === "ask" ? toolInputs : [], ...networkInputs];
257
+ const id = `sandbox:${host.crypto.createHash("sha256").update(JSON.stringify({
258
+ mode,
259
+ receiptId: permissions.receipt,
260
+ fallbackReason,
261
+ command,
262
+ files,
263
+ locals,
264
+ externalPurpose: mode === "direct" ? [] : permissions.network ?? []
265
+ })).digest("hex")}`;
266
+ if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === ask.questionId(id))) return {
267
+ kind: "refused",
268
+ reason: "rejected",
269
+ message: "stale-approval: the execution or requested resources changed."
270
+ };
271
+ if (!inputs.length && !external) return { kind: "granted" };
272
+ const targets = inputs.map((input) => input.kind === "file" ? {
273
+ access: input.operations[0],
274
+ target: input.path
275
+ } : input.kind === "host" ? {
276
+ access: input.operations[0],
277
+ target: `${input.host}:${input.port}`
278
+ } : {
279
+ access: "execute",
280
+ target: `${JSON.stringify(input.argv)} in ${input.cwd}`
281
+ });
282
+ if (external) targets.push({
283
+ access: "network",
284
+ target: "All outside addresses"
285
+ });
286
+ const decision = ask.decide(ctx, {
287
+ id,
288
+ subject: targets.map((target) => `${target.access} ${target.target}`).join("; "),
289
+ targets,
290
+ reason,
291
+ accepts: [
292
+ "allowed-once",
293
+ "allowed-always",
294
+ "rejected"
295
+ ],
296
+ globalResource: true,
297
+ warning: mode === "direct" ? `${fallbackReason ? `The preferred sandbox is unavailable: ${fallbackReason}.` : "Shell sandbox is disabled."} This command runs with host permissions, without YaoGuang file, network, sealed-state or gateway isolation; resource declarations do not confine it or create resource grants. Inherited outer restrictions still apply.` : [NETWORK_WARNING, ...permissions.listen?.length ? [LISTEN_WARNING] : []].join("\n")
298
+ });
299
+ if (decision.kind === "ask") return {
300
+ kind: "ask",
301
+ result: decision.result
302
+ };
303
+ const result = decision.result;
304
+ if (result.kind === "allowed-once") return { kind: "granted" };
305
+ if (result.kind === "allowed-always") try {
306
+ deps.access.recordResources(inputs, external);
307
+ return { kind: "granted" };
308
+ } catch (error) {
309
+ return {
310
+ kind: "refused",
311
+ reason: "record-failed",
312
+ message: `Recording permission failed: ${String(error)}. Nothing ran.`
313
+ };
314
+ }
315
+ return {
316
+ kind: "refused",
317
+ reason: "rejected",
318
+ message: result.kind === "rejected" && result.reason ? `Permission refused: ${result.reason}` : "Permission refused by the person."
319
+ };
320
+ };
321
+ }
322
+ //#endregion
323
+ //#region src/failure-authorization.ts
324
+ /** Coordinates original process evidence without executing commands or storing grants. */
325
+ /** Binds single-flight failure assessment to one prepared process scope. */
326
+ function createFailureCoordinator(deps) {
327
+ const records = /* @__PURE__ */ new Map();
328
+ const leases = /* @__PURE__ */ new Set();
329
+ const closing = /* @__PURE__ */ new Map();
330
+ const closedScopes = /* @__PURE__ */ new Set();
331
+ let stopped = false;
332
+ const empty = () => ({
333
+ diagnostics: {
334
+ availability: deps.diagnostics ? "unavailable" : "unsupported",
335
+ partial: false,
336
+ candidates: [],
337
+ omitted: 0
338
+ },
339
+ authorization: {
340
+ state: "pending",
341
+ items: []
342
+ }
343
+ });
344
+ const emit = (record) => {
345
+ for (const listener of [...record.observers]) try {
346
+ listener();
347
+ } catch {}
348
+ };
349
+ const release = (record) => {
350
+ if (!record.released) {
351
+ record.released = true;
352
+ record.registration.collector.release();
353
+ }
354
+ };
355
+ async function closeLease(lease) {
356
+ const current = closing.get(lease);
357
+ if (current) return current;
358
+ const pending = lease.close().then(() => {
359
+ leases.delete(lease);
360
+ }).finally(() => {
361
+ closing.delete(lease);
362
+ });
363
+ closing.set(lease, pending);
364
+ return pending;
365
+ }
366
+ async function closeScope(scope) {
367
+ if (closedScopes.has(scope)) return;
368
+ const current = closing.get(scope);
369
+ if (current) return current;
370
+ const pending = scope.close().then(() => {
371
+ closedScopes.add(scope);
372
+ }).finally(() => {
373
+ closing.delete(scope);
374
+ });
375
+ closing.set(scope, pending);
376
+ return pending;
377
+ }
378
+ function project(record, source) {
379
+ const items = source.items.flatMap((item) => item.input.kind === "file" ? item.input.operations.map((operation) => ({
380
+ path: item.input.kind === "file" ? item.input.path : "",
381
+ operation,
382
+ status: item.status,
383
+ ...item.source === void 0 ? {} : { source: item.source },
384
+ ...item.duration === void 0 ? {} : { duration: item.duration },
385
+ ...item.reason === void 0 ? {} : { reason: item.reason }
386
+ })) : []);
387
+ return {
388
+ diagnostics: record.snapshot.diagnostics,
389
+ authorization: {
390
+ state: source.state,
391
+ items,
392
+ ...source.receiptId ? { receiptId: source.receiptId } : {},
393
+ ...source.receiptState ? { receiptState: source.receiptState } : {},
394
+ ...record.cancelReason ? { settlementReason: record.cancelReason } : {},
395
+ cleanup: record.snapshot.authorization.cleanup?.state === "failed" ? record.snapshot.authorization.cleanup : source.cleanup
396
+ }
397
+ };
398
+ }
399
+ function current(record) {
400
+ return structuredClone(record.admission ? project(record, record.admission.current()) : record.snapshot);
401
+ }
402
+ function cancel(record, reason) {
403
+ if (record.cancelReason) return;
404
+ record.cancelReason = reason;
405
+ record.controller.abort(reason);
406
+ record.admission?.cancel(reason);
407
+ record.snapshot = {
408
+ ...record.snapshot,
409
+ authorization: {
410
+ ...record.snapshot.authorization,
411
+ state: "settled",
412
+ settlementReason: reason
413
+ }
414
+ };
415
+ emit(record);
416
+ release(record);
417
+ closeScope(record.registration.authorizationScope).catch(() => {});
418
+ }
419
+ async function assess(record, input) {
420
+ const { registration } = record;
421
+ if (input.ending.kind !== "exited" || input.ending.code === 0 || registration.launchScope.mode === "direct" || record.cancelReason) {
422
+ release(record);
423
+ record.snapshot = {
424
+ ...record.snapshot,
425
+ authorization: {
426
+ state: "not-needed",
427
+ items: [],
428
+ ...record.cancelReason ? { settlementReason: record.cancelReason } : {}
429
+ }
430
+ };
431
+ await closeScope(registration.authorizationScope);
432
+ return;
433
+ }
434
+ let frozen;
435
+ try {
436
+ frozen = await registration.collector.finish({
437
+ exitedAt: input.exitedAt,
438
+ code: input.ending.code
439
+ });
440
+ } catch {
441
+ frozen = {
442
+ availability: "unavailable",
443
+ partial: true,
444
+ dropped: 0,
445
+ records: []
446
+ };
447
+ }
448
+ release(record);
449
+ const candidates = [];
450
+ let omitted = frozen.dropped;
451
+ let bytes = 2048;
452
+ const add = (candidate) => {
453
+ if (candidates.some((prior) => prior.path === candidate.path && prior.operation === candidate.operation)) return;
454
+ const size = 4 * Buffer.byteLength(JSON.stringify(candidate)) + 512;
455
+ if (candidates.length >= 64 || bytes + size > 32768) {
456
+ omitted++;
457
+ return;
458
+ }
459
+ candidates.push({ ...candidate });
460
+ bytes += size;
461
+ };
462
+ for (const row of frozen.records) {
463
+ if (!row.path) {
464
+ omitted++;
465
+ continue;
466
+ }
467
+ add({
468
+ path: row.path,
469
+ operation: row.operation,
470
+ source: "seatbelt",
471
+ certainty: row.operation === "unknown" ? "uncertain" : "confirmed"
472
+ });
473
+ }
474
+ for (const candidate of input.candidates ?? []) if (candidate.source !== "seatbelt") add({
475
+ ...candidate,
476
+ certainty: candidate.operation === "unknown" ? "uncertain" : "inferred"
477
+ });
478
+ record.snapshot = {
479
+ diagnostics: {
480
+ availability: frozen.availability,
481
+ partial: frozen.partial || omitted > 0,
482
+ candidates,
483
+ omitted
484
+ },
485
+ authorization: {
486
+ state: "pending",
487
+ items: []
488
+ }
489
+ };
490
+ const owned = [];
491
+ let next = 0;
492
+ const worker = async () => {
493
+ for (;;) {
494
+ const index = next++;
495
+ const candidate = candidates[index];
496
+ if (!candidate || record.controller.signal.aborted) return;
497
+ if (!(deps.host.host.process.platform === "win32" ? win32.isAbsolute(candidate.path) : isAbsolute(candidate.path)) || candidate.operation === "unknown" || !deps.diagnostics) {
498
+ candidates[index] = {
499
+ ...candidate,
500
+ certainty: "uncertain",
501
+ issue: candidate.operation === "unknown" ? "unknown-operation" : "unresolved"
502
+ };
503
+ continue;
504
+ }
505
+ let lease;
506
+ try {
507
+ lease = await deps.diagnostics.observe(candidate.path, candidate.operation, { signal: record.controller.signal });
508
+ leases.add(lease);
509
+ const observed = lease.observation;
510
+ if (record.controller.signal.aborted || observed.kind === "unresolved" || !lease.verify()) {
511
+ candidates[index] = {
512
+ ...candidate,
513
+ certainty: "uncertain",
514
+ issue: "unresolved"
515
+ };
516
+ await closeLease(lease);
517
+ continue;
518
+ }
519
+ const path = observed.realPath;
520
+ if ([...registration.launchScope.deny, ...deps.host.sealedDirectories].some((root) => deps.host.containsPath(root, candidate.path) || deps.host.containsPath(root, path))) {
521
+ candidates[index] = {
522
+ ...candidate,
523
+ realPath: path,
524
+ issue: "sealed"
525
+ };
526
+ await closeLease(lease);
527
+ continue;
528
+ }
529
+ if ((candidate.operation === "read" ? [...registration.launchScope.read, ...registration.launchScope.write] : registration.launchScope.write).some((root) => deps.host.containsPath(root, path)) || deps.host.resources.holds(registration.launchScope.authority.address, registration.launchScope.authority.sessionId, path, candidate.operation)) {
530
+ candidates[index] = {
531
+ ...candidate,
532
+ realPath: path,
533
+ issue: "in-scope"
534
+ };
535
+ await closeLease(lease);
536
+ continue;
537
+ }
538
+ const authorization = {
539
+ kind: "file",
540
+ path,
541
+ operations: [candidate.operation]
542
+ };
543
+ deps.host.validateTarget(authorization);
544
+ candidates[index] = {
545
+ ...candidate,
546
+ realPath: path
547
+ };
548
+ owned.push({
549
+ index,
550
+ lease,
551
+ input: authorization
552
+ });
553
+ } catch (error) {
554
+ candidates[index] = {
555
+ ...candidate,
556
+ certainty: "uncertain",
557
+ issue: "unresolved"
558
+ };
559
+ const retained = error?.cleanupLease;
560
+ if (retained) {
561
+ leases.add(retained);
562
+ lease = retained;
563
+ }
564
+ if (lease) try {
565
+ await closeLease(lease);
566
+ } catch {
567
+ record.snapshot = {
568
+ ...record.snapshot,
569
+ authorization: {
570
+ ...record.snapshot.authorization,
571
+ cleanup: {
572
+ state: "failed",
573
+ reason: "Observation cleanup remains owned"
574
+ }
575
+ }
576
+ };
577
+ }
578
+ }
579
+ }
580
+ };
581
+ await Promise.allSettled(Array.from({ length: Math.min(8, candidates.length) }, worker));
582
+ const included = /* @__PURE__ */ new Set();
583
+ const bounded = [];
584
+ bytes = 2048;
585
+ for (const [index, candidate] of candidates.entries()) {
586
+ const size = 4 * Buffer.byteLength(JSON.stringify(candidate)) + 512;
587
+ if (bytes + size > 32768) {
588
+ omitted++;
589
+ continue;
590
+ }
591
+ bytes += size;
592
+ included.add(index);
593
+ bounded.push(candidate);
594
+ }
595
+ const excluded = owned.filter((one) => !included.has(one.index));
596
+ const cleanupExcluded = await Promise.allSettled(excluded.map(({ lease }) => closeLease(lease)));
597
+ for (let index = owned.length - 1; index >= 0; index--) if (!included.has(owned[index].index)) owned.splice(index, 1);
598
+ record.snapshot = {
599
+ ...record.snapshot,
600
+ diagnostics: {
601
+ ...record.snapshot.diagnostics,
602
+ candidates: bounded,
603
+ omitted,
604
+ partial: record.snapshot.diagnostics.partial || omitted > 0
605
+ },
606
+ ...cleanupExcluded.some((item) => item.status === "rejected") ? { authorization: {
607
+ ...record.snapshot.authorization,
608
+ cleanup: {
609
+ state: "failed",
610
+ reason: "Observation cleanup remains owned"
611
+ }
612
+ } } : {}
613
+ };
614
+ if (record.cancelReason || !owned.length) {
615
+ await Promise.allSettled(owned.map(({ lease }) => closeLease(lease)));
616
+ record.snapshot = {
617
+ ...record.snapshot,
618
+ authorization: {
619
+ ...record.snapshot.authorization,
620
+ state: "not-needed",
621
+ ...record.cancelReason ? { settlementReason: record.cancelReason } : {}
622
+ }
623
+ };
624
+ await closeScope(registration.authorizationScope);
625
+ return;
626
+ }
627
+ owned.sort((a, b) => a.index - b.index);
628
+ const inputs = owned.map((one) => one.input);
629
+ const targets = owned.map((one) => ({
630
+ access: one.input.kind === "file" ? one.input.operations[0] : "read",
631
+ target: one.input.kind === "file" ? one.input.path : ""
632
+ }));
633
+ try {
634
+ const admission = registration.authorizationScope.admit({
635
+ issuerResourceId: input.processId,
636
+ operationId: registration.launchScope.operationId,
637
+ inputs,
638
+ validations: owned.map(({ lease }) => ({
639
+ identity: lease.observation.kind === "unresolved" ? "" : lease.observation.identity,
640
+ verify: () => !record.controller.signal.aborted && lease.verify(),
641
+ close: () => lease.close()
642
+ })),
643
+ approval: {
644
+ id: `failure:${registration.scopeId}`,
645
+ subject: targets.map((target) => `${target.access} ${target.target}`).join("; "),
646
+ targets,
647
+ reason: "The original command exited unsuccessfully with observed file access denials. Approval applies to a future explicit command; the failed command will not rerun.",
648
+ warning: owned.map(({ index }) => `${candidates[index].source}: ${candidates[index].path}`).join("\n"),
649
+ accepts: [
650
+ "allowed-once",
651
+ "allowed-always",
652
+ "rejected"
653
+ ],
654
+ globalResource: true
655
+ }
656
+ });
657
+ record.admission = admission;
658
+ record.detachAdmission = admission.onChanged(() => emit(record));
659
+ for (const { lease } of owned) leases.delete(lease);
660
+ } catch {
661
+ const cleanup = await Promise.allSettled(owned.map(({ lease }) => closeLease(lease)));
662
+ record.snapshot = {
663
+ ...record.snapshot,
664
+ authorization: {
665
+ state: "settled",
666
+ items: targets.map((target) => ({
667
+ path: target.target,
668
+ operation: target.access,
669
+ status: "error",
670
+ reason: "Resource authorization admission failed"
671
+ })),
672
+ cleanup: cleanup.some((item) => item.status === "rejected") ? {
673
+ state: "failed",
674
+ reason: "Observation cleanup remains owned"
675
+ } : { state: "complete" }
676
+ }
677
+ };
678
+ await closeScope(registration.authorizationScope);
679
+ }
680
+ }
681
+ return {
682
+ register(input) {
683
+ if (stopped || records.has(input.scopeId)) throw new Error("scope-conflict: prepared failure scope is unavailable");
684
+ const record = {
685
+ registration: input,
686
+ controller: new AbortController(),
687
+ snapshot: empty(),
688
+ released: false,
689
+ detach: () => {},
690
+ observers: /* @__PURE__ */ new Set()
691
+ };
692
+ const abort = () => cancel(record, "owner-withdrawn");
693
+ input.originLifetime.addEventListener("abort", abort, { once: true });
694
+ record.detach = () => input.originLifetime.removeEventListener("abort", abort);
695
+ records.set(input.scopeId, record);
696
+ if (input.originLifetime.aborted) abort();
697
+ },
698
+ beginFailure(input) {
699
+ const record = records.get(input.scopeId);
700
+ if (!record || stopped) throw new Error("scope-unavailable: original process scope is absent");
701
+ const fingerprint = JSON.stringify(input);
702
+ if (Buffer.byteLength(fingerprint) > 65536 || !Number.isFinite(input.exitedAt)) throw new Error("failure-limit: process evidence exceeds its bound");
703
+ if (record.fingerprint !== void 0 && record.fingerprint !== fingerprint) throw new Error("scope-conflict: original process failure changed");
704
+ if (record.handle) return record.handle;
705
+ record.fingerprint = fingerprint;
706
+ const assessed = assess(record, structuredClone(input)).catch(() => {
707
+ release(record);
708
+ record.snapshot = {
709
+ ...record.snapshot,
710
+ authorization: {
711
+ state: "settled",
712
+ items: [],
713
+ settlementReason: record.cancelReason ?? "diagnostics-unavailable",
714
+ cleanup: {
715
+ state: "failed",
716
+ reason: "Failure assessment cleanup remains supervised"
717
+ }
718
+ }
719
+ };
720
+ }).then(() => {
721
+ emit(record);
722
+ return current(record);
723
+ });
724
+ record.handle = {
725
+ current: () => current(record),
726
+ assessed,
727
+ settled: assessed.then(async () => {
728
+ if (record.admission) await record.admission.settled;
729
+ emit(record);
730
+ return current(record);
731
+ }).catch(() => {
732
+ record.snapshot = {
733
+ ...record.snapshot,
734
+ authorization: {
735
+ ...record.snapshot.authorization,
736
+ state: "settled",
737
+ settlementReason: "authorization-error"
738
+ }
739
+ };
740
+ return current(record);
741
+ }),
742
+ onChanged: (listener) => {
743
+ record.observers.add(listener);
744
+ return () => {
745
+ record.observers.delete(listener);
746
+ };
747
+ },
748
+ cancel: (reason) => cancel(record, reason)
749
+ };
750
+ return record.handle;
751
+ },
752
+ invalidate(sessionId) {
753
+ for (const record of records.values()) if (record.registration.launchScope.authority.sessionId === sessionId) cancel(record, "session-ended");
754
+ },
755
+ async abandon(scopeId) {
756
+ const record = records.get(scopeId);
757
+ if (!record) return;
758
+ cancel(record, "startup-failed");
759
+ await record.handle?.settled;
760
+ await closeScope(record.registration.authorizationScope);
761
+ },
762
+ async close() {
763
+ stopped = true;
764
+ for (const record of records.values()) cancel(record, "owner-withdrawn");
765
+ await Promise.allSettled([...records.values()].flatMap((record) => record.handle ? [record.handle.settled] : []));
766
+ const cleanup = await Promise.allSettled([...[...leases].map(closeLease), ...[...records.values()].map((record) => closeScope(record.registration.authorizationScope))]);
767
+ for (const record of records.values()) {
768
+ release(record);
769
+ record.detach();
770
+ record.detachAdmission?.();
771
+ }
772
+ const failed = cleanup.flatMap((item) => item.status === "rejected" ? [item.reason] : []);
773
+ if (failed.length) throw new AggregateError(failed, "Failure authorization cleanup remains owned");
774
+ for (const record of records.values()) {
775
+ record.snapshot = {
776
+ ...record.snapshot,
777
+ authorization: {
778
+ ...record.snapshot.authorization,
779
+ cleanup: { state: "complete" }
780
+ }
781
+ };
782
+ emit(record);
783
+ record.observers.clear();
784
+ }
785
+ }
786
+ };
787
+ }
788
+ //#endregion
789
+ //#region src/local-ports.ts
790
+ /** Owns the actual gateway port, and refreshes all network decisions before spawning. */
791
+ function createSandboxNetwork(config, access, changed) {
792
+ let gatewayPort;
793
+ function protectedPorts() {
794
+ return gatewayPort === void 0 ? [] : [gatewayPort];
795
+ }
796
+ function effective(permissions = {}, triggerExternal = false) {
797
+ const policies = config.networkPolicies();
798
+ const local = (operation) => {
799
+ if (gatewayPort === void 0 || policies[operation] === "deny") return [];
800
+ if (policies[operation] === "allow") return ["any"];
801
+ return [.../* @__PURE__ */ new Set([...(access?.list() ?? []).flatMap((row) => row.kind === "host" && row.effective && isLocalHost(row.target.host) && row.target.operation === operation ? [row.target.port] : []), ...(permissions[operation] ?? []).map((item) => item.port)])].filter((port) => operation !== "connect" || port !== gatewayPort);
802
+ };
803
+ return {
804
+ connectAllow: local("connect"),
805
+ listenAllow: local("listen"),
806
+ protectedLocalPorts: protectedPorts(),
807
+ externalAllowed: policies.external !== "deny" && (policies.external === "allow" || triggerExternal || (permissions.network?.length ?? 0) > 0)
808
+ };
809
+ }
810
+ return {
811
+ protectedPorts,
812
+ effective,
813
+ /** Registers one port for this runtime; no local capability exists before registration. */
814
+ bind(port) {
815
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid gateway port");
816
+ if (gatewayPort === port) return;
817
+ if (gatewayPort !== void 0) throw new Error("The runtime already has a gateway port");
818
+ gatewayPort = port;
819
+ changed();
820
+ },
821
+ /** Refreshes against current policy and shared grants; running processes retain their profile. */
822
+ refresh(plan) {
823
+ const current = effective(plan.requested);
824
+ return {
825
+ ...plan,
826
+ ...current,
827
+ proxyEnvironment: gatewayPort === void 0 || !current.externalAllowed ? {} : plan.proxyEnvironment
828
+ };
829
+ }
830
+ };
831
+ }
832
+ //#endregion
833
+ //#region src/plan.ts
834
+ /**
835
+ * Where a sandboxed command's rules come from.
836
+ *
837
+ * Nothing here is stored. One call's rules are derived from three things —
838
+ * this workspace's directories and global grants, the readable-path list, and
839
+ * the permissions this one call asked for — and thrown away afterwards. That
840
+ * is what keeps the shell's boundary and `fs_write`'s the same boundary:
841
+ * the write set *is* the fence's read-write roots, so there is no second
842
+ * configuration for the two to disagree about, and a directory a person
843
+ * authorized a second ago is in the next plan without anything being
844
+ * invalidated.
845
+ *
846
+ * This module is the **one** caller of `fence.roots`. A tool that derived its own rules would be a second path
847
+ * judgement, and a second one is a second thing to get wrong.
848
+ */
849
+ function createSandboxPlanner(deps) {
850
+ const host = deps.host;
851
+ /** Whether a path is somewhere a command could start. A permission that names
852
+ * a file is honoured as a file; it is simply not a working directory. */
853
+ function isDirectory(path) {
854
+ try {
855
+ return host.fs.statSync(path).isDirectory();
856
+ } catch {
857
+ return false;
858
+ }
859
+ }
860
+ const sealed = (deps.sealed ?? []).map((path) => resolveThroughExisting(path, host));
861
+ const refreshers = /* @__PURE__ */ new WeakMap();
862
+ function temporaryRoots() {
863
+ const roots = deps.temporaryRoots?.();
864
+ if (!roots) return [];
865
+ return dedupe([...roots.platform === "darwin" ? ["/private/tmp"] : [], roots.userTemporaryRoot].filter((path) => isAbsolute(path)).map((path) => resolveThroughExisting(path, host)).filter((path) => !sealed.some((root) => isWithin(root, path))));
866
+ }
867
+ /** A permission path that no answer could ever grant, or
868
+ * `undefined`. Judged on the real path, so a symlink into a protected
869
+ * tree is caught, and judged *before* anybody is asked — the person never
870
+ * sees a question whose yes would not be honoured. */
871
+ function refuseProtected(path) {
872
+ if (!isAbsolute(path)) return {
873
+ ok: false,
874
+ reason: "not-absolute",
875
+ message: `permission paths must be absolute: ${path}. A session has no current directory, because a workspace is not a directory`
876
+ };
877
+ const real = resolveThroughExisting(path, host);
878
+ const sealedRoot = sealed.find((dir) => isWithin(dir, real));
879
+ if (sealedRoot !== void 0) return {
880
+ ok: false,
881
+ reason: "sealed",
882
+ message: `${path} is inside yaoguang's own state directory (${sealedRoot}) — the master key, the event log, this installation's configuration and its plugin code: no permission can cover it`
883
+ };
884
+ }
885
+ return {
886
+ refresh(plan) {
887
+ const refresh = refreshers.get(plan);
888
+ if (!refresh) throw new Error("The sandbox plan does not belong to this host");
889
+ return refresh();
890
+ },
891
+ async plan(caller, request, mode = "sandboxed", includeContributions = true) {
892
+ const workspaceId = caller.address.workspaceId;
893
+ const roots = deps.fence.roots(workspaceId);
894
+ if (!roots.allowed) return {
895
+ ok: false,
896
+ reason: roots.reason,
897
+ message: roots.message
898
+ };
899
+ const permissions = request.permissions;
900
+ for (const path of mode === "direct" ? [] : [...permissions?.read ?? [], ...permissions?.write ?? []]) {
901
+ const refusal = refuseProtected(path);
902
+ if (refusal !== void 0) return refusal;
903
+ }
904
+ const tmp = resolveThroughExisting(request.tmp, host);
905
+ const grantedRead = mode === "direct" ? [] : (permissions?.read ?? []).map((path) => resolveThroughExisting(path, host));
906
+ const grantedWrite = mode === "direct" ? [] : (permissions?.write ?? []).map((path) => resolveThroughExisting(path, host));
907
+ const authorized = roots.roots.map((root) => root.path);
908
+ const workspaceWrite = roots.roots.filter((root) => root.access === "read-write").map((root) => root.path);
909
+ const permittedRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
910
+ const permittedWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
911
+ const read = dedupe([
912
+ ...authorized,
913
+ ...permittedRead,
914
+ ...permittedWrite,
915
+ ...resolveReadablePaths(deps.readable(), host),
916
+ ...includeContributions && mode === "sandboxed" ? deps.contributed?.(caller) ?? [] : [],
917
+ tmp,
918
+ ...temporaryRoots(),
919
+ ...grantedRead,
920
+ ...grantedWrite
921
+ ]);
922
+ const write = dedupe([
923
+ ...workspaceWrite,
924
+ ...permittedWrite,
925
+ tmp,
926
+ ...deps.sharedTemporaryWrite?.() !== false ? temporaryRoots() : [],
927
+ ...grantedWrite
928
+ ]);
929
+ const deny = dedupe([...roots.sealed, ...sealed]);
930
+ const network = mode === "direct" ? {
931
+ externalAllowed: true,
932
+ connectAllow: [],
933
+ listenAllow: [],
934
+ protectedLocalPorts: []
935
+ } : deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? {
936
+ externalAllowed: false,
937
+ connectAllow: [],
938
+ listenAllow: [],
939
+ protectedLocalPorts: []
940
+ };
941
+ let cwd;
942
+ if (request.cwd === void 0) return {
943
+ ok: false,
944
+ reason: "bad-cwd",
945
+ message: "An explicit working directory is required"
946
+ };
947
+ else {
948
+ if (!isAbsolute(request.cwd)) return {
949
+ ok: false,
950
+ reason: "not-absolute",
951
+ message: `cwd must be an absolute native path resolved by the calling owner: ${request.cwd}`
952
+ };
953
+ const requested = resolveThroughExisting(request.cwd, host);
954
+ if (!read.some((root) => isWithin(root, requested))) return {
955
+ ok: false,
956
+ reason: "bad-cwd",
957
+ message: `${request.cwd} is not inside any directory this command may read. Run it in an authorized directory, or ask for the path as a read permission`
958
+ };
959
+ const protectedCwd = refuseProtected(requested);
960
+ if (protectedCwd) return protectedCwd;
961
+ if (!isDirectory(requested)) return {
962
+ ok: false,
963
+ reason: "bad-cwd",
964
+ message: "cwd must be an existing directory"
965
+ };
966
+ cwd = requested;
967
+ }
968
+ const proxyEnvironment = network.externalAllowed ? await deps.proxyEnvironment?.() ?? {} : {};
969
+ if (mode === "direct") return {
970
+ ok: true,
971
+ plan: {
972
+ mode,
973
+ execution: {
974
+ argv: [...request.argv],
975
+ cwd
976
+ },
977
+ requested: permissions ?? {},
978
+ cwd,
979
+ tmp,
980
+ externalAllowed: true,
981
+ proxyEnvironment
982
+ }
983
+ };
984
+ const currentNetwork = deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? network;
985
+ const plan = {
986
+ mode,
987
+ read,
988
+ write,
989
+ deny,
990
+ ...currentNetwork,
991
+ execution: {
992
+ argv: [...request.argv],
993
+ cwd
994
+ },
995
+ requested: permissions ?? {},
996
+ cwd,
997
+ tmp,
998
+ proxyEnvironment: currentNetwork.externalAllowed ? proxyEnvironment : {}
999
+ };
1000
+ refreshers.set(plan, () => {
1001
+ const currentRoots = deps.fence.roots(workspaceId);
1002
+ if (!currentRoots.allowed) throw new Error(currentRoots.message);
1003
+ const currentWorkspaceRead = currentRoots.roots.map((root) => root.path);
1004
+ const currentWorkspaceWrite = currentRoots.roots.filter((root) => root.access === "read-write").map((root) => root.path);
1005
+ const currentRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
1006
+ const currentWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
1007
+ const read = dedupe([
1008
+ ...currentWorkspaceRead,
1009
+ ...currentRead,
1010
+ ...currentWrite,
1011
+ ...resolveReadablePaths(deps.readable(), host),
1012
+ ...includeContributions && mode === "sandboxed" ? deps.contributed?.(caller) ?? [] : [],
1013
+ tmp,
1014
+ ...temporaryRoots(),
1015
+ ...grantedRead,
1016
+ ...grantedWrite
1017
+ ]);
1018
+ if (!read.some((root) => isWithin(root, cwd))) throw new Error("The working directory is no longer readable");
1019
+ const network = deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? currentNetwork;
1020
+ return {
1021
+ ...plan,
1022
+ read,
1023
+ write: dedupe([
1024
+ ...currentWorkspaceWrite,
1025
+ ...currentWrite,
1026
+ tmp,
1027
+ ...deps.sharedTemporaryWrite?.() !== false ? temporaryRoots() : [],
1028
+ ...grantedWrite
1029
+ ]),
1030
+ deny: dedupe([...currentRoots.sealed, ...sealed]),
1031
+ ...network,
1032
+ proxyEnvironment: network.externalAllowed && network.protectedLocalPorts.length ? proxyEnvironment : {}
1033
+ };
1034
+ });
1035
+ return {
1036
+ ok: true,
1037
+ plan
1038
+ };
1039
+ }
1040
+ };
1041
+ }
1042
+ //#endregion
1043
+ //#region src/schema.ts
1044
+ /** Sandbox-owned stored rules and management schemas. */
1045
+ /** Concrete network decision values owned by sandbox. */
1046
+ const NetworkPolicy = z.enum([
1047
+ "ask",
1048
+ "deny",
1049
+ "allow"
1050
+ ]);
1051
+ /** Independent external connection and listener policy settings. */
1052
+ const NetworkPolicies = z.object({
1053
+ external: NetworkPolicy,
1054
+ connect: NetworkPolicy,
1055
+ listen: NetworkPolicy
1056
+ }).strict();
1057
+ /** Complete persisted sandbox settings, including user read roots. */
1058
+ const SandboxConfiguration = z.object({
1059
+ enabled: z.boolean(),
1060
+ readable: z.array(z.string()),
1061
+ networkPolicies: NetworkPolicies,
1062
+ sharedTemporaryWrite: z.boolean()
1063
+ }).strict();
1064
+ /** Partial owner updates retain unrelated current settings. */
1065
+ const SandboxConfigurationUpdate = SandboxConfiguration.partial().strict();
1066
+ /** Backend capability and the current selected execution preference. */
1067
+ const SandboxStatus = z.object({
1068
+ enabled: z.boolean(),
1069
+ mode: z.enum(["sandboxed", "direct"]),
1070
+ availability: z.discriminatedUnion("ok", [z.object({
1071
+ ok: z.literal(true),
1072
+ backend: z.string()
1073
+ }), z.object({
1074
+ ok: z.literal(false),
1075
+ reason: z.string()
1076
+ })])
1077
+ });
1078
+ /** Combined professional/simple values include only active owners. */
1079
+ const SecurityConfiguration = z.object({
1080
+ approvalPolicy: NetworkPolicy.optional(),
1081
+ sandboxEnabled: z.boolean(),
1082
+ sharedTemporaryWrite: z.boolean(),
1083
+ networkPolicies: NetworkPolicies
1084
+ }).strict();
1085
+ /** Current settings snapshot; failed owner reads expose no partial values. */
1086
+ const SecurityState = z.discriminatedUnion("status", [SecurityConfiguration.extend({ status: z.literal("ready") }), z.object({
1087
+ status: z.literal("recovery-required"),
1088
+ error: z.string()
1089
+ }).strict()]);
1090
+ /** Complete manual readable-path settings response. */
1091
+ const ReadablePaths = z.object({ readable: z.array(z.string()) }).strict();
1092
+ z.object({ enabled: z.boolean() }).strict();
1093
+ /** Atomic manual read-root intent. */
1094
+ const ReadablePathsMutation = z.strictObject({
1095
+ operationId: z.uuid(),
1096
+ paths: z.array(z.string().max(4096)).min(1).max(64)
1097
+ });
1098
+ /** Durable manual read-root receipt. */
1099
+ const ReadablePathsReceipt = z.discriminatedUnion("operationState", [
1100
+ z.strictObject({
1101
+ operationState: z.literal("committed"),
1102
+ operationId: z.uuid(),
1103
+ value: ReadablePaths
1104
+ }),
1105
+ z.strictObject({
1106
+ operationState: z.literal("admitted"),
1107
+ operationId: z.uuid(),
1108
+ uncertain: z.literal(true)
1109
+ }),
1110
+ z.strictObject({
1111
+ operationState: z.literal("cleanup-pending"),
1112
+ operationId: z.uuid(),
1113
+ value: ReadablePaths,
1114
+ cleanup: z.array(z.strictObject({
1115
+ code: z.string().max(64),
1116
+ message: z.string().max(512)
1117
+ }))
1118
+ })
1119
+ ]);
1120
+ //#endregion
1121
+ //#region src/scope-note.ts
1122
+ /** Reads only current owner settings and host facts; it grants no resource authority. */
1123
+ function createScopeNote(deps) {
1124
+ return { forSession(caller) {
1125
+ const roots = deps.fence.roots(caller.address.workspaceId);
1126
+ const state = deps.settings();
1127
+ const status = deps.sandbox.status();
1128
+ const temporary = deps.temporaryRoots();
1129
+ let presets = "none";
1130
+ try {
1131
+ const summary = deps.presets()?.current();
1132
+ if (summary) presets = summary.status === "ready" ? summary.names.length ? summary.names.map((name) => JSON.stringify(name)).join(", ") : "none" : "unavailable";
1133
+ } catch {
1134
+ presets = "unavailable";
1135
+ }
1136
+ const paths = (access) => roots.allowed ? roots.roots.filter((root) => root.access === access).map((root) => JSON.stringify(root.path)).join(", ") || "none" : "unavailable";
1137
+ const shared = temporary ? [.../* @__PURE__ */ new Set([...temporary.platform === "darwin" ? ["/private/tmp (also /tmp)"] : [], temporary.userTemporaryRoot])].map((path) => JSON.stringify(path)).join(", ") : "unavailable";
1138
+ return [
1139
+ `Shell execution mode: ${status.mode}${status.availability.ok ? "" : ` (sandbox unavailable: ${status.availability.reason})`}.`,
1140
+ `Read-only workspace directories: ${paths("read")}.`,
1141
+ `Read-write workspace directories: ${paths("read-write")}.`,
1142
+ `Shared temporary directories: ${shared}; default shared writes ${state.sharedTemporaryWrite ? "enabled" : "disabled"}. Each call keeps its own writable TMPDIR; /var/tmp is not a default shared write root. Independent grants keep their own lifetime.`,
1143
+ `Sandbox network policies: external=${state.networkPolicies.external}, connect=${state.networkPolicies.connect}, listen=${state.networkPolicies.listen}.`,
1144
+ `Enabled sandbox presets: ${presets}.`,
1145
+ "Request denied access through permissions with a justification. Do not disable protection or switch paths to bypass a refusal."
1146
+ ].join("\n");
1147
+ } };
1148
+ }
1149
+ //#endregion
1150
+ //#region src/service.ts
1151
+ /** Prefers available confinement and binds the selected capability to approval and launch. */
1152
+ function createSandbox(deps) {
1153
+ const state = () => deps.state?.() ?? {
1154
+ enabled: true,
1155
+ revision: 0
1156
+ };
1157
+ const owned = /* @__PURE__ */ new WeakMap();
1158
+ let preparedId = 0;
1159
+ const launches = /* @__PURE__ */ new Map();
1160
+ function available() {
1161
+ if (!deps.backend) return {
1162
+ ok: false,
1163
+ reason: `no sandbox backend is implemented for ${deps.host.process.platform}`
1164
+ };
1165
+ const ready = deps.backend.available();
1166
+ return ready.ok ? {
1167
+ ok: true,
1168
+ backend: deps.backend.name
1169
+ } : ready;
1170
+ }
1171
+ function assertCurrent(plan) {
1172
+ deps.signal?.throwIfAborted();
1173
+ const entry = owned.get(plan);
1174
+ if (!entry || entry.revision !== void 0 && entry.revision !== state().revision) throw new Error("stale-approval: shell execution mode changed or the plan belongs to another host. Nothing ran.");
1175
+ if (deps.authorizationIdentity && (!entry.authorizationIdentity || entry.authorizationIdentity !== deps.authorizationIdentity())) throw new Error("stale-approval: authorization strategy changed. Nothing ran.");
1176
+ if (entry.routingRevision !== void 0 && entry.routingRevision !== deps.routingRevision?.()) throw new Error("stale-approval: network routing changed. Nothing ran.");
1177
+ if (entry.availability !== void 0 && entry.availability !== JSON.stringify(available())) throw new Error("stale-approval: sandbox capability changed. Plan and approve the command again.");
1178
+ if ("signal" in entry.authority && entry.authority.signal.aborted) throw new Error("exit by cancellation. The command did not run.");
1179
+ if (plan.mode !== entry.mode) throw new Error("stale-approval: the execution mode differs from the host plan");
1180
+ if (plan.cwd !== plan.execution.cwd || JSON.stringify(plan.execution) !== entry.execution) throw new Error("stale-approval: execution differs from the host plan. Nothing ran.");
1181
+ }
1182
+ async function plan(ctx, input, confined) {
1183
+ const snapshot = state();
1184
+ const routingRevision = deps.routingRevision?.();
1185
+ const authorizationIdentity = deps.authorizationIdentity?.();
1186
+ const capability = confined || snapshot.enabled ? available() : void 0;
1187
+ const result = await deps.planner.plan({
1188
+ address: ctx.address,
1189
+ sessionId: ctx.sessionId
1190
+ }, input, capability?.ok ? "sandboxed" : "direct", !confined);
1191
+ if (!result.ok) return result;
1192
+ const selected = result.plan.mode === "direct" && capability && !capability.ok ? {
1193
+ ...result.plan,
1194
+ fallbackReason: capability.reason
1195
+ } : result.plan;
1196
+ owned.set(selected, {
1197
+ ...confined ? {} : { revision: snapshot.revision },
1198
+ authority: {
1199
+ sessionId: ctx.sessionId,
1200
+ address: { ...ctx.address },
1201
+ ..."signal" in ctx ? { signal: ctx.signal } : {}
1202
+ },
1203
+ operationId: input.operationId ?? "unscoped",
1204
+ issuerToolCallId: "toolCallId" in ctx && typeof ctx.toolCallId === "string" ? ctx.toolCallId : input.operationId ?? "unscoped",
1205
+ ...input.authorizationScope ? { authorizationScope: input.authorizationScope } : {},
1206
+ ...input.originLifetime ? { originLifetime: input.originLifetime } : {},
1207
+ ...routingRevision === void 0 ? {} : { routingRevision },
1208
+ ...authorizationIdentity === void 0 ? {} : { authorizationIdentity },
1209
+ mode: selected.mode,
1210
+ execution: JSON.stringify(selected.execution),
1211
+ ...capability ? { availability: JSON.stringify(capability) } : {}
1212
+ });
1213
+ try {
1214
+ assertCurrent(selected);
1215
+ } catch (error) {
1216
+ return {
1217
+ ok: false,
1218
+ reason: "stale-approval",
1219
+ message: String(error)
1220
+ };
1221
+ }
1222
+ return {
1223
+ ok: true,
1224
+ plan: selected
1225
+ };
1226
+ }
1227
+ return {
1228
+ beginFailure(input) {
1229
+ if (deps.failures) return deps.failures.beginFailure(input);
1230
+ if (!deps.beginFailure) throw new Error("Failure authorization owner is unavailable");
1231
+ return deps.beginFailure(input);
1232
+ },
1233
+ start: async (spec, onExit) => {
1234
+ deps.signal?.throwIfAborted();
1235
+ if (!deps.start) return Promise.reject(/* @__PURE__ */ new Error("Sandbox executor is unavailable"));
1236
+ const launch = spec.authorizationScope ? launches.get(spec.authorizationScope.id) : void 0;
1237
+ try {
1238
+ const handle = await deps.start(spec, onExit);
1239
+ if (launch?.claim && launch.attempt) launch.claim.launchSettled(launch.attempt);
1240
+ return handle;
1241
+ } catch (error) {
1242
+ if (launch?.claim) {
1243
+ if (launch.attempt) try {
1244
+ launch.claim.launchSettled(launch.attempt);
1245
+ } catch {
1246
+ launch.claim.cancel("launch-failed");
1247
+ }
1248
+ else launch.claim.cancel("launch-failed");
1249
+ }
1250
+ if (launch) try {
1251
+ await deps.failures?.abandon(launch.scopeId);
1252
+ } catch {}
1253
+ throw error;
1254
+ } finally {
1255
+ if (spec.authorizationScope) launches.delete(spec.authorizationScope.id);
1256
+ }
1257
+ },
1258
+ available,
1259
+ status() {
1260
+ const enabled = state().enabled;
1261
+ const availability = available();
1262
+ return {
1263
+ enabled,
1264
+ mode: enabled && availability.ok ? "sandboxed" : "direct",
1265
+ availability
1266
+ };
1267
+ },
1268
+ plan: (ctx, input) => plan(ctx, input, false),
1269
+ planSandboxed: (ctx, input) => plan(ctx, input, true),
1270
+ prepare(plan, command, ctx) {
1271
+ assertCurrent(plan);
1272
+ if (JSON.stringify(command) !== JSON.stringify(plan.execution.argv)) throw new Error("stale-approval: command differs from approved execution");
1273
+ const entry = owned.get(plan);
1274
+ const refreshed = plan.mode === "sandboxed" ? deps.refreshPlan?.(plan) ?? plan : void 0;
1275
+ const launchScope = Object.freeze({
1276
+ authority: Object.freeze({
1277
+ sessionId: entry.authority.sessionId,
1278
+ address: Object.freeze({ ...entry.authority.address })
1279
+ }),
1280
+ issuerToolCallId: entry.issuerToolCallId,
1281
+ operationId: entry.operationId,
1282
+ owner: deps.owner ?? "sandbox",
1283
+ activationEpoch: deps.activationEpoch ?? 0,
1284
+ mode: plan.mode,
1285
+ read: Object.freeze([...refreshed?.read ?? []]),
1286
+ write: Object.freeze([...refreshed?.write ?? []]),
1287
+ deny: Object.freeze([...refreshed?.deny ?? []]),
1288
+ cwd: plan.cwd,
1289
+ tmp: plan.tmp
1290
+ });
1291
+ const scopeId = deps.newId?.() ?? `unscoped:${++preparedId}`;
1292
+ let claim;
1293
+ if (plan.requested.receipt !== void 0) {
1294
+ if (!ctx || !deps.receipts || plan.mode !== "sandboxed") throw new Error("receipt-unavailable");
1295
+ const inputs = [...(plan.requested.read ?? []).map((path) => ({
1296
+ kind: "file",
1297
+ path: resolveThroughExisting(path, deps.host),
1298
+ operations: ["read"]
1299
+ })), ...(plan.requested.write ?? []).map((path) => ({
1300
+ kind: "file",
1301
+ path: resolveThroughExisting(path, deps.host),
1302
+ operations: ["write"]
1303
+ }))];
1304
+ claim = deps.receipts.claim(ctx, {
1305
+ receiptId: plan.requested.receipt,
1306
+ inputs,
1307
+ consumerOperationId: ctx.toolCallId,
1308
+ preparedPlanId: scopeId
1309
+ });
1310
+ }
1311
+ const launch = {
1312
+ scopeId,
1313
+ ...claim ? { claim } : {}
1314
+ };
1315
+ if (entry.authorizationScope) launches.set(entry.authorizationScope.id, launch);
1316
+ let diagnosticTag;
1317
+ if (entry.authorizationScope && entry.originLifetime && deps.failures) {
1318
+ diagnosticTag = scopeId;
1319
+ const collector = deps.diagnostics?.register(diagnosticTag) ?? {
1320
+ finish: async () => ({
1321
+ availability: "unsupported",
1322
+ partial: false,
1323
+ dropped: 0,
1324
+ records: []
1325
+ }),
1326
+ release() {}
1327
+ };
1328
+ deps.failures.register({
1329
+ scopeId,
1330
+ launchScope,
1331
+ authorizationScope: entry.authorizationScope,
1332
+ originLifetime: entry.originLifetime,
1333
+ collector
1334
+ });
1335
+ }
1336
+ let released = false;
1337
+ let releasing;
1338
+ const release = async () => {
1339
+ if (released) return;
1340
+ if (releasing) return releasing;
1341
+ if (launch.attempt !== void 0 && (claim || entry.authorizationScope && entry.originLifetime)) throw new Error("prepared-launch-owned: a physical start already owns this preparation");
1342
+ releasing = (async () => {
1343
+ claim?.cancel("preparation-released");
1344
+ if (entry.authorizationScope && launches.get(entry.authorizationScope.id) === launch) launches.delete(entry.authorizationScope.id);
1345
+ if (deps.failures && entry.authorizationScope && entry.originLifetime) await deps.failures.abandon(scopeId);
1346
+ else await entry.authorizationScope?.close();
1347
+ released = true;
1348
+ })();
1349
+ try {
1350
+ await releasing;
1351
+ } finally {
1352
+ releasing = void 0;
1353
+ }
1354
+ };
1355
+ let admittedAttempt;
1356
+ const beforeSpawn = (launchAttemptId) => {
1357
+ if (released || releasing) throw new Error("prepared-launch-released");
1358
+ launch.attempt ??= launchAttemptId;
1359
+ assertCurrent(plan);
1360
+ if (admittedAttempt !== void 0 && admittedAttempt !== launchAttemptId) throw new Error("launch-attempt-mismatch: prepared execution already belongs to another physical start");
1361
+ if (plan.mode === "sandboxed" && JSON.stringify(deps.refreshPlan?.(plan) ?? plan) !== JSON.stringify(refreshed)) throw new Error("stale-approval: the final sandbox scope changed before spawn");
1362
+ admittedAttempt = launchAttemptId;
1363
+ claim?.beforeSpawn(launchAttemptId);
1364
+ };
1365
+ const prepared = {
1366
+ scopeId,
1367
+ launchScope,
1368
+ beforeSpawn,
1369
+ release
1370
+ };
1371
+ if (plan.mode === "direct") return {
1372
+ ...prepared,
1373
+ mode: "direct",
1374
+ ...plan.fallbackReason ? { fallbackReason: plan.fallbackReason } : {},
1375
+ argv: [...command],
1376
+ externalAllowed: true,
1377
+ proxyEnvironment: plan.proxyEnvironment,
1378
+ assertCurrent: () => assertCurrent(plan)
1379
+ };
1380
+ if (!deps.backend) throw new Error("no sandbox backend is available on this host");
1381
+ if (!refreshed) throw new Error("Sandboxed execution scope is unavailable");
1382
+ const available = deps.backend.available();
1383
+ if (!available.ok) throw new Error(`sandbox-unavailable: ${available.reason}`);
1384
+ return {
1385
+ ...prepared,
1386
+ mode: "sandboxed",
1387
+ argv: deps.backend.argv({
1388
+ ...refreshed,
1389
+ ...diagnosticTag ? { diagnosticTag } : {}
1390
+ }, command),
1391
+ externalAllowed: refreshed.externalAllowed,
1392
+ proxyEnvironment: refreshed.proxyEnvironment ?? {},
1393
+ assertCurrent: () => assertCurrent(plan)
1394
+ };
1395
+ },
1396
+ authorize(ctx, plan, reason) {
1397
+ try {
1398
+ assertCurrent(plan);
1399
+ } catch (error) {
1400
+ return {
1401
+ kind: "refused",
1402
+ reason: "policy",
1403
+ message: String(error)
1404
+ };
1405
+ }
1406
+ return deps.authorize(ctx, plan.requested, reason, plan.execution, plan.mode, plan.mode === "direct" ? plan.fallbackReason : void 0);
1407
+ }
1408
+ };
1409
+ }
1410
+ //#endregion
1411
+ //#region src/settings.ts
1412
+ /** Creates atomic, replayable user read-root collection updates. */
1413
+ function createReadableManagement(deps) {
1414
+ function mutate(paths, operationId, remove) {
1415
+ if (!Array.isArray(paths) || paths.length < 1 || paths.length > 64 || paths.some((path) => typeof path !== "string" || path.length > 4096)) throw new Error("paths must contain 1..64 bounded paths");
1416
+ return deps.operations.atomic({
1417
+ scope: "readable-paths",
1418
+ method: remove ? "removeReadablePaths" : "addReadablePaths",
1419
+ operationId,
1420
+ params: {
1421
+ operationId,
1422
+ paths
1423
+ }
1424
+ }, (scope) => {
1425
+ const normalized = paths.map((path) => {
1426
+ if (!remove) {
1427
+ const refusal = readablePathRefusal(path, { sealed: deps.sealed }, deps.host);
1428
+ if (refusal) throw new Error(refusal);
1429
+ }
1430
+ return resolveThroughExisting(path, deps.host);
1431
+ });
1432
+ const previous = deps.read();
1433
+ const targets = /* @__PURE__ */ new Set([...paths, ...normalized]);
1434
+ const next = remove ? previous.filter((path) => !targets.has(path)) : [.../* @__PURE__ */ new Set([...previous, ...normalized])];
1435
+ if (JSON.stringify(next) !== JSON.stringify(previous)) deps.update(next, scope);
1436
+ return { readable: [...next] };
1437
+ });
1438
+ }
1439
+ return {
1440
+ /** Adds canonical read roots in one host commit; identical intent retries replay the original result. */
1441
+ add(paths, operationId) {
1442
+ return mutate(paths, operationId, false);
1443
+ },
1444
+ /** Removes exact or canonical read roots atomically; absent roots are idempotent. */
1445
+ remove(paths, operationId) {
1446
+ return mutate(paths, operationId, true);
1447
+ }
1448
+ };
1449
+ }
1450
+ //#endregion
1451
+ //#region src/sources.ts
1452
+ /** Validates generic owner roots without interpreting capability-specific configuration. */
1453
+ /** Creates the host projection; inspection never reads file bodies or expands locators. */
1454
+ function createSandboxReadableProjection(deps) {
1455
+ const { host } = deps;
1456
+ function inspect(target) {
1457
+ if (!isAbsolute(target.path) || normalize(target.path) !== target.path || target.path === parse(target.path).root || target.path === resolveThroughExisting(host.os.homedir(), host) || !["file", "directory"].includes(target.targetType)) return "invalid";
1458
+ try {
1459
+ const real = host.fs.realpathSync(target.path);
1460
+ if (deps.sealed.some((root) => isWithin(resolveThroughExisting(root, host), real))) return "sealed";
1461
+ if (real !== target.path) return "changed-target";
1462
+ const stat = host.fs.statSync(real);
1463
+ if (target.targetType === "file" ? !stat.isFile() : !stat.isDirectory()) return "type-mismatch";
1464
+ return null;
1465
+ } catch {
1466
+ return "missing";
1467
+ }
1468
+ }
1469
+ function current() {
1470
+ const base = [...deps.base()];
1471
+ const sources = deps.registry.list().map(({ owner, epoch, source }) => {
1472
+ const view = {
1473
+ owner,
1474
+ epoch,
1475
+ id: source.id,
1476
+ label: source.label,
1477
+ revision: 0,
1478
+ paths: [],
1479
+ status: "unavailable",
1480
+ rejected: []
1481
+ };
1482
+ try {
1483
+ const data = source.read();
1484
+ if (!Number.isSafeInteger(data.revision) || data.revision < 0 || !Array.isArray(data.paths) || data.paths.length > 4096) return view;
1485
+ const paths = [], rejected = [];
1486
+ for (const target of data.paths) {
1487
+ if (!target || typeof target.path !== "string" || target.path.length > 4096) return view;
1488
+ const reason = inspect(target);
1489
+ if (reason) rejected.push({
1490
+ path: target.path,
1491
+ reason
1492
+ });
1493
+ else if (!paths.some((item) => item.path === target.path && item.targetType === target.targetType)) paths.push({
1494
+ path: target.path,
1495
+ targetType: target.targetType
1496
+ });
1497
+ }
1498
+ return {
1499
+ ...view,
1500
+ revision: data.revision,
1501
+ paths,
1502
+ rejected,
1503
+ status: "active"
1504
+ };
1505
+ } catch {
1506
+ return view;
1507
+ }
1508
+ });
1509
+ const baseTargets = base.map((path) => {
1510
+ try {
1511
+ const real = host.fs.realpathSync(path), stat = host.fs.statSync(real);
1512
+ return {
1513
+ path,
1514
+ real,
1515
+ type: stat.isFile() ? "file" : stat.isDirectory() ? "directory" : "other"
1516
+ };
1517
+ } catch {
1518
+ return {
1519
+ path,
1520
+ real: null,
1521
+ type: "missing"
1522
+ };
1523
+ }
1524
+ });
1525
+ return {
1526
+ revision: host.crypto.createHash("sha256").update(JSON.stringify({
1527
+ base,
1528
+ baseTargets,
1529
+ sources,
1530
+ enabled: deps.enabled?.() ?? true
1531
+ })).digest("hex"),
1532
+ base,
1533
+ sources,
1534
+ enabled: deps.enabled?.() ?? true
1535
+ };
1536
+ }
1537
+ return {
1538
+ inspect,
1539
+ current
1540
+ };
1541
+ }
1542
+ //#endregion
1543
+ //#region src/index.ts
1544
+ /** Owns Agent shell planning, launch orchestration, rules and settings. */
1545
+ const plugin = {
1546
+ name: "@eum-agent/sandbox",
1547
+ requires: [
1548
+ "sandbox-host",
1549
+ "network",
1550
+ "subprocess",
1551
+ "work-lifecycle",
1552
+ "configuration-transactions",
1553
+ "owner-operations",
1554
+ "bulk-transactions",
1555
+ "resource-authorization",
1556
+ "session-context"
1557
+ ],
1558
+ optionalServices: [
1559
+ "authorization-strategy",
1560
+ "session-skill-readables",
1561
+ "sandbox-preset-summary",
1562
+ "sandbox-diagnostics"
1563
+ ],
1564
+ provides: [
1565
+ "sandbox",
1566
+ "sandbox-settings",
1567
+ "sandbox-settings-participant",
1568
+ "sandbox-readable-projection",
1569
+ "workspace-directory-note"
1570
+ ],
1571
+ async apply(ctx) {
1572
+ const host = ctx.services.get("sandbox-host");
1573
+ await host.backend?.initialize?.(ctx.signal);
1574
+ ctx.signal.throwIfAborted();
1575
+ const network = ctx.services.get("network");
1576
+ const subprocess = ctx.services.get("subprocess");
1577
+ const transactions = ctx.services.get("configuration-transactions");
1578
+ let diagnostics;
1579
+ try {
1580
+ diagnostics = ctx.services.find("sandbox-diagnostics")?.acquire({ log: () => ctx.log.emit({
1581
+ level: "info",
1582
+ event: "plugin.event",
1583
+ fields: { localCode: "SANDBOX_RUNTIME_DIAGNOSTIC" }
1584
+ }) });
1585
+ } catch (error) {
1586
+ ctx.log.emit({
1587
+ level: "warn",
1588
+ event: "plugin.event",
1589
+ fields: { localCode: "SANDBOX_DIAGNOSTICS_ACQUISITION_IS_UNAVAILABLE" }
1590
+ });
1591
+ }
1592
+ const temporaryRoots = () => {
1593
+ try {
1594
+ return diagnostics?.temporaryRoots();
1595
+ } catch {
1596
+ return;
1597
+ }
1598
+ };
1599
+ const failures = createFailureCoordinator({
1600
+ host,
1601
+ ...diagnostics ? { diagnostics } : {}
1602
+ });
1603
+ const offInvalidated = ctx.services.get("session-context").onInvalidated(failures.invalidate);
1604
+ ctx.onDispose(offInvalidated);
1605
+ const storage = ctx.storage.open();
1606
+ const database = storage.db;
1607
+ const table = storage.tableName("settings");
1608
+ database.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL)`);
1609
+ const frame = ctx.client.registerFrame({
1610
+ name: "sandboxChanged",
1611
+ delivery: "broadcast",
1612
+ payload: SandboxConfiguration.extend({ protectedLocalPorts: z.array(z.number()).optional() })
1613
+ });
1614
+ let revision = 0;
1615
+ const read = () => {
1616
+ ctx.signal.throwIfAborted();
1617
+ const row = database.prepare(`SELECT value FROM ${table} WHERE id = 1`).get();
1618
+ return row ? SandboxConfiguration.parse(JSON.parse(row.value)) : {
1619
+ enabled: true,
1620
+ sharedTemporaryWrite: true,
1621
+ readable: [],
1622
+ networkPolicies: {
1623
+ external: "ask",
1624
+ connect: "ask",
1625
+ listen: "ask"
1626
+ }
1627
+ };
1628
+ };
1629
+ const strategy = () => ctx.services.find("authorization-strategy");
1630
+ const projection = createSandboxReadableProjection({
1631
+ host: host.host,
1632
+ registry: { list: () => host.readableSources() },
1633
+ enabled: () => read().enabled,
1634
+ base: () => read().readable,
1635
+ sealed: host.sealedDirectories
1636
+ });
1637
+ ctx.services.provide("sandbox-readable-projection", projection);
1638
+ const sandboxNetwork = createSandboxNetwork({ networkPolicies: () => read().networkPolicies }, host.resources, () => frame.emit({
1639
+ ...read(),
1640
+ protectedLocalPorts: [...host.protectedPorts()]
1641
+ }));
1642
+ const bindPorts = () => {
1643
+ const port = host.protectedPorts()[0];
1644
+ if (port !== void 0) sandboxNetwork.bind(port);
1645
+ };
1646
+ bindPorts();
1647
+ const unsubscribe = host.subscribe(bindPorts);
1648
+ ctx.onDispose(unsubscribe);
1649
+ const planner = createSandboxPlanner({
1650
+ host: host.host,
1651
+ fence: host.fence,
1652
+ readable: () => read().readable,
1653
+ contributed: (caller) => [...projection.current().sources.flatMap((source) => source.paths.map((target) => target.path)), ...ctx.services.find("session-skill-readables")?.roots(caller) ?? []],
1654
+ sharedTemporaryWrite: () => read().sharedTemporaryWrite,
1655
+ temporaryRoots,
1656
+ network: sandboxNetwork.effective,
1657
+ triggerExternal: (caller) => host.resources.holdsNetwork(caller.address, caller.sessionId),
1658
+ sealed: host.sealedDirectories,
1659
+ proxyEnvironment: async () => (await network.environment()).env,
1660
+ access: host.resources
1661
+ });
1662
+ const handles = /* @__PURE__ */ new Set();
1663
+ const starts = /* @__PURE__ */ new Set();
1664
+ let withdrawing = false;
1665
+ const start = (spec, onExit) => {
1666
+ ctx.signal.throwIfAborted();
1667
+ if (withdrawing) return Promise.reject(/* @__PURE__ */ new Error("Sandbox execution owner is withdrawing"));
1668
+ let completed = false;
1669
+ let owned;
1670
+ const pending = subprocess.start({
1671
+ ...spec,
1672
+ beforeSpawn(launchAttemptId) {
1673
+ ctx.signal.throwIfAborted();
1674
+ if (withdrawing) throw new Error("Sandbox execution owner is withdrawing");
1675
+ spec.beforeSpawn?.(launchAttemptId);
1676
+ }
1677
+ }, (ending) => {
1678
+ completed = true;
1679
+ if (owned) handles.delete(owned);
1680
+ return onExit(ending);
1681
+ }).then(async (handle) => {
1682
+ owned = handle;
1683
+ if (!completed) handles.add(handle);
1684
+ if (withdrawing || ctx.signal.aborted) try {
1685
+ await handle.stop("cancelled");
1686
+ } catch (error) {
1687
+ throw Object.assign(new Error("Sandbox withdrawal cleanup failed", { cause: error }), {
1688
+ reason: "unavailable",
1689
+ cleanupHandle: handle
1690
+ });
1691
+ }
1692
+ return handle;
1693
+ }, (error) => {
1694
+ const retained = error?.cleanupHandle;
1695
+ if (retained) {
1696
+ owned = retained;
1697
+ if (!completed) handles.add(retained);
1698
+ }
1699
+ throw error;
1700
+ });
1701
+ starts.add(pending);
1702
+ pending.finally(() => starts.delete(pending)).catch(() => {});
1703
+ return pending;
1704
+ };
1705
+ let draining;
1706
+ const drain = () => {
1707
+ withdrawing = true;
1708
+ draining ??= (async () => {
1709
+ await Promise.allSettled([...starts]);
1710
+ await Promise.all([...handles].map((handle) => handle.stop("cancelled")));
1711
+ await failures.close();
1712
+ await diagnostics?.close();
1713
+ })().catch((error) => {
1714
+ draining = void 0;
1715
+ throw error;
1716
+ });
1717
+ return draining;
1718
+ };
1719
+ ctx.signal.addEventListener("abort", () => {
1720
+ withdrawing = true;
1721
+ for (const handle of handles) handle.stop("cancelled").catch(() => {});
1722
+ }, { once: true });
1723
+ const removeDrain = ctx.services.get("work-lifecycle").register(drain);
1724
+ ctx.onDispose(async () => {
1725
+ await drain();
1726
+ removeDrain();
1727
+ });
1728
+ const sandbox = createSandbox({
1729
+ host: host.host,
1730
+ newId: randomUUID,
1731
+ owner: ctx.pluginName,
1732
+ activationEpoch: ctx.activationEpoch,
1733
+ failures,
1734
+ ...diagnostics ? { diagnostics } : {},
1735
+ receipts: ctx.services.get("resource-authorization"),
1736
+ signal: ctx.signal,
1737
+ routingRevision: () => network.routingRevision(),
1738
+ authorizationIdentity: strategy,
1739
+ start,
1740
+ refreshPlan: planner.refresh,
1741
+ state: () => ({
1742
+ enabled: read().enabled,
1743
+ revision
1744
+ }),
1745
+ planner,
1746
+ ...host.backend ? { backend: host.backend } : {},
1747
+ authorize: createAuthorize({
1748
+ host: host.host,
1749
+ access: host.resources,
1750
+ receipts: ctx.services.get("resource-authorization"),
1751
+ available: () => Boolean(strategy()),
1752
+ validateTarget: (input) => host.validateTarget(input),
1753
+ approval: {
1754
+ questionId: (id) => strategy()?.askQuestionId(id),
1755
+ decide: (authority, input) => strategy()?.ask(authority, input) ?? {
1756
+ kind: "result",
1757
+ result: { kind: "unavailable" },
1758
+ source: "policy-deny"
1759
+ }
1760
+ },
1761
+ defaultPolicy: () => strategy()?.policy() ?? "deny",
1762
+ policies: () => read().networkPolicies,
1763
+ protectedPorts: () => host.protectedPorts()
1764
+ })
1765
+ });
1766
+ ctx.services.provide("sandbox", sandbox);
1767
+ ctx.services.provide("workspace-directory-note", createScopeNote({
1768
+ sandbox,
1769
+ fence: host.fence,
1770
+ settings: read,
1771
+ temporaryRoots,
1772
+ presets: () => ctx.services.find("sandbox-preset-summary")
1773
+ }));
1774
+ const participant = {
1775
+ connectionIdentity: storage.connectionIdentity,
1776
+ prepare(value) {
1777
+ const update = SandboxConfigurationUpdate.parse(value);
1778
+ const input = SandboxConfiguration.parse({
1779
+ ...read(),
1780
+ ...update
1781
+ });
1782
+ const unchanged = JSON.stringify(input) === JSON.stringify(read());
1783
+ const at = revision;
1784
+ const assertCurrent = () => {
1785
+ ctx.signal.throwIfAborted();
1786
+ if (revision !== at) throw new Error("Sandbox settings changed before commit");
1787
+ };
1788
+ return {
1789
+ assertCurrent,
1790
+ write() {
1791
+ assertCurrent();
1792
+ if (unchanged) return;
1793
+ database.prepare(`INSERT INTO ${table} (id, value) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET value = excluded.value`).run(JSON.stringify(input));
1794
+ },
1795
+ publish() {
1796
+ if (!unchanged) {
1797
+ revision++;
1798
+ frame.emit(input);
1799
+ }
1800
+ }
1801
+ };
1802
+ }
1803
+ };
1804
+ ctx.services.provide("sandbox-settings-participant", participant);
1805
+ const update = (value) => transactions.commit([{
1806
+ service: "sandbox-settings-participant",
1807
+ value
1808
+ }]);
1809
+ const security = () => {
1810
+ const config = read(), policy = strategy()?.policy();
1811
+ return {
1812
+ status: "ready",
1813
+ sandboxEnabled: config.enabled,
1814
+ sharedTemporaryWrite: config.sharedTemporaryWrite,
1815
+ networkPolicies: config.networkPolicies,
1816
+ ...policy === void 0 ? {} : { approvalPolicy: policy }
1817
+ };
1818
+ };
1819
+ ctx.client.registerMethod({
1820
+ name: "securityGet",
1821
+ params: z.object({}).strict(),
1822
+ result: SecurityState,
1823
+ handle: security
1824
+ });
1825
+ ctx.client.registerMethod({
1826
+ name: "securitySet",
1827
+ params: SecurityConfiguration,
1828
+ result: SecurityState,
1829
+ handle(input) {
1830
+ transactions.commit([...input.approvalPolicy === void 0 ? [] : [{
1831
+ service: "authorization-settings-participant",
1832
+ value: { policy: input.approvalPolicy }
1833
+ }], {
1834
+ service: "sandbox-settings-participant",
1835
+ value: {
1836
+ enabled: input.sandboxEnabled,
1837
+ sharedTemporaryWrite: input.sharedTemporaryWrite,
1838
+ networkPolicies: input.networkPolicies
1839
+ }
1840
+ }]);
1841
+ return security();
1842
+ }
1843
+ });
1844
+ ctx.client.registerMethod({
1845
+ name: "getEnabled",
1846
+ params: z.object({}).strict(),
1847
+ result: SandboxStatus,
1848
+ handle: () => sandbox.status()
1849
+ });
1850
+ ctx.client.registerMethod({
1851
+ name: "setEnabled",
1852
+ params: z.object({ enabled: z.boolean() }).strict(),
1853
+ result: SandboxStatus,
1854
+ handle(input) {
1855
+ update(input);
1856
+ return sandbox.status();
1857
+ }
1858
+ });
1859
+ const networkState = () => ({
1860
+ policies: read().networkPolicies,
1861
+ protectedLocalPorts: [...host.protectedPorts()],
1862
+ externalApproval: host.resources.list().find((row) => row.kind === "sandbox-network")
1863
+ });
1864
+ const networkStateSchema = z.object({
1865
+ policies: NetworkPolicies,
1866
+ protectedLocalPorts: z.array(z.number()),
1867
+ externalApproval: z.unknown().optional()
1868
+ });
1869
+ ctx.client.registerMethod({
1870
+ name: "getNetworkPolicies",
1871
+ params: z.object({}).strict(),
1872
+ result: networkStateSchema,
1873
+ handle: networkState
1874
+ });
1875
+ ctx.client.registerMethod({
1876
+ name: "setNetworkPolicies",
1877
+ params: NetworkPolicies,
1878
+ result: networkStateSchema,
1879
+ handle(input) {
1880
+ update({ networkPolicies: input });
1881
+ return networkState();
1882
+ }
1883
+ });
1884
+ const readable = () => ({ readable: read().readable });
1885
+ const readableSchema = z.object({ readable: z.array(z.string()) });
1886
+ ctx.client.registerMethod({
1887
+ name: "listReadablePaths",
1888
+ params: z.object({}).strict(),
1889
+ result: readableSchema,
1890
+ handle: readable
1891
+ });
1892
+ const collection = createReadableManagement({
1893
+ host: host.host,
1894
+ sealed: host.sealedDirectories,
1895
+ operations: ctx.services.get("owner-operations"),
1896
+ read: () => read().readable,
1897
+ update(paths, scope) {
1898
+ const prepared = participant.prepare({ readable: [...paths] });
1899
+ ctx.services.get("bulk-transactions").commit([{
1900
+ connectionIdentity: storage.connectionIdentity,
1901
+ ...prepared
1902
+ }], scope);
1903
+ }
1904
+ });
1905
+ const management = {
1906
+ read,
1907
+ status: () => sandbox.status(),
1908
+ addReadablePaths: (paths, operationId) => ReadablePathsReceipt.parse(collection.add(paths, operationId)),
1909
+ removeReadablePaths: (paths, operationId) => ReadablePathsReceipt.parse(collection.remove(paths, operationId))
1910
+ };
1911
+ ctx.services.provide("sandbox-settings", management);
1912
+ ctx.client.registerMethod({
1913
+ name: "addReadablePaths",
1914
+ params: ReadablePathsMutation,
1915
+ result: ReadablePathsReceipt,
1916
+ handle: (input) => management.addReadablePaths(input.paths, input.operationId)
1917
+ });
1918
+ ctx.client.registerMethod({
1919
+ name: "removeReadablePaths",
1920
+ params: ReadablePathsMutation,
1921
+ result: ReadablePathsReceipt,
1922
+ handle: (input) => management.removeReadablePaths(input.paths, input.operationId)
1923
+ });
1924
+ const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1925
+ if (existsSync(module)) ctx.client.registerUi({ module });
1926
+ }
1927
+ };
1928
+ //#endregion
1929
+ export { createSandbox, createSandboxPlanner, plugin as default };