@michengai/dsh-codex-ui 2.0.20 → 2.0.21

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.mjs CHANGED
@@ -1,10 +1,8 @@
1
1
  import { n as resolveCurrentProfile, r as CODEX_UI_API_ENDPOINTS } from "./profile-resolver-BkTv7lmZ.mjs";
2
- import { spawn } from "node:child_process";
3
2
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
- import { readFile, rm, unlink, writeFile } from "node:fs/promises";
3
+ import { readFile } from "node:fs/promises";
5
4
  import { homedir } from "node:os";
6
- import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
7
- import { fileURLToPath } from "node:url";
5
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
6
  //#region src/npm-downloads.ts
9
7
  /** 关于页使用的 npm 累计下载量;历史不完整时返回 undefined,不把局部统计当总量。 */
10
8
  const cache = /* @__PURE__ */ new Map();
@@ -83,9 +81,6 @@ async function query(packageName) {
83
81
  return;
84
82
  }
85
83
  }
86
- //#endregion
87
- //#region src/dependencies.ts
88
- const SUITE_PACKAGE = "@michengai/dsh-codex-suite";
89
84
  const SUITE_MEMBER_PACKAGES = [
90
85
  "@michengai/dsh-archive-manager",
91
86
  "@michengai/dsh-codex-ui",
@@ -149,10 +144,6 @@ function managedDependency(id) {
149
144
  }
150
145
  //#endregion
151
146
  //#region src/dependency-manager.ts
152
- const PROFILE_PENDING_UPDATES_FILE = ".dsh-pending-updates.json";
153
- const APPLY_PLUGIN_UPDATES_IPC = "apply-plugin-updates";
154
- const PLUGIN_INSTALL_TIMEOUT_MS = 6e5;
155
- const PLUGIN_MOUNT_TIMEOUT_MS = 15e3;
156
147
  function optionalService(ctx, name) {
157
148
  if (ctx === void 0) return void 0;
158
149
  return typeof ctx.get === "function" ? ctx.get(name) : ctx[name];
@@ -168,194 +159,65 @@ function profileNameFromArgv(argv) {
168
159
  }
169
160
  return argv[2] === "web" ? "web" : void 0;
170
161
  }
162
+ function detectHostRuntimeRoot(env) {
163
+ if (typeof env.DSH_RUNTIME_DIR === "string" && isAbsolute(env.DSH_RUNTIME_DIR)) return resolve(env.DSH_RUNTIME_DIR);
164
+ }
171
165
  /**
172
- * Desktop 通过可选 Host service 暴露当前 profile;普通 Web/CLI 继续使用
173
- * DSH_PROFILE_DIR、命令行 profile 与默认 web profile。
166
+ * 运行时解析:优先通过宿主官方 profileContext 服务提取当前 Profile,
167
+ * 不再自建 CLI 探测与包管理 spawn。
174
168
  */
175
169
  function resolveDependencyRuntime(ctx, options = {}) {
176
170
  const env = options.env ?? process.env;
177
171
  const argv = options.argv ?? process.argv;
178
- const cwd = options.cwd ?? process.cwd();
179
172
  const home = options.homeDir ?? homedir();
173
+ const profileContext = optionalService(ctx, "profileContext");
174
+ const pluginManager = optionalService(ctx, "pluginManager");
175
+ if (profileContext !== void 0) {
176
+ if (typeof profileContext.dir !== "string" || !isAbsolute(profileContext.dir)) throw new Error("DSH 当前 Profile 路径无效,请重启 DSH 后重试。");
177
+ const profileDir = resolve(profileContext.dir);
178
+ const profileName = validProfileName(profileContext.name) ? profileContext.name : validProfileName(basename(profileDir)) ? basename(profileDir) : "web";
179
+ const detectedRoot = detectHostRuntimeRoot(env);
180
+ return {
181
+ environmentKind: profileName === "desktop" ? "desktop" : "cli",
182
+ profileName,
183
+ profileDir,
184
+ runtimeRoots: detectedRoot !== void 0 ? [detectedRoot] : [],
185
+ ...pluginManager === void 0 ? {} : { pluginManager }
186
+ };
187
+ }
180
188
  const profiles = optionalService(ctx, "desktopProfiles");
181
- const desktopPnpm = optionalService(ctx, "desktopPnpm");
182
- if (profiles === void 0 && desktopPnpm !== void 0) throw new Error("DSH Desktop Profile 服务尚未就绪,请重启 Desktop 后重试。");
183
189
  if (profiles !== void 0) {
184
190
  const current = profiles.current;
185
191
  if (!validProfileName(current?.name) || typeof current.dir !== "string" || !isAbsolute(current.dir)) throw new Error("DSH Desktop 当前 Profile 信息无效,请重启 Desktop 后重试。");
186
- if (typeof desktopPnpm?.runPlugin !== "function") throw new Error("DSH Desktop 包管理服务尚未就绪,请重启 Desktop 后重试。");
187
192
  const profileDir = resolve(current.dir);
188
- const runtimeRoots = typeof env.DSH_RUNTIME_DIR === "string" && isAbsolute(env.DSH_RUNTIME_DIR) ? [resolve(env.DSH_RUNTIME_DIR)] : [];
193
+ const detectedRoot = detectHostRuntimeRoot(env);
194
+ const runtimeRoots = detectedRoot !== void 0 ? [detectedRoot] : [];
189
195
  return {
190
196
  environmentKind: "desktop",
191
197
  profileName: current.name,
192
198
  profileDir,
193
199
  runtimeRoots,
194
- desktopPnpm
200
+ ...pluginManager === void 0 ? {} : { pluginManager }
195
201
  };
196
202
  }
197
- const launched = optionalService(ctx, "profileContext");
198
- const launchedDir = typeof launched?.dir === "string" && isAbsolute(launched.dir) ? resolve(launched.dir) : void 0;
199
- const launchedName = validProfileName(launched?.name) ? launched.name : void 0;
200
- const hostProfileDir = isOfficialDesktopHostEntry(argv[1]) && existsSync(resolve(cwd, "package.json")) ? resolve(cwd) : void 0;
201
- const profileDir = launchedDir ?? hostProfileDir ?? resolve(env.DSH_PROFILE_DIR ?? resolve(home, ".dsh", "profiles", "web"));
203
+ const profileDir = resolve(env.DSH_PROFILE_DIR ?? resolve(home, ".dsh", "profiles", "web"));
202
204
  const selected = profileNameFromArgv(argv);
203
- const profileName = launchedName ?? (validProfileName(selected) ? selected : validProfileName(basename(profileDir)) ? basename(profileDir) : "web");
204
- const cliEntry = resolveCliFromInstallAnchor(launched?.installAnchor) ?? resolveCliBesideDesktopHost(argv[1]);
205
- const cliRuntimeRoot = argv[1] === void 0 ? void 0 : resolveDshRuntimeRoot(argv[1], cwd);
206
- const anchorRoot = cliEntry === void 0 ? void 0 : resolveDshRuntimeRoot(cliEntry);
207
- const runtimeRoots = [
208
- env.DSH_RUNTIME_DIR,
209
- anchorRoot,
210
- cliRuntimeRoot
211
- ].filter((root) => root !== void 0 && root !== "");
212
- const pluginEnv = stringEnvironment(launched?.packageManager?.env);
213
- const packageManager = profilePackageManager(launched?.packageManager) ?? desktopPackageManagerFromArgv(argv);
205
+ const profileName = validProfileName(selected) ? selected : validProfileName(basename(profileDir)) ? basename(profileDir) : "web";
206
+ const detectedRoot = detectHostRuntimeRoot(env);
214
207
  return {
215
208
  environmentKind: "cli",
216
209
  profileName,
217
210
  profileDir,
218
- runtimeRoots,
219
- ...cliEntry === void 0 ? {} : { cliEntry },
220
- ...pluginEnv === void 0 ? {} : { pluginEnv },
221
- ...packageManager === void 0 ? {} : { packageManager }
211
+ runtimeRoots: detectedRoot !== void 0 ? [detectedRoot] : [],
212
+ ...pluginManager === void 0 ? {} : { pluginManager }
222
213
  };
223
214
  }
224
- function profilePackageManager(value) {
225
- if (typeof value?.command !== "string" || value.command === "") return void 0;
226
- if (!Array.isArray(value.args) || !value.args.every((item) => typeof item === "string")) return void 0;
227
- const env = stringEnvironment(value.env);
228
- return {
229
- command: value.command,
230
- args: value.args,
231
- ...env === void 0 ? {} : { env }
232
- };
233
- }
234
- /** 官方 Desktop Host 把 pnpm 入口放在 argv[5],bin 放在 argv[6],不提供 desktopPnpm。 */
235
- function desktopPackageManagerFromArgv(argv, command = process.execPath) {
236
- if (!isOfficialDesktopHostEntry(argv[1])) return void 0;
237
- const pnpm = argv[5];
238
- if (typeof pnpm !== "string" || !isAbsolute(pnpm) || !existsSync(pnpm)) return void 0;
239
- const bin = argv[6];
240
- const path = typeof bin === "string" && bin !== "" ? `${bin}${delimiter}${process.env.PATH ?? ""}` : process.env.PATH;
241
- return {
242
- command,
243
- args: ["--expose-internals", pnpm],
244
- env: {
245
- ELECTRON_RUN_AS_NODE: "1",
246
- ...typeof path === "string" && path !== "" ? { PATH: path } : {}
247
- }
248
- };
249
- }
250
- function stringEnvironment(value) {
251
- if (value === null || typeof value !== "object") return void 0;
252
- const env = {};
253
- for (const [key, item] of Object.entries(value)) if (typeof item === "string") env[key] = item;
254
- return Object.keys(env).length === 0 ? void 0 : env;
255
- }
256
- /** 从公开 profileContext.installAnchor 读出 dsh bin,不把 Desktop Host 入口当成 CLI。 */
257
- function resolveCliFromInstallAnchor(anchor) {
258
- if (typeof anchor !== "string" || anchor === "" || !isAbsolute(anchor)) return void 0;
259
- try {
260
- const bin = JSON.parse(readFileSync(anchor, "utf8")).bin;
261
- const relative = typeof bin === "string" ? bin : bin !== null && typeof bin === "object" && typeof bin.dsh === "string" ? bin.dsh : void 0;
262
- if (relative === void 0 || relative === "") return void 0;
263
- const entry = resolve(dirname(anchor), relative);
264
- return existsSync(entry) ? entry : void 0;
265
- } catch {
266
- return;
267
- }
268
- }
269
- /** 官方 Desktop Host 是 Electron 的 IPC 子进程;父进程只接受带 type 的事件。 */
270
- function isOfficialDesktopHostEntry(entry = process.argv[1]) {
271
- if (entry === void 0 || entry === "") return false;
272
- return entry.replaceAll("\\", "/").includes("/dsh-desktop-host/");
273
- }
274
- /** 从公开包布局定位同一次安装里的 dsh CLI,不读取 launcher 私有 service。 */
275
- function resolveCliBesideDesktopHost(entry = process.argv[1]) {
276
- if (!isOfficialDesktopHostEntry(entry)) return void 0;
277
- const index = entry.replaceAll("\\", "/").toLowerCase().lastIndexOf("/node_modules/@deepseek-ai/dsh-desktop-host/");
278
- if (index < 0) return void 0;
279
- return resolveCliFromInstallAnchor(resolve(entry.slice(0, index), "node_modules", "@deepseek-ai", "dsh", "package.json"));
280
- }
281
215
  function profileDirectory(runtime) {
282
216
  return runtime.profileDir;
283
217
  }
284
- async function readProfileManifest(runtime) {
285
- try {
286
- return JSON.parse(await readFile(resolve(profileDirectory(runtime), "package.json"), "utf8"));
287
- } catch (error) {
288
- if (error.code === "ENOENT") return {};
289
- throw error;
290
- }
291
- }
292
- async function declaredPluginNames(runtime) {
293
- const manifest = await readProfileManifest(runtime);
294
- return [.../* @__PURE__ */ new Set([...Object.keys({
295
- ...manifest.devDependencies,
296
- ...manifest.dependencies
297
- }), ...manifest.dsh?.profile?.bundles ?? []])];
298
- }
299
- /** 真正挂进 Profile 的插件名单;残留 node_modules 或仅写在 dependencies 里都不算。 */
300
- async function profileBundleNames(runtime) {
301
- return (await readProfileManifest(runtime)).dsh?.profile?.bundles ?? [];
302
- }
303
- /** 安装缺失插件前移除卸载遗留的目录或 Junction;已挂载插件绝不触碰。 */
304
- async function removeUnmountedPackagePath(packageName, runtime) {
305
- if (!MANAGED_DEPENDENCIES.some((dependency) => dependency.packageName === packageName)) throw new Error("不支持清理该依赖。");
306
- if (isManagedPackageDeclared(packageName, await profileBundleNames(runtime))) return;
307
- const packagePath = resolve(profileDirectory(runtime), "node_modules", ...packageName.split("/"));
308
- await rm(packagePath, {
309
- recursive: true,
310
- force: true,
311
- maxRetries: 2,
312
- retryDelay: 50
313
- });
314
- }
315
- /** 单独更新子插件时先卸套件,避免两套 patch 冲突。 */
316
- function pluginsToRemoveBeforeInstall(declared, installing) {
317
- if (SUITE_MEMBER_PACKAGES.includes(installing) && declared.includes("@michengai/dsh-codex-suite")) return [SUITE_PACKAGE];
318
- if (installing === "@michengai/dsh-codex-suite") return SUITE_MEMBER_PACKAGES.filter((name) => declared.includes(name));
319
- return [];
320
- }
321
- /** 点击哪个包就更新哪个包,不再把子插件重定向到套件。 */
322
- function resolveDshPluginTarget(installing, _declared = []) {
323
- return installing;
324
- }
325
- function isOfficialRuntimePackage(packageName) {
326
- return packageName === "@deepseek-ai/dsh" || packageName.startsWith("@deepseek-ai/dsh-");
327
- }
328
- /** 从全局 npm 安装的 dsh CLI 入口反推出包含 node_modules 的运行时目录;源码启动不匹配该目录结构。 */
329
- function resolveDshRuntimeRoot(entry = process.argv[1], cwd = process.cwd()) {
330
- if (entry === void 0 || entry === "") return void 0;
331
- const cliEntry = resolveDshCliEntry(entry, cwd);
332
- const marker = [
333
- "node_modules",
334
- "@deepseek-ai",
335
- "dsh"
336
- ].join(sep);
337
- const index = cliEntry.toLowerCase().lastIndexOf(marker.toLowerCase());
338
- if (index === -1) return void 0;
339
- const end = index + marker.length;
340
- if (end !== cliEntry.length && cliEntry[end] !== sep) return void 0;
341
- const root = cliEntry.slice(0, index);
342
- return root.endsWith(sep) ? root.slice(0, -1) : root;
343
- }
344
- function packageLookupRoots(packageName, runtime) {
345
- if (!isOfficialRuntimePackage(packageName)) return [profileDirectory(runtime)];
346
- return [.../* @__PURE__ */ new Set([...runtime.runtimeRoots, profileDirectory(runtime)])];
347
- }
348
- async function installedPackageVersion(packageName, runtime) {
349
- for (const root of packageLookupRoots(packageName, runtime)) try {
350
- const manifest = JSON.parse(await readFile(resolve(root, "node_modules", ...packageName.split("/"), "package.json"), "utf8"));
351
- if (typeof manifest.version === "string" && manifest.version !== "") return manifest.version;
352
- } catch (error) {
353
- if (error.code !== "ENOENT") throw error;
354
- }
355
- }
356
- /** 磁盘有包且仍在 profile 声明里,才算已安装。卸载后残留的 node_modules 不算。 */
218
+ /** 卸载后残留的 node_modules 在 bundles 清除后不得继续标为已安装。 */
357
219
  function isManagedPackageInstalled(input) {
358
- return input.declared && input.installedVersion !== void 0 && input.installedVersion !== "";
220
+ return input.declared && input.installedVersion !== void 0;
359
221
  }
360
222
  /** 旧 Suite 对其六个成员拥有声明权;迁移成直接依赖前也应显示真实安装版本。 */
361
223
  function isManagedPackageDeclared(packageName, declared) {
@@ -366,255 +228,132 @@ function directPackagesForInstall(requested, declared) {
366
228
  const migrateSuite = declared.includes("@michengai/dsh-codex-suite") && requested.some((packageName) => SUITE_MEMBER_PACKAGES.includes(packageName));
367
229
  return [...new Set(migrateSuite ? [...SUITE_MEMBER_PACKAGES, ...requested] : requested)];
368
230
  }
369
- /** npm latest 查询缓存有效期:避免每次打开“关于”页都打 7 个 registry 请求。 */
370
- const LATEST_CACHE_TTL_MS = 3e5;
371
- const latestCache = /* @__PURE__ */ new Map();
372
- function cacheKey(packageName, tag) {
373
- return packageName + "@" + tag;
374
- }
375
- async function npmTaggedVersion(packageName, tag) {
376
- const key = cacheKey(packageName, tag);
377
- const hit = latestCache.get(key);
378
- if (hit !== void 0 && Date.now() - hit.at < LATEST_CACHE_TTL_MS) return hit.version;
379
- try {
380
- const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageName)}/${tag}`, { signal: AbortSignal.timeout(5e3) });
381
- if (!response.ok) return void 0;
382
- const manifest = await response.json();
383
- if (typeof manifest.version !== "string") return void 0;
384
- latestCache.set(key, {
385
- version: manifest.version,
386
- at: Date.now()
387
- });
388
- return manifest.version;
389
- } catch {
390
- return;
391
- }
392
- }
393
- async function npmLatestVersion(packageName) {
394
- if (isOfficialRuntimePackage(packageName)) return await npmTaggedVersion(packageName, "next") ?? await npmTaggedVersion(packageName, "latest");
395
- return npmTaggedVersion(packageName, "latest");
396
- }
397
- /**
398
- * pnpm 11 会在首次解析带 install script 的传递依赖时中止并写入占位值。
399
- * 这些依赖的运行时不需要 postinstall,因此在调用 DSH plugin add 之前显式
400
- * 记录拒绝执行,保证“关于”页单独安装和 Suite Installer 行为一致。
401
- */
402
- function applyRequiredBuildPolicies(source) {
403
- const eol = source.includes("\r\n") ? "\r\n" : "\n";
404
- const lines = source.split(/\r?\n/);
405
- const start = lines.findIndex((line) => line === "allowBuilds:");
406
- if (start === -1) return `${source}${source === "" || source.endsWith("\n") ? "" : eol}allowBuilds:${eol} protobufjs: false${eol} koffi: false${eol}`;
407
- let end = start + 1;
408
- while (end < lines.length && (lines[end] === "" || /^\s/.test(lines[end]))) end += 1;
409
- const body = lines.slice(start + 1, end).filter((line) => !/^\s{2}(?:protobufjs|koffi):/.test(line));
410
- lines.splice(start + 1, end - start - 1, " protobufjs: false", " koffi: false", ...body);
411
- return lines.join(eol);
412
- }
413
- async function ensureRequiredBuildPolicies(runtime) {
414
- const path = resolve(profileDirectory(runtime), "pnpm-workspace.yaml");
415
- let source;
416
- try {
417
- source = await readFile(path, "utf8");
418
- } catch (error) {
419
- if (error.code !== "ENOENT") throw error;
420
- source = "";
421
- }
422
- const next = applyRequiredBuildPolicies(source);
423
- if (next !== source) await writeFile(path, next, "utf8");
424
- }
425
231
  function parseSemver(version) {
426
- const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
427
- if (match === null) return void 0;
232
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(version.trim());
233
+ if (!match) return void 0;
428
234
  return {
429
- core: [
430
- Number(match[1]),
431
- Number(match[2]),
432
- Number(match[3])
433
- ],
434
- prerelease: match[4] === void 0 ? [] : match[4].split(".")
235
+ major: Number(match[1]),
236
+ minor: Number(match[2]),
237
+ patch: Number(match[3]),
238
+ prerelease: match[4] ?? ""
435
239
  };
436
240
  }
437
- function comparePrerelease(left, right) {
438
- if (left.length === 0 || right.length === 0) return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
439
- const length = Math.max(left.length, right.length);
440
- for (let index = 0; index < length; index += 1) {
441
- const a = left[index];
442
- const b = right[index];
443
- if (a === void 0 || b === void 0) return a === b ? 0 : a === void 0 ? -1 : 1;
444
- if (a === b) continue;
445
- const aNumeric = /^\d+$/.test(a);
446
- const bNumeric = /^\d+$/.test(b);
447
- if (aNumeric && bNumeric) return Number(a) > Number(b) ? 1 : -1;
448
- if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
449
- return a > b ? 1 : -1;
241
+ function comparePrerelease(a, b) {
242
+ if (a === "" && b === "") return 0;
243
+ if (a === "") return 1;
244
+ if (b === "") return -1;
245
+ const partsA = a.split(".");
246
+ const partsB = b.split(".");
247
+ const len = Math.max(partsA.length, partsB.length);
248
+ for (let i = 0; i < len; i += 1) {
249
+ const itemA = partsA[i];
250
+ const itemB = partsB[i];
251
+ if (itemA === void 0) return -1;
252
+ if (itemB === void 0) return 1;
253
+ const isNumA = /^\d+$/.test(itemA);
254
+ const isNumB = /^\d+$/.test(itemB);
255
+ if (isNumA && isNumB) {
256
+ const numA = Number(itemA);
257
+ const numB = Number(itemB);
258
+ if (numA !== numB) return numA > numB ? 1 : -1;
259
+ continue;
260
+ }
261
+ if (isNumA && !isNumB) return -1;
262
+ if (!isNumA && isNumB) return 1;
263
+ if (itemA !== itemB) return itemA > itemB ? 1 : -1;
450
264
  }
451
265
  return 0;
452
266
  }
453
267
  function newerVersion(installed, latest) {
454
- const current = parseSemver(installed);
455
- const candidate = parseSemver(latest);
456
- if (current === void 0 || candidate === void 0) return false;
457
- for (let index = 0; index < current.core.length; index += 1) if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index];
458
- return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
268
+ const parsedInstalled = parseSemver(installed);
269
+ const parsedLatest = parseSemver(latest);
270
+ if (!parsedInstalled || !parsedLatest) return false;
271
+ if (parsedLatest.major !== parsedInstalled.major) return parsedLatest.major > parsedInstalled.major;
272
+ if (parsedLatest.minor !== parsedInstalled.minor) return parsedLatest.minor > parsedInstalled.minor;
273
+ if (parsedLatest.patch !== parsedInstalled.patch) return parsedLatest.patch > parsedInstalled.patch;
274
+ return comparePrerelease(parsedLatest.prerelease, parsedInstalled.prerelease) > 0;
459
275
  }
460
- /** 返回当前 profile 中固定管理插件的实际安装版本与 npm latest 状态。 */
461
- async function dependencyStatuses(runtime = resolveDependencyRuntime()) {
462
- const bundleNames = await profileBundleNames(runtime);
463
- return Promise.all(MANAGED_DEPENDENCIES.map(async (entry) => {
464
- const [status, totalDownloads] = await Promise.all([readStatus(entry), npmTotalDownloads(entry.packageName)]);
465
- return {
466
- ...status,
467
- totalDownloads
468
- };
469
- }));
470
- async function readStatus(dependency) {
471
- const version = await installedPackageVersion(dependency.packageName, runtime);
472
- if (version === void 0 && runtime.environmentKind === "desktop" && isOfficialRuntimePackage(dependency.packageName)) return {
473
- ...dependency,
474
- installed: true,
475
- updateAvailable: false
476
- };
477
- const declared = isOfficialRuntimePackage(dependency.packageName) || isManagedPackageDeclared(dependency.packageName, bundleNames);
478
- if (version === void 0 || !isManagedPackageInstalled({
479
- installedVersion: version,
480
- declared
481
- })) return {
482
- ...dependency,
483
- installed: false,
484
- updateAvailable: false
485
- };
486
- const latestVersion = await npmLatestVersion(dependency.packageName);
487
- return {
488
- ...dependency,
489
- installed: true,
490
- version,
491
- latestVersion,
492
- updateAvailable: latestVersion !== void 0 && newerVersion(version, latestVersion)
493
- };
494
- }
495
- }
496
- /**
497
- * 把当前进程的 CLI 入口收成绝对路径。源码启动时 argv[1] 常是相对路径,
498
- * 若再把 cwd 切到 dirname(entry),子进程会去错误目录找 bin.ts。
499
- */
500
- function resolveDshCliEntry(entry = process.argv[1], cwd = process.cwd()) {
501
- if (entry === void 0 || entry === "") throw new Error("无法定位 DSH CLI。请从 DSH 命令启动 Web 服务后重试。");
502
- if (entry.startsWith("file:")) return fileURLToPath(entry);
503
- return resolve(cwd, entry);
504
- }
505
- function requestDesktopHotUpdate(send = process.send) {
506
- if (typeof send !== "function") return false;
276
+ async function npmLatestVersion(packageName) {
277
+ const url = `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`;
507
278
  try {
508
- if (send === process.send) {
509
- if (process.connected !== true) return false;
510
- process.send?.(APPLY_PLUGIN_UPDATES_IPC);
511
- } else send(APPLY_PLUGIN_UPDATES_IPC);
512
- return true;
279
+ const response = await fetch(url, {
280
+ headers: { accept: "application/json" },
281
+ signal: AbortSignal.timeout(5e3)
282
+ });
283
+ if (!response.ok) return void 0;
284
+ const data = await response.json();
285
+ return typeof data.version === "string" && data.version !== "" ? data.version : void 0;
513
286
  } catch {
514
- return false;
287
+ return;
515
288
  }
516
289
  }
517
- /** Desktop 的包管理服务会自行安排重载;只有父进程能识别该消息的独立 Web 子进程才通知。 */
518
- function canRequestParentReload(runtime, send = process.send, entry = process.argv[1]) {
519
- return runtime.environmentKind === "cli" && !isOfficialDesktopHostEntry(entry) && typeof send === "function" && (send !== process.send || process.connected === true);
520
- }
521
- /** 响应已经发出后再通知父进程;通知失败不能变成未捕获异常。 */
522
- function scheduleParentPluginReload(delayMs = 150) {
523
- setTimeout(() => {
524
- try {
525
- requestDesktopHotUpdate();
526
- } catch {}
527
- }, delayMs).unref?.();
528
- }
529
- async function recordPendingUpdate(packageName, version, runtime) {
530
- const pendingPath = resolve(profileDirectory(runtime), PROFILE_PENDING_UPDATES_FILE);
531
- let packages = [];
290
+ async function profileBundleNames(runtime) {
291
+ const directory = profileDirectory(runtime);
292
+ const manifestPath = join(directory, "package.json");
293
+ if (!existsSync(manifestPath)) return [];
532
294
  try {
533
- const parsed = JSON.parse(await readFile(pendingPath, "utf8"));
534
- if (Array.isArray(parsed.packages)) packages = parsed.packages.flatMap((item) => {
535
- if (item === null || typeof item !== "object") return [];
536
- const record = item;
537
- if (typeof record.packageName !== "string" || typeof record.version !== "string") return [];
538
- return [{
539
- packageName: record.packageName,
540
- version: record.version
541
- }];
542
- });
543
- } catch (error) {
544
- if (error.code !== "ENOENT") throw error;
295
+ const bundles = JSON.parse(await readFile(manifestPath, "utf8")).dsh?.profile?.bundles;
296
+ return Array.isArray(bundles) && bundles.every((b) => typeof b === "string") ? bundles : [];
297
+ } catch {
298
+ return [];
545
299
  }
546
- packages = packages.filter((item) => item.packageName !== packageName);
547
- packages.push({
548
- packageName,
549
- version
550
- });
551
- await writeFile(pendingPath, `${JSON.stringify({ packages }, void 0, 2)}\n`, "utf8");
552
300
  }
553
- async function removePendingUpdate(packageName, runtime) {
554
- const pendingPath = resolve(profileDirectory(runtime), PROFILE_PENDING_UPDATES_FILE);
301
+ async function declaredPluginNames(runtime) {
302
+ const bundles = await profileBundleNames(runtime);
303
+ const directory = profileDirectory(runtime);
304
+ const manifestPath = join(directory, "package.json");
305
+ if (!existsSync(manifestPath)) return bundles;
555
306
  try {
556
- const parsed = JSON.parse(await readFile(pendingPath, "utf8"));
557
- if (!Array.isArray(parsed.packages)) return;
558
- const packages = parsed.packages.filter((item) => item === null || typeof item !== "object" || item.packageName !== packageName);
559
- if (packages.length === parsed.packages.length) return;
560
- if (packages.length === 0) {
561
- await unlink(pendingPath);
562
- return;
563
- }
564
- await writeFile(pendingPath, `${JSON.stringify({ packages }, void 0, 2)}\n`, "utf8");
565
- } catch (error) {
566
- if (error.code !== "ENOENT") throw error;
307
+ const deps = JSON.parse(await readFile(manifestPath, "utf8")).dependencies;
308
+ const names = deps !== null && typeof deps === "object" ? Object.keys(deps) : [];
309
+ return [.../* @__PURE__ */ new Set([...bundles, ...names])];
310
+ } catch {
311
+ return bundles;
567
312
  }
568
313
  }
569
- /** pnpm add 不会写 bundles。官方 Desktop 直接调宿主 pnpm 时,要自己把插件挂进 profile。 */
570
- async function declareProfileBundle(packageName, runtime) {
571
- if (isOfficialRuntimePackage(packageName)) return;
572
- const manifestPath = resolve(profileDirectory(runtime), "package.json");
573
- let manifest;
574
- try {
575
- manifest = JSON.parse(await readFile(manifestPath, "utf8"));
576
- } catch (error) {
577
- if (error.code !== "ENOENT") throw error;
578
- manifest = {};
579
- }
580
- const bundles = manifest.dsh?.profile?.bundles ?? [];
581
- if (bundles.includes(packageName)) return;
582
- manifest.dsh = {
583
- ...manifest.dsh,
584
- profile: {
585
- ...manifest.dsh?.profile,
586
- bundles: [...bundles, packageName]
587
- }
588
- };
589
- await writeFile(manifestPath, `${JSON.stringify(manifest, void 0, 2)}\n`, "utf8");
314
+ async function installedPackageVersion(packageName, runtime) {
315
+ const directory = profileDirectory(runtime);
316
+ const candidate = join(directory, "node_modules", ...packageName.split("/"), "package.json");
317
+ if (existsSync(candidate)) try {
318
+ const manifest = JSON.parse(await readFile(candidate, "utf8"));
319
+ if (typeof manifest.version === "string" && manifest.version !== "") return manifest.version;
320
+ } catch {}
590
321
  }
591
- async function recordDeclaredVersion(packageName, version, runtime) {
592
- const manifestPath = resolve(profileDirectory(runtime), "package.json");
593
- let manifest;
594
- try {
595
- manifest = JSON.parse(await readFile(manifestPath, "utf8"));
596
- } catch (error) {
597
- if (error.code !== "ENOENT") throw error;
598
- manifest = {};
599
- }
600
- manifest.dependencies = {
601
- ...manifest.dependencies,
602
- [packageName]: version
603
- };
604
- await writeFile(manifestPath, `${JSON.stringify(manifest, void 0, 2)}\n`, "utf8");
322
+ async function dependencyStatuses(runtime = resolveDependencyRuntime()) {
323
+ const bundles = await profileBundleNames(runtime);
324
+ return Promise.all(MANAGED_DEPENDENCIES.map(async (item) => {
325
+ const [installedVersion, latestVersion, totalDownloads] = await Promise.all([
326
+ installedPackageVersion(item.packageName, runtime),
327
+ npmLatestVersion(item.packageName),
328
+ npmTotalDownloads(item.packageName)
329
+ ]);
330
+ const installed = isManagedPackageInstalled({
331
+ installedVersion,
332
+ declared: isManagedPackageDeclared(item.packageName, bundles)
333
+ });
334
+ const updateAvailable = installed && installedVersion !== void 0 && latestVersion !== void 0 ? newerVersion(installedVersion, latestVersion) : false;
335
+ return {
336
+ id: item.id,
337
+ packageName: item.packageName,
338
+ installed,
339
+ version: installed ? installedVersion : void 0,
340
+ latestVersion,
341
+ totalDownloads,
342
+ updateAvailable
343
+ };
344
+ }));
605
345
  }
606
346
  const progressState = {
607
347
  active: false,
608
348
  target: "",
349
+ startedAt: 0,
609
350
  seconds: 0,
610
351
  lastLine: "",
611
352
  phase: null,
612
353
  done: 0,
613
354
  total: null,
614
355
  percent: null,
615
- currentPackage: null,
616
- leftover: "",
617
- startedAt: 0
356
+ currentPackage: null
618
357
  };
619
358
  function beginInstallProgress(target) {
620
359
  progressState.active = true;
@@ -622,17 +361,14 @@ function beginInstallProgress(target) {
622
361
  progressState.startedAt = Date.now();
623
362
  progressState.seconds = 0;
624
363
  progressState.lastLine = "";
625
- progressState.phase = null;
364
+ progressState.phase = "resolving";
626
365
  progressState.done = 0;
627
366
  progressState.total = null;
628
367
  progressState.percent = null;
629
368
  progressState.currentPackage = null;
630
- progressState.leftover = "";
631
369
  }
632
370
  function endInstallProgress() {
633
- if (progressState.leftover !== "") applyProgressLine(progressState.leftover.trim());
634
371
  progressState.active = false;
635
- progressState.leftover = "";
636
372
  }
637
373
  function installProgressSnapshot() {
638
374
  return {
@@ -647,280 +383,25 @@ function installProgressSnapshot() {
647
383
  currentPackage: progressState.currentPackage
648
384
  };
649
385
  }
650
- function applyProgressLine(line) {
651
- if (line === "") return;
652
- const human = /Progress:\s*resolved\s+(\d+),\s*reused\s+(\d+),\s*downloaded\s+(\d+),\s*added\s+(\d+)/.exec(line);
653
- if (human !== null) {
654
- const resolved = Number(human[1]);
655
- const added = Number(human[4]);
656
- progressState.lastLine = line.slice(0, 200);
657
- progressState.total = resolved;
658
- progressState.done = added;
659
- progressState.percent = resolved > 0 ? Math.max(1, Math.min(/done/i.test(line) ? 100 : 99, Math.round(added / resolved * 100))) : null;
660
- if (added > 0) progressState.phase = "linking";
661
- else if (Number(human[3]) > 0) progressState.phase = "downloading";
662
- else progressState.phase = "resolving";
663
- return;
386
+ /** 接收宿主官方 plugin-manager/install-state 广播事件,对齐官方安装进度阶段。 */
387
+ function noteHostInstallState(event) {
388
+ if (event === null || typeof event !== "object") return;
389
+ const data = event;
390
+ if (typeof data.phase === "string") {
391
+ if (data.phase === "resolving" || data.phase === "downloading" || data.phase === "linking" || data.phase === "building") progressState.phase = data.phase;
664
392
  }
665
- if (/^Done in /i.test(line)) {
666
- progressState.lastLine = line.slice(0, 200);
667
- if (progressState.percent !== null) progressState.percent = 100;
668
- progressState.phase = "linking";
669
- return;
670
- }
671
- if (line.startsWith("{")) {
672
- try {
673
- const event = JSON.parse(line);
674
- if (typeof event.name !== "string" || !event.name.startsWith("pnpm:")) return;
675
- if (event.name === "pnpm:stage" && typeof event.stage === "string") {
676
- if (event.stage.includes("resolution")) progressState.phase = "resolving";
677
- else if (event.stage.includes("import")) progressState.phase = "linking";
678
- else if (event.stage.includes("build")) progressState.phase = "building";
679
- }
680
- if (event.name === "pnpm:progress" && typeof event.packageId === "string" && event.packageId !== "") {
681
- progressState.currentPackage = event.packageId.split(">")[0] ?? event.packageId;
682
- if (event.status === "fetched") progressState.phase = "downloading";
683
- }
684
- } catch {
685
- return;
686
- }
687
- return;
688
- }
689
- progressState.lastLine = line.slice(0, 200);
690
393
  }
691
- /** 把 pnpm / dsh plugin 的输出收成关于页可轮询的进度。 */
692
394
  function noteInstallOutput(chunk) {
693
- if (!progressState.active) return;
694
- const lines = `${progressState.leftover}${chunk}`.split(/\r?\n/);
695
- progressState.leftover = lines.pop() ?? "";
696
- for (const line of lines) applyProgressLine(line.trim());
697
- }
698
- function pluginUnchangedError() {
699
- return /* @__PURE__ */ new Error("安装命令已结束,但插件没有进入当前 Profile。请重试。");
700
- }
701
- async function waitUntilPluginMounted(packageName, version, runtime, timeoutMs = PLUGIN_MOUNT_TIMEOUT_MS) {
702
- const deadline = Date.now() + timeoutMs;
703
- while (Date.now() <= deadline) {
704
- const bundles = await profileBundleNames(runtime);
705
- const inBundles = isOfficialRuntimePackage(packageName) || isManagedPackageDeclared(packageName, bundles);
706
- const installed = await installedPackageVersion(packageName, runtime);
707
- if (inBundles && installed === version) return;
708
- await new Promise((resolve) => setTimeout(resolve, 80));
709
- }
710
- throw pluginUnchangedError();
711
- }
712
- function pluginCommandError(stderr, environmentKind = "desktop") {
713
- const detail = stderr.replace(/\s+/g, " ").trim();
714
- const isWeb = environmentKind === "cli";
715
- if (/EPERM|EBUSY|EACCES|unable to unlink|ERR_PNPM_LOCKED|Lock/i.test(detail)) return /* @__PURE__ */ new Error(isWeb ? "无法覆盖正在运行的插件文件。请停止当前 DSH Web 后,在终端更新插件,再重新启动 DSH Web。" : "无法覆盖正在运行的插件文件。请先完全退出桌面端,再重新打开后更新。");
716
- if (/UNEXPECTED_STORE|Unexpected store location/i.test(detail)) return /* @__PURE__ */ new Error(isWeb ? "插件目录与 pnpm 仓库不一致。请停止当前 DSH Web 后重试;仍失败时重新安装该 Profile 的依赖。" : "插件目录和 pnpm 仓库不一致。请完全退出桌面端后再更新。");
717
- if (/ERR_PNPM_IGNORED_BUILDS|Ignored build scripts/i.test(detail)) return /* @__PURE__ */ new Error("插件依赖的 pnpm 构建脚本策略尚未确认。请更新 Profile 的 allowBuilds 配置后重试。");
718
- if (/pnpm not found|未找到 pnpm/i.test(detail)) return /* @__PURE__ */ new Error("当前环境找不到 pnpm。请确认已安装 pnpm 后重启 DSH 再试。");
719
- return /* @__PURE__ */ new Error(isWeb ? "插件更新失败。请查看 DSH Web 终端输出后重试。" : "无法在应用运行时更新插件。请先完全退出桌面端,再重新打开后更新。");
720
- }
721
- /**
722
- * 图形界面或桌面启动往往没有 shell PATH。把 pnpm 常见安装目录补进去,
723
- * 让 `dsh plugin add` 能找到本机已有的 pnpm,而不是直接启动它。
724
- */
725
- function pluginToolSearchDirs(platform = process.platform, env = process.env, home = homedir(), nodeDir = dirname(process.execPath)) {
726
- const dirs = [];
727
- const pnpmHome = (env.PNPM_HOME ?? "").trim();
728
- if (pnpmHome !== "") dirs.push(pnpmHome);
729
- if (platform === "win32") {
730
- const local = (env.LOCALAPPDATA ?? "").trim();
731
- const roaming = (env.APPDATA ?? "").trim();
732
- if (local !== "") dirs.push(join(local, "pnpm"));
733
- if (roaming !== "") dirs.push(join(roaming, "npm"));
734
- } else dirs.push("/opt/homebrew/bin", "/usr/local/bin", join(home, ".local", "bin"), join(home, ".local", "share", "pnpm"));
735
- if (nodeDir.trim() !== "") dirs.push(nodeDir);
736
- return [...new Set(dirs.filter((dir) => dir.trim() !== ""))];
737
- }
738
- function pluginSpawnEnv(env = process.env, platform = process.platform, home = homedir(), nodeDir = dirname(process.execPath)) {
739
- const separator = platform === "win32" ? ";" : ":";
740
- const parts = (env.PATH ?? env.Path ?? "").split(separator).filter((part) => part !== "");
741
- for (const dir of pluginToolSearchDirs(platform, env, home, nodeDir)) if (!parts.includes(dir)) parts.push(dir);
742
- return {
743
- ...env,
744
- CI: "true",
745
- PATH: parts.join(separator)
746
- };
747
- }
748
- /** Desktop 桥接在 Web 下不会设置 DSH_PNPM_ENTRY;补上 Node 自带的 corepack pnpm。 */
749
- function ensurePnpmEntry(env = process.env, nodeDir = dirname(process.execPath)) {
750
- const existing = (env.DSH_PNPM_ENTRY ?? "").trim();
751
- if (existing !== "") return existing;
752
- const candidate = join(nodeDir, "node_modules", "corepack", "dist", "pnpm.js");
753
- if (!existsSync(candidate)) return void 0;
754
- return candidate;
755
- }
756
- /** Desktop 桥接当前从 process.env 同步读取 pnpm 入口;调用结束后立即恢复,避免污染后续子进程。 */
757
- function withPnpmEntry(callback, env = process.env, nodeDir = dirname(process.execPath)) {
758
- const entry = ensurePnpmEntry(env, nodeDir);
759
- if (entry === void 0) return callback();
760
- const hadEntry = Object.prototype.hasOwnProperty.call(env, "DSH_PNPM_ENTRY");
761
- const previous = env.DSH_PNPM_ENTRY;
762
- env.DSH_PNPM_ENTRY = entry;
763
- try {
764
- return callback();
765
- } finally {
766
- if (hadEntry) env.DSH_PNPM_ENTRY = previous;
767
- else delete env.DSH_PNPM_ENTRY;
768
- }
395
+ if (chunk === "") return;
396
+ const trimmed = chunk.trim();
397
+ if (trimmed !== "") progressState.lastLine = trimmed.slice(0, 200);
769
398
  }
770
- /**
771
- * 复用启动当前服务的 DSH CLI:它会通过 pnpm 从 npm 安装或更新,并自动维护
772
- * dsh.profile.bundles,避免浏览器端直接管理 profile 文件。
773
- */
774
- function pluginExecArgv(args = process.execArgv) {
775
- return args.filter((arg) => !/^--(?:inspect|inspect-brk|debug|debug-brk)(?:=|$)/.test(arg));
776
- }
777
- const activePluginChildren = /* @__PURE__ */ new Set();
778
- const activeDesktopPluginHandles = /* @__PURE__ */ new Set();
779
- function terminatePluginChild(child) {
780
- if (child.exitCode !== null || child.killed) return;
781
- if (process.platform === "win32" && child.pid !== void 0) {
782
- const killer = spawn("taskkill", [
783
- "/pid",
784
- String(child.pid),
785
- "/T",
786
- "/F"
787
- ], {
788
- windowsHide: true,
789
- stdio: "ignore"
790
- });
791
- killer.once("error", () => {
792
- child.kill("SIGTERM");
793
- });
794
- killer.unref();
795
- return;
796
- }
797
- child.kill("SIGTERM");
798
- }
799
- /** 插件停用时终止仍在运行的安装进程,避免热更新后遗留 pnpm。 */
800
- function disposeDependencyInstaller() {
801
- for (const child of activePluginChildren) terminatePluginChild(child);
802
- for (const handle of activeDesktopPluginHandles) handle.cancel();
803
- }
804
- function monitorPluginChild(child, timeoutMs = PLUGIN_INSTALL_TIMEOUT_MS, environmentKind = "cli") {
805
- return new Promise((resolvePromise, reject) => {
806
- activePluginChildren.add(child);
807
- let output = "";
808
- let settled = false;
809
- const collect = (chunk) => {
810
- const text = String(chunk);
811
- output = `${output}${text}`.slice(-65536);
812
- noteInstallOutput(text);
813
- };
814
- const finish = (error) => {
815
- if (settled) return;
816
- settled = true;
817
- clearTimeout(timeout);
818
- activePluginChildren.delete(child);
819
- error === void 0 ? resolvePromise() : reject(error);
820
- };
821
- child.stdout?.on("data", collect);
822
- child.stderr?.on("data", collect);
823
- child.once("error", () => {
824
- finish(/* @__PURE__ */ new Error("无法启动 DSH 插件安装命令。请确认 Node.js 与 pnpm 可用后重试。"));
825
- });
826
- child.once("exit", (code) => {
827
- finish(code === 0 ? void 0 : pluginCommandError(output, environmentKind));
828
- });
829
- const timeout = setTimeout(() => {
830
- terminatePluginChild(child);
831
- finish(/* @__PURE__ */ new Error("插件安装超时,已终止安装进程。请检查网络后重试。"));
832
- }, timeoutMs);
833
- timeout.unref?.();
834
- });
835
- }
836
- function monitorDesktopPlugin(handle, timeoutMs = PLUGIN_INSTALL_TIMEOUT_MS) {
837
- return new Promise((resolvePromise, reject) => {
838
- activeDesktopPluginHandles.add(handle);
839
- let output = "";
840
- let settled = false;
841
- const collect = (chunk) => {
842
- const text = String(chunk);
843
- output = `${output}${text}`.slice(-65536);
844
- noteInstallOutput(text);
845
- };
846
- const finish = (error) => {
847
- if (settled) return;
848
- settled = true;
849
- clearTimeout(timeout);
850
- activeDesktopPluginHandles.delete(handle);
851
- error === void 0 ? resolvePromise() : reject(error);
852
- };
853
- handle.stdout?.on("data", collect);
854
- handle.stderr?.on("data", collect);
855
- handle.stdout?.once("error", () => {
856
- handle.cancel();
857
- finish(/* @__PURE__ */ new Error("无法读取 DSH Desktop 插件安装输出。"));
858
- });
859
- handle.stderr?.once("error", () => {
860
- handle.cancel();
861
- finish(/* @__PURE__ */ new Error("无法读取 DSH Desktop 插件安装输出。"));
862
- });
863
- handle.done.then((outcome) => {
864
- finish(outcome.exitCode === 0 && outcome.signal === null ? void 0 : pluginCommandError(output, "desktop"));
865
- }, () => {
866
- finish(pluginCommandError(output, "desktop"));
867
- });
868
- const timeout = setTimeout(() => {
869
- handle.cancel();
870
- finish(/* @__PURE__ */ new Error("插件安装超时,已终止安装进程。请检查网络后重试。"));
871
- }, timeoutMs);
872
- timeout.unref?.();
873
- });
874
- }
875
- function runDshPlugin(args, runtime = resolveDependencyRuntime(), timeoutMs = PLUGIN_INSTALL_TIMEOUT_MS) {
876
- const desktopPnpm = runtime.desktopPnpm;
877
- if (desktopPnpm !== void 0) return monitorDesktopPlugin(withPnpmEntry(() => desktopPnpm.runPlugin(args, runtime.profileDir)), timeoutMs);
878
- const packageManager = runtime.packageManager;
879
- if (packageManager !== void 0) return monitorPluginChild(spawn(packageManager.command, [...packageManager.args, ...args], {
880
- cwd: runtime.profileDir,
881
- env: {
882
- ...pluginSpawnEnv(),
883
- ...runtime.pluginEnv,
884
- ...packageManager.env
885
- },
886
- windowsHide: true,
887
- stdio: [
888
- "ignore",
889
- "pipe",
890
- "pipe"
891
- ]
892
- }), timeoutMs, "desktop");
893
- const entry = runtime.cliEntry ?? resolveDshCliEntry();
894
- if (isOfficialDesktopHostEntry(entry)) throw new Error("无法定位 DSH CLI。请从 DSH 命令启动 Web 服务后重试。");
895
- return monitorPluginChild(spawn(process.execPath, [
896
- ...pluginExecArgv(),
897
- entry,
898
- "plugin",
899
- "--profile",
900
- runtime.profileName,
901
- ...args
902
- ], {
903
- cwd: process.cwd(),
904
- env: {
905
- ...pluginSpawnEnv(),
906
- ...runtime.pluginEnv
907
- },
908
- windowsHide: true,
909
- stdio: [
910
- "ignore",
911
- "pipe",
912
- "pipe"
913
- ]
914
- }), timeoutMs, runtime.environmentKind);
915
- }
916
- /** 并发安装互斥:pnpm 锁文件竞争会触发 EPERM/EBUSY,同一时间只允许一个安装进程。 */
917
399
  let installing = false;
918
- /** 仅允许安装固定依赖,避免把浏览器输入转成任意命令。 */
919
- async function installDependency(id, requestHotUpdate = requestDesktopHotUpdate, runtime = resolveDependencyRuntime()) {
400
+ async function installDependency(id, runtime = resolveDependencyRuntime()) {
920
401
  if (installing) throw new Error("已有依赖安装正在进行,请等待完成后再试。");
921
402
  installing = true;
922
403
  try {
923
- return await installDependenciesLocked([id], requestHotUpdate, runtime);
404
+ return await installDependenciesLocked([id], runtime);
924
405
  } finally {
925
406
  installing = false;
926
407
  }
@@ -929,8 +410,7 @@ async function installDependency(id, requestHotUpdate = requestDesktopHotUpdate,
929
410
  function updatableDependencyIds(statuses) {
930
411
  return statuses.filter((status) => !status.installed || status.updateAvailable).map((status) => status.id);
931
412
  }
932
- /** 把所有待安装/更新版本一次写入清单,最后只请求一次桌面热更新。 */
933
- async function updateAllDependencies(requestHotUpdate = requestDesktopHotUpdate, runtime = resolveDependencyRuntime()) {
413
+ async function updateAllDependencies(runtime = resolveDependencyRuntime()) {
934
414
  if (installing) throw new Error("已有依赖安装正在进行,请等待完成后再试。");
935
415
  installing = true;
936
416
  try {
@@ -938,32 +418,30 @@ async function updateAllDependencies(requestHotUpdate = requestDesktopHotUpdate,
938
418
  const ids = updatableDependencyIds(current);
939
419
  if (ids.length === 0) return {
940
420
  dependencies: current,
941
- updatedCount: 0
942
- };
943
- return {
944
- dependencies: await installDependenciesLocked(ids, requestHotUpdate, runtime),
945
- updatedCount: ids.length
421
+ application: "applied",
422
+ updatedCount: 0,
423
+ results: []
946
424
  };
425
+ return await installDependenciesLocked(ids, runtime);
947
426
  } finally {
948
427
  installing = false;
949
428
  }
950
429
  }
951
- async function installDependenciesLocked(ids, requestHotUpdate, runtime) {
430
+ async function installDependenciesLocked(ids, runtime) {
431
+ if (typeof runtime.pluginManager?.installBundle !== "function") throw new Error("DSH 宿主插件管理服务尚未就绪,请重启 DSH 后重试。");
952
432
  const dependencies = [...new Set(ids)].map((id) => {
953
433
  const dependency = managedDependency(id);
954
434
  if (dependency === void 0) throw new Error("不支持安装该依赖。");
955
435
  return dependency;
956
436
  });
957
437
  const declared = await declaredPluginNames(runtime);
438
+ if (declared.includes("@michengai/dsh-codex-suite") && dependencies.some((dependency) => SUITE_MEMBER_PACKAGES.includes(dependency.packageName))) throw new Error("旧套件成员暂不支持自动迁移,请通过宿主插件管理器处理。");
958
439
  const requestedTargets = await Promise.all(dependencies.map(async (dependency) => {
959
440
  const latestVersion = await npmLatestVersion(dependency.packageName);
960
441
  if (latestVersion === void 0) throw new Error("无法获取 npm 最新版本,请检查网络或 npm registry 后重试。");
961
- const packageName = resolveDshPluginTarget(dependency.packageName, declared);
962
- const version = packageName === dependency.packageName ? latestVersion : await npmLatestVersion(packageName);
963
- if (version === void 0) throw new Error("无法获取 npm 最新版本,请检查网络或 npm registry 后重试。");
964
442
  return {
965
- packageName,
966
- version
443
+ packageName: dependency.packageName,
444
+ version: latestVersion
967
445
  };
968
446
  }));
969
447
  const requestedVersions = new Map(requestedTargets.map((target) => [target.packageName, target.version]));
@@ -975,43 +453,92 @@ async function installDependenciesLocked(ids, requestHotUpdate, runtime) {
975
453
  version: requestedVersion
976
454
  };
977
455
  const version = await installedPackageVersion(packageName, runtime) ?? await npmLatestVersion(packageName);
978
- if (version === void 0) throw new Error("无法读取 Suite 成员版本,请检查 npm 安装后重试。");
456
+ if (version === void 0) throw new Error("无法读取成员版本,请检查 npm 安装后重试。");
979
457
  return {
980
458
  packageName,
981
459
  version
982
460
  };
983
461
  }));
984
462
  beginInstallProgress(targets.map((target) => `${target.packageName}@${target.version}`).join(", "));
463
+ const results = [];
985
464
  try {
986
- const remove = [...new Set(targets.flatMap((target) => pluginsToRemoveBeforeInstall(declared, target.packageName)))];
987
- await ensureRequiredBuildPolicies(runtime);
988
465
  for (const target of targets) {
989
- if (!isOfficialRuntimePackage(target.packageName)) await removeUnmountedPackagePath(target.packageName, runtime);
990
- await recordPendingUpdate(target.packageName, target.version, runtime);
991
- }
992
- if (remove.length > 0) await runDshPlugin(["remove", ...remove], runtime);
993
- if (runtime.desktopPnpm === void 0 && requestHotUpdate()) {
994
- for (const target of targets) if (!isOfficialRuntimePackage(target.packageName)) await recordDeclaredVersion(target.packageName, target.version, runtime);
995
- return dependencyStatuses(runtime);
996
- }
997
- const officialTargets = targets.filter((target) => isOfficialRuntimePackage(target.packageName));
998
- const communityTargets = targets.filter((target) => !isOfficialRuntimePackage(target.packageName));
999
- const batches = [...officialTargets.map((target) => [target]), ...communityTargets.length === 0 ? [] : [communityTargets]];
1000
- for (const batch of batches) {
1001
- await runDshPlugin([
1002
- "add",
1003
- "--config.minimumReleaseAge=0",
1004
- ...batch.map((target) => `${target.packageName}@${target.version}`),
1005
- "--registry=https://registry.npmjs.org/"
1006
- ], runtime);
1007
- for (const target of batch) {
1008
- if (runtime.packageManager !== void 0) await declareProfileBundle(target.packageName, runtime);
1009
- await waitUntilPluginMounted(target.packageName, target.version, runtime);
1010
- if (!isOfficialRuntimePackage(target.packageName)) await recordDeclaredVersion(target.packageName, target.version, runtime);
1011
- await removePendingUpdate(target.packageName, runtime);
466
+ noteInstallOutput(`dsh: delegating ${target.packageName}@${target.version} to host pluginManager`);
467
+ let raw;
468
+ let restore;
469
+ try {
470
+ if (await installedPackageVersion(target.packageName, runtime) !== void 0 && declared.includes(target.packageName) && typeof runtime.pluginManager.updateBundle === "function") {
471
+ const update = await runtime.pluginManager.updateBundle(target.packageName, target.version);
472
+ raw = update !== null && typeof update === "object" ? update.result : void 0;
473
+ restore = update !== null && typeof update === "object" ? update.restore : void 0;
474
+ } else raw = await runtime.pluginManager.installBundle(`${target.packageName}@${target.version}`);
475
+ } catch (caught) {
476
+ results.push({
477
+ packageName: target.packageName,
478
+ application: "failed",
479
+ changed: null,
480
+ error: { message: caught instanceof Error ? caught.message : String(caught) }
481
+ });
482
+ break;
1012
483
  }
484
+ const change = raw !== null && typeof raw === "object" ? raw : void 0;
485
+ const valid = change && typeof change.changed === "boolean" && [
486
+ "applied",
487
+ "restart-required",
488
+ "overridden",
489
+ "failed",
490
+ "cancelled"
491
+ ].includes(String(change.application));
492
+ const application = valid ? change.application : "failed";
493
+ const restored = restore !== null && typeof restore === "object" ? restore : void 0;
494
+ const validRestore = restored && typeof restored.changed === "boolean" && [
495
+ "applied",
496
+ "restart-required",
497
+ "overridden",
498
+ "failed",
499
+ "cancelled"
500
+ ].includes(String(restored.application));
501
+ let errorInfo;
502
+ if (change !== void 0) {
503
+ const errObj = change.error && typeof change.error === "object" ? change.error : void 0;
504
+ const pkgResult = change.packageResult && typeof change.packageResult === "object" ? change.packageResult : void 0;
505
+ const code = typeof errObj?.code === "string" ? errObj.code : typeof change.code === "string" ? change.code : void 0;
506
+ const diagnostic = typeof errObj?.diagnostic === "string" ? errObj.diagnostic : typeof change.diagnostic === "string" ? change.diagnostic : void 0;
507
+ const message = typeof errObj?.message === "string" ? errObj.message : typeof change.error === "string" ? change.error : void 0;
508
+ const kind = typeof pkgResult?.kind === "string" ? pkgResult.kind : void 0;
509
+ if (code !== void 0 || diagnostic !== void 0 || message !== void 0 || kind !== void 0) errorInfo = {
510
+ ...code !== void 0 ? { code } : {},
511
+ ...diagnostic !== void 0 ? { diagnostic } : {},
512
+ ...message !== void 0 ? { message } : {},
513
+ ...kind !== void 0 ? { kind } : {}
514
+ };
515
+ }
516
+ results.push({
517
+ packageName: target.packageName,
518
+ application,
519
+ changed: valid ? change.changed : null,
520
+ ...validRestore ? { restore: {
521
+ application: restored.application,
522
+ changed: restored.changed
523
+ } } : {},
524
+ ...application === "restart-required" && typeof change?.restartReason === "string" && [
525
+ "no-hmr",
526
+ "package-moved",
527
+ "host-module",
528
+ "unmanaged-plugin",
529
+ "module-comparison"
530
+ ].includes(change.restartReason) ? { restartReason: change.restartReason } : {},
531
+ ...errorInfo !== void 0 ? { error: errorInfo } : {}
532
+ });
533
+ if (application === "failed" || application === "cancelled") break;
1013
534
  }
1014
- return dependencyStatuses(runtime);
535
+ const application = results.find((r) => r.application === "failed" || r.application === "cancelled")?.application ?? (results.some((r) => r.application === "overridden") ? "overridden" : results.some((r) => r.application === "restart-required") ? "restart-required" : "applied");
536
+ return {
537
+ dependencies: await dependencyStatuses(runtime),
538
+ application,
539
+ updatedCount: results.filter((r) => r.changed && r.application !== "failed" && r.application !== "cancelled").length,
540
+ results
541
+ };
1015
542
  } finally {
1016
543
  endInstallProgress();
1017
544
  }
@@ -1188,10 +715,20 @@ function authenticateBusinessRequest(ctx, request, response, errorBody = (_statu
1188
715
  return reject(503, "宿主认证服务暂不可用。");
1189
716
  }
1190
717
  }
1191
- const inject = ["webServer"];
718
+ const inject = [
719
+ "webServer",
720
+ "profileContext",
721
+ "pluginManager"
722
+ ];
1192
723
  /** 提供不泄露地址、命令和凭证的连接器目录。 */
1193
724
  function apply(ctx) {
1194
725
  const host = hostServices(ctx);
726
+ ctx.effect(() => {
727
+ if (typeof ctx.on !== "function") return () => {};
728
+ return ctx.on("plugin-manager/install-state", (event) => {
729
+ noteHostInstallState(event);
730
+ });
731
+ }, "codex-ui: host plugin-manager install state");
1195
732
  ctx.effect(() => {
1196
733
  const disposeDependencies = host.webServer.register({
1197
734
  kind: "exact",
@@ -1218,45 +755,41 @@ function apply(ctx) {
1218
755
  return;
1219
756
  }
1220
757
  if (request.method === "POST") {
1221
- if (url.searchParams.get("action") === "update-all") {
1222
- const runtime = resolveDependencyRuntime(ctx);
1223
- const notifyParent = canRequestParentReload(runtime);
1224
- const autoReload = runtime.environmentKind === "desktop" || notifyParent;
1225
- let restartAfterResponse = false;
1226
- const { dependencies, updatedCount } = await updateAllDependencies(() => {
1227
- restartAfterResponse = notifyParent;
1228
- return restartAfterResponse;
1229
- }, runtime);
1230
- response.writeHead(200, {
1231
- "content-type": "application/json; charset=utf-8",
1232
- "cache-control": "no-store"
1233
- });
1234
- response.end(JSON.stringify({
1235
- dependencies,
1236
- restartRequired: updatedCount > 0,
1237
- autoReload
1238
- }));
1239
- if (restartAfterResponse) scheduleParentPluginReload();
1240
- return;
1241
- }
1242
758
  const runtime = resolveDependencyRuntime(ctx);
1243
- const notifyParent = canRequestParentReload(runtime);
1244
- const autoReload = runtime.environmentKind === "desktop" || notifyParent;
1245
- let restartAfterResponse = false;
1246
- const dependencies = await installDependency(url.searchParams.get("dependency"), () => {
1247
- restartAfterResponse = notifyParent;
1248
- return restartAfterResponse;
1249
- }, runtime);
1250
- response.writeHead(200, {
759
+ const result = url.searchParams.get("action") === "update-all" ? await updateAllDependencies(runtime) : await installDependency(url.searchParams.get("dependency"), runtime);
760
+ const failed = result.application === "failed" || result.application === "cancelled";
761
+ let failureMessage;
762
+ if (failed) {
763
+ if (result.application === "cancelled") failureMessage = "依赖安装已取消。";
764
+ else {
765
+ const failedItem = result.results.find((item) => item.application === "failed" || item.application === "cancelled");
766
+ const errKind = failedItem?.error?.kind;
767
+ const errCode = failedItem?.error?.code;
768
+ const errMsg = failedItem?.error?.message ?? failedItem?.error?.diagnostic;
769
+ if (errKind === "timeout" || errCode === "timeout" || /timeout|timed out/i.test(errMsg ?? "")) failureMessage = "插件安装超时,请检查网络后重试。";
770
+ else if (errKind === "build-blocked" || errCode === "build-blocked" || /build-blocked|构建脚本/i.test(errMsg ?? "")) failureMessage = "插件依赖的 pnpm 构建脚本策略尚未确认,请更新 Profile 配置后重试。";
771
+ else failureMessage = "从 npm 安装或更新依赖失败。请检查网络或 npm registry 后重试。";
772
+ }
773
+ }
774
+ const sanitizedResults = result.results.map((item) => ({
775
+ ...item,
776
+ ...item.error !== void 0 ? { error: {
777
+ ...item.error,
778
+ ...item.error.message !== void 0 ? { message: publicDependencyError(new Error(item.error.message)) } : {},
779
+ ...item.error.diagnostic !== void 0 ? { diagnostic: publicDependencyError(new Error(item.error.diagnostic)) } : {}
780
+ } } : {}
781
+ }));
782
+ response.writeHead(failed ? 503 : 200, {
1251
783
  "content-type": "application/json; charset=utf-8",
1252
784
  "cache-control": "no-store"
1253
785
  });
1254
786
  response.end(JSON.stringify({
1255
- dependencies,
1256
- restartRequired: true,
1257
- autoReload
787
+ ...result,
788
+ results: sanitizedResults,
789
+ restartRequired: result.results.some((item) => item.application === "restart-required" || item.restore?.application === "restart-required"),
790
+ autoReload: false,
791
+ ...failed && failureMessage !== void 0 ? { error: publicDependencyError(new Error(failureMessage)) } : {}
1258
792
  }));
1259
- if (restartAfterResponse) scheduleParentPluginReload();
1260
793
  return;
1261
794
  }
1262
795
  response.writeHead(405);
@@ -1333,7 +866,6 @@ function apply(ctx) {
1333
866
  }
1334
867
  });
1335
868
  return () => {
1336
- disposeDependencyInstaller();
1337
869
  disposeDependencies();
1338
870
  disposeSections?.();
1339
871
  };