pi-web-ui 0.110.0 → 0.111.0

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.
Files changed (64) hide show
  1. package/bin/frp-manager.mjs +85 -7
  2. package/dist/server/agent-formatters.js +10 -6
  3. package/dist/server/agent-service-daemon.js +27 -9
  4. package/dist/server/agent-service.js +140 -24
  5. package/dist/server/attachments.js +114 -31
  6. package/dist/server/canvas/canvas-agent-tool.js +587 -0
  7. package/dist/server/canvas/canvas-cards.js +144 -0
  8. package/dist/server/canvas/canvas-dispatch.js +155 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +1027 -0
  10. package/dist/server/canvas/canvas-store.js +260 -0
  11. package/dist/server/client-id-utils.js +2 -2
  12. package/dist/server/client-state.js +24 -0
  13. package/dist/server/context-budget.js +6 -3
  14. package/dist/server/dsh/dsh-agent-service.js +115 -9
  15. package/dist/server/dsh/dsh-client.js +10 -1
  16. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  17. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  18. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  19. package/dist/server/durable/durable-agent-service.js +3 -0
  20. package/dist/server/file-transfer-routes.js +8 -2
  21. package/dist/server/files-service.js +10 -2
  22. package/dist/server/index.js +137 -4
  23. package/dist/server/marker-service.js +3 -1
  24. package/dist/server/markers/marker.js +45 -4
  25. package/dist/server/markers/registry.js +31 -0
  26. package/dist/server/message-window.js +6 -3
  27. package/dist/server/office-parse.js +394 -7
  28. package/dist/server/plugin-api-catalog.js +6 -0
  29. package/dist/server/plugins.js +97 -20
  30. package/dist/server/preset-fields.js +35 -1
  31. package/dist/server/preset-share.js +3 -0
  32. package/dist/server/prompt-assembler.js +7 -1
  33. package/dist/server/prompt-composer.js +66 -36
  34. package/dist/server/protocol-version.js +1 -1
  35. package/dist/server/remote-ssh-service.js +16 -4
  36. package/dist/server/settings-service.js +19 -3
  37. package/dist/server/tool-manager.js +30 -0
  38. package/dist/server/univer-service.js +448 -0
  39. package/dist/server/universal/drivers/claude-code.js +19 -2
  40. package/dist/server/universal/universal-attachments.js +5 -0
  41. package/dist/server/universal/universal-service.js +5 -0
  42. package/dist/server/universal/universal-session.js +28 -12
  43. package/dist/server/update-check.js +90 -5
  44. package/dist/server/workspace-snapshot.js +33 -2
  45. package/docs/dsh-engine.md +497 -0
  46. package/package.json +5 -4
  47. package/plugin-sdk/index.d.ts +17 -0
  48. package/plugin-sdk/index.mjs +5 -0
  49. package/plugins/catalog.json +22 -0
  50. package/themes/aetheris.css +114 -0
  51. package/themes/bases/obsidian-base.css +216 -0
  52. package/themes/md-preview.css +113 -0
  53. package/themes/wallpaper-flow.css +182 -0
  54. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-BiUNySMA.js} +2 -2
  55. package/web/dist/assets/index-B0ajS__T.js +697 -0
  56. package/web/dist/assets/index-BHik5WGG.css +1 -0
  57. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  58. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  59. package/web/dist/index.html +4 -4
  60. package/web/dist/sw.js +1 -1
  61. package/web/dist/assets/es-DIDZppIF.js +0 -2
  62. package/web/dist/assets/index-DwInT7-a.css +0 -1
  63. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  64. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -17,13 +17,52 @@ import { resolve } from "node:path";
17
17
  import { dirname, join } from "node:path";
18
18
  import { fileURLToPath, pathToFileURL } from "node:url";
19
19
  import { existsSync } from "node:fs";
20
- import { JsonRpcLineTransport } from "@deepseek-ai/dsh-sdk-protocol";
21
- import { defineTool } from "@deepseek-ai/dsh-tools";
20
+ import { resolveRuntimeBase } from "./runtime-root.mjs";
22
21
 
23
22
  const HERE = dirname(fileURLToPath(import.meta.url));
24
23
 
25
- /** 官方 jsonrpc-server 入口(env 优先,兜底从本文件向上找 node_modules 里的官方包)。 */
24
+ if (!process.env.PI_WEB_DSH_RUNTIME_BASE) {
25
+ try {
26
+ const detected = await resolveRuntimeBase();
27
+ if (detected) process.env.PI_WEB_DSH_RUNTIME_BASE = detected;
28
+ } catch {}
29
+ }
30
+
31
+ /** 动态解析并加载 DSH 相关模块(优先使用当前正在运行的运行时树,兜底本地依赖) */
32
+ async function loadDshModule(pkgName) {
33
+ const rt = process.env.PI_WEB_DSH_RUNTIME_BASE;
34
+ if (rt) {
35
+ const candidate = join(rt, pkgName, "lib", "index.js");
36
+ if (existsSync(candidate)) {
37
+ return import(pathToFileURL(candidate).href);
38
+ }
39
+ }
40
+ let cur = HERE;
41
+ for (let i = 0; i < 6; i++) {
42
+ const candidate = join(cur, "node_modules", pkgName, "lib", "index.js");
43
+ if (existsSync(candidate)) {
44
+ return import(pathToFileURL(candidate).href);
45
+ }
46
+ cur = dirname(cur);
47
+ }
48
+ return import(pkgName);
49
+ }
50
+
51
+ const { JsonRpcLineTransport } = await loadDshModule("@deepseek-ai/dsh-sdk-protocol");
52
+ const { defineTool } = await loadDshModule("@deepseek-ai/dsh-tools");
53
+
54
+ /** 官方 jsonrpc-server 入口(优先运行时树,次选 env,兜底从项目依赖向上找)。 */
26
55
  function findOfficialEntry() {
56
+ if (process.env.PI_WEB_DSH_RUNTIME_BASE) {
57
+ const candidate = join(
58
+ process.env.PI_WEB_DSH_RUNTIME_BASE,
59
+ "@deepseek-ai",
60
+ "dsh-sdk-jsonrpc-server",
61
+ "lib",
62
+ "index.js",
63
+ );
64
+ if (existsSync(candidate)) return candidate;
65
+ }
27
66
  if (process.env.PI_WEB_DSH_JSONRPC_ENTRY) return resolve(process.env.PI_WEB_DSH_JSONRPC_ENTRY);
28
67
  let cur = HERE;
29
68
  for (let i = 0; i < 6; i++) {
@@ -533,6 +572,90 @@ class DshGoalJsonRpcServer extends HarnessSdkJsonRpcServer {
533
572
  return { tools: schemas.map((s) => s.name).sort() };
534
573
  }
535
574
 
575
+ /** prompt/inspect RPC:返回系统提示词全文、分段(sections)、上下文(contexts)与工具 schemas。 */
576
+ async promptInspect(params) {
577
+ let context = {};
578
+ if (typeof params?.sessionId === "string" && params.sessionId) {
579
+ try {
580
+ const rec = await this.getOrCreateSession(params.sessionId);
581
+ const agent = this.liveAgent(rec, params.sessionId);
582
+ context = { agent, scope: agent };
583
+ } catch {
584
+ /* ignore */
585
+ }
586
+ }
587
+ if (!context.agent) {
588
+ try {
589
+ const agent = await this.ensureInventoryAgent();
590
+ context = { agent, scope: agent };
591
+ } catch {
592
+ /* ignore */
593
+ }
594
+ }
595
+ const contexts = context.agent
596
+ ? [{ agent: context.agent, scope: context.agent }, { scope: context.agent }, { scope: context.agent.ctx }, {}]
597
+ : [{}];
598
+ let asm = null;
599
+ let lastErr = null;
600
+ for (const ctx of contexts) {
601
+ try {
602
+ asm = await this.ctx.systemPrompt.assemble(ctx);
603
+ if (asm) break;
604
+ } catch (err) {
605
+ lastErr = err;
606
+ }
607
+ }
608
+ if (!asm) {
609
+ return {
610
+ prompt: "",
611
+ sections: [],
612
+ contexts: [],
613
+ tools: [],
614
+ error: String(lastErr?.message ?? lastErr ?? "assembly failed"),
615
+ };
616
+ }
617
+ const sections = Array.isArray(asm.sections)
618
+ ? asm.sections.map((s) => ({
619
+ name: s.name,
620
+ text: typeof s.text === "string" ? s.text : String(s.text ?? ""),
621
+ chars: String(s.text ?? "").length,
622
+ }))
623
+ : [];
624
+ const promptContexts = Array.isArray(asm.contexts)
625
+ ? asm.contexts.map((c) => ({
626
+ name: c.name,
627
+ text: typeof c.text === "string" ? c.text : String(c.text ?? ""),
628
+ chars: String(c.text ?? "").length,
629
+ }))
630
+ : [];
631
+ const tools = Array.isArray(asm.tools)
632
+ ? asm.tools.map((t) => ({
633
+ name: t.name,
634
+ description: t.description,
635
+ parameters: t.parameters,
636
+ }))
637
+ : [];
638
+ const sectionTexts = sections.map((s) => s.text).filter(Boolean);
639
+ let fullPrompt = sectionTexts.join("\n\n");
640
+ if (promptContexts.length > 0) {
641
+ const ctxBody = promptContexts
642
+ .map((c) => c.text)
643
+ .filter(Boolean)
644
+ .join("\n\n");
645
+ if (ctxBody) {
646
+ fullPrompt +=
647
+ (fullPrompt ? "\n\n" : "") +
648
+ `Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\n${ctxBody}`;
649
+ }
650
+ }
651
+ return {
652
+ prompt: fullPrompt,
653
+ sections,
654
+ contexts: promptContexts,
655
+ tools,
656
+ };
657
+ }
658
+
536
659
  /** debug/assemble RPC(仅 DEBUG):读一个会话 agent 视角的系统提示词 section 名录
537
660
  * (零 token 验证 persona 遮蔽/complete 压制/自定义 section 用;不返回正文)。 */
538
661
  async debugAssemble(params) {
@@ -721,6 +844,8 @@ class DshGoalJsonRpcServer extends HarnessSdkJsonRpcServer {
721
844
  return this.setPermission(params);
722
845
  case "preset/tools":
723
846
  return this.presetTools(params);
847
+ case "prompt/inspect":
848
+ return this.promptInspect(params);
724
849
  case "debug/assemble":
725
850
  return this.debugAssemble(params);
726
851
  default:
@@ -23,20 +23,60 @@
23
23
  import { dirname, join, resolve } from "node:path";
24
24
  import { readdirSync } from "node:fs";
25
25
  import { fileURLToPath, pathToFileURL } from "node:url";
26
- import { resolveRuntimeBase } from "./runtime-root.mjs";
26
+ import { resolveRuntimeBaseWithDetails, getExpectedDshVersion, getDshFamily } from "./runtime-root.mjs";
27
27
 
28
28
  const HERE = dirname(fileURLToPath(import.meta.url));
29
29
  const BIN_NAME = "pi-web-ui-dsh";
30
30
 
31
- const runtimeBase = await resolveRuntimeBase();
31
+ const expectedVersion = getExpectedDshVersion();
32
+ const expectedFamily = getDshFamily(expectedVersion);
33
+
34
+ const { base: runtimeBase, scannedPaths, compatibility } = await resolveRuntimeBaseWithDetails();
32
35
  if (!runtimeBase) {
33
- console.error(
34
- `[${BIN_NAME}] 找不到 DSH 运行时树(含 @deepseek-ai/dsh-base 的 node_modules)。` +
35
- "请先执行 npm i -g @deepseek-ai/dsh(或设置 PI_WEB_DSH_RUNTIME 指向其 node_modules)。",
36
+ const pathList = scannedPaths
37
+ .slice(0, 15)
38
+ .map((s) => ` - ${s.path} (${s.exists ? s.reason || "已存在但非有效运行时树" : "不存在"})`)
39
+ .join("\n");
40
+ const more = scannedPaths.length > 15 ? `\n ... 另有 ${scannedPaths.length - 15} 处候选` : "";
41
+ process.stderr.write(
42
+ `[${BIN_NAME}] 找不到 DSH 运行时树(含 @deepseek-ai/dsh-base 的 node_modules)。\n` +
43
+ `请先执行 npm i -g @deepseek-ai/dsh@${expectedVersion}(或设置 PI_WEB_DSH_RUNTIME 指向其 node_modules 目录)。\n\n` +
44
+ `已探测的候选路径:\n${pathList}${more}\n\n` +
45
+ `详见文档 docs/dsh-engine.md。\n`,
36
46
  );
37
47
  process.exit(1);
38
48
  }
39
49
 
50
+ process.env.PI_WEB_DSH_RUNTIME_BASE = runtimeBase;
51
+
52
+ // 检查版本族兼容性(默认宽松尝试运行;若需严格匹配可设置 PI_WEB_DSH_STRICT_VERSION=1)
53
+ if (!compatibility?.compatible) {
54
+ const strictVer = process.env.PI_WEB_DSH_STRICT_VERSION === "1" || process.env.PI_WEB_DSH_STRICT_VERSION === "true";
55
+ const verMsg =
56
+ `[${BIN_NAME}] 注意:检测到 DSH 运行时版本(${compatibility?.runtimeVersion ?? "未知"})与期望版本(${expectedVersion},版本族 ${expectedFamily})不同。\n` +
57
+ ` - 运行时树位置:${runtimeBase}\n` +
58
+ ` - 默认以可用运行时树为准并尝试向前兼容启动。如需强制版本一致,可设置 PI_WEB_DSH_STRICT_VERSION=1。\n`;
59
+
60
+ if (strictVer) {
61
+ process.stderr.write(
62
+ `[${BIN_NAME}] DSH 运行时版本族不匹配(已开启 PI_WEB_DSH_STRICT_VERSION 严格模式):\n` +
63
+ ` - 检测到运行时版本:${compatibility?.runtimeVersion ?? "未知"}(位于 ${runtimeBase})\n` +
64
+ ` - pi-web-ui 期望版本族:${expectedFamily}(当前依赖 @deepseek-ai/dsh@${expectedVersion})\n\n` +
65
+ `推荐解决方案:\n` +
66
+ ` 1. 全局安装匹配版本的运行时:\n` +
67
+ ` npm i -g @deepseek-ai/dsh@${expectedVersion}\n` +
68
+ ` 2. 或通过独立前缀安装并配置环境变量(推荐,不影响全局 CLI):\n` +
69
+ ` npm i -g @deepseek-ai/dsh@${expectedVersion} --prefix ~/.pi-web/dsh-runtime-${expectedFamily}\n` +
70
+ ` 并在启动 pi-web-ui 时设置环境变量:\n` +
71
+ ` PI_WEB_DSH_RUNTIME=~/.pi-web/dsh-runtime-${expectedFamily}/lib/node_modules\n\n` +
72
+ `详见文档 docs/dsh-engine.md。\n`,
73
+ );
74
+ process.exit(1);
75
+ } else {
76
+ process.stderr.write(verMsg);
77
+ }
78
+ }
79
+
40
80
  const runConfig = process.env.DSH_CORDIS_CONFIG ?? join(HERE, "cordis.yml");
41
81
  const baseBundlePatch = join(runtimeBase, "@deepseek-ai", "dsh-base", "cordis.patch.yml");
42
82
  const overridePatch = join(HERE, "override.patch.yml");
@@ -143,10 +183,18 @@ try {
143
183
  );
144
184
  } catch (err) {
145
185
  const seen = new Set();
186
+ let isTypertFailure = false;
146
187
  const walk = (e, depth) => {
147
188
  if (!e || seen.has(e)) return;
148
189
  seen.add(e);
149
190
  const msg = e?.message ?? String(e);
191
+ if (
192
+ msg.includes("typert contributor") ||
193
+ msg.includes("codec has no create() factory") ||
194
+ msg.includes("typert-loader")
195
+ ) {
196
+ isTypertFailure = true;
197
+ }
150
198
  const indent = " " + " ".repeat(Math.min(depth, 6));
151
199
  process.stderr.write(`${indent}${msg}\n`);
152
200
  const kids = e?.aggregateErrors ?? e?.errors ?? (e?.cause ? [e.cause] : []);
@@ -154,6 +202,12 @@ try {
154
202
  };
155
203
  process.stderr.write(`[${BIN_NAME}] boot 失败: ${err?.message ?? String(err)}\n runtime base: ${runtimeBase}\n`);
156
204
  walk(err, 0);
205
+ if (isTypertFailure || !compatibility?.compatible) {
206
+ process.stderr.write(
207
+ `\n[${BIN_NAME}] 诊断:检测到启动失败。当前运行时版本为 ${compatibility?.runtimeVersion ?? "未知"}(期望版本族 ${expectedFamily})。\n` +
208
+ `若因跨版本破坏性变更引起,请执行 npm i -g @deepseek-ai/dsh@${expectedVersion} 重新安装匹配版本的运行时。\n\n`,
209
+ );
210
+ }
157
211
  process.exit(1);
158
212
  }
159
213
 
@@ -16,12 +16,16 @@
16
16
  // The returned value is always the *bare-module base dir*: the node_modules
17
17
  // root that directly contains the runtime packages. That is what
18
18
  // boot(bareModuleBaseUrl) anchors bare package names (dsh-base rows) to.
19
- import { existsSync } from "node:fs";
20
- import { dirname, join, resolve } from "node:path";
19
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
20
+ import { delimiter, dirname, join, resolve } from "node:path";
21
+ import { homedir } from "node:os";
21
22
  import { fileURLToPath } from "node:url";
22
23
 
23
24
  const HERE = dirname(fileURLToPath(import.meta.url));
24
25
 
26
+ /** 兜底固定的 DSH 版本族,与 package.json / lockfile 对齐 */
27
+ export const FALLBACK_DSH_VERSION = "0.2.1-rc.2";
28
+
25
29
  /** Given a candidate node_modules root, return the bare-module base dir, or null. */
26
30
  export function runtimeBaseFor(root) {
27
31
  if (root == null) return null;
@@ -42,51 +46,360 @@ export function runtimeBaseFor(root) {
42
46
  return null;
43
47
  }
44
48
 
49
+ /** 向上查找 pi-web-ui 包根目录(支持源码态 server/ 与构建态 dist/) */
50
+ export function findLocalPackageRoot(startDir = HERE) {
51
+ let cur = resolve(startDir);
52
+ for (let i = 0; i < 6; i++) {
53
+ const pkgPath = join(cur, "package.json");
54
+ if (existsSync(pkgPath)) {
55
+ try {
56
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
57
+ if (pkg.name === "pi-web-ui") return cur;
58
+ } catch {}
59
+ }
60
+ const parent = dirname(cur);
61
+ if (parent === cur) break;
62
+ cur = parent;
63
+ }
64
+ return null;
65
+ }
66
+
45
67
  /**
46
- * Resolution order:
47
- * 1. $PI_WEB_DSH_RUNTIME — explicit node_modules root
48
- * 2. this package's node_modules — full local install scenario
49
- * 3. execPath-adjacent node_modules — fnm / standalone node stable layout
50
- * (<node.exe dir>/node_modules is a junction to the global tree)
51
- * 4. `npm root -g` — global install (win32 .cmd shim needs a shell)
68
+ * 提取 DSH 版本族。
69
+ * 在 pre-release(0.x)阶段,按 major.minor 分族(如 0.1.x 同族,0.2.x 同族),
70
+ * 既隔离 0.1 与 0.2 底层重大协议断裂,又避免 patch/rc 微调时过度阻断;正式版(>=1.0)按 major 分族。
52
71
  */
53
- export async function resolveRuntimeBase() {
54
- const explicit = process.env.PI_WEB_DSH_RUNTIME;
55
- if (explicit) {
56
- const base = runtimeBaseFor(explicit);
57
- if (base) return base;
72
+ export function getDshFamily(version) {
73
+ if (!version || typeof version !== "string") return "";
74
+ const clean = version.replace(/^[v^~]/, "").trim();
75
+ const m = clean.match(/^(\d+)\.(\d+)/);
76
+ if (!m) return clean;
77
+ const [, major, minor] = m;
78
+ if (major === "0") {
79
+ return `${major}.${minor}`;
58
80
  }
59
- const local = join(resolve(HERE, "..", "..", ".."), "node_modules");
60
- {
61
- const base = runtimeBaseFor(local);
62
- if (base) return base;
81
+ return `${major}`;
82
+ }
83
+
84
+ /** 读取运行时树中已安装的 @deepseek-ai/dsh-base 版本 */
85
+ export function getRuntimeDshVersion(runtimeBase) {
86
+ if (!runtimeBase) return null;
87
+ const pkgPath = join(runtimeBase, "@deepseek-ai", "dsh-base", "package.json");
88
+ if (existsSync(pkgPath)) {
89
+ try {
90
+ return JSON.parse(readFileSync(pkgPath, "utf8")).version || null;
91
+ } catch {
92
+ return null;
93
+ }
63
94
  }
64
- const adjacent = join(dirname(process.execPath), "node_modules");
65
- {
66
- const base = runtimeBaseFor(adjacent);
67
- if (base) return base;
95
+ return null;
96
+ }
97
+
98
+ /** 读取 pi-web-ui 本地期望绑定的 DSH 版本 */
99
+ export function getExpectedDshVersion(pkgRoot) {
100
+ const root = pkgRoot || findLocalPackageRoot(HERE);
101
+ if (root) {
102
+ try {
103
+ const p = join(root, "node_modules", "@deepseek-ai", "dsh-sdk-jsonrpc-server", "package.json");
104
+ if (existsSync(p)) {
105
+ const v = JSON.parse(readFileSync(p, "utf8")).version;
106
+ if (v) return v;
107
+ }
108
+ } catch {}
109
+ try {
110
+ const p = join(root, "package.json");
111
+ if (existsSync(p)) {
112
+ const pkg = JSON.parse(readFileSync(p, "utf8"));
113
+ const v = pkg.dependencies?.["@deepseek-ai/dsh-sdk-jsonrpc-server"];
114
+ if (v) return v.replace(/^[v^~]/, "").trim();
115
+ }
116
+ } catch {}
68
117
  }
69
- // PATCHED (pi-web-ui #78 / Android-Termux deadlock): this used to run
70
- // spawnSync("npm", ["root", "-g"]) as a last resort — a synchronous fork
71
- // inside a multi-threaded process, which can deadlock on Android/Termux
72
- // (child stuck between fork and exec while the caller blocks on libuv's
73
- // spawn error pipe). Compute the npm global root without spawning instead.
74
- try {
75
- const prefixCandidates = [
76
- process.env.NPM_CONFIG_PREFIX,
77
- process.env.npm_config_prefix,
78
- join(dirname(process.execPath), ".."),
79
- ];
80
- for (const prefix of prefixCandidates) {
81
- if (!prefix) continue;
82
- for (const root of [join(prefix, "lib", "node_modules"), join(prefix, "node_modules")]) {
83
- if (!existsSync(root)) continue;
84
- const base = runtimeBaseFor(root);
85
- if (base) return base;
118
+ return FALLBACK_DSH_VERSION;
119
+ }
120
+
121
+ /** 校验运行时树与 pi-web-ui 依赖的版本族兼容性 */
122
+ export function checkDshRuntimeCompatibility(runtimeBase, expectedVersion) {
123
+ const runtimeVersion = getRuntimeDshVersion(runtimeBase);
124
+ const expected = expectedVersion || getExpectedDshVersion();
125
+ const runtimeFamily = getDshFamily(runtimeVersion);
126
+ const expectedFamily = getDshFamily(expected);
127
+ const compatible = Boolean(runtimeFamily && expectedFamily && runtimeFamily === expectedFamily);
128
+ return {
129
+ compatible,
130
+ runtimeVersion,
131
+ expectedVersion: expected,
132
+ runtimeFamily,
133
+ expectedFamily,
134
+ };
135
+ }
136
+
137
+ /** 解析 .npmrc 内容中的 prefix 配置值 */
138
+ export function parseNpmrcPrefix(content) {
139
+ if (!content || typeof content !== "string") return null;
140
+ const lines = content.split(/\r?\n/);
141
+ for (const line of lines) {
142
+ const trimmed = line.trim();
143
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;
144
+ const m = trimmed.match(/^prefix\s*=\s*(.+)$/);
145
+ if (m) {
146
+ let val = m[1].trim();
147
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
148
+ val = val.slice(1, -1).trim();
149
+ }
150
+ if (val.startsWith("~")) {
151
+ val = join(homedir(), val.slice(1));
86
152
  }
153
+ return resolve(val);
87
154
  }
88
- } catch {
89
- /* fall through */
90
155
  }
91
156
  return null;
92
157
  }
158
+
159
+ /** 从常见 npmrc 位置发现用户与系统配置的 prefix */
160
+ export function findPrefixFromNpmrc() {
161
+ const prefixes = [];
162
+ const npmrcLocations = [
163
+ join(homedir(), ".npmrc"),
164
+ process.env.PREFIX ? join(process.env.PREFIX, "etc", "npmrc") : null,
165
+ process.platform === "win32"
166
+ ? process.env.APPDATA
167
+ ? join(process.env.APPDATA, "npm", "etc", "npmrc")
168
+ : null
169
+ : "/usr/local/etc/npmrc",
170
+ process.platform === "win32"
171
+ ? process.env.ProgramFiles
172
+ ? join(process.env.ProgramFiles, "nodejs", "etc", "npmrc")
173
+ : null
174
+ : "/etc/npmrc",
175
+ process.platform !== "win32" ? "/usr/etc/npmrc" : null,
176
+ ].filter(Boolean);
177
+
178
+ for (const loc of npmrcLocations) {
179
+ try {
180
+ if (existsSync(loc)) {
181
+ const content = readFileSync(loc, "utf8");
182
+ const p = parseNpmrcPrefix(content);
183
+ if (p && !prefixes.includes(p)) {
184
+ prefixes.push(p);
185
+ }
186
+ }
187
+ } catch {}
188
+ }
189
+ return prefixes;
190
+ }
191
+
192
+ /** 从 $PATH 中探测 dsh / pi-web-ui / npm 二进制并推导 node_modules 候选 */
193
+ export function findCandidatesFromPath() {
194
+ const candidates = [];
195
+ const rawPath = process.env.PATH || process.env.Path || "";
196
+ if (!rawPath) return candidates;
197
+
198
+ const binNames =
199
+ process.platform === "win32"
200
+ ? [
201
+ "dsh.cmd",
202
+ "dsh.ps1",
203
+ "dsh.exe",
204
+ "dsh",
205
+ "pi-web-ui.cmd",
206
+ "pi-web-ui.ps1",
207
+ "pi-web-ui.exe",
208
+ "pi-web-ui",
209
+ "npm.cmd",
210
+ "npm.ps1",
211
+ "npm.exe",
212
+ "npm",
213
+ ]
214
+ : ["dsh", "pi-web-ui", "npm"];
215
+
216
+ const dirs = rawPath.split(delimiter).filter(Boolean);
217
+ for (const dir of dirs) {
218
+ let dirExists = false;
219
+ try {
220
+ dirExists = existsSync(dir);
221
+ } catch {}
222
+ if (!dirExists) continue;
223
+
224
+ for (const bin of binNames) {
225
+ const binPath = join(dir, bin);
226
+ let binExists = false;
227
+ try {
228
+ binExists = existsSync(binPath);
229
+ } catch {}
230
+ if (!binExists) continue;
231
+
232
+ // a) 符号链接真实路径反查 node_modules 根
233
+ try {
234
+ const real = realpathSync(binPath);
235
+ const nmIdx = real.lastIndexOf("node_modules");
236
+ if (nmIdx !== -1) {
237
+ const nmRoot = real.slice(0, nmIdx + "node_modules".length);
238
+ candidates.push({ path: nmRoot, source: `path:${bin} (symlink realpath)` });
239
+ }
240
+ } catch {}
241
+
242
+ // b) Windows npm 全局安装常见布局:<prefix>/dsh.cmd,对应 <prefix>/node_modules
243
+ candidates.push({ path: join(dir, "node_modules"), source: `path:${bin} (adjacent)` });
244
+ candidates.push({ path: join(dir, "lib", "node_modules"), source: `path:${bin} (lib)` });
245
+
246
+ // c) POSIX npm 全局安装常见布局:<prefix>/bin/dsh,对应 <prefix>/lib/node_modules
247
+ const parent = dirname(dir);
248
+ if (parent && parent !== dir) {
249
+ candidates.push({ path: join(parent, "lib", "node_modules"), source: `path:${bin} (parent/lib)` });
250
+ candidates.push({ path: join(parent, "node_modules"), source: `path:${bin} (parent)` });
251
+ }
252
+ }
253
+ }
254
+ return candidates;
255
+ }
256
+
257
+ /**
258
+ * 完整运行时树探测与详情收集(纯 fs 操作,无子进程 spawn,杜绝 Android/Termux 死锁)。
259
+ * 顺序:
260
+ * 1. $PI_WEB_DSH_RUNTIME — 显式指定最高优先级
261
+ * 2. 本包(pi-web-ui)的 node_modules
262
+ * 3. execPath 邻近 node_modules
263
+ * 4. 从 $PATH 二进制推断的全局目录(支持符号链接 realpath 反查)
264
+ * 5. 从 .npmrc prefix 配置派生的全局目录
265
+ * 6. 环境变量 NPM_CONFIG_PREFIX / npm_config_prefix / PREFIX
266
+ * 7. 系统常见全局 node_modules 目录
267
+ */
268
+ export async function resolveRuntimeBaseWithDetails() {
269
+ const scannedPaths = [];
270
+ const seenPaths = new Set();
271
+ let firstFoundBase = null;
272
+ let firstCompatibleBase = null;
273
+
274
+ const expectedVersion = getExpectedDshVersion();
275
+
276
+ const probe = (candidatePath, source) => {
277
+ if (!candidatePath) return null;
278
+ const norm = resolve(candidatePath);
279
+ if (seenPaths.has(norm)) return null;
280
+ seenPaths.add(norm);
281
+
282
+ let exists = false;
283
+ try {
284
+ exists = existsSync(norm);
285
+ } catch {}
286
+
287
+ if (!exists) {
288
+ scannedPaths.push({ path: norm, exists: false, validRuntime: false, source });
289
+ return null;
290
+ }
291
+
292
+ const base = runtimeBaseFor(norm);
293
+ if (!base) {
294
+ scannedPaths.push({
295
+ path: norm,
296
+ exists: true,
297
+ validRuntime: false,
298
+ reason: "缺少 @deepseek-ai/dsh-base 或 dsh-app-boot",
299
+ source,
300
+ });
301
+ return null;
302
+ }
303
+
304
+ const compat = checkDshRuntimeCompatibility(base, expectedVersion);
305
+ scannedPaths.push({
306
+ path: norm,
307
+ exists: true,
308
+ validRuntime: true,
309
+ base,
310
+ version: compat.runtimeVersion,
311
+ family: compat.runtimeFamily,
312
+ compatible: compat.compatible,
313
+ source,
314
+ });
315
+
316
+ if (!firstFoundBase) {
317
+ firstFoundBase = base;
318
+ }
319
+ if (compat.compatible && !firstCompatibleBase) {
320
+ firstCompatibleBase = base;
321
+ }
322
+
323
+ return base;
324
+ };
325
+
326
+ // 1. $PI_WEB_DSH_RUNTIME — 显式指定
327
+ const explicit = process.env.PI_WEB_DSH_RUNTIME;
328
+ if (explicit) {
329
+ const base = probe(explicit, "env:PI_WEB_DSH_RUNTIME");
330
+ if (base) {
331
+ return {
332
+ base,
333
+ scannedPaths,
334
+ compatibility: checkDshRuntimeCompatibility(base, expectedVersion),
335
+ };
336
+ }
337
+ }
338
+
339
+ // 2. 本包(pi-web-ui)的 node_modules
340
+ const pkgRoot = findLocalPackageRoot(HERE);
341
+ if (pkgRoot) {
342
+ probe(join(pkgRoot, "node_modules"), "local:packageRoot");
343
+ }
344
+ probe(join(resolve(HERE, "..", "..", ".."), "node_modules"), "local:relative-3");
345
+ probe(join(resolve(HERE, "..", "..", "..", ".."), "node_modules"), "local:relative-4");
346
+
347
+ // 3. execPath 邻近 node_modules
348
+ probe(join(dirname(process.execPath), "node_modules"), "execPath:adjacent");
349
+ probe(join(dirname(process.execPath), "..", "lib", "node_modules"), "execPath:parent-lib");
350
+ probe(join(dirname(process.execPath), "..", "node_modules"), "execPath:parent");
351
+
352
+ // 4. 从 $PATH 中探测到的候选
353
+ for (const cand of findCandidatesFromPath()) {
354
+ probe(cand.path, cand.source);
355
+ }
356
+
357
+ // 5. 从 npmrc 中探测到的 prefix
358
+ for (const p of findPrefixFromNpmrc()) {
359
+ probe(join(p, "lib", "node_modules"), "npmrc:prefix-lib");
360
+ probe(join(p, "node_modules"), "npmrc:prefix");
361
+ }
362
+
363
+ // 6. 环境变量里的前缀
364
+ const envPrefixes = [process.env.NPM_CONFIG_PREFIX, process.env.npm_config_prefix, process.env.PREFIX];
365
+ for (const p of envPrefixes) {
366
+ if (p) {
367
+ probe(join(p, "lib", "node_modules"), "env:prefix-lib");
368
+ probe(join(p, "node_modules"), "env:prefix");
369
+ }
370
+ }
371
+
372
+ // 7. 常见系统默认路径
373
+ if (process.platform === "win32") {
374
+ if (process.env.APPDATA) probe(join(process.env.APPDATA, "npm", "node_modules"), "default:win-appdata");
375
+ if (process.env.LOCALAPPDATA)
376
+ probe(join(process.env.LOCALAPPDATA, "npm", "node_modules"), "default:win-localappdata");
377
+ if (process.env.ProgramFiles)
378
+ probe(join(process.env.ProgramFiles, "nodejs", "node_modules"), "default:win-programfiles");
379
+ } else {
380
+ probe("/usr/local/lib/node_modules", "default:posix-usr-local");
381
+ probe("/usr/lib/node_modules", "default:posix-usr");
382
+ const home = homedir();
383
+ probe(join(home, ".local", "npm", "lib", "node_modules"), "default:posix-home-local-npm");
384
+ probe(join(home, ".local", "npm", "node_modules"), "default:posix-home-local-npm-flat");
385
+ probe(join(home, ".local", "lib", "node_modules"), "default:posix-home-local");
386
+ probe(join(home, ".npm-global", "lib", "node_modules"), "default:posix-npm-global");
387
+ probe(join(home, ".npm-global", "node_modules"), "default:posix-npm-global-flat");
388
+ }
389
+
390
+ // 若存在同版本族的有效树,优先选择;否则回退至首个可用树(由 launcher 报错指引版本)
391
+ const chosenBase = firstCompatibleBase || firstFoundBase || null;
392
+ const compatibility = chosenBase ? checkDshRuntimeCompatibility(chosenBase, expectedVersion) : null;
393
+
394
+ return {
395
+ base: chosenBase,
396
+ scannedPaths,
397
+ compatibility,
398
+ };
399
+ }
400
+
401
+ /** 供已有代码直接获取有效 runtimeBase 路径 */
402
+ export async function resolveRuntimeBase() {
403
+ const { base } = await resolveRuntimeBaseWithDetails();
404
+ return base;
405
+ }
@@ -139,6 +139,9 @@ export class DurableAgentService {
139
139
  applyPluginCommandCatalog() {
140
140
  // 斜杠命令热重载通知
141
141
  }
142
+ applyPluginMarkers() {
143
+ // 插件标记热重载通知
144
+ }
142
145
  refreshBackgroundServers() {
143
146
  for (const session of this.sessions.values()) {
144
147
  session.listBgServers();