pi-web-ui 0.114.3 → 0.116.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 (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +233 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -1,4 +1,5 @@
1
1
  import { SchedulerValidationError } from "./scheduler-tasks.js";
2
+ import { normalizePathKey } from "./client-state.js";
2
3
  /** 文件与工作区相关操作 */
3
4
  export function handleFileMessage(msg, cs) {
4
5
  switch (msg.type) {
@@ -407,7 +408,7 @@ export function handleTerminalMessage(msg, cs) {
407
408
  }
408
409
  }
409
410
  /** 会话生命周期与分支管理相关操作 */
410
- export function handleSessionLifecycleMessage(msg, cs, send) {
411
+ export function handleSessionLifecycleMessage(msg, cs, send, daemon, clientId) {
411
412
  switch (msg.type) {
412
413
  case "new_chat": {
413
414
  let acknowledged = false;
@@ -423,11 +424,22 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
423
424
  });
424
425
  };
425
426
  void cs
426
- .newChat(msg.preset, msg.ephemeral, acknowledge)
427
+ .newChat(msg.preset, msg.ephemeral, acknowledge, msg.independent)
427
428
  .then(() => acknowledge())
428
429
  .catch(() => acknowledge());
429
430
  return true;
430
431
  }
432
+ case "delete_message":
433
+ if (cs.deleteMessage)
434
+ void cs.deleteMessage(msg.messageId, msg.conversationId);
435
+ else
436
+ send?.({
437
+ type: "notice",
438
+ level: "error",
439
+ text: "当前引擎不支持删除消息",
440
+ textEn: "This engine does not support message deletion",
441
+ });
442
+ return true;
431
443
  case "edit_message":
432
444
  void cs.editMessage(msg.messageId, msg.text, msg.attachments);
433
445
  return true;
@@ -438,7 +450,12 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
438
450
  void cs.rollbackSession?.(msg.messageId, msg.conversationId, msg.restoreWorkspace);
439
451
  return true;
440
452
  case "list_sessions":
441
- void cs.refreshSessions();
453
+ if (msg.path && normalizePathKey(msg.path) !== normalizePathKey(cs.cwd)) {
454
+ void cs.pushSessionsForCwd?.(msg.path);
455
+ }
456
+ else {
457
+ void cs.refreshSessions();
458
+ }
442
459
  return true;
443
460
  case "list_projects":
444
461
  void cs.pushProjects();
@@ -456,7 +473,12 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
456
473
  void cs.renameConversation(msg.id, msg.name);
457
474
  return true;
458
475
  case "dismiss_conversation":
459
- void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
476
+ if (clientId && daemon?.dismissConversation) {
477
+ void daemon.dismissConversation(clientId, msg);
478
+ }
479
+ else {
480
+ void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
481
+ }
460
482
  return true;
461
483
  case "persist_conversation":
462
484
  void cs.persistConversation?.(msg.id);
@@ -471,7 +493,7 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
471
493
  void cs.dismissFinishedSubagents(msg.parentId);
472
494
  return true;
473
495
  case "switch_session":
474
- void cs.switchSession(msg.path, msg.sessionId);
496
+ void cs.switchSession(msg.path, msg.sessionId, msg.independent);
475
497
  return true;
476
498
  case "switch_conversation":
477
499
  void cs.switchConversation(msg.id);
@@ -622,7 +644,7 @@ export function handleSettingsMessage(msg, cs, send) {
622
644
  void cs.saveCommands(msg.commands);
623
645
  return true;
624
646
  case "get_settings":
625
- cs.pushSettings();
647
+ cs.refreshSettings();
626
648
  return true;
627
649
  case "set_settings":
628
650
  // SAFETY: Both dispatch engines validate the explicitly enumerated settings fields below.
@@ -669,6 +691,8 @@ export function handleSettingsMessage(msg, cs, send) {
669
691
  skillsCatalogMaxDesc: msg.skillsCatalogMaxDesc,
670
692
  skillsCatalogShowLocation: msg.skillsCatalogShowLocation,
671
693
  skillsCatalogBudget: msg.skillsCatalogBudget,
694
+ skillsMaxFileBytes: msg.skillsMaxFileBytes,
695
+ skillsFullTextMaxBytes: msg.skillsFullTextMaxBytes,
672
696
  codemodeMode: msg.codemodeMode,
673
697
  codemodeInlineBudget: msg.codemodeInlineBudget,
674
698
  visionBridgeEnabled: msg.visionBridgeEnabled,
@@ -758,6 +782,8 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
758
782
  cs.handleTuiOverlayCancel?.(msg.id);
759
783
  return true;
760
784
  case "question_answer":
785
+ if (clientId && service.resolveSharedQuestion?.(clientId, msg.id, msg.answers, msg.cancelled, msg.cancelReason))
786
+ return true;
761
787
  if (msg.owner) {
762
788
  // 跨页作答:答案转交持有方会话(本页不持有该问卷)。
763
789
  if (typeof service.answerElsewhereQuestion === "function" && clientId) {
@@ -777,6 +803,9 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
777
803
  }
778
804
  return true;
779
805
  case "tool_approval_response":
806
+ if (clientId &&
807
+ service.resolveSharedToolApproval?.(clientId, msg.id, msg.decision, msg.editedParams, msg.reason, msg.scope))
808
+ return true;
780
809
  cs.resolveToolApproval?.(msg.id, msg.decision, msg.editedParams, msg.reason, msg.scope);
781
810
  return true;
782
811
  case "set_approval_policy":
@@ -3742,6 +3742,9 @@ export class DshClientSession {
3742
3742
  }
3743
3743
  return defs;
3744
3744
  }
3745
+ refreshSettings() {
3746
+ this.pushSettings();
3747
+ }
3745
3748
  pushSettings() {
3746
3749
  if (this.runtime?.alive && !this.cachedEffectiveSystemPrompt) {
3747
3750
  void this.refreshPromptInfo().catch(() => { });
@@ -3799,6 +3802,9 @@ export class DshClientSession {
3799
3802
  skillsCatalogMaxDesc: 250,
3800
3803
  skillsCatalogShowLocation: false,
3801
3804
  skillsCatalogBudget: 20000,
3805
+ // DSH 不注入技能正文,但协议字段要齐全(设置页读快照)。
3806
+ skillsMaxFileBytes: 8192,
3807
+ skillsFullTextMaxBytes: 32768,
3802
3808
  chatUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).chatUploadMaxMb ?? 20,
3803
3809
  workspaceUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).workspaceUploadMaxMb ?? 100,
3804
3810
  folderUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).folderUploadMaxMb ?? 32,
@@ -0,0 +1,11 @@
1
+ /**
2
+ * durable-capabilities.ts — Pi Durable 引擎的能力事实源。
3
+ */
4
+ import { DEFAULT_DURABLE_CAPABILITIES } from "../engine-capabilities.js";
5
+ export { DEFAULT_DURABLE_CAPABILITIES };
6
+ export function resolveDurableCapabilities(caps) {
7
+ return {
8
+ ...DEFAULT_DURABLE_CAPABILITIES,
9
+ ...caps,
10
+ };
11
+ }
@@ -40,7 +40,7 @@ const CACHE_TTL_MS = 5000;
40
40
  /** 远端 npm registry 查询缓存:5 分钟 */
41
41
  const REGISTRY_CACHE_TTL_MS = 5 * 60 * 1000;
42
42
  const registryCache = new Map();
43
- /** 引擎状态原子字典:单一事实源,收敛 status / probedAt / updating 三元组,杜绝独立状态撕裂 */
43
+ /** 引擎状态原子字典:单一事实源,收敛 status / probedAt / updating / uninstalling,杜绝独立状态撕裂 */
44
44
  const engineRegistry = new Map([
45
45
  [
46
46
  "pi",
@@ -48,6 +48,7 @@ const engineRegistry = new Map([
48
48
  status: { id: "pi", installed: true, packageName: ENGINE_PACKAGES.pi.packageName, version: VERSION },
49
49
  probedAt: 0,
50
50
  updating: false,
51
+ uninstalling: false,
51
52
  },
52
53
  ],
53
54
  [
@@ -56,6 +57,7 @@ const engineRegistry = new Map([
56
57
  status: { id: "dsh", installed: false, packageName: ENGINE_PACKAGES.dsh.packageName },
57
58
  probedAt: 0,
58
59
  updating: false,
60
+ uninstalling: false,
59
61
  },
60
62
  ],
61
63
  [
@@ -64,6 +66,7 @@ const engineRegistry = new Map([
64
66
  status: { id: "claude", installed: false, packageName: ENGINE_PACKAGES.claude.packageName },
65
67
  probedAt: 0,
66
68
  updating: false,
69
+ uninstalling: false,
67
70
  },
68
71
  ],
69
72
  [
@@ -72,6 +75,7 @@ const engineRegistry = new Map([
72
75
  status: { id: "codex", installed: false, packageName: ENGINE_PACKAGES.codex.packageName },
73
76
  probedAt: 0,
74
77
  updating: false,
78
+ uninstalling: false,
75
79
  },
76
80
  ],
77
81
  [
@@ -80,6 +84,7 @@ const engineRegistry = new Map([
80
84
  status: { id: "durable", installed: false, packageName: ENGINE_PACKAGES.durable.packageName },
81
85
  probedAt: 0,
82
86
  updating: false,
87
+ uninstalling: false,
83
88
  },
84
89
  ],
85
90
  ]);
@@ -87,6 +92,7 @@ function toPublicStatus(entry) {
87
92
  return {
88
93
  ...entry.status,
89
94
  ...(entry.updating ? { updating: true } : {}),
95
+ ...(entry.uninstalling ? { uninstalling: true } : {}),
90
96
  };
91
97
  }
92
98
  /**
@@ -313,6 +319,7 @@ export async function probeEngine(id, force = false) {
313
319
  status: result,
314
320
  probedAt: Date.now(),
315
321
  updating: entry?.updating ?? false,
322
+ uninstalling: entry?.uninstalling ?? false,
316
323
  };
317
324
  engineRegistry.set(id, updatedEntry);
318
325
  return toPublicStatus(updatedEntry);
@@ -354,6 +361,7 @@ export async function probeAllEngines(force = false) {
354
361
  status: res,
355
362
  probedAt: timestamp,
356
363
  updating: existing?.updating ?? false,
364
+ uninstalling: existing?.uninstalling ?? false,
357
365
  });
358
366
  }
359
367
  return Array.from(engineRegistry.values()).map(toPublicStatus);
@@ -370,6 +378,109 @@ export function getCachedEngineStatuses() {
370
378
  export function isEngineUpdating(engineId) {
371
379
  return engineRegistry.get(engineId)?.updating ?? false;
372
380
  }
381
+ /**
382
+ * 查询指定引擎是否正在执行后台卸载子进程。
383
+ */
384
+ export function isEngineUninstalling(engineId) {
385
+ return engineRegistry.get(engineId)?.uninstalling ?? false;
386
+ }
387
+ /**
388
+ * 在后台子进程中执行引擎全局包卸载(npm uninstall -g <pkg>)。
389
+ */
390
+ export async function uninstallEngineBackground(engineId, options) {
391
+ if (engineId === "pi") {
392
+ return { ok: false, error: "Pi 为内置核心引擎,不支持卸载" };
393
+ }
394
+ const meta = ENGINE_PACKAGES[engineId];
395
+ if (!meta || !meta.packageName) {
396
+ return { ok: false, error: `不支持或未知的引擎「${engineId}」` };
397
+ }
398
+ const currentEntry = engineRegistry.get(engineId);
399
+ if (currentEntry?.uninstalling) {
400
+ return { ok: false, error: `引擎「${engineId}」正在后台卸载中,请勿重复操作` };
401
+ }
402
+ if (currentEntry?.updating) {
403
+ return { ok: false, error: `引擎「${engineId}」正在后台更新中,请稍候再试` };
404
+ }
405
+ if (currentEntry)
406
+ currentEntry.uninstalling = true;
407
+ const pkg = meta.packageName;
408
+ const timeoutMs = Math.max(10_000, Number(options?.timeoutMs ?? 180_000));
409
+ const isWin = process.platform === "win32";
410
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : "npm";
411
+ const spawnArgs = isWin ? ["/d", "/s", "/c", "npm", "uninstall", "-g", pkg] : ["uninstall", "-g", pkg];
412
+ try {
413
+ const child = spawn(spawnCmd, spawnArgs, {
414
+ windowsHide: true,
415
+ detached: !isWin,
416
+ stdio: ["ignore", "pipe", "pipe"],
417
+ env: {
418
+ ...process.env,
419
+ NO_COLOR: "1",
420
+ },
421
+ });
422
+ let out = "";
423
+ const appendOut = (chunk) => {
424
+ out = (out + chunk.toString()).slice(-8000);
425
+ };
426
+ child.stdout?.on("data", appendOut);
427
+ child.stderr?.on("data", appendOut);
428
+ const res = await new Promise((resolve) => {
429
+ let done = false;
430
+ const timer = setTimeout(() => {
431
+ if (done)
432
+ return;
433
+ done = true;
434
+ if (child.pid)
435
+ void killPidTree(child.pid);
436
+ resolve({ ok: false, code: null, error: `卸载超时(超过 ${Math.round(timeoutMs / 1000)} 秒)` });
437
+ }, timeoutMs);
438
+ child.on("error", (err) => {
439
+ if (done)
440
+ return;
441
+ done = true;
442
+ clearTimeout(timer);
443
+ resolve({ ok: false, code: null, error: err.message });
444
+ });
445
+ child.on("close", (code) => {
446
+ if (done)
447
+ return;
448
+ done = true;
449
+ clearTimeout(timer);
450
+ resolve({
451
+ ok: code === 0,
452
+ code,
453
+ error: code === 0 ? undefined : `npm 退出码 ${code}`,
454
+ });
455
+ });
456
+ });
457
+ if (res.ok) {
458
+ registryCache.delete(pkg);
459
+ try {
460
+ await probeAllEngines(true);
461
+ }
462
+ catch {
463
+ /* best effort */
464
+ }
465
+ }
466
+ return {
467
+ ok: res.ok,
468
+ error: res.error,
469
+ output: out.trim(),
470
+ };
471
+ }
472
+ catch (err) {
473
+ return {
474
+ ok: false,
475
+ error: err.message,
476
+ };
477
+ }
478
+ finally {
479
+ const finalEntry = engineRegistry.get(engineId);
480
+ if (finalEntry)
481
+ finalEntry.uninstalling = false;
482
+ }
483
+ }
373
484
  /**
374
485
  * 在后台子进程中执行引擎全局包更新(npm i -g <pkg>@latest)。
375
486
  * 避免在可见终端中通过 PTY 模拟输入导致命令首字母丢失或输入不全的问题。
@@ -12,38 +12,138 @@
12
12
  * 3. 严格遵循 package.json 的 exports 条件导出规范解析入口文件;
13
13
  * 4. 基于 file:// URL 协议跨环境穿透动态导入 ESM 模块(dynamicImportGlobalPackage)。
14
14
  */
15
- import { execSync } from "node:child_process";
16
15
  import { existsSync, readdirSync, readFileSync } from "node:fs";
17
16
  import { homedir } from "node:os";
18
17
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
19
18
  import { fileURLToPath, pathToFileURL } from "node:url";
20
- let cachedNpmRootG = null;
19
+ // undefined = 尚未解析;null = 已解析但系统里没有 npm 全局 root
20
+ let cachedNpmRootG;
21
21
  let cachedCandidateRoots = null;
22
22
  let candidateRootsCachedAt = 0;
23
23
  const CANDIDATE_CACHE_TTL_MS = 5000;
24
24
  const packageRootCache = new Map();
25
+ /** npm 显式指定的配置文件(npm 自己也认这两个环境变量)。 */
26
+ function npmrcOverrides() {
27
+ const env = process.env;
28
+ const user = env.npm_config_userconfig || env.NPM_CONFIG_USERCONFIG || null;
29
+ const globalConfig = env.npm_config_globalconfig || env.NPM_CONFIG_GLOBALCONFIG || null;
30
+ return { user, global: globalConfig };
31
+ }
32
+ /** prefix 候选(不含 npmrc):环境变量优先,其余来自运行中的 node 二分进制。 */
33
+ function envPrefixes() {
34
+ const out = [];
35
+ for (const p of [process.env.npm_config_prefix, process.env.NPM_CONFIG_PREFIX]) {
36
+ if (p)
37
+ out.push(p);
38
+ }
39
+ return out;
40
+ }
25
41
  /**
26
- * 安全且带缓存地获取系统 npm 全局 root 目录。
42
+ * 默认 prefix:npm 在 POSIX 上取 node 可执行文件的安装前缀,在 Windows 上取 %APPDATA%\npm。
27
43
  */
28
- export function getSystemNpmRootG() {
29
- if (cachedNpmRootG !== null)
30
- return cachedNpmRootG;
44
+ function defaultPrefixes() {
45
+ const out = [];
46
+ // Windows:npm 的全局 prefix 是 %APPDATA%\npm,跟 node 的安装目录无关,所以排在前面
47
+ if (process.platform === "win32" && process.env.APPDATA)
48
+ out.push(join(process.env.APPDATA, "npm"));
31
49
  try {
32
- const out = execSync("npm root -g", {
33
- timeout: 2500,
34
- encoding: "utf8",
35
- stdio: ["ignore", "pipe", "ignore"],
36
- shell: process.platform === "win32" ? "cmd.exe" : undefined,
37
- windowsHide: true,
38
- }).trim();
39
- if (out && existsSync(out)) {
40
- cachedNpmRootG = resolve(out);
41
- return cachedNpmRootG;
42
- }
50
+ const nodeDir = dirname(process.execPath);
51
+ out.push(join(nodeDir, ".."), nodeDir);
43
52
  }
44
53
  catch {
45
54
  /* ignore */
46
55
  }
56
+ return out;
57
+ }
58
+ /**
59
+ * npmrc 候选位置:显式覆盖 > 用户级 > 各 prefix 的 etc/npmrc > 平台固定路径(顺序同 npm)。
60
+ */
61
+ function npmrcLocations(prefixes) {
62
+ const env = process.env;
63
+ const home = env.HOME || env.USERPROFILE || homedir();
64
+ const isWin = process.platform === "win32";
65
+ const { user, global } = npmrcOverrides();
66
+ const locations = [];
67
+ if (user)
68
+ locations.push(user);
69
+ locations.push(join(home, ".npmrc"));
70
+ if (global)
71
+ locations.push(global);
72
+ for (const prefix of prefixes)
73
+ locations.push(join(prefix, "etc", "npmrc"));
74
+ // 包管理器/系统的固定位置(Homebrew 在 Apple Silicon 上走 /opt/homebrew)
75
+ locations.push("/etc/npmrc", "/usr/etc/npmrc", "/usr/local/etc/npmrc", "/opt/homebrew/etc/npmrc");
76
+ if (isWin && env.APPDATA)
77
+ locations.push(join(env.APPDATA, "npm", "etc", "npmrc"));
78
+ if (isWin && env.ProgramFiles)
79
+ locations.push(join(env.ProgramFiles, "nodejs", "etc", "npmrc"));
80
+ return [...new Set(locations.map((loc) => resolve(loc)))];
81
+ }
82
+ /** 从给定位置读取 npmrc 里的 `prefix=`(纯解析,不执行 npm 本体)。 */
83
+ function readNpmrcPrefixes(locations) {
84
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
85
+ const prefixes = [];
86
+ for (const loc of locations) {
87
+ try {
88
+ if (!existsSync(loc))
89
+ continue;
90
+ for (const line of readFileSync(loc, "utf8").split(/\r?\n/)) {
91
+ const trimmed = line.trim();
92
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";"))
93
+ continue;
94
+ const m = trimmed.match(/^prefix\s*=\s*(.+)$/);
95
+ if (!m)
96
+ continue;
97
+ let value = m[1].trim();
98
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
99
+ value = value.slice(1, -1).trim();
100
+ }
101
+ if (value.startsWith("~"))
102
+ value = join(home, value.slice(1));
103
+ if (value && isAbsolute(value))
104
+ prefixes.push(resolve(value));
105
+ }
106
+ }
107
+ catch {
108
+ /* 配置不可读就跳过,继续下一个位置 */
109
+ }
110
+ }
111
+ return prefixes;
112
+ }
113
+ /**
114
+ * npm 全局 prefix 候选,优先级同 npm 自身:环境变量 > npmrc 的 prefix= > 默认安装位置。
115
+ */
116
+ function npmPrefixCandidates() {
117
+ const env = envPrefixes();
118
+ const defaults = defaultPrefixes();
119
+ const fromNpmrc = readNpmrcPrefixes(npmrcLocations([...env, ...defaults]));
120
+ return [...new Set([...env, ...fromNpmrc, ...defaults].filter(Boolean).map((p) => resolve(p)))];
121
+ }
122
+ /**
123
+ * 安全且带缓存地获取系统 npm 全局 root 目录。
124
+ *
125
+ * 纯计算,不再同步执行 `npm root -g`。此前的实现用 execSync 跑这条 npm 命令,而它在
126
+ * 引擎探测的热路径上(probeAllEngines → probeGlobalPackage → getCandidateNodeModulesRoots,
127
+ * 客户端每次请求都可能触发)。同步 spawn 在主线程上做 fork+exec,一旦子进程卡在 exec 之前,
128
+ * 主线程就会永远阻塞在 spawn 错误管道的 read 上,整个事件循环定格(Termux/libuv 上实测的假死)。
129
+ * prefix 完全可以静态推导,代价只有几次 existsSync。
130
+ */
131
+ export function getSystemNpmRootG() {
132
+ if (cachedNpmRootG !== undefined)
133
+ return cachedNpmRootG;
134
+ // npm 在 POSIX 上装进 <prefix>/lib/node_modules,在 Windows 上装进 <prefix>/node_modules
135
+ const layouts = process.platform === "win32"
136
+ ? ["node_modules", join("lib", "node_modules")]
137
+ : [join("lib", "node_modules"), "node_modules"];
138
+ for (const prefix of npmPrefixCandidates()) {
139
+ for (const layout of layouts) {
140
+ const root = join(prefix, layout);
141
+ if (existsSync(root)) {
142
+ cachedNpmRootG = resolve(root);
143
+ return cachedNpmRootG;
144
+ }
145
+ }
146
+ }
47
147
  cachedNpmRootG = null;
48
148
  return null;
49
149
  }
@@ -57,8 +157,8 @@ export function getCandidateNodeModulesRoots(options) {
57
157
  Date.now() - candidateRootsCachedAt < CANDIDATE_CACHE_TTL_MS) {
58
158
  return cachedCandidateRoots;
59
159
  }
60
- // A refreshed discovery must also re-query npm when its prefix changed.
61
- cachedNpmRootG = null;
160
+ // 重新发现时也要重新推导 npm 全局 root(prefix 可能被改过)
161
+ cachedNpmRootG = undefined;
62
162
  const candidates = new Set();
63
163
  // 1. 本包内部与向上的祖先链路 node_modules
64
164
  let cur = dirname(fileURLToPath(import.meta.url));
@@ -615,7 +615,7 @@ export class GoalService {
615
615
  * the existing select/input dialog), converging on a goal, then auto-sets it.
616
616
  * Mutually exclusive with the review loop of the same conversation.
617
617
  */
618
- async startGoalWizard(text, opts) {
618
+ async startGoalWizard(text, opts, target) {
619
619
  if (this.host.quiesceBlocked())
620
620
  return;
621
621
  if (!this.goalEnabled()) {
@@ -633,8 +633,10 @@ export class GoalService {
633
633
  // The wizard and its progress cards belong to the conversation that
634
634
  // launched it. If the user switches away, do not later set a goal on the
635
635
  // new active conversation while the wizard is still finishing.
636
- const wizardConversationId = this.host.activeConvId();
637
- const wizardConversation = this.host.activeConv();
636
+ const wizardConversation = target ?? this.host.activeConv();
637
+ if (this.host.getConv(wizardConversation.id) !== wizardConversation)
638
+ return;
639
+ const wizardConversationId = wizardConversation.id;
638
640
  const wizardGeneration = wizardConversation.goalGeneration;
639
641
  // Human-readable name for notices that must say WHICH conversation the survey
640
642
  // belongs to (issue #292: the user is expected to switch away mid-survey).
@@ -1104,10 +1106,13 @@ export class GoalService {
1104
1106
  /** Persist goal/review preference defaults (model, rounds cap, locked) without
1105
1107
  * touching the active goal — so changes in the goal bar are remembered across
1106
1108
  * reloads. maxRounds 0 = unlimited. Emits goal_status so the UI stays synced. */
1107
- async setGoalPrefs(opts) {
1109
+ async setGoalPrefs(opts, target) {
1108
1110
  if (!this.goalEnabled())
1109
1111
  return;
1110
- const goal = this.host.activeConv().goal;
1112
+ const conv = target ?? this.host.activeConv();
1113
+ if (this.host.getConv(conv.id) !== conv)
1114
+ return;
1115
+ const goal = conv.goal;
1111
1116
  if (opts?.reviewModel !== undefined)
1112
1117
  goal.reviewModel = opts?.reviewModel || null;
1113
1118
  if (typeof opts?.maxRounds === "number") {