@linxin666/dsh-client-ui-preset-center 0.3.19

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/lib/index.js ADDED
@@ -0,0 +1,1000 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
2
+ import { isAbsolute, join, sep } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
5
+ import { createHash } from "node:crypto";
6
+ //#region src/mount-once.ts
7
+ /**
8
+ * Host single-instance guard shared by the plugin family. The family bundle
9
+ * (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
10
+ * the loader accepts a standalone install of the same package side by side;
11
+ * without this guard the second instance would still re-register the same
12
+ * webserver routes, tools, settings namespaces, and system-prompt sections
13
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
14
+ * lifetime of the first instance (the browser half is already deduped by
15
+ * package name in the client module host).
16
+ *
17
+ * The registry rides a global symbol so two module instances of the same
18
+ * package (npm copy vs repository link) still share one verdict. cordis
19
+ * `ctx.effect` runs its callback immediately and treats the callback's
20
+ * return value as the fiber disposer, so the unmarker is returned, not run.
21
+ */
22
+ const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
23
+ function mountedSet() {
24
+ const registry = globalThis;
25
+ return registry[MOUNTED] ??= /* @__PURE__ */ new Set();
26
+ }
27
+ /**
28
+ * Wrap a cordis plugin apply so the package runs at most once per process.
29
+ * The first mount registers normally and unmarks when its fiber disposes;
30
+ * any later mount of the same package name is a no-op.
31
+ * @param packageName - npm package identity shared by every install source.
32
+ * @param fn - the original plugin apply.
33
+ * @returns an apply of the same shape.
34
+ */
35
+ function mountOnce(packageName, fn) {
36
+ return ((...args) => {
37
+ const mounted = mountedSet();
38
+ if (mounted.has(packageName)) return;
39
+ mounted.add(packageName);
40
+ args[0]?.effect?.(() => () => {
41
+ mounted.delete(packageName);
42
+ });
43
+ return fn(...args);
44
+ });
45
+ }
46
+ //#endregion
47
+ //#region src/dsh-home.ts
48
+ /**
49
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
50
+ * environment override wins, the platform home fallback follows. Mirrors
51
+ * what dsh-pet and dsh-liangshen each used to implement locally.
52
+ */
53
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
54
+ function expandHome(path, home = homedir()) {
55
+ const j = home.startsWith("/") ? join$1 : join;
56
+ if (path === "~") return home;
57
+ if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
58
+ return path;
59
+ }
60
+ /**
61
+ * Resolve the DSH home directory.
62
+ * @param env - process environment to read DSH_HOME from.
63
+ * @param home - platform home directory fallback (test seam).
64
+ * @returns the absolute DSH home path.
65
+ */
66
+ function resolveDshHome(env = process.env, home = homedir()) {
67
+ const isPosix = home.startsWith("/");
68
+ const j = isPosix ? join$1 : join;
69
+ const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
70
+ const raw = env.DSH_HOME;
71
+ if (raw !== void 0 && raw.trim() !== "") {
72
+ const expanded = expandHome(raw.trim(), home);
73
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
74
+ }
75
+ return j(home, ".dsh");
76
+ }
77
+ /** Resolve the DSH home directory from the live environment. */
78
+ function dshHome() {
79
+ return resolveDshHome();
80
+ }
81
+ //#endregion
82
+ //#region src/host/run-guarded.ts
83
+ /**
84
+ * Async-boundary guard shared by the plugin family's Host halves: every
85
+ * fire-and-forget promise chain and callback the host runtime does not own
86
+ * (route handlers, timers, event listeners, spawned work) funnels through
87
+ * these helpers. The dsh host installs a process-level fail-loud guard that
88
+ * turns ANY unhandled promise rejection into a whole-process exit — one
89
+ * plugin's stray rejection would otherwise take every plugin down. These
90
+ * helpers exist so that failure mode is structurally impossible in family
91
+ * code: the rejection becomes a logged error at the plugin boundary instead.
92
+ *
93
+ * Complements the aggregate's shell isolation (packages/dsh-web-all): the
94
+ * shell contains import/activation failures at boot; runGuarded contains
95
+ * run-time failures after activation.
96
+ * @module dsh-web-shared/host/run-guarded
97
+ */
98
+ /** Format one failure line for logging. */
99
+ function formatFailure(label, error) {
100
+ return /* @__PURE__ */ new Error(`[${label}] unhandled async failure: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
101
+ }
102
+ /**
103
+ * Wrap one callback so every invocation is individually guarded: a rejection
104
+ * inside one call is logged and swallowed instead of escaping into whatever
105
+ * infrastructure invoked the callback (HTTP server, EventEmitter, interval).
106
+ * Sync throws are caught identically; a returned promise is replaced by
107
+ * `undefined` after guarding (callers that need the original rejection should
108
+ * await inside their own try/catch instead).
109
+ * @param label - log prefix naming the callback site.
110
+ * @param handler - the work to guard.
111
+ * @param log - error sink; defaults to console.error.
112
+ * @returns a wrapped callback with the same parameter list.
113
+ */
114
+ function guardedHandler(label, handler, log = console.error) {
115
+ return (...args) => {
116
+ try {
117
+ const result = handler(...args);
118
+ if (isPromiseLike(result)) {
119
+ Promise.resolve(result).catch((error) => {
120
+ log(formatFailure(label, error));
121
+ });
122
+ return;
123
+ }
124
+ return result;
125
+ } catch (error) {
126
+ log(formatFailure(label, error));
127
+ return;
128
+ }
129
+ };
130
+ }
131
+ function isPromiseLike(value) {
132
+ return typeof value === "object" && value !== null && typeof value.then === "function";
133
+ }
134
+ //#endregion
135
+ //#region src/loopback.ts
136
+ /** IPv4 127/8 predicate (four decimal octets, first == 127). */
137
+ function isIPv4Loopback(v4) {
138
+ const parts = v4.split(".");
139
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
140
+ }
141
+ /** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
142
+ function isLoopbackAddress(address) {
143
+ if (address === void 0) return false;
144
+ const normalized = address.toLowerCase();
145
+ if (normalized === "::1") return true;
146
+ if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice(7));
147
+ return isIPv4Loopback(normalized);
148
+ }
149
+ /** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
150
+ function isLoopbackHostname(hostname) {
151
+ if (hostname === "localhost" || hostname === "[::1]") return true;
152
+ return isIPv4Loopback(hostname);
153
+ }
154
+ /**
155
+ * Request-level trust fence: a loopback socket address AND a loopback Host
156
+ * header, plus browser same-origin markers. The socket address is
157
+ * authoritative; X-Forwarded-For is never trusted.
158
+ */
159
+ function isLoopbackRequest(request) {
160
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
161
+ const host = request.headers.host;
162
+ if (typeof host !== "string") return false;
163
+ let hostUrl;
164
+ try {
165
+ hostUrl = new URL("http://" + host);
166
+ } catch {
167
+ return false;
168
+ }
169
+ if (!isLoopbackHostname(hostUrl.hostname)) return false;
170
+ if (request.headers["sec-fetch-site"] === "cross-site") return false;
171
+ const origin = request.headers.origin;
172
+ if (origin === void 0) return true;
173
+ try {
174
+ return new URL(origin).host === hostUrl.host;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+ //#endregion
180
+ //#region src/http.ts
181
+ /** Default body cap for readJsonBody: 64 KiB. */
182
+ const DEFAULT_JSON_BODY_MAX_BYTES = 64 * 1024;
183
+ /** Family-default JSON response headers; callers may append or override. */
184
+ const JSON_HEADERS = {
185
+ "content-type": "application/json; charset=utf-8",
186
+ "referrer-policy": "no-referrer"
187
+ };
188
+ /**
189
+ * Lenient bounded body reader: parse a request body as JSON, or null on an
190
+ * empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
191
+ * Overflow destroys the request instead of draining the remainder (no drain
192
+ * call, matching the current repo-wide behavior); callers must not keep
193
+ * reading the request afterwards. With objectOnly, non-JSON-object payloads
194
+ * also yield null.
195
+ */
196
+ async function readJsonBody(req, opts = {}) {
197
+ const maxBytes = opts.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES;
198
+ const chunks = [];
199
+ let size = 0;
200
+ for await (const chunk of req) {
201
+ const buffer = chunk;
202
+ size += buffer.length;
203
+ if (size > maxBytes) {
204
+ req.destroy();
205
+ return null;
206
+ }
207
+ chunks.push(buffer);
208
+ }
209
+ const text = Buffer.concat(chunks).toString("utf8");
210
+ if (text === "") return null;
211
+ try {
212
+ const parsed = JSON.parse(text);
213
+ if (opts.objectOnly && !isJsonObject(parsed)) return null;
214
+ return parsed;
215
+ } catch {
216
+ return null;
217
+ }
218
+ }
219
+ /** Whether a value is a JSON object: typeof object, not null, not an array. */
220
+ function isJsonObject(value) {
221
+ return typeof value === "object" && value !== null && !Array.isArray(value);
222
+ }
223
+ /**
224
+ * Write one JSON response. Default headers are the family defaults
225
+ * (content-type and referrer-policy); caller headers are appended or
226
+ * override them.
227
+ */
228
+ function writeJson(res, status, body, headers = {}) {
229
+ const payload = JSON.stringify(body);
230
+ res.writeHead(status, {
231
+ ...JSON_HEADERS,
232
+ ...headers
233
+ });
234
+ res.end(payload);
235
+ }
236
+ //#endregion
237
+ //#region src/core/paths.ts
238
+ /**
239
+ * The preset-center storage contract: where an installed preset lives while it
240
+ * is inert (the library) and where it must live to be discovered (the harness
241
+ * home's user preset root).
242
+ *
243
+ * Both paths are a cross-package contract, not private state:
244
+ * - the library is the destination the market installer writes (`preset`
245
+ * asset kind) and no discovery root scans;
246
+ * - the discovery root is `USER_PRESET_DIR` of
247
+ * `@deepseek-ai/dsh-agent-presets`, appended to the roster unless a
248
+ * deployment sets `includeUserRoot: false`.
249
+ * @module @linxin666/dsh-client-ui-preset-center/core/paths
250
+ */
251
+ /** Library directory under the DSH home: installed but inert. */
252
+ const LIBRARY_DIR = "agent-presets";
253
+ /** Official user preset root under the DSH home: present means enabled. */
254
+ const ENABLED_DIR = ".agent-presets";
255
+ /**
256
+ * Provenance filename written by the market installer (mirrors
257
+ * `PROVENANCE_FILENAME` in `@linxin666/dsh-client-ui-market`; no
258
+ * cross-package runtime import, the same way the skin center mirrors it).
259
+ */
260
+ const PROVENANCE_FILENAME = "dsh-market.provenance.json";
261
+ /** The composition file that makes a directory a preset. */
262
+ const COMPOSITION_FILE = "agent.cordis.yml";
263
+ /** Official preset id rule (mirrors `PRESET_ID` in `@deepseek-ai/dsh-agent-presets`). */
264
+ const PRESET_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
265
+ /** Whether `id` is a usable preset directory name. */
266
+ function isPresetId(id) {
267
+ return typeof id === "string" && PRESET_ID_RE.test(id);
268
+ }
269
+ /** The library directory for one DSH home. */
270
+ function libraryRoot(dshHome) {
271
+ return join(dshHome, LIBRARY_DIR);
272
+ }
273
+ /** The discovery root for one DSH home. */
274
+ function enabledRoot(dshHome) {
275
+ return join(dshHome, ENABLED_DIR);
276
+ }
277
+ //#endregion
278
+ //#region src/core/provenance.ts
279
+ /**
280
+ * Market provenance for one installed preset: the record the market installer
281
+ * writes at install time (market origin, asset version, per-file sha256).
282
+ *
283
+ * It is what lets the panel tell a workshop-managed preset apart from a
284
+ * hand-authored directory, and a pristine copy apart from one edited after
285
+ * install. Fail-closed: unreadable or wrongly-shaped provenance is `missing`,
286
+ * never trusted.
287
+ * @module @linxin666/dsh-client-ui-preset-center/core/provenance
288
+ */
289
+ /** Market origin the provenance must pin (mirrors MARKET_ORIGIN in the market package). */
290
+ const MARKET_ORIGIN = "https://dsh-market.com";
291
+ function sha256Hex(abs) {
292
+ try {
293
+ return createHash("sha256").update(readFileSync(abs)).digest("hex");
294
+ } catch {
295
+ return null;
296
+ }
297
+ }
298
+ /** Every regular file under `dir`, as sorted relative POSIX paths. */
299
+ function listFiles(dir, base = "") {
300
+ const out = [];
301
+ let entries;
302
+ try {
303
+ entries = readdirSync(join(dir, base), { withFileTypes: true });
304
+ } catch {
305
+ return out;
306
+ }
307
+ for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
308
+ if (entry.name.startsWith(".")) continue;
309
+ const rel = base === "" ? entry.name : base + "/" + entry.name;
310
+ if (entry.isDirectory()) out.push(...listFiles(dir, rel));
311
+ else out.push(rel);
312
+ }
313
+ return out;
314
+ }
315
+ /** Read one preset directory's provenance record; null when absent or malformed. */
316
+ function readProvenance(dir, id) {
317
+ let raw;
318
+ try {
319
+ raw = JSON.parse(readFileSync(join(dir, PROVENANCE_FILENAME), "utf8"));
320
+ } catch {
321
+ return null;
322
+ }
323
+ if (typeof raw !== "object" || raw === null) return null;
324
+ const record = raw;
325
+ if (record.version !== 1) return null;
326
+ if (record.source !== "https://dsh-market.com") return null;
327
+ if (record.id !== id) return null;
328
+ const files = record.files;
329
+ if (typeof files !== "object" || files === null) return null;
330
+ const hashes = {};
331
+ for (const [rel, hash] of Object.entries(files)) {
332
+ if (typeof hash !== "string" || !/^[0-9a-f]{64}$/.test(hash)) return null;
333
+ hashes[rel] = hash;
334
+ }
335
+ const installedAt = typeof record.installedAt === "string" ? record.installedAt : "";
336
+ const assetVersion = typeof record.assetVersion === "string" ? record.assetVersion : void 0;
337
+ return {
338
+ version: 1,
339
+ source: MARKET_ORIGIN,
340
+ id,
341
+ installedAt,
342
+ ...assetVersion === void 0 ? {} : { assetVersion },
343
+ files: hashes
344
+ };
345
+ }
346
+ /** Verify one directory's bytes against its own provenance record. */
347
+ function verifyProvenance(dir, id) {
348
+ const provenance = readProvenance(dir, id);
349
+ if (provenance === null) return {
350
+ state: "missing",
351
+ provenance: null,
352
+ mismatches: [],
353
+ missing: [],
354
+ extra: []
355
+ };
356
+ const mismatches = [];
357
+ const missing = [];
358
+ for (const [rel, expected] of Object.entries(provenance.files)) {
359
+ const actual = sha256Hex(join(dir, ...rel.split("/")));
360
+ if (actual === null) missing.push(rel);
361
+ else if (actual !== expected) mismatches.push(rel);
362
+ }
363
+ const extra = listFiles(dir).filter((rel) => rel !== "dsh-market.provenance.json" && provenance.files[rel] === void 0);
364
+ return {
365
+ state: mismatches.length === 0 && missing.length === 0 ? "valid" : "modified",
366
+ provenance,
367
+ mismatches,
368
+ missing,
369
+ extra
370
+ };
371
+ }
372
+ /** Whether `dir` is a directory that exists. */
373
+ function isDirectory(dir) {
374
+ try {
375
+ return statSync(dir).isDirectory();
376
+ } catch {
377
+ return false;
378
+ }
379
+ }
380
+ //#endregion
381
+ //#region src/core/profile.ts
382
+ /**
383
+ * What a preset's composition will actually load, read from the installed
384
+ * bytes on the host — never from the market catalog, which a client could
385
+ * restate.
386
+ *
387
+ * The profile answers three questions the enabling confirmation needs: which
388
+ * plugins the composition names, which of those are files that travel inside
389
+ * the preset directory, and whether the file carries inline `!!js`
390
+ * expressions. All three are execution surfaces: a relative row and an inline
391
+ * expression both run inside the host process when a session composes the
392
+ * preset, exactly like an npm plugin does.
393
+ *
394
+ * The scan is deliberately shallow (line-oriented) and is a display signal,
395
+ * not a sandbox: the authoritative health verdict comes from the official
396
+ * roster after the directory is discoverable. A preset that hides a row from
397
+ * this scan is still gated by the install/enable split and the operator's
398
+ * confirmation.
399
+ * @module @linxin666/dsh-client-ui-preset-center/core/profile
400
+ */
401
+ const CODE_FILE_RE = /\.(?:mjs|cjs|js)$/;
402
+ /** Unquote a YAML scalar the shallow way (the profile is not a parser). */
403
+ function unquote(value) {
404
+ const trimmed = value.trim();
405
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") || trimmed.startsWith("\"") && trimmed.endsWith("\"")) return trimmed.slice(1, -1);
406
+ return trimmed;
407
+ }
408
+ /** Profile one composition document. */
409
+ function profileComposition(text, codeFiles) {
410
+ const plugins = [];
411
+ const relativeNames = [];
412
+ let inlineExpressions = 0;
413
+ let rows = 0;
414
+ for (const rawLine of text.split(/\r?\n/)) {
415
+ const line = rawLine.replace(/\s+#.*$/, "");
416
+ if (line.includes("!!js")) inlineExpressions += 1;
417
+ const match = /^\s*-?\s*name:\s*(.+?)\s*$/.exec(line);
418
+ if (match === null) continue;
419
+ rows += 1;
420
+ const name = unquote(match[1]);
421
+ if (name === "" || name === "cordis:group") continue;
422
+ if (name.startsWith(".")) relativeNames.push(name);
423
+ else plugins.push(name);
424
+ }
425
+ const localCode = codeFiles.filter((rel) => CODE_FILE_RE.test(rel));
426
+ const codeExecution = localCode.length > 0 || relativeNames.length > 0 ? "local" : inlineExpressions > 0 ? "inline" : "none";
427
+ return {
428
+ plugins: [...new Set(plugins)],
429
+ relativeNames: [...new Set(relativeNames)],
430
+ inlineExpressions,
431
+ codeFiles: localCode,
432
+ codeExecution,
433
+ rows
434
+ };
435
+ }
436
+ /** Profile one installed preset directory; an unreadable composition yields an empty profile. */
437
+ function profilePresetDir(dir) {
438
+ let text = "";
439
+ try {
440
+ text = readFileSync(join(dir, COMPOSITION_FILE), "utf8");
441
+ } catch {
442
+ text = "";
443
+ }
444
+ return profileComposition(text, listFiles(dir));
445
+ }
446
+ /** Whether enabling this profile needs an explicit confirmation from the operator. */
447
+ function needsConfirmation(profile) {
448
+ return profile.codeExecution !== "none";
449
+ }
450
+ //#endregion
451
+ //#region src/core/library.ts
452
+ /**
453
+ * The preset library state machine: install, enable, disable, uninstall, and
454
+ * the filesystem-derived state every surface reads.
455
+ *
456
+ * Two directories, one truth (see `paths.ts`): a preset in the library is
457
+ * inert because no discovery root scans it; a preset in the discovery root is
458
+ * live because the official roster re-reads its roots on every call. Every
459
+ * transition is a directory move, so a crash between steps leaves a state the
460
+ * next scan reports instead of a half-written preset.
461
+ *
462
+ * The module owns no policy: reserved ids and the default-preset guard live in
463
+ * the route layer, which is the only place that can read the roster.
464
+ * @module @linxin666/dsh-client-ui-preset-center/core/library
465
+ */
466
+ /** A refused library operation. */
467
+ var PresetOperationError = class extends Error {
468
+ code;
469
+ constructor(code, message) {
470
+ super(message);
471
+ this.code = code;
472
+ }
473
+ };
474
+ /** Subdirectory ids of one root, sorted; absent roots yield none. */
475
+ function scanPresetIds(root) {
476
+ let entries;
477
+ try {
478
+ entries = readdirSync(root, { withFileTypes: true });
479
+ } catch {
480
+ return [];
481
+ }
482
+ return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && isPresetId(entry.name)).map((entry) => entry.name).sort();
483
+ }
484
+ /** The state of one id, derived from the two directories. */
485
+ function readPresetState(dshHome, id) {
486
+ const libraryDir = join(libraryRoot(dshHome), id);
487
+ const enabledDir = join(enabledRoot(dshHome), id);
488
+ const installed = isDirectory(libraryDir);
489
+ const enabled = isDirectory(enabledDir);
490
+ const dir = enabled ? enabledDir : libraryDir;
491
+ const report = dir === libraryDir && !installed ? {
492
+ state: "missing",
493
+ provenance: null,
494
+ mismatches: [],
495
+ missing: [],
496
+ extra: []
497
+ } : verifyProvenance(dir, id);
498
+ const provenance = report.provenance;
499
+ return {
500
+ id,
501
+ installed,
502
+ enabled,
503
+ managed: provenance !== null,
504
+ ...provenance?.assetVersion === void 0 ? {} : { assetVersion: provenance.assetVersion },
505
+ ...provenance?.installedAt === void 0 ? {} : { installedAt: provenance.installedAt },
506
+ integrity: installed || enabled ? report.state : "none",
507
+ conflict: installed && enabled,
508
+ dir
509
+ };
510
+ }
511
+ /** Every id present in either directory, sorted, with its state. */
512
+ function listPresetStates(dshHome) {
513
+ return [.../* @__PURE__ */ new Set([...scanPresetIds(libraryRoot(dshHome)), ...scanPresetIds(enabledRoot(dshHome))])].sort().map((id) => readPresetState(dshHome, id));
514
+ }
515
+ const RETRYABLE = /* @__PURE__ */ new Set([
516
+ "EPERM",
517
+ "EBUSY",
518
+ "EACCES",
519
+ "ENOTEMPTY"
520
+ ]);
521
+ function errnoOf(err) {
522
+ const code = typeof err === "object" && err !== null ? err.code : void 0;
523
+ return typeof code === "string" ? code : void 0;
524
+ }
525
+ /** File count and byte total of a tree, for the cross-volume copy check. */
526
+ function treeStats(dir) {
527
+ let files = 0;
528
+ let bytes = 0;
529
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
530
+ const abs = join(dir, entry.name);
531
+ if (entry.isDirectory()) {
532
+ const nested = treeStats(abs);
533
+ files += nested.files;
534
+ bytes += nested.bytes;
535
+ } else if (entry.isFile()) {
536
+ files += 1;
537
+ bytes += statSync(abs).size;
538
+ }
539
+ }
540
+ return {
541
+ files,
542
+ bytes
543
+ };
544
+ }
545
+ /**
546
+ * Move one directory into a destination that must not exist yet. A rename is
547
+ * atomic within a volume; across volumes the directory is copied, verified by
548
+ * file count and byte total, and only then removed from the source. Transient
549
+ * Windows handle-release failures are retried briefly before giving up.
550
+ */
551
+ function moveDirectory(src, dest) {
552
+ let lastError;
553
+ for (let attempt = 0; attempt < 4; attempt += 1) try {
554
+ renameSync(src, dest);
555
+ return;
556
+ } catch (err) {
557
+ lastError = err;
558
+ const code = errnoOf(err);
559
+ if (code === "EXDEV") try {
560
+ cpSync(src, dest, {
561
+ recursive: true,
562
+ errorOnExist: true,
563
+ force: false
564
+ });
565
+ const from = treeStats(src);
566
+ const to = treeStats(dest);
567
+ if (from.files !== to.files || from.bytes !== to.bytes) {
568
+ rmSync(dest, {
569
+ recursive: true,
570
+ force: true
571
+ });
572
+ throw new PresetOperationError("write", `cross-volume copy of ${src} did not match its source`);
573
+ }
574
+ rmSync(src, {
575
+ recursive: true,
576
+ force: true
577
+ });
578
+ return;
579
+ } catch (copyErr) {
580
+ try {
581
+ rmSync(dest, {
582
+ recursive: true,
583
+ force: true
584
+ });
585
+ } catch {}
586
+ throw copyErr instanceof PresetOperationError ? copyErr : new PresetOperationError("write", copyErr instanceof Error ? copyErr.message : String(copyErr));
587
+ }
588
+ if (code === void 0 || !RETRYABLE.has(code)) break;
589
+ const until = Date.now() + 60 * (attempt + 1);
590
+ while (Date.now() < until);
591
+ }
592
+ throw new PresetOperationError("write", lastError instanceof Error ? lastError.message : String(lastError));
593
+ }
594
+ /** Absolute library path of one id. */
595
+ function libraryDirOf(dshHome, id) {
596
+ return join(libraryRoot(dshHome), id);
597
+ }
598
+ /** Absolute discovery-root path of one id. */
599
+ function enabledDirOf(dshHome, id) {
600
+ return join(enabledRoot(dshHome), id);
601
+ }
602
+ /**
603
+ * Move a preset from the library into the discovery root.
604
+ * @throws {PresetOperationError} invalid-id, not-installed, already-enabled, conflict, write.
605
+ */
606
+ function enablePreset(dshHome, id) {
607
+ if (!isPresetId(id)) throw new PresetOperationError("invalid-id", `invalid preset id: ${String(id)}`);
608
+ const src = libraryDirOf(dshHome, id);
609
+ const dest = enabledDirOf(dshHome, id);
610
+ if (isDirectory(dest)) throw new PresetOperationError("already-enabled", `preset is already enabled: ${id}`);
611
+ if (!isDirectory(src)) throw new PresetOperationError("not-installed", `preset is not installed: ${id}`);
612
+ mkdirSync(enabledRoot(dshHome), { recursive: true });
613
+ moveDirectory(src, dest);
614
+ return readPresetState(dshHome, id);
615
+ }
616
+ /**
617
+ * Move a preset from the discovery root back into the library.
618
+ * @throws {PresetOperationError} invalid-id, not-enabled, not-managed, conflict, write.
619
+ */
620
+ function disablePreset(dshHome, id) {
621
+ if (!isPresetId(id)) throw new PresetOperationError("invalid-id", `invalid preset id: ${String(id)}`);
622
+ const src = enabledDirOf(dshHome, id);
623
+ const dest = libraryDirOf(dshHome, id);
624
+ if (!isDirectory(src)) throw new PresetOperationError("not-enabled", `preset is not enabled: ${id}`);
625
+ if (!readPresetState(dshHome, id).managed) throw new PresetOperationError("not-managed", `preset was not installed from the Workshop: ${id}`);
626
+ if (existsSync(dest)) throw new PresetOperationError("conflict", `library already holds ${id}`);
627
+ mkdirSync(libraryRoot(dshHome), { recursive: true });
628
+ moveDirectory(src, dest);
629
+ return readPresetState(dshHome, id);
630
+ }
631
+ /**
632
+ * Remove every copy of a workshop-managed preset.
633
+ * @throws {PresetOperationError} invalid-id, not-managed, write.
634
+ */
635
+ function uninstallPreset(dshHome, id) {
636
+ if (!isPresetId(id)) throw new PresetOperationError("invalid-id", `invalid preset id: ${String(id)}`);
637
+ const state = readPresetState(dshHome, id);
638
+ if (!state.installed && !state.enabled) return;
639
+ if (!state.managed) throw new PresetOperationError("not-managed", `preset was not installed from the Workshop: ${id}`);
640
+ for (const dir of [libraryDirOf(dshHome, id), enabledDirOf(dshHome, id)]) {
641
+ if (!isDirectory(dir)) continue;
642
+ try {
643
+ rmSync(dir, {
644
+ recursive: true,
645
+ force: true,
646
+ maxRetries: 3,
647
+ retryDelay: 50
648
+ });
649
+ } catch (err) {
650
+ throw new PresetOperationError("write", err instanceof Error ? err.message : String(err));
651
+ }
652
+ }
653
+ }
654
+ //#endregion
655
+ //#region src/routes.ts
656
+ const PRESET_CENTER_API_PREFIX = "/api/preset-center";
657
+ /** Composition viewer size cap (bytes). */
658
+ const COMPOSITION_MAX_BYTES = 256 * 1024;
659
+ const ERRORS = {
660
+ "invalid-id": {
661
+ status: 400,
662
+ error: "invalid-id",
663
+ message: "invalid preset id"
664
+ },
665
+ "invalid-body": {
666
+ status: 400,
667
+ error: "invalid-body"
668
+ },
669
+ "loopback-only": {
670
+ status: 403,
671
+ error: "loopback-only"
672
+ },
673
+ "method-not-allowed": {
674
+ status: 405,
675
+ error: "method-not-allowed"
676
+ },
677
+ "not-installed": {
678
+ status: 404,
679
+ error: "not-installed"
680
+ },
681
+ "not-enabled": {
682
+ status: 404,
683
+ error: "not-enabled"
684
+ },
685
+ "not-managed": {
686
+ status: 409,
687
+ error: "not-managed"
688
+ },
689
+ "already-enabled": {
690
+ status: 409,
691
+ error: "already-enabled"
692
+ },
693
+ "conflict": {
694
+ status: 409,
695
+ error: "conflict"
696
+ },
697
+ "shadowed": {
698
+ status: 409,
699
+ error: "shadowed"
700
+ },
701
+ "confirmation-required": {
702
+ status: 409,
703
+ error: "confirmation-required"
704
+ },
705
+ "broken": {
706
+ status: 409,
707
+ error: "broken"
708
+ },
709
+ "default-preset": {
710
+ status: 409,
711
+ error: "default-preset"
712
+ },
713
+ "roster-unavailable": {
714
+ status: 503,
715
+ error: "roster-unavailable"
716
+ },
717
+ "write": {
718
+ status: 500,
719
+ error: "write"
720
+ }
721
+ };
722
+ function send(res, status, payload) {
723
+ writeJson(res, status, payload, { "cache-control": "no-store" });
724
+ }
725
+ function sendError(res, err, message) {
726
+ send(res, err.status, {
727
+ ok: false,
728
+ error: err.error,
729
+ ...message === void 0 && err.message === void 0 ? {} : { message: message ?? err.message }
730
+ });
731
+ }
732
+ /** Whether `path` lives inside `root` (a boundary-safe prefix test). */
733
+ function isUnder(path, root) {
734
+ return path === root || path.startsWith(root + sep);
735
+ }
736
+ /** Ids supplied by every root except the discovery root this feature manages. */
737
+ async function occupiedIds(roster, root) {
738
+ if (roster === void 0) return null;
739
+ try {
740
+ return (await roster.list()).filter((row) => !isUnder(row.path, root)).map((row) => row.id).sort();
741
+ } catch {
742
+ return null;
743
+ }
744
+ }
745
+ /** The default preset id, or null when the roster is unavailable. */
746
+ function defaultIdOf(roster) {
747
+ if (roster === void 0) return null;
748
+ try {
749
+ return roster.defaultId;
750
+ } catch {
751
+ return null;
752
+ }
753
+ }
754
+ /** One state row enriched with the composition profile. */
755
+ function rowPayload(home, row) {
756
+ return {
757
+ ...row,
758
+ profile: profilePresetDir(row.dir)
759
+ };
760
+ }
761
+ /** Build the preset-center routes. */
762
+ function makePresetCenterRoutes(deps = {}) {
763
+ const home = deps.dshHome ?? dshHome();
764
+ const root = enabledRoot(home);
765
+ const rosterOf = deps.roster ?? (() => deps.ctx?.get("agentPresets"));
766
+ const guard = (req, res, method) => {
767
+ if (!isLoopbackRequest(req)) {
768
+ sendError(res, ERRORS["loopback-only"]);
769
+ return false;
770
+ }
771
+ if (req.method !== method) {
772
+ sendError(res, ERRORS["method-not-allowed"]);
773
+ return false;
774
+ }
775
+ return true;
776
+ };
777
+ const readId = async (req, res) => {
778
+ let body;
779
+ try {
780
+ body = await readJsonBody(req, { maxBytes: 16 * 1024 }) ?? {};
781
+ } catch {
782
+ sendError(res, ERRORS["invalid-body"]);
783
+ return null;
784
+ }
785
+ if (!isPresetId(body.id)) {
786
+ sendError(res, ERRORS["invalid-id"]);
787
+ return null;
788
+ }
789
+ return {
790
+ id: body.id,
791
+ confirm: body.confirm === true
792
+ };
793
+ };
794
+ const handleState = guardedHandler("preset-center/state", async (req, res) => {
795
+ if (!guard(req, res, "GET")) return;
796
+ const roster = rosterOf();
797
+ const occupied = await occupiedIds(roster, root);
798
+ const presets = listPresetStates(home).map((row) => rowPayload(home, row));
799
+ send(res, 200, {
800
+ ok: true,
801
+ defaultId: defaultIdOf(roster),
802
+ occupied: occupied ?? [],
803
+ rosterAvailable: occupied !== null,
804
+ presets
805
+ });
806
+ });
807
+ const handleComposition = guardedHandler("preset-center/composition", async (req, res) => {
808
+ if (!guard(req, res, "GET")) return;
809
+ const id = new URL(req.url ?? "/", "http://127.0.0.1").searchParams.get("id");
810
+ if (!isPresetId(id)) {
811
+ sendError(res, ERRORS["invalid-id"]);
812
+ return;
813
+ }
814
+ const row = readPresetState(home, id);
815
+ if (!row.installed && !row.enabled) {
816
+ sendError(res, ERRORS["not-installed"]);
817
+ return;
818
+ }
819
+ const file = join(row.dir, COMPOSITION_FILE);
820
+ try {
821
+ if (statSync(file).size > 262144) {
822
+ send(res, 200, {
823
+ ok: true,
824
+ id,
825
+ text: "",
826
+ truncated: true,
827
+ profile: profilePresetDir(row.dir)
828
+ });
829
+ return;
830
+ }
831
+ send(res, 200, {
832
+ ok: true,
833
+ id,
834
+ text: readFileSync(file, "utf8"),
835
+ truncated: false,
836
+ profile: profilePresetDir(row.dir)
837
+ });
838
+ } catch {
839
+ sendError(res, ERRORS["not-installed"], "composition file is missing");
840
+ }
841
+ });
842
+ const handleEnable = guardedHandler("preset-center/enable", async (req, res) => {
843
+ if (!guard(req, res, "POST")) return;
844
+ const parsed = await readId(req, res);
845
+ if (parsed === null) return;
846
+ const { id, confirm } = parsed;
847
+ const roster = rosterOf();
848
+ const occupied = await occupiedIds(roster, root);
849
+ if (occupied === null) {
850
+ sendError(res, ERRORS["roster-unavailable"], "the agent-preset roster is unavailable");
851
+ return;
852
+ }
853
+ if (occupied.includes(id)) {
854
+ sendError(res, ERRORS["shadowed"], `preset id is already supplied by another root: ${id}`);
855
+ return;
856
+ }
857
+ const state = readPresetState(home, id);
858
+ if (!state.installed && !state.enabled) {
859
+ sendError(res, ERRORS["not-installed"]);
860
+ return;
861
+ }
862
+ if (!state.managed) {
863
+ sendError(res, ERRORS["not-managed"]);
864
+ return;
865
+ }
866
+ const profile = profilePresetDir(state.dir);
867
+ if (needsConfirmation(profile) && !confirm) {
868
+ send(res, 409, {
869
+ ok: false,
870
+ error: "confirmation-required",
871
+ message: "preset carries executable content",
872
+ profile
873
+ });
874
+ return;
875
+ }
876
+ try {
877
+ enablePreset(home, id);
878
+ } catch (err) {
879
+ if (err instanceof PresetOperationError) {
880
+ sendError(res, ERRORS[err.code] ?? ERRORS.write, err.message);
881
+ return;
882
+ }
883
+ throw err;
884
+ }
885
+ const broken = await brokenReason(roster, id);
886
+ if (broken !== void 0) {
887
+ try {
888
+ disablePreset(home, id);
889
+ } catch {}
890
+ send(res, 409, {
891
+ ok: false,
892
+ error: "broken",
893
+ message: broken
894
+ });
895
+ return;
896
+ }
897
+ send(res, 200, {
898
+ ok: true,
899
+ state: rowPayload(home, readPresetState(home, id))
900
+ });
901
+ });
902
+ const handleDisable = guardedHandler("preset-center/disable", async (req, res) => {
903
+ if (!guard(req, res, "POST")) return;
904
+ const parsed = await readId(req, res);
905
+ if (parsed === null) return;
906
+ const { id } = parsed;
907
+ const refusal = refusalForProtected(rosterOf(), id);
908
+ if (refusal !== null) {
909
+ sendError(res, ERRORS["default-preset"], refusal);
910
+ return;
911
+ }
912
+ try {
913
+ disablePreset(home, id);
914
+ } catch (err) {
915
+ if (err instanceof PresetOperationError) {
916
+ sendError(res, ERRORS[err.code] ?? ERRORS.write, err.message);
917
+ return;
918
+ }
919
+ throw err;
920
+ }
921
+ send(res, 200, {
922
+ ok: true,
923
+ state: rowPayload(home, readPresetState(home, id))
924
+ });
925
+ });
926
+ const handleUninstall = guardedHandler("preset-center/uninstall", async (req, res) => {
927
+ if (!guard(req, res, "POST")) return;
928
+ const parsed = await readId(req, res);
929
+ if (parsed === null) return;
930
+ const { id } = parsed;
931
+ const refusal = refusalForProtected(rosterOf(), id);
932
+ if (refusal !== null) {
933
+ sendError(res, ERRORS["default-preset"], refusal);
934
+ return;
935
+ }
936
+ try {
937
+ uninstallPreset(home, id);
938
+ } catch (err) {
939
+ if (err instanceof PresetOperationError) {
940
+ sendError(res, ERRORS[err.code] ?? ERRORS.write, err.message);
941
+ return;
942
+ }
943
+ throw err;
944
+ }
945
+ send(res, 200, {
946
+ ok: true,
947
+ id
948
+ });
949
+ });
950
+ const route = (path, handler) => ({
951
+ kind: "exact",
952
+ path,
953
+ handler: (req, res) => {
954
+ handler(req, res);
955
+ }
956
+ });
957
+ return [
958
+ route(`${PRESET_CENTER_API_PREFIX}/state`, handleState),
959
+ route(`${PRESET_CENTER_API_PREFIX}/composition`, handleComposition),
960
+ route(`${PRESET_CENTER_API_PREFIX}/enable`, handleEnable),
961
+ route(`${PRESET_CENTER_API_PREFIX}/disable`, handleDisable),
962
+ route(`${PRESET_CENTER_API_PREFIX}/uninstall`, handleUninstall)
963
+ ];
964
+ }
965
+ /** Why a disable/uninstall of `id` is refused, or null when it is allowed. */
966
+ function refusalForProtected(roster, id) {
967
+ const current = defaultIdOf(roster);
968
+ if (current !== null && current === id) return `preset is the current default; change the default in Settings - Agent presets first: ${id}`;
969
+ return null;
970
+ }
971
+ /** The roster's broken reason for `id`, or undefined when healthy or unknown. */
972
+ async function brokenReason(roster, id) {
973
+ if (roster === void 0) return void 0;
974
+ try {
975
+ return (await roster.list()).find((entry) => entry.id === id)?.broken;
976
+ } catch {
977
+ return;
978
+ }
979
+ }
980
+ //#endregion
981
+ //#region src/index.ts
982
+ /** Stable cordis plugin name (matches the cordis.patch.yml insert id). */
983
+ const name = "ui-preset-center";
984
+ /** The gateway requires the host webserver; the roster is read opportunistically. */
985
+ const inject = ["webServer"];
986
+ /** Mount the preset-center gateway (once per process). */
987
+ const apply = mountOnce("@linxin666/dsh-client-ui-preset-center", applyImpl);
988
+ function applyImpl(ctx) {
989
+ const routes = makePresetCenterRoutes({ ctx });
990
+ for (const route of routes) try {
991
+ ctx.effect(() => {
992
+ const dispose = ctx.webServer.register(route);
993
+ return () => {
994
+ dispose();
995
+ };
996
+ }, `dsh-preset-center: route ${route.path}`);
997
+ } catch {}
998
+ }
999
+ //#endregion
1000
+ export { COMPOSITION_FILE, COMPOSITION_MAX_BYTES, ENABLED_DIR, LIBRARY_DIR, PRESET_CENTER_API_PREFIX, PRESET_ID_RE, PROVENANCE_FILENAME, PresetOperationError, apply, disablePreset, enablePreset, enabledRoot, inject, isPresetId, libraryRoot, listFiles, listPresetStates, makePresetCenterRoutes, moveDirectory, name, needsConfirmation, profileComposition, profilePresetDir, readPresetState, readProvenance, scanPresetIds, uninstallPreset, verifyProvenance };