@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.10.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 (439) hide show
  1. package/README.md +38 -5
  2. package/docs/architecture.md +1673 -75
  3. package/package.json +23 -15
  4. package/packages/extension/package.json +8 -8
  5. package/packages/extension/src/ask-user-tool.ts +65 -3
  6. package/packages/extension/src/auto-session-namer.ts +190 -50
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +450 -0
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  9. package/packages/extension/src/bridge-handlers/instance.ts +220 -0
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +1030 -0
  11. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  12. package/packages/extension/src/bridge-identity-log.ts +45 -0
  13. package/packages/extension/src/bridge.ts +480 -2510
  14. package/packages/extension/src/command-handler.ts +180 -11
  15. package/packages/extension/src/connection.ts +265 -18
  16. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  17. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  18. package/packages/extension/src/flow-event-wiring.ts +1 -1
  19. package/packages/extension/src/followup-buffer.ts +1 -1
  20. package/packages/extension/src/followup-drain.ts +79 -0
  21. package/packages/extension/src/local-token-header.ts +161 -17
  22. package/packages/extension/src/message-update-coalescer.ts +3 -1
  23. package/packages/extension/src/model-refresh.ts +19 -0
  24. package/packages/extension/src/multiselect-list.ts +6 -2
  25. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  26. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  27. package/packages/extension/src/path-gate/decide.ts +15 -41
  28. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  29. package/packages/extension/src/path-gate/handler.ts +51 -2
  30. package/packages/extension/src/path-gate/index.ts +12 -1
  31. package/packages/extension/src/path-gate/resolve.ts +6 -124
  32. package/packages/extension/src/path-gate/roots.ts +4 -1
  33. package/packages/extension/src/path-gate/suppression.ts +4 -1
  34. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  35. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  36. package/packages/extension/src/project-trust.ts +119 -25
  37. package/packages/extension/src/prompt-expander.ts +5 -1
  38. package/packages/extension/src/prompt-meta.ts +64 -0
  39. package/packages/extension/src/provider-register.ts +87 -20
  40. package/packages/extension/src/role-manager.ts +5 -4
  41. package/packages/extension/src/server-auto-start.ts +12 -5
  42. package/packages/extension/src/server-launcher.ts +11 -13
  43. package/packages/extension/src/session-move.ts +19 -0
  44. package/packages/extension/src/session-sync.ts +31 -38
  45. package/packages/extension/src/spawn-token.ts +46 -0
  46. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  47. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  48. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  49. package/packages/extension/src/vault-delivery.ts +394 -0
  50. package/packages/extension/src/vault-forwarder.ts +128 -0
  51. package/packages/extension/src/vault-masker.ts +165 -0
  52. package/packages/extension/src/vault-redaction.ts +181 -0
  53. package/packages/extension/src/vcs-info.ts +5 -2
  54. package/packages/server/bin/pi-dashboard.mjs +26 -89
  55. package/packages/server/package.json +29 -15
  56. package/packages/server/src/access/access-grants.ts +18 -0
  57. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  58. package/packages/server/src/access/agent-grant.ts +1 -1
  59. package/packages/server/src/access/agent-yolo.ts +91 -0
  60. package/packages/server/src/access/containment-gate.ts +28 -1
  61. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  62. package/packages/server/src/access/cwd-verdict.ts +144 -0
  63. package/packages/server/src/access/grant-coordinator.ts +3 -1
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +374 -0
  65. package/packages/server/src/access/planes.ts +10 -1
  66. package/packages/server/src/access/refusal-ledger.ts +6 -6
  67. package/packages/server/src/access/yolo-session.ts +73 -12
  68. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  69. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  70. package/packages/server/src/acp-bridge/acp-session-adapter.ts +544 -0
  71. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  72. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  73. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  74. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  75. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  76. package/packages/server/src/acp-bridge/main.ts +118 -0
  77. package/packages/server/src/acp-bridge/models.ts +33 -0
  78. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  79. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  80. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  81. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  82. package/packages/server/src/addons/addons-catalog.ts +408 -0
  83. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  84. package/packages/server/src/addons/addons-folder.ts +310 -0
  85. package/packages/server/src/addons/addons-service.ts +470 -0
  86. package/packages/server/src/addons/package-contents.ts +99 -0
  87. package/packages/server/src/addons/settings-entries.ts +120 -0
  88. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  89. package/packages/server/src/auth/approval-refusal.ts +87 -0
  90. package/packages/server/src/auth/auth-plugin.ts +292 -79
  91. package/packages/server/src/auth/auth.ts +78 -7
  92. package/packages/server/src/auth/bearer-auth.ts +23 -1
  93. package/packages/server/src/auth/cors-origin.ts +10 -0
  94. package/packages/server/src/auth/csp.ts +6 -0
  95. package/packages/server/src/auth/host-admission.ts +26 -0
  96. package/packages/server/src/auth/host-gate.ts +6 -1
  97. package/packages/server/src/auth/local-credential.ts +258 -0
  98. package/packages/server/src/auth/local-proof.ts +7 -4
  99. package/packages/server/src/auth/local-token.ts +16 -0
  100. package/packages/server/src/auth/localhost-guard.ts +251 -8
  101. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  102. package/packages/server/src/auth/node-guard.ts +43 -0
  103. package/packages/server/src/auth/operate-required.ts +126 -0
  104. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  105. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  106. package/packages/server/src/auth/passkey/passkey-pages.ts +173 -0
  107. package/packages/server/src/auth/passkey/passkey-routes.ts +224 -0
  108. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  109. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  110. package/packages/server/src/auth/passkey/requester.ts +83 -0
  111. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  112. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  113. package/packages/server/src/auth/pi-legacy-credentials.ts +321 -0
  114. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  115. package/packages/server/src/auth/provider-auth-storage.ts +55 -8
  116. package/packages/server/src/auth/radius-override.ts +13 -0
  117. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  118. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  119. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  120. package/packages/server/src/auth/serve-app-host.ts +97 -0
  121. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  122. package/packages/server/src/auth/trust-mode.ts +83 -0
  123. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  124. package/packages/server/src/browse.ts +114 -2
  125. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  126. package/packages/server/src/browser-handlers/directory-handler.ts +128 -6
  127. package/packages/server/src/browser-handlers/session-action-handler.ts +129 -62
  128. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  129. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  130. package/packages/server/src/cli.ts +883 -97
  131. package/packages/server/src/config-api.ts +143 -1
  132. package/packages/server/src/config-snapshot.ts +5 -0
  133. package/packages/server/src/directory-service.ts +435 -32
  134. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  135. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  136. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  137. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  138. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  139. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  140. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  141. package/packages/server/src/event-wiring.ts +208 -35
  142. package/packages/server/src/file-watch-manager.ts +187 -39
  143. package/packages/server/src/git-worktree/git-operations.ts +16 -5
  144. package/packages/server/src/git-worktree/worktree-init-trust.ts +48 -5
  145. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  146. package/packages/server/src/identity/host-resources.ts +3 -0
  147. package/packages/server/src/identity/http-road-classification.ts +18 -0
  148. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  149. package/packages/server/src/identity/plugin-identity.ts +19 -0
  150. package/packages/server/src/identity/policy-registry.ts +4 -1
  151. package/packages/server/src/identity/resolver-registry.ts +12 -3
  152. package/packages/server/src/identity/ws-message-scope.ts +9 -0
  153. package/packages/server/src/identity/ws-road-classification.ts +9 -0
  154. package/packages/server/src/known-server-moves.ts +175 -0
  155. package/packages/server/src/lib/browse-roots.ts +36 -0
  156. package/packages/server/src/lib/digest-gate.ts +82 -0
  157. package/packages/server/src/lib/file-write-lock.ts +24 -0
  158. package/packages/server/src/lib/folder-project.ts +439 -0
  159. package/packages/server/src/lib/purify.ts +13 -5
  160. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  161. package/packages/server/src/lib/writable-md-target.ts +12 -1
  162. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  163. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  164. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  165. package/packages/server/src/lifecycle/recovery-server.ts +77 -1
  166. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  167. package/packages/server/src/live-server/live-capability.ts +254 -0
  168. package/packages/server/src/live-server/live-server-proxy.ts +173 -26
  169. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  170. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  171. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  172. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  173. package/packages/server/src/openspec/openspec-change-watcher.ts +109 -16
  174. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +132 -0
  175. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +90 -35
  176. package/packages/server/src/openspec/openspec-poll-worker.ts +200 -44
  177. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  178. package/packages/server/src/openspec/readiness.ts +9 -0
  179. package/packages/server/src/openspec/workflow-schema.ts +1128 -0
  180. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  181. package/packages/server/src/package/package-health-scanner.ts +133 -0
  182. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  183. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  184. package/packages/server/src/package/provider-probe.ts +5 -3
  185. package/packages/server/src/pairing/browser-gateway.ts +108 -8
  186. package/packages/server/src/pairing/knock-admission.ts +277 -0
  187. package/packages/server/src/pairing/pairing.ts +154 -27
  188. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  189. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  190. package/packages/server/src/peer-servers.ts +77 -0
  191. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  192. package/packages/server/src/persistence/boot-state.ts +48 -1
  193. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  194. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  195. package/packages/server/src/persistence/preferences-store.ts +116 -7
  196. package/packages/server/src/pi/bridge-upgrade-auth.ts +32 -21
  197. package/packages/server/src/pi/folder-commands.ts +141 -0
  198. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  199. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  200. package/packages/server/src/pi/host-project-trust.ts +158 -33
  201. package/packages/server/src/pi/pi-gateway.ts +93 -9
  202. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  203. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  204. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  205. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  206. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  207. package/packages/server/src/pi/trust-challenges.ts +38 -0
  208. package/packages/server/src/pi-agent-settings.ts +701 -100
  209. package/packages/server/src/pi-settings-themes.ts +104 -0
  210. package/packages/server/src/questions/brief-generator.ts +138 -0
  211. package/packages/server/src/questions/brief-model.ts +55 -0
  212. package/packages/server/src/questions/brief-policy.ts +36 -0
  213. package/packages/server/src/questions/brief-prompt.ts +92 -0
  214. package/packages/server/src/questions/brief-runtime.ts +50 -0
  215. package/packages/server/src/questions/question-answer.ts +55 -0
  216. package/packages/server/src/questions/question-broadcast.ts +106 -0
  217. package/packages/server/src/questions/question-files.ts +128 -0
  218. package/packages/server/src/questions/question-routes.ts +126 -0
  219. package/packages/server/src/questions/question-snapshot.ts +150 -0
  220. package/packages/server/src/questions/question-stack.ts +57 -0
  221. package/packages/server/src/questions/question-store.ts +477 -0
  222. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  223. package/packages/server/src/routes/access-routes.ts +123 -5
  224. package/packages/server/src/routes/acme-routes.ts +190 -0
  225. package/packages/server/src/routes/acp-routes.ts +16 -0
  226. package/packages/server/src/routes/addons-routes.ts +221 -0
  227. package/packages/server/src/routes/file-routes.ts +366 -75
  228. package/packages/server/src/routes/file-write-binary-routes.ts +473 -0
  229. package/packages/server/src/routes/folder-project-routes.ts +99 -0
  230. package/packages/server/src/routes/git-routes.ts +17 -2
  231. package/packages/server/src/routes/known-servers-routes.ts +333 -53
  232. package/packages/server/src/routes/live-server-routes.ts +72 -4
  233. package/packages/server/src/routes/local-proof-routes.ts +12 -7
  234. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  235. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  236. package/packages/server/src/routes/openspec-routes.ts +270 -40
  237. package/packages/server/src/routes/package-health-routes.ts +140 -0
  238. package/packages/server/src/routes/package-routes.ts +28 -1
  239. package/packages/server/src/routes/pairing-routes.ts +158 -24
  240. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  241. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  242. package/packages/server/src/routes/plugin-activation-routes.ts +87 -27
  243. package/packages/server/src/routes/provider-auth-routes.ts +22 -5
  244. package/packages/server/src/routes/provider-routes.ts +29 -0
  245. package/packages/server/src/routes/resource-activation-routes.ts +16 -32
  246. package/packages/server/src/routes/session-routes.ts +49 -5
  247. package/packages/server/src/routes/system-routes.ts +207 -23
  248. package/packages/server/src/routes/tls-routes.ts +55 -0
  249. package/packages/server/src/routes/user-routes.ts +192 -0
  250. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  251. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  252. package/packages/server/src/server.ts +919 -139
  253. package/packages/server/src/services/attached-driver.ts +175 -0
  254. package/packages/server/src/services/change-notifier.ts +55 -0
  255. package/packages/server/src/services/cli-service.ts +450 -0
  256. package/packages/server/src/services/command-runner.ts +92 -0
  257. package/packages/server/src/services/definitions-store.ts +121 -0
  258. package/packages/server/src/services/driver.ts +112 -0
  259. package/packages/server/src/services/health.ts +94 -0
  260. package/packages/server/src/services/leases.ts +117 -0
  261. package/packages/server/src/services/log-text.ts +97 -0
  262. package/packages/server/src/services/native-driver.ts +283 -0
  263. package/packages/server/src/services/oci-driver.ts +590 -0
  264. package/packages/server/src/services/output-capture.ts +183 -0
  265. package/packages/server/src/services/paths.ts +82 -0
  266. package/packages/server/src/services/ports.ts +26 -0
  267. package/packages/server/src/services/routes.ts +140 -0
  268. package/packages/server/src/services/runtime-detect.ts +108 -0
  269. package/packages/server/src/services/secret-delivery.ts +61 -0
  270. package/packages/server/src/services/secrets-resolver.ts +145 -0
  271. package/packages/server/src/services/secrets-store.ts +137 -0
  272. package/packages/server/src/services/service-manager.ts +1565 -0
  273. package/packages/server/src/services/start-record.ts +66 -0
  274. package/packages/server/src/services/state-machine.ts +241 -0
  275. package/packages/server/src/session/archive-sweeper.ts +92 -3
  276. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  277. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  278. package/packages/server/src/session/memory-session-manager.ts +53 -0
  279. package/packages/server/src/session/name-provenance.ts +102 -0
  280. package/packages/server/src/session/open-tool-calls.ts +15 -6
  281. package/packages/server/src/session/session-api.ts +47 -12
  282. package/packages/server/src/session/session-archive.ts +56 -4
  283. package/packages/server/src/session/session-diff-cache.ts +11 -4
  284. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  285. package/packages/server/src/session/session-scanner.ts +73 -3
  286. package/packages/server/src/session/session-to-meta.ts +15 -0
  287. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  288. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  289. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  290. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  291. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  292. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  293. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  294. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  295. package/packages/server/src/terminal/terminal-manager.ts +67 -1
  296. package/packages/server/src/tls/cert-files.ts +228 -0
  297. package/packages/server/src/tls/cert-manager.ts +703 -0
  298. package/packages/server/src/tls/cert-store.ts +69 -0
  299. package/packages/server/src/tls/source-registry.ts +71 -0
  300. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  301. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  302. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  303. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  304. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  305. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  306. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  307. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  308. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  309. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  310. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  311. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  312. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  313. package/packages/server/src/tls/tls-config-validation.ts +92 -0
  314. package/packages/server/src/tls/tls-listener.ts +351 -0
  315. package/packages/server/src/tls/types.ts +80 -0
  316. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  317. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  318. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  319. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  320. package/packages/server/src/vault/vault-bindings.ts +101 -0
  321. package/packages/server/src/vault/vault-delivery-hub.ts +294 -0
  322. package/packages/server/src/vault/vault-grants.ts +260 -0
  323. package/packages/server/src/vault/vault-import.ts +161 -0
  324. package/packages/server/src/vault/vault-permissions.ts +39 -0
  325. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  326. package/packages/server/src/vault/vault-projects.ts +156 -0
  327. package/packages/server/src/vault/vault-routes.ts +277 -0
  328. package/packages/server/src/vault/vault-store.ts +371 -0
  329. package/packages/shared/package.json +5 -2
  330. package/packages/shared/src/acp/acp-config.ts +123 -0
  331. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  332. package/packages/shared/src/acp/paths.ts +36 -0
  333. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  334. package/packages/shared/src/acp/update-model.ts +574 -0
  335. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  336. package/packages/shared/src/bind-reachability.ts +21 -2
  337. package/packages/shared/src/boot-state.ts +6 -0
  338. package/packages/shared/src/browser-host-identity.ts +49 -0
  339. package/packages/shared/src/browser-host-ipc.ts +107 -0
  340. package/packages/shared/src/browser-protocol.ts +385 -71
  341. package/packages/shared/src/canonical-subject.ts +27 -2
  342. package/packages/shared/src/card-sections.ts +185 -1
  343. package/packages/shared/src/chrome-profiles.ts +188 -0
  344. package/packages/shared/src/config.ts +473 -26
  345. package/packages/shared/src/custom-event-groups.ts +5 -2
  346. package/packages/shared/src/cwd-guard.ts +381 -1
  347. package/packages/shared/src/dashboard-paths.ts +12 -0
  348. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  349. package/packages/shared/src/dashboard-plugin/file-handler.ts +71 -0
  350. package/packages/shared/src/dashboard-plugin/index.ts +7 -3
  351. package/packages/shared/src/dashboard-plugin/manifest-types.ts +106 -2
  352. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  353. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  354. package/packages/shared/src/dashboard-plugin/slot-props.ts +95 -0
  355. package/packages/shared/src/dashboard-plugin/slot-types.ts +64 -4
  356. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +22 -3
  357. package/packages/shared/src/dashboard-starter.ts +30 -0
  358. package/packages/shared/src/display-name.ts +42 -0
  359. package/packages/shared/src/doctor-core.ts +25 -107
  360. package/packages/shared/src/enabled-models-match.ts +47 -0
  361. package/packages/shared/src/event-forward-declaration.ts +187 -0
  362. package/packages/shared/src/file-kind.ts +54 -2
  363. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  364. package/packages/shared/src/grammar-types.ts +3 -1
  365. package/packages/shared/src/host-admission.ts +2 -1
  366. package/packages/shared/src/host-port.ts +34 -0
  367. package/packages/shared/src/launcher-origin.ts +26 -0
  368. package/packages/shared/src/local-credential-proof.ts +219 -0
  369. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  370. package/packages/shared/src/markup-repair/types.ts +13 -0
  371. package/packages/shared/src/md-table-cell.ts +11 -0
  372. package/packages/shared/src/mdns-discovery.ts +392 -42
  373. package/packages/shared/src/models-json-reader.ts +6 -0
  374. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  375. package/packages/shared/src/openspec-poller.ts +210 -9
  376. package/packages/shared/src/openspec-status-all.ts +393 -0
  377. package/packages/shared/src/operate-required.ts +29 -0
  378. package/packages/shared/src/pairing-knock-client.ts +261 -0
  379. package/packages/shared/src/pairing-knock.ts +71 -0
  380. package/packages/shared/src/pairing-refusal.ts +32 -0
  381. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  382. package/packages/shared/src/pi-settings-keys.ts +9 -0
  383. package/packages/shared/src/pi-settings-schema.ts +285 -0
  384. package/packages/shared/src/pi-trust-mirror-snapshot.ts +200 -0
  385. package/packages/shared/src/pi-trust-mirror-types.ts +57 -0
  386. package/packages/shared/src/pi-trust-mirror.ts +328 -0
  387. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  388. package/packages/shared/src/platform/git.ts +204 -4
  389. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  390. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  391. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  392. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  393. package/packages/shared/src/platform/node-spawn.ts +1 -2
  394. package/packages/shared/src/platform/openspec.ts +129 -31
  395. package/packages/shared/src/platform/process-scan.ts +199 -1
  396. package/packages/shared/src/platform/process.ts +51 -0
  397. package/packages/shared/src/platform/runner.ts +46 -2
  398. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  399. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  400. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  401. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  402. package/packages/shared/src/project-name.ts +42 -0
  403. package/packages/shared/src/prompt-answer.ts +183 -0
  404. package/packages/shared/src/protocol.ts +133 -8
  405. package/packages/shared/src/question-types.ts +73 -0
  406. package/packages/shared/src/recommended-extensions.ts +80 -23
  407. package/packages/shared/src/recovery-timing.ts +12 -0
  408. package/packages/shared/src/redaction.ts +50 -0
  409. package/packages/shared/src/rest-api.ts +484 -1
  410. package/packages/shared/src/role-config-disk.ts +23 -0
  411. package/packages/shared/src/role-schema.ts +79 -0
  412. package/packages/shared/src/route-tiers.ts +127 -0
  413. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  414. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  415. package/packages/shared/src/server-identity.ts +51 -15
  416. package/packages/shared/src/server-launcher.ts +12 -33
  417. package/packages/shared/src/server-pinning.ts +81 -0
  418. package/packages/shared/src/services/offers.ts +114 -0
  419. package/packages/shared/src/services/schema.ts +628 -0
  420. package/packages/shared/src/services/status.ts +169 -0
  421. package/packages/shared/src/session-meta.ts +59 -2
  422. package/packages/shared/src/session-name.ts +8 -0
  423. package/packages/shared/src/skill-block-parser.ts +14 -0
  424. package/packages/shared/src/source-matching.ts +5 -1
  425. package/packages/shared/src/state-replay.ts +19 -0
  426. package/packages/shared/src/terminal-safe.ts +24 -0
  427. package/packages/shared/src/tls-status.ts +69 -0
  428. package/packages/shared/src/tool-path-resolve.ts +243 -0
  429. package/packages/shared/src/tool-registry/definitions.ts +26 -4
  430. package/packages/shared/src/tool-registry/index.ts +2 -2
  431. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  432. package/packages/shared/src/tunnel-provider.ts +3 -2
  433. package/packages/shared/src/types.ts +104 -9
  434. package/packages/shared/src/vault-delivery.ts +73 -0
  435. package/packages/shared/src/vault-origin.ts +51 -0
  436. package/packages/shared/src/vault-project-key.ts +53 -0
  437. package/packages/shared/src/worktree-init-hook.ts +69 -0
  438. package/packages/shared/src/ws-message-tiers.ts +135 -0
  439. package/tsconfig.base.json +1 -0
@@ -0,0 +1,1030 @@
1
+ /**
2
+ * pi lifecycle handlers (`session_start`, `turn_end`, `session_shutdown`, `session_info_changed`, `project_trust`).
3
+ *
4
+ * Extracted from `bridge.ts` (change: test-trust-audit, design D2). Receives the per-incarnation
5
+ * `BridgeInstance`; holds no module-level mutable state and never imports the bridge entry point.
6
+ */
7
+
8
+ import { loadConfig, resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
10
+ import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
11
+ import { Loader } from "@earendil-works/pi-tui";
12
+ import { cleanupAttachmentsForSession, } from "../ask-user-attachments.js";
13
+ import { registerAskUserTool } from "../ask-user-tool.js";
14
+ import { extractFirstMessage, filterHiddenCommands, getCurrentModelString, isHeadlessRpcSession, safeCwd } from "../bridge-context.js";
15
+ import { hasExplicitModelArg, shouldApplyDefaultModel } from "../bridge-default-model-gate.js";
16
+ import { drainDisposables } from "../bridge-polling.js";
17
+ import { registerCanvasTool } from "../canvas-tool.js";
18
+ import { DashboardDefaultAdapter } from "../dashboard-default-adapter.js";
19
+ import { decideRetarget } from "../endpoint-resolution.js";
20
+ import { mapEventToProtocol } from "../event-forwarder.js";
21
+ import { bridgeExtensionIdentity } from "../extension-identity.js";
22
+ import { registerFlowEventListeners } from "../flow-event-wiring.js";
23
+ import { createGitPollState, runGitPollTick } from "../git-poll.js";
24
+ import { flipHasUI } from "../hasui-flip.js";
25
+ import { healthUrlForInstance, probeEndpointReachability, verifyInstanceIdentity } from "../instance-verification.js";
26
+ import { sendPiVersionIfChanged as _sendPiVersionIfChanged } from "../model-tracker.js";
27
+ import { provisionOpenspecCli } from "../openspec-cli-shim.js";
28
+ import { pollCost } from "../poll-cost.js";
29
+ import { collectMetrics, startMetricsMonitor, stopMetricsMonitor } from "../process-metrics.js";
30
+ import { createProcessScanScheduler } from "../process-scan-scheduler.js";
31
+ import { scanChildProcessesAsync } from "../process-scanner.js";
32
+ import { decideBridgeProjectTrust, readEventCwd } from "../project-trust.js";
33
+ import { PromptBus } from "../prompt-bus.js";
34
+ import { buildProviderCatalogue, toModelInfo } from "../provider-register.js";
35
+ import { gateRemoteRegistration, isRemoteEndpoint } from "../remote-registration-gate.js";
36
+ import { registerRoleModelTools } from "../role-model-tools.js";
37
+ import { autoStartServer } from "../server-auto-start.js";
38
+ import { launchServer } from "../server-launcher.js";
39
+ import { loadServerPins, notePinEndpoint, serverPinsPath } from "../server-pin-store.js";
40
+ import { handleSessionChange as _handleSessionChange, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
41
+ import { detectSessionSource } from "../source-detector.js";
42
+ import { consumePendingReloadOnSessionStart, releaseBridgeOwnerOnShutdown, reloadCompletedFeedback } from "../terminal-reload.js";
43
+ import { refreshUiModules, subscribeUiInvalidate } from "../ui-modules.js";
44
+ import { runUiSafely } from "../ui-stale-guard.js";
45
+ import { sendShutdownUsageThenUnregister, type UsageDrain } from "../usage-drain.js";
46
+ import { detectIsGitRepo } from "../vcs-info.js";
47
+ import { buildVisibilityRegisterFields } from "../visibility-intent.js";
48
+ import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
49
+ import type { BridgeInstance } from "./instance.js";
50
+ import { patchUiForPromptBus } from "./ui-prompt-patch.js";
51
+
52
+ const HEARTBEAT_INTERVAL = 15_000;
53
+ const GIT_POLL_INTERVAL = 30_000;
54
+ // Platform-aware process scan cadence. Windows keeps the original 10 s /
55
+ // 30 s floor because PowerShell Get-CimInstance is expensive and can flash consoles;
56
+ // Unix uses 5 s / 5 s so legitimate bash subprocesses surface while still
57
+ // running. See change: tighten-process-list-ux.
58
+ const PROCESS_MIN_ELAPSED_MS = process.platform === "win32" ? 30_000 : 5_000; // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
59
+
60
+ /** Env var a plugin spawn uses to override `askUserPromptTimeoutSeconds` for one session. */
61
+ const ASK_USER_TIMEOUT_ENV = "PI_EXT_PI_DASHBOARD_ASK_USER_PROMPT_TIMEOUT_SECONDS";
62
+
63
+ /**
64
+ * Effective PromptBus `timeoutMs`: a valid integer override from the environment
65
+ * wins over `configSeconds`; a value `<= 0` means infinite (returned as `-1`).
66
+ * A non-integer override is ignored with a warning; empty counts as absent.
67
+ * See change: add-pending-question-stack (D11).
68
+ */
69
+ export function resolveAskUserTimeoutMs(
70
+ configSeconds: number,
71
+ env: NodeJS.ProcessEnv = process.env,
72
+ warn: (msg: string) => void = (m) => console.warn(m),
73
+ ): number {
74
+ let seconds = configSeconds;
75
+ const raw = env[ASK_USER_TIMEOUT_ENV]?.trim();
76
+ if (raw) {
77
+ if (/^-?\d+$/.test(raw)) seconds = Number.parseInt(raw, 10);
78
+ else warn(`[bridge] ignoring ${ASK_USER_TIMEOUT_ENV}=${JSON.stringify(raw)}: not an integer; using config`);
79
+ }
80
+ return seconds > 0 ? seconds * 1000 : -1;
81
+ }
82
+
83
+ // Shared handler for session changes (new/fork/resume)
84
+ function handleSessionChange(inst: BridgeInstance, ctx: any, usageSeed?: ReturnType<UsageDrain["baseline"]>) {
85
+ // Clear attachedChange on a real session switch (new/fork/resume): it is
86
+ // persisted globally + restored at activate, so without this the previous
87
+ // session's attached change would leak into the new session's prompt until
88
+ // the server replays. The server re-pushes the correct value for the new
89
+ // sessionId on its session_register. See change: inject-session-context-into-agent.
90
+ inst.attachedChange = null;
91
+ inst.shared.attachedChange = null;
92
+ // Drop retained subagent frames/snapshots on a real session switch — the
93
+ // new/fork/resumed session's subagents are unrelated to the outgoing one.
94
+ // See change: fix-subagent-live-detail-reliability.
95
+ inst.subagentFrameBuffer.reset();
96
+ // Same disposal point for the tick throttle: clear every armed trailing
97
+ // timer and drop every held frame, so nothing from the outgoing session
98
+ // can fire against the new one.
99
+ // See change: reduce-bridge-tick-bandwidth (D3).
100
+ inst.subagentTickThrottle.reset();
101
+ // A session boundary invalidates the CONTENT itself (unlike a reconnect), so
102
+ // drop any parked text snapshot and cancel its window rather than flushing
103
+ // it into the new session. See change:
104
+ // coalesce-bridge-message-update-snapshots (D8).
105
+ inst.coalescer.clear();
106
+ // Clear the stop-after-turn latch so a new/fork/resumed session does not
107
+ // inherit the previous session's pending graceful-stop and shut down on
108
+ // its first turn_end. See change: adopt-pi-071-072-073-features.
109
+ inst.shared.shouldStopAfterTurn = false;
110
+ // Drop the auto-namer and its carried state: it is a PER-SESSION state
111
+ // machine, so a new/fork/resumed session must not inherit the outgoing
112
+ // session's permanent stop, spent attempt budget or auto-named flag — it
113
+ // would report `stopped` / `already-named` without ever attempting to name.
114
+ // The server re-pushes the incoming session's own persisted state on its
115
+ // session_register. See change: fix-auto-naming-reasoning-model.
116
+ inst.autoNamer = undefined;
117
+ inst.namerState = undefined;
118
+ inst.shared.namerState = undefined;
119
+ // Bridge shadow queues reset on session change so the new session
120
+ // starts with empty chips. See change: add-followup-edit-and-steer-cancel.
121
+ if (inst.bridgeSteering.length > 0 || inst.bridgeFollowUp.length > 0) {
122
+ inst.bridgeSteering = [];
123
+ // Drops every entry AND its image bytes, releasing the byte budget.
124
+ inst.bridgeFollowUp.reset();
125
+ inst.emitQueueUpdate();
126
+ }
127
+ inst.renewGitTracker();
128
+ const bc = inst.syncBc();
129
+ _handleSessionChange(bc, ctx, inst.getFlowsList, usageSeed);
130
+ inst.applyBc(bc);
131
+ // A new session id needs its own `pi_version_update` (below-floor flag).
132
+ // After applyBc, so syncBc() carries the NEW session id.
133
+ // See change: update-pi-core-1-0-adopt-apis.
134
+ inst.sendPiVersionIfChanged();
135
+
136
+ // Restart polling timers
137
+ startGitPollTimer(inst, ctx);
138
+ }
139
+
140
+ // Single source of truth for the git + name/model poll loop. Both session
141
+ // start and session change call this so the two timers can never drift.
142
+ // Caches ctx.cwd (the throwing getter) and clears any prior timer first.
143
+ function startGitPollTimer(inst: BridgeInstance, ctx: any) {
144
+ if (inst.gitPollTimer) clearInterval(inst.gitPollTimer);
145
+ // safeCwd: startGitPollTimer runs inside handleSessionChange BEFORE
146
+ // connection.connect(); an un-guarded ctx.cwd throw here skips connect()
147
+ // (#393). See change: fix-bridge-resume-disconnect.
148
+ inst.cachedCwd = safeCwd(ctx);
149
+ const pollState = createGitPollState();
150
+ inst.gitPollTimer = setInterval(() => {
151
+ // runGitPollTick handles a rejecting git tick itself; this catch is the
152
+ // last line so the interval callback can never raise an unhandled rejection.
153
+ runGitPollTick({
154
+ isActive: inst.isActive,
155
+ cachedCwd: () => inst.cachedCwd,
156
+ tickGit: (cwd) => {
157
+ const gbc = inst.syncBc();
158
+ inst.polling.gitTracker?.tick(gbc, cwd);
159
+ inst.applyBc(gbc);
160
+ },
161
+ sendCwdMissingIfChanged: inst.sendCwdMissingIfChanged,
162
+ sendSessionNameIfChanged: inst.sendSessionNameIfChanged,
163
+ sendModelUpdateIfChanged: inst.sendModelUpdateIfChanged,
164
+ sendPiVersionIfChanged: () => _sendPiVersionIfChanged(inst.syncBc()),
165
+ state: pollState,
166
+ }).catch((err) => console.error("[dashboard] git poll tick failed:", err));
167
+ }, GIT_POLL_INTERVAL);
168
+ inst.shared.timers!.push(inst.gitPollTimer);
169
+ }
170
+
171
+ /** `session_info_changed`: relay a pi-side session rename to the dashboard. */
172
+ export function registerSessionInfoChanged(inst: BridgeInstance): void {
173
+ const pi = inst.pi;
174
+ try {
175
+ pi.on("session_info_changed" as any, inst.safe(async (event: any) => {
176
+ if (!inst.isActive() || !inst.sessionReady) return;
177
+ const name = typeof event?.name === "string" ? event.name : pi.getSessionName();
178
+ if (typeof name === "string" && name.length > 0) {
179
+ inst.getAutoNamer().onObservedName(name);
180
+ }
181
+ }));
182
+ } catch { /* older pi: no session_info_changed — poll fallback covers it */ }
183
+ }
184
+
185
+ /** `project_trust`: trust-gate decision for the dashboard-spawned project. */
186
+ export function registerProjectTrust(inst: BridgeInstance): void {
187
+ const pi = inst.pi;
188
+ try {
189
+ pi.on("project_trust" as any, inst.safe((event: any, ctx: any) => {
190
+ // Return the pi trust decision. A newer bridge taking over, or any
191
+ // non-match, defers. `remember:false` = trust for THIS run only.
192
+ if (!inst.isActive()) return { trusted: "undecided" };
193
+ const decision = decideBridgeProjectTrust({
194
+ dashboardSpawned: inst.dashboardSpawned,
195
+ isHeadless: isHeadlessRpcSession(),
196
+ eventCwd: readEventCwd(event, ctx),
197
+ activationCwd: inst.activationCwd,
198
+ });
199
+ return decision.trusted === "yes"
200
+ ? { trusted: "yes", remember: false }
201
+ : { trusted: "undecided" };
202
+ }));
203
+ } catch { /* older pi: no project_trust event — no-op */ }
204
+ }
205
+
206
+ const VAULT_START_REASONS = new Set(["startup", "reload", "new", "resume", "fork"]);
207
+
208
+ /** `session_start`: register the session, build the PromptBus, patch `ctx.ui`, arm timers. */
209
+ export function registerSessionStart(inst: BridgeInstance): void {
210
+ const pi = inst.pi;
211
+ pi.on("session_start", inst.safe(async (_event: any, ctx: any) => {
212
+
213
+ // Bail out if a newer bridge instance has taken over
214
+ if (!inst.isActive()) return;
215
+ const newSessionId = ctx.sessionManager.getSessionId();
216
+ inst.pathGate.onSessionStart();
217
+ // Credential vault: resolve the project from THIS session's own cwd (never the
218
+ // launch directory) on every start reason; an unreadable cwd withdraws all.
219
+ // See change: add-credential-vault (D2, D3).
220
+ void inst.vaultDelivery
221
+ .onSessionStart({
222
+ reason: VAULT_START_REASONS.has(_event?.reason) ? _event.reason : "startup",
223
+ getCwd: () => ctx.sessionManager.getCwd(),
224
+ })
225
+ .catch(() => {});
226
+ // Re-arm MCP registration for the (replacement) session; its mint below
227
+ // registers pi-dashboard again. See change: migrate-mcp-to-pi-builtin (D1).
228
+ inst.mcpRegistrar.onSessionStart();
229
+
230
+ // On session switch/fork (0.65.0+: event.reason replaces session_switch/session_fork events),
231
+ // unregister the old session before re-registering the new one.
232
+ const reason = _event?.reason;
233
+ // Synchronous compare-and-set BEFORE any await: this instance was loaded
234
+ // by a dashboard-requested reload → it owns the `/reload` `completed`,
235
+ // emitted after `replay_complete` below.
236
+ // See change: fix-terminal-session-dashboard-reload (D4).
237
+ const reloadDelivered = consumePendingReloadOnSessionStart(reason, newSessionId);
238
+ // Baseline + seed from ONE snapshot, before any register goes out: the
239
+ // drain forwards only entries appended after this point, and the register
240
+ // carries this snapshot's full totals. Undefined on a failed read.
241
+ // See change: count-non-message-usage.
242
+ let usageSeed: ReturnType<UsageDrain["baseline"]> | undefined;
243
+ try {
244
+ usageSeed = inst.usageDrain.baseline(ctx.sessionManager);
245
+ } catch (err) {
246
+ console.error("[dashboard] usage baseline failed:", err);
247
+ }
248
+ const sessionChanged =
249
+ (reason === "new" || reason === "fork" || reason === "resume") && !!inst.sessionId && inst.sessionId !== newSessionId;
250
+ if (sessionChanged) {
251
+ // Clear any latched abort for the OUTGOING session id. Otherwise a
252
+ // latched old session that is resumed later would have its first
253
+ // legitimate turn aborted by the agent_start/message_start latch hooks.
254
+ // See change: unify-error-retry-lifecycle.
255
+ inst.abortLatch.clear(inst.sessionId);
256
+ handleSessionChange(inst, ctx, usageSeed);
257
+ }
258
+
259
+ inst.cachedHasUI = ctx.hasUI;
260
+ inst.cachedCtx = ctx;
261
+ inst.sessionId = newSessionId;
262
+
263
+ // Provision the openspec CLI: drop a shim on process.env.PATH so the
264
+ // generated openspec-* skills' bare `openspec` resolves in-session. Runs on
265
+ // init AND /reload (re-points the shim on extension upgrade); the PATH
266
+ // prepend is idempotent. Fail-soft: on hard failure, surface a
267
+ // dashboard-visible missing-tool signal. See change:
268
+ // provision-openspec-cli-in-sessions.
269
+ provisionOpenspecCli({
270
+ onMissingTool: (reason) => {
271
+ inst.connection.send({
272
+ type: "event_forward",
273
+ sessionId: inst.sessionId,
274
+ event: {
275
+ eventType: "bash_output",
276
+ timestamp: Date.now(),
277
+ data: {
278
+ command: "openspec (session provisioning)",
279
+ output: reason,
280
+ exitCode: 127,
281
+ excludeFromContext: true,
282
+ missingTool: { kind: "missing-tool", toolName: "openspec" },
283
+ },
284
+ },
285
+ });
286
+ },
287
+ });
288
+
289
+ // Wrap sessionManager.appendMessage so that future message_end events can
290
+ // recover the just-generated entry id, even when their setTimeout(0)
291
+ // fires before pi has finished mutating event.message in place. The
292
+ // helper is idempotent and re-wraps on session replacement.
293
+ // See change: fix-per-message-fork.
294
+ inst.appendMessageWrapped = false;
295
+ inst.lastWrappedSm = null;
296
+ inst.wrapAppendMessageForCtx(ctx);
297
+ // Wrap the custom-persistence chokepoint BEFORE any events flow, so an
298
+ // extension appending at session_start is still forwarded. See change:
299
+ // render-inline-reasoning-and-custom-entries (D2).
300
+ inst.customPersistenceWrapped = false;
301
+ inst.customWrappedSm = null;
302
+ inst.wrapCustomPersistenceForCtx(ctx);
303
+
304
+ // Register ask_user at runtime (not at load time) to avoid static
305
+ // tool-name conflicts with other extensions like pi-flows.
306
+ registerAskUserTool(pi);
307
+
308
+ // Register the canvas declare-tool (change: auto-canvas). Fire-and-forget
309
+ // UI intent; the server observes the forwarded tool call and drives the
310
+ // canvas. Runtime registration for the same conflict-avoidance reason.
311
+ registerCanvasTool(pi);
312
+
313
+ // Register the agent-facing role/model tools (list_models, list_roles,
314
+ // update_roles). list_models reads the in-process session registry via a
315
+ // live getter so its refs match the human Model Selector exactly.
316
+ // See change: add-agent-role-model-tools.
317
+ registerRoleModelTools(pi, {
318
+ getRegistry: () => inst.cachedModelRegistry,
319
+ // Live scope read at call time from the latest captured ctx (dynamic via
320
+ // Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
321
+ // See change: update-pi-core-0-83-adopt-apis.
322
+ getScopedModels: () => (inst.cachedCtx as any)?.scopedModels,
323
+ });
324
+
325
+ // Extract session file/dir early — needed for source detection and UI proxy
326
+ const sessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
327
+ const sessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
328
+ inst.lastSessionFile = sessionFile;
329
+ inst.lastSessionDir = sessionDir;
330
+
331
+ // ── PromptBus setup ──
332
+ // Create bus with dashboard connection wiring.
333
+ // Replaces the old ui-proxy race pattern.
334
+ // Convert seconds → milliseconds for PromptBus.
335
+ // Values <= 0 (e.g. -1) are passed through as-is to signal infinite wait.
336
+ // A per-session env override (set by plugin spawns) wins over config.
337
+ // See change: add-pending-question-stack (D11).
338
+ const askUserTimeoutMs = resolveAskUserTimeoutMs(inst.config.askUserPromptTimeoutSeconds);
339
+ inst.promptBus = new PromptBus({
340
+ timeoutMs: askUserTimeoutMs,
341
+ onDashboardRequest: (prompt, component, placement) => {
342
+ inst.connection.send({
343
+ type: "prompt_request" as any,
344
+ sessionId: inst.sessionId,
345
+ promptId: prompt.id,
346
+ prompt: {
347
+ question: prompt.question,
348
+ type: prompt.type,
349
+ options: prompt.options,
350
+ defaultValue: prompt.defaultValue,
351
+ pipeline: prompt.pipeline,
352
+ metadata: prompt.metadata,
353
+ },
354
+ component,
355
+ placement,
356
+ });
357
+ },
358
+ onDashboardDismiss: (id) => {
359
+ inst.connection.send({ type: "prompt_dismiss" as any, sessionId: inst.sessionId, promptId: id });
360
+ },
361
+ onDashboardCancel: (id) => {
362
+ inst.connection.send({ type: "prompt_cancel" as any, sessionId: inst.sessionId, promptId: id });
363
+ },
364
+ });
365
+
366
+ // Register built-in default adapter (always present, works without pi-flows)
367
+ inst.promptBus.registerAdapter(new DashboardDefaultAdapter());
368
+
369
+ patchUiForPromptBus(inst, ctx, inst.promptBus);
370
+
371
+ // Flip ctx.hasUI=true now that ctx.ui.* has been patched to route
372
+ // through PromptBus → dashboard. `cachedHasUI` (captured earlier at
373
+ // line ~1287) retains the pi-supplied original value, so
374
+ // `detectSessionSource` continues to classify dashboard-spawned RPC
375
+ // vs tmux correctly. Extensions that branch on `ctx.hasUI`
376
+ // (context-mode `/ctx-stats` / `/ctx-doctor`, pi-agent-browser auto-install)
377
+ // now take their UI-present branch and render output via the proxied
378
+ // `ctx.ui.notify`. See change: fix-bridge-hasui-for-headless-rpc.
379
+ flipHasUI(ctx);
380
+
381
+ // Listen for adapter registrations from other extensions (e.g. pi-flows)
382
+ if (pi.events) {
383
+ pi.events.on("prompt:register-adapter", (adapter: any) => {
384
+ if (inst.promptBus && adapter && typeof adapter.name === "string") {
385
+ inst.promptBus.registerAdapter(adapter);
386
+ // Inject respond/cancel functions so cross-package adapters can talk back
387
+ if (typeof adapter.setRespond === "function") {
388
+ adapter.setRespond((response: any) => inst.promptBus!.respond(response));
389
+ }
390
+ if (typeof adapter.setCancel === "function") {
391
+ adapter.setCancel((id: string) => inst.promptBus!.cancel(id));
392
+ }
393
+ }
394
+ });
395
+
396
+ // Expose bus request function for pi-flows to use via emitPromptAndAwait
397
+ pi.events.emit("prompt:set-bus-request", {
398
+ request: (options: any) => inst.promptBus!.request(options),
399
+ });
400
+
401
+ // Generic system-follow-up channel: any plugin bridge entry can request
402
+ // a system-originated continuation through the single drain path by
403
+ // emitting `dashboard:enqueue-followup`. Inert when no plugin emits it.
404
+ // See change: add-goal-continuation-plugin (Decision 2).
405
+ pi.events.on("dashboard:enqueue-followup", (payload: any) => {
406
+ if (payload && typeof payload.text === "string") {
407
+ inst.enqueueSystemFollowup(payload.text);
408
+ }
409
+ });
410
+
411
+ // Generic plugin bridge→server channel: a plugin bridge entry emits
412
+ // `dashboard:plugin-message` and the main bridge wraps it in a
413
+ // `plugin_pi_message` envelope over the extension WS. The server
414
+ // dispatches to handlers registered via
415
+ // `ServerPluginContext.registerPiHandler(messageType, handler)`.
416
+ // See change: add-goal-continuation-plugin.
417
+ pi.events.on("dashboard:plugin-message", (payload: any) => {
418
+ if (
419
+ payload &&
420
+ typeof payload.pluginId === "string" &&
421
+ typeof payload.messageType === "string"
422
+ ) {
423
+ inst.connection.send({
424
+ type: "plugin_pi_message",
425
+ sessionId: inst.sessionId,
426
+ pluginId: payload.pluginId,
427
+ messageType: payload.messageType,
428
+ payload: payload.payload ?? null,
429
+ });
430
+ }
431
+ });
432
+ }
433
+
434
+ // Connect first, then auto-start if needed.
435
+ // session_register must be buffered before any event_forward messages.
436
+ //
437
+ // (tasks 7.2/7.3) A REMOTE endpoint is challenged BEFORE the connection
438
+ // opens: across a network an address proves nothing, so the pinned Ed25519
439
+ // identity is the only thing that answers "is this my dashboard?" (D8).
440
+ // Local endpoints are unaffected — the socket/loopback token already
441
+ // authorises them — so this adds no latency to the common path.
442
+ if (isRemoteEndpoint(inst.dashboardUrl)) {
443
+ const pinsFile = serverPinsPath();
444
+ const connectIfIdentityVerifies = async () => {
445
+ const verdict = await gateRemoteRegistration({
446
+ endpoint: inst.dashboardUrl,
447
+ store: loadServerPins(pinsFile),
448
+ });
449
+ // Task 10.3: the cause is distinguishable in the log, not folded into
450
+ // a generic connection failure.
451
+ const line = `[dashboard] remote identity ${verdict.cause}: ${verdict.reason}`;
452
+ if (!verdict.allow) {
453
+ console.error(`${line} — not registering`);
454
+ return;
455
+ }
456
+ console.log(line);
457
+ // Only a VERIFIED identity gets its address remembered.
458
+ if (verdict.fingerprint) notePinEndpoint(pinsFile, verdict.fingerprint, inst.dashboardUrl);
459
+ inst.connection.connect();
460
+ };
461
+ // Guarded discard: a failure here must be OBSERVED, never take the host
462
+ // pi agent down.
463
+ void connectIfIdentityVerifies().catch((err) => console.error("[dashboard]", err));
464
+ } else {
465
+ inst.connection.connect();
466
+ }
467
+ // Drain the buffered transport diagnostics through the live connection
468
+ // (task 10.5). `send()` buffers while the socket is down, which is the
469
+ // right behaviour here: the detail is self-describing, so a late delivery
470
+ // is still a true one.
471
+ inst.transportDiagnostics.attach({
472
+ send: (m) => inst.connection.send(m),
473
+ getSessionId: () => inst.sessionId,
474
+ });
475
+
476
+ // (task 3.8) Verify the instance answering at the recorded endpoint really
477
+ // is the one the record named. The socket's mode and the local token are
478
+ // both per-HOME, so a same-HOME impostor passes them — only the published
479
+ // `instanceId` distinguishes instances. Refusal is loud and does NOT fall
480
+ // back to a discovered substitute: that substitution is the bug.
481
+ if (
482
+ inst.endpointChoice.available &&
483
+ inst.endpointChoice.source === "rendezvous-record" &&
484
+ inst.rendezvous?.instanceId
485
+ ) {
486
+ // Alias: property narrowing on `inst.rendezvous` does not survive into the closure.
487
+ const rendezvous = inst.rendezvous;
488
+ const verifyRecordedInstance = async () => {
489
+ const verdict = await verifyInstanceIdentity({
490
+ healthUrl: healthUrlForInstance(rendezvous.httpPort),
491
+ expectedInstanceId: rendezvous.instanceId,
492
+ });
493
+ if (verdict.adopt) {
494
+ inst.registeredInstanceId = rendezvous.instanceId;
495
+ return;
496
+ }
497
+ // Only a CONFLICT justifies tearing the connection down. `disconnect()`
498
+ // sets `intentionalClose`, so nothing rearms the backoff loop and the
499
+ // session is dead until pi itself restarts — right for an impostor,
500
+ // catastrophic for an outage. `/api/health` is unreachable for seconds
501
+ // on every `POST /api/restart` while the gateway socket stays healthy,
502
+ // so treating silence as refusal would kill every bridge on the host on
503
+ // every rebuild. Unverified means we simply do not claim an identity.
504
+ if (!verdict.conflict) {
505
+ console.error(
506
+ `[dashboard] instance verification ${verdict.reason} — keeping the connection, identity unclaimed`,
507
+ );
508
+ inst.registeredInstanceId = undefined;
509
+ return;
510
+ }
511
+ console.error(`[dashboard] instance verification ${verdict.reason} — disconnecting`);
512
+ inst.registeredInstanceId = undefined;
513
+ try {
514
+ inst.connection.disconnect();
515
+ } catch {
516
+ /* already down */
517
+ }
518
+ };
519
+ // Guarded discard: the verification runs alongside the connection and
520
+ // must never take the host pi agent down, but its failure must still be
521
+ // OBSERVED rather than dropped on the floor.
522
+ void verifyRecordedInstance().catch((err) => console.error("[dashboard]", err));
523
+ }
524
+
525
+ // Extract first message (sessionFile/sessionDir already extracted above)
526
+ const firstMessage = extractFirstMessage(ctx);
527
+ inst.lastFirstMessage = firstMessage;
528
+
529
+ // Register session with initial model/thinkingLevel
530
+ inst.lastSessionName = pi.getSessionName() ?? "";
531
+ const initialModel = getCurrentModelString(inst.syncBc());
532
+ const initialThinkingLevel = (pi as any).getThinkingLevel?.() ?? undefined;
533
+ inst.lastModel = initialModel;
534
+ inst.lastThinkingLevel = initialThinkingLevel;
535
+
536
+ // Include eventCount so server can skip event wipe on reconnect
537
+ let eventCount: number | undefined;
538
+ try {
539
+ const entries = ctx.sessionManager?.getBranch?.();
540
+ if (entries) eventCount = entries.length;
541
+ } catch { /* ignore */ }
542
+
543
+ // See change: fix-dashboard-source-mislabelling — sent on every
544
+ // register so server can re-stamp source after restart. Derived from the
545
+ // capture-once boolean (token may already be scrubbed). See change:
546
+ // fix-spawn-token-env-leak.
547
+ // ctx.cwd is the guarded getter that throws once the session is replaced.
548
+ // Read it once, defensively — a throw here would skip session_register +
549
+ // the heartbeat/git timers, leaving a resumed session dead in the UI.
550
+ // See change: fix-bridge-resume-disconnect.
551
+ const startCwd = safeCwd(ctx);
552
+ const spawnToken = consumeSpawnToken();
553
+ inst.connection.send({
554
+ type: "session_register",
555
+ extensionIdentity: bridgeExtensionIdentity(),
556
+ sessionId: inst.sessionId,
557
+ cwd: startCwd,
558
+ name: inst.lastSessionName || undefined,
559
+ source: detectSessionSource(inst.cachedHasUI, sessionFile),
560
+ model: initialModel,
561
+ thinkingLevel: initialThinkingLevel,
562
+ sessionFile,
563
+ sessionDir,
564
+ firstMessage,
565
+ eventCount,
566
+ // The ONLY channel by which the server learns this session's process for a
567
+ // non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
568
+ // so without this the server's record has no `pid` and shutdown has
569
+ // nothing to escalate to — the session was unregistered while a ~127 MB
570
+ // pi kept running (#452). The two `session_register` sends in
571
+ // session-sync.ts already carry it; this one, the FIRST register of a
572
+ // fresh session, did not.
573
+ // See change: fix-tmux-session-shutdown-leak (D6).
574
+ pid: process.pid,
575
+ // The spawn correlation token, echoed back so the server can match THIS
576
+ // register to the spawn that produced it. This is a fresh session's FIRST
577
+ // register, and it omitted the token entirely: tier-1 correlation never
578
+ // fired for a dashboard spawn, so the spawn watchdog could only match by
579
+ // cwd and reported false register-timeouts for concurrent spawns into one
580
+ // directory. Single-use — `consumeSpawnToken` scrubs the env.
581
+ // See change: fix-tmux-session-shutdown-leak (D5).
582
+ ...(spawnToken ? { spawnToken } : {}),
583
+ ...(inst.dashboardSpawned ? { dashboardSpawned: true } : {}),
584
+ // Tri-state git-repo signal, computed at register time (authority).
585
+ // See change: gate-session-worktree-button-on-git.
586
+ isGitRepo: detectIsGitRepo(startCwd),
587
+ // Fact-forwarding: server decides auto-hide. See change:
588
+ // auto-hide-headless-worker-sessions.
589
+ ...buildVisibilityRegisterFields(inst.cachedHasUI, process.env),
590
+ // Applied server-side only for an id it has no record of.
591
+ // See change: count-non-message-usage.
592
+ ...(usageSeed ? { usageSeed } : {}),
593
+ });
594
+
595
+ // The register above just went out (live socket, or buffered for the
596
+ // open — either way the manager learns its last-registered endpoint for
597
+ // the migration gate's reversal target).
598
+ // See change: fix-bridge-mdns-migration-hijack (task 2.1).
599
+ inst.connection.noteRegistered();
600
+
601
+ // Allow event forwarding now that session_register is buffered
602
+ inst.sessionReady = true;
603
+
604
+ // D3: mint-on-registration. Ask the mcp-server plugin for this session's
605
+ // /mcp credential now that the socket is (re)registered — the reply
606
+ // arrives on the session-private lane (mcp_token_minted) and registers
607
+ // pi-dashboard with pi's built-in MCP, and re-registers after every
608
+ // reconnect, which is what makes a dashboard restart self-heal. Ordered
609
+ // after session_register on the SAME socket, so the server's
610
+ // connection-key attribution is already established when it arrives.
611
+ // See change: wire-mcp-session-token (D3/D5).
612
+ inst.connection.send({
613
+ type: "plugin_pi_message",
614
+ sessionId: inst.sessionId,
615
+ pluginId: "mcp-server",
616
+ messageType: "mcp/mint-token",
617
+ payload: {},
618
+ });
619
+
620
+ // Flush any subagent frames buffered during the not-ready window (D1) so a
621
+ // reconnect/discovery/reload gap self-heals instead of leaving a running
622
+ // subagent's detail empty. See change: fix-subagent-live-detail-reliability.
623
+ inst.flushPendingSubagentFrames();
624
+
625
+ // Replay full session history so the dashboard has all messages. A turn
626
+ // still running across a `/reload` keeps its in-flight calls open instead
627
+ // of getting a fabricated `session_ended` end. See change:
628
+ // fix-replay-fabricates-orphan-end-for-live-calls (D3).
629
+ inst.replaySessionEntries({ liveTailOpen: isLive(ctx, inst.shared.isAgentStreaming) });
630
+ inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
631
+ // After replay_complete: inside the replay window the server may drop
632
+ // forwarded events without insert or broadcast (`skipReplayInsert`).
633
+ // See change: fix-terminal-session-dashboard-reload (D4).
634
+ if (reloadDelivered) inst.connection.send(reloadCompletedFeedback(inst.sessionId));
635
+ // If agent is mid-turn (e.g. reload during streaming), send synthetic agent_start
636
+ if (inst.shared.isAgentStreaming) {
637
+ // `synthetic` lets the server's end-of-session open-call scan see past
638
+ // this re-announcement. See change: fix-replay-fabricates-orphan-end-for-live-calls (D4).
639
+ inst.connection.send(mapEventToProtocol(inst.sessionId, { type: "agent_start", synthetic: true }));
640
+ }
641
+
642
+ // Send initial commands list
643
+ const commands = filterHiddenCommands(pi.getCommands());
644
+ inst.connection.send({
645
+ type: "commands_list",
646
+ sessionId: inst.sessionId,
647
+ commands,
648
+ });
649
+
650
+ // Send initial flows list
651
+ inst.sendFlowsList();
652
+
653
+ // Send available models
654
+ inst.cachedModelRegistry = (ctx as any).modelRegistry;
655
+ if (inst.cachedModelRegistry) {
656
+ try {
657
+ const models = filterByEnabledModels(inst.cachedModelRegistry.getAvailable().map(toModelInfo));
658
+ inst.connection.send({ type: "models_list", sessionId: inst.sessionId, models });
659
+ // See change: replace-hardcoded-provider-lists.
660
+ inst.connection.send({ type: "providers_list", sessionId: inst.sessionId, providers: buildProviderCatalogue() });
661
+ } catch { /* modelRegistry not available */ }
662
+ }
663
+
664
+ // Apply default model only on brand-new sessions (no prior message history)
665
+ // that were NOT launched with an explicit --model flag. Resume (--session) and
666
+ // fork (--fork) both load parent messages, so messageCount > 0 and we keep their
667
+ // existing model. Mirrors pi's own !hasExistingSession gate (sdk.js:106 —
668
+ // `existingSession.messages.length > 0`). NOT the raw getEntries() count: pi's
669
+ // sdk.js auto-appends model_change + thinking_level_change setup entries to a
670
+ // brand-new session BEFORE emitting session_start, so getEntries() is ≥ 2 even
671
+ // for a session with no user history. Only message entries count.
672
+ // The bridge runs inside the pi process, so process.argv is pi's argv — an
673
+ // explicit --model there is the spawner's resolved choice and the default
674
+ // never overrides it. The deferred retry below needs no separate guard: when
675
+ // the gate is false this never sets pendingDefaultModel, so onProviderChanged
676
+ // has nothing to re-apply.
677
+ // See changes: fix-resume-keeps-session-model,
678
+ // fix-default-model-new-session-entry-count,
679
+ // fix-default-model-clobbers-explicit-model (issue #595).
680
+ const entryCount = ctx.sessionManager.buildSessionContext?.()?.messages?.length ?? 0;
681
+ const freshConfig = loadConfig();
682
+ if (shouldApplyDefaultModel({
683
+ reason: _event?.reason,
684
+ entryCount,
685
+ hasModelRegistry: Boolean(inst.cachedModelRegistry),
686
+ hasDefaultModel: Boolean(freshConfig.defaultModel),
687
+ hasExplicitModel: hasExplicitModelArg(process.argv),
688
+ })) {
689
+ inst.pendingDefaultModel = inst.applyDefaultModel();
690
+ }
691
+
692
+ // Send initial roles
693
+ if (pi.events) {
694
+ const rolesData: any = {};
695
+ pi.events.emit("roles:get-all", rolesData);
696
+ if (rolesData.roles) {
697
+ inst.connection.send({
698
+ type: "roles_list",
699
+ sessionId: inst.sessionId,
700
+ roles: rolesData.roles ?? {},
701
+ presets: rolesData.presets ?? [],
702
+ activePreset: rolesData.activePreset ?? null,
703
+ builtinRoleNames: rolesData.builtinRoleNames ?? [],
704
+ });
705
+ }
706
+ }
707
+
708
+ // Discover or auto-start server (non-blocking — connection will reconnect)
709
+ //
710
+ // When a real launchServer() is about to run (not on mDNS/health-check
711
+ // paths), mount an animated TUI widget above the editor using pi-tui's
712
+ // Loader (a real Component, self-animating at 80ms, like pi-flows'
713
+ // architect-widget). The previous implementation used
714
+ // ctx.ui.setStatus(...) which only writes a footer string and relies on
715
+ // the TUI render loop being ticked elsewhere — on the cold-start path
716
+ // nothing else requests renders, so the spinner never animated and often
717
+ // never appeared. setWidget(key, factory, {placement:"aboveEditor"}) gives
718
+ // us a managed component that owns its own render loop and is always
719
+ // visible while the launch is in flight.
720
+ let spinnerTimer: NodeJS.Timeout | null = null;
721
+ let spinnerStart = 0;
722
+ let activeLoader: Loader | null = null;
723
+ const stopSpinner = () => {
724
+ // Release the interval BEFORE the guarded ctx.ui call, so a stale ctx
725
+ // still stops the 1s label refresh instead of leaking it.
726
+ if (spinnerTimer) {
727
+ clearInterval(spinnerTimer);
728
+ spinnerTimer = null;
729
+ }
730
+ activeLoader = null;
731
+ // This runs from `onLaunchEnd` AND from the terminal .then()/.catch()
732
+ // below, either of which can land after a session replacement/reload has
733
+ // invalidated `ctx`. See ui-stale-guard.ts.
734
+ runUiSafely(() => ctx.ui.setWidget("pi-dashboard-launch", undefined));
735
+ };
736
+ // Resolve the ports the auto-start chain uses (health check + launch)
737
+ // with the shared env → config.json → default precedence, so a session
738
+ // whose environment names the dashboard's real ports attaches to (or
739
+ // launches on) THOSE ports instead of a stale config/default — this is
740
+ // the split-brain fix: without it, a harness/container session with
741
+ // DASHBOARD_PORT in its env health-checked 8000, found nothing, and
742
+ // launched a competing dashboard on 8000. `config` is not mutated;
743
+ // `loadConfig()` stays untouched (design D1/D2).
744
+ // See change: fix-bridge-autostart-port-resolution.
745
+ autoStartServer({ ...inst.config, ...resolveDashboardPorts(process.env, inst.config) }, {
746
+ discoverDashboard,
747
+ isDashboardRunning,
748
+ launchServer,
749
+ notify: (msg, level) => runUiSafely(() => ctx.ui.notify(msg, level)),
750
+ onLaunchStart: () => {
751
+ spinnerStart = Date.now();
752
+ const buildMessage = () => {
753
+ const elapsed = Math.floor((Date.now() - spinnerStart) / 1000);
754
+ return `starting dashboard server … (${elapsed}s)`;
755
+ };
756
+ runUiSafely(() =>
757
+ ctx.ui.setWidget(
758
+ "pi-dashboard-launch",
759
+ (tui: unknown, theme: { fg: (role: string, s: string) => string }) => {
760
+ const loader = new Loader(
761
+ tui as ConstructorParameters<typeof Loader>[0],
762
+ (s: string) => theme.fg("accent", s),
763
+ (s: string) => theme.fg("muted", s),
764
+ buildMessage(),
765
+ );
766
+ activeLoader = loader;
767
+ // Loader has stop() but no dispose(); wire dispose so that
768
+ // setExtensionWidget's teardown stops the 80ms animation interval.
769
+ (loader as Loader & { dispose?: () => void }).dispose = () => loader.stop();
770
+ return loader;
771
+ },
772
+ { placement: "aboveEditor" },
773
+ ),
774
+ );
775
+ // Refresh the elapsed-seconds label every second. Frame animation is
776
+ // driven by the Loader's own 80ms interval.
777
+ spinnerTimer = setInterval(() => {
778
+ activeLoader?.setMessage(buildMessage());
779
+ }, 1000);
780
+ },
781
+ onLaunchEnd: () => {
782
+ stopSpinner();
783
+ },
784
+ // Register the spawned dashboard-server PID into `selfSpawnedPgids`
785
+ // synchronously, before the next 5 s process-scan tick. Keeps the
786
+ // dashboard's own `node` infrastructure out of the session-card
787
+ // process list. See change: tighten-process-list-ux.
788
+ onServerSpawned: (childPid: number) => {
789
+ inst.selfSpawnedPgids.add(childPid);
790
+ },
791
+ // Honor the server's `server_restarting` quiesce window. While a
792
+ // deliberate restart/shutdown is in flight, skip the spawn step so we
793
+ // don't race the orchestrator. Discovery + reconnection still run.
794
+ // See change: fix-restart-bridge-auto-start-race.
795
+ shouldSuppressAutoStart: () => inst.connection.shouldSuppressAutoStart(),
796
+ }).then((result) => {
797
+ stopSpinner(); // safety net — covers onLaunchEnd not firing
798
+ if (result.server && result.server.piPort !== inst.config.piPort) {
799
+ const candidateUrl = `ws://${formatHostPort(result.server.host, result.server.piPort)}`;
800
+ // fix-bridge-mdns-migration-hijack: a DISCOVERED candidate only
801
+ // SUGGESTS. Whether the connection follows it is decided — and
802
+ // recorded — by `ConnectionManager.retargetTo`, which refuses to
803
+ // drop an established, registered connection until the candidate has
804
+ // PROVEN reachable (`GET /api/health` → `{ok:true}`, D1), honours
805
+ // localhost preference against a remote candidate (D3), and returns
806
+ // to the last registered endpoint if the candidate dies after
807
+ // adoption (D2). The blanket refusal this replaces also blocked
808
+ // every LEGITIMATE migration (a server that really moved).
809
+ if (inst.endpointPinned) {
810
+ // D3 (add-pi-gateway-transport-identity): a pinned endpoint
811
+ // refuses every re-target. The refusal stays on the record (10.2).
812
+ const decision = decideRetarget({
813
+ current: { endpoint: inst.dashboardUrl, instanceId: inst.registeredInstanceId },
814
+ candidate: { endpoint: candidateUrl },
815
+ pinned: true,
816
+ failed: false,
817
+ identityVerified: false,
818
+ });
819
+ const refusedDetail = `${inst.dashboardUrl} -> ${candidateUrl}: ${decision.reason}`;
820
+ console.log(`[dashboard] re-target ${refusedDetail}`);
821
+ inst.transportDiagnostics.record({ event: "retarget_refused", detail: refusedDetail });
822
+ return;
823
+ }
824
+ const trigger = `mdns discovery (${result.server.host}:${result.server.port}, gateway ${result.server.piPort})`;
825
+ // The health probe runs on the candidate's HTTP port — the record's
826
+ // `port`, not the gateway port — and completes BEFORE the incumbent
827
+ // is dropped (retargetTo owns that ordering).
828
+ const healthUrl = `http://${formatHostPort(result.server.host, result.server.port)}/api/health`;
829
+ inst.connection
830
+ .retargetTo(candidateUrl, {
831
+ trigger,
832
+ verify: () => probeEndpointReachability({ healthUrl }),
833
+ })
834
+ .then((accepted) => {
835
+ console.log(`[dashboard] re-target ${inst.dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);
836
+ })
837
+ .catch((err: unknown) => console.error("[dashboard] re-target decision failed:", err));
838
+ }
839
+ }).catch(() => { stopSpinner(); });
840
+
841
+ // Send initial git info + the session's pi version. A session change already
842
+ // ran the first evaluation (and renewed the tracker) in handleSessionChange;
843
+ // doing it again would double the synchronous git work.
844
+ if (!sessionChanged) {
845
+ const gbc = inst.syncBc();
846
+ inst.renewGitTracker().evaluateFirst(gbc, startCwd);
847
+ inst.applyBc(gbc);
848
+ }
849
+ inst.sendCwdMissingIfChanged(startCwd);
850
+ inst.sendPiVersionIfChanged();
851
+
852
+ // Start metrics monitor and heartbeat
853
+ startMetricsMonitor();
854
+ inst.heartbeatTimer = setInterval(() => {
855
+ if (!inst.isActive()) return;
856
+ inst.vaultDelivery.tick();
857
+ inst.connection.send({
858
+ type: "session_heartbeat",
859
+ sessionId: inst.sessionId,
860
+ // Liveness truth for the server's status reconcile: `streaming` is
861
+ // otherwise a one-way latch and a single dropped `agent_end` sticks
862
+ // the card on `Thinking…` forever.
863
+ // `=== true` because the flag is optional and is `undefined` before
864
+ // the first turn: sent raw it would serialize away and read as "old
865
+ // bridge, no liveness truth" instead of "idle".
866
+ // See change: fix-stuck-streaming-status-latch.
867
+ agentRunning: inst.shared.isAgentStreaming === true,
868
+ // Fold the bridge→server ring-buffer eviction count into the heartbeat
869
+ // so it reaches `/api/health`. See change:
870
+ // fix-stuck-tool-card-on-dropped-event.
871
+ metrics: {
872
+ ...collectMetrics(),
873
+ droppedBufferedFrames: inst.connection.getDroppedBufferedCount(),
874
+ refusedInboundFrames: inst.connection.getDroppedInboundCount(),
875
+ // Subagent-tick throttle counters ride the same transport, so the
876
+ // throttle's two information-loss modes are observable in production
877
+ // instead of only at L1. See change: reduce-bridge-tick-bandwidth (D6).
878
+ ...inst.subagentTickThrottle.stats,
879
+ // Plugin event-forward registry counters. See change:
880
+ // add-plugin-bridge-contributions.
881
+ pluginForwardDeclared: inst.pluginForwardRegistry.stats.declared,
882
+ pluginForwardRejected:
883
+ inst.pluginForwardRegistry.stats.rejected + inst.pluginForwardRegistry.stats.rejectedDeclarations,
884
+ pluginForwardConflicts: inst.pluginForwardRegistry.stats.conflicts,
885
+ pluginForwardRetained: inst.pluginForwardRegistry.stats.buffer.retained,
886
+ pluginForwardDropped:
887
+ inst.pluginForwardRegistry.stats.buffer.dropped + inst.pluginForwardRegistry.stats.buffer.keyRejected,
888
+ // Subagent fan-out admission counters ride the same transport, so a
889
+ // narrowed fan-out is observable instead of looking like a model that
890
+ // chose not to parallelize. See change:
891
+ // bound-subagent-fanout-under-host-pressure (D7).
892
+ ...inst.fanoutAdmission.counters,
893
+ // Agent path gate counters (in-root decisions are counted, not logged).
894
+ pathGateInRoot: inst.pathGate.counters.inRoot,
895
+ pathGateAsked: inst.pathGate.counters.asked,
896
+ pathGateBlocked: inst.pathGate.counters.blocked,
897
+ pathGateYoloAllowed: inst.pathGate.counters.yoloAllowed,
898
+ // Poll-cost counters (summed across sessions on /api/health).
899
+ // See change: optimize-polling-hot-paths.
900
+ ...pollCost,
901
+ },
902
+ });
903
+ }, HEARTBEAT_INTERVAL);
904
+ inst.shared.timers!.push(inst.heartbeatTimer);
905
+
906
+ // Start git + name/model polling
907
+ startGitPollTimer(inst, ctx);
908
+
909
+ // Start the adaptive process scanner (detect stalled child processes).
910
+ // One async `ps -A` per scan; fast while the agent/tools run, idle
911
+ // otherwise. session_start re-runs: dispose the previous scheduler first so
912
+ // schedules never stack. See change: optimize-polling-hot-paths.
913
+ inst.ensurePollingDisposable();
914
+ const scheduler = createProcessScanScheduler({
915
+ platform: process.platform,
916
+ setTimer: inst.setRegisteredTimeout,
917
+ clearTimer: inst.clearRegisteredTimeout,
918
+ scan: async () => {
919
+ if (!inst.isActive()) return { changed: false };
920
+ const processes = await scanChildProcessesAsync(
921
+ process.pid,
922
+ inst.trackedPgids,
923
+ PROCESS_MIN_ELAPSED_MS,
924
+ { excludedPgids: inst.selfSpawnedPgids },
925
+ );
926
+ if (!inst.isActive() || inst.polling.processScan !== scheduler) return { changed: false };
927
+ const currentPids = JSON.stringify(processes.map((p) => p.pid).sort());
928
+ if (currentPids === inst.previousProcessPids) return { changed: false };
929
+ inst.previousProcessPids = currentPids;
930
+ inst.connection.send({
931
+ type: "process_list",
932
+ sessionId: inst.sessionId,
933
+ processes: processes.map((p) => ({ pid: p.pid, pgid: p.pgid, command: p.command, elapsedMs: p.elapsedMs })),
934
+ });
935
+ return { changed: true };
936
+ },
937
+ });
938
+ inst.polling.replaceProcessScan(scheduler);
939
+ scheduler.start();
940
+
941
+ // Register flow event listeners (pi-flows emits these via pi.events)
942
+ registerFlowEventListeners(inst.syncBc(), () => inst.sessionReady, inst.getFlowsList);
943
+
944
+ // Extension UI System (Phase 1): subscribe to invalidate once per
945
+ // session, then run the discovery probe. The probe is synchronous
946
+ // and re-runs on every reconnect (see `onReconnect` callback above).
947
+ // See change: add-extension-ui-modal.
948
+ subscribeUiInvalidate(inst.uiModulesBridgeCtx);
949
+ refreshUiModules(inst.uiModulesBridgeCtx);
950
+ }));
951
+ }
952
+
953
+ /** `turn_end`: stop-after-turn latch, auto-name, usage drain. */
954
+ export function registerTurnEnd(inst: BridgeInstance): void {
955
+ const pi = inst.pi;
956
+ pi.on("turn_end", inst.safe(async (event: any, ctx: any) => {
957
+ if (!inst.isActive()) return;
958
+ inst.cachedCtx = ctx;
959
+ if (!inst.sessionReady) return;
960
+ // Drain point: compaction / usage entries recorded during the turn.
961
+ // See change: count-non-message-usage.
962
+ inst.drainUsage(ctx);
963
+
964
+ // Send firstMessage update after first turn if not previously sent
965
+ if (!inst.lastFirstMessage) {
966
+ const firstMsg = extractFirstMessage(ctx);
967
+ if (firstMsg) {
968
+ inst.lastFirstMessage = firstMsg;
969
+ inst.connection.send({
970
+ type: "first_message_update",
971
+ sessionId: inst.sessionId,
972
+ firstMessage: firstMsg,
973
+ });
974
+ }
975
+ }
976
+
977
+ }));
978
+ }
979
+
980
+ /** `session_shutdown`: disconnect and clean up this incarnation. */
981
+ export function registerSessionShutdown(inst: BridgeInstance): void {
982
+ const pi = inst.pi;
983
+ pi.on("session_shutdown", inst.safe(async (event: any, ctx: any) => {
984
+ if (!inst.isActive()) return;
985
+ // Let the reloaded instance (fresh ExtensionAPI) pass the re-entry guard.
986
+ // See change: fix-terminal-session-dashboard-reload (D4).
987
+ releaseBridgeOwnerOnShutdown(inst.shared, event?.reason);
988
+ // Remove this session's pi-dashboard MCP registration (a reloaded
989
+ // instance re-registers on its own mint). See change: migrate-mcp-to-pi-builtin (D1).
990
+ inst.mcpRegistrar.onSessionShutdown();
991
+ inst.shared.isAgentStreaming = false;
992
+ stopMetricsMonitor();
993
+ if (inst.heartbeatTimer) {
994
+ clearInterval(inst.heartbeatTimer);
995
+ inst.heartbeatTimer = null;
996
+ }
997
+ if (inst.gitPollTimer) {
998
+ clearInterval(inst.gitPollTimer);
999
+ inst.gitPollTimer = null;
1000
+ }
1001
+ drainDisposables(inst.shared);
1002
+ // Flush undrained entry usage BEFORE session_unregister (which ends the
1003
+ // session server-side), on every shutdown reason: quit, reload and
1004
+ // session replacement (new/resume/fork). See change: count-non-message-usage.
1005
+ sendShutdownUsageThenUnregister(
1006
+ () => inst.drainUsage(ctx),
1007
+ () => inst.connection.send({
1008
+ type: "session_unregister",
1009
+ sessionId: inst.sessionId,
1010
+ }),
1011
+ );
1012
+
1013
+ // Drop retained subagent frames/snapshots on shutdown.
1014
+ // See change: fix-subagent-live-detail-reliability.
1015
+ inst.subagentFrameBuffer.reset();
1016
+ // See change: reduce-bridge-tick-bandwidth (D3).
1017
+ inst.subagentTickThrottle.reset();
1018
+ // A shutdown is a session boundary: discard parked text, cancel the window.
1019
+ // See change: coalesce-bridge-message-update-snapshots (D8).
1020
+ inst.coalescer.clear();
1021
+
1022
+ // Best-effort: remove this session's pasted ask_user attachments.
1023
+ // See change: add-ask-user-input-multiline-paste.
1024
+ cleanupAttachmentsForSession(inst.sessionId);
1025
+
1026
+ // Give time for the unregister to send
1027
+ await new Promise((resolve) => setTimeout(resolve, 100));
1028
+ inst.connection.disconnect();
1029
+ }));
1030
+ }