@linxin666/dsh-client-ui-plugin-manager 0.4.2 → 0.4.4

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
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync, readFileSync } from "node:fs";
2
+ import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
3
3
  import { copyFile, readFile, rename, writeFile } from "node:fs/promises";
4
- import { isAbsolute, join, posix, win32 } from "node:path";
4
+ import { basename, dirname, isAbsolute, join, normalize, posix, sep, win32 } from "node:path";
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";
@@ -12,38 +12,111 @@ import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
12
12
  * the loader accepts a standalone install of the same package side by side;
13
13
  * without this guard the second instance would still re-register the same
14
14
  * webserver routes, tools, settings namespaces, and system-prompt sections
15
- * and fail the boot. mountOnce makes the second host apply a no-op for the
16
- * lifetime of the first instance (the browser half is already deduped by
17
- * package name in the client module host).
15
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
16
+ * no-op for as long as the first instance lives (the browser half is already
17
+ * deduped by package name in the client module host).
18
+ *
19
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
20
+ * long after the refused mount ran its course: the Host reloads a profile by
21
+ * creating the new loader entries before the old ones are torn down (a
22
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
23
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
24
+ * previous entry still owns the name. Dropping that refused mount lost the
25
+ * plugin for good - the previous entry then disposed its own mount, releasing
26
+ * the name with nobody left to take it, and the family row stayed listed as
27
+ * active while its host routes 404ed (the task-board panel showed
28
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
29
+ * restart recovered it).
30
+ *
31
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
32
+ * the holder releases the name - if the waiting fiber is still alive then. The
33
+ * single-instance guarantee is unchanged: exactly one mount is live per
34
+ * package name, and the replay re-enters the guard so a later mount still
35
+ * dedupes against it.
18
36
  *
19
37
  * The registry rides a global symbol so two module instances of the same
20
- * package (npm copy vs repository link) still share one verdict. cordis
21
- * `ctx.effect` runs its callback immediately and treats the callback's
38
+ * package (npm copy vs repository link) still share one verdict. That symbol
39
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
40
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
41
+ * dsh-community-plugins) are separate repositories carrying their own copy of
42
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
43
+ * must keep the shape every published copy reads (a `Set` of package names
44
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
45
+ * under their own additive key, and the registry reads back a `Set` even when
46
+ * some other build left a different value there. Changing `MOUNTED`'s shape
47
+ * in place broke that contract once: a satellite's legacy copy created a
48
+ * `Set`, the family's new copy read it as a `Map`, and every family row
49
+ * mounted after it failed with "claims.get is not a function".
50
+ *
51
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
22
52
  * return value as the fiber disposer, so the unmarker is returned, not run.
23
53
  */
54
+ /** Published cross-repository contract: package names currently mounted. */
24
55
  const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
56
+ /** Additive key this guard owns: refused mounts waiting for the name. */
57
+ const WAITERS = Symbol.for("dsh-web.mounted-plugins.waiters");
58
+ /**
59
+ * The shared name registry, always a `Set` whatever another build stored here:
60
+ * a foreign value (an interim shape, a hand-written global) must not take every
61
+ * family plugin down with it.
62
+ * @returns the process-wide set of mounted package names.
63
+ */
25
64
  function mountedSet() {
26
65
  const registry = globalThis;
27
- return registry[MOUNTED] ??= /* @__PURE__ */ new Set();
66
+ const existing = registry[MOUNTED];
67
+ if (existing instanceof Set) return existing;
68
+ const created = /* @__PURE__ */ new Set();
69
+ registry[MOUNTED] = created;
70
+ return created;
71
+ }
72
+ /** Queue per package name for mounts refused while a holder was alive. */
73
+ function mountWaiters() {
74
+ const registry = globalThis;
75
+ return registry[WAITERS] ??= /* @__PURE__ */ new Map();
28
76
  }
29
77
  /**
30
78
  * Wrap a cordis plugin apply so the package runs at most once per process.
31
- * The first mount registers normally and unmarks when its fiber disposes;
32
- * any later mount of the same package name is a no-op.
79
+ * The first mount registers normally and releases the name when its fiber
80
+ * disposes; a mount refused while that name is held waits for the release and
81
+ * then runs, unless its own fiber disposes first.
33
82
  * @param packageName - npm package identity shared by every install source.
34
83
  * @param fn - the original plugin apply.
35
84
  * @returns an apply of the same shape.
36
85
  */
37
86
  function mountOnce(packageName, fn) {
38
- return ((...args) => {
87
+ const mount = (...args) => {
39
88
  const mounted = mountedSet();
40
- if (mounted.has(packageName)) return;
89
+ const ctx = args[0];
90
+ if (mounted.has(packageName)) {
91
+ const waiters = mountWaiters();
92
+ const queue = waiters.get(packageName) ?? [];
93
+ let alive = true;
94
+ const pending = { run: () => {
95
+ if (alive) mount(...args);
96
+ } };
97
+ ctx?.effect?.(() => () => {
98
+ alive = false;
99
+ const index = queue.indexOf(pending);
100
+ if (index >= 0) queue.splice(index, 1);
101
+ });
102
+ queue.push(pending);
103
+ waiters.set(packageName, queue);
104
+ return;
105
+ }
41
106
  mounted.add(packageName);
42
- args[0]?.effect?.(() => () => {
107
+ ctx?.effect?.(() => () => {
43
108
  mounted.delete(packageName);
109
+ const waiters = mountWaiters();
110
+ const queue = waiters.get(packageName);
111
+ if (queue === void 0) return;
112
+ waiters.delete(packageName);
113
+ for (const waiter of queue.splice(0)) queueMicrotask(() => {
114
+ waiter.run();
115
+ });
44
116
  });
45
117
  return fn(...args);
46
- });
118
+ };
119
+ return mount;
47
120
  }
48
121
  //#endregion
49
122
  //#region src/core/patch-diff.ts
@@ -505,32 +578,126 @@ function desktopSelectedProfile(env = process.env) {
505
578
  } catch {}
506
579
  }
507
580
  /**
508
- * Resolve the boot profile name from the host argv: an explicit `--profile`
509
- * flag wins, then the DSH_PROFILE environment override, then the `web`
510
- * subcommand alias. The launcher hands the app its own args verbatim, so the
511
- * web app's argv is the reliable source on every CLI-launched host.
581
+ * Whether the host argv names the packaged Desktop launcher, whose entry
582
+ * script is `@deepseek-ai/dsh-desktop-host`. The Desktop client boots the
583
+ * `desktop` profile through `runProfile()` WITHOUT a `--profile` flag and
584
+ * without exporting DSH_PROFILE, so argv is the only launcher fact left and
585
+ * the desktop channel probe must stay on for that shape (the packaged host
586
+ * registers the official installer services programmatically, which the CLI
587
+ * boot dump cannot see).
588
+ * @param argv - process argv.
589
+ */
590
+ function isPackagedDesktopArgv(argv) {
591
+ return argv.some((argument) => argument.includes(`${sep}dsh-desktop-host${sep}`) || argument.includes("/dsh-desktop-host/"));
592
+ }
593
+ /**
594
+ * The profile directory a packaged Desktop launch carries in its OWN argv.
595
+ * Electron under ELECTRON_RUN_AS_NODE (and node alike) strips exec switches
596
+ * from `process.argv`, so the desktop host launches as
597
+ * `[execPath, dsh-desktop-host/lib/index.js, <dsh>, <profileDir>, ...]` and
598
+ * hands the profile directory to its own `loadProfileDirectory` as that
599
+ * positional argument. This is a launcher fact independent of the
600
+ * `profileContext` service, so a runtime that publishes no service can
601
+ * still be named correctly; a published service stays authoritative above it.
602
+ * @param argv - process argv.
603
+ * @returns the absolute profile directory, or undefined when argv names none.
604
+ */
605
+ function desktopProfileDirFromArgv(argv) {
606
+ if (!isPackagedDesktopArgv(argv)) return void 0;
607
+ for (const argument of argv) {
608
+ if (!isAbsolute(argument)) continue;
609
+ if (basename(dirname(argument)) !== "profiles") continue;
610
+ const name = basename(argument);
611
+ if (name === "" || name === "." || name === "..") continue;
612
+ return argument;
613
+ }
614
+ }
615
+ /**
616
+ * Resolve the boot profile from the launcher facts: an explicit `--profile`
617
+ * flag wins, then the profile the official runtime published on the host
618
+ * context, then the profile directory a packaged launch carries in its own
619
+ * argv, then the DSH_PROFILE environment override, then the `web` subcommand
620
+ * alias, then the packaged Desktop app's persisted selection.
621
+ *
622
+ * Why the launched facts outrank DSH_PROFILE: in this runtime the variable is
623
+ * an OUTPUT, not a boot selector. `runProfile()` is the single launch path for
624
+ * CLI and Desktop alike and provides `profileContext` in both, and
625
+ * `@deepseek-ai/dsh-shell-env` DERIVES `DSH_PROFILE` from `profileContext.name`
626
+ * for the shell children it spawns; no runtime module reads it to choose a
627
+ * profile. Whenever both exist they therefore describe the same profile, and
628
+ * the service carries the more precise facts (the exact directory and patch
629
+ * file). A hand-set or stale value disagreeing with the running host is the
630
+ * one case where the order matters, and following it would mount the gateway -
631
+ * and write its rows - into a profile this host never reads.
512
632
  * @param argv - process argv (test seam).
513
633
  * @param env - process environment (test seam).
634
+ * @param launched - the profile facts the Host published, when available.
635
+ * @param desktopLauncher - whether argv names the packaged Desktop launcher.
514
636
  * @returns the resolved profile facts.
515
637
  */
516
- function resolveProfile(argv = process.argv, env = process.env) {
638
+ function resolveProfile(argv = process.argv, env = process.env, launched, desktopLauncher = isPackagedDesktopArgv(argv)) {
517
639
  const flagIndex = argv.indexOf("--profile");
518
- let name;
519
- let desktop = false;
520
- if (flagIndex !== -1 && argv[flagIndex + 1] !== void 0 && argv[flagIndex + 1] !== "") name = argv[flagIndex + 1];
521
- else if (env.DSH_PROFILE !== void 0 && env.DSH_PROFILE.trim() !== "") {
522
- name = env.DSH_PROFILE.trim();
523
- desktop = argv.length <= 1 && desktopSelectedProfile(env) === name;
524
- } else if (argv.includes("web")) name = "web";
525
- else {
526
- name = desktopSelectedProfile(env);
527
- desktop = name !== void 0;
528
- }
529
- if (name === void 0) throw new Error("plugin-manager: cannot determine the boot profile; pass --profile <name> or set DSH_PROFILE");
530
- if (name.includes("/") || name.includes("\\") || name.includes("..")) throw new Error(`plugin-manager: invalid profile name ${JSON.stringify(name)}`);
531
- const profileDir = join(resolveDshHome(env), "profiles", name);
640
+ if (flagIndex !== -1 && argv[flagIndex + 1] !== void 0 && argv[flagIndex + 1] !== "") return factsFor(argv[flagIndex + 1], env, desktopLauncher);
641
+ const published = launchedFacts(launched, desktopLauncher, env);
642
+ if (published !== void 0) return published;
643
+ const desktopDir = desktopProfileDirFromArgv(argv);
644
+ if (desktopDir !== void 0) {
645
+ const argvFacts = launchedFacts({
646
+ name: basename(desktopDir),
647
+ dir: desktopDir
648
+ }, desktopLauncher, env);
649
+ if (argvFacts !== void 0) return argvFacts;
650
+ }
651
+ if (env.DSH_PROFILE !== void 0 && env.DSH_PROFILE.trim() !== "") {
652
+ const name = env.DSH_PROFILE.trim();
653
+ return factsFor(name, env, desktopLauncher || argv.length <= 1 && desktopSelectedProfile(env) === name);
654
+ }
655
+ if (argv.includes("web")) return factsFor("web", env, desktopLauncher);
656
+ const selected = desktopSelectedProfile(env);
657
+ if (selected !== void 0) return factsFor(selected, env, true);
658
+ throw new Error("plugin-manager: cannot determine the boot profile; pass --profile <name> or set DSH_PROFILE");
659
+ }
660
+ /**
661
+ * Facts from the profile the Host published on `profileContext`, when that
662
+ * service carries a usable name (or directory). The published directory is the
663
+ * launched profile's real location, which is exactly what the runtime passes
664
+ * to the profile loader itself — the name-based builder would only reproduce
665
+ * it. It is still validated before it becomes the root of every later lookup.
666
+ * @param launched - the host's published profile facts.
667
+ * @param desktopLauncher - whether argv names the packaged Desktop launcher.
668
+ * @param env - process environment, for the name-only fallback layout.
669
+ * @returns the facts, or undefined when nothing usable was published.
670
+ */
671
+ function launchedFacts(launched, desktopLauncher, env) {
672
+ if (launched === void 0) return void 0;
673
+ const name = typeof launched.name === "string" ? launched.name.trim() : "";
674
+ const dir = typeof launched.dir === "string" ? launched.dir.trim() : "";
675
+ if (name === "" && dir === "") return void 0;
676
+ if (name !== "") assertSafeProfileName(name);
677
+ const profileRoot = join(resolveDshHome(env), "profiles");
678
+ const profileDir = dir !== "" ? dir : join(profileRoot, name);
679
+ if (!isAbsolute(profileDir) || profileDir.split(/[\/\\]/).includes("..")) throw new Error(`plugin-manager: published profile directory is not a safe absolute path ${JSON.stringify(launched.dir ?? "")}`);
680
+ const dirBase = profileDir.split(/[\/\\]/).filter(Boolean).pop() ?? basename(profileDir);
681
+ if (name !== "" && name !== dirBase) throw new Error(`plugin-manager: published profile name and directory disagree ${JSON.stringify(name)} vs ${JSON.stringify(profileDir)}`);
682
+ const isPosixLiteral = profileDir.includes("/") && !profileDir.includes("\\");
683
+ const ownPatchPath = isPosixLiteral ? `${profileDir}/cordis.patch.yml` : join(profileDir, "cordis.patch.yml");
684
+ const publishedPatchPath = typeof launched.patchPath === "string" ? launched.patchPath.trim() : "";
685
+ if (publishedPatchPath !== "" && publishedPatchPath !== ownPatchPath && normalize(publishedPatchPath) !== normalize(ownPatchPath)) throw new Error(`plugin-manager: published patch path is not the launched profile's own patch file ${JSON.stringify(launched.patchPath)}`);
686
+ return {
687
+ profileName: name !== "" ? name : dirBase,
688
+ profileDir,
689
+ patchPath: ownPatchPath,
690
+ packageJsonPath: isPosixLiteral ? `${profileDir}/package.json` : join(profileDir, "package.json"),
691
+ desktop: desktopLauncher
692
+ };
693
+ }
694
+ /** Facts for one explicitly named profile, resolved under `$DSH_HOME/profiles`. */
695
+ function factsFor(name, env, desktop) {
696
+ const trimmed = name.trim();
697
+ assertSafeProfileName(trimmed);
698
+ const profileDir = join(resolveDshHome(env), "profiles", trimmed);
532
699
  return {
533
- profileName: name,
700
+ profileName: trimmed,
534
701
  profileDir,
535
702
  patchPath: join(profileDir, "cordis.patch.yml"),
536
703
  packageJsonPath: join(profileDir, "package.json"),
@@ -538,6 +705,15 @@ function resolveProfile(argv = process.argv, env = process.env) {
538
705
  };
539
706
  }
540
707
  /**
708
+ * Reject a profile name that is not exactly one directory segment under
709
+ * `profiles/`. `.` is rejected alongside separators and `..`: `join` normalizes
710
+ * it away, so accepting it would silently resolve to the `profiles` directory
711
+ * itself rather than to a profile.
712
+ */
713
+ function assertSafeProfileName(name) {
714
+ if (name === "" || name === "." || name === ".." || name.includes("/") || name.includes("\\")) throw new Error(`plugin-manager: invalid profile name ${JSON.stringify(name)}`);
715
+ }
716
+ /**
541
717
  * Read the profile manifest; a missing or malformed file fails loud.
542
718
  * @param packageJsonPath - absolute path of the profile's package.json.
543
719
  * @returns the parsed bundles and dependencies.
@@ -867,6 +1043,11 @@ function createOutputCapture(maxBytes) {
867
1043
  * CLI changed (the conflict ledger). The npm web runtime has no installer
868
1044
  * service, so this gateway is its write path; on runtimes with official
869
1045
  * channels the browser half never calls it.
1046
+ *
1047
+ * One exception: an application-owned profile (a packaged Desktop launch)
1048
+ * cannot be written by the CLI at all — the official launcher refuses it — so
1049
+ * installs, updates and removals there run through the official in-process
1050
+ * plugin manager instead (see {@link NativePluginManager}).
870
1051
  * @module @linxin666/dsh-client-ui-plugin-manager/host
871
1052
  */
872
1053
  /** Hard deadline for one CLI add (git clones can take minutes). */
@@ -932,22 +1113,77 @@ function findDshBinary(env = process.env, platform = process.platform, exists =
932
1113
  function capture(chunk, buffer) {
933
1114
  buffer.push(chunk);
934
1115
  }
1116
+ /** Bytes read for the shebang probe (a Node script names its interpreter on line 1). */
1117
+ const SHEBANG_PROBE_BYTES = 256;
1118
+ /**
1119
+ * Read a file's leading bytes for the shebang probe. Every failure — a missing
1120
+ * file, a directory, a permission error, an unreadable asar entry — reads as
1121
+ * "no head", so the caller falls back to spawning the path directly.
1122
+ * @param path - file to probe.
1123
+ * @returns the leading text, or undefined.
1124
+ */
1125
+ function readFileHead(path) {
1126
+ let fd;
1127
+ try {
1128
+ fd = openSync(path, "r");
1129
+ const buffer = Buffer.alloc(SHEBANG_PROBE_BYTES);
1130
+ const read = readSync(fd, buffer, 0, SHEBANG_PROBE_BYTES, 0);
1131
+ return buffer.subarray(0, read).toString("utf8");
1132
+ } catch {
1133
+ return;
1134
+ } finally {
1135
+ if (fd !== void 0) try {
1136
+ closeSync(fd);
1137
+ } catch {}
1138
+ }
1139
+ }
935
1140
  /**
936
- * The spawn command for the dsh CLI on this platform. Windows runs the
937
- * npm-generated dsh.cmd wrapper by resolving its node binary and bin.js script
938
- * and spawning them directly: going through cmd.exe splits unquoted paths with
939
- * spaces (`'D:\Program' is not recognized`).
1141
+ * Whether a resolved CLI path is a Node script: a `.js` module, or a file whose
1142
+ * shebang names node. A Node script cannot be spawned as an executable on its
1143
+ * own: the kernel hands the shebang to the interpreter it names, and
1144
+ * `#!/usr/bin/env node` resolves node through PATH — which a GUI-launched host
1145
+ * (the packaged Desktop app) does not carry, so the child dies before the CLI
1146
+ * starts with `env: node: No such file or directory` (exit 127).
1147
+ * @param path - the resolved CLI path.
1148
+ * @param readHead - head probe (test seam).
1149
+ * @returns true when the path needs a Node interpreter.
1150
+ */
1151
+ function isNodeScript(path, readHead = readFileHead) {
1152
+ if (/\.(?:c|m)?js$/i.test(path)) return true;
1153
+ const head = readHead(path);
1154
+ if (head === void 0) return false;
1155
+ const firstLine = head.split("\n", 1)[0] ?? "";
1156
+ return /^#!.*\bnode\b/.test(firstLine);
1157
+ }
1158
+ /**
1159
+ * The spawn command for the dsh CLI on this platform. A Node script (the
1160
+ * npm/homebrew `dsh` shim, a `.bin` symlink, a packaged `lib/bin.js`) is run
1161
+ * by an interpreter that exists regardless of PATH: a `node` sitting beside the
1162
+ * CLI when the installation ships one (npm-global and homebrew layouts), else
1163
+ * the host's own interpreter — `process.execPath`, which the ELECTRON_RUN_AS_NODE
1164
+ * branch in {@link spawnDsh} covers for an Electron host. Windows additionally
1165
+ * resolves the npm-generated shim into node plus bin.js and spawns them
1166
+ * directly: going through cmd.exe splits unquoted paths with spaces
1167
+ * (`'D:\Program' is not recognized`).
940
1168
  * @param binary - the dsh CLI path found by {@link findDshBinary}.
941
1169
  * @param platform - process platform (test seam).
942
1170
  * @param localNodeExists - existence probe (test seam).
943
1171
  * @param binJsExists - existence probe for the resolved bin script (test seam).
1172
+ * @param readHead - shebang probe (test seam).
944
1173
  * @returns the executable and the argument prefix to run the dsh bin script.
945
1174
  */
946
- function dshSpawnCommand(binary, platform = process.platform, localNodeExists = existsSync, binJsExists = existsSync) {
947
- if (platform !== "win32") return {
948
- command: binary,
949
- argsPrefix: []
950
- };
1175
+ function dshSpawnCommand(binary, platform = process.platform, localNodeExists = existsSync, binJsExists = existsSync, readHead = readFileHead) {
1176
+ if (platform !== "win32") {
1177
+ if (!isNodeScript(binary, readHead)) return {
1178
+ command: binary,
1179
+ argsPrefix: []
1180
+ };
1181
+ const sibling = posix.join(posix.dirname(binary), "node");
1182
+ return {
1183
+ command: localNodeExists(sibling) ? sibling : process.execPath,
1184
+ argsPrefix: [binary]
1185
+ };
1186
+ }
951
1187
  const dir = win32.dirname(binary);
952
1188
  const localNode = win32.join(dir, "node.exe");
953
1189
  if (win32.basename(binary).toLowerCase() === "bin.js") return {
@@ -975,11 +1211,45 @@ function windowsCmdShimArgs(binary, args) {
975
1211
  `""${binary}" ${args.map((arg) => `"${arg}"`).join(" ")}"`
976
1212
  ];
977
1213
  }
978
- /** Spawn the dsh CLI with piped stdio and no shell parsing (see {@link dshSpawnCommand}). */
1214
+ /**
1215
+ * Prepend one directory to a child environment's PATH, collapsing every case
1216
+ * variant of the key into one `PATH`. Windows exposes the variable as `Path`,
1217
+ * and spreading `process.env` into a plain object preserves that spelling:
1218
+ * assigning `env.PATH` beside it would leave two keys whose serialization
1219
+ * drops the system directories (the desktop childEnv defect).
1220
+ * @param env - the environment to copy.
1221
+ * @param dir - directory to put first.
1222
+ * @param platform - process platform (test seam).
1223
+ * @returns a new environment with one normalized, prepended PATH.
1224
+ */
1225
+ function withPrependedPath(env, dir, platform = process.platform) {
1226
+ const separator = platform === "win32" ? ";" : ":";
1227
+ const current = Object.keys(env).filter((key) => key.toUpperCase() === "PATH").map((key) => env[key]).find((value) => value !== void 0 && value !== "") ?? "";
1228
+ const next = {};
1229
+ for (const [key, value] of Object.entries(env)) if (key.toUpperCase() !== "PATH") next[key] = value;
1230
+ next.PATH = current === "" ? dir : `${dir}${separator}${current}`;
1231
+ return next;
1232
+ }
1233
+ /**
1234
+ * Spawn the dsh CLI with piped stdio and no shell parsing (see
1235
+ * {@link dshSpawnCommand}).
1236
+ *
1237
+ * The CLI's own directory goes first on the child PATH: npm-global, homebrew and
1238
+ * packaged layouts keep `node`, `pnpm` and `npx` beside the `dsh` shim, and a
1239
+ * GUI-launched host carries none of them on its own PATH — the CLI forwards
1240
+ * `dsh plugin` to pnpm, so without this the update would start and then fail on
1241
+ * a missing pnpm instead. This mirrors the packaged Desktop launcher, which
1242
+ * prepends its bundled runtime bin to the host it spawns.
1243
+ * @param binary - the resolved dsh CLI path.
1244
+ * @param args - arguments after the interpreter/script prefix.
1245
+ * @param env - the host environment.
1246
+ * @returns the spawned child process.
1247
+ */
979
1248
  function spawnDsh(binary, args, env) {
980
1249
  const { command, argsPrefix } = dshSpawnCommand(binary);
1250
+ const childEnv = withPrependedPath(env, (process.platform === "win32" ? win32 : posix).dirname(binary));
981
1251
  if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return spawn("cmd.exe", windowsCmdShimArgs(command, args), {
982
- env,
1252
+ env: childEnv,
983
1253
  windowsVerbatimArguments: true,
984
1254
  stdio: [
985
1255
  "ignore",
@@ -989,9 +1259,9 @@ function spawnDsh(binary, args, env) {
989
1259
  });
990
1260
  return spawn(command, [...argsPrefix, ...args], {
991
1261
  env: command === process.execPath ? {
992
- ...env,
1262
+ ...childEnv,
993
1263
  ELECTRON_RUN_AS_NODE: "1"
994
- } : env,
1264
+ } : childEnv,
995
1265
  stdio: [
996
1266
  "ignore",
997
1267
  "pipe",
@@ -1035,6 +1305,27 @@ async function detectOfficialChannels(binary, profileName, env = process.env, sp
1035
1305
  }) !== 0) return false;
1036
1306
  return OFFICIAL_INSTALLER_PATTERN.test(output.read());
1037
1307
  }
1308
+ /**
1309
+ * The official manager's own failure text for one run, or undefined when its
1310
+ * verdict is not a failure. The manager resolves a failed run instead of
1311
+ * rejecting it, so this is the only place its refusal can be read — the profile
1312
+ * re-read afterwards can only say that nothing moved, never why.
1313
+ * @param outcome - the resolved value of `installBundle` / `removeBundle`.
1314
+ * @returns the failure text to report, or undefined for a run that did not fail.
1315
+ */
1316
+ function nativeManagerFailure(outcome) {
1317
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1318
+ const verdict = outcome;
1319
+ if (verdict.application === "cancelled") return "本次操作已取消(profile 未改动)";
1320
+ if (verdict.application !== "failed") return void 0;
1321
+ const failure = verdict.error;
1322
+ const diagnostic = typeof failure?.diagnostic === "string" ? failure.diagnostic.trim() : "";
1323
+ if (diagnostic !== "") return diagnostic;
1324
+ const incompatible = failure?.incompatible;
1325
+ if (Array.isArray(incompatible) && incompatible.length > 0) return incompatible.map((item) => `${item.name ?? "未知包"}@${item.version ?? "未知版本"} 与 dsh ${item.runtimeVersion ?? "当前版本"} 不兼容`).join(";");
1326
+ const code = failure?.code;
1327
+ return typeof code === "string" && code !== "" ? `官方插件管理器拒绝执行(${code})` : "官方插件管理器报告失败";
1328
+ }
1038
1329
  /** The gateway: serializes CLI operations through one job table and one mutation queue. */
1039
1330
  var CliGateway = class {
1040
1331
  facts;
@@ -1084,6 +1375,29 @@ var CliGateway = class {
1084
1375
  binary() {
1085
1376
  return this.deps.findBinary !== void 0 ? this.deps.findBinary(this.env) : findDshBinary(this.env);
1086
1377
  }
1378
+ /**
1379
+ * The official in-process manager to write through, or undefined when the CLI
1380
+ * is the writer. Only an application-owned profile (a packaged Desktop launch)
1381
+ * takes this path: there the CLI refuses the profile outright, while the
1382
+ * official manager — which the launcher configures with its bundled
1383
+ * package-manager invocation — owns the same files this gateway reads. On
1384
+ * every other runtime the CLI stays the single writer, exactly as before.
1385
+ * @returns the manager, or undefined when the CLI should run.
1386
+ */
1387
+ nativeManager() {
1388
+ if (this.facts.desktop !== true) return void 0;
1389
+ return this.deps.nativeManager?.();
1390
+ }
1391
+ /**
1392
+ * Whether this gateway will write through the official in-process manager
1393
+ * instead of the CLI (an application-owned profile, see
1394
+ * {@link nativeManager}). The HTTP layer reads it so its CLI-availability
1395
+ * guard never rejects a job the CLI is not going to run.
1396
+ * @returns true when the native writer serves installs, updates and removals.
1397
+ */
1398
+ usesNativeWriter() {
1399
+ return this.nativeManager() !== void 0;
1400
+ }
1087
1401
  /** Run one CLI command to completion and return the bounded output. */
1088
1402
  async runCli(binary, args, timeoutMs) {
1089
1403
  const output = createOutputCapture(MAX_OUTPUT_BYTES);
@@ -1261,7 +1575,12 @@ var CliGateway = class {
1261
1575
  spawnCli(binary, args) {
1262
1576
  return (this.deps.spawnImpl ?? spawnDsh)(binary, args, this.env);
1263
1577
  }
1264
- /** Start an install; the caller polls {@link status}. */
1578
+ /**
1579
+ * Start an install; the caller polls {@link status}. An application-owned
1580
+ * profile runs it through the official in-process manager instead of the CLI
1581
+ * (see {@link nativeManager}), exactly like {@link update}; the job table,
1582
+ * polling contract and profile verification are identical either way.
1583
+ */
1265
1584
  install(spec) {
1266
1585
  const job = {
1267
1586
  id: `job-${++this.counter}`,
@@ -1277,6 +1596,11 @@ var CliGateway = class {
1277
1596
  this.retainFinished(job.id);
1278
1597
  return { jobId: job.id };
1279
1598
  }
1599
+ const native = this.nativeManager();
1600
+ if (native !== void 0) {
1601
+ this.enqueueNativeInstall(job, native);
1602
+ return { jobId: job.id };
1603
+ }
1280
1604
  this.enqueue(() => this.run(job, [
1281
1605
  "plugin",
1282
1606
  "--profile",
@@ -1286,7 +1610,12 @@ var CliGateway = class {
1286
1610
  ], ADD_TIMEOUT_MS));
1287
1611
  return { jobId: job.id };
1288
1612
  }
1289
- /** Start an in-place npm update; the caller polls {@link status}. */
1613
+ /**
1614
+ * Start an in-place npm update; the caller polls {@link status}. An
1615
+ * application-owned profile runs it through the official in-process manager
1616
+ * instead of the CLI (see {@link nativeManager}), and the job/status/polling
1617
+ * contract the browser half drives is identical either way.
1618
+ */
1290
1619
  update(id, version) {
1291
1620
  const spec = `${id}@${version}`;
1292
1621
  const job = {
@@ -1305,6 +1634,11 @@ var CliGateway = class {
1305
1634
  this.retainFinished(job.id);
1306
1635
  return { jobId: job.id };
1307
1636
  }
1637
+ const native = this.nativeManager();
1638
+ if (native !== void 0) {
1639
+ this.enqueueNativeUpdate(job, native);
1640
+ return { jobId: job.id };
1641
+ }
1308
1642
  this.enqueue(() => this.run(job, [
1309
1643
  "plugin",
1310
1644
  "--profile",
@@ -1314,6 +1648,128 @@ var CliGateway = class {
1314
1648
  ], ADD_TIMEOUT_MS));
1315
1649
  return { jobId: job.id };
1316
1650
  }
1651
+ /** Start an install through the official in-process manager. */
1652
+ enqueueNativeInstall(job, native) {
1653
+ this.enqueue(async () => {
1654
+ try {
1655
+ await this.runNativeInstall(job, native);
1656
+ } catch (error) {
1657
+ job.phase = "error";
1658
+ job.error = `plugin-manager: 官方插件管理器安装失败:${error instanceof Error ? error.message : String(error)}`;
1659
+ }
1660
+ this.retainFinished(job.id);
1661
+ });
1662
+ }
1663
+ /**
1664
+ * Run one install through the official in-process manager (an
1665
+ * application-owned profile, where the CLI refuses to write). The manager
1666
+ * resolves the registry, runs pnpm with the launcher's bundled toolchain and
1667
+ * applies the bundle, then this reads the profile the same way the CLI path
1668
+ * does: the install is only `done` once the profile carries a dependency it
1669
+ * did not carry before, so a green manager call that added nothing is still
1670
+ * reported as a failure. Its resolved verdict is read first
1671
+ * ({@link nativeManagerFailure}): the manager folds a refused run into that
1672
+ * value instead of rejecting, and only the verdict names the reason. The
1673
+ * CLI-specific guards are deliberately absent — the official manager
1674
+ * validates and applies the bundle itself, exactly as it does for the
1675
+ * official Plugins page.
1676
+ * @param job - the install job being settled.
1677
+ * @param native - the official manager.
1678
+ */
1679
+ async runNativeInstall(job, native) {
1680
+ const before = await this.capture();
1681
+ const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
1682
+ enabled: true,
1683
+ requestId: job.id
1684
+ }));
1685
+ if (refusal !== void 0) {
1686
+ job.phase = "error";
1687
+ job.error = `plugin-manager: 官方插件管理器安装失败:${refusal}`;
1688
+ return;
1689
+ }
1690
+ const after = await this.capture();
1691
+ const name = this.newDependency(before, after);
1692
+ if (name === void 0) {
1693
+ job.phase = "error";
1694
+ job.error = "plugin-manager: 官方插件管理器报告成功,但 profile 未新增任何依赖(安装未生效)";
1695
+ return;
1696
+ }
1697
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
1698
+ job.plugin = await buildPluginRow(this.facts, name, manifest.dependencies[name] ?? job.spec, after.layer.rows);
1699
+ job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
1700
+ id: change.id,
1701
+ name: change.id,
1702
+ from: change.from,
1703
+ to: change.to
1704
+ }));
1705
+ job.phase = "done";
1706
+ }
1707
+ /** Start an in-place update through the official in-process manager. */
1708
+ enqueueNativeUpdate(job, native) {
1709
+ this.enqueue(async () => {
1710
+ try {
1711
+ await this.runNativeUpdate(job, native);
1712
+ } catch (error) {
1713
+ job.phase = "error";
1714
+ job.error = `plugin-manager: 官方插件管理器更新失败:${error instanceof Error ? error.message : String(error)}`;
1715
+ }
1716
+ this.retainFinished(job.id);
1717
+ });
1718
+ }
1719
+ /**
1720
+ * Run one update through the official in-process manager (an application-owned
1721
+ * profile, where the CLI refuses to write). The manager resolves the registry,
1722
+ * runs pnpm with the launcher's bundled toolchain and applies the bundle, then
1723
+ * this reads the profile the same way the CLI path does: the dependency must
1724
+ * still be there and the installed version must be the one the route resolved,
1725
+ * so a green manager call that changed nothing is still reported as a failure.
1726
+ * Its resolved verdict is read first ({@link nativeManagerFailure}): a refused
1727
+ * run (pnpm exited non-zero, an incompatible version, a cancellation) resolves
1728
+ * with `application: 'failed'`, and only that verdict carries the reason — the
1729
+ * profile re-read can only show that the version did not move.
1730
+ * @param job - the update job being settled.
1731
+ * @param native - the official manager.
1732
+ */
1733
+ async runNativeUpdate(job, native) {
1734
+ const targetId = job.targetId;
1735
+ const targetVersion = job.targetVersion;
1736
+ if (targetId === void 0 || targetVersion === void 0) {
1737
+ job.phase = "error";
1738
+ job.error = "plugin-manager: update job is missing the target id or version";
1739
+ return;
1740
+ }
1741
+ const before = await this.capture();
1742
+ const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
1743
+ enabled: true,
1744
+ requestId: job.id
1745
+ }));
1746
+ if (refusal !== void 0) {
1747
+ job.phase = "error";
1748
+ job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
1749
+ return;
1750
+ }
1751
+ const after = await this.capture();
1752
+ if (!after.dependencies.includes(targetId)) {
1753
+ job.phase = "error";
1754
+ job.error = `plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)`;
1755
+ return;
1756
+ }
1757
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
1758
+ const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? job.spec, after.layer.rows);
1759
+ if (updated.version !== targetVersion) {
1760
+ job.phase = "error";
1761
+ job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
1762
+ return;
1763
+ }
1764
+ job.plugin = updated;
1765
+ job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
1766
+ id: change.id,
1767
+ name: change.id,
1768
+ from: change.from,
1769
+ to: change.to
1770
+ }));
1771
+ job.phase = "done";
1772
+ }
1317
1773
  /** Start a deterministic legacy aggregate migration. */
1318
1774
  migrate(sourceId, targetId, targetVersion, targetSpec) {
1319
1775
  const job = {
@@ -1347,7 +1803,11 @@ var CliGateway = class {
1347
1803
  });
1348
1804
  return { jobId: job.id };
1349
1805
  }
1350
- /** Start a removal; the caller polls {@link status}. */
1806
+ /**
1807
+ * Start a removal; the caller polls {@link status}. An application-owned
1808
+ * profile removes through the official in-process manager, the same writer
1809
+ * the install and update paths use there (the CLI refuses that profile).
1810
+ */
1351
1811
  remove(id) {
1352
1812
  const job = {
1353
1813
  id: `job-${++this.counter}`,
@@ -1363,6 +1823,11 @@ var CliGateway = class {
1363
1823
  this.retainFinished(job.id);
1364
1824
  return { jobId: job.id };
1365
1825
  }
1826
+ const native = this.nativeManager();
1827
+ if (native !== void 0) {
1828
+ this.enqueueNativeRemove(job, native);
1829
+ return { jobId: job.id };
1830
+ }
1366
1831
  this.enqueue(() => this.run(job, [
1367
1832
  "plugin",
1368
1833
  "--profile",
@@ -1372,6 +1837,51 @@ var CliGateway = class {
1372
1837
  ], REMOVE_TIMEOUT_MS));
1373
1838
  return { jobId: job.id };
1374
1839
  }
1840
+ /** Start a removal through the official in-process manager. */
1841
+ enqueueNativeRemove(job, native) {
1842
+ this.enqueue(async () => {
1843
+ try {
1844
+ await this.runNativeRemove(job, native);
1845
+ } catch (error) {
1846
+ job.phase = "error";
1847
+ job.error = `plugin-manager: 官方插件管理器卸载失败:${error instanceof Error ? error.message : String(error)}`;
1848
+ }
1849
+ this.retainFinished(job.id);
1850
+ });
1851
+ }
1852
+ /**
1853
+ * Run one removal through the official in-process manager (an
1854
+ * application-owned profile, where the CLI refuses to write). The removal is
1855
+ * only `done` once a dependency the profile carried before is gone, exactly
1856
+ * the verification the CLI path performs. Its resolved verdict is read first
1857
+ * ({@link nativeManagerFailure}): a refused removal resolves with
1858
+ * `application: 'failed'` rather than rejecting.
1859
+ * @param job - the removal job being settled.
1860
+ * @param native - the official manager.
1861
+ */
1862
+ async runNativeRemove(job, native) {
1863
+ const before = await this.capture();
1864
+ const refusal = nativeManagerFailure(await native.removeBundle(job.spec));
1865
+ if (refusal !== void 0) {
1866
+ job.phase = "error";
1867
+ job.error = `plugin-manager: 官方插件管理器卸载失败:${refusal}`;
1868
+ return;
1869
+ }
1870
+ const after = await this.capture();
1871
+ if (before.dependencies.find((candidate) => !after.dependencies.includes(candidate)) === void 0) {
1872
+ job.phase = "error";
1873
+ job.error = "plugin-manager: 官方插件管理器报告成功,但依赖仍在 profile 中(卸载未生效)";
1874
+ return;
1875
+ }
1876
+ job.plugin = await this.rowFor("remove", job.spec, before, after);
1877
+ job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
1878
+ id: change.id,
1879
+ name: change.id,
1880
+ from: change.from,
1881
+ to: change.to
1882
+ }));
1883
+ job.phase = "done";
1884
+ }
1375
1885
  /**
1376
1886
  * Read one job's current state (a shallow copy). Finished jobs beyond the
1377
1887
  * ring cap are evicted and read as not-found, the same as an id that never
@@ -2137,7 +2647,7 @@ function makeGatewayRoutes(deps) {
2137
2647
  writeJson(res, 400, { error: unsafeSpec });
2138
2648
  return;
2139
2649
  }
2140
- if (!deps.cliAvailable()) {
2650
+ if (!deps.cliAvailable() && !gateway.usesNativeWriter()) {
2141
2651
  writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
2142
2652
  return;
2143
2653
  }
@@ -2158,7 +2668,7 @@ function makeGatewayRoutes(deps) {
2158
2668
  writeJson(res, 400, { error: unsafe });
2159
2669
  return;
2160
2670
  }
2161
- if (!deps.cliAvailable()) {
2671
+ if (!deps.cliAvailable() && !gateway.usesNativeWriter()) {
2162
2672
  writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
2163
2673
  return;
2164
2674
  }
@@ -2255,7 +2765,7 @@ function makeGatewayRoutes(deps) {
2255
2765
  writeJson(res, 400, { error: unsafeId });
2256
2766
  return;
2257
2767
  }
2258
- if (!deps.cliAvailable()) {
2768
+ if (!deps.cliAvailable() && !gateway.usesNativeWriter()) {
2259
2769
  writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
2260
2770
  return;
2261
2771
  }
@@ -2435,16 +2945,47 @@ const name = "ui-plugin-manager";
2435
2945
  const inject = ["webServer"];
2436
2946
  /** Apply the host half (once per process). */
2437
2947
  const apply = mountOnce("@linxin666/dsh-client-ui-plugin-manager", applyImpl);
2948
+ /**
2949
+ * The launched profile the official runtime publishes on the host context
2950
+ * (`profileContext`, `{ name, dir, patchPath, ... }`). The packaged Desktop
2951
+ * launcher boots "desktop" through `runProfile()` with neither a `--profile`
2952
+ * flag nor a DSH_PROFILE variable, so this service is the only launcher fact
2953
+ * that names the running profile there; a CLI-booted host keeps resolving from
2954
+ * argv and the environment exactly as before. It is an OPTIONAL read, not an
2955
+ * injected dependency: hosts without the service simply fall through.
2956
+ * @param ctx - host plugin context.
2957
+ * @returns the published facts, or undefined when the host publishes none.
2958
+ */
2959
+ function launchedProfile(ctx) {
2960
+ const facts = ctx.get("profileContext");
2961
+ return facts === void 0 || facts === null ? void 0 : facts;
2962
+ }
2963
+ /**
2964
+ * The official in-process plugin manager, when the running host mounts one.
2965
+ * `@deepseek-ai/dsh-plugin-manager` registers itself as the `pluginManager`
2966
+ * service (a TypertRemoteService, which is an ordinary Cordis Service under
2967
+ * that key); this is the same writer the official Plugins page drives, read here
2968
+ * as a contract observation rather than an import — the repository builds
2969
+ * against the official SDK's public packages, and this package must keep
2970
+ * running when a host mounts no manager at all. Only an application-owned
2971
+ * profile uses it (see CliGateway), because there the CLI refuses the profile.
2972
+ * @param ctx - host plugin context.
2973
+ * @returns the manager, or undefined when the host publishes none.
2974
+ */
2975
+ function officialManager(ctx) {
2976
+ const manager = ctx.get("pluginManager");
2977
+ return manager === void 0 || manager === null ? void 0 : manager;
2978
+ }
2438
2979
  function applyImpl(ctx) {
2439
2980
  let facts;
2440
2981
  try {
2441
- facts = resolveProfile();
2982
+ facts = resolveProfile(process.argv, process.env, launchedProfile(ctx));
2442
2983
  } catch (error) {
2443
2984
  console.error("[plugin-manager]", error instanceof Error ? error.message : String(error));
2444
2985
  return;
2445
2986
  }
2446
2987
  if (!profileExists(facts.profileDir)) return;
2447
- const gateway = new CliGateway(facts);
2988
+ const gateway = new CliGateway(facts, process.env, { nativeManager: () => officialManager(ctx) });
2448
2989
  const cliAvailable = () => findDshBinary() !== null;
2449
2990
  ctx.effect(() => {
2450
2991
  const disposers = makeGatewayRoutes({