pi-web-ui 0.113.0 → 0.114.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 (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. 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;
@@ -892,52 +907,48 @@ function cleanNonSecretSettingsField(f, v, lang) {
892
907
  return { value: v === undefined ? (f.default ?? "") : String(v) };
893
908
  }
894
909
  /** 校验并写回 settings(storage.json 的 settings 键,原子写);返回错误信息或 null。
895
- * secret 字段写加密 secrets(明文永不落盘、不进 storage.json):空串/缺省 = 不改;
910
+ * secret 字段加密后与 settings 同文件原子提交(明文永不落盘):空串/缺省 = 不改;
896
911
  * 返回的 clean 含 secret 真值(给 onSettingsChanged 用),调用方不得下发浏览器。 */
897
912
  function saveSettingsValues(dir, schema, values,
898
913
  /** 错误文案语言(默认英文);调用方可传 () => getLang() 实现跟随。 */
899
914
  lang, secrets) {
900
915
  const l = lang?.() ?? "en";
901
916
  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 ?? "";
917
+ const secretUpdates = {};
918
+ try {
919
+ for (const f of schema) {
920
+ const v = values?.[f.key];
921
+ if (f.type !== "secret") {
922
+ const r = cleanNonSecretSettingsField(f, v, l);
923
+ if (r.error)
924
+ return { error: r.error, clean };
925
+ clean[f.key] = r.value;
914
926
  }
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
- };
927
+ else if (f.type === "secret") {
928
+ // 空串/缺省 = 不改(浏览器侧回显的本来就是有无布尔,前端把“没碰”发成空串)。
929
+ if (v === undefined || v === "") {
930
+ clean[f.key] = secrets?.get(secretSettingKey(f.key)) ?? f.default ?? "";
924
931
  }
925
- try {
926
- secrets?.set(secretSettingKey(f.key), s);
927
- }
928
- catch (err) {
929
- return { error: err.message, clean };
932
+ else {
933
+ const s = String(v);
934
+ if (s.length > 4096) {
935
+ return {
936
+ error: pick(l, `${f.label} 过长`, `${f.label} too long`, "plugins.settings.too.long", {
937
+ "f.label": f.label,
938
+ }),
939
+ clean,
940
+ };
941
+ }
942
+ secretUpdates[secretSettingKey(f.key)] = s;
943
+ clean[f.key] = s;
930
944
  }
931
- clean[f.key] = s;
945
+ }
946
+ else {
947
+ clean[f.key] = v === undefined ? (f.default ?? "") : String(v);
932
948
  }
933
949
  }
934
- else {
935
- clean[f.key] = v === undefined ? (f.default ?? "") : String(v);
936
- }
937
- }
938
- try {
939
950
  // 保留 storage.json 里其它键(插件自己的数据),只动 settings。
940
- // secret 真值永不进 storage.json(只进加密 secrets),这里整份剥掉。
951
+ // settings 只存普通值,secret 密文由 commitSettings 写入宿主保留容器。
941
952
  const secretKeys = new Set(schema.filter((f) => f.type === "secret").map((f) => f.key));
942
953
  const persist = {};
943
954
  for (const [k, v] of Object.entries(clean))
@@ -946,19 +957,28 @@ lang, secrets) {
946
957
  const file = join(dir, "storage.json");
947
958
  // 与 PluginStorage.set/delete 同一把按文件路径的 RMW 锁(见 plugin-facilities.ts
948
959
  // 的 withFileRmwLock):两个「读-改-写」者串行,谁也不会拿旧快照抹掉对方刚写的键。
949
- withFileRmwLock(file, () => {
950
- let existing = {};
951
- try {
952
- existing = JSON.parse(readFileSync(file, "utf8"));
953
- }
954
- catch {
955
- /* 首次 */
960
+ withFileRmwLockSync(file, () => {
961
+ if (secrets)
962
+ secrets.commitSettings(persist, secretUpdates);
963
+ else {
964
+ let existing = {};
965
+ try {
966
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
967
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
968
+ throw new Error("Invalid plugin storage");
969
+ existing = parsed;
970
+ }
971
+ catch (err) {
972
+ if (err.code !== "ENOENT")
973
+ throw err;
974
+ }
975
+ writeJsonAtomicSync(file, { ...existing, settings: persist }, 0);
956
976
  }
957
- writeJsonAtomicSync(file, { ...existing, settings: persist }, 0);
958
977
  });
959
978
  }
960
979
  catch (err) {
961
980
  console.error(`[plugins] settings persist failed (${dir}):`, err);
981
+ return { error: err.message, clean };
962
982
  }
963
983
  return { clean };
964
984
  }
@@ -992,14 +1012,32 @@ export class PluginManager {
992
1012
  panelSweepTimer = null;
993
1013
  /** 服务端重载纪元:每次 reload() +1,前端用作 import 缓存击穿参数。 */
994
1014
  epochCounter = 0;
1015
+ /** 生命周期代次独立于客户端缓存 epoch(授权变化不会取消激活)。 */
1016
+ lifecycleGeneration = 0;
1017
+ loading;
1018
+ reloading;
1019
+ activatingEffects = new Set();
995
1020
  /** 插件市场列表纪元:每次 add/remove +1,前端据此重渲。 */
996
1021
  catalogEpoch = 0;
997
1022
  /** 当前全局工作区(host.cwd 的背后存储)——随 notifyCwd 更新。 */
998
- cwdValue;
1023
+ globalCwd;
1024
+ httpWorkspace = new AsyncLocalStorage();
1025
+ get cwdValue() {
1026
+ return this.httpWorkspace.getStore()?.cwd ?? this.globalCwd;
1027
+ }
1028
+ set cwdValue(value) {
1029
+ this.globalCwd = value;
1030
+ }
999
1031
  /** 当前项目的**额外工作区根**(宿主侧多根,见 protocol 的 set_workspace_roots)——
1000
1032
  * 由 index.ts 在 set_cwd / set_workspace_roots 后调 notifyWorkspaceRoots 同步。
1001
1033
  * 它们只影响「哪些路径算工作区内」(免授权的受支持路径),不改变 cwd 本身。 */
1002
- workspaceRoots = [];
1034
+ globalWorkspaceRoots = [];
1035
+ get workspaceRoots() {
1036
+ return this.httpWorkspace.getStore()?.roots ?? this.globalWorkspaceRoots;
1037
+ }
1038
+ set workspaceRoots(value) {
1039
+ this.globalWorkspaceRoots = value;
1040
+ }
1003
1041
  /** 插件目录授权表(<dataDir>/plugin-grants.json,issue #146)。 */
1004
1042
  grants;
1005
1043
  /** 特权 DOM 授权表(<dataDir>/plugin-dom.json):wantsDom 插件的 bundle 门禁。 */
@@ -1036,6 +1074,7 @@ export class PluginManager {
1036
1074
  builtinCatalogPath) {
1037
1075
  this.dataDir = dataDir;
1038
1076
  this.builtinCatalogPath = builtinCatalogPath;
1077
+ cleanupRemovedPlugins(dataDir);
1039
1078
  this.cwdValue = resolve(cwd);
1040
1079
  this.grants = new PluginGrantsStore(dataDir);
1041
1080
  this.permGrants = new PluginPermissionStore(dataDir);
@@ -1144,7 +1183,14 @@ export class PluginManager {
1144
1183
  return {
1145
1184
  error: pick(l, "该插件没有声明式设置(manifest 未声明 settings)", "This plugin has no declarative settings (manifest declares no settings)", "plugins.settings.no.declarative"),
1146
1185
  };
1147
- const { error, clean } = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
1186
+ let result;
1187
+ try {
1188
+ result = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
1189
+ }
1190
+ catch (err) {
1191
+ return { error: err.message };
1192
+ }
1193
+ const { error, clean } = result;
1148
1194
  if (error)
1149
1195
  return { error };
1150
1196
  // 通知插件(异常隔离)
@@ -1305,7 +1351,14 @@ export class PluginManager {
1305
1351
  }
1306
1352
  /** index.ts 的 /plugins-api/:id/* 挂载点转发到这里:找到对应插件的已注册
1307
1353
  * 路由并执行;未知插件/路径 → 404,handler 抛错 → 500(不炸进程)。 */
1308
- handleHttp(pluginId, method, pathIn, req, res) {
1354
+ handleHttp(pluginId, method, pathIn, req, res, workspace) {
1355
+ const context = {
1356
+ cwd: resolve(workspace?.cwd ?? this.globalCwd),
1357
+ roots: [...(workspace?.roots ?? (workspace ? [] : this.globalWorkspaceRoots))],
1358
+ };
1359
+ this.httpWorkspace.run(context, () => this.handleHttpInWorkspace(pluginId, method, pathIn, req, res));
1360
+ }
1361
+ handleHttpInWorkspace(pluginId, method, pathIn, req, res) {
1309
1362
  if (!ID_RE.test(pluginId)) {
1310
1363
  res.status(404).end("plugin not found");
1311
1364
  return;
@@ -1534,17 +1587,29 @@ export class PluginManager {
1534
1587
  /** 服务端热重载:反激活全部 → 清缓存 → 重扫重激活 → epoch+1。
1535
1588
  * 返回新目录清单(含激活结果)。重激活后的插件实例是新模块,
1536
1589
  * 内存状态为初始值——逐个客户端触发 onAttach 让它们重推自身状态。 */
1537
- async reload(lang) {
1590
+ reload(lang) {
1591
+ if (this.reloading)
1592
+ return this.reloading;
1538
1593
  this.dispose();
1539
- this.attempted.clear();
1540
1594
  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;
1595
+ const generation = this.lifecycleGeneration;
1596
+ const pending = this.ensureLoaded(lang)
1597
+ .then((list) => {
1598
+ if (generation !== this.lifecycleGeneration)
1599
+ return [];
1600
+ for (const s of this.senders) {
1601
+ const cid = s.cid();
1602
+ if (cid)
1603
+ this.notifyAttach(cid);
1604
+ }
1605
+ return list;
1606
+ })
1607
+ .finally(() => {
1608
+ if (this.reloading === pending)
1609
+ this.reloading = undefined;
1610
+ });
1611
+ this.reloading = pending;
1612
+ return pending;
1548
1613
  }
1549
1614
  /** 每个客户端 attach 后调用:让各插件向该客户端推送自身完整状态。
1550
1615
  * 异常隔离——单个插件钩子报错不影响其他插件与其他钩子。 */
@@ -1679,7 +1744,7 @@ export class PluginManager {
1679
1744
  /** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
1680
1745
  modelLister = undefined;
1681
1746
  /** 由 index.ts 接入 McpBridge:供 host.mcp 读取实时运行状态与热重载。 */
1682
- mcpBridge = undefined;
1747
+ mcpProjects = undefined;
1683
1748
  /** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
1684
1749
  permGrants;
1685
1750
  /** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
@@ -2229,9 +2294,21 @@ export class PluginManager {
2229
2294
  * attach 时调用:重扫目录 + 激活尚未加载的新插件。
2230
2295
  * 返回给浏览器的目录(含激活失败的条目,前端显示为不可用)。
2231
2296
  */
2232
- async ensureLoaded(lang) {
2297
+ ensureLoaded(lang) {
2298
+ if (this.loading)
2299
+ return this.loading;
2300
+ const pending = this.loadGeneration(this.lifecycleGeneration, lang).finally(() => {
2301
+ if (this.loading === pending)
2302
+ this.loading = undefined;
2303
+ });
2304
+ this.loading = pending;
2305
+ return pending;
2306
+ }
2307
+ async loadGeneration(generation, lang) {
2233
2308
  const l = lang?.() ?? "en";
2234
2309
  const found = await this.scan(lang);
2310
+ if (generation !== this.lifecycleGeneration)
2311
+ return [];
2235
2312
  const byId = new Map(found.map((f) => [f.id, f]));
2236
2313
  const scannedIds = new Set(byId.keys());
2237
2314
  // P2-8:依赖拓扑排序激活(被依赖者先行;决定启动时机的是依赖,不是目录顺序)。
@@ -2251,6 +2328,8 @@ export class PluginManager {
2251
2328
  if (!existsSync(join(this.pluginsDir, info.id, "index.mjs")))
2252
2329
  continue; // 纯前端插件
2253
2330
  await this.activate(info, lang);
2331
+ if (generation !== this.lifecycleGeneration)
2332
+ return [];
2254
2333
  }
2255
2334
  // 已被删除的插件:调用 deactivate 并移出缓存
2256
2335
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
@@ -2306,6 +2385,17 @@ export class PluginManager {
2306
2385
  }
2307
2386
  }
2308
2387
  }
2388
+ /** 插件可返回 async cleanup:观察拒绝,避免旧代清理变成未处理的 rejection。 */
2389
+ runDeactivate(id, deactivate) {
2390
+ try {
2391
+ void Promise.resolve(deactivate?.()).catch((err) => {
2392
+ console.error(`[plugin:${id}] deactivate failed:`, err);
2393
+ });
2394
+ }
2395
+ catch (err) {
2396
+ console.error(`[plugin:${id}] deactivate failed:`, err);
2397
+ }
2398
+ }
2309
2399
  /** 反激活单个插件:deactivate + 注销 AI 工具 + 清缓存。
2310
2400
  *
2311
2401
  * 注意这里必须把 id 从 attempted 里摘掉:目录一时不在(`pi-web-ui install --force`
@@ -2314,12 +2404,7 @@ export class PluginManager {
2314
2404
  * 前端只会看到「代理请求失败 404 <url>」(插件的 /proxy 路由不存在),且 CLI 承诺的
2315
2405
  * 「刷新浏览器即可加载」失效,必须重启服务才能恢复。 */
2316
2406
  deactivateEntry(id, p) {
2317
- try {
2318
- p.deactivate?.();
2319
- }
2320
- catch (err) {
2321
- console.error(`[plugin:${id}] deactivate failed:`, err);
2322
- }
2407
+ this.runDeactivate(id, p.deactivate);
2323
2408
  this.releaseEntry(p);
2324
2409
  this.loaded.delete(id);
2325
2410
  this.messageHandlers.delete(id);
@@ -2340,15 +2425,18 @@ export class PluginManager {
2340
2425
  }
2341
2426
  /** 关机 / reload 时反激活全部插件(dispose 后 loaded 为空,后续 releaseEntry 是 no-op)。 */
2342
2427
  dispose() {
2428
+ this.lifecycleGeneration += 1;
2429
+ this.loading = undefined;
2430
+ this.reloading = undefined;
2431
+ this.attempted.clear();
2432
+ this.activatingGates.clear();
2433
+ for (const effects of this.activatingEffects)
2434
+ effects.release();
2435
+ this.activatingEffects.clear();
2343
2436
  const pluginIds = new Set();
2344
2437
  for (const [id, p] of this.loaded) {
2345
2438
  pluginIds.add(id);
2346
- try {
2347
- p.deactivate?.();
2348
- }
2349
- catch (err) {
2350
- console.error(`[plugin:${id}] deactivate failed:`, err);
2351
- }
2439
+ this.runDeactivate(id, p.deactivate);
2352
2440
  }
2353
2441
  // ① 先回卷全部 effect 栈(含 bgTask 停表、工具/命令/路由/watch/UI 条目注销),
2354
2442
  // 并把 loaded 清掉 —— 之后逐个走 releaseEntry 的兜底回收。
@@ -2474,11 +2562,14 @@ export class PluginManager {
2474
2562
  }
2475
2563
  /** 读 manifest 清单;坏目录(无 manifest/id 非法)直接跳过。 */
2476
2564
  async scan(lang) {
2565
+ const generation = this.lifecycleGeneration;
2477
2566
  this.syncBuiltinPlugins();
2478
2567
  const l = lang?.() ?? "en";
2479
2568
  let names;
2480
2569
  try {
2481
2570
  names = await readdir(this.pluginsDir);
2571
+ if (generation !== this.lifecycleGeneration)
2572
+ return [];
2482
2573
  }
2483
2574
  catch {
2484
2575
  return []; // 目录不存在 = 没装任何插件
@@ -2490,6 +2581,8 @@ export class PluginManager {
2490
2581
  const dir = join(this.pluginsDir, name);
2491
2582
  try {
2492
2583
  const st = await stat(dir);
2584
+ if (generation !== this.lifecycleGeneration)
2585
+ return [];
2493
2586
  if (!st.isDirectory())
2494
2587
  continue;
2495
2588
  }
@@ -2499,6 +2592,8 @@ export class PluginManager {
2499
2592
  }
2500
2593
  try {
2501
2594
  const raw = await readFile(join(dir, "manifest.json"), "utf8");
2595
+ if (generation !== this.lifecycleGeneration)
2596
+ return [];
2502
2597
  // wantsDom 快照供静态门禁用(manifest 坏了 → JSON.parse 抛 → catch 跳过,旧快照残留无害:门禁只拦「快照里要且没授权」的)。
2503
2598
  const m = JSON.parse(raw);
2504
2599
  const wantsDom = declarationWantsDom(m.permissions);
@@ -2684,6 +2779,8 @@ export class PluginManager {
2684
2779
  })
2685
2780
  .catch(() => undefined),
2686
2781
  });
2782
+ if (generation !== this.lifecycleGeneration)
2783
+ return [];
2687
2784
  // 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
2688
2785
  this.manifestDiags.set(name, uiDiags);
2689
2786
  const agentTools = this.agentToolsSnapshot(name);
@@ -2701,6 +2798,8 @@ export class PluginManager {
2701
2798
  }
2702
2799
  }
2703
2800
  catch {
2801
+ if (generation !== this.lifecycleGeneration)
2802
+ return [];
2704
2803
  // 无 manifest.json / JSON 解析失败 —— 占位行展示(坏插件不跳过,
2705
2804
  // 设置面板清单标红 + 给原因;ensureLoaded 照例跳过激活)。
2706
2805
  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 +2944,12 @@ export class PluginManager {
2845
2944
  // UI 条目/事件订阅…)都经 effects.add 登记,反激活时**逆序**回卷 —— 插件忘写
2846
2945
  // 注销也不会留下孤儿订阅/定时器/路由(热重载后事件双触发、定时器叠加、watcher
2847
2946
  // 堆积都是这个漏法的症状)。cleanup 抛错只记诊断,不阻断回卷。
2848
- const effects = new PluginEffectStack(info.id, (m) => this.pushRuntimeDiag(info.id, m));
2947
+ const generation = this.lifecycleGeneration;
2948
+ const effects = new PluginEffectStack(info.id, (m) => {
2949
+ if (generation === this.lifecycleGeneration)
2950
+ this.pushRuntimeDiag(info.id, m);
2951
+ });
2952
+ const isCurrent = () => generation === this.lifecycleGeneration && !effects.isReleased;
2849
2953
  // 宿主 API 版本协商:插件要的比宿主新 → 明确拒绝(而不是让它在运行期
2850
2954
  // 撞 undefined 接口莫名其妙地坏)。与激活失败同一处理:error 字段 + 置灰。
2851
2955
  let apiVersion = 1;
@@ -3133,6 +3237,14 @@ export class PluginManager {
3133
3237
  // issue #226:透传定时任务对齐的四件套(各按长度封顶,语义校验归宿主 chatFromPlugin)。
3134
3238
  const r = (req ?? {});
3135
3239
  const passthrough = { text, accountId };
3240
+ try {
3241
+ const attachments = normalizePluginChatAttachments(r.attachments);
3242
+ if (attachments?.length)
3243
+ passthrough.attachments = attachments;
3244
+ }
3245
+ catch (err) {
3246
+ return Promise.reject(err);
3247
+ }
3136
3248
  const cwd = String(r.cwd ?? "").trim();
3137
3249
  if (cwd)
3138
3250
  passthrough.cwd = cwd.slice(0, 1024);
@@ -3690,6 +3802,8 @@ export class PluginManager {
3690
3802
  inFlight = true;
3691
3803
  try {
3692
3804
  const res = await checkFn();
3805
+ if (!isCurrent() || !bgTaskTable.has(id))
3806
+ return;
3693
3807
  let alive = false;
3694
3808
  let nextStatus;
3695
3809
  if (typeof res === "boolean") {
@@ -3718,6 +3832,8 @@ export class PluginManager {
3718
3832
  finally {
3719
3833
  inFlight = false;
3720
3834
  }
3835
+ if (!isCurrent() || !bgTaskTable.has(id))
3836
+ return;
3721
3837
  if (consecutiveFailures >= maxFailures) {
3722
3838
  removeEffect();
3723
3839
  try {
@@ -4057,24 +4173,21 @@ export class PluginManager {
4057
4173
  * - 延迟走 `armDelay` 分片(默认 ≤6 小时),因为 Node 的 setTimeout 延迟超过
4058
4174
  * 2^31-1ms(≈24.8 天)会**溢出成 1ms**,配上「下次在 42 天/一年后」的
4059
4175
  * 合法 cron 就是「1ms 后再触发」的死循环(触发还会回调插件 → 写盘 + 广播)。
4060
- * 分片醒来后重新计算,真到点才 fire。
4176
+ * 分片保持 dueAt,真到点才 fire,然后计算下一次。
4061
4177
  */
4178
+ let dueAt = parts ? nextCronFire(parts, Date.now()) : null;
4062
4179
  const armCron = () => {
4063
- if (cancelled || !parts)
4064
- return;
4065
- const next = nextCronFire(parts, Date.now());
4066
- if (next === null)
4180
+ if (cancelled || !parts || dueAt === null)
4067
4181
  return;
4068
4182
  timer = setTimeout(() => {
4069
- if (cancelled)
4183
+ if (cancelled || dueAt === null)
4070
4184
  return;
4071
- const at = nextCronFire(parts, Date.now());
4072
- if (at === null)
4073
- return;
4074
- if (at <= Date.now() + 1000)
4185
+ if (Date.now() >= dueAt) {
4075
4186
  fire();
4187
+ dueAt = nextCronFire(parts, Date.now());
4188
+ }
4076
4189
  armCron();
4077
- }, armDelay(next, Date.now()));
4190
+ }, armDelay(dueAt, Date.now()));
4078
4191
  timer.unref?.();
4079
4192
  };
4080
4193
  if (parts)
@@ -4108,6 +4221,8 @@ export class PluginManager {
4108
4221
  clearTimeout(grace);
4109
4222
  };
4110
4223
  const off = () => {
4224
+ if (!isCurrent())
4225
+ return;
4111
4226
  cancelTimer();
4112
4227
  bgUnreg?.();
4113
4228
  if (persistent) {
@@ -4143,11 +4258,13 @@ export class PluginManager {
4143
4258
  mcp: {
4144
4259
  list: async () => {
4145
4260
  try {
4261
+ const cwd = self.cwdValue;
4262
+ const bridge = await self.mcpProjects?.prepare(cwd);
4146
4263
  const res = listAllMcpServers({
4147
- agentDir: self.mcpBridge?.getAgentDir(),
4148
- cwd: self.cwdValue,
4264
+ agentDir: bridge?.getAgentDir(),
4265
+ cwd,
4149
4266
  dataDir: self.dataDir,
4150
- bridge: self.mcpBridge,
4267
+ bridge,
4151
4268
  });
4152
4269
  return res.servers;
4153
4270
  }
@@ -4158,11 +4275,13 @@ export class PluginManager {
4158
4275
  },
4159
4276
  check: async (query) => {
4160
4277
  try {
4278
+ const cwd = self.cwdValue;
4279
+ const bridge = await self.mcpProjects?.prepare(cwd);
4161
4280
  return checkMcpServer({
4162
- agentDir: self.mcpBridge?.getAgentDir(),
4163
- cwd: self.cwdValue,
4281
+ agentDir: bridge?.getAgentDir(),
4282
+ cwd,
4164
4283
  dataDir: self.dataDir,
4165
- bridge: self.mcpBridge,
4284
+ bridge,
4166
4285
  query: String(query ?? ""),
4167
4286
  });
4168
4287
  }
@@ -4176,14 +4295,25 @@ export class PluginManager {
4176
4295
  return { ok: false, error: '插件未声明能力 "tools"(manifest.permissions)——请求被拒' };
4177
4296
  }
4178
4297
  try {
4298
+ const cwd = self.cwdValue;
4299
+ const bridge = await self.mcpProjects?.prepare(cwd);
4179
4300
  const res = await installMcpServer({
4180
- agentDir: self.mcpBridge?.getAgentDir(),
4181
- cwd: self.cwdValue,
4301
+ agentDir: bridge?.getAgentDir(),
4302
+ cwd,
4182
4303
  dataDir: self.dataDir,
4183
- bridge: self.mcpBridge,
4184
4304
  spec: spec ?? {},
4185
4305
  });
4186
4306
  if (res.ok) {
4307
+ await self.mcpProjects?.reload(cwd, res.scope ?? "project");
4308
+ const server = checkMcpServer({
4309
+ agentDir: bridge?.getAgentDir(),
4310
+ cwd,
4311
+ dataDir: self.dataDir,
4312
+ bridge,
4313
+ query: res.name,
4314
+ }).matches.find((s) => s.name === res.name && s.scope === res.scope);
4315
+ if (server)
4316
+ Object.assign(res, { server, status: server.status, tools: server.tools, error: server.error });
4187
4317
  try {
4188
4318
  self.onAgentToolsChanged?.();
4189
4319
  }
@@ -4389,12 +4519,47 @@ export class PluginManager {
4389
4519
  status: (spec) => getPluginAssetStatus(dir, spec),
4390
4520
  },
4391
4521
  };
4522
+ // 每个 facade 方法都绑定本次激活;旧异步 continuation 不得借同 id 操作新注册表。
4523
+ // effect 是例外:过期后仍立即执行 cleanup,回收插件刚创建的外部资源。
4524
+ const facades = new WeakMap();
4525
+ const guard = (target) => {
4526
+ const cached = facades.get(target);
4527
+ if (cached)
4528
+ return cached;
4529
+ const proxy = new Proxy(target, {
4530
+ get: (obj, key) => {
4531
+ const value = Reflect.get(obj, key);
4532
+ if (typeof value === "function")
4533
+ return (...args) => {
4534
+ if (obj === host && key === "log" && !isCurrent())
4535
+ return;
4536
+ if (!(obj === host && key === "effect") && !isCurrent())
4537
+ throw new Error(`Plugin ${info.id} activation has been disposed`);
4538
+ return Reflect.apply(value, obj, args);
4539
+ };
4540
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype)
4541
+ return guard(value);
4542
+ return value;
4543
+ },
4544
+ });
4545
+ facades.set(target, proxy);
4546
+ return proxy;
4547
+ };
4548
+ const guardedHost = guard(host);
4549
+ this.activatingEffects.add(effects);
4392
4550
  try {
4393
4551
  // Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
4394
4552
  // 击穿缓存,让 plugins_reload 后的重新激活能拿到磁盘上的新代码。
4395
4553
  const mod = (await import(pathToFileURL(join(dir, "index.mjs")).href + `?e=${this.epochCounter}`));
4554
+ if (!isCurrent())
4555
+ return;
4396
4556
  const activateFn = typeof mod.default === "function" ? mod.default : mod.default?.activate;
4397
- const ret = await activateFn?.(host);
4557
+ const ret = await activateFn?.(guardedHost);
4558
+ if (!isCurrent()) {
4559
+ if (typeof ret === "function")
4560
+ this.runDeactivate(info.id, ret);
4561
+ return;
4562
+ }
4398
4563
  const gateWarned = self.activatingGates.get(info.id)?.legacyWarned;
4399
4564
  self.activatingGates.delete(info.id);
4400
4565
  // activate() 执行期间经 host 注册产生的运行时诊断(重复工具/命令、ui 丢弃等)
@@ -4430,6 +4595,8 @@ export class PluginManager {
4430
4595
  // 定时器不能留着 —— 插件已经坏了,谁也不会来撤它们),再留一条错误占位行。
4431
4596
  const failed = effects.release();
4432
4597
  httpRoutes.clear();
4598
+ if (generation !== this.lifecycleGeneration)
4599
+ return;
4433
4600
  self.activatingGates.delete(info.id);
4434
4601
  this.pushRuntimeDiag(info.id, `activate failed: ${err.message}`);
4435
4602
  if (failed.length > 0)
@@ -4446,6 +4613,9 @@ export class PluginManager {
4446
4613
  });
4447
4614
  console.error(`[plugin:${info.id}] activate failed:`, err);
4448
4615
  }
4616
+ finally {
4617
+ this.activatingEffects.delete(effects);
4618
+ }
4449
4619
  }
4450
4620
  }
4451
4621
  /**