@eum-agent/sandbox 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +996 -145
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,15 +1,12 @@
1
+ import { basename, dirname, isAbsolute, normalize, parse, posix, win32 } from "node:path";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { existsSync } from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { z } from "zod";
5
- import { isAbsolute, normalize, parse, posix, win32 } from "node:path";
6
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
7
  function pathsFor(platform = process.platform) {
10
8
  return platform === "win32" ? win32 : posix;
11
9
  }
12
- /** Accepts POSIX roots or complete Windows drive/UNC roots; rejects NUL and implicit drives. */
13
10
  function isCompleteAbsolute(path, paths = pathsFor()) {
14
11
  if (path.includes("\0")) return false;
15
12
  if (paths !== win32) return paths.isAbsolute(path);
@@ -21,11 +18,6 @@ function isCompleteAbsolute(path, paths = pathsFor()) {
21
18
  "?"
22
19
  ].includes(unc[1] ?? "") && ![".", ".."].includes(unc[2] ?? "");
23
20
  }
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
21
  function containsPath(root, path, paths = pathsFor()) {
30
22
  if (!isCompleteAbsolute(root, paths) || !isCompleteAbsolute(path, paths)) return false;
31
23
  const parts = (value) => {
@@ -43,14 +35,11 @@ function containsPath(root, path, paths = pathsFor()) {
43
35
  //#endregion
44
36
  //#region src/paths.ts
45
37
  const MAX_LINK_HOPS = 40;
46
- /** Resolves existing physical objects and follows dangling links without assuming absence. */
47
38
  function resolveThroughExisting(path, host) {
48
39
  const paths = pathsFor(host.process.platform);
49
40
  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
41
  const { basename, dirname, resolve } = paths;
51
42
  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
43
  function resolveWithHops(path, hops) {
55
44
  let candidate = resolve(host.process.cwd(), path);
56
45
  const rest = [];
@@ -63,19 +52,6 @@ function resolveThroughExisting(path, host) {
63
52
  candidate = parent;
64
53
  }
65
54
  }
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
55
  function realPathOf(path, hops) {
80
56
  try {
81
57
  return host.fs.realpathSync(path);
@@ -101,16 +77,6 @@ function isWithin(root, path, paths = pathsFor()) {
101
77
  }
102
78
  //#endregion
103
79
  //#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
80
  function resolveReadablePaths(paths, host) {
115
81
  const resolved = [];
116
82
  for (const path of paths) {
@@ -120,30 +86,17 @@ function resolveReadablePaths(paths, host) {
120
86
  }
121
87
  return dedupe(resolved);
122
88
  }
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
89
  function readablePathRefusal(path, protectedPaths, host) {
134
90
  if (!isAbsolute(path)) return `readable path must be absolute: ${path}`;
135
91
  const real = resolveThroughExisting(path, host);
136
92
  const sealedRoot = (protectedPaths.sealed ?? []).find((dir) => isWithin(dir, real));
137
93
  if (sealedRoot !== void 0) return `${path} is inside yaoguang's own state directory (${sealedRoot}), which no readable path can cover`;
138
94
  }
139
- /** Insertion order, first occurrence wins — the order a person wrote the
140
- * list in is the order they read it back in. */
141
95
  function dedupe(paths) {
142
96
  return [...new Set(paths)];
143
97
  }
144
98
  //#endregion
145
99
  //#region src/targets.ts
146
- /** Canonical loopback host forms share machine-wide TCP port grants. */
147
100
  function isLocalHost(host) {
148
101
  return [
149
102
  "localhost",
@@ -151,7 +104,6 @@ function isLocalHost(host) {
151
104
  "::1"
152
105
  ].includes(host);
153
106
  }
154
- /** Validates exact argv and a complete physical working directory. */
155
107
  function commandTarget(target, host) {
156
108
  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
109
  return {
@@ -161,15 +113,12 @@ function commandTarget(target, host) {
161
113
  }
162
114
  //#endregion
163
115
  //#region src/authorize.ts
164
- /** External hosts are purpose declarations, never address restrictions for shell processes. */
165
116
  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
117
  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
118
  function createAuthorize(deps) {
170
119
  const host = deps.host;
171
120
  const ask = deps.approval;
172
- return function authorize(ctx, permissions, reason, execution, mode = "sandboxed", fallbackReason) {
121
+ function assess(ctx, permissions, execution, mode = "sandboxed", fallbackReason) {
173
122
  if (!deps.available()) return {
174
123
  kind: "refused",
175
124
  reason: "policy",
@@ -254,21 +203,35 @@ function createAuthorize(deps) {
254
203
  message: "The default authorization policy refuses this command or file access."
255
204
  };
256
205
  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,
206
+ return {
207
+ kind: "assessed",
208
+ id: `sandbox:${host.crypto.createHash("sha256").update(JSON.stringify({
209
+ mode,
210
+ receiptId: permissions.receipt,
211
+ fallbackReason,
212
+ command,
213
+ files,
214
+ locals,
215
+ externalPurpose: mode === "direct" ? [] : permissions.network ?? []
216
+ })).digest("hex")}`,
217
+ inputs,
218
+ external,
261
219
  command,
262
220
  files,
263
221
  locals,
264
- externalPurpose: mode === "direct" ? [] : permissions.network ?? []
265
- })).digest("hex")}`;
222
+ permissions,
223
+ mode,
224
+ fallbackReason
225
+ };
226
+ }
227
+ function decide(ctx, assessment, reason, onceOnly = false, forceAsk = false) {
228
+ const { id, inputs, external, mode, permissions, fallbackReason } = assessment;
266
229
  if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === ask.questionId(id))) return {
267
230
  kind: "refused",
268
231
  reason: "rejected",
269
232
  message: "stale-approval: the execution or requested resources changed."
270
233
  };
271
- if (!inputs.length && !external) return { kind: "granted" };
234
+ if (!inputs.length && !external && !forceAsk) return { kind: "granted" };
272
235
  const targets = inputs.map((input) => input.kind === "file" ? {
273
236
  access: input.operations[0],
274
237
  target: input.path
@@ -288,13 +251,13 @@ function createAuthorize(deps) {
288
251
  subject: targets.map((target) => `${target.access} ${target.target}`).join("; "),
289
252
  targets,
290
253
  reason,
291
- accepts: [
254
+ accepts: onceOnly ? ["allowed-once", "rejected"] : [
292
255
  "allowed-once",
293
256
  "allowed-always",
294
257
  "rejected"
295
258
  ],
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")
259
+ globalResource: !onceOnly,
260
+ warning: onceOnly ? "Only this fixed readonly evaluation batch is authorized. No lasting resource permission is recorded." : 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
261
  });
299
262
  if (decision.kind === "ask") return {
300
263
  kind: "ask",
@@ -302,7 +265,7 @@ function createAuthorize(deps) {
302
265
  };
303
266
  const result = decision.result;
304
267
  if (result.kind === "allowed-once") return { kind: "granted" };
305
- if (result.kind === "allowed-always") try {
268
+ if (result.kind === "allowed-always" && !onceOnly) try {
306
269
  deps.access.recordResources(inputs, external);
307
270
  return { kind: "granted" };
308
271
  } catch (error) {
@@ -317,14 +280,52 @@ function createAuthorize(deps) {
317
280
  reason: "rejected",
318
281
  message: result.kind === "rejected" && result.reason ? `Permission refused: ${result.reason}` : "Permission refused by the person."
319
282
  };
320
- };
283
+ }
284
+ function authorize(ctx, permissions, reason, execution, mode = "sandboxed", fallbackReason) {
285
+ const assessment = assess(ctx, permissions, execution, mode, fallbackReason);
286
+ return assessment.kind === "refused" ? assessment : decide(ctx, assessment, reason);
287
+ }
288
+ return Object.assign(authorize, { batch(ctx, input) {
289
+ if (!input.executions.length || input.executions.length > 64 || !input.requestId || input.requestId.length > 512 || !input.planDigest || input.planDigest.length > 512 || Buffer.byteLength(input.reason) > 65536) return {
290
+ kind: "refused",
291
+ reason: "policy",
292
+ message: "Invalid readonly authorization batch"
293
+ };
294
+ const assessments = [];
295
+ for (const execution of input.executions) {
296
+ const assessment = assess(ctx, {}, execution, "sandboxed");
297
+ if (assessment.kind === "refused") return assessment;
298
+ assessments.push(assessment);
299
+ }
300
+ const id = `sandbox-batch:${host.crypto.createHash("sha256").update(JSON.stringify({
301
+ requestId: input.requestId,
302
+ planDigest: input.planDigest,
303
+ reason: input.reason,
304
+ executions: assessments.map((one) => ({
305
+ id: one.id,
306
+ command: one.command
307
+ }))
308
+ })).digest("hex")}`;
309
+ return decide(ctx, {
310
+ ...assessments[0],
311
+ id,
312
+ external: false,
313
+ inputs: assessments.map((one) => ({
314
+ kind: "command",
315
+ ...one.command
316
+ }))
317
+ }, JSON.stringify({
318
+ requestId: input.requestId,
319
+ planDigest: input.planDigest,
320
+ summary: input.reason
321
+ }), true, true);
322
+ } });
321
323
  }
322
324
  //#endregion
323
325
  //#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
326
  function createFailureCoordinator(deps) {
327
327
  const records = /* @__PURE__ */ new Map();
328
+ const processes = /* @__PURE__ */ new Map();
328
329
  const leases = /* @__PURE__ */ new Set();
329
330
  const closing = /* @__PURE__ */ new Map();
330
331
  const closedScopes = /* @__PURE__ */ new Set();
@@ -678,6 +679,21 @@ function createFailureCoordinator(deps) {
678
679
  await closeScope(registration.authorizationScope);
679
680
  }
680
681
  }
682
+ async function retire(scopeId) {
683
+ const record = records.get(scopeId);
684
+ if (!record) return;
685
+ if (!record.handle) cancel(record, "retired");
686
+ await record.handle?.settled;
687
+ await closeScope(record.registration.authorizationScope);
688
+ if (records.get(scopeId) !== record) return;
689
+ release(record);
690
+ record.detach();
691
+ record.detachAdmission?.();
692
+ record.observers.clear();
693
+ records.delete(scopeId);
694
+ closedScopes.delete(record.registration.authorizationScope);
695
+ for (const [processId, owner] of processes) if (owner === scopeId) processes.delete(processId);
696
+ }
681
697
  return {
682
698
  register(input) {
683
699
  if (stopped || records.has(input.scopeId)) throw new Error("scope-conflict: prepared failure scope is unavailable");
@@ -758,6 +774,16 @@ function createFailureCoordinator(deps) {
758
774
  cancel(record, "startup-failed");
759
775
  await record.handle?.settled;
760
776
  await closeScope(record.registration.authorizationScope);
777
+ await retire(scopeId);
778
+ },
779
+ bind(scopeId, processId) {
780
+ if (records.has(scopeId)) processes.set(processId, scopeId);
781
+ },
782
+ async retireProcess(processId) {
783
+ const scopeId = processes.get(processId);
784
+ if (scopeId === void 0) return;
785
+ processes.delete(processId);
786
+ await retire(scopeId);
761
787
  },
762
788
  async close() {
763
789
  stopped = true;
@@ -786,8 +812,56 @@ function createFailureCoordinator(deps) {
786
812
  };
787
813
  }
788
814
  //#endregion
815
+ //#region src/judge-temporary.ts
816
+ function createJudgeTemporaries(deps) {
817
+ const owned = /* @__PURE__ */ new Set();
818
+ return {
819
+ async temporary() {
820
+ const path = await deps.createTemporaryDirectory();
821
+ let parent;
822
+ let identity;
823
+ let removed = false, transferred = false;
824
+ const cleanup = async () => {
825
+ if (!parent || !identity) throw new Error("Readonly judge temporary identity remains unknown");
826
+ if (!transferred && !removed) {
827
+ await parent.remove(basename(path), identity);
828
+ removed = true;
829
+ }
830
+ await parent.close();
831
+ owned.delete(cleanup);
832
+ };
833
+ owned.add(cleanup);
834
+ try {
835
+ parent = await deps.files.anchor(dirname(path), { sealedDirectories: deps.sealedDirectories });
836
+ identity = await parent.stat(basename(path));
837
+ } catch (error) {
838
+ owned.delete(cleanup);
839
+ const anchored = parent;
840
+ if (anchored) {
841
+ const close = async () => {
842
+ await anchored.close();
843
+ owned.delete(close);
844
+ };
845
+ owned.add(close);
846
+ await close().catch(() => {});
847
+ }
848
+ throw error;
849
+ }
850
+ return {
851
+ path,
852
+ async release(admitted) {
853
+ transferred ||= admitted;
854
+ await cleanup();
855
+ }
856
+ };
857
+ },
858
+ async drain() {
859
+ await Promise.all([...owned].map((cleanup) => cleanup()));
860
+ }
861
+ };
862
+ }
863
+ //#endregion
789
864
  //#region src/local-ports.ts
790
- /** Owns the actual gateway port, and refreshes all network decisions before spawning. */
791
865
  function createSandboxNetwork(config, access, changed) {
792
866
  let gatewayPort;
793
867
  function protectedPorts() {
@@ -810,7 +884,6 @@ function createSandboxNetwork(config, access, changed) {
810
884
  return {
811
885
  protectedPorts,
812
886
  effective,
813
- /** Registers one port for this runtime; no local capability exists before registration. */
814
887
  bind(port) {
815
888
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid gateway port");
816
889
  if (gatewayPort === port) return;
@@ -818,7 +891,6 @@ function createSandboxNetwork(config, access, changed) {
818
891
  gatewayPort = port;
819
892
  changed();
820
893
  },
821
- /** Refreshes against current policy and shared grants; running processes retain their profile. */
822
894
  refresh(plan) {
823
895
  const current = effective(plan.requested);
824
896
  return {
@@ -831,25 +903,8 @@ function createSandboxNetwork(config, access, changed) {
831
903
  }
832
904
  //#endregion
833
905
  //#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
906
  function createSandboxPlanner(deps) {
850
907
  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
908
  function isDirectory(path) {
854
909
  try {
855
910
  return host.fs.statSync(path).isDirectory();
@@ -864,10 +919,6 @@ function createSandboxPlanner(deps) {
864
919
  if (!roots) return [];
865
920
  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
921
  }
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
922
  function refuseProtected(path) {
872
923
  if (!isAbsolute(path)) return {
873
924
  ok: false,
@@ -879,7 +930,7 @@ function createSandboxPlanner(deps) {
879
930
  if (sealedRoot !== void 0) return {
880
931
  ok: false,
881
932
  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`
933
+ message: `${path} is inside yaoguang's own state directory (${sealedRoot}) \u2014 the master key, the event log, this installation's configuration and its plugin code: no permission can cover it`
883
934
  };
884
935
  }
885
936
  return {
@@ -1041,29 +1092,23 @@ function createSandboxPlanner(deps) {
1041
1092
  }
1042
1093
  //#endregion
1043
1094
  //#region src/schema.ts
1044
- /** Sandbox-owned stored rules and management schemas. */
1045
- /** Concrete network decision values owned by sandbox. */
1046
1095
  const NetworkPolicy = z.enum([
1047
1096
  "ask",
1048
1097
  "deny",
1049
1098
  "allow"
1050
1099
  ]);
1051
- /** Independent external connection and listener policy settings. */
1052
1100
  const NetworkPolicies = z.object({
1053
1101
  external: NetworkPolicy,
1054
1102
  connect: NetworkPolicy,
1055
1103
  listen: NetworkPolicy
1056
1104
  }).strict();
1057
- /** Complete persisted sandbox settings, including user read roots. */
1058
1105
  const SandboxConfiguration = z.object({
1059
1106
  enabled: z.boolean(),
1060
1107
  readable: z.array(z.string()),
1061
1108
  networkPolicies: NetworkPolicies,
1062
1109
  sharedTemporaryWrite: z.boolean()
1063
1110
  }).strict();
1064
- /** Partial owner updates retain unrelated current settings. */
1065
1111
  const SandboxConfigurationUpdate = SandboxConfiguration.partial().strict();
1066
- /** Backend capability and the current selected execution preference. */
1067
1112
  const SandboxStatus = z.object({
1068
1113
  enabled: z.boolean(),
1069
1114
  mode: z.enum(["sandboxed", "direct"]),
@@ -1075,27 +1120,22 @@ const SandboxStatus = z.object({
1075
1120
  reason: z.string()
1076
1121
  })])
1077
1122
  });
1078
- /** Combined professional/simple values include only active owners. */
1079
1123
  const SecurityConfiguration = z.object({
1080
1124
  approvalPolicy: NetworkPolicy.optional(),
1081
1125
  sandboxEnabled: z.boolean(),
1082
1126
  sharedTemporaryWrite: z.boolean(),
1083
1127
  networkPolicies: NetworkPolicies
1084
1128
  }).strict();
1085
- /** Current settings snapshot; failed owner reads expose no partial values. */
1086
1129
  const SecurityState = z.discriminatedUnion("status", [SecurityConfiguration.extend({ status: z.literal("ready") }), z.object({
1087
1130
  status: z.literal("recovery-required"),
1088
1131
  error: z.string()
1089
1132
  }).strict()]);
1090
- /** Complete manual readable-path settings response. */
1091
1133
  const ReadablePaths = z.object({ readable: z.array(z.string()) }).strict();
1092
1134
  z.object({ enabled: z.boolean() }).strict();
1093
- /** Atomic manual read-root intent. */
1094
1135
  const ReadablePathsMutation = z.strictObject({
1095
1136
  operationId: z.uuid(),
1096
1137
  paths: z.array(z.string().max(4096)).min(1).max(64)
1097
1138
  });
1098
- /** Durable manual read-root receipt. */
1099
1139
  const ReadablePathsReceipt = z.discriminatedUnion("operationState", [
1100
1140
  z.strictObject({
1101
1141
  operationState: z.literal("committed"),
@@ -1119,7 +1159,6 @@ const ReadablePathsReceipt = z.discriminatedUnion("operationState", [
1119
1159
  ]);
1120
1160
  //#endregion
1121
1161
  //#region src/scope-note.ts
1122
- /** Reads only current owner settings and host facts; it grants no resource authority. */
1123
1162
  function createScopeNote(deps) {
1124
1163
  return { forSession(caller) {
1125
1164
  const roots = deps.fence.roots(caller.address.workspaceId);
@@ -1148,7 +1187,6 @@ function createScopeNote(deps) {
1148
1187
  }
1149
1188
  //#endregion
1150
1189
  //#region src/service.ts
1151
- /** Prefers available confinement and binds the selected capability to approval and launch. */
1152
1190
  function createSandbox(deps) {
1153
1191
  const state = () => deps.state?.() ?? {
1154
1192
  enabled: true,
@@ -1236,6 +1274,7 @@ function createSandbox(deps) {
1236
1274
  const launch = spec.authorizationScope ? launches.get(spec.authorizationScope.id) : void 0;
1237
1275
  try {
1238
1276
  const handle = await deps.start(spec, onExit);
1277
+ if (launch) deps.failures?.bind(launch.scopeId, handle.processId);
1239
1278
  if (launch?.claim && launch.attempt) launch.claim.launchSettled(launch.attempt);
1240
1279
  return handle;
1241
1280
  } catch (error) {
@@ -1408,8 +1447,74 @@ function createSandbox(deps) {
1408
1447
  };
1409
1448
  }
1410
1449
  //#endregion
1450
+ //#region src/session-starts.ts
1451
+ const START_KIND = "start";
1452
+ const StartDescriptorSchema = z.strictObject({});
1453
+ const outcome = (managed) => ({
1454
+ managedCleanup: managed,
1455
+ descendantCoverage: "not-applicable",
1456
+ residual: "none",
1457
+ ...managed === "retry" ? { code: "sandbox_stop_failed" } : {}
1458
+ });
1459
+ const startCleanup = {
1460
+ descriptorSchema: StartDescriptorSchema,
1461
+ async recover() {
1462
+ return outcome("complete");
1463
+ }
1464
+ };
1465
+ function registerStartRecovery(ctx) {
1466
+ ctx.register(START_KIND, startCleanup);
1467
+ }
1468
+ const retainedBy = (error) => error?.cleanupHandle;
1469
+ function createSessionStarts(lifecycle) {
1470
+ lifecycle.register(START_KIND, startCleanup);
1471
+ return { start(spec, start, onExit) {
1472
+ const lease = spec.session;
1473
+ if (!lease) return start(spec, onExit);
1474
+ const receipt = lifecycle.reserve(lease, {
1475
+ kind: START_KIND,
1476
+ descriptor: {}
1477
+ });
1478
+ let ended = false;
1479
+ let pending;
1480
+ receipt.retain({ async cleanup() {
1481
+ const handle = await pending.catch(retainedBy);
1482
+ if (!handle || ended) return outcome("complete");
1483
+ try {
1484
+ await handle.stop("cancelled");
1485
+ return outcome("complete");
1486
+ } catch {
1487
+ return outcome("retry");
1488
+ }
1489
+ } });
1490
+ try {
1491
+ pending = start({
1492
+ ...spec,
1493
+ beforeSpawn(launchAttemptId) {
1494
+ receipt.assertCurrent();
1495
+ spec.beforeSpawn?.(launchAttemptId);
1496
+ }
1497
+ }, (ending) => {
1498
+ ended = true;
1499
+ receipt.retire();
1500
+ return onExit(ending);
1501
+ });
1502
+ } catch (error) {
1503
+ pending = Promise.reject(error);
1504
+ }
1505
+ pending.then(() => {
1506
+ receipt.acquired({});
1507
+ receipt.finishAcquisition();
1508
+ }, (error) => {
1509
+ if (retainedBy(error)) receipt.acquired({});
1510
+ receipt.finishAcquisition();
1511
+ if (!retainedBy(error)) receipt.retire();
1512
+ });
1513
+ return pending;
1514
+ } };
1515
+ }
1516
+ //#endregion
1411
1517
  //#region src/settings.ts
1412
- /** Creates atomic, replayable user read-root collection updates. */
1413
1518
  function createReadableManagement(deps) {
1414
1519
  function mutate(paths, operationId, remove) {
1415
1520
  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");
@@ -1437,11 +1542,9 @@ function createReadableManagement(deps) {
1437
1542
  });
1438
1543
  }
1439
1544
  return {
1440
- /** Adds canonical read roots in one host commit; identical intent retries replay the original result. */
1441
1545
  add(paths, operationId) {
1442
1546
  return mutate(paths, operationId, false);
1443
1547
  },
1444
- /** Removes exact or canonical read roots atomically; absent roots are idempotent. */
1445
1548
  remove(paths, operationId) {
1446
1549
  return mutate(paths, operationId, true);
1447
1550
  }
@@ -1449,8 +1552,6 @@ function createReadableManagement(deps) {
1449
1552
  }
1450
1553
  //#endregion
1451
1554
  //#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
1555
  function createSandboxReadableProjection(deps) {
1455
1556
  const { host } = deps;
1456
1557
  function inspect(target) {
@@ -1540,8 +1641,682 @@ function createSandboxReadableProjection(deps) {
1540
1641
  };
1541
1642
  }
1542
1643
  //#endregion
1644
+ //#region src/readonly-judge.ts
1645
+ async function resultFromProcess(deps, handle) {
1646
+ let offset = 0;
1647
+ let total;
1648
+ const chunks = [];
1649
+ do {
1650
+ const page = await deps.process.read(handle.processId, {
1651
+ stream: "stdout",
1652
+ offset,
1653
+ limit: 32768
1654
+ });
1655
+ const capture = page.capture;
1656
+ if (page.stream !== "stdout" || page.state !== "ended" || !capture || capture.limitReached || capture.lostBytes !== 0 || capture.observedBytes !== capture.retainedBytes || capture.observedBytes !== page.total || page.total > 65536 || page.total < 0 || page.startOffset !== offset || page.offset < offset || page.offset > page.total || Buffer.byteLength(page.bytes) !== page.offset - offset || total !== void 0 && total !== page.total || page.offset === offset && page.total > offset) throw new Error("readonly_judge_incomplete_stdout");
1657
+ total = page.total;
1658
+ offset = page.offset;
1659
+ chunks.push(page.bytes);
1660
+ } while (offset < total);
1661
+ let parsed;
1662
+ try {
1663
+ parsed = JSON.parse(chunks.join(""));
1664
+ } catch {
1665
+ throw new Error("readonly_judge_invalid_result");
1666
+ }
1667
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("readonly_judge_invalid_result");
1668
+ const value = parsed;
1669
+ if (Object.keys(value).sort().join(",") !== "evidence,passed" || typeof value.passed !== "boolean" || typeof value.evidence !== "string" || Buffer.byteLength(value.evidence) > 8192) throw new Error("readonly_judge_invalid_result");
1670
+ return {
1671
+ status: value.passed ? "passed" : "failed",
1672
+ evidence: value.evidence
1673
+ };
1674
+ }
1675
+ function createReadonlyJudge(deps) {
1676
+ const launches = /* @__PURE__ */ new Set();
1677
+ const admissions = /* @__PURE__ */ new WeakMap();
1678
+ const batches = /* @__PURE__ */ new Set();
1679
+ const requests = /* @__PURE__ */ new Map();
1680
+ const activeRequests = /* @__PURE__ */ new Set();
1681
+ const originKey = (origin) => JSON.stringify(origin);
1682
+ const assertAdmission = (item) => {
1683
+ deps.signal.throwIfAborted();
1684
+ if (closed || item.disposed() || !deps.backend?.available().ok) throw new Error("readonly_judge_stale");
1685
+ const lease = item.lease();
1686
+ lease.assertCurrent();
1687
+ const real = (path) => String(deps.host.fs.realpathSync(path));
1688
+ for (const path of [
1689
+ lease.argv[0],
1690
+ lease.cwd,
1691
+ ...lease.read
1692
+ ]) {
1693
+ const canonical = real(path);
1694
+ if (canonical !== path || deps.sealed.some((root) => canonical === root || canonical.startsWith(`${root}/`))) throw new Error("readonly_judge_sealed_or_replaced");
1695
+ }
1696
+ };
1697
+ let closed = false;
1698
+ const report = (error) => deps.log?.emit({
1699
+ level: "error",
1700
+ event: "plugin.event",
1701
+ fields: { localCode: "READONLY_JUDGE_FAILED" },
1702
+ error
1703
+ });
1704
+ return {
1705
+ prepareBatch(call, scope, ...caps) {
1706
+ deps.signal.throwIfAborted();
1707
+ call.signal.throwIfAborted();
1708
+ if (!caps.length || caps.length > 64 || new Set(caps).size !== caps.length) throw new Error("readonly_judge_batch_limit");
1709
+ if (!scope.requestId || scope.requestId.length > 512 || !scope.planDigest || scope.planDigest.length > 512 || Buffer.byteLength(scope.reason) > 65536) throw new Error("readonly_judge_batch_scope");
1710
+ const items = caps.map((cap) => {
1711
+ const item = admissions.get(cap);
1712
+ if (!item) throw new Error("readonly_judge_unauthenticated");
1713
+ return item;
1714
+ });
1715
+ const state = {
1716
+ cap: void 0,
1717
+ items,
1718
+ scope: Object.freeze({ ...scope }),
1719
+ ready: false,
1720
+ approved: false,
1721
+ closing: false
1722
+ };
1723
+ let preparing;
1724
+ let cleaning;
1725
+ const cap = Object.freeze({
1726
+ ready() {
1727
+ if (preparing) return preparing;
1728
+ if (state.closing) return Promise.reject(/* @__PURE__ */ new Error("readonly_judge_batch_released"));
1729
+ preparing = (async () => {
1730
+ await Promise.all(items.map((item) => item.ready()));
1731
+ const origins = items.map((item) => {
1732
+ assertAdmission(item);
1733
+ return item.lease().authenticate(call);
1734
+ });
1735
+ if (origins.some((origin) => originKey(origin) !== originKey(origins[0]))) throw new Error("readonly_judge_origin_mismatch");
1736
+ const key = JSON.stringify([origins[0], state.scope.requestId]);
1737
+ const previous = requests.get(key);
1738
+ if (previous !== void 0 && previous !== state.scope.planDigest) throw new Error("idempotency_conflict");
1739
+ if (previous || items.some((item) => item.batch)) throw new Error("readonly_judge_batch_owned");
1740
+ if (activeRequests.size >= 128) throw new Error("readonly_judge_batch_capacity");
1741
+ if (state.closing) throw new Error("readonly_judge_batch_released");
1742
+ state.origin = origins[0];
1743
+ for (const item of items) item.batch = state;
1744
+ requests.set(key, state.scope.planDigest);
1745
+ activeRequests.add(state);
1746
+ state.ready = true;
1747
+ })();
1748
+ preparing.catch(report);
1749
+ return preparing;
1750
+ },
1751
+ authorize(current) {
1752
+ if (!state.ready || state.closing) throw new Error("readonly_judge_batch_not_ready");
1753
+ for (const item of state.items) {
1754
+ assertAdmission(item);
1755
+ if (item.batch !== state || originKey(item.lease().authenticate(current)) !== originKey(state.origin)) throw new Error("readonly_judge_unauthenticated");
1756
+ }
1757
+ if (state.approved) {
1758
+ if (deps.authorizationIdentity && state.authorizationIdentity !== deps.authorizationIdentity()) throw new Error("readonly_judge_authorization_changed");
1759
+ return { kind: "granted" };
1760
+ }
1761
+ const result = deps.authorizeBatch(current, {
1762
+ ...state.scope,
1763
+ executions: state.items.map((item) => ({
1764
+ argv: item.lease().argv,
1765
+ cwd: item.lease().cwd
1766
+ }))
1767
+ });
1768
+ if (result.kind === "granted") {
1769
+ state.authorizationIdentity = deps.authorizationIdentity?.();
1770
+ state.approved = true;
1771
+ }
1772
+ return result;
1773
+ },
1774
+ async release() {
1775
+ state.closing = true;
1776
+ if (cleaning) return cleaning;
1777
+ const work = (async () => {
1778
+ await preparing?.catch(() => {});
1779
+ const errors = (await Promise.allSettled(items.filter((item) => !item.batch || item.batch === state).map((item) => item.launch.release()))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1780
+ if (errors.length) throw new AggregateError(errors, "Readonly batch cleanup remains owned");
1781
+ state.approved = false;
1782
+ state.items = [];
1783
+ activeRequests.delete(state);
1784
+ batches.delete(state);
1785
+ })();
1786
+ cleaning = work;
1787
+ work.catch(() => {
1788
+ cleaning = void 0;
1789
+ });
1790
+ return work;
1791
+ }
1792
+ });
1793
+ state.cap = cap;
1794
+ batches.add(state);
1795
+ return cap;
1796
+ },
1797
+ prepare(call, manifest, commandId) {
1798
+ deps.signal.throwIfAborted();
1799
+ if (closed) throw new Error("readonly_judge_closed");
1800
+ const cancellation = new AbortController();
1801
+ const signal = AbortSignal.any([deps.signal, cancellation.signal]);
1802
+ const cancelPending = () => cancellation.abort(call.signal.reason);
1803
+ call.signal.addEventListener("abort", cancelPending, { once: true });
1804
+ let prepared;
1805
+ let lease;
1806
+ let temporary;
1807
+ let transferred = false;
1808
+ let handle;
1809
+ let work;
1810
+ let cleaning;
1811
+ let disposed = false;
1812
+ let detachLease;
1813
+ const stop = () => {
1814
+ if (handle) handle.stop("cancelled").catch(report);
1815
+ };
1816
+ signal.addEventListener("abort", stop);
1817
+ const cleanup = () => {
1818
+ if (cleaning) return cleaning;
1819
+ cleaning = (async () => {
1820
+ if (handle) {
1821
+ await handle.stop();
1822
+ handle = void 0;
1823
+ }
1824
+ if (temporary) {
1825
+ await temporary.release(transferred);
1826
+ temporary = void 0;
1827
+ }
1828
+ if (lease) {
1829
+ await lease.close();
1830
+ lease = void 0;
1831
+ }
1832
+ detachLease?.();
1833
+ signal.removeEventListener("abort", stop);
1834
+ launches.delete(launch);
1835
+ })();
1836
+ cleaning.catch(() => {
1837
+ cleaning = void 0;
1838
+ });
1839
+ return cleaning;
1840
+ };
1841
+ const launch = Object.freeze({
1842
+ ready: () => prepared,
1843
+ run() {
1844
+ if (disposed) return Promise.resolve({ status: "judge_error" });
1845
+ if (work) return work;
1846
+ work = (async () => {
1847
+ const timer = setTimeout(() => cancellation.abort(/* @__PURE__ */ new Error("readonly_judge_timeout")), 3e4);
1848
+ timer.unref?.();
1849
+ let result = { status: "judge_error" };
1850
+ try {
1851
+ await prepared;
1852
+ signal.throwIfAborted();
1853
+ const admitted = admissions.get(launch);
1854
+ if (!admitted.batch?.approved || admitted.batch.closing) throw new Error("readonly_judge_not_authorized");
1855
+ assertAdmission(admitted);
1856
+ const backend = deps.backend;
1857
+ const acquired = lease;
1858
+ await acquired.verify();
1859
+ const real = (path) => String(deps.host.fs.realpathSync(path));
1860
+ const execution = {
1861
+ argv: acquired.argv,
1862
+ cwd: acquired.cwd
1863
+ };
1864
+ temporary = await deps.temporary();
1865
+ signal.throwIfAborted();
1866
+ const read = [
1867
+ ...acquired.read,
1868
+ real(deps.commands.execPath),
1869
+ real("/usr/lib"),
1870
+ real("/System/Library")
1871
+ ];
1872
+ const plan = {
1873
+ mode: "sandboxed",
1874
+ execution,
1875
+ cwd: acquired.cwd,
1876
+ tmp: temporary.path,
1877
+ read,
1878
+ write: [],
1879
+ deny: [...deps.sealed],
1880
+ externalAllowed: false,
1881
+ connectAllow: [],
1882
+ listenAllow: [],
1883
+ protectedLocalPorts: [...deps.protectedPorts()],
1884
+ requested: {},
1885
+ proxyEnvironment: {}
1886
+ };
1887
+ const identities = [.../* @__PURE__ */ new Set([
1888
+ ...read,
1889
+ acquired.cwd,
1890
+ temporary.path
1891
+ ])].map((path) => {
1892
+ const observed = deps.host.fs.statSync(path);
1893
+ return {
1894
+ path,
1895
+ dev: observed.dev,
1896
+ ino: observed.ino
1897
+ };
1898
+ });
1899
+ const argv = backend.argv(plan, acquired.argv);
1900
+ await acquired.verify();
1901
+ try {
1902
+ handle = await deps.process.start({
1903
+ purpose: "task",
1904
+ mode: "foreground",
1905
+ argv,
1906
+ command: "Readonly script judge",
1907
+ cwd: acquired.cwd,
1908
+ env: {
1909
+ LANG: "C",
1910
+ LC_ALL: "C",
1911
+ TZ: "UTC"
1912
+ },
1913
+ sessionId: call.sessionId,
1914
+ agentId: call.address.agentId,
1915
+ workspaceId: call.address.workspaceId,
1916
+ held: read.map((path) => ({
1917
+ path,
1918
+ access: "read"
1919
+ })),
1920
+ tempDir: temporary.path,
1921
+ timeoutMs: 3e4,
1922
+ beforeSpawn() {
1923
+ signal.throwIfAborted();
1924
+ acquired.assertCurrent();
1925
+ if (!backend.available().ok) throw new Error("readonly_judge_confinement_unavailable");
1926
+ if (!admitted.batch?.approved || admitted.batch.closing || deps.authorizationIdentity && admitted.batch.authorizationIdentity !== deps.authorizationIdentity()) throw new Error("readonly_judge_authorization_changed");
1927
+ for (const identity of identities) {
1928
+ const current = deps.host.fs.statSync(identity.path);
1929
+ if (current.dev !== identity.dev || current.ino !== identity.ino || real(identity.path) !== identity.path) throw new Error("readonly_judge_replaced_resource");
1930
+ }
1931
+ }
1932
+ }, () => false);
1933
+ transferred = true;
1934
+ } catch (error) {
1935
+ const receipt = error?.cleanupHandle;
1936
+ if (receipt) {
1937
+ handle = receipt;
1938
+ transferred = true;
1939
+ }
1940
+ throw error;
1941
+ }
1942
+ if (signal.aborted) stop();
1943
+ const command = await handle.command;
1944
+ const ending = await handle.stop();
1945
+ if (signal.aborted || command.code !== 0 || command.signal !== null || command.error || ending.kind !== "exited" || ending.code !== 0) throw new Error("readonly_judge_process_failed");
1946
+ result = await resultFromProcess(deps, handle);
1947
+ } catch (error) {
1948
+ report(error);
1949
+ } finally {
1950
+ clearTimeout(timer);
1951
+ try {
1952
+ await cleanup();
1953
+ } catch (error) {
1954
+ result = { status: "judge_error" };
1955
+ report(error);
1956
+ }
1957
+ }
1958
+ return result;
1959
+ })();
1960
+ return work;
1961
+ },
1962
+ async release() {
1963
+ disposed = true;
1964
+ cancellation.abort(/* @__PURE__ */ new Error("readonly_judge_released"));
1965
+ await prepared.catch(() => {});
1966
+ await work;
1967
+ await cleanup();
1968
+ }
1969
+ });
1970
+ launches.add(launch);
1971
+ admissions.set(launch, {
1972
+ launch,
1973
+ ready: () => prepared,
1974
+ disposed: () => disposed,
1975
+ lease() {
1976
+ if (!lease) throw new Error("readonly_judge_resources_unavailable");
1977
+ return lease;
1978
+ }
1979
+ });
1980
+ prepared = (async () => {
1981
+ try {
1982
+ signal.throwIfAborted();
1983
+ call.signal.throwIfAborted();
1984
+ if (!deps.backend?.available().ok || deps.host.process.platform !== "darwin") throw new Error("readonly_judge_confinement_unavailable");
1985
+ const resources = deps.resources();
1986
+ if (!resources) throw new Error("readonly_judge_issuer_unavailable");
1987
+ lease = await resources.acquire(call, manifest, commandId);
1988
+ const acquired = lease;
1989
+ const cancelLease = () => cancellation.abort(/* @__PURE__ */ new Error("readonly_judge_resources_withdrawn"));
1990
+ acquired.signal.addEventListener("abort", cancelLease, { once: true });
1991
+ detachLease = () => acquired.signal.removeEventListener("abort", cancelLease);
1992
+ if (acquired.signal.aborted) cancelLease();
1993
+ signal.throwIfAborted();
1994
+ call.signal.throwIfAborted();
1995
+ await acquired.verify();
1996
+ const real = (path) => String(deps.host.fs.realpathSync(path));
1997
+ if (real(acquired.argv[0]) !== real(deps.commands.execPath)) throw new Error("readonly_judge_executable");
1998
+ call.signal.throwIfAborted();
1999
+ } finally {
2000
+ call.signal.removeEventListener("abort", cancelPending);
2001
+ }
2002
+ })();
2003
+ prepared.catch(report);
2004
+ const aborted = () => {
2005
+ if (!work) prepared.catch(() => {}).then(cleanup).catch(report);
2006
+ };
2007
+ signal.addEventListener("abort", aborted, { once: true });
2008
+ if (signal.aborted) aborted();
2009
+ return launch;
2010
+ },
2011
+ async close() {
2012
+ closed = true;
2013
+ const errors = (await Promise.allSettled([...[...batches].map((batch) => batch.cap.release()), ...[...launches].map((launch) => launch.release())])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2014
+ if (errors.length) throw new AggregateError(errors, "Readonly judge resources remain owned");
2015
+ }
2016
+ };
2017
+ }
2018
+ //#endregion
2019
+ //#region src/readonly-commands.ts
2020
+ function createReadonlyCommands(deps) {
2021
+ const batches = /* @__PURE__ */ new Set();
2022
+ const members = /* @__PURE__ */ new WeakMap();
2023
+ const requests = /* @__PURE__ */ new Map();
2024
+ let closed = false;
2025
+ const assertBatch = (batch) => {
2026
+ deps.signal.throwIfAborted();
2027
+ if (closed || batch.closing || !deps.backend?.available().ok) throw new Error("command_execution_unavailable");
2028
+ for (const lease of batch.items.values()) lease.assertCurrent();
2029
+ };
2030
+ return {
2031
+ prepare(call, scope, ...manifests) {
2032
+ deps.signal.throwIfAborted();
2033
+ call.signal.throwIfAborted();
2034
+ if (closed || batches.size >= 128 || !manifests.length || manifests.length > 64 || new Set(manifests).size !== manifests.length || !scope.requestId || scope.requestId.length > 128 || !scope.planDigest || Buffer.byteLength(scope.reason) > 65536) throw new Error("command_batch_invalid");
2035
+ const fixedScope = Object.freeze({ ...scope });
2036
+ const batch = {
2037
+ cap: void 0,
2038
+ items: /* @__PURE__ */ new Map(),
2039
+ active: /* @__PURE__ */ new Set(),
2040
+ handles: /* @__PURE__ */ new Set(),
2041
+ temporaries: /* @__PURE__ */ new Map(),
2042
+ approved: false,
2043
+ closing: false
2044
+ };
2045
+ let cleaning;
2046
+ const ready = (async () => {
2047
+ if (!deps.backend?.available().ok || deps.host.process.platform !== "darwin") throw new Error("command_confinement_unavailable");
2048
+ const resources = deps.resources();
2049
+ if (!resources) throw new Error("command_issuer_unavailable");
2050
+ let origin;
2051
+ for (const manifest of manifests) {
2052
+ if (members.has(manifest)) throw new Error("command_manifest_owned");
2053
+ const lease = await resources.acquire(call, manifest);
2054
+ batch.items.set(manifest, lease);
2055
+ const current = JSON.stringify(lease.authenticate(call));
2056
+ if (origin !== void 0 && current !== origin) throw new Error("command_origin_mismatch");
2057
+ origin = current;
2058
+ for (const execution of lease.executions) for (const path of [execution.argv[0], execution.cwd]) if (String(deps.host.fs.realpathSync(path)) !== path || deps.sealed.some((root) => path === root || path.startsWith(`${root}/`))) throw new Error("command_sealed_or_replaced");
2059
+ members.set(manifest, batch);
2060
+ }
2061
+ const key = JSON.stringify([origin, fixedScope.requestId]);
2062
+ if (requests.has(key)) throw new Error("command_request_already_used");
2063
+ requests.set(key, fixedScope.planDigest);
2064
+ assertBatch(batch);
2065
+ })();
2066
+ ready.catch(() => {});
2067
+ const cap = Object.freeze({
2068
+ ready: () => ready,
2069
+ authorize(current) {
2070
+ assertBatch(batch);
2071
+ if (batch.items.size !== manifests.length) throw new Error("command_batch_not_ready");
2072
+ const origins = [...batch.items.values()].map((lease) => JSON.stringify(lease.authenticate(current)));
2073
+ if (new Set(origins).size !== 1) throw new Error("command_origin_mismatch");
2074
+ if (batch.approved) {
2075
+ if (deps.authorizationIdentity && batch.authorizationIdentity !== deps.authorizationIdentity()) throw new Error("command_authorization_changed");
2076
+ return { kind: "granted" };
2077
+ }
2078
+ const result = deps.authorizeBatch(current, {
2079
+ ...fixedScope,
2080
+ executions: [...batch.items.values()].flatMap((lease) => lease.executions.map((execution) => ({
2081
+ argv: execution.argv,
2082
+ cwd: execution.cwd
2083
+ })))
2084
+ });
2085
+ if (result.kind === "granted") {
2086
+ batch.approved = true;
2087
+ batch.authorizationIdentity = deps.authorizationIdentity?.();
2088
+ }
2089
+ return result;
2090
+ },
2091
+ async releaseSlot(manifest) {
2092
+ await Promise.allSettled([...batch.active]);
2093
+ if (batch.handles.size) throw new Error("command_cleanup_pending");
2094
+ for (const cleanup of [...batch.temporaries.values()]) await cleanup();
2095
+ const lease = batch.items.get(manifest);
2096
+ if (!lease) return;
2097
+ await lease.close();
2098
+ batch.items.delete(manifest);
2099
+ if (members.get(manifest) === batch) members.delete(manifest);
2100
+ },
2101
+ release() {
2102
+ batch.closing = true;
2103
+ if (cleaning) return cleaning;
2104
+ const work = (async () => {
2105
+ await ready.catch(() => {});
2106
+ for (const handle of [...batch.handles]) {
2107
+ await handle.stop("cancelled");
2108
+ batch.handles.delete(handle);
2109
+ }
2110
+ await Promise.allSettled([...batch.active]);
2111
+ if (batch.handles.size) throw new Error("command_cleanup_pending");
2112
+ for (const cleanup of [...batch.temporaries.values()]) await cleanup();
2113
+ for (const [manifest, lease] of batch.items) {
2114
+ await lease.close();
2115
+ batch.items.delete(manifest);
2116
+ if (members.get(manifest) === batch) members.delete(manifest);
2117
+ }
2118
+ batches.delete(batch);
2119
+ })();
2120
+ cleaning = work;
2121
+ work.catch(() => {
2122
+ cleaning = void 0;
2123
+ });
2124
+ return work;
2125
+ }
2126
+ });
2127
+ batch.cap = cap;
2128
+ batches.add(batch);
2129
+ return cap;
2130
+ },
2131
+ async execute(call, id) {
2132
+ const manifest = deps.resources()?.forCall(call);
2133
+ const batch = manifest ? members.get(manifest) : void 0;
2134
+ const lease = manifest ? batch?.items.get(manifest) : void 0;
2135
+ if (!batch || !lease || !batch.approved) throw new Error("authorization_refused: command is not approved");
2136
+ assertBatch(batch);
2137
+ const execution = lease.executions.find((one) => one.id === id);
2138
+ if (!execution) throw new Error("authorization_refused: unknown command id");
2139
+ const work = (async () => {
2140
+ const cancellation = new AbortController();
2141
+ const signal = AbortSignal.any([
2142
+ call.signal,
2143
+ lease.signal,
2144
+ deps.signal,
2145
+ cancellation.signal
2146
+ ]);
2147
+ const timer = setTimeout(() => cancellation.abort(/* @__PURE__ */ new Error("command_timeout")), 3e4);
2148
+ timer.unref?.();
2149
+ let handle;
2150
+ let transferred = false;
2151
+ let closeTemporary;
2152
+ let result;
2153
+ let failure;
2154
+ const stop = () => {
2155
+ if (handle) handle.stop("cancelled").catch((error) => deps.log?.emit({
2156
+ level: "error",
2157
+ event: "plugin.event",
2158
+ error
2159
+ }));
2160
+ };
2161
+ signal.addEventListener("abort", stop, { once: true });
2162
+ try {
2163
+ const roots = await lease.verify(call, id);
2164
+ signal.throwIfAborted();
2165
+ const real = (path) => String(deps.host.fs.realpathSync(path));
2166
+ const read = [.../* @__PURE__ */ new Set([
2167
+ ...roots,
2168
+ real(execution.argv[0]),
2169
+ real("/usr/lib"),
2170
+ real("/System/Library")
2171
+ ])];
2172
+ const temporary = await deps.temporary();
2173
+ const temporaryKey = Symbol("command temporary");
2174
+ closeTemporary = async () => {
2175
+ await temporary.release(transferred);
2176
+ batch.temporaries.delete(temporaryKey);
2177
+ };
2178
+ batch.temporaries.set(temporaryKey, closeTemporary);
2179
+ const plan = {
2180
+ mode: "sandboxed",
2181
+ execution: {
2182
+ argv: execution.argv,
2183
+ cwd: execution.cwd
2184
+ },
2185
+ cwd: execution.cwd,
2186
+ tmp: temporary.path,
2187
+ read,
2188
+ write: [],
2189
+ deny: [...deps.sealed],
2190
+ externalAllowed: false,
2191
+ connectAllow: [],
2192
+ listenAllow: [],
2193
+ protectedLocalPorts: [...deps.protectedPorts()],
2194
+ requested: {},
2195
+ proxyEnvironment: {}
2196
+ };
2197
+ const identities = [.../* @__PURE__ */ new Set([
2198
+ ...read,
2199
+ execution.cwd,
2200
+ temporary.path
2201
+ ])].map((path) => ({
2202
+ path,
2203
+ stat: deps.host.fs.statSync(path)
2204
+ }));
2205
+ const backend = deps.backend;
2206
+ try {
2207
+ handle = await deps.process.start({
2208
+ purpose: "task",
2209
+ mode: "foreground",
2210
+ argv: backend.argv(plan, execution.argv),
2211
+ command: `Readonly task command ${id}`,
2212
+ cwd: execution.cwd,
2213
+ env: {
2214
+ LANG: "C",
2215
+ LC_ALL: "C",
2216
+ TZ: "UTC"
2217
+ },
2218
+ sessionId: call.sessionId,
2219
+ agentId: call.address.agentId,
2220
+ workspaceId: call.address.workspaceId,
2221
+ held: read.map((path) => ({
2222
+ path,
2223
+ access: "read"
2224
+ })),
2225
+ tempDir: temporary.path,
2226
+ timeoutMs: 3e4,
2227
+ beforeSpawn(launchAttemptId) {
2228
+ signal.throwIfAborted();
2229
+ assertBatch(batch);
2230
+ if (!batch.approved || deps.authorizationIdentity && batch.authorizationIdentity !== deps.authorizationIdentity()) throw new Error("command_authorization_changed");
2231
+ for (const { path, stat } of identities) {
2232
+ const current = deps.host.fs.statSync(path);
2233
+ if (current.dev !== stat.dev || current.ino !== stat.ino || real(path) !== path) throw new Error("command_resource_replaced");
2234
+ }
2235
+ lease.reserve(call, id, launchAttemptId);
2236
+ }
2237
+ }, () => false);
2238
+ transferred = true;
2239
+ } catch (error) {
2240
+ const receipt = error?.cleanupHandle;
2241
+ if (receipt) {
2242
+ handle = receipt;
2243
+ batch.handles.add(receipt);
2244
+ transferred = true;
2245
+ }
2246
+ throw error;
2247
+ }
2248
+ batch.handles.add(handle);
2249
+ if (signal.aborted) stop();
2250
+ const command = await handle.command;
2251
+ const ending = await handle.stop();
2252
+ batch.handles.delete(handle);
2253
+ if (signal.aborted || command.error || command.signal !== null || ending.kind !== "exited" || command.code === null) throw new Error("command_execution_failed");
2254
+ const chunks = [];
2255
+ let offset = 0, total;
2256
+ const stdoutRef = handle.logs.stdout;
2257
+ do {
2258
+ const page = await deps.process.read(handle.processId, {
2259
+ stream: "stdout",
2260
+ offset,
2261
+ limit: 32768
2262
+ });
2263
+ const capture = page.capture;
2264
+ if (page.state !== "ended" || page.stream !== "stdout" || !capture || capture.limitReached || capture.lostBytes || capture.observedBytes !== capture.retainedBytes || page.total > 65536 || capture.observedBytes !== page.total || page.startOffset !== offset || page.offset < offset || page.offset > page.total || Buffer.byteLength(page.bytes) !== page.offset - offset || total !== void 0 && total !== page.total || page.offset === offset && page.total > offset) throw new Error("command_stdout_incomplete");
2265
+ total = page.total;
2266
+ offset = page.offset;
2267
+ chunks.push(page.bytes);
2268
+ } while (offset < total);
2269
+ result = {
2270
+ processId: handle.processId,
2271
+ stdoutRef,
2272
+ stdout: chunks.join(""),
2273
+ code: command.code
2274
+ };
2275
+ } catch (error) {
2276
+ failure = { error };
2277
+ deps.log?.emit({
2278
+ level: "error",
2279
+ event: "plugin.event",
2280
+ error
2281
+ });
2282
+ }
2283
+ clearTimeout(timer);
2284
+ signal.removeEventListener("abort", stop);
2285
+ try {
2286
+ if (handle) {
2287
+ await handle.stop();
2288
+ batch.handles.delete(handle);
2289
+ }
2290
+ await closeTemporary?.();
2291
+ } catch (cleanup) {
2292
+ deps.log?.emit({
2293
+ level: "error",
2294
+ event: "plugin.event",
2295
+ error: cleanup
2296
+ });
2297
+ if (failure) throw new AggregateError([failure.error, cleanup], "Readonly command startup and cleanup failed", { cause: failure.error });
2298
+ throw cleanup;
2299
+ }
2300
+ if (failure) throw failure.error;
2301
+ if (!result) throw new Error("command_result_unavailable");
2302
+ return result;
2303
+ })();
2304
+ batch.active.add(work);
2305
+ try {
2306
+ return await work;
2307
+ } finally {
2308
+ batch.active.delete(work);
2309
+ }
2310
+ },
2311
+ async close() {
2312
+ closed = true;
2313
+ const errors = (await Promise.allSettled([...batches].map((batch) => batch.cap.release()))).flatMap((one) => one.status === "rejected" ? [one.reason] : []);
2314
+ if (errors.length) throw new AggregateError(errors, "Readonly command cleanup remains owned");
2315
+ }
2316
+ };
2317
+ }
2318
+ //#endregion
1543
2319
  //#region src/index.ts
1544
- /** Owns Agent shell planning, launch orchestration, rules and settings. */
1545
2320
  const plugin = {
1546
2321
  name: "@eum-agent/sandbox",
1547
2322
  requires: [
@@ -1553,16 +2328,24 @@ const plugin = {
1553
2328
  "owner-operations",
1554
2329
  "bulk-transactions",
1555
2330
  "resource-authorization",
1556
- "session-context"
2331
+ "session-context",
2332
+ "session-lifecycle"
1557
2333
  ],
2334
+ recoverSessionResources: registerStartRecovery,
1558
2335
  optionalServices: [
1559
2336
  "authorization-strategy",
1560
2337
  "session-skill-readables",
1561
2338
  "sandbox-preset-summary",
1562
- "sandbox-diagnostics"
2339
+ "sandbox-diagnostics",
2340
+ "restricted-judge-resources",
2341
+ "restricted-command-resources",
2342
+ "host-commands",
2343
+ "client-files"
1563
2344
  ],
1564
2345
  provides: [
1565
2346
  "sandbox",
2347
+ "restricted-judge",
2348
+ "restricted-commands",
1566
2349
  "sandbox-settings",
1567
2350
  "sandbox-settings-participant",
1568
2351
  "sandbox-readable-projection",
@@ -1602,6 +2385,10 @@ const plugin = {
1602
2385
  });
1603
2386
  const offInvalidated = ctx.services.get("session-context").onInvalidated(failures.invalidate);
1604
2387
  ctx.onDispose(offInvalidated);
2388
+ const offRetired = subprocess.onRetired?.((processId) => {
2389
+ failures.retireProcess(processId).catch(() => {});
2390
+ });
2391
+ if (offRetired) ctx.onDispose(offRetired);
1605
2392
  const storage = ctx.storage.open();
1606
2393
  const database = storage.db;
1607
2394
  const table = storage.tableName("settings");
@@ -1661,24 +2448,31 @@ const plugin = {
1661
2448
  });
1662
2449
  const handles = /* @__PURE__ */ new Set();
1663
2450
  const starts = /* @__PURE__ */ new Set();
2451
+ const sessionStarts = createSessionStarts(ctx.services.get("session-lifecycle"));
1664
2452
  let withdrawing = false;
1665
2453
  const start = (spec, onExit) => {
1666
2454
  ctx.signal.throwIfAborted();
1667
2455
  if (withdrawing) return Promise.reject(/* @__PURE__ */ new Error("Sandbox execution owner is withdrawing"));
1668
2456
  let completed = false;
1669
2457
  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) => {
2458
+ let admitted;
2459
+ try {
2460
+ admitted = sessionStarts.start({
2461
+ ...spec,
2462
+ beforeSpawn(launchAttemptId) {
2463
+ ctx.signal.throwIfAborted();
2464
+ if (withdrawing) throw new Error("Sandbox execution owner is withdrawing");
2465
+ spec.beforeSpawn?.(launchAttemptId);
2466
+ }
2467
+ }, subprocess.start.bind(subprocess), (ending) => {
2468
+ completed = true;
2469
+ if (owned) handles.delete(owned);
2470
+ return onExit(ending);
2471
+ });
2472
+ } catch (error) {
2473
+ return Promise.reject(error);
2474
+ }
2475
+ const pending = admitted.then(async (handle) => {
1682
2476
  owned = handle;
1683
2477
  if (!completed) handles.add(handle);
1684
2478
  if (withdrawing || ctx.signal.aborted) try {
@@ -1720,11 +2514,30 @@ const plugin = {
1720
2514
  withdrawing = true;
1721
2515
  for (const handle of handles) handle.stop("cancelled").catch(() => {});
1722
2516
  }, { once: true });
1723
- const removeDrain = ctx.services.get("work-lifecycle").register(drain);
2517
+ const lifecycle = ctx.services.get("work-lifecycle");
2518
+ const removeDrain = lifecycle.register(drain);
1724
2519
  ctx.onDispose(async () => {
1725
2520
  await drain();
1726
2521
  removeDrain();
1727
2522
  });
2523
+ const authorize = createAuthorize({
2524
+ host: host.host,
2525
+ access: host.resources,
2526
+ receipts: ctx.services.get("resource-authorization"),
2527
+ available: () => Boolean(strategy()),
2528
+ validateTarget: (input) => host.validateTarget(input),
2529
+ approval: {
2530
+ questionId: (id) => strategy()?.askQuestionId(id),
2531
+ decide: (authority, input) => strategy()?.ask(authority, input) ?? {
2532
+ kind: "result",
2533
+ result: { kind: "unavailable" },
2534
+ source: "policy-deny"
2535
+ }
2536
+ },
2537
+ defaultPolicy: () => strategy()?.policy() ?? "deny",
2538
+ policies: () => read().networkPolicies,
2539
+ protectedPorts: () => host.protectedPorts()
2540
+ });
1728
2541
  const sandbox = createSandbox({
1729
2542
  host: host.host,
1730
2543
  newId: randomUUID,
@@ -1744,26 +2557,61 @@ const plugin = {
1744
2557
  }),
1745
2558
  planner,
1746
2559
  ...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
- })
2560
+ authorize
1765
2561
  });
1766
2562
  ctx.services.provide("sandbox", sandbox);
2563
+ const commands = ctx.services.find("host-commands");
2564
+ const files = ctx.services.find("client-files");
2565
+ const judgeTemps = commands && files ? createJudgeTemporaries({
2566
+ createTemporaryDirectory: () => commands.createTemporaryDirectory(),
2567
+ files,
2568
+ sealedDirectories: host.sealedDirectories
2569
+ }) : void 0;
2570
+ const readonlyDeps = {
2571
+ host: host.host,
2572
+ backend: host.backend?.readonlyJudge?.(),
2573
+ process: {
2574
+ start,
2575
+ read: (id, input) => subprocess.read(id, input)
2576
+ },
2577
+ authorizationIdentity: strategy,
2578
+ authorizeBatch: (call, input) => authorize.batch(call, input),
2579
+ async temporary() {
2580
+ if (!judgeTemps) throw new Error("readonly_judge_temporary_unavailable");
2581
+ return await judgeTemps.temporary();
2582
+ },
2583
+ commands: commands ?? { execPath: "" },
2584
+ sealed: host.sealedDirectories,
2585
+ protectedPorts: () => host.protectedPorts(),
2586
+ signal: ctx.signal,
2587
+ log: ctx.log
2588
+ };
2589
+ const judge = createReadonlyJudge({
2590
+ ...readonlyDeps,
2591
+ resources: () => ctx.services.find("restricted-judge-resources")
2592
+ });
2593
+ const taskCommands = createReadonlyCommands({
2594
+ ...readonlyDeps,
2595
+ resources: () => ctx.services.find("restricted-command-resources")
2596
+ });
2597
+ ctx.services.provide("restricted-commands", {
2598
+ prepare: taskCommands.prepare,
2599
+ execute: taskCommands.execute
2600
+ });
2601
+ const drainJudge = async () => {
2602
+ await taskCommands.close();
2603
+ await judge.close();
2604
+ await judgeTemps?.drain();
2605
+ };
2606
+ const removeJudgeDrain = lifecycle.register(drainJudge);
2607
+ ctx.onDispose(async () => {
2608
+ await drainJudge();
2609
+ removeJudgeDrain();
2610
+ });
2611
+ ctx.services.provide("restricted-judge", {
2612
+ prepare: judge.prepare,
2613
+ prepareBatch: judge.prepareBatch
2614
+ });
1767
2615
  ctx.services.provide("workspace-directory-note", createScopeNote({
1768
2616
  sandbox,
1769
2617
  fence: host.fence,
@@ -1922,7 +2770,10 @@ const plugin = {
1922
2770
  handle: (input) => management.removeReadablePaths(input.paths, input.operationId)
1923
2771
  });
1924
2772
  const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1925
- if (existsSync(module)) ctx.client.registerUi({ module });
2773
+ if (existsSync(module)) ctx.client.registerPackageFiles({
2774
+ root: dirname(module),
2775
+ entry: "ui.js"
2776
+ });
1926
2777
  }
1927
2778
  };
1928
2779
  //#endregion