pi-web-ui 0.116.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 (529) hide show
  1. package/CHANGELOG.md +83 -3
  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 +163 -36
  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 +184 -504
  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 +203 -371
  14. package/dist/server/agent-service.js +1281 -3030
  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 +42 -114
  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 +36 -214
  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 +38 -92
  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 +142 -68
  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 +48 -9
  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 +27 -11
  69. package/dist/server/device-center/collab-tool.js +393 -27
  70. package/dist/server/device-center/connector.js +128 -48
  71. package/dist/server/device-center/delivery-authority.js +95 -0
  72. package/dist/server/device-center/delivery-subject.js +29 -0
  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 +452 -208
  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 +15 -6
  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 +46 -31
  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 +13 -15
  101. package/dist/server/device-center/hub-deliveries.js +119 -15
  102. package/dist/server/device-center/hub-integration.js +647 -334
  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 +28 -9
  107. package/dist/server/device-center/hub-setup.js +23 -7
  108. package/dist/server/device-center/hub-transaction-log.js +175 -0
  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 +946 -404
  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 +111 -0
  115. package/dist/server/device-center/local-hub.js +6 -4
  116. package/dist/server/device-center/local-publication.js +416 -0
  117. package/dist/server/device-center/local-verification-job.js +95 -0
  118. package/dist/server/device-center/local-verification.js +273 -0
  119. package/dist/server/device-center/local.js +341 -18
  120. package/dist/server/device-center/main.js +18 -2
  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 +52 -46
  125. package/dist/server/device-center/path-portal.js +42 -12
  126. package/dist/server/device-center/publication-journal.js +305 -0
  127. package/dist/server/device-center/publish-intent.js +374 -0
  128. package/dist/server/device-center/relay.js +217 -52
  129. package/dist/server/device-center/report-upload.js +0 -1
  130. package/dist/server/device-center/runtime.js +419 -52
  131. package/dist/server/device-center/store.js +223 -65
  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 +68 -0
  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 +569 -227
  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 +335 -0
  143. package/dist/server/device-center/task-state.js +0 -12
  144. package/dist/server/device-center/task-workspace.js +393 -0
  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 +9 -0
  148. package/dist/server/device-center/work-contract.js +923 -0
  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 +202 -29
  152. package/dist/server/dispatch-plugin-handlers.js +2 -19
  153. package/dist/server/dsh/dsh-agent-service.js +78 -601
  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 +199 -677
  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 +6 -45
  247. package/dist/server/patch-remote-catalog.js +4 -34
  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 +24 -61
  282. package/dist/server/preset-plugin-dependencies.js +0 -2
  283. package/dist/server/preset-share.js +4 -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 +61 -0
  295. package/dist/server/quick-ask.js +260 -0
  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 +55 -31
  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 +32 -56
  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 +215 -0
  318. package/dist/server/session-open.js +69 -0
  319. package/dist/server/session-parser.js +4 -54
  320. package/dist/server/session-scan.js +81 -45
  321. package/dist/server/session-search.js +0 -56
  322. package/dist/server/settings-service.js +19 -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 +3 -40
  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 +55 -0
  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 +98 -194
  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 +30 -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 +373 -0
  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 +55 -6
  387. package/docs/device-center.md +57 -23
  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 +9 -6
  393. package/plugin-sdk/README.md +22 -8
  394. package/plugin-sdk/client-utils.mjs +0 -7
  395. package/plugin-sdk/client.d.ts +26 -0
  396. package/plugin-sdk/client.mjs +52 -0
  397. package/plugin-sdk/import-check.mjs +4 -51
  398. package/plugin-sdk/index.d.ts +128 -117
  399. package/plugin-sdk/index.mjs +2 -687
  400. package/plugin-sdk/package.json +15 -4
  401. package/plugin-sdk/ssh-host-trust.mjs +0 -12
  402. package/plugin-sdk/testing.d.ts +9 -0
  403. package/plugin-sdk/testing.mjs +511 -0
  404. package/plugins/catalog.json +52 -4
  405. package/plugins/superagent/README.md +110 -0
  406. package/plugins/superagent/client/entry.mjs +21 -0
  407. package/plugins/superagent/index.mjs +8 -0
  408. package/plugins/superagent/main.mjs +218 -0
  409. package/plugins/superagent/manifest.json +15 -0
  410. package/plugins/superagent/server.mjs +572 -0
  411. package/plugins/superagent/style.css +167 -0
  412. package/themes/aetheris.css +1 -31
  413. package/themes/ayu-light.css +0 -1
  414. package/themes/bases/flow-base.css +2 -83
  415. package/themes/bases/obsidian-base.css +2 -37
  416. package/themes/bases/statusbar-flat-base.css +0 -1
  417. package/themes/bases/zhujian-base.css +0 -63
  418. package/themes/bases/zhupi-base.css +0 -64
  419. package/themes/catppuccin-latte.css +0 -1
  420. package/themes/catppuccin.css +0 -1
  421. package/themes/claude-code-dark.css +0 -1
  422. package/themes/codex.css +0 -1
  423. package/themes/dark-teal.css +22 -54
  424. package/themes/everforest-light.css +0 -1
  425. package/themes/flow-cristallo.css +160 -0
  426. package/themes/flow-ink.css +160 -0
  427. package/themes/flow-light.css +1 -10
  428. package/themes/flow-obsidian.css +160 -0
  429. package/themes/flow-zurich.css +160 -0
  430. package/themes/flow.css +1 -9
  431. package/themes/geist.css +0 -1
  432. package/themes/gruvbox-light.css +0 -1
  433. package/themes/kanagawa-lotus.css +0 -1
  434. package/themes/md-preview.css +1 -2
  435. package/themes/mist.css +0 -1
  436. package/themes/nord.css +0 -1
  437. package/themes/one-dark.css +0 -1
  438. package/themes/paper.css +0 -1
  439. package/themes/rose-pine-dawn.css +0 -1
  440. package/themes/sakura.css +0 -1
  441. package/themes/solarized-light.css +0 -1
  442. package/themes/tokyo-night.css +0 -1
  443. package/themes/translucent.css +4 -35
  444. package/themes/transparent.css +4 -41
  445. package/themes/vs-code-dark.css +0 -1
  446. package/themes/wallpaper-flow.css +3 -17
  447. package/themes/wallpaper-obsidian.css +1 -4
  448. package/themes/white.css +0 -1
  449. package/web/dist/.build-assets.json +1 -1
  450. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-D-x7kA63.js} +1 -1
  451. package/web/dist/assets/CanvasStudio-CAWcs9tm.js +1579 -0
  452. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +3 -0
  453. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +1 -0
  454. package/web/dist/assets/DeviceGroups-C_fZMNeK.js +1 -0
  455. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CTgVLUbp.js} +1 -1
  456. package/web/dist/assets/FilePreview-C6W0PvaK.js +2 -0
  457. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +1 -0
  458. package/web/dist/assets/GroupConversation-C81YjF2C.js +61 -0
  459. package/web/dist/assets/GroupWorkItems-BIvZtr10.js +1 -0
  460. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-Da6qc566.js} +1 -1
  461. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +2 -0
  462. package/web/dist/assets/NativeCliPanel-CU1rZmyu.js +5 -0
  463. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-DZKY5Wiw.js} +1 -1
  464. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +1 -0
  465. package/web/dist/assets/SCMPanel-CuEgzAlO.js +2 -0
  466. package/web/dist/assets/SettingsModal-Cdu5h29p.js +33 -0
  467. package/web/dist/assets/TermXterm-Bt5WKAxP.js +3 -0
  468. package/web/dist/assets/TerminalPanel-BCIBV8se.js +1 -0
  469. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +1 -0
  470. package/web/dist/assets/app-globals-CZjFtI4F.js +129 -0
  471. package/web/dist/assets/canvas-client-WkhM55mR.js +1 -0
  472. package/web/dist/assets/composer-bridge-CImnjDHq.js +1 -0
  473. package/web/dist/assets/desktop-B8NZ3KW-.js +1 -0
  474. package/web/dist/assets/index-CQc3VrWa.css +1 -0
  475. package/web/dist/assets/index-D_AGu4Zv.js +404 -0
  476. package/web/dist/assets/plugin-host-uqZGpvCs.js +1 -0
  477. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Cdf-cTUe.js} +1 -1
  478. package/web/dist/assets/theme-DGL7hLUs.js +1 -0
  479. package/web/dist/index.html +12 -11
  480. package/web/dist/sw.js +15 -61
  481. package/web/public/sw.js +14 -60
  482. package/dist/gh-comment-781.md +0 -5
  483. package/dist/server/device-center/local-page.js +0 -17
  484. package/dist/server/device-center/smoke-preview.js +0 -3
  485. package/dist/server/durable/durable-capabilities.js +0 -11
  486. package/dist/server/markers/builtins/services.js +0 -123
  487. package/dist/server/markers/builtins/todo.js +0 -189
  488. package/dist/server/markers-list-tool.js +0 -34
  489. package/dist/server/orchestrator.js +0 -109
  490. package/dist/server/patch-turn-end-boundary.js +0 -77
  491. package/dist/server/system-prompt-soul.js +0 -41
  492. package/dist/server/univer-service.js +0 -448
  493. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  494. package/dist/test-artifact.md +0 -9
  495. package/dist/test-preview-modal.md +0 -11
  496. package/dist/test-report.html +0 -20
  497. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +0 -1
  498. package/web/dist/assets/CanvasStudio-B8thymBN.js +0 -1579
  499. package/web/dist/assets/CanvasStudio-zSxyIx1R.js +0 -1579
  500. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  501. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  502. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +0 -1
  503. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  504. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  505. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  506. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  507. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +0 -1
  508. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +0 -1
  509. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  510. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  511. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  512. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  513. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +0 -1
  514. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  515. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  516. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  517. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  518. package/web/dist/assets/TerminalPanel-0CYvD72B.js +0 -3
  519. package/web/dist/assets/TerminalPanel-DDavKvFr.js +0 -3
  520. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +0 -1
  521. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +0 -1
  522. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  523. package/web/dist/assets/canvas-client-CUnXlQYX.js +0 -1
  524. package/web/dist/assets/desktop-aAKpvKJV.js +0 -1
  525. package/web/dist/assets/index-C6DwztqE.css +0 -1
  526. package/web/dist/assets/index-CuN802Sj.js +0 -93
  527. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
  528. package/web/dist/assets/plugin-host-BRWib9DF.js +0 -1
  529. package/web/dist/assets/theme-D2l_mLNo.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,6 +735,14 @@ export class AgentService {
705
735
  }
706
736
  return false;
707
737
  }
738
+ resolveGlobalQuestion(id, answers, cancelled, cancelReason) {
739
+ for (const client of this.clients.values()) {
740
+ if (client.resolveQuestion(id, answers, cancelled, cancelReason)) {
741
+ return true;
742
+ }
743
+ }
744
+ return false;
745
+ }
708
746
  resolveSharedToolApproval(viewerId, ...args) {
709
747
  if (!this.clients.has(viewerId) || isSharedExecutionClientId(viewerId))
710
748
  return false;
@@ -727,9 +765,6 @@ export class AgentService {
727
765
  }
728
766
  return false;
729
767
  }
730
- /** issue #231:同项目视口回退 —— 原绑定对话不在时,把唤醒投给该项目最近活跃
731
- * 的对话(用户当前正看着的面),而不是静默转无头。excludeIds 跳过已知忙对话;
732
- * 候选全部忙回 busy:true;无候选回 ok:false。成功带回实际投递方(调用方重绑定)。 */
733
768
  async wakeViewportInCwd(cwd, text, excludeIds) {
734
769
  const want = String(cwd ?? "").trim();
735
770
  if (!want || !text.trim())
@@ -743,9 +778,7 @@ export class AgentService {
743
778
  if (conv)
744
779
  cands.push({ cs, clientId, conv });
745
780
  }
746
- catch {
747
- // 单客户端坏了继续找下一个
748
- }
781
+ catch { }
749
782
  }
750
783
  cands.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
751
784
  if (cands.length === 0)
@@ -758,9 +791,7 @@ export class AgentService {
758
791
  try {
759
792
  c.cs.flushSnapshot();
760
793
  }
761
- catch {
762
- // 推送失败不影响已投递的唤醒
763
- }
794
+ catch { }
764
795
  let f = "";
765
796
  try {
766
797
  f = String(c.conv.session.sessionFile ?? "");
@@ -773,15 +804,12 @@ export class AgentService {
773
804
  if (r.busy)
774
805
  busyError = r.error;
775
806
  }
776
- catch {
777
- // 单客户端坏了继续找下一个
778
- }
807
+ catch { }
779
808
  }
780
809
  if (busyError)
781
810
  return { ok: false, busy: true, error: busyError };
782
811
  return { ok: false, error: "同项目对话投递失败" };
783
812
  }
784
- /** issue #145:别处在某 cwd 下正在跑的对话(同项目并行感知用,不含请求方)。 */
785
813
  listProjectRunners(cwd, excludeClientId) {
786
814
  const out = [];
787
815
  for (const [clientId, cs] of this.clients) {
@@ -792,10 +820,6 @@ export class AgentService {
792
820
  }
793
821
  return out;
794
822
  }
795
- /** 按 SDK 会话(runtime 身份)找它当前归属的客户端会话与对话 id(过户后归属会变):
796
- * 桥接工具(问卷 / 页面)在调用瞬间用它投递,见 ClientSession.bridgeTarget。
797
- * 一条对话任一时刻只属于一个会话(过户先摘后插),扫一遍即可 —— 问卷/截图都是
798
- * 低频调用,不值得为此再维护一张全局索引。 */
799
823
  findConversationHome(sdkSession) {
800
824
  for (const cs of this.clients.values()) {
801
825
  try {
@@ -803,16 +827,12 @@ export class AgentService {
803
827
  if (convId)
804
828
  return { session: cs, convId };
805
829
  }
806
- catch {
807
- // 单客户端坏了不影响解析
808
- }
830
+ catch { }
809
831
  }
810
832
  return undefined;
811
833
  }
812
- /** Stable execution addresses resolve exactly; legacy display ids must be globally unique. */
813
834
  findSubagentOwner(convId) {
814
835
  // Local cN ids are not global addresses. Never let a transfer alias or
815
- // insertion order choose between clients owning the same display id.
816
836
  const matches = [];
817
837
  for (const cs of this.clients.values()) {
818
838
  const current = cs.resolveExecutionAddress(convId);
@@ -821,11 +841,7 @@ export class AgentService {
821
841
  }
822
842
  return matches.length === 1 ? matches[0] : undefined;
823
843
  }
824
- /** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
825
- * owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
826
844
  listExternalRunning(excludeClientId) {
827
- // 1) 收集当前请求客户端自己持有的对话(按 sessionFile 与 cwd+title 双维度),
828
- // 本机已经持有的对话绝不作为 elsewhere 行推给本机(避免左栏同一对话既是“当前”又是“另一处”)。
829
845
  const currentCs = this.clients.get(excludeClientId);
830
846
  const localFiles = new Set();
831
847
  const localCwdTitles = new Set();
@@ -836,34 +852,24 @@ export class AgentService {
836
852
  localCwdTitles.add(`${b.cwd}\0${b.title}`);
837
853
  }
838
854
  }
839
- // 2) 遍历其他客户端,收集条目并按 sessionFile / cwd+title 去重。
840
- // 若多个客户端持有同会话(如断连竞争、多标签残留),保留正在运行(streaming)或有问卷的更活跃者,
841
- // 杜绝“一堆同一个对话的另一处”在左栏堆积。
842
855
  const dedupMap = new Map();
843
856
  const now = Date.now();
844
857
  for (const [clientId, cs] of this.clients) {
845
858
  if (clientId === excludeClientId)
846
859
  continue;
847
- // 伪客户端(scheduler:/plugin:)不走浏览器,sinkCount 永远为 0,保留。
848
860
  const isPseudo = isSharedExecutionClientId(clientId);
849
- // 无浏览器连接的残骸(sinkCount=0 = 断连留存):宽限期内仍下发(标
850
- // ownerOffline,可接管),过期或 TTL=0 时按 issue #291 不入列表。
851
861
  const offline = !isPseudo && cs.sinkCount() === 0;
852
862
  if (offline && OFFLINE_ROW_TTL_MS <= 0)
853
863
  continue;
854
864
  const offlineSince = offline ? (this.offlineSince.get(clientId) ?? 0) : 0;
855
865
  for (const r of cs.streamingSummariesAll()) {
856
- // activity 只服务宽限期判定,不进 wire(ElsewhereRunning 无此字段)。
857
866
  const { activity, ...rest } = r;
858
867
  if (offline && !rest.isStreaming) {
859
- // 宽限期从「断开时刻」与「最后一次活动」里取较晚者:跑动的后台任务
860
- // 每有事件就续期,不会跑到一半从别人列表里消失。
861
868
  const latest = Math.max(offlineSince, activity || 0);
862
869
  if (latest > 0 && now - latest > OFFLINE_ROW_TTL_MS)
863
870
  continue;
864
871
  }
865
872
  const normFile = rest.sessionFile ? resolve(rest.sessionFile) : undefined;
866
- // 本机已持有该会话文件,或本机在同项目下已有同名可见对话:排除
867
873
  if (normFile && localFiles.has(normFile))
868
874
  continue;
869
875
  if (rest.independent !== false && localCwdTitles.has(`${rest.cwd}\0${rest.title}`))
@@ -874,7 +880,6 @@ export class AgentService {
874
880
  ...(isPseudo ? { pseudo: true } : {}),
875
881
  ...(offline ? { ownerOffline: true } : {}),
876
882
  };
877
- // 跨客户端去重键:有文件按规范路径去重,无文件按 cwd + title 去重
878
883
  const dedupKey = normFile
879
884
  ? `file:${normFile}`
880
885
  : rest.independent === false
@@ -882,7 +887,6 @@ export class AgentService {
882
887
  : `title:${rest.cwd}\0${rest.title}`;
883
888
  const existing = dedupMap.get(dedupKey);
884
889
  if (existing) {
885
- // 优先保留 streaming,其次保留 hasQuestion,最后才轮到离线行让位在线行
886
890
  const preferNew = (!existing.isStreaming && entry.isStreaming) ||
887
891
  (!existing.hasQuestion && entry.hasQuestion) ||
888
892
  (Boolean(existing.ownerOffline) && !entry.ownerOffline);
@@ -896,11 +900,6 @@ export class AgentService {
896
900
  }
897
901
  return [...dedupMap.values()];
898
902
  }
899
- /** 离线行宽限期到期 → 让其他客户端重推一次(行随之从列表消失,回到 #291 口径)。
900
- *
901
- * 到期时刻取「断开时刻」与「最后一次活动」的较晚者:断开后 run 还在跑的后台任务
902
- * 每有流式变化都会重排(见 pokeExternalRunning),跑完那一刻的推送把宽限期从新起算。
903
- * 到期回调只推送、**不再重排**,否则「行已过期」会被无限排成 1s 轮询。 */
904
903
  armOfflineRowExpiry(clientId, cs) {
905
904
  if (OFFLINE_ROW_TTL_MS <= 0)
906
905
  return;
@@ -918,7 +917,6 @@ export class AgentService {
918
917
  const delay = Math.max(1_000, since + OFFLINE_ROW_TTL_MS - Date.now() + 1_000);
919
918
  const timer = setTimeout(() => {
920
919
  this.offlineTimers.delete(clientId);
921
- // 期间重连/被认领/被回收都算作废:只推真实还存在的离线残骸。
922
920
  if (this.clients.get(clientId) === cs && !AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
923
921
  this.notifyExternalRunning(clientId);
924
922
  }
@@ -926,7 +924,6 @@ export class AgentService {
926
924
  timer.unref?.();
927
925
  this.offlineTimers.set(clientId, timer);
928
926
  }
929
- /** 又有浏览器连上(或残骸被认领/回收):离线行状态作废,别的页面按在线行重推。 */
930
927
  clearOfflineRows(clientId) {
931
928
  const had = this.offlineSince.delete(clientId);
932
929
  const timer = this.offlineTimers.get(clientId);
@@ -937,35 +934,23 @@ export class AgentService {
937
934
  if (had)
938
935
  this.pokeExternalRunning(clientId);
939
936
  }
940
- /** issue #291:删除定时任务后回收对应伪客户端,避免残留在 elsewhere 列表。 */
941
937
  releaseSchedulerClient(taskId) {
942
938
  const safe = String(taskId ?? "").replace(/[^A-Za-z0-9_-]/g, "") || "task";
943
939
  const clientId = `scheduler:${safe}`;
944
940
  const cs = this.clients.get(clientId);
945
941
  if (!cs)
946
942
  return;
947
- // 伪客户端常驻一个 noop sink(chatFromScheduler 的 attach),所以不能按
948
- // sinkCount 判断「有没有浏览器」—— 它永远为 1。这里就是它的回收点。
949
943
  this.clients.delete(clientId);
950
- // 先摘出 map 再异步 dispose:只删 map 的话,对话的 runtime/终端/看门狗
951
- // 计时器全都留在内存里(泄漏),转录还挂着活 writer(同文件双写者风险)。
952
- void cs.dispose().catch(() => {
953
- // 回收失败不拦主流程:尽力而为,进程退出时 OS 兜底
954
- });
955
- // 通知其他客户端刷新 elsewhere 列表。
944
+ void cs.dispose().catch(() => { });
956
945
  this.pokeExternalRunning(clientId);
957
946
  }
958
- /** issue #145: 某客户端流式集合变化 → 其他客户端重推 conversations。 */
959
947
  pokeExternalRunning(excludeClientId) {
960
- // 离线残骸刚有状态变化(run 跑完 / 又有事件):离线行宽限期重新起算,
961
- // 定时器顺延到「最后一次活动 + TTL」——否则任务跑完后再没人推它。
962
948
  const offlineCs = this.clients.get(excludeClientId);
963
949
  if (offlineCs && !AgentService.isPseudoClientId(excludeClientId) && offlineCs.sinkCount() === 0) {
964
950
  this.armOfflineRowExpiry(excludeClientId, offlineCs);
965
951
  }
966
952
  this.notifyExternalRunning(excludeClientId);
967
953
  }
968
- /** 只让其他客户端重推一次(不碰离线宽限期定时器)。 */
969
954
  notifyExternalRunning(excludeClientId) {
970
955
  for (const [clientId, cs] of this.clients) {
971
956
  if (clientId === excludeClientId)
@@ -973,57 +958,42 @@ export class AgentService {
973
958
  try {
974
959
  cs.refreshExternalRunning();
975
960
  }
976
- catch {
977
- // 单客户端坏了不影响其他
978
- }
961
+ catch { }
979
962
  }
980
963
  }
981
- /** issue #145:向除请求方外的所有客户端发一条 notice(并行通告用)。 */
982
964
  notifyClientsExcept(excludeClientId, msg) {
983
965
  for (const [clientId, cs] of this.clients) {
984
966
  if (clientId === excludeClientId)
985
967
  continue;
986
968
  try {
987
- // 经 ClientSession.emit 才能进该客户端的 sink 组播;用公开发送面。
988
969
  cs.sendNotice(msg);
989
970
  }
990
- catch {
991
- // 单客户端坏了不影响其他
992
- }
971
+ catch { }
993
972
  }
994
973
  }
995
- /** Aggregate across every client session: conversations with in-flight runs. */
996
974
  activeConversations() {
997
975
  let n = 0;
998
976
  for (const cs of this.clients.values())
999
977
  n += cs.activeConversations();
1000
978
  return n;
1001
979
  }
1002
- /** Aggregate across every client session: messages queued in the SDK. */
1003
980
  pendingMessages() {
1004
981
  let n = 0;
1005
982
  for (const cs of this.clients.values())
1006
983
  n += cs.pendingMessages();
1007
984
  return n;
1008
985
  }
1009
- /** 插件用:全客户端最近活跃对话的快照(#542:按 clientId 取某个标签页正在看的
1010
- * 对话;缺省回落「最近活跃的**非子代理**会话」——子代理跑得再勤也不会把用户
1011
- * 正在看的对话挤出快照)。clientId 不认识/该客户端暂无对话时同样走回落。 */
1012
986
  readConversationForPlugins(opts) {
1013
987
  const want = (opts?.clientId ?? "").trim();
1014
988
  if (want) {
1015
989
  const cs = this.clients.get(want);
1016
990
  if (cs) {
1017
991
  try {
1018
- // 显式客户端:返回它**真正在看**的对话(含子代理对话——那是事实,
1019
- // 快照带 isSubagent 由插件自己判)。
1020
992
  const s = cs.readConversationForPlugins({ preferActive: true, includeSubagents: true });
1021
993
  if (s)
1022
994
  return s;
1023
995
  }
1024
- catch {
1025
- /* 单客户端坏了不影响回落 */
1026
- }
996
+ catch { }
1027
997
  }
1028
998
  }
1029
999
  const snaps = [];
@@ -1031,23 +1001,10 @@ export class AgentService {
1031
1001
  try {
1032
1002
  snaps.push(cs.readConversationForPlugins());
1033
1003
  }
1034
- catch {
1035
- /* 单客户端坏了不影响其他 */
1036
- }
1004
+ catch { }
1037
1005
  }
1038
1006
  return pickLatestClientSnapshot(snaps);
1039
1007
  }
1040
- /** 插件无头调用(host.chat 的落地):外部通道(微信等)把文本投给 agent。
1041
- * 每个 (pluginId, accountId) 独立伪客户端——复用 attach 完整链路
1042
- * (会话恢复/持久化/工具注入/快照),无浏览器也能跑;sink 是空函数,
1043
- * 快照/notice 发了即丢,不攒内存。fire-and-forget:prompt 投递即返回,
1044
- * 运行结果经 onRunEvent(run_end) 按 conversationId 关联。
1045
- * v1 语义:与该服务 cwd 下最近会话共享(单用户视角连续);peer 名由插件
1046
- * 拼进文本前缀,per-peer 会话隔离以后再加。
1047
- * issue #226:对齐定时任务的四件套——conversationId 命中时走 steer 语义
1048
- * 投递(网页端实时可见,miss 则回落无头);cwd 显式 pin 住(不存在/系统
1049
- * 目录即拒绝,不默默跑错目录);model/thinkingLevel 投递前应用(失败即
1050
- * 拒绝,不回落,避免账单/效果与预期不符)。 */
1051
1008
  async chatFromPlugin(pluginId, req) {
1052
1009
  const safe = String(pluginId ?? "plugin").replace(/[^A-Za-z0-9_-]/g, "") || "plugin";
1053
1010
  const acct = String(req?.accountId ?? "default").replace(/[^A-Za-z0-9_-]/g, "") || "default";
@@ -1058,16 +1015,9 @@ export class AgentService {
1058
1015
  throw new Error("chatFromPlugin: text 为空");
1059
1016
  if (this.quiesced)
1060
1017
  throw new QuiesceRejectedError("插件无头调用被拒绝,请等服务器恢复后重试");
1061
- // 本轮运行的稳定标识:随该轮所有 run 事件下发。为何需要:过户会把对话搬到
1062
- // 别的客户端会话(clientId 变),目标会话已有同名 id 时还会就地改名
1063
- // (conversationId 变)——两个键全失效,通道插件靠它认领自己的回包。
1064
1018
  const runId = `pr-${randomUUID()}`;
1065
- // 1. 绑定已有会话:steer 语义投递,网页端实时可见(微信当远程遥控器用)。
1066
- // miss/已回收时不抛错,回落无头伪客户端(浏览器关着时微信照常可用)。
1067
1019
  const target = String(req?.conversationId ?? "").trim();
1068
1020
  if (target) {
1069
- // Conversation ids are local to a client. Prefer this channel's own
1070
- // client; otherwise require an unambiguous target instead of guessing.
1071
1021
  const own = this.clients.get(clientId);
1072
1022
  const ownConv = own?.getConversation(target);
1073
1023
  const hits = [];
@@ -1087,8 +1037,6 @@ export class AgentService {
1087
1037
  if (req.cwd && resolve(req.cwd) !== resolve(conv.cwd))
1088
1038
  throw new Error("chatFromPlugin: bound conversation cwd differs; start a new channel conversation");
1089
1039
  if (req.model || req.thinkingLevel) {
1090
- // Apply overrides only when the captured conversation is active;
1091
- // these APIs address the owner's active conversation.
1092
1040
  if (owner.readConversationForPlugins()?.conversationId !== conv.id)
1093
1041
  throw new Error("chatFromPlugin: cannot change settings of an inactive bound conversation");
1094
1042
  if (req.model)
@@ -1103,7 +1051,6 @@ export class AgentService {
1103
1051
  return { conversationId: conv.id, clientId: ownerId, sessionId: conv.session.sessionId, runId };
1104
1052
  }
1105
1053
  }
1106
- // 2. 工作空间:不传回落伪客户端当前目录;传了必须存在且非系统目录。
1107
1054
  const cwdReq = String(req?.cwd ?? "").trim();
1108
1055
  let cwdAbs = "";
1109
1056
  if (cwdReq) {
@@ -1139,20 +1086,16 @@ export class AgentService {
1139
1086
  throw new Error(`chatFromPlugin: 切换思考强度失败(${thinking}):${err.message}`);
1140
1087
  }
1141
1088
  }
1142
- // 打运行 token(没真跑起来就不认领,不会污染用户自己下一轮的事件归属)。
1143
1089
  let stampedId = "";
1144
1090
  try {
1145
1091
  stampedId = cs.markPluginRun(runId);
1146
1092
  }
1147
- catch {
1148
- /* 打标尽力而为 */
1149
- }
1093
+ catch { }
1150
1094
  const conversationId = stampedId || (cs.readConversationForPlugins()?.conversationId ?? "");
1151
1095
  const conv = cs.getConversation(conversationId);
1152
1096
  void cs.prompt(text, attachments, false, conv).catch((err) => console.error("[plugin chat] prompt failed", err));
1153
1097
  return { conversationId, clientId, sessionId: conv?.session.sessionId, runId };
1154
1098
  }
1155
- /** Abort by the stable plugin run token, including after conversation takeover. */
1156
1099
  async abortPluginRun(runId) {
1157
1100
  for (const owner of this.clients.values()) {
1158
1101
  if (owner.findPluginRun(runId))
@@ -1160,13 +1103,6 @@ export class AgentService {
1160
1103
  }
1161
1104
  return { ok: false, error: "Plugin run is no longer active" };
1162
1105
  }
1163
- /** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
1164
- * 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
1165
- * cwd 按任务配置 pin 住(不存在即失败,不默默跑错目录);可选模型/思考强度
1166
- * 在投递前应用(失败即返回错误,不回落,避免账单/效果与预期不符)。
1167
- * fire-and-forget 投递后等待运行结束(最长 10 分钟轮询),回填真实 outcome
1168
- * (成功/失败/耗时/会话 id)供历史记录与通知使用;超时按失败记录(运行本身
1169
- * 不中止,继续在后台跑完)。 */
1170
1106
  async chatFromScheduler(task) {
1171
1107
  const safe = String(task.id ?? "task").replace(/[^A-Za-z0-9_-]/g, "") || "task";
1172
1108
  const clientId = `scheduler:${safe}`;
@@ -1210,11 +1146,23 @@ export class AgentService {
1210
1146
  if (conversationId && taskTitle) {
1211
1147
  void cs.renameConversation(conversationId, taskTitle);
1212
1148
  }
1213
- void cs.prompt(`[定时任务] ${text}`);
1214
- // 等待运行结束:每 2s 轮询,最长 10 分钟。超时按失败记录(运行继续)。
1149
+ if (cs.readConversationForPlugins()?.isStreaming === true) {
1150
+ return {
1151
+ ok: false,
1152
+ conversationId: conversationId || undefined,
1153
+ error: "上一轮后台任务仍在执行中,跳过本次触发",
1154
+ };
1155
+ }
1156
+ let promptError;
1157
+ void cs.prompt(`[定时任务] ${text}`).catch((err) => {
1158
+ promptError = String(err?.message ?? err);
1159
+ });
1215
1160
  const deadline = Date.now() + 10 * 60 * 1000;
1216
1161
  for (;;) {
1217
1162
  await new Promise((r) => setTimeout(r, 2000));
1163
+ if (promptError) {
1164
+ return { ok: false, conversationId: conversationId || undefined, error: promptError };
1165
+ }
1218
1166
  let streaming = false;
1219
1167
  let lastError;
1220
1168
  try {
@@ -1239,17 +1187,23 @@ export class AgentService {
1239
1187
  return { ok: false, conversationId: conversationId || undefined, error: lastError };
1240
1188
  return { ok: true, conversationId: conversationId || undefined };
1241
1189
  }
1242
- if (Date.now() >= deadline)
1243
- return { ok: false, conversationId: conversationId || undefined, error: "运行超时(10 分钟),仍在后台继续" };
1190
+ if (Date.now() >= deadline) {
1191
+ try {
1192
+ await cs.abort();
1193
+ }
1194
+ catch { }
1195
+ return {
1196
+ ok: false,
1197
+ conversationId: conversationId || undefined,
1198
+ error: "运行超时(10 分钟),已中止后台会话",
1199
+ };
1200
+ }
1244
1201
  }
1245
1202
  }
1246
1203
  catch (err) {
1247
1204
  return { ok: false, error: err.message };
1248
1205
  }
1249
1206
  }
1250
- /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
1251
- * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
1252
- * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
1253
1207
  async completeForPlugins(pluginId, req) {
1254
1208
  try {
1255
1209
  if (this.quiesced)
@@ -1274,14 +1228,12 @@ export class AgentService {
1274
1228
  return { ok: false, error: err.message };
1275
1229
  }
1276
1230
  }
1277
- /** index.ts calls this when a browser socket opens/closes. */
1278
1231
  noteSocketOpen() {
1279
1232
  this.socketCount += 1;
1280
1233
  }
1281
1234
  noteSocketClose() {
1282
1235
  this.socketCount = Math.max(0, this.socketCount - 1);
1283
1236
  }
1284
- /** Full status for the control socket / `server status` command. */
1285
1237
  serviceStatus() {
1286
1238
  return {
1287
1239
  pid: process.pid,
@@ -1294,13 +1246,6 @@ export class AgentService {
1294
1246
  service: toServiceInfo(launchOrigin()),
1295
1247
  };
1296
1248
  }
1297
- // (原 private static isPseudoClientId 已抽到模块级导出并挂为 static 属性)
1298
- /**
1299
- * 浏览器重启认领:给 fresh clientId 找一个可接管的断开残留会话(返回旧 id)。
1300
- * 有别的在线浏览器时返回 null(issue #10 隔离优先)。
1301
- * 全同步:attach 里的认领段不含 await,并发的新标签后到者看到 sinkCount>0,
1302
- * 不会抢走同一个残留。
1303
- */
1304
1249
  findAdoptableOrphan(excludeClientId) {
1305
1250
  const cands = [];
1306
1251
  for (const [id, cs] of this.clients) {
@@ -1345,12 +1290,6 @@ export class AgentService {
1345
1290
  const cs = this.clients.get(picked);
1346
1291
  return cs ? { oldId: picked, cs } : null;
1347
1292
  }
1348
- /**
1349
- * 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表 / 跨端 steer)。
1350
- * attach 尾部与认领分支共用 —— 认领换了 map 键,必须在首帧推送(attachSink)
1351
- * 前就按新 id 重接,否则 self-exclusion 失效:把自己当成“另一处”(elsewhere
1352
- * 误报 + prompt/switch 自拦)。尾部会再调一次,幂等。
1353
- */
1354
1293
  wireClient(cs, clientId) {
1355
1294
  if (isSharedExecutionClientId(clientId) && !this.sharedInteractionSinks.has(cs)) {
1356
1295
  const relay = (msg) => {
@@ -1379,7 +1318,6 @@ export class AgentService {
1379
1318
  cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
1380
1319
  cs.getClaimStore = () => this.claimStore;
1381
1320
  cs.findConversationHome = (sdkSession) => this.findConversationHome(sdkSession);
1382
- // B20:过户后 subagent 工具族的跨会话解析(旧 host 闭包搬不动,按 id 现查持有方)。
1383
1321
  cs.findSubagentOwner = (convId) => this.findSubagentOwner(convId);
1384
1322
  cs.allSubagentSessions = () => [...this.clients.values()];
1385
1323
  cs.listExternalRunning = () => this.listExternalRunning(clientId);
@@ -1388,12 +1326,6 @@ export class AgentService {
1388
1326
  cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
1389
1327
  cs.schedulerStore = this.schedulerStore;
1390
1328
  }
1391
- /**
1392
- * 手动过户(take_over_conversation):把 owner 会话的某主对话(含子代理后代、
1393
- * 等答复问卷/页调用)整体搬到 target 会话并切过去。搬的是 runtime 本体不是
1394
- * 副本,单 writer 不变 —— 从在线标签页手里接管也是安全的;源会话修好 active
1395
- * 并推全量刷新,双方都收到去向通知。quiesce 排空期也放行(重连既有工作)。
1396
- */
1397
1329
  async takeOverConversation(targetId, ownerId, convId) {
1398
1330
  const target = this.clients.get(targetId);
1399
1331
  if (!target)
@@ -1406,13 +1338,10 @@ export class AgentService {
1406
1338
  return;
1407
1339
  }
1408
1340
  if (ownerId === targetId) {
1409
- // 自己的对话 → 退化为普通切换。
1410
1341
  try {
1411
1342
  await target.switchConversation(convId);
1412
1343
  }
1413
- catch {
1414
- /* switch 内部已用 notice 报错 */
1415
- }
1344
+ catch { }
1416
1345
  return;
1417
1346
  }
1418
1347
  if (ownerId.startsWith("scheduler:")) {
@@ -1438,7 +1367,6 @@ export class AgentService {
1438
1367
  }
1439
1368
  const moveIds = [convId, ...collectSubagentDescendantIds(briefs, convId)];
1440
1369
  const moveSet = new Set(moveIds);
1441
- // 容量:与 switchSession 同口径(目标项目非子代理且非临时会话 8 个)。
1442
1370
  const movedMains = briefs.filter((b) => moveSet.has(b.id) && !b.isSubagent && !b.isEphemeral).length;
1443
1371
  const openInProject = target.takeoverBriefs().filter((b) => b.cwd === main.cwd && !b.isSubagent && !b.isEphemeral).length + movedMains;
1444
1372
  const maxOpenConversations = getMaxOpenConversations();
@@ -1458,8 +1386,6 @@ export class AgentService {
1458
1386
  target.refreshExternalRunning();
1459
1387
  return;
1460
1388
  }
1461
- // 测试专用故障注入(默认情况下一行不生效):让「接进目标」这一步必错,用来回归
1462
- // 「过户夭折不得变成幽灵」(tests/takeover-rollback-test.mjs)。
1463
1389
  let newMainId;
1464
1390
  try {
1465
1391
  if (process.env.PI_WEB_TEST_TAKEOVER_FAIL_INSERT === "1")
@@ -1469,13 +1395,9 @@ export class AgentService {
1469
1395
  await target.bindSession();
1470
1396
  }
1471
1397
  catch (err) {
1472
- // 夭折回滚:对话已经从源会话摘下来了(源侧 map 已删、订阅已断),接进目标或切换失败就是
1473
- // 「还在跑但谁的列表里都没有」的幽灵 —— 只有重启服务才能靠落盘恢复(issue #556)。
1474
- // 原样搬回源会话,两边都拿到诚实的回执。
1475
1398
  const where = await this.returnTakeoverPayload(source, target, detached.payload);
1476
1399
  console.error("[takeover] insert/activate failed, payload returned to", where, err);
1477
1400
  if (where === "source") {
1478
- // 源页面也得知道发生了什么:它的对话刚才静默地从列表里消失过一瞬间。
1479
1401
  source.sendNotice({
1480
1402
  type: "notice",
1481
1403
  level: "info",
@@ -1490,8 +1412,6 @@ export class AgentService {
1490
1412
  : `Takeover failed (${err.message}) — the conversation is kept in this page's running list; refresh to pick it up.`);
1491
1413
  return;
1492
1414
  }
1493
- // 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
1494
- // 无 sink 时 emit 即丢,无需判断。
1495
1415
  source.sendNotice({
1496
1416
  type: "notice",
1497
1417
  level: "info",
@@ -1509,19 +1429,7 @@ export class AgentService {
1509
1429
  fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
1510
1430
  }
1511
1431
  }
1512
- /**
1513
- * 过户夭折回滚:把已经摘下来的对话搬回源会话(及其运行列表)。
1514
- *
1515
- * 为什么要它:detach 与 insert 之间是唯一的空档期 —— 源侧已经删了 map、断了订阅,
1516
- * 一旦 insert 报错,对话就两头不挂,但 runtime 还在跑(“幽灵会话”,只有重启服务
1517
- * 才能靠落盘会话恢复,issue #556)。这里用同一套 insert 接线原样搬回去。
1518
- *
1519
- * 搬不回去(二次失败,理论上不该发生)时把它们**留在目标会话**:宁可留在新页面
1520
- * 的运行列表里(insert 已给主对话置 listed),也绝不落到“没人持有”的空档。
1521
- * 返回最终归属方,调用方据此给用户出对应文案。
1522
- */
1523
1432
  async returnTakeoverPayload(source, target, payload) {
1524
- // 先摘掉已部分插进目标的残留(不 dispose:runtime 要原样搬)。
1525
1433
  target.reclaimTakeoverConvs(payload);
1526
1434
  try {
1527
1435
  const mainId = source.insertTakeoverConvs(payload);
@@ -1534,16 +1442,10 @@ export class AgentService {
1534
1442
  try {
1535
1443
  target.insertTakeoverConvs(payload);
1536
1444
  }
1537
- catch {
1538
- /* 双失败:对象还在 payload 里,不要再次搬运 —— 不抛,不让 handler 崩 */
1539
- }
1445
+ catch { }
1540
1446
  return "target";
1541
1447
  }
1542
1448
  }
1543
- /**
1544
- * 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
1545
- * 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
1546
- */
1547
1449
  async peekElsewhereQuestion(targetId, ownerId, convId) {
1548
1450
  const target = this.clients.get(targetId);
1549
1451
  if (!target)
@@ -1556,7 +1458,7 @@ export class AgentService {
1556
1458
  return;
1557
1459
  }
1558
1460
  if (ownerId === targetId)
1559
- return; // 自己的问卷走本地通道,不需要预告
1461
+ return;
1560
1462
  if (AgentService.isPseudoClientId(ownerId)) {
1561
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.");
1562
1464
  return;
@@ -1570,16 +1472,20 @@ export class AgentService {
1570
1472
  }
1571
1473
  target.pushElsewhereQuestion(ownerId, convId, q);
1572
1474
  }
1573
- /**
1574
- * 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
1575
- * 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
1576
- */
1577
1475
  async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
1578
1476
  const target = this.clients.get(targetId);
1579
1477
  if (!target)
1580
1478
  return;
1581
- const source = this.clients.get(ownerId);
1582
- const ok = source ? source.resolveQuestion(id, answers, cancelled, cancelReason) : false;
1479
+ let source = ownerId ? this.clients.get(ownerId) : undefined;
1480
+ let ok = source ? source.resolveQuestion(id, answers, cancelled, cancelReason) : false;
1481
+ if (!ok) {
1482
+ for (const candidate of this.clients.values()) {
1483
+ if (candidate !== source && candidate.resolveQuestion(id, answers, cancelled, cancelReason)) {
1484
+ ok = true;
1485
+ break;
1486
+ }
1487
+ }
1488
+ }
1583
1489
  if (!ok) {
1584
1490
  target.sendNotice({
1585
1491
  type: "notice",
@@ -1590,7 +1496,6 @@ export class AgentService {
1590
1496
  target.refreshExternalRunning();
1591
1497
  }
1592
1498
  }
1593
- /** Locate the live request again after takeover; conversation IDs may have changed. */
1594
1499
  async navigateQuestion(targetId, id) {
1595
1500
  const target = this.clients.get(targetId);
1596
1501
  if (!target)
@@ -1615,7 +1520,6 @@ export class AgentService {
1615
1520
  textEn: "The question has ended; its source is no longer available.",
1616
1521
  });
1617
1522
  }
1618
- /** Get or create the session for a client, racing attach calls safely. */
1619
1523
  async attach(clientId, send, sendShared = send) {
1620
1524
  let cs = this.clients.get(clientId);
1621
1525
  if (!cs) {
@@ -1624,41 +1528,23 @@ export class AgentService {
1624
1528
  cs = await inflight;
1625
1529
  }
1626
1530
  else {
1627
- // 浏览器重启认领(clientId 存 sessionStorage,关浏览器即失;服务端残留
1628
- // ClientSession 的运行中对话否则永远卡在“另一处”只读,连看都看不了):
1629
- // 无其他在线浏览器时,把最近断开的残留会话整体过户给这个新 id
1630
- // (只换 map 键,不搬 runtime:对话/终端/订阅/cwd 原样保留,
1631
- // 流式增量经尾部 attachSink 直接推给新 socket)。
1632
- // 有其他在线标签时不认领(issue #10 隔离优先);quiesce 排空期也放行
1633
- // (这是重连既有工作,不是新工作)。本段无 await,并发 attach 原子。
1634
- // 伪客户端(含 device-task- 私有 Bot capability)绝不认领;
1635
- // 候选端同样排除伪客户端,禁止浏览器接管 Bot 或新任务复用旧 capability。
1636
1531
  const orphan = isOrphanAdoptionExcludedClientId(clientId) ? null : this.findAdoptableOrphan(clientId);
1637
1532
  if (orphan) {
1638
1533
  this.clients.delete(orphan.oldId);
1639
- // 残骸被本页认领:它的离线行状态随 id 作废(行归到新 id 名下)。
1640
1534
  this.clearOfflineRows(orphan.oldId);
1641
1535
  this.clients.set(clientId, orphan.cs);
1642
1536
  cs = orphan.cs;
1643
- // 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
1537
+ orphan.cs.updateClientId?.(clientId);
1644
1538
  this.wireClient(cs, clientId);
1645
1539
  cs.noteAdopted();
1646
- // 服务重启前记在旧 id 名下的中断记录搬到新 id 名下,尾部
1647
- // resumeInterrupted 按新 id 消费(只认领一次,不重复恢复)。
1648
1540
  const inter = this.stateStore.takeInterrupted(orphan.oldId);
1649
1541
  if (inter?.length)
1650
1542
  this.stateStore.saveInterrupted(clientId, inter);
1651
1543
  }
1652
1544
  else {
1653
- // Restore this client's last-used workspace when it still exists;
1654
- // Admission gate: while quiesced, only clients with an EXISTING
1655
- // session may attach (they can watch their runs drain); brand-new
1656
- // clients are refused — index.ts closes their socket (4403) and the
1657
- // browser reconnect loop retries after admission reopens.
1658
1545
  if (this.quiesced) {
1659
1546
  throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
1660
1547
  }
1661
- // otherwise fall back to the server's configured default cwd.
1662
1548
  let cwd = this.cwd;
1663
1549
  const saved = this.stateStore.get(clientId);
1664
1550
  if (saved.lastCwd && saved.lastCwd !== this.cwd) {
@@ -1667,27 +1553,16 @@ export class AgentService {
1667
1553
  }
1668
1554
  else {
1669
1555
  try {
1670
- // issue #295:异步 stat —— 同步 stat 落在坏挂载(已卸载的外部卷/
1671
- // autofs 触发点)上会在内核里挂起,冻住整个事件循环(含控制
1672
- // socket 与其他客户端的心跳);异步版本只挡本连接,超时提示照发。
1673
1556
  const { stat } = await import("node:fs/promises");
1674
1557
  if ((await stat(saved.lastCwd)).isDirectory())
1675
1558
  cwd = saved.lastCwd;
1676
1559
  }
1677
- catch {
1678
- // gone (unmounted drive / deleted / hanging mount) — fall back to the default
1679
- }
1560
+ catch { }
1680
1561
  }
1681
1562
  }
1682
- // Sessions use the SDK default per-project dir — no per-client dir.
1683
- // issue #145:新标签页默认恢复项目最近的会话 —— 若那条仍被别处持有
1684
- // (跑着或空闲),建之前就决定空白(第二个 writer 根本不会被打开,
1685
- // 也无需事后拆 runtime)。之前只拦 running:空闲持有照样恢复出双
1686
- // writer,两边轮流发送分叉历史。其他客户端不存在时不扫目录。
1687
1563
  let createOpts;
1688
1564
  const requiresBlankSession = isOrphanAdoptionExcludedClientId(clientId);
1689
1565
  if (requiresBlankSession) {
1690
- // 伪客户端(插件、调度、Canvas、Bot):禁止自动恢复工作区历史或旧任务,强制空白
1691
1566
  createOpts = { blank: true };
1692
1567
  }
1693
1568
  else if (this.clients.size > 0) {
@@ -1700,19 +1575,18 @@ export class AgentService {
1700
1575
  createOpts = { blank: true, blankTitle: owner.title, ...(owner.isStreaming ? {} : { idleHeld: true }) };
1701
1576
  }
1702
1577
  }
1703
- catch {
1704
- // 列表失败不挡正常恢复
1705
- }
1578
+ catch { }
1706
1579
  }
1707
- 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(() => {
1708
1584
  this.pending.delete(clientId);
1709
1585
  });
1710
1586
  this.pending.set(clientId, creating);
1711
1587
  cs = await creating;
1712
1588
  this.clients.set(clientId, cs);
1713
- // issue #145 接线提前:首帧 elsewhere 依赖它。
1714
1589
  this.wireClient(cs, clientId);
1715
- // Make sure the restored/default workspace appears in the project list.
1716
1590
  this.stateStore.remember(clientId, cwd);
1717
1591
  if (cwd !== this.cwd) {
1718
1592
  send({
@@ -1725,11 +1599,6 @@ export class AgentService {
1725
1599
  }
1726
1600
  }
1727
1601
  }
1728
- // First attach after a restart: reopen sessions that were streaming
1729
- // when the previous process shut down and continue them (consumed
1730
- // once, then cleared). Fire-and-forget AFTER attachSink + hooks:
1731
- // resume emits directly to sinks and needs the owner guards.
1732
- // Progress arrives over the socket as usual.
1733
1602
  const detachedSinks = this.pendingDetaches.get(clientId);
1734
1603
  if (detachedSinks?.has(send)) {
1735
1604
  detachedSinks.delete(send);
@@ -1747,10 +1616,8 @@ export class AgentService {
1747
1616
  this.resumeSharedConversation(clientId, sendShared);
1748
1617
  if (!isSharedExecutionClientId(clientId))
1749
1618
  send(this.globalInteractions());
1750
- // 又有浏览器连上:离线行状态作废(别的页面按在线行重推,去掉离线标记)。
1751
1619
  this.clearOfflineRows(clientId);
1752
1620
  }
1753
- // Forward hooks (set once by index.ts) to every session.
1754
1621
  cs.onDisposed = () => this.releaseSharedClient(cs);
1755
1622
  cs.onQuit = this.onQuit;
1756
1623
  cs.onToolEvent = this.onToolEvent;
@@ -1763,16 +1630,12 @@ export class AgentService {
1763
1630
  cs.pluginBgTasksProvider = this.pluginBgTasksProvider;
1764
1631
  cs.pluginStopBgTask = this.pluginStopBgTask;
1765
1632
  cs.isQuiesced = () => this.quiesced;
1766
- // issue #145 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表)。
1767
1633
  this.wireClient(cs, clientId);
1768
- // 插件宿主工作区跟随:初次接入也同步一次(恢复的 lastCwd 可能≠服务启动目录),
1769
- // notifyCwd 幂等去重;此后 set_cwd 成功时由 cs.onCwdChanged 继续驱动。
1770
1634
  cs.onCwdChanged = (abs, roots) => this.onClientCwdChanged?.(abs, roots);
1771
1635
  this.onClientCwdChanged?.(cs.cwd, cs.workspaceRoots);
1772
1636
  void cs.resumeInterrupted(this.stateStore.takeInterrupted(clientId));
1773
1637
  return cs;
1774
1638
  }
1775
- /** 插件 AI 工具集合变化(注册/注销)时由 index.ts 触发:推送到所有客户端的全部会话。 */
1776
1639
  applyPluginAgentTools() {
1777
1640
  for (const cs of this.clients.values())
1778
1641
  cs.refreshPluginTools();
@@ -1780,7 +1643,6 @@ export class AgentService {
1780
1643
  mcpProjectCwds() {
1781
1644
  return [...new Set([...this.clients.values()].flatMap((cs) => cs.mcpProjectCwds()))];
1782
1645
  }
1783
- /** Runtime initialization/reload also updates management UI, including clients without conversations. */
1784
1646
  refreshMcpProject(cwd) {
1785
1647
  for (const cs of this.clients.values()) {
1786
1648
  if (resolve(cs.cwd) !== resolve(cwd))
@@ -1789,41 +1651,32 @@ export class AgentService {
1789
1651
  cs.pushSettings();
1790
1652
  }
1791
1653
  }
1792
- /** Browser UI locale report (hello.locale / set_locale): persist per client
1793
- * and refresh lang-aware prompts (streaming-safe via ClientSession). */
1794
1654
  async setLocale(clientId, locale) {
1795
1655
  const cs = this.clients.get(clientId);
1796
1656
  if (cs) {
1797
1657
  await cs.setLocale(locale);
1798
1658
  return;
1799
1659
  }
1800
- // hello race: session still being created — wait for it, then apply.
1801
1660
  const inflight = this.pending.get(clientId);
1802
1661
  if (inflight) {
1803
1662
  try {
1804
1663
  await (await inflight).setLocale(locale);
1805
1664
  }
1806
- catch {
1807
- /* attach failed — nothing to apply to */
1808
- }
1665
+ catch { }
1809
1666
  }
1810
1667
  }
1811
- /** 插件斜杠命令集合变化时由 index.ts 触发:重推各客户端的命令目录。 */
1812
1668
  applyPluginCommandCatalog() {
1813
1669
  for (const cs of this.clients.values())
1814
1670
  void cs.pushSlashCommands();
1815
1671
  }
1816
- /** 插件内联标记变化时由 index.ts 触发:重推各客户端 markers 与设置状态。 */
1817
1672
  applyPluginMarkers() {
1818
1673
  for (const cs of this.clients.values())
1819
1674
  cs.refreshPluginMarkers();
1820
1675
  }
1821
- /** 插件常驻后台任务变化时由 index.ts 触发:重推各客户端的 bg_servers。 */
1822
1676
  refreshBackgroundServers() {
1823
1677
  for (const cs of this.clients.values())
1824
1678
  cs.refreshBgTasks();
1825
1679
  }
1826
- /** Remove a socket from a client's broadcast set (called on socket close). */
1827
1680
  detach(clientId, send) {
1828
1681
  const binding = this.sharedViewers.get(clientId);
1829
1682
  if (binding?.send === send) {
@@ -1837,17 +1690,11 @@ export class AgentService {
1837
1690
  if (clientId.startsWith("canvas:") ||
1838
1691
  clientId.startsWith("canvas-") ||
1839
1692
  (clientId.startsWith("device-task-") && !isBotExecutionRegistered(clientId))) {
1840
- // Bot registration is released only after the executor confirms stop.
1841
- // Keep uncertain/disconnected executions owned until that confirmation.
1842
1693
  this.clients.delete(clientId);
1843
1694
  void cs.dispose().catch(() => { });
1844
1695
  this.pokeExternalRunning(clientId);
1845
1696
  return;
1846
1697
  }
1847
- // 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
1848
- // (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
1849
- // (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
1850
- // 「残骸不永久占位」仍然成立)。
1851
1698
  if (!AgentService.isPseudoClientId(clientId)) {
1852
1699
  this.offlineSince.set(clientId, Date.now());
1853
1700
  this.pokeExternalRunning(clientId);
@@ -1856,7 +1703,6 @@ export class AgentService {
1856
1703
  }
1857
1704
  }
1858
1705
  else if (this.pending.has(clientId)) {
1859
- // 连接在 attach 异步创建期间断开:记录待 detach 的 sink,attach 完成后清理,避免死连接泄漏
1860
1706
  let set = this.pendingDetaches.get(clientId);
1861
1707
  if (!set) {
1862
1708
  set = new Set();
@@ -1868,10 +1714,6 @@ export class AgentService {
1868
1714
  get(clientId) {
1869
1715
  return this.clients.get(clientId);
1870
1716
  }
1871
- /** 插件扩展点 v2:挑一个最合适的客户端会话供无浏览器调用的插件 API 用
1872
- * (conversationLister/Searcher/Writer、modelLister、runAborter)。
1873
- * 有运行中对话的优先,否则任意残留客户端;一个没有时返回 undefined,
1874
- * 调用方(index.ts 注入)回退空列表 / {ok:false},绝不抛错。 */
1875
1717
  pluginClient() {
1876
1718
  let fallback;
1877
1719
  for (const cs of this.clients.values()) {
@@ -1881,19 +1723,11 @@ export class AgentService {
1881
1723
  if (cs.activeConversations() > 0)
1882
1724
  return cs;
1883
1725
  }
1884
- catch {
1885
- // 单客户端坏了不影响挑选
1886
- }
1726
+ catch { }
1887
1727
  }
1888
1728
  return fallback;
1889
1729
  }
1890
- /** Snapshot still-streaming conversations for post-restart resume.
1891
- * Called during graceful shutdown AND from the restart_service handler
1892
- * (which exits without shutdown under systemd — without this, the
1893
- * interrupted-run record would silently never be written there). */
1894
1730
  recordInterruptedRuns() {
1895
- // Record still-streaming conversations BEFORE tearing anything down, so
1896
- // the next attach can tell the user what was lost (SIGTERM / update).
1897
1731
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
1898
1732
  for (const [clientId, cs] of [...this.clients]) {
1899
1733
  try {
@@ -1902,9 +1736,7 @@ export class AgentService {
1902
1736
  this.stateStore.saveInterrupted(clientId, running.map((r) => ({ ...r, at: Date.now() })));
1903
1737
  }
1904
1738
  }
1905
- catch {
1906
- // best effort — never block shutdown on bookkeeping
1907
- }
1739
+ catch { }
1908
1740
  }
1909
1741
  }
1910
1742
  getCapabilities() {