pi-web-ui 0.117.0 → 0.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (512) hide show
  1. package/CHANGELOG.md +48 -2
  2. package/README.md +69 -138
  3. package/README.zh-CN.md +70 -179
  4. package/README.zh-TW.md +3 -1
  5. package/bin/device-hub-cli.mjs +147 -43
  6. package/bin/frp-manager.mjs +4 -80
  7. package/bin/hub-upgrade.mjs +561 -0
  8. package/bin/pi-device-hub.mjs +0 -1
  9. package/bin/pi-web-ui.mjs +56 -444
  10. package/deploy/nginx-subpath.conf +0 -33
  11. package/deploy/pi-web-ui.service +0 -20
  12. package/dist/server/agent-formatters.js +4 -38
  13. package/dist/server/agent-service-daemon.js +160 -374
  14. package/dist/server/agent-service.js +875 -2978
  15. package/dist/server/approval-audit.js +2 -23
  16. package/dist/server/approval-default-rules.js +0 -6
  17. package/dist/server/approval-rules.js +7 -105
  18. package/dist/server/ask-user-question-tool.js +1 -12
  19. package/dist/server/atomic-file.js +33 -5
  20. package/dist/server/attachment-store.js +0 -36
  21. package/dist/server/attachments.js +3 -112
  22. package/dist/server/auth-cookie.js +0 -21
  23. package/dist/server/bash-tool.js +1 -32
  24. package/dist/server/bg-servers.js +0 -96
  25. package/dist/server/browser-page-tool.js +11 -62
  26. package/dist/server/builtin-modules.js +7 -0
  27. package/dist/server/canvas/canvas-agent-tool.js +58 -47
  28. package/dist/server/canvas/canvas-cards.js +0 -14
  29. package/dist/server/canvas/canvas-dispatch.js +7 -4
  30. package/dist/server/canvas/canvas-orchestrator.js +167 -181
  31. package/dist/server/canvas/canvas-runtime-messages.js +30 -0
  32. package/dist/server/canvas/canvas-scheduled-task.js +0 -3
  33. package/dist/server/canvas/canvas-scheduler.js +5 -7
  34. package/dist/server/canvas/canvas-store.js +24 -35
  35. package/dist/server/canvas/canvas-validation.js +17 -14
  36. package/dist/server/canvas/canvas-workspace.js +26 -30
  37. package/dist/server/canvas/pstack-skills-data.js +0 -5
  38. package/dist/server/claim-files-tool.js +1 -15
  39. package/dist/server/claim-store.js +5 -49
  40. package/dist/server/client-id-utils.js +0 -16
  41. package/dist/server/client-state.js +6 -213
  42. package/dist/server/communicate-tool.js +0 -3
  43. package/dist/server/compact-context-tool.js +0 -30
  44. package/dist/server/compacted-history.js +0 -35
  45. package/dist/server/compaction-instructions.js +0 -13
  46. package/dist/server/compaction-markers.js +3 -76
  47. package/dist/server/compaction-state.js +0 -21
  48. package/dist/server/composer-drafts.js +0 -34
  49. package/dist/server/context-budget-runner.js +0 -11
  50. package/dist/server/context-budget.js +1 -70
  51. package/dist/server/context-evidence.js +0 -14
  52. package/dist/server/context-usage.js +0 -12
  53. package/dist/server/control-socket.js +4 -48
  54. package/dist/server/conversation-communication.js +0 -10
  55. package/dist/server/conversation-identity.js +0 -1
  56. package/dist/server/conversation-read-tool.js +0 -58
  57. package/dist/server/conversation-tool-names.js +0 -1
  58. package/dist/server/conversation-tool.js +0 -1
  59. package/dist/server/conversation-touches.js +4 -75
  60. package/dist/server/dangling-tools.js +0 -82
  61. package/dist/server/delegate-mode.js +0 -36
  62. package/dist/server/delegate-task.js +2 -28
  63. package/dist/server/device-center/approval-summary.js +0 -1
  64. package/dist/server/device-center/bot-catalog.js +0 -3
  65. package/dist/server/device-center/bot-execution.js +0 -8
  66. package/dist/server/device-center/bot-presets.js +0 -1
  67. package/dist/server/device-center/bots.js +0 -1
  68. package/dist/server/device-center/collab-service.js +1 -3
  69. package/dist/server/device-center/collab-tool.js +0 -10
  70. package/dist/server/device-center/connector.js +21 -11
  71. package/dist/server/device-center/delivery-authority.js +0 -3
  72. package/dist/server/device-center/delivery-subject.js +0 -1
  73. package/dist/server/device-center/desktop-linux.js +3 -15
  74. package/dist/server/device-center/desktop-native.js +1 -10
  75. package/dist/server/device-center/desktop-page.js +2 -3
  76. package/dist/server/device-center/desktop-setup.js +1 -3
  77. package/dist/server/device-center/desktop.js +1 -7
  78. package/dist/server/device-center/device-integration.js +1 -27
  79. package/dist/server/device-center/device-lan-access.js +403 -0
  80. package/dist/server/device-center/device-lan.js +484 -0
  81. package/dist/server/device-center/device-portals.js +0 -3
  82. package/dist/server/device-center/execution-failure.js +0 -2
  83. package/dist/server/device-center/execution-guides.js +0 -1
  84. package/dist/server/device-center/execution-instructions.js +0 -1
  85. package/dist/server/device-center/execution-settings.js +0 -1
  86. package/dist/server/device-center/execution-system-prompt.js +0 -3
  87. package/dist/server/device-center/execution-workspace.js +1 -4
  88. package/dist/server/device-center/executor.js +0 -27
  89. package/dist/server/device-center/file-sync-paths.js +0 -5
  90. package/dist/server/device-center/file-sync.js +0 -10
  91. package/dist/server/device-center/group-context-delta.js +0 -8
  92. package/dist/server/device-center/group-context-message.js +0 -14
  93. package/dist/server/device-center/group-context.js +0 -19
  94. package/dist/server/device-center/group-events.js +0 -2
  95. package/dist/server/device-center/group-plan-guard.js +1 -35
  96. package/dist/server/device-center/group-router-runtime.js +182 -0
  97. package/dist/server/device-center/group-router-worker.js +178 -0
  98. package/dist/server/device-center/group-router.js +359 -0
  99. package/dist/server/device-center/hub-auth.js +24 -2
  100. package/dist/server/device-center/hub-conversations.js +0 -12
  101. package/dist/server/device-center/hub-deliveries.js +0 -1
  102. package/dist/server/device-center/hub-integration.js +0 -8
  103. package/dist/server/device-center/hub-locks.js +1 -5
  104. package/dist/server/device-center/hub-mobile.js +147 -0
  105. package/dist/server/device-center/hub-orchestration.js +400 -0
  106. package/dist/server/device-center/hub-page.js +25 -7
  107. package/dist/server/device-center/hub-setup.js +0 -6
  108. package/dist/server/device-center/hub-transaction-log.js +0 -22
  109. package/dist/server/device-center/hub-upgrade.js +162 -0
  110. package/dist/server/device-center/hub-webhooks.js +1 -3
  111. package/dist/server/device-center/hub.js +210 -86
  112. package/dist/server/device-center/human-interaction.js +1 -4
  113. package/dist/server/device-center/integration-errors.js +0 -2
  114. package/dist/server/device-center/integration-verification.js +0 -2
  115. package/dist/server/device-center/local-hub.js +0 -2
  116. package/dist/server/device-center/local-publication.js +1 -8
  117. package/dist/server/device-center/local-verification-job.js +0 -2
  118. package/dist/server/device-center/local-verification.js +0 -1
  119. package/dist/server/device-center/local.js +267 -39
  120. package/dist/server/device-center/main.js +14 -1
  121. package/dist/server/device-center/mobile-notification-forwarder.js +292 -0
  122. package/dist/server/device-center/native-desktop/macos.js +0 -1
  123. package/dist/server/device-center/native-desktop/windows.js +0 -1
  124. package/dist/server/device-center/partition-log.js +0 -31
  125. package/dist/server/device-center/path-portal.js +42 -12
  126. package/dist/server/device-center/publication-journal.js +0 -7
  127. package/dist/server/device-center/publish-intent.js +0 -5
  128. package/dist/server/device-center/relay.js +85 -30
  129. package/dist/server/device-center/report-upload.js +0 -1
  130. package/dist/server/device-center/runtime.js +1 -18
  131. package/dist/server/device-center/store.js +13 -33
  132. package/dist/server/device-center/task-context-budget.js +0 -3
  133. package/dist/server/device-center/task-error.js +0 -1
  134. package/dist/server/device-center/task-journal.js +6 -23
  135. package/dist/server/device-center/task-outcome.js +0 -13
  136. package/dist/server/device-center/task-plan.js +0 -1
  137. package/dist/server/device-center/task-progress.js +0 -16
  138. package/dist/server/device-center/task-recovery.js +5 -88
  139. package/dist/server/device-center/task-report-outbox.js +0 -4
  140. package/dist/server/device-center/task-report.js +2 -10
  141. package/dist/server/device-center/task-scheduler.js +1 -35
  142. package/dist/server/device-center/task-settlement.js +0 -18
  143. package/dist/server/device-center/task-state.js +0 -12
  144. package/dist/server/device-center/task-workspace.js +0 -50
  145. package/dist/server/device-center/transfer-stream.js +5 -45
  146. package/dist/server/device-center/transfers.js +2 -10
  147. package/dist/server/device-center/verification-limits.js +0 -1
  148. package/dist/server/device-center/work-contract.js +1 -73
  149. package/dist/server/device-center/work-items.js +317 -0
  150. package/dist/server/device-center/workspaces.js +0 -1
  151. package/dist/server/dispatch-domain-handlers.js +190 -32
  152. package/dist/server/dispatch-plugin-handlers.js +2 -19
  153. package/dist/server/dsh/dsh-agent-service.js +69 -599
  154. package/dist/server/dsh/dsh-client.js +7 -111
  155. package/dist/server/dsh/dsh-market-service.js +4 -25
  156. package/dist/server/dsh/dsh-serialize.js +0 -49
  157. package/dist/server/dsh/dsh-sessions.js +0 -37
  158. package/dist/server/dsh/dsh-usage.js +0 -37
  159. package/dist/server/dsh/preset-clones.js +1 -65
  160. package/dist/server/dsh/runtime/custom-prompt.mjs +0 -14
  161. package/dist/server/dsh/runtime/goal-rpc.mjs +7 -176
  162. package/dist/server/dsh/runtime/launcher.mjs +2 -53
  163. package/dist/server/dsh/runtime/override.patch.yml +0 -29
  164. package/dist/server/dsh/runtime/runtime-root.mjs +0 -54
  165. package/dist/server/durable/durable-agent-service.js +5 -23
  166. package/dist/server/durable/durable-driver.js +12 -73
  167. package/dist/server/durable/durable-event-projector.js +1 -50
  168. package/dist/server/durable/durable-loader.js +0 -12
  169. package/dist/server/durable/durable-models.js +11 -80
  170. package/dist/server/durable/durable-storage.js +1 -17
  171. package/dist/server/durable/durable-tools.js +2 -20
  172. package/dist/server/durable/index.js +0 -3
  173. package/dist/server/edit-soft-tool.js +2 -81
  174. package/dist/server/engine-capabilities.js +0 -13
  175. package/dist/server/engine-catalog.js +74 -0
  176. package/dist/server/engine-cli.js +89 -0
  177. package/dist/server/engine-probe.js +35 -217
  178. package/dist/server/ensure-bash.js +2 -28
  179. package/dist/server/eval-tool.js +1 -50
  180. package/dist/server/evidence-tool-hooks.js +0 -2
  181. package/dist/server/file-archives.js +0 -10
  182. package/dist/server/file-save.js +1 -12
  183. package/dist/server/file-transfer-routes.js +0 -11
  184. package/dist/server/files-service.js +18 -271
  185. package/dist/server/global-loader.js +9 -89
  186. package/dist/server/goal-evidence.js +1 -35
  187. package/dist/server/goal-review-gate.js +0 -58
  188. package/dist/server/goal-service.js +19 -422
  189. package/dist/server/hashline-engine.js +8 -112
  190. package/dist/server/host-guard.js +0 -24
  191. package/dist/server/host-metrics.js +0 -6
  192. package/dist/server/http-proxy.js +1 -7
  193. package/dist/server/i18n.js +5 -72
  194. package/dist/server/icon-svg.js +0 -15
  195. package/dist/server/index.js +177 -680
  196. package/dist/server/json-utils.js +0 -12
  197. package/dist/server/launch-origin.js +0 -44
  198. package/dist/server/left-panel-running.js +0 -9
  199. package/dist/server/load-timing.js +1 -4
  200. package/dist/server/load-tools-tool.js +0 -20
  201. package/dist/server/locales.js +1 -46
  202. package/dist/server/lsp-tool.js +13 -126
  203. package/dist/server/managed.js +0 -48
  204. package/dist/server/marker-service.js +1 -22
  205. package/dist/server/markers/builtins/action.js +0 -19
  206. package/dist/server/markers/builtins/notify.js +1 -9
  207. package/dist/server/markers/builtins/rename.js +0 -13
  208. package/dist/server/markers/index.js +0 -3
  209. package/dist/server/markers/marker.js +0 -13
  210. package/dist/server/markers/registry.js +0 -3
  211. package/dist/server/markers/store.js +1 -12
  212. package/dist/server/market-service.js +7 -43
  213. package/dist/server/mcp-agent-tool.js +0 -10
  214. package/dist/server/mcp-bridge.js +6 -138
  215. package/dist/server/mcp-hot-reload.js +0 -25
  216. package/dist/server/mcp-manager.js +2 -44
  217. package/dist/server/mcp-oauth-login.js +0 -2
  218. package/dist/server/mcp-oauth-ui.js +1 -4
  219. package/dist/server/mcp-oauth.js +5 -79
  220. package/dist/server/mcp-project-runtime.js +0 -4
  221. package/dist/server/message-deletion.js +0 -2
  222. package/dist/server/message-entry-resolver.js +0 -8
  223. package/dist/server/message-window.js +0 -71
  224. package/dist/server/mobile-notification-events.js +16 -0
  225. package/dist/server/mobile-origin.js +79 -0
  226. package/dist/server/mobile-push.js +523 -0
  227. package/dist/server/model-admin.js +19 -358
  228. package/dist/server/model-enrich.js +0 -19
  229. package/dist/server/model-resolver.js +2 -61
  230. package/dist/server/native-cli-discovery.js +115 -0
  231. package/dist/server/native-cli-model.js +71 -0
  232. package/dist/server/native-cli-references.js +214 -0
  233. package/dist/server/native-cli-remote-cleanup.js +58 -0
  234. package/dist/server/native-cli-remote-files.js +282 -0
  235. package/dist/server/native-cli-routes.js +68 -0
  236. package/dist/server/native-cli-runtime.js +1 -0
  237. package/dist/server/native-cli-session-hooks.js +170 -0
  238. package/dist/server/native-cli-session.js +585 -0
  239. package/dist/server/native-cli-state.js +82 -0
  240. package/dist/server/native-cli.js +210 -0
  241. package/dist/server/net-guard.js +9 -71
  242. package/dist/server/office-parse.js +0 -50
  243. package/dist/server/orphan-manager.js +0 -18
  244. package/dist/server/patch-bash-process.js +0 -4
  245. package/dist/server/patch-executable-lookup.js +0 -77
  246. package/dist/server/patch-node-pty.js +3 -43
  247. package/dist/server/patch-remote-catalog.js +1 -32
  248. package/dist/server/patch-tool.js +0 -15
  249. package/dist/server/payload-limits.js +0 -5
  250. package/dist/server/pending-question.js +0 -5
  251. package/dist/server/permission-preset.js +4 -33
  252. package/dist/server/persona-chain.js +0 -26
  253. package/dist/server/pkg-info.js +1 -17
  254. package/dist/server/plan-manager.js +2 -49
  255. package/dist/server/plan-mode.js +0 -97
  256. package/dist/server/plan-update-tool.js +1 -15
  257. package/dist/server/plugin-api-catalog.js +6 -4
  258. package/dist/server/plugin-assets.js +1 -35
  259. package/dist/server/plugin-bundled.js +68 -0
  260. package/dist/server/plugin-catalog-sync.js +0 -37
  261. package/dist/server/plugin-catalog.js +13 -67
  262. package/dist/server/plugin-chat-attachments.js +0 -1
  263. package/dist/server/plugin-conversation-view.js +0 -20
  264. package/dist/server/plugin-dom.js +1 -23
  265. package/dist/server/plugin-facilities.js +4 -115
  266. package/dist/server/plugin-grants.js +2 -90
  267. package/dist/server/plugin-install-spec.js +0 -43
  268. package/dist/server/plugin-installer.js +34 -75
  269. package/dist/server/plugin-llm.js +4 -38
  270. package/dist/server/plugin-manifest-validate.js +0 -31
  271. package/dist/server/plugin-permissions.js +1 -24
  272. package/dist/server/plugin-project.js +7 -129
  273. package/dist/server/plugin-removal.js +1 -8
  274. package/dist/server/plugin-schedule.js +1 -38
  275. package/dist/server/plugin-secrets.js +3 -16
  276. package/dist/server/plugin-tool-guard.js +1 -28
  277. package/dist/server/plugin-ui-slots.js +0 -4
  278. package/dist/server/plugin-updater.js +15 -90
  279. package/dist/server/plugins.js +71 -619
  280. package/dist/server/present-files-tool.js +0 -57
  281. package/dist/server/preset-fields.js +9 -62
  282. package/dist/server/preset-plugin-dependencies.js +0 -2
  283. package/dist/server/preset-share.js +3 -172
  284. package/dist/server/process-utils.js +4 -80
  285. package/dist/server/prompt-assembler.js +2 -30
  286. package/dist/server/prompt-base-store.js +0 -47
  287. package/dist/server/prompt-composer.js +21 -98
  288. package/dist/server/prompt-templates.js +0 -2
  289. package/dist/server/protocol-version.js +1 -11
  290. package/dist/server/protocol.js +0 -5
  291. package/dist/server/queue-modes.js +0 -3
  292. package/dist/server/queue-utils.js +0 -40
  293. package/dist/server/quick-ask-context.js +384 -0
  294. package/dist/server/quick-ask-settings.js +34 -1
  295. package/dist/server/quick-ask.js +123 -27
  296. package/dist/server/read-tool.js +0 -65
  297. package/dist/server/reasoning-registry.js +1 -29
  298. package/dist/server/remote-cli-persistence.js +373 -0
  299. package/dist/server/remote-native-cli.js +78 -0
  300. package/dist/server/remote-ssh-service.js +481 -190
  301. package/dist/server/request-context.js +0 -9
  302. package/dist/server/resolve-global-sdk.js +0 -26
  303. package/dist/server/sandbox-data.js +0 -1
  304. package/dist/server/sandbox-engines.js +0 -1
  305. package/dist/server/sandbox-runtime-gate.js +0 -3
  306. package/dist/server/sandbox-service.js +0 -41
  307. package/dist/server/sandbox-tool.js +0 -20
  308. package/dist/server/schedule-agent-tool.js +2 -31
  309. package/dist/server/scheduler-tasks.js +3 -54
  310. package/dist/server/scm-commitmsg.js +0 -53
  311. package/dist/server/scm.js +3 -48
  312. package/dist/server/sdk-builtin-extensions.js +2 -29
  313. package/dist/server/sdk-origin.js +0 -45
  314. package/dist/server/serialize.js +2 -92
  315. package/dist/server/server-config.js +0 -11
  316. package/dist/server/session-branch.js +1 -87
  317. package/dist/server/session-list-scan.js +17 -25
  318. package/dist/server/session-open.js +2 -26
  319. package/dist/server/session-parser.js +1 -55
  320. package/dist/server/session-scan.js +1 -17
  321. package/dist/server/session-search.js +0 -56
  322. package/dist/server/settings-service.js +11 -126
  323. package/dist/server/setup-config.js +0 -2
  324. package/dist/server/setup-page.js +0 -9
  325. package/dist/server/skill-content-filler.js +0 -17
  326. package/dist/server/skill-discovery.js +5 -92
  327. package/dist/server/skill-maintenance.js +1 -28
  328. package/dist/server/skill-tool.js +0 -30
  329. package/dist/server/slash-commands.js +5 -50
  330. package/dist/server/soft-cap.js +0 -42
  331. package/dist/server/startup-banner.js +0 -8
  332. package/dist/server/subagent-handoff.js +0 -11
  333. package/dist/server/subagent-helpers.js +2 -17
  334. package/dist/server/subagent-notify.js +0 -19
  335. package/dist/server/subagent-security-gate.js +0 -50
  336. package/dist/server/subagent-task.js +0 -9
  337. package/dist/server/subagent-templates-hant.js +0 -10
  338. package/dist/server/subagent-templates.js +3 -103
  339. package/dist/server/subagents.js +1 -87
  340. package/dist/server/system-screenshot-windows.js +259 -0
  341. package/dist/server/system-screenshot.js +77 -0
  342. package/dist/server/tabs.js +3 -48
  343. package/dist/server/terminals.js +559 -586
  344. package/dist/server/text-quote.js +0 -12
  345. package/dist/server/text-sniff.js +2 -52
  346. package/dist/server/themes.js +2 -41
  347. package/dist/server/tool-approval.js +0 -47
  348. package/dist/server/tool-guards.js +0 -90
  349. package/dist/server/tool-host-factories.js +1 -16
  350. package/dist/server/tool-info.js +0 -13
  351. package/dist/server/tool-manager.js +1 -229
  352. package/dist/server/tool-overrides.js +1 -46
  353. package/dist/server/tool-prompt-overrides.js +1 -30
  354. package/dist/server/tool-prompts.js +0 -14
  355. package/dist/server/tool-signature.js +0 -25
  356. package/dist/server/transcript-prepare.js +1 -19
  357. package/dist/server/tts-routes.js +58 -0
  358. package/dist/server/tts-service.js +106 -0
  359. package/dist/server/tts-system.js +160 -0
  360. package/dist/server/turn-timing.js +0 -1
  361. package/dist/server/unauthorized-page.js +0 -8
  362. package/dist/server/universal/driver-base.js +2 -31
  363. package/dist/server/universal/drivers/claude-code.js +12 -172
  364. package/dist/server/universal/drivers/codex.js +12 -35
  365. package/dist/server/universal/drivers/mock-driver.js +1 -11
  366. package/dist/server/universal/index.js +0 -3
  367. package/dist/server/universal/session-store.js +4 -21
  368. package/dist/server/universal/universal-attachments.js +2 -36
  369. package/dist/server/universal/universal-service.js +5 -24
  370. package/dist/server/universal/universal-session.js +26 -148
  371. package/dist/server/universal/universal-types.js +0 -3
  372. package/dist/server/update-check.js +6 -182
  373. package/dist/server/uploads.js +4 -43
  374. package/dist/server/virtual-tui.js +2 -27
  375. package/dist/server/vision-bridge.js +0 -27
  376. package/dist/server/wait-subscription-scan.js +13 -115
  377. package/dist/server/webui-context.js +2 -87
  378. package/dist/server/workspace-handle.js +1 -56
  379. package/dist/server/workspace-snapshot.js +7 -113
  380. package/dist/server/worktree-service.js +2 -53
  381. package/dist/server/worktree-tool.js +0 -11
  382. package/dist/server/ws-client-id.js +0 -18
  383. package/dist/server/ws-pending-queue.js +0 -7
  384. package/dist/server/ws-unknown-types.js +0 -17
  385. package/docs/README.md +24 -17
  386. package/docs/architecture-plugins.md +37 -1
  387. package/docs/device-center.md +28 -2
  388. package/docs/device-desktop.md +3 -3
  389. package/docs/group-orchestration.md +142 -0
  390. package/docs/hub-upgrade-release-testing.md +46 -0
  391. package/extensions/webui.ts +3 -74
  392. package/package.json +7 -3
  393. package/plugin-sdk/README.md +6 -0
  394. package/plugin-sdk/client-utils.mjs +0 -7
  395. package/plugin-sdk/client.d.ts +0 -1
  396. package/plugin-sdk/client.mjs +1 -31
  397. package/plugin-sdk/import-check.mjs +4 -51
  398. package/plugin-sdk/index.d.ts +120 -119
  399. package/plugin-sdk/index.mjs +0 -6
  400. package/plugin-sdk/ssh-host-trust.mjs +0 -12
  401. package/plugin-sdk/testing.d.ts +0 -1
  402. package/plugin-sdk/testing.mjs +31 -86
  403. package/plugins/catalog.json +52 -4
  404. package/plugins/superagent/README.md +110 -0
  405. package/plugins/superagent/client/entry.mjs +21 -0
  406. package/plugins/superagent/index.mjs +8 -0
  407. package/plugins/superagent/main.mjs +218 -0
  408. package/plugins/superagent/manifest.json +15 -0
  409. package/plugins/superagent/server.mjs +572 -0
  410. package/plugins/superagent/style.css +167 -0
  411. package/themes/aetheris.css +1 -31
  412. package/themes/ayu-light.css +0 -1
  413. package/themes/bases/flow-base.css +2 -83
  414. package/themes/bases/obsidian-base.css +2 -37
  415. package/themes/bases/statusbar-flat-base.css +0 -1
  416. package/themes/bases/zhujian-base.css +0 -63
  417. package/themes/bases/zhupi-base.css +0 -64
  418. package/themes/catppuccin-latte.css +0 -1
  419. package/themes/catppuccin.css +0 -1
  420. package/themes/claude-code-dark.css +0 -1
  421. package/themes/codex.css +0 -1
  422. package/themes/dark-teal.css +22 -54
  423. package/themes/everforest-light.css +0 -1
  424. package/themes/flow-cristallo.css +1 -9
  425. package/themes/flow-ink.css +1 -10
  426. package/themes/flow-light.css +1 -10
  427. package/themes/flow-obsidian.css +1 -10
  428. package/themes/flow-zurich.css +1 -10
  429. package/themes/flow.css +1 -9
  430. package/themes/geist.css +0 -1
  431. package/themes/gruvbox-light.css +0 -1
  432. package/themes/kanagawa-lotus.css +0 -1
  433. package/themes/md-preview.css +1 -2
  434. package/themes/mist.css +0 -1
  435. package/themes/nord.css +0 -1
  436. package/themes/one-dark.css +0 -1
  437. package/themes/paper.css +0 -1
  438. package/themes/rose-pine-dawn.css +0 -1
  439. package/themes/sakura.css +0 -1
  440. package/themes/solarized-light.css +0 -1
  441. package/themes/tokyo-night.css +0 -1
  442. package/themes/translucent.css +4 -35
  443. package/themes/transparent.css +4 -41
  444. package/themes/vs-code-dark.css +0 -1
  445. package/themes/wallpaper-flow.css +3 -17
  446. package/themes/wallpaper-obsidian.css +1 -4
  447. package/themes/white.css +0 -1
  448. package/web/dist/.build-assets.json +1 -1
  449. package/web/dist/assets/{BgTasksModal-BjNRIUIc.js → BgTasksModal-D-x7kA63.js} +1 -1
  450. package/web/dist/assets/CanvasStudio-CAWcs9tm.js +1579 -0
  451. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +3 -0
  452. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +1 -0
  453. package/web/dist/assets/DeviceGroups-C_fZMNeK.js +1 -0
  454. package/web/dist/assets/{Dropdown-CQtstPGv.js → Dropdown-CTgVLUbp.js} +1 -1
  455. package/web/dist/assets/FilePreview-C6W0PvaK.js +2 -0
  456. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +1 -0
  457. package/web/dist/assets/GroupConversation-C81YjF2C.js +61 -0
  458. package/web/dist/assets/GroupWorkItems-BIvZtr10.js +1 -0
  459. package/web/dist/assets/{HintTip-ChTW8o1m.js → HintTip-Da6qc566.js} +1 -1
  460. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +2 -0
  461. package/web/dist/assets/NativeCliPanel-CU1rZmyu.js +5 -0
  462. package/web/dist/assets/{PiSetupModal-BX5rUuoI.js → PiSetupModal-DZKY5Wiw.js} +1 -1
  463. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +1 -0
  464. package/web/dist/assets/{SCMPanel-DPAyY2sW.js → SCMPanel-CuEgzAlO.js} +2 -2
  465. package/web/dist/assets/SettingsModal-Cdu5h29p.js +33 -0
  466. package/web/dist/assets/TermXterm-Bt5WKAxP.js +3 -0
  467. package/web/dist/assets/TerminalPanel-BCIBV8se.js +1 -0
  468. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +1 -0
  469. package/web/dist/assets/app-globals-CZjFtI4F.js +129 -0
  470. package/web/dist/assets/canvas-client-WkhM55mR.js +1 -0
  471. package/web/dist/assets/composer-bridge-CImnjDHq.js +1 -0
  472. package/web/dist/assets/desktop-B8NZ3KW-.js +1 -0
  473. package/web/dist/assets/index-CQc3VrWa.css +1 -0
  474. package/web/dist/assets/index-D_AGu4Zv.js +404 -0
  475. package/web/dist/assets/plugin-host-uqZGpvCs.js +1 -0
  476. package/web/dist/assets/{remote-ssh-client-Dzi-eEyE.js → remote-ssh-client-Cdf-cTUe.js} +1 -1
  477. package/web/dist/assets/theme-DGL7hLUs.js +1 -0
  478. package/web/dist/index.html +11 -10
  479. package/web/dist/sw.js +15 -61
  480. package/web/public/sw.js +14 -60
  481. package/web/dist/assets/BgTasksModal-C0zuU8FE.js +0 -1
  482. package/web/dist/assets/CanvasStudio-BWvdmJ0M.js +0 -1579
  483. package/web/dist/assets/CanvasStudio-VQFjmTGq.js +0 -1579
  484. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +0 -3
  485. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +0 -3
  486. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +0 -1
  487. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +0 -1
  488. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +0 -1
  489. package/web/dist/assets/FilePreview-BMB2tNyT.js +0 -2
  490. package/web/dist/assets/FilePreview-RGFQUbJo.js +0 -2
  491. package/web/dist/assets/GlobalSearchModal-BM5wxiqU.js +0 -1
  492. package/web/dist/assets/GlobalSearchModal-DGv_WINq.js +0 -1
  493. package/web/dist/assets/GroupConversation-B7SnuXj1.js +0 -61
  494. package/web/dist/assets/GroupConversation-Dda69q-2.js +0 -61
  495. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +0 -2
  496. package/web/dist/assets/ModelConfigModal-yqeadyab.js +0 -2
  497. package/web/dist/assets/ProviderOAuthControls-DY4SCfXg.js +0 -1
  498. package/web/dist/assets/SCMPanel-C4KbQvvK.js +0 -2
  499. package/web/dist/assets/SettingsModal-DxZp6D_g.js +0 -32
  500. package/web/dist/assets/SettingsModal-WhQzaOPt.js +0 -32
  501. package/web/dist/assets/TerminalPanel-D4By_RVc.js +0 -3
  502. package/web/dist/assets/TerminalPanel-lZw8-i3j.js +0 -3
  503. package/web/dist/assets/TuiOverlayModal-C3pAVuC8.js +0 -1
  504. package/web/dist/assets/TuiOverlayModal-D7_rEXcJ.js +0 -1
  505. package/web/dist/assets/app-globals-KqOVtmp1.js +0 -123
  506. package/web/dist/assets/canvas-client-BY6ojmle.js +0 -1
  507. package/web/dist/assets/desktop-CV6KKp9R.js +0 -1
  508. package/web/dist/assets/index-BawF7ZP5.js +0 -397
  509. package/web/dist/assets/index-BoGCoq5X.js +0 -397
  510. package/web/dist/assets/index-CVW9FoY2.css +0 -1
  511. package/web/dist/assets/plugin-host-Dn8Dd6SC.js +0 -1
  512. package/web/dist/assets/theme-D_bihpdN.js +0 -1
@@ -1,35 +1,20 @@
1
- /**
2
- * TerminalManager — conversation-owned PTY sessions (node-pty) bridged over
3
- * the WebSocket protocol, plus the user command list persisted in
4
- * `<workspaceRoot>/.pi/commands.json`.
5
- *
6
- * Each conversation gets its own manager; terminals are shared across browser
7
- * tabs through the session emit. A socket drop does not kill them: the
8
- * conversation owns their lifecycle and releases them on disposal.
9
- *
10
- * Commands file format:
11
- * { "commands": [ { "name": "dev", "command": "npm run dev", "cwd": "${pwd}" } ] }
12
- * `${pwd}` inside cwd/command resolves to the agent session's current working
13
- * directory (the same directory the agent operates in — see set_cwd).
14
- */
15
- import { randomBytes } from "node:crypto";
1
+ import { randomBytes, randomUUID } from "node:crypto";
16
2
  import { chmodSync, existsSync, readdirSync, realpathSync, statSync } from "node:fs";
17
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
18
4
  import { createRequire } from "node:module";
19
5
  import { homedir } from "node:os";
20
6
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
21
- // MUST run before node-pty is required: rewrites the installed node-pty copies
22
- // so their worker/agent handlers tolerate Node `--watch`'s IPC traffic (see the
23
- // module itself for details).
24
7
  import "./patch-node-pty.js";
25
8
  import { spawn } from "node-pty";
26
9
  import { defineTool } from "@earendil-works/pi-coding-agent";
27
10
  import { Type } from "typebox";
11
+ import { MAX_NATIVE_CLI_PASTE, resolveNativeCliLaunch, sanitizeNativeCliPaste, validateNativeCliConfig, } from "./native-cli.js";
12
+ import { attachPersistentRemoteNativeCli, openPersistentRemoteNativeCli, probePersistentRemoteNativeCli, } from "./remote-cli-persistence.js";
13
+ import { resolveRemoteNativeCliLaunch } from "./remote-native-cli.js";
28
14
  import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
29
15
  import { pick } from "./i18n.js";
30
16
  import { armDelay } from "./plugin-schedule.js";
31
17
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveWorkspaceSessionDir, } from "./remote-ssh-service.js";
32
- /** Location of the command list for a project: <workspaceRoot>/.pi/commands.json */
33
18
  export function commandsFilePath(workspaceRoot) {
34
19
  if (isRemoteWorkspaceUri(workspaceRoot)) {
35
20
  const dataDir = process.env.PI_WEB_DATA_DIR || join(homedir(), ".pi-web");
@@ -37,7 +22,6 @@ export function commandsFilePath(workspaceRoot) {
37
22
  }
38
23
  return join(workspaceRoot, ".pi", "commands.json");
39
24
  }
40
- /** Expand ${pwd} (and ~) in a cwd/command string against the session's cwd. */
41
25
  export function expandPwd(input, pwd) {
42
26
  let out = input.replace(/\$\{pwd\}/g, pwd);
43
27
  if (out === "~")
@@ -46,7 +30,6 @@ export function expandPwd(input, pwd) {
46
30
  out = join(homedir(), out.slice(2));
47
31
  return out;
48
32
  }
49
- /** Resolve a command's directory: default to the session cwd, expand ${pwd}/~, resolve relative paths. */
50
33
  export function resolveCommandCwd(cwd, pwd) {
51
34
  if (!cwd || cwd.trim() === "" || cwd.trim() === "${pwd}")
52
35
  return pwd;
@@ -55,7 +38,6 @@ export function resolveCommandCwd(cwd, pwd) {
55
38
  const expanded = expandPwd(cwd.trim(), pwd);
56
39
  return isAbsolute(expanded) ? expanded : resolve(pwd, expanded);
57
40
  }
58
- /** Read the command list; missing file → empty list; malformed → empty list + warning text. */
59
41
  export async function loadCommands(workspaceRoot) {
60
42
  const path = commandsFilePath(workspaceRoot);
61
43
  const { commands, warning, warningEn } = await readCommandsFile(path);
@@ -87,7 +69,6 @@ async function readCommandsFile(path) {
87
69
  };
88
70
  }
89
71
  if (Array.isArray(parsed)) {
90
- // Tolerate a bare array: [{name, command, cwd}]
91
72
  return {
92
73
  commands: parsed
93
74
  .filter((c) => typeof c === "object" &&
@@ -110,7 +91,6 @@ async function readCommandsFile(path) {
110
91
  }
111
92
  return { commands: [], warning: `命令文件格式不正确:${path}`, warningEn: `Commands file has a bad format: ${path}` };
112
93
  }
113
- /** Persist the command list, creating .pi/ if needed. */
114
94
  export async function saveCommandsFile(workspaceRoot, commands) {
115
95
  const path = commandsFilePath(workspaceRoot);
116
96
  try {
@@ -129,59 +109,31 @@ export async function saveCommandsFile(workspaceRoot, commands) {
129
109
  }
130
110
  const isWindows = process.platform === "win32";
131
111
  const MAX_TERMINALS = 16;
132
- /** Coalescing window for terminal_output WS messages (one animation frame). */
133
112
  const OUTPUT_FLUSH_MS = 16;
134
113
  const MAX_TERMINAL_HISTORY = 32;
135
114
  const MAX_OUTPUT = 200_000;
136
115
  const MAX_INPUT = 64 * 1024;
137
116
  const MAX_ID = 80;
138
- /**
139
- * 终端活力检测阈值:agent 触碰过的终端连续静默这么久且该对话正在运行时,
140
- * 通过 onAgentIdle 回调通知宿主(宿主注入一条 steer 消息唤醒 AI 去检查)。
141
- * PI_WEB_TERMINAL_IDLE_MS 覆盖;0 = 关闭检测。每次调用时读取(测试可注入)。
142
- */
143
117
  export function terminalIdleNotifyMs() {
144
118
  const raw = Number(process.env.PI_WEB_TERMINAL_IDLE_MS);
145
119
  return Number.isFinite(raw) && raw >= 0 ? raw : 15_000;
146
120
  }
147
- /** 静默解阻时默认回送的最近输出行数(仅用于把已有输出截到可读量)。
148
- * PI_WEB_TERMINAL_IDLE_LINES 覆盖;0 = 不截;限制在 1..500。每次调用时读取。 */
149
121
  export function terminalIdleNotifyLines() {
150
122
  const raw = Number(process.env.PI_WEB_TERMINAL_IDLE_LINES);
151
123
  const n = Number.isFinite(raw) && raw >= 0 ? Math.floor(raw) : 10;
152
124
  return Math.max(1, Math.min(n, 500));
153
125
  }
154
- // ---------------------------------------------------------------------------
155
- // 终端接管 bash(terminal-backed bash tool)
156
- // ---------------------------------------------------------------------------
157
- /** 哨兵行:命令执行完后由 shell 打印,形如 `[pi-exit-<nonce>:<退出码>]`。
158
- * nonce 每次调用随机生成(12 位 hex):回显里的 printf 格式串(`%s`)、真实输出里
159
- * 的 `[pi-exit:42]` 之类字面量都不会与本次哨兵混淆(#572)。 */
160
126
  const SENTINEL_NONCE_SRC = "[0-9a-f]{12}";
161
- /** 任意 nonce 的哨兵(终端级通用等待用)。bash 工具自己的完成判定请用 sentinelReFor。 */
162
127
  const BASH_SENTINEL_RE = new RegExp(`\\[pi-exit-${SENTINEL_NONCE_SRC}:(\\d+)\\]`, "g");
163
- /** 本次调用的哨兵 nonce。 */
164
128
  export function newSentinelNonce() {
165
129
  return randomBytes(6).toString("hex");
166
130
  }
167
- /** 只匹配本次 nonce 的哨兵(bash 工具的完成判定只认自己注入的那一个)。 */
168
131
  function sentinelReFor(nonce) {
169
132
  return new RegExp(`\\[pi-exit-${nonce}:(\\d+)\\]`, "g");
170
133
  }
171
- /** bash 阻塞循环 collected 的累积上限:超限丢最旧一半(见 bash 工具执行循环)。 */
172
134
  const BASH_COLLECT_MAX = 2 * 1024 * 1024;
173
- /**
174
- * 把任意命令(含多行脚本)构造成一行交互 shell 命令:执行 + 捕获退出码。
175
- *
176
- * 单行很关键:整行先被 shell 完整解析再执行,命令中途读 stdin 也不会吃掉
177
- * 后续哨兵;也避开交互 shell 的 bracketed-paste 对多行输入的特殊处理。
178
- * 多行脚本用 `$'...'` ANSI-C 引号转义后交给 eval(bash/zsh/busybox ash 都支持)。
179
- */
180
135
  export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonce()) {
181
136
  const trimmed = command.replace(/\s+$/, "");
182
- // Preserve bash's status, including the caller's pipefail setting and SIGPIPE.
183
- // tailFile:`cmd > log 2>&1 | tail -N`——拆掉 tail 后 stdout 进文件、终端为空;
184
- // 在哨兵前补一个 `tail -N log` 让模型看到日志尾部,退出码仍是底层命令的。
185
137
  const tailPart = tailFile
186
138
  ? `; tail -n ${Math.max(1, Math.floor(tailFile.lines))} -- '${tailFile.file.replace(/'/g, `'\\''`)}'`
187
139
  : "";
@@ -189,8 +141,6 @@ export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonc
189
141
  const sentinel = `__pi_rc=$?${tailPart}; printf '\\n[pi-exit-${nonce}:%s]\\n' "$__pi_rc"`;
190
142
  if (sentinelUnsafeReason(trimmed))
191
143
  return trimmed;
192
- // Parse the whole physical line before a command can read stdin. The eval
193
- // boundary isolates trailing comments, multiline scripts and heredocs.
194
144
  const body = `eval $'${trimmed
195
145
  .replace(/\\/g, "\\\\")
196
146
  .replace(/'/g, "\\'")
@@ -199,41 +149,20 @@ export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonc
199
149
  .replace(/\t/g, "\\t")}'`;
200
150
  return `${body}; ${sentinel}`;
201
151
  }
202
- /**
203
- * 判定命令能否安全追加「独占一行的退出码哨兵」;返回拒注入原因或 null(可注入)。
204
- *
205
- * - 尾随续行符 `\`:下一行被并入本命令,哨兵行成为命令的一部分。
206
- * - 未闭合引号:哨兵行被吞进字符串字面量,永远不会作为代码执行。
207
- * - 未闭合的 `{}` / `()` 组:shell 停在 PS2 续行,哨兵永远不会执行(#573)。
208
- * - 未闭合的 heredoc(`<<`,非 `<<<`):哨兵行被当成 heredoc 正文吞掉,shell
209
- * 停在 PS2 等 EOF——不仅本条零执行,持久 shell 的后续命令也会连环被吞。
210
- * - 未闭合的 if/for/while/until/case 块:同样停在 PS2 等续行。
211
- * - 多行命令:经 `$'...'` 转义单行化后引号/换行全部字面化,总是安全 → null。
212
- *
213
- * 扫描按 POSIX 引号语义跟踪 `'`/`"`/`` ` `` 三种引号与转义;`$'...'`(ANSI-C
214
- * 引号)内 `\'` 不闭合引号,也一并识别。
215
- */
216
152
  export function sentinelUnsafeReason(command) {
217
153
  const trimmed = command.replace(/\s+$/, "");
218
154
  if (trimmed.includes("\n"))
219
155
  return null;
220
156
  let quote = null;
221
- // 当前单引号是否 $' 开头(ANSI-C 引号,内含转义语义)
222
157
  let ansiC = false;
223
158
  let escaped = false;
224
- // `{` 未闭合深度:残句(如 `{ a; b | tail -3`)注入后 shell 停在 PS2、哨兵永不执行(#573)
225
159
  let depth = 0;
226
- // `(` 栈:区分普通组与算术上下文(`(())`)——算术里的 `<<` 是左移不是 heredoc
227
160
  const parenStack = [];
228
- // 关键字块计数(命令位置的 if / for|while|until|select / case)
229
161
  let ifDepth = 0;
230
162
  let loopDepth = 0;
231
163
  let caseDepth = 0;
232
164
  let heredoc = false;
233
- // [[ ]] 内是测试表达式,单词不是命令
234
165
  let inDoubleBracket = false;
235
- // 当前累积的词;wordCmdPos 记录该词是否处于命令位置
236
- // (行首/`;|&(`/`{`/`}`/then|else|do 之后)——`echo if` 的 `if` 是参数不是关键字
237
166
  let word = "";
238
167
  let wordCmdPos = false;
239
168
  let cmdPos = true;
@@ -271,7 +200,6 @@ export function sentinelUnsafeReason(command) {
271
200
  escaped = false;
272
201
  continue;
273
202
  }
274
- // POSIX 单引号内 `\` 是普通字符;ANSI-C/双引号/反引号内 `\` 转义下一字符
275
203
  if (ch === "\\" && (quote !== "'" || ansiC)) {
276
204
  escaped = true;
277
205
  continue;
@@ -281,12 +209,11 @@ export function sentinelUnsafeReason(command) {
281
209
  continue;
282
210
  }
283
211
  if (escaped) {
284
- // 引号外的转义:被转义字符原样跳过(`\"` 不开引号等)
285
212
  escaped = false;
286
213
  continue;
287
214
  }
288
215
  if (ch === "#" && (i === 0 || /\s/.test(trimmed[i - 1])))
289
- break; // 注释到行尾,不再计引号/括号
216
+ break;
290
217
  if (ch === "\\") {
291
218
  escaped = true;
292
219
  continue;
@@ -309,14 +236,14 @@ export function sentinelUnsafeReason(command) {
309
236
  flushWord();
310
237
  cmdPos = false;
311
238
  if (trimmed[i + 2] === "<") {
312
- i += 2; // `<<<` here-string:不等待后续行,安全
239
+ i += 2;
313
240
  }
314
241
  else if (parenStack[parenStack.length - 1] !== "arith" && !inDoubleBracket) {
315
242
  heredoc = true;
316
- break; // 哨兵行必然被当 heredoc 正文吞掉
243
+ break;
317
244
  }
318
245
  else {
319
- i += 1; // 算术左移 / [[ 内:非 heredoc
246
+ i += 1;
320
247
  }
321
248
  continue;
322
249
  }
@@ -342,7 +269,6 @@ export function sentinelUnsafeReason(command) {
342
269
  else if (top === "group") {
343
270
  parenStack.pop();
344
271
  }
345
- // 栈空/不匹配的 `)`(case 模式 `a)`、算术残留)保持忽略
346
272
  cmdPos = true;
347
273
  continue;
348
274
  }
@@ -370,7 +296,6 @@ export function sentinelUnsafeReason(command) {
370
296
  cmdPos = true;
371
297
  continue;
372
298
  }
373
- // 其余字符(空白/`;|&`/`$`/`!` 等)结束当前词
374
299
  flushWord();
375
300
  if (ch === ";" || ch === "|" || ch === "&" || ch === "!")
376
301
  cmdPos = true;
@@ -380,7 +305,6 @@ export function sentinelUnsafeReason(command) {
380
305
  flushWord();
381
306
  if (quote !== null)
382
307
  return "unclosed_quote";
383
- // 扫描结束仍在转义态 = 最后一个字符是引号外的 `\`(尾随续行符)
384
308
  if (escaped)
385
309
  return "trailing_backslash";
386
310
  if (heredoc)
@@ -393,18 +317,13 @@ export function sentinelUnsafeReason(command) {
393
317
  return "unclosed_group";
394
318
  return null;
395
319
  }
396
- /** 顶层(引号/反引号/转义外、且不在 `()` / `{}` 组内)按 `|` 拆分的管道元素。
397
- * 组内的 `|`(`{ a; b | tail; }`)属于组本身,不是顶层管道(#573)。 */
398
320
  export function splitTopLevelPipes(cmd) {
399
321
  return scanTopLevel(cmd).parts;
400
322
  }
401
- /** 顶层管道扫描:引号 / ANSI-C 引号 / 转义 / `||` 不拆;`()` `{}` 组内的 `|` 不拆。
402
- * openGroups > 0 = 结尾仍有未闭合的组(调用方据此放弃拆管 / 拒注入)。 */
403
323
  function scanTopLevel(cmd) {
404
324
  const parts = [];
405
325
  let cur = "";
406
326
  let quote = null;
407
- // 当前单引号是否 $' 开头(ANSI-C 引号:内含 \' 等转义,不闭合引号)
408
327
  let ansiC = false;
409
328
  let depth = 0;
410
329
  for (let i = 0; i < cmd.length; i++) {
@@ -418,12 +337,10 @@ function scanTopLevel(cmd) {
418
337
  continue;
419
338
  }
420
339
  if (ch === "#" && (i === 0 || /\s/.test(cmd[i - 1]))) {
421
- // 词首的 # 注释到行尾:之后的 | 和引号都不是 shell 结构(否则 `echo hi # don't` 会被当成未闭合引号)
422
340
  cur += cmd.slice(i);
423
341
  break;
424
342
  }
425
343
  if (ch === "\\" && i + 1 < cmd.length) {
426
- // 引号外的转义:被转义字符原样保留(`\|` 是字面竖线,不是管道)
427
344
  cur += ch + cmd[++i];
428
345
  continue;
429
346
  }
@@ -438,7 +355,6 @@ function scanTopLevel(cmd) {
438
355
  else if ((ch === ")" || ch === "}") && depth > 0)
439
356
  depth--;
440
357
  if (ch === "|" && cmd[i + 1] === "|") {
441
- // `||` 是逻辑或,不是管道
442
358
  cur += "||";
443
359
  i++;
444
360
  continue;
@@ -453,37 +369,18 @@ function scanTopLevel(cmd) {
453
369
  parts.push(cur.trimEnd());
454
370
  return { parts, openGroups: depth };
455
371
  }
456
- /** 从 tail 参数里解析行数:`-n 15` / `-n15` / `-15` / `--lines=15` / `--lines 15`。 */
457
372
  function parseTailLines(rest) {
458
373
  const m = rest.match(/--lines(?:=|\s+)(\d+)|-n\s*(\d+)|(?:^|\s)-(\d+)/);
459
374
  if (!m)
460
375
  return null;
461
376
  return Number(m[1] ?? m[2] ?? m[3]);
462
377
  }
463
- /**
464
- * 识别命令**末尾**用来「限制输出量」的管道:`| tail [-n N|-N]`(不含 -f)、`| less`、
465
- * `| more`、`| cat`。这类管道会 ①缓冲输出(可见终端全程哑火、无法感知实时进度)②把
466
- * 退出码变成**管道最后一个命令**(tail 恒 0)——掩盖底层真实失败 ③需 stdin 的管道
467
- * (尤其长驻命令)出错后可能一直挂到超时。
468
- *
469
- * 识别后由调用方拆掉它:底层命令直跑(实时可见 + 真实退出码),只在返回给模型时取
470
- * 末尾 N 行(tail)或全部输出。
471
- *
472
- * - **只拆末尾单个纯“限输出/透传”**;`| grep`/`| head`/`| awk`/`| sed`/`| sort`/`| uniq`
473
- * (真过滤/变换,拆掉会丢语义或崩出海量未过滤输出)与 `| tee`(写文件副作用)都**不拆**。
474
- * - `tail -f` / `tail --follow`(长驻观察)也不拆。
475
- */
476
378
  export function detectTrailingLimiter(command) {
477
- // 含命令替换($() / 反引号)的命令保守跳过拆管:splitTopLevelPipes 只跟踪引号
478
- // 与顶层 `|`,不解析括号嵌套——`cmd $(x | y)` 里替换内的管道会被误判为顶层
479
- // 管道段,拆掉后直接破坏命令语义。保守正确优先,宁可少优化。
480
379
  if (/\$\(|`/.test(command))
481
380
  return null;
482
381
  const { parts, openGroups } = scanTopLevel(command);
483
- // 结尾仍有未闭合的 `{` / `(`:这条命令本身就是残的,拆管只会把组截断(#573)。
484
382
  if (parts.length < 2 || openGroups > 0)
485
383
  return null;
486
- // 管道分隔处可能在 `|` 后留前导空白(`| tail`),trim 掉再匹配。
487
384
  const last = parts[parts.length - 1].trim();
488
385
  const m = last.match(/^(tail|less|more|cat)\b(.*)$/i);
489
386
  if (!m)
@@ -491,10 +388,9 @@ export function detectTrailingLimiter(command) {
491
388
  const kind = m[1].toLowerCase();
492
389
  const rest = m[2].trim();
493
390
  if (kind === "tail") {
494
- // 长驻观察:tail -f / tail --follow —— 不拆。
495
391
  if (/(?:^|\s)(?:-f|--follow(?:=|\b))/.test(rest))
496
392
  return null;
497
- const lines = parseTailLines(rest) ?? 10; // 裸 `| tail` 默认 10 行
393
+ const lines = parseTailLines(rest) ?? 10;
498
394
  return {
499
395
  base: parts
500
396
  .slice(0, -1)
@@ -505,7 +401,6 @@ export function detectTrailingLimiter(command) {
505
401
  segment: last,
506
402
  };
507
403
  }
508
- // less / more / cat:纯透传,拆掉只为修正退出码 + 避免交互分页器在 PTY 里挂起。
509
404
  return {
510
405
  base: parts
511
406
  .slice(0, -1)
@@ -516,9 +411,6 @@ export function detectTrailingLimiter(command) {
516
411
  segment: last,
517
412
  };
518
413
  }
519
- /** 识别命令里把 stdout 重定向到文件的 `> file` / `>> file`(忽略 2>N / >&N / /dev/null)。
520
- * 用于 `cmd > log 2>&1 | tail -N`:拆掉 tail 后输出进文件,终端为空——补一个 tail 文件
521
- * 让模型能看到日志尾部与真实退出码。返回文件路径;复杂/带引号目标暂不处理。 */
522
414
  export function detectStdoutRedirect(command) {
523
415
  const all = [...command.matchAll(/(?:^|[\s;&|])(>>|>)\s*([^\s;|&]+)/g)];
524
416
  for (let i = all.length - 1; i >= 0; i--) {
@@ -529,8 +421,6 @@ export function detectStdoutRedirect(command) {
529
421
  }
530
422
  return null;
531
423
  }
532
- /** 对终端输出缓冲做快照查询:head / tail / search(+context)。返回带 1-based 行号的
533
- * 人类可读文本,便于 AI 定位后继续按行查看/搜索。纯函数(单测可覆盖)。 */
534
424
  export function queryTerminalOutput(output, q, running = false, exitCode = null) {
535
425
  const lines = stripAnsi(output)
536
426
  .replace(/\r(?!\n)/g, "")
@@ -585,16 +475,13 @@ export function queryTerminalOutput(output, q, running = false, exitCode = null)
585
475
  }
586
476
  return { text: numbered(lines, 0), running, exitCode };
587
477
  }
588
- /** 去掉 ANSI 转义序列(OSC/CSI/其余 ESC 序列)与孤立 CR(进度条重绘),
589
- * 让 PTY 回显变成 bash 工具风格的纯文本。 */
590
478
  export function stripAnsi(s) {
591
479
  return s
592
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "") // OSC(标题/超链接等)
593
- .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "") // CSI(颜色/光标/清屏等)
594
- .replace(/\x1b[@-_]/g, "") // 其余单字符 ESC 序列
595
- .replace(/\r(?!\n)/g, ""); // 孤立 CR(进度条原地重绘)
480
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
481
+ .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "")
482
+ .replace(/\x1b[@-_]/g, "")
483
+ .replace(/\r(?!\n)/g, "");
596
484
  }
597
- /** 截断过长的工具结果:保留头尾,中间省略。 */
598
485
  function truncateMiddle(text, max = 30_000) {
599
486
  if (text.length <= max)
600
487
  return text;
@@ -602,26 +489,9 @@ function truncateMiddle(text, max = 30_000) {
602
489
  const tail = max - head;
603
490
  return `${text.slice(0, head)}\n…(中间省略 ${text.length - max} 字符)…\n${text.slice(-tail)}`;
604
491
  }
605
- /** `-i` makes bash interactive; cmd.exe / powershell.exe are interactive on their own. */
606
492
  function bashArgs(shell) {
607
493
  return /[\\/]bash(\.exe)?$/i.test(shell) ? ["-i"] : [];
608
494
  }
609
- /**
610
- * Interactive shell for PTYs.
611
- * - Windows: prefer bash — it matches the SDK's bash tool, so the agent and
612
- * the terminal speak the same shell language (no more PowerShell/bash
613
- * 混用 that leaves heredocs / `&&` / `<<` hanging or erroring). Order:
614
- * 1. PI_WEB_SHELL (explicit override)
615
- * 2. $SHELL when it exists on disk (user launched from a Git Bash session)
616
- * 3. Git Bash install paths (ProgramFiles / ProgramFiles(x86))
617
- * 4. busybox-w32 fallback in <home>/.pi-web/bin/bash.exe (ensure-bash.ts
618
- * downloads it automatically when 2–3 are absent)
619
- * 5. $COMSPEC (cmd.exe — always set)
620
- * 6. powershell.exe (last resort)
621
- * - POSIX: the user's login shell, falling back to bash.
622
- * Resolved per terminal spawn (not at module load) so a busybox download that
623
- * finishes after startup is picked up by the next terminal.
624
- */
625
495
  function resolveShell() {
626
496
  if (isWindows) {
627
497
  const explicit = process.env.PI_WEB_SHELL;
@@ -646,12 +516,6 @@ function resolveShell() {
646
516
  }
647
517
  return { shell: process.env.SHELL || "bash", args: ["-i"] };
648
518
  }
649
- /**
650
- * Shell for the terminal-backed bash tool ('ai-bash'): ALWAYS bash, never the
651
- * user's login shell (often zsh on macOS, whose `read -p` etc. diverge from
652
- * the bash semantics models write). Windows already prefers Git Bash/busybox
653
- * bash; on posix pick $SHELL when it is bash, else plain `bash`.
654
- */
655
519
  function resolveBashShell() {
656
520
  if (isWindows) {
657
521
  const explicit = process.env.PI_WEB_SHELL;
@@ -679,13 +543,6 @@ function resolveBashShell() {
679
543
  }
680
544
  return { shell: "bash", args: ["-i"] };
681
545
  }
682
- /**
683
- * Environment for spawned shells. System services (launchd/systemd) run with
684
- * no locale variables, which puts the shell in the C locale: its line editor
685
- * then renders UTF-8 continuation bytes 0x80–0x9F as C1 control characters
686
- * (e.g. `�<0091><0098>` for 员), garbling Chinese input in the terminal.
687
- * Default a UTF-8 locale so multibyte text round-trips.
688
- */
689
546
  function shellEnv() {
690
547
  const env = {
691
548
  ...process.env,
@@ -695,42 +552,15 @@ function shellEnv() {
695
552
  env.LANG = "en_US.UTF-8";
696
553
  return env;
697
554
  }
698
- // ---------------------------------------------------------------------------
699
- // node-pty ConoutConnection warning noise (Node --watch)
700
- // ---------------------------------------------------------------------------
701
- // node-pty's ConoutConnection warns about every unknown message from its ConPTY
702
- // worker thread. Under `node --watch` (the dev server: `node --watch --import
703
- // tsx`), Node's watch mode pushes `watch:require` / `watch:import` messages over
704
- // the worker's message channel to track module dependencies; node-pty doesn't
705
- // recognize them and logs one `Unexpected ConoutWorkerMessage { … }` per message
706
- // — hundreds of lines per terminal (the SCM panel's hidden query PTY triggers it
707
- // on every git-view open). The messages are harmless: the worker only ever sends
708
- // its READY sentinel, which the handler does process. Filter that exact warning
709
- // at the console boundary so dev output stays readable. Production runs without
710
- // --watch and never produces these.
711
555
  const originalWarn = console.warn.bind(console);
712
556
  console.warn = (...args) => {
713
557
  if (args[0] === "Unexpected ConoutWorkerMessage")
714
558
  return;
715
559
  originalWarn(...args);
716
560
  };
717
- // ---------------------------------------------------------------------------
718
- // spawn-helper permission repair (node-pty macOS prebuilds)
719
- // ---------------------------------------------------------------------------
720
- // node-pty 1.1.0 publishes its macOS prebuilds with `spawn-helper` lacking the
721
- // execute bit (mode 0644 in the npm tarball), so posix_spawn fails with EACCES
722
- // and node-pty throws the generic "posix_spawnp failed". Locally-built
723
- // copies (build/Release) are fine; every `npm install` that picks the prebuild
724
- // — e.g. `npm i -g pi-web-ui`, which is what system-service installs run — is
725
- // broken until the bit is restored. Self-heal at startup AND lazily before
726
- // every spawn (an `npm i -g` while the server is running replaces the helper
727
- // under the running process, so the startup-only repair misses it).
728
- // Best-effort: a read-only node_modules just keeps the old failure.
729
561
  const require = createRequire(import.meta.url);
730
- /** Absolute paths of every node-pty spawn-helper this install can exec. */
731
562
  function spawnHelperPaths() {
732
563
  try {
733
- // require.resolve("node-pty") → <pkg>/lib/index.js → package root is two up.
734
564
  const pkgDir = dirname(dirname(require.resolve("node-pty")));
735
565
  const out = [];
736
566
  const built = join(pkgDir, "build", "Release", "spawn-helper");
@@ -750,7 +580,6 @@ function spawnHelperPaths() {
750
580
  return [];
751
581
  }
752
582
  }
753
- /** Restore the +x bit on node-pty's spawn-helper binaries (idempotent). */
754
583
  function repairSpawnHelperPermissions() {
755
584
  if (isWindows)
756
585
  return;
@@ -759,13 +588,10 @@ function repairSpawnHelperPermissions() {
759
588
  if ((statSync(p).mode & 0o111) === 0)
760
589
  chmodSync(p, 0o755);
761
590
  }
762
- catch {
763
- // best-effort; a read-only node_modules just keeps the old failure
764
- }
591
+ catch { }
765
592
  }
766
593
  }
767
594
  repairSpawnHelperPermissions();
768
- /** Path of a still-broken helper, for the error hint ("" when none). */
769
595
  function brokenSpawnHelper() {
770
596
  if (isWindows)
771
597
  return "";
@@ -774,23 +600,10 @@ function brokenSpawnHelper() {
774
600
  if ((statSync(p).mode & 0o111) === 0)
775
601
  return p;
776
602
  }
777
- catch {
778
- // ignore
779
- }
603
+ catch { }
780
604
  }
781
605
  return "";
782
606
  }
783
- // ---------------------------------------------------------------------------
784
- // macOS TCC camera/mic warning (launchd-spawned servers)
785
- // ---------------------------------------------------------------------------
786
- // TCC attributes camera/mic access to the process chain's "responsible
787
- // process". When pi-web-ui runs as a launchd LaunchAgent (node ← launchd),
788
- // the responsible process is node itself — a bare CLI binary with no app
789
- // bundle / Info.plist / NSCameraUsageDescription — so TCC silently denies
790
- // camera access (no prompt, nothing to tick in System Settings) and
791
- // ffmpeg-style grabbers hang on frame capture. The identical command works
792
- // from a terminal app that already holds the camera grant. Detect the
793
- // "no GUI ancestor" case (ppid === 1 on macOS) and warn in the terminal.
794
607
  const TCC_HINT = [
795
608
  "\x1b[33m[提示] 本终端由后台服务(launchd)启动,macOS 隐私权限(相机/麦克风/屏幕录制等)对此类进程不可用。\x1b[0m",
796
609
  "\x1b[90m · 需要隐私权限的命令会被系统静默拒绝:不弹授权窗,系统设置里也无法勾选,表现多为卡死或无输出。",
@@ -798,22 +611,9 @@ const TCC_HINT = [
798
611
  " · 本终端内可运行不需要隐私权限的命令(如文件处理、网络请求、远程设备流)。",
799
612
  " · 若改在前台终端里运行 pi-web-ui,本提示即不再出现。\x1b[0m",
800
613
  ].join("\r\n") + "\r\n";
801
- /** True when this server was spawned by launchd (or orphaned) on macOS — no GUI app in the ancestry, so camera/mic TCC grants are unavailable. */
802
614
  function launchdSpawnedOnMac() {
803
615
  return process.platform === "darwin" && process.ppid === 1;
804
616
  }
805
- /**
806
- * Translate a logical key (named key or single character) plus modifiers into
807
- * the exact byte sequence a PTY expects. Named keys are routed by NAME, so a
808
- * Ctrl/Alt combo is NEVER derived from the key's first letter: Ctrl+ArrowUp
809
- * must produce `ESC[1;5A`, not Ctrl+A, and Ctrl+Enter `ESC[13;5u`, not Ctrl+E.
810
- * - arrows / F1–F4 / Home / End keep their plain form when unmodified and
811
- * gain the xterm modifier parameter (`ESC[1;<m>X`) under Shift/Alt/Ctrl;
812
- * - other named keys (Enter/Tab/Backspace/Escape/Insert/Delete/PageUp/PageDown)
813
- * fall back to the CSI-u form (`ESC[<code>;<m>u`) once modified;
814
- * - plain characters: Ctrl maps A–Z to 0x01–0x1A (error for non-letters),
815
- * Shift uppercases, Alt prefixes with ESC.
816
- */
817
617
  export function encodeTerminalKey(key, modifiers = {}) {
818
618
  const named = {
819
619
  Enter: "\r",
@@ -843,8 +643,6 @@ export function encodeTerminalKey(key, modifiers = {}) {
843
643
  let data = named[key] ?? (key.length === 1 ? key : "");
844
644
  if (!data)
845
645
  return { error: `不支持的终端按键:${key}` };
846
- // xterm modifier encoding: 1=plain, 2=Shift, 3=Alt, 5=Ctrl,
847
- // 6=Ctrl+Shift, 7=Ctrl+Alt, 8=Ctrl+Alt+Shift.
848
646
  const modifier = 1 + (modifiers.shift ? 1 : 0) + (modifiers.alt ? 2 : 0) + (modifiers.ctrl ? 4 : 0);
849
647
  const arrow = /^\x1b\[([A-DHF])$/.exec(data);
850
648
  const functionKey = /^\x1bO([P-S])$/.exec(data);
@@ -868,8 +666,6 @@ export function encodeTerminalKey(key, modifiers = {}) {
868
666
  data = `\x1b[1;${modifier}${functionKey[1]}`;
869
667
  }
870
668
  else if (namedCode[key] !== undefined && modifier !== 1) {
871
- // CSI-u keeps named keys identifiable. In particular, Ctrl+Enter and
872
- // Ctrl+Tab must not be derived from the first letter of "Enter"/"Tab".
873
669
  data = `\x1b[${namedCode[key]};${modifier}u`;
874
670
  }
875
671
  else {
@@ -890,12 +686,6 @@ export function encodeTerminalKey(key, modifiers = {}) {
890
686
  }
891
687
  return { data };
892
688
  }
893
- /**
894
- * 终端行输入流状态机解析(纯函数,issue #721)。
895
- *
896
- * 结合前次未完成的行缓冲与本次输入字符,按换行符(CR / LF / CRLF)切分出
897
- * 全部已闭合的完整命令行,并正确处理退格(Backspace)与中断清除(Ctrl+C / Ctrl+U)。
898
- */
899
689
  export function parseTerminalLineStream(previousPending, inputChunk) {
900
690
  const completedLines = [];
901
691
  let current = previousPending;
@@ -905,17 +695,14 @@ export function parseTerminalLineStream(previousPending, inputChunk) {
905
695
  if (ch === "\r" || ch === "\n") {
906
696
  completedLines.push(current);
907
697
  current = "";
908
- // 处理 CRLF 双字符换行:若为 \r 且后一个字符是 \n,跳过后续 \n
909
698
  if (ch === "\r" && i + 1 < inputChunk.length && inputChunk[i + 1] === "\n") {
910
699
  i++;
911
700
  }
912
701
  }
913
702
  else if (ch === "\x03" || ch === "\x15") {
914
- // Ctrl+C (ETX) 或 Ctrl+U (NAK) 清除当前行
915
703
  current = "";
916
704
  }
917
705
  else if (ch === "\x7f" || ch === "\x08") {
918
- // 退格键 Backspace
919
706
  if (current.length > 0) {
920
707
  current = current.slice(0, -1);
921
708
  }
@@ -930,18 +717,6 @@ export function parseTerminalLineStream(previousPending, inputChunk) {
930
717
  remainingPending: current,
931
718
  };
932
719
  }
933
- /**
934
- * Owns one or more PTYs for a conversation. All output is forwarded as
935
- * `terminal_output` messages through the provided emit (broadcast to every
936
- * socket attached to the client session). Failed spawns emit an error notice and
937
- * terminal_exit instead of throwing into the WebSocket dispatcher.
938
- */
939
- /**
940
- * 识别是否属于终端仿真器自动回传的握手/探测序列(如光标位置报告 CPR、设备属性 DA1/DA2、焦点通知等)。
941
- * 这些序列由 xterm.js 接收到 Shell/ConPTY 发出的探针后自动回复,绝非用户真实键盘输入。
942
- * 收到此类自动响应时不应把 pristine 裸 shell 标记为 used,否则点开终端自动建的空 shell 会被永久误判为
943
- * “用户动过的终端”并阻断会话移出。
944
- */
945
720
  export const TERMINAL_QUERY_RESPONSE_RE = /^(?:\x1b\[(?:\??|>|<)?\d*(?:;\d+)*(?:\$?y|[cRnIOt])|\x1b\]\d+;[^\x07\x1b]*(?:\x07|\x1b\\))+$/;
946
721
  export function isTerminalQueryResponse(data) {
947
722
  return TERMINAL_QUERY_RESPONSE_RE.test(data);
@@ -950,38 +725,35 @@ export class TerminalManager {
950
725
  rootSource;
951
726
  lang;
952
727
  ownerKind;
953
- /** Live PTYs only. Exited entries move to history so they no longer consume
954
- * the live-terminal limit while their output remains readable/replayable. */
728
+ resolveNativeCliModel;
955
729
  terms = new Map();
956
730
  history = new Map();
731
+ pendingNativeCli = new Map();
732
+ nativeCliRuns = new Map();
733
+ nativeCliStops = new Map();
734
+ nativeCliRuntime;
957
735
  seq = 0;
958
736
  tccHintShown = false;
959
- /** 宿主回调:AI 触碰过的终端静默 ≥ 阈值时触发(一次性/纪元语义见
960
- * noteAgentActivity)。宿主自行判断会话是否在运行并决定是否注入。 */
961
737
  onAgentIdle = null;
962
- /** 获取该终端当前被 AI 累积但尚未提交的命令行(issue #721) */
963
738
  getAgentPendingLine(id) {
964
739
  return this.terms.get(id)?.agentPendingLine ?? "";
965
740
  }
966
- /** 设置该终端 AI 累积的待提交行(issue #721) */
967
741
  setAgentPendingLine(id, line) {
968
742
  const entry = this.terms.get(id);
969
743
  if (entry)
970
744
  entry.agentPendingLine = line;
971
745
  }
972
- /** 清空该终端 AI 累积的待提交行(issue #721) */
973
746
  clearAgentPendingLine(id) {
974
747
  const entry = this.terms.get(id);
975
748
  if (entry)
976
749
  entry.agentPendingLine = "";
977
750
  }
978
751
  emit;
979
- constructor(emit, rootSource,
980
- // issue #91:按键/输入校验错误按客户端 UI 语言出中英(英文默认)。
981
- lang, ownerKind = "conversation") {
752
+ constructor(emit, rootSource, lang, ownerKind = "conversation", resolveNativeCliModel) {
982
753
  this.rootSource = rootSource;
983
754
  this.lang = lang;
984
755
  this.ownerKind = ownerKind;
756
+ this.resolveNativeCliModel = resolveNativeCliModel;
985
757
  this.emit = this.ownedEmit(emit);
986
758
  }
987
759
  get workspaceRoot() {
@@ -996,12 +768,9 @@ export class TerminalManager {
996
768
  emit(msg);
997
769
  };
998
770
  }
999
- /** 过户:对话整体搬到另一个 ClientSession 时,把输出/退出事件改发给新宿主。
1000
- * PTY 本体不动(进程不重启,输出缓冲保留),只换投递地址. */
1001
771
  rebindEmit(emit) {
1002
772
  this.emit = this.ownedEmit(emit);
1003
773
  }
1004
- /** Attach to an existing PTY or retained history; never spawn or restart. */
1005
774
  attach(id, cols, rows) {
1006
775
  const entry = this.find(id);
1007
776
  if (!entry)
@@ -1011,53 +780,400 @@ export class TerminalManager {
1011
780
  this.emit({ type: "terminal_output", terminalId: id, data: entry.output, reset: true });
1012
781
  return true;
1013
782
  }
1014
- /** Start a plain interactive shell in the given directory. */
1015
- create(id, cwd, cols, rows, fallbackCwd, title, opts) {
783
+ async createNativeCli(...args) {
784
+ const [id, cwd, cols, rows, fallbackCwd, title, opts] = args;
785
+ const remote = isRemoteWorkspaceUri(cwd || fallbackCwd) || isRemoteWorkspaceUri(this.workspaceRoot);
786
+ const needsAuth = opts?.nativeCli?.model &&
787
+ this.resolveNativeCliModel &&
788
+ (opts.nativeCli.preset === "claude" || opts.nativeCli.preset === "codex");
789
+ if (!opts?.nativeCli || (!remote && !needsAuth && !this.nativeCliRuntime))
790
+ return this.create(...args);
791
+ if (this.nativeCliStops.has(id)) {
792
+ this.emit({ type: "notice", level: "warning", text: "CLI is stopping; reconnect after the stop completes" });
793
+ return null;
794
+ }
795
+ if (this.terms.has(id))
796
+ return this.info(this.terms.get(id));
797
+ const existing = this.pendingNativeCli.get(id);
798
+ if (existing)
799
+ return existing.task;
1016
800
  const valid = this.validateId(id);
1017
801
  if (valid) {
1018
802
  this.fail(id, valid.text, valid.textEn);
1019
803
  return null;
1020
804
  }
805
+ if (!this.ensureSpawnAllowed(id))
806
+ return null;
807
+ const root = this.workspaceRoot;
808
+ const pending = { controller: new AbortController(), task: Promise.resolve(null) };
809
+ this.pendingNativeCli.set(id, pending);
810
+ const startupTimer = remote
811
+ ? setTimeout(() => {
812
+ if (this.pendingNativeCli.get(id) !== pending)
813
+ return;
814
+ pending.controller.abort();
815
+ this.nativeCliRuntime?.onStatus(id, {
816
+ phase: "error",
817
+ error: "Remote CLI startup timed out",
818
+ updatedAt: Date.now(),
819
+ });
820
+ }, 90_000)
821
+ : void 0;
822
+ startupTimer?.unref?.();
823
+ this.nativeCliRuntime?.onStatus(id, { phase: "starting", updatedAt: Date.now() });
824
+ pending.task = (async () => {
825
+ let prepared;
826
+ let run;
827
+ let adopted = false;
828
+ try {
829
+ const config = validateNativeCliConfig(opts.nativeCli);
830
+ if (config.keepAlive && !remote)
831
+ throw new Error("CLI keep-alive requires an SSH workspace");
832
+ const safeCwd = this.safeCwd(cwd || fallbackCwd);
833
+ if (!safeCwd)
834
+ throw new Error("Terminal cwd must be inside the current workspace");
835
+ const remoteService = remote ? getGlobalRemoteSshService() : null;
836
+ const persistentRef = config.keepAlive ? this.nativeCliRuntime?.reference?.(id) : void 0;
837
+ let observeOnly = false;
838
+ if (config.keepAlive) {
839
+ if (!remoteService || !persistentRef)
840
+ throw new Error("Persistent CLI requires a saved session binding and SSH service");
841
+ observeOnly = (await probePersistentRemoteNativeCli(remoteService, safeCwd, persistentRef.key)).alive;
842
+ }
843
+ const connection = needsAuth && !observeOnly ? await this.resolveNativeCliModel(config) : undefined;
844
+ if (this.pendingNativeCli.get(id) !== pending ||
845
+ root !== this.workspaceRoot ||
846
+ pending.controller.signal.aborted)
847
+ return null;
848
+ if (this.nativeCliRuntime)
849
+ prepared = await this.nativeCliRuntime.prepare(id, config, safeCwd, pending.controller.signal, (event) => {
850
+ if ((!pending.controller.signal.aborted && this.pendingNativeCli.get(id) === pending) ||
851
+ (run && this.nativeCliRuns.get(id) === run && !run.stopping))
852
+ this.nativeCliRuntime?.onEvent(id, event);
853
+ }, observeOnly);
854
+ if (this.pendingNativeCli.get(id) !== pending ||
855
+ root !== this.workspaceRoot ||
856
+ pending.controller.signal.aborted)
857
+ return null;
858
+ run = { controller: pending.controller, session: prepared };
859
+ const launchConfig = prepared?.config ?? config;
860
+ const previousEntry = this.find(id);
861
+ const previousRun = this.nativeCliRuns.get(id);
862
+ if (!remote) {
863
+ args[6] = {
864
+ ...opts,
865
+ nativeCliConnection: connection,
866
+ nativeCliLaunchConfig: launchConfig,
867
+ nativeCliEnv: prepared?.env,
868
+ nativeCliRun: run,
869
+ };
870
+ const terminal = this.create(...args);
871
+ if (!terminal)
872
+ return null;
873
+ this.adoptNativeCliRun(id, run, previousRun);
874
+ adopted = true;
875
+ return terminal;
876
+ }
877
+ const service = remoteService;
878
+ if (!service)
879
+ throw new Error("SSH service is unavailable");
880
+ let pty;
881
+ if (observeOnly) {
882
+ run.persistent = await attachPersistentRemoteNativeCli(service, safeCwd, {
883
+ key: persistentRef.key,
884
+ cols,
885
+ rows,
886
+ signal: pending.controller.signal,
887
+ });
888
+ pty = run.persistent.pty;
889
+ }
890
+ else {
891
+ const launch = await resolveRemoteNativeCliLaunch(service, launchConfig, safeCwd, connection, pending.controller.signal);
892
+ if (prepared?.env)
893
+ launch.env = { ...launch.env, ...prepared.env };
894
+ if (this.pendingNativeCli.get(id) !== pending ||
895
+ root !== this.workspaceRoot ||
896
+ pending.controller.signal.aborted)
897
+ return null;
898
+ if (config.keepAlive) {
899
+ run.persistent = await openPersistentRemoteNativeCli(service, safeCwd, launch, {
900
+ key: persistentRef.key,
901
+ cols,
902
+ rows,
903
+ signal: pending.controller.signal,
904
+ });
905
+ pty = run.persistent.pty;
906
+ }
907
+ else
908
+ pty = await service.createCommandPty(safeCwd, launch, cols, rows, { signal: pending.controller.signal });
909
+ }
910
+ if (this.pendingNativeCli.get(id) !== pending ||
911
+ root !== this.workspaceRoot ||
912
+ pending.controller.signal.aborted ||
913
+ !this.ensureSpawnAllowed(id)) {
914
+ pty.kill();
915
+ return null;
916
+ }
917
+ this.registerPty(id, pty, safeCwd, cols, rows, title || "CLI " + ++this.seq, void 0, false, opts.locale, config, run);
918
+ const attached = this.terms.get(id);
919
+ if (attached && previousEntry) {
920
+ if (run.persistent && !run.persistent.created)
921
+ attached.nativeCliCleanups = previousEntry.nativeCliCleanups;
922
+ else
923
+ this.cleanupNativeCli(previousEntry);
924
+ }
925
+ this.history.delete(id);
926
+ this.adoptNativeCliRun(id, run, previousRun);
927
+ adopted = true;
928
+ this.emitList();
929
+ const entry = this.find(id);
930
+ return entry ? this.info(entry) : null;
931
+ }
932
+ catch (err) {
933
+ if (this.pendingNativeCli.get(id) === pending && !pending.controller.signal.aborted) {
934
+ const message = `Failed to start CLI: ${err.message}`;
935
+ this.nativeCliRuntime?.onStatus(id, { phase: "error", error: err.message, updatedAt: Date.now() });
936
+ this.fail(id, message, message);
937
+ this.emitList();
938
+ }
939
+ return null;
940
+ }
941
+ finally {
942
+ if (startupTimer)
943
+ clearTimeout(startupTimer);
944
+ if (!adopted) {
945
+ if (run?.persistent?.created)
946
+ await run.persistent.terminate().catch(() => { });
947
+ await prepared?.dispose().catch(() => { });
948
+ }
949
+ if (this.pendingNativeCli.get(id) === pending)
950
+ this.pendingNativeCli.delete(id);
951
+ }
952
+ })();
953
+ return pending.task;
954
+ }
955
+ adoptNativeCliRun(id, run, previous) {
956
+ if (previous && previous !== run)
957
+ this.releaseNativeCliRun(id, previous);
958
+ this.nativeCliRuns.set(id, run);
959
+ run.processId = this.nativeCliRuntime?.onProcess?.(id, run.persistent?.created ?? true) ?? randomUUID();
960
+ try {
961
+ run.stopWatch = run.session?.start();
962
+ }
963
+ catch {
964
+ this.nativeCliRuntime?.onStatus(id, { nativeEvents: false });
965
+ }
966
+ this.nativeCliRuntime?.onStatus(id, {
967
+ phase: this.terms.has(id) ? "running" : run.persistent ? "disconnected" : "exited",
968
+ updatedAt: Date.now(),
969
+ error: void 0,
970
+ persistent: Boolean(run.persistent),
971
+ nativeEvents: run.session?.capabilities.events === "process" ? false : void 0,
972
+ resumable: Boolean(run.session?.ref.nativeId && run.session.capabilities.resume !== "none"),
973
+ ...(run.session?.ref.nativeId ? { sessionId: run.session.ref.nativeId } : {}),
974
+ });
975
+ if (run.persistent)
976
+ this.armNativeCliProbe(id, run);
977
+ }
978
+ releaseNativeCliRun(id, run) {
979
+ if (run.probeTimer)
980
+ clearTimeout(run.probeTimer);
981
+ run.stopWatch?.();
982
+ run.controller.abort();
983
+ if (this.nativeCliRuns.get(id) === run)
984
+ this.nativeCliRuns.delete(id);
985
+ void run.session?.dispose().catch(() => { });
986
+ }
987
+ armNativeCliProbe(id, run) {
988
+ if (this.nativeCliRuns.get(id) !== run || !run.persistent || run.stopping || run.probeTimer)
989
+ return;
990
+ run.probeTimer = setTimeout(async () => {
991
+ run.probeTimer = void 0;
992
+ try {
993
+ const state = await run.persistent.probe();
994
+ if (this.nativeCliRuns.get(id) !== run || run.stopping)
995
+ return;
996
+ if (!state.alive) {
997
+ await run.session?.flush?.().catch(() => { });
998
+ if (this.nativeCliRuns.get(id) !== run || run.stopping)
999
+ return;
1000
+ const entry = this.find(id);
1001
+ if (entry) {
1002
+ entry.retired = true;
1003
+ this.flushPending(entry);
1004
+ this.terms.delete(id);
1005
+ entry.exited = true;
1006
+ entry.exitCode = state.exitCode ?? null;
1007
+ this.history.set(id, entry);
1008
+ this.cleanupNativeCli(entry);
1009
+ try {
1010
+ entry.pty.kill();
1011
+ }
1012
+ catch { }
1013
+ }
1014
+ this.reportNativeCliProcessExit(id, run, state.exitCode);
1015
+ this.releaseNativeCliRun(id, run);
1016
+ this.nativeCliRuntime?.onStatus(id, {
1017
+ phase: "exited",
1018
+ exitCode: state.exitCode ?? null,
1019
+ updatedAt: Date.now(),
1020
+ });
1021
+ this.emit({ type: "terminal_exit", terminalId: id, exitCode: state.exitCode ?? null });
1022
+ this.emitList();
1023
+ return;
1024
+ }
1025
+ }
1026
+ catch { }
1027
+ this.armNativeCliProbe(id, run);
1028
+ }, 3000);
1029
+ run.probeTimer.unref?.();
1030
+ }
1031
+ reportNativeCliProcessExit(id, run, exitCode) {
1032
+ if (exitCode !== undefined && exitCode !== 0 && !run.stopping && run.session?.capabilities.events === "process") {
1033
+ this.nativeCliRuntime?.onEvent(id, {
1034
+ type: "error",
1035
+ code: "process_exit",
1036
+ message: `CLI exited with code ${exitCode}`,
1037
+ eventId: `process:${run.processId}:exit:${exitCode}`,
1038
+ });
1039
+ }
1040
+ }
1041
+ reportNativeCliActivity(id, entry) {
1042
+ const run = entry.nativeCliRun;
1043
+ const now = Date.now();
1044
+ if (run && now - (run.activityReportedAt ?? 0) >= 2000) {
1045
+ run.activityReportedAt = now;
1046
+ this.nativeCliRuntime?.onStatus(id, { lastActivityAt: now });
1047
+ }
1048
+ }
1049
+ detachNativeCli(id) {
1050
+ const entry = this.terms.get(id);
1051
+ const run = this.nativeCliRuns.get(id);
1052
+ if (!run?.persistent)
1053
+ throw new Error("This CLI does not have remote keep-alive enabled");
1054
+ if (!entry)
1055
+ return;
1056
+ entry.retired = true;
1057
+ entry.nativeCliLifetime?.abort();
1058
+ this.disarmIdleWatch(entry);
1059
+ this.flushPending(entry);
1060
+ this.terms.delete(id);
1061
+ entry.exited = true;
1062
+ entry.exitCode = null;
1063
+ this.history.set(id, entry);
1064
+ try {
1065
+ entry.pty.kill();
1066
+ }
1067
+ catch { }
1068
+ this.nativeCliRuntime?.onStatus(id, { phase: "disconnected", persistent: true, updatedAt: Date.now() });
1069
+ this.emit({ type: "terminal_exit", terminalId: id, exitCode: null });
1070
+ this.emitList();
1071
+ }
1072
+ hasPersistentNativeCli(id) {
1073
+ return Boolean(this.nativeCliRuns.get(id)?.persistent);
1074
+ }
1075
+ async stopNativeCli(id) {
1076
+ const current = this.nativeCliStops.get(id);
1077
+ if (current)
1078
+ return current;
1079
+ const task = this.performNativeCliStop(id);
1080
+ this.nativeCliStops.set(id, task);
1081
+ try {
1082
+ await task;
1083
+ }
1084
+ finally {
1085
+ if (this.nativeCliStops.get(id) === task)
1086
+ this.nativeCliStops.delete(id);
1087
+ }
1088
+ }
1089
+ async performNativeCliStop(id) {
1090
+ const pending = this.pendingNativeCli.get(id);
1091
+ pending?.controller.abort();
1092
+ if (pending)
1093
+ await pending.task;
1094
+ const run = this.nativeCliRuns.get(id);
1095
+ const entry = this.find(id);
1096
+ if (run)
1097
+ run.stopping = true;
1098
+ entry?.nativeCliLifetime?.abort();
1099
+ try {
1100
+ await run?.persistent?.terminate();
1101
+ }
1102
+ catch (error) {
1103
+ if (run)
1104
+ run.stopping = false;
1105
+ if (entry && !entry.retired)
1106
+ entry.nativeCliLifetime = new AbortController();
1107
+ if (run?.persistent)
1108
+ this.armNativeCliProbe(id, run);
1109
+ throw error;
1110
+ }
1111
+ if ((run && this.nativeCliRuns.get(id) !== run) || (entry && this.find(id) !== entry)) {
1112
+ if (entry)
1113
+ this.cleanupNativeCli(entry);
1114
+ if (run)
1115
+ this.releaseNativeCliRun(id, run);
1116
+ return;
1117
+ }
1118
+ if (entry) {
1119
+ this.retireTaskEntry(entry);
1120
+ this.terms.delete(id);
1121
+ entry.exited = true;
1122
+ entry.exitCode = null;
1123
+ this.history.set(id, entry);
1124
+ this.cleanupNativeCli(entry);
1125
+ }
1126
+ if (run)
1127
+ this.releaseNativeCliRun(id, run);
1128
+ this.nativeCliRuntime?.onStatus(id, { phase: "exited", exitCode: null, updatedAt: Date.now() });
1129
+ this.emit({ type: "terminal_exit", terminalId: id, exitCode: null });
1130
+ this.emitList();
1131
+ }
1132
+ create(id, cwd, cols, rows, fallbackCwd, title, opts) {
1133
+ const failed = () => {
1134
+ if (opts?.nativeCli !== undefined)
1135
+ this.emitList();
1136
+ return null;
1137
+ };
1138
+ const valid = this.validateId(id);
1139
+ if (valid) {
1140
+ this.fail(id, valid.text, valid.textEn);
1141
+ return failed();
1142
+ }
1143
+ let nativeCli;
1144
+ try {
1145
+ if (opts?.nativeCli !== undefined)
1146
+ nativeCli = validateNativeCliConfig(opts.nativeCli);
1147
+ }
1148
+ catch (err) {
1149
+ const message = err.message;
1150
+ this.fail(id, message, message);
1151
+ return failed();
1152
+ }
1021
1153
  if (this.terms.has(id))
1022
1154
  return this.info(this.terms.get(id));
1023
- // Every spawn path shares the same admission rule (ensureSpawnAllowed):
1024
- // a NEW live PTY needs a free slot under the cap. Reusing an exited name
1025
- // starts a fresh PTY and discards its old history — but only after the
1026
- // slot check, so a rejected request keeps its retained output.
1027
- // 重建已退出终端时继承其原有身份:前端刷新/重挂载会为 history 里的每条
1028
- // 记录重发 terminal_create,旧消息体不带 agentBash——不继承的话 AI 终端
1029
- // 会被降级为用户终端并占满 16 个名额(issue #147)。history.delete 位于
1030
- // 检查之后,故此处仍可取到旧 entry。
1031
1155
  const priorAgentBash = opts?.agentBash ?? this.history.get(id)?.agentBash ?? false;
1032
1156
  if (!this.ensureSpawnAllowed(id, priorAgentBash))
1033
- return null;
1034
- this.history.delete(id);
1157
+ return failed();
1035
1158
  const safeCwd = this.safeCwd(cwd || fallbackCwd);
1036
1159
  if (!safeCwd) {
1037
1160
  this.fail(id, pick(this.lang?.() ?? "en", "终端工作目录必须位于当前工作区内", "Terminal cwd must be inside the current workspace", "terminals.cwd.outside.workspace"), "Terminal cwd must be inside the current workspace");
1038
- return null;
1161
+ return failed();
1039
1162
  }
1040
- if (this.spawnShell(id, safeCwd, cols, rows, title || `终端 ${++this.seq}`, undefined, opts?.forceBash, priorAgentBash, opts?.locale)) {
1163
+ if (this.spawnShell(id, safeCwd, cols, rows, title || `终端 ${++this.seq}`, undefined, opts?.forceBash, priorAgentBash, opts?.locale, nativeCli, opts?.nativeCliConnection, opts?.nativeCliLaunchConfig, opts?.nativeCliEnv, opts?.nativeCliRun)) {
1164
+ this.history.delete(id);
1041
1165
  this.maybeEmitTccHint(id);
1042
1166
  this.emitList();
1043
1167
  return this.info(this.terms.get(id));
1044
1168
  }
1045
- return null;
1169
+ return failed();
1046
1170
  }
1047
- /** Warn about unavailable camera/mic TCC grants in a fresh terminal, once per client. */
1048
1171
  maybeEmitTccHint(id) {
1049
1172
  if (this.tccHintShown || !launchdSpawnedOnMac())
1050
1173
  return;
1051
1174
  this.tccHintShown = true;
1052
1175
  this.writeOut(id, TCC_HINT);
1053
1176
  }
1054
- /**
1055
- * Start a shell in the command's directory and run the command in it.
1056
- *
1057
- * If a terminal with this id already exists it is RESTARTED in place: the
1058
- * running process is killed and a fresh shell runs the command again in the
1059
- * same terminal (used when re-running a command by clicking its entry).
1060
- */
1061
1177
  runCommand(id, def, cols, rows, pwd, locale) {
1062
1178
  const invalidId = this.validateId(id);
1063
1179
  if (invalidId) {
@@ -1065,10 +1181,6 @@ export class TerminalManager {
1065
1181
  return;
1066
1182
  }
1067
1183
  const existing = this.terms.get(id);
1068
- // Same admission rule as create(): a live terminal may be restarted in
1069
- // place, but a NEW live PTY needs a free slot — an id sitting in history
1070
- // (exited) does NOT grant one, or re-running exited terminals while at
1071
- // the cap could push the live count past MAX_TERMINALS.
1072
1184
  if (!existing && !this.ensureSpawnAllowed(id))
1073
1185
  return;
1074
1186
  const rawDir = resolveCommandCwd(def.cwd, pwd);
@@ -1080,9 +1192,6 @@ export class TerminalManager {
1080
1192
  return;
1081
1193
  }
1082
1194
  if (existing) {
1083
- // Re-run in place: interrupt the current process (kill the PTY's
1084
- // process group) and start a fresh shell with the same id. Keep the
1085
- // last known size so the replacement matches the xterm's dimensions.
1086
1195
  if (!existing.exited) {
1087
1196
  this.retireTaskEntry(existing);
1088
1197
  }
@@ -1096,8 +1205,6 @@ export class TerminalManager {
1096
1205
  if (!ok)
1097
1206
  return;
1098
1207
  this.emitList();
1099
- // Clear the previous run's output, then show a banner and run the command
1100
- // once the fresh shell is ready to read (see writeWhenReady).
1101
1208
  const banner = "\x1b[2J\x1b[3J\x1b[H" + `\x1b[90m> ${command}\x1b[0m \x1b[90m(${dir})\x1b[0m\r\n`;
1102
1209
  const fresh = this.terms.get(id);
1103
1210
  if (fresh)
@@ -1107,15 +1214,6 @@ export class TerminalManager {
1107
1214
  if (command)
1108
1215
  this.writeWhenReady(id, command + "\r");
1109
1216
  }
1110
- /**
1111
- * Type text into a freshly spawned shell once it is ready to read.
1112
- *
1113
- * Input written to a brand-new PTY before its shell is reading can lose
1114
- * the first bytes (Windows ConPTY is the usual victim — the classic
1115
- * symptom is `pi-web-ui` arriving as `i-web-ui`). The shell's first
1116
- * output is the readiness signal; a timeout covers shells that start
1117
- * silent. Stale entries (restarted/killed while waiting) are skipped.
1118
- */
1119
1217
  writeWhenReady(id, text, timeoutMs = 1500) {
1120
1218
  const entry = this.terms.get(id);
1121
1219
  if (!entry || entry.exited)
@@ -1130,9 +1228,7 @@ export class TerminalManager {
1130
1228
  try {
1131
1229
  disp?.dispose();
1132
1230
  }
1133
- catch {
1134
- // PTY already gone — the stale-entry guard below no-ops.
1135
- }
1231
+ catch { }
1136
1232
  const live = this.terms.get(id);
1137
1233
  if (!live || live !== entry || live.exited)
1138
1234
  return;
@@ -1143,12 +1239,9 @@ export class TerminalManager {
1143
1239
  try {
1144
1240
  disp = entry.pty.onData(() => send());
1145
1241
  }
1146
- catch {
1147
- // Spawn failed between the lookup and now — timer fallback no-ops.
1148
- }
1242
+ catch { }
1149
1243
  }
1150
- /** Spawn the user's shell as a PTY. Returns false when the spawn failed. */
1151
- spawnShell(id, cwd, cols, rows, title, command, forceBash, agentBash = false, locale) {
1244
+ spawnShell(id, cwd, cols, rows, title, command, forceBash, agentBash = false, locale, nativeCli, nativeCliConnection, nativeCliLaunchConfig, nativeCliEnv, nativeCliRun) {
1152
1245
  let abs = cwd;
1153
1246
  let shell;
1154
1247
  let args;
@@ -1157,6 +1250,10 @@ export class TerminalManager {
1157
1250
  : this.workspaceRoot && this.workspaceRoot.startsWith("ssh://")
1158
1251
  ? this.workspaceRoot
1159
1252
  : null;
1253
+ if (nativeCli && targetUri) {
1254
+ this.fail(id, "远程 CLI 需要异步启动", "Remote CLI requires asynchronous startup");
1255
+ return false;
1256
+ }
1160
1257
  if (targetUri) {
1161
1258
  const match = /^ssh:\/\/([^@]+)@([^:]+):(\d+)(\/.*)$/.exec(targetUri);
1162
1259
  if (match) {
@@ -1197,11 +1294,22 @@ export class TerminalManager {
1197
1294
  shell = s.shell;
1198
1295
  args = s.args;
1199
1296
  }
1200
- // node-pty's spawn-helper may have lost its +x bit since the last repair
1201
1297
  // (e.g. a global npm install replaced the helper while this server runs).
1202
1298
  repairSpawnHelperPermissions();
1203
1299
  let pty;
1300
+ let env = { ...shellEnv(), ...nativeCliEnv };
1204
1301
  try {
1302
+ if (nativeCli) {
1303
+ const launch = resolveNativeCliLaunch(nativeCliLaunchConfig ?? nativeCli, {
1304
+ cwd: abs,
1305
+ env,
1306
+ modelConnection: nativeCliConnection,
1307
+ });
1308
+ if (launch.env)
1309
+ env = launch.env;
1310
+ shell = launch.file;
1311
+ args = launch.args;
1312
+ }
1205
1313
  const sshSvc = targetUri ? getGlobalRemoteSshService() : null;
1206
1314
  if (targetUri && sshSvc) {
1207
1315
  pty = sshSvc.createVirtualPty(targetUri, cols, rows);
@@ -1212,7 +1320,8 @@ export class TerminalManager {
1212
1320
  cols: Math.max(2, Math.floor(cols) || 80),
1213
1321
  rows: Math.max(2, Math.floor(rows) || 24),
1214
1322
  cwd: abs,
1215
- env: shellEnv(),
1323
+ env,
1324
+ useConptyDll: process.platform === "win32",
1216
1325
  });
1217
1326
  }
1218
1327
  }
@@ -1225,16 +1334,23 @@ export class TerminalManager {
1225
1334
  : `Failed to start terminal: ${err.message}`);
1226
1335
  return false;
1227
1336
  }
1337
+ this.registerPty(id, pty, abs, cols, rows, title, command, agentBash, locale, nativeCli, nativeCliRun);
1338
+ return true;
1339
+ }
1340
+ registerPty(id, pty, cwd, cols, rows, title, command, agentBash = false, locale, nativeCli, nativeCliRun) {
1228
1341
  const entry = {
1229
1342
  id,
1230
1343
  pty,
1231
1344
  title,
1232
- cwd: abs,
1345
+ cwd,
1233
1346
  cols: Math.max(2, Math.floor(cols) || 80),
1234
1347
  rows: Math.max(2, Math.floor(rows) || 24),
1235
1348
  exited: false,
1236
1349
  exitCode: null,
1237
1350
  command,
1351
+ nativeCli,
1352
+ nativeCliLifetime: nativeCli ? new AbortController() : undefined,
1353
+ nativeCliRun,
1238
1354
  output: "",
1239
1355
  outputOffset: 0,
1240
1356
  waiters: new Set(),
@@ -1245,44 +1361,28 @@ export class TerminalManager {
1245
1361
  idleTimer: null,
1246
1362
  watches: [],
1247
1363
  agentBash,
1248
- // 有命令的终端(runCommand)与 ai-bash 天生就是“用过”的;裸 shell
1249
- // 从 pristine 开始,第一次输入/agent 触碰时才置位(见 inputChecked /
1250
- // noteAgentActivity)。
1251
- used: agentBash || command !== undefined,
1364
+ used: agentBash || command !== undefined || nativeCli !== undefined,
1252
1365
  locale,
1253
1366
  agentPendingLine: "",
1254
1367
  };
1255
1368
  this.terms.set(id, entry);
1256
- // The closures capture `entry`: after a restart the map points at the
1257
- // replacement, so a late event from the OLD pty must be ignored.
1258
1369
  pty.onData((data) => {
1259
- if (this.terms.get(id) !== entry)
1370
+ if (this.terms.get(id) !== entry || entry.retired)
1260
1371
  return;
1261
1372
  this.appendOutput(entry, data);
1262
- // Coalesce instead of emitting per chunk: node-pty onData fires per
1263
- // ConPTY read buffer (dozens of bytes to a few KB each), so a build or
1264
- // `cat` of a big file used to produce hundreds/thousands of WS frames
1265
- // per second — each paying stringify + frame + parse + dispatch cost.
1266
- // A one-frame micro-batch cuts the frame rate 10-50× at ≤16ms latency
1267
- // (imperceptible; xterm writes batch data more efficiently anyway).
1373
+ if (entry.nativeCli)
1374
+ this.reportNativeCliActivity(id, entry);
1268
1375
  this.queueOut(entry, data);
1269
1376
  });
1270
1377
  pty.onExit(({ exitCode }) => {
1271
- if (this.terms.get(id) !== entry)
1378
+ if (this.terms.get(id) !== entry || entry.retired)
1272
1379
  return;
1273
- this.exit(id, exitCode);
1380
+ if (entry.nativeCliRun?.persistent)
1381
+ this.detachNativeCli(id);
1382
+ else
1383
+ this.exit(id, exitCode);
1274
1384
  });
1275
- return true;
1276
1385
  }
1277
- /**
1278
- * 记录一次 agent 工具触碰并启动一个新的静默纪元(terminal_create /
1279
- * terminal_input / terminal_key 的工具包装层调用——浏览器路径绝不调用,
1280
- * 用户自己开的终端永远不会收到静默提醒)。
1281
- *
1282
- * 纪元语义(防骚扰):agentTouched 同时是「纪元武装」标志。看门狗触发
1283
- * 一次后即解除武装,之后无论静默多久都不再提醒,直到 agent 再次触碰
1284
- * (再发输入 = AI 又在等结果了)。纪元内的每一段输出都重置倒计时。
1285
- */
1286
1386
  noteAgentActivity(id) {
1287
1387
  const entry = this.terms.get(id);
1288
1388
  if (!entry || entry.exited)
@@ -1292,7 +1392,6 @@ export class TerminalManager {
1292
1392
  entry.lastActivityAt = Date.now();
1293
1393
  this.armIdleWatch(entry);
1294
1394
  }
1295
- /** 武装(或按当前 lastActivityAt 重置)静默看门狗。 */
1296
1395
  armIdleWatch(entry) {
1297
1396
  if (entry.idleTimer) {
1298
1397
  clearTimeout(entry.idleTimer);
@@ -1304,23 +1403,17 @@ export class TerminalManager {
1304
1403
  const delay = Math.max(0, idleMs - (Date.now() - entry.lastActivityAt));
1305
1404
  entry.idleTimer = setTimeout(() => {
1306
1405
  entry.idleTimer = null;
1307
- // 原地重启/退出后旧 entry 的事件必须忽略(与 onData/onExit 同款守卫)。
1308
1406
  if (this.terms.get(entry.id) !== entry || entry.exited)
1309
1407
  return;
1310
- // 一次性:触发后解除武装,直到下次 agent 触碰。
1311
1408
  entry.agentTouched = false;
1312
- // 附带最近 N 行输出(可配),便于 AI 直接看到终端当前状态。
1313
1409
  const lastLines = queryTerminalOutput(entry.output, { tail: terminalIdleNotifyLines() })?.text ?? "";
1314
1410
  this.onAgentIdle?.(entry.id, Date.now() - entry.lastActivityAt, entry.title, lastLines);
1315
1411
  }, delay);
1316
1412
  entry.idleTimer.unref?.();
1317
1413
  }
1318
- /** Emit output immediately, bypassing the coalescing window (rare paths:
1319
- * one-shot hints/banners — not per-chunk data). */
1320
1414
  writeOut(id, data) {
1321
1415
  this.emit({ type: "terminal_output", terminalId: id, data });
1322
1416
  }
1323
- /** Queue output for the coalescing window; flushes via flushPending. */
1324
1417
  queueOut(entry, data) {
1325
1418
  entry.pendingOut += data;
1326
1419
  if (entry.flushTimer)
@@ -1330,7 +1423,6 @@ export class TerminalManager {
1330
1423
  this.flushPending(entry);
1331
1424
  }, OUTPUT_FLUSH_MS);
1332
1425
  }
1333
- /** Emit everything queued for this terminal (no-op when nothing pending). */
1334
1426
  flushPending(entry) {
1335
1427
  if (entry.flushTimer) {
1336
1428
  clearTimeout(entry.flushTimer);
@@ -1352,11 +1444,9 @@ export class TerminalManager {
1352
1444
  for (const wake of entry.waiters)
1353
1445
  wake();
1354
1446
  entry.waiters.clear();
1355
- // 纪元内的输出重置静默倒计时。
1356
1447
  entry.lastActivityAt = Date.now();
1357
1448
  if (entry.idleTimer)
1358
1449
  this.armIdleWatch(entry);
1359
- // 输出观察器:累积匹配,命中一次即移除(终端接管 bash 的完成检测)。
1360
1450
  if (entry.watches.length > 0) {
1361
1451
  const remaining = [];
1362
1452
  const hits = [];
@@ -1367,7 +1457,7 @@ export class TerminalManager {
1367
1457
  if (w.buf.length > 64_000)
1368
1458
  w.buf = w.buf.slice(-32_000);
1369
1459
  if (m)
1370
- hits.push({ w, m }); // 命中 → 移出(cb 在下面统一触发)
1460
+ hits.push({ w, m });
1371
1461
  else
1372
1462
  remaining.push(w);
1373
1463
  }
@@ -1385,21 +1475,13 @@ export class TerminalManager {
1385
1475
  }
1386
1476
  return null;
1387
1477
  }
1388
- /**
1389
- * Admission control for EVERY spawn path (create / runCommand): spawning a
1390
- * NEW live PTY is only allowed while the live count is below MAX_TERMINALS.
1391
- * Restarting an id that is ALREADY live is always allowed (no extra slot).
1392
- * History entries (exited terminals) do not reserve a slot — re-spawning
1393
- * one while at the cap is rejected with the standard error feedback.
1394
- * 终端接管 bash(ai-bash,agentBash=true)永远放行:它由 API 自动创建且
1395
- * 常驻,不占用户的名额,也不受用户已开满上限影响。
1396
- */
1397
1478
  ensureSpawnAllowed(id, agentBash = false) {
1398
1479
  if (this.terms.has(id))
1399
1480
  return true;
1400
1481
  if (agentBash)
1401
1482
  return true;
1402
- const liveUser = [...this.terms.values()].filter((t) => !t.agentBash).length;
1483
+ const pendingUser = [...this.pendingNativeCli.keys()].filter((key) => key !== id && !this.terms.has(key)).length;
1484
+ const liveUser = [...this.terms.values()].filter((t) => !t.agentBash).length + pendingUser;
1403
1485
  if (liveUser >= MAX_TERMINALS) {
1404
1486
  this.fail(id, `终端数量已达上限(${MAX_TERMINALS})`, `Terminal limit reached (${MAX_TERMINALS})`);
1405
1487
  return false;
@@ -1407,10 +1489,6 @@ export class TerminalManager {
1407
1489
  return true;
1408
1490
  }
1409
1491
  safeCwd(raw) {
1410
- // 远程工作区的根是 ssh:// URI:下面的本地文件系统边界(realpath/relative)
1411
- // 无法解析它,会让远程终端的每次创建/接管命令都被「必须位于工作区内」拒掉,
1412
- // spawnShell 的远程分支成为死代码。远程侧的目录边界由 SSH 服务在远端校验,
1413
- // 这里只做同主机校验与 URI 规范化(spawnShell 的 URI 正则要求带端口)。
1414
1492
  if (isRemoteWorkspaceUri(this.workspaceRoot)) {
1415
1493
  const root = parseRemoteWorkspaceUri(this.workspaceRoot);
1416
1494
  if (!root)
@@ -1427,7 +1505,6 @@ export class TerminalManager {
1427
1505
  return null;
1428
1506
  return `ssh://${cand.username}@${cand.host}:${cand.port}${candidatePath}`;
1429
1507
  }
1430
- // 相对/本地写法一律挂到远程根下解析(与本地分支 resolve(root, raw) 同语义)
1431
1508
  const rel = String(raw).replace(/\\/g, "/").replace(/^\/+/, "");
1432
1509
  const joined = posix.normalize(`${root.remotePath}/${rel}`).replace(/\/+$/, "") || "/";
1433
1510
  const prefix = root.remotePath === "/" ? "/" : `${root.remotePath}/`;
@@ -1443,9 +1520,7 @@ export class TerminalManager {
1443
1520
  return candidate;
1444
1521
  }
1445
1522
  }
1446
- catch {
1447
- // Missing directories and broken symlinks are rejected by the boundary.
1448
- }
1523
+ catch { }
1449
1524
  return null;
1450
1525
  }
1451
1526
  info(entry) {
@@ -1458,12 +1533,13 @@ export class TerminalManager {
1458
1533
  running: !entry.exited,
1459
1534
  exitCode: entry.exitCode,
1460
1535
  command: entry.command,
1536
+ nativeCli: entry.nativeCli ? validateNativeCliConfig(entry.nativeCli) : undefined,
1461
1537
  agentBash: entry.agentBash,
1462
1538
  ownerKind: this.ownerKind,
1463
1539
  };
1464
1540
  }
1465
1541
  has(id) {
1466
- return this.terms.has(id) || this.history.has(id);
1542
+ return this.terms.has(id) || this.history.has(id) || this.pendingNativeCli.has(id);
1467
1543
  }
1468
1544
  find(id) {
1469
1545
  return this.terms.get(id) ?? this.history.get(id);
@@ -1471,10 +1547,6 @@ export class TerminalManager {
1471
1547
  list() {
1472
1548
  return [...this.terms.values(), ...this.history.values()].map((entry) => this.info(entry));
1473
1549
  }
1474
- /** Count of LIVE PTYs only — exited terminals that merely retain their
1475
- * output for review (history) do NOT count. Conversations are kept in the
1476
- * running list while a live terminal exists; exited leftovers must not
1477
- * pin an idle conversation forever. */
1478
1550
  countLive() {
1479
1551
  let n = 0;
1480
1552
  for (const entry of this.terms.values())
@@ -1482,14 +1554,6 @@ export class TerminalManager {
1482
1554
  n++;
1483
1555
  return n;
1484
1556
  }
1485
- /** Count of LIVE terminals that were actually used (typed into / ran a
1486
- * command / touched by the agent / ai-bash). Pristine shells — e.g. the
1487
- * one auto-created when the user opens the terminal tab but never types
1488
- * anything — do NOT count: they hold no foreground work and no shell
1489
- * state worth protecting, so they neither retain the conversation nor
1490
- * block its dismissal (they are killed together with the conversation).
1491
- * Retained-output history never counts either (same as countLive).
1492
- * 存活且“用过”的终端数——对话保留只看这个口径(含 AI bash:切走不杀后台活)。 */
1493
1557
  countBlockingLive() {
1494
1558
  let n = 0;
1495
1559
  for (const entry of this.terms.values())
@@ -1497,34 +1561,24 @@ export class TerminalManager {
1497
1561
  n++;
1498
1562
  return n;
1499
1563
  }
1500
- /** Count of LIVE *user* terminals that were actually used. AI terminals
1501
- * (agentBash — 终端接管 bash 的一次性/持久终端) are EXCLUDED: they are
1502
- * internal execution records owned by the agent, killed together with the
1503
- * conversation on dismissal (removeConversation 里 killAll), so they must
1504
- * never block it (issue #181:残留 ai-bash-98/99 把会话永久钉在列表里)。
1505
- * 只保护用户在交互式终端里的现场:用户亲手开且用过的存活终端才阻断移出。 */
1506
1564
  countUserBlockingLive() {
1507
1565
  let n = 0;
1508
- for (const entry of this.terms.values())
1509
- if (!entry.exited && entry.used && !entry.agentBash)
1566
+ for (const entry of this.terms.values()) {
1567
+ if (!entry.exited && entry.used && !entry.agentBash && !(this.ownerKind === "conversation" && entry.nativeCli))
1510
1568
  n++;
1569
+ }
1511
1570
  return n;
1512
1571
  }
1513
1572
  emitList() {
1514
1573
  this.emit({ type: "terminal_list", terminals: this.list() });
1515
1574
  }
1516
- /** Replay the retained output window after switching back to this conversation. */
1517
1575
  replay() {
1518
- // Deliver coalesced live output before resetting viewers to the retained window.
1519
1576
  for (const entry of this.terms.values())
1520
1577
  this.flushPending(entry);
1521
1578
  return [...this.terms.values(), ...this.history.values()]
1522
1579
  .filter((entry) => entry.output.length > 0)
1523
1580
  .map((entry) => ({ terminalId: entry.id, data: entry.output }));
1524
1581
  }
1525
- /** Read output after an absolute cursor.
1526
- * commandPending:终端接管 bash 注入的命令是否仍未见到退出码哨兵(即 shell 级 running
1527
- * 之外的「这条命令结束了没有」)。手工 terminal_input 的命令没有哨兵,不计入。 */
1528
1582
  read(id, cursor = 0, maxBytes = 20_000) {
1529
1583
  const entry = this.find(id);
1530
1584
  if (!entry)
@@ -1560,15 +1614,56 @@ export class TerminalManager {
1560
1614
  signal?.addEventListener("abort", done, { once: true });
1561
1615
  });
1562
1616
  }
1617
+ captureNativeCliPasteTarget(id) {
1618
+ const entry = this.terms.get(id);
1619
+ if (!entry?.nativeCli || entry.exited || entry.retired || entry.nativeCliRun?.stopping)
1620
+ return undefined;
1621
+ const lifetime = entry.nativeCliLifetime;
1622
+ return {
1623
+ cwd: entry.cwd,
1624
+ signal: lifetime.signal,
1625
+ paste: (data) => !lifetime.signal.aborted &&
1626
+ this.terms.get(id) === entry &&
1627
+ !entry.exited &&
1628
+ !entry.retired &&
1629
+ !entry.nativeCliRun?.stopping &&
1630
+ this.pasteNativeCli(id, data),
1631
+ retainCleanup: (cleanup, paths) => {
1632
+ if (lifetime.signal.aborted ||
1633
+ this.terms.get(id) !== entry ||
1634
+ entry.exited ||
1635
+ entry.retired ||
1636
+ entry.nativeCliRun?.stopping)
1637
+ return false;
1638
+ if (paths?.length)
1639
+ this.nativeCliRuntime?.onRetainFiles?.(id, paths);
1640
+ (entry.nativeCliCleanups ??= new Set()).add(cleanup);
1641
+ return true;
1642
+ },
1643
+ };
1644
+ }
1645
+ getNativeCliTerminal(id) {
1646
+ const entry = this.terms.get(id);
1647
+ return entry && !entry.exited && !entry.nativeCliRun?.stopping && entry.nativeCli ? this.info(entry) : undefined;
1648
+ }
1649
+ pasteNativeCli(id, data) {
1650
+ if (!this.getNativeCliTerminal(id) || typeof data !== "string")
1651
+ return false;
1652
+ const text = sanitizeNativeCliPaste(data);
1653
+ if (!text.trim() || text.length > MAX_NATIVE_CLI_PASTE || Buffer.byteLength(text, "utf8") > MAX_NATIVE_CLI_PASTE)
1654
+ return false;
1655
+ return this.inputChecked(id, `\x1b[200~${text}\x1b[201~`) === null;
1656
+ }
1563
1657
  inputChecked(id, data) {
1564
1658
  if (data.length > MAX_INPUT)
1565
1659
  return `输入过长(上限 ${MAX_INPUT} 字符) Input too long (max ${MAX_INPUT} chars)`;
1566
1660
  const entry = this.terms.get(id);
1567
1661
  if (!entry || entry.exited)
1568
1662
  return pick(this.lang?.() ?? "en", "终端不存在或进程已退出", "Terminal not found or its process has exited", "terminals.not.found.exited");
1569
- // 已武装的纪元里任何人(含用户手动敲键盘)写了输入都算新活动,重置倒计时。
1570
- // 成功的输入同时把终端标为“用过”(见 used):动过的 shell 才参与对话保留/
1571
- // 关闭拦截,没动过的空 shell 不算。仿真器自动应答探针(CPR/DA 等)不计入用过。
1663
+ if (entry.nativeCliRun?.stopping)
1664
+ return "CLI is stopping";
1665
+ if (entry.nativeCli && !isTerminalQueryResponse(data))
1666
+ this.reportNativeCliActivity(id, entry);
1572
1667
  entry.lastActivityAt = Date.now();
1573
1668
  if (entry.idleTimer)
1574
1669
  this.armIdleWatch(entry);
@@ -1584,7 +1679,6 @@ export class TerminalManager {
1584
1679
  return encoded.error;
1585
1680
  return this.inputChecked(id, encoded.data);
1586
1681
  }
1587
- /** 解除静默看门狗(退出/关闭/全部停止时)。 */
1588
1682
  disarmIdleWatch(entry) {
1589
1683
  if (entry.idleTimer) {
1590
1684
  clearTimeout(entry.idleTimer);
@@ -1592,7 +1686,6 @@ export class TerminalManager {
1592
1686
  }
1593
1687
  entry.agentTouched = false;
1594
1688
  }
1595
- /** 只拆钟不清标记(终端接管 bash 阻塞期间挂起活力提醒,避免双重通知)。 */
1596
1689
  suspendIdleWatch(id) {
1597
1690
  const entry = this.terms.get(id);
1598
1691
  if (!entry || !entry.idleTimer)
@@ -1600,27 +1693,17 @@ export class TerminalManager {
1600
1693
  clearTimeout(entry.idleTimer);
1601
1694
  entry.idleTimer = null;
1602
1695
  }
1603
- /** 输出末尾的绝对 cursor(terminal-backed bash 的读取起点)。 */
1604
1696
  endCursor(id) {
1605
1697
  const entry = this.find(id);
1606
1698
  if (!entry)
1607
1699
  return null;
1608
1700
  return entry.outputOffset + entry.output.length;
1609
1701
  }
1610
- /**
1611
- * 阻塞等待当前前台命令结束(哨兵行出现或终端退出)。terminal_wait 工具
1612
- * 用它在静默解阻后「重新加入等待」——AI 不必反复 terminal_read 轮询。
1613
- *
1614
- * @param afterCursor 只认该绝对偏移之后的哨兵(排除上一条命令残留的旧标记;
1615
- * 调用方传 endCursor() 即表示「等我调用之后才出现的结束」)
1616
- * @returns finished=false 表示超时/中止(命令仍在跑),可再次调用继续等
1617
- */
1618
1702
  async waitForCompletion(id, timeoutMs, signal, afterCursor = 0) {
1619
1703
  const entry = this.find(id);
1620
1704
  if (!entry)
1621
1705
  return { finished: false, exitCode: null };
1622
1706
  return new Promise((resolve) => {
1623
- // 命令可能在调用前就已结束:先扫 afterCursor 之后的存量缓冲。
1624
1707
  const relStart = Math.max(0, afterCursor - entry.outputOffset);
1625
1708
  const segment = entry.output.slice(relStart);
1626
1709
  const completionRe = entry.sentinelNonce ? sentinelReFor(entry.sentinelNonce) : BASH_SENTINEL_RE;
@@ -1649,7 +1732,6 @@ export class TerminalManager {
1649
1732
  resolve(r);
1650
1733
  };
1651
1734
  unwatch = this.watchOutput(id, completionRe, (m) => {
1652
- // m=null = 终端被关闭/退出 → 命令肯定结束了(退出码未知)。
1653
1735
  done({ finished: true, exitCode: m ? Number(m[1]) : entry.exitCode });
1654
1736
  });
1655
1737
  if (settled)
@@ -1661,7 +1743,6 @@ export class TerminalManager {
1661
1743
  onAbort();
1662
1744
  });
1663
1745
  }
1664
- /** 标记/清除「哨兵待决」状态(终端接管 bash 工具专用)。 */
1665
1746
  setSentinelPending(id, pending, nonce) {
1666
1747
  const entry = this.find(id);
1667
1748
  if (!entry || (!pending && nonce !== undefined && entry.sentinelNonce !== nonce))
@@ -1670,23 +1751,19 @@ export class TerminalManager {
1670
1751
  if (pending)
1671
1752
  entry.sentinelNonce = nonce;
1672
1753
  }
1673
- /** Snapshot task termination without confusing a closed shell with silence. */
1674
1754
  bashTaskState(id) {
1675
1755
  const entry = this.find(id);
1676
1756
  return { exited: !entry || entry.exited || entry.retired === true, exitCode: entry?.exitCode ?? null };
1677
1757
  }
1678
- /** 是否有带哨兵的命令尚未结束(terminal_wait 的适用性判断)。 */
1679
1758
  isSentinelPending(id) {
1680
1759
  return this.find(id)?.sentinelPending === true;
1681
1760
  }
1682
- /** 注册一次性输出观察器:命中 re 或终端退出时回调一次。返回注销函数。 */
1683
1761
  watchOutput(id, re, cb) {
1684
1762
  const entry = this.find(id);
1685
1763
  if (!entry || entry.exited || entry.retired) {
1686
1764
  cb(null);
1687
1765
  return () => { };
1688
1766
  }
1689
- // 每个观察器独立 regex 实例(global 正则的 lastIndex 是共享可变状态)。
1690
1767
  const own = new RegExp(re.source, re.flags);
1691
1768
  const watch = { re: own, buf: "", cb };
1692
1769
  entry.watches.push(watch);
@@ -1694,7 +1771,6 @@ export class TerminalManager {
1694
1771
  entry.watches = entry.watches.filter((w) => w !== watch);
1695
1772
  };
1696
1773
  }
1697
- /** Emit a terminal failure (bad cwd, spawn error) and mark the terminal dead. */
1698
1774
  fail(id, text, textEn) {
1699
1775
  this.emit({ type: "notice", level: "error", text, textEn });
1700
1776
  this.emit({
@@ -1709,23 +1785,18 @@ export class TerminalManager {
1709
1785
  if (!entry || entry.exited)
1710
1786
  return;
1711
1787
  this.disarmIdleWatch(entry);
1712
- // Flush queued output BEFORE the exit marker so ordering is preserved.
1713
- // Banner text is CLIENT-rendered (live locale); the stream carries only
1714
- // a machine sentinel the client strips and replaces.
1715
1788
  this.flushPending(entry);
1716
1789
  const marker = `\r\n[pi-term-exit:${exitCode}]\r\n`;
1717
1790
  this.appendOutput(entry, marker);
1718
1791
  this.emit({ type: "terminal_output", terminalId: id, data: marker });
1719
1792
  entry.exited = true;
1720
1793
  entry.exitCode = exitCode;
1721
- // 终端退出 → 未命中的输出观察器以 null 回调(宿主可据此通知「终端已关闭」)。
1794
+ this.cleanupNativeCli(entry);
1722
1795
  const pendingWatches = entry.watches;
1723
1796
  entry.watches = [];
1724
1797
  for (const w of pendingWatches)
1725
1798
  w.cb(null);
1726
1799
  this.terms.delete(id);
1727
- // 进程已退出,立即释放底层的 PTY 句柄(Windows ConPTY / HPCON / sockets 等),
1728
- // 避免已退出的终端长期占用 ConPTY 与 MSYS2 控制台资源(issue #269)。
1729
1800
  this.killNative(entry);
1730
1801
  while (this.history.size >= MAX_TERMINAL_HISTORY) {
1731
1802
  const oldest = this.history.keys().next().value;
@@ -1737,6 +1808,15 @@ export class TerminalManager {
1737
1808
  this.history.delete(oldest);
1738
1809
  }
1739
1810
  this.history.set(id, entry);
1811
+ this.nativeCliRuntime?.onStatus(id, { phase: "exited", exitCode, updatedAt: Date.now() });
1812
+ const run = entry.nativeCliRun;
1813
+ if (run)
1814
+ void (async () => {
1815
+ await run.session?.flush?.().catch(() => { });
1816
+ if (this.nativeCliRuns.get(id) === run)
1817
+ this.reportNativeCliProcessExit(id, run, exitCode);
1818
+ this.releaseNativeCliRun(id, run);
1819
+ })();
1740
1820
  this.emit({ type: "terminal_exit", terminalId: id, exitCode });
1741
1821
  this.emitList();
1742
1822
  }
@@ -1752,22 +1832,30 @@ export class TerminalManager {
1752
1832
  return;
1753
1833
  try {
1754
1834
  entry.pty.resize(Math.max(2, Math.floor(cols) || 80), Math.max(2, Math.floor(rows) || 24));
1755
- // Remember the size so an in-place restart spawns at the same dims.
1756
1835
  entry.cols = Math.max(2, Math.floor(cols) || 80);
1757
1836
  entry.rows = Math.max(2, Math.floor(rows) || 24);
1758
1837
  }
1759
- catch {
1760
- // PTY already gone — nothing to do.
1761
- }
1838
+ catch { }
1839
+ }
1840
+ cleanupNativeCli(entry) {
1841
+ entry.nativeCliLifetime?.abort();
1842
+ const cleanups = [...(entry.nativeCliCleanups ?? [])];
1843
+ entry.nativeCliCleanups?.clear();
1844
+ void Promise.allSettled(cleanups.map((cleanup) => Promise.resolve().then(cleanup)));
1762
1845
  }
1763
- /** Retire callbacks against this exact generation without faking native exit. */
1764
1846
  retireTaskEntry(entry, shutdown = false) {
1765
1847
  if (entry.retired)
1766
1848
  return;
1849
+ entry.retired = true;
1850
+ if (entry.nativeCliRun) {
1851
+ entry.nativeCliRun.stopping = true;
1852
+ if (!entry.nativeCliRun.persistent)
1853
+ this.releaseNativeCliRun(entry.id, entry.nativeCliRun);
1854
+ }
1855
+ this.cleanupNativeCli(entry);
1767
1856
  this.disarmIdleWatch(entry);
1768
1857
  this.flushPending(entry);
1769
1858
  this.killNative(entry, shutdown);
1770
- entry.retired = true;
1771
1859
  entry.sentinelPending = false;
1772
1860
  const watches = entry.watches;
1773
1861
  entry.watches = [];
@@ -1777,8 +1865,17 @@ export class TerminalManager {
1777
1865
  for (const watch of watches)
1778
1866
  watch.cb(null);
1779
1867
  }
1780
- /** Kill one terminal (tab closed), including an exited terminal's retained history. */
1781
1868
  kill(id) {
1869
+ this.pendingNativeCli.get(id)?.controller.abort();
1870
+ const run = this.nativeCliRuns.get(id);
1871
+ if (run?.persistent) {
1872
+ void this.stopNativeCli(id)
1873
+ .then(() => this.kill(id))
1874
+ .catch((error) => {
1875
+ this.emit({ type: "notice", level: "error", text: `Failed to stop remote CLI: ${error.message}` });
1876
+ });
1877
+ return;
1878
+ }
1782
1879
  const entry = this.terms.get(id);
1783
1880
  if (entry) {
1784
1881
  this.retireTaskEntry(entry);
@@ -1795,7 +1892,6 @@ export class TerminalManager {
1795
1892
  return;
1796
1893
  }
1797
1894
  }
1798
- /** Rename a terminal tab (live or retained history). Empty names ignored. */
1799
1895
  rename(id, title) {
1800
1896
  const trimmed = (title ?? "").trim();
1801
1897
  if (!trimmed)
@@ -1806,36 +1902,24 @@ export class TerminalManager {
1806
1902
  entry.title = trimmed;
1807
1903
  this.emitList();
1808
1904
  }
1809
- /**
1810
- * Kill the native PTY (issue #215:Windows ConPTY 关机死锁;issue #269:MSYS2 控制台耗尽死锁)。
1811
- *
1812
- * Windows 下:
1813
- * 1. 若进程已经退出(entry.exited):直接调 pty.kill() 释放 HPCON 句柄
1814
- * (子进程已死、管道见 EOF,绝不会死锁);关机路径跳过,由 OS 回收。
1815
- * 2. 若进程尚未退出(!entry.exited):先向 PTY 写入 \x03exit\r 优雅关闭(让
1816
- * bash 正常触发清理钩子),300ms 后仍活着再调 pty.kill() 兜底——node-pty 在
1817
- * Windows 上走 console-process-list 做**全树**清理。不再使用裸
1818
- * process.kill(pid)(TerminateProcess):它只杀 ConPTY 附着的单一进程,
1819
- * 且从拿到 pid 到调用之间隔着一个 PID 复用误杀窗口。
1820
- * 3. 关机(shutdown=true):只做优雅写,跳过 pty.kill() 与 300ms 兜底,由 OS
1821
- * 回收(保持 50ms 内退出的关机预算)。
1822
- * 非 Windows 原样直调 pty.kill()(POSIX 下 shell 是直接子进程,pty.kill 足够,
1823
- * 保持既有行为不做额外延迟)。
1824
- */
1825
1905
  killNative(entry, shutdown = false) {
1906
+ if (isRemoteWorkspaceUri(entry.cwd)) {
1907
+ try {
1908
+ entry.pty.kill();
1909
+ }
1910
+ catch { }
1911
+ return;
1912
+ }
1826
1913
  if (process.platform === "win32") {
1827
1914
  if (entry.exited) {
1828
1915
  if (!shutdown) {
1829
1916
  try {
1830
1917
  entry.pty.kill();
1831
1918
  }
1832
- catch {
1833
- // already dead
1834
- }
1919
+ catch { }
1835
1920
  }
1836
1921
  return;
1837
1922
  }
1838
- // 优雅关闭:先发 Ctrl+C,再发 exit\r
1839
1923
  try {
1840
1924
  entry.pty.write("\x03exit\r");
1841
1925
  }
@@ -1848,9 +1932,7 @@ export class TerminalManager {
1848
1932
  try {
1849
1933
  entry.pty.kill();
1850
1934
  }
1851
- catch {
1852
- // already dead
1853
- }
1935
+ catch { }
1854
1936
  }, 300);
1855
1937
  t.unref?.();
1856
1938
  return;
@@ -1858,56 +1940,52 @@ export class TerminalManager {
1858
1940
  try {
1859
1941
  entry.pty.kill();
1860
1942
  }
1861
- catch {
1862
- // already dead
1863
- }
1943
+ catch { }
1864
1944
  }
1865
- /**
1866
- * Kill every terminal owned by this conversation.
1867
- * @param opts.shutdown=true = 进程关机路径(disposeAll):Windows 下跳过
1868
- * `pty.kill()`(见 killNative),只做 TerminateProcess + 状态清理,50ms 内退出。
1869
- * 日常移出对话走默认 false,必须释放 HPC 句柄。
1870
- */
1871
1945
  killAll(opts) {
1946
+ for (const pending of this.pendingNativeCli.values())
1947
+ pending.controller.abort();
1872
1948
  const shutdown = opts?.shutdown === true;
1873
- for (const entry of this.terms.values()) {
1874
- this.retireTaskEntry(entry, shutdown);
1875
- }
1876
- for (const entry of this.history.values()) {
1877
- this.killNative(entry, shutdown);
1949
+ for (const entry of new Set([...this.terms.values(), ...this.history.values()])) {
1950
+ const run = this.nativeCliRuns.get(entry.id);
1951
+ if (run?.persistent) {
1952
+ if (shutdown)
1953
+ this.releaseNativeCliRun(entry.id, run);
1954
+ else
1955
+ void this.stopNativeCli(entry.id)
1956
+ .catch((error) => {
1957
+ this.emit({
1958
+ type: "notice",
1959
+ level: "error",
1960
+ text: "Remote CLI stop could not be confirmed: " + error.message,
1961
+ });
1962
+ })
1963
+ .finally(() => this.releaseNativeCliRun(entry.id, run));
1964
+ entry.retired = true;
1965
+ entry.nativeCliLifetime?.abort();
1966
+ this.disarmIdleWatch(entry);
1967
+ this.flushPending(entry);
1968
+ this.killNative(entry, shutdown);
1969
+ }
1970
+ else {
1971
+ this.retireTaskEntry(entry, shutdown);
1972
+ if (run)
1973
+ this.releaseNativeCliRun(entry.id, run);
1974
+ }
1878
1975
  }
1879
1976
  this.terms.clear();
1880
1977
  this.history.clear();
1881
1978
  this.emitList();
1882
1979
  }
1883
1980
  }
1884
- // ---------------------------------------------------------------------------
1885
- // 终端接管 bash:bash 风格工具跑在持久可见终端里
1886
- // ---------------------------------------------------------------------------
1887
1981
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1888
- /** 取 collected 尾部里最后一个哨兵匹配(哨兵只可能出现在新输出的尾部)。 */
1889
1982
  function lastSentinel(collected, nonce) {
1890
1983
  const tail = collected.length > 8000 ? collected.slice(-8000) : collected;
1891
1984
  return [...tail.matchAll(sentinelReFor(nonce))].pop() ?? null;
1892
1985
  }
1893
- /**
1894
- * 去掉注入回显、哨兵及其后的 shell 提示符垃圾与 ANSI 序列,还原 bash 风格纯文本。
1895
- *
1896
- * 清洗只依赖两个与时序无关的锚点,不再假定「哨兵回显一定在真实输出之前」——那个假定
1897
- * 在 Windows ConPTY 下不成立:shell 读到哨兵行才回显它,于是哨兵回显排在真实输出之后,
1898
- * 旧实现按它截断会把输出整段吃掉、只剩 `[exit:0]`(#572 ①)。
1899
- *
1900
- * ① 含本次 nonce 哨兵格式串的行(`printf '…[pi-exit-<nonce>:%s]…'` 的回显,
1901
- * 无论出现在输出前还是后)整行删除——nonce 随机,真实输出不可能与之相同。
1902
- * ② 命令回显:第一次出现的命令首行(及其之前的提示符)整段丢弃——它总在真实输出之前。
1903
- * 最后一个本次哨兵之后的内容是 shell 新提示符,整段截掉。
1904
- */
1905
1986
  export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
1906
1987
  const fmt = `[pi-exit-${nonce}:%s]`;
1907
1988
  const rawLines = stripAnsi(raw).replace(/\r\n/g, "\n").split("\n");
1908
- // ConPTY wraps a single physical input line at screen columns, including
1909
- // inside the nonce or printf's final argument. Rejoin only exact fragments
1910
- // of this invocation's generated input, never a generic control-looking line.
1911
1989
  if (command) {
1912
1990
  const injected = injectedLine ?? buildTerminalBashLine(command, undefined, nonce);
1913
1991
  for (let i = 0; i < rawLines.length; i++) {
@@ -1918,8 +1996,6 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
1918
1996
  let end = i;
1919
1997
  for (; end < rawLines.length; end++) {
1920
1998
  let fragment = end === i ? rawLines[end].slice(start) : rawLines[end];
1921
- // Preserve a real space at the wrap boundary; trim screen padding only
1922
- // when the untrimmed fragment cannot belong to the injected command.
1923
1999
  if (!injected.startsWith(fragment, matched))
1924
2000
  fragment = fragment.trimEnd();
1925
2001
  if (!fragment || !injected.startsWith(fragment, matched))
@@ -1932,31 +2008,23 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
1932
2008
  }
1933
2009
  }
1934
2010
  }
1935
- // The complete eval echo includes the printf format and is removed as one
1936
- // physical line. Capture a preceding two-line prompt before removing it.
1937
2011
  const echoAt = rawLines.findIndex((line) => line.includes(fmt));
1938
2012
  const preceding = echoAt > 0 ? rawLines[echoAt - 1].trim() : "";
1939
2013
  const echoedPrompt = /^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+ /.test(preceding) ? preceding : "";
1940
2014
  let lines = rawLines.filter((line, index) => !line.includes(fmt) && !/^\s*\[pi-term-exit:-?\d+\]\s*$/.test(line) && !(echoedPrompt && index === echoAt - 1));
1941
2015
  const anchor = (command.split("\n")[0] ?? "").trim().slice(0, 80);
1942
- // 命令回显前那一行提示符(如 `user@host MINGW64 /cwd`):收尾时用它识别「哨兵前残留的新提示符」。
1943
2016
  let promptLine = echoedPrompt;
1944
- // 锚点找不到(横向滚动只回显尾部 / 回显缺失)时的回落:首个非空行若呈
1945
- // 提示符形状(`user@host … $ ` / `[user@host dir]$ `),按提示符+回显行剥掉,
1946
- // 否则命令回显与提示符会整行留在返回给模型的输出里。
1947
2017
  const fallbackPromptDetect = () => {
1948
2018
  const idx = lines.findIndex((line) => line.trim() !== "");
1949
2019
  if (idx < 0)
1950
2020
  return;
1951
2021
  const first = lines[idx].trim();
1952
- // 单行提示符:`user@host MINGW64 /tmp$ cmd`(MINGW)或 `user@host:~/p$ cmd`(Linux)
1953
2022
  if (/^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+[^\n]*[$#] /.test(first) ||
1954
2023
  /^\[[A-Za-z0-9._-]+@[A-Za-z0-9._-]+[^\]]*\][$#] /.test(first)) {
1955
2024
  promptLine = first;
1956
2025
  lines = lines.slice(idx + 1);
1957
2026
  return;
1958
2027
  }
1959
- // MINGW 双行提示符:`user@host MINGW64 /path` 换行后 `$ cmd`
1960
2028
  if (/^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+ /.test(first) && /^[$#] /.test(lines[idx + 1]?.trim() ?? "")) {
1961
2029
  promptLine = first;
1962
2030
  lines = lines.slice(idx + 2);
@@ -1970,8 +2038,6 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
1970
2038
  if (t && t !== "$")
1971
2039
  promptLine = t;
1972
2040
  }
1973
- // 回显折行:锚点行只含命令的前一段,后续折行若恰好逐行拼接出命令的
1974
- // 剩余文本,也一并剥掉(精确匹配,匹配不上即停,保守不误删输出)。
1975
2041
  const firstLine = (command.split("\n")[0] ?? "").trim();
1976
2042
  const echoLine = lines[echoIdx].trimEnd();
1977
2043
  const anchorAt = echoLine.indexOf(anchor);
@@ -1993,7 +2059,6 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
1993
2059
  else {
1994
2060
  fallbackPromptDetect();
1995
2061
  }
1996
- // 最后一个本次哨兵之后的内容全是 shell 新提示符——整段截掉。
1997
2062
  const text = lines.join("\n");
1998
2063
  const re = sentinelReFor(nonce);
1999
2064
  let last = null;
@@ -2001,8 +2066,6 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
2001
2066
  last = m;
2002
2067
  }
2003
2068
  const kept = (last ? text.slice(0, last.index) : text).split("\n").map((line) => line.trimEnd());
2004
- // 收尾残留:空行、裸 `$`、与命令前相同的提示符行(ConPTY 在哨兵回显前重打了一次提示符)。
2005
- // 提示符的 `user@host` 段:让 cd 之后路径变了的提示符也能识别。
2006
2069
  const promptHead = promptLine.match(/^\S+@\S+/)?.[0] ?? "";
2007
2070
  const isResidue = (line) => {
2008
2071
  const t = line.trim();
@@ -2016,42 +2079,11 @@ export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
2016
2079
  kept.pop();
2017
2080
  return truncateMiddle(kept.join("\n").trim());
2018
2081
  }
2019
- /**
2020
- * 终端接管的 bash 工具:覆盖 SDK 内置 bash,执行体把命令写进可见终端并等哨兵
2021
- * 行拿到真实退出码。参数除 SDK 的 command + timeout 外,还多出 persist / head /
2022
- * tail 三个可选参数。
2023
- *
2024
- * persist=false(默认,一次性):每次新建一个终端(agentBash、单独归「AI bash」
2025
- * 分组、不占用户名额),命令结束 shell 用 exit 退场(进程结束),输出保留在
2026
- * history 供查阅;阻塞到命令结束,不做静默解阻。
2027
- *
2028
- * persist=true(复用 'ai-bash' 持久终端):
2029
- * - 默认阻塞:等到命令结束才返回完整输出(ANSI 已清理)+ 真实退出码;
2030
- * - 静默解阻:连续 idleMs 毫秒无新输出且未结束 → 立即返回「仍在运行」+ 已有
2031
- * 输出,命令留在终端里继续跑,并注册完成观察器——结束后由宿主
2032
- * notifyBackgroundDone 主动通知 AI(流式中 steer / 空闲时 nextTurn);
2033
- * - shell 状态跨调用保留(cd / venv activate / ssh 会话)——这是原生一次性的
2034
- * bash 工具做不到的。
2035
- *
2036
- * 两者都支持 abort(AbortController 注册进 kills 集合,abort 向 PTY 发 Ctrl+C)、
2037
- * timeout,以及 head / tail 参数(只返回前/后 N 行,替代 `| head` / `| tail` 管道)。
2038
- */
2039
- /** 一次性 bash 终端序号:非持久调用每次新建一个终端,进程结束后退出、输出
2040
- * 保留在 history 供查阅——故每调用独立 id,避免复用覆盖旧输出。 */
2041
2082
  let oneShotBashSeq = 0;
2042
- /** head / tail 的运行时上限,与 bash 工具参数 schema 的 maximum 5000 一致
2043
- * (agent-service.ts)——schema 只影响提示不拦运行时(issue #462)。 */
2044
2083
  const MAX_HEAD_TAIL_LINES = 5000;
2045
- /** 应用 head / tail 参数到输出顶层行(替代 `| head` / `| tail` 管道——管道会
2046
- * 缓冲输出、让可见终端全程哑火,还容易白白触发静默解阻)。两者同时给时先
2047
- * 截头再截尾。 */
2048
2084
  export function applyHeadTail(text, head, tail, lang = "en") {
2049
- // 入口钳到 schema 上限:此前只判 >0,传 1e9 会把整段缓冲灌进单条工具结果
2050
- // 并持久化进转录。
2051
2085
  const headN = head && head > 0 ? Math.min(Math.floor(head), MAX_HEAD_TAIL_LINES) : 0;
2052
2086
  const tailN = tail && tail > 0 ? Math.min(Math.floor(tail), MAX_HEAD_TAIL_LINES) : 0;
2053
- // 只对真实数据行切片;省略提示行单独存,最后再包回输出,避免提示行在
2054
- // head+tail 组合时被当成数据行参与第二次截取(导致尾部少截一行)。
2055
2087
  let data = text.split("\n");
2056
2088
  let headNote = null;
2057
2089
  let tailNote = null;
@@ -2082,8 +2114,6 @@ export function makeTerminalBashTool(terminals, opts) {
2082
2114
  return defineTool({
2083
2115
  name: "bash",
2084
2116
  label: "Run bash command",
2085
- // 提示词单源:模型看到的 bash 定义由 makeAdaptiveBashTool 从 tool-prompts.ts 取,
2086
- // 本定义只提供终端这条执行路径(description/schema 必须与另两条一致,不另写一套)。
2087
2117
  description: BASH_DESCRIPTION,
2088
2118
  promptSnippet: BASH_PROMPT_SNIPPET,
2089
2119
  promptGuidelines: BASH_PROMPT_GUIDELINES,
@@ -2092,9 +2122,6 @@ export function makeTerminalBashTool(terminals, opts) {
2092
2122
  const lang = opts.lang?.() ?? "en";
2093
2123
  if (signal?.aborted)
2094
2124
  throw new Error("Command aborted");
2095
- // 语法不完整的命令(续行符结尾 / 未闭合引号 / 未闭合括号组):交互 shell 会停在续行提示符
2096
- // (PS2)零执行,且无法注入退出码哨兵——没有任何办法得知它何时结束。直接拒绝,不建终端、
2097
- // 不注入,避免空等 60 秒后回报「仍在后台运行」这种与事实相反的状态(#571)。
2098
2125
  const incomplete = sentinelUnsafeReason(detectTrailingLimiter(p.command)?.base ?? p.command);
2099
2126
  if (incomplete) {
2100
2127
  const reasonZh = incomplete === "trailing_backslash"
@@ -2118,11 +2145,6 @@ export function makeTerminalBashTool(terminals, opts) {
2118
2145
  throw new Error(pick(lang, `命令语法不完整(${reasonZh}),未执行。终端接管 bash 无法为它注入退出码哨兵,残句还会让 shell 停在续行提示符、零执行。请补全引号 / 续行符 / 括号后重试。`, `Command is syntactically incomplete (${reasonEn}); nothing was executed. The terminal bash path cannot inject an exit-code sentinel here, and the leftover fragment would leave the shell waiting at a continuation prompt. Complete the quote / continuation / bracket and retry.`, "terminals.bash.incomplete", { reason: reasonEn, reasonEn, reasonZh }));
2119
2146
  }
2120
2147
  const persist = p.persist ?? opts.defaultPersist();
2121
- // create() 对已存活的同名终端原样返回、对已退出的原地重启。
2122
- // forceBash:该终端永远跑 bash(而非用户登录 shell),模型写的
2123
- // bash 语法(数组/read -p/process substitution…)不会踩 zsh 差异。
2124
- // agentBash:标记为终端接管 bash,前端单独归到「AI bash」分组,
2125
- // 也不计入终端数量上限。
2126
2148
  const termId = persist ? PERSIST_ID : `ai-bash-${++oneShotBashSeq}`;
2127
2149
  const title = persist ? "AI bash" : `AI bash ${oneShotBashSeq}`;
2128
2150
  if (terminals.isSentinelPending?.(termId)) {
@@ -2134,13 +2156,10 @@ export function makeTerminalBashTool(terminals, opts) {
2134
2156
  }) === null) {
2135
2157
  throw new Error(pick(lang, `无法打开 AI bash 终端(${termId})`, `Failed to open the AI bash terminal (${termId})`, "terminals.bash.open.failed", { termId }));
2136
2158
  }
2137
- // 阻塞等待期间挂起活力提醒(我们自己在检测静默,避免双重通知)。
2138
2159
  terminals.suspendIdleWatch(termId);
2139
2160
  const start = terminals.endCursor(termId);
2140
2161
  const ac = new AbortController();
2141
2162
  opts.kills.add(ac);
2142
- // 一键退出一次性终端:命令结束后 shell 用 exit 退场(进程结束),
2143
- // 输出保留在 history 供查阅;持久终端则保留 shell 状态跨调用。
2144
2163
  const closeOneShot = () => {
2145
2164
  if (!persist)
2146
2165
  void terminals.inputChecked(termId, "exit\r");
@@ -2149,21 +2168,12 @@ export function makeTerminalBashTool(terminals, opts) {
2149
2168
  const maxForegroundMs = Math.max(0, opts.maxForegroundMs?.() ?? 0);
2150
2169
  const startTime = Date.now();
2151
2170
  const deadline = p.timeout && p.timeout > 0 ? Date.now() + p.timeout * 1000 : null;
2152
- // 拆掉模型常写的尾部输出限制/过滤管道(`| tail -N` / `| less` / `| more` / `| cat`):
2153
- // 这类管道在终端里 ①缓冲输出——可见终端全程哑火、无法感知实时进度;②吞掉真实退出码——
2154
- // 退出码取管道最后一个命令(tail 恒 0),掩盖真实失败;③需 stdin 的管道出错后可能一直挂到超时。
2155
- // 拆掉后底层命令直跑(实时可见 + 真实退出码),只在返回给模型时取末尾 N 行或全部。
2156
2171
  const limiter = detectTrailingLimiter(p.command);
2157
2172
  const stripped = limiter !== null;
2158
2173
  const effectiveTail = p.tail ?? (limiter?.kind === "tail" ? (limiter.lines ?? undefined) : undefined);
2159
2174
  const runCommand = stripped ? limiter.base : p.command;
2160
- // `cmd > log 2>&1 | tail -N`:拆掉 tail 后 stdout 进文件、终端为空 → 补一个
2161
- // tail 文件让模型看到日志尾部与真实退出码(否则输出为空)。
2162
2175
  const redirect = stripped && limiter.kind === "tail" ? detectStdoutRedirect(runCommand) : null;
2163
2176
  const tailFile = redirect ? { file: redirect.file, lines: limiter.lines ?? 10 } : undefined;
2164
- // 复杂子表达式先 hoist 成干净 const(issue #91 v2:vars key 不写复杂表达式)。
2165
- // 注意:limiter 对「没有尾部限输出管道」的命令是 null(issue #121)——
2166
- // 这些 const 一律走可选链,只在 stripped=true(limiterNote 才被取用)时才有意义。
2167
2177
  const limiterSegment = limiter?.segment ?? "";
2168
2178
  const limiterTailLines = limiter?.lines ?? 10;
2169
2179
  const limiterTailZh = limiter?.kind === "tail" ? `本次返回末尾 ${limiterTailLines} 行。` : "本次返回全部输出。";
@@ -2203,8 +2213,6 @@ export function makeTerminalBashTool(terminals, opts) {
2203
2213
  if (finished)
2204
2214
  return;
2205
2215
  failure = error;
2206
- // Destroy this task's shell rather than leave an unknown foreground reader
2207
- // alive after Ctrl+C. Completion removes all callbacks before reuse.
2208
2216
  try {
2209
2217
  terminals.kill?.(termId);
2210
2218
  }
@@ -2258,15 +2266,10 @@ export function makeTerminalBashTool(terminals, opts) {
2258
2266
  collected += read.data;
2259
2267
  cursor = read.cursor;
2260
2268
  lastDataAt = Date.now();
2261
- // 长跑/刷屏命令的累积无上限会拖爆服务进程内存。哨兵判定只看尾部
2262
- // 8KB(lastSentinel),超限丢最旧一半、保留近期输出即可;
2263
- // 命令结束后的 cleanBashOutput 语义不受影响。
2264
2269
  if (collected.length > BASH_COLLECT_MAX) {
2265
2270
  collected = collected.slice(collected.length - BASH_COLLECT_MAX / 2);
2266
2271
  }
2267
2272
  }
2268
- // Also scan the collected slice: adapters may deliver buffered output
2269
- // without invoking live watchers. Both paths use the same nonce.
2270
2273
  const marker = lastSentinel(collected, nonce);
2271
2274
  if (!finished && marker)
2272
2275
  finish(Number(marker[1]));
@@ -2286,12 +2289,10 @@ export function makeTerminalBashTool(terminals, opts) {
2286
2289
  details: { exitCode, output: text },
2287
2290
  };
2288
2291
  }
2289
- // 静默解阻(仅持久终端):转后台 + 注册完成观察器,立即把控制权还给模型。
2290
2292
  if (persist && idleMs > 0 && Date.now() - lastDataAt >= idleMs) {
2291
2293
  background = true;
2292
2294
  return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanCollected(collected), p.head, effectiveTail, lang), Math.round((Date.now() - lastDataAt) / 1000), lang, nonce, termId, persist, "idle");
2293
2295
  }
2294
- // 总时长解阻(持久与一次性终端):前台运行达到上限,转入后台继续执行,避免卡死。
2295
2296
  if (maxForegroundMs > 0 && Date.now() - startTime >= maxForegroundMs) {
2296
2297
  background = true;
2297
2298
  return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanCollected(collected), p.head, effectiveTail, lang), Math.round((Date.now() - startTime) / 1000), lang, nonce, termId, persist, "elapsed");
@@ -2309,12 +2310,8 @@ export function makeTerminalBashTool(terminals, opts) {
2309
2310
  },
2310
2311
  });
2311
2312
  }
2312
- /** 静默 / 总时长解阻路径:注册完成观察器后立即返回「仍在后台运行」。 */
2313
2313
  function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, nonce, termId = "ai-bash", persist = true, reason = "idle") {
2314
- // The task controller retains completion, cancellation and deadline ownership.
2315
- // partialText 已在调用方做过 cleanBashOutput + applyTail。
2316
2314
  const partial = truncateMiddle(partialText, 6000);
2317
- // 空输出占位按语言预渲染(issue #91 v2:vars 只收干净标识)。
2318
2315
  const partialZh = partial || "(暂无输出)";
2319
2316
  const partialEn = partial || "(no output yet)";
2320
2317
  let descZh = "";
@@ -2379,11 +2376,8 @@ function backgroundResult(terminals, opts, command, partialText, durationSeconds
2379
2376
  details: { running: true, terminalId: termId, persist, durationSeconds, reason },
2380
2377
  };
2381
2378
  }
2382
- /** Agent 持久终端工具名(唯一登记见 tool-manager.ts;此处 re-export 保兼容)。 */
2383
2379
  export { TERMINAL_TOOL_NAMES } from "./tool-manager.js";
2384
- /** Guidance for choosing the persistent terminal over ordinary bash calls. */
2385
2380
  export const TERMINAL_TOOLS_GUIDANCE = `Use terminal(action) for interactive programs, REPLs, TUIs, persistent servers, or work in the visible terminal panel. Prefer bash for ordinary commands. Use create/list to select a terminal, input/key to drive it, and close when finished. read supports incremental cursors, output waiting, head/tail, and literal search. wait blocks for a tracked bash command's exit marker; commands submitted through input/key have no such marker, so observe them with read(waitMs). bash({persist:true}) uses terminalId='ai-bash' and may wait before returning. read/wait are read-only; other actions are write operations. When a liveness reminder arrives, read the terminal, answer its prompt, or close it.`;
2386
- /** Build the single agent-facing persistent terminal tool for one conversation. */
2387
2381
  export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2388
2382
  const getLang = lang ?? (() => "en");
2389
2383
  const result = (text, details = {}) => ({ content: [{ type: "text", text }], details });
@@ -2391,7 +2385,6 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2391
2385
  if (error)
2392
2386
  throw new Error(error);
2393
2387
  };
2394
- // 针对单测或外部 mock 的行缓冲兜底支持
2395
2388
  const fallbackPending = new Map();
2396
2389
  const getPending = (id) => {
2397
2390
  if (typeof terminals.getAgentPendingLine === "function") {
@@ -2475,7 +2468,6 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2475
2468
  const infoJson = JSON.stringify(info);
2476
2469
  if (!info)
2477
2470
  throw new Error(pick(lang, `创建终端失败:${p.terminalId}`, `Failed to create terminal: ${p.terminalId}`, "terminals.create.failed", { "p.terminalId": p.terminalId }));
2478
- // AI 创建 → 启动活力检测纪元(静默提醒只针对 agent 触碰过的终端)。
2479
2471
  terminals.noteAgentActivity(p.terminalId);
2480
2472
  return result(pick(lang, `终端已创建:${infoJson}`, `Terminal created: ${infoJson}`, "terminals.create.done", {
2481
2473
  infoJson,
@@ -2511,14 +2503,11 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2511
2503
  });
2512
2504
  signal?.throwIfAborted();
2513
2505
  if (safety.blocked) {
2514
- // 发现阻断:若终端此前已留有未提交字符,发送 \x03 取消当前行
2515
2506
  if (prevPending) {
2516
2507
  try {
2517
2508
  terminals.inputChecked(p.terminalId, "\x03");
2518
2509
  }
2519
- catch {
2520
- // ignore
2521
- }
2510
+ catch { }
2522
2511
  }
2523
2512
  clearPending(p.terminalId);
2524
2513
  const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
@@ -2528,14 +2517,11 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2528
2517
  : pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
2529
2518
  }
2530
2519
  if (safety.editedCommand !== undefined) {
2531
- // 用户通过审批改写了命令
2532
2520
  if (prevPending) {
2533
2521
  try {
2534
2522
  terminals.inputChecked(p.terminalId, "\x03");
2535
2523
  }
2536
- catch {
2537
- // ignore
2538
- }
2524
+ catch { }
2539
2525
  }
2540
2526
  clearPending(p.terminalId);
2541
2527
  failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
@@ -2546,7 +2532,6 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2546
2532
  }
2547
2533
  failIf(terminals.inputChecked(p.terminalId, p.data));
2548
2534
  setPending(p.terminalId, parsed.remainingPending);
2549
- // AI 发了输入 = 在等结果,重开一个静默纪元。
2550
2535
  terminals.noteAgentActivity(p.terminalId);
2551
2536
  return result(pick(lang, `已发送 ${p.data.length} 个字符到 ${p.terminalId}`, `Sent ${p.data.length} chars to ${p.terminalId}`, "terminals.input.sent", { "p.data.length": p.data.length, "p.terminalId": p.terminalId }));
2552
2537
  }
@@ -2568,13 +2553,10 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2568
2553
  });
2569
2554
  signal?.throwIfAborted();
2570
2555
  if (safety.blocked) {
2571
- // 阻断 Enter 提交:发送 \x03 冲刷取消终端屏幕残留的脏命令
2572
2556
  try {
2573
2557
  terminals.inputChecked(p.terminalId, "\x03");
2574
2558
  }
2575
- catch {
2576
- // ignore
2577
- }
2559
+ catch { }
2578
2560
  clearPending(p.terminalId);
2579
2561
  const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
2580
2562
  const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
@@ -2583,26 +2565,21 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2583
2565
  : pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
2584
2566
  }
2585
2567
  if (safety.editedCommand !== undefined) {
2586
- // 用户在审批弹窗中改写了命令:先取消原行,再提交改写后的命令
2587
2568
  try {
2588
2569
  terminals.inputChecked(p.terminalId, "\x03");
2589
2570
  }
2590
- catch {
2591
- // ignore
2592
- }
2571
+ catch { }
2593
2572
  clearPending(p.terminalId);
2594
2573
  failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
2595
2574
  terminals.noteAgentActivity(p.terminalId);
2596
2575
  return result(pick(lang, `已发送改写后的命令到 ${p.terminalId}:${safety.editedCommand}`, `Sent edited command to ${p.terminalId}: ${safety.editedCommand}`, "terminals.key.edited_sent", { command: safety.editedCommand, "p.terminalId": p.terminalId }));
2597
2576
  }
2598
2577
  }
2599
- // 提交回车成功
2600
2578
  failIf(terminals.inputChecked(p.terminalId, encoded.data));
2601
2579
  clearPending(p.terminalId);
2602
2580
  terminals.noteAgentActivity(p.terminalId);
2603
2581
  return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
2604
2582
  }
2605
- // 非回车按键:若为退格或清除键,更新 pending 缓冲
2606
2583
  const prev = getPending(p.terminalId);
2607
2584
  const parsed = parseTerminalLineStream(prev, encoded.data);
2608
2585
  failIf(terminals.inputChecked(p.terminalId, encoded.data));
@@ -2640,10 +2617,6 @@ export function makePersistentTerminalTools(terminals, cwd, lang, options) {
2640
2617
  if (!terminals.has(p.terminalId)) {
2641
2618
  throw new Error(pick(lang, `终端不存在:${p.terminalId}(可能已被关闭或会话重置,请先 terminal(action='create'))`, `Terminal not found: ${p.terminalId} (it may have been closed or the session was reset — run terminal(action='create') first)`, "terminals.wait.not.found", { "p.terminalId": p.terminalId }));
2642
2619
  }
2643
- // 没有带哨兵的待决命令:shell 空闲在提示符,或该终端的命令是经
2644
- // terminal(action='input') 手动发的(无完成标记)——等哨兵永远等不到,直接
2645
- // 说明并引导改用 terminal(action='read'),避免 AI 无限重试。(显式传 cursor
2646
- // 的调用是有目的的追溯查询,不拦。)
2647
2620
  if (p.cursor === undefined && !terminals.isSentinelPending(p.terminalId)) {
2648
2621
  const why = pick(lang, `终端 ${p.terminalId} 当前没有正在等待完成的 bash 工具命令(shell 空闲,或该命令是通过 terminal(action='input') 发出的、没有完成标记)。terminal(action='wait') 不适用;要观察输出请用 terminal(action='read', terminalId="${p.terminalId}", waitMs=…)。`, `Terminal ${p.terminalId} has no pending bash-tool command to wait for (the shell is idle, or the command was sent via terminal(action='input') and has no completion marker). terminal(action='wait') does not apply; use terminal(action='read', terminalId="${p.terminalId}", waitMs=…) to observe output.`, "terminals.wait.no.pending", { "p.terminalId": p.terminalId });
2649
2622
  return result(JSON.stringify({ applicable: false, reason: why }), { applicable: false });