@linxin666/dsh-client-ui-plugin-manager 0.4.6 → 0.4.8

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 CHANGED
@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, normalize, posix, sep, win32 } fro
5
5
  import { isMap, isScalar, isSeq, parseDocument } from "yaml";
6
6
  import { homedir } from "node:os";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
+ import semver from "semver";
8
9
  import { AsyncResource } from "node:async_hooks";
9
10
  //#region src/mount-once.ts
10
11
  /**
@@ -319,6 +320,44 @@ function claimedIdsOf(patchText) {
319
320
  return ids;
320
321
  }
321
322
  /**
323
+ * Every entry id a layer declares: its top-level `- id:` rows (bare override
324
+ * rows and config rows alike) plus the entries of its `- insert:` lists. Ids
325
+ * nested inside a row's own `config:` are composition children of that entry,
326
+ * not layer entries, and are not declared here.
327
+ *
328
+ * This answers "does this layer still declare that row?" without composing, so
329
+ * it stays true in the states where a composition probe is not: a host that
330
+ * composes mid-upgrade, or while a bundle's package is being replaced, drops
331
+ * rows whose layers still exist.
332
+ * @param patchText - a patch layer's text.
333
+ * @param filename - absolute path (diagnostics only).
334
+ * @returns the declared ids, in file order, without duplicates.
335
+ * @throws when the layer does not parse; a caller must then treat this layer's
336
+ * declarations as unknown rather than empty.
337
+ */
338
+ function declaredRowIds(patchText, filename) {
339
+ const { root } = parsePatch(patchText, filename);
340
+ const ids = [];
341
+ const push = (value) => {
342
+ if (value === void 0 || ids.includes(value)) return;
343
+ ids.push(value);
344
+ };
345
+ const idOf = (node) => {
346
+ const id = node.get("id", true);
347
+ return isScalar(id) && typeof id.value === "string" ? id.value : void 0;
348
+ };
349
+ for (const item of root.items) {
350
+ if (!isMap(item)) continue;
351
+ const insert = item.get("insert", true);
352
+ if (isSeq(insert)) {
353
+ for (const entry of insert.items) if (isMap(entry)) push(idOf(entry));
354
+ continue;
355
+ }
356
+ push(idOf(item));
357
+ }
358
+ return ids;
359
+ }
360
+ /**
322
361
  * The insert entries of an installed package's own bundle patch, with both
323
362
  * the claimed id and the entry's own name. The name matters twice: the
324
363
  * loader imports the plugin by it (an unresolvable name is a boot failure),
@@ -431,6 +470,130 @@ function setRowEnabled(text, filename, id, name, enabled, baseEnabled = true) {
431
470
  }));
432
471
  return document.toString({ lineWidth: 0 }) + "\n";
433
472
  }
473
+ /** The complete key set of an enablement override row this package writes. */
474
+ const OVERRIDE_ROW_KEYS = /* @__PURE__ */ new Set([
475
+ "id",
476
+ "name",
477
+ "disabled"
478
+ ]);
479
+ /**
480
+ * The entry id of an enablement override row this package owns, when the item
481
+ * is one: a bare row carrying a string `id`, a boolean `disabled`, and no
482
+ * other key. Anything else is somebody else's row — a config row carrying
483
+ * options, a row with an unknown shape, an insert wrapper — and the manager
484
+ * never edits or removes it.
485
+ * @param item - one top-level patch item.
486
+ * @returns the override's entry id, or undefined when the item is not ours.
487
+ */
488
+ function overrideRowId(item) {
489
+ if (!isBareRow(item)) return void 0;
490
+ const id = bareRowId(item);
491
+ if (id === void 0) return void 0;
492
+ const disabled = item.get("disabled", true);
493
+ if (!(isScalar(disabled) && typeof disabled.value === "boolean")) return void 0;
494
+ for (const pair of item.items) {
495
+ const key = pair.key;
496
+ if (!isScalar(key) || !OVERRIDE_ROW_KEYS.has(String(key.value))) return void 0;
497
+ }
498
+ return id;
499
+ }
500
+ /**
501
+ * Drop this package's own enablement overrides whose entry id the composed
502
+ * profile no longer carries — a retired row leaves a stale override behind,
503
+ * which the loader reports on every boot as `patch: entry "<id>" not found`.
504
+ * The prunable set is decided by the caller from the composed entry ids: an
505
+ * id the composition does not carry has no row left to override. Only rows
506
+ * {@link overrideRowId} recognizes are removed, comments and every other row
507
+ * are kept, and an already-pruned file returns its input text unchanged so the
508
+ * caller can skip the write entirely.
509
+ * @param text - current patch file text.
510
+ * @param filename - absolute path (diagnostics only).
511
+ * @param composedIds - the entry ids the composed profile carries.
512
+ * @returns the rewritten text and the pruned ids.
513
+ */
514
+ function pruneOrphanRowOverrides(text, filename, composedIds) {
515
+ const { document, root } = parsePatch(text, filename);
516
+ const pruned = [];
517
+ for (let index = root.items.length - 1; index >= 0; index -= 1) {
518
+ const item = root.items[index];
519
+ const id = overrideRowId(item);
520
+ if (id === void 0 || composedIds.has(id)) continue;
521
+ pruned.unshift(id);
522
+ const comment = isMap(item) ? item.commentBefore : void 0;
523
+ root.items.splice(index, 1);
524
+ if (comment === void 0 || comment === null || comment === "") continue;
525
+ const next = root.items[index];
526
+ if (isMap(next) || isSeq(next)) next.commentBefore = appendComment(comment, next.commentBefore);
527
+ else document.comment = appendComment(comment, document.comment);
528
+ }
529
+ if (pruned.length === 0) return {
530
+ text,
531
+ pruned
532
+ };
533
+ const serialized = document.toString({ lineWidth: 0 });
534
+ return {
535
+ text: `${serialized.endsWith("\n") ? serialized.slice(0, -1) : serialized}${text.endsWith("\n") ? "\n" : ""}`,
536
+ pruned
537
+ };
538
+ }
539
+ /**
540
+ * One node's comment block followed by another's.
541
+ * @param first - the comment block to keep first.
542
+ * @param second - the existing block, when there is one.
543
+ * @returns the combined block.
544
+ */
545
+ function appendComment(first, second) {
546
+ return second === void 0 || second === null || second === "" ? first : `${first}\n${second}`;
547
+ }
548
+ /**
549
+ * Point the profile's own rows at the packages that now carry those entry ids.
550
+ *
551
+ * The include patch semantics skip a row whose `name` does not match the name
552
+ * of the row a bundle inserted under that id, and the skip takes the whole row
553
+ * with it: a config row stops configuring anything and a `disabled` override
554
+ * stops disabling anything, both without a word in the browser. A package that
555
+ * changes its name — the aggregate's family rows moved from the
556
+ * `@linxin666/dsh-web-all/<family>` subpath to the real package in issue
557
+ * #1901 — therefore leaves every profile row that named it dead.
558
+ *
559
+ * The live names come from the installed bundles' own patch files, which is
560
+ * where the loader takes the row it inserts, so a repaired row names exactly
561
+ * the package the loader mounts under that id. A row whose id no bundle claims
562
+ * is left alone: its package may still be carried by a layer this manager
563
+ * cannot see, and a name it cannot prove is a name it must not write.
564
+ *
565
+ * @param text - current patch file text.
566
+ * @param filename - absolute path (diagnostics only).
567
+ * @param liveNames - the live entry names, by entry id.
568
+ * @returns the rewritten text and the repaired rows.
569
+ */
570
+ function repairStaleRowNames(text, filename, liveNames) {
571
+ const { document, root } = parsePatch(text, filename);
572
+ const repaired = [];
573
+ for (const item of root.items) {
574
+ if (!isBareRow(item)) continue;
575
+ const id = bareRowId(item);
576
+ const from = bareRowName(item);
577
+ if (id === void 0 || from === void 0) continue;
578
+ const to = liveNames.get(id);
579
+ if (to === void 0 || to === from) continue;
580
+ item.set("name", document.createNode(to));
581
+ repaired.push({
582
+ id,
583
+ from,
584
+ to
585
+ });
586
+ }
587
+ if (repaired.length === 0) return {
588
+ text,
589
+ repaired
590
+ };
591
+ const serialized = document.toString({ lineWidth: 0 });
592
+ return {
593
+ text: `${serialized.endsWith("\n") ? serialized.slice(0, -1) : serialized}${text.endsWith("\n") ? "\n" : ""}`,
594
+ repaired
595
+ };
596
+ }
434
597
  //#endregion
435
598
  //#region src/host/bundle-guard.ts
436
599
  /**
@@ -841,19 +1004,22 @@ function profileExists(profileDir) {
841
1004
  */
842
1005
  /**
843
1006
  * Entry rows that must never carry a disabled override: the manager tab
844
- * itself (the UI performing the write), the family settings surface the tab
845
- * injects into, and the aggregate compat face (disabling it unmounts the
846
- * whole folded client bundle while host rows keep running — a half-dead
847
- * page). Covers both the standalone and the aggregate row ids. The standalone
848
- * id is this package's own `cordis.patch.yml` insert id, never the official
849
- * `ui-plugin-manager` row the DSH web-app bundle already claims.
1007
+ * itself (the UI performing the write) and the family settings surface the
1008
+ * tab injects into. Covers both the standalone and the aggregate row ids. The
1009
+ * standalone id is this package's own `cordis.patch.yml` insert id, never the
1010
+ * official `ui-plugin-manager` row the DSH web-app bundle already claims.
1011
+ *
1012
+ * `web-ui-compat` is deliberately NOT locked (issue #1901). It used to be:
1013
+ * the compat row carried the inlined browser half of every family, so
1014
+ * disabling it blanked the whole page while the host rows kept running. Family
1015
+ * rows mount their own packages now, and the compat row is the optional
1016
+ * compatibility patch layer the issue asks users to be able to turn off.
850
1017
  */
851
1018
  const LOCKED_ENTRY_IDS = /* @__PURE__ */ new Set([
852
1019
  "ui-plugin-manager-update-check",
853
1020
  "web-ui-plugin-manager",
854
1021
  "ui-web-ui-settings",
855
- "web-ui-settings",
856
- "web-ui-compat"
1022
+ "web-ui-settings"
857
1023
  ]);
858
1024
  /** The node_modules path of one (possibly scoped) package name. */
859
1025
  function modulePathOf(profileDir, name) {
@@ -1290,6 +1456,47 @@ function dshSpawnCommand(binary, platform = process.platform, localNodeExists =
1290
1456
  argsPrefix: [binJs]
1291
1457
  };
1292
1458
  }
1459
+ /** The Windows directory used when the environment names no system root at all. */
1460
+ const WINDOWS_ROOT_FALLBACK = "C:\\Windows";
1461
+ /**
1462
+ * Read one environment variable by name, case-insensitively, ignoring blank
1463
+ * values. Windows spells the same variable `ComSpec` and `comspec` depending on
1464
+ * who wrote it (a launcher, a service, the user's own shell), and a plain
1465
+ * object seam carries whatever spelling the caller built.
1466
+ * @param env - the environment to read.
1467
+ * @param name - the variable name, matched without regard to case.
1468
+ * @returns the first non-blank value, or undefined.
1469
+ */
1470
+ function envValue(env, name) {
1471
+ const wanted = name.toUpperCase();
1472
+ for (const [key, value] of Object.entries(env)) {
1473
+ if (typeof value !== "string" || value.trim() === "") continue;
1474
+ if (key.toUpperCase() === wanted) return value;
1475
+ }
1476
+ }
1477
+ /**
1478
+ * Absolute path of the Windows command processor, resolved from an environment
1479
+ * rather than from PATH.
1480
+ *
1481
+ * Every `.cmd` shim still has to be executed through cmd.exe, and a bare
1482
+ * `cmd.exe` spawn resolves through the host PATH: a GUI-launched host whose PATH
1483
+ * carries no `%SystemRoot%\system32` (a packaged Desktop launch, a service, a
1484
+ * stripped environment) gets ENOENT for a name that is present on disk, and the
1485
+ * whole feature fails with it (issue #1857). ComSpec is the variable Windows
1486
+ * itself uses for this and names the real binary, so it is preferred; otherwise
1487
+ * the system root is read from `SystemRoot` or `windir`, with the conventional
1488
+ * `C:\Windows` as the last resort.
1489
+ *
1490
+ * Only the Windows branch needs it — a POSIX host spawns the CLI directly.
1491
+ * @param env - the environment to resolve from.
1492
+ * @returns the absolute cmd.exe path.
1493
+ */
1494
+ function windowsCmdPath(env = process.env) {
1495
+ const comSpec = envValue(env, "ComSpec");
1496
+ if (comSpec !== void 0) return comSpec;
1497
+ const root = envValue(env, "SystemRoot") ?? envValue(env, "windir") ?? WINDOWS_ROOT_FALLBACK;
1498
+ return win32.join(root, "System32", "cmd.exe");
1499
+ }
1293
1500
  /** Build the exact cmd.exe command line required to execute a trusted .cmd shim. */
1294
1501
  function windowsCmdShimArgs(binary, args) {
1295
1502
  const unsafe = /[&|<>"'`%!\n\r\0]/;
@@ -1320,6 +1527,105 @@ function withPrependedPath(env, dir, platform = process.platform) {
1320
1527
  next.PATH = current === "" ? dir : `${dir}${separator}${current}`;
1321
1528
  return next;
1322
1529
  }
1530
+ /** The spawn failure recorded on a guarded child, read by {@link awaitChildExit}. */
1531
+ const SPAWN_FAILURE = /* @__PURE__ */ new WeakMap();
1532
+ /**
1533
+ * Whether an emitted error is a spawn failure rather than a later lifecycle
1534
+ * failure (a kill that did not land, a closed stdio pipe). Only a spawn failure
1535
+ * means the child will never close on its own.
1536
+ * @param error - the emitted error.
1537
+ * @returns true when no process was ever created.
1538
+ */
1539
+ function isSpawnFailure(error) {
1540
+ if (typeof error !== "object" || error === null) return false;
1541
+ const syscall = error.syscall;
1542
+ return typeof syscall === "string" && syscall.startsWith("spawn");
1543
+ }
1544
+ /**
1545
+ * The operator-facing text of one spawn failure.
1546
+ * @param error - the emitted error.
1547
+ * @returns a readable one-line reason.
1548
+ */
1549
+ function spawnFailureText(error) {
1550
+ return "plugin-manager: 无法启动子进程(" + (error instanceof Error ? error.message : String(error)) + ")";
1551
+ }
1552
+ /**
1553
+ * Attach the error fallback every spawn outlet needs.
1554
+ *
1555
+ * A ChildProcess without an `error` listener turns a spawn failure into an
1556
+ * unhandled `error` event, which is an uncaught exception: the failure of one
1557
+ * CLI call took the whole dsh host process down with it. This records the
1558
+ * reason and, when the child never closed, settles it as a failed exit so a
1559
+ * caller that only waits for `close` neither hangs nor crashes (issue #1857).
1560
+ * @param child - the spawned child.
1561
+ * @returns the same child, guarded.
1562
+ */
1563
+ function guardSpawnFailure(child) {
1564
+ let closed = false;
1565
+ child.on("close", () => {
1566
+ closed = true;
1567
+ });
1568
+ child.on("error", (error) => {
1569
+ if (!isSpawnFailure(error)) return;
1570
+ SPAWN_FAILURE.set(child, spawnFailureText(error));
1571
+ if (closed) return;
1572
+ closed = true;
1573
+ child.emit("close", -1, null);
1574
+ });
1575
+ return child;
1576
+ }
1577
+ /**
1578
+ * Wait for a spawned child to close, settling on a spawn failure as well.
1579
+ *
1580
+ * The listener pair is attached to every child this package waits on, so the
1581
+ * wait is safe for a child that arrived through a seam ({@link guardSpawnFailure}
1582
+ * guards the real spawn outlets, an injected one may skip it).
1583
+ * @param child - the spawned child.
1584
+ * @returns the exit verdict.
1585
+ */
1586
+ async function awaitChildExit(child) {
1587
+ return new Promise((resolve) => {
1588
+ let settled = false;
1589
+ const finish = (code) => {
1590
+ if (settled) return;
1591
+ settled = true;
1592
+ const spawnError = SPAWN_FAILURE.get(child);
1593
+ resolve(spawnError === void 0 ? { code } : {
1594
+ code,
1595
+ spawnError
1596
+ });
1597
+ };
1598
+ child.on("close", (code) => {
1599
+ finish(code);
1600
+ });
1601
+ child.on("error", () => {
1602
+ finish(-1);
1603
+ });
1604
+ });
1605
+ }
1606
+ /**
1607
+ * Wait for one spawned CLI child, folding a spawn failure into its output.
1608
+ *
1609
+ * Every caller already reports a non-zero exit through the captured output, so
1610
+ * a process that never started is reported the same readable way instead of as
1611
+ * a silent failure or a hang.
1612
+ * @param child - the spawned child.
1613
+ * @param output - the bounded capture the failure text is appended to.
1614
+ * @param timeoutMs - kill the child after this long; omitted for no deadline.
1615
+ * @returns the exit code, or null when a signal ended the child.
1616
+ */
1617
+ async function awaitCliExit(child, output, timeoutMs) {
1618
+ const timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
1619
+ child.kill();
1620
+ }, timeoutMs);
1621
+ try {
1622
+ const exit = await awaitChildExit(child);
1623
+ if (exit.spawnError !== void 0) capture(Buffer.from(exit.spawnError + "\n"), output);
1624
+ return exit.code;
1625
+ } finally {
1626
+ if (timer !== void 0) clearTimeout(timer);
1627
+ }
1628
+ }
1323
1629
  /**
1324
1630
  * Spawn the dsh CLI with piped stdio and no shell parsing (see
1325
1631
  * {@link dshSpawnCommand}).
@@ -1330,6 +1636,9 @@ function withPrependedPath(env, dir, platform = process.platform) {
1330
1636
  * `dsh plugin` to pnpm, so without this the update would start and then fail on
1331
1637
  * a missing pnpm instead. This mirrors the packaged Desktop launcher, which
1332
1638
  * prepends its bundled runtime bin to the host it spawns.
1639
+ *
1640
+ * Every child leaves here guarded ({@link guardSpawnFailure}), so a spawn that
1641
+ * fails settles as a non-zero exit instead of raising an unhandled error.
1333
1642
  * @param binary - the resolved dsh CLI path.
1334
1643
  * @param args - arguments after the interpreter/script prefix.
1335
1644
  * @param env - the host environment.
@@ -1338,7 +1647,7 @@ function withPrependedPath(env, dir, platform = process.platform) {
1338
1647
  function spawnDsh(binary, args, env) {
1339
1648
  const { command, argsPrefix } = dshSpawnCommand(binary);
1340
1649
  const childEnv = withPrependedPath(env, (process.platform === "win32" ? win32 : posix).dirname(binary));
1341
- if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return spawn("cmd.exe", windowsCmdShimArgs(command, args), {
1650
+ if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return guardSpawnFailure(spawn(windowsCmdPath(env), windowsCmdShimArgs(command, args), {
1342
1651
  env: childEnv,
1343
1652
  windowsVerbatimArguments: true,
1344
1653
  stdio: [
@@ -1346,8 +1655,8 @@ function spawnDsh(binary, args, env) {
1346
1655
  "pipe",
1347
1656
  "pipe"
1348
1657
  ]
1349
- });
1350
- return spawn(command, [...argsPrefix, ...args], {
1658
+ }));
1659
+ return guardSpawnFailure(spawn(command, [...argsPrefix, ...args], {
1351
1660
  env: command === process.execPath ? {
1352
1661
  ...childEnv,
1353
1662
  ELECTRON_RUN_AS_NODE: "1"
@@ -1357,7 +1666,7 @@ function spawnDsh(binary, args, env) {
1357
1666
  "pipe",
1358
1667
  "pipe"
1359
1668
  ]
1360
- });
1669
+ }));
1361
1670
  }
1362
1671
  /**
1363
1672
  * Entry-id line of the official installer channels in the boot dump. A plain
@@ -1366,6 +1675,28 @@ function spawnDsh(binary, args, env) {
1366
1675
  */
1367
1676
  const OFFICIAL_INSTALLER_PATTERN = /^\s*-?\s*id:\s*['"]?plugin-(?:installer|control)['"]?\s*$/m;
1368
1677
  /**
1678
+ * The entry ids of a composed profile dump (`dsh --profile <name>
1679
+ * --dump-config`). The dump prints one YAML block per patch layer under a
1680
+ * `# ==` header, with the composed entries as column-0 `- id:` items — an
1681
+ * entry a profile patch overrides appears once, carrying the override's keys,
1682
+ * so those lines are exactly the loader's own entry set. Nested config keeps
1683
+ * its own `id` keys indented and is never mistaken for an entry.
1684
+ * @param dump - the dump's captured text.
1685
+ * @returns the composed entry ids, or undefined when the dump carried none.
1686
+ */
1687
+ function composedEntryIdsOf(dump) {
1688
+ const ids = /* @__PURE__ */ new Set();
1689
+ for (const rawLine of dump.split("\n")) {
1690
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1691
+ const match = /^-[ \t]+id:[ \t]*(.+?)[ \t]*$/.exec(line);
1692
+ if (match === null) continue;
1693
+ const value = match[1];
1694
+ const unquoted = /^'(.*)'$/.exec(value)?.[1] ?? /^"(.*)"$/.exec(value)?.[1] ?? value;
1695
+ if (unquoted !== "") ids.add(unquoted);
1696
+ }
1697
+ return ids.size === 0 ? void 0 : ids;
1698
+ }
1699
+ /**
1369
1700
  * Detect whether the official installer channels exist on this runtime by
1370
1701
  * dumping the boot composition once: the npm-published web never contains
1371
1702
  * `plugin-installer` entries, DSHCode and the checkout web do. The browser
@@ -1390,9 +1721,7 @@ async function detectOfficialChannels(binary, profileName, env = process.env, sp
1390
1721
  child.stderr?.on("data", (chunk) => {
1391
1722
  capture(chunk, output);
1392
1723
  });
1393
- if (await new Promise((resolve) => {
1394
- child.on("close", resolve);
1395
- }) !== 0) return false;
1724
+ if (await awaitCliExit(child, output) !== 0) return false;
1396
1725
  return OFFICIAL_INSTALLER_PATTERN.test(output.read());
1397
1726
  }
1398
1727
  /**
@@ -1416,6 +1745,22 @@ function nativeManagerFailure(outcome) {
1416
1745
  const code = failure?.code;
1417
1746
  return typeof code === "string" && code !== "" ? `官方插件管理器拒绝执行(${code})` : "官方插件管理器报告失败";
1418
1747
  }
1748
+ /**
1749
+ * The official manager's own refusal code for one run, or undefined when its
1750
+ * verdict is not a failure. {@link nativeManagerFailure} renders the code for the
1751
+ * person; this is the same verdict read for a decision, which is how the update
1752
+ * path recognises the `already-installed` refusal it has to answer with a
1753
+ * two-phase replacement.
1754
+ * @param outcome - the resolved value of `installBundle` / `removeBundle`.
1755
+ * @returns the manager's failure code, or undefined for a run that did not fail.
1756
+ */
1757
+ function nativeManagerRefusalCode(outcome) {
1758
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1759
+ const verdict = outcome;
1760
+ if (verdict.application !== "failed") return void 0;
1761
+ const code = verdict.error?.code;
1762
+ return typeof code === "string" && code !== "" ? code : void 0;
1763
+ }
1419
1764
  /** The gateway: serializes CLI operations through one job table and one mutation queue. */
1420
1765
  var CliGateway = class {
1421
1766
  facts;
@@ -1498,15 +1843,8 @@ var CliGateway = class {
1498
1843
  child.stderr?.on("data", (chunk) => {
1499
1844
  capture(chunk, output);
1500
1845
  });
1501
- const timer = setTimeout(() => {
1502
- child.kill();
1503
- }, timeoutMs);
1504
- const code = await new Promise((resolve) => {
1505
- child.on("close", resolve);
1506
- });
1507
- clearTimeout(timer);
1508
1846
  return {
1509
- code,
1847
+ code: await awaitCliExit(child, output, timeoutMs),
1510
1848
  output: output.read().trim()
1511
1849
  };
1512
1850
  }
@@ -1607,6 +1945,7 @@ var CliGateway = class {
1607
1945
  job.error = `plugin-manager: 迁移后的启动预检失败${verify.output === "" ? "" : `:\n${verify.output}`}`;
1608
1946
  return;
1609
1947
  }
1948
+ if (await this.pruneOrphanOverrides(job, verify.output) === void 0) return;
1610
1949
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
1611
1950
  const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? targetSpec, after.layer.rows);
1612
1951
  if (!/^(?:link:|file:)/.test(targetSpec) && updated.version !== targetVersion) {
@@ -1817,6 +2156,13 @@ var CliGateway = class {
1817
2156
  * run (pnpm exited non-zero, an incompatible version, a cancellation) resolves
1818
2157
  * with `application: 'failed'`, and only that verdict carries the reason — the
1819
2158
  * profile re-read can only show that the version did not move.
2159
+ *
2160
+ * An `already-installed` refusal is answered by {@link replaceInstalled}: the
2161
+ * manager refuses to install a dependency the profile already carries while the
2162
+ * host mounts `hmr` (0.2.1-rc.2, and dsh-base mounts that service on every
2163
+ * profile host), so an in-place update there is only expressible as its two
2164
+ * phases. The single call stays first so the day the manager accepts an
2165
+ * in-place update this path needs no change.
1820
2166
  * @param job - the update job being settled.
1821
2167
  * @param native - the official manager.
1822
2168
  */
@@ -1829,10 +2175,13 @@ var CliGateway = class {
1829
2175
  return;
1830
2176
  }
1831
2177
  const before = await this.capture();
1832
- const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
2178
+ const carried = await readProfileManifest(this.facts.packageJsonPath);
2179
+ const first = await native.installBundle(job.spec, {
1833
2180
  enabled: true,
1834
2181
  requestId: job.id
1835
- }));
2182
+ });
2183
+ let refusal = nativeManagerFailure(first);
2184
+ if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") refusal = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
1836
2185
  if (refusal !== void 0) {
1837
2186
  job.phase = "error";
1838
2187
  job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
@@ -1851,6 +2200,7 @@ var CliGateway = class {
1851
2200
  job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
1852
2201
  return;
1853
2202
  }
2203
+ if (await this.pruneOrphanOverrides(job) === void 0) return;
1854
2204
  job.plugin = updated;
1855
2205
  job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
1856
2206
  id: change.id,
@@ -1860,6 +2210,158 @@ var CliGateway = class {
1860
2210
  }));
1861
2211
  job.phase = "done";
1862
2212
  }
2213
+ /**
2214
+ * Replace an installed bundle with the update job's target spec through the
2215
+ * official manager, the only writer an application-owned profile accepts.
2216
+ * Removing first is what makes the install possible: the manager's
2217
+ * `already-installed` guard reads the profile, so the same name is a fresh
2218
+ * dependency once the old one is gone.
2219
+ *
2220
+ * A failed second phase reinstalls the spec the profile carried before the run,
2221
+ * so an update that cannot land leaves a working plugin behind instead of an
2222
+ * empty slot; the report says which of the two happened.
2223
+ *
2224
+ * Two facts make the replacement safe to repeat in one session:
2225
+ *
2226
+ * - **The bundle keeps its layer index.** A removal drops the name from
2227
+ * `dsh.profile.bundles` and the reinstall appends it, so a plain
2228
+ * remove-then-install moves the bundle behind every bundle that followed it
2229
+ * and its patch layer starts overriding rows it never overrode
2230
+ * ({@link restoreBundleIndex} puts it back).
2231
+ * - **A `bundle-in-use` refusal is answered once, not repeated.** The
2232
+ * official guard deselects the bundle and reloads before it checks whether
2233
+ * the bundle's rows still run, so a refusal means the session still holds
2234
+ * them: the update is retried exactly once against that settled state, and a
2235
+ * second refusal restores the selection and names the restart the person has
2236
+ * to do ({@link removeForReplacement}).
2237
+ *
2238
+ * @param job - the update job whose spec is installed.
2239
+ * @param native - the official manager.
2240
+ * @param targetId - the installed bundle being replaced.
2241
+ * @param previousSpec - the dependency spec the profile carried before the run.
2242
+ * @returns the failure to report, or undefined once the target spec landed.
2243
+ */
2244
+ async replaceInstalled(job, native, targetId, previousSpec) {
2245
+ if (previousSpec === void 0) return `${targetId} 不在 profile 依赖中,无法替换已安装版本`;
2246
+ const index = await this.bundleIndexOf(targetId);
2247
+ const removal = await this.removeForReplacement(native, targetId);
2248
+ if (removal.failure !== void 0) {
2249
+ if (removal.deselected) await this.restoreBundleSelection(native, targetId);
2250
+ return `已安装版本无法移除(${removal.failure}),本次更新未做改动${removal.remedy}`;
2251
+ }
2252
+ const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
2253
+ enabled: true,
2254
+ requestId: job.id
2255
+ }));
2256
+ if (refusal === void 0) {
2257
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2258
+ return;
2259
+ }
2260
+ const restoreSpec = `${targetId}@${previousSpec}`;
2261
+ const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
2262
+ enabled: true,
2263
+ requestId: job.id
2264
+ }));
2265
+ if (restoreFailure !== void 0) return `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`;
2266
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2267
+ return `${refusal};已装回 ${restoreSpec}`;
2268
+ }
2269
+ /**
2270
+ * Where a bundle sits in the layer order, read before the removal drops it.
2271
+ * @param name - the installed bundle name.
2272
+ * @returns the index in `dsh.profile.bundles`, or undefined when the profile
2273
+ * does not list it (nothing to restore in that case).
2274
+ */
2275
+ async bundleIndexOf(name) {
2276
+ try {
2277
+ const index = (await readProfileManifest(this.facts.packageJsonPath)).bundles.indexOf(name);
2278
+ return index < 0 ? void 0 : index;
2279
+ } catch {
2280
+ return;
2281
+ }
2282
+ }
2283
+ /**
2284
+ * Put a replaced bundle back at the layer index it had before the removal.
2285
+ *
2286
+ * The loader applies one patch layer per entry of `dsh.profile.bundles`, in
2287
+ * that order, so the index is behavior: a bundle that is removed and
2288
+ * reinstalled without this lands behind every bundle that followed it, and
2289
+ * whole rows start inheriting from a layer that used to come first. The write
2290
+ * is the manifest's own backup + tmp + rename path, and nothing is written
2291
+ * when the profile already lists the bundle where it belongs.
2292
+ * @param name - the reinstalled bundle.
2293
+ * @param spec - the dependency spec the reinstall recorded (unused when the bundle is absent).
2294
+ * @param index - the position captured before the removal.
2295
+ */
2296
+ async restoreBundleIndex(name, spec, index) {
2297
+ if (index === void 0) return;
2298
+ try {
2299
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2300
+ if (!Object.hasOwn(manifest.dependencies, name)) return;
2301
+ if (manifest.bundles.indexOf(name) === index) return;
2302
+ await reorderProfileBundle(this.facts.packageJsonPath, name, index);
2303
+ } catch (error) {
2304
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 顺序(${spec}):${error instanceof Error ? error.message : String(error)}`);
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Remove a bundle for the two-phase replacement, answering the official
2309
+ * manager's in-use refusal instead of repeating it.
2310
+ *
2311
+ * Read the official `removeBundle` guard in order: it deselects the bundle,
2312
+ * reloads the profile, and only then checks whether the bundle's own rows
2313
+ * still hold a running fiber, which it reports as `bundle-in-use`. The
2314
+ * deselection is therefore already on disk when the refusal arrives — the
2315
+ * guard re-reads the selection on entry, so asking once more after that
2316
+ * settled state is idempotent and is the only way an update can continue
2317
+ * without a restart. A second refusal means the rows really are still
2318
+ * loaded, and the report then names the restart instead of a bare code.
2319
+ * @param native - the official manager.
2320
+ * @param name - the bundle to remove.
2321
+ * @returns the refusal to report, whether the profile lost the selection on the
2322
+ * way, and the remedy text for that refusal.
2323
+ */
2324
+ async removeForReplacement(native, name) {
2325
+ const first = await native.removeBundle(name);
2326
+ const failure = nativeManagerFailure(first);
2327
+ if (failure === void 0) return {
2328
+ deselected: false,
2329
+ remedy: ""
2330
+ };
2331
+ if (nativeManagerRefusalCode(first) !== "bundle-in-use") return {
2332
+ failure,
2333
+ deselected: await this.bundleSelectionLost(name),
2334
+ remedy: ""
2335
+ };
2336
+ const retryFailure = nativeManagerFailure(await native.removeBundle(name));
2337
+ if (retryFailure === void 0) return {
2338
+ deselected: false,
2339
+ remedy: ""
2340
+ };
2341
+ return {
2342
+ failure: retryFailure,
2343
+ deselected: await this.bundleSelectionLost(name),
2344
+ remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可"
2345
+ };
2346
+ }
2347
+ /** Whether a bundle is still an installed dependency but no longer selected. */
2348
+ async bundleSelectionLost(name) {
2349
+ try {
2350
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2351
+ return Object.hasOwn(manifest.dependencies, name) && !manifest.bundles.includes(name);
2352
+ } catch {
2353
+ return false;
2354
+ }
2355
+ }
2356
+ /** Put a selection back after a refused removal, so the profile is as it was found. */
2357
+ async restoreBundleSelection(native, name) {
2358
+ if (native.setBundleEnabled === void 0) return;
2359
+ try {
2360
+ await native.setBundleEnabled(name, true);
2361
+ } catch (error) {
2362
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 启用状态:${error instanceof Error ? error.message : String(error)}`);
2363
+ }
2364
+ }
1863
2365
  /** Start a deterministic legacy aggregate migration. */
1864
2366
  migrate(sourceId, targetId, targetVersion, targetSpec) {
1865
2367
  const job = {
@@ -2058,13 +2560,7 @@ var CliGateway = class {
2058
2560
  child.stderr?.on("data", (chunk) => {
2059
2561
  capture(chunk, output);
2060
2562
  });
2061
- const timer = setTimeout(() => {
2062
- child.kill();
2063
- }, timeoutMs);
2064
- const code = await new Promise((resolve) => {
2065
- child.on("close", resolve);
2066
- });
2067
- clearTimeout(timer);
2563
+ const code = await awaitCliExit(child, output, timeoutMs);
2068
2564
  if (code !== 0) {
2069
2565
  job.phase = "error";
2070
2566
  const tail = output.read().trim();
@@ -2119,8 +2615,9 @@ var CliGateway = class {
2119
2615
  return;
2120
2616
  }
2121
2617
  job.plugin = updated;
2122
- await this.verifyBoot(job, before, after, conflicts);
2618
+ const dump = await this.verifyBoot(job, before, after, conflicts);
2123
2619
  if (job.phase === "error") return;
2620
+ if (await this.pruneOrphanOverrides(job, dump) === void 0) return;
2124
2621
  } else if (before.dependencies.find((candidate) => !after.dependencies.includes(candidate)) === void 0) {
2125
2622
  job.phase = "error";
2126
2623
  job.error = "plugin-manager: dsh plugin remove 报告成功,但依赖仍在 profile 中(卸载未生效)";
@@ -2165,6 +2662,211 @@ var CliGateway = class {
2165
2662
  }
2166
2663
  }
2167
2664
  /**
2665
+ * Compose the profile with the CLI's read-only `--dump-config` probe and
2666
+ * return the dump text. Composition writes nothing and binds no port, so it
2667
+ * is safe on every runtime — including an application-owned profile whose
2668
+ * *writes* the CLI refuses. A run that cannot compose (no CLI on this
2669
+ * runtime, a non-zero exit, a spawn failure) reports undefined, and the
2670
+ * caller must then leave the profile alone instead of guessing at the entry
2671
+ * set.
2672
+ * @returns the composed dump text, or undefined when it is unavailable.
2673
+ */
2674
+ async compositionOf() {
2675
+ const binary = this.binary();
2676
+ if (binary === null) return void 0;
2677
+ try {
2678
+ const output = createOutputCapture(MAX_OUTPUT_BYTES);
2679
+ const child = this.spawnCli(binary, [
2680
+ "--profile",
2681
+ this.facts.profileName,
2682
+ "--dump-config"
2683
+ ]);
2684
+ child.stdout?.on("data", (chunk) => {
2685
+ capture(chunk, output);
2686
+ });
2687
+ child.stderr?.on("data", (chunk) => {
2688
+ capture(chunk, output);
2689
+ });
2690
+ return await awaitCliExit(child, output, 9e4) === 0 ? output.read() : void 0;
2691
+ } catch {
2692
+ return;
2693
+ }
2694
+ }
2695
+ /**
2696
+ * The entry ids a user-layer override may still point at: the composed ids
2697
+ * plus every id the profile's own bundle layers still declare.
2698
+ *
2699
+ * The composition alone does not prove a row is retired. A host that
2700
+ * composes while a bundle is being replaced — the remove-then-install half of
2701
+ * an application-owned update, or an upgrade whose packages are half
2702
+ * installed — composes *without* the rows of the bundle that is momentarily
2703
+ * gone, and pruning on that probe deletes the user's override for a row that
2704
+ * still exists (0.4.7 lost `web-ui-remote-web-ui` and `ui-schedule` this
2705
+ * way). Declarations live in the bundle layers, so they survive that window.
2706
+ * @param composed - the entry ids of the composition probe.
2707
+ * @returns the ids to keep, or undefined when a declared layer cannot be
2708
+ * read, which proves nothing either way and must leave the file alone.
2709
+ */
2710
+ async liveOverrideIds(composed) {
2711
+ const live = new Set(composed);
2712
+ let manifest;
2713
+ try {
2714
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2715
+ } catch {
2716
+ return;
2717
+ }
2718
+ for (const name of manifest.bundles) {
2719
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2720
+ try {
2721
+ await readFile(join(dir, "package.json"), "utf8");
2722
+ } catch {
2723
+ return;
2724
+ }
2725
+ let text;
2726
+ try {
2727
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2728
+ } catch (error) {
2729
+ if (error.code === "ENOENT") continue;
2730
+ return;
2731
+ }
2732
+ try {
2733
+ for (const id of declaredRowIds(text, join(dir, "cordis.patch.yml"))) live.add(id);
2734
+ } catch {
2735
+ return;
2736
+ }
2737
+ }
2738
+ return live;
2739
+ }
2740
+ /**
2741
+ * The entry names the installed bundles' own rows carry, by entry id.
2742
+ *
2743
+ * The loader inserts one row per id and takes that row's name from the
2744
+ * bundle's own patch file, so this map is the very fact the loader composes:
2745
+ * a profile row naming something else is a row the loader skips.
2746
+ *
2747
+ * @returns the live names, or undefined when a bundle's patch cannot be read
2748
+ * (which proves nothing either way and must leave the profile alone).
2749
+ */
2750
+ async liveEntryNames() {
2751
+ const names = /* @__PURE__ */ new Map();
2752
+ let manifest;
2753
+ try {
2754
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2755
+ } catch {
2756
+ return;
2757
+ }
2758
+ for (const name of manifest.bundles) {
2759
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2760
+ let text;
2761
+ try {
2762
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2763
+ } catch (error) {
2764
+ if (error.code === "ENOENT") continue;
2765
+ return;
2766
+ }
2767
+ for (const row of insertRowsOf(text)) {
2768
+ if (row.id === void 0 || row.name === void 0) continue;
2769
+ names.set(row.id, row.name);
2770
+ }
2771
+ }
2772
+ return names;
2773
+ }
2774
+ /**
2775
+ * Point the profile's own rows at the packages that now carry those entry ids.
2776
+ *
2777
+ * A bundle that renames a row's package leaves every profile row that named
2778
+ * the old one dead: the include patch semantics skip a row whose name does
2779
+ * not match the inserted row, and the skip takes the whole row with it — a
2780
+ * config row stops configuring and a `disabled` override stops disabling,
2781
+ * both without a word in the browser. Issue #1901 moved the aggregate's
2782
+ * family rows from the `@linxin666/dsh-web-all/<family>` subpath to the
2783
+ * real package, so every profile row written before that upgrade went dead
2784
+ * with it.
2785
+ *
2786
+ * The repair is idempotent and writes only when a row actually changed, so a
2787
+ * healthy profile is never rewritten.
2788
+ *
2789
+ * @returns the repaired rows, in file order.
2790
+ */
2791
+ async repairProfileRowNames() {
2792
+ const names = await this.liveEntryNames();
2793
+ if (names === void 0 || names.size === 0) return [];
2794
+ let text;
2795
+ try {
2796
+ text = await readFile(this.facts.patchPath, "utf8");
2797
+ } catch {
2798
+ return [];
2799
+ }
2800
+ let repaired;
2801
+ try {
2802
+ repaired = repairStaleRowNames(text, this.facts.patchPath, names);
2803
+ } catch {
2804
+ return [];
2805
+ }
2806
+ if (repaired.repaired.length === 0) return [];
2807
+ await writePatchAtomic(this.facts.patchPath, repaired.text);
2808
+ return repaired.repaired;
2809
+ }
2810
+ /**
2811
+ * Post-update orphan guard: drop this package's own enablement overrides
2812
+ * whose entry id neither the composed *target* profile nor any bundle layer
2813
+ * still declares. The composition is the loader's own after the update
2814
+ * ({@link composedEntryIdsOf}), widened by the bundle layers' declarations
2815
+ * ({@link liveOverrideIds}) because a composition taken mid-upgrade omits
2816
+ * rows that still exist. A retired row would otherwise leave a stale
2817
+ * override that the loader reports on every boot as
2818
+ * `patch: entry "<id>" not found`.
2819
+ *
2820
+ * The stale-row-name repair ({@link repairProfileRowNames}) runs first and
2821
+ * on its own authority, so a profile whose bundle declarations cannot be
2822
+ * resolved is repaired even though the prune then writes nothing.
2823
+ *
2824
+ * Nothing is written when nothing is orphaned — a second run over a pruned
2825
+ * profile returns the input text untouched, so no write and no second backup
2826
+ * happen — and an unobtainable composition leaves the file as it is instead
2827
+ * of emptying it. A write that does fail settles the job as an error the way
2828
+ * every other post-mutation patch write in this transaction does, with the
2829
+ * backup the write helper takes first left in place.
2830
+ * @param job - the settling job (error target on write failure).
2831
+ * @param dumpText - an already captured composition, when the caller has one.
2832
+ * @returns the pruned entry ids, or undefined when the job failed.
2833
+ */
2834
+ async pruneOrphanOverrides(job, dumpText) {
2835
+ try {
2836
+ const repaired = await this.repairProfileRowNames();
2837
+ if (repaired.length > 0) console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
2838
+ } catch (error) {
2839
+ console.warn("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
2840
+ }
2841
+ const dump = dumpText ?? await this.compositionOf();
2842
+ if (dump === void 0) return [];
2843
+ const composed = composedEntryIdsOf(dump);
2844
+ if (composed === void 0) return [];
2845
+ const live = await this.liveOverrideIds(composed);
2846
+ if (live === void 0) return [];
2847
+ let text;
2848
+ try {
2849
+ text = await readFile(this.facts.patchPath, "utf8");
2850
+ } catch {
2851
+ return [];
2852
+ }
2853
+ let pruned;
2854
+ try {
2855
+ pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, live);
2856
+ } catch {
2857
+ return [];
2858
+ }
2859
+ if (pruned.pruned.length === 0) return [];
2860
+ try {
2861
+ await writePatchAtomic(this.facts.patchPath, pruned.text);
2862
+ return pruned.pruned;
2863
+ } catch (error) {
2864
+ job.phase = "error";
2865
+ job.error = `plugin-manager: 失效行覆盖清理写回失败:${error instanceof Error ? error.message : String(error)}(备份在 ${this.facts.patchPath}.bak-plugin-manager,下次启动前请手动检查 ${this.facts.patchPath})`;
2866
+ return;
2867
+ }
2868
+ }
2869
+ /**
2168
2870
  * Roll back a freshly installed dependency through the official remove
2169
2871
  * path (which also drops its bundle), then settle the job as an error.
2170
2872
  * This is the owner-aware conflict resolution: the existing plugin keeps
@@ -2189,14 +2891,7 @@ var CliGateway = class {
2189
2891
  child.stderr?.on("data", (chunk) => {
2190
2892
  capture(chunk, output);
2191
2893
  });
2192
- const timer = setTimeout(() => {
2193
- child.kill();
2194
- }, REMOVE_TIMEOUT_MS);
2195
- const code = await new Promise((resolve) => {
2196
- child.on("close", resolve);
2197
- });
2198
- clearTimeout(timer);
2199
- rolledBack = code === 0;
2894
+ rolledBack = await awaitCliExit(child, output, REMOVE_TIMEOUT_MS) === 0;
2200
2895
  tail = output.read().trim();
2201
2896
  }
2202
2897
  job.phase = "error";
@@ -2266,14 +2961,19 @@ var CliGateway = class {
2266
2961
  };
2267
2962
  }
2268
2963
  /**
2269
- * Boot preflight after an install: compose the profile with the CLI's
2270
- * `--dump-config` (resolves every entry without binding the port). A failure
2271
- * that implicates the new plugin disables it so the next start cannot fail;
2272
- * an unrelated failure is reported without touching anything.
2964
+ * Boot preflight after an install or update: compose the profile with the
2965
+ * CLI's `--dump-config` (resolves every entry without binding the port). A
2966
+ * failure that implicates the new plugin disables it so the next start
2967
+ * cannot fail; an unrelated failure is reported without touching anything.
2968
+ * The captured dump is returned on success so the update path can read the
2969
+ * composed entry set from the same probe (see {@link pruneOrphanOverrides}).
2970
+ * @returns the composed dump text, or undefined when the preflight did not
2971
+ * produce one (no CLI on this runtime, or a failure the caller must read
2972
+ * from `job`).
2273
2973
  */
2274
2974
  async verifyBoot(job, before, after, conflicts) {
2275
2975
  const binary = this.binary();
2276
- if (binary === null) return;
2976
+ if (binary === null) return void 0;
2277
2977
  const name = this.newDependency(before, after);
2278
2978
  const verifyOutput = createOutputCapture(MAX_OUTPUT_BYTES);
2279
2979
  const child = this.spawnCli(binary, [
@@ -2287,15 +2987,10 @@ var CliGateway = class {
2287
2987
  child.stderr?.on("data", (chunk) => {
2288
2988
  capture(chunk, verifyOutput);
2289
2989
  });
2290
- const timer = setTimeout(() => {
2291
- child.kill();
2292
- }, 9e4);
2293
- const code = await new Promise((resolve) => {
2294
- child.on("close", resolve);
2295
- });
2296
- clearTimeout(timer);
2297
- if (code === 0) return;
2298
- const tail = verifyOutput.read().trim();
2990
+ const code = await awaitCliExit(child, verifyOutput, 9e4);
2991
+ const dump = verifyOutput.read();
2992
+ if (code === 0) return dump;
2993
+ const tail = dump.trim();
2299
2994
  if (name === void 0) {
2300
2995
  job.phase = "error";
2301
2996
  job.error = tail === "" ? "plugin-manager: boot preflight failed" : tail;
@@ -2409,12 +3104,26 @@ function isLoopbackHostname(hostname) {
2409
3104
  return isIPv4Loopback(hostname);
2410
3105
  }
2411
3106
  /**
3107
+ * Whether a reverse proxy stood between the client and this host: the request
3108
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
3109
+ * hop that forwards traffic, so the request did not originate on this machine.
3110
+ * @param request - node HTTP request.
3111
+ * @returns true when a forwarding header is present.
3112
+ */
3113
+ function isProxiedRequest(request) {
3114
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
3115
+ }
3116
+ /**
2412
3117
  * Request-level trust fence: a loopback socket address AND a loopback Host
2413
3118
  * header, plus browser same-origin markers. The socket address is
2414
- * authoritative; X-Forwarded-For is never trusted.
3119
+ * authoritative for a direct connection; a request that carries a forwarding
3120
+ * header is refused outright, because a proxy in front of the host makes both
3121
+ * the socket address and the Host header describe the proxy rather than the
3122
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
2415
3123
  */
2416
3124
  function isLoopbackRequest(request) {
2417
3125
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
3126
+ if (isProxiedRequest(request)) return false;
2418
3127
  const host = request.headers.host;
2419
3128
  if (typeof host !== "string") return false;
2420
3129
  let hostUrl;
@@ -2454,62 +3163,6 @@ function parseDshVersion(value) {
2454
3163
  };
2455
3164
  }
2456
3165
  /**
2457
- * Compare two version strings by semver order (a release is newer than any
2458
- * prerelease of the same tuple).
2459
- * @returns -1 / 0 / 1, or undefined when either side is malformed.
2460
- */
2461
- function compareVersions(left, right) {
2462
- const a = parseDshVersion(left);
2463
- const b = parseDshVersion(right);
2464
- if (a === void 0 || b === void 0) return void 0;
2465
- for (const key of [
2466
- "major",
2467
- "minor",
2468
- "patch"
2469
- ]) if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1;
2470
- return comparePrerelease(a.prerelease, b.prerelease);
2471
- }
2472
- /**
2473
- * Semver prerelease ordering: numeric identifiers compare numerically,
2474
- * numeric identifiers rank below alphanumeric ones, alphanumeric identifiers
2475
- * compare lexically, and a longer list wins when the shared prefix is equal.
2476
- */
2477
- function comparePrerelease(left, right) {
2478
- if (left.length === 0 && right.length === 0) return 0;
2479
- if (left.length === 0) return 1;
2480
- if (right.length === 0) return -1;
2481
- const length = Math.max(left.length, right.length);
2482
- for (let index = 0; index < length; index += 1) {
2483
- const a = left[index];
2484
- const b = right[index];
2485
- if (a === void 0) return -1;
2486
- if (b === void 0) return 1;
2487
- if (typeof a === "number" && typeof b === "number") {
2488
- if (a !== b) return a < b ? -1 : 1;
2489
- } else if (typeof a === "number") return -1;
2490
- else if (typeof b === "number") return 1;
2491
- else if (a !== b) return a < b ? -1 : 1;
2492
- }
2493
- return 0;
2494
- }
2495
- const MINIMUM_RANGE_PATTERN = /^>=\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
2496
- /**
2497
- * Whether a host version satisfies a declared `>=X.Y.Z[-prerelease]` minimum.
2498
- * @param host - the running DSH host version.
2499
- * @param minimum - the declared minimum; any form other than `>=<semver>`
2500
- * (plain semver, `^`, `~`, multi-comparator ranges, empty) returns undefined.
2501
- * @returns true / false, or undefined when the host version is malformed or
2502
- * the minimum uses an unsupported form — callers treat undefined as
2503
- * "cannot verify" and fail closed for declared requirements.
2504
- */
2505
- function meetsMinimumDsh(host, minimum) {
2506
- const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim());
2507
- if (match === null) return void 0;
2508
- const compared = compareVersions(host, match[1]);
2509
- if (compared === void 0) return void 0;
2510
- return compared >= 0;
2511
- }
2512
- /**
2513
3166
  * Read the declared DSH minimum from a published registry manifest:
2514
3167
  * `dsh.engines.dsh` first, top-level `engines.dsh` next, and
2515
3168
  * `peerDependencies["@deepseek-ai/dsh"]` last, which is where a package that
@@ -2527,6 +3180,40 @@ function dshRequirementOf(manifest) {
2527
3180
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
2528
3181
  }
2529
3182
  //#endregion
3183
+ //#region src/host/dsh-compat.ts
3184
+ /**
3185
+ * The DSH runtime compatibility verdict for one declared plugin requirement,
3186
+ * evaluated the way the official boot gate evaluates it
3187
+ * (`evaluatePluginCompatibility` in app-boot's `plugin-compatibility.ts`):
3188
+ * the requirement is a node-semver range and the host satisfies it when
3189
+ * `semver.satisfies(host, range, { includePrerelease: true })` holds. Every
3190
+ * legal range form therefore decides: `||` alternatives, `^` and `~`,
3191
+ * whitespace-separated comparators, x-ranges, and prerelease tags compared as
3192
+ * ordinary versions.
3193
+ *
3194
+ * The requirement itself comes from `dshRequirementOf` in
3195
+ * `../core/version.ts`, which owns the field priority (this module only
3196
+ * decides the verdict). Host-only on purpose: `semver` is a node package and
3197
+ * must never be reachable from the browser half, which renders the same
3198
+ * declaration through the regex-only `displayMinimumVersion`.
3199
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
3200
+ */
3201
+ /**
3202
+ * Decide whether the running DSH host satisfies a declared requirement range.
3203
+ * @param host - the running DSH host version.
3204
+ * @param range - the declared requirement, in any node-semver range form.
3205
+ * @returns `satisfied` when the host satisfies the declaration,
3206
+ * `host-too-low` when it was compared and does not, and `unverifiable` when
3207
+ * no comparison could be made. Callers fail closed on the last two (issue
3208
+ * #754) but must not describe them with the same words.
3209
+ */
3210
+ function evaluateDshCompatibility(host, range) {
3211
+ if (range.trim() === "") return { verdict: "unverifiable" };
3212
+ if (semver.validRange(range) === null) return { verdict: "unverifiable" };
3213
+ if (semver.valid(host) === null) return { verdict: "unverifiable" };
3214
+ return semver.satisfies(host, range, { includePrerelease: true }) ? { verdict: "satisfied" } : { verdict: "host-too-low" };
3215
+ }
3216
+ //#endregion
2530
3217
  //#region src/host/legacy-migration.ts
2531
3218
  /**
2532
3219
  * Deterministic mapping for the dsh-web aggregate package rename.
@@ -2627,6 +3314,25 @@ const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0
2627
3314
  function runDetached(work) {
2628
3315
  return DETACHED.runInAsyncScope(work);
2629
3316
  }
3317
+ /**
3318
+ * Environment marker a Desktop shell sets when it guarantees that a host which
3319
+ * exits is replaced by a fresh host (rather than reported as stopped).
3320
+ *
3321
+ * The packaged Desktop shell owns the process tree but has no obligation to
3322
+ * respawn it: the shipped shell in this repository's compat matrix answers a
3323
+ * host exit with `desktop host stopped` and an error page. Stopping ourselves
3324
+ * under such a shell turns the restart button into "kill the app", so the mode
3325
+ * requires proof of the opposite behaviour.
3326
+ */
3327
+ const SHELL_RESTART_CAPABILITY_ENV = "DSH_SHELL_RESTARTS_HOST";
3328
+ /**
3329
+ * Whether the launching shell promises to bring the host back after it exits.
3330
+ * @param env - the environment the host was launched with.
3331
+ * @returns true only for an opt-in marker value of `1`.
3332
+ */
3333
+ function shellRestartIsSupported(env) {
3334
+ return env[SHELL_RESTART_CAPABILITY_ENV] === "1";
3335
+ }
2630
3336
  /** How long the helper waits for this process to disappear before giving up on the wait. */
2631
3337
  const RESTART_WAIT_MS = 3e4;
2632
3338
  /** Exit/interpreter arguments a relaunch must not repeat (they re-bind fixed ports). */
@@ -2639,7 +3345,7 @@ function isReusableExecArg(argument) {
2639
3345
  * @returns the planned mode, with the relaunch command when one is used.
2640
3346
  */
2641
3347
  function planRestart(facts) {
2642
- if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return { mode: "shell" };
3348
+ if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return shellRestartIsSupported(facts.env) ? { mode: "shell" } : { mode: "manual" };
2643
3349
  if (!facts.interactive) return { mode: "manual" };
2644
3350
  const script = facts.argv[0];
2645
3351
  if (script === void 0 || script === "") return { mode: "manual" };
@@ -2679,11 +3385,13 @@ const launch = (attempt) => {
2679
3385
  const child = cp.spawn(job.execPath, job.argv, { cwd: job.cwd, env: process.env, detached: true, stdio: ['ignore', fd, fd] });
2680
3386
  child.unref();
2681
3387
  let code = null;
3388
+ let spawnError = null;
2682
3389
  child.on('exit', (value) => { code = value; });
3390
+ child.on('error', (err) => { spawnError = err; log('relaunch spawn error: ' + err.message); });
2683
3391
  setTimeout(() => {
2684
- if (code === null) { log('relaunch started (pid ' + child.pid + ')'); fs.closeSync(fd); return; }
2685
- if (attempt < 4) { log('relaunch exited with ' + code + '; retrying'); launch(attempt + 1); return; }
2686
- log('relaunch gave up after exit ' + code);
3392
+ if (code === null && spawnError === null) { log('relaunch started (pid ' + child.pid + ')'); fs.closeSync(fd); return; }
3393
+ if (attempt < 4) { log('relaunch failed (' + (spawnError === null ? 'exit ' + code : spawnError.message) + '); retrying'); launch(attempt + 1); return; }
3394
+ log('relaunch gave up after ' + (spawnError === null ? 'exit ' + code : spawnError.message));
2687
3395
  fs.closeSync(fd);
2688
3396
  }, 3000);
2689
3397
  };
@@ -2722,6 +3430,11 @@ function startRelaunchHelper(command, logPath = restartLogPath()) {
2722
3430
  stdio: "ignore"
2723
3431
  });
2724
3432
  helper.unref();
3433
+ helper.on("error", (error) => {
3434
+ try {
3435
+ appendFileSync(logPath, (/* @__PURE__ */ new Date()).toISOString() + " helper spawn error: " + error.message + "\n");
3436
+ } catch {}
3437
+ });
2725
3438
  return helper.pid !== void 0;
2726
3439
  } catch (error) {
2727
3440
  try {
@@ -2919,17 +3632,27 @@ function makeGatewayRoutes(deps) {
2919
3632
  return dshVersionPending;
2920
3633
  };
2921
3634
  /**
2922
- * Compat verdict for one declared requirement. Unverified (unknown host,
2923
- * malformed host output, unsupported range) is incompatible so an update
2924
- * can never run against a runtime we cannot prove compatible (issue #754);
2925
- * only absent metadata keeps the update fail-open.
3635
+ * Compat verdict for one declared requirement, plus the running version the
3636
+ * verdict was made from. Unverified (unknown host, malformed host output, a
3637
+ * range node-semver rejects) is incompatible so an update can never run
3638
+ * against a runtime we cannot prove compatible (issue #754); only absent
3639
+ * metadata keeps the update fail-open.
3640
+ *
3641
+ * `hostVersion` is reported only for a verdict that really compared the
3642
+ * running version and lost it. Its absence is the wire's way of saying "this
3643
+ * declaration could not be checked", which is what the browser reads to tell
3644
+ * "your DSH is too old" from "we could not verify" (issues #1819 and #1899):
3645
+ * a blocked row with no version must never be described as below the
3646
+ * minimum, because nothing was compared.
2926
3647
  */
2927
3648
  const compatibleVerdict = async (requiresDsh) => {
2928
3649
  const hostVersion = await resolveDshVersion();
2929
3650
  if (hostVersion === void 0) return { compatible: false };
3651
+ const compatibility = evaluateDshCompatibility(hostVersion, requiresDsh);
3652
+ if (compatibility.verdict === "unverifiable") return { compatible: false };
2930
3653
  return {
2931
3654
  hostVersion,
2932
- compatible: meetsMinimumDsh(hostVersion, requiresDsh) === true
3655
+ compatible: compatibility.verdict === "satisfied"
2933
3656
  };
2934
3657
  };
2935
3658
  /** Wrap a handler with the loopback fence and JSON error reporting. */
@@ -3033,7 +3756,7 @@ function makeGatewayRoutes(deps) {
3033
3756
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3034
3757
  if (!compatible) return {
3035
3758
  status: 412,
3036
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to}; check the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3759
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3037
3760
  };
3038
3761
  }
3039
3762
  return {
@@ -3069,7 +3792,7 @@ function makeGatewayRoutes(deps) {
3069
3792
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3070
3793
  if (!compatible) return {
3071
3794
  status: 412,
3072
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target}; check the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3795
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3073
3796
  };
3074
3797
  }
3075
3798
  return {
@@ -3382,6 +4105,19 @@ function applyImpl(ctx) {
3382
4105
  for (const dispose of disposers) dispose();
3383
4106
  };
3384
4107
  }, "plugin-manager: gateway routes");
4108
+ ctx.effect(() => {
4109
+ const timer = setTimeout(() => {
4110
+ gateway.repairProfileRowNames().then((repaired) => {
4111
+ if (repaired.length === 0) return;
4112
+ console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
4113
+ }).catch((error) => {
4114
+ console.error("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
4115
+ });
4116
+ }, 1500);
4117
+ return () => {
4118
+ clearTimeout(timer);
4119
+ };
4120
+ }, "plugin-manager: stale row name repair");
3385
4121
  }
3386
4122
  //#endregion
3387
4123
  export { apply, inject, name };