pi-web-ui 0.113.1 → 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 (222) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/README.md +117 -246
  3. package/README.zh-CN.md +145 -217
  4. package/README.zh-TW.md +145 -217
  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 +47 -15
  8. package/dist/server/agent-service-daemon.js +102 -24
  9. package/dist/server/agent-service.js +2289 -1120
  10. package/dist/server/approval-rules.js +29 -3
  11. package/dist/server/ask-user-question-tool.js +8 -8
  12. package/dist/server/atomic-file.js +35 -14
  13. package/dist/server/attachment-store.js +71 -35
  14. package/dist/server/attachments.js +18 -8
  15. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  16. package/dist/server/canvas/canvas-dispatch.js +61 -20
  17. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  18. package/dist/server/canvas/canvas-scheduler.js +99 -0
  19. package/dist/server/canvas/canvas-store.js +107 -54
  20. package/dist/server/canvas/canvas-validation.js +131 -0
  21. package/dist/server/canvas/canvas-workspace.js +284 -0
  22. package/dist/server/client-id-utils.js +8 -0
  23. package/dist/server/client-state.js +104 -22
  24. package/dist/server/communicate-tool.js +76 -0
  25. package/dist/server/compact-context-tool.js +2 -3
  26. package/dist/server/compaction-instructions.js +75 -0
  27. package/dist/server/compaction-markers.js +7 -2
  28. package/dist/server/compaction-state.js +84 -0
  29. package/dist/server/composer-drafts.js +43 -40
  30. package/dist/server/context-evidence.js +346 -0
  31. package/dist/server/conversation-communication.js +368 -0
  32. package/dist/server/conversation-read-tool.js +3 -4
  33. package/dist/server/conversation-tool-names.js +14 -0
  34. package/dist/server/conversation-tool.js +57 -0
  35. package/dist/server/delegate-mode.js +17 -4
  36. package/dist/server/device-center/bot-catalog.js +88 -0
  37. package/dist/server/device-center/bot-execution.js +106 -0
  38. package/dist/server/device-center/bots.js +170 -0
  39. package/dist/server/device-center/collab-service.js +153 -0
  40. package/dist/server/device-center/collab-tool.js +184 -0
  41. package/dist/server/device-center/connector.js +332 -0
  42. package/dist/server/device-center/desktop-linux.js +372 -0
  43. package/dist/server/device-center/desktop-native.js +413 -0
  44. package/dist/server/device-center/desktop-page.js +232 -0
  45. package/dist/server/device-center/desktop-setup.js +30 -0
  46. package/dist/server/device-center/desktop.js +387 -0
  47. package/dist/server/device-center/device-portals.js +241 -0
  48. package/dist/server/device-center/execution-failure.js +70 -0
  49. package/dist/server/device-center/executor.js +371 -0
  50. package/dist/server/device-center/file-sync.js +493 -0
  51. package/dist/server/device-center/hub-auth.js +69 -0
  52. package/dist/server/device-center/hub-page.js +68 -0
  53. package/dist/server/device-center/hub-setup.js +214 -0
  54. package/dist/server/device-center/hub.js +829 -0
  55. package/dist/server/device-center/local-page.js +17 -0
  56. package/dist/server/device-center/local.js +476 -0
  57. package/dist/server/device-center/main.js +118 -0
  58. package/dist/server/device-center/native-desktop/macos.js +192 -0
  59. package/dist/server/device-center/native-desktop/windows.js +118 -0
  60. package/dist/server/device-center/path-portal.js +120 -0
  61. package/dist/server/device-center/relay.js +959 -0
  62. package/dist/server/device-center/runtime.js +253 -0
  63. package/dist/server/device-center/smoke-preview.js +3 -0
  64. package/dist/server/device-center/store.js +122 -0
  65. package/dist/server/device-center/task-error.js +14 -0
  66. package/dist/server/device-center/transfers.js +293 -0
  67. package/dist/server/device-center/workspaces.js +45 -0
  68. package/dist/server/dispatch-domain-handlers.js +83 -27
  69. package/dist/server/dsh/dsh-agent-service.js +277 -158
  70. package/dist/server/dsh/dsh-client.js +12 -2
  71. package/dist/server/durable/durable-agent-service.js +1 -1
  72. package/dist/server/evidence-tool-hooks.js +49 -0
  73. package/dist/server/file-save.js +95 -0
  74. package/dist/server/file-transfer-routes.js +97 -47
  75. package/dist/server/files-service.js +38 -26
  76. package/dist/server/goal-review-gate.js +16 -6
  77. package/dist/server/goal-service.js +54 -30
  78. package/dist/server/http-proxy.js +120 -0
  79. package/dist/server/index.js +229 -223
  80. package/dist/server/load-timing.js +31 -0
  81. package/dist/server/mcp-bridge.js +219 -94
  82. package/dist/server/mcp-hot-reload.js +31 -5
  83. package/dist/server/mcp-manager.js +192 -93
  84. package/dist/server/mcp-oauth-login.js +169 -0
  85. package/dist/server/mcp-oauth-ui.js +137 -0
  86. package/dist/server/mcp-oauth.js +395 -0
  87. package/dist/server/mcp-project-runtime.js +207 -0
  88. package/dist/server/message-window.js +74 -21
  89. package/dist/server/net-guard.js +122 -20
  90. package/dist/server/payload-limits.js +17 -0
  91. package/dist/server/pending-question.js +82 -0
  92. package/dist/server/plan-mode.js +338 -137
  93. package/dist/server/plugin-assets.js +8 -4
  94. package/dist/server/plugin-chat-attachments.js +48 -0
  95. package/dist/server/plugin-facilities.js +67 -220
  96. package/dist/server/plugin-installer.js +2 -1
  97. package/dist/server/plugin-removal.js +49 -0
  98. package/dist/server/plugin-secrets.js +179 -0
  99. package/dist/server/plugins.js +262 -92
  100. package/dist/server/preset-fields.js +49 -0
  101. package/dist/server/preset-plugin-dependencies.js +57 -0
  102. package/dist/server/preset-share.js +112 -72
  103. package/dist/server/protocol-version.js +1 -1
  104. package/dist/server/queue-modes.js +10 -0
  105. package/dist/server/remote-ssh-service.js +160 -67
  106. package/dist/server/request-context.js +164 -0
  107. package/dist/server/sandbox-data.js +655 -0
  108. package/dist/server/sandbox-engines.js +7 -0
  109. package/dist/server/sandbox-runtime-gate.js +41 -0
  110. package/dist/server/sandbox-service.js +139 -698
  111. package/dist/server/sandbox-tool.js +21 -4
  112. package/dist/server/scheduler-tasks.js +63 -48
  113. package/dist/server/serialize.js +48 -19
  114. package/dist/server/session-branch.js +25 -3
  115. package/dist/server/session-parser.js +28 -18
  116. package/dist/server/session-scan.js +130 -0
  117. package/dist/server/session-search.js +51 -37
  118. package/dist/server/settings-service.js +267 -111
  119. package/dist/server/setup-config.js +58 -0
  120. package/dist/server/skill-maintenance.js +112 -24
  121. package/dist/server/subagent-helpers.js +4 -1
  122. package/dist/server/subagent-notify.js +4 -1
  123. package/dist/server/subagent-security-gate.js +52 -11
  124. package/dist/server/subagent-task.js +27 -0
  125. package/dist/server/subagents.js +217 -46
  126. package/dist/server/tabs.js +9 -1
  127. package/dist/server/terminals.js +467 -363
  128. package/dist/server/tool-guards.js +42 -6
  129. package/dist/server/tool-manager.js +47 -20
  130. package/dist/server/tool-overrides.js +13 -11
  131. package/dist/server/tool-prompt-overrides.js +32 -2
  132. package/dist/server/tool-prompts.js +1 -1
  133. package/dist/server/turn-timing.js +11 -0
  134. package/dist/server/universal/session-store.js +48 -6
  135. package/dist/server/universal/universal-service.js +1 -1
  136. package/dist/server/universal/universal-session.js +334 -231
  137. package/dist/server/uploads.js +64 -5
  138. package/dist/server/worktree-service.js +32 -24
  139. package/dist/server/ws-pending-queue.js +73 -27
  140. package/docs/device-center.md +142 -0
  141. package/docs/device-desktop.md +48 -0
  142. package/package.json +4 -1
  143. package/plugin-sdk/index.d.ts +28 -6
  144. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  145. package/plugins/catalog.json +1 -1
  146. package/themes/aetheris.css +1 -107
  147. package/themes/ayu-light.css +5 -29
  148. package/themes/bases/flow-base.css +0 -6
  149. package/themes/bases/statusbar-flat-base.css +112 -0
  150. package/themes/bases/zhujian-base.css +1 -0
  151. package/themes/bases/zhupi-base.css +1 -0
  152. package/themes/catppuccin-latte.css +4 -27
  153. package/themes/catppuccin.css +4 -35
  154. package/themes/claude-code-dark.css +1 -0
  155. package/themes/codex.css +4 -28
  156. package/themes/cyberpunk.css +3 -61
  157. package/themes/dark-teal.css +0 -1
  158. package/themes/dazzle.css +3 -73
  159. package/themes/everforest-light.css +4 -27
  160. package/themes/geist.css +4 -28
  161. package/themes/gruvbox-light.css +4 -27
  162. package/themes/kanagawa-lotus.css +4 -27
  163. package/themes/md-preview.css +3 -213
  164. package/themes/mist.css +4 -24
  165. package/themes/nord.css +4 -35
  166. package/themes/one-dark.css +4 -37
  167. package/themes/paper.css +4 -16
  168. package/themes/rose-pine-dawn.css +4 -28
  169. package/themes/sakura.css +4 -24
  170. package/themes/solarized-light.css +4 -27
  171. package/themes/tokyo-night.css +3 -34
  172. package/themes/white.css +4 -26
  173. package/themes/zhujian-dark.css +1 -0
  174. package/themes/zhupi-dark.css +1 -0
  175. package/web/dist/.build-assets.json +1 -0
  176. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  177. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  178. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  179. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  180. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  181. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  182. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  183. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  184. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  185. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  186. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  187. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  188. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  189. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  190. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  191. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  192. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  193. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  194. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  195. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  196. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  197. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  198. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  199. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  200. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  201. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  202. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  203. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  204. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  205. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  206. package/web/dist/assets/index-Cje8iugL.js +83 -0
  207. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  208. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  209. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  210. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  211. package/web/dist/assets/math-BorAY7qD.css +1 -0
  212. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  213. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  214. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  215. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  216. package/web/dist/index.html +15 -9
  217. package/web/dist/sw.js +1 -1
  218. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  219. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  220. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  221. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  222. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -16,12 +16,15 @@
16
16
  * all share one conversation list per project.
17
17
  * PI_CODING_AGENT_DIR pi config dir (auth/models/skills) — passed to the SDK
18
18
  */
19
+ import { botExecutionMessageAllowed } from "./device-center/bot-execution.js";
19
20
  // MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
20
21
  import "./patch-remote-catalog.js";
21
22
  import "./patch-turn-end-boundary.js";
22
23
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
23
24
  import { readFile, stat } from "node:fs/promises";
24
- import { createServer, request as proxyRequest } from "node:http";
25
+ import { createServer } from "node:http";
26
+ import { proxyHttp } from "./http-proxy.js";
27
+ import { saveSetupConfig } from "./setup-config.js";
25
28
  import { createConnection } from "node:net";
26
29
  import { basename, delimiter, join, resolve, sep } from "node:path";
27
30
  import { homedir } from "node:os";
@@ -34,10 +37,11 @@ import { sdkCopies, sdkOriginNote } from "./sdk-origin.js";
34
37
  import { PROTOCOL_VERSION } from "./protocol-version.js";
35
38
  import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
36
39
  import { ClientStateStore } from "./client-state.js";
37
- import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
40
+ import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
41
+ import { WS_MAX_PAYLOAD_BYTES } from "./payload-limits.js";
38
42
  import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
39
43
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
40
- import { initAttachmentStore, readAttachment } from "./attachment-store.js";
44
+ import { initAttachmentStore, findAttachment } from "./attachment-store.js";
41
45
  import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
42
46
  import { startControlServer } from "./control-socket.js";
43
47
  import { scheduleUploadCleanup } from "./uploads.js";
@@ -49,13 +53,18 @@ import { parseTabs, tabsRefusal } from "./tabs.js";
49
53
  import { recordUnknownWsType } from "./ws-unknown-types.js";
50
54
  import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
51
55
  import { validateClientId } from "./ws-client-id.js";
52
- import { PendingCommandQueue } from "./ws-pending-queue.js";
56
+ import { PendingCommandQueue, MAX_PRE_HELLO_WS_BYTES, isClientMessageEnvelope, isClientMessageWithinByteLimit, } from "./ws-pending-queue.js";
53
57
  import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
54
58
  import { PluginManager, resolvePluginClientFile, resolvePluginSharedFile, } from "./plugins.js";
55
59
  import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
56
60
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
57
- import { McpBridge } from "./mcp-bridge.js";
58
- import { createMcpHotReload } from "./mcp-hot-reload.js";
61
+ import { McpProjectRuntimeRegistry } from "./mcp-project-runtime.js";
62
+ import { installLocalDeviceCenter } from "./device-center/local.js";
63
+ import { createDeviceConnector } from "./device-center/connector.js";
64
+ import { createDeviceRuntime } from "./device-center/runtime.js";
65
+ import { createLocalBotRegistry } from "./device-center/bots.js";
66
+ import { setDeviceCollabService } from "./device-center/collab-tool.js";
67
+ import { createDeviceDesktop } from "./device-center/desktop.js";
59
68
  import { createHostMetricsSampler } from "./host-metrics.js";
60
69
  import { SchedulerStore } from "./scheduler-tasks.js";
61
70
  import { initHttpProxy } from "./http-proxy.js";
@@ -208,7 +217,10 @@ function buildId() {
208
217
  if (buildIdCache === null) {
209
218
  try {
210
219
  const html = readFileSync(join(webDistPath(), "index.html"), "utf8");
211
- buildIdCache = html.match(/\/assets\/index-([A-Za-z0-9_-]+)\.js/)?.[1] ?? "";
220
+ buildIdCache =
221
+ html.match(/<meta\s+name="pi-web-build-id"\s+content="([^"]+)"/)?.[1] ??
222
+ html.match(/(?:\/|\.\/)assets\/index-([A-Za-z0-9_-]+)\.js/)?.[1] ??
223
+ "";
212
224
  }
213
225
  catch {
214
226
  buildIdCache = "";
@@ -360,84 +372,23 @@ app.get("/api/setup/status", setupGate, (_req, res) => {
360
372
  });
361
373
  });
362
374
  app.post("/api/setup/save", setupGate, (req, res) => {
363
- const body = (req.body ?? {});
364
- const prev = loadServerFileConfig(DATA_DIR);
365
- const next = { ...prev };
366
- let tokenChanged = false;
367
- if (typeof body.token === "string") {
368
- const t = body.token.trim();
369
- if (t)
370
- next.token = t;
371
- else
372
- delete next.token;
373
- tokenChanged = t !== AUTH_TOKEN;
374
- AUTH_TOKEN = t;
375
- }
376
- const setStr = (key, v, valid, what) => {
377
- if (v === undefined)
378
- return true;
379
- if (typeof v !== "string") {
380
- res.status(400).json({ ok: false, error: `${what} 必须是字符串` });
381
- return false;
382
- }
383
- const s = v.trim();
384
- if (s && !valid(s)) {
385
- res.status(400).json({ ok: false, error: `${what} 格式不合法:${s}` });
386
- return false;
387
- }
388
- if (s)
389
- next[key] = s;
390
- else
391
- delete next[key];
392
- return true;
393
- };
394
- if (!setStr("host", body.host, (s) => /^[A-Za-z0-9.:_-]+$/.test(s) && s.length <= 253, "host"))
395
- return;
396
- if (!setStr("allowHosts", body.allowHosts, (s) => /^[A-Za-z0-9.,:_\-\s]+$/.test(s), "allowHosts"))
375
+ const result = saveSetupConfig(req.body, loadServerFileConfig(DATA_DIR), { token: AUTH_TOKEN, host: HOST, port: PORT, allowHosts: ALLOW_HOSTS, allowOrigins: ALLOW_ORIGINS }, (next) => saveServerFileConfig(DATA_DIR, next));
376
+ if (!result.ok) {
377
+ res.status(result.status).json({ ok: false, error: result.error });
397
378
  return;
398
- if (!setStr("allowOrigins", body.allowOrigins, (s) => s.length <= 2000, "allowOrigins"))
399
- return;
400
- if (body.port !== undefined && body.port !== "" && body.port !== null) {
401
- const p = Number(body.port);
402
- if (!Number.isInteger(p) || p <= 0 || p > 65535) {
403
- res.status(400).json({ ok: false, error: `port 必须是 1-65535:${String(body.port)}` });
404
- return;
405
- }
406
- next.port = p;
407
379
  }
408
- else if (body.port === "") {
409
- delete next.port;
410
- }
411
- try {
412
- saveServerFileConfig(DATA_DIR, next);
413
- }
414
- catch (err) {
415
- res.status(500).json({ ok: false, error: `写入配置失败:${err.message}` });
416
- return;
417
- }
418
- const norm = (s) => s
419
- .split(",")
420
- .map((x) => x.trim().toLowerCase())
421
- .filter(Boolean)
422
- .join(",");
423
- const restartRequired = (typeof body.host === "string" && body.host.trim() !== HOST) ||
424
- (body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
425
- (typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
426
- (typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
427
- // 如果设置了新 token,直接给当前回环浏览器下发匹配的 cookie,避免保存后直接 401
380
+ AUTH_TOKEN = result.nextToken;
428
381
  if (AUTH_TOKEN) {
429
- const secure = isTlsRequest(req);
430
- res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
382
+ res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, isTlsRequest(req)));
431
383
  }
432
- else if (tokenChanged && !AUTH_TOKEN) {
433
- // 清除了 token,同时清理旧 cookie
384
+ else if (result.tokenApplied) {
434
385
  res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
435
386
  }
436
387
  res.json({
437
388
  ok: true,
438
- tokenApplied: tokenChanged,
439
- restartRequired,
440
- saved: next,
389
+ tokenApplied: result.tokenApplied,
390
+ restartRequired: result.restartRequired,
391
+ saved: result.saved,
441
392
  });
442
393
  });
443
394
  /** 从请求中提取候选 token:头 / 查询参数 / cookie(浏览器导航场景靠 cookie 续命)。 */
@@ -510,9 +461,29 @@ function splatParam(req) {
510
461
  return v.join("/");
511
462
  return String(v ?? "");
512
463
  }
464
+ /** Preview capabilities authorize only a currently registered live-preview proxy.
465
+ * Forward here, never call next(): capability paths cannot reach any host API. */
466
+ function livePreviewCapability(req) {
467
+ if (req.method !== "GET" && req.method !== "HEAD")
468
+ return undefined;
469
+ const candidate = /^\/__live-preview\/[a-f0-9]{64}(?=\/|$)/.exec(req.path)?.[0];
470
+ if (!candidate)
471
+ return undefined;
472
+ const hit = pluginMgr.findProxy(req.path);
473
+ if (!hit || hit.pluginId !== "live-preview" || !/^\/__live-preview\/[a-f0-9]{64}$/.test(hit.prefix))
474
+ return undefined;
475
+ if (!timingSafeEqual(createHash("sha256").update(candidate).digest(), createHash("sha256").update(hit.prefix).digest()))
476
+ return undefined;
477
+ return hit;
478
+ }
513
479
  // 常挂载:本地 /setup 页支持运行时设置/清除口令(AUTH_TOKEN 是 let,热旋转)。
514
480
  // 无口令时直接放行,保持原有行为不变。
515
481
  app.use((req, res, next) => {
482
+ const preview = livePreviewCapability(req);
483
+ if (preview) {
484
+ proxyHttp(preview, req, res);
485
+ return;
486
+ }
516
487
  if (!AUTH_TOKEN) {
517
488
  next();
518
489
  return;
@@ -599,7 +570,7 @@ const ORIGIN = launchOrigin();
599
570
  const SERVICE_INFO = toServiceInfo(ORIGIN);
600
571
  /** PI_WEB_TABS: the tabs this instance offers. null = all of them, as before. */
601
572
  const TABS = parseTabs();
602
- registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
573
+ registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd, undefined, (clientId) => (sharedStateStore.getSettingsSnapshot(clientId).folderUploadMaxMb ?? 32) * 1024 * 1024);
603
574
  app.get("/api/health", (_req, res) => {
604
575
  // 审查 #352:该端点对未鉴权开放(监控探针需要),故只保留版本/引擎与 SDK
605
576
  // 副本诊断信息,不再暴露 cwd(工作区路径披露)与 pid(指纹/信息收集面)。
@@ -615,6 +586,13 @@ app.get("/api/health", (_req, res) => {
615
586
  faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
616
587
  });
617
588
  });
589
+ /** Every inline file response is untrusted active content, regardless of MIME.
590
+ * This runs before local/remote dispatch and covers HEAD, Range and 304 too. */
591
+ app.use(["/api/file", "/api/attachment/:hash", "/api/preview"], (req, res, next) => {
592
+ res.setHeader("Content-Security-Policy", req.query.allowJs === "1" ? "sandbox allow-scripts" : "sandbox");
593
+ res.setHeader("X-Content-Type-Options", "nosniff");
594
+ next();
595
+ });
618
596
  /**
619
597
  * 基于 SHA-256 内容寻址的附件静态服务:
620
598
  * 永久强缓存(immutable),支持图片和文件读取。
@@ -622,24 +600,22 @@ app.get("/api/health", (_req, res) => {
622
600
  app.get("/api/attachment/:hash", async (req, res) => {
623
601
  try {
624
602
  const hash = String(req.params.hash ?? "").trim();
625
- const hit = await readAttachment(hash);
603
+ const hit = await findAttachment(hash);
626
604
  if (!hit) {
627
605
  res.status(404).end("attachment not found");
628
606
  return;
629
607
  }
630
608
  res.setHeader("Content-Type", hit.mimeType);
631
- res.setHeader("Content-Length", hit.buffer.length);
632
609
  res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
633
- if (hit.mimeType === "image/svg+xml") {
634
- // SVG 以文档形态打开(顶层导航/iframe)时内嵌 <script> 会在本应用
635
- // origin 执行——附件内容可来自剪贴板/工作区文件,等同存储型 XSS
636
- // (审查 #352 P0-1)。sandbox CSP 让文档形态降级到不透明 origin;
637
- // <img> 引用不受影响(子资源响应的 CSP 不作用于引用页,且
638
- // SVG-as-image 本就不执行脚本)。
639
- res.setHeader("Content-Security-Policy", "sandbox");
640
- res.setHeader("X-Content-Type-Options", "nosniff");
641
- }
642
- res.end(hit.buffer);
610
+ // Hash-located attachments may reside under a hidden dataDir (e.g. .pi-web).
611
+ res.sendFile(hit.filePath, { dotfiles: "allow" }, (err) => {
612
+ if (!err)
613
+ return;
614
+ if (!res.headersSent)
615
+ res.status(err.statusCode ?? 500).end();
616
+ else
617
+ res.destroy(err);
618
+ });
643
619
  }
644
620
  catch (err) {
645
621
  res.status(500).end(err.message);
@@ -687,11 +663,6 @@ app.get("/api/file", async (req, res) => {
687
663
  }
688
664
  const name = basename(abs);
689
665
  const isDownload = req.query.download === "1";
690
- // HTML files preview through a sandboxed <iframe> in the file modal
691
- // (FilePreview.tsx). They are text as far as previewKind goes, so
692
- // allowlist them explicitly here.
693
- const lower = name.toLowerCase();
694
- const isHtmlPreview = lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml");
695
666
  const st = await stat(abs);
696
667
  if (!st.isFile()) {
697
668
  res.status(400).end("not a file");
@@ -708,26 +679,6 @@ app.get("/api/file", async (req, res) => {
708
679
  res.download(abs, name, { dotfiles: "allow" });
709
680
  }
710
681
  else {
711
- if (isHtmlPreview) {
712
- // Sandbox even a top-level navigation to this URL: a workspace
713
- // HTML file must never get our origin (it could otherwise read
714
- // the token cookie). The modal iframe carries its own sandbox
715
- // attribute as well (defense in depth).
716
- //
717
- // ?allowJs=1 is the explicit per-file opt-in from the preview
718
- // modal ("启用脚本"): scripts run, but still in an opaque
719
- // origin — no DOM/cookie/storage access to our app, no forms,
720
- // no top-navigation. NEVER add allow-same-origin here.
721
- const allowJs = req.query.allowJs === "1";
722
- res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
723
- res.setHeader("X-Content-Type-Options", "nosniff");
724
- }
725
- else if (lower.endsWith(".svg")) {
726
- // 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化
727
- // (审查 #352 P0-1),<img> 内嵌用法不受影响。
728
- res.setHeader("Content-Security-Policy", "sandbox");
729
- res.setHeader("X-Content-Type-Options", "nosniff");
730
- }
731
682
  res.sendFile(abs, { dotfiles: "allow" });
732
683
  }
733
684
  }
@@ -864,22 +815,11 @@ app.get("/api/preview/*splat", async (req, res) => {
864
815
  }
865
816
  abs = wp.abs;
866
817
  }
867
- const name = basename(abs);
868
818
  const st = await stat(abs);
869
819
  if (!st.isFile()) {
870
820
  res.status(400).end("not a file");
871
821
  return;
872
822
  }
873
- res.setHeader("X-Content-Type-Options", "nosniff");
874
- const lower = name.toLowerCase();
875
- if (lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml")) {
876
- const allowJs = req.query.allowJs === "1";
877
- res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
878
- }
879
- else if (lower.endsWith(".svg")) {
880
- // 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化(审查 #352 P0-1)。
881
- res.setHeader("Content-Security-Policy", "sandbox");
882
- }
883
823
  res.sendFile(abs, { dotfiles: "allow" });
884
824
  }
885
825
  catch {
@@ -1001,69 +941,17 @@ const PLUGINS_DIR = join(DATA_DIR, "plugins");
1001
941
  app.all(["/plugins-api/:id/*splat", "/plugins-api/:id"], (req, res) => {
1002
942
  // 多段子路径的 splat 是数组(见 splatParam),拼回 "/" 后再交插件路由。
1003
943
  const rest = splatParam(req);
1004
- pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res);
944
+ const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
945
+ const cs = cid ? service.get(cid) : undefined;
946
+ if (cid && !cs) {
947
+ res.status(400).json({ error: "Unknown client workspace" });
948
+ return;
949
+ }
950
+ pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res, cs ? { cwd: cs.cwd, roots: cs.workspaceRoots } : undefined);
1005
951
  });
1006
- function proxyForwardPath(hit, url) {
1007
- let fwd = String(url ?? "/").slice(hit.prefix.length);
1008
- if (!fwd.startsWith("/"))
1009
- fwd = `/${fwd}`;
1010
- return fwd || "/";
1011
- }
1012
- function proxyHttp(hit, req, res) {
1013
- const fwdPath = proxyForwardPath(hit, req.url ?? "/");
1014
- const headers = {};
1015
- for (const [k, v] of Object.entries(req.headers)) {
1016
- if (v === undefined)
1017
- continue;
1018
- if (k.toLowerCase() === "host")
1019
- continue;
1020
- if (k.toLowerCase() === "content-length" && req.method !== "GET" && req.method !== "HEAD")
1021
- continue;
1022
- headers[k] = v;
1023
- }
1024
- // 内页拼 SSE/资源绝对地址用(子路径反代下 import.meta 推导不到前缀,靠这个头)。
1025
- headers["x-pi-proxy-prefix"] = hit.prefix;
1026
- let body;
1027
- if (req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined) {
1028
- const b = req.body;
1029
- if (Buffer.isBuffer(b))
1030
- body = b;
1031
- else if (typeof b === "string")
1032
- body = Buffer.from(b);
1033
- else if (b !== undefined) {
1034
- body = Buffer.from(JSON.stringify(b));
1035
- if (!headers["content-type"])
1036
- headers["content-type"] = "application/json";
1037
- }
1038
- if (body)
1039
- headers["content-length"] = String(body.length);
1040
- }
1041
- const up = proxyRequest({ host: hit.host, port: hit.port, method: req.method, path: fwdPath, headers, timeout: 30000 }, (upRes) => {
1042
- const out = {};
1043
- for (const [k, v] of Object.entries(upRes.headers)) {
1044
- if (v === undefined)
1045
- continue;
1046
- const lk = k.toLowerCase();
1047
- if (lk === "connection" || lk === "keep-alive" || lk === "transfer-encoding" || lk === "upgrade")
1048
- continue;
1049
- out[k] = v;
1050
- }
1051
- res.writeHead(upRes.statusCode ?? 502, out);
1052
- upRes.pipe(res);
1053
- });
1054
- up.on("timeout", () => up.destroy(new Error("proxy timeout")));
1055
- up.on("error", (err) => {
1056
- console.error(`[proxy:${hit.prefix}] → 127.0.0.1:${hit.port}${fwdPath} failed:`, err);
1057
- if (!res.headersSent)
1058
- res.status(502).end("proxy target unreachable");
1059
- else
1060
- res.end();
1061
- });
1062
- if (body)
1063
- up.end(body);
1064
- else
1065
- req.pipe(up);
1066
- }
952
+ /** 通用插件代理(host.registerProxy 注册的前缀落到这里):去前缀后原样透传到
953
+ * 127.0.0.1:port——相对路径/Range/SSE 天然可用。PI_WEB_TOKEN 鉴权已在上方覆盖。
954
+ * 必须站在静态资源与 SPA catch-all 之前,否则子路径被 index.html 吞掉。 */
1067
955
  app.use((req, res, next) => {
1068
956
  const hit = pluginMgr.findProxy(req.path);
1069
957
  if (!hit) {
@@ -1122,6 +1010,61 @@ app.get("/plugins-shared/*splat", (req, res) => {
1122
1010
  });
1123
1011
  /** Set in the env of the replacement child spawned by a self-update restart. */
1124
1012
  const RESTART_CHILD_ENV = "PI_WEB_RESTART_CHILD";
1013
+ // Local-only device enrollment stays behind host authentication and ahead of the SPA fallback.
1014
+ const deviceDesktop = createDeviceDesktop({ app, dataDir: DATA_DIR, authorize: (req) => !AUTH_TOKEN || tokenOk(req) });
1015
+ const deviceBots = await createLocalBotRegistry(DATA_DIR);
1016
+ const deviceCenter = await installLocalDeviceCenter({
1017
+ app,
1018
+ dataDir: DATA_DIR,
1019
+ bots: deviceBots,
1020
+ botCatalog: {
1021
+ defaultCwd: CWD,
1022
+ dataDir: DATA_DIR,
1023
+ models: async (signal) => {
1024
+ signal.throwIfAborted();
1025
+ const models = (await piServiceInstance?.pluginClient()?.listLocalBotModels()) ?? [];
1026
+ signal.throwIfAborted();
1027
+ return models;
1028
+ },
1029
+ projects: () => sharedStateStore.getRecentProjects(""),
1030
+ defaultModel: () => sharedStateStore.getDefaultModel("pi"),
1031
+ peekMcpBridge: (cwd) => mcpProjects.peekBridge(cwd),
1032
+ },
1033
+ async connect(config, syncBots) {
1034
+ const localOrigin = `http://127.0.0.1:${PORT}`;
1035
+ const runtime = createDeviceRuntime({
1036
+ config,
1037
+ localOrigin,
1038
+ localAuthToken: AUTH_TOKEN,
1039
+ dataDir: DATA_DIR,
1040
+ bots: deviceBots,
1041
+ });
1042
+ setDeviceCollabService(runtime.collabService);
1043
+ const connector = createDeviceConnector({
1044
+ hubUrl: config.hubUrl,
1045
+ deviceId: config.deviceId,
1046
+ credential: config.credential,
1047
+ localOrigin,
1048
+ localAuthToken: AUTH_TOKEN,
1049
+ onTask: runtime.onTask,
1050
+ onConnect: syncBots,
1051
+ onCommand: runtime.onCommand,
1052
+ onDisconnect: () => {
1053
+ void runtime
1054
+ .onDisconnect()
1055
+ .catch(() => console.warn("[device-center] Task stop was not confirmed; project remains locked"));
1056
+ },
1057
+ });
1058
+ return {
1059
+ isConnected: connector.isOnline,
1060
+ async close() {
1061
+ setDeviceCollabService(undefined);
1062
+ connector.close();
1063
+ await runtime.close();
1064
+ },
1065
+ };
1066
+ },
1067
+ });
1125
1068
  const webDist = join(pkgRoot, "web", "dist");
1126
1069
  /** webDist accessor for buildId() (declared above webDist's const). */
1127
1070
  function webDistPath() {
@@ -1250,6 +1193,8 @@ function originAllowed(req) {
1250
1193
  return false;
1251
1194
  }
1252
1195
  httpServer.on("upgrade", (req, socket, head) => {
1196
+ if (deviceDesktop.handleUpgrade(req, socket, head))
1197
+ return;
1253
1198
  let pathname = "/";
1254
1199
  try {
1255
1200
  pathname = new URL(req.url ?? "/", "http://localhost").pathname;
@@ -1612,10 +1557,14 @@ const service = {
1612
1557
  }
1613
1558
  return Promise.resolve();
1614
1559
  },
1615
- answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled) {
1560
+ navigateQuestion(targetId, id) {
1561
+ const targetSvc = ensureEngine(resolveClientEngine(targetId));
1562
+ return targetSvc.navigateQuestion?.(targetId, id) ?? Promise.resolve();
1563
+ },
1564
+ answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
1616
1565
  const targetSvc = ensureEngine(resolveClientEngine(targetId));
1617
1566
  if (typeof targetSvc.answerElsewhereQuestion === "function") {
1618
- return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled);
1567
+ return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason);
1619
1568
  }
1620
1569
  return Promise.resolve();
1621
1570
  },
@@ -1970,30 +1919,23 @@ function pushNoticeToAll(level, text, textEn) {
1970
1919
  }
1971
1920
  // MCP 工具桥:读取配置启动外部 MCP 服务器(stdio / HTTP streamable-http),把它们的
1972
1921
  // 工具并入与插件工具相同的 customTools 管线;单服务器失败不炸进程。
1973
- const mcpBridge = new McpBridge(DATA_DIR, (...a) => console.log("[mcp]", ...a), {
1974
- agentDir: getAgentDir(),
1975
- cwd: CWD,
1976
- onToolsChanged: () => service.applyPluginAgentTools(),
1977
- });
1978
- ClientSession.mcpBridge = mcpBridge;
1979
- pluginMgr.mcpBridge = mcpBridge;
1980
- // mcp.json 热加载:保存文件即生效,改完不必再重启服务。两半都在这里收口 —— reload 换入
1981
- // 新的服务器集合(只重启规格真变了的),applyPluginAgentTools 把新工具推给已有会话。
1982
- const mcpHotReload = createMcpHotReload({
1922
+ const mcpProjects = new McpProjectRuntimeRegistry({
1983
1923
  dataDir: DATA_DIR,
1924
+ isProjectInUse: (cwd) => {
1925
+ const key = (value) => (process.platform === "win32" ? resolve(value).toLowerCase() : resolve(value));
1926
+ return activeEngines().some((svc) => svc.mcpProjectCwds?.().some((project) => key(project) === key(cwd)));
1927
+ },
1984
1928
  agentDir: getAgentDir(),
1985
- cwd: CWD,
1986
- reload: () => mcpBridge.reload(),
1987
- onToolsChanged: () => service.applyPluginAgentTools(),
1988
- onNotice: (level, text, textEn) => pushNoticeToAll(level, text, textEn),
1989
- log: (...a) => console.log(...a),
1990
- });
1991
- void mcpBridge.load().then(() => {
1992
- if (mcpBridge.getTools().length)
1929
+ onToolsChanged: (cwd) => {
1993
1930
  service.applyPluginAgentTools();
1994
- // 播种在 load 之后:否则指纹可能记在 load 读到的版本之前,白重载一次。
1995
- mcpHotReload.start();
1931
+ for (const svc of activeEngines())
1932
+ svc.refreshMcpProject?.(cwd);
1933
+ },
1934
+ onNotice: (_cwd, level, text, textEn) => pushNoticeToAll(level, text, textEn),
1935
+ log: (...a) => console.log("[mcp]", ...a),
1996
1936
  });
1937
+ ClientSession.mcpProjects = mcpProjects;
1938
+ pluginMgr.mcpProjects = mcpProjects;
1997
1939
  // 插件与宿主钩子统一挂载器:无论引擎在启动时预热还是运行期按需懒加载,都一致注入全部回调。
1998
1940
  wireEngineHooks = (svc) => {
1999
1941
  svc.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
@@ -2004,7 +1946,7 @@ wireEngineHooks = (svc) => {
2004
1946
  svc.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
2005
1947
  svc.onConversationChanged = () => pluginMgr.emitConversationChanged();
2006
1948
  svc.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
2007
- svc.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
1949
+ svc.pluginToolsProvider = (cwd) => [...pluginMgr.getAgentTools(), ...(cwd ? mcpProjects.getTools(cwd) : [])];
2008
1950
  svc.pluginCommandsProvider = () => pluginMgr.listCommands();
2009
1951
  svc.pluginBgTasksProvider = () => pluginMgr.bgTasks();
2010
1952
  svc.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
@@ -2125,6 +2067,11 @@ pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
2125
2067
  // runAborter:有现成 abort 路径(interruptRun,卡住/空转强制重置语义继承)。
2126
2068
  pm.runAborter = async (id) => {
2127
2069
  try {
2070
+ if (id.startsWith("pr-")) {
2071
+ if (!piServiceInstance)
2072
+ return { ok: false, error: "not supported" };
2073
+ return await piServiceInstance.abortPluginRun(id);
2074
+ }
2128
2075
  const cs = pickClient();
2129
2076
  if (!cs || typeof cs.abortForPlugins !== "function")
2130
2077
  return { ok: false, error: "not supported" };
@@ -2237,10 +2184,15 @@ wss.on("connection", (ws) => {
2237
2184
  service.noteSocketOpen();
2238
2185
  let clientId = null;
2239
2186
  let closed = false;
2187
+ const helloTimer = setTimeout(() => {
2188
+ if (!clientId)
2189
+ ws.close(1008, "Handshake timed out");
2190
+ }, 15_000);
2191
+ helloTimer.unref?.();
2240
2192
  /** 最近一份全量 snapshot 的估算字节数(UTF-16 ×2),供背压相对阈值用(issue #11)。 */
2241
2193
  let lastSnapshotBytes = 0;
2242
2194
  /** Commands received while the session is still being created — replayed after attach.
2243
- * 带上限(256 条):attach 挂死/失败保活期间队列不再无界增长,超限丢最旧并告警。 */
2195
+ * 按条数和累计字节限制;超限关闭连接,避免静默丢弃已接收的命令。 */
2244
2196
  const pending = new PendingCommandQueue();
2245
2197
  /** attach 完成(含插件链 + 首快照)前一律排队(见 hello 分支的 replayQueued):
2246
2198
  * ready 先行后,ready 只代表传输通,插件命令目录/首快照都还没好,直接分发
@@ -2306,7 +2258,13 @@ wss.on("connection", (ws) => {
2306
2258
  // Plugins broadcast to every open socket; unregister on close below.
2307
2259
  // Plugins broadcast to every open socket; unregister on close below. The
2308
2260
  // cid getter lets plugins target THIS socket via host.sendTo(clientId).
2309
- const removePluginSender = pluginMgr.addSender(send, () => clientId);
2261
+ const removePluginSender = pluginMgr.addSender((msg) => {
2262
+ // Task sockets receive only their executor/session events. Global plugin
2263
+ // notices have no session attribution and must not abort unrelated tasks.
2264
+ if (!clientId || clientId.startsWith("device-task-"))
2265
+ return;
2266
+ send(msg);
2267
+ }, () => clientId);
2310
2268
  /** DOM 授权落盘 + notice 反馈(两步握手的 grant 与单步 revoke 共用收尾)。
2311
2269
  * cs 缺席(未 attach 完成)时只落盘不提示——消息本来就会在 attach 前排队。 */
2312
2270
  const applyDomConsent = (pluginId, granted) => {
@@ -2530,9 +2488,10 @@ wss.on("connection", (ws) => {
2530
2488
  });
2531
2489
  }
2532
2490
  };
2533
- const dispatch = (msg) => {
2491
+ const dispatch = (msg, wireBytes) => {
2534
2492
  if (!clientId) {
2535
- pending.push(msg);
2493
+ if (!pending.push(msg, wireBytes))
2494
+ ws.close(1009, "Pending command budget exceeded");
2536
2495
  return;
2537
2496
  }
2538
2497
  // switch_engine 为宿主级控制消息:豁免 cs 初始化与 attachDone 门禁,确保任何异常状态下都能自由切回!
@@ -2554,7 +2513,8 @@ wss.on("connection", (ws) => {
2554
2513
  const cs = service.get(clientId);
2555
2514
  if (!cs || !attachDone) {
2556
2515
  // Session not ready yet (hello processing / plugin chain) — hold the command.
2557
- pending.push(msg);
2516
+ if (!pending.push(msg, wireBytes))
2517
+ ws.close(1009, "Pending command budget exceeded");
2558
2518
  return;
2559
2519
  }
2560
2520
  // 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
@@ -2566,6 +2526,7 @@ wss.on("connection", (ws) => {
2566
2526
  conversationId: msg.conversationId,
2567
2527
  beforeId: msg.beforeId,
2568
2528
  before: msg.before,
2529
+ historyGeneration: msg.historyGeneration,
2569
2530
  });
2570
2531
  if (!handled && cs) {
2571
2532
  const activeId = typeof cs.activeConversationId === "function" ? cs.activeConversationId() : undefined;
@@ -2579,6 +2540,7 @@ wss.on("connection", (ws) => {
2579
2540
  conversationId: convId,
2580
2541
  beforeId: msg.beforeId,
2581
2542
  before: msg.before,
2543
+ historyGeneration: msg.historyGeneration,
2582
2544
  });
2583
2545
  }
2584
2546
  if (!handled && (!msg.conversationId || msg.conversationId === activeId)) {
@@ -2609,7 +2571,7 @@ wss.on("connection", (ws) => {
2609
2571
  return;
2610
2572
  if (handleTerminalMessage(msg, cs))
2611
2573
  return;
2612
- if (handleSessionLifecycleMessage(msg, cs))
2574
+ if (handleSessionLifecycleMessage(msg, cs, send))
2613
2575
  return;
2614
2576
  if (handlePlanAndGoalMessage(msg, cs))
2615
2577
  return;
@@ -2617,7 +2579,7 @@ wss.on("connection", (ws) => {
2617
2579
  return;
2618
2580
  if (handleRemoteSshMessage(msg, remoteSshService, send))
2619
2581
  return;
2620
- if (handleSettingsMessage(msg, cs))
2582
+ if (handleSettingsMessage(msg, cs, send))
2621
2583
  return;
2622
2584
  if (handleCanvasMessage(msg, DATA_DIR, canvasOrchestrator, send, { runBase: cs.cwd }))
2623
2585
  return;
@@ -2645,6 +2607,20 @@ wss.on("connection", (ws) => {
2645
2607
  return;
2646
2608
  switch (msg.type) {
2647
2609
  case "prompt": {
2610
+ // No await between identity validation and prompt(): engines capture
2611
+ // their conversation synchronously at entry.
2612
+ if (msg.targetConversationId !== undefined &&
2613
+ (typeof msg.targetConversationId !== "string" ||
2614
+ !msg.targetConversationId ||
2615
+ cs.activeConversationId?.() !== msg.targetConversationId)) {
2616
+ send({
2617
+ type: "notice",
2618
+ level: "warning",
2619
+ text: "发送已取消:目标对话已改变,请重新发送。",
2620
+ textEn: "Prompt canceled: the target conversation changed. Please send again.",
2621
+ });
2622
+ break;
2623
+ }
2648
2624
  const hasAttach = Boolean(msg.attachments && msg.attachments.length > 0);
2649
2625
  if (!msg.text?.trim() && !hasAttach) {
2650
2626
  send({
@@ -2716,6 +2692,10 @@ wss.on("connection", (ws) => {
2716
2692
  });
2717
2693
  }
2718
2694
  break;
2695
+ case "navigate_question":
2696
+ if (typeof service.navigateQuestion === "function")
2697
+ void service.navigateQuestion(clientId, msg.id);
2698
+ break;
2719
2699
  case "peek_elsewhere_question":
2720
2700
  if (typeof service.peekElsewhereQuestion === "function") {
2721
2701
  void service.peekElsewhereQuestion(clientId, msg.owner, msg.id);
@@ -2827,14 +2807,38 @@ wss.on("connection", (ws) => {
2827
2807
  ws.on("message", (data) => {
2828
2808
  tracked.isAlive = true;
2829
2809
  tracked.missedPings = 0;
2830
- let msg;
2810
+ const wireBytes = Array.isArray(data) ? data.reduce((n, chunk) => n + chunk.length, 0) : data.byteLength;
2811
+ if (!clientId && wireBytes > MAX_PRE_HELLO_WS_BYTES) {
2812
+ ws.close(1009, "Handshake message too large");
2813
+ return;
2814
+ }
2815
+ let parsed;
2831
2816
  try {
2832
- msg = JSON.parse(data.toString());
2817
+ parsed = JSON.parse(data.toString());
2818
+ }
2819
+ catch {
2820
+ return;
2821
+ }
2822
+ if (!isClientMessageEnvelope(parsed))
2823
+ return;
2824
+ if (!isClientMessageWithinByteLimit(parsed.type, wireBytes, !!clientId)) {
2825
+ ws.close(1009, "Message budget exceeded");
2826
+ return;
2827
+ }
2828
+ const msg = parsed;
2829
+ try {
2830
+ const botClientId = clientId ?? (msg.type === "hello" ? msg.clientId : undefined);
2831
+ if (botClientId && !botExecutionMessageAllowed(botClientId, msg.type)) {
2832
+ ws.close(1008, "Bot control command denied");
2833
+ return;
2834
+ }
2833
2835
  }
2834
2836
  catch {
2837
+ ws.close(1008, "Invalid Bot execution capability");
2835
2838
  return;
2836
2839
  }
2837
2840
  if (msg.type === "hello") {
2841
+ clearTimeout(helloTimer);
2838
2842
  // 重放守卫:一条连接只允许 attach 一次。clientId 已赋值说明 hello 处理过
2839
2843
  //(或进行中),再来的 hello 幂等回一条 ready 即可——否则重复 hello 会把
2840
2844
  // service.attach 整个再跑一遍:重型 ClientSession 重复创建 + 旧 send sink
@@ -3026,9 +3030,10 @@ wss.on("connection", (ws) => {
3026
3030
  });
3027
3031
  return;
3028
3032
  }
3029
- dispatch(msg);
3033
+ dispatch(msg, wireBytes);
3030
3034
  });
3031
3035
  ws.on("close", () => {
3036
+ clearTimeout(helloTimer);
3032
3037
  service.noteSocketClose();
3033
3038
  closed = true;
3034
3039
  pending.clear();
@@ -3218,12 +3223,13 @@ async function shutdown(signal = "SIGINT") {
3218
3223
  let code = 0;
3219
3224
  try {
3220
3225
  clearInterval(heartbeatTimer);
3226
+ await deviceCenter.close();
3227
+ await deviceDesktop.close();
3221
3228
  stopControl();
3222
3229
  scheduler.stop();
3223
3230
  pluginMgr.dispose();
3224
3231
  pluginInstaller.dispose();
3225
- mcpHotReload.dispose();
3226
- mcpBridge.dispose();
3232
+ await mcpProjects.dispose();
3227
3233
  await globalLspPool.shutdownAll();
3228
3234
  await service.disposeAll();
3229
3235
  // Don't let dead browsers hold the exit open: half-open WebSocket /