@linxin666/dsh-client-ui-plugin-manager 0.4.5 → 0.4.7
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/README.i18n.yaml +2 -2
- package/README.md +5 -5
- package/README.zh.md +5 -5
- package/lib/client.js +12 -3
- package/lib/client.js.map +1 -1
- package/lib/index.js +613 -67
- package/lib/types/client/locales.d.ts +3 -0
- package/lib/types/core/protocol.d.ts +6 -0
- package/lib/types/host/detached-work.d.ts +44 -0
- package/lib/types/host/gateway.d.ts +162 -7
- package/lib/types/host/profile.d.ts +28 -0
- package/lib/types/host/routes.d.ts +11 -1
- package/lib/types/host/rows.d.ts +32 -0
- package/package.json +20 -17
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 { AsyncResource } from "node:async_hooks";
|
|
8
9
|
//#region src/mount-once.ts
|
|
9
10
|
/**
|
|
10
11
|
* Host single-instance guard shared by the plugin family. The family bundle
|
|
@@ -430,6 +431,81 @@ function setRowEnabled(text, filename, id, name, enabled, baseEnabled = true) {
|
|
|
430
431
|
}));
|
|
431
432
|
return document.toString({ lineWidth: 0 }) + "\n";
|
|
432
433
|
}
|
|
434
|
+
/** The complete key set of an enablement override row this package writes. */
|
|
435
|
+
const OVERRIDE_ROW_KEYS = /* @__PURE__ */ new Set([
|
|
436
|
+
"id",
|
|
437
|
+
"name",
|
|
438
|
+
"disabled"
|
|
439
|
+
]);
|
|
440
|
+
/**
|
|
441
|
+
* The entry id of an enablement override row this package owns, when the item
|
|
442
|
+
* is one: a bare row carrying a string `id`, a boolean `disabled`, and no
|
|
443
|
+
* other key. Anything else is somebody else's row — a config row carrying
|
|
444
|
+
* options, a row with an unknown shape, an insert wrapper — and the manager
|
|
445
|
+
* never edits or removes it.
|
|
446
|
+
* @param item - one top-level patch item.
|
|
447
|
+
* @returns the override's entry id, or undefined when the item is not ours.
|
|
448
|
+
*/
|
|
449
|
+
function overrideRowId(item) {
|
|
450
|
+
if (!isBareRow(item)) return void 0;
|
|
451
|
+
const id = bareRowId(item);
|
|
452
|
+
if (id === void 0) return void 0;
|
|
453
|
+
const disabled = item.get("disabled", true);
|
|
454
|
+
if (!(isScalar(disabled) && typeof disabled.value === "boolean")) return void 0;
|
|
455
|
+
for (const pair of item.items) {
|
|
456
|
+
const key = pair.key;
|
|
457
|
+
if (!isScalar(key) || !OVERRIDE_ROW_KEYS.has(String(key.value))) return void 0;
|
|
458
|
+
}
|
|
459
|
+
return id;
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Drop this package's own enablement overrides whose entry id the composed
|
|
463
|
+
* profile no longer carries — a retired row leaves a stale override behind,
|
|
464
|
+
* which the loader reports on every boot as `patch: entry "<id>" not found`.
|
|
465
|
+
* The prunable set is decided by the caller from the composed entry ids: an
|
|
466
|
+
* id the composition does not carry has no row left to override. Only rows
|
|
467
|
+
* {@link overrideRowId} recognizes are removed, comments and every other row
|
|
468
|
+
* are kept, and an already-pruned file returns its input text unchanged so the
|
|
469
|
+
* caller can skip the write entirely.
|
|
470
|
+
* @param text - current patch file text.
|
|
471
|
+
* @param filename - absolute path (diagnostics only).
|
|
472
|
+
* @param composedIds - the entry ids the composed profile carries.
|
|
473
|
+
* @returns the rewritten text and the pruned ids.
|
|
474
|
+
*/
|
|
475
|
+
function pruneOrphanRowOverrides(text, filename, composedIds) {
|
|
476
|
+
const { document, root } = parsePatch(text, filename);
|
|
477
|
+
const pruned = [];
|
|
478
|
+
for (let index = root.items.length - 1; index >= 0; index -= 1) {
|
|
479
|
+
const item = root.items[index];
|
|
480
|
+
const id = overrideRowId(item);
|
|
481
|
+
if (id === void 0 || composedIds.has(id)) continue;
|
|
482
|
+
pruned.unshift(id);
|
|
483
|
+
const comment = isMap(item) ? item.commentBefore : void 0;
|
|
484
|
+
root.items.splice(index, 1);
|
|
485
|
+
if (comment === void 0 || comment === null || comment === "") continue;
|
|
486
|
+
const next = root.items[index];
|
|
487
|
+
if (isMap(next) || isSeq(next)) next.commentBefore = appendComment(comment, next.commentBefore);
|
|
488
|
+
else document.comment = appendComment(comment, document.comment);
|
|
489
|
+
}
|
|
490
|
+
if (pruned.length === 0) return {
|
|
491
|
+
text,
|
|
492
|
+
pruned
|
|
493
|
+
};
|
|
494
|
+
const serialized = document.toString({ lineWidth: 0 });
|
|
495
|
+
return {
|
|
496
|
+
text: `${serialized.endsWith("\n") ? serialized.slice(0, -1) : serialized}${text.endsWith("\n") ? "\n" : ""}`,
|
|
497
|
+
pruned
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* One node's comment block followed by another's.
|
|
502
|
+
* @param first - the comment block to keep first.
|
|
503
|
+
* @param second - the existing block, when there is one.
|
|
504
|
+
* @returns the combined block.
|
|
505
|
+
*/
|
|
506
|
+
function appendComment(first, second) {
|
|
507
|
+
return second === void 0 || second === null || second === "" ? first : `${first}\n${second}`;
|
|
508
|
+
}
|
|
433
509
|
//#endregion
|
|
434
510
|
//#region src/host/bundle-guard.ts
|
|
435
511
|
/**
|
|
@@ -582,6 +658,38 @@ function desktopSelectedProfile(env = process.env) {
|
|
|
582
658
|
} catch {}
|
|
583
659
|
}
|
|
584
660
|
/**
|
|
661
|
+
* The running installation's own `@deepseek-ai/dsh` package.json, as the
|
|
662
|
+
* launcher published it on `profileContext`, or undefined when the host
|
|
663
|
+
* publishes none (or publishes something unusable). This is a READ-ONLY
|
|
664
|
+
* fact — unlike the profile directory and the patch path it is never a write
|
|
665
|
+
* target — but it still arrives from outside this package, so it must be an
|
|
666
|
+
* absolute, traversal-free path before anything reads a version out of it.
|
|
667
|
+
* @param launched - the profile facts the Host published, when available.
|
|
668
|
+
* @returns the validated anchor path, or undefined.
|
|
669
|
+
*/
|
|
670
|
+
function launchedInstallAnchor(launched) {
|
|
671
|
+
const anchor = launched === void 0 || typeof launched.installAnchor !== "string" ? "" : launched.installAnchor.trim();
|
|
672
|
+
if (anchor === "") return void 0;
|
|
673
|
+
if (!isAbsolute(anchor) || anchor.split(/[\/\\]/).includes("..")) return void 0;
|
|
674
|
+
return anchor;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Read the `version` field of one package manifest, tolerating every failure:
|
|
678
|
+
* a missing file, an unreadable one (a stripped asar entry), malformed JSON, or
|
|
679
|
+
* a non-string version all read as "no version". Callers fall back to their next
|
|
680
|
+
* source rather than reporting a version nobody declared.
|
|
681
|
+
* @param manifestPath - absolute path of a package.json.
|
|
682
|
+
* @returns the declared version, or undefined.
|
|
683
|
+
*/
|
|
684
|
+
function readManifestVersion(manifestPath) {
|
|
685
|
+
try {
|
|
686
|
+
const parsed = JSON.parse(stripBom(readFileSync(manifestPath, "utf8")));
|
|
687
|
+
return typeof parsed.version === "string" && parsed.version.trim() !== "" ? parsed.version.trim() : void 0;
|
|
688
|
+
} catch {
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
585
693
|
* Whether the host argv names the packaged Desktop launcher, whose entry
|
|
586
694
|
* script is `@deepseek-ai/dsh-desktop-host`. The Desktop client boots the
|
|
587
695
|
* `desktop` profile through `runProfile()` WITHOUT a `--profile` flag and
|
|
@@ -1079,8 +1187,54 @@ const UNSAFE_SPEC_CHARS = /[&|<>"'`%!\n\r\0]/;
|
|
|
1079
1187
|
function unsafeSpecReason(spec) {
|
|
1080
1188
|
return UNSAFE_SPEC_CHARS.test(spec) ? "plugin-manager: spec 含有危险的 shell 元字符或控制字符,已拒绝" : void 0;
|
|
1081
1189
|
}
|
|
1190
|
+
/**
|
|
1191
|
+
* The Electron resource roots a packaged Desktop install may carry, as
|
|
1192
|
+
* absolute directories. Two independent launcher facts name them, and either
|
|
1193
|
+
* alone is enough:
|
|
1194
|
+
*
|
|
1195
|
+
* - `process.resourcesPath` is Electron's own answer for the directory holding
|
|
1196
|
+
* `app.asar` and the bundled runtime (the Desktop host runs as an Electron
|
|
1197
|
+
* Node-mode child, so it always has one);
|
|
1198
|
+
* - the running host entry script sits INSIDE that tree
|
|
1199
|
+
* (`<resources>/app.asar/dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/index.js`),
|
|
1200
|
+
* so the first ancestor directory named `resources` is the same location even
|
|
1201
|
+
* when the process is not Electron.
|
|
1202
|
+
*
|
|
1203
|
+
* A root is only ever used to build a candidate path that must then exist, so
|
|
1204
|
+
* an unrelated `resources` directory elsewhere in the tree resolves to nothing.
|
|
1205
|
+
* @param hostEntryPath - the running host's entry script.
|
|
1206
|
+
* @param resourcesPath - Electron's resource directory, when the host has one.
|
|
1207
|
+
* @param pathApi - platform path semantics.
|
|
1208
|
+
* @returns candidate resource roots, in probe order.
|
|
1209
|
+
*/
|
|
1210
|
+
function desktopResourceRoots(hostEntryPath, resourcesPath, pathApi) {
|
|
1211
|
+
const roots = [];
|
|
1212
|
+
if (resourcesPath !== void 0 && resourcesPath !== "") roots.push(resourcesPath);
|
|
1213
|
+
if (hostEntryPath !== void 0 && hostEntryPath !== "") {
|
|
1214
|
+
let current = pathApi.dirname(hostEntryPath);
|
|
1215
|
+
for (let depth = 0; depth < 12; depth += 1) {
|
|
1216
|
+
const parent = pathApi.dirname(current);
|
|
1217
|
+
if (parent === current) break;
|
|
1218
|
+
current = parent;
|
|
1219
|
+
if (pathApi.basename(current).toLowerCase() === "resources") {
|
|
1220
|
+
roots.push(current);
|
|
1221
|
+
break;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return roots;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Electron's resource directory when this process is an Electron child, read
|
|
1229
|
+
* defensively: the type is not in `@types/node`, and a plain Node host has no
|
|
1230
|
+
* such property at all.
|
|
1231
|
+
*/
|
|
1232
|
+
function processResourcesPath() {
|
|
1233
|
+
const value = process.resourcesPath;
|
|
1234
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
1235
|
+
}
|
|
1082
1236
|
/** The binary search roots for the dsh CLI. */
|
|
1083
|
-
function findDshBinary(env = process.env, platform = process.platform, exists = existsSync, hostEntryPath = process.argv[1]) {
|
|
1237
|
+
function findDshBinary(env = process.env, platform = process.platform, exists = existsSync, hostEntryPath = process.argv[1], resourcesPath = processResourcesPath()) {
|
|
1084
1238
|
const candidates = [];
|
|
1085
1239
|
const separator = platform === "win32" ? ";" : ":";
|
|
1086
1240
|
const pathApi = platform === "win32" ? win32 : posix;
|
|
@@ -1106,6 +1260,11 @@ function findDshBinary(env = process.env, platform = process.platform, exists =
|
|
|
1106
1260
|
const packageRoot = pathApi.dirname(entryDir);
|
|
1107
1261
|
candidates.push(pathApi.join(packageRoot, "lib", "bin.js"));
|
|
1108
1262
|
}
|
|
1263
|
+
for (const root of desktopResourceRoots(hostEntryPath, resourcesPath, pathApi)) {
|
|
1264
|
+
const cliBin = pathApi.join(root, "runtime", "cli", "bin");
|
|
1265
|
+
if (platform === "win32") candidates.push(pathApi.join(cliBin, "dsh.cmd"), pathApi.join(cliBin, "dsh.exe"));
|
|
1266
|
+
else candidates.push(pathApi.join(cliBin, "dsh"));
|
|
1267
|
+
}
|
|
1109
1268
|
for (const candidate of candidates) if (exists(candidate)) return candidate;
|
|
1110
1269
|
return null;
|
|
1111
1270
|
}
|
|
@@ -1206,6 +1365,47 @@ function dshSpawnCommand(binary, platform = process.platform, localNodeExists =
|
|
|
1206
1365
|
argsPrefix: [binJs]
|
|
1207
1366
|
};
|
|
1208
1367
|
}
|
|
1368
|
+
/** The Windows directory used when the environment names no system root at all. */
|
|
1369
|
+
const WINDOWS_ROOT_FALLBACK = "C:\\Windows";
|
|
1370
|
+
/**
|
|
1371
|
+
* Read one environment variable by name, case-insensitively, ignoring blank
|
|
1372
|
+
* values. Windows spells the same variable `ComSpec` and `comspec` depending on
|
|
1373
|
+
* who wrote it (a launcher, a service, the user's own shell), and a plain
|
|
1374
|
+
* object seam carries whatever spelling the caller built.
|
|
1375
|
+
* @param env - the environment to read.
|
|
1376
|
+
* @param name - the variable name, matched without regard to case.
|
|
1377
|
+
* @returns the first non-blank value, or undefined.
|
|
1378
|
+
*/
|
|
1379
|
+
function envValue(env, name) {
|
|
1380
|
+
const wanted = name.toUpperCase();
|
|
1381
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1382
|
+
if (typeof value !== "string" || value.trim() === "") continue;
|
|
1383
|
+
if (key.toUpperCase() === wanted) return value;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Absolute path of the Windows command processor, resolved from an environment
|
|
1388
|
+
* rather than from PATH.
|
|
1389
|
+
*
|
|
1390
|
+
* Every `.cmd` shim still has to be executed through cmd.exe, and a bare
|
|
1391
|
+
* `cmd.exe` spawn resolves through the host PATH: a GUI-launched host whose PATH
|
|
1392
|
+
* carries no `%SystemRoot%\system32` (a packaged Desktop launch, a service, a
|
|
1393
|
+
* stripped environment) gets ENOENT for a name that is present on disk, and the
|
|
1394
|
+
* whole feature fails with it (issue #1857). ComSpec is the variable Windows
|
|
1395
|
+
* itself uses for this and names the real binary, so it is preferred; otherwise
|
|
1396
|
+
* the system root is read from `SystemRoot` or `windir`, with the conventional
|
|
1397
|
+
* `C:\Windows` as the last resort.
|
|
1398
|
+
*
|
|
1399
|
+
* Only the Windows branch needs it — a POSIX host spawns the CLI directly.
|
|
1400
|
+
* @param env - the environment to resolve from.
|
|
1401
|
+
* @returns the absolute cmd.exe path.
|
|
1402
|
+
*/
|
|
1403
|
+
function windowsCmdPath(env = process.env) {
|
|
1404
|
+
const comSpec = envValue(env, "ComSpec");
|
|
1405
|
+
if (comSpec !== void 0) return comSpec;
|
|
1406
|
+
const root = envValue(env, "SystemRoot") ?? envValue(env, "windir") ?? WINDOWS_ROOT_FALLBACK;
|
|
1407
|
+
return win32.join(root, "System32", "cmd.exe");
|
|
1408
|
+
}
|
|
1209
1409
|
/** Build the exact cmd.exe command line required to execute a trusted .cmd shim. */
|
|
1210
1410
|
function windowsCmdShimArgs(binary, args) {
|
|
1211
1411
|
const unsafe = /[&|<>"'`%!\n\r\0]/;
|
|
@@ -1236,6 +1436,105 @@ function withPrependedPath(env, dir, platform = process.platform) {
|
|
|
1236
1436
|
next.PATH = current === "" ? dir : `${dir}${separator}${current}`;
|
|
1237
1437
|
return next;
|
|
1238
1438
|
}
|
|
1439
|
+
/** The spawn failure recorded on a guarded child, read by {@link awaitChildExit}. */
|
|
1440
|
+
const SPAWN_FAILURE = /* @__PURE__ */ new WeakMap();
|
|
1441
|
+
/**
|
|
1442
|
+
* Whether an emitted error is a spawn failure rather than a later lifecycle
|
|
1443
|
+
* failure (a kill that did not land, a closed stdio pipe). Only a spawn failure
|
|
1444
|
+
* means the child will never close on its own.
|
|
1445
|
+
* @param error - the emitted error.
|
|
1446
|
+
* @returns true when no process was ever created.
|
|
1447
|
+
*/
|
|
1448
|
+
function isSpawnFailure(error) {
|
|
1449
|
+
if (typeof error !== "object" || error === null) return false;
|
|
1450
|
+
const syscall = error.syscall;
|
|
1451
|
+
return typeof syscall === "string" && syscall.startsWith("spawn");
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* The operator-facing text of one spawn failure.
|
|
1455
|
+
* @param error - the emitted error.
|
|
1456
|
+
* @returns a readable one-line reason.
|
|
1457
|
+
*/
|
|
1458
|
+
function spawnFailureText(error) {
|
|
1459
|
+
return "plugin-manager: 无法启动子进程(" + (error instanceof Error ? error.message : String(error)) + ")";
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Attach the error fallback every spawn outlet needs.
|
|
1463
|
+
*
|
|
1464
|
+
* A ChildProcess without an `error` listener turns a spawn failure into an
|
|
1465
|
+
* unhandled `error` event, which is an uncaught exception: the failure of one
|
|
1466
|
+
* CLI call took the whole dsh host process down with it. This records the
|
|
1467
|
+
* reason and, when the child never closed, settles it as a failed exit so a
|
|
1468
|
+
* caller that only waits for `close` neither hangs nor crashes (issue #1857).
|
|
1469
|
+
* @param child - the spawned child.
|
|
1470
|
+
* @returns the same child, guarded.
|
|
1471
|
+
*/
|
|
1472
|
+
function guardSpawnFailure(child) {
|
|
1473
|
+
let closed = false;
|
|
1474
|
+
child.on("close", () => {
|
|
1475
|
+
closed = true;
|
|
1476
|
+
});
|
|
1477
|
+
child.on("error", (error) => {
|
|
1478
|
+
if (!isSpawnFailure(error)) return;
|
|
1479
|
+
SPAWN_FAILURE.set(child, spawnFailureText(error));
|
|
1480
|
+
if (closed) return;
|
|
1481
|
+
closed = true;
|
|
1482
|
+
child.emit("close", -1, null);
|
|
1483
|
+
});
|
|
1484
|
+
return child;
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Wait for a spawned child to close, settling on a spawn failure as well.
|
|
1488
|
+
*
|
|
1489
|
+
* The listener pair is attached to every child this package waits on, so the
|
|
1490
|
+
* wait is safe for a child that arrived through a seam ({@link guardSpawnFailure}
|
|
1491
|
+
* guards the real spawn outlets, an injected one may skip it).
|
|
1492
|
+
* @param child - the spawned child.
|
|
1493
|
+
* @returns the exit verdict.
|
|
1494
|
+
*/
|
|
1495
|
+
async function awaitChildExit(child) {
|
|
1496
|
+
return new Promise((resolve) => {
|
|
1497
|
+
let settled = false;
|
|
1498
|
+
const finish = (code) => {
|
|
1499
|
+
if (settled) return;
|
|
1500
|
+
settled = true;
|
|
1501
|
+
const spawnError = SPAWN_FAILURE.get(child);
|
|
1502
|
+
resolve(spawnError === void 0 ? { code } : {
|
|
1503
|
+
code,
|
|
1504
|
+
spawnError
|
|
1505
|
+
});
|
|
1506
|
+
};
|
|
1507
|
+
child.on("close", (code) => {
|
|
1508
|
+
finish(code);
|
|
1509
|
+
});
|
|
1510
|
+
child.on("error", () => {
|
|
1511
|
+
finish(-1);
|
|
1512
|
+
});
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Wait for one spawned CLI child, folding a spawn failure into its output.
|
|
1517
|
+
*
|
|
1518
|
+
* Every caller already reports a non-zero exit through the captured output, so
|
|
1519
|
+
* a process that never started is reported the same readable way instead of as
|
|
1520
|
+
* a silent failure or a hang.
|
|
1521
|
+
* @param child - the spawned child.
|
|
1522
|
+
* @param output - the bounded capture the failure text is appended to.
|
|
1523
|
+
* @param timeoutMs - kill the child after this long; omitted for no deadline.
|
|
1524
|
+
* @returns the exit code, or null when a signal ended the child.
|
|
1525
|
+
*/
|
|
1526
|
+
async function awaitCliExit(child, output, timeoutMs) {
|
|
1527
|
+
const timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
|
|
1528
|
+
child.kill();
|
|
1529
|
+
}, timeoutMs);
|
|
1530
|
+
try {
|
|
1531
|
+
const exit = await awaitChildExit(child);
|
|
1532
|
+
if (exit.spawnError !== void 0) capture(Buffer.from(exit.spawnError + "\n"), output);
|
|
1533
|
+
return exit.code;
|
|
1534
|
+
} finally {
|
|
1535
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1239
1538
|
/**
|
|
1240
1539
|
* Spawn the dsh CLI with piped stdio and no shell parsing (see
|
|
1241
1540
|
* {@link dshSpawnCommand}).
|
|
@@ -1246,6 +1545,9 @@ function withPrependedPath(env, dir, platform = process.platform) {
|
|
|
1246
1545
|
* `dsh plugin` to pnpm, so without this the update would start and then fail on
|
|
1247
1546
|
* a missing pnpm instead. This mirrors the packaged Desktop launcher, which
|
|
1248
1547
|
* prepends its bundled runtime bin to the host it spawns.
|
|
1548
|
+
*
|
|
1549
|
+
* Every child leaves here guarded ({@link guardSpawnFailure}), so a spawn that
|
|
1550
|
+
* fails settles as a non-zero exit instead of raising an unhandled error.
|
|
1249
1551
|
* @param binary - the resolved dsh CLI path.
|
|
1250
1552
|
* @param args - arguments after the interpreter/script prefix.
|
|
1251
1553
|
* @param env - the host environment.
|
|
@@ -1254,7 +1556,7 @@ function withPrependedPath(env, dir, platform = process.platform) {
|
|
|
1254
1556
|
function spawnDsh(binary, args, env) {
|
|
1255
1557
|
const { command, argsPrefix } = dshSpawnCommand(binary);
|
|
1256
1558
|
const childEnv = withPrependedPath(env, (process.platform === "win32" ? win32 : posix).dirname(binary));
|
|
1257
|
-
if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return spawn(
|
|
1559
|
+
if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return guardSpawnFailure(spawn(windowsCmdPath(env), windowsCmdShimArgs(command, args), {
|
|
1258
1560
|
env: childEnv,
|
|
1259
1561
|
windowsVerbatimArguments: true,
|
|
1260
1562
|
stdio: [
|
|
@@ -1262,8 +1564,8 @@ function spawnDsh(binary, args, env) {
|
|
|
1262
1564
|
"pipe",
|
|
1263
1565
|
"pipe"
|
|
1264
1566
|
]
|
|
1265
|
-
});
|
|
1266
|
-
return spawn(command, [...argsPrefix, ...args], {
|
|
1567
|
+
}));
|
|
1568
|
+
return guardSpawnFailure(spawn(command, [...argsPrefix, ...args], {
|
|
1267
1569
|
env: command === process.execPath ? {
|
|
1268
1570
|
...childEnv,
|
|
1269
1571
|
ELECTRON_RUN_AS_NODE: "1"
|
|
@@ -1273,7 +1575,7 @@ function spawnDsh(binary, args, env) {
|
|
|
1273
1575
|
"pipe",
|
|
1274
1576
|
"pipe"
|
|
1275
1577
|
]
|
|
1276
|
-
});
|
|
1578
|
+
}));
|
|
1277
1579
|
}
|
|
1278
1580
|
/**
|
|
1279
1581
|
* Entry-id line of the official installer channels in the boot dump. A plain
|
|
@@ -1282,6 +1584,28 @@ function spawnDsh(binary, args, env) {
|
|
|
1282
1584
|
*/
|
|
1283
1585
|
const OFFICIAL_INSTALLER_PATTERN = /^\s*-?\s*id:\s*['"]?plugin-(?:installer|control)['"]?\s*$/m;
|
|
1284
1586
|
/**
|
|
1587
|
+
* The entry ids of a composed profile dump (`dsh --profile <name>
|
|
1588
|
+
* --dump-config`). The dump prints one YAML block per patch layer under a
|
|
1589
|
+
* `# ==` header, with the composed entries as column-0 `- id:` items — an
|
|
1590
|
+
* entry a profile patch overrides appears once, carrying the override's keys,
|
|
1591
|
+
* so those lines are exactly the loader's own entry set. Nested config keeps
|
|
1592
|
+
* its own `id` keys indented and is never mistaken for an entry.
|
|
1593
|
+
* @param dump - the dump's captured text.
|
|
1594
|
+
* @returns the composed entry ids, or undefined when the dump carried none.
|
|
1595
|
+
*/
|
|
1596
|
+
function composedEntryIdsOf(dump) {
|
|
1597
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1598
|
+
for (const rawLine of dump.split("\n")) {
|
|
1599
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
1600
|
+
const match = /^-[ \t]+id:[ \t]*(.+?)[ \t]*$/.exec(line);
|
|
1601
|
+
if (match === null) continue;
|
|
1602
|
+
const value = match[1];
|
|
1603
|
+
const unquoted = /^'(.*)'$/.exec(value)?.[1] ?? /^"(.*)"$/.exec(value)?.[1] ?? value;
|
|
1604
|
+
if (unquoted !== "") ids.add(unquoted);
|
|
1605
|
+
}
|
|
1606
|
+
return ids.size === 0 ? void 0 : ids;
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1285
1609
|
* Detect whether the official installer channels exist on this runtime by
|
|
1286
1610
|
* dumping the boot composition once: the npm-published web never contains
|
|
1287
1611
|
* `plugin-installer` entries, DSHCode and the checkout web do. The browser
|
|
@@ -1306,9 +1630,7 @@ async function detectOfficialChannels(binary, profileName, env = process.env, sp
|
|
|
1306
1630
|
child.stderr?.on("data", (chunk) => {
|
|
1307
1631
|
capture(chunk, output);
|
|
1308
1632
|
});
|
|
1309
|
-
if (await
|
|
1310
|
-
child.on("close", resolve);
|
|
1311
|
-
}) !== 0) return false;
|
|
1633
|
+
if (await awaitCliExit(child, output) !== 0) return false;
|
|
1312
1634
|
return OFFICIAL_INSTALLER_PATTERN.test(output.read());
|
|
1313
1635
|
}
|
|
1314
1636
|
/**
|
|
@@ -1332,6 +1654,22 @@ function nativeManagerFailure(outcome) {
|
|
|
1332
1654
|
const code = failure?.code;
|
|
1333
1655
|
return typeof code === "string" && code !== "" ? `官方插件管理器拒绝执行(${code})` : "官方插件管理器报告失败";
|
|
1334
1656
|
}
|
|
1657
|
+
/**
|
|
1658
|
+
* The official manager's own refusal code for one run, or undefined when its
|
|
1659
|
+
* verdict is not a failure. {@link nativeManagerFailure} renders the code for the
|
|
1660
|
+
* person; this is the same verdict read for a decision, which is how the update
|
|
1661
|
+
* path recognises the `already-installed` refusal it has to answer with a
|
|
1662
|
+
* two-phase replacement.
|
|
1663
|
+
* @param outcome - the resolved value of `installBundle` / `removeBundle`.
|
|
1664
|
+
* @returns the manager's failure code, or undefined for a run that did not fail.
|
|
1665
|
+
*/
|
|
1666
|
+
function nativeManagerRefusalCode(outcome) {
|
|
1667
|
+
if (typeof outcome !== "object" || outcome === null) return void 0;
|
|
1668
|
+
const verdict = outcome;
|
|
1669
|
+
if (verdict.application !== "failed") return void 0;
|
|
1670
|
+
const code = verdict.error?.code;
|
|
1671
|
+
return typeof code === "string" && code !== "" ? code : void 0;
|
|
1672
|
+
}
|
|
1335
1673
|
/** The gateway: serializes CLI operations through one job table and one mutation queue. */
|
|
1336
1674
|
var CliGateway = class {
|
|
1337
1675
|
facts;
|
|
@@ -1414,15 +1752,8 @@ var CliGateway = class {
|
|
|
1414
1752
|
child.stderr?.on("data", (chunk) => {
|
|
1415
1753
|
capture(chunk, output);
|
|
1416
1754
|
});
|
|
1417
|
-
const timer = setTimeout(() => {
|
|
1418
|
-
child.kill();
|
|
1419
|
-
}, timeoutMs);
|
|
1420
|
-
const code = await new Promise((resolve) => {
|
|
1421
|
-
child.on("close", resolve);
|
|
1422
|
-
});
|
|
1423
|
-
clearTimeout(timer);
|
|
1424
1755
|
return {
|
|
1425
|
-
code,
|
|
1756
|
+
code: await awaitCliExit(child, output, timeoutMs),
|
|
1426
1757
|
output: output.read().trim()
|
|
1427
1758
|
};
|
|
1428
1759
|
}
|
|
@@ -1523,6 +1854,7 @@ var CliGateway = class {
|
|
|
1523
1854
|
job.error = `plugin-manager: 迁移后的启动预检失败${verify.output === "" ? "" : `:\n${verify.output}`}`;
|
|
1524
1855
|
return;
|
|
1525
1856
|
}
|
|
1857
|
+
if (await this.pruneOrphanOverrides(job, verify.output) === void 0) return;
|
|
1526
1858
|
const manifest = await readProfileManifest(this.facts.packageJsonPath);
|
|
1527
1859
|
const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? targetSpec, after.layer.rows);
|
|
1528
1860
|
if (!/^(?:link:|file:)/.test(targetSpec) && updated.version !== targetVersion) {
|
|
@@ -1733,6 +2065,13 @@ var CliGateway = class {
|
|
|
1733
2065
|
* run (pnpm exited non-zero, an incompatible version, a cancellation) resolves
|
|
1734
2066
|
* with `application: 'failed'`, and only that verdict carries the reason — the
|
|
1735
2067
|
* profile re-read can only show that the version did not move.
|
|
2068
|
+
*
|
|
2069
|
+
* An `already-installed` refusal is answered by {@link replaceInstalled}: the
|
|
2070
|
+
* manager refuses to install a dependency the profile already carries while the
|
|
2071
|
+
* host mounts `hmr` (0.2.1-rc.2, and dsh-base mounts that service on every
|
|
2072
|
+
* profile host), so an in-place update there is only expressible as its two
|
|
2073
|
+
* phases. The single call stays first so the day the manager accepts an
|
|
2074
|
+
* in-place update this path needs no change.
|
|
1736
2075
|
* @param job - the update job being settled.
|
|
1737
2076
|
* @param native - the official manager.
|
|
1738
2077
|
*/
|
|
@@ -1745,10 +2084,13 @@ var CliGateway = class {
|
|
|
1745
2084
|
return;
|
|
1746
2085
|
}
|
|
1747
2086
|
const before = await this.capture();
|
|
1748
|
-
const
|
|
2087
|
+
const carried = await readProfileManifest(this.facts.packageJsonPath);
|
|
2088
|
+
const first = await native.installBundle(job.spec, {
|
|
1749
2089
|
enabled: true,
|
|
1750
2090
|
requestId: job.id
|
|
1751
|
-
})
|
|
2091
|
+
});
|
|
2092
|
+
let refusal = nativeManagerFailure(first);
|
|
2093
|
+
if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") refusal = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
|
|
1752
2094
|
if (refusal !== void 0) {
|
|
1753
2095
|
job.phase = "error";
|
|
1754
2096
|
job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
|
|
@@ -1767,6 +2109,7 @@ var CliGateway = class {
|
|
|
1767
2109
|
job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
|
|
1768
2110
|
return;
|
|
1769
2111
|
}
|
|
2112
|
+
if (await this.pruneOrphanOverrides(job) === void 0) return;
|
|
1770
2113
|
job.plugin = updated;
|
|
1771
2114
|
job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
|
|
1772
2115
|
id: change.id,
|
|
@@ -1776,6 +2119,39 @@ var CliGateway = class {
|
|
|
1776
2119
|
}));
|
|
1777
2120
|
job.phase = "done";
|
|
1778
2121
|
}
|
|
2122
|
+
/**
|
|
2123
|
+
* Replace an installed bundle with the update job's target spec through the
|
|
2124
|
+
* official manager, the only writer an application-owned profile accepts.
|
|
2125
|
+
* Removing first is what makes the install possible: the manager's
|
|
2126
|
+
* `already-installed` guard reads the profile, so the same name is a fresh
|
|
2127
|
+
* dependency once the old one is gone.
|
|
2128
|
+
*
|
|
2129
|
+
* A failed second phase reinstalls the spec the profile carried before the run,
|
|
2130
|
+
* so an update that cannot land leaves a working plugin behind instead of an
|
|
2131
|
+
* empty slot; the report says which of the two happened.
|
|
2132
|
+
* @param job - the update job whose spec is installed.
|
|
2133
|
+
* @param native - the official manager.
|
|
2134
|
+
* @param targetId - the installed bundle being replaced.
|
|
2135
|
+
* @param previousSpec - the dependency spec the profile carried before the run.
|
|
2136
|
+
* @returns the failure to report, or undefined once the target spec landed.
|
|
2137
|
+
*/
|
|
2138
|
+
async replaceInstalled(job, native, targetId, previousSpec) {
|
|
2139
|
+
if (previousSpec === void 0) return `${targetId} 不在 profile 依赖中,无法替换已安装版本`;
|
|
2140
|
+
const removalFailure = nativeManagerFailure(await native.removeBundle(targetId));
|
|
2141
|
+
if (removalFailure !== void 0) return `已安装版本无法移除(${removalFailure}),本次更新未做改动`;
|
|
2142
|
+
const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
|
|
2143
|
+
enabled: true,
|
|
2144
|
+
requestId: job.id
|
|
2145
|
+
}));
|
|
2146
|
+
if (refusal === void 0) return void 0;
|
|
2147
|
+
const restoreSpec = `${targetId}@${previousSpec}`;
|
|
2148
|
+
const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
|
|
2149
|
+
enabled: true,
|
|
2150
|
+
requestId: job.id
|
|
2151
|
+
}));
|
|
2152
|
+
if (restoreFailure === void 0) return `${refusal};已装回 ${restoreSpec}`;
|
|
2153
|
+
return `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`;
|
|
2154
|
+
}
|
|
1779
2155
|
/** Start a deterministic legacy aggregate migration. */
|
|
1780
2156
|
migrate(sourceId, targetId, targetVersion, targetSpec) {
|
|
1781
2157
|
const job = {
|
|
@@ -1974,13 +2350,7 @@ var CliGateway = class {
|
|
|
1974
2350
|
child.stderr?.on("data", (chunk) => {
|
|
1975
2351
|
capture(chunk, output);
|
|
1976
2352
|
});
|
|
1977
|
-
const
|
|
1978
|
-
child.kill();
|
|
1979
|
-
}, timeoutMs);
|
|
1980
|
-
const code = await new Promise((resolve) => {
|
|
1981
|
-
child.on("close", resolve);
|
|
1982
|
-
});
|
|
1983
|
-
clearTimeout(timer);
|
|
2353
|
+
const code = await awaitCliExit(child, output, timeoutMs);
|
|
1984
2354
|
if (code !== 0) {
|
|
1985
2355
|
job.phase = "error";
|
|
1986
2356
|
const tail = output.read().trim();
|
|
@@ -2035,8 +2405,9 @@ var CliGateway = class {
|
|
|
2035
2405
|
return;
|
|
2036
2406
|
}
|
|
2037
2407
|
job.plugin = updated;
|
|
2038
|
-
await this.verifyBoot(job, before, after, conflicts);
|
|
2408
|
+
const dump = await this.verifyBoot(job, before, after, conflicts);
|
|
2039
2409
|
if (job.phase === "error") return;
|
|
2410
|
+
if (await this.pruneOrphanOverrides(job, dump) === void 0) return;
|
|
2040
2411
|
} else if (before.dependencies.find((candidate) => !after.dependencies.includes(candidate)) === void 0) {
|
|
2041
2412
|
job.phase = "error";
|
|
2042
2413
|
job.error = "plugin-manager: dsh plugin remove 报告成功,但依赖仍在 profile 中(卸载未生效)";
|
|
@@ -2081,6 +2452,84 @@ var CliGateway = class {
|
|
|
2081
2452
|
}
|
|
2082
2453
|
}
|
|
2083
2454
|
/**
|
|
2455
|
+
* Compose the profile with the CLI's read-only `--dump-config` probe and
|
|
2456
|
+
* return the dump text. Composition writes nothing and binds no port, so it
|
|
2457
|
+
* is safe on every runtime — including an application-owned profile whose
|
|
2458
|
+
* *writes* the CLI refuses. A run that cannot compose (no CLI on this
|
|
2459
|
+
* runtime, a non-zero exit, a spawn failure) reports undefined, and the
|
|
2460
|
+
* caller must then leave the profile alone instead of guessing at the entry
|
|
2461
|
+
* set.
|
|
2462
|
+
* @returns the composed dump text, or undefined when it is unavailable.
|
|
2463
|
+
*/
|
|
2464
|
+
async compositionOf() {
|
|
2465
|
+
const binary = this.binary();
|
|
2466
|
+
if (binary === null) return void 0;
|
|
2467
|
+
try {
|
|
2468
|
+
const output = createOutputCapture(MAX_OUTPUT_BYTES);
|
|
2469
|
+
const child = this.spawnCli(binary, [
|
|
2470
|
+
"--profile",
|
|
2471
|
+
this.facts.profileName,
|
|
2472
|
+
"--dump-config"
|
|
2473
|
+
]);
|
|
2474
|
+
child.stdout?.on("data", (chunk) => {
|
|
2475
|
+
capture(chunk, output);
|
|
2476
|
+
});
|
|
2477
|
+
child.stderr?.on("data", (chunk) => {
|
|
2478
|
+
capture(chunk, output);
|
|
2479
|
+
});
|
|
2480
|
+
return await awaitCliExit(child, output, 9e4) === 0 ? output.read() : void 0;
|
|
2481
|
+
} catch {
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
/**
|
|
2486
|
+
* Post-update orphan guard: drop this package's own enablement overrides
|
|
2487
|
+
* whose entry id the composed *target* profile no longer carries. The
|
|
2488
|
+
* authority is the loader's own composition after the update
|
|
2489
|
+
* ({@link composedEntryIdsOf}), not the profile patch and not the source
|
|
2490
|
+
* profile: an override is only orphaned once the target composition stops
|
|
2491
|
+
* declaring that id, and ids the official base or another bundle still
|
|
2492
|
+
* mounts stay valid. A retired row would otherwise leave a stale override
|
|
2493
|
+
* that the loader reports on every boot as `patch: entry "<id>" not found`.
|
|
2494
|
+
*
|
|
2495
|
+
* Nothing is written when nothing is orphaned — a second run over a pruned
|
|
2496
|
+
* profile returns the input text untouched, so no write and no second backup
|
|
2497
|
+
* happen — and an unobtainable composition leaves the file as it is instead
|
|
2498
|
+
* of emptying it. A write that does fail settles the job as an error the way
|
|
2499
|
+
* every other post-mutation patch write in this transaction does, with the
|
|
2500
|
+
* backup the write helper takes first left in place.
|
|
2501
|
+
* @param job - the settling job (error target on write failure).
|
|
2502
|
+
* @param dumpText - an already captured composition, when the caller has one.
|
|
2503
|
+
* @returns the pruned entry ids, or undefined when the job failed.
|
|
2504
|
+
*/
|
|
2505
|
+
async pruneOrphanOverrides(job, dumpText) {
|
|
2506
|
+
const dump = dumpText ?? await this.compositionOf();
|
|
2507
|
+
if (dump === void 0) return [];
|
|
2508
|
+
const composed = composedEntryIdsOf(dump);
|
|
2509
|
+
if (composed === void 0) return [];
|
|
2510
|
+
let text;
|
|
2511
|
+
try {
|
|
2512
|
+
text = await readFile(this.facts.patchPath, "utf8");
|
|
2513
|
+
} catch {
|
|
2514
|
+
return [];
|
|
2515
|
+
}
|
|
2516
|
+
let pruned;
|
|
2517
|
+
try {
|
|
2518
|
+
pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, composed);
|
|
2519
|
+
} catch {
|
|
2520
|
+
return [];
|
|
2521
|
+
}
|
|
2522
|
+
if (pruned.pruned.length === 0) return [];
|
|
2523
|
+
try {
|
|
2524
|
+
await writePatchAtomic(this.facts.patchPath, pruned.text);
|
|
2525
|
+
return pruned.pruned;
|
|
2526
|
+
} catch (error) {
|
|
2527
|
+
job.phase = "error";
|
|
2528
|
+
job.error = `plugin-manager: 失效行覆盖清理写回失败:${error instanceof Error ? error.message : String(error)}(备份在 ${this.facts.patchPath}.bak-plugin-manager,下次启动前请手动检查 ${this.facts.patchPath})`;
|
|
2529
|
+
return;
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2084
2533
|
* Roll back a freshly installed dependency through the official remove
|
|
2085
2534
|
* path (which also drops its bundle), then settle the job as an error.
|
|
2086
2535
|
* This is the owner-aware conflict resolution: the existing plugin keeps
|
|
@@ -2105,14 +2554,7 @@ var CliGateway = class {
|
|
|
2105
2554
|
child.stderr?.on("data", (chunk) => {
|
|
2106
2555
|
capture(chunk, output);
|
|
2107
2556
|
});
|
|
2108
|
-
|
|
2109
|
-
child.kill();
|
|
2110
|
-
}, REMOVE_TIMEOUT_MS);
|
|
2111
|
-
const code = await new Promise((resolve) => {
|
|
2112
|
-
child.on("close", resolve);
|
|
2113
|
-
});
|
|
2114
|
-
clearTimeout(timer);
|
|
2115
|
-
rolledBack = code === 0;
|
|
2557
|
+
rolledBack = await awaitCliExit(child, output, REMOVE_TIMEOUT_MS) === 0;
|
|
2116
2558
|
tail = output.read().trim();
|
|
2117
2559
|
}
|
|
2118
2560
|
job.phase = "error";
|
|
@@ -2182,14 +2624,19 @@ var CliGateway = class {
|
|
|
2182
2624
|
};
|
|
2183
2625
|
}
|
|
2184
2626
|
/**
|
|
2185
|
-
* Boot preflight after an install: compose the profile with the
|
|
2186
|
-
* `--dump-config` (resolves every entry without binding the port). A
|
|
2187
|
-
* that implicates the new plugin disables it so the next start
|
|
2188
|
-
* an unrelated failure is reported without touching anything.
|
|
2627
|
+
* Boot preflight after an install or update: compose the profile with the
|
|
2628
|
+
* CLI's `--dump-config` (resolves every entry without binding the port). A
|
|
2629
|
+
* failure that implicates the new plugin disables it so the next start
|
|
2630
|
+
* cannot fail; an unrelated failure is reported without touching anything.
|
|
2631
|
+
* The captured dump is returned on success so the update path can read the
|
|
2632
|
+
* composed entry set from the same probe (see {@link pruneOrphanOverrides}).
|
|
2633
|
+
* @returns the composed dump text, or undefined when the preflight did not
|
|
2634
|
+
* produce one (no CLI on this runtime, or a failure the caller must read
|
|
2635
|
+
* from `job`).
|
|
2189
2636
|
*/
|
|
2190
2637
|
async verifyBoot(job, before, after, conflicts) {
|
|
2191
2638
|
const binary = this.binary();
|
|
2192
|
-
if (binary === null) return;
|
|
2639
|
+
if (binary === null) return void 0;
|
|
2193
2640
|
const name = this.newDependency(before, after);
|
|
2194
2641
|
const verifyOutput = createOutputCapture(MAX_OUTPUT_BYTES);
|
|
2195
2642
|
const child = this.spawnCli(binary, [
|
|
@@ -2203,15 +2650,10 @@ var CliGateway = class {
|
|
|
2203
2650
|
child.stderr?.on("data", (chunk) => {
|
|
2204
2651
|
capture(chunk, verifyOutput);
|
|
2205
2652
|
});
|
|
2206
|
-
const
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
const
|
|
2210
|
-
child.on("close", resolve);
|
|
2211
|
-
});
|
|
2212
|
-
clearTimeout(timer);
|
|
2213
|
-
if (code === 0) return;
|
|
2214
|
-
const tail = verifyOutput.read().trim();
|
|
2653
|
+
const code = await awaitCliExit(child, verifyOutput, 9e4);
|
|
2654
|
+
const dump = verifyOutput.read();
|
|
2655
|
+
if (code === 0) return dump;
|
|
2656
|
+
const tail = dump.trim();
|
|
2215
2657
|
if (name === void 0) {
|
|
2216
2658
|
job.phase = "error";
|
|
2217
2659
|
job.error = tail === "" ? "plugin-manager: boot preflight failed" : tail;
|
|
@@ -2488,6 +2930,61 @@ function targetSpecForLegacy(sourceSpec, familyVersion) {
|
|
|
2488
2930
|
if (familyVersion === "") return void 0;
|
|
2489
2931
|
return `${CURRENT_AGGREGATE}@${familyVersion}`;
|
|
2490
2932
|
}
|
|
2933
|
+
//#endregion
|
|
2934
|
+
//#region src/host/detached-work.ts
|
|
2935
|
+
/**
|
|
2936
|
+
* Run one piece of work outside the caller's async context.
|
|
2937
|
+
*
|
|
2938
|
+
* A Host mutation that runs inside `hmr.runExclusive` marks the running async
|
|
2939
|
+
* context with an AsyncLocalStorage store. Side effects on that path that write
|
|
2940
|
+
* a file the HMR config watcher refreshes from - `cordis.patch.yml` above all -
|
|
2941
|
+
* must not run under that mark, or the watcher's refresh re-enters the
|
|
2942
|
+
* exclusive transaction and is refused with "HMR transactions cannot be nested"
|
|
2943
|
+
* (#1751, #1754, #1816).
|
|
2944
|
+
*
|
|
2945
|
+
* Deferring is NOT enough, and the earlier belt that this one replaces was
|
|
2946
|
+
* built on a disproven premise: Node propagates an AsyncLocalStorage store into
|
|
2947
|
+
* `setImmediate`, into `node:timers`, into promise continuations, and into any
|
|
2948
|
+
* AsyncResource scoped to the current async id. Measured on Node 24:
|
|
2949
|
+
*
|
|
2950
|
+
* ```
|
|
2951
|
+
* als.run(true, () => setImmediate(() => als.getStore())) // -> true
|
|
2952
|
+
* ```
|
|
2953
|
+
*
|
|
2954
|
+
* What DOES start clean is an AsyncResource whose `triggerAsyncId` is not the
|
|
2955
|
+
* transaction. A resource created once at module scope - that is, before any
|
|
2956
|
+
* transaction existed - carries no store, and everything it schedules inherits
|
|
2957
|
+
* that emptiness rather than the caller's mark:
|
|
2958
|
+
*
|
|
2959
|
+
* ```
|
|
2960
|
+
* const detached = new AsyncResource('...') // module scope
|
|
2961
|
+
* als.run(true, () => detached.runInAsyncScope(() => setImmediate(() => als.getStore())))
|
|
2962
|
+
* // -> undefined
|
|
2963
|
+
* ```
|
|
2964
|
+
*
|
|
2965
|
+
* @module dsh-web-shared/host/detached-work
|
|
2966
|
+
*/
|
|
2967
|
+
/**
|
|
2968
|
+
* The escape hatch, created at module scope on purpose: a resource built while
|
|
2969
|
+
* a transaction is running would capture that transaction, so this single
|
|
2970
|
+
* instance is the only one the module ever needs. It carries no context of its
|
|
2971
|
+
* own, so every job run through it starts from the process's root context.
|
|
2972
|
+
*/
|
|
2973
|
+
const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0 });
|
|
2974
|
+
/**
|
|
2975
|
+
* Run `work` outside the caller's AsyncLocalStorage context.
|
|
2976
|
+
*
|
|
2977
|
+
* The call itself is synchronous - this schedules, it does not defer. Work that
|
|
2978
|
+
* must not block the caller should schedule its own `setImmediate` inside
|
|
2979
|
+
* `work`, which then also starts clean because it inherits this resource's
|
|
2980
|
+
* empty context rather than the caller's.
|
|
2981
|
+
*
|
|
2982
|
+
* @param work - the side effect to detach from the caller's async context.
|
|
2983
|
+
* @returns whatever `work` returns.
|
|
2984
|
+
*/
|
|
2985
|
+
function runDetached(work) {
|
|
2986
|
+
return DETACHED.runInAsyncScope(work);
|
|
2987
|
+
}
|
|
2491
2988
|
/** How long the helper waits for this process to disappear before giving up on the wait. */
|
|
2492
2989
|
const RESTART_WAIT_MS = 3e4;
|
|
2493
2990
|
/** Exit/interpreter arguments a relaunch must not repeat (they re-bind fixed ports). */
|
|
@@ -2540,11 +3037,13 @@ const launch = (attempt) => {
|
|
|
2540
3037
|
const child = cp.spawn(job.execPath, job.argv, { cwd: job.cwd, env: process.env, detached: true, stdio: ['ignore', fd, fd] });
|
|
2541
3038
|
child.unref();
|
|
2542
3039
|
let code = null;
|
|
3040
|
+
let spawnError = null;
|
|
2543
3041
|
child.on('exit', (value) => { code = value; });
|
|
3042
|
+
child.on('error', (err) => { spawnError = err; log('relaunch spawn error: ' + err.message); });
|
|
2544
3043
|
setTimeout(() => {
|
|
2545
|
-
if (code === null) { log('relaunch started (pid ' + child.pid + ')'); fs.closeSync(fd); return; }
|
|
2546
|
-
if (attempt < 4) { log('relaunch
|
|
2547
|
-
log('relaunch gave up after exit ' + code);
|
|
3044
|
+
if (code === null && spawnError === null) { log('relaunch started (pid ' + child.pid + ')'); fs.closeSync(fd); return; }
|
|
3045
|
+
if (attempt < 4) { log('relaunch failed (' + (spawnError === null ? 'exit ' + code : spawnError.message) + '); retrying'); launch(attempt + 1); return; }
|
|
3046
|
+
log('relaunch gave up after ' + (spawnError === null ? 'exit ' + code : spawnError.message));
|
|
2548
3047
|
fs.closeSync(fd);
|
|
2549
3048
|
}, 3000);
|
|
2550
3049
|
};
|
|
@@ -2583,6 +3082,11 @@ function startRelaunchHelper(command, logPath = restartLogPath()) {
|
|
|
2583
3082
|
stdio: "ignore"
|
|
2584
3083
|
});
|
|
2585
3084
|
helper.unref();
|
|
3085
|
+
helper.on("error", (error) => {
|
|
3086
|
+
try {
|
|
3087
|
+
appendFileSync(logPath, (/* @__PURE__ */ new Date()).toISOString() + " helper spawn error: " + error.message + "\n");
|
|
3088
|
+
} catch {}
|
|
3089
|
+
});
|
|
2586
3090
|
return helper.pid !== void 0;
|
|
2587
3091
|
} catch (error) {
|
|
2588
3092
|
try {
|
|
@@ -2655,11 +3159,34 @@ async function fetchRegistryManifest(name) {
|
|
|
2655
3159
|
};
|
|
2656
3160
|
}
|
|
2657
3161
|
/**
|
|
2658
|
-
* Read the running DSH host version
|
|
2659
|
-
*
|
|
2660
|
-
*
|
|
2661
|
-
*
|
|
2662
|
-
*
|
|
3162
|
+
* Read the running DSH host version out of the installation's own manifest.
|
|
3163
|
+
*
|
|
3164
|
+
* The launcher publishes the `@deepseek-ai/dsh` package.json it booted from on
|
|
3165
|
+
* `profileContext.installAnchor`; that manifest's `version` is by construction
|
|
3166
|
+
* the version of the DSH this host is running. It is the primary source because
|
|
3167
|
+
* it is the only one a packaged Desktop install can answer: there the CLI is not
|
|
3168
|
+
* on PATH, every `.bin` shim is stripped from the installer, and the private
|
|
3169
|
+
* host package ships no `lib/bin.js` to run (issue #1819). A runtime that
|
|
3170
|
+
* publishes no anchor (or one whose manifest cannot be read) falls through to
|
|
3171
|
+
* {@link probeDshVersion}.
|
|
3172
|
+
* @param installAnchor - the published anchor path, when there is one.
|
|
3173
|
+
* @returns the running version, or undefined when it cannot be read.
|
|
3174
|
+
*/
|
|
3175
|
+
function readInstalledDshVersion(installAnchor) {
|
|
3176
|
+
if (installAnchor === void 0) return void 0;
|
|
3177
|
+
return readManifestVersion(installAnchor);
|
|
3178
|
+
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Read the running DSH host version through `dsh --version`.
|
|
3181
|
+
*
|
|
3182
|
+
* This is the FALLBACK source, used only when the installation's own manifest
|
|
3183
|
+
* could not be read. It costs a subprocess and needs a CLI this host can reach,
|
|
3184
|
+
* which a packaged Desktop host cannot: the launcher puts only `node` on its
|
|
3185
|
+
* PATH, the installer strips every `node_modules/.bin`, and the private host
|
|
3186
|
+
* package ships no `lib/bin.js` (issue #1819). Returns undefined when the
|
|
3187
|
+
* binary is unavailable or the output is not a plain semver; callers treat an
|
|
3188
|
+
* unknown host version as a fail-closed verdict for declared requirements
|
|
3189
|
+
* (issue #754).
|
|
2663
3190
|
*/
|
|
2664
3191
|
async function probeDshVersion(cliAvailable) {
|
|
2665
3192
|
if (!cliAvailable()) return void 0;
|
|
@@ -2722,16 +3249,24 @@ function makeGatewayRoutes(deps) {
|
|
|
2722
3249
|
const { facts, gateway } = deps;
|
|
2723
3250
|
const fetchManifest = deps.fetchManifest ?? fetchRegistryManifest;
|
|
2724
3251
|
/**
|
|
2725
|
-
* Cached
|
|
2726
|
-
*
|
|
2727
|
-
*
|
|
2728
|
-
*
|
|
3252
|
+
* Cached host version: successful verdicts refresh after a TTL (the CLI update
|
|
3253
|
+
* path is the gateway itself, so a stale success is wrong long-term), failed
|
|
3254
|
+
* probes are retried after a cooldown instead of being cached forever, and
|
|
3255
|
+
* concurrent requests share one in-flight probe.
|
|
3256
|
+
*
|
|
3257
|
+
* The running installation's own manifest is read first. That is a local file
|
|
3258
|
+
* read with no process to spawn and nothing to fall out of date mid-run, so it
|
|
3259
|
+
* is re-read per resolution and never cached: a packaged Desktop host, where
|
|
3260
|
+
* the CLI fallback is unreachable, would otherwise spend its first request on
|
|
3261
|
+
* a probe that cannot succeed.
|
|
2729
3262
|
*/
|
|
2730
3263
|
let dshVersion;
|
|
2731
3264
|
let dshVersionAt = 0;
|
|
2732
3265
|
let dshVersionPending;
|
|
2733
3266
|
const resolveDshVersion = () => {
|
|
2734
3267
|
if (deps.dshVersion !== void 0) return deps.dshVersion();
|
|
3268
|
+
const installed = readInstalledDshVersion(deps.installAnchor);
|
|
3269
|
+
if (installed !== void 0) return Promise.resolve(installed);
|
|
2735
3270
|
const now = Date.now();
|
|
2736
3271
|
if (dshVersion !== void 0 && now - dshVersionAt < VERSION_PROBE_TTL_MS) return Promise.resolve(dshVersion);
|
|
2737
3272
|
if (dshVersionAt !== 0 && now - dshVersionAt < VERSION_PROBE_COOLDOWN_MS) return Promise.resolve(void 0);
|
|
@@ -2863,7 +3398,7 @@ function makeGatewayRoutes(deps) {
|
|
|
2863
3398
|
const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
|
|
2864
3399
|
if (!compatible) return {
|
|
2865
3400
|
status: 412,
|
|
2866
|
-
error: hostVersion === void 0 ? `plugin-manager: cannot verify the DSH version for ${migration.to}
|
|
3401
|
+
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`
|
|
2867
3402
|
};
|
|
2868
3403
|
}
|
|
2869
3404
|
return {
|
|
@@ -2899,7 +3434,7 @@ function makeGatewayRoutes(deps) {
|
|
|
2899
3434
|
const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
|
|
2900
3435
|
if (!compatible) return {
|
|
2901
3436
|
status: 412,
|
|
2902
|
-
error: hostVersion === void 0 ? `plugin-manager: cannot verify the DSH version for ${target}
|
|
3437
|
+
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`
|
|
2903
3438
|
};
|
|
2904
3439
|
}
|
|
2905
3440
|
return {
|
|
@@ -2981,7 +3516,11 @@ function makeGatewayRoutes(deps) {
|
|
|
2981
3516
|
const entryEnabled = enabled || LOCKED_ENTRY_IDS.has(entry.id);
|
|
2982
3517
|
next = setRowEnabled(next, facts.patchPath, entry.id, entry.name, entryEnabled, entry.baseEnabled);
|
|
2983
3518
|
}
|
|
2984
|
-
if (next !== patchText) await
|
|
3519
|
+
if (next !== patchText) await runDetached(() => new Promise((resolve, reject) => {
|
|
3520
|
+
setImmediate(() => {
|
|
3521
|
+
writePatchAtomic(facts.patchPath, next).then(resolve, reject);
|
|
3522
|
+
});
|
|
3523
|
+
}));
|
|
2985
3524
|
const plugin = (await snapshotGateway(facts, next)).plugins.find((item) => item.id === ownerName);
|
|
2986
3525
|
return plugin === void 0 ? { error: `plugin-manager: plugin ${ownerName} is not installed` } : { plugin };
|
|
2987
3526
|
});
|
|
@@ -3029,7 +3568,9 @@ function makeGatewayRoutes(deps) {
|
|
|
3029
3568
|
const requiresDsh = dshRequirementOf(targetManifest);
|
|
3030
3569
|
if (requiresDsh !== void 0) {
|
|
3031
3570
|
update.requiresDsh = requiresDsh;
|
|
3032
|
-
|
|
3571
|
+
const verdict = await compatibleVerdict(requiresDsh);
|
|
3572
|
+
update.compatible = verdict.compatible;
|
|
3573
|
+
if (verdict.hostVersion !== void 0) update.hostVersion = verdict.hostVersion;
|
|
3033
3574
|
}
|
|
3034
3575
|
updates.push(update);
|
|
3035
3576
|
continue;
|
|
@@ -3045,7 +3586,9 @@ function makeGatewayRoutes(deps) {
|
|
|
3045
3586
|
const requiresDsh = dshRequirementOf(manifest);
|
|
3046
3587
|
if (requiresDsh !== void 0) {
|
|
3047
3588
|
update.requiresDsh = requiresDsh;
|
|
3048
|
-
|
|
3589
|
+
const verdict = await compatibleVerdict(requiresDsh);
|
|
3590
|
+
update.compatible = verdict.compatible;
|
|
3591
|
+
if (verdict.hostVersion !== void 0) update.hostVersion = verdict.hostVersion;
|
|
3049
3592
|
}
|
|
3050
3593
|
updates.push(update);
|
|
3051
3594
|
}
|
|
@@ -3182,8 +3725,9 @@ function officialManager(ctx) {
|
|
|
3182
3725
|
}
|
|
3183
3726
|
function applyImpl(ctx) {
|
|
3184
3727
|
let facts;
|
|
3728
|
+
const launched = launchedProfile(ctx);
|
|
3185
3729
|
try {
|
|
3186
|
-
facts = resolveProfile(process.argv, process.env,
|
|
3730
|
+
facts = resolveProfile(process.argv, process.env, launched);
|
|
3187
3731
|
} catch (error) {
|
|
3188
3732
|
console.error("[plugin-manager]", error instanceof Error ? error.message : String(error));
|
|
3189
3733
|
return;
|
|
@@ -3191,11 +3735,13 @@ function applyImpl(ctx) {
|
|
|
3191
3735
|
if (!profileExists(facts.profileDir)) return;
|
|
3192
3736
|
const gateway = new CliGateway(facts, process.env, { nativeManager: () => officialManager(ctx) });
|
|
3193
3737
|
const cliAvailable = () => findDshBinary() !== null;
|
|
3738
|
+
const installAnchor = launchedInstallAnchor(launched);
|
|
3194
3739
|
ctx.effect(() => {
|
|
3195
3740
|
const disposers = makeGatewayRoutes({
|
|
3196
3741
|
facts,
|
|
3197
3742
|
gateway,
|
|
3198
|
-
cliAvailable
|
|
3743
|
+
cliAvailable,
|
|
3744
|
+
installAnchor
|
|
3199
3745
|
}).map((route) => ctx.webServer.register(route));
|
|
3200
3746
|
return () => {
|
|
3201
3747
|
for (const dispose of disposers) dispose();
|