pi-web-ui 0.118.0 → 0.120.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 (195) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -0,0 +1,93 @@
1
+ import { cpSync, lstatSync, readdirSync, rmSync, rmdirSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
3
+ /**
4
+ * 复制目录树的单源原语。
5
+ *
6
+ * 为什么必须集中一处:判据只在**相对路径**上生效才有意义。npm -g 安装时源目录自身就在
7
+ * `.../node_modules/pi-web-ui/plugins/<id>` 里,用绝对路径去匹配 `node_modules` 会把整棵树
8
+ * (连根带叶)全部过滤掉,得到一份空副本还以为成功(issue #856)。
9
+ */
10
+ /** 默认永不复制的内容:版本库元数据与可重装的依赖树 */
11
+ export const SKIP_VCS_AND_DEPS = [".git", "node_modules"];
12
+ export function toPosixPath(rel) {
13
+ return sep === "/" ? rel : rel.split(sep).join("/");
14
+ }
15
+ /** 相对路径里出现被跳过名字的任意一段即跳过;源根(`""`)永远放行 */
16
+ export function isSkippedPath(rel, skip) {
17
+ if (!rel)
18
+ return false;
19
+ return rel.split(/[\\/]/).some((part) => skip.includes(part));
20
+ }
21
+ export function copyTree(src, dst, opts = {}) {
22
+ const skip = opts.skip ?? SKIP_VCS_AND_DEPS;
23
+ cpSync(src, dst, {
24
+ recursive: true,
25
+ // 判据用相对路径:源根路径本身可能含 node_modules(全局安装布局)
26
+ filter: (from, to) => {
27
+ if (isSkippedPath(relative(src, from), skip))
28
+ return false;
29
+ // 只补缺:目录必须放行(否则整棵子树都进不来),已存在的文件一律不覆盖
30
+ if (!opts.missingOnly)
31
+ return true;
32
+ try {
33
+ return lstatSync(from).isDirectory() || !statExists(to);
34
+ }
35
+ catch {
36
+ return true;
37
+ }
38
+ },
39
+ });
40
+ }
41
+ function statExists(path) {
42
+ try {
43
+ lstatSync(path);
44
+ return true;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /** 列出目录树里的普通文件(posix 相对路径,已排序),跳过 `skip` 命中的目录 */
51
+ export function listTreeFiles(root, opts = {}) {
52
+ const skip = opts.skip ?? SKIP_VCS_AND_DEPS;
53
+ const out = [];
54
+ const walk = (dir) => {
55
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
56
+ if (skip.includes(entry.name))
57
+ continue;
58
+ const abs = join(dir, entry.name);
59
+ if (entry.isDirectory())
60
+ walk(abs);
61
+ else if (entry.isFile())
62
+ out.push(toPosixPath(relative(root, abs)));
63
+ }
64
+ };
65
+ walk(root);
66
+ return out.sort();
67
+ }
68
+ /** 删除 `stale` 列出的文件(只接受 root 内的相对路径),并顺手清理空出来的目录 */
69
+ export function pruneTreeFiles(root, stale) {
70
+ for (const rel of stale) {
71
+ if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).includes(".."))
72
+ continue;
73
+ const abs = join(root, rel);
74
+ try {
75
+ rmSync(abs, { force: true });
76
+ }
77
+ catch {
78
+ continue;
79
+ }
80
+ let dir = dirname(abs);
81
+ while (dir !== root && dir.startsWith(root)) {
82
+ try {
83
+ if (readdirSync(dir).length)
84
+ break;
85
+ rmdirSync(dir);
86
+ }
87
+ catch {
88
+ break;
89
+ }
90
+ dir = dirname(dir);
91
+ }
92
+ }
93
+ }
@@ -7,7 +7,6 @@ const WRITE_TOOLS = new Set([
7
7
  "write_file",
8
8
  "edit",
9
9
  "edit_file",
10
- "edit_soft",
11
10
  "apply_patch",
12
11
  "patch",
13
12
  "patch_tool",
@@ -158,8 +157,8 @@ export function goalReviewDenial(toolName, params) {
158
157
  }
159
158
  return {
160
159
  kind: "dispatch-tool",
161
- reason: `目标审查回合:不能调用 subagent(action="${act || "spawn"}") —— 轮次由服务端控制。请只做本轮审查、只回 verdict JSON。`,
162
- reasonEn: `Goal review round: subagent(action="${act || "spawn"}") is unavailable — the server owns the rounds. Just review this round and reply with only the verdict JSON.`,
160
+ reason: `目标审查回合:不能调用 conversation(action="${act || "spawn"}") —— 轮次由服务端控制。请只做本轮审查、只回 verdict JSON。`,
161
+ reasonEn: `Goal review round: conversation(action="${act || "spawn"}") is unavailable — the server owns the rounds. Just review this round and reply with only the verdict JSON.`,
163
162
  };
164
163
  }
165
164
  if (DISPATCH_TOOLS.has(name)) {
@@ -78,6 +78,7 @@ import { createDeviceDesktop } from "./device-center/desktop.js";
78
78
  import { createDeviceLanAccess } from "./device-center/device-lan-access.js";
79
79
  import { createHostMetricsSampler } from "./host-metrics.js";
80
80
  import { SchedulerStore } from "./scheduler-tasks.js";
81
+ import { BackgroundExecutorRegistry } from "./background-executors.js";
81
82
  import { initHttpProxy } from "./http-proxy.js";
82
83
  import { globalLspPool } from "./lsp-tool.js";
83
84
  import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
@@ -530,6 +531,8 @@ app.get("/api/health", (_req, res) => {
530
531
  engine: currentDefaultEngine,
531
532
  instanceName: process.env.PI_WEB_INSTANCE_NAME?.trim() || undefined,
532
533
  faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
534
+ executors: backgroundExecutors.snapshotLive(),
535
+ unhealthy: backgroundExecutors.unhealthy(),
533
536
  });
534
537
  });
535
538
  app.use(["/api/file", "/api/attachment/:hash", "/api/preview"], (req, res, next) => {
@@ -1202,7 +1205,7 @@ function ensureEngine(engine) {
1202
1205
  agentDir: getAgentDir(),
1203
1206
  stateStore: sharedStateStore,
1204
1207
  engine: "codex",
1205
- driverFactory: (cwd) => new CodexDriver(cwd),
1208
+ driverFactory: (cwd) => new CodexDriver(cwd, { agentDir: getAgentDir(), dataDir: DATA_DIR }),
1206
1209
  });
1207
1210
  for (let i = 0; i < sharedSocketCount; i++)
1208
1211
  codexServiceInstance.noteSocketOpen();
@@ -1235,7 +1238,7 @@ function ensureEngine(engine) {
1235
1238
  dataDir: DATA_DIR,
1236
1239
  agentDir: getAgentDir(),
1237
1240
  stateStore: sharedStateStore,
1238
- driverFactory: (cwd) => new ClaudeCodeDriver(cwd, { agentDir: getAgentDir() }),
1241
+ driverFactory: (cwd) => new ClaudeCodeDriver(cwd, { agentDir: getAgentDir(), dataDir: DATA_DIR }),
1239
1242
  });
1240
1243
  for (let i = 0; i < sharedSocketCount; i++)
1241
1244
  claudeServiceInstance.noteSocketOpen();
@@ -1411,6 +1414,21 @@ const service = {
1411
1414
  }
1412
1415
  return Promise.resolve();
1413
1416
  },
1417
+ /**
1418
+ * 关闭对话:pi 引擎走 daemon 的跨客户端路由(左栏 elsewhere / 离线残骸行都能删)。
1419
+ * 其他引擎的 `dismissConversation` 是本端语义(id, withFinished, force),不能当 daemon 路由用,
1420
+ * 直接退回请求方自己的会话。
1421
+ */
1422
+ async dismissConversation(clientId, msg) {
1423
+ const engine = ensureEngine(resolveClientEngine(clientId));
1424
+ if (engine instanceof AgentService)
1425
+ return engine.dismissConversation(clientId, msg);
1426
+ const cs = engine.get(clientId);
1427
+ if (!cs?.dismissConversation)
1428
+ return false;
1429
+ await cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
1430
+ return true;
1431
+ },
1414
1432
  peekElsewhereQuestion(targetId, ownerId, convId) {
1415
1433
  const targetSvc = ensureEngine(resolveClientEngine(targetId));
1416
1434
  if (typeof targetSvc.peekElsewhereQuestion === "function") {
@@ -1445,6 +1463,20 @@ initAttachmentStore(DATA_DIR);
1445
1463
  loadServerStrings(DATA_DIR);
1446
1464
  const pluginMgr = new PluginManager(DATA_DIR, CWD, join(pkgRoot, "plugins", "catalog.json"));
1447
1465
  const pluginInstaller = new PluginInstaller({ dataDir: DATA_DIR, pkgRoot, managed: MANAGED });
1466
+ /**
1467
+ * 后台执行者统一监管:监听端口后启动 `kind: "boot"` 的执行者(常驻插件、定时任务),
1468
+ * 60s 探针写入 /api/health。以前插件只能寄生在首个 WS attach 上,没人开页面就不上线。
1469
+ */
1470
+ const backgroundExecutors = new BackgroundExecutorRegistry({
1471
+ log: (level, message) => {
1472
+ if (level === "error")
1473
+ console.error(`[background] ${message}`);
1474
+ else if (level === "warning")
1475
+ console.warn(`[background] ${message}`);
1476
+ else
1477
+ console.log(`[background] ${message}`);
1478
+ },
1479
+ });
1448
1480
  async function reloadPluginsAndPush(lang) {
1449
1481
  await pluginMgr.reload(lang);
1450
1482
  await pluginMgr.pushToAll();
@@ -1686,7 +1718,8 @@ const scheduler = new SchedulerStore(DATA_DIR, {
1686
1718
  catch { }
1687
1719
  },
1688
1720
  });
1689
- scheduler.start();
1721
+ // 定时任务不再在模块顶层直接 start —— 由 backgroundExecutors 的 boot 阶段统一拉起,
1722
+ // 这样它的启用时机、失败与健康快照和其它常驻执行者一致。
1690
1723
  function pushSchedulerTasks() {
1691
1724
  try {
1692
1725
  const payload = JSON.stringify({ type: "scheduler_tasks", tasks: scheduler.list() });
@@ -1777,6 +1810,56 @@ pluginMgr.onAgentToolsChanged = () => {
1777
1810
  pluginMgr.onCommandsChanged = () => service.applyPluginCommandCatalog();
1778
1811
  pluginMgr.onMarkersChanged = () => service.applyPluginMarkers?.();
1779
1812
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1813
+ // ── 后台执行者登记:所有「无客户端连接也该活着」的组件都在这里启动 ──
1814
+ // 只影响 boot 期插件诊断文案的语言(无客户端时取不到 cs.getLang()),复用已有的 PI_WEB_LOCALE。
1815
+ const bootLang = () => process.env.PI_WEB_LOCALE?.trim() || "zh";
1816
+ backgroundExecutors.register({
1817
+ id: "scheduler",
1818
+ kind: "boot",
1819
+ start: () => {
1820
+ scheduler.start();
1821
+ },
1822
+ health: () => {
1823
+ const tasks = scheduler.list();
1824
+ const enabled = tasks.filter((t) => t.enabled).length;
1825
+ return { ok: true, detail: `${tasks.length} task(s), ${enabled} enabled`, stats: { tasks: tasks.length, enabled } };
1826
+ },
1827
+ });
1828
+ backgroundExecutors.register({
1829
+ id: "plugins:always-on",
1830
+ kind: "boot",
1831
+ // 激活失败通常是暂时的(数据目录瞬断 / 外部依赖未就绪):5min 冷却、最多 3 次,之后只报警。
1832
+ restart: "on-failure",
1833
+ start: async () => {
1834
+ const plugins = await pluginMgr.rescanAlwaysOn(bootLang);
1835
+ const alwaysOn = plugins.filter((p) => p.alwaysOn === true);
1836
+ const failed = alwaysOn.filter((p) => p.error);
1837
+ if (failed.length > 0) {
1838
+ throw new Error(`${failed.length}/${alwaysOn.length} alwaysOn plugin(s) failed: ${failed.map((p) => p.id).join(", ")}`);
1839
+ }
1840
+ },
1841
+ health: () => {
1842
+ const loaded = pluginMgr.alwaysOnSnapshot();
1843
+ const broken = loaded.filter((p) => !p.active);
1844
+ // 出站/入站的死信与积压是「静默失败」的唯一可观测出口,一起进 health。
1845
+ const delivery = pluginMgr.deliveryStats();
1846
+ const deadLetters = delivery.totalDead;
1847
+ return {
1848
+ ok: broken.length === 0,
1849
+ detail: broken.length > 0
1850
+ ? `${broken.length}/${loaded.length} alwaysOn plugin(s) not active: ${broken.map((p) => p.id).join(", ")}`
1851
+ : `${loaded.length} alwaysOn plugin(s) active; outbox queued ${delivery.totalQueued}, dead letters ${deadLetters}`,
1852
+ stats: {
1853
+ active: loaded.length - broken.length,
1854
+ total: loaded.length,
1855
+ ids: loaded.map((p) => p.id),
1856
+ outbox: delivery.plugins,
1857
+ outboxQueued: delivery.totalQueued,
1858
+ deadLetters,
1859
+ },
1860
+ };
1861
+ },
1862
+ });
1780
1863
  {
1781
1864
  const pm = pluginMgr;
1782
1865
  const pickClient = () => {
@@ -2896,6 +2979,12 @@ httpServer.listen(PORT, HOST, () => {
2896
2979
  console.warn(" ─────────────────────────────────────────────────────────────────────────────");
2897
2980
  }
2898
2981
  console.log("");
2982
+ // 无客户端连接也能跑的后台执行者(常驻插件 / 定时任务):永不抛错、不阻断监听。
2983
+ void backgroundExecutors
2984
+ .startAll()
2985
+ .then(() => backgroundExecutors.probe())
2986
+ .then(() => backgroundExecutors.startProbing())
2987
+ .catch((err) => console.warn(`[background] start failed: ${err.message}`));
2899
2988
  });
2900
2989
  scheduleUploadCleanup();
2901
2990
  const OFFICIAL_PLUGIN_CATALOG_URL = "https://xing-shuyin.github.io/pi-web-ui-plugins/catalog.json";
@@ -0,0 +1,345 @@
1
+ /**
2
+ * 进程内后台任务注册表:`bash({ background: true })` 的落点。
3
+ *
4
+ * 为什么不直接调 `scripts/safe-exec.mjs`:发布包(npm / 桌面)不带 `scripts/`,而且那个脚本的
5
+ * `.pid/.state.json/.cursor` 三件套 + detach 守护进程,本质是补偿「调用方不常驻」。pi-web-ui 的
6
+ * server 本身就常驻,所以这里只保留真正有用的机件:
7
+ * - 跨平台启动目标(Windows 优先 Git Bash,回退 cmd.exe;POSIX 用 bash/sh)
8
+ * - 子进程 stdin 接空设备(交互确认 / pager / REPL 一律读到 EOF,永不阻塞)
9
+ * - 原始输出先落盘,只按需回显尾部(不淹没上下文)
10
+ * - 总时长硬超时 + 空闲看门狗(0 = 关闭)
11
+ * - 进程树终止复用 `server/process-utils.ts` 的 killPidTree(单源)
12
+ *
13
+ * 不做的:日志游标文件、守护进程巡检、孤儿 jobfile 状态机 —— 进程挂在 server 上,正常退出时由
14
+ * dispose() 杀整棵进程树收场;server 被强杀留下的子进程目前只能靠面板 / `killPidTree` 手动清,
15
+ * 没有启动扫描(刻意不做:宁可漏报也不能拿存盘 pid 去杀陌生进程)。
16
+ *
17
+ * 与 `scripts/safe-exec.mjs` 的分工:那个脚本吃 argv、带 `--shell-bin` / `.cmd` 垫片解析 /
18
+ * detach 守护进程,服务的对象是「调用方不常驻」的 CI 与人工终端;这里吃整行命令字符串,服务的
19
+ * 对象是常驻 server 内的 bash 工具。两者共用 `killPidTree` 单源,其余各自演进,不强行合体。
20
+ */
21
+ import { spawn } from "node:child_process";
22
+ import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, readSync, statSync } from "node:fs";
23
+ import { join, resolve } from "node:path";
24
+ import { killPidTree, pidAlive } from "./process-utils.js";
25
+ import { MAX_BACKGROUND_TIMEOUT_SEC } from "./bash-timeout.js";
26
+ const BASH_LIKE_SHELL = /(?:^|[\\/])(?:bash|sh|zsh|dash)(?:\.exe)?$/i;
27
+ const READ_WINDOW = 256 * 1024;
28
+ const TAIL_DEFAULT = 40;
29
+ const FIRST_OUTPUT_WAIT_MS = 600;
30
+ /** 面板行 taskId 前缀:`list()` 生成与 `killBackgroundServer()` 解析必须同源(别各写一份 "job:")。 */
31
+ export const JOB_TASK_PREFIX = "job:";
32
+ /** Windows 下优先真 Git Bash:模型写的 `&&` / POSIX 路径 / 管道才不会被 cmd.exe 认错。 */
33
+ export function pickJobShell() {
34
+ if (process.platform !== "win32")
35
+ return existsSync("/bin/bash") ? "/bin/bash" : "sh";
36
+ const candidates = [
37
+ process.env.PI_WEB_SHELL,
38
+ process.env.EXEPATH && join(process.env.EXEPATH, "usr", "bin", "bash.exe"),
39
+ "C:\\Program Files\\Git\\bin\\bash.exe",
40
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
41
+ ];
42
+ for (const candidate of candidates) {
43
+ if (candidate && BASH_LIKE_SHELL.test(candidate) && existsSync(candidate))
44
+ return candidate;
45
+ }
46
+ return process.env.ComSpec ?? "cmd.exe";
47
+ }
48
+ /** 整行命令 → spawn 目标。bash 类 shell 用 `-c`;cmd.exe 用 `/d /s /c`(不经 Node 的 shell:true,引号可预期)。 */
49
+ export function bootCommand(command, shell = pickJobShell()) {
50
+ if (process.platform !== "win32" || BASH_LIKE_SHELL.test(shell))
51
+ return { file: shell, args: ["-c", command] };
52
+ return { file: shell, args: ["/d", "/s", "/c", command] };
53
+ }
54
+ function slug(text) {
55
+ const cleaned = text.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
56
+ return (cleaned || "job").slice(0, 48);
57
+ }
58
+ function readTail(path, lines) {
59
+ if (lines <= 0 || !existsSync(path))
60
+ return "";
61
+ const size = statSync(path).size;
62
+ if (size === 0)
63
+ return "";
64
+ const window = Math.min(size, READ_WINDOW);
65
+ const fd = openSync(path, "r");
66
+ try {
67
+ const buffer = Buffer.allocUnsafe(window);
68
+ readSync(fd, buffer, 0, window, size - window);
69
+ const text = buffer.toString("utf8");
70
+ const all = text.split(/\r?\n/);
71
+ return all.slice(-lines).join("\n").trimEnd();
72
+ }
73
+ finally {
74
+ closeSync(fd);
75
+ }
76
+ }
77
+ function readFrom(path, offset) {
78
+ if (!existsSync(path))
79
+ return { text: "", next: offset };
80
+ const size = statSync(path).size;
81
+ if (size <= offset)
82
+ return { text: "", next: offset };
83
+ const start = Math.max(offset, size - READ_WINDOW);
84
+ const fd = openSync(path, "r");
85
+ try {
86
+ const buffer = Buffer.allocUnsafe(size - start);
87
+ readSync(fd, buffer, 0, size - start, start);
88
+ return { text: buffer.toString("utf8"), next: size };
89
+ }
90
+ finally {
91
+ closeSync(fd);
92
+ }
93
+ }
94
+ export class JobRegistry {
95
+ jobs = new Map();
96
+ seq = 0;
97
+ disposed = false;
98
+ logDir;
99
+ opts;
100
+ constructor(opts = {}) {
101
+ this.opts = opts;
102
+ this.logDir = opts.logDir ?? (() => join(process.cwd(), ".safe-exec", "jobs"));
103
+ }
104
+ get size() {
105
+ return this.jobs.size;
106
+ }
107
+ /** 起一个后台任务:立即返回快照,不等命令结束。 */
108
+ start(spec) {
109
+ if (this.disposed)
110
+ throw new Error("Background job registry is disposed");
111
+ const command = String(spec.command ?? "").trim();
112
+ if (!command)
113
+ throw new Error("background job requires a non-empty command");
114
+ const dir = resolve(this.logDir());
115
+ mkdirSync(dir, { recursive: true });
116
+ const id = `${Date.now().toString(36)}${(++this.seq).toString(36).padStart(2, "0")}`;
117
+ const label = (spec.label ?? command).replace(/\s+/g, " ").slice(0, 120);
118
+ const logPath = join(dir, `${id}-${slug(label)}.log`);
119
+ const stream = createWriteStream(logPath, { flags: "a" });
120
+ const target = bootCommand(command);
121
+ const child = spawn(target.file, target.args, {
122
+ cwd: resolve(spec.cwd),
123
+ stdio: ["ignore", "pipe", "pipe"],
124
+ windowsHide: true,
125
+ // POSIX 下建新进程组:kill(-pid) 能带走整棵树,避免漏杀子进程变孤儿;
126
+ // Windows 不用 detached(taskkill /T 负责整棵树,且 detached 会留下独立控制台窗口)。
127
+ ...(process.platform === "win32" ? {} : { detached: true }),
128
+ env: { ...process.env, PAGER: "cat", GIT_PAGER: "cat", CI: process.env.CI ?? "true" },
129
+ });
130
+ const now = Date.now();
131
+ const record = {
132
+ id,
133
+ child,
134
+ pid: child.pid ?? 0,
135
+ command,
136
+ label,
137
+ cwd: resolve(spec.cwd),
138
+ ...(spec.origin ? { origin: spec.origin } : {}),
139
+ since: now,
140
+ logPath,
141
+ stream,
142
+ timeoutSec: Math.min(Math.max(0, Math.floor(spec.timeoutSec ?? 0)), MAX_BACKGROUND_TIMEOUT_SEC),
143
+ idleTimeoutSec: Math.max(0, Math.floor(spec.idleTimeoutSec ?? 0)),
144
+ lastOutputAt: now,
145
+ timer: null,
146
+ state: "running",
147
+ exitCode: null,
148
+ killing: false,
149
+ readCursor: 0,
150
+ };
151
+ this.jobs.set(id, record);
152
+ stream.write(`[job] ${new Date(now).toISOString()} cwd=${record.cwd} timeout=${record.timeoutSec}s idle=${record.idleTimeoutSec}s\n$ ${command}\n`);
153
+ const onData = (chunk) => {
154
+ const text = String(chunk);
155
+ record.lastOutputAt = Date.now();
156
+ stream.write(text);
157
+ };
158
+ child.stdout?.on("data", onData);
159
+ child.stderr?.on("data", onData);
160
+ child.once("error", (error) => {
161
+ stream.write(`\n[job] SPAWN_ERROR ${error.message}\n`);
162
+ this.finish(record, null, "spawn-error");
163
+ });
164
+ child.once("close", (code) => {
165
+ const tailText = readTail(record.logPath, 40);
166
+ if (tailText)
167
+ stream.write(`${tailText.endsWith("\n") ? "" : "\n"}`);
168
+ this.finish(record, code, record.reason ?? "exit");
169
+ });
170
+ if (record.timeoutSec > 0 || record.idleTimeoutSec > 0) {
171
+ record.timer = setInterval(() => this.check(record), 1000);
172
+ record.timer.unref?.();
173
+ }
174
+ this.opts.onChange?.();
175
+ return this.snapshot(record);
176
+ }
177
+ check(record) {
178
+ if (record.state !== "running" || record.killing)
179
+ return;
180
+ const now = Date.now();
181
+ if (record.timeoutSec > 0 && now - record.since >= record.timeoutSec * 1000) {
182
+ record.reason = "timeout";
183
+ this.kill(record.id);
184
+ return;
185
+ }
186
+ if (record.idleTimeoutSec > 0 && now - record.lastOutputAt >= record.idleTimeoutSec * 1000) {
187
+ record.reason = "idle";
188
+ this.kill(record.id);
189
+ }
190
+ }
191
+ snapshot(record) {
192
+ return {
193
+ id: record.id,
194
+ pid: record.pid,
195
+ command: record.command,
196
+ label: record.label,
197
+ cwd: record.cwd,
198
+ ...(record.origin ? { origin: record.origin } : {}),
199
+ since: record.since,
200
+ logPath: record.logPath,
201
+ state: record.state,
202
+ exitCode: record.exitCode,
203
+ ...(record.reason ? { reason: record.reason } : {}),
204
+ };
205
+ }
206
+ finish(record, exitCode, reason) {
207
+ if (record.state === "exited")
208
+ return;
209
+ if (record.timer) {
210
+ clearInterval(record.timer);
211
+ record.timer = null;
212
+ }
213
+ record.state = "exited";
214
+ record.exitCode = exitCode;
215
+ record.reason = reason;
216
+ record.stream.write(`\n[job] ${reason} exit=${exitCode === null ? "null" : exitCode}\n`);
217
+ record.stream.end();
218
+ const snap = { ...this.snapshot(record), tail: readTail(record.logPath, 20) };
219
+ this.jobs.delete(record.id);
220
+ this.opts.onChange?.();
221
+ try {
222
+ this.opts.onExit?.(snap);
223
+ }
224
+ catch { }
225
+ }
226
+ list() {
227
+ return [...this.jobs.values()].filter((j) => j.state === "running").map((j) => this.snapshot(j));
228
+ }
229
+ get(id) {
230
+ const record = this.jobs.get(id);
231
+ return record ? this.snapshot(record) : undefined;
232
+ }
233
+ /** 非破坏性读尾部(只回尾部,避免上下文被日志淹没)。 */
234
+ tail(id, lines = TAIL_DEFAULT) {
235
+ const record = this.jobs.get(id);
236
+ if (!record)
237
+ return "";
238
+ return readTail(record.logPath, lines);
239
+ }
240
+ /** 增量读:默认推进游标,下一次只回新输出。 */
241
+ readNew(id, opts = {}) {
242
+ const record = this.jobs.get(id);
243
+ if (!record)
244
+ return "";
245
+ const { text, next } = readFrom(record.logPath, record.readCursor);
246
+ if (opts.advance !== false)
247
+ record.readCursor = next;
248
+ return text.trimEnd();
249
+ }
250
+ /** 起任务后等首屏输出:服务类命令通常几百毫秒内会打印 listening 行。 */
251
+ async awaitFirstOutput(id, ms = FIRST_OUTPUT_WAIT_MS) {
252
+ const record = this.jobs.get(id);
253
+ if (!record)
254
+ return "";
255
+ const deadline = Date.now() + Math.max(0, ms);
256
+ while (Date.now() < deadline) {
257
+ const text = readTail(record.logPath, TAIL_DEFAULT);
258
+ if (text)
259
+ return text;
260
+ if (record.state === "exited")
261
+ break;
262
+ await new Promise((r) => setTimeout(r, 100));
263
+ }
264
+ return readTail(record.logPath, TAIL_DEFAULT);
265
+ }
266
+ kill(id) {
267
+ const record = this.jobs.get(id);
268
+ if (!record)
269
+ return false;
270
+ if (record.state !== "running")
271
+ return false;
272
+ record.killing = true;
273
+ record.reason ??= "killed";
274
+ if (record.pid > 1) {
275
+ void killPidTree(record.pid)
276
+ .catch(() => { })
277
+ .finally(() => {
278
+ // taskkill 是异步的:close 事件到了 finish 会自然收场;
279
+ // 若子进程迟迟不退出(Windows 上偶发),兜底强制收场,避免面板上“关不了”。
280
+ setTimeout(() => {
281
+ const cur = this.jobs.get(id);
282
+ if (cur && cur.state === "running" && cur.killing) {
283
+ if (cur.pid > 1)
284
+ void killPidTree(cur.pid).catch(() => { });
285
+ setTimeout(() => {
286
+ const again = this.jobs.get(id);
287
+ if (again && again.state === "running")
288
+ this.finish(again, null, "killed");
289
+ }, 3000);
290
+ }
291
+ }, 4000)?.unref?.();
292
+ });
293
+ }
294
+ else
295
+ this.finish(record, null, "killed");
296
+ return true;
297
+ }
298
+ /** 同步语义的杀:发 kill 后轮询确认进程真死了才返回(给面板停止按钮用,有明确成功/失败)。 */
299
+ async killAndWait(id, timeoutMs = 8000) {
300
+ const record = this.jobs.get(id);
301
+ if (!record)
302
+ return { ok: false, exited: true, timedOut: false };
303
+ if (record.state !== "running")
304
+ return { ok: false, exited: true, timedOut: false };
305
+ this.kill(id);
306
+ const deadline = Date.now() + Math.max(1000, timeoutMs);
307
+ while (Date.now() < deadline) {
308
+ const cur = this.jobs.get(id);
309
+ if (!cur || cur.state !== "running")
310
+ return { ok: true, exited: true, timedOut: false };
311
+ if (cur.pid > 1 && !pidAlive(cur.pid)) {
312
+ const grace = Date.now() + 1500;
313
+ while (Date.now() < grace) {
314
+ const again = this.jobs.get(id);
315
+ if (!again || again.state !== "running")
316
+ return { ok: true, exited: true, timedOut: false };
317
+ await new Promise((r) => setTimeout(r, 200));
318
+ }
319
+ const still = this.jobs.get(id);
320
+ if (still && still.state === "running")
321
+ this.finish(still, null, "killed");
322
+ return { ok: true, exited: true, timedOut: false };
323
+ }
324
+ await new Promise((r) => setTimeout(r, 250));
325
+ }
326
+ return { ok: true, exited: false, timedOut: true };
327
+ }
328
+ killAll() {
329
+ const ids = [...this.jobs.keys()];
330
+ for (const id of ids)
331
+ this.kill(id);
332
+ return ids;
333
+ }
334
+ /** 服务器退出前收场:杀整棵进程树,别留孤儿。 */
335
+ dispose() {
336
+ this.disposed = true;
337
+ for (const record of this.jobs.values()) {
338
+ if (record.timer)
339
+ clearInterval(record.timer);
340
+ if (record.pid > 1)
341
+ void killPidTree(record.pid).catch(() => { });
342
+ }
343
+ this.jobs.clear();
344
+ }
345
+ }
@@ -793,10 +793,7 @@ export function makeLspTool(options) {
793
793
  name: LSP_TOOL_NAME,
794
794
  promptSnippet: "semantic code intelligence (definitions, references, diagnostics, impact)",
795
795
  label: "LSP code intelligence",
796
- description: "IDE-grade semantic analysis (LSP) across the workspace (lines are 1-indexed). `definition` / `references` / `hover`: " +
797
- "resolve the symbol at `line`/`character` in `path` to its definition, workspace usages, or type and docs. `diagnostics`: " +
798
- "file errors/warnings. `documentSymbol`: symbol outline. `read_symbol`: body of `symbol` in `path`. `workspaceSymbol`: " +
799
- "symbols matching `query`. `cascade`: diagnostics of files referencing `path`.",
796
+ description: "IDE-grade semantic analysis (LSP) across the workspace; lines are 1-indexed.",
800
797
  parameters: Type.Object({
801
798
  action: Type.Unsafe({
802
799
  type: "string",
@@ -810,31 +807,16 @@ export function makeLspTool(options) {
810
807
  "workspaceSymbol",
811
808
  "cascade",
812
809
  ],
813
- description: "The LSP operation to perform.",
810
+ description: "definition|references|hover(path,line,character?) | diagnostics|documentSymbol|cascade(path) | " +
811
+ "read_symbol(path,symbol) | workspaceSymbol(query)",
814
812
  }),
815
- path: Type.Optional(Type.String({
816
- description: "Workspace-relative or absolute file path (required for every action except workspaceSymbol).",
817
- })),
818
- symbol: Type.Optional(Type.String({
819
- description: "Symbol for 'read_symbol' (e.g. 'fn' or 'Class.method').",
820
- })),
821
- query: Type.Optional(Type.String({
822
- description: "Search query for 'workspaceSymbol'.",
823
- })),
824
- line: Type.Optional(Type.Number({
825
- description: "1-indexed line in the file.",
826
- })),
827
- character: Type.Optional(Type.Number({
828
- description: "1-indexed column/character position (defaults to 1).",
829
- })),
830
- timeout: Type.Optional(Type.Number({
831
- minimum: 1,
832
- maximum: 120,
833
- description: "Timeout in seconds (default 15).",
834
- })),
835
- allowInstall: Type.Optional(Type.Boolean({
836
- description: "Install the missing language server into ~/.pi-web/lsp-servers (user-space, no sudo). Default false: the tool returns an installHint instead.",
837
- })),
813
+ path: Type.Optional(Type.String()),
814
+ symbol: Type.Optional(Type.String()),
815
+ query: Type.Optional(Type.String()),
816
+ line: Type.Optional(Type.Number()),
817
+ character: Type.Optional(Type.Number()),
818
+ timeout: Type.Optional(Type.Number({ description: "Seconds, default 15" })),
819
+ allowInstall: Type.Optional(Type.Boolean({ description: "Install missing language server in user space" })),
838
820
  }),
839
821
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
840
822
  const L = getLang();