@morlay/configurable-sandbox 0.0.0-stage → 0.2.0-alpha.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.
- package/LICENSE +21 -0
- package/README.md +61 -2
- package/dist/index.d.mts +184 -0
- package/dist/index.mjs +792 -0
- package/dist/rolldown-runtime-3qf6kE1h.d.mts +1 -0
- package/package.json +36 -3
- package/src/configurable-sandbox.provide.ts +15 -0
- package/src/containment.ts +50 -0
- package/src/contract/index.ts +3 -0
- package/src/contract/sandbox-file.contract.ts +13 -0
- package/src/contract/sandbox-rules.contract.ts +30 -0
- package/src/defaults.ts +105 -0
- package/src/dialects.ts +115 -0
- package/src/events.ts +12 -0
- package/src/fs.service.ts +209 -0
- package/src/index.ts +16 -0
- package/src/policy-text.ts +46 -0
- package/src/rules.ts +228 -0
- package/src/runtime-contexts.service.ts +125 -0
- package/src/sandbox-file.service.ts +81 -0
- package/src/sandbox-rules.service.ts +187 -0
- package/src/sandbox.service.ts +114 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
import { EventEmitter, Injectable, Logger, inject, provide } from "@morlay/zephyr";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
3
|
+
import { canonicalPath, writableRoots } from "@morlay/dsh-sandbox/contract";
|
|
4
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { LocalSandboxProvider, Sandbox, SandboxPolicy } from "@morlay/dsh-sandbox";
|
|
6
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
7
|
+
import { FsError } from "@morlay/dsh-fs/contract";
|
|
8
|
+
import { FileSystem, LocalFileSystem } from "@morlay/dsh-fs";
|
|
9
|
+
import { AppEnv, parseToml } from "@morlay/zephyr-app";
|
|
10
|
+
// \0rolldown/runtime.js
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __exportAll = (all, flags) => {
|
|
13
|
+
let target = Object.setPrototypeOf({}, null);
|
|
14
|
+
for (var name in all) __defProp(target, name, {
|
|
15
|
+
get: all[name],
|
|
16
|
+
enumerable: true
|
|
17
|
+
});
|
|
18
|
+
if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
19
|
+
return flags & 2 ? target : Object.preventExtensions(target);
|
|
20
|
+
};
|
|
21
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
|
|
22
|
+
function __decorate(decorators, target, key, desc) {
|
|
23
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
24
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
25
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
26
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
27
|
+
}
|
|
28
|
+
// src/contract/sandbox-file.contract.ts
|
|
29
|
+
let SandboxFile = class SandboxFile {};
|
|
30
|
+
SandboxFile = __decorate([Injectable()], SandboxFile);
|
|
31
|
+
// src/contract/sandbox-rules.contract.ts
|
|
32
|
+
let SandboxRules = class SandboxRules {};
|
|
33
|
+
SandboxRules = __decorate([Injectable()], SandboxRules);
|
|
34
|
+
// src/rules.ts
|
|
35
|
+
const ENV_TEMPLATE = /\{\{\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
|
|
36
|
+
const ACCESS_LINE = /^(rw|r-|--)(?:\s+(.*))?$/u;
|
|
37
|
+
const GLOB_META = /[*?[]/;
|
|
38
|
+
const REGEX_META = /[\\^$+.(){}|]/;
|
|
39
|
+
function expandEnvTemplates(value, env) {
|
|
40
|
+
return value.replace(ENV_TEMPLATE, (_match, name) => {
|
|
41
|
+
const resolved = env[name];
|
|
42
|
+
if (resolved === void 0 || resolved.length === 0) throw new Error(`sandbox rules: "${value}" references the unset environment variable "${name}"`);
|
|
43
|
+
return resolved;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
function globToRegexSource(pattern) {
|
|
47
|
+
let source = "";
|
|
48
|
+
for (let index = 0; index < pattern.length; index += 1) {
|
|
49
|
+
const char = pattern[index];
|
|
50
|
+
if (char === "*") {
|
|
51
|
+
if (pattern[index + 1] === "*") {
|
|
52
|
+
index += 1;
|
|
53
|
+
if (pattern[index + 1] === "/") {
|
|
54
|
+
index += 1;
|
|
55
|
+
source += "(.*/)?";
|
|
56
|
+
} else source += ".*";
|
|
57
|
+
} else source += "[^/]*";
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (char === "?") {
|
|
61
|
+
source += "[^/]";
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (char === "[") {
|
|
65
|
+
const close = pattern.indexOf("]", index + 1);
|
|
66
|
+
if (close === -1) {
|
|
67
|
+
source += "\\[";
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const body = pattern.slice(index + 1, close);
|
|
71
|
+
if (body.length === 0) {
|
|
72
|
+
source += "\\[\\]";
|
|
73
|
+
index = close;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
source += body.startsWith("!") ? `[^${body.slice(1)}]` : `[${body}]`;
|
|
77
|
+
index = close;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
source += REGEX_META.test(char) ? `\\${char}` : char;
|
|
81
|
+
}
|
|
82
|
+
return source;
|
|
83
|
+
}
|
|
84
|
+
function isEmptyRules(rules) {
|
|
85
|
+
return rules.allowRoots.length === 0 && rules.readOnlySubtrees.length === 0 && rules.readOnlyPatterns.length === 0 && rules.denySubtrees.length === 0 && rules.denyPatterns.length === 0;
|
|
86
|
+
}
|
|
87
|
+
function withoutAllowRoots(rules) {
|
|
88
|
+
return rules.allowRoots.length === 0 ? rules : {
|
|
89
|
+
...rules,
|
|
90
|
+
allowRoots: []
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function parseAccess(input) {
|
|
94
|
+
const lines = (input === void 0 ? [] : typeof input === "string" ? [input] : [...input]).flatMap((value) => value.split(/\r?\n/u)).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
95
|
+
const allowWrite = [];
|
|
96
|
+
const readOnly = [];
|
|
97
|
+
const deny = [];
|
|
98
|
+
for (const line of lines) {
|
|
99
|
+
const match = ACCESS_LINE.exec(line);
|
|
100
|
+
if (match === null) throw new Error(`sandbox rules: access entry ${JSON.stringify(line)} must start with "rw " (write), "r- " (read-only) or "-- " (deny)`);
|
|
101
|
+
const rule = (match[2] ?? "").trim();
|
|
102
|
+
if (rule.length === 0) throw new Error(`sandbox rules: access entry ${JSON.stringify(line)} carries no path`);
|
|
103
|
+
if (match[1] === "rw") allowWrite.push(rule);
|
|
104
|
+
else if (match[1] === "r-") readOnly.push(rule);
|
|
105
|
+
else deny.push(rule);
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
allowWrite,
|
|
109
|
+
readOnly,
|
|
110
|
+
deny
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function ruleSourceOf(access, env) {
|
|
114
|
+
const parsed = parseAccess(access);
|
|
115
|
+
const expand = (values) => values.map((value) => expandEnvTemplates(value, env));
|
|
116
|
+
return {
|
|
117
|
+
allowWrite: expand(parsed.allowWrite),
|
|
118
|
+
readOnly: expand(parsed.readOnly),
|
|
119
|
+
deny: expand(parsed.deny)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function absolutize(value, workspaceRoot) {
|
|
123
|
+
return isAbsolute(value) ? value : resolve(workspaceRoot, value);
|
|
124
|
+
}
|
|
125
|
+
function compilePaths(values, workspaceRoot) {
|
|
126
|
+
const subtrees = [];
|
|
127
|
+
const patterns = [];
|
|
128
|
+
for (const value of values) {
|
|
129
|
+
const absolute = absolutize(value, workspaceRoot);
|
|
130
|
+
if (GLOB_META.test(value)) {
|
|
131
|
+
const pattern = `^${globToRegexSource(absolute)}$`;
|
|
132
|
+
patterns.push({
|
|
133
|
+
source: pattern,
|
|
134
|
+
regex: new RegExp(pattern)
|
|
135
|
+
});
|
|
136
|
+
} else subtrees.push(canonicalPath(absolute));
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
subtrees,
|
|
140
|
+
patterns
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function compileRules(source, workspaceRoot) {
|
|
144
|
+
const allowRoots = [];
|
|
145
|
+
for (const value of source.allowWrite) {
|
|
146
|
+
if (GLOB_META.test(value)) throw new Error(`sandbox rules: rw entry "${value}" must name a concrete path, not a glob`);
|
|
147
|
+
allowRoots.push(canonicalPath(absolutize(value, workspaceRoot)));
|
|
148
|
+
}
|
|
149
|
+
const readOnly = compilePaths(source.readOnly, workspaceRoot);
|
|
150
|
+
const deny = compilePaths(source.deny, workspaceRoot);
|
|
151
|
+
return {
|
|
152
|
+
allowRoots,
|
|
153
|
+
readOnlySubtrees: readOnly.subtrees,
|
|
154
|
+
readOnlyPatterns: readOnly.patterns,
|
|
155
|
+
denySubtrees: deny.subtrees,
|
|
156
|
+
denyPatterns: deny.patterns
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function writableRootsWith(rules, policy) {
|
|
160
|
+
const roots = writableRoots(policy);
|
|
161
|
+
return policy.mode === "workspace-write" ? [...roots, ...rules.allowRoots] : roots;
|
|
162
|
+
}
|
|
163
|
+
function isUnder(path, root) {
|
|
164
|
+
if (path === root) return true;
|
|
165
|
+
return path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
166
|
+
}
|
|
167
|
+
function matches(canonicalTarget, subtrees, patterns) {
|
|
168
|
+
for (const subtree of subtrees) if (isUnder(canonicalTarget, subtree)) return true;
|
|
169
|
+
return patterns.some((pattern) => pattern.regex.test(canonicalTarget));
|
|
170
|
+
}
|
|
171
|
+
function isDenied(rules, canonicalTarget) {
|
|
172
|
+
return matches(canonicalTarget, rules.denySubtrees, rules.denyPatterns);
|
|
173
|
+
}
|
|
174
|
+
function isReadOnly(rules, canonicalTarget) {
|
|
175
|
+
return matches(canonicalTarget, rules.readOnlySubtrees, rules.readOnlyPatterns);
|
|
176
|
+
}
|
|
177
|
+
function blocksWrite(rules, canonicalTarget) {
|
|
178
|
+
return isDenied(rules, canonicalTarget) || isReadOnly(rules, canonicalTarget);
|
|
179
|
+
}
|
|
180
|
+
// src/containment.ts
|
|
181
|
+
const MISSING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
|
|
182
|
+
async function statIfPresent(path) {
|
|
183
|
+
try {
|
|
184
|
+
return await stat(path, { bigint: true });
|
|
185
|
+
} catch (error) {
|
|
186
|
+
const code = error.code;
|
|
187
|
+
if (code !== void 0 && MISSING_CODES.has(code)) return void 0;
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function comparablePath(path, caseSensitive) {
|
|
192
|
+
return caseSensitive ? path : path.toLowerCase();
|
|
193
|
+
}
|
|
194
|
+
function isLexicallyUnder(path, root, caseSensitive) {
|
|
195
|
+
const comparableTarget = comparablePath(path, caseSensitive);
|
|
196
|
+
const comparableRoot = comparablePath(root, caseSensitive);
|
|
197
|
+
if (comparableTarget === comparableRoot) return true;
|
|
198
|
+
const prefix = comparableRoot.endsWith(sep) ? comparableRoot : comparableRoot + sep;
|
|
199
|
+
return comparableTarget.startsWith(prefix);
|
|
200
|
+
}
|
|
201
|
+
function sameIdentity(left, right) {
|
|
202
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
203
|
+
}
|
|
204
|
+
async function isPathUnder(path, root, caseSensitive = process.platform !== "win32") {
|
|
205
|
+
if (isLexicallyUnder(path, root, caseSensitive)) return true;
|
|
206
|
+
const rootInfo = await statIfPresent(root);
|
|
207
|
+
if (rootInfo === void 0) return false;
|
|
208
|
+
let ancestor = path;
|
|
209
|
+
for (;;) {
|
|
210
|
+
const ancestorInfo = await statIfPresent(ancestor);
|
|
211
|
+
if (ancestorInfo !== void 0 && sameIdentity(ancestorInfo, rootInfo)) return true;
|
|
212
|
+
const parent = dirname(ancestor);
|
|
213
|
+
if (parent === ancestor) return false;
|
|
214
|
+
ancestor = parent;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// src/dialects.ts
|
|
218
|
+
const SEPARATOR = "--";
|
|
219
|
+
const DIALECT_CAPABILITIES = {
|
|
220
|
+
seatbelt: {
|
|
221
|
+
allowWrite: true,
|
|
222
|
+
readOnly: true,
|
|
223
|
+
denyReadWrite: true,
|
|
224
|
+
denyWriteOnly: false
|
|
225
|
+
},
|
|
226
|
+
bwrap: {
|
|
227
|
+
allowWrite: true,
|
|
228
|
+
readOnly: true,
|
|
229
|
+
denyReadWrite: false,
|
|
230
|
+
denyWriteOnly: true
|
|
231
|
+
},
|
|
232
|
+
landlock: {
|
|
233
|
+
allowWrite: true,
|
|
234
|
+
readOnly: false,
|
|
235
|
+
denyReadWrite: false,
|
|
236
|
+
denyWriteOnly: false
|
|
237
|
+
},
|
|
238
|
+
"windows-acl": {
|
|
239
|
+
allowWrite: false,
|
|
240
|
+
readOnly: false,
|
|
241
|
+
denyReadWrite: false,
|
|
242
|
+
denyWriteOnly: false
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
function separatorIndex(argv) {
|
|
246
|
+
const index = argv.indexOf(SEPARATOR);
|
|
247
|
+
if (index === -1) throw new Error("sandbox rules: the confined argv carries no `--` separator to extend");
|
|
248
|
+
return index;
|
|
249
|
+
}
|
|
250
|
+
function dialectOf(argv) {
|
|
251
|
+
const separator = argv.indexOf(SEPARATOR);
|
|
252
|
+
const runner = separator === -1 ? argv : argv.slice(0, separator);
|
|
253
|
+
if (runner.includes("-p")) return "seatbelt";
|
|
254
|
+
if (runner[0] === "bwrap") return "bwrap";
|
|
255
|
+
if (runner.includes("--workspace")) return "windows-acl";
|
|
256
|
+
if (runner.includes("--ro") || runner.includes("--rw")) return "landlock";
|
|
257
|
+
}
|
|
258
|
+
function sbplString(value) {
|
|
259
|
+
return `"${value.replaceAll("\\", String.raw`\\`).replaceAll("\"", String.raw`\"`)}"`;
|
|
260
|
+
}
|
|
261
|
+
function sbplRegexBody(source) {
|
|
262
|
+
if (source.includes("\"")) throw new Error(`sandbox rules: deny pattern ${JSON.stringify(source)} cannot be expressed in a Seatbelt profile`);
|
|
263
|
+
return source;
|
|
264
|
+
}
|
|
265
|
+
function extendSeatbelt(argv, rules) {
|
|
266
|
+
const index = argv.indexOf("-p");
|
|
267
|
+
const profile = index === -1 ? void 0 : argv[index + 1];
|
|
268
|
+
if (profile === void 0) throw new Error("sandbox rules: the Seatbelt runner argv carries no `-p` profile to extend");
|
|
269
|
+
const extended = `${profile} ${[
|
|
270
|
+
...rules.allowRoots.map((root) => `(allow file-write* (subpath ${sbplString(root)}))`),
|
|
271
|
+
...rules.readOnlySubtrees.map((path) => `(deny file-write* (subpath ${sbplString(path)}))`),
|
|
272
|
+
...rules.readOnlyPatterns.map((pattern) => `(deny file-write* (regex #"${sbplRegexBody(pattern.source)}"))`),
|
|
273
|
+
...rules.denySubtrees.map((path) => `(deny file-read* file-write* (subpath ${sbplString(path)}))`),
|
|
274
|
+
...rules.denyPatterns.map((pattern) => `(deny file-read* file-write* (regex #"${sbplRegexBody(pattern.source)}"))`)
|
|
275
|
+
].join(" ")}`;
|
|
276
|
+
return [
|
|
277
|
+
...argv.slice(0, index + 1),
|
|
278
|
+
extended,
|
|
279
|
+
...argv.slice(index + 2)
|
|
280
|
+
];
|
|
281
|
+
}
|
|
282
|
+
function extendBwrap(argv, rules) {
|
|
283
|
+
const separator = separatorIndex(argv);
|
|
284
|
+
const additions = [];
|
|
285
|
+
for (const root of rules.allowRoots) additions.push("--bind-try", root, root);
|
|
286
|
+
for (const path of [...rules.readOnlySubtrees, ...rules.denySubtrees]) additions.push("--ro-bind-try", path, path);
|
|
287
|
+
return [
|
|
288
|
+
...argv.slice(0, separator),
|
|
289
|
+
...additions,
|
|
290
|
+
...argv.slice(separator)
|
|
291
|
+
];
|
|
292
|
+
}
|
|
293
|
+
function extendLandlock(argv, rules) {
|
|
294
|
+
const separator = separatorIndex(argv);
|
|
295
|
+
const additions = rules.allowRoots.flatMap((root) => ["--rw", root]);
|
|
296
|
+
return [
|
|
297
|
+
...argv.slice(0, separator),
|
|
298
|
+
...additions,
|
|
299
|
+
...argv.slice(separator)
|
|
300
|
+
];
|
|
301
|
+
}
|
|
302
|
+
function extendConfinedArgv(argv, rules) {
|
|
303
|
+
if (isEmptyRules(rules)) return [...argv];
|
|
304
|
+
const dialect = dialectOf(argv);
|
|
305
|
+
if (dialect === void 0) throw new Error("sandbox rules: cannot extend an unrecognized sandbox runner argv; drop allowWrite/deny or configure a bwrap-compatible runnerCommand");
|
|
306
|
+
switch (dialect) {
|
|
307
|
+
case "seatbelt": return extendSeatbelt(argv, rules);
|
|
308
|
+
case "bwrap": return extendBwrap(argv, rules);
|
|
309
|
+
case "landlock": return extendLandlock(argv, rules);
|
|
310
|
+
case "windows-acl": return [...argv];
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// src/policy-text.ts
|
|
314
|
+
const SANDBOX_POLICY_CONTEXT = "sandbox:policy";
|
|
315
|
+
const APPROVAL_POLICY_CONTEXT = "approval:policy";
|
|
316
|
+
function renderPolicyContext(policy, rules) {
|
|
317
|
+
const base = (() => {
|
|
318
|
+
switch (policy.mode) {
|
|
319
|
+
case "read-only": return "文件策略:只读——不能修改任何文件。别因此拒绝必需的修改:照常尝试工具,按它的拒绝与升级指引行动。";
|
|
320
|
+
case "workspace-write": return `文件策略:workspace-write——可改会话工作区 ${JSON.stringify(policy.workspaceRoot)} 下的文件,部分平台临时目录同样可写。`;
|
|
321
|
+
case "danger-full-access": return "文件策略:全权——文件改动不再受限。";
|
|
322
|
+
}
|
|
323
|
+
})();
|
|
324
|
+
const extras = [];
|
|
325
|
+
if (rules.allowWrite.length > 0) extras.push(`额外可写:${rules.allowWrite.join("、")}。`);
|
|
326
|
+
if (rules.readOnly.length > 0) extras.push(`只读(不可写):${rules.readOnly.join("、")}。`);
|
|
327
|
+
if (rules.deny.length > 0) extras.push(`拒绝(读写都拒):${rules.deny.join("、")}。`);
|
|
328
|
+
return extras.length === 0 ? base : `${base} ${extras.join("")}`;
|
|
329
|
+
}
|
|
330
|
+
const APPROVAL_ASK_TEXT = "审批策略:ask——需要审批的操作会询问用户;没有可用的应答者时直接失败。";
|
|
331
|
+
const APPROVAL_NEVER_TEXT = "审批提示已禁用:需要审批的操作一律自动拒绝——不要请求沙箱升级(不要设 sandbox_permissions)。";
|
|
332
|
+
function renderApprovalContext(policy) {
|
|
333
|
+
return policy === "never" ? APPROVAL_NEVER_TEXT : APPROVAL_ASK_TEXT;
|
|
334
|
+
}
|
|
335
|
+
// src/sandbox.service.ts
|
|
336
|
+
const RULES_DEP$1 = "sandboxRules";
|
|
337
|
+
function upstreamConfigOf(settings) {
|
|
338
|
+
return {
|
|
339
|
+
runnerCommand: [...settings.runnerCommand],
|
|
340
|
+
runnerFailureSignatures: [...settings.runnerFailureSignatures],
|
|
341
|
+
probeTimeoutMs: settings.probeTimeoutMs
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
var ConfigurableSandboxProvider = class extends LocalSandboxProvider {
|
|
345
|
+
rules;
|
|
346
|
+
compiled = /* @__PURE__ */ new Map();
|
|
347
|
+
constructor(ctx, config) {
|
|
348
|
+
super(ctx, config);
|
|
349
|
+
this.rules = ctx.get(RULES_DEP$1);
|
|
350
|
+
}
|
|
351
|
+
async confine(argv, policy, signal) {
|
|
352
|
+
const confined = await super.confine(argv, policy, signal);
|
|
353
|
+
const rules = this.rulesFor(policy.workspaceRoot);
|
|
354
|
+
const effective = policy.mode === "workspace-write" ? rules : withoutAllowRoots(rules);
|
|
355
|
+
if (isEmptyRules(effective)) return confined;
|
|
356
|
+
return {
|
|
357
|
+
...confined,
|
|
358
|
+
argv: extendConfinedArgv(confined.argv, effective)
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
rulesFor(workspaceRoot) {
|
|
362
|
+
const cached = this.compiled.get(workspaceRoot);
|
|
363
|
+
if (cached !== void 0) return cached;
|
|
364
|
+
const compiled = compileRules(this.rules.source(), workspaceRoot);
|
|
365
|
+
this.compiled.set(workspaceRoot, compiled);
|
|
366
|
+
return compiled;
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
let ConfigurableSandbox = class ConfigurableSandbox extends fromCordis(Sandbox, ConfigurableSandboxProvider) {
|
|
370
|
+
rulesSource = inject(SandboxRules);
|
|
371
|
+
loggerFace = inject(Logger);
|
|
372
|
+
async onInit(ctx) {
|
|
373
|
+
await this.mount(ctx, upstreamConfigOf(this.rulesSource.settings()), { [RULES_DEP$1]: this.rulesSource });
|
|
374
|
+
this.warnAboutDegradedRules(this.rulesSource.source());
|
|
375
|
+
}
|
|
376
|
+
warnAboutDegradedRules(rules) {
|
|
377
|
+
const grants = rules.allowWrite.length > 0;
|
|
378
|
+
const readOnly = rules.readOnly.length > 0;
|
|
379
|
+
const denials = rules.deny.length > 0;
|
|
380
|
+
if (!grants && !readOnly && !denials) return;
|
|
381
|
+
if (process.platform === "darwin") return;
|
|
382
|
+
if (readOnly || denials) this.loggerFace.warn(`configurable-sandbox: "r-" / "--" entries cannot be fully enforced for confined subprocesses on ${process.platform} (Seatbelt enforces both; bwrap binds the path read-only, so "--" degrades to write-only; Landlock and the Windows ACL runner cannot express a subpath rule at all) — tools that read through ctx.fs stay covered`);
|
|
383
|
+
if (grants && process.platform === "win32") this.loggerFace.warn("configurable-sandbox: \"rw\" entries cannot be granted to confined subprocesses on win32; ctx.fs covers the extra roots, the Windows ACL runner does not");
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
ConfigurableSandbox = __decorate([Injectable()], ConfigurableSandbox);
|
|
387
|
+
// src/fs.service.ts
|
|
388
|
+
function upstreamFsConfigOf(settings) {
|
|
389
|
+
return {
|
|
390
|
+
cwd: settings.cwd,
|
|
391
|
+
diffBasisMaxBytes: settings.diffBasisMaxBytes
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
const RULES_DEP = "sandboxRules";
|
|
395
|
+
const POLICY_DEP = "sandboxPolicy";
|
|
396
|
+
let ConfigurableFileSystem = class ConfigurableFileSystem extends LocalFileSystem {
|
|
397
|
+
rules;
|
|
398
|
+
policy;
|
|
399
|
+
compiled = /* @__PURE__ */ new Map();
|
|
400
|
+
constructor(ctx, config) {
|
|
401
|
+
super(ctx, config);
|
|
402
|
+
const read = ctx.get.bind(ctx);
|
|
403
|
+
this.rules = read(RULES_DEP);
|
|
404
|
+
this.policy = read(POLICY_DEP);
|
|
405
|
+
}
|
|
406
|
+
get sandboxMode() {
|
|
407
|
+
return this.policy.defaultMode;
|
|
408
|
+
}
|
|
409
|
+
async resolve(path, opts) {
|
|
410
|
+
const target = await super.resolve(path, opts);
|
|
411
|
+
this.assertNotDenied(this.rulesFor(this.policy.resolve().workspaceRoot), target.targetKey, target.displayPath);
|
|
412
|
+
return target;
|
|
413
|
+
}
|
|
414
|
+
async writeText(target, content, expected, signal, sandboxPolicy) {
|
|
415
|
+
return super.writeText(await this.checkedTarget(target, sandboxPolicy), content, expected, signal);
|
|
416
|
+
}
|
|
417
|
+
async editText(target, edit, expected, signal, sandboxPolicy) {
|
|
418
|
+
return super.editText(await this.checkedTarget(target, sandboxPolicy), edit, expected, signal);
|
|
419
|
+
}
|
|
420
|
+
async patchText(target, hunks, expected, signal, sandboxPolicy) {
|
|
421
|
+
return super.patchText(await this.checkedTarget(target, sandboxPolicy), hunks, expected, signal);
|
|
422
|
+
}
|
|
423
|
+
async deleteFile(target, expected, signal, sandboxPolicy) {
|
|
424
|
+
return super.deleteFile(await this.checkedTarget(target, sandboxPolicy), expected, signal);
|
|
425
|
+
}
|
|
426
|
+
async moveFile(source, destination, options, signal, sandboxPolicy) {
|
|
427
|
+
const checkedSource = await this.checkedTarget(source, sandboxPolicy);
|
|
428
|
+
const checkedDestination = await this.checkedTarget(destination, sandboxPolicy);
|
|
429
|
+
return super.moveFile(checkedSource, checkedDestination, options, signal);
|
|
430
|
+
}
|
|
431
|
+
assertNotDenied(rules, canonicalTarget, displayPath) {
|
|
432
|
+
if (!isDenied(rules, canonicalTarget)) return;
|
|
433
|
+
throw new FsError(`cannot access "${displayPath}": file access denied by the configured "--" rules`, "FS_SANDBOX_DENIED");
|
|
434
|
+
}
|
|
435
|
+
assertWritable(rules, canonicalTarget, displayPath) {
|
|
436
|
+
this.assertNotDenied(rules, canonicalTarget, displayPath);
|
|
437
|
+
if (!isReadOnly(rules, canonicalTarget)) return;
|
|
438
|
+
throw new FsError(`cannot write "${displayPath}": path is read-only by the configured "r-" rule`, "FS_SANDBOX_DENIED");
|
|
439
|
+
}
|
|
440
|
+
async checkedTarget(target, sandboxPolicy) {
|
|
441
|
+
const policy = sandboxPolicy ?? this.policy.resolve();
|
|
442
|
+
const rules = this.rulesFor(policy.workspaceRoot);
|
|
443
|
+
this.assertWritable(rules, target.targetKey, target.displayPath);
|
|
444
|
+
if (policy.mode === "danger-full-access") return target;
|
|
445
|
+
if (policy.mode === "read-only") throw new FsError(`cannot write "${target.displayPath}": file access denied under read-only mode`, "FS_SANDBOX_DENIED");
|
|
446
|
+
const fresh = await super.resolve(target.displayPath);
|
|
447
|
+
this.assertWritable(rules, fresh.targetKey, fresh.displayPath);
|
|
448
|
+
for (const root of writableRootsWith(rules, policy)) if (await isPathUnder(fresh.targetKey, root)) return fresh;
|
|
449
|
+
throw new FsError(`cannot write "${target.displayPath}": file access denied under workspace-write mode`, "FS_SANDBOX_DENIED");
|
|
450
|
+
}
|
|
451
|
+
rulesFor(workspaceRoot) {
|
|
452
|
+
const cached = this.compiled.get(workspaceRoot);
|
|
453
|
+
if (cached !== void 0) return cached;
|
|
454
|
+
const compiled = compileRules(this.rules.source(), workspaceRoot);
|
|
455
|
+
this.compiled.set(workspaceRoot, compiled);
|
|
456
|
+
return compiled;
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
ConfigurableFileSystem = __decorate([Injectable()], ConfigurableFileSystem);
|
|
460
|
+
let ConfigurableFsSandbox = class ConfigurableFsSandbox extends fromCordis(FileSystem, ConfigurableFileSystem) {
|
|
461
|
+
rulesSource = inject(SandboxRules);
|
|
462
|
+
sandboxPolicyFace = inject(SandboxPolicy);
|
|
463
|
+
async onInit(ctx) {
|
|
464
|
+
await this.mount(ctx, upstreamFsConfigOf(this.rulesSource.settings()), {
|
|
465
|
+
[RULES_DEP]: this.rulesSource,
|
|
466
|
+
[POLICY_DEP]: this.sandboxPolicyFace
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
ConfigurableFsSandbox = __decorate([Injectable()], ConfigurableFsSandbox);
|
|
471
|
+
// src/defaults.ts
|
|
472
|
+
/** XDG 目录在变量缺失时的回退(XDG Base Directory 的惯例路径,相对用户主目录)。 */
|
|
473
|
+
const XDG_FALLBACKS = {
|
|
474
|
+
XDG_CACHE_HOME: [".cache"],
|
|
475
|
+
XDG_STATE_HOME: [".local", "state"],
|
|
476
|
+
XDG_DATA_HOME: [".local", "share"],
|
|
477
|
+
XDG_CONFIG_HOME: [".config"]
|
|
478
|
+
};
|
|
479
|
+
/**
|
|
480
|
+
* 环境变量的非空值(XDG 惯例:空串等于未设)。
|
|
481
|
+
* @param env - 进程环境。
|
|
482
|
+
* @param name - 变量名。
|
|
483
|
+
* @returns 非空值,或 `undefined`。
|
|
484
|
+
*/
|
|
485
|
+
function valueOf(env, name) {
|
|
486
|
+
const value = env[name];
|
|
487
|
+
return value === void 0 || value.length === 0 ? void 0 : value;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* 造首次写盘用的默认规则:用户目录与 XDG 目录在这里就落成本机具体路径。
|
|
491
|
+
* @param env - 进程环境(用户目录与 XDG 目录的唯一来源)。
|
|
492
|
+
* @returns 文本与跳过的条目。
|
|
493
|
+
*/
|
|
494
|
+
function defaultSandboxToml(env) {
|
|
495
|
+
const home = valueOf(env, "HOME");
|
|
496
|
+
const skipped = [];
|
|
497
|
+
/** 一个 XDG 目录:显式值优先,否则按惯例回退到 `home` 下。 */
|
|
498
|
+
const userDirOf = (name) => {
|
|
499
|
+
const explicit = valueOf(env, name);
|
|
500
|
+
if (explicit !== void 0) return explicit;
|
|
501
|
+
if (home === void 0) {
|
|
502
|
+
skipped.push(name);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
return join(home, ...XDG_FALLBACKS[name]);
|
|
506
|
+
};
|
|
507
|
+
const lines = ["rw /tmp"];
|
|
508
|
+
if (home === void 0) skipped.push("HOME");
|
|
509
|
+
else lines.push(`rw ${join(home, ".agent-browser")}`);
|
|
510
|
+
const cache = userDirOf("XDG_CACHE_HOME");
|
|
511
|
+
const state = userDirOf("XDG_STATE_HOME");
|
|
512
|
+
const data = userDirOf("XDG_DATA_HOME");
|
|
513
|
+
const config = userDirOf("XDG_CONFIG_HOME");
|
|
514
|
+
if (cache !== void 0) lines.push(`rw ${cache}`);
|
|
515
|
+
if (state !== void 0) lines.push(`rw ${state}`);
|
|
516
|
+
if (data !== void 0) lines.push(`rw ${data}`);
|
|
517
|
+
if (config !== void 0) lines.push(`r- ${config}`);
|
|
518
|
+
lines.push("-- mise.*.toml", "-- **/*.pem");
|
|
519
|
+
return {
|
|
520
|
+
text: renderSandboxToml(lines),
|
|
521
|
+
skipped
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* 把条目行拼成整份 `sandbox.toml`(块标量一行一条;尾部换行固定)。
|
|
526
|
+
* @param lines - `access` 的条目行。
|
|
527
|
+
* @returns 文本。
|
|
528
|
+
*/
|
|
529
|
+
function renderSandboxToml(lines) {
|
|
530
|
+
return [
|
|
531
|
+
"",
|
|
532
|
+
"# 本机可写:临时目录(构建工具、npm、各种 tmp)",
|
|
533
|
+
"access = \"\"\"",
|
|
534
|
+
...lines,
|
|
535
|
+
"\"\"\"",
|
|
536
|
+
"",
|
|
537
|
+
"# runner 探测超时(毫秒):平台自带的链选不出可用 runner 时的兜底上限。",
|
|
538
|
+
"probeTimeoutMs = 5000",
|
|
539
|
+
"",
|
|
540
|
+
"# 覆盖写差异的单侧字节上限(10 MiB)。",
|
|
541
|
+
"diffBasisMaxBytes = 10485760",
|
|
542
|
+
""
|
|
543
|
+
].join("\n");
|
|
544
|
+
}
|
|
545
|
+
// src/sandbox-file.service.ts
|
|
546
|
+
let SandboxFileDefault = class SandboxFileDefault extends SandboxFile {
|
|
547
|
+
/**
|
|
548
|
+
* 数据根:`AppEnv` 是**唯一**来源(部署值由装配面给,包内不读进程环境)。
|
|
549
|
+
*
|
|
550
|
+
* 路径必须是 getter:字段初始化那一刻 `inject(AppEnv)` 还是注入占位,把路径在那里算死就永远
|
|
551
|
+
* 拿到占位值(同包 `SandboxRulesDefault` 的惰性状态同一条理由)。
|
|
552
|
+
*/
|
|
553
|
+
appEnv = inject(AppEnv);
|
|
554
|
+
/** 配置文件路径:`<dataDir>/sandbox.toml`。 */
|
|
555
|
+
get path() {
|
|
556
|
+
return join(this.appEnv.values.dataDir, "sandbox.toml");
|
|
557
|
+
}
|
|
558
|
+
logger = inject.optional(Logger);
|
|
559
|
+
/**
|
|
560
|
+
* 诊断:`Logger` 是可选注入(纯规则装配里没有它),缺的时候拿到的是注入占位而不是实例。
|
|
561
|
+
* 这里判一次成员类型,缺了就当没有——诊断丢了不影响规则面正确性。
|
|
562
|
+
*/
|
|
563
|
+
log(level, message, ...args) {
|
|
564
|
+
const sink = this.logger;
|
|
565
|
+
const write = sink?.[level];
|
|
566
|
+
if (typeof write === "function") write.call(sink, message, ...args);
|
|
567
|
+
}
|
|
568
|
+
async read() {
|
|
569
|
+
try {
|
|
570
|
+
return await readFile(this.path, "utf8");
|
|
571
|
+
} catch (error) {
|
|
572
|
+
if (error.code !== "ENOENT") throw error;
|
|
573
|
+
}
|
|
574
|
+
return await this.createDefault();
|
|
575
|
+
}
|
|
576
|
+
/** 首次启动:把默认规则落盘;写不进去就只在内存里用它,并记一条警告。 */
|
|
577
|
+
async createDefault() {
|
|
578
|
+
const { text, skipped } = defaultSandboxToml(process.env);
|
|
579
|
+
if (skipped.length > 0) this.log("warn", "默认沙箱规则有 %d 条写不出来(环境变量未设:%s),这份文件会缺那几条:%s", skipped.length, skipped.join(" / "), this.path);
|
|
580
|
+
try {
|
|
581
|
+
await writeFile(this.path, text, {
|
|
582
|
+
encoding: "utf8",
|
|
583
|
+
flag: "wx"
|
|
584
|
+
});
|
|
585
|
+
this.log("info", "已创建默认沙箱规则:%s", this.path);
|
|
586
|
+
} catch (error) {
|
|
587
|
+
if (error.code === "EEXIST") return await readFile(this.path, "utf8").catch(() => text);
|
|
588
|
+
this.log("warn", "默认沙箱规则写不进去(%s),本次用内置那份:%s", this.path, String(error));
|
|
589
|
+
}
|
|
590
|
+
return text;
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
SandboxFileDefault = __decorate([Injectable()], SandboxFileDefault);
|
|
594
|
+
// src/sandbox-rules.service.ts
|
|
595
|
+
const KNOWN_KEYS = /* @__PURE__ */ new Set([
|
|
596
|
+
"access",
|
|
597
|
+
"runnerCommand",
|
|
598
|
+
"runnerFailureSignatures",
|
|
599
|
+
"probeTimeoutMs",
|
|
600
|
+
"cwd",
|
|
601
|
+
"diffBasisMaxBytes"
|
|
602
|
+
]);
|
|
603
|
+
function emptySource() {
|
|
604
|
+
return {
|
|
605
|
+
allowWrite: [],
|
|
606
|
+
readOnly: [],
|
|
607
|
+
deny: []
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* 缺省规则。
|
|
612
|
+
*
|
|
613
|
+
* `cwd`(相对路径的解析基准)由调用方给 `AppEnv` 的起始目录——环境事实只有那一个来源。
|
|
614
|
+
* 每次新建:模块级常量会被多个实例(多个 app)共享,前一个用例的规则会漏到后一个。
|
|
615
|
+
* @param cwd - 相对路径的解析基准。
|
|
616
|
+
* @returns 一份全新的缺省设置。
|
|
617
|
+
*/
|
|
618
|
+
function defaults(cwd) {
|
|
619
|
+
return {
|
|
620
|
+
access: [],
|
|
621
|
+
runnerCommand: [],
|
|
622
|
+
runnerFailureSignatures: [],
|
|
623
|
+
probeTimeoutMs: 5e3,
|
|
624
|
+
cwd,
|
|
625
|
+
diffBasisMaxBytes: 0xa00000
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function strings(value, field) {
|
|
629
|
+
if (value === void 0) return [];
|
|
630
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new TypeError(`"${field}" must be an array of strings`);
|
|
631
|
+
return value;
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* 规则条目:**数组与多行字符串两种写法都收**。
|
|
635
|
+
*
|
|
636
|
+
* TOML 里最顺手的写法是块标量(`access = """\nrw /tmp\n"""`,一行一条),源部署的 patch 就是那个形状;
|
|
637
|
+
* 只认数组会让那份配置整份被当成坏文件退到空规则——症状是沙箱静默只剩工作区可写。
|
|
638
|
+
* 空行丢弃(块标量首尾的空行是写法带来的,不是规则)。
|
|
639
|
+
* @param value - 文档里的 `access` 字段。
|
|
640
|
+
* @returns 一条条规则文本。
|
|
641
|
+
*/
|
|
642
|
+
function accessEntries(value) {
|
|
643
|
+
if (typeof value === "string") return value.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
644
|
+
return strings(value, "access");
|
|
645
|
+
}
|
|
646
|
+
function positiveInteger(value, field, fallback) {
|
|
647
|
+
if (value === void 0) return fallback;
|
|
648
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) throw new TypeError(`"${field}" must be a positive integer`);
|
|
649
|
+
return value;
|
|
650
|
+
}
|
|
651
|
+
function text(value, field, fallback) {
|
|
652
|
+
if (value === void 0) return fallback;
|
|
653
|
+
if (typeof value !== "string" || value.length === 0) throw new TypeError(`"${field}" must be a non-empty string`);
|
|
654
|
+
return value;
|
|
655
|
+
}
|
|
656
|
+
let SandboxRulesDefault = class SandboxRulesDefault extends SandboxRules {
|
|
657
|
+
file = inject(SandboxFile);
|
|
658
|
+
logger = inject(Logger);
|
|
659
|
+
/**
|
|
660
|
+
* `cwd` 缺省的来源:`AppEnv.defaultWorkingDirectory`。
|
|
661
|
+
*
|
|
662
|
+
* 注入而不是在缺省值里读 `process.cwd()`:环境事实只有一个来源,
|
|
663
|
+
* 打包形态下进程 cwd 不是用户的项目目录。
|
|
664
|
+
*/
|
|
665
|
+
appEnv = inject(AppEnv);
|
|
666
|
+
state;
|
|
667
|
+
rules = emptySource();
|
|
668
|
+
async onInit(_ctx) {
|
|
669
|
+
const raw = await this.file.read();
|
|
670
|
+
if (raw === void 0) return;
|
|
671
|
+
const loaded = this.load(raw);
|
|
672
|
+
if (loaded === void 0) return;
|
|
673
|
+
Object.assign(this.settings(), loaded.settings);
|
|
674
|
+
Object.assign(this.rules, loaded.source);
|
|
675
|
+
}
|
|
676
|
+
settings() {
|
|
677
|
+
this.state ??= defaults(this.appEnv.defaultWorkingDirectory);
|
|
678
|
+
return this.state;
|
|
679
|
+
}
|
|
680
|
+
source() {
|
|
681
|
+
return this.rules;
|
|
682
|
+
}
|
|
683
|
+
load(raw) {
|
|
684
|
+
let document;
|
|
685
|
+
try {
|
|
686
|
+
document = parseToml(raw);
|
|
687
|
+
} catch (error) {
|
|
688
|
+
return this.degraded(`is not valid TOML (${String(error)})`);
|
|
689
|
+
}
|
|
690
|
+
const unknown = Object.keys(document).filter((key) => !KNOWN_KEYS.has(key));
|
|
691
|
+
if (unknown.length > 0) return this.degraded(`has unknown field(s) ${unknown.join(", ")}`);
|
|
692
|
+
const base = this.settings();
|
|
693
|
+
let settings;
|
|
694
|
+
try {
|
|
695
|
+
settings = {
|
|
696
|
+
access: accessEntries(document["access"]),
|
|
697
|
+
runnerCommand: strings(document["runnerCommand"], "runnerCommand"),
|
|
698
|
+
runnerFailureSignatures: strings(document["runnerFailureSignatures"], "runnerFailureSignatures"),
|
|
699
|
+
probeTimeoutMs: positiveInteger(document["probeTimeoutMs"], "probeTimeoutMs", base.probeTimeoutMs),
|
|
700
|
+
cwd: text(document["cwd"], "cwd", base.cwd),
|
|
701
|
+
diffBasisMaxBytes: positiveInteger(document["diffBasisMaxBytes"], "diffBasisMaxBytes", base.diffBasisMaxBytes)
|
|
702
|
+
};
|
|
703
|
+
} catch (error) {
|
|
704
|
+
return this.degraded(`has a wrongly typed field (${String(error)})`);
|
|
705
|
+
}
|
|
706
|
+
try {
|
|
707
|
+
return {
|
|
708
|
+
settings,
|
|
709
|
+
source: ruleSourceOf(settings.access, process.env)
|
|
710
|
+
};
|
|
711
|
+
} catch (error) {
|
|
712
|
+
this.warn(`has an unusable access entry (${String(error)})`);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
degraded(reason) {
|
|
717
|
+
this.warn(reason);
|
|
718
|
+
}
|
|
719
|
+
warn(reason) {
|
|
720
|
+
this.logger.warn(`configurable-sandbox: ${this.file.path} ${reason}, so no sandbox rules are applied`);
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
SandboxRulesDefault = __decorate([Injectable()], SandboxRulesDefault);
|
|
724
|
+
// src/events.ts
|
|
725
|
+
var events_exports = /* @__PURE__ */ __exportAll({ AgentCreated: () => AgentCreated });
|
|
726
|
+
var AgentCreated = class extends EventEmitter {
|
|
727
|
+
constructor() {
|
|
728
|
+
super("agent/created");
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
// src/runtime-contexts.service.ts
|
|
732
|
+
function effectiveApprovalPolicy(approval, session) {
|
|
733
|
+
return approval.overrideOf(session) ?? approval.config.policy ?? "ask";
|
|
734
|
+
}
|
|
735
|
+
let SandboxRuntimeContexts = class SandboxRuntimeContexts {
|
|
736
|
+
created$ = new AgentCreated();
|
|
737
|
+
rules = inject(SandboxRules);
|
|
738
|
+
policy = inject(SandboxPolicy);
|
|
739
|
+
installed = /* @__PURE__ */ new WeakSet();
|
|
740
|
+
onInit(ctx) {
|
|
741
|
+
this.created$.on(({ agent }) => {
|
|
742
|
+
this.install(agent);
|
|
743
|
+
});
|
|
744
|
+
for (const agent of this.existingAgents(ctx)) this.install(agent);
|
|
745
|
+
}
|
|
746
|
+
existingAgents(ctx) {
|
|
747
|
+
return ctx.get("agents", false)?.list() ?? [];
|
|
748
|
+
}
|
|
749
|
+
install(agent) {
|
|
750
|
+
if (this.installed.has(agent)) return;
|
|
751
|
+
this.installed.add(agent);
|
|
752
|
+
const prompt = agent.ctx.get("systemPrompt", false);
|
|
753
|
+
if (prompt === void 0) return;
|
|
754
|
+
this.registerSandboxPolicy(prompt);
|
|
755
|
+
this.registerApprovalPolicy(prompt);
|
|
756
|
+
}
|
|
757
|
+
registerSandboxPolicy(prompt) {
|
|
758
|
+
const rules = this.rules.source();
|
|
759
|
+
const policy = this.policy;
|
|
760
|
+
prompt.context({
|
|
761
|
+
name: SANDBOX_POLICY_CONTEXT,
|
|
762
|
+
order: prompt.getContextOrder("SANDBOX_POLICY"),
|
|
763
|
+
text: (context) => {
|
|
764
|
+
const session = context.agent?.session;
|
|
765
|
+
if (session === void 0) return "";
|
|
766
|
+
return renderPolicyContext(policy.resolve({ session }), rules);
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
registerApprovalPolicy(prompt) {
|
|
771
|
+
prompt.context({
|
|
772
|
+
name: APPROVAL_POLICY_CONTEXT,
|
|
773
|
+
order: prompt.getContextOrder("APPROVAL_POLICY"),
|
|
774
|
+
text: (context) => {
|
|
775
|
+
const current = context.agent;
|
|
776
|
+
if (current === void 0) return "";
|
|
777
|
+
const approval = current.ctx.get("approval", false);
|
|
778
|
+
return approval === void 0 ? "" : renderApprovalContext(effectiveApprovalPolicy(approval, current.session));
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
SandboxRuntimeContexts = __decorate([Injectable()], SandboxRuntimeContexts);
|
|
784
|
+
// src/configurable-sandbox.provide.ts
|
|
785
|
+
const provideConfigurableSandbox = provide([
|
|
786
|
+
SandboxFileDefault,
|
|
787
|
+
SandboxRulesDefault,
|
|
788
|
+
ConfigurableSandbox,
|
|
789
|
+
ConfigurableFsSandbox,
|
|
790
|
+
SandboxRuntimeContexts
|
|
791
|
+
]);
|
|
792
|
+
export { APPROVAL_POLICY_CONTEXT, ConfigurableFileSystem, ConfigurableFsSandbox, ConfigurableSandbox, ConfigurableSandboxProvider, DIALECT_CAPABILITIES, events_exports as Events, SANDBOX_POLICY_CONTEXT, SandboxFile, SandboxFileDefault, SandboxRules, SandboxRulesDefault, SandboxRuntimeContexts, blocksWrite, compileRules, dialectOf, expandEnvTemplates, extendConfinedArgv, globToRegexSource, isDenied, isEmptyRules, isPathUnder, isReadOnly, parseAccess, provideConfigurableSandbox, renderApprovalContext, renderPolicyContext, ruleSourceOf, upstreamConfigOf, upstreamFsConfigOf, withoutAllowRoots, writableRootsWith };
|