pi-web-ui 0.115.0 → 0.117.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 (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -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;
@@ -449,7 +450,15 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
449
450
  void cs.rollbackSession?.(msg.messageId, msg.conversationId, msg.restoreWorkspace);
450
451
  return true;
451
452
  case "list_sessions":
452
- void cs.refreshSessions();
453
+ // B5:带 limit 的请求(左栏「显示更多」翻页)先记住该项目的条数,之后的自动刷新沿用它
454
+ if (typeof msg.limit === "number")
455
+ cs.setSessionListLimit?.(msg.path ?? cs.cwd, msg.limit);
456
+ if (msg.path && normalizePathKey(msg.path) !== normalizePathKey(cs.cwd)) {
457
+ void cs.pushSessionsForCwd?.(msg.path);
458
+ }
459
+ else {
460
+ void cs.refreshSessions();
461
+ }
453
462
  return true;
454
463
  case "list_projects":
455
464
  void cs.pushProjects();
@@ -467,7 +476,12 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
467
476
  void cs.renameConversation(msg.id, msg.name);
468
477
  return true;
469
478
  case "dismiss_conversation":
470
- void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
479
+ if (clientId && daemon?.dismissConversation) {
480
+ void daemon.dismissConversation(clientId, msg);
481
+ }
482
+ else {
483
+ void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
484
+ }
471
485
  return true;
472
486
  case "persist_conversation":
473
487
  void cs.persistConversation?.(msg.id);
@@ -688,12 +702,18 @@ export function handleSettingsMessage(msg, cs, send) {
688
702
  visionBridgeModel: msg.visionBridgeModel,
689
703
  visionBridgePromptMode: msg.visionBridgePromptMode,
690
704
  visionBridgePrompt: msg.visionBridgePrompt,
705
+ quickAskEnabled: msg.quickAskEnabled,
706
+ quickAskModel: msg.quickAskModel,
707
+ quickAskThinking: msg.quickAskThinking,
708
+ quickAskSystemPrompt: msg.quickAskSystemPrompt,
709
+ quickAskExplainPrompt: msg.quickAskExplainPrompt,
691
710
  subagentDefaultModel: msg.subagentDefaultModel,
692
711
  subagentMaxDepth: msg.subagentMaxDepth,
693
712
  subagentAutoWakeMaxTurns: msg.subagentAutoWakeMaxTurns,
694
713
  retryMaxAttempts: msg.retryMaxAttempts,
695
714
  softCapTokens: msg.softCapTokens,
696
715
  softCapByModel: msg.softCapByModel,
716
+ autoCompactionInstructions: msg.autoCompactionInstructions,
697
717
  reviewPrompt: msg.reviewPrompt,
698
718
  reviewDisabledSkills: msg.reviewDisabledSkills,
699
719
  markersEnabled: msg.markersEnabled,
@@ -773,6 +793,12 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
773
793
  case "question_answer":
774
794
  if (clientId && service.resolveSharedQuestion?.(clientId, msg.id, msg.answers, msg.cancelled, msg.cancelReason))
775
795
  return true;
796
+ // 1. 优先尝试由当前会话直接解决(若当前客户端直接持有该问卷,即使携带了旧 owner 也能直接消费,防止因 orphan 认领/过户等导致 owner 不匹配)
797
+ if (cs.resolveQuestion?.(msg.id, msg.answers, msg.cancelled, msg.cancelReason))
798
+ return true;
799
+ // 2. 全局问卷直决:无需依赖 ownerId,全局根据唯一问卷 UUID 查找命中目标会话并 resolve
800
+ if (service.resolveGlobalQuestion?.(msg.id, msg.answers, msg.cancelled, msg.cancelReason))
801
+ return true;
776
802
  if (msg.owner) {
777
803
  // 跨页作答:答案转交持有方会话(本页不持有该问卷)。
778
804
  if (typeof service.answerElsewhereQuestion === "function" && clientId) {
@@ -26,13 +26,14 @@
26
26
  */
27
27
  import { startTurnTiming, finishTurnTiming } from "../turn-timing.js";
28
28
  import { DEFAULT_DSH_CAPABILITIES } from "../engine-capabilities.js";
29
+ import { mergeQuickAskSettings, normalizeQuickAskSettings } from "../quick-ask-settings.js";
29
30
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
30
31
  import { basename, dirname, join, resolve, sep } from "node:path";
31
32
  import { randomUUID } from "node:crypto";
32
33
  import { homedir } from "node:os";
33
34
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "../bg-servers.js";
34
35
  import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizeBgCleanupMinutes, normalizePathKey, normalizeToolWatchdogTimeoutMs, settingsPresetToUi, } from "../client-state.js";
35
- import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES } from "../client-state.js";
36
+ import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES, RECENT_PROJECTS_MAX, } from "../client-state.js";
36
37
  import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
37
38
  import { buildToolsSchemaText } from "../prompt-composer.js";
38
39
  import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
@@ -2482,6 +2483,7 @@ export class DshClientSession {
2482
2483
  summaries.push({
2483
2484
  path: file,
2484
2485
  sessionId,
2486
+ cwd: this.cwd,
2485
2487
  name: explicitTitle,
2486
2488
  displayName,
2487
2489
  firstMessage: firstMsg,
@@ -3060,7 +3062,7 @@ export class DshClientSession {
3060
3062
  return sbx ? { path, lastUsed, sandbox: sbx } : { path, lastUsed };
3061
3063
  })
3062
3064
  .sort((a, b) => b.lastUsed - a.lastUsed)
3063
- .slice(0, 30);
3065
+ .slice(0, RECENT_PROJECTS_MAX);
3064
3066
  this.emit({ type: "projects", projects: list });
3065
3067
  }
3066
3068
  decodeProjectKey(key) {
@@ -3755,6 +3757,7 @@ export class DshClientSession {
3755
3757
  : this.buildFallbackPromptSourceDefaults();
3756
3758
  const promptSections = this.cachedPromptSections.length > 0 ? this.cachedPromptSections : this.buildFallbackPromptSections();
3757
3759
  const settings = {
3760
+ ...normalizeQuickAskSettings(this.stateStore.getSettingsSnapshot(this.clientId)),
3758
3761
  steeringMode: "all",
3759
3762
  followUpMode: "all",
3760
3763
  promptMode: this.settings.promptMode,
@@ -3783,6 +3786,7 @@ export class DshClientSession {
3783
3786
  // DSH 另有运行时:压缩软上限是 pi 引擎概念,这里保持关闭保协议完整。
3784
3787
  softCapTokens: 0,
3785
3788
  softCapByModel: {},
3789
+ autoCompactionInstructions: "",
3786
3790
  questionnaireEnabled: this.settings.questionnaireEnabled,
3787
3791
  toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
3788
3792
  // DSH 无审批弹窗,策略恒为空(保协议完整)。
@@ -3935,6 +3939,7 @@ export class DshClientSession {
3935
3939
  const markerGuidanceChanged = this.markerSvc.buildGuidance() !== prevMarkerGuidance;
3936
3940
  // 持久化(跨重连存活)。
3937
3941
  this.stateStore.saveSettings(this.clientId, {
3942
+ ...mergeQuickAskSettings(this.stateStore.getSettingsSnapshot(this.clientId), partial),
3938
3943
  chatUploadMaxMb: partial.chatUploadMaxMb,
3939
3944
  workspaceUploadMaxMb: partial.workspaceUploadMaxMb,
3940
3945
  folderUploadMaxMb: partial.folderUploadMaxMb,
@@ -3952,6 +3957,7 @@ export class DshClientSession {
3952
3957
  // DSH 另有运行时:压缩软上限是 pi 引擎概念,这里保持关闭保协议完整。
3953
3958
  softCapTokens: 0,
3954
3959
  softCapByModel: {},
3960
+ autoCompactionInstructions: "",
3955
3961
  questionnaireEnabled: this.settings.questionnaireEnabled,
3956
3962
  toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
3957
3963
  goalModeEnabled: this.settings.goalModeEnabled,
@@ -4344,6 +4350,7 @@ export class DshClientSession {
4344
4350
  // DSH 另有运行时:压缩软上限是 pi 引擎概念,预设里保持关闭。
4345
4351
  softCapTokens: 0,
4346
4352
  softCapByModel: {},
4353
+ autoCompactionInstructions: "",
4347
4354
  visionBridgePromptMode: "append",
4348
4355
  visionBridgePrompt: "",
4349
4356
  reviewPrompt: this.settings.reviewPrompt,
@@ -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));