@eum-agent/sandbox 1.0.0 → 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 (3) hide show
  1. package/dist/index.js +854 -61
  2. package/package.json +4 -4
  3. package/ui/ui.js +70 -12
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { z } from "zod";
@@ -206,6 +207,19 @@ function createAuthorize(deps) {
206
207
  ...item,
207
208
  operations: ["listen"]
208
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
+ }
209
223
  try {
210
224
  for (const input of locals) deps.validateTarget(input);
211
225
  } catch (error) {
@@ -226,7 +240,7 @@ function createAuthorize(deps) {
226
240
  reason: "policy",
227
241
  message: "The requested sandbox network capability is denied by its policy."
228
242
  };
229
- const toolInputs = 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")));
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")));
230
244
  if (!deps.access.holdsCommand(command)) toolInputs.unshift({
231
245
  kind: "command",
232
246
  ...command
@@ -242,6 +256,7 @@ function createAuthorize(deps) {
242
256
  const inputs = [...defaultPolicy === "ask" ? toolInputs : [], ...networkInputs];
243
257
  const id = `sandbox:${host.crypto.createHash("sha256").update(JSON.stringify({
244
258
  mode,
259
+ receiptId: permissions.receipt,
245
260
  fallbackReason,
246
261
  command,
247
262
  files,
@@ -305,6 +320,472 @@ function createAuthorize(deps) {
305
320
  };
306
321
  }
307
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
308
789
  //#region src/local-ports.ts
309
790
  /** Owns the actual gateway port, and refreshes all network decisions before spawning. */
310
791
  function createSandboxNetwork(config, access, changed) {
@@ -365,11 +846,6 @@ function createSandboxNetwork(config, access, changed) {
365
846
  * This module is the **one** caller of `fence.roots`. A tool that derived its own rules would be a second path
366
847
  * judgement, and a second one is a second thing to get wrong.
367
848
  */
368
- /** `/tmp` on macOS is a symlink to this, and a command that writes through
369
- * `/tmp` has to land somewhere the rules name. The per-call temporary
370
- * directory is under it already; this makes the shared one readable, which
371
- * is what `mktemp`-using scripts and most build tools assume. */
372
- const SHARED_TMP = "/private/tmp";
373
849
  function createSandboxPlanner(deps) {
374
850
  const host = deps.host;
375
851
  /** Whether a path is somewhere a command could start. A permission that names
@@ -383,6 +859,11 @@ function createSandboxPlanner(deps) {
383
859
  }
384
860
  const sealed = (deps.sealed ?? []).map((path) => resolveThroughExisting(path, host));
385
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
+ }
386
867
  /** A permission path that no answer could ever grant, or
387
868
  * `undefined`. Judged on the real path, so a symlink into a protected
388
869
  * tree is caught, and judged *before* anybody is asked — the person never
@@ -424,6 +905,7 @@ function createSandboxPlanner(deps) {
424
905
  const grantedRead = mode === "direct" ? [] : (permissions?.read ?? []).map((path) => resolveThroughExisting(path, host));
425
906
  const grantedWrite = mode === "direct" ? [] : (permissions?.write ?? []).map((path) => resolveThroughExisting(path, host));
426
907
  const authorized = roots.roots.map((root) => root.path);
908
+ const workspaceWrite = roots.roots.filter((root) => root.access === "read-write").map((root) => root.path);
427
909
  const permittedRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
428
910
  const permittedWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
429
911
  const read = dedupe([
@@ -431,15 +913,17 @@ function createSandboxPlanner(deps) {
431
913
  ...permittedRead,
432
914
  ...permittedWrite,
433
915
  ...resolveReadablePaths(deps.readable(), host),
434
- ...includeContributions && mode === "sandboxed" ? deps.contributed?.() ?? [] : [],
916
+ ...includeContributions && mode === "sandboxed" ? deps.contributed?.(caller) ?? [] : [],
435
917
  tmp,
436
- SHARED_TMP,
918
+ ...temporaryRoots(),
437
919
  ...grantedRead,
438
920
  ...grantedWrite
439
921
  ]);
440
922
  const write = dedupe([
923
+ ...workspaceWrite,
441
924
  ...permittedWrite,
442
925
  tmp,
926
+ ...deps.sharedTemporaryWrite?.() !== false ? temporaryRoots() : [],
443
927
  ...grantedWrite
444
928
  ]);
445
929
  const deny = dedupe([...roots.sealed, ...sealed]);
@@ -455,19 +939,16 @@ function createSandboxPlanner(deps) {
455
939
  protectedLocalPorts: []
456
940
  };
457
941
  let cwd;
458
- if (request.cwd === void 0) {
459
- const fallback = [...permittedWrite, ...authorized].find(isDirectory);
460
- if (fallback === void 0) return {
461
- ok: false,
462
- reason: "no-directories",
463
- message: `workspace ${workspaceId} has nowhere for a command to run: none of its directories exist and nothing it may write is one`
464
- };
465
- cwd = fallback;
466
- } else {
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 {
467
948
  if (!isAbsolute(request.cwd)) return {
468
949
  ok: false,
469
950
  reason: "not-absolute",
470
- message: `cwd must be an absolute path: ${request.cwd}. A session has no current directory, because a workspace is not a directory`
951
+ message: `cwd must be an absolute native path resolved by the calling owner: ${request.cwd}`
471
952
  };
472
953
  const requested = resolveThroughExisting(request.cwd, host);
473
954
  if (!read.some((root) => isWithin(root, requested))) return {
@@ -517,16 +998,20 @@ function createSandboxPlanner(deps) {
517
998
  proxyEnvironment: currentNetwork.externalAllowed ? proxyEnvironment : {}
518
999
  };
519
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);
520
1005
  const currentRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
521
1006
  const currentWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
522
1007
  const read = dedupe([
523
- ...authorized,
1008
+ ...currentWorkspaceRead,
524
1009
  ...currentRead,
525
1010
  ...currentWrite,
526
1011
  ...resolveReadablePaths(deps.readable(), host),
527
- ...includeContributions && mode === "sandboxed" ? deps.contributed?.() ?? [] : [],
1012
+ ...includeContributions && mode === "sandboxed" ? deps.contributed?.(caller) ?? [] : [],
528
1013
  tmp,
529
- SHARED_TMP,
1014
+ ...temporaryRoots(),
530
1015
  ...grantedRead,
531
1016
  ...grantedWrite
532
1017
  ]);
@@ -536,10 +1021,13 @@ function createSandboxPlanner(deps) {
536
1021
  ...plan,
537
1022
  read,
538
1023
  write: dedupe([
1024
+ ...currentWorkspaceWrite,
539
1025
  ...currentWrite,
540
1026
  tmp,
1027
+ ...deps.sharedTemporaryWrite?.() !== false ? temporaryRoots() : [],
541
1028
  ...grantedWrite
542
1029
  ]),
1030
+ deny: dedupe([...currentRoots.sealed, ...sealed]),
543
1031
  ...network,
544
1032
  proxyEnvironment: network.externalAllowed && network.protectedLocalPorts.length ? proxyEnvironment : {}
545
1033
  };
@@ -570,7 +1058,8 @@ const NetworkPolicies = z.object({
570
1058
  const SandboxConfiguration = z.object({
571
1059
  enabled: z.boolean(),
572
1060
  readable: z.array(z.string()),
573
- networkPolicies: NetworkPolicies
1061
+ networkPolicies: NetworkPolicies,
1062
+ sharedTemporaryWrite: z.boolean()
574
1063
  }).strict();
575
1064
  /** Partial owner updates retain unrelated current settings. */
576
1065
  const SandboxConfigurationUpdate = SandboxConfiguration.partial().strict();
@@ -590,6 +1079,7 @@ const SandboxStatus = z.object({
590
1079
  const SecurityConfiguration = z.object({
591
1080
  approvalPolicy: NetworkPolicy.optional(),
592
1081
  sandboxEnabled: z.boolean(),
1082
+ sharedTemporaryWrite: z.boolean(),
593
1083
  networkPolicies: NetworkPolicies
594
1084
  }).strict();
595
1085
  /** Current settings snapshot; failed owner reads expose no partial values. */
@@ -597,8 +1087,65 @@ const SecurityState = z.discriminatedUnion("status", [SecurityConfiguration.exte
597
1087
  status: z.literal("recovery-required"),
598
1088
  error: z.string()
599
1089
  }).strict()]);
600
- z.object({ readable: z.array(z.string()) }).strict();
1090
+ /** Complete manual readable-path settings response. */
1091
+ const ReadablePaths = z.object({ readable: z.array(z.string()) }).strict();
601
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
+ }
602
1149
  //#endregion
603
1150
  //#region src/service.ts
604
1151
  /** Prefers available confinement and binds the selected capability to approval and launch. */
@@ -608,6 +1155,8 @@ function createSandbox(deps) {
608
1155
  revision: 0
609
1156
  };
610
1157
  const owned = /* @__PURE__ */ new WeakMap();
1158
+ let preparedId = 0;
1159
+ const launches = /* @__PURE__ */ new Map();
611
1160
  function available() {
612
1161
  if (!deps.backend) return {
613
1162
  ok: false,
@@ -646,7 +1195,15 @@ function createSandbox(deps) {
646
1195
  } : result.plan;
647
1196
  owned.set(selected, {
648
1197
  ...confined ? {} : { revision: snapshot.revision },
649
- authority: ctx,
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 } : {},
650
1207
  ...routingRevision === void 0 ? {} : { routingRevision },
651
1208
  ...authorizationIdentity === void 0 ? {} : { authorizationIdentity },
652
1209
  mode: selected.mode,
@@ -668,10 +1225,35 @@ function createSandbox(deps) {
668
1225
  };
669
1226
  }
670
1227
  return {
671
- start: (spec, onExit) => {
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) => {
672
1234
  deps.signal?.throwIfAborted();
673
1235
  if (!deps.start) return Promise.reject(/* @__PURE__ */ new Error("Sandbox executor is unavailable"));
674
- return deps.start(spec, onExit);
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
+ }
675
1257
  },
676
1258
  available,
677
1259
  status() {
@@ -685,10 +1267,109 @@ function createSandbox(deps) {
685
1267
  },
686
1268
  plan: (ctx, input) => plan(ctx, input, false),
687
1269
  planSandboxed: (ctx, input) => plan(ctx, input, true),
688
- prepare(plan, command) {
1270
+ prepare(plan, command, ctx) {
689
1271
  assertCurrent(plan);
690
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
+ };
691
1371
  if (plan.mode === "direct") return {
1372
+ ...prepared,
692
1373
  mode: "direct",
693
1374
  ...plan.fallbackReason ? { fallbackReason: plan.fallbackReason } : {},
694
1375
  argv: [...command],
@@ -697,12 +1378,16 @@ function createSandbox(deps) {
697
1378
  assertCurrent: () => assertCurrent(plan)
698
1379
  };
699
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");
700
1382
  const available = deps.backend.available();
701
1383
  if (!available.ok) throw new Error(`sandbox-unavailable: ${available.reason}`);
702
- const refreshed = deps.refreshPlan?.(plan) ?? plan;
703
1384
  return {
1385
+ ...prepared,
704
1386
  mode: "sandboxed",
705
- argv: deps.backend.argv(refreshed, command),
1387
+ argv: deps.backend.argv({
1388
+ ...refreshed,
1389
+ ...diagnosticTag ? { diagnosticTag } : {}
1390
+ }, command),
706
1391
  externalAllowed: refreshed.externalAllowed,
707
1392
  proxyEnvironment: refreshed.proxyEnvironment ?? {},
708
1393
  assertCurrent: () => assertCurrent(plan)
@@ -723,6 +1408,46 @@ function createSandbox(deps) {
723
1408
  };
724
1409
  }
725
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
726
1451
  //#region src/sources.ts
727
1452
  /** Validates generic owner roots without interpreting capability-specific configuration. */
728
1453
  /** Creates the host projection; inspection never reads file bodies or expands locators. */
@@ -824,20 +1549,59 @@ const plugin = {
824
1549
  "network",
825
1550
  "subprocess",
826
1551
  "work-lifecycle",
827
- "configuration-transactions"
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"
828
1563
  ],
829
- optionalServices: ["authorization-strategy"],
830
1564
  provides: [
831
1565
  "sandbox",
832
1566
  "sandbox-settings",
833
1567
  "sandbox-settings-participant",
834
- "sandbox-readable-projection"
1568
+ "sandbox-readable-projection",
1569
+ "workspace-directory-note"
835
1570
  ],
836
- apply(ctx) {
1571
+ async apply(ctx) {
837
1572
  const host = ctx.services.get("sandbox-host");
1573
+ await host.backend?.initialize?.(ctx.signal);
1574
+ ctx.signal.throwIfAborted();
838
1575
  const network = ctx.services.get("network");
839
1576
  const subprocess = ctx.services.get("subprocess");
840
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);
841
1605
  const storage = ctx.storage.open();
842
1606
  const database = storage.db;
843
1607
  const table = storage.tableName("settings");
@@ -853,6 +1617,7 @@ const plugin = {
853
1617
  const row = database.prepare(`SELECT value FROM ${table} WHERE id = 1`).get();
854
1618
  return row ? SandboxConfiguration.parse(JSON.parse(row.value)) : {
855
1619
  enabled: true,
1620
+ sharedTemporaryWrite: true,
856
1621
  readable: [],
857
1622
  networkPolicies: {
858
1623
  external: "ask",
@@ -885,7 +1650,9 @@ const plugin = {
885
1650
  host: host.host,
886
1651
  fence: host.fence,
887
1652
  readable: () => read().readable,
888
- contributed: () => projection.current().sources.flatMap((source) => source.paths.map((target) => target.path)),
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,
889
1656
  network: sandboxNetwork.effective,
890
1657
  triggerExternal: (caller) => host.resources.holdsNetwork(caller.address, caller.sessionId),
891
1658
  sealed: host.sealedDirectories,
@@ -902,10 +1669,10 @@ const plugin = {
902
1669
  let owned;
903
1670
  const pending = subprocess.start({
904
1671
  ...spec,
905
- beforeSpawn() {
1672
+ beforeSpawn(launchAttemptId) {
906
1673
  ctx.signal.throwIfAborted();
907
1674
  if (withdrawing) throw new Error("Sandbox execution owner is withdrawing");
908
- spec.beforeSpawn?.();
1675
+ spec.beforeSpawn?.(launchAttemptId);
909
1676
  }
910
1677
  }, (ending) => {
911
1678
  completed = true;
@@ -935,10 +1702,19 @@ const plugin = {
935
1702
  pending.finally(() => starts.delete(pending)).catch(() => {});
936
1703
  return pending;
937
1704
  };
938
- const drain = async () => {
1705
+ let draining;
1706
+ const drain = () => {
939
1707
  withdrawing = true;
940
- await Promise.allSettled([...starts]);
941
- await Promise.all([...handles].map((handle) => handle.stop("cancelled")));
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;
942
1718
  };
943
1719
  ctx.signal.addEventListener("abort", () => {
944
1720
  withdrawing = true;
@@ -951,6 +1727,12 @@ const plugin = {
951
1727
  });
952
1728
  const sandbox = createSandbox({
953
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"),
954
1736
  signal: ctx.signal,
955
1737
  routingRevision: () => network.routingRevision(),
956
1738
  authorizationIdentity: strategy,
@@ -965,6 +1747,7 @@ const plugin = {
965
1747
  authorize: createAuthorize({
966
1748
  host: host.host,
967
1749
  access: host.resources,
1750
+ receipts: ctx.services.get("resource-authorization"),
968
1751
  available: () => Boolean(strategy()),
969
1752
  validateTarget: (input) => host.validateTarget(input),
970
1753
  approval: {
@@ -981,6 +1764,13 @@ const plugin = {
981
1764
  })
982
1765
  });
983
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
+ }));
984
1774
  const participant = {
985
1775
  connectionIdentity: storage.connectionIdentity,
986
1776
  prepare(value) {
@@ -1021,6 +1811,7 @@ const plugin = {
1021
1811
  return {
1022
1812
  status: "ready",
1023
1813
  sandboxEnabled: config.enabled,
1814
+ sharedTemporaryWrite: config.sharedTemporaryWrite,
1024
1815
  networkPolicies: config.networkPolicies,
1025
1816
  ...policy === void 0 ? {} : { approvalPolicy: policy }
1026
1817
  };
@@ -1043,6 +1834,7 @@ const plugin = {
1043
1834
  service: "sandbox-settings-participant",
1044
1835
  value: {
1045
1836
  enabled: input.sandboxEnabled,
1837
+ sharedTemporaryWrite: input.sharedTemporaryWrite,
1046
1838
  networkPolicies: input.networkPolicies
1047
1839
  }
1048
1840
  }]);
@@ -1097,36 +1889,37 @@ const plugin = {
1097
1889
  result: readableSchema,
1098
1890
  handle: readable
1099
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
+ });
1100
1905
  const management = {
1101
1906
  read,
1102
1907
  status: () => sandbox.status(),
1103
- addReadablePath(path) {
1104
- const refusal = readablePathRefusal(path, { sealed: host.sealedDirectories }, host.host);
1105
- if (refusal) throw new Error(refusal);
1106
- update({ readable: [.../* @__PURE__ */ new Set([...read().readable, resolveThroughExisting(path, host.host)])] });
1107
- return readable();
1108
- },
1109
- removeReadablePath(path) {
1110
- const paths = /* @__PURE__ */ new Set([path, resolveThroughExisting(path, host.host)]);
1111
- const previous = read();
1112
- const next = previous.readable.filter((entry) => !paths.has(entry));
1113
- update({ readable: next });
1114
- if (next.length === previous.readable.length) frame.emit(previous);
1115
- return readable();
1116
- }
1908
+ addReadablePaths: (paths, operationId) => ReadablePathsReceipt.parse(collection.add(paths, operationId)),
1909
+ removeReadablePaths: (paths, operationId) => ReadablePathsReceipt.parse(collection.remove(paths, operationId))
1117
1910
  };
1118
1911
  ctx.services.provide("sandbox-settings", management);
1119
1912
  ctx.client.registerMethod({
1120
- name: "addReadablePath",
1121
- params: z.object({ path: z.string() }).strict(),
1122
- result: readableSchema,
1123
- handle: (input) => management.addReadablePath(input.path)
1913
+ name: "addReadablePaths",
1914
+ params: ReadablePathsMutation,
1915
+ result: ReadablePathsReceipt,
1916
+ handle: (input) => management.addReadablePaths(input.paths, input.operationId)
1124
1917
  });
1125
1918
  ctx.client.registerMethod({
1126
- name: "removeReadablePath",
1127
- params: z.object({ path: z.string() }).strict(),
1128
- result: readableSchema,
1129
- handle: (input) => management.removeReadablePath(input.path)
1919
+ name: "removeReadablePaths",
1920
+ params: ReadablePathsMutation,
1921
+ result: ReadablePathsReceipt,
1922
+ handle: (input) => management.removeReadablePaths(input.paths, input.operationId)
1130
1923
  });
1131
1924
  const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1132
1925
  if (existsSync(module)) ctx.client.registerUi({ module });
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "en-US": "Sandbox",
5
5
  "zh-CN": "沙箱"
6
6
  },
7
- "version": "1.0.0",
7
+ "version": "1.0.1",
8
8
  "type": "module",
9
9
  "description": "Agent sandbox planning, execution and isolation settings",
10
10
  "license": "MIT",
@@ -22,7 +22,7 @@
22
22
  "i18next": "^26.4.1"
23
23
  },
24
24
  "devDependencies": {
25
- "@eum-agent/plugin": "1.0.0",
25
+ "@eum-agent/plugin": "1.0.1",
26
26
  "@types/react": "^19.2.18",
27
27
  "@types/react-dom": "^19.2.5",
28
28
  "react": "^19.2.0",
@@ -43,8 +43,8 @@
43
43
  },
44
44
  "dependencies": {},
45
45
  "foundationDependencies": {
46
- "@eum-agent/storage-sqlite": "1.0.0",
47
- "@eum-agent/infra-local": "1.0.0"
46
+ "@eum-agent/storage-sqlite": "1.0.1",
47
+ "@eum-agent/infra-local": "1.0.1"
48
48
  }
49
49
  },
50
50
  "scripts": {
package/ui/ui.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ActionButton, Alert, Button, Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, Failure, FilePicker, FormFailure, Panel, Popover, Radio, ReadFailure, RuleEditor, SecurityRuleList, Segmented, SettingsLink, Tabs, TabsContent, TabsList, TabsTrigger, Warning, failureText, useBrowserService, useGateway, useGatewayAction, useTranslation } from "@eum-agent/host/framework";
1
+ import { ActionButton, Alert, Button, Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, Failure, FilePicker, FormFailure, Panel, Popover, Radio, ReadFailure, RuleEditor, SecurityRuleList, Segmented, SettingsLink, Tabs, TabsContent, TabsList, TabsTrigger, Warning, failureText, useBrowserService, useGateway, useGatewayAction, useTranslation, uuid } from "@eum-agent/host/framework";
2
2
  import { useCallback, useEffect, useId, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region ui-src/api.ts
@@ -263,11 +263,12 @@ var SECURITY_PRESETS = [
263
263
  "dangerous"
264
264
  ];
265
265
  /** Builds a complete policy bundle without changing grants or readable paths. */
266
- function configurationFor(preset) {
266
+ function configurationFor(preset, sharedTemporaryWrite = true) {
267
267
  const policy = preset === "default" ? "ask" : "allow";
268
268
  return {
269
269
  approvalPolicy: policy,
270
270
  sandboxEnabled: preset !== "dangerous",
271
+ sharedTemporaryWrite,
271
272
  networkPolicies: {
272
273
  external: policy,
273
274
  connect: policy,
@@ -307,7 +308,7 @@ function SecurityPresets({ state, saving, reading, readError, error, onRetry, on
307
308
  checked: selected === preset,
308
309
  disabled: saving || reading || readError !== null || state?.status !== "ready",
309
310
  onChange: () => {
310
- onSelect(configurationFor(preset));
311
+ onSelect(configurationFor(preset, state?.status === "ready" ? state.sharedTemporaryWrite : true));
311
312
  },
312
313
  className: preset === "dangerous" ? "shrink-0 [--primary:var(--destructive)]" : "shrink-0"
313
314
  }), /* @__PURE__ */ jsx("span", {
@@ -389,6 +390,42 @@ function SandboxStatusPanel({ read, security }) {
389
390
  });
390
391
  }
391
392
  //#endregion
393
+ //#region ui-src/components/settings/shared-temporary.tsx
394
+ /** Saved shared temporary write preference, independent from security presets. */
395
+ /** Retains the committed preference until the complete security replacement succeeds. */
396
+ function SharedTemporaryPanel({ security }) {
397
+ const { t } = useTranslation$1();
398
+ const ready = security.state?.status === "ready" ? security.state : null;
399
+ return /* @__PURE__ */ jsx(Panel, {
400
+ title: t("permissions.sharedTemporary"),
401
+ hint: t("permissions.sharedTemporaryHint"),
402
+ inline: true,
403
+ children: /* @__PURE__ */ jsx("div", {
404
+ className: "flex min-w-0 justify-end",
405
+ children: /* @__PURE__ */ jsx(Segmented, {
406
+ label: t("permissions.sharedTemporary"),
407
+ value: ready?.sharedTemporaryWrite ? "allow" : "off",
408
+ options: [{
409
+ value: "off",
410
+ label: t("authorization.sandboxOff")
411
+ }, {
412
+ value: "allow",
413
+ label: t("permissions.sharedTemporaryAllow")
414
+ }],
415
+ disabled: !ready || security.reading || security.saving || security.readError !== null,
416
+ onSelect: (value) => {
417
+ if (!ready) return;
418
+ const { status: _status, ...current } = ready;
419
+ security.save({
420
+ ...current,
421
+ sharedTemporaryWrite: value === "allow"
422
+ });
423
+ }
424
+ })
425
+ })
426
+ });
427
+ }
428
+ //#endregion
392
429
  //#region ui-src/components/settings/security-state.ts
393
430
  /** Holds committed values while a replacement is being persisted. */
394
431
  function useSecurityState() {
@@ -493,16 +530,24 @@ function AddReadablePathDialog({ open, onOpenChange }) {
493
530
  const { t } = useTranslation$1();
494
531
  const add = useGatewayAction();
495
532
  const [paths, setPaths] = useState([]);
533
+ const intent = useRef(null);
496
534
  useEffect(() => {
497
535
  if (!open) setPaths([]);
498
536
  }, [open]);
499
537
  async function submit() {
500
538
  if (add.pending || paths.length === 0) return;
501
539
  if ((await add.run(async () => {
502
- for (const path of paths) {
503
- await sandboxCall("addReadablePath", { path });
504
- setPaths((remaining) => remaining.filter((entry) => entry !== path));
505
- }
540
+ const key = JSON.stringify(paths);
541
+ const operationId = intent.current?.paths === key ? intent.current.operationId : uuid();
542
+ intent.current = {
543
+ paths: key,
544
+ operationId
545
+ };
546
+ if ((await sandboxCall("addReadablePaths", {
547
+ paths,
548
+ operationId
549
+ })).operationState === "admitted") throw new Error("Readable paths are being verified; retry the same selection.");
550
+ intent.current = null;
506
551
  })).ok) onOpenChange(false);
507
552
  }
508
553
  return /* @__PURE__ */ jsx(Dialog, {
@@ -600,7 +645,10 @@ function ReadablePathsList() {
600
645
  reload: list.reload,
601
646
  empty: t("permissions.noCustomRules"),
602
647
  removalHint: t("securityRules.removalHint"),
603
- onRemove: (_client, path) => sandboxCall("removeReadablePath", { path }),
648
+ onRemove: (_client, paths) => sandboxCall("removeReadablePaths", {
649
+ paths,
650
+ operationId: uuid()
651
+ }),
604
652
  tools: /* @__PURE__ */ jsx(ActionButton, {
605
653
  label: t("permissions.readableAdd"),
606
654
  onClick: () => setAdding(true)
@@ -643,7 +691,7 @@ function ReadablePathsList() {
643
691
  });
644
692
  }
645
693
  /** Retains the complete authorization and sandbox editors in professional mode. */
646
- function ProfessionalPermissions({ sandboxStatus }) {
694
+ function ProfessionalPermissions({ sandboxStatus, security }) {
647
695
  const { t } = useTranslation$1();
648
696
  const authorization = useBrowserService("authorization-settings");
649
697
  const AuthorPanel = authorization?.component;
@@ -673,6 +721,7 @@ function ProfessionalPermissions({ sandboxStatus }) {
673
721
  className: "flex min-h-0 flex-col gap-6 overflow-x-hidden overflow-y-auto py-2 pl-3 pr-5 [scrollbar-gutter:stable] [&>*]:shrink-0",
674
722
  children: [
675
723
  /* @__PURE__ */ jsx(SandboxEnabledPanel, { read: sandboxStatus }),
724
+ /* @__PURE__ */ jsx(SharedTemporaryPanel, { security }),
676
725
  /* @__PURE__ */ jsx(NetworkPoliciesPanel, {}),
677
726
  /* @__PURE__ */ jsx(ReadablePathsList, {}),
678
727
  LocalPortsPanel && /* @__PURE__ */ jsx(LocalPortsPanel, {})
@@ -734,7 +783,10 @@ function PermissionsPanel() {
734
783
  }) }), /* @__PURE__ */ jsx("fieldset", {
735
784
  disabled: security.reading || security.readError !== null || security.state?.status !== "ready",
736
785
  className: "m-0 flex min-h-0 min-w-0 flex-1 flex-col border-0 p-0",
737
- children: /* @__PURE__ */ jsx(ProfessionalPermissions, { sandboxStatus })
786
+ children: /* @__PURE__ */ jsx(ProfessionalPermissions, {
787
+ sandboxStatus,
788
+ security
789
+ })
738
790
  })] })] }),
739
791
  /* @__PURE__ */ jsx(SandboxStatusPanel, {
740
792
  read: sandboxStatus,
@@ -807,7 +859,10 @@ var en_US_default = {
807
859
  "readableRemove": "Remove",
808
860
  "readablePlaceholder": "Absolute path",
809
861
  "readableWarning": "Commands may read the selected files or directories, including directory contents.",
810
- "systemRulesManage": "Manage installed templates and read rules"
862
+ "systemRulesManage": "Manage installed templates and read rules",
863
+ "sharedTemporary": "Allow system temporary directory writes",
864
+ "sharedTemporaryAllow": "Allow",
865
+ "sharedTemporaryHint": "Allow commands to write to system temporary directories. Each call keeps its own writable temporary directory when disabled."
811
866
  },
812
867
  common: {
813
868
  "increase": "Increase",
@@ -1056,7 +1111,10 @@ var zh_CN_default = {
1056
1111
  "readableRemove": "移除",
1057
1112
  "readablePlaceholder": "绝对路径",
1058
1113
  "readableWarning": "所选文件或目录将允许命令读取,包含目录内的内容。",
1059
- "systemRulesManage": "管理已安装模板与读取规则"
1114
+ "systemRulesManage": "管理已安装模板与读取规则",
1115
+ "sharedTemporary": "允许写入系统临时目录",
1116
+ "sharedTemporaryAllow": "允许",
1117
+ "sharedTemporaryHint": "允许命令写入系统临时目录,关闭后仍可使用独立临时目录。"
1060
1118
  },
1061
1119
  common: {
1062
1120
  "increase": "增加",