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
package/bin/pi-web-ui.mjs CHANGED
@@ -1,34 +1,8 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * pi-web-ui CLI.
4
- *
5
- * pi-web-ui 启动生产服务器(前台,Ctrl+C 停止,自动打开浏览器)
6
- * pi-web-ui --engine dsh --port 9000 --cwd /path 同上,覆盖引擎/端口/工作目录/数据目录
7
- * pi-web-ui --no-browser 启动但不自动打开浏览器
8
- * pi-web-ui --version | --help
9
- * pi-web-ui server install [选项] 安装系统服务(开机自启)并启动
10
- * pi-web-ui server shortcut [选项] 在桌面创建「一键启动」图标(启动服务并打开浏览器)
11
- * pi-web-ui server uninstall [选项] 卸载系统服务(同时移除桌面图标)
12
- * pi-web-ui server start|stop|restart|status [选项]
13
- * pi-web-ui install <源> [选项] 安装 GitHub 上的界面插件(见下方「界面插件」)
14
- * pi-web-ui plugins / uninstall <id> 列出 / 卸载界面插件
15
- *
16
- * 系统服务:
17
- * - macOS → launchd 用户代理,label 默认 com.xingshuyin.pi-web-ui
18
- * (--name 自定义时 com.<name>.server),无需 sudo
19
- * - Linux → systemd 单元 <name>.service(/etc/systemd/system/,自动 sudo)
20
- * - Windows → 登录自启 Run 键(HKCU,无需管理员)+ wscript 隐藏启动(无黑窗);
21
- * PowerShell 启动脚本 / VBS 启动器 / PID 文件生成在
22
- * %APPDATA%\pi-web-ui\
23
- *
24
- * 环境变量(flag 优先,环境变量后备):PI_WEB_PORT / PI_WEB_CWD / PI_WEB_DATA_DIR /
25
- * PI_WEB_ENGINE / PI_WEB_HOST / PI_CODING_AGENT_DIR;token 仅环境变量,不走命令行。
26
- */
27
2
  import { spawn, spawnSync } from "node:child_process";
28
3
  import { createConnection } from "node:net";
29
4
  import { get as httpGet } from "node:http";
30
5
  import { createInterface } from "node:readline/promises";
31
- // Dispatch Hub before loading optional plugin/FRP dependencies or the server build.
32
6
  if (process.argv[2] === "hub") {
33
7
  try {
34
8
  const { runHubCliEntry } = await import("./device-hub-cli.mjs");
@@ -51,6 +25,7 @@ import {
51
25
  readdirSync,
52
26
  renameSync,
53
27
  rmSync,
28
+ statSync,
54
29
  writeFileSync,
55
30
  } from "node:fs";
56
31
  import { homedir, networkInterfaces, tmpdir, userInfo } from "node:os";
@@ -69,43 +44,32 @@ const {
69
44
  } = isHubCommand ? {} : await import("../dist/server/plugin-updater.js");
70
45
 
71
46
  const BIN_DIR = dirname(fileURLToPath(import.meta.url));
72
- /** <pkg>/dist/server/index.js — the actual server entry. */
73
47
  const SERVER_ENTRY = join(BIN_DIR, "..", "dist", "server", "index.js");
74
- /** 「机器上有更新的 pi 副本就跟随它」解析钩子(issue #260;#321 起默认启用)。
75
- * 必须早于任何 SDK 静态 import 加载 —— 所以每条启动路径都把它当 `--import` 传进去;
76
- * PI_WEB_SDK=bundled 显式钉死自带副本(见 server/resolve-global-sdk.ts)。 */
77
48
  const SDK_HOOK = join(BIN_DIR, "..", "dist", "server", "resolve-global-sdk.js");
78
- /** dist 可能是旧构建(没有这个钩子文件)—— 只有文件在才注入:`--import <missing>` 会让
79
- * CLI/服务直接起不来,那比少个开关严重得多。 */
80
49
  const HAS_SDK_HOOK = existsSync(SDK_HOOK);
81
50
  const NODE = process.execPath;
82
51
  let pkg = { version: "0.0.0" };
83
52
  try {
84
53
  pkg = JSON.parse(readFileSync(join(BIN_DIR, "..", "package.json"), "utf8"));
85
- } catch {
86
- // version is best-effort — the server itself doesn't need it
87
- }
54
+ } catch {}
88
55
 
89
- /** Detect if the user prefers Chinese locale: POSIX env vars win, then Intl API fallback. */
90
56
  function isZhLang() {
91
57
  const env = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "";
92
58
  if (env.startsWith("zh")) return true;
93
59
  if (!env) {
94
60
  try {
95
61
  return Intl.DateTimeFormat().resolvedOptions().locale.startsWith("zh");
96
- } catch {
97
- /* ignore */
98
- }
62
+ } catch {}
99
63
  }
100
64
  return false;
101
65
  }
102
66
 
103
- /** Resolved once: CLI messages below pick zh/en with `ZH ? zh : en` (only the chosen branch is evaluated). */
104
67
  const ZH = isZhLang();
105
68
 
106
69
  const HELP_ZH = `pi-web-ui v${pkg.version} — web chat for the pi coding agent
107
70
 
108
- 用法:
71
+ 用法(pwu / piwebui / pi-web-ui 等价):
72
+ pwu [目录] 在指定目录启动(如 pwu .);不能与 --cwd 同用
109
73
  pi-web-ui 启动服务器(前台,Ctrl+C 停止,自动打开浏览器)
110
74
  pi-web-ui --engine dsh --port 9000 --cwd /path 启动并指定引擎 / 端口 / 工作目录 / 数据目录
111
75
  pi-web-ui --no-browser 启动但不自动打开浏览器
@@ -171,7 +135,8 @@ FRP 内网穿透(将本地 pi-web-ui 服务端口通过 FRP 穿透转发到远
171
135
 
172
136
  const HELP_EN = `pi-web-ui v${pkg.version} — web chat for the pi coding agent
173
137
 
174
- Usage:
138
+ Usage (pwu / piwebui / pi-web-ui are equivalent):
139
+ pwu [directory] Start in a directory (e.g. pwu .); cannot combine with --cwd
175
140
  pi-web-ui Start server (foreground, Ctrl+C to stop, auto-opens browser)
176
141
  pi-web-ui --engine dsh --port 9000 --cwd /path Start with engine/port/cwd/data-dir overrides
177
142
  pi-web-ui --no-browser Start without auto-opening browser
@@ -239,7 +204,6 @@ Environment variables (flag takes precedence, env var as fallback):
239
204
 
240
205
  const HELP = isZhLang() ? HELP_ZH : HELP_EN;
241
206
 
242
- /** Minimum Node required by the pi SDK (its dist uses `import … with { type: "json" }`). */
243
207
  const NODE_MIN = [22, 19, 0];
244
208
  function checkNodeVersion() {
245
209
  const v = process.versions.node.split(".").map(Number);
@@ -266,7 +230,6 @@ function fail(msg) {
266
230
  process.exit(1);
267
231
  }
268
232
 
269
- /** Run a command, inheriting stdio; exits on failure unless ignoreError. */
270
233
  function run(cmd, args, { ignoreError = false, silent = false } = {}) {
271
234
  const res = spawnSync(cmd, args, {
272
235
  stdio: silent ? ["inherit", "ignore", "ignore"] : "inherit",
@@ -275,7 +238,6 @@ function run(cmd, args, { ignoreError = false, silent = false } = {}) {
275
238
  return res;
276
239
  }
277
240
 
278
- /** Parse --flag value / --flag=value options; returns { opts, positionals }. */
279
241
  function parseFlags(argv) {
280
242
  const opts = {
281
243
  port: undefined,
@@ -383,11 +345,6 @@ function parseFlags(argv) {
383
345
  return { opts, positionals };
384
346
  }
385
347
 
386
- // ---------------------------------------------------------------------------
387
- // 前台启动
388
- // ---------------------------------------------------------------------------
389
-
390
- /** Open a URL in the OS default browser; failures are ignored (best-effort). */
391
348
  function openBrowser(url) {
392
349
  let res;
393
350
  if (isMac) {
@@ -397,7 +354,6 @@ function openBrowser(url) {
397
354
  } else {
398
355
  res = spawnSync("xdg-open", [url], { stdio: "ignore" });
399
356
  }
400
- // spawnSync 不抛异常:命令缺失(headless 服务器)时在返回对象里带 error 字段。
401
357
  if (res?.error) {
402
358
  if (res.error.code === "ENOENT") {
403
359
  console.warn(
@@ -413,13 +369,6 @@ function openBrowser(url) {
413
369
  }
414
370
  }
415
371
 
416
- /**
417
- * Poll `url` until the server answers (or ~15s pass), then open it in the
418
- * default browser. The foreground server runs in this process, so the first
419
- * HTTP response is the "listening" signal; if the server crashes meanwhile
420
- * (e.g. port already taken), the pending timers die with the process and
421
- * nothing is opened.
422
- */
423
372
  function openBrowserWhenUp(url) {
424
373
  const deadline = Date.now() + 15_000;
425
374
  const attempt = () => {
@@ -448,9 +397,7 @@ function loadStoredFileToken(dataDir) {
448
397
  const raw = readFileSync(join(dataDir, "server-config.json"), "utf8");
449
398
  const parsed = JSON.parse(raw);
450
399
  if (typeof parsed?.token === "string" && parsed.token.trim()) return parsed.token.trim();
451
- } catch {
452
- /* ignore */
453
- }
400
+ } catch {}
454
401
  return "";
455
402
  }
456
403
 
@@ -510,10 +457,6 @@ async function startForeground(opts) {
510
457
  if (!opts.noBrowser) openBrowserWhenUp(url);
511
458
  }
512
459
 
513
- // ---------------------------------------------------------------------------
514
- // 系统服务管理
515
- // ---------------------------------------------------------------------------
516
-
517
460
  const isMac = process.platform === "darwin";
518
461
  const isLinux = process.platform === "linux";
519
462
  const isWin = process.platform === "win32";
@@ -526,7 +469,6 @@ function uid() {
526
469
  }
527
470
  }
528
471
 
529
- /** launchd label / systemd unit name / Windows task name for a service name. */
530
472
  function serviceLabel(name) {
531
473
  if (isMac) {
532
474
  return name === "pi-web-ui" ? "com.xingshuyin.pi-web-ui" : `com.${name}.server`;
@@ -542,7 +484,6 @@ function systemdUnitPath(name) {
542
484
  return `/etc/systemd/system/${name}.service`;
543
485
  }
544
486
 
545
- /** Windows: per-user config dir (%APPDATA%\pi-web-ui) holding the ps1/vbs launchers + pid file. */
546
487
  function winServiceDir() {
547
488
  return join(process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "pi-web-ui");
548
489
  }
@@ -563,22 +504,18 @@ function winTaskXmlPath(name) {
563
504
  return join(winServiceDir(), `${name}.xml`);
564
505
  }
565
506
 
566
- /** Windows log file (per service name — multiple services must not share one log). */
567
507
  function winLogPath(name) {
568
508
  return join(homedir(), name === "pi-web-ui" ? "pi-web-ui.log" : `pi-web-ui-${name}.log`);
569
509
  }
570
510
 
571
- /** True when a scheduled task with this name exists (schtasks exits 0). */
572
511
  function winTaskExists(name) {
573
512
  return spawnSync("schtasks", ["/Query", "/TN", name], { stdio: "ignore" }).status === 0;
574
513
  }
575
514
 
576
- /** Windows: per-user autostart registry key (HKCU — writable without admin). */
577
515
  function winRunKeyName() {
578
516
  return "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
579
517
  }
580
518
 
581
- /** True when the per-user autostart Run key value exists. */
582
519
  function winRunKeyInstalled(name) {
583
520
  return (
584
521
  spawnSync("reg", ["query", `HKCU\\${winRunKeyName()}`, "/v", name], {
@@ -587,39 +524,26 @@ function winRunKeyInstalled(name) {
587
524
  );
588
525
  }
589
526
 
590
- /** Set the per-user autostart Run key value (no admin needed for HKCU). */
591
527
  function winRunKeySet(name, value) {
592
528
  run("reg", ["add", `HKCU\\${winRunKeyName()}`, "/v", name, "/t", "REG_SZ", "/d", value, "/f"], { silent: true });
593
529
  }
594
530
 
595
- /** Remove the per-user autostart Run key value (missing key is a no-op). */
596
531
  function winRunKeyDelete(name) {
597
532
  run("reg", ["delete", `HKCU\\${winRunKeyName()}`, "/v", name, "/f"], { ignoreError: true, silent: true });
598
533
  }
599
534
 
600
- // ---------------------------------------------------------------------------
601
- // 桌面快捷方式(server shortcut)
602
- // ---------------------------------------------------------------------------
603
-
604
- const SHORTCUT_LNK_NAME = "pi-web-ui.lnk"; // Windows 桌面快捷方式
605
- const SHORTCUT_MAC_NAME = "pi-web-ui.command"; // macOS 双击启动器
606
- const SHORTCUT_LINUX_NAME = "pi-web-ui.desktop"; // Linux 桌面图标
535
+ const SHORTCUT_LNK_NAME = "pi-web-ui.lnk";
536
+ const SHORTCUT_MAC_NAME = "pi-web-ui.command";
537
+ const SHORTCUT_LINUX_NAME = "pi-web-ui.desktop";
607
538
 
608
- /** 快捷方式图标(品牌 .ico,随包发布;.lnk / .desktop 指向它)。 */
609
- const APP_ICO_NAME = "pi-web-ui-logo.ico"; // 复制到用户目录后的稳定文件名(避开 pi-web-ui.ico —— Windows 对该路径有损坏的图标缓存残留,见 issue #xxx)
610
- const APP_ICO_SOURCE = join(BIN_DIR, "..", "web", "public", "icon.ico"); // 包内品牌图标源文件(10 帧多分辨率,DPI 密度帧保证桌面/任务栏各尺寸颜色不失真)
611
- /** Branded SVG logo (source of truth: web/public/favicon.svg) — used on Linux. */
539
+ const APP_ICO_NAME = "pi-web-ui-logo.ico";
540
+ const APP_ICO_SOURCE = join(BIN_DIR, "..", "web", "public", "icon.ico");
612
541
  const APP_SVG_PACKAGE = join(BIN_DIR, "..", "web", "public", "favicon.svg");
613
542
 
614
- /** Windows: per-user copy of the branded .ico (stable path for the .lnk icon). */
615
543
  function winIcoPath() {
616
544
  return join(winServiceDir(), APP_ICO_NAME);
617
545
  }
618
546
 
619
- /** Full path to Windows PowerShell. Prefers pwsh.exe (PowerShell 7) when it is
620
- * resolvable on PATH: some machines ship Windows PowerShell 5.1 as a broken
621
- * stub whose launch fails silently, so probe for a working shell first and
622
- * fall back to the built-in path. */
623
547
  function winPowershell() {
624
548
  const which = spawnSync("where.exe", ["pwsh.exe"], { encoding: "utf8" });
625
549
  if (which.status === 0) {
@@ -629,28 +553,14 @@ function winPowershell() {
629
553
  return join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
630
554
  }
631
555
 
632
- /** Full path to wscript.exe — a console-free host (no conhost window, so no black
633
- * console box ever appears in the taskbar on double-click). Used as the .lnk target;
634
- * it launches the .ps1 hidden via a thin VBS launcher. */
635
556
  function winWscript() {
636
557
  return join(process.env.SystemRoot ?? "C:\\Windows", "System32", "wscript.exe");
637
558
  }
638
559
 
639
- /**
640
- * The node binary the launcher scripts must bake in: the executable this
641
- * process itself runs on. Under Bun this resolves to bun, so a Bun-hosted
642
- * install never bakes in pi.exe.
643
- */
644
560
  function resolveNode() {
645
561
  return process.execPath;
646
562
  }
647
563
 
648
- /**
649
- * Resolve the real node binary. fnm/volta/nvm shims (e.g. fnm_multishells)
650
- * point into temp dirs that vanish when the installing shell exits — the
651
- * baked-in launcher scripts must use the stable real path instead.
652
- * Also applies resolveNode() so Bun-hosted pi never bakes in pi.exe.
653
- */
654
564
  function realNode() {
655
565
  try {
656
566
  return realpathSync(resolveNode());
@@ -659,22 +569,18 @@ function realNode() {
659
569
  }
660
570
  }
661
571
 
662
- /** Windows: launcher ps1 the desktop .lnk runs (hidden). */
663
572
  function winShortcutPs1Path(name) {
664
573
  return join(winServiceDir(), `${name}-shortcut.ps1`);
665
574
  }
666
575
 
667
- /** Windows: launcher vbs the desktop .lnk actually runs (wscript.exe, console-free). */
668
576
  function winShortcutVbsPath(name) {
669
577
  return join(winServiceDir(), `${name}-shortcut.vbs`);
670
578
  }
671
579
 
672
- /** Windows: PID file of a shortcut-started (no scheduled task) instance. */
673
580
  function winPidFilePath(name) {
674
581
  return join(winServiceDir(), `${name}.pid`);
675
582
  }
676
583
 
677
- /** Read the recorded PID of a shortcut-started Windows instance. */
678
584
  function winReadPid(name) {
679
585
  try {
680
586
  const pid = Number(readFileSync(winPidFilePath(name), "utf8").trim());
@@ -684,7 +590,6 @@ function winReadPid(name) {
684
590
  }
685
591
  }
686
592
 
687
- /** True when a PID exists (signal 0; EPERM means exists but not ours). */
688
593
  function pidAlive(pid) {
689
594
  if (!pid) return false;
690
595
  try {
@@ -695,18 +600,10 @@ function pidAlive(pid) {
695
600
  }
696
601
  }
697
602
 
698
- /** Single-quote a string for embedding in a POSIX shell script. */
699
603
  function shQuote(s) {
700
604
  return "'" + s.replace(/'/g, `'\\''`) + "'";
701
605
  }
702
606
 
703
- /**
704
- * Windows shortcut launcher. Double-click the .lnk → this script runs hidden:
705
- * server already up → just open the browser; autostart service installed
706
- * (HKCU Run key + wscript/VBS launcher) → start it (manageable via `server
707
- * stop`); otherwise run the server in the foreground of this hidden window and
708
- * record its PID so `server stop` / `server uninstall` can terminate it too.
709
- */
710
607
  function buildWinShortcutPs1(env, cwd, taskName, url, logPath, pidPath) {
711
608
  const sets = Object.entries(env)
712
609
  .map(([k, v]) => `$env:${k} = ${psQuote(v)}`)
@@ -763,22 +660,8 @@ function buildWinShortcutPs1(env, cwd, taskName, url, logPath, pidPath) {
763
660
  ].join("\r\n");
764
661
  }
765
662
 
766
- /**
767
- * Build the tiny VBS launcher that starts a .ps1 *without* creating any console
768
- * host: wscript.exe has no console, and WScript.Shell.Run(…, 0, False) launches
769
- * the child hidden and returns at once (0 = hidden window, False = don't wait).
770
- * Used by both the desktop .lnk and the logon autostart service. Note:
771
- * `powershell -WindowStyle Hidden` alone is unreliable when Windows itself
772
- * spawns the process (Task Scheduler) — the console window can still show;
773
- * this launcher never creates one at all.
774
- */
775
663
  function buildWinHiddenVbs(ps1Path) {
776
- // 可执行文件必须带引号:winPowershell() 常返回 `C:\Program Files\PowerShell\7\pwsh.exe`,
777
- // 含空格且未加引号时 WScript.Shell.Run 找不到文件,直接报 80070002(系统找不到指定的文件)。
778
664
  const cmd = `"${winPowershell()}" -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "${ps1Path}"`;
779
- // VBScript 字符串没有 \" 转义(也没有 \uXXXX),内嵌引号必须写成 "";
780
- // 不能用 JSON.stringify —— 它输出 \" 会在 VBScript 里提前结束字符串(语句未结束 800A0401),
781
- // 且会把非 ASCII 路径转成 \uXXXX 字面量(wscript 不识别,中文用户名直接变成乱码路径)。
782
665
  const vbsCmd = cmd.replace(/"/g, '""');
783
666
  return [
784
667
  "Option Explicit",
@@ -791,18 +674,9 @@ function buildWinHiddenVbs(ps1Path) {
791
674
  ].join("\r\n");
792
675
  }
793
676
 
794
- /**
795
- * Create the Windows desktop .lnk via WScript.Shell COM (correct Desktop path
796
- * even with OneDrive redirection). Target is powershell.exe with
797
- * -WindowStyle Hidden so nothing flashes on double-click.
798
- */
799
677
  function installWinShortcut(opts) {
800
678
  const { name, port, cwd, dataDir, engine, host, agentDir } = serviceOptions(opts);
801
679
  const env = serviceEnv(port, cwd, dataDir, engine, host, agentDir);
802
- // The server binds 127.0.0.1 by default; PowerShell 7's Invoke-WebRequest
803
- // resolves `localhost` to ::1 first and hangs until TimeoutSec when nothing
804
- // listens on IPv6, making the health probe misfire ("server not running").
805
- // Pin the probe (and the opened URL) to the IPv4 loopback the server uses.
806
680
  const url = `http://127.0.0.1:${port}`;
807
681
  const ps1Path = winShortcutPs1Path(name);
808
682
  const ps1 = buildWinShortcutPs1(env, cwd, name, url, winLogPath(name), winPidFilePath(name));
@@ -811,11 +685,9 @@ function installWinShortcut(opts) {
811
685
  return;
812
686
  }
813
687
  mkdirSync(dirname(ps1Path), { recursive: true });
814
- writeFileSync(ps1Path, "\uFEFF" + ps1, "utf8"); // PS 5.1 需要 BOM
815
- // wscript host + VBS launcher: no console window / taskbar black box on double-click.
688
+ writeFileSync(ps1Path, "\uFEFF" + ps1, "utf8");
816
689
  const vbsPath = winShortcutVbsPath(name);
817
- writeFileSync(vbsPath, "\uFEFF" + buildWinHiddenVbs(ps1Path), "utf16le"); // wscript 只认 UTF-16/ANSI,UTF-8 BOM 会报“无效字符”,中文路径用 utf16le + BOM
818
- // 把品牌图标准备好:复制到用户目录(.lnk 图标指向稳定路径)
690
+ writeFileSync(vbsPath, "\uFEFF" + buildWinHiddenVbs(ps1Path), "utf16le");
819
691
  if (existsSync(APP_ICO_SOURCE)) {
820
692
  copyFileSync(APP_ICO_SOURCE, winIcoPath());
821
693
  } else {
@@ -865,7 +737,6 @@ function installWinShortcut(opts) {
865
737
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
866
738
  }
867
739
 
868
- /** macOS: double-clickable .command launcher (the .lnk equivalent). */
869
740
  function buildMacShortcut(label, plist, url, env) {
870
741
  const exports = Object.entries(env)
871
742
  .map(([k, v]) => `export ${k}=${shQuote(v)}`)
@@ -942,7 +813,6 @@ function installMacShortcut(opts) {
942
813
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
943
814
  }
944
815
 
945
- /** Linux: launcher script run by the .desktop icon. */
946
816
  function buildLinuxStartScript(unitName, url) {
947
817
  const log = join(homedir(), ".local", "share", "pi-web-ui", "pi-web-ui.log");
948
818
  const node = realNode();
@@ -983,7 +853,7 @@ function installLinuxShortcut(opts) {
983
853
  const scriptDir = join(homedir(), ".local", "share", "pi-web-ui");
984
854
  const scriptPath = join(scriptDir, `${name}-start.sh`);
985
855
  const desktopPath = join(homedir(), "Desktop", SHORTCUT_LINUX_NAME);
986
- const icoPath = join(scriptDir, APP_ICO_NAME); // 备用;优先 SVG
856
+ const icoPath = join(scriptDir, APP_ICO_NAME);
987
857
  const svgPath = join(scriptDir, "pi-web-ui.svg");
988
858
  const script = buildLinuxStartScript(name, url);
989
859
  const desktopIcon = existsSync(APP_SVG_PACKAGE) ? svgPath : APP_ICO_NAME;
@@ -1003,14 +873,12 @@ Categories=Network;WebBrowser;
1003
873
  return;
1004
874
  }
1005
875
  mkdirSync(scriptDir, { recursive: true });
1006
- // 品牌图标(缺失时跳过,桌面自动回退默认图标)
1007
876
  if (existsSync(APP_SVG_PACKAGE)) copyFileSync(APP_SVG_PACKAGE, svgPath);
1008
877
  else if (existsSync(APP_ICO_SOURCE)) copyFileSync(APP_ICO_SOURCE, icoPath);
1009
878
  writeFileSync(scriptPath, script);
1010
879
  chmodSync(scriptPath, 0o755);
1011
880
  writeFileSync(desktopPath, desktop);
1012
881
  chmodSync(desktopPath, 0o755);
1013
- // GNOME 需要标记可信才能双击运行
1014
882
  run("gio", ["set", desktopPath, "metadata::trusted", "true"], {
1015
883
  ignoreError: true,
1016
884
  silent: true,
@@ -1025,7 +893,6 @@ Categories=Network;WebBrowser;
1025
893
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1026
894
  }
1027
895
 
1028
- /** Remove desktop shortcut artifacts created by `server shortcut`. */
1029
896
  function removeShortcut(name) {
1030
897
  if (isWin) {
1031
898
  for (const f of [winShortcutPs1Path(name), winShortcutVbsPath(name), winPidFilePath(name), winIcoPath()]) {
@@ -1056,20 +923,10 @@ function removeShortcut(name) {
1056
923
  }
1057
924
  }
1058
925
 
1059
- /** Single-quote a string for embedding in a generated PowerShell script. */
1060
926
  function psQuote(s) {
1061
927
  return "'" + s.replace(/'/g, "''") + "'";
1062
928
  }
1063
929
 
1064
- /**
1065
- * Build the PowerShell launcher the autostart service runs. Windows never sees
1066
- * a console from it: the HKCU Run key launches wscript.exe → VBS → powershell
1067
- * (hidden), so no black box can appear. The script sets the env, cd's to the
1068
- * workspace, records its PID to <name>.pid (for `server stop`), then runs node
1069
- * inside a watchdog loop — if node exits, it restarts after 10s (same
1070
- * philosophy as launchd KeepAlive / systemd Restart=always). `server stop`
1071
- * force-kills the recorded PID tree, which takes the loop down with it.
1072
- */
1073
930
  function buildWinStartPs1(env, cwd, logPath, pidPath) {
1074
931
  const sets = Object.entries(env)
1075
932
  .map(([k, v]) => `$env:${k} = ${psQuote(v)}`)
@@ -1097,7 +954,6 @@ function esc(s) {
1097
954
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1098
955
  }
1099
956
 
1100
- /** Start the autostart service now: wscript runs the VBS hidden and exits at once. */
1101
957
  function launchWinService(vbsPath) {
1102
958
  const child = spawn(winWscript(), [vbsPath], {
1103
959
  detached: true,
@@ -1107,30 +963,20 @@ function launchWinService(vbsPath) {
1107
963
  child.unref();
1108
964
  }
1109
965
 
1110
- /**
1111
- * PID 文件记录的是看门狗 PowerShell 的 $PID(winPowershell() 可能选 pwsh.exe),
1112
- * node 是它的子进程 —— 这三者是本服务实例的合理映像名。taskkill /T /F 是树级强杀,
1113
- * PID 若已退出被系统复用就会误杀无辜进程,所以杀前必须核对映像名。
1114
- */
1115
966
  const WIN_SERVICE_IMAGE_RE = /^(powershell|pwsh|node)\.exe$/i;
1116
967
 
1117
- /** tasklist 查询 PID 对应的进程映像名;查询失败/无此进程返回 null(无法核实)。 */
1118
968
  function winPidImageName(pid) {
1119
969
  const res = spawnSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8" });
1120
970
  if (res.status !== 0) return null;
1121
971
  const line = (res.stdout ?? "").split(/\r?\n/).find((l) => l.trim());
1122
- if (!line) return null; // tasklist 的 "INFO: 无任务" 输出没有 CSV 行
972
+ if (!line) return null;
1123
973
  return (line.match(/^"([^"]+)"/) ?? [])[1] ?? null;
1124
974
  }
1125
975
 
1126
- /** Kill a running Windows instance via its PID file (whole tree). */
1127
976
  function stopWinInstance(name) {
1128
977
  const pid = winReadPid(name);
1129
978
  if (pid) {
1130
979
  if (pidAlive(pid)) {
1131
- // PID 可能已退出并被系统复用给别的进程:杀前核对映像名,不符则警告并跳过,
1132
- // 绝不 taskkill /T /F 盲杀。macOS/Linux 无按 PID 杀的路径(launchctl/systemctl
1133
- // 按服务单元管理),只有 Windows 需要这道核对。
1134
980
  const image = winPidImageName(pid);
1135
981
  if (image === null) {
1136
982
  console.warn(
@@ -1149,7 +995,6 @@ function stopWinInstance(name) {
1149
995
  ignoreError: true,
1150
996
  silent: true,
1151
997
  });
1152
- // taskkill /F 异步生效:等到进程树真正退出(restart 需要避免端口竞争)
1153
998
  const deadline = Date.now() + 5000;
1154
999
  while (Date.now() < deadline && pidAlive(pid)) {
1155
1000
  spawnSync("ping", ["-n", "2", "127.0.0.1"], { stdio: "ignore" });
@@ -1160,7 +1005,6 @@ function stopWinInstance(name) {
1160
1005
  }
1161
1006
  }
1162
1007
 
1163
- /** Build the launchd plist XML. */
1164
1008
  function buildPlist(label, cwd, env) {
1165
1009
  const entries = Object.entries(env)
1166
1010
  .map(([k, v]) => ` <key>${esc(k)}</key>\n <string>${esc(v)}</string>`)
@@ -1205,23 +1049,14 @@ ${entries}
1205
1049
  `;
1206
1050
  }
1207
1051
 
1208
- /** systemd quoted strings use C-style escapes; %% prevents specifier expansion. */
1209
1052
  function systemdQuote(value) {
1210
1053
  return JSON.stringify(String(value)).replace(/%/g, "%%");
1211
1054
  }
1212
1055
 
1213
- /**
1214
- * systemd paths (WorkingDirectory=) must NOT be quoted: unlike Environment= and
1215
- * ExecStart=, the path directives do not strip surrounding double quotes, so
1216
- * WorkingDirectory="/home/me/work" makes systemd fail with "path is not absolute".
1217
- * The whole (trimmed) value is the path, so inner spaces need no escaping —
1218
- * only % has to be doubled to survive specifier expansion.
1219
- */
1220
1056
  function systemdPath(value) {
1221
1057
  return String(value).replace(/%/g, "%%");
1222
1058
  }
1223
1059
 
1224
- /** Build the systemd unit file. */
1225
1060
  function buildUnit(cwd, env) {
1226
1061
  const envLines = Object.entries(env)
1227
1062
  .map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`)
@@ -1249,29 +1084,18 @@ WantedBy=multi-user.target
1249
1084
  `;
1250
1085
  }
1251
1086
 
1252
- /** If not root on Linux, re-exec the same server command through sudo. */
1253
1087
  function ensureRootForSystemctl() {
1254
1088
  if (typeof process.getuid === "function" && process.getuid() === 0) return;
1255
- // process.argv = [node, <bin>, "server", <action>, ...rest] — forward
1256
- // everything after "server" so flags like --port/--cwd survive.
1257
1089
  const res = spawnSync("sudo", [NODE, fileURLToPath(import.meta.url), "server", ...process.argv.slice(3)], {
1258
1090
  stdio: "inherit",
1259
1091
  });
1260
1092
  process.exit(res.status ?? 1);
1261
1093
  }
1262
1094
 
1263
- /** Resolve the effective HTTP port: --port > $PI_WEB_PORT > 8787. */
1264
1095
  function effectivePort(opts) {
1265
1096
  return String(opts.port ?? process.env.PI_WEB_PORT ?? "8787");
1266
1097
  }
1267
1098
 
1268
- /**
1269
- * 服务名(--name)统一校验。name 会被原样拼进 systemd unit 文件名
1270
- * (/etc/systemd/system/<name>.service)、Windows 启动脚本/PID 文件路径
1271
- * (%APPDATA%\pi-web-ui\<name>.ps1) 与 HKCU Run 键值名 —— 不限字符集时,
1272
- * 路径分隔符/引号/空格都能进这些拼接点(路径穿越或 unit 内容注入)。
1273
- * 收紧为:字母或数字开头,仅字母/数字/-/_,最长 64 字符。
1274
- */
1275
1099
  function serviceName(opts) {
1276
1100
  const name = opts.name ?? "pi-web-ui";
1277
1101
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name))
@@ -1283,19 +1107,12 @@ function serviceName(opts) {
1283
1107
  return name;
1284
1108
  }
1285
1109
 
1286
- /** Shared option normalization for install. */
1287
1110
  function serviceOptions(opts) {
1288
1111
  const name = serviceName(opts);
1289
1112
  const port = effectivePort(opts);
1290
1113
  if (!/^\d{1,5}$/.test(port) || Number(port) < 1 || Number(port) > 65535) {
1291
1114
  fail(ZH ? `无效端口: ${port}` : `Invalid port: ${port}`);
1292
1115
  }
1293
- // 服务默认工作区(issue #295):安装命令的当前目录不可靠(例如 Windows 提权提示符
1294
- // 默认在 C:\WINDOWS\system32),且直接拿用户主目录当 agent cwd 会让 SDK 的
1295
- // resourceLoader.reload 等同步目录扫描落在 $HOME 上 —— 家目录下的 iCloud 占位符、
1296
- // 外部/网络卷坏挂载会让 scandir/open 在内核里挂起,整个事件循环假死(hello 后永远
1297
- // 收不到 ready)。默认落到干净的 ~/pi-web-ui 子目录(不存在即建);显式 --cwd /
1298
- // PI_WEB_CWD 保持原语义(不存在则报错)。前台启动仍默认当前目录。
1299
1116
  const explicitCwd = opts.cwd ?? process.env.PI_WEB_CWD;
1300
1117
  const cwd = resolve(explicitCwd ?? join(homedir(), "pi-web-ui"));
1301
1118
  if (explicitCwd) {
@@ -1309,7 +1126,6 @@ function serviceOptions(opts) {
1309
1126
  } else if (process.env.PI_WEB_DATA_DIR) {
1310
1127
  dataDir = resolve(process.env.PI_WEB_DATA_DIR);
1311
1128
  }
1312
- // 引擎/监听地址/agent 配置目录:flag 优先,环境变量后备(token 不走命令行,仅环境变量)。
1313
1129
  const engine = opts.engine ?? process.env.PI_WEB_ENGINE ?? "pi";
1314
1130
  if (!["pi", "dsh", "claude", "codex", "durable"].includes(engine))
1315
1131
  fail(
@@ -1327,16 +1143,10 @@ function serviceEnv(port, cwd, dataDir, engine, host, agentDir, service = {}) {
1327
1143
  PI_WEB_PORT: port,
1328
1144
  PI_WEB_CWD: cwd,
1329
1145
  };
1330
- // 启动来源标记(见 server/launch-origin.ts):只有真正被平台服务管理器托管的
1331
- // 启动器才写。桌面快捷方式 / .command 在「未安装服务」时是前台跑(退出不回来),
1332
- // 不能带这个标记,所以它们不传 service。已装好的老服务没有这两个变量,服务端
1333
- // 仍能靠运行时判据(XPC_SERVICE_NAME / INVOCATION_ID / PID 文件)认出来。
1334
1146
  if (service.name) {
1335
1147
  env.PI_WEB_LAUNCHED_BY = "service";
1336
1148
  env.PI_WEB_SERVICE_NAME = service.name;
1337
1149
  }
1338
- // Interactive Windows tasks inherit the user's PATH; only systemd/launchd
1339
- // run with a minimal environment that needs an explicit PATH.
1340
1150
  if (!isWin) {
1341
1151
  const defaultPath =
1342
1152
  process.platform === "darwin"
@@ -1349,14 +1159,10 @@ function serviceEnv(port, cwd, dataDir, engine, host, agentDir, service = {}) {
1349
1159
  env.PATH = currentPath;
1350
1160
  }
1351
1161
  }
1352
- // Same for the locale: launchd/systemd drop LANG/LC_ALL, and a C-locale
1353
- // shell garbles multibyte input in the terminal (UTF-8 continuation
1354
- // bytes 0x80–0x9F rendered as C1 control chars). Bake the installing
1355
- // shell's locale into the service env so spawned terminals are UTF-8.
1356
1162
  if (!isWin && process.env.LANG) env.LANG = process.env.LANG;
1357
1163
  if (!isWin && process.env.LC_ALL) env.LC_ALL = process.env.LC_ALL;
1358
1164
  if (dataDir) env.PI_WEB_DATA_DIR = dataDir;
1359
- if (engine !== "pi") env.PI_WEB_ENGINE = engine; // 仅非默认引擎才烘焙,保持服务单元简洁
1165
+ if (engine !== "pi") env.PI_WEB_ENGINE = engine;
1360
1166
  if (host) env.PI_WEB_HOST = host;
1361
1167
  if (agentDir) env.PI_CODING_AGENT_DIR = agentDir;
1362
1168
  return env;
@@ -1371,7 +1177,6 @@ function installLaunchd(opts) {
1371
1177
  console.log(`# ${plist}\n${content}`);
1372
1178
  return;
1373
1179
  }
1374
- // Unload any existing instance (ignore "not loaded"), then (re)install.
1375
1180
  run("launchctl", ["bootout", `gui/${uid()}/${label}`], {
1376
1181
  ignoreError: true,
1377
1182
  silent: true,
@@ -1398,8 +1203,6 @@ function installLaunchd(opts) {
1398
1203
  );
1399
1204
  }
1400
1205
 
1401
- /** Elevate only the privileged operation, not the CLI that captures the user's environment.
1402
- * Unit contents travel through stdin, never argv (which may expose the token via ps). */
1403
1206
  function runSystemdRoot(command, args, input) {
1404
1207
  const root = typeof process.getuid === "function" && process.getuid() === 0;
1405
1208
  const result = spawnSync(root ? command : "sudo", root ? args : ["--", command, ...args], {
@@ -1421,9 +1224,6 @@ function installSystemd(opts) {
1421
1224
  console.log(`# ${unitPath}\n${content}`);
1422
1225
  return;
1423
1226
  }
1424
- // Generated units can contain credentials. install also corrects an existing unit's mode.
1425
- // Stage through a temp file: `install /dev/stdin` fails on some hosts (WSL) with
1426
- // ENXIO when stdin is a pipe rather than a tty.
1427
1227
  const staged = join(tmpdir(), `pi-web-ui-${name}-${process.pid}.service`);
1428
1228
  writeFileSync(staged, content, { mode: 0o600 });
1429
1229
  try {
@@ -1433,7 +1233,6 @@ function installSystemd(opts) {
1433
1233
  }
1434
1234
  runSystemdRoot("systemctl", ["daemon-reload"]);
1435
1235
  runSystemdRoot("systemctl", ["enable", `${name}.service`]);
1436
- // enable --now does not restart an already-active unit after configuration changes.
1437
1236
  runSystemdRoot("systemctl", ["restart", `${name}.service`]);
1438
1237
  console.log(
1439
1238
  ZH ? `✅ 已安装并启动 systemd 服务 ${name}.service` : `✅ systemd service installed and started ${name}.service`,
@@ -1497,7 +1296,6 @@ function installWindows(opts) {
1497
1296
  const pidPath = winPidFilePath(name);
1498
1297
  const ps1 = buildWinStartPs1(env, cwd, winLogPath(name), pidPath);
1499
1298
  const vbs = buildWinHiddenVbs(ps1Path);
1500
- // HKCU Run 键值:wscript.exe 以隐藏方式启动 VBS(无控制台,登录后自启)
1501
1299
  const runValue = `"${winWscript()}" "${vbsPath}"`;
1502
1300
  if (opts.print) {
1503
1301
  console.log(`# ${ps1Path}\n${ps1}`);
@@ -1507,18 +1305,14 @@ function installWindows(opts) {
1507
1305
  return;
1508
1306
  }
1509
1307
  mkdirSync(dirname(ps1Path), { recursive: true });
1510
- // UTF-8 with BOM: Windows PowerShell 5.1 misreads BOM-less UTF-8 as ANSI.
1511
1308
  writeFileSync(ps1Path, "\uFEFF" + ps1, "utf8");
1512
- // wscript host + VBS launcher: no console window / taskbar black box ever.
1513
- writeFileSync(vbsPath, "\uFEFF" + vbs, "utf16le"); // wscript 只认 UTF-16/ANSI,UTF-8 BOM 会报“无效字符”
1514
- // 迁移:移除旧版 .cmd 包装与历史计划任务(普通用户下 schtasks 无法创建,改为 Run 键)。
1309
+ writeFileSync(vbsPath, "\uFEFF" + vbs, "utf16le");
1515
1310
  if (existsSync(winCmdPath(name))) rmSync(winCmdPath(name));
1516
1311
  if (winTaskExists(name)) {
1517
1312
  run("schtasks", ["/End", "/TN", name], {
1518
1313
  ignoreError: true,
1519
1314
  silent: true,
1520
1315
  });
1521
- // /End 异步生效:稍候再删任务,避免新实例与旧实例端口竞争
1522
1316
  spawnSync("ping", ["-n", "2", "127.0.0.1"], { stdio: "ignore" });
1523
1317
  run("schtasks", ["/Delete", "/TN", name, "/F"], {
1524
1318
  ignoreError: true,
@@ -1556,11 +1350,9 @@ function installWindows(opts) {
1556
1350
  function uninstallWindows(opts) {
1557
1351
  const name = serviceName(opts);
1558
1352
  winRunKeyDelete(name);
1559
- // 历史计划任务(旧版本 install 可能注册过)
1560
1353
  if (winTaskExists(name)) {
1561
1354
  run("schtasks", ["/Delete", "/TN", name, "/F"], { ignoreError: true });
1562
1355
  }
1563
- // 运行中的实例(服务或快捷方式启动,均记录 PID 文件)
1564
1356
  stopWinInstance(name);
1565
1357
  for (const f of [winCmdPath(name), winPs1Path(name), winVbsPath(name), winTaskXmlPath(name)]) {
1566
1358
  if (existsSync(f)) rmSync(f);
@@ -1574,15 +1366,6 @@ function uninstallWindows(opts) {
1574
1366
  console.log(ZH ? `🗑 已移除桌面快捷方式` : `🗑 Desktop shortcut removed`);
1575
1367
  }
1576
1368
 
1577
- // ---------------------------------------------------------------------------
1578
- // ---------------------------------------------------------------------------
1579
- // Local control socket (status / quiesce / unquiesce). The server listens on
1580
- // a mode-0600 Unix socket (POSIX) or a named pipe (Windows) under its data
1581
- // dir; same path rules as server/control-socket.ts so the CLI and server
1582
- // always agree without sharing code.
1583
- // ---------------------------------------------------------------------------
1584
-
1585
- /** Resolve the control socket path for the given options. */
1586
1369
  function controlPath(opts) {
1587
1370
  const dir = opts.dataDir
1588
1371
  ? resolve(opts.dataDir)
@@ -1592,7 +1375,6 @@ function controlPath(opts) {
1592
1375
  return isWin ? `\\\\.\\pipe\\pi-web-ui-${effectivePort(opts)}` : join(dir, "pi-web-ui.sock");
1593
1376
  }
1594
1377
 
1595
- /** Send one control command to a RUNNING server; resolves null if unreachable. */
1596
1378
  function controlCommand(opts, cmd) {
1597
1379
  const path = controlPath(opts);
1598
1380
  return new Promise((resolvePromise) => {
@@ -1649,13 +1431,10 @@ function getLocalLanIpv4s() {
1649
1431
  }
1650
1432
  }
1651
1433
  }
1652
- } catch {
1653
- // best-effort
1654
- }
1434
+ } catch {}
1655
1435
  return ips;
1656
1436
  }
1657
1437
 
1658
- /** 格式化打印服务的访问链接(包含本机、局域网 IP 与 Token / Setup 入口) */
1659
1438
  function printServiceUrls(port, host, token = "") {
1660
1439
  const tokenSuffix = token ? `?token=${token}` : "";
1661
1440
  const isLoopback = !host || isLocalLoopback(host);
@@ -1693,7 +1472,6 @@ function printServiceUrls(port, host, token = "") {
1693
1472
  );
1694
1473
  }
1695
1474
 
1696
- /** 轮询等待后台服务就绪并打印包含实时 token 的访问信息 */
1697
1475
  async function printRunningServiceAccess(opts, host, fallbackToken = "") {
1698
1476
  const t0 = Date.now();
1699
1477
  let st = null;
@@ -1706,7 +1484,6 @@ async function printRunningServiceAccess(opts, host, fallbackToken = "") {
1706
1484
  printServiceUrls(effectivePort(opts), host, token);
1707
1485
  }
1708
1486
 
1709
- /** Append the live server status (via the control socket) to `server status`. */
1710
1487
  async function printLiveStatus(opts) {
1711
1488
  const st = await controlCommand(opts, "status");
1712
1489
  if (!st || !st.ok) {
@@ -1724,8 +1501,6 @@ async function printLiveStatus(opts) {
1724
1501
  }
1725
1502
  console.log(ZH ? ` 版本 : ${st.version} · PID ${st.pid}` : ` Version : ${st.version} · PID ${st.pid}`);
1726
1503
  console.log(ZH ? ` 目录 : ${st.cwd}` : ` Directory : ${st.cwd}`);
1727
- // 启动来源(server/launch-origin.ts):有 supervisor = 这个进程退出后会被自动
1728
- // 拉起(server restart / 更新面板的「重启服务」才有意义)。
1729
1504
  console.log(
1730
1505
  ZH
1731
1506
  ? ` 启动 : ${
@@ -1751,7 +1526,6 @@ async function printLiveStatus(opts) {
1751
1526
  );
1752
1527
  }
1753
1528
 
1754
- /** `server quiesce|unquiesce` — toggle the admission gate on a RUNNING server. */
1755
1529
  async function setQuiesce(opts, on) {
1756
1530
  const st = await controlCommand(opts, on ? "quiesce" : "unquiesce");
1757
1531
  if (!st || !st.ok) {
@@ -1858,7 +1632,7 @@ function controlService(action, opts) {
1858
1632
 
1859
1633
  if (isWin) {
1860
1634
  const installed = winRunKeyInstalled(name);
1861
- const legacy = !installed && winTaskExists(name); // 旧版计划任务安装(未迁移)
1635
+ const legacy = !installed && winTaskExists(name);
1862
1636
 
1863
1637
  if (action === "status") {
1864
1638
  const pid = winReadPid(name);
@@ -1988,11 +1762,6 @@ function controlService(action, opts) {
1988
1762
  );
1989
1763
  }
1990
1764
 
1991
- // ---------------------------------------------------------------------------
1992
- // 界面插件管理(<dataDir>/plugins/,从 GitHub 安装)
1993
- // ---------------------------------------------------------------------------
1994
-
1995
- /** 合法插件 id(同 server/plugins.ts 的 ID_RE)。 */
1996
1765
  const PLUGIN_ID_RE = /^[A-Za-z0-9_-]+$/;
1997
1766
 
1998
1767
  const PLUGIN_HELP = ZH
@@ -2091,7 +1860,6 @@ function pluginDataDir(opts) {
2091
1860
  return resolve(opts.dataDir ?? process.env.PI_WEB_DATA_DIR ?? join(homedir(), ".pi-web"));
2092
1861
  }
2093
1862
 
2094
- /** 解析安装源为 { owner, repo, ref, subpath, cloneUrl } 或本地路径;非法输入直接退出。 */
2095
1863
  function parsePluginSource(rawSpec) {
2096
1864
  let spec = rawSpec.trim();
2097
1865
  let ref;
@@ -2106,7 +1874,6 @@ function parsePluginSource(rawSpec) {
2106
1874
  );
2107
1875
  spec = spec.slice(0, hash).replace(/\/+$/, "");
2108
1876
  }
2109
- // ssh 形式转 https 拉取(不要求本机配 ssh key);URL 去掉协议前缀统一按路径段解析
2110
1877
  const ssh = spec.match(/^git@([^:]+):(.+?)(?:\.git)?$/);
2111
1878
  if (ssh) [, , spec] = ssh;
2112
1879
  else {
@@ -2115,7 +1882,6 @@ function parsePluginSource(rawSpec) {
2115
1882
  }
2116
1883
  const segs = spec.split("/").filter(Boolean);
2117
1884
  if (segs.length < 2) {
2118
- // 单段名称(如 browser-use):若本地随包官方插件或 catalog 存在该 id,自动补齐为官方插件源
2119
1885
  if (segs.length === 1 && PLUGIN_ID_RE.test(segs[0])) {
2120
1886
  const id = segs[0];
2121
1887
  const pkgRoot = resolve(BIN_DIR, "..");
@@ -2156,12 +1922,11 @@ function parsePluginSource(rawSpec) {
2156
1922
  if (!ref && segs.length > 3) ref = segs[3];
2157
1923
  subpath = segs.slice(4).join("/") || undefined;
2158
1924
  } else if (segs.length > 2) {
2159
- subpath = segs.slice(2).join("/"); // owner/repo/sub/dir —— 子目录写法
1925
+ subpath = segs.slice(2).join("/");
2160
1926
  }
2161
1927
  return { owner, repo, ref, subpath, cloneUrl: `https://github.com/${owner}/${repo}.git` };
2162
1928
  }
2163
1929
 
2164
- /** 清理临时目录下残留超过 1 小时的 pi-web-ui-plugin-* 安装目录。 */
2165
1930
  function cleanStalePluginTmpDirs() {
2166
1931
  try {
2167
1932
  const base = tmpdir();
@@ -2181,13 +1946,6 @@ function cleanStalePluginTmpDirs() {
2181
1946
  } catch {}
2182
1947
  }
2183
1948
 
2184
- /**
2185
- * 尝试定位随包自带的内置官方插件目录。
2186
- * 命中条件:
2187
- * 1. 未开启强制远端拉取标志(opts.remote / PI_WEB_PLUGIN_FORCE_REMOTE);
2188
- * 2. 未显式指定非主干 git ref(除 main/master/HEAD 之外的 ref 说明用户想试特定提交);
2189
- * 3. 属于官方仓库(xing-shuyin/pi-web-ui)的 plugins/<id> 子路径,且随包目录存在合法 manifest.json。
2190
- */
2191
1949
  function resolveLocalBuiltinPluginDir(rawSpec, src, opts = {}) {
2192
1950
  if (opts.remote === true || process.env.PI_WEB_PLUGIN_FORCE_REMOTE === "1") return null;
2193
1951
  if (src?.ref && src.ref !== "main" && src.ref !== "master" && src.ref !== "HEAD") return null;
@@ -2209,19 +1967,11 @@ function resolveLocalBuiltinPluginDir(rawSpec, src, opts = {}) {
2209
1967
  return null;
2210
1968
  }
2211
1969
 
2212
- /**
2213
- * 把仓库拉到 tmpDir 并返回检出根目录。
2214
- * 优化策略:
2215
- * 1. 共享缓存复用:同一批量操作/同源仓库共享检出,增量 sparse-checkout add,杜绝反复 clone;
2216
- * 2. 稀疏拉取(Sparse Checkout + Blobless filter):只拉取元数据与目标子目录,免除全量下载数十兆整仓;
2217
- * 3. 健壮降级:稀疏失败平滑降级常规 shallow clone,再失败回退 tarball 直连。
2218
- */
2219
1970
  async function acquireRepo(src, tmpDir, opts = {}) {
2220
1971
  const sharedCache = opts.sharedCache;
2221
1972
  const cacheKey = sharedCache ? `${src.cloneUrl}#${src.ref || "HEAD"}` : null;
2222
1973
  const normalizedSubpath = src.subpath ? src.subpath.split(/[\\/]/).filter(Boolean).join("/") : null;
2223
1974
 
2224
- // 1. 尝试从共享缓存中复用已有检出
2225
1975
  if (sharedCache && cacheKey && sharedCache.has(cacheKey)) {
2226
1976
  const cached = sharedCache.get(cacheKey);
2227
1977
  if (existsSync(cached.dir)) {
@@ -2259,7 +2009,6 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2259
2009
  const gitTimeout = Number(process.env.PI_WEB_GIT_TIMEOUT_MS) || 45_000;
2260
2010
  const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
2261
2011
 
2262
- // 2. 稀疏拉取:当指定了 subpath 时,优先尝试 --filter=blob:none --sparse
2263
2012
  if (normalizedSubpath) {
2264
2013
  const sparseArgs = [
2265
2014
  "-c",
@@ -2308,7 +2057,6 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2308
2057
  }
2309
2058
  }
2310
2059
  }
2311
- // 稀疏拉取失败,清理已产生的残骸,准备降级
2312
2060
  if (existsSync(dst)) {
2313
2061
  try {
2314
2062
  rmSync(dst, { recursive: true, force: true });
@@ -2319,7 +2067,6 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2319
2067
  );
2320
2068
  }
2321
2069
 
2322
- // 3. 常规 shallow clone(未指定 subpath 或稀疏拉取失败时的降级通路)
2323
2070
  const args = ["-c", "connect.timeout=15", "clone", "--depth", "1", "--single-branch"];
2324
2071
  if (src.ref) args.push("--branch", src.ref);
2325
2072
  args.push(src.cloneUrl, dst);
@@ -2349,9 +2096,6 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2349
2096
 
2350
2097
  const url = `https://codeload.github.com/${src.owner}/${src.repo}/tar.gz/${src.ref || "HEAD"}`;
2351
2098
  console.log(ZH ? `· 下载 ${url}` : `· Downloading ${url}`);
2352
- // 注意:这里不用 fail()/process.exit —— async 上下文里还有未关闭的 socket 时
2353
- // 直接退出会触发 Windows libuv "UV_HANDLE_CLOSING" 断言崩溃;改为 throw,
2354
- // 由 pluginInstallCmd 捕获后设 exitCode 让事件循环自然排空。
2355
2099
  let buf;
2356
2100
  try {
2357
2101
  const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(120_000) });
@@ -2376,7 +2120,6 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2376
2120
  writeFileSync(join(tmpDir, "src.tar.gz"), buf);
2377
2121
  const extractTo = join(tmpDir, "tar");
2378
2122
  mkdirSync(extractTo, { recursive: true });
2379
- // 相对路径解压:win32 的 GNU tar 会把 "C:\..." 里的 C: 当远程主机(Cannot connect to C:)
2380
2123
  const tarRes = spawnSync("tar", ["-xzf", "src.tar.gz", "-C", "tar"], {
2381
2124
  cwd: tmpDir,
2382
2125
  stdio: "inherit",
@@ -2397,13 +2140,12 @@ async function acquireRepo(src, tmpDir, opts = {}) {
2397
2140
  return join(extractTo, entries[0]);
2398
2141
  }
2399
2142
 
2400
- /** 在检出树里找包含 manifest.json 的目录(深度 ≤3,跳过 .git/node_modules)。 */
2401
2143
  function findManifestDirs(root) {
2402
2144
  const hits = [];
2403
2145
  const walk = (dir, depth) => {
2404
2146
  if (existsSync(join(dir, "manifest.json"))) {
2405
2147
  hits.push(dir);
2406
- return; // 目录本身是插件就不再往下搜嵌套插件
2148
+ return;
2407
2149
  }
2408
2150
  if (depth >= 3) return;
2409
2151
  for (const ent of readdirSync(dir, { withFileTypes: true })) {
@@ -2415,7 +2157,6 @@ function findManifestDirs(root) {
2415
2157
  return hits;
2416
2158
  }
2417
2159
 
2418
- /** 定位插件根目录:显式子路径 > 根目录 manifest > 全树搜索(唯一命中才继续)。 */
2419
2160
  function locatePluginRoot(checkout, subpath, repoLabel) {
2420
2161
  if (subpath) {
2421
2162
  const dir = join(checkout, ...subpath.split("/"));
@@ -2446,14 +2187,6 @@ function locatePluginRoot(checkout, subpath, repoLabel) {
2446
2187
  return hits[0];
2447
2188
  }
2448
2189
 
2449
- /**
2450
- * 插件的源码构建声明(--build,issue #150):
2451
- * manifest.json: { "build": { "install"?: "npm install --ignore-scripts",
2452
- * "command": "npm run build",
2453
- * "outputs"?: ["index.mjs", "client/entry.mjs"] } }
2454
- * 缺 command 时回落到 package.json 的 scripts.build;两者都没有 = 没声明构建方式。
2455
- * 返回 null 表示该插件没声明构建(--build 会明确报错,而不是猜一个命令出来)。
2456
- */
2457
2190
  function resolveBuildPlan(pluginRoot, manifest) {
2458
2191
  const declared = manifest && typeof manifest.build === "object" && manifest.build ? manifest.build : null;
2459
2192
  let command = declared && typeof declared.command === "string" ? declared.command.trim() : "";
@@ -2461,9 +2194,7 @@ function resolveBuildPlan(pluginRoot, manifest) {
2461
2194
  try {
2462
2195
  const pkg = JSON.parse(readFileSync(join(pluginRoot, "package.json"), "utf8"));
2463
2196
  if (pkg?.scripts && typeof pkg.scripts.build === "string" && pkg.scripts.build.trim()) command = "npm run build";
2464
- } catch {
2465
- /* 没有 package.json */
2466
- }
2197
+ } catch {}
2467
2198
  }
2468
2199
  if (!command) return null;
2469
2200
  const install =
@@ -2477,17 +2208,11 @@ function resolveBuildPlan(pluginRoot, manifest) {
2477
2208
  return { install, command, outputs };
2478
2209
  }
2479
2210
 
2480
- /** 拷贝插件树时的过滤:不带 .git / node_modules(与安装同一套)。 */
2481
2211
  const PLUGIN_COPY_FILTER = (s) => !/(^|[\\/])(\.git|node_modules)([\\/]|$)/.test(s);
2482
2212
 
2483
- /** 插件目录里「属于随包代码」的清单文件:升级时只删清单里的路径,插件自己的
2484
- * 数据(db-connections.json 之类)不在清单里,因此不会被删(issue #813)。 */
2485
2213
  const SHIPPED_LIST = ".pi-files.json";
2486
- /** 这些顶层目录就地保留:既免重下几百 MB 模型,也规避 Windows 下已加载的
2487
- * .node/.dll 被 rmSync 触发 EBUSY 导致更新失败。 */
2488
2214
  const PRESERVED_DIRS = new Set(["whisper-cache", "node_modules"]);
2489
2215
 
2490
- /** 列出将要随包安装的相对路径(与 cpSync 同过滤)。 */
2491
2216
  function listShippedFiles(root) {
2492
2217
  const out = [];
2493
2218
  const walk = (dir, prefix) => {
@@ -2513,7 +2238,6 @@ function listShippedFiles(root) {
2513
2238
  return out.sort();
2514
2239
  }
2515
2240
 
2516
- /** 在给定目录跑一条外部命令(shell 执行,继承 stdio 让用户看到进度)。失败抛错。 */
2517
2241
  function runBuildCommand(cmd, cwd, label) {
2518
2242
  console.log(`· ${label}: ${cmd}`);
2519
2243
  const res = spawnSync(cmd, {
@@ -2531,13 +2255,6 @@ function runBuildCommand(cmd, cwd, label) {
2531
2255
  );
2532
2256
  }
2533
2257
 
2534
- /**
2535
- * 隔离构建:把插件源码拷进临时目录 → 只在那里安装声明的构建依赖(默认
2536
- * npm install --ignore-scripts:不执行任意生命周期脚本)→ 执行声明的构建命令 →
2537
- * 校验产物齐全 → 返回可安装的目录。
2538
- *
2539
- * 全程不碰目标目录:构建失败时上一版插件原样还在(替换只在构建成功后才发生)。
2540
- */
2541
2258
  function buildPluginSource(pluginRoot, tmpDir, manifest) {
2542
2259
  const plan = resolveBuildPlan(pluginRoot, manifest);
2543
2260
  if (!plan)
@@ -2566,16 +2283,6 @@ function buildPluginSource(pluginRoot, tmpDir, manifest) {
2566
2283
  return buildDir;
2567
2284
  }
2568
2285
 
2569
- /**
2570
- * 构建决策(issue #165:--build 自动推断)。
2571
- *
2572
- * 只有源码、没有产物(index.mjs 与 client/entry.mjs 都缺)且存在可解析的构建声明 =
2573
- * “不构建这次安装必死”,此前会直接自动构建;但构建命令来自远端 manifest/package.json,
2574
- * 经 shell:true 执行属于任意命令执行面,非交互环境下静默跑等于替用户放行。
2575
- * 收紧后(审计修复):mode=auto 只表示“有构建声明且必要”,是否真正执行由
2576
- * installOnePlugin 二次把关 —— 交互 TTY 且用户输入 y 才跑,否则跳过并警告。
2577
- * --no-build 保留旧的“装个空目录”行为(脚本化镜像/检查用),并明确打印跳过原因。
2578
- */
2579
2286
  function decideBuildAction({ pluginRoot, manifest, build, noBuild, isCatalog = false }) {
2580
2287
  if (build && noBuild)
2581
2288
  throw new Error(
@@ -2602,10 +2309,6 @@ function decideBuildAction({ pluginRoot, manifest, build, noBuild, isCatalog = f
2602
2309
  return { mode: "none", plan };
2603
2310
  }
2604
2311
 
2605
- /**
2606
- * 交互确认:插件声明的构建命令将经 shell 在本机执行(install + command 都来自
2607
- * 远端 manifest/package.json),必须用户显式输入 y 才跑。仅 TTY 下会被调用。
2608
- */
2609
2312
  async function confirmSourceBuild(plan) {
2610
2313
  const rl = createInterface({ input: process.stdin, output: process.stdout });
2611
2314
  try {
@@ -2621,11 +2324,6 @@ async function confirmSourceBuild(plan) {
2621
2324
  }
2622
2325
  }
2623
2326
 
2624
- /**
2625
- * 装一个插件(单源模式与目录模式共用):拉取/定位 → 读 manifest → 构建决策 →
2626
- * 覆盖(备份+保留 config.json)→ 落盘 → 记录来源/sha。
2627
- * 失败抛 Error(目录模式逐条 try/catch 继续下一条,单源模式由调用方转 fail)。
2628
- */
2629
2327
  async function installOnePlugin({
2630
2328
  rawSpec,
2631
2329
  name,
@@ -2651,7 +2349,6 @@ async function installOnePlugin({
2651
2349
  const isLocal = existsSync(localCandidate);
2652
2350
  const src = isLocal ? null : parsePluginSource(rawSpec);
2653
2351
 
2654
- // 随包内置插件快速路径:若随包已自带官方插件且满足版本条件,优先走本地快速通路
2655
2352
  const localBuiltinDir = isLocal ? null : resolveLocalBuiltinPluginDir(rawSpec, src, { remote });
2656
2353
  let fastPathCandidate = null;
2657
2354
  if (localBuiltinDir) {
@@ -2663,15 +2360,12 @@ async function installOnePlugin({
2663
2360
  const id = name ?? fallbackId;
2664
2361
  const target = join(pluginsDir, id);
2665
2362
  if (!existsSync(target)) {
2666
- // 未安装:全新安装直接采用本地随包
2667
2363
  fastPathCandidate = localBuiltinDir;
2668
2364
  } else if (force) {
2669
- // 覆盖更新:对比随包版本与已装版本
2670
2365
  try {
2671
2366
  const tgtM = JSON.parse(readFileSync(join(target, "manifest.json"), "utf8"));
2672
2367
  const srcM = JSON.parse(readFileSync(join(localBuiltinDir, "manifest.json"), "utf8"));
2673
2368
  if (srcM?.version && tgtM?.version && compareVersions(srcM.version, tgtM.version) > 0) {
2674
- // 随包版本比已装版本更新(刚升级了主程序),优先直接使用本地随包
2675
2369
  fastPathCandidate = localBuiltinDir;
2676
2370
  }
2677
2371
  } catch {}
@@ -2694,7 +2388,6 @@ async function installOnePlugin({
2694
2388
  try {
2695
2389
  checkout = await acquireRepo(src, tmp, { sharedCache });
2696
2390
  } catch (err) {
2697
- // 若远端拉取失败,且属于官方插件,优雅回退到本地随包(离线与断网容错保护)
2698
2391
  if (localBuiltinDir && existsSync(join(localBuiltinDir, "manifest.json"))) {
2699
2392
  console.warn(
2700
2393
  ZH
@@ -2719,8 +2412,6 @@ async function installOnePlugin({
2719
2412
  : `manifest.json is not valid JSON: ${err?.message ?? err}`,
2720
2413
  );
2721
2414
  }
2722
- // 构建决策(issue #150 的 --build + issue #165 的自动推断):构建在临时目录里完成,
2723
- // 成功后才进入覆盖流程——构建失败 = 目标目录完全没被动过(上一版插件照常可用)。
2724
2415
  const decision = decideBuildAction({
2725
2416
  pluginRoot,
2726
2417
  manifest,
@@ -2728,9 +2419,6 @@ async function installOnePlugin({
2728
2419
  noBuild: noBuild === true,
2729
2420
  isCatalog,
2730
2421
  });
2731
- // 授权把关(审计修复):--build 显式传参行为不变;mode=auto 的构建命令来自
2732
- // 远端 manifest/package.json 且经 shell:true 执行 —— 非交互环境绝不自动跑
2733
- // (跳过并警告),交互 TTY 也要用户显式输入 y 才执行。
2734
2422
  let authorized = decision.mode === "explicit";
2735
2423
  if (decision.mode === "auto") {
2736
2424
  if (!process.stdin.isTTY) {
@@ -2774,7 +2462,6 @@ async function installOnePlugin({
2774
2462
  : "· Build skipped: no artifacts in directory, plugin will not load after install (re-install with authorization to build)",
2775
2463
  );
2776
2464
  }
2777
- // 默认 id:子目录名 > 仓库名 > 本地目录名
2778
2465
  const sourceName = src?.subpath ? src.subpath.split("/").pop() : (src?.repo ?? localCandidate.split(/[\\/]/).pop());
2779
2466
  const fallbackId =
2780
2467
  String(manifest.id ?? sourceName)
@@ -2798,32 +2485,20 @@ async function installOnePlugin({
2798
2485
  ? `插件目录已存在:${target}\n 加 --force 覆盖,或用 --name <id> 换个名字。`
2799
2486
  : `Plugin directory already exists: ${target}\n Add --force to overwrite, or use --name <id> to choose a different name.`,
2800
2487
  );
2801
- // 更新前备份旧版本(<dataDir>/plugin-backups/<id>-<ts>/,保留最近 3 份),
2802
- // 失败时自动回滚。备份与安装同 filter:不带 .git/node_modules。
2803
2488
  backupTs = ensurePluginBackup(dataDir, id, { source: rawSpec });
2804
- // 插件凭据/加密机密/私有存储/运行时依赖声明不因升级丢失:先取出,拷完新文件后若新包未自带则原样放回
2805
2489
  for (const fname of PRESERVED_FILES) {
2806
2490
  try {
2807
2491
  preservedData.set(fname, readFileSync(join(target, fname)));
2808
- } catch {
2809
- /* 无该文件 */
2810
- }
2492
+ } catch {}
2811
2493
  }
2812
- // 只删上一版**随包安装**的文件:插件把自己的数据写在插件目录里
2813
- // (db-client 的 db-connections.json、聊天记录、索引……)时,整目录清空会
2814
- // 把它们一起删掉(issue #813)。没有清单的老安装不敢猜,宁可少删:
2815
- // 残留的旧代码文件不会被加载,而删错的数据找不回来。
2816
2494
  let previous = null;
2817
2495
  try {
2818
2496
  const raw = JSON.parse(readFileSync(join(target, SHIPPED_LIST), "utf8"));
2819
2497
  if (Array.isArray(raw?.files)) previous = raw.files.filter((f) => typeof f === "string" && f);
2820
- } catch {
2821
- /* 老版本安装没留清单 */
2822
- }
2498
+ } catch {}
2823
2499
  if (previous) {
2824
2500
  for (const rel of previous) {
2825
2501
  const full = resolve(target, rel);
2826
- // 清单来自磁盘,越界路径一律忽略(不支持插件把文件删到目录外)。
2827
2502
  if (!full.startsWith(target + sep)) continue;
2828
2503
  if (PRESERVED_DIRS.has(relative(target, full).split(sep)[0])) continue;
2829
2504
  rmSync(full, { recursive: true, force: true });
@@ -2840,7 +2515,6 @@ async function installOnePlugin({
2840
2515
  try {
2841
2516
  cpSync(installRoot, target, { recursive: true, filter: PLUGIN_COPY_FILTER });
2842
2517
  } catch (err) {
2843
- // 拷贝失败 → 有备份则自动回滚,保持旧版本可用
2844
2518
  if (backupTs && restorePluginBackup(dataDir, id)) {
2845
2519
  throw new Error(
2846
2520
  ZH
@@ -2859,33 +2533,21 @@ async function installOnePlugin({
2859
2533
  writeFileSync(join(target, fname), buf);
2860
2534
  }
2861
2535
  }
2862
- // 记录来源 / 远端 sha / 随包文件清单。清单是下一次升级的删除依据:只删它,
2863
- // 插件自己写进目录的数据就不会被清空。
2864
2536
  try {
2865
2537
  writeFileSync(
2866
2538
  join(target, SHIPPED_LIST),
2867
2539
  JSON.stringify({ files: listShippedFiles(installRoot) }, null, 2) + "\n",
2868
2540
  );
2869
- } catch {
2870
- /* 尽力而为:没有清单时下次升级退化为「不清理旧文件」 */
2871
- }
2872
- // 记录安装来源:设置面板「更新」按钮据此重跑同一条安装命令(--force 覆盖)。
2541
+ } catch {}
2873
2542
  try {
2874
2543
  writeFileSync(join(target, ".pi-source.json"), JSON.stringify({ source: rawSpec }, null, 2) + "\n");
2875
- } catch {
2876
- /* 尽力而为:没有来源信息只是不显示更新按钮 */
2877
- }
2878
- // 记录本次安装的远端 sha(git ls-remote HEAD,离线也支持本地 git 源):
2879
- // 供 `pi-web-ui plugins --check-updates` 对比更新。失败静默(无 sha = 保守可更新)。
2544
+ } catch {}
2880
2545
  try {
2881
2546
  const sha = await resolveRemoteSha(rawSpec);
2882
2547
  if (sha) writeFileSync(join(target, ".pi-git-sha"), sha + "\n");
2883
- } catch {
2884
- /* 尽力而为 */
2885
- }
2548
+ } catch {}
2886
2549
  return { id, target, manifest, buildMode: decision.mode };
2887
2550
  } finally {
2888
- // 若当前 tmp 正在被 sharedCache 共享复用,不在此清理,留给批量操作统一释放
2889
2551
  let isCached = false;
2890
2552
  if (sharedCache) {
2891
2553
  for (const c of sharedCache.values()) {
@@ -2898,29 +2560,16 @@ async function installOnePlugin({
2898
2560
  if (!isCached) {
2899
2561
  try {
2900
2562
  rmSync(tmp, { recursive: true, force: true });
2901
- } catch {
2902
- /* Windows 等平台杀毒/进程占用可能抛 EBUSY,不应翻转已成功的安装 */
2903
- }
2563
+ } catch {}
2904
2564
  }
2905
2565
  }
2906
2566
  }
2907
2567
 
2908
- /**
2909
- * 目录文档校验(issue #165 的 CLI --catalog)。
2910
- *
2911
- * 规则与 server/plugin-catalog.ts 的 toEntry 对齐(id 字符集、source 形状、字段裁剪),
2912
- * 仅放宽一条:CLI 跑在使用者的本机信任上下文里,允许已存在的本地目录源(离线开发、
2913
- * 本地目录同步);服务端 toEntry(网络/插件触发)仍只收远端源。两边规则若漂移,
2914
- * tests/plugin-catalog-cli-test.mjs 的行为断言会先响(离线全链路)。
2915
- */
2916
2568
  function isCatalogEntrySource(s) {
2917
2569
  if (!s || s.length > 300) return false;
2918
- // 本地目录:CLI 才放行(存在性检查,file:// 前缀兼容 install 单源写法)
2919
2570
  try {
2920
2571
  if (existsSync(resolve(s.replace(/^file:\/\//, "")))) return true;
2921
- } catch {
2922
- /* 非法路径字符:走下面的远端规则 */
2923
- }
2572
+ } catch {}
2924
2573
  if (/^https?:\/\//.test(s)) return true;
2925
2574
  const spec = s.split("#")[0].replace(/\/+$/, "");
2926
2575
  const segs = spec.split("/").filter(Boolean);
@@ -2938,9 +2587,7 @@ function deriveCatalogEntryId(rawId, source) {
2938
2587
  const cleaned = base.replace(/[^A-Za-z0-9_-]/g, "-").replace(/^-+|-+$/g, "");
2939
2588
  return cleaned || "plugin";
2940
2589
  }
2941
- } catch {
2942
- /* 走远端规则 */
2943
- }
2590
+ } catch {}
2944
2591
  const spec = source.split("#")[0].replace(/\/+$/, "");
2945
2592
  const segs = spec.split("/").filter(Boolean);
2946
2593
  const last = segs.length >= 2 ? segs[segs.length - 1] : (segs[0] ?? "plugin");
@@ -2971,7 +2618,6 @@ function catalogEntryFromRaw(raw) {
2971
2618
  };
2972
2619
  }
2973
2620
 
2974
- /** 目录文档形状:JSON 数组或 {entries:[...]};非法条目丢弃并计数(与服务端同语义)。 */
2975
2621
  function normalizeCatalogEntries(raw) {
2976
2622
  const list = Array.isArray(raw)
2977
2623
  ? raw
@@ -2994,7 +2640,6 @@ function normalizeCatalogEntries(raw) {
2994
2640
  return { entries, skipped };
2995
2641
  }
2996
2642
 
2997
- /** 读目录文档:http(s) 拉取(30s 超时),其余当本地绝对路径(与服务端同口径)。 */
2998
2643
  async function readCatalogDocumentText(source) {
2999
2644
  const src = String(source ?? "").trim();
3000
2645
  if (!src)
@@ -3036,9 +2681,7 @@ function readCatalogFileEntries(customPath) {
3036
2681
  try {
3037
2682
  const raw = JSON.parse(readFileSync(customPath, "utf8"));
3038
2683
  if (raw && typeof raw === "object" && Array.isArray(raw.entries)) return raw.entries;
3039
- } catch {
3040
- /* 无文件/坏文件 = 空列表 */
3041
- }
2684
+ } catch {}
3042
2685
  return [];
3043
2686
  }
3044
2687
 
@@ -3049,7 +2692,6 @@ function writeCatalogFileEntries(customPath, entries) {
3049
2692
  renameSync(tmp, customPath);
3050
2693
  }
3051
2694
 
3052
- /** install --catalog <url>:同步可安装列表 + 逐条安装/更新(单条失败不中断整批)。 */
3053
2695
  async function installCatalogCmd(opts) {
3054
2696
  const dataDir = pluginDataDir(opts);
3055
2697
  const customPath = join(dataDir, "plugin-catalog.json");
@@ -3068,7 +2710,6 @@ async function installCatalogCmd(opts) {
3068
2710
  } catch (err) {
3069
2711
  fail(`${err?.message ?? err}`);
3070
2712
  }
3071
- // 到这里才动磁盘:形状不对的文档绝不覆盖有效列表(与服务端同纪律)。
3072
2713
  if (opts.replace) {
3073
2714
  writeCatalogFileEntries(customPath, entries);
3074
2715
  } else {
@@ -3123,7 +2764,6 @@ async function installCatalogCmd(opts) {
3123
2764
  }
3124
2765
  }
3125
2766
  } finally {
3126
- // 统一清理同批任务复用的共享缓存检出目录
3127
2767
  for (const entry of sharedCache.values()) {
3128
2768
  if (entry.tmpDir) {
3129
2769
  try {
@@ -3140,20 +2780,14 @@ async function installCatalogCmd(opts) {
3140
2780
  if (failCount) process.exitCode = 1;
3141
2781
  }
3142
2782
 
3143
- // ---------------------------------------------------------------------------
3144
- // 插件脚手架(plugin create):生成最小可跑骨架
3145
- // 形态 = <dataDir>/plugins/<id>/(manifest.json + index.mjs + client/entry.mjs),
3146
- // 与 server/plugins.ts 的加载约定对齐;官方插件(plugins/demo-mailbox 等)可作参考。
3147
- // ---------------------------------------------------------------------------
3148
-
3149
- /** 脚手架模板:minimal(零权限)| ui-slot | agent-tool | renderer(view:false)。 */
3150
2783
  const PLUGIN_TEMPLATES = ["minimal", "ui-slot", "agent-tool", "renderer"];
3151
2784
 
3152
- /** 随包发布的 plugin-sdk 文件:`index.mjs`(入口)+ `client-utils.mjs`(`index.mjs` 末尾
3153
- * `export * from "./client-utils.mjs"`;**少一份连服务端 import 都会 ERR_MODULE_NOT_FOUND**)。*/
3154
- const PLUGIN_SDK_FILES = ["index.mjs", "client-utils.mjs"];
2785
+ const PLUGIN_SDK_FILES = ["index.mjs", "client.mjs", "client-utils.mjs", "testing.mjs"];
2786
+
2787
+ const PLUGIN_SDK_CLIENT_FILES = ["client.mjs", "client-utils.mjs"];
2788
+
2789
+ const CLIENT_SDK_INDEX_COMPAT = `export * from "./client.mjs";\n`;
3155
2790
 
3156
- /** 包内 plugin-sdk 文件清单(随包发布,见 package.json files);缺任一 = 包不完整,按「无 SDK」处理。 */
3157
2791
  function pluginSdkSources() {
3158
2792
  const dir = join(BIN_DIR, "..", "plugin-sdk");
3159
2793
  const files = [];
@@ -3165,12 +2799,27 @@ function pluginSdkSources() {
3165
2799
  return files;
3166
2800
  }
3167
2801
 
3168
- function copySdkInto(dir, sources) {
2802
+ function copyServerSdkInto(dir, sources) {
2803
+ mkdirSync(dir, { recursive: true });
2804
+ const map = new Map(sources.map((s) => [s.name, s.src]));
2805
+ for (const name of PLUGIN_SDK_FILES) {
2806
+ const src = map.get(name);
2807
+ if (src && existsSync(src)) copyFileSync(src, join(dir, name));
2808
+ }
2809
+ }
2810
+
2811
+ function copyClientSdkInto(dir, sources) {
3169
2812
  mkdirSync(dir, { recursive: true });
3170
- for (const { name, src } of sources) copyFileSync(src, join(dir, name));
2813
+ const map = new Map(sources.map((s) => [s.name, s.src]));
2814
+ for (const name of PLUGIN_SDK_CLIENT_FILES) {
2815
+ const src = map.get(name);
2816
+ if (src && existsSync(src)) copyFileSync(src, join(dir, name));
2817
+ }
2818
+ writeFileSync(join(dir, "index.mjs"), CLIENT_SDK_INDEX_COMPAT);
2819
+ const testFile = join(dir, "testing.mjs");
2820
+ if (existsSync(testFile)) rmSync(testFile, { force: true });
3171
2821
  }
3172
2822
 
3173
- /** 各模板的 manifest.description(一句话说明骨架来源)。 */
3174
2823
  function scaffoldDescription(template) {
3175
2824
  switch (template) {
3176
2825
  case "ui-slot":
@@ -3184,18 +2833,13 @@ function scaffoldDescription(template) {
3184
2833
  }
3185
2834
  }
3186
2835
 
3187
- /** 模板的客户端是否 import SDK:**除 renderer 外都 import `./sdk/index.mjs`**(renderer 渲染器走裸 ESM)。
3188
- * 决定 `client/sdk/` 要不要拷、README 怎么写;拷完还用 import-check 复验(模板以后改了也不漏)。 */
3189
2836
  function templateClientUsesSdk(template) {
3190
2837
  return template !== "renderer";
3191
2838
  }
3192
2839
 
3193
- /** 拼骨架文件:{ 相对路径: 内容 }。useSdk=false 时走无 SDK 导入的等价写法。
3194
- * withTest=true(且 useSdk)时多带 index.test.mjs(node --test + createMockHost 最小单测)。 */
3195
2840
  function buildPluginScaffold(id, template, useSdk, withTest = false) {
3196
2841
  const sdkServer = useSdk ? `import { definePlugin } from "./sdk/index.mjs";\n\n` : "";
3197
- // 客户端 import 必须落在 client/ 内:宿主只暴露 /plugins/<id>/client/*(见 import-check)。
3198
- const sdkClient = useSdk ? `import { defineView, onUiAction } from "./sdk/index.mjs";\n\n` : "";
2842
+ const sdkClient = useSdk ? `import { defineView, onUiAction } from "./sdk/client.mjs";\n\n` : "";
3199
2843
  const wrapServer = (body) =>
3200
2844
  useSdk ? `${sdkServer}export default definePlugin({\n${body}\n});\n` : `export default {\n${body}\n};\n`;
3201
2845
  const wrapClient = (body) =>
@@ -3210,8 +2854,6 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3210
2854
  version: "0.1.0",
3211
2855
  description: scaffoldDescription(template),
3212
2856
  apiVersion: 2,
3213
- // apiVersion 2 **必须**声明 permissions(缺字段 = 宿主直接拒激活,issue #546 现场顺带发现):
3214
- // 模板按需覆写(ui-slot → ["ui"]、agent-tool → ["tools"]),零能力的就是空数组。
3215
2857
  permissions: [],
3216
2858
  };
3217
2859
 
@@ -3335,7 +2977,6 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3335
2977
  `\t\t};\n` +
3336
2978
  `\t},`,
3337
2979
  );
3338
- // 渲染器走裸 ESM(命中围栏才懒加载):默认导出 { renderers },不用 defineView。
3339
2980
  clientJs =
3340
2981
  `/**\n` +
3341
2982
  ` * ${id} —— fenced-code 渲染器(pi-web-ui plugin create 生成)。\n` +
@@ -3378,13 +3019,13 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3378
3019
  `- \`index.mjs\` —— 服务端入口(\`export default { activate(host) }\`)\n` +
3379
3020
  `- \`client/entry.mjs\` —— 客户端视图${template === "renderer" ? "(渲染器:`{ renderers }`)" : "(`{ mount }`)"}\n` +
3380
3021
  (useSdk
3381
- ? `- \`sdk/index.mjs\` + \`sdk/client-utils.mjs\` —— plugin-sdk 拷贝(服务端用:definePlugin/defineView/onUiAction)\n`
3022
+ ? `- \`sdk/\` —— 服务端 plugin-sdk 拷贝(\`index.mjs\`、\`client.mjs\`、\`client-utils.mjs\`、\`testing.mjs\`;\`index.mjs\` 为服务端总入口)\n`
3382
3023
  : "") +
3383
3024
  (useSdk && templateClientUsesSdk(template)
3384
- ? `- \`client/sdk/\` —— 同一份 SDK 的**客户端**拷贝:宿主只暴露 \`/plugins/<id>/client/*\`,客户端依赖必须落在 \`client/\` 内(\`client/entry.mjs\` 只能 \`import "./sdk/index.mjs"\`)\n`
3025
+ ? `- \`client/sdk/\` —— 客户端 plugin-sdk 拷贝(仅 \`client.mjs\`、\`client-utils.mjs\` 及兼容入口 \`index.mjs\`):宿主只暴露 \`/plugins/<id>/client/*\`,客户端依赖必须落在 \`client/\` 内(新模板使用 \`import "./sdk/client.mjs"\`)\n`
3385
3026
  : "") +
3386
3027
  (withTest && useSdk
3387
- ? "- `index.test.mjs` —— 最小单测(`node --test index.test.mjs`,createMockHost harness)\n"
3028
+ ? "- `index.test.mjs` —— 最小单测(`node --test index.test.mjs`,从 `./sdk/testing.mjs` 导入 createMockHost harness)\n"
3388
3029
  : "") +
3389
3030
  `\n` +
3390
3031
  `## 下一步\n` +
@@ -3408,7 +3049,6 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3408
3049
  "README.md": readme,
3409
3050
  };
3410
3051
  if (withTest && useSdk) {
3411
- // 最小单测:四个模板的 activate 都会 host.log("activated"),断言与模板无关。
3412
3052
  out["index.test.mjs"] =
3413
3053
  `/**\n` +
3414
3054
  ` * ${id} —— 最小单测(pi-web-ui plugin create --with-test 生成)。\n` +
@@ -3417,7 +3057,7 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3417
3057
  `import { describe, it } from "node:test";\n` +
3418
3058
  `import assert from "node:assert/strict";\n` +
3419
3059
  `import plugin from "./index.mjs";\n` +
3420
- `import { createMockHost } from "./sdk/index.mjs";\n` +
3060
+ `import { createMockHost } from "./sdk/testing.mjs";\n` +
3421
3061
  `\n` +
3422
3062
  `describe("${id} activate", () => {\n` +
3423
3063
  `\tit("激活不抛错,且调了 host 方法", async () => {\n` +
@@ -3444,7 +3084,6 @@ function buildPluginScaffold(id, template, useSdk, withTest = false) {
3444
3084
  return out;
3445
3085
  }
3446
3086
 
3447
- /** 生成后的 manifest 基础校验(必填/口径);返回 warnings(无则空数组)。 */
3448
3087
  function validateScaffoldManifest(manifest, dirName) {
3449
3088
  const warnings = [];
3450
3089
  for (const k of ["id", "name", "version", "description"]) {
@@ -3481,8 +3120,6 @@ function validateScaffoldManifest(manifest, dirName) {
3481
3120
  : `manifest.permissions must be a string array (e.g. ["ui"])`,
3482
3121
  );
3483
3122
  }
3484
- // 与宿主同口径(server/plugin-manifest-validate.ts):apiVersion 2 必须有 permissions 字段,
3485
- // 缺失 = 扫到就报错误、插件被拒(零能力也写 [])—— 骨架曾经漏写,装上去才发现。
3486
3123
  if (manifest.apiVersion === 2 && manifest.permissions === undefined)
3487
3124
  warnings.push(
3488
3125
  ZH
@@ -3499,53 +3136,48 @@ function validateScaffoldManifest(manifest, dirName) {
3499
3136
  return warnings;
3500
3137
  }
3501
3138
 
3502
- /** 已装插件的 sdk/index.mjs 里解析 SDK_VERSION(老拷贝无此常量 → null,即未知旧版)。 */
3503
- function installedSdkVersion(sdkFile) {
3139
+ function installedSdkVersion(dirOrFile) {
3504
3140
  try {
3505
- const src = readFileSync(sdkFile, "utf8");
3506
- const m = src.match(/SDK_VERSION\s*=\s*["']([^"']+)["']/);
3507
- return m ? m[1] : null;
3141
+ const isDir = statSync(dirOrFile).isDirectory();
3142
+ const dir = isDir ? dirOrFile : dirname(dirOrFile);
3143
+ for (const name of ["client.mjs", "index.mjs"]) {
3144
+ const file = join(dir, name);
3145
+ if (existsSync(file)) {
3146
+ const src = readFileSync(file, "utf8");
3147
+ const m = src.match(/SDK_VERSION\s*=\s*["']([^"']+)["']/);
3148
+ if (m) return m[1];
3149
+ }
3150
+ }
3151
+ return null;
3508
3152
  } catch {
3509
3153
  return null;
3510
3154
  }
3511
3155
  }
3512
3156
 
3513
- /** 包内 SDK 版本(单源:plugin-sdk/index.mjs 的 `export const SDK_VERSION`)。 */
3514
3157
  function packageSdkVersion() {
3515
3158
  const sources = pluginSdkSources();
3516
- const sdkSrc = sources?.find((f) => f.name === "index.mjs")?.src;
3517
- if (!sdkSrc)
3159
+ if (!sources) {
3518
3160
  fail(
3519
- ZH
3520
- ? `包内无 plugin-sdk(找不到 plugin-sdk/index.mjs),无法刷新`
3521
- : `No plugin-sdk in package (plugin-sdk/index.mjs not found), cannot refresh`,
3522
- );
3523
- let src;
3524
- try {
3525
- src = readFileSync(sdkSrc, "utf8");
3526
- } catch {
3527
- fail(
3528
- ZH
3529
- ? `包内 plugin-sdk/index.mjs 不可读,无法刷新`
3530
- : `plugin-sdk/index.mjs in package is unreadable, cannot refresh`,
3161
+ ZH ? `包内无完整 plugin-sdk(缺少必要 SDK 文件),无法刷新` : `No complete plugin-sdk in package, cannot refresh`,
3531
3162
  );
3532
3163
  }
3533
- const m = src.match(/export const SDK_VERSION\s*=\s*["']([^"']+)["']/);
3534
- if (!m)
3535
- fail(
3536
- ZH
3537
- ? `包内 plugin-sdk/index.mjs 无 SDK_VERSION 导出,无法刷新(请升级 pi-web-ui)`
3538
- : `plugin-sdk/index.mjs in package has no SDK_VERSION export, cannot refresh (please upgrade pi-web-ui)`,
3539
- );
3540
- return { version: m[1], file: sdkSrc, sources };
3541
- }
3542
-
3543
- /** 插件目录里现存的 SDK 拷贝目录:服务端用 `sdk/`,客户端用 `client/sdk/`(两份都要刷)。 */
3544
- function pluginSdkDirs(pluginDir) {
3545
- return [join(pluginDir, "sdk"), join(pluginDir, "client", "sdk")].filter((d) => existsSync(d));
3164
+ const clientSrc = sources.find((f) => f.name === "client.mjs")?.src;
3165
+ const indexSrc = sources.find((f) => f.name === "index.mjs")?.src;
3166
+ for (const candidate of [clientSrc, indexSrc]) {
3167
+ if (!candidate || !existsSync(candidate)) continue;
3168
+ try {
3169
+ const src = readFileSync(candidate, "utf8");
3170
+ const m = src.match(/export const SDK_VERSION\s*=\s*["']([^"']+)["']/);
3171
+ if (m) return { version: m[1], file: candidate, sources };
3172
+ } catch {}
3173
+ }
3174
+ fail(
3175
+ ZH
3176
+ ? `包内 plugin-sdk 无 SDK_VERSION 导出,无法刷新(请升级 pi-web-ui)`
3177
+ : `plugin-sdk in package has no SDK_VERSION export, cannot refresh (please upgrade pi-web-ui)`,
3178
+ );
3546
3179
  }
3547
3180
 
3548
- /** 静态 import 自检问题的双语文案(create / upgrade-sdk 共用)。 */
3549
3181
  function importProblemText(p) {
3550
3182
  if (p.kind === "escapes-client")
3551
3183
  return ZH
@@ -3556,7 +3188,6 @@ function importProblemText(p) {
3556
3188
  : `${p.file}: import "${p.spec}" target does not exist (${p.target}) — typo, or a missing vendored dependency?`;
3557
3189
  }
3558
3190
 
3559
- /** 懒加载 import-check(随包发布,但裁剪包可能没有 → 跳自检而不是崩)。 */
3560
3191
  let importCheckModule;
3561
3192
  async function loadImportCheck() {
3562
3193
  if (importCheckModule === undefined) {
@@ -3565,7 +3196,6 @@ async function loadImportCheck() {
3565
3196
  return importCheckModule;
3566
3197
  }
3567
3198
 
3568
- /** 刷新已装插件的 SDK 拷贝(服务端 `sdk/` + 客户端 `client/sdk/`,版本/文件对不上才拷)。 */
3569
3199
  async function pluginUpgradeSdkCmd(argv) {
3570
3200
  const { opts, positionals } = parseFlags(argv);
3571
3201
  if (opts.help || positionals.length > 1) {
@@ -3601,43 +3231,86 @@ async function pluginUpgradeSdkCmd(argv) {
3601
3231
  const broken = [];
3602
3232
  for (const id of targets) {
3603
3233
  const pluginDir = join(parentDir, id);
3604
- let dirs = pluginSdkDirs(pluginDir);
3605
- if (dirs.length === 0) {
3234
+ const serverSdkDir = join(pluginDir, "sdk");
3235
+ const clientSdkDir = join(pluginDir, "client", "sdk");
3236
+ const hasServerSdk = existsSync(serverSdkDir);
3237
+ const hasClientSdk = existsSync(clientSdkDir);
3238
+
3239
+ let wantsClientSdk = false;
3240
+ if (!hasClientSdk) {
3241
+ wantsClientSdk =
3242
+ importCheck?.scanPluginImports(pluginDir).some((r) => r.client && r.target.startsWith("client/sdk/")) ?? false;
3243
+ }
3244
+
3245
+ if (!hasServerSdk && !hasClientSdk && !wantsClientSdk) {
3606
3246
  skipped++;
3607
3247
  console.log(ZH ? `- ${id}:无 sdk/ 拷贝,跳过` : `- ${id}: no sdk/ copy, skipping`);
3608
3248
  continue;
3609
3249
  }
3610
- // 客户端侧缺失但代码确实 import ./sdk/ → 补建(修好 issue #546 之前生成的插件)。
3611
- if (!existsSync(join(pluginDir, "client", "sdk"))) {
3612
- const wantsClientSdk =
3613
- importCheck?.scanPluginImports(pluginDir).some((r) => r.client && r.target.startsWith("client/sdk/")) ?? false;
3614
- if (wantsClientSdk) {
3615
- dirs = [...dirs, join(pluginDir, "client", "sdk")];
3616
- healed.push(id);
3617
- }
3250
+
3251
+ let serverStale = false;
3252
+ if (hasServerSdk) {
3253
+ const missingFiles = PLUGIN_SDK_FILES.some((name) => !existsSync(join(serverSdkDir, name)));
3254
+ const ver = installedSdkVersion(serverSdkDir);
3255
+ serverStale = missingFiles || ver !== latest;
3256
+ }
3257
+
3258
+ let clientStale = false;
3259
+ if (wantsClientSdk) {
3260
+ clientStale = true;
3261
+ healed.push(id);
3262
+ } else if (hasClientSdk) {
3263
+ const missingFiles = PLUGIN_SDK_CLIENT_FILES.some((name) => !existsSync(join(clientSdkDir, name)));
3264
+ const ver = installedSdkVersion(clientSdkDir);
3265
+ const compatFile = join(clientSdkDir, "index.mjs");
3266
+ const compatOk =
3267
+ existsSync(compatFile) && readFileSync(compatFile, "utf8").trim() === CLIENT_SDK_INDEX_COMPAT.trim();
3268
+ const hasTestingResidual = existsSync(join(clientSdkDir, "testing.mjs"));
3269
+ clientStale = missingFiles || ver !== latest || !compatOk || hasTestingResidual;
3618
3270
  }
3619
- const stale =
3620
- dirs.some((d) => PLUGIN_SDK_FILES.some((name) => !existsSync(join(d, name)))) ||
3621
- installedSdkVersion(join(dirs[0], "index.mjs")) !== latest;
3622
- if (!stale) {
3271
+
3272
+ if (!serverStale && !clientStale) {
3623
3273
  fresh++;
3624
3274
  console.log(ZH ? `✔ ${id}:已是最新(SDK ${latest})` : `✔ ${id}: already up to date (SDK ${latest})`);
3625
3275
  continue;
3626
3276
  }
3627
- const cur = installedSdkVersion(join(dirs[0], "index.mjs"));
3628
- for (const d of dirs) copySdkInto(d, sources);
3629
- const bad = dirs.filter(
3630
- (d) => spawnSync(NODE, ["--check", join(d, "index.mjs")], { stdio: "ignore" }).status !== 0,
3631
- );
3632
- if (bad.length > 0)
3277
+
3278
+ const cur =
3279
+ (hasServerSdk ? installedSdkVersion(serverSdkDir) : null) ??
3280
+ (hasClientSdk ? installedSdkVersion(clientSdkDir) : null);
3281
+
3282
+ const updatedDirs = [];
3283
+ if (hasServerSdk) {
3284
+ copyServerSdkInto(serverSdkDir, sources);
3285
+ updatedDirs.push(serverSdkDir);
3286
+ }
3287
+ if (hasClientSdk || wantsClientSdk) {
3288
+ copyClientSdkInto(clientSdkDir, sources);
3289
+ updatedDirs.push(clientSdkDir);
3290
+ }
3291
+
3292
+ const bad = [];
3293
+ for (const d of updatedDirs) {
3294
+ const isClientDir = d === clientSdkDir;
3295
+ const checkFiles = isClientDir ? ["index.mjs", "client.mjs"] : ["index.mjs", "client.mjs", "testing.mjs"];
3296
+ for (const f of checkFiles) {
3297
+ const full = join(d, f);
3298
+ if (existsSync(full)) {
3299
+ const r = spawnSync(NODE, ["--check", full], { stdio: "ignore" });
3300
+ if (r.status !== 0) bad.push(full);
3301
+ }
3302
+ }
3303
+ }
3304
+
3305
+ if (bad.length > 0) {
3633
3306
  broken.push(
3634
3307
  ZH
3635
3308
  ? `${bad.join("、")} 未通过 node --check(磁盘/权限异常?请手动检查)`
3636
3309
  : `${bad.join(", ")} failed node --check (disk/permission issue? please check manually)`,
3637
3310
  );
3638
- else {
3311
+ } else {
3639
3312
  upgraded++;
3640
- const where = dirs.map((d) => (d === join(pluginDir, "sdk") ? "sdk/" : "client/sdk/")).join(" + ");
3313
+ const where = updatedDirs.map((d) => (d === serverSdkDir ? "sdk/" : "client/sdk/")).join(" + ");
3641
3314
  console.log(
3642
3315
  ZH
3643
3316
  ? `✔ ${id}:SDK ${cur ?? "未知旧版"} → ${latest}(${where})`
@@ -3652,7 +3325,6 @@ async function pluginUpgradeSdkCmd(argv) {
3652
3325
  : ` ↳ ${id}: created the missing client/sdk/ (needed by the client-side ./sdk/ import)`,
3653
3326
  );
3654
3327
  for (const w of broken) console.log(`⚠ ${w}`);
3655
- // 顺带自检 import 越界/缺失(issue #546:客户端越界会让插件页整页空白,而服务端看不出来)。
3656
3328
  if (importCheck) {
3657
3329
  for (const id of targets) {
3658
3330
  for (const p of importCheck.checkPluginImports(join(parentDir, id)).problems)
@@ -3700,17 +3372,14 @@ async function pluginCreateCmd(argv) {
3700
3372
  const useSdk = Boolean(sdkSources);
3701
3373
  const wantTest = opts.withTest === true;
3702
3374
  const files = buildPluginScaffold(id, template, useSdk, wantTest && useSdk);
3703
- if (useSdk) copySdkInto(join(target, "sdk"), sdkSources);
3375
+ if (useSdk) copyServerSdkInto(join(target, "sdk"), sdkSources);
3704
3376
  for (const [rel, content] of Object.entries(files)) writeFileSync(join(target, rel), content);
3705
- // 客户端侧的相对依赖必须落在 client/ 内(宿主只暴露 /plugins/<id>/client/*):生成文件里
3706
- // 引到 client/ 内的 SDK 就把 SDK 也拷进 client/sdk/(renderer 模板客户端不用 SDK,不白拷)。
3707
3377
  const importCheck = await loadImportCheck();
3708
- if (useSdk && importCheck) {
3709
- // 模板按约定先拷(renderer 除外),再用扫描复验一遍 —— 模板以后加了客户端 SDK 引用也不会漏。
3710
- const scanned = importCheck.scanPluginImports(target).some((r) => r.client && r.target.startsWith("client/sdk/"));
3711
- if (templateClientUsesSdk(template) || scanned) copySdkInto(join(target, "client", "sdk"), sdkSources);
3378
+ if (useSdk) {
3379
+ const scanned =
3380
+ importCheck?.scanPluginImports(target).some((r) => r.client && r.target.startsWith("client/sdk/")) ?? false;
3381
+ if (templateClientUsesSdk(template) || scanned) copyClientSdkInto(join(target, "client", "sdk"), sdkSources);
3712
3382
  }
3713
- // 生成后校验:manifest 基础必填 + 生成文件的 node 语法检查 + 静态 import 自检。
3714
3383
  let manifest;
3715
3384
  try {
3716
3385
  manifest = JSON.parse(readFileSync(join(target, "manifest.json"), "utf8"));
@@ -3739,8 +3408,6 @@ async function pluginCreateCmd(argv) {
3739
3408
  : `${rel} failed node --check (please check generated files)`,
3740
3409
  );
3741
3410
  }
3742
- // 静态 import 自检(issue #546):客户端越界 / 目标缺失都会让插件在浏览器里整页空白,
3743
- // 而服务端看不出来 —— 在脚手架阶段就报出来。
3744
3411
  if (importCheck) {
3745
3412
  const { problems } = importCheck.checkPluginImports(target);
3746
3413
  for (const p of problems) warnings.push(importProblemText(p));
@@ -3780,8 +3447,6 @@ async function pluginInstallCmd(argv) {
3780
3447
  console.log(PLUGIN_HELP);
3781
3448
  return;
3782
3449
  }
3783
- // 目录同步模式(issue #165):install --catalog <url> —— 读目录文档 → 校验 →
3784
- // 原子写盘 → 逐条安装/更新(与服务端 plugin-catalog-sync 同语义)。
3785
3450
  if (opts.catalog !== undefined) {
3786
3451
  if (positionals.length !== 0)
3787
3452
  fail(
@@ -3875,7 +3540,6 @@ function pluginListCmd(argv) {
3875
3540
  return;
3876
3541
  }
3877
3542
  const dataDir = pluginDataDir(opts);
3878
- // --rollback <id>:回滚到最近一份更新前备份
3879
3543
  if (opts.rollback) {
3880
3544
  const id = String(opts.rollback);
3881
3545
  if (!PLUGIN_ID_RE.test(id)) fail(ZH ? `非法插件 id: ${id}` : `Invalid plugin id: ${id}`);
@@ -3900,7 +3564,6 @@ function pluginListCmd(argv) {
3900
3564
  );
3901
3565
  return;
3902
3566
  }
3903
- // --check-updates:对比各插件记录的最后安装 sha 与远端 HEAD(git ls-remote)
3904
3567
  if (opts.checkUpdates) {
3905
3568
  return checkUpdatesCmd(dataDir).then(() => {});
3906
3569
  }
@@ -3909,9 +3572,7 @@ function pluginListCmd(argv) {
3909
3572
  let names = [];
3910
3573
  try {
3911
3574
  names = readdirSync(pluginsDir).sort();
3912
- } catch {
3913
- /* 目录不存在 = 未安装任何插件 */
3914
- }
3575
+ } catch {}
3915
3576
  for (const n of names) {
3916
3577
  if (!PLUGIN_ID_RE.test(n)) continue;
3917
3578
  try {
@@ -3920,7 +3581,7 @@ function pluginListCmd(argv) {
3920
3581
  ` ${n.padEnd(24)} ${[m.name, m.version ? `v${m.version}` : "", m.description].filter(Boolean).join(" ")}`,
3921
3582
  );
3922
3583
  } catch {
3923
- continue; // 坏目录跳过
3584
+ continue;
3924
3585
  }
3925
3586
  }
3926
3587
  if (rows.length === 0) {
@@ -4143,16 +3804,35 @@ async function main() {
4143
3804
  pluginListCmd(argv.slice(1));
4144
3805
  return;
4145
3806
  }
4146
- // One-shot server with optional --port/--cwd/--data-dir overrides.
4147
3807
  const { opts, positionals } = parseFlags(argv);
4148
3808
  if (opts.help) {
4149
3809
  console.log(HELP);
4150
3810
  return;
4151
3811
  }
4152
- if (positionals.length > 0)
3812
+ if (positionals.length > 1)
4153
3813
  fail(
4154
- ZH ? `未知命令: ${positionals[0]}(--help 查看用法)` : `Unknown command: ${positionals[0]} (--help for usage)`,
3814
+ ZH
3815
+ ? `未知命令: ${positionals.join(" ")}(--help 查看用法)`
3816
+ : `Unknown command: ${positionals.join(" ")} (--help for usage)`,
4155
3817
  );
3818
+ if (positionals.length === 1) {
3819
+ if (opts.cwd !== undefined) {
3820
+ fail(ZH ? "目录参数不能与 --cwd 同时使用" : "Cannot combine a directory argument with --cwd");
3821
+ }
3822
+ const cwd = resolve(positionals[0]);
3823
+ let isDirectory = false;
3824
+ try {
3825
+ isDirectory = statSync(cwd).isDirectory();
3826
+ } catch {}
3827
+ if (!isDirectory) {
3828
+ fail(
3829
+ ZH
3830
+ ? `目录不存在或不可访问: ${positionals[0]}`
3831
+ : `Directory does not exist or is inaccessible: ${positionals[0]}`,
3832
+ );
3833
+ }
3834
+ opts.cwd = cwd;
3835
+ }
4156
3836
  await startForeground(opts);
4157
3837
  }
4158
3838