@eum-agent/sandbox-presets 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.js +1209 -0
  2. package/package.json +57 -3
  3. package/ui/ui.js +952 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,1209 @@
1
+ import { existsSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { z } from "zod";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { delimiter, isAbsolute, normalize, parse, resolve } from "node:path";
6
+ //#region src/sandbox-presets/schema.ts
7
+ /** Strict public preset data and persisted application shapes. */
8
+ /** Fixed repository; users never submit arbitrary download URLs. */
9
+ const PRESET_REPOSITORY = "https://github.com/yanxuan-lc/yaoguang-presets";
10
+ /** A full Git object identity. */
11
+ const ShaSchema = z.string().regex(/^[a-f0-9]{40}$/);
12
+ /** Portable owner-local category identity. */
13
+ const IdSchema = z.string().max(80).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
14
+ const text = (max) => z.string().refine((s) => [...s].length >= 1 && [...s].length <= max && /\S/u.test(s), "invalid text length");
15
+ const url = z.string().max(2048).refine((value) => {
16
+ try {
17
+ const u = new URL(value);
18
+ return value.startsWith("https://") && u.protocol === "https:" && !!u.hostname && !u.username && !u.password;
19
+ } catch {
20
+ return false;
21
+ }
22
+ }, "expected credential-free HTTPS URL");
23
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
24
+ const d = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
25
+ return Number.isFinite(d.getTime()) && d.toISOString().slice(0, 10) === value;
26
+ }, "invalid calendar date");
27
+ /** Environment names allowed by preset locator syntax; bootstrap injects these as explicit policy. */
28
+ const SANDBOX_LOCATOR_ENVIRONMENT_NAMES = [
29
+ "XDG_CONFIG_HOME",
30
+ "XDG_CACHE_HOME",
31
+ "XDG_DATA_HOME",
32
+ "XDG_STATE_HOME",
33
+ "JAVA_HOME",
34
+ "GRADLE_USER_HOME",
35
+ "SDKMAN_DIR",
36
+ "GOPATH",
37
+ "GOCACHE",
38
+ "GOROOT",
39
+ "CARGO_HOME",
40
+ "RUSTUP_HOME",
41
+ "PNPM_HOME",
42
+ "NVM_DIR",
43
+ "VOLTA_HOME",
44
+ "FNM_DIR",
45
+ "PYENV_ROOT",
46
+ "PIP_CONFIG_FILE",
47
+ "PIP_CACHE_DIR",
48
+ "UV_CACHE_DIR",
49
+ "UV_CONFIG_FILE",
50
+ "UV_TOOL_DIR",
51
+ "UV_PYTHON_INSTALL_DIR",
52
+ "UV_CREDENTIALS_DIR",
53
+ "POETRY_CONFIG_DIR",
54
+ "POETRY_CACHE_DIR",
55
+ "CONDA_PREFIX",
56
+ "NUGET_PACKAGES",
57
+ "DOTNET_ROOT",
58
+ "GEM_HOME",
59
+ "COMPOSER_HOME",
60
+ "COMPOSER_CACHE_DIR",
61
+ "PUB_CACHE",
62
+ "ANDROID_HOME",
63
+ "ANDROID_USER_HOME",
64
+ "PLAYWRIGHT_BROWSERS_PATH",
65
+ "DOCKER_CONFIG",
66
+ "GH_CONFIG_DIR",
67
+ "GLAB_CONFIG_DIR",
68
+ "AWS_CONFIG_FILE",
69
+ "AWS_SHARED_CREDENTIALS_FILE",
70
+ "CLOUDSDK_CONFIG",
71
+ "AZURE_CONFIG_DIR",
72
+ "TF_CLI_CONFIG_FILE",
73
+ "APPDATA",
74
+ "LOCALAPPDATA",
75
+ "USERPROFILE"
76
+ ];
77
+ /** Literal locator syntax shared with the maintained schema; no interpolation code. */
78
+ const LocatorSchema = z.string().max(4096).regex(new RegExp(String.raw`^(?!.*(?:^|\/)(?:\.|\.\.)(?:\/|$))(?!.*\/\/)(?:~\/(?!$)|\/(?!\/|$)|[A-Za-z]:\/(?!\/|$)|\$\{(?:${SANDBOX_LOCATOR_ENVIRONMENT_NAMES.join("|")})\}(?:\/|$))[^\u0000-\u001f\u007f\\*?[\]{}$\x60:]*$`, "u"));
79
+ /** One declared configuration root and its public provenance. */
80
+ const EntrySchema = z.object({
81
+ id: IdSchema,
82
+ path: LocatorSchema,
83
+ targetType: z.enum(["file", "directory"]),
84
+ description: text(512),
85
+ containsCredentials: z.boolean(),
86
+ sources: z.array(url).min(1).max(8)
87
+ }).strict();
88
+ const platform = z.object({ readable: z.array(EntrySchema).min(1).max(4096) }).strict();
89
+ /** Complete category content; unknown fields cannot acquire semantics. */
90
+ const ProfileSchema = z.object({
91
+ id: IdSchema,
92
+ name: text(120),
93
+ description: text(1024),
94
+ verification: z.object({
95
+ level: z.enum(["documentation", "sandbox-tested"]),
96
+ toolVersions: z.array(text(160)).min(1).max(16),
97
+ checkedAt: date
98
+ }).strict(),
99
+ notes: z.array(text(2048)).max(32),
100
+ platforms: z.object({
101
+ darwin: platform.optional(),
102
+ linux: platform.optional(),
103
+ win32: platform.optional()
104
+ }).strict().refine((v) => Object.keys(v).length > 0, "missing platform")
105
+ }).strict().superRefine((value, ctx) => {
106
+ for (const [name, p] of Object.entries(value.platforms)) {
107
+ if (!p) continue;
108
+ const ids = /* @__PURE__ */ new Set(), targets = /* @__PURE__ */ new Set();
109
+ for (const [i, entry] of p.readable.entries()) {
110
+ const key = `${entry.path.replace(/\/+$/, "")}\0${entry.targetType}`;
111
+ if (ids.has(entry.id) || targets.has(key)) ctx.addIssue({
112
+ code: "custom",
113
+ path: [
114
+ "platforms",
115
+ name,
116
+ "readable",
117
+ i
118
+ ],
119
+ message: "duplicate entry identity or target"
120
+ });
121
+ ids.add(entry.id);
122
+ targets.add(key);
123
+ }
124
+ }
125
+ });
126
+ /** Exact source bytes and revision: remote Git commit or package-local Git blob identity. */
127
+ const StoredProfileSchema = z.object({
128
+ id: IdSchema,
129
+ commit: ShaSchema,
130
+ blobSha: ShaSchema,
131
+ content: z.string().max(131072),
132
+ profile: ProfileSchema
133
+ }).strict();
134
+ /** Complete verified snapshot used for new selections. */
135
+ const SnapshotSchema = z.object({
136
+ commit: ShaSchema,
137
+ syncedAt: z.string(),
138
+ profiles: z.array(StoredProfileSchema).min(1).max(128)
139
+ }).strict();
140
+ /** User choice identifies an exact category revision, never a filesystem root. */
141
+ const SelectionSchema = z.object({
142
+ presetId: IdSchema,
143
+ commit: ShaSchema
144
+ }).strict();
145
+ /** Roots explicitly confirmed at apply time; missing locators are not persisted as permissions. */
146
+ const ContributionSchema = z.object({
147
+ presetId: IdSchema,
148
+ entryId: IdSchema,
149
+ commit: ShaSchema,
150
+ locator: LocatorSchema,
151
+ path: z.string().max(4096),
152
+ targetType: z.enum(["file", "directory"]),
153
+ description: text(512),
154
+ containsCredentials: z.boolean(),
155
+ sources: z.array(url).min(1).max(8)
156
+ }).strict();
157
+ /** Durable receipt for the most recently committed application only. */
158
+ const ReceiptSchema = z.object({
159
+ previewId: z.uuid(),
160
+ revision: z.number().int().nonnegative(),
161
+ selections: z.array(SelectionSchema).max(128)
162
+ }).strict();
163
+ /** One atomic installation-level state row. */
164
+ const StoredStateSchema = z.object({
165
+ revision: z.number().int().nonnegative(),
166
+ available: SnapshotSchema.nullable(),
167
+ profiles: z.array(StoredProfileSchema).max(128),
168
+ contributions: z.array(ContributionSchema).max(4096),
169
+ receipt: ReceiptSchema.nullable()
170
+ }).strict();
171
+ //#endregion
172
+ //#region src/sandbox-presets/bundled.ts
173
+ /** Offline runtime profile copied verbatim from the maintained preset repository. */
174
+ const content$1 = "{\n \"id\": \"system-runtime\",\n \"name\": \"基础运行环境\",\n \"description\": \"macOS 基础命令、系统库和系统运行数据的只读访问;新安装随平台扩展默认安装。\",\n \"verification\": {\n \"level\": \"documentation\",\n \"toolVersions\": [\n \"macOS system runtime\"\n ],\n \"checkedAt\": \"2026-10-04\"\n },\n \"notes\": [\n \"不另行增加 /opt/homebrew、Xcode 或用户研发工具目录;/usr 的递归读取包含 /usr/local,因此也覆盖 Intel Homebrew 安装在该处的内容。\",\n \"/Library 和系统配置目录可能包含主机及应用配置;安装前核对整个递归读取范围。\",\n \"只授予读取,缺失目录不会在以后出现时自动获权。\"\n ],\n \"platforms\": {\n \"darwin\": {\n \"readable\": [\n {\n \"id\": \"system-1\",\n \"path\": \"/usr\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/usr;不授予写入。\",\n \"containsCredentials\": false,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-2\",\n \"path\": \"/bin\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/bin;不授予写入。\",\n \"containsCredentials\": false,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-3\",\n \"path\": \"/sbin\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/sbin;不授予写入。\",\n \"containsCredentials\": false,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-4\",\n \"path\": \"/System\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/System;不授予写入。\",\n \"containsCredentials\": false,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-5\",\n \"path\": \"/Library\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/Library;不授予写入。\",\n \"containsCredentials\": true,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-6\",\n \"path\": \"/private/etc\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/private/etc;不授予写入。\",\n \"containsCredentials\": true,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-7\",\n \"path\": \"/private/var/db\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/private/var/db;不授予写入。\",\n \"containsCredentials\": true,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n },\n {\n \"id\": \"system-8\",\n \"path\": \"/private/var/select\",\n \"targetType\": \"directory\",\n \"description\": \"macOS 系统运行目录的递归读取:/private/var/select;不授予写入。\",\n \"containsCredentials\": false,\n \"sources\": [\n \"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html\"\n ]\n }\n ]\n }\n }\n}\n";
175
+ /** Exact profile bytes from https://github.com/yanxuan-lc/yaoguang-presets/blob/8f5eab8e92914178791d7f562d141d0d84857592/sandbox/system-runtime/paths.json. */
176
+ const BUNDLED_PRESETS = [StoredProfileSchema.parse({
177
+ id: "system-runtime",
178
+ commit: "8f5eab8e92914178791d7f562d141d0d84857592",
179
+ blobSha: "6c0ebc45a5246436ab75287495848717f90f7e40",
180
+ content: content$1,
181
+ profile: JSON.parse(content$1)
182
+ })];
183
+ //#endregion
184
+ //#region src/sandbox-presets/errors.ts
185
+ /** Safe error categories; neither environment values nor remote error bodies cross this boundary. */
186
+ var PresetError = class extends Error {
187
+ /** Stable management failure code. */
188
+ code;
189
+ /** Optional server-directed retry delay in seconds. */
190
+ retryAfterSeconds;
191
+ /** Creates an actionable failure with already sanitized text. */
192
+ constructor(code, message, retryAfterSeconds) {
193
+ super(message);
194
+ this.name = "PresetError";
195
+ this.code = code;
196
+ this.retryAfterSeconds = retryAfterSeconds;
197
+ }
198
+ };
199
+ /** Throws a bounded catalog error without echoing untrusted input. */
200
+ function invalid(message) {
201
+ throw new PresetError("CATALOG_INVALID", message);
202
+ }
203
+ /** Parses JSON without silently accepting duplicate object keys. */
204
+ function parseJson(content) {
205
+ let value;
206
+ try {
207
+ value = JSON.parse(content);
208
+ } catch {
209
+ return invalid("Invalid JSON");
210
+ }
211
+ const stack = [];
212
+ for (const match of content.matchAll(/"(?:[^"\\]|\\.)*"|[{}[\]]/g)) {
213
+ const token = match[0];
214
+ if (token === "{") stack.push(/* @__PURE__ */ new Set());
215
+ else if (token === "[") stack.push(null);
216
+ else if (token === "}" || token === "]") stack.pop();
217
+ else if (/^\s*:/.test(content.slice((match.index ?? 0) + token.length))) {
218
+ const keys = stack.at(-1);
219
+ if (keys) {
220
+ const key = JSON.parse(token);
221
+ if (keys.has(key)) return invalid("Duplicate JSON property");
222
+ keys.add(key);
223
+ }
224
+ }
225
+ }
226
+ return value;
227
+ }
228
+ /** Decodes lossless UTF-8, retaining BOMs for the JSON grammar to reject. */
229
+ function decodeUtf8(bytes) {
230
+ try {
231
+ return new TextDecoder("utf-8", {
232
+ fatal: true,
233
+ ignoreBOM: true
234
+ }).decode(bytes);
235
+ } catch {
236
+ return invalid("Invalid UTF-8");
237
+ }
238
+ }
239
+ //#endregion
240
+ //#region src/sandbox-presets/catalog.ts
241
+ /** Generated bundle verification for one pinned commit of the fixed public repository. */
242
+ /** Computes Git's SHA-1 blob identity over exact UTF-8 bytes. */
243
+ function blobSha(bytes) {
244
+ return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
245
+ }
246
+ const BundleSchema = z.object({ presets: z.array(z.object({
247
+ id: IdSchema,
248
+ path: z.string().max(160),
249
+ blobSha: ShaSchema,
250
+ content: z.string()
251
+ }).strict()).min(1).max(128) }).strict();
252
+ /** Validates retained source bytes against their decoded profile and digest. */
253
+ function verifyProfile(stored) {
254
+ const bytes = Buffer.from(stored.content);
255
+ if (bytes.length > 131072) throw new PresetError("LIMIT_EXCEEDED", "Profile exceeds 128 KiB");
256
+ if (stored.content.includes("\r") || blobSha(bytes) !== stored.blobSha) invalid("Profile bytes or digest are invalid");
257
+ const result = ProfileSchema.safeParse(parseJson(stored.content));
258
+ if (!result.success || result.data.id !== stored.id || JSON.stringify(result.data) !== JSON.stringify(stored.profile)) invalid("Profile content and identity disagree");
259
+ }
260
+ /**
261
+ * Decodes the generated bundle read from one pinned commit into a complete snapshot.
262
+ * Every category must have a unique id, live at `sandbox/<id>/paths.json`, and carry content
263
+ * whose Git blob identity matches its declared digest. Throws `PresetError` with
264
+ * `CATALOG_INVALID` for malformed or inconsistent data and `LIMIT_EXCEEDED` for oversized input.
265
+ */
266
+ function decodeCatalog(commit, bytes, syncedAt = (/* @__PURE__ */ new Date()).toISOString()) {
267
+ if (bytes.length > 8388608) throw new PresetError("LIMIT_EXCEEDED", "Catalog exceeds 8 MiB");
268
+ const bundle = BundleSchema.safeParse(parseJson(decodeUtf8(bytes)));
269
+ if (!ShaSchema.safeParse(commit).success || !bundle.success) invalid("Invalid catalog bundle");
270
+ const profiles = [], ids = /* @__PURE__ */ new Set();
271
+ let entries = 0;
272
+ for (const item of bundle.data.presets) {
273
+ if (ids.has(item.id) || item.path !== `sandbox/${item.id}/paths.json`) invalid("Category identity or path mismatch");
274
+ if (Buffer.byteLength(item.content) > 131072) throw new PresetError("LIMIT_EXCEEDED", "Profile exceeds 128 KiB");
275
+ const parsed = ProfileSchema.safeParse(parseJson(item.content));
276
+ if (!parsed.success) invalid(`Invalid profile: ${item.id}`);
277
+ const profile = {
278
+ id: item.id,
279
+ commit,
280
+ blobSha: item.blobSha,
281
+ content: item.content,
282
+ profile: parsed.data
283
+ };
284
+ verifyProfile(profile);
285
+ entries += Object.values(parsed.data.platforms).reduce((n, p) => n + (p?.readable.length ?? 0), 0);
286
+ if (entries > 4096) throw new PresetError("LIMIT_EXCEEDED", "Catalog exceeds 4096 entries");
287
+ ids.add(item.id);
288
+ profiles.push(profile);
289
+ }
290
+ return {
291
+ commit,
292
+ syncedAt,
293
+ profiles: profiles.sort((a, b) => a.id < b.id ? -1 : 1)
294
+ };
295
+ }
296
+ //#endregion
297
+ //#region src/sandbox-presets/linux-bundled.ts
298
+ /** Package-maintained Linux baseline; independent of the downloaded Darwin snapshot. */
299
+ const profile = ProfileSchema.parse({
300
+ id: "linux-system-runtime",
301
+ name: "Linux 基础运行环境",
302
+ description: "Linux 系统命令、动态库、名称解析与公共证书的只读访问;新安装默认启用,可移除。",
303
+ verification: {
304
+ level: "documentation",
305
+ toolVersions: ["Linux filesystem hierarchy"],
306
+ checkedAt: "2026-10-06"
307
+ },
308
+ notes: [
309
+ "由平台扩展维护,修订号为随包内容的 Git blob 身份,不代表远程预设仓库的提交。",
310
+ "/usr 包含 /usr/local;只授予读取,不增加用户工具目录、私钥目录或写入权限。",
311
+ "符号链接解析到真实目标;缺失目标不会在之后出现时自动获权。"
312
+ ],
313
+ platforms: { linux: { readable: [
314
+ "/usr",
315
+ "/bin",
316
+ "/sbin",
317
+ "/lib",
318
+ "/lib64",
319
+ "/etc/ssl/certs",
320
+ "/etc/ld.so.cache",
321
+ "/etc/resolv.conf",
322
+ "/etc/hosts",
323
+ "/etc/nsswitch.conf",
324
+ "/etc/passwd",
325
+ "/etc/group",
326
+ "/etc/localtime"
327
+ ].map((path, index) => ({
328
+ id: `runtime-${index + 1}`,
329
+ path,
330
+ targetType: index < 6 ? "directory" : "file",
331
+ description: `Linux 基础运行环境只读目标:${path}`,
332
+ containsCredentials: false,
333
+ sources: ["https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html"]
334
+ })) } }
335
+ });
336
+ const content = `${JSON.stringify(profile, null, 2)}\n`;
337
+ const identity = blobSha(Buffer.from(content));
338
+ /** Local immutable content revision, never treated as a remote catalog commit. */
339
+ const BUNDLED_LINUX_PRESETS = [{
340
+ id: profile.id,
341
+ commit: identity,
342
+ blobSha: identity,
343
+ content,
344
+ profile
345
+ }];
346
+ //#endregion
347
+ //#region src/sandbox-presets/paths.ts
348
+ /** Locator resolution reads host facts and metadata only, never configuration bodies. */
349
+ /** Resolves one platform's entries and fingerprints locator facts without returning raw environment. */
350
+ function resolveProfile(profile, commit, host, reads) {
351
+ const platform = profile.platforms[host.platform];
352
+ const rows = [], contributions = [], facts = [];
353
+ const home = host.realpath(host.homedir());
354
+ for (const entry of platform?.readable ?? []) {
355
+ let path = null, status = "ready", candidate = null;
356
+ const variable = /^\$\{([A-Z_]+)\}(.*)$/.exec(entry.path);
357
+ let env;
358
+ if (variable) {
359
+ env = host.environment(variable[1] ?? "");
360
+ if (!env || !isAbsolute(env) || env.includes(delimiter) || [...env].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) status = "unresolved";
361
+ else candidate = normalize(`${env}${variable[2]}`);
362
+ } else candidate = entry.path.startsWith("~/") ? resolve(home, entry.path.slice(2)) : entry.path;
363
+ if (candidate && (!isAbsolute(candidate) || candidate === parse(candidate).root || candidate === home)) status = "invalid";
364
+ if (status === "ready" && candidate) try {
365
+ path = host.realpath(candidate);
366
+ if (path === home || path === parse(path).root) status = "invalid";
367
+ else status = reads.inspect({
368
+ path,
369
+ targetType: entry.targetType
370
+ }) ?? "ready";
371
+ } catch {
372
+ status = "missing";
373
+ }
374
+ const row = {
375
+ presetId: profile.id,
376
+ entryId: entry.id,
377
+ commit,
378
+ locator: entry.path,
379
+ path,
380
+ targetType: entry.targetType,
381
+ status,
382
+ description: entry.description,
383
+ containsCredentials: entry.containsCredentials,
384
+ sources: entry.sources
385
+ };
386
+ rows.push(row);
387
+ facts.push([
388
+ entry.id,
389
+ env ?? null,
390
+ candidate,
391
+ path,
392
+ status
393
+ ]);
394
+ if (status === "ready" && path) contributions.push({
395
+ presetId: profile.id,
396
+ entryId: entry.id,
397
+ commit,
398
+ locator: entry.path,
399
+ path,
400
+ targetType: entry.targetType,
401
+ description: entry.description,
402
+ containsCredentials: entry.containsCredentials,
403
+ sources: entry.sources
404
+ });
405
+ }
406
+ return {
407
+ rows,
408
+ contributions,
409
+ fingerprint: createHash("sha256").update(JSON.stringify(facts)).digest("hex")
410
+ };
411
+ }
412
+ //#endregion
413
+ //#region src/sandbox-presets/sync.ts
414
+ const refsUrl = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
415
+ const rawBase = "https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets";
416
+ /** Reads one bounded public response; failures map to stable preset error codes. */
417
+ async function readResponse(network, url, signal) {
418
+ signal.throwIfAborted();
419
+ let response;
420
+ try {
421
+ response = await network.fetch(url, {
422
+ signal,
423
+ redirect: "error",
424
+ headers: { "User-Agent": "YaoGuang-presets" }
425
+ });
426
+ } catch {
427
+ signal.throwIfAborted();
428
+ throw new PresetError("FETCH_FAILED", "Could not fetch the preset catalog through the gateway route");
429
+ }
430
+ if (!response.ok) {
431
+ response.body?.cancel();
432
+ if (response.status === 429 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
433
+ const after = Number(response.headers.get("retry-after")) || Math.max(0, Number(response.headers.get("x-ratelimit-reset")) - Math.floor(Date.now() / 1e3));
434
+ throw new PresetError("RATE_LIMITED", "GitHub rate limit reached", Number.isFinite(after) ? Math.min(86400, Math.max(0, after)) : void 0);
435
+ }
436
+ throw new PresetError(response.status === 409 || response.status === 404 ? "CATALOG_EMPTY" : "FETCH_FAILED", `Catalog request failed (HTTP ${response.status})`);
437
+ }
438
+ if (Number(response.headers.get("content-length")) > 8388608) {
439
+ response.body?.cancel();
440
+ throw new PresetError("LIMIT_EXCEEDED", "Response exceeds 8 MiB");
441
+ }
442
+ const reader = response.body?.getReader();
443
+ if (!reader) return /* @__PURE__ */ new Uint8Array();
444
+ const chunks = [];
445
+ let size = 0;
446
+ try {
447
+ for (;;) {
448
+ signal.throwIfAborted();
449
+ const chunk = await reader.read();
450
+ if (chunk.done) break;
451
+ size += chunk.value.length;
452
+ if (size > 8388608) throw new PresetError("LIMIT_EXCEEDED", "Response exceeds 8 MiB");
453
+ chunks.push(chunk.value);
454
+ }
455
+ signal.throwIfAborted();
456
+ return Buffer.concat(chunks, size);
457
+ } finally {
458
+ await reader.cancel().catch(() => {});
459
+ reader.releaseLock();
460
+ }
461
+ }
462
+ /**
463
+ * Extracts the `refs/heads/main` commit from a Git smart HTTP upload-pack ref advertisement.
464
+ * Requires the `# service=git-upload-pack` announcement and well-formed pkt-lines; throws
465
+ * `PresetError` with `CATALOG_INVALID` otherwise.
466
+ */
467
+ function mainCommit(text) {
468
+ const lines = [];
469
+ for (let at = 0; at < text.length;) {
470
+ const header = text.slice(at, at + 4);
471
+ if (!/^[0-9a-f]{4}$/.test(header)) invalid("Malformed ref advertisement");
472
+ const length = Number.parseInt(header, 16);
473
+ if (length === 0) {
474
+ at += 4;
475
+ continue;
476
+ }
477
+ if (length < 4 || at + length > text.length) invalid("Malformed ref advertisement");
478
+ lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
479
+ at += length;
480
+ }
481
+ if (lines[0] !== "# service=git-upload-pack") invalid("Missing upload-pack announcement");
482
+ for (const line of lines.slice(1)) {
483
+ const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
484
+ if (match?.[2] === "refs/heads/main") return match[1];
485
+ }
486
+ return invalid("Branch main is not advertised");
487
+ }
488
+ /**
489
+ * Resolves `main` with one ref-advertisement request, then reads `sandbox/index.json` pinned to
490
+ * that commit. An unchanged commit reuses `previous` with a fresh sync time and no second request.
491
+ */
492
+ async function synchronize(network, signal, previous) {
493
+ const commit = mainCommit(decodeUtf8(await readResponse(network, refsUrl, signal)));
494
+ if (previous?.commit === commit) return {
495
+ ...previous,
496
+ syncedAt: (/* @__PURE__ */ new Date()).toISOString()
497
+ };
498
+ const bytes = await readResponse(network, `${rawBase}/${commit}/sandbox/index.json`, signal);
499
+ signal.throwIfAborted();
500
+ return decodeCatalog(commit, bytes);
501
+ }
502
+ //#endregion
503
+ //#region src/sandbox-presets/service.ts
504
+ /**
505
+ * Creates one activation with committed owner permissions and offline package candidates.
506
+ * Installs the supplied package profiles only into a pristine supported-platform state; a recorded
507
+ * application or explicit removal prevents later automatic installation. An absent optional
508
+ * projection defers installation until a state or readable-source read can inspect roots. Initialization
509
+ * failures contribute no preset permissions. Source reads never download catalogs.
510
+ */
511
+ function createPresetService(deps) {
512
+ const { host, store, reads, owner } = deps;
513
+ const supportedPlatform = host.platform === "darwin" || host.platform === "linux";
514
+ const bundled = (deps.bundled ?? []).filter((p) => p.profile.platforms[host.platform]);
515
+ for (const profile of bundled) verifyProfile(profile);
516
+ let initializationError = null;
517
+ let initializationReady = false;
518
+ let initializationAttempted = false;
519
+ const bundleView = bundled.length ? {
520
+ commit: bundled[0].commit,
521
+ presetIds: bundled.map((p) => p.id)
522
+ } : null;
523
+ function availableProfiles(state) {
524
+ const profiles = new Map(bundled.map((p) => [p.id, p]));
525
+ for (const profile of state.available?.profiles ?? []) profiles.set(profile.id, profile);
526
+ return [...profiles.values()];
527
+ }
528
+ const previews = /* @__PURE__ */ new Map();
529
+ let syncing = null;
530
+ const guard = () => deps.signal.throwIfAborted();
531
+ const source = reads.register({
532
+ id: "sandbox-presets",
533
+ label: "Sandbox presets",
534
+ read() {
535
+ guard();
536
+ initialize();
537
+ if (initializationError) throw initializationError;
538
+ const state = store.readApplied();
539
+ return {
540
+ revision: state.revision,
541
+ paths: state.contributions.map((c) => ({
542
+ path: c.path,
543
+ targetType: c.targetType
544
+ }))
545
+ };
546
+ }
547
+ });
548
+ function notify(reason, revision) {
549
+ try {
550
+ deps.notify?.(reason, revision);
551
+ } catch {}
552
+ }
553
+ function targets(current, contributions) {
554
+ const groups = /* @__PURE__ */ new Map();
555
+ function add(path, targetType, provenance) {
556
+ const key = JSON.stringify([path, targetType]);
557
+ const target = groups.get(key) ?? {
558
+ path,
559
+ targetType,
560
+ sources: []
561
+ };
562
+ target.sources.push(provenance);
563
+ groups.set(key, target);
564
+ }
565
+ for (const base of current.base) try {
566
+ const path = host.realpath(base), stat = host.stat(path);
567
+ if (stat.file || stat.directory) add(path, stat.directory ? "directory" : "file", {
568
+ owner: "core",
569
+ id: base,
570
+ label: "Local readable path",
571
+ origin: "base"
572
+ });
573
+ } catch {}
574
+ for (const registered of current.sources) {
575
+ if (registered.owner === owner && registered.id === "sandbox-presets") continue;
576
+ for (const root of registered.paths) add(root.path, root.targetType, {
577
+ owner: registered.owner,
578
+ id: registered.id,
579
+ label: registered.label,
580
+ origin: "owner"
581
+ });
582
+ }
583
+ for (const c of contributions) if (!reads.inspect(c)) add(c.path, c.targetType, {
584
+ owner,
585
+ id: "sandbox-presets",
586
+ label: c.presetId,
587
+ origin: "preset",
588
+ presetId: c.presetId,
589
+ entryId: c.entryId,
590
+ commit: c.commit
591
+ });
592
+ return [...groups.values()].sort((a, b) => a.path.localeCompare(b.path));
593
+ }
594
+ function list() {
595
+ guard();
596
+ initialize();
597
+ const current = reads.current();
598
+ let state;
599
+ try {
600
+ state = store.read();
601
+ } catch (error) {
602
+ const e = error instanceof PresetError ? error : new PresetError("CATALOG_INVALID", "Stored preset state cannot be read");
603
+ return {
604
+ source: PRESET_REPOSITORY,
605
+ bundled: bundleView,
606
+ platform: host.platform,
607
+ supportedPlatform,
608
+ sandboxEnabled: current.enabled,
609
+ availableCommit: null,
610
+ lastSyncedAt: null,
611
+ appliedRevision: 0,
612
+ selections: [],
613
+ profiles: [],
614
+ contributions: [],
615
+ inactive: [],
616
+ effective: targets(current, []),
617
+ syncState: syncing ? { operationId: syncing.operationId } : null,
618
+ lastReceipt: null,
619
+ error: {
620
+ code: e.code,
621
+ message: e.message
622
+ }
623
+ };
624
+ }
625
+ const available = availableProfiles(state), ids = [.../* @__PURE__ */ new Set([...available.map((p) => p.id), ...state.profiles.map((p) => p.id)])].sort();
626
+ return {
627
+ source: PRESET_REPOSITORY,
628
+ bundled: bundleView,
629
+ platform: host.platform,
630
+ supportedPlatform,
631
+ sandboxEnabled: current.enabled,
632
+ availableCommit: state.available?.commit ?? null,
633
+ lastSyncedAt: state.available?.syncedAt ?? null,
634
+ appliedRevision: state.revision,
635
+ selections: state.profiles.map((p) => ({
636
+ presetId: p.id,
637
+ commit: p.commit
638
+ })),
639
+ profiles: ids.map((id) => {
640
+ const latest = available.find((p) => p.id === id), applied = state.profiles.find((p) => p.id === id), p = applied ?? latest;
641
+ if (!p) throw new Error("Missing category");
642
+ const entries = p.profile.platforms[host.platform]?.readable;
643
+ return {
644
+ id,
645
+ name: p.profile.name,
646
+ description: p.profile.description,
647
+ notes: p.profile.notes,
648
+ verification: p.profile.verification,
649
+ availableCommit: latest?.commit ?? null,
650
+ bundledCommit: bundled.find((p) => p.id === id)?.commit ?? null,
651
+ appliedCommit: applied?.commit ?? null,
652
+ sourceUrl: p.commit === p.blobSha ? null : `${PRESET_REPOSITORY}/blob/${p.commit}/sandbox/${p.id}/paths.json`,
653
+ supported: !!entries,
654
+ removed: !latest,
655
+ latest: latest?.profile ?? null,
656
+ entries: entries ?? []
657
+ };
658
+ }),
659
+ contributions: state.contributions,
660
+ inactive: state.contributions.flatMap((c) => {
661
+ const reason = reads.inspect(c);
662
+ return reason ? [{
663
+ path: c.path,
664
+ reason
665
+ }] : [];
666
+ }),
667
+ effective: targets(current, state.contributions),
668
+ syncState: syncing ? { operationId: syncing.operationId } : null,
669
+ lastReceipt: state.receipt,
670
+ error: initializationError ? {
671
+ code: initializationError.code,
672
+ message: initializationError.message
673
+ } : store.cacheError()
674
+ };
675
+ }
676
+ function prepare(selections, state) {
677
+ const ids = /* @__PURE__ */ new Set();
678
+ const sorted = [...selections].sort((a, b) => a.presetId.localeCompare(b.presetId));
679
+ const profiles = sorted.map((s) => {
680
+ if (ids.has(s.presetId)) throw new PresetError("PROFILE_UNAVAILABLE", "Category selected more than once");
681
+ ids.add(s.presetId);
682
+ const p = [
683
+ ...state.available?.profiles ?? [],
684
+ ...bundled,
685
+ ...state.profiles
686
+ ].find((p) => p.id === s.presetId && p.commit === s.commit);
687
+ if (!p) throw new PresetError("PROFILE_UNAVAILABLE", "Selected category revision is unavailable");
688
+ if (!p.profile.platforms[host.platform]) throw new PresetError("UNSUPPORTED_PLATFORM", "Selected category does not support this gateway platform");
689
+ return p;
690
+ });
691
+ const resolved = profiles.map((p) => resolveProfile(p.profile, p.commit, host, reads));
692
+ const rows = resolved.flatMap((r) => r.rows), contributions = resolved.flatMap((r) => r.contributions);
693
+ const current = reads.current(), before = targets(current, state.contributions), after = targets(current, contributions);
694
+ const key = (t) => JSON.stringify([t.path, t.targetType]);
695
+ const beforeMap = new Map(before.map((t) => [key(t), t])), afterMap = new Map(after.map((t) => [key(t), t]));
696
+ const blockedCount = rows.filter((r) => ![
697
+ "ready",
698
+ "missing",
699
+ "unresolved"
700
+ ].includes(r.status)).length;
701
+ return {
702
+ fingerprint: createHash("sha256").update(JSON.stringify({
703
+ selections: sorted,
704
+ revision: state.revision,
705
+ available: state.available?.commit ?? null,
706
+ current: current.revision,
707
+ facts: resolved.map((r) => r.fingerprint)
708
+ })).digest("hex"),
709
+ profiles,
710
+ contributions,
711
+ view: {
712
+ inputRevision: current.revision,
713
+ selections: sorted,
714
+ rows,
715
+ added: after.filter((t) => !beforeMap.has(key(t))),
716
+ removed: before.filter((t) => !afterMap.has(key(t))),
717
+ retained: after.filter((t) => beforeMap.has(key(t))),
718
+ sourceChanges: after.flatMap((t) => {
719
+ const old = beforeMap.get(key(t));
720
+ return old && JSON.stringify(old.sources) !== JSON.stringify(t.sources) ? [{
721
+ path: t.path,
722
+ before: old.sources,
723
+ after: t.sources
724
+ }] : [];
725
+ }),
726
+ blockedCount,
727
+ inactiveCount: rows.filter((r) => r.status !== "ready").length,
728
+ canApply: supportedPlatform && blockedCount === 0
729
+ }
730
+ };
731
+ }
732
+ const service = {
733
+ list,
734
+ preview(selections) {
735
+ guard();
736
+ const p = prepare(selections, store.read()), previewId = randomUUID();
737
+ const view = {
738
+ ...p.view,
739
+ previewId
740
+ };
741
+ if (previews.size >= 32) previews.delete(previews.keys().next().value ?? "");
742
+ previews.set(previewId, {
743
+ ...p,
744
+ view
745
+ });
746
+ return view;
747
+ },
748
+ apply(previewId) {
749
+ guard();
750
+ const latest = store.read();
751
+ if (latest.receipt?.previewId === previewId) return {
752
+ state: list(),
753
+ receipt: latest.receipt,
754
+ alreadyApplied: true
755
+ };
756
+ const candidate = previews.get(previewId);
757
+ if (!candidate) throw new PresetError("PREVIEW_REQUIRED", "Preview is unavailable; review your selection again");
758
+ if (!candidate.view.canApply) throw new PresetError(supportedPlatform ? "PREVIEW_BLOCKED" : "UNSUPPORTED_PLATFORM", "This preview cannot be applied");
759
+ let written;
760
+ try {
761
+ written = store.transact((before) => {
762
+ guard();
763
+ const now = prepare(candidate.view.selections, before);
764
+ if (now.fingerprint !== candidate.fingerprint) throw new PresetError("PREVIEW_STALE", "Configuration or targets changed; preview again");
765
+ const revision = before.revision + 1;
766
+ return {
767
+ ...before,
768
+ revision,
769
+ profiles: now.profiles,
770
+ contributions: now.contributions,
771
+ receipt: {
772
+ previewId,
773
+ revision,
774
+ selections: candidate.view.selections
775
+ }
776
+ };
777
+ });
778
+ } catch (error) {
779
+ if (error instanceof PresetError) throw error;
780
+ throw new PresetError("APPLY_FAILED", "Could not persist preset application; previous state is retained");
781
+ }
782
+ initializationError = null;
783
+ try {
784
+ source.changed();
785
+ } catch {}
786
+ notify("applied", written.revision);
787
+ if (!written.receipt) throw new Error("Missing application receipt");
788
+ return {
789
+ state: list(),
790
+ receipt: written.receipt,
791
+ alreadyApplied: false
792
+ };
793
+ },
794
+ async sync(operationId, connectionSignal) {
795
+ guard();
796
+ if (syncing) throw new PresetError("BUSY", "A synchronization is already running");
797
+ const revision = store.read().revision;
798
+ const abort = new AbortController(), operation = {
799
+ operationId,
800
+ abort
801
+ };
802
+ syncing = operation;
803
+ notify("sync-started", revision);
804
+ const signal = AbortSignal.any([
805
+ deps.signal,
806
+ connectionSignal,
807
+ abort.signal,
808
+ AbortSignal.timeout(6e4)
809
+ ]);
810
+ let reason = "sync-failed";
811
+ try {
812
+ const snapshot = await synchronize(deps.network, signal, store.read().available);
813
+ signal.throwIfAborted();
814
+ guard();
815
+ store.saveSnapshot(snapshot);
816
+ reason = "sync-complete";
817
+ } catch (error) {
818
+ if (signal.aborted) {
819
+ reason = "sync-cancelled";
820
+ throw new PresetError("FETCH_FAILED", "Synchronization cancelled or timed out; previous state is retained");
821
+ }
822
+ if (error instanceof PresetError) throw error;
823
+ throw new PresetError("FETCH_FAILED", "Synchronization failed; previous state is retained");
824
+ } finally {
825
+ if (syncing === operation) syncing = null;
826
+ if (!deps.signal.aborted) notify(reason, revision);
827
+ }
828
+ return list();
829
+ },
830
+ cancel(operationId) {
831
+ guard();
832
+ if (!syncing || syncing.operationId !== operationId || syncing.abort.signal.aborted) return { cancelled: false };
833
+ syncing.abort.abort();
834
+ return { cancelled: true };
835
+ },
836
+ dispose() {
837
+ syncing?.abort.abort();
838
+ source.dispose();
839
+ previews.clear();
840
+ }
841
+ };
842
+ function initialize() {
843
+ if (!initializationReady || initializationAttempted || !bundled.length || !supportedPlatform || deps.projectionAvailable && !deps.projectionAvailable()) return;
844
+ initializationAttempted = true;
845
+ try {
846
+ const state = store.read();
847
+ if (state.revision === 0 && !state.profiles.length && !state.contributions.length && !state.receipt) {
848
+ if (store.cacheError()) throw new PresetError("CATALOG_INVALID", "Stored catalog cache is invalid; initialization is disabled");
849
+ const preview = service.preview(bundled.map((p) => ({
850
+ presetId: p.id,
851
+ commit: p.commit
852
+ })));
853
+ service.apply(preview.previewId);
854
+ }
855
+ } catch (error) {
856
+ initializationError = error instanceof PresetError ? error : new PresetError("APPLY_FAILED", "Could not install bundled runtime; contribution is disabled");
857
+ }
858
+ }
859
+ initializationReady = true;
860
+ initialize();
861
+ return service;
862
+ }
863
+ //#endregion
864
+ //#region src/sandbox-presets/store.ts
865
+ /** Checks relational identities in addition to the strict JSON shape. */
866
+ function validateState(input) {
867
+ const parsed = StoredStateSchema.safeParse(input);
868
+ if (!parsed.success) throw new PresetError("CATALOG_INVALID", "Stored preset state is invalid; contribution is disabled");
869
+ const state = parsed.data;
870
+ for (const profiles of [state.profiles, state.available?.profiles ?? []]) {
871
+ const ids = /* @__PURE__ */ new Set();
872
+ let count = 0;
873
+ for (const profile of profiles) {
874
+ if (ids.has(profile.id)) throw new PresetError("CATALOG_INVALID", "Duplicate stored category");
875
+ ids.add(profile.id);
876
+ verifyProfile(profile);
877
+ count += Object.values(profile.profile.platforms).reduce((n, p) => n + (p?.readable.length ?? 0), 0);
878
+ if (count > 4096) throw new PresetError("LIMIT_EXCEEDED", "Stored entries exceed budget");
879
+ }
880
+ }
881
+ if (state.available?.profiles.some((p) => p.commit !== state.available?.commit)) throw new PresetError("CATALOG_INVALID", "Snapshot commit mismatch");
882
+ const keys = /* @__PURE__ */ new Set();
883
+ for (const c of state.contributions) {
884
+ const profile = state.profiles.find((p) => p.id === c.presetId && p.commit === c.commit);
885
+ const key = `${c.presetId}\0${c.entryId}`;
886
+ if (!(profile && Object.values(profile.profile.platforms).flatMap((p) => p?.readable ?? []).find((e) => e.id === c.entryId && e.path === c.locator && e.targetType === c.targetType)) || keys.has(key)) throw new PresetError("CATALOG_INVALID", "Contribution does not match its selected profile");
887
+ keys.add(key);
888
+ }
889
+ const selections = state.profiles.map((p) => ({
890
+ presetId: p.id,
891
+ commit: p.commit
892
+ }));
893
+ if (state.receipt && (state.receipt.revision !== state.revision || JSON.stringify(selections) !== JSON.stringify(state.receipt.selections))) throw new PresetError("CATALOG_INVALID", "Receipt does not match applied state");
894
+ return state;
895
+ }
896
+ /** Creates the state authority on the supplied cooperative database lease. */
897
+ function createPresetStore(storage) {
898
+ const { db } = storage;
899
+ const name = storage.tableName("sandbox_catalog_state");
900
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
901
+ const table = `"${name}"`;
902
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER NOT NULL PRIMARY KEY CHECK(id=1), applied_revision INTEGER NOT NULL DEFAULT 0 CHECK(applied_revision>=0), available_json TEXT NOT NULL DEFAULT 'null', applied_profiles_json TEXT NOT NULL DEFAULT '[]', contributions_json TEXT NOT NULL DEFAULT '[]', last_apply_json TEXT NOT NULL DEFAULT 'null')`);
903
+ db.prepare(`INSERT OR IGNORE INTO ${table}(id) VALUES(1)`).run();
904
+ function row() {
905
+ return db.prepare(`SELECT * FROM ${table} WHERE id=1`).get();
906
+ }
907
+ function applied(record) {
908
+ try {
909
+ return validateState({
910
+ revision: record.applied_revision,
911
+ available: null,
912
+ profiles: JSON.parse(String(record.applied_profiles_json)),
913
+ contributions: JSON.parse(String(record.contributions_json)),
914
+ receipt: JSON.parse(String(record.last_apply_json))
915
+ });
916
+ } catch (error) {
917
+ if (error instanceof PresetError) throw error;
918
+ throw new PresetError("CATALOG_INVALID", "Stored applied JSON is damaged; contribution is disabled");
919
+ }
920
+ }
921
+ function available(record) {
922
+ try {
923
+ return validateState({
924
+ revision: 0,
925
+ profiles: [],
926
+ contributions: [],
927
+ receipt: null,
928
+ available: JSON.parse(String(record.available_json))
929
+ }).available;
930
+ } catch {
931
+ throw new PresetError("CATALOG_INVALID", "Downloaded catalog cache is damaged; sync to repair it. Applied targets are retained");
932
+ }
933
+ }
934
+ function read() {
935
+ const record = row(), state = applied(record);
936
+ try {
937
+ return {
938
+ ...state,
939
+ available: available(record)
940
+ };
941
+ } catch {
942
+ return state;
943
+ }
944
+ }
945
+ function transact(work) {
946
+ db.exec("BEGIN IMMEDIATE");
947
+ try {
948
+ const result = validateState(work(read()));
949
+ db.prepare(`UPDATE ${table} SET applied_revision=?, available_json=?, applied_profiles_json=?, contributions_json=?, last_apply_json=? WHERE id=1`).run(result.revision, JSON.stringify(result.available), JSON.stringify(result.profiles), JSON.stringify(result.contributions), JSON.stringify(result.receipt));
950
+ db.exec("COMMIT");
951
+ return result;
952
+ } catch (error) {
953
+ if (db.isTransaction) db.exec("ROLLBACK");
954
+ throw error;
955
+ }
956
+ }
957
+ return {
958
+ read,
959
+ /** Reads confirmed permissions independently of the replaceable download cache. */
960
+ readApplied() {
961
+ return applied(row());
962
+ },
963
+ /** Reports damaged downloaded data without invalidating confirmed permissions. */
964
+ cacheError() {
965
+ try {
966
+ available(row());
967
+ return null;
968
+ } catch (error) {
969
+ const e = error;
970
+ return {
971
+ code: e.code,
972
+ message: e.message
973
+ };
974
+ }
975
+ },
976
+ transact,
977
+ /** Replaces available data only after full validation; applied fields are preserved. */
978
+ saveSnapshot(snapshot) {
979
+ return transact((before) => ({
980
+ ...before,
981
+ available: snapshot
982
+ }));
983
+ }
984
+ };
985
+ }
986
+ //#endregion
987
+ //#region src/sandbox-presets/views.ts
988
+ /** Browser management values validated by the extension at the socket boundary. */
989
+ /** Per-entry locator and current metadata outcome. */
990
+ const RowSchema = z.object({
991
+ presetId: z.string(),
992
+ entryId: z.string(),
993
+ commit: ShaSchema,
994
+ locator: z.string(),
995
+ path: z.string().nullable(),
996
+ targetType: z.enum(["file", "directory"]),
997
+ status: z.enum([
998
+ "ready",
999
+ "missing",
1000
+ "unresolved",
1001
+ "invalid",
1002
+ "sealed",
1003
+ "type-mismatch",
1004
+ "changed-target",
1005
+ "unsupported"
1006
+ ]),
1007
+ description: z.string(),
1008
+ containsCredentials: z.boolean(),
1009
+ sources: z.array(z.string())
1010
+ }).strict();
1011
+ /** All provenance retained for one target. */
1012
+ const TargetSourceSchema = z.object({
1013
+ owner: z.string(),
1014
+ id: z.string(),
1015
+ label: z.string(),
1016
+ origin: z.enum([
1017
+ "base",
1018
+ "owner",
1019
+ "preset"
1020
+ ]),
1021
+ presetId: z.string().optional(),
1022
+ entryId: z.string().optional(),
1023
+ commit: ShaSchema.optional()
1024
+ }).strict();
1025
+ /** A unique actual read root; parents never replace child roots. */
1026
+ const TargetSchema = z.object({
1027
+ path: z.string(),
1028
+ targetType: z.enum(["file", "directory"]),
1029
+ sources: z.array(TargetSourceSchema)
1030
+ }).strict();
1031
+ /** One selectable category, including removed-but-applied old versions. */
1032
+ const CategorySchema = z.object({
1033
+ id: z.string(),
1034
+ name: z.string(),
1035
+ description: z.string(),
1036
+ notes: z.array(z.string()),
1037
+ verification: ProfileSchema.shape.verification,
1038
+ availableCommit: ShaSchema.nullable(),
1039
+ bundledCommit: ShaSchema.nullable(),
1040
+ appliedCommit: ShaSchema.nullable(),
1041
+ sourceUrl: z.string().url().nullable(),
1042
+ supported: z.boolean(),
1043
+ removed: z.boolean(),
1044
+ latest: ProfileSchema.nullable(),
1045
+ entries: z.array(EntrySchema)
1046
+ }).strict();
1047
+ /** Current local state; list never makes HTTP requests. */
1048
+ const StateSchema = z.object({
1049
+ source: z.string(),
1050
+ bundled: z.object({
1051
+ commit: ShaSchema,
1052
+ presetIds: z.array(z.string())
1053
+ }).strict().nullable(),
1054
+ platform: z.string(),
1055
+ supportedPlatform: z.boolean(),
1056
+ sandboxEnabled: z.boolean(),
1057
+ availableCommit: ShaSchema.nullable(),
1058
+ lastSyncedAt: z.string().nullable(),
1059
+ appliedRevision: z.number(),
1060
+ selections: z.array(SelectionSchema),
1061
+ profiles: z.array(CategorySchema),
1062
+ contributions: z.array(ContributionSchema),
1063
+ inactive: z.array(z.object({
1064
+ path: z.string(),
1065
+ reason: z.string()
1066
+ })),
1067
+ effective: z.array(TargetSchema),
1068
+ syncState: z.object({ operationId: z.string() }).nullable(),
1069
+ lastReceipt: ReceiptSchema.nullable(),
1070
+ error: z.object({
1071
+ code: z.string(),
1072
+ message: z.string()
1073
+ }).nullable()
1074
+ }).strict();
1075
+ /** An exact permission draft with actual roots, inactive rows, and full source differences. */
1076
+ const PreviewSchema = z.object({
1077
+ previewId: z.uuid(),
1078
+ inputRevision: z.string(),
1079
+ selections: z.array(SelectionSchema),
1080
+ rows: z.array(RowSchema),
1081
+ added: z.array(TargetSchema),
1082
+ removed: z.array(TargetSchema),
1083
+ retained: z.array(TargetSchema),
1084
+ sourceChanges: z.array(z.object({
1085
+ path: z.string(),
1086
+ before: z.array(TargetSourceSchema),
1087
+ after: z.array(TargetSourceSchema)
1088
+ })),
1089
+ blockedCount: z.number(),
1090
+ inactiveCount: z.number(),
1091
+ canApply: z.boolean()
1092
+ }).strict();
1093
+ /** Committed application with most-recent receipt replay status. */
1094
+ const ApplySchema = z.object({
1095
+ state: StateSchema,
1096
+ receipt: ReceiptSchema,
1097
+ alreadyApplied: z.boolean()
1098
+ }).strict();
1099
+ /** A business failure that leaves prior permission state untouched. */
1100
+ const FailureSchema = z.object({
1101
+ ok: z.literal(false),
1102
+ code: z.string(),
1103
+ message: z.string(),
1104
+ retryAfterSeconds: z.number().optional()
1105
+ }).strict();
1106
+ /** Constructs a real result schema for owner-managed RPC responses. */
1107
+ function resultSchema(data) {
1108
+ return z.union([z.object({
1109
+ ok: z.literal(true),
1110
+ data
1111
+ }).strict(), FailureSchema]);
1112
+ }
1113
+ //#endregion
1114
+ //#region src/sandbox-presets/register.ts
1115
+ /** Registers installation-level catalog management and a pure invalidation frame. */
1116
+ function registerSandboxPresets(ctx) {
1117
+ const frame = ctx.client.registerFrame({
1118
+ name: "sandboxPresetChanged",
1119
+ delivery: "broadcast",
1120
+ payload: z.object({
1121
+ reason: z.enum([
1122
+ "sync-started",
1123
+ "sync-complete",
1124
+ "sync-failed",
1125
+ "sync-cancelled",
1126
+ "applied"
1127
+ ]),
1128
+ revision: z.number().int().nonnegative()
1129
+ }).strict()
1130
+ });
1131
+ const host = ctx.services.get("sandbox-path-locator");
1132
+ const service = createPresetService({
1133
+ host,
1134
+ store: createPresetStore(ctx.storage.open()),
1135
+ reads: ctx.sandboxReadables,
1136
+ network: ctx.services.get("network"),
1137
+ signal: ctx.signal,
1138
+ owner: ctx.pluginName,
1139
+ bundled: host.platform === "linux" ? BUNDLED_LINUX_PRESETS : BUNDLED_PRESETS,
1140
+ projectionAvailable: () => ctx.services.find("sandbox-readable-projection") !== void 0,
1141
+ notify: (reason, revision) => frame.emit({
1142
+ reason,
1143
+ revision
1144
+ })
1145
+ });
1146
+ ctx.onDispose(() => service.dispose());
1147
+ async function result(work) {
1148
+ try {
1149
+ return {
1150
+ ok: true,
1151
+ data: await work()
1152
+ };
1153
+ } catch (error) {
1154
+ if (ctx.signal.aborted) throw error;
1155
+ const e = error instanceof PresetError ? error : new PresetError("APPLY_FAILED", "Preset operation failed; reload current state before retrying");
1156
+ return {
1157
+ ok: false,
1158
+ code: e.code,
1159
+ message: e.message,
1160
+ ...e.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: e.retryAfterSeconds }
1161
+ };
1162
+ }
1163
+ }
1164
+ ctx.client.registerMethod({
1165
+ name: "sandboxPresetList",
1166
+ params: z.object({}).strict(),
1167
+ result: resultSchema(StateSchema),
1168
+ handle: () => result(() => service.list())
1169
+ });
1170
+ ctx.client.registerMethod({
1171
+ name: "sandboxPresetSync",
1172
+ params: z.object({ operationId: z.uuid() }).strict(),
1173
+ result: resultSchema(StateSchema),
1174
+ handle: (p, call) => result(() => service.sync(p.operationId, call.signal))
1175
+ });
1176
+ ctx.client.registerMethod({
1177
+ name: "sandboxPresetSyncCancel",
1178
+ params: z.object({ operationId: z.uuid() }).strict(),
1179
+ result: resultSchema(z.object({ cancelled: z.boolean() }).strict()),
1180
+ handle: (p) => result(() => service.cancel(p.operationId))
1181
+ });
1182
+ ctx.client.registerMethod({
1183
+ name: "sandboxPresetPreview",
1184
+ params: z.object({ selections: z.array(SelectionSchema).max(128) }).strict(),
1185
+ result: resultSchema(PreviewSchema),
1186
+ handle: (p) => result(() => service.preview(p.selections))
1187
+ });
1188
+ ctx.client.registerMethod({
1189
+ name: "sandboxPresetApply",
1190
+ params: z.object({ previewId: z.uuid() }).strict(),
1191
+ result: resultSchema(ApplySchema),
1192
+ handle: (p) => result(() => service.apply(p.previewId))
1193
+ });
1194
+ }
1195
+ //#endregion
1196
+ //#region src/index.ts
1197
+ /** Owns sandbox-presets capabilities independently from bootstrap resources. */
1198
+ const plugin = {
1199
+ name: "@eum-agent/sandbox-presets",
1200
+ requires: ["sandbox-path-locator", "network"],
1201
+ optionalServices: ["sandbox-readable-projection"],
1202
+ apply(ctx) {
1203
+ registerSandboxPresets(ctx);
1204
+ const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1205
+ if (existsSync(module)) ctx.client.registerUi({ module });
1206
+ }
1207
+ };
1208
+ //#endregion
1209
+ export { SANDBOX_LOCATOR_ENVIRONMENT_NAMES, plugin as default };