pi-web-ui 0.117.0 → 0.118.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 (512) hide show
  1. package/CHANGELOG.md +48 -2
  2. package/README.md +69 -138
  3. package/README.zh-CN.md +70 -179
  4. package/README.zh-TW.md +3 -1
  5. package/bin/device-hub-cli.mjs +147 -43
  6. package/bin/frp-manager.mjs +4 -80
  7. package/bin/hub-upgrade.mjs +561 -0
  8. package/bin/pi-device-hub.mjs +0 -1
  9. package/bin/pi-web-ui.mjs +56 -444
  10. package/deploy/nginx-subpath.conf +0 -33
  11. package/deploy/pi-web-ui.service +0 -20
  12. package/dist/server/agent-formatters.js +4 -38
  13. package/dist/server/agent-service-daemon.js +160 -374
  14. package/dist/server/agent-service.js +875 -2978
  15. package/dist/server/approval-audit.js +2 -23
  16. package/dist/server/approval-default-rules.js +0 -6
  17. package/dist/server/approval-rules.js +7 -105
  18. package/dist/server/ask-user-question-tool.js +1 -12
  19. package/dist/server/atomic-file.js +33 -5
  20. package/dist/server/attachment-store.js +0 -36
  21. package/dist/server/attachments.js +3 -112
  22. package/dist/server/auth-cookie.js +0 -21
  23. package/dist/server/bash-tool.js +1 -32
  24. package/dist/server/bg-servers.js +0 -96
  25. package/dist/server/browser-page-tool.js +11 -62
  26. package/dist/server/builtin-modules.js +7 -0
  27. package/dist/server/canvas/canvas-agent-tool.js +58 -47
  28. package/dist/server/canvas/canvas-cards.js +0 -14
  29. package/dist/server/canvas/canvas-dispatch.js +7 -4
  30. package/dist/server/canvas/canvas-orchestrator.js +167 -181
  31. package/dist/server/canvas/canvas-runtime-messages.js +30 -0
  32. package/dist/server/canvas/canvas-scheduled-task.js +0 -3
  33. package/dist/server/canvas/canvas-scheduler.js +5 -7
  34. package/dist/server/canvas/canvas-store.js +24 -35
  35. package/dist/server/canvas/canvas-validation.js +17 -14
  36. package/dist/server/canvas/canvas-workspace.js +26 -30
  37. package/dist/server/canvas/pstack-skills-data.js +0 -5
  38. package/dist/server/claim-files-tool.js +1 -15
  39. package/dist/server/claim-store.js +5 -49
  40. package/dist/server/client-id-utils.js +0 -16
  41. package/dist/server/client-state.js +6 -213
  42. package/dist/server/communicate-tool.js +0 -3
  43. package/dist/server/compact-context-tool.js +0 -30
  44. package/dist/server/compacted-history.js +0 -35
  45. package/dist/server/compaction-instructions.js +0 -13
  46. package/dist/server/compaction-markers.js +3 -76
  47. package/dist/server/compaction-state.js +0 -21
  48. package/dist/server/composer-drafts.js +0 -34
  49. package/dist/server/context-budget-runner.js +0 -11
  50. package/dist/server/context-budget.js +1 -70
  51. package/dist/server/context-evidence.js +0 -14
  52. package/dist/server/context-usage.js +0 -12
  53. package/dist/server/control-socket.js +4 -48
  54. package/dist/server/conversation-communication.js +0 -10
  55. package/dist/server/conversation-identity.js +0 -1
  56. package/dist/server/conversation-read-tool.js +0 -58
  57. package/dist/server/conversation-tool-names.js +0 -1
  58. package/dist/server/conversation-tool.js +0 -1
  59. package/dist/server/conversation-touches.js +4 -75
  60. package/dist/server/dangling-tools.js +0 -82
  61. package/dist/server/delegate-mode.js +0 -36
  62. package/dist/server/delegate-task.js +2 -28
  63. package/dist/server/device-center/approval-summary.js +0 -1
  64. package/dist/server/device-center/bot-catalog.js +0 -3
  65. package/dist/server/device-center/bot-execution.js +0 -8
  66. package/dist/server/device-center/bot-presets.js +0 -1
  67. package/dist/server/device-center/bots.js +0 -1
  68. package/dist/server/device-center/collab-service.js +1 -3
  69. package/dist/server/device-center/collab-tool.js +0 -10
  70. package/dist/server/device-center/connector.js +21 -11
  71. package/dist/server/device-center/delivery-authority.js +0 -3
  72. package/dist/server/device-center/delivery-subject.js +0 -1
  73. package/dist/server/device-center/desktop-linux.js +3 -15
  74. package/dist/server/device-center/desktop-native.js +1 -10
  75. package/dist/server/device-center/desktop-page.js +2 -3
  76. package/dist/server/device-center/desktop-setup.js +1 -3
  77. package/dist/server/device-center/desktop.js +1 -7
  78. package/dist/server/device-center/device-integration.js +1 -27
  79. package/dist/server/device-center/device-lan-access.js +403 -0
  80. package/dist/server/device-center/device-lan.js +484 -0
  81. package/dist/server/device-center/device-portals.js +0 -3
  82. package/dist/server/device-center/execution-failure.js +0 -2
  83. package/dist/server/device-center/execution-guides.js +0 -1
  84. package/dist/server/device-center/execution-instructions.js +0 -1
  85. package/dist/server/device-center/execution-settings.js +0 -1
  86. package/dist/server/device-center/execution-system-prompt.js +0 -3
  87. package/dist/server/device-center/execution-workspace.js +1 -4
  88. package/dist/server/device-center/executor.js +0 -27
  89. package/dist/server/device-center/file-sync-paths.js +0 -5
  90. package/dist/server/device-center/file-sync.js +0 -10
  91. package/dist/server/device-center/group-context-delta.js +0 -8
  92. package/dist/server/device-center/group-context-message.js +0 -14
  93. package/dist/server/device-center/group-context.js +0 -19
  94. package/dist/server/device-center/group-events.js +0 -2
  95. package/dist/server/device-center/group-plan-guard.js +1 -35
  96. package/dist/server/device-center/group-router-runtime.js +182 -0
  97. package/dist/server/device-center/group-router-worker.js +178 -0
  98. package/dist/server/device-center/group-router.js +359 -0
  99. package/dist/server/device-center/hub-auth.js +24 -2
  100. package/dist/server/device-center/hub-conversations.js +0 -12
  101. package/dist/server/device-center/hub-deliveries.js +0 -1
  102. package/dist/server/device-center/hub-integration.js +0 -8
  103. package/dist/server/device-center/hub-locks.js +1 -5
  104. package/dist/server/device-center/hub-mobile.js +147 -0
  105. package/dist/server/device-center/hub-orchestration.js +400 -0
  106. package/dist/server/device-center/hub-page.js +25 -7
  107. package/dist/server/device-center/hub-setup.js +0 -6
  108. package/dist/server/device-center/hub-transaction-log.js +0 -22
  109. package/dist/server/device-center/hub-upgrade.js +162 -0
  110. package/dist/server/device-center/hub-webhooks.js +1 -3
  111. package/dist/server/device-center/hub.js +210 -86
  112. package/dist/server/device-center/human-interaction.js +1 -4
  113. package/dist/server/device-center/integration-errors.js +0 -2
  114. package/dist/server/device-center/integration-verification.js +0 -2
  115. package/dist/server/device-center/local-hub.js +0 -2
  116. package/dist/server/device-center/local-publication.js +1 -8
  117. package/dist/server/device-center/local-verification-job.js +0 -2
  118. package/dist/server/device-center/local-verification.js +0 -1
  119. package/dist/server/device-center/local.js +267 -39
  120. package/dist/server/device-center/main.js +14 -1
  121. package/dist/server/device-center/mobile-notification-forwarder.js +292 -0
  122. package/dist/server/device-center/native-desktop/macos.js +0 -1
  123. package/dist/server/device-center/native-desktop/windows.js +0 -1
  124. package/dist/server/device-center/partition-log.js +0 -31
  125. package/dist/server/device-center/path-portal.js +42 -12
  126. package/dist/server/device-center/publication-journal.js +0 -7
  127. package/dist/server/device-center/publish-intent.js +0 -5
  128. package/dist/server/device-center/relay.js +85 -30
  129. package/dist/server/device-center/report-upload.js +0 -1
  130. package/dist/server/device-center/runtime.js +1 -18
  131. package/dist/server/device-center/store.js +13 -33
  132. package/dist/server/device-center/task-context-budget.js +0 -3
  133. package/dist/server/device-center/task-error.js +0 -1
  134. package/dist/server/device-center/task-journal.js +6 -23
  135. package/dist/server/device-center/task-outcome.js +0 -13
  136. package/dist/server/device-center/task-plan.js +0 -1
  137. package/dist/server/device-center/task-progress.js +0 -16
  138. package/dist/server/device-center/task-recovery.js +5 -88
  139. package/dist/server/device-center/task-report-outbox.js +0 -4
  140. package/dist/server/device-center/task-report.js +2 -10
  141. package/dist/server/device-center/task-scheduler.js +1 -35
  142. package/dist/server/device-center/task-settlement.js +0 -18
  143. package/dist/server/device-center/task-state.js +0 -12
  144. package/dist/server/device-center/task-workspace.js +0 -50
  145. package/dist/server/device-center/transfer-stream.js +5 -45
  146. package/dist/server/device-center/transfers.js +2 -10
  147. package/dist/server/device-center/verification-limits.js +0 -1
  148. package/dist/server/device-center/work-contract.js +1 -73
  149. package/dist/server/device-center/work-items.js +317 -0
  150. package/dist/server/device-center/workspaces.js +0 -1
  151. package/dist/server/dispatch-domain-handlers.js +190 -32
  152. package/dist/server/dispatch-plugin-handlers.js +2 -19
  153. package/dist/server/dsh/dsh-agent-service.js +69 -599
  154. package/dist/server/dsh/dsh-client.js +7 -111
  155. package/dist/server/dsh/dsh-market-service.js +4 -25
  156. package/dist/server/dsh/dsh-serialize.js +0 -49
  157. package/dist/server/dsh/dsh-sessions.js +0 -37
  158. package/dist/server/dsh/dsh-usage.js +0 -37
  159. package/dist/server/dsh/preset-clones.js +1 -65
  160. package/dist/server/dsh/runtime/custom-prompt.mjs +0 -14
  161. package/dist/server/dsh/runtime/goal-rpc.mjs +7 -176
  162. package/dist/server/dsh/runtime/launcher.mjs +2 -53
  163. package/dist/server/dsh/runtime/override.patch.yml +0 -29
  164. package/dist/server/dsh/runtime/runtime-root.mjs +0 -54
  165. package/dist/server/durable/durable-agent-service.js +5 -23
  166. package/dist/server/durable/durable-driver.js +12 -73
  167. package/dist/server/durable/durable-event-projector.js +1 -50
  168. package/dist/server/durable/durable-loader.js +0 -12
  169. package/dist/server/durable/durable-models.js +11 -80
  170. package/dist/server/durable/durable-storage.js +1 -17
  171. package/dist/server/durable/durable-tools.js +2 -20
  172. package/dist/server/durable/index.js +0 -3
  173. package/dist/server/edit-soft-tool.js +2 -81
  174. package/dist/server/engine-capabilities.js +0 -13
  175. package/dist/server/engine-catalog.js +74 -0
  176. package/dist/server/engine-cli.js +89 -0
  177. package/dist/server/engine-probe.js +35 -217
  178. package/dist/server/ensure-bash.js +2 -28
  179. package/dist/server/eval-tool.js +1 -50
  180. package/dist/server/evidence-tool-hooks.js +0 -2
  181. package/dist/server/file-archives.js +0 -10
  182. package/dist/server/file-save.js +1 -12
  183. package/dist/server/file-transfer-routes.js +0 -11
  184. package/dist/server/files-service.js +18 -271
  185. package/dist/server/global-loader.js +9 -89
  186. package/dist/server/goal-evidence.js +1 -35
  187. package/dist/server/goal-review-gate.js +0 -58
  188. package/dist/server/goal-service.js +19 -422
  189. package/dist/server/hashline-engine.js +8 -112
  190. package/dist/server/host-guard.js +0 -24
  191. package/dist/server/host-metrics.js +0 -6
  192. package/dist/server/http-proxy.js +1 -7
  193. package/dist/server/i18n.js +5 -72
  194. package/dist/server/icon-svg.js +0 -15
  195. package/dist/server/index.js +177 -680
  196. package/dist/server/json-utils.js +0 -12
  197. package/dist/server/launch-origin.js +0 -44
  198. package/dist/server/left-panel-running.js +0 -9
  199. package/dist/server/load-timing.js +1 -4
  200. package/dist/server/load-tools-tool.js +0 -20
  201. package/dist/server/locales.js +1 -46
  202. package/dist/server/lsp-tool.js +13 -126
  203. package/dist/server/managed.js +0 -48
  204. package/dist/server/marker-service.js +1 -22
  205. package/dist/server/markers/builtins/action.js +0 -19
  206. package/dist/server/markers/builtins/notify.js +1 -9
  207. package/dist/server/markers/builtins/rename.js +0 -13
  208. package/dist/server/markers/index.js +0 -3
  209. package/dist/server/markers/marker.js +0 -13
  210. package/dist/server/markers/registry.js +0 -3
  211. package/dist/server/markers/store.js +1 -12
  212. package/dist/server/market-service.js +7 -43
  213. package/dist/server/mcp-agent-tool.js +0 -10
  214. package/dist/server/mcp-bridge.js +6 -138
  215. package/dist/server/mcp-hot-reload.js +0 -25
  216. package/dist/server/mcp-manager.js +2 -44
  217. package/dist/server/mcp-oauth-login.js +0 -2
  218. package/dist/server/mcp-oauth-ui.js +1 -4
  219. package/dist/server/mcp-oauth.js +5 -79
  220. package/dist/server/mcp-project-runtime.js +0 -4
  221. package/dist/server/message-deletion.js +0 -2
  222. package/dist/server/message-entry-resolver.js +0 -8
  223. package/dist/server/message-window.js +0 -71
  224. package/dist/server/mobile-notification-events.js +16 -0
  225. package/dist/server/mobile-origin.js +79 -0
  226. package/dist/server/mobile-push.js +523 -0
  227. package/dist/server/model-admin.js +19 -358
  228. package/dist/server/model-enrich.js +0 -19
  229. package/dist/server/model-resolver.js +2 -61
  230. package/dist/server/native-cli-discovery.js +115 -0
  231. package/dist/server/native-cli-model.js +71 -0
  232. package/dist/server/native-cli-references.js +214 -0
  233. package/dist/server/native-cli-remote-cleanup.js +58 -0
  234. package/dist/server/native-cli-remote-files.js +282 -0
  235. package/dist/server/native-cli-routes.js +68 -0
  236. package/dist/server/native-cli-runtime.js +1 -0
  237. package/dist/server/native-cli-session-hooks.js +170 -0
  238. package/dist/server/native-cli-session.js +585 -0
  239. package/dist/server/native-cli-state.js +82 -0
  240. package/dist/server/native-cli.js +210 -0
  241. package/dist/server/net-guard.js +9 -71
  242. package/dist/server/office-parse.js +0 -50
  243. package/dist/server/orphan-manager.js +0 -18
  244. package/dist/server/patch-bash-process.js +0 -4
  245. package/dist/server/patch-executable-lookup.js +0 -77
  246. package/dist/server/patch-node-pty.js +3 -43
  247. package/dist/server/patch-remote-catalog.js +1 -32
  248. package/dist/server/patch-tool.js +0 -15
  249. package/dist/server/payload-limits.js +0 -5
  250. package/dist/server/pending-question.js +0 -5
  251. package/dist/server/permission-preset.js +4 -33
  252. package/dist/server/persona-chain.js +0 -26
  253. package/dist/server/pkg-info.js +1 -17
  254. package/dist/server/plan-manager.js +2 -49
  255. package/dist/server/plan-mode.js +0 -97
  256. package/dist/server/plan-update-tool.js +1 -15
  257. package/dist/server/plugin-api-catalog.js +6 -4
  258. package/dist/server/plugin-assets.js +1 -35
  259. package/dist/server/plugin-bundled.js +68 -0
  260. package/dist/server/plugin-catalog-sync.js +0 -37
  261. package/dist/server/plugin-catalog.js +13 -67
  262. package/dist/server/plugin-chat-attachments.js +0 -1
  263. package/dist/server/plugin-conversation-view.js +0 -20
  264. package/dist/server/plugin-dom.js +1 -23
  265. package/dist/server/plugin-facilities.js +4 -115
  266. package/dist/server/plugin-grants.js +2 -90
  267. package/dist/server/plugin-install-spec.js +0 -43
  268. package/dist/server/plugin-installer.js +34 -75
  269. package/dist/server/plugin-llm.js +4 -38
  270. package/dist/server/plugin-manifest-validate.js +0 -31
  271. package/dist/server/plugin-permissions.js +1 -24
  272. package/dist/server/plugin-project.js +7 -129
  273. package/dist/server/plugin-removal.js +1 -8
  274. package/dist/server/plugin-schedule.js +1 -38
  275. package/dist/server/plugin-secrets.js +3 -16
  276. package/dist/server/plugin-tool-guard.js +1 -28
  277. package/dist/server/plugin-ui-slots.js +0 -4
  278. package/dist/server/plugin-updater.js +15 -90
  279. package/dist/server/plugins.js +71 -619
  280. package/dist/server/present-files-tool.js +0 -57
  281. package/dist/server/preset-fields.js +9 -62
  282. package/dist/server/preset-plugin-dependencies.js +0 -2
  283. package/dist/server/preset-share.js +3 -172
  284. package/dist/server/process-utils.js +4 -80
  285. package/dist/server/prompt-assembler.js +2 -30
  286. package/dist/server/prompt-base-store.js +0 -47
  287. package/dist/server/prompt-composer.js +21 -98
  288. package/dist/server/prompt-templates.js +0 -2
  289. package/dist/server/protocol-version.js +1 -11
  290. package/dist/server/protocol.js +0 -5
  291. package/dist/server/queue-modes.js +0 -3
  292. package/dist/server/queue-utils.js +0 -40
  293. package/dist/server/quick-ask-context.js +384 -0
  294. package/dist/server/quick-ask-settings.js +34 -1
  295. package/dist/server/quick-ask.js +123 -27
  296. package/dist/server/read-tool.js +0 -65
  297. package/dist/server/reasoning-registry.js +1 -29
  298. package/dist/server/remote-cli-persistence.js +373 -0
  299. package/dist/server/remote-native-cli.js +78 -0
  300. package/dist/server/remote-ssh-service.js +481 -190
  301. package/dist/server/request-context.js +0 -9
  302. package/dist/server/resolve-global-sdk.js +0 -26
  303. package/dist/server/sandbox-data.js +0 -1
  304. package/dist/server/sandbox-engines.js +0 -1
  305. package/dist/server/sandbox-runtime-gate.js +0 -3
  306. package/dist/server/sandbox-service.js +0 -41
  307. package/dist/server/sandbox-tool.js +0 -20
  308. package/dist/server/schedule-agent-tool.js +2 -31
  309. package/dist/server/scheduler-tasks.js +3 -54
  310. package/dist/server/scm-commitmsg.js +0 -53
  311. package/dist/server/scm.js +3 -48
  312. package/dist/server/sdk-builtin-extensions.js +2 -29
  313. package/dist/server/sdk-origin.js +0 -45
  314. package/dist/server/serialize.js +2 -92
  315. package/dist/server/server-config.js +0 -11
  316. package/dist/server/session-branch.js +1 -87
  317. package/dist/server/session-list-scan.js +17 -25
  318. package/dist/server/session-open.js +2 -26
  319. package/dist/server/session-parser.js +1 -55
  320. package/dist/server/session-scan.js +1 -17
  321. package/dist/server/session-search.js +0 -56
  322. package/dist/server/settings-service.js +11 -126
  323. package/dist/server/setup-config.js +0 -2
  324. package/dist/server/setup-page.js +0 -9
  325. package/dist/server/skill-content-filler.js +0 -17
  326. package/dist/server/skill-discovery.js +5 -92
  327. package/dist/server/skill-maintenance.js +1 -28
  328. package/dist/server/skill-tool.js +0 -30
  329. package/dist/server/slash-commands.js +5 -50
  330. package/dist/server/soft-cap.js +0 -42
  331. package/dist/server/startup-banner.js +0 -8
  332. package/dist/server/subagent-handoff.js +0 -11
  333. package/dist/server/subagent-helpers.js +2 -17
  334. package/dist/server/subagent-notify.js +0 -19
  335. package/dist/server/subagent-security-gate.js +0 -50
  336. package/dist/server/subagent-task.js +0 -9
  337. package/dist/server/subagent-templates-hant.js +0 -10
  338. package/dist/server/subagent-templates.js +3 -103
  339. package/dist/server/subagents.js +1 -87
  340. package/dist/server/system-screenshot-windows.js +259 -0
  341. package/dist/server/system-screenshot.js +77 -0
  342. package/dist/server/tabs.js +3 -48
  343. package/dist/server/terminals.js +559 -586
  344. package/dist/server/text-quote.js +0 -12
  345. package/dist/server/text-sniff.js +2 -52
  346. package/dist/server/themes.js +2 -41
  347. package/dist/server/tool-approval.js +0 -47
  348. package/dist/server/tool-guards.js +0 -90
  349. package/dist/server/tool-host-factories.js +1 -16
  350. package/dist/server/tool-info.js +0 -13
  351. package/dist/server/tool-manager.js +1 -229
  352. package/dist/server/tool-overrides.js +1 -46
  353. package/dist/server/tool-prompt-overrides.js +1 -30
  354. package/dist/server/tool-prompts.js +0 -14
  355. package/dist/server/tool-signature.js +0 -25
  356. package/dist/server/transcript-prepare.js +1 -19
  357. package/dist/server/tts-routes.js +58 -0
  358. package/dist/server/tts-service.js +106 -0
  359. package/dist/server/tts-system.js +160 -0
  360. package/dist/server/turn-timing.js +0 -1
  361. package/dist/server/unauthorized-page.js +0 -8
  362. package/dist/server/universal/driver-base.js +2 -31
  363. package/dist/server/universal/drivers/claude-code.js +12 -172
  364. package/dist/server/universal/drivers/codex.js +12 -35
  365. package/dist/server/universal/drivers/mock-driver.js +1 -11
  366. package/dist/server/universal/index.js +0 -3
  367. package/dist/server/universal/session-store.js +4 -21
  368. package/dist/server/universal/universal-attachments.js +2 -36
  369. package/dist/server/universal/universal-service.js +5 -24
  370. package/dist/server/universal/universal-session.js +26 -148
  371. package/dist/server/universal/universal-types.js +0 -3
  372. package/dist/server/update-check.js +6 -182
  373. package/dist/server/uploads.js +4 -43
  374. package/dist/server/virtual-tui.js +2 -27
  375. package/dist/server/vision-bridge.js +0 -27
  376. package/dist/server/wait-subscription-scan.js +13 -115
  377. package/dist/server/webui-context.js +2 -87
  378. package/dist/server/workspace-handle.js +1 -56
  379. package/dist/server/workspace-snapshot.js +7 -113
  380. package/dist/server/worktree-service.js +2 -53
  381. package/dist/server/worktree-tool.js +0 -11
  382. package/dist/server/ws-client-id.js +0 -18
  383. package/dist/server/ws-pending-queue.js +0 -7
  384. package/dist/server/ws-unknown-types.js +0 -17
  385. package/docs/README.md +24 -17
  386. package/docs/architecture-plugins.md +37 -1
  387. package/docs/device-center.md +28 -2
  388. package/docs/device-desktop.md +3 -3
  389. package/docs/group-orchestration.md +142 -0
  390. package/docs/hub-upgrade-release-testing.md +46 -0
  391. package/extensions/webui.ts +3 -74
  392. package/package.json +7 -3
  393. package/plugin-sdk/README.md +6 -0
  394. package/plugin-sdk/client-utils.mjs +0 -7
  395. package/plugin-sdk/client.d.ts +0 -1
  396. package/plugin-sdk/client.mjs +1 -31
  397. package/plugin-sdk/import-check.mjs +4 -51
  398. package/plugin-sdk/index.d.ts +120 -119
  399. package/plugin-sdk/index.mjs +0 -6
  400. package/plugin-sdk/ssh-host-trust.mjs +0 -12
  401. package/plugin-sdk/testing.d.ts +0 -1
  402. package/plugin-sdk/testing.mjs +31 -86
  403. package/plugins/catalog.json +52 -4
  404. package/plugins/superagent/README.md +110 -0
  405. package/plugins/superagent/client/entry.mjs +21 -0
  406. package/plugins/superagent/index.mjs +8 -0
  407. package/plugins/superagent/main.mjs +218 -0
  408. package/plugins/superagent/manifest.json +15 -0
  409. package/plugins/superagent/server.mjs +572 -0
  410. package/plugins/superagent/style.css +167 -0
  411. package/themes/aetheris.css +1 -31
  412. package/themes/ayu-light.css +0 -1
  413. package/themes/bases/flow-base.css +2 -83
  414. package/themes/bases/obsidian-base.css +2 -37
  415. package/themes/bases/statusbar-flat-base.css +0 -1
  416. package/themes/bases/zhujian-base.css +0 -63
  417. package/themes/bases/zhupi-base.css +0 -64
  418. package/themes/catppuccin-latte.css +0 -1
  419. package/themes/catppuccin.css +0 -1
  420. package/themes/claude-code-dark.css +0 -1
  421. package/themes/codex.css +0 -1
  422. package/themes/dark-teal.css +22 -54
  423. package/themes/everforest-light.css +0 -1
  424. package/themes/flow-cristallo.css +1 -9
  425. package/themes/flow-ink.css +1 -10
  426. package/themes/flow-light.css +1 -10
  427. package/themes/flow-obsidian.css +1 -10
  428. package/themes/flow-zurich.css +1 -10
  429. package/themes/flow.css +1 -9
  430. package/themes/geist.css +0 -1
  431. package/themes/gruvbox-light.css +0 -1
  432. package/themes/kanagawa-lotus.css +0 -1
  433. package/themes/md-preview.css +1 -2
  434. package/themes/mist.css +0 -1
  435. package/themes/nord.css +0 -1
  436. package/themes/one-dark.css +0 -1
  437. package/themes/paper.css +0 -1
  438. package/themes/rose-pine-dawn.css +0 -1
  439. package/themes/sakura.css +0 -1
  440. package/themes/solarized-light.css +0 -1
  441. package/themes/tokyo-night.css +0 -1
  442. package/themes/translucent.css +4 -35
  443. package/themes/transparent.css +4 -41
  444. package/themes/vs-code-dark.css +0 -1
  445. package/themes/wallpaper-flow.css +3 -17
  446. package/themes/wallpaper-obsidian.css +1 -4
  447. package/themes/white.css +0 -1
  448. package/web/dist/.build-assets.json +1 -1
  449. package/web/dist/assets/{BgTasksModal-BjNRIUIc.js → BgTasksModal-D-x7kA63.js} +1 -1
  450. package/web/dist/assets/CanvasStudio-CAWcs9tm.js +1579 -0
  451. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +3 -0
  452. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +1 -0
  453. package/web/dist/assets/DeviceGroups-C_fZMNeK.js +1 -0
  454. package/web/dist/assets/{Dropdown-CQtstPGv.js → Dropdown-CTgVLUbp.js} +1 -1
  455. package/web/dist/assets/FilePreview-C6W0PvaK.js +2 -0
  456. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +1 -0
  457. package/web/dist/assets/GroupConversation-C81YjF2C.js +61 -0
  458. package/web/dist/assets/GroupWorkItems-BIvZtr10.js +1 -0
  459. package/web/dist/assets/{HintTip-ChTW8o1m.js → HintTip-Da6qc566.js} +1 -1
  460. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +2 -0
  461. package/web/dist/assets/NativeCliPanel-CU1rZmyu.js +5 -0
  462. package/web/dist/assets/{PiSetupModal-BX5rUuoI.js → PiSetupModal-DZKY5Wiw.js} +1 -1
  463. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +1 -0
  464. package/web/dist/assets/{SCMPanel-DPAyY2sW.js → SCMPanel-CuEgzAlO.js} +2 -2
  465. package/web/dist/assets/SettingsModal-Cdu5h29p.js +33 -0
  466. package/web/dist/assets/TermXterm-Bt5WKAxP.js +3 -0
  467. package/web/dist/assets/TerminalPanel-BCIBV8se.js +1 -0
  468. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +1 -0
  469. package/web/dist/assets/app-globals-CZjFtI4F.js +129 -0
  470. package/web/dist/assets/canvas-client-WkhM55mR.js +1 -0
  471. package/web/dist/assets/composer-bridge-CImnjDHq.js +1 -0
  472. package/web/dist/assets/desktop-B8NZ3KW-.js +1 -0
  473. package/web/dist/assets/index-CQc3VrWa.css +1 -0
  474. package/web/dist/assets/index-D_AGu4Zv.js +404 -0
  475. package/web/dist/assets/plugin-host-uqZGpvCs.js +1 -0
  476. package/web/dist/assets/{remote-ssh-client-Dzi-eEyE.js → remote-ssh-client-Cdf-cTUe.js} +1 -1
  477. package/web/dist/assets/theme-DGL7hLUs.js +1 -0
  478. package/web/dist/index.html +11 -10
  479. package/web/dist/sw.js +15 -61
  480. package/web/public/sw.js +14 -60
  481. package/web/dist/assets/BgTasksModal-C0zuU8FE.js +0 -1
  482. package/web/dist/assets/CanvasStudio-BWvdmJ0M.js +0 -1579
  483. package/web/dist/assets/CanvasStudio-VQFjmTGq.js +0 -1579
  484. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +0 -3
  485. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +0 -3
  486. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +0 -1
  487. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +0 -1
  488. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +0 -1
  489. package/web/dist/assets/FilePreview-BMB2tNyT.js +0 -2
  490. package/web/dist/assets/FilePreview-RGFQUbJo.js +0 -2
  491. package/web/dist/assets/GlobalSearchModal-BM5wxiqU.js +0 -1
  492. package/web/dist/assets/GlobalSearchModal-DGv_WINq.js +0 -1
  493. package/web/dist/assets/GroupConversation-B7SnuXj1.js +0 -61
  494. package/web/dist/assets/GroupConversation-Dda69q-2.js +0 -61
  495. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +0 -2
  496. package/web/dist/assets/ModelConfigModal-yqeadyab.js +0 -2
  497. package/web/dist/assets/ProviderOAuthControls-DY4SCfXg.js +0 -1
  498. package/web/dist/assets/SCMPanel-C4KbQvvK.js +0 -2
  499. package/web/dist/assets/SettingsModal-DxZp6D_g.js +0 -32
  500. package/web/dist/assets/SettingsModal-WhQzaOPt.js +0 -32
  501. package/web/dist/assets/TerminalPanel-D4By_RVc.js +0 -3
  502. package/web/dist/assets/TerminalPanel-lZw8-i3j.js +0 -3
  503. package/web/dist/assets/TuiOverlayModal-C3pAVuC8.js +0 -1
  504. package/web/dist/assets/TuiOverlayModal-D7_rEXcJ.js +0 -1
  505. package/web/dist/assets/app-globals-KqOVtmp1.js +0 -123
  506. package/web/dist/assets/canvas-client-BY6ojmle.js +0 -1
  507. package/web/dist/assets/desktop-CV6KKp9R.js +0 -1
  508. package/web/dist/assets/index-BawF7ZP5.js +0 -397
  509. package/web/dist/assets/index-BoGCoq5X.js +0 -397
  510. package/web/dist/assets/index-CVW9FoY2.css +0 -1
  511. package/web/dist/assets/plugin-host-Dn8Dd6SC.js +0 -1
  512. package/web/dist/assets/theme-D_bihpdN.js +0 -1
@@ -1,21 +1,7 @@
1
- /**
2
- * agent-service-daemon — pi-web-ui 多客户端顶层连接服务与过户事务编排引擎。
3
- *
4
- * 负责:
5
- * - 多客户端会话池管理(ClientSession registry & attach/detach 连接池)
6
- * - 服务排空门禁与状态机(Quiesce / Draining state machine)
7
- * - 跨标签页会话查重与同项目并行感知(SessionOwnerInfo & ElsewhereRunning)
8
- * - 跨端手动过户事务与夭折回滚(Takeover Transactions & Rollback)
9
- * - 跨端问卷预告与答复路由(Peek & Answer Elsewhere Questions)
10
- * - 插件/调度器无头客户端隔离执行(completeForPlugins & scheduler dispatch)
11
- * - 服务端运行状态快照(serviceStatus)
12
- *
13
- * 从 agent-service.ts 抽出为独立模块。
14
- */
15
1
  import { join, resolve } from "node:path";
16
2
  import { statSync } from "node:fs";
17
3
  import { randomUUID } from "node:crypto";
18
- import { VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { VERSION, getAgentDir, ModelRuntime } from "@earendil-works/pi-coding-agent";
19
5
  import { ClientStateStore } from "./client-state.js";
20
6
  import { ClaimStore } from "./claim-store.js";
21
7
  import { isBotExecutionRegistered } from "./device-center/bot-execution.js";
@@ -35,7 +21,7 @@ export class AgentService {
35
21
  cwd;
36
22
  static isPseudoClientId = isPseudoClientId;
37
23
  sharedViewers = new Map();
38
- openSharedConversation(viewerClientId, ownerClientId, convId, send) {
24
+ openSharedConversation(viewerClientId, ownerClientId, convId, send, options = {}) {
39
25
  const viewer = this.clients.get(viewerClientId);
40
26
  const owner = this.clients.get(ownerClientId);
41
27
  const conversation = owner?.getConversation(convId);
@@ -43,11 +29,18 @@ export class AgentService {
43
29
  if (!viewer ||
44
30
  !owner ||
45
31
  !conversation ||
46
- (conversation.independent !== false && !isScheduler) ||
47
- conversation.isSubagent)
32
+ (!options.readOnly && ((conversation.independent !== false && !isScheduler) || conversation.isSubagent)))
48
33
  return false;
49
34
  this.closeSharedConversation(viewerClientId);
50
- const binding = { owner, conversation, ownerClientId, conversationId: convId, close: () => { }, send };
35
+ const binding = {
36
+ owner,
37
+ conversation,
38
+ ownerClientId,
39
+ conversationId: convId,
40
+ readOnly: options.readOnly === true,
41
+ close: () => { },
42
+ send,
43
+ };
51
44
  this.sharedViewers.set(viewerClientId, binding);
52
45
  this.subscribeSharedConversation(viewerClientId, binding);
53
46
  return true;
@@ -63,7 +56,11 @@ export class AgentService {
63
56
  state: {
64
57
  ...message.state,
65
58
  clientId: viewerClientId,
66
- sharedConversation: { owner: ownerClientId, conversationId: convId },
59
+ sharedConversation: {
60
+ owner: ownerClientId,
61
+ conversationId: convId,
62
+ ...(binding.readOnly ? { readOnly: true } : {}),
63
+ },
67
64
  },
68
65
  });
69
66
  else if (message.type === "snapshot_delta")
@@ -72,7 +69,11 @@ export class AgentService {
72
69
  state: {
73
70
  ...message.state,
74
71
  clientId: viewerClientId,
75
- sharedConversation: { owner: ownerClientId, conversationId: convId },
72
+ sharedConversation: {
73
+ owner: ownerClientId,
74
+ conversationId: convId,
75
+ ...(binding.readOnly ? { readOnly: true } : {}),
76
+ },
76
77
  },
77
78
  });
78
79
  else
@@ -113,17 +114,37 @@ export class AgentService {
113
114
  if (binding &&
114
115
  this.clients.get(binding.ownerClientId) === binding.owner &&
115
116
  binding.owner.getConversation(binding.conversationId) === binding.conversation &&
116
- (binding.conversation.independent === false || binding.ownerClientId.startsWith("scheduler:")))
117
+ (binding.readOnly || binding.conversation.independent === false || binding.ownerClientId.startsWith("scheduler:")))
117
118
  return binding;
118
119
  if (binding)
119
120
  this.closeSharedConversation(viewerClientId);
120
121
  return undefined;
121
122
  }
122
123
  dispatchSharedConversationMessage(viewerClientId, message) {
124
+ if ("ownerKind" in message &&
125
+ message.ownerKind === "client" &&
126
+ [
127
+ "terminal_create",
128
+ "terminal_attach",
129
+ "terminal_input",
130
+ "terminal_cli_paste",
131
+ "terminal_resize",
132
+ "terminal_kill",
133
+ "rename_terminal",
134
+ ].includes(message.type))
135
+ return false;
123
136
  const binding = this.sharedConversationTarget(viewerClientId);
124
137
  if (!binding)
125
138
  return false;
126
- if (["new_chat", "switch_session", "switch_conversation", "set_cwd", "resume_session"].includes(message.type)) {
139
+ if ([
140
+ "new_chat",
141
+ "new_cli_chat",
142
+ "switch_session",
143
+ "switch_conversation",
144
+ "set_cwd",
145
+ "resume_session",
146
+ "close_shared_conversation",
147
+ ].includes(message.type)) {
127
148
  this.closeSharedConversation(viewerClientId);
128
149
  return false;
129
150
  }
@@ -132,9 +153,7 @@ export class AgentService {
132
153
  try {
133
154
  send({ type: "notice", level: "error", text: String(error), textEn: String(error) });
134
155
  }
135
- catch {
136
- /* disconnected viewer */
137
- }
156
+ catch { }
138
157
  };
139
158
  const run = (action) => {
140
159
  try {
@@ -148,7 +167,24 @@ export class AgentService {
148
167
  const reject = () => run(() => {
149
168
  throw new Error(`Shared conversation operation unavailable: ${message.type}`);
150
169
  });
151
- // One workspace service per binding; close its watchers with the subscription.
170
+ if (binding.readOnly &&
171
+ ![
172
+ "get_state",
173
+ "list_files",
174
+ "read_file",
175
+ "search_files",
176
+ "complete_path",
177
+ "scm_status",
178
+ "scm_history",
179
+ "scm_filediff",
180
+ "scm_commit",
181
+ "get_compacted_messages",
182
+ "question_answer",
183
+ "tool_approval_response",
184
+ ].includes(message.type))
185
+ return reject();
186
+ if (binding.readOnly && "owner" in message && message.owner && message.owner !== binding.ownerClientId)
187
+ return reject();
152
188
  const fileBinding = binding;
153
189
  const files = () => {
154
190
  if (!fileBinding.files) {
@@ -223,6 +259,39 @@ export class AgentService {
223
259
  return run(() => files().scmQuery("commit", message.reqId, { hash: message.hash }));
224
260
  case "scm_commitmsg":
225
261
  return run(() => owner.scmGenCommitMessage(message.reqId, conv, send));
262
+ case "terminal_cli_control": {
263
+ if (message.conversationId !== conv.id ||
264
+ message.ownerKind !== "conversation" ||
265
+ conv.nativeCli?.terminalId !== message.terminalId ||
266
+ typeof message.requestId !== "string" ||
267
+ !message.requestId ||
268
+ message.requestId.length > 128 ||
269
+ /[\x00-\x1f\x7f-\x9f]/.test(message.requestId) ||
270
+ !["detach", "reconnect", "stop"].includes(message.action))
271
+ return reject();
272
+ return run(async () => {
273
+ try {
274
+ await owner.controlNativeCli(conv.id, message.terminalId, message.action);
275
+ send({
276
+ type: "terminal_cli_control_result",
277
+ requestId: message.requestId,
278
+ terminalId: message.terminalId,
279
+ conversationId: message.conversationId,
280
+ ok: true,
281
+ });
282
+ }
283
+ catch (error) {
284
+ send({
285
+ type: "terminal_cli_control_result",
286
+ requestId: message.requestId,
287
+ terminalId: message.terminalId,
288
+ conversationId: message.conversationId,
289
+ ok: false,
290
+ error: error.message,
291
+ });
292
+ }
293
+ });
294
+ }
226
295
  case "terminal_create":
227
296
  case "terminal_attach":
228
297
  case "terminal_input":
@@ -238,6 +307,8 @@ export class AgentService {
238
307
  return run(() => {
239
308
  switch (message.type) {
240
309
  case "terminal_create":
310
+ if (conv.nativeCli?.terminalId === message.terminalId)
311
+ return owner.controlNativeCli(conv.id, message.terminalId, "reconnect");
241
312
  return tm.create(message.terminalId, message.cwd, message.cols, message.rows, conv.cwd, message.title, {
242
313
  locale: message.locale,
243
314
  agentBash: message.agentBash,
@@ -289,7 +360,7 @@ export class AgentService {
289
360
  : reject();
290
361
  }
291
362
  if (message.type === "get_state") {
292
- this.openSharedConversation(viewerClientId, binding.ownerClientId, conv.id, send);
363
+ this.openSharedConversation(viewerClientId, binding.ownerClientId, conv.id, send, { readOnly: binding.readOnly });
293
364
  return true;
294
365
  }
295
366
  if (message.type === "prompt") {
@@ -358,17 +429,12 @@ export class AgentService {
358
429
  return false;
359
430
  }
360
431
  }
361
- /**
362
- * 关闭对话(支持本端自身会话,或跨端关闭群组 Bot / 共享执行 / 离线残骸 / elsewhere 会话)。
363
- */
364
432
  async dismissConversation(requesterClientId, msg) {
365
433
  const requester = this.clients.get(requesterClientId);
366
- // 1. 本客户端自己持有该会话:走当前客户端正常流程
367
434
  if (requester?.getConversation(msg.id)) {
368
435
  await requester.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
369
436
  return true;
370
437
  }
371
- // 2. 跨客户端定位持有该会话的 owner
372
438
  let ownerId = msg.owner;
373
439
  let owner = ownerId ? this.clients.get(ownerId) : undefined;
374
440
  let conv = owner?.getConversation(msg.id);
@@ -392,7 +458,6 @@ export class AgentService {
392
458
  });
393
459
  return false;
394
460
  }
395
- // 3. 针对共享执行客户端(如群组 Bot device-task-、定时任务、无头残骸)
396
461
  const isSharedExecution = isSharedExecutionClientId(ownerId);
397
462
  const isOffline = owner.sinkCount() === 0;
398
463
  if (isSharedExecution || isOffline) {
@@ -424,34 +489,22 @@ export class AgentService {
424
489
  });
425
490
  return true;
426
491
  }
427
- // 4. 普通在线客户端持有的 shared/可过户会话
428
492
  await owner.dismissConversation(conv.id, msg.withFinishedSubagents, msg.force);
429
493
  this.pokeExternalRunning(ownerId);
430
494
  return true;
431
495
  }
432
- /** 客户端 -> 最后一个浏览器断开的时刻(离线行宽限期起点;重连/认领即删)。 */
433
496
  offlineSince = new Map();
434
- /** 客户端 -> 离线行宽限期到期定时器(到期后让其他客户端重推,行消失)。 */
435
497
  offlineTimers = new Map();
436
- /** index.ts 注入:SDK 工具执行事件的插件转发钩子,attach 时拷贝到每个新会话。 */
437
498
  onToolEvent = undefined;
438
- /** index.ts 注入:bash/read 插件拦截钩子,attach 时拷贝到每个新会话。 */
439
499
  toolGuard = undefined;
440
- /** index.ts 注入:运行轨迹事件的插件转发钩子,attach 时拷贝到每个新会话。 */
441
500
  onRunEvent = undefined;
442
- /** index.ts 注入:对话切换通知钩子,attach 时拷贝到每个新会话。 */
501
+ onNotificationEvent = undefined;
443
502
  onConversationChanged = undefined;
444
- /** index.ts 注入:模型切换成功通知钩子(#542),attach 时拷贝到每个新会话。 */
445
503
  onClientModelChanged = undefined;
446
- /** index.ts 注入:读取插件当前注册的 AI 工具(attach 时拷贝到每个新会话)。 */
447
504
  pluginToolsProvider = undefined;
448
- /** index.ts 注入:读取插件当前注册的斜杠命令(attach 时拷贝到每个新会话)。 */
449
505
  pluginCommandsProvider = undefined;
450
- /** index.ts 注入:读取插件注册的常驻后台任务(并入 bg_servers 面板)。 */
451
506
  pluginBgTasksProvider = undefined;
452
- /** index.ts 注入:停止插件任务(kill_background_server with taskId)。 */
453
507
  pluginStopBgTask = undefined;
454
- /** index.ts 注入:内置调度存储(attach 时拷贝到每个新会话,供 schedule_* 工具)。 */
455
508
  schedulerStore = undefined;
456
509
  clients = new Map();
457
510
  sharedInteractionSinks = new WeakMap();
@@ -470,51 +523,64 @@ export class AgentService {
470
523
  }
471
524
  return { type: "global_interactions", questions, approvals };
472
525
  }
473
- /** 全局认领表(跨浏览器标签页共享;<dataDir>/claims.json,best-effort 持久化)。 */
474
526
  claimStore;
475
- /** Quiesce (draining) state — the service refuses NEW work (prompts, forks,
476
- * session resumes, new clients) so a deploy/upgrade/backup can stop cleanly
477
- * once existing runs finish. Controlled via the local control socket:
478
- * `pi-web-ui server quiesce|unquiesce`. */
479
527
  quiesced = false;
480
528
  quiescedAt = 0;
481
- /** Attached browser sockets (reported by index.ts on open/close) — the
482
- * control socket reports real sockets, not cached client-session objects. */
483
529
  socketCount = 0;
484
530
  pending = new Map();
485
531
  pendingDetaches = new Map();
486
532
  stateStore;
487
- /** Set by index.ts: called when /pi-web-ui:quit is invoked. */
488
533
  onQuit = undefined;
489
- /** 任意客户端成功切换工作区后触发(新绝对路径 + 该项目的额外工作区根)。
490
- * index.ts 接到 PluginManager.notifyCwd / notifyWorkspaceRoots,让插件宿主的
491
- * host.cwd 实时跟随当前项目、受支持路径范围跟着多根变。 */
492
534
  onClientCwdChanged = undefined;
493
535
  constructor(cwd, stateFile) {
494
536
  this.cwd = cwd;
495
537
  this.stateStore = typeof stateFile === "string" ? new ClientStateStore(stateFile) : stateFile;
496
538
  this.claimStore = new ClaimStore(join(this.stateStore.dataDir, "claims.json"));
497
539
  }
498
- /** Get or create the session for a client, racing attach calls safely. */
499
- /** True while the service is draining — new work is refused. */
540
+ groupRouterModelRuntime;
541
+ async getGroupRouterModelRuntime(signal) {
542
+ signal.throwIfAborted();
543
+ if (!this.groupRouterModelRuntime) {
544
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
545
+ this.groupRouterModelRuntime = ModelRuntime.create({
546
+ authPath: join(agentDir, "auth.json"),
547
+ modelsPath: join(agentDir, "models.json"),
548
+ }).catch((error) => {
549
+ this.groupRouterModelRuntime = undefined;
550
+ throw error;
551
+ });
552
+ }
553
+ const runtime = await this.groupRouterModelRuntime;
554
+ signal.throwIfAborted();
555
+ return runtime;
556
+ }
557
+ async listGroupRouterModels(signal) {
558
+ signal.throwIfAborted();
559
+ const runtime = await this.getGroupRouterModelRuntime(signal);
560
+ await runtime.refresh({ allowNetwork: false, signal });
561
+ const models = await runtime.getAvailable(undefined, { signal });
562
+ return models.map((model) => ({
563
+ id: `${model.provider}/${model.id}`,
564
+ name: model.name,
565
+ provider: model.provider,
566
+ reasoning: model.reasoning,
567
+ vision: model.input?.includes("image") ?? false,
568
+ }));
569
+ }
500
570
  isQuiesced() {
501
571
  return this.quiesced;
502
572
  }
503
- /** Enter quiesce: stop admitting new work. Existing runs keep going. */
504
573
  quiesce() {
505
574
  this.quiesced = true;
506
575
  this.quiescedAt = Date.now();
507
576
  }
508
- /** Leave quiesce: admit new work again. */
509
577
  unquiesce() {
510
578
  this.quiesced = false;
511
579
  this.quiescedAt = 0;
512
580
  }
513
- /** Snapshot for the control socket / status command. */
514
581
  quiesceInfo() {
515
582
  return this.quiesced ? { quiesced: true, quiescedSince: this.quiescedAt } : { quiesced: false };
516
583
  }
517
- /** issue #145:除请求方外是否有客户端正在跑(扫目录查重前置的无 I/O 判断)。 */
518
584
  hasStreamingElsewhere(excludeClientId) {
519
585
  for (const [clientId, cs] of this.clients) {
520
586
  if (clientId === excludeClientId)
@@ -523,13 +589,10 @@ export class AgentService {
523
589
  if (cs.activeConversations() > 0)
524
590
  return true;
525
591
  }
526
- catch {
527
- // 单客户端坏了不影响判断
528
- }
592
+ catch { }
529
593
  }
530
594
  return false;
531
595
  }
532
- /** Dispose confirmed-stopped Bot owners before reopening their authorized transcript. */
533
596
  async prepareBotSessionResume(targetPath, excludeClientId) {
534
597
  for (const [ownerId, owner] of this.clients) {
535
598
  if (ownerId === excludeClientId || !ownerId.startsWith("device-task-") || isBotExecutionRegistered(ownerId))
@@ -537,13 +600,10 @@ export class AgentService {
537
600
  const conv = owner.findConversationBySessionFile(targetPath);
538
601
  if (!conv || owner.conversationStreaming(conv))
539
602
  continue;
540
- // Registration is released only after confirmed stop. Retire the old
541
- // runtime before reopening, even if its socket close is still in flight.
542
603
  this.clients.delete(ownerId);
543
604
  await owner.dispose();
544
605
  }
545
606
  }
546
- /** issue #145:打开转录前查重,禁止同一文件出现第二个 writer。 */
547
607
  findSessionOwner(targetPath, excludeClientId) {
548
608
  for (const [clientId, cs] of this.clients) {
549
609
  if (clientId === excludeClientId)
@@ -562,9 +622,6 @@ export class AgentService {
562
622
  }
563
623
  return null;
564
624
  }
565
- /** 插件 steer 跨客户端兜底:除请求方外逐个问其他客户端的 conversations,
566
- * 找到持有方由其执行 steer(只调 steerOwnConversation,不碰钩子,无递归);
567
- * 都找不到回 undefined,调用方回未知对话。单客户端异常跳过,不影响其他。 */
568
625
  async steerElsewhere(excludeClientId, id, text) {
569
626
  for (const [clientId, cs] of this.clients) {
570
627
  if (clientId === excludeClientId)
@@ -574,21 +631,10 @@ export class AgentService {
574
631
  if (r)
575
632
  return r;
576
633
  }
577
- catch {
578
- // 单客户端坏了继续找下一个
579
- }
634
+ catch { }
580
635
  }
581
636
  return undefined;
582
637
  }
583
- /** issue #193:定时任务唤醒发起对话。逐个客户端找持有方,用 steer 语义投递
584
- * (运行时插队、未跑时普通投递,不切用户当前对话);都找不到回 ok:false,
585
- * 调用方(index.ts executor)回落视口/无头执行。quiesced 时直接拒绝。
586
- * issue #226:成功时带回持有方 clientId(插件绑定网页会话时原样回执)。
587
- * issue #231:opts.sessionFile 是跨压缩/重启的稳定键 —— 优先按它认同一会话
588
- * (内存对话 id 重启即失效,压缩后同文件对话可能已换新 id,成功时带回**实际**
589
- * 投递的 conversationId + sessionFile,调用方据此重绑定任务);id 相位带 cwd
590
- * 护栏(各客户端计数器都从 c1 开始,不校验会把报告投进无关项目)。压缩进行中
591
- * 的持有方回 busy:true(调用方另寻视口兄弟,而不是当成“不在”静默转无头)。 */
592
638
  async wakeConversation(id, text, opts) {
593
639
  const wantFile = String(opts?.sessionFile ?? "").trim();
594
640
  const wantCwd = String(opts?.cwd ?? "").trim();
@@ -608,12 +654,8 @@ export class AgentService {
608
654
  try {
609
655
  cs.flushSnapshot();
610
656
  }
611
- catch {
612
- // 推送失败不影响已投递的唤醒
613
- }
657
+ catch { }
614
658
  };
615
- // 相位一:落盘会话文件(稳定键)。同文件可能在多处打开,取最近活跃者;
616
- // 全部忙(压缩中)则报 busy,调用方去找视口兄弟。
617
659
  if (wantFile) {
618
660
  const hits = [];
619
661
  for (const [clientId, cs] of this.clients) {
@@ -622,9 +664,7 @@ export class AgentService {
622
664
  if (conv)
623
665
  hits.push({ cs, clientId, conv });
624
666
  }
625
- catch {
626
- // 单客户端坏了继续找下一个
627
- }
667
+ catch { }
628
668
  }
629
669
  hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
630
670
  let busyError;
@@ -637,21 +677,15 @@ export class AgentService {
637
677
  }
638
678
  if (r.busy)
639
679
  busyError = r.error;
640
- // 非忙失败(投递异常)试下一个同文件持有方
641
- }
642
- catch {
643
- // 单客户端坏了继续找下一个
644
680
  }
681
+ catch { }
645
682
  }
646
683
  if (hits.length > 0) {
647
684
  if (busyError)
648
685
  return { ok: false, busy: true, error: busyError };
649
- // 同文件持有方都在但都投递失败 —— id 相位大概率指向同一批,无需再试
650
686
  return { ok: false, error: "目标对话投递失败(持有方异常)" };
651
687
  }
652
- // 无同文件持有方 —— 老任务只有 id,继续相位二
653
688
  }
654
- // 相位二:内存对话 id(易失键,必须配 cwd 护栏防跨项目串台)。
655
689
  if (id) {
656
690
  const hits = [];
657
691
  for (const [clientId, cs] of this.clients) {
@@ -663,9 +697,7 @@ export class AgentService {
663
697
  if (conv)
664
698
  hits.push({ cs, clientId, conv });
665
699
  }
666
- catch {
667
- // 单客户端坏了继续找下一个
668
- }
700
+ catch { }
669
701
  }
670
702
  hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
671
703
  let busyError;
@@ -679,9 +711,7 @@ export class AgentService {
679
711
  if (r.busy)
680
712
  busyError = r.error;
681
713
  }
682
- catch {
683
- // 单客户端坏了继续找下一个
684
- }
714
+ catch { }
685
715
  }
686
716
  if (busyError)
687
717
  return { ok: false, busy: true, error: busyError };
@@ -705,10 +735,6 @@ export class AgentService {
705
735
  }
706
736
  return false;
707
737
  }
708
- /**
709
- * 全局问卷直决:直接通过全局随机 UUID 定位持有问卷的会话并 resolve。
710
- * 无需强依赖临时变更的 ownerId,跨页、重连认领与代理穿透均可直接命中。
711
- */
712
738
  resolveGlobalQuestion(id, answers, cancelled, cancelReason) {
713
739
  for (const client of this.clients.values()) {
714
740
  if (client.resolveQuestion(id, answers, cancelled, cancelReason)) {
@@ -739,9 +765,6 @@ export class AgentService {
739
765
  }
740
766
  return false;
741
767
  }
742
- /** issue #231:同项目视口回退 —— 原绑定对话不在时,把唤醒投给该项目最近活跃
743
- * 的对话(用户当前正看着的面),而不是静默转无头。excludeIds 跳过已知忙对话;
744
- * 候选全部忙回 busy:true;无候选回 ok:false。成功带回实际投递方(调用方重绑定)。 */
745
768
  async wakeViewportInCwd(cwd, text, excludeIds) {
746
769
  const want = String(cwd ?? "").trim();
747
770
  if (!want || !text.trim())
@@ -755,9 +778,7 @@ export class AgentService {
755
778
  if (conv)
756
779
  cands.push({ cs, clientId, conv });
757
780
  }
758
- catch {
759
- // 单客户端坏了继续找下一个
760
- }
781
+ catch { }
761
782
  }
762
783
  cands.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
763
784
  if (cands.length === 0)
@@ -770,9 +791,7 @@ export class AgentService {
770
791
  try {
771
792
  c.cs.flushSnapshot();
772
793
  }
773
- catch {
774
- // 推送失败不影响已投递的唤醒
775
- }
794
+ catch { }
776
795
  let f = "";
777
796
  try {
778
797
  f = String(c.conv.session.sessionFile ?? "");
@@ -785,15 +804,12 @@ export class AgentService {
785
804
  if (r.busy)
786
805
  busyError = r.error;
787
806
  }
788
- catch {
789
- // 单客户端坏了继续找下一个
790
- }
807
+ catch { }
791
808
  }
792
809
  if (busyError)
793
810
  return { ok: false, busy: true, error: busyError };
794
811
  return { ok: false, error: "同项目对话投递失败" };
795
812
  }
796
- /** issue #145:别处在某 cwd 下正在跑的对话(同项目并行感知用,不含请求方)。 */
797
813
  listProjectRunners(cwd, excludeClientId) {
798
814
  const out = [];
799
815
  for (const [clientId, cs] of this.clients) {
@@ -804,10 +820,6 @@ export class AgentService {
804
820
  }
805
821
  return out;
806
822
  }
807
- /** 按 SDK 会话(runtime 身份)找它当前归属的客户端会话与对话 id(过户后归属会变):
808
- * 桥接工具(问卷 / 页面)在调用瞬间用它投递,见 ClientSession.bridgeTarget。
809
- * 一条对话任一时刻只属于一个会话(过户先摘后插),扫一遍即可 —— 问卷/截图都是
810
- * 低频调用,不值得为此再维护一张全局索引。 */
811
823
  findConversationHome(sdkSession) {
812
824
  for (const cs of this.clients.values()) {
813
825
  try {
@@ -815,16 +827,12 @@ export class AgentService {
815
827
  if (convId)
816
828
  return { session: cs, convId };
817
829
  }
818
- catch {
819
- // 单客户端坏了不影响解析
820
- }
830
+ catch { }
821
831
  }
822
832
  return undefined;
823
833
  }
824
- /** Stable execution addresses resolve exactly; legacy display ids must be globally unique. */
825
834
  findSubagentOwner(convId) {
826
835
  // Local cN ids are not global addresses. Never let a transfer alias or
827
- // insertion order choose between clients owning the same display id.
828
836
  const matches = [];
829
837
  for (const cs of this.clients.values()) {
830
838
  const current = cs.resolveExecutionAddress(convId);
@@ -833,11 +841,7 @@ export class AgentService {
833
841
  }
834
842
  return matches.length === 1 ? matches[0] : undefined;
835
843
  }
836
- /** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
837
- * owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
838
844
  listExternalRunning(excludeClientId) {
839
- // 1) 收集当前请求客户端自己持有的对话(按 sessionFile 与 cwd+title 双维度),
840
- // 本机已经持有的对话绝不作为 elsewhere 行推给本机(避免左栏同一对话既是“当前”又是“另一处”)。
841
845
  const currentCs = this.clients.get(excludeClientId);
842
846
  const localFiles = new Set();
843
847
  const localCwdTitles = new Set();
@@ -848,34 +852,24 @@ export class AgentService {
848
852
  localCwdTitles.add(`${b.cwd}\0${b.title}`);
849
853
  }
850
854
  }
851
- // 2) 遍历其他客户端,收集条目并按 sessionFile / cwd+title 去重。
852
- // 若多个客户端持有同会话(如断连竞争、多标签残留),保留正在运行(streaming)或有问卷的更活跃者,
853
- // 杜绝“一堆同一个对话的另一处”在左栏堆积。
854
855
  const dedupMap = new Map();
855
856
  const now = Date.now();
856
857
  for (const [clientId, cs] of this.clients) {
857
858
  if (clientId === excludeClientId)
858
859
  continue;
859
- // 伪客户端(scheduler:/plugin:)不走浏览器,sinkCount 永远为 0,保留。
860
860
  const isPseudo = isSharedExecutionClientId(clientId);
861
- // 无浏览器连接的残骸(sinkCount=0 = 断连留存):宽限期内仍下发(标
862
- // ownerOffline,可接管),过期或 TTL=0 时按 issue #291 不入列表。
863
861
  const offline = !isPseudo && cs.sinkCount() === 0;
864
862
  if (offline && OFFLINE_ROW_TTL_MS <= 0)
865
863
  continue;
866
864
  const offlineSince = offline ? (this.offlineSince.get(clientId) ?? 0) : 0;
867
865
  for (const r of cs.streamingSummariesAll()) {
868
- // activity 只服务宽限期判定,不进 wire(ElsewhereRunning 无此字段)。
869
866
  const { activity, ...rest } = r;
870
867
  if (offline && !rest.isStreaming) {
871
- // 宽限期从「断开时刻」与「最后一次活动」里取较晚者:跑动的后台任务
872
- // 每有事件就续期,不会跑到一半从别人列表里消失。
873
868
  const latest = Math.max(offlineSince, activity || 0);
874
869
  if (latest > 0 && now - latest > OFFLINE_ROW_TTL_MS)
875
870
  continue;
876
871
  }
877
872
  const normFile = rest.sessionFile ? resolve(rest.sessionFile) : undefined;
878
- // 本机已持有该会话文件,或本机在同项目下已有同名可见对话:排除
879
873
  if (normFile && localFiles.has(normFile))
880
874
  continue;
881
875
  if (rest.independent !== false && localCwdTitles.has(`${rest.cwd}\0${rest.title}`))
@@ -886,7 +880,6 @@ export class AgentService {
886
880
  ...(isPseudo ? { pseudo: true } : {}),
887
881
  ...(offline ? { ownerOffline: true } : {}),
888
882
  };
889
- // 跨客户端去重键:有文件按规范路径去重,无文件按 cwd + title 去重
890
883
  const dedupKey = normFile
891
884
  ? `file:${normFile}`
892
885
  : rest.independent === false
@@ -894,7 +887,6 @@ export class AgentService {
894
887
  : `title:${rest.cwd}\0${rest.title}`;
895
888
  const existing = dedupMap.get(dedupKey);
896
889
  if (existing) {
897
- // 优先保留 streaming,其次保留 hasQuestion,最后才轮到离线行让位在线行
898
890
  const preferNew = (!existing.isStreaming && entry.isStreaming) ||
899
891
  (!existing.hasQuestion && entry.hasQuestion) ||
900
892
  (Boolean(existing.ownerOffline) && !entry.ownerOffline);
@@ -908,11 +900,6 @@ export class AgentService {
908
900
  }
909
901
  return [...dedupMap.values()];
910
902
  }
911
- /** 离线行宽限期到期 → 让其他客户端重推一次(行随之从列表消失,回到 #291 口径)。
912
- *
913
- * 到期时刻取「断开时刻」与「最后一次活动」的较晚者:断开后 run 还在跑的后台任务
914
- * 每有流式变化都会重排(见 pokeExternalRunning),跑完那一刻的推送把宽限期从新起算。
915
- * 到期回调只推送、**不再重排**,否则「行已过期」会被无限排成 1s 轮询。 */
916
903
  armOfflineRowExpiry(clientId, cs) {
917
904
  if (OFFLINE_ROW_TTL_MS <= 0)
918
905
  return;
@@ -930,7 +917,6 @@ export class AgentService {
930
917
  const delay = Math.max(1_000, since + OFFLINE_ROW_TTL_MS - Date.now() + 1_000);
931
918
  const timer = setTimeout(() => {
932
919
  this.offlineTimers.delete(clientId);
933
- // 期间重连/被认领/被回收都算作废:只推真实还存在的离线残骸。
934
920
  if (this.clients.get(clientId) === cs && !AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
935
921
  this.notifyExternalRunning(clientId);
936
922
  }
@@ -938,7 +924,6 @@ export class AgentService {
938
924
  timer.unref?.();
939
925
  this.offlineTimers.set(clientId, timer);
940
926
  }
941
- /** 又有浏览器连上(或残骸被认领/回收):离线行状态作废,别的页面按在线行重推。 */
942
927
  clearOfflineRows(clientId) {
943
928
  const had = this.offlineSince.delete(clientId);
944
929
  const timer = this.offlineTimers.get(clientId);
@@ -949,35 +934,23 @@ export class AgentService {
949
934
  if (had)
950
935
  this.pokeExternalRunning(clientId);
951
936
  }
952
- /** issue #291:删除定时任务后回收对应伪客户端,避免残留在 elsewhere 列表。 */
953
937
  releaseSchedulerClient(taskId) {
954
938
  const safe = String(taskId ?? "").replace(/[^A-Za-z0-9_-]/g, "") || "task";
955
939
  const clientId = `scheduler:${safe}`;
956
940
  const cs = this.clients.get(clientId);
957
941
  if (!cs)
958
942
  return;
959
- // 伪客户端常驻一个 noop sink(chatFromScheduler 的 attach),所以不能按
960
- // sinkCount 判断「有没有浏览器」—— 它永远为 1。这里就是它的回收点。
961
943
  this.clients.delete(clientId);
962
- // 先摘出 map 再异步 dispose:只删 map 的话,对话的 runtime/终端/看门狗
963
- // 计时器全都留在内存里(泄漏),转录还挂着活 writer(同文件双写者风险)。
964
- void cs.dispose().catch(() => {
965
- // 回收失败不拦主流程:尽力而为,进程退出时 OS 兜底
966
- });
967
- // 通知其他客户端刷新 elsewhere 列表。
944
+ void cs.dispose().catch(() => { });
968
945
  this.pokeExternalRunning(clientId);
969
946
  }
970
- /** issue #145: 某客户端流式集合变化 → 其他客户端重推 conversations。 */
971
947
  pokeExternalRunning(excludeClientId) {
972
- // 离线残骸刚有状态变化(run 跑完 / 又有事件):离线行宽限期重新起算,
973
- // 定时器顺延到「最后一次活动 + TTL」——否则任务跑完后再没人推它。
974
948
  const offlineCs = this.clients.get(excludeClientId);
975
949
  if (offlineCs && !AgentService.isPseudoClientId(excludeClientId) && offlineCs.sinkCount() === 0) {
976
950
  this.armOfflineRowExpiry(excludeClientId, offlineCs);
977
951
  }
978
952
  this.notifyExternalRunning(excludeClientId);
979
953
  }
980
- /** 只让其他客户端重推一次(不碰离线宽限期定时器)。 */
981
954
  notifyExternalRunning(excludeClientId) {
982
955
  for (const [clientId, cs] of this.clients) {
983
956
  if (clientId === excludeClientId)
@@ -985,57 +958,42 @@ export class AgentService {
985
958
  try {
986
959
  cs.refreshExternalRunning();
987
960
  }
988
- catch {
989
- // 单客户端坏了不影响其他
990
- }
961
+ catch { }
991
962
  }
992
963
  }
993
- /** issue #145:向除请求方外的所有客户端发一条 notice(并行通告用)。 */
994
964
  notifyClientsExcept(excludeClientId, msg) {
995
965
  for (const [clientId, cs] of this.clients) {
996
966
  if (clientId === excludeClientId)
997
967
  continue;
998
968
  try {
999
- // 经 ClientSession.emit 才能进该客户端的 sink 组播;用公开发送面。
1000
969
  cs.sendNotice(msg);
1001
970
  }
1002
- catch {
1003
- // 单客户端坏了不影响其他
1004
- }
971
+ catch { }
1005
972
  }
1006
973
  }
1007
- /** Aggregate across every client session: conversations with in-flight runs. */
1008
974
  activeConversations() {
1009
975
  let n = 0;
1010
976
  for (const cs of this.clients.values())
1011
977
  n += cs.activeConversations();
1012
978
  return n;
1013
979
  }
1014
- /** Aggregate across every client session: messages queued in the SDK. */
1015
980
  pendingMessages() {
1016
981
  let n = 0;
1017
982
  for (const cs of this.clients.values())
1018
983
  n += cs.pendingMessages();
1019
984
  return n;
1020
985
  }
1021
- /** 插件用:全客户端最近活跃对话的快照(#542:按 clientId 取某个标签页正在看的
1022
- * 对话;缺省回落「最近活跃的**非子代理**会话」——子代理跑得再勤也不会把用户
1023
- * 正在看的对话挤出快照)。clientId 不认识/该客户端暂无对话时同样走回落。 */
1024
986
  readConversationForPlugins(opts) {
1025
987
  const want = (opts?.clientId ?? "").trim();
1026
988
  if (want) {
1027
989
  const cs = this.clients.get(want);
1028
990
  if (cs) {
1029
991
  try {
1030
- // 显式客户端:返回它**真正在看**的对话(含子代理对话——那是事实,
1031
- // 快照带 isSubagent 由插件自己判)。
1032
992
  const s = cs.readConversationForPlugins({ preferActive: true, includeSubagents: true });
1033
993
  if (s)
1034
994
  return s;
1035
995
  }
1036
- catch {
1037
- /* 单客户端坏了不影响回落 */
1038
- }
996
+ catch { }
1039
997
  }
1040
998
  }
1041
999
  const snaps = [];
@@ -1043,23 +1001,10 @@ export class AgentService {
1043
1001
  try {
1044
1002
  snaps.push(cs.readConversationForPlugins());
1045
1003
  }
1046
- catch {
1047
- /* 单客户端坏了不影响其他 */
1048
- }
1004
+ catch { }
1049
1005
  }
1050
1006
  return pickLatestClientSnapshot(snaps);
1051
1007
  }
1052
- /** 插件无头调用(host.chat 的落地):外部通道(微信等)把文本投给 agent。
1053
- * 每个 (pluginId, accountId) 独立伪客户端——复用 attach 完整链路
1054
- * (会话恢复/持久化/工具注入/快照),无浏览器也能跑;sink 是空函数,
1055
- * 快照/notice 发了即丢,不攒内存。fire-and-forget:prompt 投递即返回,
1056
- * 运行结果经 onRunEvent(run_end) 按 conversationId 关联。
1057
- * v1 语义:与该服务 cwd 下最近会话共享(单用户视角连续);peer 名由插件
1058
- * 拼进文本前缀,per-peer 会话隔离以后再加。
1059
- * issue #226:对齐定时任务的四件套——conversationId 命中时走 steer 语义
1060
- * 投递(网页端实时可见,miss 则回落无头);cwd 显式 pin 住(不存在/系统
1061
- * 目录即拒绝,不默默跑错目录);model/thinkingLevel 投递前应用(失败即
1062
- * 拒绝,不回落,避免账单/效果与预期不符)。 */
1063
1008
  async chatFromPlugin(pluginId, req) {
1064
1009
  const safe = String(pluginId ?? "plugin").replace(/[^A-Za-z0-9_-]/g, "") || "plugin";
1065
1010
  const acct = String(req?.accountId ?? "default").replace(/[^A-Za-z0-9_-]/g, "") || "default";
@@ -1070,16 +1015,9 @@ export class AgentService {
1070
1015
  throw new Error("chatFromPlugin: text 为空");
1071
1016
  if (this.quiesced)
1072
1017
  throw new QuiesceRejectedError("插件无头调用被拒绝,请等服务器恢复后重试");
1073
- // 本轮运行的稳定标识:随该轮所有 run 事件下发。为何需要:过户会把对话搬到
1074
- // 别的客户端会话(clientId 变),目标会话已有同名 id 时还会就地改名
1075
- // (conversationId 变)——两个键全失效,通道插件靠它认领自己的回包。
1076
1018
  const runId = `pr-${randomUUID()}`;
1077
- // 1. 绑定已有会话:steer 语义投递,网页端实时可见(微信当远程遥控器用)。
1078
- // miss/已回收时不抛错,回落无头伪客户端(浏览器关着时微信照常可用)。
1079
1019
  const target = String(req?.conversationId ?? "").trim();
1080
1020
  if (target) {
1081
- // Conversation ids are local to a client. Prefer this channel's own
1082
- // client; otherwise require an unambiguous target instead of guessing.
1083
1021
  const own = this.clients.get(clientId);
1084
1022
  const ownConv = own?.getConversation(target);
1085
1023
  const hits = [];
@@ -1099,8 +1037,6 @@ export class AgentService {
1099
1037
  if (req.cwd && resolve(req.cwd) !== resolve(conv.cwd))
1100
1038
  throw new Error("chatFromPlugin: bound conversation cwd differs; start a new channel conversation");
1101
1039
  if (req.model || req.thinkingLevel) {
1102
- // Apply overrides only when the captured conversation is active;
1103
- // these APIs address the owner's active conversation.
1104
1040
  if (owner.readConversationForPlugins()?.conversationId !== conv.id)
1105
1041
  throw new Error("chatFromPlugin: cannot change settings of an inactive bound conversation");
1106
1042
  if (req.model)
@@ -1115,7 +1051,6 @@ export class AgentService {
1115
1051
  return { conversationId: conv.id, clientId: ownerId, sessionId: conv.session.sessionId, runId };
1116
1052
  }
1117
1053
  }
1118
- // 2. 工作空间:不传回落伪客户端当前目录;传了必须存在且非系统目录。
1119
1054
  const cwdReq = String(req?.cwd ?? "").trim();
1120
1055
  let cwdAbs = "";
1121
1056
  if (cwdReq) {
@@ -1151,20 +1086,16 @@ export class AgentService {
1151
1086
  throw new Error(`chatFromPlugin: 切换思考强度失败(${thinking}):${err.message}`);
1152
1087
  }
1153
1088
  }
1154
- // 打运行 token(没真跑起来就不认领,不会污染用户自己下一轮的事件归属)。
1155
1089
  let stampedId = "";
1156
1090
  try {
1157
1091
  stampedId = cs.markPluginRun(runId);
1158
1092
  }
1159
- catch {
1160
- /* 打标尽力而为 */
1161
- }
1093
+ catch { }
1162
1094
  const conversationId = stampedId || (cs.readConversationForPlugins()?.conversationId ?? "");
1163
1095
  const conv = cs.getConversation(conversationId);
1164
1096
  void cs.prompt(text, attachments, false, conv).catch((err) => console.error("[plugin chat] prompt failed", err));
1165
1097
  return { conversationId, clientId, sessionId: conv?.session.sessionId, runId };
1166
1098
  }
1167
- /** Abort by the stable plugin run token, including after conversation takeover. */
1168
1099
  async abortPluginRun(runId) {
1169
1100
  for (const owner of this.clients.values()) {
1170
1101
  if (owner.findPluginRun(runId))
@@ -1172,13 +1103,6 @@ export class AgentService {
1172
1103
  }
1173
1104
  return { ok: false, error: "Plugin run is no longer active" };
1174
1105
  }
1175
- /** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
1176
- * 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
1177
- * cwd 按任务配置 pin 住(不存在即失败,不默默跑错目录);可选模型/思考强度
1178
- * 在投递前应用(失败即返回错误,不回落,避免账单/效果与预期不符)。
1179
- * fire-and-forget 投递后等待运行结束(最长 10 分钟轮询),回填真实 outcome
1180
- * (成功/失败/耗时/会话 id)供历史记录与通知使用;超时按失败记录(运行本身
1181
- * 不中止,继续在后台跑完)。 */
1182
1106
  async chatFromScheduler(task) {
1183
1107
  const safe = String(task.id ?? "task").replace(/[^A-Za-z0-9_-]/g, "") || "task";
1184
1108
  const clientId = `scheduler:${safe}`;
@@ -1233,7 +1157,6 @@ export class AgentService {
1233
1157
  void cs.prompt(`[定时任务] ${text}`).catch((err) => {
1234
1158
  promptError = String(err?.message ?? err);
1235
1159
  });
1236
- // 等待运行结束:每 2s 轮询,最长 10 分钟。超时按失败记录并中止运行(避免后台成为僵尸任务)。
1237
1160
  const deadline = Date.now() + 10 * 60 * 1000;
1238
1161
  for (;;) {
1239
1162
  await new Promise((r) => setTimeout(r, 2000));
@@ -1268,9 +1191,7 @@ export class AgentService {
1268
1191
  try {
1269
1192
  await cs.abort();
1270
1193
  }
1271
- catch {
1272
- /* best-effort */
1273
- }
1194
+ catch { }
1274
1195
  return {
1275
1196
  ok: false,
1276
1197
  conversationId: conversationId || undefined,
@@ -1283,9 +1204,6 @@ export class AgentService {
1283
1204
  return { ok: false, error: err.message };
1284
1205
  }
1285
1206
  }
1286
- /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
1287
- * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
1288
- * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
1289
1207
  async completeForPlugins(pluginId, req) {
1290
1208
  try {
1291
1209
  if (this.quiesced)
@@ -1310,14 +1228,12 @@ export class AgentService {
1310
1228
  return { ok: false, error: err.message };
1311
1229
  }
1312
1230
  }
1313
- /** index.ts calls this when a browser socket opens/closes. */
1314
1231
  noteSocketOpen() {
1315
1232
  this.socketCount += 1;
1316
1233
  }
1317
1234
  noteSocketClose() {
1318
1235
  this.socketCount = Math.max(0, this.socketCount - 1);
1319
1236
  }
1320
- /** Full status for the control socket / `server status` command. */
1321
1237
  serviceStatus() {
1322
1238
  return {
1323
1239
  pid: process.pid,
@@ -1330,13 +1246,6 @@ export class AgentService {
1330
1246
  service: toServiceInfo(launchOrigin()),
1331
1247
  };
1332
1248
  }
1333
- // (原 private static isPseudoClientId 已抽到模块级导出并挂为 static 属性)
1334
- /**
1335
- * 浏览器重启认领:给 fresh clientId 找一个可接管的断开残留会话(返回旧 id)。
1336
- * 有别的在线浏览器时返回 null(issue #10 隔离优先)。
1337
- * 全同步:attach 里的认领段不含 await,并发的新标签后到者看到 sinkCount>0,
1338
- * 不会抢走同一个残留。
1339
- */
1340
1249
  findAdoptableOrphan(excludeClientId) {
1341
1250
  const cands = [];
1342
1251
  for (const [id, cs] of this.clients) {
@@ -1381,12 +1290,6 @@ export class AgentService {
1381
1290
  const cs = this.clients.get(picked);
1382
1291
  return cs ? { oldId: picked, cs } : null;
1383
1292
  }
1384
- /**
1385
- * 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表 / 跨端 steer)。
1386
- * attach 尾部与认领分支共用 —— 认领换了 map 键,必须在首帧推送(attachSink)
1387
- * 前就按新 id 重接,否则 self-exclusion 失效:把自己当成“另一处”(elsewhere
1388
- * 误报 + prompt/switch 自拦)。尾部会再调一次,幂等。
1389
- */
1390
1293
  wireClient(cs, clientId) {
1391
1294
  if (isSharedExecutionClientId(clientId) && !this.sharedInteractionSinks.has(cs)) {
1392
1295
  const relay = (msg) => {
@@ -1415,7 +1318,6 @@ export class AgentService {
1415
1318
  cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
1416
1319
  cs.getClaimStore = () => this.claimStore;
1417
1320
  cs.findConversationHome = (sdkSession) => this.findConversationHome(sdkSession);
1418
- // B20:过户后 subagent 工具族的跨会话解析(旧 host 闭包搬不动,按 id 现查持有方)。
1419
1321
  cs.findSubagentOwner = (convId) => this.findSubagentOwner(convId);
1420
1322
  cs.allSubagentSessions = () => [...this.clients.values()];
1421
1323
  cs.listExternalRunning = () => this.listExternalRunning(clientId);
@@ -1424,12 +1326,6 @@ export class AgentService {
1424
1326
  cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
1425
1327
  cs.schedulerStore = this.schedulerStore;
1426
1328
  }
1427
- /**
1428
- * 手动过户(take_over_conversation):把 owner 会话的某主对话(含子代理后代、
1429
- * 等答复问卷/页调用)整体搬到 target 会话并切过去。搬的是 runtime 本体不是
1430
- * 副本,单 writer 不变 —— 从在线标签页手里接管也是安全的;源会话修好 active
1431
- * 并推全量刷新,双方都收到去向通知。quiesce 排空期也放行(重连既有工作)。
1432
- */
1433
1329
  async takeOverConversation(targetId, ownerId, convId) {
1434
1330
  const target = this.clients.get(targetId);
1435
1331
  if (!target)
@@ -1442,13 +1338,10 @@ export class AgentService {
1442
1338
  return;
1443
1339
  }
1444
1340
  if (ownerId === targetId) {
1445
- // 自己的对话 → 退化为普通切换。
1446
1341
  try {
1447
1342
  await target.switchConversation(convId);
1448
1343
  }
1449
- catch {
1450
- /* switch 内部已用 notice 报错 */
1451
- }
1344
+ catch { }
1452
1345
  return;
1453
1346
  }
1454
1347
  if (ownerId.startsWith("scheduler:")) {
@@ -1474,7 +1367,6 @@ export class AgentService {
1474
1367
  }
1475
1368
  const moveIds = [convId, ...collectSubagentDescendantIds(briefs, convId)];
1476
1369
  const moveSet = new Set(moveIds);
1477
- // 容量:与 switchSession 同口径(目标项目非子代理且非临时会话 8 个)。
1478
1370
  const movedMains = briefs.filter((b) => moveSet.has(b.id) && !b.isSubagent && !b.isEphemeral).length;
1479
1371
  const openInProject = target.takeoverBriefs().filter((b) => b.cwd === main.cwd && !b.isSubagent && !b.isEphemeral).length + movedMains;
1480
1372
  const maxOpenConversations = getMaxOpenConversations();
@@ -1494,8 +1386,6 @@ export class AgentService {
1494
1386
  target.refreshExternalRunning();
1495
1387
  return;
1496
1388
  }
1497
- // 测试专用故障注入(默认情况下一行不生效):让「接进目标」这一步必错,用来回归
1498
- // 「过户夭折不得变成幽灵」(tests/takeover-rollback-test.mjs)。
1499
1389
  let newMainId;
1500
1390
  try {
1501
1391
  if (process.env.PI_WEB_TEST_TAKEOVER_FAIL_INSERT === "1")
@@ -1505,13 +1395,9 @@ export class AgentService {
1505
1395
  await target.bindSession();
1506
1396
  }
1507
1397
  catch (err) {
1508
- // 夭折回滚:对话已经从源会话摘下来了(源侧 map 已删、订阅已断),接进目标或切换失败就是
1509
- // 「还在跑但谁的列表里都没有」的幽灵 —— 只有重启服务才能靠落盘恢复(issue #556)。
1510
- // 原样搬回源会话,两边都拿到诚实的回执。
1511
1398
  const where = await this.returnTakeoverPayload(source, target, detached.payload);
1512
1399
  console.error("[takeover] insert/activate failed, payload returned to", where, err);
1513
1400
  if (where === "source") {
1514
- // 源页面也得知道发生了什么:它的对话刚才静默地从列表里消失过一瞬间。
1515
1401
  source.sendNotice({
1516
1402
  type: "notice",
1517
1403
  level: "info",
@@ -1526,8 +1412,6 @@ export class AgentService {
1526
1412
  : `Takeover failed (${err.message}) — the conversation is kept in this page's running list; refresh to pick it up.`);
1527
1413
  return;
1528
1414
  }
1529
- // 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
1530
- // 无 sink 时 emit 即丢,无需判断。
1531
1415
  source.sendNotice({
1532
1416
  type: "notice",
1533
1417
  level: "info",
@@ -1545,19 +1429,7 @@ export class AgentService {
1545
1429
  fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
1546
1430
  }
1547
1431
  }
1548
- /**
1549
- * 过户夭折回滚:把已经摘下来的对话搬回源会话(及其运行列表)。
1550
- *
1551
- * 为什么要它:detach 与 insert 之间是唯一的空档期 —— 源侧已经删了 map、断了订阅,
1552
- * 一旦 insert 报错,对话就两头不挂,但 runtime 还在跑(“幽灵会话”,只有重启服务
1553
- * 才能靠落盘会话恢复,issue #556)。这里用同一套 insert 接线原样搬回去。
1554
- *
1555
- * 搬不回去(二次失败,理论上不该发生)时把它们**留在目标会话**:宁可留在新页面
1556
- * 的运行列表里(insert 已给主对话置 listed),也绝不落到“没人持有”的空档。
1557
- * 返回最终归属方,调用方据此给用户出对应文案。
1558
- */
1559
1432
  async returnTakeoverPayload(source, target, payload) {
1560
- // 先摘掉已部分插进目标的残留(不 dispose:runtime 要原样搬)。
1561
1433
  target.reclaimTakeoverConvs(payload);
1562
1434
  try {
1563
1435
  const mainId = source.insertTakeoverConvs(payload);
@@ -1570,16 +1442,10 @@ export class AgentService {
1570
1442
  try {
1571
1443
  target.insertTakeoverConvs(payload);
1572
1444
  }
1573
- catch {
1574
- /* 双失败:对象还在 payload 里,不要再次搬运 —— 不抛,不让 handler 崩 */
1575
- }
1445
+ catch { }
1576
1446
  return "target";
1577
1447
  }
1578
1448
  }
1579
- /**
1580
- * 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
1581
- * 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
1582
- */
1583
1449
  async peekElsewhereQuestion(targetId, ownerId, convId) {
1584
1450
  const target = this.clients.get(targetId);
1585
1451
  if (!target)
@@ -1592,7 +1458,7 @@ export class AgentService {
1592
1458
  return;
1593
1459
  }
1594
1460
  if (ownerId === targetId)
1595
- return; // 自己的问卷走本地通道,不需要预告
1461
+ return;
1596
1462
  if (AgentService.isPseudoClientId(ownerId)) {
1597
1463
  fail("定时任务/插件会话的问卷不支持跨页作答 —— 报告会自动落回绑定的对话,可在后台任务面板查看进度", "Scheduler/plugin session questions cannot be answered cross-page — reports are saved to the bound conversation automatically; check progress in the Background Tasks panel.");
1598
1464
  return;
@@ -1606,10 +1472,6 @@ export class AgentService {
1606
1472
  }
1607
1473
  target.pushElsewhereQuestion(ownerId, convId, q);
1608
1474
  }
1609
- /**
1610
- * 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
1611
- * 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
1612
- */
1613
1475
  async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
1614
1476
  const target = this.clients.get(targetId);
1615
1477
  if (!target)
@@ -1617,7 +1479,6 @@ export class AgentService {
1617
1479
  let source = ownerId ? this.clients.get(ownerId) : undefined;
1618
1480
  let ok = source ? source.resolveQuestion(id, answers, cancelled, cancelReason) : false;
1619
1481
  if (!ok) {
1620
- // 若指定的 owner 未命中或未持有该问卷(重连认领/过户导致 ownerId 变动),遍历所有 clients 寻找持有该 id 的会话
1621
1482
  for (const candidate of this.clients.values()) {
1622
1483
  if (candidate !== source && candidate.resolveQuestion(id, answers, cancelled, cancelReason)) {
1623
1484
  ok = true;
@@ -1635,7 +1496,6 @@ export class AgentService {
1635
1496
  target.refreshExternalRunning();
1636
1497
  }
1637
1498
  }
1638
- /** Locate the live request again after takeover; conversation IDs may have changed. */
1639
1499
  async navigateQuestion(targetId, id) {
1640
1500
  const target = this.clients.get(targetId);
1641
1501
  if (!target)
@@ -1660,7 +1520,6 @@ export class AgentService {
1660
1520
  textEn: "The question has ended; its source is no longer available.",
1661
1521
  });
1662
1522
  }
1663
- /** Get or create the session for a client, racing attach calls safely. */
1664
1523
  async attach(clientId, send, sendShared = send) {
1665
1524
  let cs = this.clients.get(clientId);
1666
1525
  if (!cs) {
@@ -1669,42 +1528,23 @@ export class AgentService {
1669
1528
  cs = await inflight;
1670
1529
  }
1671
1530
  else {
1672
- // 浏览器重启认领(clientId 存 sessionStorage,关浏览器即失;服务端残留
1673
- // ClientSession 的运行中对话否则永远卡在“另一处”只读,连看都看不了):
1674
- // 无其他在线浏览器时,把最近断开的残留会话整体过户给这个新 id
1675
- // (只换 map 键,不搬 runtime:对话/终端/订阅/cwd 原样保留,
1676
- // 流式增量经尾部 attachSink 直接推给新 socket)。
1677
- // 有其他在线标签时不认领(issue #10 隔离优先);quiesce 排空期也放行
1678
- // (这是重连既有工作,不是新工作)。本段无 await,并发 attach 原子。
1679
- // 伪客户端(含 device-task- 私有 Bot capability)绝不认领;
1680
- // 候选端同样排除伪客户端,禁止浏览器接管 Bot 或新任务复用旧 capability。
1681
1531
  const orphan = isOrphanAdoptionExcludedClientId(clientId) ? null : this.findAdoptableOrphan(clientId);
1682
1532
  if (orphan) {
1683
1533
  this.clients.delete(orphan.oldId);
1684
- // 残骸被本页认领:它的离线行状态随 id 作废(行归到新 id 名下)。
1685
1534
  this.clearOfflineRows(orphan.oldId);
1686
1535
  this.clients.set(clientId, orphan.cs);
1687
1536
  cs = orphan.cs;
1688
1537
  orphan.cs.updateClientId?.(clientId);
1689
- // 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
1690
1538
  this.wireClient(cs, clientId);
1691
1539
  cs.noteAdopted();
1692
- // 服务重启前记在旧 id 名下的中断记录搬到新 id 名下,尾部
1693
- // resumeInterrupted 按新 id 消费(只认领一次,不重复恢复)。
1694
1540
  const inter = this.stateStore.takeInterrupted(orphan.oldId);
1695
1541
  if (inter?.length)
1696
1542
  this.stateStore.saveInterrupted(clientId, inter);
1697
1543
  }
1698
1544
  else {
1699
- // Restore this client's last-used workspace when it still exists;
1700
- // Admission gate: while quiesced, only clients with an EXISTING
1701
- // session may attach (they can watch their runs drain); brand-new
1702
- // clients are refused — index.ts closes their socket (4403) and the
1703
- // browser reconnect loop retries after admission reopens.
1704
1545
  if (this.quiesced) {
1705
1546
  throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
1706
1547
  }
1707
- // otherwise fall back to the server's configured default cwd.
1708
1548
  let cwd = this.cwd;
1709
1549
  const saved = this.stateStore.get(clientId);
1710
1550
  if (saved.lastCwd && saved.lastCwd !== this.cwd) {
@@ -1713,27 +1553,16 @@ export class AgentService {
1713
1553
  }
1714
1554
  else {
1715
1555
  try {
1716
- // issue #295:异步 stat —— 同步 stat 落在坏挂载(已卸载的外部卷/
1717
- // autofs 触发点)上会在内核里挂起,冻住整个事件循环(含控制
1718
- // socket 与其他客户端的心跳);异步版本只挡本连接,超时提示照发。
1719
1556
  const { stat } = await import("node:fs/promises");
1720
1557
  if ((await stat(saved.lastCwd)).isDirectory())
1721
1558
  cwd = saved.lastCwd;
1722
1559
  }
1723
- catch {
1724
- // gone (unmounted drive / deleted / hanging mount) — fall back to the default
1725
- }
1560
+ catch { }
1726
1561
  }
1727
1562
  }
1728
- // Sessions use the SDK default per-project dir — no per-client dir.
1729
- // issue #145:新标签页默认恢复项目最近的会话 —— 若那条仍被别处持有
1730
- // (跑着或空闲),建之前就决定空白(第二个 writer 根本不会被打开,
1731
- // 也无需事后拆 runtime)。之前只拦 running:空闲持有照样恢复出双
1732
- // writer,两边轮流发送分叉历史。其他客户端不存在时不扫目录。
1733
1563
  let createOpts;
1734
1564
  const requiresBlankSession = isOrphanAdoptionExcludedClientId(clientId);
1735
1565
  if (requiresBlankSession) {
1736
- // 伪客户端(插件、调度、Canvas、Bot):禁止自动恢复工作区历史或旧任务,强制空白
1737
1566
  createOpts = { blank: true };
1738
1567
  }
1739
1568
  else if (this.clients.size > 0) {
@@ -1746,19 +1575,18 @@ export class AgentService {
1746
1575
  createOpts = { blank: true, blankTitle: owner.title, ...(owner.isStreaming ? {} : { idleHeld: true }) };
1747
1576
  }
1748
1577
  }
1749
- catch {
1750
- // 列表失败不挡正常恢复
1751
- }
1578
+ catch { }
1752
1579
  }
1753
- const creating = ClientSession.create(clientId, cwd, this.stateStore, createOpts).finally(() => {
1580
+ const creating = ClientSession.create(clientId, cwd, this.stateStore, {
1581
+ ...createOpts,
1582
+ onNotificationEvent: (event) => this.onNotificationEvent?.(event),
1583
+ }).finally(() => {
1754
1584
  this.pending.delete(clientId);
1755
1585
  });
1756
1586
  this.pending.set(clientId, creating);
1757
1587
  cs = await creating;
1758
1588
  this.clients.set(clientId, cs);
1759
- // issue #145 接线提前:首帧 elsewhere 依赖它。
1760
1589
  this.wireClient(cs, clientId);
1761
- // Make sure the restored/default workspace appears in the project list.
1762
1590
  this.stateStore.remember(clientId, cwd);
1763
1591
  if (cwd !== this.cwd) {
1764
1592
  send({
@@ -1771,11 +1599,6 @@ export class AgentService {
1771
1599
  }
1772
1600
  }
1773
1601
  }
1774
- // First attach after a restart: reopen sessions that were streaming
1775
- // when the previous process shut down and continue them (consumed
1776
- // once, then cleared). Fire-and-forget AFTER attachSink + hooks:
1777
- // resume emits directly to sinks and needs the owner guards.
1778
- // Progress arrives over the socket as usual.
1779
1602
  const detachedSinks = this.pendingDetaches.get(clientId);
1780
1603
  if (detachedSinks?.has(send)) {
1781
1604
  detachedSinks.delete(send);
@@ -1793,10 +1616,8 @@ export class AgentService {
1793
1616
  this.resumeSharedConversation(clientId, sendShared);
1794
1617
  if (!isSharedExecutionClientId(clientId))
1795
1618
  send(this.globalInteractions());
1796
- // 又有浏览器连上:离线行状态作废(别的页面按在线行重推,去掉离线标记)。
1797
1619
  this.clearOfflineRows(clientId);
1798
1620
  }
1799
- // Forward hooks (set once by index.ts) to every session.
1800
1621
  cs.onDisposed = () => this.releaseSharedClient(cs);
1801
1622
  cs.onQuit = this.onQuit;
1802
1623
  cs.onToolEvent = this.onToolEvent;
@@ -1809,16 +1630,12 @@ export class AgentService {
1809
1630
  cs.pluginBgTasksProvider = this.pluginBgTasksProvider;
1810
1631
  cs.pluginStopBgTask = this.pluginStopBgTask;
1811
1632
  cs.isQuiesced = () => this.quiesced;
1812
- // issue #145 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表)。
1813
1633
  this.wireClient(cs, clientId);
1814
- // 插件宿主工作区跟随:初次接入也同步一次(恢复的 lastCwd 可能≠服务启动目录),
1815
- // notifyCwd 幂等去重;此后 set_cwd 成功时由 cs.onCwdChanged 继续驱动。
1816
1634
  cs.onCwdChanged = (abs, roots) => this.onClientCwdChanged?.(abs, roots);
1817
1635
  this.onClientCwdChanged?.(cs.cwd, cs.workspaceRoots);
1818
1636
  void cs.resumeInterrupted(this.stateStore.takeInterrupted(clientId));
1819
1637
  return cs;
1820
1638
  }
1821
- /** 插件 AI 工具集合变化(注册/注销)时由 index.ts 触发:推送到所有客户端的全部会话。 */
1822
1639
  applyPluginAgentTools() {
1823
1640
  for (const cs of this.clients.values())
1824
1641
  cs.refreshPluginTools();
@@ -1826,7 +1643,6 @@ export class AgentService {
1826
1643
  mcpProjectCwds() {
1827
1644
  return [...new Set([...this.clients.values()].flatMap((cs) => cs.mcpProjectCwds()))];
1828
1645
  }
1829
- /** Runtime initialization/reload also updates management UI, including clients without conversations. */
1830
1646
  refreshMcpProject(cwd) {
1831
1647
  for (const cs of this.clients.values()) {
1832
1648
  if (resolve(cs.cwd) !== resolve(cwd))
@@ -1835,41 +1651,32 @@ export class AgentService {
1835
1651
  cs.pushSettings();
1836
1652
  }
1837
1653
  }
1838
- /** Browser UI locale report (hello.locale / set_locale): persist per client
1839
- * and refresh lang-aware prompts (streaming-safe via ClientSession). */
1840
1654
  async setLocale(clientId, locale) {
1841
1655
  const cs = this.clients.get(clientId);
1842
1656
  if (cs) {
1843
1657
  await cs.setLocale(locale);
1844
1658
  return;
1845
1659
  }
1846
- // hello race: session still being created — wait for it, then apply.
1847
1660
  const inflight = this.pending.get(clientId);
1848
1661
  if (inflight) {
1849
1662
  try {
1850
1663
  await (await inflight).setLocale(locale);
1851
1664
  }
1852
- catch {
1853
- /* attach failed — nothing to apply to */
1854
- }
1665
+ catch { }
1855
1666
  }
1856
1667
  }
1857
- /** 插件斜杠命令集合变化时由 index.ts 触发:重推各客户端的命令目录。 */
1858
1668
  applyPluginCommandCatalog() {
1859
1669
  for (const cs of this.clients.values())
1860
1670
  void cs.pushSlashCommands();
1861
1671
  }
1862
- /** 插件内联标记变化时由 index.ts 触发:重推各客户端 markers 与设置状态。 */
1863
1672
  applyPluginMarkers() {
1864
1673
  for (const cs of this.clients.values())
1865
1674
  cs.refreshPluginMarkers();
1866
1675
  }
1867
- /** 插件常驻后台任务变化时由 index.ts 触发:重推各客户端的 bg_servers。 */
1868
1676
  refreshBackgroundServers() {
1869
1677
  for (const cs of this.clients.values())
1870
1678
  cs.refreshBgTasks();
1871
1679
  }
1872
- /** Remove a socket from a client's broadcast set (called on socket close). */
1873
1680
  detach(clientId, send) {
1874
1681
  const binding = this.sharedViewers.get(clientId);
1875
1682
  if (binding?.send === send) {
@@ -1883,17 +1690,11 @@ export class AgentService {
1883
1690
  if (clientId.startsWith("canvas:") ||
1884
1691
  clientId.startsWith("canvas-") ||
1885
1692
  (clientId.startsWith("device-task-") && !isBotExecutionRegistered(clientId))) {
1886
- // Bot registration is released only after the executor confirms stop.
1887
- // Keep uncertain/disconnected executions owned until that confirmation.
1888
1693
  this.clients.delete(clientId);
1889
1694
  void cs.dispose().catch(() => { });
1890
1695
  this.pokeExternalRunning(clientId);
1891
1696
  return;
1892
1697
  }
1893
- // 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
1894
- // (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
1895
- // (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
1896
- // 「残骸不永久占位」仍然成立)。
1897
1698
  if (!AgentService.isPseudoClientId(clientId)) {
1898
1699
  this.offlineSince.set(clientId, Date.now());
1899
1700
  this.pokeExternalRunning(clientId);
@@ -1902,7 +1703,6 @@ export class AgentService {
1902
1703
  }
1903
1704
  }
1904
1705
  else if (this.pending.has(clientId)) {
1905
- // 连接在 attach 异步创建期间断开:记录待 detach 的 sink,attach 完成后清理,避免死连接泄漏
1906
1706
  let set = this.pendingDetaches.get(clientId);
1907
1707
  if (!set) {
1908
1708
  set = new Set();
@@ -1914,10 +1714,6 @@ export class AgentService {
1914
1714
  get(clientId) {
1915
1715
  return this.clients.get(clientId);
1916
1716
  }
1917
- /** 插件扩展点 v2:挑一个最合适的客户端会话供无浏览器调用的插件 API 用
1918
- * (conversationLister/Searcher/Writer、modelLister、runAborter)。
1919
- * 有运行中对话的优先,否则任意残留客户端;一个没有时返回 undefined,
1920
- * 调用方(index.ts 注入)回退空列表 / {ok:false},绝不抛错。 */
1921
1717
  pluginClient() {
1922
1718
  let fallback;
1923
1719
  for (const cs of this.clients.values()) {
@@ -1927,19 +1723,11 @@ export class AgentService {
1927
1723
  if (cs.activeConversations() > 0)
1928
1724
  return cs;
1929
1725
  }
1930
- catch {
1931
- // 单客户端坏了不影响挑选
1932
- }
1726
+ catch { }
1933
1727
  }
1934
1728
  return fallback;
1935
1729
  }
1936
- /** Snapshot still-streaming conversations for post-restart resume.
1937
- * Called during graceful shutdown AND from the restart_service handler
1938
- * (which exits without shutdown under systemd — without this, the
1939
- * interrupted-run record would silently never be written there). */
1940
1730
  recordInterruptedRuns() {
1941
- // Record still-streaming conversations BEFORE tearing anything down, so
1942
- // the next attach can tell the user what was lost (SIGTERM / update).
1943
1731
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
1944
1732
  for (const [clientId, cs] of [...this.clients]) {
1945
1733
  try {
@@ -1948,9 +1736,7 @@ export class AgentService {
1948
1736
  this.stateStore.saveInterrupted(clientId, running.map((r) => ({ ...r, at: Date.now() })));
1949
1737
  }
1950
1738
  }
1951
- catch {
1952
- // best effort — never block shutdown on bookkeeping
1953
- }
1739
+ catch { }
1954
1740
  }
1955
1741
  }
1956
1742
  getCapabilities() {