@linxin666/dsh-client-ui-plugin-manager 0.4.1 → 0.4.3

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, 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,124 @@ 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;
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);
528
654
  }
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);
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(sep).includes("..")) throw new Error(`plugin-manager: published profile directory is not a safe absolute path ${JSON.stringify(launched.dir ?? "")}`);
680
+ if (name !== "" && name !== basename(profileDir)) throw new Error(`plugin-manager: published profile name and directory disagree ${JSON.stringify(name)} vs ${JSON.stringify(profileDir)}`);
681
+ const ownPatchPath = join(profileDir, "cordis.patch.yml");
682
+ const publishedPatchPath = typeof launched.patchPath === "string" ? launched.patchPath.trim() : "";
683
+ if (publishedPatchPath !== "" && publishedPatchPath !== ownPatchPath) throw new Error(`plugin-manager: published patch path is not the launched profile's own patch file ${JSON.stringify(launched.patchPath)}`);
532
684
  return {
533
- profileName: name,
685
+ profileName: name !== "" ? name : basename(profileDir),
686
+ profileDir,
687
+ patchPath: ownPatchPath,
688
+ packageJsonPath: join(profileDir, "package.json"),
689
+ desktop: desktopLauncher
690
+ };
691
+ }
692
+ /** Facts for one explicitly named profile, resolved under `$DSH_HOME/profiles`. */
693
+ function factsFor(name, env, desktop) {
694
+ const trimmed = name.trim();
695
+ assertSafeProfileName(trimmed);
696
+ const profileDir = join(resolveDshHome(env), "profiles", trimmed);
697
+ return {
698
+ profileName: trimmed,
534
699
  profileDir,
535
700
  patchPath: join(profileDir, "cordis.patch.yml"),
536
701
  packageJsonPath: join(profileDir, "package.json"),
@@ -538,6 +703,15 @@ function resolveProfile(argv = process.argv, env = process.env) {
538
703
  };
539
704
  }
540
705
  /**
706
+ * Reject a profile name that is not exactly one directory segment under
707
+ * `profiles/`. `.` is rejected alongside separators and `..`: `join` normalizes
708
+ * it away, so accepting it would silently resolve to the `profiles` directory
709
+ * itself rather than to a profile.
710
+ */
711
+ function assertSafeProfileName(name) {
712
+ if (name === "" || name === "." || name === ".." || name.includes("/") || name.includes("\\")) throw new Error(`plugin-manager: invalid profile name ${JSON.stringify(name)}`);
713
+ }
714
+ /**
541
715
  * Read the profile manifest; a missing or malformed file fails loud.
542
716
  * @param packageJsonPath - absolute path of the profile's package.json.
543
717
  * @returns the parsed bundles and dependencies.
@@ -932,22 +1106,77 @@ function findDshBinary(env = process.env, platform = process.platform, exists =
932
1106
  function capture(chunk, buffer) {
933
1107
  buffer.push(chunk);
934
1108
  }
1109
+ /** Bytes read for the shebang probe (a Node script names its interpreter on line 1). */
1110
+ const SHEBANG_PROBE_BYTES = 256;
1111
+ /**
1112
+ * Read a file's leading bytes for the shebang probe. Every failure — a missing
1113
+ * file, a directory, a permission error, an unreadable asar entry — reads as
1114
+ * "no head", so the caller falls back to spawning the path directly.
1115
+ * @param path - file to probe.
1116
+ * @returns the leading text, or undefined.
1117
+ */
1118
+ function readFileHead(path) {
1119
+ let fd;
1120
+ try {
1121
+ fd = openSync(path, "r");
1122
+ const buffer = Buffer.alloc(SHEBANG_PROBE_BYTES);
1123
+ const read = readSync(fd, buffer, 0, SHEBANG_PROBE_BYTES, 0);
1124
+ return buffer.subarray(0, read).toString("utf8");
1125
+ } catch {
1126
+ return;
1127
+ } finally {
1128
+ if (fd !== void 0) try {
1129
+ closeSync(fd);
1130
+ } catch {}
1131
+ }
1132
+ }
935
1133
  /**
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`).
1134
+ * Whether a resolved CLI path is a Node script: a `.js` module, or a file whose
1135
+ * shebang names node. A Node script cannot be spawned as an executable on its
1136
+ * own: the kernel hands the shebang to the interpreter it names, and
1137
+ * `#!/usr/bin/env node` resolves node through PATH — which a GUI-launched host
1138
+ * (the packaged Desktop app) does not carry, so the child dies before the CLI
1139
+ * starts with `env: node: No such file or directory` (exit 127).
1140
+ * @param path - the resolved CLI path.
1141
+ * @param readHead - head probe (test seam).
1142
+ * @returns true when the path needs a Node interpreter.
1143
+ */
1144
+ function isNodeScript(path, readHead = readFileHead) {
1145
+ if (/\.(?:c|m)?js$/i.test(path)) return true;
1146
+ const head = readHead(path);
1147
+ if (head === void 0) return false;
1148
+ const firstLine = head.split("\n", 1)[0] ?? "";
1149
+ return /^#!.*\bnode\b/.test(firstLine);
1150
+ }
1151
+ /**
1152
+ * The spawn command for the dsh CLI on this platform. A Node script (the
1153
+ * npm/homebrew `dsh` shim, a `.bin` symlink, a packaged `lib/bin.js`) is run
1154
+ * by an interpreter that exists regardless of PATH: a `node` sitting beside the
1155
+ * CLI when the installation ships one (npm-global and homebrew layouts), else
1156
+ * the host's own interpreter — `process.execPath`, which the ELECTRON_RUN_AS_NODE
1157
+ * branch in {@link spawnDsh} covers for an Electron host. Windows additionally
1158
+ * resolves the npm-generated shim into node plus bin.js and spawns them
1159
+ * directly: going through cmd.exe splits unquoted paths with spaces
1160
+ * (`'D:\Program' is not recognized`).
940
1161
  * @param binary - the dsh CLI path found by {@link findDshBinary}.
941
1162
  * @param platform - process platform (test seam).
942
1163
  * @param localNodeExists - existence probe (test seam).
943
1164
  * @param binJsExists - existence probe for the resolved bin script (test seam).
1165
+ * @param readHead - shebang probe (test seam).
944
1166
  * @returns the executable and the argument prefix to run the dsh bin script.
945
1167
  */
946
- function dshSpawnCommand(binary, platform = process.platform, localNodeExists = existsSync, binJsExists = existsSync) {
947
- if (platform !== "win32") return {
948
- command: binary,
949
- argsPrefix: []
950
- };
1168
+ function dshSpawnCommand(binary, platform = process.platform, localNodeExists = existsSync, binJsExists = existsSync, readHead = readFileHead) {
1169
+ if (platform !== "win32") {
1170
+ if (!isNodeScript(binary, readHead)) return {
1171
+ command: binary,
1172
+ argsPrefix: []
1173
+ };
1174
+ const sibling = posix.join(posix.dirname(binary), "node");
1175
+ return {
1176
+ command: localNodeExists(sibling) ? sibling : process.execPath,
1177
+ argsPrefix: [binary]
1178
+ };
1179
+ }
951
1180
  const dir = win32.dirname(binary);
952
1181
  const localNode = win32.join(dir, "node.exe");
953
1182
  if (win32.basename(binary).toLowerCase() === "bin.js") return {
@@ -975,11 +1204,45 @@ function windowsCmdShimArgs(binary, args) {
975
1204
  `""${binary}" ${args.map((arg) => `"${arg}"`).join(" ")}"`
976
1205
  ];
977
1206
  }
978
- /** Spawn the dsh CLI with piped stdio and no shell parsing (see {@link dshSpawnCommand}). */
1207
+ /**
1208
+ * Prepend one directory to a child environment's PATH, collapsing every case
1209
+ * variant of the key into one `PATH`. Windows exposes the variable as `Path`,
1210
+ * and spreading `process.env` into a plain object preserves that spelling:
1211
+ * assigning `env.PATH` beside it would leave two keys whose serialization
1212
+ * drops the system directories (the desktop childEnv defect).
1213
+ * @param env - the environment to copy.
1214
+ * @param dir - directory to put first.
1215
+ * @param platform - process platform (test seam).
1216
+ * @returns a new environment with one normalized, prepended PATH.
1217
+ */
1218
+ function withPrependedPath(env, dir, platform = process.platform) {
1219
+ const separator = platform === "win32" ? ";" : ":";
1220
+ const current = Object.keys(env).filter((key) => key.toUpperCase() === "PATH").map((key) => env[key]).find((value) => value !== void 0 && value !== "") ?? "";
1221
+ const next = {};
1222
+ for (const [key, value] of Object.entries(env)) if (key.toUpperCase() !== "PATH") next[key] = value;
1223
+ next.PATH = current === "" ? dir : `${dir}${separator}${current}`;
1224
+ return next;
1225
+ }
1226
+ /**
1227
+ * Spawn the dsh CLI with piped stdio and no shell parsing (see
1228
+ * {@link dshSpawnCommand}).
1229
+ *
1230
+ * The CLI's own directory goes first on the child PATH: npm-global, homebrew and
1231
+ * packaged layouts keep `node`, `pnpm` and `npx` beside the `dsh` shim, and a
1232
+ * GUI-launched host carries none of them on its own PATH — the CLI forwards
1233
+ * `dsh plugin` to pnpm, so without this the update would start and then fail on
1234
+ * a missing pnpm instead. This mirrors the packaged Desktop launcher, which
1235
+ * prepends its bundled runtime bin to the host it spawns.
1236
+ * @param binary - the resolved dsh CLI path.
1237
+ * @param args - arguments after the interpreter/script prefix.
1238
+ * @param env - the host environment.
1239
+ * @returns the spawned child process.
1240
+ */
979
1241
  function spawnDsh(binary, args, env) {
980
1242
  const { command, argsPrefix } = dshSpawnCommand(binary);
1243
+ const childEnv = withPrependedPath(env, (process.platform === "win32" ? win32 : posix).dirname(binary));
981
1244
  if (process.platform === "win32" && command.toLowerCase().endsWith(".cmd")) return spawn("cmd.exe", windowsCmdShimArgs(command, args), {
982
- env,
1245
+ env: childEnv,
983
1246
  windowsVerbatimArguments: true,
984
1247
  stdio: [
985
1248
  "ignore",
@@ -989,9 +1252,9 @@ function spawnDsh(binary, args, env) {
989
1252
  });
990
1253
  return spawn(command, [...argsPrefix, ...args], {
991
1254
  env: command === process.execPath ? {
992
- ...env,
1255
+ ...childEnv,
993
1256
  ELECTRON_RUN_AS_NODE: "1"
994
- } : env,
1257
+ } : childEnv,
995
1258
  stdio: [
996
1259
  "ignore",
997
1260
  "pipe",
@@ -1084,6 +1347,19 @@ var CliGateway = class {
1084
1347
  binary() {
1085
1348
  return this.deps.findBinary !== void 0 ? this.deps.findBinary(this.env) : findDshBinary(this.env);
1086
1349
  }
1350
+ /**
1351
+ * The official in-process manager to write through, or undefined when the CLI
1352
+ * is the writer. Only an application-owned profile (a packaged Desktop launch)
1353
+ * takes this path: there the CLI refuses the profile outright, while the
1354
+ * official manager — which the launcher configures with its bundled
1355
+ * package-manager invocation — owns the same files this gateway reads. On
1356
+ * every other runtime the CLI stays the single writer, exactly as before.
1357
+ * @returns the manager, or undefined when the CLI should run.
1358
+ */
1359
+ nativeManager() {
1360
+ if (this.facts.desktop !== true) return void 0;
1361
+ return this.deps.nativeManager?.();
1362
+ }
1087
1363
  /** Run one CLI command to completion and return the bounded output. */
1088
1364
  async runCli(binary, args, timeoutMs) {
1089
1365
  const output = createOutputCapture(MAX_OUTPUT_BYTES);
@@ -1286,7 +1562,12 @@ var CliGateway = class {
1286
1562
  ], ADD_TIMEOUT_MS));
1287
1563
  return { jobId: job.id };
1288
1564
  }
1289
- /** Start an in-place npm update; the caller polls {@link status}. */
1565
+ /**
1566
+ * Start an in-place npm update; the caller polls {@link status}. An
1567
+ * application-owned profile runs it through the official in-process manager
1568
+ * instead of the CLI (see {@link nativeManager}), and the job/status/polling
1569
+ * contract the browser half drives is identical either way.
1570
+ */
1290
1571
  update(id, version) {
1291
1572
  const spec = `${id}@${version}`;
1292
1573
  const job = {
@@ -1305,6 +1586,11 @@ var CliGateway = class {
1305
1586
  this.retainFinished(job.id);
1306
1587
  return { jobId: job.id };
1307
1588
  }
1589
+ const native = this.nativeManager();
1590
+ if (native !== void 0) {
1591
+ this.enqueueNativeUpdate(job, native);
1592
+ return { jobId: job.id };
1593
+ }
1308
1594
  this.enqueue(() => this.run(job, [
1309
1595
  "plugin",
1310
1596
  "--profile",
@@ -1314,6 +1600,63 @@ var CliGateway = class {
1314
1600
  ], ADD_TIMEOUT_MS));
1315
1601
  return { jobId: job.id };
1316
1602
  }
1603
+ /** Start an in-place update through the official in-process manager. */
1604
+ enqueueNativeUpdate(job, native) {
1605
+ this.enqueue(async () => {
1606
+ try {
1607
+ await this.runNativeUpdate(job, native);
1608
+ } catch (error) {
1609
+ job.phase = "error";
1610
+ job.error = `plugin-manager: 官方插件管理器更新失败:${error instanceof Error ? error.message : String(error)}`;
1611
+ }
1612
+ this.retainFinished(job.id);
1613
+ });
1614
+ }
1615
+ /**
1616
+ * Run one update through the official in-process manager (an application-owned
1617
+ * profile, where the CLI refuses to write). The manager resolves the registry,
1618
+ * runs pnpm with the launcher's bundled toolchain and applies the bundle, then
1619
+ * this reads the profile the same way the CLI path does: the dependency must
1620
+ * still be there and the installed version must be the one the route resolved,
1621
+ * so a green manager call that changed nothing is still reported as a failure.
1622
+ * @param job - the update job being settled.
1623
+ * @param native - the official manager.
1624
+ */
1625
+ async runNativeUpdate(job, native) {
1626
+ const targetId = job.targetId;
1627
+ const targetVersion = job.targetVersion;
1628
+ if (targetId === void 0 || targetVersion === void 0) {
1629
+ job.phase = "error";
1630
+ job.error = "plugin-manager: update job is missing the target id or version";
1631
+ return;
1632
+ }
1633
+ const before = await this.capture();
1634
+ await native.installBundle(job.spec, {
1635
+ enabled: true,
1636
+ requestId: job.id
1637
+ });
1638
+ const after = await this.capture();
1639
+ if (!after.dependencies.includes(targetId)) {
1640
+ job.phase = "error";
1641
+ job.error = `plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)`;
1642
+ return;
1643
+ }
1644
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
1645
+ const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? job.spec, after.layer.rows);
1646
+ if (updated.version !== targetVersion) {
1647
+ job.phase = "error";
1648
+ job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
1649
+ return;
1650
+ }
1651
+ job.plugin = updated;
1652
+ job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
1653
+ id: change.id,
1654
+ name: change.id,
1655
+ from: change.from,
1656
+ to: change.to
1657
+ }));
1658
+ job.phase = "done";
1659
+ }
1317
1660
  /** Start a deterministic legacy aggregate migration. */
1318
1661
  migrate(sourceId, targetId, targetVersion, targetSpec) {
1319
1662
  const job = {
@@ -2435,16 +2778,47 @@ const name = "ui-plugin-manager";
2435
2778
  const inject = ["webServer"];
2436
2779
  /** Apply the host half (once per process). */
2437
2780
  const apply = mountOnce("@linxin666/dsh-client-ui-plugin-manager", applyImpl);
2781
+ /**
2782
+ * The launched profile the official runtime publishes on the host context
2783
+ * (`profileContext`, `{ name, dir, patchPath, ... }`). The packaged Desktop
2784
+ * launcher boots "desktop" through `runProfile()` with neither a `--profile`
2785
+ * flag nor a DSH_PROFILE variable, so this service is the only launcher fact
2786
+ * that names the running profile there; a CLI-booted host keeps resolving from
2787
+ * argv and the environment exactly as before. It is an OPTIONAL read, not an
2788
+ * injected dependency: hosts without the service simply fall through.
2789
+ * @param ctx - host plugin context.
2790
+ * @returns the published facts, or undefined when the host publishes none.
2791
+ */
2792
+ function launchedProfile(ctx) {
2793
+ const facts = ctx.get("profileContext");
2794
+ return facts === void 0 || facts === null ? void 0 : facts;
2795
+ }
2796
+ /**
2797
+ * The official in-process plugin manager, when the running host mounts one.
2798
+ * `@deepseek-ai/dsh-plugin-manager` registers itself as the `pluginManager`
2799
+ * service (a TypertRemoteService, which is an ordinary Cordis Service under
2800
+ * that key); this is the same writer the official Plugins page drives, read here
2801
+ * as a contract observation rather than an import — the repository builds
2802
+ * against the official SDK's public packages, and this package must keep
2803
+ * running when a host mounts no manager at all. Only an application-owned
2804
+ * profile uses it (see CliGateway), because there the CLI refuses the profile.
2805
+ * @param ctx - host plugin context.
2806
+ * @returns the manager, or undefined when the host publishes none.
2807
+ */
2808
+ function officialManager(ctx) {
2809
+ const manager = ctx.get("pluginManager");
2810
+ return manager === void 0 || manager === null ? void 0 : manager;
2811
+ }
2438
2812
  function applyImpl(ctx) {
2439
2813
  let facts;
2440
2814
  try {
2441
- facts = resolveProfile();
2815
+ facts = resolveProfile(process.argv, process.env, launchedProfile(ctx));
2442
2816
  } catch (error) {
2443
2817
  console.error("[plugin-manager]", error instanceof Error ? error.message : String(error));
2444
2818
  return;
2445
2819
  }
2446
2820
  if (!profileExists(facts.profileDir)) return;
2447
- const gateway = new CliGateway(facts);
2821
+ const gateway = new CliGateway(facts, process.env, { nativeManager: () => officialManager(ctx) });
2448
2822
  const cliAvailable = () => findDshBinary() !== null;
2449
2823
  ctx.effect(() => {
2450
2824
  const disposers = makeGatewayRoutes({
@@ -0,0 +1,70 @@
1
+ import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
2
+ import type { InstallProgressItem, PluginUpdateItem } from '../core/protocol.ts';
3
+ /** One loader row of a bundle, as the official page's subject carries it. */
4
+ export interface PluginPageRowRef {
5
+ rowId: string;
6
+ moduleName: string;
7
+ enabled: boolean;
8
+ }
9
+ /** One bundle, as the official page's subject carries it. */
10
+ export interface PluginPageBundleRef {
11
+ name: string;
12
+ version?: string;
13
+ installed: boolean;
14
+ enabled: boolean;
15
+ rows: readonly PluginPageRowRef[];
16
+ }
17
+ /**
18
+ * The subject the official Plugins page renders a contributed section with:
19
+ * its bundle page, its row page, or an official plugin's page. This package
20
+ * only speaks to the bundle case.
21
+ */
22
+ export type PluginPageSubject = {
23
+ kind: 'bundle';
24
+ pkg: PluginPageBundleRef;
25
+ } | {
26
+ kind: 'row';
27
+ pkg: PluginPageBundleRef;
28
+ row: PluginPageRowRef;
29
+ } | {
30
+ kind: 'item';
31
+ id: string;
32
+ };
33
+ declare module '@deepseek-ai/dsh-client-ui-slots' {
34
+ interface SlotMap {
35
+ /**
36
+ * One section contributed under a Plugins page's own content. Declared at
37
+ * runtime by the official plugin-manager page's `main` registration; the
38
+ * type is re-declared here, identically, so this package can register into
39
+ * it without importing the page (the same way family plugins re-declare
40
+ * `plugins.bundle.config`).
41
+ */
42
+ 'plugins.detail.section': {
43
+ kind: 'list';
44
+ scope: 'root';
45
+ owner: {
46
+ subject: PluginPageSubject;
47
+ };
48
+ };
49
+ }
50
+ }
51
+ /** Registration-side wire face the patch consumes. */
52
+ export interface PluginUpdatePatchInjected {
53
+ /** Whether this browser has loopback authority to use the host routes. */
54
+ isLoopback: boolean;
55
+ /** Compare every installed plugin against the version its source serves. */
56
+ checkUpdates: () => Promise<PluginUpdateItem[]>;
57
+ /** Re-install one plugin from its recorded source. */
58
+ update: (id: string) => Promise<unknown>;
59
+ /** Read the current install/update progress. */
60
+ status: () => Promise<InstallProgressItem>;
61
+ }
62
+ /** Full component props assembled by the Plugins page's section renderer. */
63
+ export type PluginUpdatePatchProps = PropsRuntime<'plugins.detail.section'> & PropsLocale<'settings.pluginManager'> & InjectFace<PluginUpdatePatchInjected>;
64
+ /**
65
+ * The update block on one official Plugins page: one check action, the verdict
66
+ * for this page's bundle, and the update action it unlocks. The check is
67
+ * explicit rather than automatic because one check reads every installed
68
+ * plugin's registry manifest; a page visit must not fan that out.
69
+ */
70
+ export declare function PluginUpdatePatch(props: PluginUpdatePatchProps): import("react").JSX.Element | null;