pi-web-ui 0.113.1 → 0.114.1

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 (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -1,21 +1,24 @@
1
1
  import { registerMarker, unregisterMarker, isBuiltinMarker } from "./markers/index.js";
2
2
  import { ensurePluginAsset, getPluginAssetStatus, } from "./plugin-assets.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
3
4
  import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
4
5
  import { cpSync, existsSync, lstatSync, readFileSync, readdirSync, watch as fsWatch, writeFileSync } from "node:fs";
5
6
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
7
  import { pathToFileURL } from "node:url";
7
8
  import { writeJsonAtomicSync } from "./atomic-file.js";
9
+ import { normalizePluginChatAttachments } from "./plugin-chat-attachments.js";
8
10
  import {} from "./protocol.js";
9
11
  import { UI_SLOTS } from "./plugin-ui-slots.js";
10
12
  import { LeftPanelRunningStore } from "./left-panel-running.js";
11
13
  import { pick } from "./i18n.js";
12
- import { PluginStorage, PluginSecrets, ensurePluginDeps, WorkspaceFS, withFileRmwLock } from "./plugin-facilities.js";
14
+ import { PluginStorage, PluginSecrets, ensurePluginDeps, WorkspaceFS, withFileRmwLockSync, } from "./plugin-facilities.js";
13
15
  import { parseCronSpec, armDelay, nextCronFire, loadScheduleRecords, saveScheduleRecords, } from "./plugin-schedule.js";
14
16
  import { PluginPermissionStore } from "./plugin-permissions.js";
15
17
  import { getAppVersion } from "./pkg-info.js";
16
18
  import { readCatalog, addCustomEntry, removeCustomEntry } from "./plugin-catalog.js";
17
19
  import { PluginGrantsStore, normalizeGrantPath } from "./plugin-grants.js";
18
20
  import { normalizeIconSvg } from "./icon-svg.js";
21
+ import { cleanupRemovedPlugins } from "./plugin-removal.js";
19
22
  import { PluginDomConsent, declarationWantsDom } from "./plugin-dom.js";
20
23
  import { validatePluginManifest, formatManifestIssue, isKnownPermission } from "./plugin-manifest-validate.js";
21
24
  import { buildPluginApiCatalog } from "./plugin-api-catalog.js";
@@ -128,9 +131,21 @@ export class PluginEffectStack {
128
131
  /** 登记一条副作用;返回「只撤这一条」的注销函数(幂等,重复调用无副作用)。 */
129
132
  add(label, dispose) {
130
133
  const item = { label, dispose };
134
+ if (this.released) {
135
+ try {
136
+ dispose();
137
+ }
138
+ catch (err) {
139
+ this.report(label, err);
140
+ }
141
+ return () => { };
142
+ }
131
143
  this.items.push(item);
132
144
  return () => this.remove(item);
133
145
  }
146
+ get isReleased() {
147
+ return this.released;
148
+ }
134
149
  /** 当前未回卷的副作用数(单测断言「activate → deactivate 后栈空」)。 */
135
150
  get size() {
136
151
  return this.items.length;
@@ -718,6 +733,28 @@ function parseSettingsSchema(raw) {
718
733
  const type = (typeof o.type === "string" && o.type ? o.type : optionsFrom ? "select" : "");
719
734
  if (!key || !SETTING_TYPES.has(type) || out.some((x) => x.key === key))
720
735
  continue;
736
+ let options;
737
+ if (Array.isArray(o.options)) {
738
+ const parsed = [];
739
+ for (const opt of o.options) {
740
+ if (typeof opt === "string") {
741
+ parsed.push(opt);
742
+ }
743
+ else if (opt && typeof opt === "object" && typeof opt.value === "string") {
744
+ const val = opt.value;
745
+ const item = { value: val };
746
+ if (typeof opt.label === "string") {
747
+ item.label = opt.label;
748
+ }
749
+ if (typeof opt.labelEn === "string") {
750
+ item.labelEn = opt.labelEn;
751
+ }
752
+ parsed.push(item);
753
+ }
754
+ }
755
+ if (parsed.length > 0)
756
+ options = parsed;
757
+ }
721
758
  const field = {
722
759
  key,
723
760
  type: type,
@@ -725,7 +762,7 @@ function parseSettingsSchema(raw) {
725
762
  ...(o.default !== undefined ? { default: o.default } : {}),
726
763
  ...(typeof o.min === "number" ? { min: o.min } : {}),
727
764
  ...(typeof o.max === "number" ? { max: o.max } : {}),
728
- ...(Array.isArray(o.options) ? { options: o.options.filter((x) => typeof x === "string") } : {}),
765
+ ...(options ? { options } : {}),
729
766
  ...(type === "select" && optionsFrom ? { optionsFrom } : {}),
730
767
  ...(typeof o.hint === "string" ? { hint: o.hint } : {}),
731
768
  };
@@ -881,7 +918,9 @@ function cleanNonSecretSettingsField(f, v, lang) {
881
918
  }
882
919
  return { value: v === undefined ? (f.default ?? "") : s };
883
920
  }
884
- if (v !== undefined && !f.options?.includes(s))
921
+ const hasOptions = Array.isArray(f.options);
922
+ const allowedValues = f.options?.map((opt) => (typeof opt === "string" ? opt : opt.value));
923
+ if (v !== undefined && (!hasOptions || !allowedValues?.includes(s)))
885
924
  return {
886
925
  error: pick(lang, `${f.label} 值非法`, `Invalid value for ${f.label}`, "plugins.settings.invalid.value", {
887
926
  "f.label": f.label,
@@ -892,52 +931,48 @@ function cleanNonSecretSettingsField(f, v, lang) {
892
931
  return { value: v === undefined ? (f.default ?? "") : String(v) };
893
932
  }
894
933
  /** 校验并写回 settings(storage.json 的 settings 键,原子写);返回错误信息或 null。
895
- * secret 字段写加密 secrets(明文永不落盘、不进 storage.json):空串/缺省 = 不改;
934
+ * secret 字段加密后与 settings 同文件原子提交(明文永不落盘):空串/缺省 = 不改;
896
935
  * 返回的 clean 含 secret 真值(给 onSettingsChanged 用),调用方不得下发浏览器。 */
897
936
  function saveSettingsValues(dir, schema, values,
898
937
  /** 错误文案语言(默认英文);调用方可传 () => getLang() 实现跟随。 */
899
938
  lang, secrets) {
900
939
  const l = lang?.() ?? "en";
901
940
  const clean = {};
902
- for (const f of schema) {
903
- const v = values?.[f.key];
904
- if (f.type !== "secret") {
905
- const r = cleanNonSecretSettingsField(f, v, l);
906
- if (r.error)
907
- return { error: r.error, clean };
908
- clean[f.key] = r.value;
909
- }
910
- else if (f.type === "secret") {
911
- // 空串/缺省 = 不改(浏览器侧回显的本来就是有无布尔,前端把“没碰”发成空串)。
912
- if (v === undefined || v === "") {
913
- clean[f.key] = secrets?.get(secretSettingKey(f.key)) ?? f.default ?? "";
941
+ const secretUpdates = {};
942
+ try {
943
+ for (const f of schema) {
944
+ const v = values?.[f.key];
945
+ if (f.type !== "secret") {
946
+ const r = cleanNonSecretSettingsField(f, v, l);
947
+ if (r.error)
948
+ return { error: r.error, clean };
949
+ clean[f.key] = r.value;
914
950
  }
915
- else {
916
- const s = String(v);
917
- if (s.length > 4096) {
918
- return {
919
- error: pick(l, `${f.label} 过长`, `${f.label} too long`, "plugins.settings.too.long", {
920
- "f.label": f.label,
921
- }),
922
- clean,
923
- };
924
- }
925
- try {
926
- secrets?.set(secretSettingKey(f.key), s);
951
+ else if (f.type === "secret") {
952
+ // 空串/缺省 = 不改(浏览器侧回显的本来就是有无布尔,前端把“没碰”发成空串)。
953
+ if (v === undefined || v === "") {
954
+ clean[f.key] = secrets?.get(secretSettingKey(f.key)) ?? f.default ?? "";
927
955
  }
928
- catch (err) {
929
- return { error: err.message, clean };
956
+ else {
957
+ const s = String(v);
958
+ if (s.length > 4096) {
959
+ return {
960
+ error: pick(l, `${f.label} 过长`, `${f.label} too long`, "plugins.settings.too.long", {
961
+ "f.label": f.label,
962
+ }),
963
+ clean,
964
+ };
965
+ }
966
+ secretUpdates[secretSettingKey(f.key)] = s;
967
+ clean[f.key] = s;
930
968
  }
931
- clean[f.key] = s;
969
+ }
970
+ else {
971
+ clean[f.key] = v === undefined ? (f.default ?? "") : String(v);
932
972
  }
933
973
  }
934
- else {
935
- clean[f.key] = v === undefined ? (f.default ?? "") : String(v);
936
- }
937
- }
938
- try {
939
974
  // 保留 storage.json 里其它键(插件自己的数据),只动 settings。
940
- // secret 真值永不进 storage.json(只进加密 secrets),这里整份剥掉。
975
+ // settings 只存普通值,secret 密文由 commitSettings 写入宿主保留容器。
941
976
  const secretKeys = new Set(schema.filter((f) => f.type === "secret").map((f) => f.key));
942
977
  const persist = {};
943
978
  for (const [k, v] of Object.entries(clean))
@@ -946,19 +981,28 @@ lang, secrets) {
946
981
  const file = join(dir, "storage.json");
947
982
  // 与 PluginStorage.set/delete 同一把按文件路径的 RMW 锁(见 plugin-facilities.ts
948
983
  // 的 withFileRmwLock):两个「读-改-写」者串行,谁也不会拿旧快照抹掉对方刚写的键。
949
- withFileRmwLock(file, () => {
950
- let existing = {};
951
- try {
952
- existing = JSON.parse(readFileSync(file, "utf8"));
953
- }
954
- catch {
955
- /* 首次 */
984
+ withFileRmwLockSync(file, () => {
985
+ if (secrets)
986
+ secrets.commitSettings(persist, secretUpdates);
987
+ else {
988
+ let existing = {};
989
+ try {
990
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
991
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
992
+ throw new Error("Invalid plugin storage");
993
+ existing = parsed;
994
+ }
995
+ catch (err) {
996
+ if (err.code !== "ENOENT")
997
+ throw err;
998
+ }
999
+ writeJsonAtomicSync(file, { ...existing, settings: persist }, 0);
956
1000
  }
957
- writeJsonAtomicSync(file, { ...existing, settings: persist }, 0);
958
1001
  });
959
1002
  }
960
1003
  catch (err) {
961
1004
  console.error(`[plugins] settings persist failed (${dir}):`, err);
1005
+ return { error: err.message, clean };
962
1006
  }
963
1007
  return { clean };
964
1008
  }
@@ -992,14 +1036,32 @@ export class PluginManager {
992
1036
  panelSweepTimer = null;
993
1037
  /** 服务端重载纪元:每次 reload() +1,前端用作 import 缓存击穿参数。 */
994
1038
  epochCounter = 0;
1039
+ /** 生命周期代次独立于客户端缓存 epoch(授权变化不会取消激活)。 */
1040
+ lifecycleGeneration = 0;
1041
+ loading;
1042
+ reloading;
1043
+ activatingEffects = new Set();
995
1044
  /** 插件市场列表纪元:每次 add/remove +1,前端据此重渲。 */
996
1045
  catalogEpoch = 0;
997
1046
  /** 当前全局工作区(host.cwd 的背后存储)——随 notifyCwd 更新。 */
998
- cwdValue;
1047
+ globalCwd;
1048
+ httpWorkspace = new AsyncLocalStorage();
1049
+ get cwdValue() {
1050
+ return this.httpWorkspace.getStore()?.cwd ?? this.globalCwd;
1051
+ }
1052
+ set cwdValue(value) {
1053
+ this.globalCwd = value;
1054
+ }
999
1055
  /** 当前项目的**额外工作区根**(宿主侧多根,见 protocol 的 set_workspace_roots)——
1000
1056
  * 由 index.ts 在 set_cwd / set_workspace_roots 后调 notifyWorkspaceRoots 同步。
1001
1057
  * 它们只影响「哪些路径算工作区内」(免授权的受支持路径),不改变 cwd 本身。 */
1002
- workspaceRoots = [];
1058
+ globalWorkspaceRoots = [];
1059
+ get workspaceRoots() {
1060
+ return this.httpWorkspace.getStore()?.roots ?? this.globalWorkspaceRoots;
1061
+ }
1062
+ set workspaceRoots(value) {
1063
+ this.globalWorkspaceRoots = value;
1064
+ }
1003
1065
  /** 插件目录授权表(<dataDir>/plugin-grants.json,issue #146)。 */
1004
1066
  grants;
1005
1067
  /** 特权 DOM 授权表(<dataDir>/plugin-dom.json):wantsDom 插件的 bundle 门禁。 */
@@ -1036,6 +1098,7 @@ export class PluginManager {
1036
1098
  builtinCatalogPath) {
1037
1099
  this.dataDir = dataDir;
1038
1100
  this.builtinCatalogPath = builtinCatalogPath;
1101
+ cleanupRemovedPlugins(dataDir);
1039
1102
  this.cwdValue = resolve(cwd);
1040
1103
  this.grants = new PluginGrantsStore(dataDir);
1041
1104
  this.permGrants = new PluginPermissionStore(dataDir);
@@ -1144,7 +1207,14 @@ export class PluginManager {
1144
1207
  return {
1145
1208
  error: pick(l, "该插件没有声明式设置(manifest 未声明 settings)", "This plugin has no declarative settings (manifest declares no settings)", "plugins.settings.no.declarative"),
1146
1209
  };
1147
- const { error, clean } = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
1210
+ let result;
1211
+ try {
1212
+ result = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
1213
+ }
1214
+ catch (err) {
1215
+ return { error: err.message };
1216
+ }
1217
+ const { error, clean } = result;
1148
1218
  if (error)
1149
1219
  return { error };
1150
1220
  // 通知插件(异常隔离)
@@ -1305,7 +1375,14 @@ export class PluginManager {
1305
1375
  }
1306
1376
  /** index.ts 的 /plugins-api/:id/* 挂载点转发到这里:找到对应插件的已注册
1307
1377
  * 路由并执行;未知插件/路径 → 404,handler 抛错 → 500(不炸进程)。 */
1308
- handleHttp(pluginId, method, pathIn, req, res) {
1378
+ handleHttp(pluginId, method, pathIn, req, res, workspace) {
1379
+ const context = {
1380
+ cwd: resolve(workspace?.cwd ?? this.globalCwd),
1381
+ roots: [...(workspace?.roots ?? (workspace ? [] : this.globalWorkspaceRoots))],
1382
+ };
1383
+ this.httpWorkspace.run(context, () => this.handleHttpInWorkspace(pluginId, method, pathIn, req, res));
1384
+ }
1385
+ handleHttpInWorkspace(pluginId, method, pathIn, req, res) {
1309
1386
  if (!ID_RE.test(pluginId)) {
1310
1387
  res.status(404).end("plugin not found");
1311
1388
  return;
@@ -1534,17 +1611,29 @@ export class PluginManager {
1534
1611
  /** 服务端热重载:反激活全部 → 清缓存 → 重扫重激活 → epoch+1。
1535
1612
  * 返回新目录清单(含激活结果)。重激活后的插件实例是新模块,
1536
1613
  * 内存状态为初始值——逐个客户端触发 onAttach 让它们重推自身状态。 */
1537
- async reload(lang) {
1614
+ reload(lang) {
1615
+ if (this.reloading)
1616
+ return this.reloading;
1538
1617
  this.dispose();
1539
- this.attempted.clear();
1540
1618
  this.epochCounter += 1;
1541
- const list = await this.ensureLoaded(lang);
1542
- for (const s of this.senders) {
1543
- const cid = s.cid();
1544
- if (cid)
1545
- this.notifyAttach(cid);
1546
- }
1547
- return list;
1619
+ const generation = this.lifecycleGeneration;
1620
+ const pending = this.ensureLoaded(lang)
1621
+ .then((list) => {
1622
+ if (generation !== this.lifecycleGeneration)
1623
+ return [];
1624
+ for (const s of this.senders) {
1625
+ const cid = s.cid();
1626
+ if (cid)
1627
+ this.notifyAttach(cid);
1628
+ }
1629
+ return list;
1630
+ })
1631
+ .finally(() => {
1632
+ if (this.reloading === pending)
1633
+ this.reloading = undefined;
1634
+ });
1635
+ this.reloading = pending;
1636
+ return pending;
1548
1637
  }
1549
1638
  /** 每个客户端 attach 后调用:让各插件向该客户端推送自身完整状态。
1550
1639
  * 异常隔离——单个插件钩子报错不影响其他插件与其他钩子。 */
@@ -1679,7 +1768,7 @@ export class PluginManager {
1679
1768
  /** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
1680
1769
  modelLister = undefined;
1681
1770
  /** 由 index.ts 接入 McpBridge:供 host.mcp 读取实时运行状态与热重载。 */
1682
- mcpBridge = undefined;
1771
+ mcpProjects = undefined;
1683
1772
  /** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
1684
1773
  permGrants;
1685
1774
  /** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
@@ -2229,9 +2318,21 @@ export class PluginManager {
2229
2318
  * attach 时调用:重扫目录 + 激活尚未加载的新插件。
2230
2319
  * 返回给浏览器的目录(含激活失败的条目,前端显示为不可用)。
2231
2320
  */
2232
- async ensureLoaded(lang) {
2321
+ ensureLoaded(lang) {
2322
+ if (this.loading)
2323
+ return this.loading;
2324
+ const pending = this.loadGeneration(this.lifecycleGeneration, lang).finally(() => {
2325
+ if (this.loading === pending)
2326
+ this.loading = undefined;
2327
+ });
2328
+ this.loading = pending;
2329
+ return pending;
2330
+ }
2331
+ async loadGeneration(generation, lang) {
2233
2332
  const l = lang?.() ?? "en";
2234
2333
  const found = await this.scan(lang);
2334
+ if (generation !== this.lifecycleGeneration)
2335
+ return [];
2235
2336
  const byId = new Map(found.map((f) => [f.id, f]));
2236
2337
  const scannedIds = new Set(byId.keys());
2237
2338
  // P2-8:依赖拓扑排序激活(被依赖者先行;决定启动时机的是依赖,不是目录顺序)。
@@ -2251,6 +2352,8 @@ export class PluginManager {
2251
2352
  if (!existsSync(join(this.pluginsDir, info.id, "index.mjs")))
2252
2353
  continue; // 纯前端插件
2253
2354
  await this.activate(info, lang);
2355
+ if (generation !== this.lifecycleGeneration)
2356
+ return [];
2254
2357
  }
2255
2358
  // 已被删除的插件:调用 deactivate 并移出缓存
2256
2359
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
@@ -2306,6 +2409,17 @@ export class PluginManager {
2306
2409
  }
2307
2410
  }
2308
2411
  }
2412
+ /** 插件可返回 async cleanup:观察拒绝,避免旧代清理变成未处理的 rejection。 */
2413
+ runDeactivate(id, deactivate) {
2414
+ try {
2415
+ void Promise.resolve(deactivate?.()).catch((err) => {
2416
+ console.error(`[plugin:${id}] deactivate failed:`, err);
2417
+ });
2418
+ }
2419
+ catch (err) {
2420
+ console.error(`[plugin:${id}] deactivate failed:`, err);
2421
+ }
2422
+ }
2309
2423
  /** 反激活单个插件:deactivate + 注销 AI 工具 + 清缓存。
2310
2424
  *
2311
2425
  * 注意这里必须把 id 从 attempted 里摘掉:目录一时不在(`pi-web-ui install --force`
@@ -2314,12 +2428,7 @@ export class PluginManager {
2314
2428
  * 前端只会看到「代理请求失败 404 <url>」(插件的 /proxy 路由不存在),且 CLI 承诺的
2315
2429
  * 「刷新浏览器即可加载」失效,必须重启服务才能恢复。 */
2316
2430
  deactivateEntry(id, p) {
2317
- try {
2318
- p.deactivate?.();
2319
- }
2320
- catch (err) {
2321
- console.error(`[plugin:${id}] deactivate failed:`, err);
2322
- }
2431
+ this.runDeactivate(id, p.deactivate);
2323
2432
  this.releaseEntry(p);
2324
2433
  this.loaded.delete(id);
2325
2434
  this.messageHandlers.delete(id);
@@ -2340,15 +2449,18 @@ export class PluginManager {
2340
2449
  }
2341
2450
  /** 关机 / reload 时反激活全部插件(dispose 后 loaded 为空,后续 releaseEntry 是 no-op)。 */
2342
2451
  dispose() {
2452
+ this.lifecycleGeneration += 1;
2453
+ this.loading = undefined;
2454
+ this.reloading = undefined;
2455
+ this.attempted.clear();
2456
+ this.activatingGates.clear();
2457
+ for (const effects of this.activatingEffects)
2458
+ effects.release();
2459
+ this.activatingEffects.clear();
2343
2460
  const pluginIds = new Set();
2344
2461
  for (const [id, p] of this.loaded) {
2345
2462
  pluginIds.add(id);
2346
- try {
2347
- p.deactivate?.();
2348
- }
2349
- catch (err) {
2350
- console.error(`[plugin:${id}] deactivate failed:`, err);
2351
- }
2463
+ this.runDeactivate(id, p.deactivate);
2352
2464
  }
2353
2465
  // ① 先回卷全部 effect 栈(含 bgTask 停表、工具/命令/路由/watch/UI 条目注销),
2354
2466
  // 并把 loaded 清掉 —— 之后逐个走 releaseEntry 的兜底回收。
@@ -2474,11 +2586,14 @@ export class PluginManager {
2474
2586
  }
2475
2587
  /** 读 manifest 清单;坏目录(无 manifest/id 非法)直接跳过。 */
2476
2588
  async scan(lang) {
2589
+ const generation = this.lifecycleGeneration;
2477
2590
  this.syncBuiltinPlugins();
2478
2591
  const l = lang?.() ?? "en";
2479
2592
  let names;
2480
2593
  try {
2481
2594
  names = await readdir(this.pluginsDir);
2595
+ if (generation !== this.lifecycleGeneration)
2596
+ return [];
2482
2597
  }
2483
2598
  catch {
2484
2599
  return []; // 目录不存在 = 没装任何插件
@@ -2490,6 +2605,8 @@ export class PluginManager {
2490
2605
  const dir = join(this.pluginsDir, name);
2491
2606
  try {
2492
2607
  const st = await stat(dir);
2608
+ if (generation !== this.lifecycleGeneration)
2609
+ return [];
2493
2610
  if (!st.isDirectory())
2494
2611
  continue;
2495
2612
  }
@@ -2499,6 +2616,8 @@ export class PluginManager {
2499
2616
  }
2500
2617
  try {
2501
2618
  const raw = await readFile(join(dir, "manifest.json"), "utf8");
2619
+ if (generation !== this.lifecycleGeneration)
2620
+ return [];
2502
2621
  // wantsDom 快照供静态门禁用(manifest 坏了 → JSON.parse 抛 → catch 跳过,旧快照残留无害:门禁只拦「快照里要且没授权」的)。
2503
2622
  const m = JSON.parse(raw);
2504
2623
  const wantsDom = declarationWantsDom(m.permissions);
@@ -2684,6 +2803,8 @@ export class PluginManager {
2684
2803
  })
2685
2804
  .catch(() => undefined),
2686
2805
  });
2806
+ if (generation !== this.lifecycleGeneration)
2807
+ return [];
2687
2808
  // 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
2688
2809
  this.manifestDiags.set(name, uiDiags);
2689
2810
  const agentTools = this.agentToolsSnapshot(name);
@@ -2701,6 +2822,8 @@ export class PluginManager {
2701
2822
  }
2702
2823
  }
2703
2824
  catch {
2825
+ if (generation !== this.lifecycleGeneration)
2826
+ return [];
2704
2827
  // 无 manifest.json / JSON 解析失败 —— 占位行展示(坏插件不跳过,
2705
2828
  // 设置面板清单标红 + 给原因;ensureLoaded 照例跳过激活)。
2706
2829
  const msg = pick(l, `manifest.json 缺失或解析失败(${name}/),不是有效插件 —— 修复或移走该目录后点“重新扫描”`, `manifest.json missing or unparsable (${name}/), not a valid plugin — fix or remove the directory, then hit Rescan`, "plugins.manifest.broken", { name });
@@ -2845,7 +2968,12 @@ export class PluginManager {
2845
2968
  // UI 条目/事件订阅…)都经 effects.add 登记,反激活时**逆序**回卷 —— 插件忘写
2846
2969
  // 注销也不会留下孤儿订阅/定时器/路由(热重载后事件双触发、定时器叠加、watcher
2847
2970
  // 堆积都是这个漏法的症状)。cleanup 抛错只记诊断,不阻断回卷。
2848
- const effects = new PluginEffectStack(info.id, (m) => this.pushRuntimeDiag(info.id, m));
2971
+ const generation = this.lifecycleGeneration;
2972
+ const effects = new PluginEffectStack(info.id, (m) => {
2973
+ if (generation === this.lifecycleGeneration)
2974
+ this.pushRuntimeDiag(info.id, m);
2975
+ });
2976
+ const isCurrent = () => generation === this.lifecycleGeneration && !effects.isReleased;
2849
2977
  // 宿主 API 版本协商:插件要的比宿主新 → 明确拒绝(而不是让它在运行期
2850
2978
  // 撞 undefined 接口莫名其妙地坏)。与激活失败同一处理:error 字段 + 置灰。
2851
2979
  let apiVersion = 1;
@@ -3133,6 +3261,14 @@ export class PluginManager {
3133
3261
  // issue #226:透传定时任务对齐的四件套(各按长度封顶,语义校验归宿主 chatFromPlugin)。
3134
3262
  const r = (req ?? {});
3135
3263
  const passthrough = { text, accountId };
3264
+ try {
3265
+ const attachments = normalizePluginChatAttachments(r.attachments);
3266
+ if (attachments?.length)
3267
+ passthrough.attachments = attachments;
3268
+ }
3269
+ catch (err) {
3270
+ return Promise.reject(err);
3271
+ }
3136
3272
  const cwd = String(r.cwd ?? "").trim();
3137
3273
  if (cwd)
3138
3274
  passthrough.cwd = cwd.slice(0, 1024);
@@ -3690,6 +3826,8 @@ export class PluginManager {
3690
3826
  inFlight = true;
3691
3827
  try {
3692
3828
  const res = await checkFn();
3829
+ if (!isCurrent() || !bgTaskTable.has(id))
3830
+ return;
3693
3831
  let alive = false;
3694
3832
  let nextStatus;
3695
3833
  if (typeof res === "boolean") {
@@ -3718,6 +3856,8 @@ export class PluginManager {
3718
3856
  finally {
3719
3857
  inFlight = false;
3720
3858
  }
3859
+ if (!isCurrent() || !bgTaskTable.has(id))
3860
+ return;
3721
3861
  if (consecutiveFailures >= maxFailures) {
3722
3862
  removeEffect();
3723
3863
  try {
@@ -4057,24 +4197,21 @@ export class PluginManager {
4057
4197
  * - 延迟走 `armDelay` 分片(默认 ≤6 小时),因为 Node 的 setTimeout 延迟超过
4058
4198
  * 2^31-1ms(≈24.8 天)会**溢出成 1ms**,配上「下次在 42 天/一年后」的
4059
4199
  * 合法 cron 就是「1ms 后再触发」的死循环(触发还会回调插件 → 写盘 + 广播)。
4060
- * 分片醒来后重新计算,真到点才 fire。
4200
+ * 分片保持 dueAt,真到点才 fire,然后计算下一次。
4061
4201
  */
4202
+ let dueAt = parts ? nextCronFire(parts, Date.now()) : null;
4062
4203
  const armCron = () => {
4063
- if (cancelled || !parts)
4064
- return;
4065
- const next = nextCronFire(parts, Date.now());
4066
- if (next === null)
4204
+ if (cancelled || !parts || dueAt === null)
4067
4205
  return;
4068
4206
  timer = setTimeout(() => {
4069
- if (cancelled)
4207
+ if (cancelled || dueAt === null)
4070
4208
  return;
4071
- const at = nextCronFire(parts, Date.now());
4072
- if (at === null)
4073
- return;
4074
- if (at <= Date.now() + 1000)
4209
+ if (Date.now() >= dueAt) {
4075
4210
  fire();
4211
+ dueAt = nextCronFire(parts, Date.now());
4212
+ }
4076
4213
  armCron();
4077
- }, armDelay(next, Date.now()));
4214
+ }, armDelay(dueAt, Date.now()));
4078
4215
  timer.unref?.();
4079
4216
  };
4080
4217
  if (parts)
@@ -4108,6 +4245,8 @@ export class PluginManager {
4108
4245
  clearTimeout(grace);
4109
4246
  };
4110
4247
  const off = () => {
4248
+ if (!isCurrent())
4249
+ return;
4111
4250
  cancelTimer();
4112
4251
  bgUnreg?.();
4113
4252
  if (persistent) {
@@ -4143,11 +4282,13 @@ export class PluginManager {
4143
4282
  mcp: {
4144
4283
  list: async () => {
4145
4284
  try {
4285
+ const cwd = self.cwdValue;
4286
+ const bridge = await self.mcpProjects?.prepare(cwd);
4146
4287
  const res = listAllMcpServers({
4147
- agentDir: self.mcpBridge?.getAgentDir(),
4148
- cwd: self.cwdValue,
4288
+ agentDir: bridge?.getAgentDir(),
4289
+ cwd,
4149
4290
  dataDir: self.dataDir,
4150
- bridge: self.mcpBridge,
4291
+ bridge,
4151
4292
  });
4152
4293
  return res.servers;
4153
4294
  }
@@ -4158,11 +4299,13 @@ export class PluginManager {
4158
4299
  },
4159
4300
  check: async (query) => {
4160
4301
  try {
4302
+ const cwd = self.cwdValue;
4303
+ const bridge = await self.mcpProjects?.prepare(cwd);
4161
4304
  return checkMcpServer({
4162
- agentDir: self.mcpBridge?.getAgentDir(),
4163
- cwd: self.cwdValue,
4305
+ agentDir: bridge?.getAgentDir(),
4306
+ cwd,
4164
4307
  dataDir: self.dataDir,
4165
- bridge: self.mcpBridge,
4308
+ bridge,
4166
4309
  query: String(query ?? ""),
4167
4310
  });
4168
4311
  }
@@ -4176,14 +4319,25 @@ export class PluginManager {
4176
4319
  return { ok: false, error: '插件未声明能力 "tools"(manifest.permissions)——请求被拒' };
4177
4320
  }
4178
4321
  try {
4322
+ const cwd = self.cwdValue;
4323
+ const bridge = await self.mcpProjects?.prepare(cwd);
4179
4324
  const res = await installMcpServer({
4180
- agentDir: self.mcpBridge?.getAgentDir(),
4181
- cwd: self.cwdValue,
4325
+ agentDir: bridge?.getAgentDir(),
4326
+ cwd,
4182
4327
  dataDir: self.dataDir,
4183
- bridge: self.mcpBridge,
4184
4328
  spec: spec ?? {},
4185
4329
  });
4186
4330
  if (res.ok) {
4331
+ await self.mcpProjects?.reload(cwd, res.scope ?? "project");
4332
+ const server = checkMcpServer({
4333
+ agentDir: bridge?.getAgentDir(),
4334
+ cwd,
4335
+ dataDir: self.dataDir,
4336
+ bridge,
4337
+ query: res.name,
4338
+ }).matches.find((s) => s.name === res.name && s.scope === res.scope);
4339
+ if (server)
4340
+ Object.assign(res, { server, status: server.status, tools: server.tools, error: server.error });
4187
4341
  try {
4188
4342
  self.onAgentToolsChanged?.();
4189
4343
  }
@@ -4389,12 +4543,47 @@ export class PluginManager {
4389
4543
  status: (spec) => getPluginAssetStatus(dir, spec),
4390
4544
  },
4391
4545
  };
4546
+ // 每个 facade 方法都绑定本次激活;旧异步 continuation 不得借同 id 操作新注册表。
4547
+ // effect 是例外:过期后仍立即执行 cleanup,回收插件刚创建的外部资源。
4548
+ const facades = new WeakMap();
4549
+ const guard = (target) => {
4550
+ const cached = facades.get(target);
4551
+ if (cached)
4552
+ return cached;
4553
+ const proxy = new Proxy(target, {
4554
+ get: (obj, key) => {
4555
+ const value = Reflect.get(obj, key);
4556
+ if (typeof value === "function")
4557
+ return (...args) => {
4558
+ if (obj === host && key === "log" && !isCurrent())
4559
+ return;
4560
+ if (!(obj === host && key === "effect") && !isCurrent())
4561
+ throw new Error(`Plugin ${info.id} activation has been disposed`);
4562
+ return Reflect.apply(value, obj, args);
4563
+ };
4564
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype)
4565
+ return guard(value);
4566
+ return value;
4567
+ },
4568
+ });
4569
+ facades.set(target, proxy);
4570
+ return proxy;
4571
+ };
4572
+ const guardedHost = guard(host);
4573
+ this.activatingEffects.add(effects);
4392
4574
  try {
4393
4575
  // Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
4394
4576
  // 击穿缓存,让 plugins_reload 后的重新激活能拿到磁盘上的新代码。
4395
4577
  const mod = (await import(pathToFileURL(join(dir, "index.mjs")).href + `?e=${this.epochCounter}`));
4578
+ if (!isCurrent())
4579
+ return;
4396
4580
  const activateFn = typeof mod.default === "function" ? mod.default : mod.default?.activate;
4397
- const ret = await activateFn?.(host);
4581
+ const ret = await activateFn?.(guardedHost);
4582
+ if (!isCurrent()) {
4583
+ if (typeof ret === "function")
4584
+ this.runDeactivate(info.id, ret);
4585
+ return;
4586
+ }
4398
4587
  const gateWarned = self.activatingGates.get(info.id)?.legacyWarned;
4399
4588
  self.activatingGates.delete(info.id);
4400
4589
  // activate() 执行期间经 host 注册产生的运行时诊断(重复工具/命令、ui 丢弃等)
@@ -4430,6 +4619,8 @@ export class PluginManager {
4430
4619
  // 定时器不能留着 —— 插件已经坏了,谁也不会来撤它们),再留一条错误占位行。
4431
4620
  const failed = effects.release();
4432
4621
  httpRoutes.clear();
4622
+ if (generation !== this.lifecycleGeneration)
4623
+ return;
4433
4624
  self.activatingGates.delete(info.id);
4434
4625
  this.pushRuntimeDiag(info.id, `activate failed: ${err.message}`);
4435
4626
  if (failed.length > 0)
@@ -4446,6 +4637,9 @@ export class PluginManager {
4446
4637
  });
4447
4638
  console.error(`[plugin:${info.id}] activate failed:`, err);
4448
4639
  }
4640
+ finally {
4641
+ this.activatingEffects.delete(effects);
4642
+ }
4449
4643
  }
4450
4644
  }
4451
4645
  /**