@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
@@ -5,40 +5,22 @@
5
5
  * forwards all pi events, and relays commands back.
6
6
  */
7
7
 
8
+ import { appendIdentityLog } from "./bridge-identity-log.js";
8
9
  import { bridgeExtensionIdentity } from "./extension-identity.js";
9
10
  import fs from "node:fs";
10
- import os from "node:os";
11
11
  import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
- import { ensureConfig, loadConfig, resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
13
+ import { ensureConfig, loadConfig, } from "@blackbelt-technology/pi-dashboard-shared/config.js";
14
14
  import { shouldActivateBridge } from "./bridge-activation.js";
15
- import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
16
- import type {
17
- ServerToExtensionMessage,
18
- TranscriptRequestMessage,
19
- } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
20
15
  import { rendezvousEndpoint } from "@blackbelt-technology/pi-dashboard-shared/rendezvous.js";
21
- import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
22
- import { decideTranscriptRequest } from "@blackbelt-technology/pi-dashboard-shared/transcript-request-guard.js";
23
- import type { FlowInfo, ImageContent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
+ import type { FlowInfo, } from "@blackbelt-technology/pi-dashboard-shared/types.js";
24
17
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
25
- import { Loader } from "@earendil-works/pi-tui";
26
18
  import { AbortLatch } from "./abort-latch.js";
27
- import { isUnderArtifactRoot, resolveArtifactRoots } from "./artifact-roots.js";
28
- import {
29
- MAX_PER_MESSAGE_BYTES as ATTACH_MAX_PER_MESSAGE_BYTES,
30
- cleanupAttachmentsForSession,
31
- persistAttachment,
32
- } from "./ask-user-attachments.js";
33
- import { registerAskUserTool } from "./ask-user-tool.js";
34
- import { type AutoNamer, adoptRestoredNamerState, createAutoNamer, type PersistedNamerState, type StreamSimpleFn } from "./auto-session-namer.js";
19
+ import { type AutoNamer, createAutoNamer, type PersistedNamerState, type StreamSimpleFn } from "./auto-session-namer.js";
35
20
  import type { BridgeContext } from "./bridge-context.js";
36
- import { extractFirstMessage, extractLatestTurnWindow, filterHiddenCommands, getCurrentModelString, isHeadlessRpcSession, safeCwd } from "./bridge-context.js";
37
- import { hasExplicitModelArg, shouldApplyDefaultModel } from "./bridge-default-model-gate.js";
21
+ import { extractLatestTurnWindow, } from "./bridge-context.js";
38
22
  import { mintBridgeTicket, readDeviceToken, withTicket } from "./bridge-ticket-client.js";
39
- import { registerCanvasTool } from "./canvas-tool.js";
40
23
  import {
41
- buildUserMessageContent,
42
24
  createCommandHandler,
43
25
  tryExecSlashTemplate,
44
26
  validateImages,
@@ -46,85 +28,64 @@ import {
46
28
  import { buildSessionContextText, runForkSubagentDraft } from "./commit-draft-agent.js";
47
29
  import { ConnectionManager, type WatchdogFireInfo } from "./connection.js";
48
30
  import {
49
- consumePendingReloadOnSessionStart,
50
31
  createTerminalReload,
51
32
  isBridgeReentry,
52
33
  RELOAD_COMMAND_NAME,
53
- releaseBridgeOwnerOnShutdown,
54
- reloadCompletedFeedback,
55
34
  } from "./terminal-reload.js";
56
35
  import { toCustomEntryForward, toCustomMessageForward } from "./custom-entry-forward.js";
57
36
  import { registerDashboardContextInjector } from "./dashboard-context-injector.js";
58
- import { DashboardDefaultAdapter } from "./dashboard-default-adapter.js";
59
37
  import { runDevBuild } from "./dev-build.js";
60
- import { EmptyActionableGuard, SURFACE_MESSAGE } from "./empty-actionable-guard.js";
38
+ import { EmptyActionableGuard, } from "./empty-actionable-guard.js";
61
39
  import { resolveGuardConfig } from "./empty-actionable-guard-config.js";
62
- import { decideRetarget, instanceIdFileForSocket, resolveEndpoint } from "./endpoint-resolution.js";
63
- import { mapEventToProtocol, redactBeforeSettleContext, redactCompactionEntry } from "./event-forwarder.js";
40
+ import { instanceIdFileForSocket, resolveEndpoint } from "./endpoint-resolution.js";
41
+ import { mapEventToProtocol, } from "./event-forwarder.js";
64
42
  import {
65
43
  FLOW_EVENT_MAP,
66
44
  registerEventBusForwarding,
67
- registerFlowEventListeners,
68
45
  SUBAGENT_EVENT_MAP,
69
46
  } from "./flow-event-wiring.js";
70
47
  import { createFollowupBuffer } from "./followup-buffer.js";
71
- import { createPollingHolder, drainDisposables, ensureDisposable, feedPollingEvent, routeGitInfoRefresh, scheduleModelRecheckOnSelect, teardownPreviousIncarnation } from "./bridge-polling.js";
72
- import { createGitPollState, runGitPollTick } from "./git-poll.js";
48
+ import { drainOneFollowup } from "./followup-drain.js";
49
+ import { createPollingHolder, drainDisposables, ensureDisposable, teardownPreviousIncarnation } from "./bridge-polling.js";
73
50
  import { createGitTracker, type GitTracker } from "./git-tracker.js";
74
51
  import { createPrStatusScheduler, type PrStatusScheduler } from "./pr-status.js";
75
52
  import * as git from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
76
- import { flipHasUI } from "./hasui-flip.js";
77
- import { healthUrlForInstance, probeEndpointReachability, verifyInstanceIdentity } from "./instance-verification.js";
78
- import { localTokenHeaders } from "./local-token-header.js";
53
+ import { localCredentialPlan } from "./local-token-header.js";
79
54
  import { inlineMessageText, type ReadFileOutcome } from "./markdown-image-inliner.js";
80
- import { createMcpDashboardRegistrar, type McpRegistrationApi, type McpTokenMintedPayload } from "./mcp-token-delivery.js";
55
+ import { createMcpDashboardRegistrar, type McpRegistrationApi, } from "./mcp-token-delivery.js";
81
56
  import { createPluginRequestClient, installPluginRequest } from "./plugin-request-client.js";
82
- import { COALESCE_WINDOW_MS, flushesParkedText, MessageUpdateCoalescer } from "./message-update-coalescer.js";
83
- import { reportRefresh } from "./model-refresh.js";
57
+ import { COALESCE_WINDOW_MS, MessageUpdateCoalescer } from "./message-update-coalescer.js";
84
58
  import { resetReconnectCaches as _resetReconnectCaches, sendCwdMissingIfChanged as _sendCwdMissingIfChanged, sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendPiVersionIfChanged as _sendPiVersionIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged } from "./model-tracker.js";
85
- import { decodeMultiselectAnswer } from "./multiselect-decode.js";
86
- import { createNotifyProxy } from "./notify-proxy.js";
87
- import { provisionOpenspecCli } from "./openspec-cli-shim.js";
88
59
  import { createPathGate } from "./path-gate/index.js";
89
60
  import { Suppression } from "./path-gate/suppression.js";
90
61
  import { emitPendingPrompts } from "./pending-prompt-emitter.js";
91
62
  import { readPiRetrySettings } from "./pi-retry-settings.js";
92
- import { collectMetrics, startMetricsMonitor, stopMetricsMonitor } from "./process-metrics.js";
93
- import { getOwnPgid, scanChildProcessesAsync } from "./process-scanner.js";
94
- import { createProcessScanScheduler } from "./process-scan-scheduler.js";
95
- import { pollCost } from "./poll-cost.js";
96
- import { decideProjectTrust, readEventCwd } from "./project-trust.js";
97
- import { PromptBus } from "./prompt-bus.js";
63
+ import { getOwnPgid, } from "./process-scanner.js";
98
64
  import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
99
65
  import { activate as activateProviderRegister, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
100
- import { gateRemoteRegistration, httpBaseUrlFor, isRemoteEndpoint } from "./remote-registration-gate.js";
66
+ import { httpBaseUrlFor, isRemoteEndpoint } from "./remote-registration-gate.js";
101
67
  import { RetryTracker } from "./retry-tracker.js";
102
- import { activate as activateRoleManager, lookupRole, resolveNamingModel } from "./role-manager.js";
103
- import { registerRoleModelTools } from "./role-model-tools.js";
104
- import { autoStartServer } from "./server-auto-start.js";
105
- import { launchServer } from "./server-launcher.js";
106
- import { loadServerPins, notePinEndpoint, serverPinsPath } from "./server-pin-store.js";
107
- import { handleSessionChange as _handleSessionChange, replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, consumeSpawnToken, filterByEnabledModels } from "./session-sync.js";
68
+ import { activate as activateRoleManager, resolveNamingModel } from "./role-manager.js";
69
+ import { replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, filterByEnabledModels, isLive } from "./session-sync.js";
108
70
  import { tryDispatchExtensionCommand } from "./slash-dispatch.js";
109
- import { UsageDrain, drainUsageAndSend, makeCacheWarmingDecisionHandler, sendShutdownUsageThenUnregister } from "./usage-drain.js";
110
- import { detectSessionSource } from "./source-detector.js";
111
- import { flushBufferedSubagentFrames, serveSubagentResync } from "./subagent-forward-sites.js";
71
+ import { UsageDrain, drainUsageAndSend, makeCacheWarmingDecisionHandler, } from "./usage-drain.js";
72
+ import { flushBufferedSubagentFrames, } from "./subagent-forward-sites.js";
73
+ import { PluginForwardRegistry } from "./plugin-event-forward-registry.js";
112
74
  import { SubagentFrameBuffer } from "./subagent-frame-buffer.js";
113
75
  import { stripForForward } from "./subagent-frame-strip.js";
114
76
  import { FanoutAdmissionGate, resolveAdmissionConfig } from "./subagent-fanout-admission.js";
115
77
  import { SaturationSampler } from "./subagent-saturation.js";
116
- import { isSubagentTick, SubagentTickThrottle } from "./subagent-tick-throttle.js";
117
- import { inlineToolResultImages } from "./tool-result-image-inliner.js";
118
- import { readTranscriptChunk, type TranscriptCursor } from "./transcript-backfill.js";
78
+ import { SubagentTickThrottle } from "./subagent-tick-throttle.js";
119
79
  import { createTransportDiagnostics } from "./transport-diagnostics.js";
120
- import { createTuiPromptAdapter } from "./tui-prompt-adapter.js";
121
- import { classifyTurnActionability } from "./turn-actionability.js";
122
- import { handleUiManagement, refreshUiModules, subscribeUiInvalidate, type UiModulesBridgeCtx } from "./ui-modules.js";
123
- import { runUiSafely } from "./ui-stale-guard.js";
124
- import { detectIsGitRepo } from "./vcs-info.js";
125
- import { buildVisibilityRegisterFields } from "./visibility-intent.js";
126
-
127
- const HEARTBEAT_INTERVAL = 15_000;
80
+ import { refreshUiModules, type UiModulesBridgeCtx } from "./ui-modules.js";
81
+ import { createInstance, type BridgeState } from "./bridge-handlers/instance.js";
82
+ import { createVaultDelivery } from "./vault-delivery.js";
83
+ import { createVaultForwardFilter } from "./vault-forwarder.js";
84
+ import { createVaultRedaction } from "./vault-redaction.js";
85
+ import { captureSpawnTokenAtActivation } from "./spawn-token.js";
86
+ import { registerSessionInfoChanged, registerProjectTrust, registerSessionStart, registerTurnEnd, registerSessionShutdown } from "./bridge-handlers/lifecycle.js";
87
+ import { registerEnrichedForwarders, registerPassThroughForwarders } from "./bridge-handlers/forwarders.js";
88
+ import { handleInboundMessage } from "./bridge-handlers/dispatch.js";
128
89
 
129
90
  /**
130
91
  * Formats the state behind a watchdog force-close for `server.log`.
@@ -139,72 +100,13 @@ function formatWatchdogFire(w: WatchdogFireInfo): string {
139
100
  `readyState=${w.readyState} inboundQueue=${w.inboundQueueDepth} ` +
140
101
  `refusedInbound=${w.refusedInbound} maxTickDrift=${w.maxTickDriftMs}ms`
141
102
  );
142
- }
143
- const GIT_POLL_INTERVAL = 30_000;
144
- // Platform-aware process scan cadence. Windows keeps the original 10 s /
145
- // 30 s floor because PowerShell Get-CimInstance is expensive and can flash consoles;
146
- // Unix uses 5 s / 5 s so legitimate bash subprocesses surface while still
147
- // running. See change: tighten-process-list-ux.
148
- const PROCESS_MIN_ELAPSED_MS = process.platform === "win32" ? 30_000 : 5_000; // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
103
+ } // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
149
104
 
150
105
 
151
106
 
152
107
  // Use `process` (not `globalThis`) to survive jiti module cache invalidation
153
108
  // AND to share state across isolated extension contexts (vm sandboxes).
154
109
  const BRIDGE_KEY = "__pi_dashboard_bridge__";
155
- interface BridgeState {
156
- cleanup?: () => void;
157
- sessionId?: string;
158
- ctx?: any;
159
- modelRegistry?: any;
160
- hasUI?: boolean;
161
- /** Monotonic generation counter — stale listeners bail out when mismatched */
162
- generation?: number;
163
- /** Path-gate denial map; process-global so a /reload keeps the 120 s suppression. */
164
- pathGateSuppression?: Suppression;
165
- /** The pi instance that owns the bridge (used to detect subagent re-entry) */
166
- pi?: ExtensionAPI;
167
- /** All connection instances from any bridge incarnation (for cleanup) */
168
- connections?: ConnectionManager[];
169
- /** All interval timers from any bridge incarnation (for cleanup) */
170
- timers?: ReturnType<typeof setInterval>[];
171
- /**
172
- * Teardown callbacks for schedulers/watchers owned by a bridge incarnation
173
- * (process-scan scheduler, git probe scheduler, git-dir watcher). Drained on
174
- * re-init, `state.cleanup` and `session_shutdown`.
175
- * See change: optimize-polling-hot-paths.
176
- */
177
- disposables?: Array<() => void>;
178
- /** True when the agent is currently in a turn (between agent_start and agent_end) */
179
- isAgentStreaming?: boolean;
180
- /**
181
- * The auto-namer's durable state set, carried across reload as VALUES. The
182
- * namer OBJECT is deliberately not carried: its closures would hold a stale
183
- * connection, session id and ctx. See change: fix-auto-naming-reasoning-model.
184
- */
185
- namerState?: PersistedNamerState;
186
- /**
187
- * Capture-once "was this pi dashboard-spawned?" boolean. Set on first bridge
188
- * activation from `!!process.env.PI_DASHBOARD_SPAWN_TOKEN` BEFORE the token is
189
- * scrubbed; persisted here so reload/reattach keeps the value after the env
190
- * var is gone. See change: fix-spawn-token-env-leak.
191
- */
192
- dashboardSpawned?: boolean;
193
- /**
194
- * Dashboard-attached OpenSpec change name persisted across reload so the
195
- * `before_agent_start` injector keeps the fragment after `npm run reload`
196
- * even before the server re-replays on `session_register`. `null`/absent
197
- * when no change attached. See change: inject-session-context-into-agent.
198
- */
199
- attachedChange?: string | null;
200
- /**
201
- * Graceful stop-after-turn latch (pi 0.72+). Set true on a `stop_after_turn`
202
- * message; the next `turn_end` calls cachedCtx.shutdown() (fallback abort)
203
- * and clears the flag. Idempotent: repeated sets while pending are no-ops.
204
- * See change: adopt-pi-071-072-073-features.
205
- */
206
- shouldStopAfterTurn?: boolean;
207
- }
208
110
  function getBridgeState(): BridgeState {
209
111
  if (!(process as any)[BRIDGE_KEY]) {
210
112
  (process as any)[BRIDGE_KEY] = {};
@@ -263,43 +165,44 @@ function initBridge(pi: ExtensionAPI) {
263
165
  const generation = (prev.generation ?? 0) + 1;
264
166
  prev.generation = generation;
265
167
  prev.pi = pi;
168
+ const inst = createInstance(pi, generation, prev);
266
169
  /** Return true if this bridge instance is still the active one */
267
- function isActive(): boolean {
268
- return getBridgeState().generation === generation;
269
- }
170
+ const isActive = (): boolean => inst.isActive();
270
171
 
271
- let sessionId: string = prev.sessionId ?? crypto.randomUUID();
272
- let attachedChange: string | null = prev.attachedChange ?? null;
273
- let sessionReady = false; // true after session_start has run
172
+ inst.sessionId = prev.sessionId ?? crypto.randomUUID();
173
+ inst.attachedChange = prev.attachedChange ?? null;
174
+ inst.sessionReady = false; // true after session_start has run
274
175
  // Non-message usage drain cursor (usage / compaction / branch_summary
275
176
  // entries → `usage_recorded`). Baselined at every session_start (init,
276
177
  // reload, new/fork/resume) from the same snapshot as `usageSeed`; a
277
178
  // reconnect never touches it. See change: count-non-message-usage.
278
179
  const usageDrain = new UsageDrain();
180
+ inst.usageDrain = usageDrain;
279
181
  function drainUsage(ctx: any): void {
280
- if (!sessionReady) return;
281
- drainUsageAndSend(usageDrain, (ctx ?? cachedCtx)?.sessionManager, (m) => connection.send(m));
182
+ if (!inst.sessionReady) return;
183
+ drainUsageAndSend(usageDrain, (ctx ?? inst.cachedCtx)?.sessionManager, (m) => inst.connection.send(m));
282
184
  }
283
- let lastSessionFile: string | undefined;
284
- let lastSessionDir: string | undefined;
285
- let lastFirstMessage: string | undefined;
185
+ inst.drainUsage = drainUsage;
186
+ // → inst.lastSessionFile (BridgeInstance field; unset until assigned)
187
+ // → inst.lastSessionDir (BridgeInstance field; unset until assigned)
188
+ // → inst.lastFirstMessage (BridgeInstance field; unset until assigned)
286
189
  // ctx.cwd is a guarded getter on ExtensionRunner that throws once the session
287
190
  // is replaced (new/fork/resume/reload). Poll timers must read this cached copy
288
191
  // instead of the captured ctx, or they crash the host after a session change.
289
192
  // See change: fix-stale-ctx-cwd-crash.
290
- let cachedCwd: string | undefined;
291
- let pendingDefaultModel: string | null = null; // non-null if default model not yet applied (custom provider not ready)
193
+ // → inst.cachedCwd (BridgeInstance field; unset until assigned)
194
+ inst.pendingDefaultModel = null; // non-null if default model not yet applied (custom provider not ready)
292
195
 
293
196
  /** Try to apply the default model from config. Returns the model string if not found (pending), null if applied or no default. */
294
197
  function applyDefaultModel(): string | null {
295
198
  const freshConfig = loadConfig();
296
- if (!freshConfig.defaultModel || !cachedModelRegistry) return null;
199
+ if (!freshConfig.defaultModel || !inst.cachedModelRegistry) return null;
297
200
  const slashIdx = freshConfig.defaultModel.indexOf("/");
298
201
  if (slashIdx <= 0) return null;
299
202
  const provider = freshConfig.defaultModel.slice(0, slashIdx);
300
203
  const modelId = freshConfig.defaultModel.slice(slashIdx + 1);
301
204
  try {
302
- const found = cachedModelRegistry.find(provider, modelId);
205
+ const found = inst.cachedModelRegistry.find(provider, modelId);
303
206
  if (found) {
304
207
  (pi as any).setModel(found).then(() => {
305
208
  // Apply the configured default thinking level alongside the default
@@ -316,6 +219,7 @@ function initBridge(pi: ExtensionAPI) {
316
219
  } catch { /* ignore */ }
317
220
  return freshConfig.defaultModel; // not found yet — pending
318
221
  }
222
+ inst.applyDefaultModel = applyDefaultModel;
319
223
 
320
224
  /** Query pi-flows for available flows via synchronous event RPC */
321
225
  function getFlowsList(): FlowInfo[] {
@@ -325,30 +229,35 @@ function initBridge(pi: ExtensionAPI) {
325
229
  } catch { /* ignore */ }
326
230
  return (probe.flows as FlowInfo[] | undefined) ?? [];
327
231
  }
232
+ inst.getFlowsList = getFlowsList;
328
233
 
329
234
  /** Send flows_list message to the dashboard server */
330
235
  function sendFlowsList() {
331
236
  const flows = getFlowsList();
332
- console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${sessionId.slice(0,8)}`);
333
- connection.send({ type: "flows_list", sessionId, flows });
237
+ console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${inst.sessionId.slice(0,8)}`);
238
+ inst.connection.send({ type: "flows_list", sessionId: inst.sessionId, flows });
334
239
  }
240
+ inst.sendFlowsList = sendFlowsList;
335
241
 
336
242
 
337
- let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
338
- let gitPollTimer: ReturnType<typeof setInterval> | null = null;
243
+ inst.heartbeatTimer = null;
244
+ inst.gitPollTimer = null;
339
245
  // Adaptive async process-scan scheduler (replaces the fixed setInterval).
340
246
  // See change: optimize-polling-hot-paths.
341
247
  const polling = createPollingHolder();
248
+ inst.polling = polling;
342
249
  // Per-session git tracker (facts cache, HEAD branch, async status probe);
343
250
  // renewed at every session_start / session change. See change:
344
251
  // optimize-polling-hot-paths.
345
- let previousProcessPids: string = ""; // JSON-stringified PID set for diff
346
- const trackedPgids = new Set<number>(); // PGIDs captured during bash tool calls
252
+ inst.previousProcessPids = ""; // JSON-stringified PID set for diff
253
+ const trackedPgids = new Set<number>();
254
+ inst.trackedPgids = trackedPgids; // PGIDs captured during bash tool calls
347
255
  // PIDs of subprocesses the bridge has spawned itself (dashboard server,
348
256
  // RPC keeper). Threaded into `scanChildProcesses` as `excludedPgids` so
349
257
  // bridge infrastructure never surfaces in the process list.
350
258
  // See change: tighten-process-list-ux.
351
259
  const selfSpawnedPgids = new Set<number>();
260
+ inst.selfSpawnedPgids = selfSpawnedPgids;
352
261
  // Seed pi's OWN process-group id so pi-self + same-group plugin/MCP
353
262
  // sidecars (context-mode bun, etc.) never enter `trackedPgids` or the
354
263
  // process list. Cached one-shot `ps` lookup; no-op on Windows.
@@ -379,10 +288,12 @@ function initBridge(pi: ExtensionAPI) {
379
288
  getBridgeState().timers!.push(timer as unknown as ReturnType<typeof setInterval>);
380
289
  return timer;
381
290
  };
291
+ inst.setRegisteredTimeout = setRegisteredTimeout;
382
292
  const clearRegisteredTimeout = (timer: ReturnType<typeof setTimeout>): void => {
383
293
  clearTimeout(timer);
384
294
  unregisterTimer(timer);
385
295
  };
296
+ inst.clearRegisteredTimeout = clearRegisteredTimeout;
386
297
  const registerDisposable = (fn: () => void): void => {
387
298
  (getBridgeState().disposables ??= []).push(fn);
388
299
  };
@@ -390,6 +301,7 @@ function initBridge(pi: ExtensionAPI) {
390
301
  // and empties the list, and this incarnation may start a new session after it.
391
302
  const disposePolling = () => polling.disposeAll();
392
303
  const ensurePollingDisposable = () => ensureDisposable(getBridgeState(), disposePolling);
304
+ inst.ensurePollingDisposable = ensurePollingDisposable;
393
305
  ensurePollingDisposable();
394
306
  /** Dispose the previous tracker and start a fresh one for the incoming session. */
395
307
  function renewGitTracker(): GitTracker {
@@ -402,6 +314,7 @@ function initBridge(pi: ExtensionAPI) {
402
314
  clearTimer: clearRegisteredTimeout,
403
315
  }));
404
316
  }
317
+ inst.renewGitTracker = renewGitTracker;
405
318
  const prStatus: PrStatusScheduler = createPrStatusScheduler({
406
319
  probe: (cwd) => git.prStatusAsync({ cwd }),
407
320
  // A reload starts a new bridge incarnation; the old scheduler must not
@@ -414,26 +327,27 @@ function initBridge(pi: ExtensionAPI) {
414
327
  setTimer: setRegisteredTimeout,
415
328
  clearTimer: clearRegisteredTimeout,
416
329
  });
330
+ inst.prStatus = prStatus;
417
331
  let lastGitWorktreeJson: string | undefined; // see change: add-worktree-spawn-dialog
418
332
  let lastGitStatusJson: string | undefined; // see change: add-session-uncommitted-indicator-and-commit
419
333
  let lastCwdMissing: boolean | undefined; // see change: add-worktree-lifecycle-actions
420
- let lastSessionName: string | undefined;
334
+ // → inst.lastSessionName (BridgeInstance field; unset until assigned)
421
335
  // ── add-auto-session-naming ────────────────────────────────────────────
422
336
  // Global auto-naming toggle, relayed by the server via `preferences_update`.
423
337
  // Default true so a bridge that registers before the first push still names.
424
- let autoNameSessions = true;
425
- let autoNamer: AutoNamer | undefined;
338
+ inst.autoNameSessions = true;
339
+ // → inst.autoNamer (BridgeInstance field; unset until assigned)
426
340
  // The namer's durable state set is carried across reload as VALUES, never as
427
341
  // the namer object: its closures would retain a stale connection, session id
428
342
  // and ctx. See change: fix-auto-naming-reasoning-model (design D7).
429
- let namerState: PersistedNamerState | undefined = prev.namerState;
343
+ inst.namerState = prev.namerState;
430
344
  // Lazily-loaded pi-ai streamSimple (null = load attempted and failed).
431
345
  let piAiStreamSimple: StreamSimpleFn | null | undefined;
432
- let cachedHasUI: boolean | undefined = prev.hasUI;
433
- let cachedModelRegistry: any | undefined = prev.modelRegistry;
434
- let cachedCtx: any | undefined = prev.ctx;
435
- let lastModel: string | undefined;
436
- let lastThinkingLevel: string | undefined;
346
+ inst.cachedHasUI = prev.hasUI;
347
+ inst.cachedModelRegistry = prev.modelRegistry;
348
+ inst.cachedCtx = prev.ctx;
349
+ // → inst.lastModel (BridgeInstance field; unset until assigned)
350
+ // → inst.lastThinkingLevel (BridgeInstance field; unset until assigned)
437
351
  let hasRegisteredOnce = false; // see change: reattach-move-to-front
438
352
  // Capture-once "was this pi dashboard-spawned?" boolean, read BEFORE the
439
353
  // single-use `PI_DASHBOARD_SPAWN_TOKEN` is scrubbed on first register.
@@ -441,9 +355,12 @@ function initBridge(pi: ExtensionAPI) {
441
355
  // this module after the env was scrubbed — keeps the correct value instead
442
356
  // of regressing to false. See change: fix-spawn-token-env-leak.
443
357
  if (prev.dashboardSpawned === undefined) {
444
- prev.dashboardSpawned = !!process.env.PI_DASHBOARD_SPAWN_TOKEN;
358
+ // Reads AND scrubs the token here (not at first register): nested pi the
359
+ // agent starts later never inherits it. See change: mirror-dashboard-trust-to-pi.
360
+ prev.dashboardSpawned = captureSpawnTokenAtActivation();
445
361
  }
446
362
  const dashboardSpawned = prev.dashboardSpawned;
363
+ inst.dashboardSpawned = dashboardSpawned;
447
364
 
448
365
  // Capture the cwd at bridge ACTIVATION (module scope). `project_trust` fires
449
366
  // during resource-loader reload — BEFORE `session_start` reaches extension
@@ -451,8 +368,9 @@ function initBridge(pi: ExtensionAPI) {
451
368
  // when the trust handler runs. For a fresh headless spawn this IS the
452
369
  // dashboard-provided spawn cwd. See change: adopt-pi-074-080-features (A.3).
453
370
  const activationCwd = process.cwd();
371
+ inst.activationCwd = activationCwd;
454
372
 
455
- let promptBus: PromptBus | undefined;
373
+ // → inst.promptBus (BridgeInstance field; unset until assigned)
456
374
 
457
375
  // Provider-retry synthesis tracker. pi's ExtensionAPI does not expose
458
376
  // `auto_retry_*` events, so the bridge synthesizes them by OBSERVING pi's
@@ -461,35 +379,39 @@ function initBridge(pi: ExtensionAPI) {
461
379
  // are sourced READ-ONLY from pi's retry settings for the display countdown;
462
380
  // the bridge never writes them. See change: retry-forever-with-stop-control.
463
381
  const retryTracker = new RetryTracker(readPiRetrySettings({ cwd: activationCwd }));
382
+ inst.retryTracker = retryTracker;
464
383
  // Empty-actionable-turn guard: when a terminal turn is a clean-but-empty
465
384
  // `stop` (thinking-only, no text, no tool call), continue-or-surface instead
466
385
  // of idling silently. Provider-agnostic. See change:
467
386
  // fix-gemini-subagent-silent-tool-schema-failure.
468
387
  const guardConfig = resolveGuardConfig();
469
388
  const emptyActionableGuard = new EmptyActionableGuard(guardConfig.mode, guardConfig.retryCap);
389
+ inst.emptyActionableGuard = emptyActionableGuard;
470
390
  // Abort latch: keeps a user abort latched so a provider backoff that
471
391
  // outlives the 2 s persistent-abort scheduler still stops pi's retry.
472
392
  // Set on abort; cleared on a new user prompt or terminal agent_end; honored
473
393
  // on every observed resumption of the aborted turn. See change:
474
394
  // unify-error-retry-lifecycle (design D3b).
475
395
  const abortLatch = new AbortLatch();
396
+ inst.abortLatch = abortLatch;
476
397
 
477
398
  // Subagent live-detail reliability: retain subagent frames emitted while the
478
399
  // bridge is not ready (buffer-and-flush on re-register, D1) and keep the
479
400
  // latest snapshot of each running subagent for the resync responder (D2).
480
401
  // See change: fix-subagent-live-detail-reliability.
481
402
  const subagentFrameBuffer = new SubagentFrameBuffer();
403
+ inst.subagentFrameBuffer = subagentFrameBuffer;
482
404
 
483
405
  // Dashboard MCP server registration with pi's built-in MCP. The bearer lives
484
406
  // only in this registrar and pi's registration — never in process.env.
485
407
  // See change: migrate-mcp-to-pi-builtin (D1).
486
408
  const mcpRegistrar = createMcpDashboardRegistrar({
487
409
  pi: pi as unknown as McpRegistrationApi,
488
- sessionId: () => sessionId,
410
+ sessionId: () => inst.sessionId,
489
411
  reportUnavailable: (reason) => {
490
- connection.send({
412
+ inst.connection.send({
491
413
  type: "plugin_pi_message",
492
- sessionId,
414
+ sessionId: inst.sessionId,
493
415
  pluginId: "mcp-server",
494
416
  messageType: "mcp/registration-unavailable",
495
417
  payload: { reason },
@@ -497,6 +419,7 @@ function initBridge(pi: ExtensionAPI) {
497
419
  },
498
420
  log: console,
499
421
  });
422
+ inst.mcpRegistrar = mcpRegistrar;
500
423
 
501
424
  // Bound the Agent-tick rate on the `tool_execution_update` carrier. That
502
425
  // carrier has no throttle anywhere on its path, so its rate is the
@@ -512,9 +435,10 @@ function initBridge(pi: ExtensionAPI) {
512
435
  // See change: reduce-bridge-tick-bandwidth (D2/D3/D4).
513
436
  const subagentTickThrottle = new SubagentTickThrottle<unknown>({
514
437
  windowMs: loadConfig().subagentTickThrottleMs,
515
- send: (msg) => connection.send(msg),
516
- canSend: (frameSessionId) => isActive() && sessionReady && frameSessionId === sessionId,
438
+ send: (msg) => inst.connection.send(msg),
439
+ canSend: (frameSessionId) => isActive() && inst.sessionReady && frameSessionId === inst.sessionId,
517
440
  });
441
+ inst.subagentTickThrottle = subagentTickThrottle;
518
442
 
519
443
  // Bound the bridge's per-token streaming cost. pi's `message_update` carries
520
444
  // the FULL accumulated text snapshot, so forwarding each one synchronously
@@ -533,11 +457,11 @@ function initBridge(pi: ExtensionAPI) {
533
457
  // See change: coalesce-bridge-message-update-snapshots (D1–D7).
534
458
  const coalescer = new MessageUpdateCoalescer<Record<string, unknown>>({
535
459
  windowMs: COALESCE_WINDOW_MS,
536
- isActive: () => isActive() && sessionReady,
460
+ isActive: () => isActive() && inst.sessionReady,
537
461
  send: (event) => {
538
- if (!isActive() || !sessionReady) return;
462
+ if (!isActive() || !inst.sessionReady) return;
539
463
  maybeInlineAssistantImages(event);
540
- connection.send(mapEventToProtocol(sessionId, event));
464
+ inst.connection.send(mapEventToProtocol(inst.sessionId, event));
541
465
  },
542
466
  setTimer: (fn, ms) => {
543
467
  const timer = setTimeout(fn, ms);
@@ -551,6 +475,7 @@ function initBridge(pi: ExtensionAPI) {
551
475
  if (index !== -1) timers!.splice(index, 1);
552
476
  },
553
477
  });
478
+ inst.coalescer = coalescer;
554
479
 
555
480
  // Per-message generation for the coalescing barrier. Distinct from the
556
481
  // bridge-instance `generation` above, which only changes on `initBridge` and
@@ -564,13 +489,14 @@ function initBridge(pi: ExtensionAPI) {
564
489
  // generation of its own — an update can only be stamped with the counter's
565
490
  // current value.
566
491
  // See change: coalesce-bridge-message-update-snapshots (D4).
567
- let assistantMessageGen = 0;
492
+ inst.assistantMessageGen = 0;
568
493
 
569
494
  /**
570
495
  * Identity of a message for the barrier: `<gen>:<role>:<timestamp>`.
571
496
  * `message.id` is unusable — pi stamps it only at post-handler persistence.
572
497
  */
573
498
  const messageKeyOf = (gen: number, message: unknown): string => coalescer.keyOf(gen, message);
499
+ inst.messageKeyOf = messageKeyOf;
574
500
 
575
501
  // Bridge-owned queue structures with TWO different ownership models:
576
502
  //
@@ -582,7 +508,7 @@ function initBridge(pi: ExtensionAPI) {
582
508
  // • bridgeFollowUp (BRIDGE-OWNED BUFFER) — authoritative store for
583
509
  // dashboard-originated follow-up entries while the agent is streaming.
584
510
  // Pi never sees these entries until `drainFollowupQueue()` ships them
585
- // one-at-a-time on `agent_end`. Mutated by `bufferFollowupSend`,
511
+ // one-at-a-time on `agent_settled`. Mutated by `bufferFollowupSend`,
586
512
  // `drainFollowupQueue`, and the four mutation handlers (edit / remove /
587
513
  // promote / clear).
588
514
  //
@@ -597,28 +523,30 @@ function initBridge(pi: ExtensionAPI) {
597
523
  // turn_end for mutation UI to matter; user direction).
598
524
  //
599
525
  // See change: rework-mid-turn-prompt-queue (spec mid-turn-prompt-queue).
600
- let bridgeSteering: string[] = [];
526
+ inst.bridgeSteering = [];
601
527
  const bridgeFollowUp = createFollowupBuffer();
528
+ inst.bridgeFollowUp = bridgeFollowUp;
602
529
  function emitQueueUpdate(): void {
603
- if (!isActive() || !sessionReady) return;
604
- connection.send({
530
+ if (!isActive() || !inst.sessionReady) return;
531
+ inst.connection.send({
605
532
  type: "queue_update",
606
- sessionId,
607
- steering: [...bridgeSteering],
533
+ sessionId: inst.sessionId,
534
+ steering: [...inst.bridgeSteering],
608
535
  // Views only: text + image COUNT. Image bytes never cross the wire.
609
536
  followUp: bridgeFollowUp.views(),
610
537
  });
611
538
  }
539
+ inst.emitQueueUpdate = emitQueueUpdate;
612
540
  /**
613
541
  * Surface a refusal to the user. Every follow-up refusal path emits one:
614
542
  * a bare `console.warn` is invisible in the dashboard, which is the same
615
543
  * defect class this change exists to fix (design D4).
616
544
  */
617
545
  function sendCommandFeedback(command: string, message: string): void {
618
- if (!isActive() || !sessionReady) return;
619
- connection.send({
546
+ if (!isActive() || !inst.sessionReady) return;
547
+ inst.connection.send({
620
548
  type: "event_forward",
621
- sessionId,
549
+ sessionId: inst.sessionId,
622
550
  event: {
623
551
  eventType: "command_feedback",
624
552
  timestamp: Date.now(),
@@ -626,12 +554,13 @@ function initBridge(pi: ExtensionAPI) {
626
554
  },
627
555
  });
628
556
  }
557
+ inst.sendCommandFeedback = sendCommandFeedback;
629
558
  function recordSteerSent(text: string): void {
630
559
  // Only record when the agent was actually streaming at send time. Idle
631
560
  // sends start a new turn directly — pi doesn't queue them, so the
632
561
  // shadow queue must not show a chip. See change: add-followup-edit-and-steer-cancel.
633
562
  if (!getBridgeState().isAgentStreaming) return;
634
- bridgeSteering.push(text);
563
+ inst.bridgeSteering.push(text);
635
564
  emitQueueUpdate();
636
565
  }
637
566
  /**
@@ -677,109 +606,57 @@ function initBridge(pi: ExtensionAPI) {
677
606
  }
678
607
  emitQueueUpdate();
679
608
  }
609
+ let isDraining = false;
680
610
  /**
681
- * Drain loop: on `agent_end`, pop the front of `bridgeFollowUp` and ship it
682
- * to pi as a fresh-turn `sendUserMessage` (no `deliverAs`). Pop-before-send
611
+ * Drain the bridge-owned follow-up buffer: on `agent_settled` (and from
612
+ * `enqueueSystemFollowup`), pop the front of `bridgeFollowUp` and ship it to
613
+ * pi as a fresh-turn `sendUserMessage` (no `deliverAs`). Pop-before-send
683
614
  * invariant: the entry is shifted off the buffer BEFORE the pi call. If
684
615
  * `pi.sendUserMessage` throws, the entry is LOST by design (double-shipping
685
616
  * is worse than dropping).
686
617
  *
687
- * Gates (all must pass): re-entrancy lock, idle, pi.hasPendingMessages,
688
- * non-empty buffer. One entry per agent_end — the next agent_end re-enters
618
+ * Gates (the pure sequence in `followup-drain.ts`): re-entrancy lock (here),
619
+ * non-empty buffer, pi.hasPendingMessages, idle. A false `isIdle()` returns
620
+ * without popping and without re-scheduling: pi clears its run-active flag
621
+ * BEFORE it emits `agent_settled`, so a drain scheduled from the settle sees
622
+ * an idle session unless another run already started, and then the next
623
+ * `agent_settled` drains. One entry per settle — the next settle re-enters
689
624
  * this function for the next entry (natural serialization).
690
625
  *
691
- * See change: rework-mid-turn-prompt-queue (design.md D2).
692
- */
693
- let isDraining = false;
694
- /**
695
- * Drain the bridge-owned follow-up buffer by handing one entry to pi
696
- * as a fresh-turn `sendUserMessage` (no `deliverAs`).
697
- *
698
- * Why no `deliverAs`: pi's agent loop calls `getFollowUpMessages()` only
699
- * while the loop is active. Once `agent_end` fires and the loop's
700
- * `executor` returns, pi's `finishRun()` flips `isStreaming = false` and
701
- * `activeRun = undefined`. After that point, anything queued into pi's
702
- * internal followUpQueue NEVER drains — pi has stopped reading it.
703
- * (Verified at pi-coding-agent pi-agent-core/agent.js: `finishRun()` clears
704
- * `isStreaming` + `activeRun`, and `getFollowUpMessages` is only supplied to
705
- * the loop while a run is active. Re-verified against pi 0.84.1 — behaviour
706
- * unchanged, line numbers moved. See change: update-pi-core-0-84-adopt-apis.)
626
+ * Why no `deliverAs`: once the run has settled pi no longer reads its
627
+ * follow-up queue, so a `{deliverAs:"followUp"}` entry would never drain.
707
628
  *
708
- * Two retry loops handle the transition window correctly:
709
- * - retryCount tracks how many setTimeout retries we've done
710
- * - if pi.isStreaming is still true (transition), we wait + retry
711
- * - once truly idle, sendUserMessage(entry) starts a fresh turn
712
- *
713
- * See change: rework-mid-turn-prompt-queue (post-smoke fix #3).
629
+ * See changes: rework-mid-turn-prompt-queue (design.md D2),
630
+ * update-pi-core-1-3-adopt-apis (design D4: agent_settled trigger, no
631
+ * idle-retry loop).
714
632
  */
715
- function drainFollowupQueue(retryCount = 0): void {
633
+ function drainFollowupQueue(): void {
716
634
  if (isDraining) return;
717
- if (bridgeFollowUp.length === 0) return;
718
-
719
- // TUI-coexistence gate: if pi has its own queued items (TUI alt+enter
720
- // sends), wait for pi to drain those first via its own loop. The
721
- // method lives on `ctx` (verified at pi 0.76.0 extensions/types.d.ts:227).
722
- if (typeof cachedCtx?.hasPendingMessages === "function") {
723
- try {
724
- if (cachedCtx.hasPendingMessages()) return;
725
- } catch { /* probe failure non-fatal */ }
726
- }
727
-
728
- // Idle gate: pi flips isStreaming=false in finishRun() AFTER the
729
- // executor returns from runAgentLoop. queueMicrotask runs inside the
730
- // executor (too early), so we use setTimeout to escape the loop AND
731
- // poll for isIdle with bounded retries.
732
- const idle = (() => {
733
- try { return cachedCtx?.isIdle?.() === true; } catch { return false; }
734
- })();
735
- if (!idle) {
736
- if (retryCount < 20) { // ~2s total (20 × 100ms)
737
- setTimeout(() => drainFollowupQueue(retryCount + 1), 100);
738
- } else {
739
- console.warn("[dashboard] drainFollowupQueue: pi never idled after 2s; giving up");
740
- }
741
- return;
742
- }
743
-
744
635
  isDraining = true;
745
636
  try {
746
- // POP FIRST. Once shifted, the entry exists only on this stack frame.
747
- const entry = bridgeFollowUp.shift()!;
748
- // Emit immediately so wire-state matches buffer-state BEFORE the pi call.
749
- emitQueueUpdate();
750
-
751
- // Hand to pi as a fresh turn (no deliverAs). Pi is now idle, so
752
- // pi.sendUserMessage starts a new run via Agent.prompt().
753
- //
754
- // NO send options, deliberately: `{deliverAs:"followUp"}` here is a
755
- // known-broken path (pi has already exited `getFollowUpMessages()`, so
756
- // the entry would never drain). `buildUserMessageContent` supplies the
757
- // content shape WITHOUT inheriting the steer/idle send options.
758
- // See change: fix-bridge-followup-image-drop (design D6).
759
- try {
760
- (pi.sendUserMessage as any)(buildUserMessageContent(entry.text, entry.images));
761
- } catch (err) {
762
- console.warn(
763
- "[dashboard] drainFollowupQueue: pi.sendUserMessage threw — entry lost:",
764
- err,
765
- );
766
- // INTENTIONAL: no re-push. Double-shipping is worse than dropping.
767
- }
637
+ drainOneFollowup({
638
+ buffer: bridgeFollowUp,
639
+ ctx: inst.cachedCtx,
640
+ emitQueueUpdate,
641
+ sendUserMessage: (content) => (pi.sendUserMessage as any)(content),
642
+ });
768
643
  } finally {
769
644
  isDraining = false;
770
645
  }
771
646
  }
647
+ inst.drainFollowupQueue = drainFollowupQueue;
772
648
  /**
773
649
  * System-originated follow-up enqueue. Unlike `bufferFollowupSend`, this
774
650
  * does NOT gate on `isAgentStreaming` — it is called by plugin bridges
775
- * (via the `dashboard:enqueue-followup` pi.event) AFTER `agent_end` has
776
- * fired, by which point `isAgentStreaming` is already `false` and the
777
- * streaming gate would silently discard the entry.
651
+ * (via the `dashboard:enqueue-followup` pi.event) AFTER the run's terminal
652
+ * events have fired, by which point `isAgentStreaming` is already `false`
653
+ * and the streaming gate would silently discard the entry.
778
654
  *
779
655
  * Routes through the SINGLE existing `drainFollowupQueue` path so a
780
656
  * plugin-requested continuation cannot race or double-inject against
781
657
  * user follow-ups: both share the one `bridgeFollowUp` buffer and the
782
- * `isDraining` lock, shipping one entry per `agent_end`.
658
+ * `isDraining` lock, shipping one entry per settle. It ships at once when
659
+ * the session is idle, otherwise on the next `agent_settled`.
783
660
  *
784
661
  * Text-only by design — the plugin path has no image source — so it wraps
785
662
  * into a `{ text }` entry. Subject to BOTH buffer bounds, with the refusal
@@ -787,9 +664,9 @@ function initBridge(pi: ExtensionAPI) {
787
664
  * nudge is a lost plugin continuation, and attributing it to `send_prompt`
788
665
  * would misreport a programmatic refusal as a user action (design D8).
789
666
  *
790
- * Schedules `drainFollowupQueue(0)` via
667
+ * Schedules `drainFollowupQueue()` via
791
668
  * `setTimeout(…, 0)` so the drain re-runs AFTER the async judge verdict
792
- * resolves (the bridge's own `agent_end` drain already ran against an
669
+ * resolves (the bridge's own `agent_settled` drain already ran against an
793
670
  * empty buffer by then).
794
671
  *
795
672
  * Generic infrastructure — not goal-specific. See change:
@@ -804,8 +681,9 @@ function initBridge(pi: ExtensionAPI) {
804
681
  return;
805
682
  }
806
683
  emitQueueUpdate();
807
- setTimeout(() => drainFollowupQueue(0), 0);
684
+ setTimeout(() => drainFollowupQueue(), 0);
808
685
  }
686
+ inst.enqueueSystemFollowup = enqueueSystemFollowup;
809
687
  /**
810
688
  * Mirror of pi's `_getUserMessageText` (pi-coding-agent agent-session.js).
811
689
  * Used by the per-entry shadow-queue drain matcher in the `message_start`
@@ -822,6 +700,7 @@ function initBridge(pi: ExtensionAPI) {
822
700
  .map((c: any) => c.text ?? "")
823
701
  .join("");
824
702
  }
703
+ inst.extractUserMessageText = extractUserMessageText;
825
704
 
826
705
  // rewriteFollowupQueue removed. The clear-then-replay strategy was broken
827
706
  // by construction (pi.clearFollowUpQueue is not on the ExtensionAPI, so the
@@ -830,16 +709,17 @@ function initBridge(pi: ExtensionAPI) {
830
709
 
831
710
  /** Forward a synthesized auto_retry_* event using the standard event_forward shape. */
832
711
  const sendSyntheticRetryEvent = (eventType: string, data: Record<string, unknown>): void => {
833
- if (!isActive() || !sessionReady) return;
712
+ if (!isActive() || !inst.sessionReady) return;
834
713
  // A synthesized retry event renders as a chat row, so a parked snapshot must
835
714
  // still land first. See change: coalesce-bridge-message-update-snapshots (D5).
836
715
  coalescer.flush();
837
- connection.send({
716
+ inst.connection.send({
838
717
  type: "event_forward",
839
- sessionId,
718
+ sessionId: inst.sessionId,
840
719
  event: { eventType, timestamp: Date.now(), data },
841
720
  });
842
721
  };
722
+ inst.sendSyntheticRetryEvent = sendSyntheticRetryEvent;
843
723
 
844
724
  // ── Per-message entry id tracking (for fix-per-message-fork) ──
845
725
  // Pi 0.69+ awaits extension handlers BEFORE sessionManager.appendMessage runs,
@@ -854,11 +734,14 @@ function initBridge(pi: ExtensionAPI) {
854
734
  // back-fill user-message ChatMessage.entryId.
855
735
  // See change: fix-per-message-fork.
856
736
  const idByMessage = new WeakMap<object, string>();
737
+ inst.idByMessage = idByMessage;
857
738
  const pendingNonces = new WeakMap<object, string>();
739
+ inst.pendingNonces = pendingNonces;
858
740
  let nonceCounter = 0;
859
741
  const nextNonce = (): string => `n-${++nonceCounter}-${Date.now()}`;
860
- let appendMessageWrapped = false;
861
- let lastWrappedSm: any = null;
742
+ inst.nextNonce = nextNonce;
743
+ inst.appendMessageWrapped = false;
744
+ inst.lastWrappedSm = null;
862
745
 
863
746
  // ---------------------------------------------------------------------
864
747
  // Markdown-image inliner state (chat-markdown-local-images-and-math).
@@ -876,6 +759,7 @@ function initBridge(pi: ExtensionAPI) {
876
759
  }
877
760
  return s;
878
761
  }
762
+ inst.getEmittedAssetHashes = getEmittedAssetHashes;
879
763
 
880
764
  /**
881
765
  * Synchronous fs probe + read for the inliner. Wraps `fs.statSync` /
@@ -899,6 +783,7 @@ function initBridge(pi: ExtensionAPI) {
899
783
  return { ok: false, kind: "EOTHER" };
900
784
  }
901
785
  }
786
+ inst.inlinerReadFile = inlinerReadFile;
902
787
 
903
788
  /**
904
789
  * Apply the markdown-image inliner to an assistant message_update /
@@ -914,8 +799,8 @@ function initBridge(pi: ExtensionAPI) {
914
799
  if (msg.role !== "assistant") return;
915
800
  // Use the *current* live cwd if available; fall back to the bridge
916
801
  // process cwd. The inliner resolves relative `./pic.png` against this.
917
- const cwd = (cachedCtx?.cwd as string | undefined) ?? process.cwd();
918
- const alreadyEmitted = getEmittedAssetHashes(sessionId);
802
+ const cwd = (inst.cachedCtx?.cwd as string | undefined) ?? process.cwd();
803
+ const alreadyEmitted = getEmittedAssetHashes(inst.sessionId);
919
804
  const allAssets: { hash: string; mimeType: string; data: string }[] = [];
920
805
 
921
806
  const rewriteOne = (text: string): string => {
@@ -940,15 +825,16 @@ function initBridge(pi: ExtensionAPI) {
940
825
 
941
826
  // Send each new asset BEFORE the (rewritten) message event lands.
942
827
  for (const a of allAssets) {
943
- connection.send({
828
+ inst.connection.send({
944
829
  type: "asset_register",
945
- sessionId,
830
+ sessionId: inst.sessionId,
946
831
  hash: a.hash,
947
832
  mimeType: a.mimeType,
948
833
  data: a.data,
949
834
  });
950
835
  }
951
836
  }
837
+ inst.maybeInlineAssistantImages = maybeInlineAssistantImages;
952
838
 
953
839
  /**
954
840
  * Wrap ctx.sessionManager.appendMessage once per session so that when pi
@@ -959,7 +845,7 @@ function initBridge(pi: ExtensionAPI) {
959
845
  const sm = ctx?.sessionManager;
960
846
  if (!sm || typeof sm.appendMessage !== "function") return;
961
847
  // Re-wrap when sessionManager identity changes (session replacement).
962
- if (sm === lastWrappedSm && appendMessageWrapped) return;
848
+ if (sm === inst.lastWrappedSm && inst.appendMessageWrapped) return;
963
849
  const original = sm.appendMessage.bind(sm);
964
850
  sm.appendMessage = (msg: any, ...rest: any[]) => {
965
851
  const result = original(msg, ...rest);
@@ -967,13 +853,13 @@ function initBridge(pi: ExtensionAPI) {
967
853
  if (msg && typeof msg === "object" && typeof msg.id === "string") {
968
854
  idByMessage.set(msg as object, msg.id);
969
855
  const nonce = pendingNonces.get(msg as object);
970
- if (nonce && sessionReady && isActive()) {
856
+ if (nonce && inst.sessionReady && isActive()) {
971
857
  const ev = {
972
858
  type: "entry_persisted",
973
859
  entryId: msg.id,
974
860
  nonce,
975
861
  };
976
- connection.send(mapEventToProtocol(sessionId, ev));
862
+ inst.connection.send(mapEventToProtocol(inst.sessionId, ev));
977
863
  pendingNonces.delete(msg as object);
978
864
  }
979
865
  }
@@ -982,12 +868,13 @@ function initBridge(pi: ExtensionAPI) {
982
868
  }
983
869
  return result;
984
870
  };
985
- lastWrappedSm = sm;
986
- appendMessageWrapped = true;
871
+ inst.lastWrappedSm = sm;
872
+ inst.appendMessageWrapped = true;
987
873
  }
874
+ inst.wrapAppendMessageForCtx = wrapAppendMessageForCtx;
988
875
 
989
- let customPersistenceWrapped = false;
990
- let customWrappedSm: any = null;
876
+ inst.customPersistenceWrapped = false;
877
+ inst.customWrappedSm = null;
991
878
 
992
879
  /**
993
880
  * Wrap the sessionManager custom-persistence methods so the bridge can
@@ -1012,7 +899,7 @@ function initBridge(pi: ExtensionAPI) {
1012
899
  return;
1013
900
  }
1014
901
  // Re-wrap when sessionManager identity changes (session replacement).
1015
- if (sm === customWrappedSm && customPersistenceWrapped) return;
902
+ if (sm === inst.customWrappedSm && inst.customPersistenceWrapped) return;
1016
903
  const origMessage = sm.appendCustomMessageEntry.bind(sm);
1017
904
  sm.appendCustomMessageEntry = (customType: any, content: any, display: any, details: any) => {
1018
905
  const entryId = origMessage(customType, content, display, details);
@@ -1021,10 +908,10 @@ function initBridge(pi: ExtensionAPI) {
1021
908
  coalescer.flush();
1022
909
  try {
1023
910
  const forward = toCustomMessageForward({ customType, content, display, details, entryId });
1024
- if (forward && sessionReady && isActive()) {
1025
- connection.send({
911
+ if (forward && inst.sessionReady && isActive()) {
912
+ inst.connection.send({
1026
913
  type: "event_forward",
1027
- sessionId,
914
+ sessionId: inst.sessionId,
1028
915
  event: {
1029
916
  eventType: "message_end",
1030
917
  timestamp: Date.now(),
@@ -1044,10 +931,10 @@ function initBridge(pi: ExtensionAPI) {
1044
931
  coalescer.flush();
1045
932
  try {
1046
933
  const forward = toCustomEntryForward({ type: "custom", customType, data, id: entryId });
1047
- if (forward && sessionReady && isActive()) {
1048
- connection.send({
934
+ if (forward && inst.sessionReady && isActive()) {
935
+ inst.connection.send({
1049
936
  type: "event_forward",
1050
- sessionId,
937
+ sessionId: inst.sessionId,
1051
938
  event: {
1052
939
  eventType: "custom_entry",
1053
940
  timestamp: Date.now(),
@@ -1060,9 +947,10 @@ function initBridge(pi: ExtensionAPI) {
1060
947
  }
1061
948
  return entryId;
1062
949
  };
1063
- customWrappedSm = sm;
1064
- customPersistenceWrapped = true;
950
+ inst.customWrappedSm = sm;
951
+ inst.customPersistenceWrapped = true;
1065
952
  }
953
+ inst.wrapCustomPersistenceForCtx = wrapCustomPersistenceForCtx;
1066
954
 
1067
955
  /** Wrap a callback so errors log instead of crashing the host pi agent. */
1068
956
  function safe<T extends (...args: any[]) => any>(fn: T): T {
@@ -1080,26 +968,30 @@ function initBridge(pi: ExtensionAPI) {
1080
968
  }
1081
969
  }) as T;
1082
970
  }
971
+ inst.safe = safe;
1083
972
 
1084
973
  // Load config to determine WebSocket URL
1085
974
  ensureConfig();
1086
975
  const config = loadConfig();
976
+ inst.config = config;
1087
977
  // The ONE place an endpoint is chosen (D3, task 3.1). Explicit configuration
1088
978
  // is pinned and outranks everything; the HOME-derived rendezvous record is
1089
979
  // the default; discovery may only suggest. The legacy
1090
980
  // `ws://localhost:<configured piPort>` is the last resort, kept so a new
1091
981
  // bridge still works against a dashboard that predates the record (task 8.3).
1092
982
  const rendezvous = rendezvousEndpoint();
983
+ inst.rendezvous = rendezvous;
1093
984
  const endpointChoice = resolveEndpoint({
1094
985
  socketEnv: process.env.PI_DASHBOARD_SOCKET,
1095
986
  urlEnv: process.env.PI_DASHBOARD_URL,
1096
987
  record: rendezvous ?? undefined,
1097
988
  });
989
+ inst.endpointChoice = endpointChoice;
1098
990
  // The instance this bridge believes it is talking to (task 3.4). Any
1099
991
  // re-target is judged against THIS id, not against the endpoint string —
1100
992
  // the same instance may legitimately move, and a different instance may
1101
993
  // legitimately answer at the same endpoint.
1102
- let registeredInstanceId: string | undefined = endpointChoice.available
994
+ inst.registeredInstanceId = endpointChoice.available
1103
995
  ? endpointChoice.instanceId
1104
996
  : undefined;
1105
997
  // A socket-pinned bridge learns its instance from the FILESYSTEM, beside the
@@ -1110,12 +1002,12 @@ function initBridge(pi: ExtensionAPI) {
1110
1002
  // socket. Best-effort: a missing or unreadable file leaves the id unset,
1111
1003
  // which is the honest answer and exactly today's behaviour.
1112
1004
  // See change: add-pi-gateway-transport-identity (task 9.6).
1113
- if (registeredInstanceId === undefined && endpointChoice.available && process.env.PI_DASHBOARD_SOCKET) {
1005
+ if (inst.registeredInstanceId === undefined && endpointChoice.available && process.env.PI_DASHBOARD_SOCKET) {
1114
1006
  const idFile = instanceIdFileForSocket(process.env.PI_DASHBOARD_SOCKET);
1115
1007
  if (idFile) {
1116
1008
  try {
1117
1009
  const id = fs.readFileSync(idFile, "utf8").trim();
1118
- if (id) registeredInstanceId = id;
1010
+ if (id) inst.registeredInstanceId = id;
1119
1011
  } catch {
1120
1012
  /* absent or unreadable — stay unverified rather than guess */
1121
1013
  }
@@ -1124,20 +1016,22 @@ function initBridge(pi: ExtensionAPI) {
1124
1016
  // `let`: a completed move re-points this, so diagnostics and `/dashboard-where`
1125
1017
  // report where the session actually IS rather than where it started.
1126
1018
  // biome-ignore lint/style/useConst: reassigned by the move command.
1127
- let dashboardUrl = endpointChoice.available
1019
+ inst.dashboardUrl = endpointChoice.available
1128
1020
  ? endpointChoice.url
1129
1021
  : `ws://localhost:${config.piPort}`;
1130
1022
  // Pinned endpoints refuse every re-target, including a discovered one (D3).
1131
1023
  const endpointPinned = endpointChoice.available && endpointChoice.pinned;
1024
+ inst.endpointPinned = endpointPinned;
1132
1025
  // Task 10.1: log the winning precedence rule, or diagnosing "it connected to
1133
1026
  // the wrong dashboard" means guessing which source won.
1134
- const endpointDetail = `${dashboardUrl} (source=${
1027
+ const endpointDetail = `${inst.dashboardUrl} (source=${
1135
1028
  endpointChoice.available ? endpointChoice.source : "legacy-config-piPort"
1136
1029
  } pinned=${endpointPinned})`;
1137
1030
  console.log(`[dashboard] endpoint ${endpointDetail}`);
1138
1031
  // ...and again over the wire, because the line above is discarded under the
1139
1032
  // default `capturePiOutput:false` (task 10.5).
1140
1033
  const transportDiagnostics = createTransportDiagnostics();
1034
+ inst.transportDiagnostics = transportDiagnostics;
1141
1035
  transportDiagnostics.record({ event: "endpoint_resolved", detail: endpointDetail });
1142
1036
 
1143
1037
  /**
@@ -1168,9 +1062,10 @@ function initBridge(pi: ExtensionAPI) {
1168
1062
  // mutated when `event.reason ∈ {"new","fork","resume"}` fires).
1169
1063
  const uiModulesBridgeCtx: UiModulesBridgeCtx = {
1170
1064
  pi: pi as any,
1171
- connection: { send: (msg: unknown) => connection.send(msg) },
1172
- getSessionId: () => sessionId,
1065
+ connection: { send: (msg: unknown) => inst.connection.send(msg) },
1066
+ getSessionId: () => inst.sessionId,
1173
1067
  };
1068
+ inst.uiModulesBridgeCtx = uiModulesBridgeCtx;
1174
1069
 
1175
1070
  // `let`, not `const`: a completed move REBINDS this to the target's
1176
1071
  // connection, and every closure in this module captured the BINDING rather
@@ -1181,7 +1076,8 @@ function initBridge(pi: ExtensionAPI) {
1181
1076
  // installed only while the socket is open; a close fails pending calls
1182
1077
  // `disconnected`. See change: expose-plugin-credential-and-oauth-seams (D7).
1183
1078
  // Non-buffering send: a request must never be replayed after a reconnect.
1184
- const pluginRequests = createPluginRequestClient({ send: (m) => connection.sendIfOpen(m) });
1079
+ const pluginRequests = createPluginRequestClient({ send: (m) => inst.connection.sendIfOpen(m) });
1080
+ inst.pluginRequests = pluginRequests;
1185
1081
  let uninstallPluginRequest: (() => void) | null = null;
1186
1082
  const pluginLaneUp = (): void => {
1187
1083
  uninstallPluginRequest?.();
@@ -1198,14 +1094,14 @@ function initBridge(pi: ExtensionAPI) {
1198
1094
  // See change: ask-agent-file-access-in-chat.
1199
1095
  const pathGate = createPathGate({
1200
1096
  suppression: (getBridgeState().pathGateSuppression ??= new Suppression()),
1201
- getSessionId: () => sessionId,
1202
- getPromptBus: () => promptBus,
1203
- send: (m) => connection.sendIfOpen(m),
1097
+ getSessionId: () => inst.sessionId,
1098
+ getPromptBus: () => inst.promptBus,
1099
+ send: (m) => inst.connection.sendIfOpen(m),
1204
1100
  readConfig: () => loadConfig().agentPathGate,
1205
- getCwd: () => cachedCwd ?? process.cwd(),
1101
+ getCwd: () => inst.cachedCwd ?? process.cwd(),
1206
1102
  getSessionDir: () => {
1207
1103
  try {
1208
- return cachedCtx?.sessionManager?.getSessionDir?.();
1104
+ return inst.cachedCtx?.sessionManager?.getSessionDir?.();
1209
1105
  } catch {
1210
1106
  return undefined;
1211
1107
  }
@@ -1213,15 +1109,71 @@ function initBridge(pi: ExtensionAPI) {
1213
1109
  log: (line) => console.log(line),
1214
1110
  notify: (message) => {
1215
1111
  try {
1216
- cachedCtx?.ui?.notify?.(message, "warning");
1112
+ inst.cachedCtx?.ui?.notify?.(message, "warning");
1217
1113
  } catch {
1218
1114
  /* best effort */
1219
1115
  }
1220
1116
  },
1221
1117
  });
1118
+ inst.pathGate = pathGate;
1119
+
1120
+ // Credential vault: applies the hub's granted env values to process.env and
1121
+ // reconciles on every connect and session_start. State lives on `process`, so
1122
+ // a reload keeps it. See change: add-credential-vault.
1123
+ const vaultDelivery = createVaultDelivery({
1124
+ send: (m) => inst.connection.sendIfOpen(m),
1125
+ sessionId: () => inst.sessionId ?? "",
1126
+ log: (line) => console.log(line),
1127
+ });
1128
+ inst.vaultDelivery = vaultDelivery;
1129
+ // Redaction: the value set is vaultDelivery's process-global redaction registry,
1130
+ // so a reload and a nested pi mask the same values. The forward filter masks
1131
+ // every outgoing event_forward frame on a copy (with tail hold-back) and is
1132
+ // installed at the connection, so no plaintext value reaches the send buffer.
1133
+ const vaultRedaction = createVaultRedaction({
1134
+ getState: () => vaultDelivery.redactionState(),
1135
+ createLocalBashOperations: async () => {
1136
+ try {
1137
+ const pkg: any = await import("@earendil-works/pi-coding-agent");
1138
+ const create: (() => unknown) | undefined = pkg.createLocalBashOperations ?? pkg.default?.createLocalBashOperations;
1139
+ return create?.() as any;
1140
+ } catch {
1141
+ return undefined; // the forwarded copy is still masked
1142
+ }
1143
+ },
1144
+ log: (line) => console.log(line),
1145
+ });
1146
+ const vaultForwardFilter = createVaultForwardFilter(vaultRedaction.masker);
1147
+ // tool_result / message_end / user_bash: masked before pi records the result.
1148
+ // Fail CLOSED: if masking throws, the output is withheld rather than passed raw.
1149
+ pi.on("tool_result", async (event: any) => {
1150
+ try {
1151
+ return (await vaultRedaction.toolResult(event)) as any;
1152
+ } catch {
1153
+ return { content: [{ type: "text", text: "[output withheld: vault redaction failed]" }], details: undefined, structuredContent: undefined } as any;
1154
+ }
1155
+ });
1156
+ pi.on("message_end", (event: any) => {
1157
+ try {
1158
+ return vaultRedaction.messageEnd(event) as any;
1159
+ } catch {
1160
+ // Fail CLOSED like tool_result: record a placeholder, keep the role.
1161
+ const message = event?.message;
1162
+ if (!message || typeof message !== "object") return undefined;
1163
+ return { message: { ...message, content: [{ type: "text", text: "[message withheld: vault redaction failed]" }] } } as any;
1164
+ }
1165
+ });
1166
+ pi.on("user_bash", async () => {
1167
+ try {
1168
+ return (await vaultRedaction.userBash()) as any;
1169
+ } catch {
1170
+ return undefined;
1171
+ }
1172
+ });
1222
1173
 
1223
- let connection = new ConnectionManager({
1224
- url: dashboardUrl,
1174
+ inst.connection = new ConnectionManager({
1175
+ url: inst.dashboardUrl,
1176
+ outboundFilter: (m) => vaultForwardFilter.filter(m),
1225
1177
  // fix-bridge-mdns-migration-hijack (D5): every migration decision —
1226
1178
  // accepted or refused, including a reversibility fallback — is reported
1227
1179
  // through this single chokepoint. `console.log` serves capture-enabled
@@ -1236,24 +1188,31 @@ function initBridge(pi: ExtensionAPI) {
1236
1188
  detail,
1237
1189
  });
1238
1190
  },
1239
- // D6 (task 5.3): a LOOPBACK TCP dial carries this HOME's local token, the
1240
- // credential that replaces the socket's file mode where there is no socket
1241
- // (Windows, or a sun_path fallback). Undefined over a socket and never
1242
- // sent to a remote endpoint.
1243
- headers: localTokenHeaders(dashboardUrl),
1191
+ // D6 (task 5.3): a LOOPBACK TCP dial carries a PROOF of possession of this
1192
+ // HOME's local token (never the token), bound to the address actually
1193
+ // reached — the credential that replaces the socket's file mode where there
1194
+ // is no socket (Windows, or a sun_path fallback). Planned per dial, so each
1195
+ // attempt has a fresh nonce; nothing is planned over a socket or for a
1196
+ // remote endpoint. A bridge MARKED by its spawner also verifies the server
1197
+ // counter-proof before `open`. See change: loopback-credential-proof (D6, D7).
1198
+ planDial: (base) => localCredentialPlan(base),
1199
+ onIdentityFailure: (report) => {
1200
+ console.error(`[dashboard] server identity check failed (${report.cause}) at ${report.endpoint}`);
1201
+ appendIdentityLog(report);
1202
+ },
1244
1203
  // Every accepted re-target (and every reversal) re-derives these from the
1245
- // endpoint actually being dialled — a loopback token must never ride a
1204
+ // endpoint actually being dialled — a loopback proof must never ride a
1246
1205
  // dial to a discovered remote host, and a remote candidate needs its own
1247
1206
  // bridge ticket. (CodeRabbit review, fix-bridge-mdns-migration-hijack.)
1248
1207
  credentialsFor: (u) => ({
1249
- headers: localTokenHeaders(u),
1208
+ planDial: (base) => localCredentialPlan(base),
1250
1209
  prepare: () => prepareRemoteUpgrade(u),
1251
1210
  }),
1252
1211
  // A REMOTE endpoint needs a bridge ticket per attempt (§6 made TCP bridge
1253
1212
  // auth mandatory). Local dials — unix socket or loopback — are authorised
1254
1213
  // by file mode or the local token and mint nothing.
1255
1214
  // See change: add-pi-gateway-transport-identity (D10b).
1256
- prepareConnect: () => prepareRemoteUpgrade(dashboardUrl),
1215
+ prepareConnect: () => prepareRemoteUpgrade(inst.dashboardUrl),
1257
1216
  // Attribute every force-close. `record` flushes through the live socket
1258
1217
  // when one is still OPEN (the callback runs BEFORE teardown) and falls
1259
1218
  // back to the buffer otherwise, so the report survives either way.
@@ -1265,444 +1224,35 @@ function initBridge(pi: ExtensionAPI) {
1265
1224
  // Routing field for a drop report — the reporting bridge's OWN session,
1266
1225
  // never the id the dropped message named.
1267
1226
  // See change: fix-spawn-correlation-ttl-coupling (D6).
1268
- getSessionId: () => sessionId,
1227
+ getSessionId: () => inst.sessionId,
1269
1228
  // Lane lifecycle follows the CURRENT connection only: after a
1270
1229
  // `/dashboard-connect` move, `connection` is rebound to the target.
1271
1230
  onOpen: () => {
1272
- if (!isActive() || connection !== primaryConnection) return;
1231
+ if (!isActive() || inst.connection !== primaryConnection) return;
1273
1232
  pluginLaneUp();
1233
+ vaultDelivery.onOpen();
1234
+ // `onReconnect` skips the FIRST open, so plugin latest/stream messages
1235
+ // retained before it would wait for the next emission. Drain after the
1236
+ // manager flushes its buffered register frame (microtask).
1237
+ // See change: add-plugin-bridge-contributions.
1238
+ queueMicrotask(() => {
1239
+ if (!isActive() || inst.connection !== primaryConnection) return;
1240
+ try {
1241
+ pluginForwardRegistry.flush();
1242
+ } catch {
1243
+ /* registry not yet initialised (declared later in initBridge) */
1244
+ }
1245
+ });
1274
1246
  },
1275
1247
  onClose: () => {
1276
- if (connection !== primaryConnection) return;
1248
+ if (inst.connection !== primaryConnection) return;
1277
1249
  pluginLaneDown();
1278
1250
  pathGate.reset();
1251
+ vaultDelivery.onClose();
1279
1252
  },
1280
1253
  onMessage: safe(async (data: unknown) => {
1281
- if (!isActive()) return; // Stale listener guard
1282
- const msg = data as ServerToExtensionMessage;
1283
- // D12: the dashboard asking for a slice of THIS session's transcript.
1284
- // Guarded before any filesystem touch — a request naming a path, or
1285
- // another session, never reaches the reader. See change:
1286
- // add-pi-gateway-transport-identity (tasks 11.3/11.4/11.6).
1287
- if ((msg as any).type === "transcript_request") {
1288
- const req = msg as unknown as TranscriptRequestMessage;
1289
- const verdict = decideTranscriptRequest({
1290
- request: req as never,
1291
- ownSessionId: sessionId,
1292
- });
1293
- if (!verdict.allow) {
1294
- console.warn(`[dashboard] transcript request refused: ${verdict.reason}`);
1295
- connection.send({
1296
- type: "transcript_chunk",
1297
- // Echo the caller's id: routing is the connection, and the server
1298
- // must be able to correlate a refusal with what it asked for.
1299
- sessionId: req.sessionId,
1300
- entries: [],
1301
- complete: false,
1302
- restarted: false,
1303
- refused: { cause: verdict.cause, reason: verdict.reason },
1304
- });
1305
- return;
1306
- }
1307
- if (!lastSessionFile) return;
1308
- const chunk = readTranscriptChunk(
1309
- lastSessionFile,
1310
- req.cursor as TranscriptCursor | undefined,
1311
- { maxBytes: req.maxBytes },
1312
- );
1313
- connection.send({
1314
- type: "transcript_chunk",
1315
- sessionId: req.sessionId,
1316
- entries: chunk.entries,
1317
- cursor: chunk.cursor,
1318
- complete: chunk.complete,
1319
- restarted: chunk.restarted,
1320
- });
1321
- return;
1322
- }
1323
- // Extension UI System (Phase 1): browser-originated action / data
1324
- // request. Re-emit on pi.events; the listener either populates
1325
- // data.items synchronously or calls _reply asynchronously.
1326
- // See change: add-extension-ui-modal.
1327
- if ((msg as any).type === "ui_management") {
1328
- handleUiManagement(uiModulesBridgeCtx, msg as any);
1329
- return;
1330
- }
1331
- // Server announced a deliberate restart/shutdown. Pause the auto-start
1332
- // spawn step in `server-auto-start.ts` for `quiesceMs` so we don't
1333
- // race the orchestrator that's about to bring up the replacement.
1334
- // Discovery + reconnection still run via the normal backoff path.
1335
- // See change: fix-restart-bridge-auto-start-race.
1336
- if ((msg as any).type === "server_restarting") {
1337
- const reason = (msg as any).reason;
1338
- const quiesceMs = (msg as any).quiesceMs;
1339
- if (typeof quiesceMs === "number" && quiesceMs > 0) {
1340
- connection.pauseAutoStart(quiesceMs);
1341
- console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${quiesceMs})`);
1342
- }
1343
- return;
1344
- }
1345
- // Legacy extension_ui_response removed — now handled by prompt_response → promptBus.respond()
1346
- if (msg.type === "plugin_reply") {
1347
- // Resolves the caller's Promise only — never re-emitted on pi.events.
1348
- pluginRequests.handleReply(msg);
1349
- return;
1350
- }
1351
- // Agent path gate: grant-store identity + grant results (never re-emitted).
1352
- if (pathGate.onServerMessage(msg as { type?: string })) return;
1353
- if (msg.type === "mcp_token_minted") {
1354
- // The minted MCP bearer (+ /mcp url) arrives on the session-private
1355
- // lane and is registered with pi's built-in MCP — never placed in
1356
- // process.env, a log line, or pi.events.
1357
- // See change: migrate-mcp-to-pi-builtin (D1).
1358
- mcpRegistrar.onMinted(msg as McpTokenMintedPayload);
1359
- return;
1360
- }
1361
- // Reload auth credentials when dashboard notifies of changes
1362
- if (msg.type === "credentials_updated") {
1363
- try {
1364
- // Hot-reload providers.json diff BEFORE refreshing the registry,
1365
- // so any newly added providers are registered before getAvailable() runs.
1366
- const diff = await reloadProviders(pi).catch((err) => {
1367
- console.error("[dashboard] reloadProviders failed:", err);
1368
- return { added: [], removed: [], changed: [] };
1369
- });
1370
- if (diff.added.length || diff.removed.length || diff.changed.length) {
1371
- console.log(
1372
- `[dashboard] hot-reloaded providers: added=${JSON.stringify(diff.added)} removed=${JSON.stringify(diff.removed)} changed=${JSON.stringify(diff.changed)}`,
1373
- );
1374
- }
1375
- cachedModelRegistry?.authStorage?.reload?.();
1376
- // pi 0.84.0: refresh() takes ModelsRefreshOptions and returns
1377
- // { aborted, errors }. Await + inspect it so getAvailable() below
1378
- // sees the refreshed catalogue and a per-provider failure is
1379
- // reported rather than silently dropped. Scope the refresh to the
1380
- // providers this reload actually touched -- an unrelated provider's
1381
- // catalogue has no reason to be re-fetched because one credential
1382
- // changed. Empty scope (removals only) => refresh nothing.
1383
- // See change: update-pi-core-0-84-adopt-apis.
1384
- const touched = [...new Set([...diff.added, ...diff.changed])];
1385
- if (touched.length > 0) {
1386
- await reportRefresh(
1387
- cachedModelRegistry?.refresh?.({ providers: touched }),
1388
- `credentials reload refresh (${touched.join(", ")})`,
1389
- );
1390
- }
1391
- } catch (err) { console.error("[dashboard] credentials reload failed:", err); }
1392
- // Push updated models list to dashboard client
1393
- if (cachedModelRegistry && sessionReady) {
1394
- try {
1395
- const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
1396
- connection.send({ type: "models_list", sessionId, models });
1397
- // See change: replace-hardcoded-provider-lists.
1398
- connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
1399
- } catch (err) { console.error("[dashboard] models_list push failed:", err); }
1400
- }
1401
- return;
1402
- }
1403
- // Auto-naming toggle relay: store the pushed value so the namer gates on
1404
- // the current preference. See change: add-auto-session-naming.
1405
- if (msg.type === "preferences_update") {
1406
- if (typeof (msg as any).autoNameSessions === "boolean") {
1407
- autoNameSessions = (msg as any).autoNameSessions;
1408
- }
1409
- return;
1410
- }
1411
- // Persisted stop state pushed at register, so a permanent stop survives a
1412
- // PROCESS restart. Only the STOP fields are adopted. `nameSource`,
1413
- // `lastSelfApplied` and `hasAutoName` are deliberately NOT restored:
1414
- // reinstating them would change the behaviour of the separate auto→`user`
1415
- // relabel bug, which has a different root cause and is tracked on its own
1416
- // (design D8b, change: investigate-auto-name-provenance-relabel). They are
1417
- // still carried across an in-process RELOAD via `prev.namerState`.
1418
- // See change: fix-auto-naming-reasoning-model (design D7).
1419
- if (msg.type === "auto_name_state_restore") {
1420
- const adopted = adoptRestoredNamerState((msg as any).state);
1421
- if (adopted && !autoNamer) {
1422
- namerState = adopted;
1423
- prev.namerState = adopted;
1424
- }
1425
- return;
1426
- }
1427
- // Graceful stop-after-turn: latch a per-session flag; the next turn_end
1428
- // shuts the session down cleanly. Idempotent. See change:
1429
- // adopt-pi-071-072-073-features.
1430
- if (msg.type === "stop_after_turn") {
1431
- getBridgeState().shouldStopAfterTurn = true;
1432
- return;
1433
- }
1434
- // Forced PR-status probe after a worktree Push / Open PR. The server
1435
- // only targets bridges whose cwd is inside the worktree. See change:
1436
- // redesign-composer-session-strip (D5).
1437
- if (routeGitInfoRefresh(msg, { prStatus, gitTracker: polling.gitTracker })) return;
1438
- // Route flow management actions from dashboard buttons
1439
- if (msg.type === "flow_management" && pi.events) {
1440
- if (msg.action === "run") {
1441
- pi.events.emit("flow:run", { flowName: msg.flowName, task: msg.task || undefined });
1442
- } else if (msg.action === "set-edit-mode") {
1443
- // Edit-mode toggle (rework-flows-plugin-for-new-pi-flows). pi-flows
1444
- // persists flows.editFlow, syncs skill visibility, reloads.
1445
- // /flows:new + /flows:edit removed upstream — authoring is now the
1446
- // edit-flow skill via send_prompt from the dashboard.
1447
- if (typeof (msg as { enabled?: unknown }).enabled === "boolean") {
1448
- pi.events.emit("flow:set-edit-mode", { enabled: (msg as { enabled: boolean }).enabled });
1449
- }
1450
- } else if (msg.action === "delete") {
1451
- // Dashboard already confirmed upfront — delete directly
1452
- pi.events.emit("flow:delete-request", { flowName: msg.flowName });
1453
- pi.events.emit("flow:notify", { message: `Flow "${msg.flowName}" deleted.`, level: "info" });
1454
- }
1455
- return;
1456
- }
1457
- // Route role management from dashboard
1458
- if (msg.type === "role_set" && pi.events) {
1459
- const data: any = { role: (msg as any).role, modelId: (msg as any).modelId };
1460
- pi.events.emit("roles:set", data);
1461
- if (data.success) {
1462
- const rolesData: any = {};
1463
- pi.events.emit("roles:get-all", rolesData);
1464
- connection.send({
1465
- type: "roles_list",
1466
- sessionId,
1467
- roles: rolesData.roles ?? {},
1468
- presets: rolesData.presets ?? [],
1469
- activePreset: rolesData.activePreset ?? null,
1470
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1471
- });
1472
- }
1473
- return;
1474
- }
1475
- if (msg.type === "role_preset_load" && pi.events) {
1476
- const data: any = { name: (msg as any).presetName };
1477
- pi.events.emit("roles:preset-load", data);
1478
- if (data.success) {
1479
- const rolesData: any = {};
1480
- pi.events.emit("roles:get-all", rolesData);
1481
- connection.send({
1482
- type: "roles_list",
1483
- sessionId,
1484
- roles: rolesData.roles ?? {},
1485
- presets: rolesData.presets ?? [],
1486
- activePreset: rolesData.activePreset ?? null,
1487
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1488
- });
1489
- }
1490
- return;
1491
- }
1492
- if (msg.type === "role_preset_save" && pi.events) {
1493
- const data: any = { name: (msg as any).presetName };
1494
- pi.events.emit("roles:preset-save", data);
1495
- if (data.success) {
1496
- const rolesData: any = {};
1497
- pi.events.emit("roles:get-all", rolesData);
1498
- connection.send({
1499
- type: "roles_list",
1500
- sessionId,
1501
- roles: rolesData.roles ?? {},
1502
- presets: rolesData.presets ?? [],
1503
- activePreset: rolesData.activePreset ?? null,
1504
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1505
- });
1506
- }
1507
- return;
1508
- }
1509
- if (msg.type === "role_preset_delete" && pi.events) {
1510
- const data: any = { name: (msg as any).presetName };
1511
- pi.events.emit("roles:preset-delete", data);
1512
- if (data.success) {
1513
- const rolesData: any = {};
1514
- pi.events.emit("roles:get-all", rolesData);
1515
- connection.send({
1516
- type: "roles_list",
1517
- sessionId,
1518
- roles: rolesData.roles ?? {},
1519
- presets: rolesData.presets ?? [],
1520
- activePreset: rolesData.activePreset ?? null,
1521
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1522
- });
1523
- }
1524
- return;
1525
- }
1526
- // Remove a CUSTOM role: purge from schema + active map + every preset.
1527
- // Built-ins are rejected server-side in the roles:remove handler.
1528
- // Mirrors the role_set routing block. See change: add-custom-roles-ui.
1529
- if (msg.type === "role_remove" && pi.events) {
1530
- const data: any = { role: (msg as any).role };
1531
- pi.events.emit("roles:remove", data);
1532
- if (data.success) {
1533
- const rolesData: any = {};
1534
- pi.events.emit("roles:get-all", rolesData);
1535
- connection.send({
1536
- type: "roles_list",
1537
- sessionId,
1538
- roles: rolesData.roles ?? {},
1539
- presets: rolesData.presets ?? [],
1540
- activePreset: rolesData.activePreset ?? null,
1541
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1542
- });
1543
- }
1544
- return;
1545
- }
1546
- if (msg.type === "request_roles" && pi.events) {
1547
- const rolesData: any = {};
1548
- pi.events.emit("roles:get-all", rolesData);
1549
- connection.send({
1550
- type: "roles_list",
1551
- sessionId,
1552
- roles: rolesData.roles ?? {},
1553
- presets: rolesData.presets ?? [],
1554
- activePreset: rolesData.activePreset ?? null,
1555
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
1556
- });
1557
- return;
1558
- }
1559
- // Route PromptBus responses from dashboard client
1560
- if (msg.type === "prompt_response" && promptBus) {
1561
- promptBus.respond({
1562
- id: (msg as any).promptId,
1563
- answer: (msg as any).answer,
1564
- cancelled: (msg as any).cancelled,
1565
- source: (msg as any).source ?? "dashboard-default",
1566
- // Optional pasted images for method:"input".
1567
- // See change: add-ask-user-input-multiline-paste.
1568
- images: (msg as any).images,
1569
- });
1570
- return;
1571
- }
1572
- // Legacy architect_prompt_response routing REMOVED.
1573
- // Previously routed to flow:prompt-response + cancelAllPending().
1574
- // Now handled by PromptBus: dashboard sends prompt_response,
1575
- // bus calls respond(), adapters get onResponse() for cross-cancellation.
1576
- // Route flow control messages to pi-flows via pi.events
1577
- // Generic plugin-registered event emission. A dashboard plugin action
1578
- // (e.g. automation) emits a configured event INTO this session; the
1579
- // bridge relays it onto pi.events. Decoupled: the bridge does not know
1580
- // which events exist. See change: automation-emit-configured-event.
1581
- if (msg.type === "plugin_emit_event" && pi.events) {
1582
- const eventType = (msg as { eventType?: unknown }).eventType;
1583
- if (typeof eventType === "string" && eventType.length > 0) {
1584
- const data = (msg as { data?: unknown }).data;
1585
- pi.events.emit(eventType, data && typeof data === "object" ? (data as Record<string, unknown>) : {});
1586
- }
1587
- return;
1588
- }
1589
- // Subagent resync (D2): reply with the latest retained snapshot of a
1590
- // running subagent as a synthetic subagent_started event_forward. No-op
1591
- // for an unknown/finished agent (durable completed-case backfill covers
1592
- // those). See change: fix-subagent-live-detail-reliability.
1593
- if (msg.type === "subagent_resync_request") {
1594
- // The incoming id may be EITHER a v4 agentId or a v7 runner
1595
- // agentSessionId (from a deep-link route); resync() resolves both.
1596
- // See change: resolve-subagent-inspector-by-session-id (D3/D4).
1597
- const requestedId = (msg as { agentId?: unknown }).agentId;
1598
- if (typeof requestedId === "string" && requestedId.length > 0) {
1599
- // The reply is NEVER stripped: it IS the pull model's answer and
1600
- // carries the full timeline for a RUNNING agent — exactly the shape a
1601
- // strip inside `sendEventForward` would have destroyed.
1602
- // See change: reduce-subagent-details-payload (X6).
1603
- const echoId = (msg as { requestId?: unknown }).requestId;
1604
- const resolvedAgentId = serveSubagentResync(
1605
- subagentFrameBuffer,
1606
- requestedId,
1607
- sendEventForward,
1608
- () => sessionReady && isActive(),
1609
- typeof echoId === "string" && echoId.length > 0 ? echoId : undefined,
1610
- (msg as { reason?: "open" | "cadence" }).reason,
1611
- );
1612
- console.log(
1613
- resolvedAgentId
1614
- ? `[dashboard] served subagent resync for id=${requestedId} (resolved agentId=${resolvedAgentId})`
1615
- : `[dashboard] subagent resync no-op (unknown/finished/not-ready) id=${requestedId}`,
1616
- );
1617
- }
1618
- return;
1619
- }
1620
- // Prompt resync (fix B, extension half): a browser asked the bridge to
1621
- // re-emit every prompt it is still awaiting an answer for — the bus's
1622
- // pending set is the source of truth, NOT the server's derived registry
1623
- // (D6). Each frame echoes the requester token so the server unicasts it
1624
- // back to the asking browser as a critical frame. Empty pending set →
1625
- // zero frames, no error (E10); a malformed token degrades to tokenless.
1626
- // See change: fix-pending-prompt-lost-on-replay (design D5/D6/D7).
1627
- if (msg.type === "prompt_resync_request") {
1628
- const echoId = (msg as { requestId?: unknown }).requestId;
1629
- const token = typeof echoId === "string" && echoId.length > 0 ? echoId : undefined;
1630
- if (promptBus) {
1631
- emitPendingPrompts(promptBus, (m) => connection.send(m as any), sessionId, token);
1632
- }
1633
- return;
1634
- }
1635
- if (msg.type === "flow_control" && pi.events) {
1636
- if (msg.action === "abort") {
1637
- pi.events.emit("flow:abort", {});
1638
- // Also abort architect if running (mutually exclusive with flow execution;
1639
- // the irrelevant emit is a no-op due to guard checks on both listeners)
1640
- pi.events.emit("flow:architect-abort", {});
1641
- } else if (msg.action === "toggle_autonomous") {
1642
- pi.events.emit("flow:toggle-autonomous", {});
1643
- } else if (msg.action === "dismiss_summary") {
1644
- pi.events.emit("flow:summary-dismissed", {});
1645
- }
1646
- return;
1647
- }
1648
- // ── Follow-up queue mutation (bridge-owned buffer) ─────────────────
1649
- //
1650
- // These four handlers mutate `bridgeFollowUp` only. NONE of them
1651
- // call pi.sendUserMessage, pi.clear*Queue, or any other pi method.
1652
- // The bridge owns the buffer; pi never sees these entries until the
1653
- // drain loop ships them on agent_end as fresh-turn sendUserMessage.
1654
- //
1655
- // The OLD pi-mutation handler set from Phase 3 (clear_steering_queue,
1656
- // clear_followup_slot, edit_followup_slot) is GONE forever — pi's
1657
- // ExtensionAPI exposes no clear*Queue primitives (verified through
1658
- // pi 0.76.0). Steer mutation will never be exposed (steer drains too
1659
- // fast for it to matter; user direction).
1660
- //
1661
- // See change: rework-mid-turn-prompt-queue (design.md D3).
1662
- if (msg.type === "edit_followup_entry") {
1663
- const { index, text } = msg as { type: string; index: number; text: string };
1664
- // Text-only edit: the entry's images are PRESERVED (design D5). Gated
1665
- // on the byte ceiling because the inline editor can grow text without
1666
- // bound; a refused edit leaves the entry untouched and emits no
1667
- // `queue_update`. See change: fix-bridge-followup-image-drop.
1668
- const edited = bridgeFollowUp.editText(index, text);
1669
- if (!edited.ok) {
1670
- sendCommandFeedback("edit_followup_entry", edited.message);
1671
- return;
1672
- }
1673
- emitQueueUpdate();
1674
- return;
1675
- }
1676
- if (msg.type === "remove_followup_entry") {
1677
- const { index } = msg as { type: string; index: number };
1678
- if (!bridgeFollowUp.removeAt(index)) {
1679
- sendCommandFeedback("remove_followup_entry", "Index out of range");
1680
- return;
1681
- }
1682
- emitQueueUpdate();
1683
- return;
1684
- }
1685
- if (msg.type === "promote_followup_entry") {
1686
- const { index } = msg as { type: string; index: number };
1687
- // Silent no-op for index 0 or invalid — no emit (D3). Carries images.
1688
- if (bridgeFollowUp.promote(index)) emitQueueUpdate();
1689
- return;
1690
- }
1691
- if (msg.type === "clear_followup_entries") {
1692
- const { indices } = msg as { type: string; indices: number[] | "all" };
1693
- const mutated =
1694
- indices === "all" ? bridgeFollowUp.clearAll() : bridgeFollowUp.clearIndices(indices);
1695
- if (mutated) emitQueueUpdate();
1696
- return;
1697
- }
1698
- const response = await commandHandler.handle(msg);
1699
- if (response) connection.send(response);
1700
- // Immediately send model/thinking update after handling set_thinking_level
1701
- if (msg.type === "set_thinking_level") {
1702
- // Small delay to let pi process the level change
1703
- setTimeout(() => sendModelUpdateIfChanged(), 50);
1704
- }
1705
- }),
1254
+ return handleInboundMessage(inst, data);
1255
+ }),
1706
1256
  onReconnect: safe(() => {
1707
1257
  if (!isActive()) return; // Stale listener guard
1708
1258
  // A reconnect is a TRANSPORT boundary, not a session boundary: the live
@@ -1723,7 +1273,7 @@ function initBridge(pi: ExtensionAPI) {
1723
1273
  // doesn't have direct ctx here, so we walk the active session.
1724
1274
  try {
1725
1275
  const activeId = (pi as any).getCurrentSessionId?.();
1726
- const activeCtx = activeId ? (pi as any).getCtx?.(activeId) : (cachedCtx as any);
1276
+ const activeCtx = activeId ? (pi as any).getCtx?.(activeId) : (inst.cachedCtx as any);
1727
1277
  if (activeCtx?.cwd) {
1728
1278
  // First evaluation again: the server lost its git state with the connection.
1729
1279
  const gbc = syncBc();
@@ -1732,7 +1282,9 @@ function initBridge(pi: ExtensionAPI) {
1732
1282
  sendCwdMissingIfChanged(activeCtx.cwd);
1733
1283
  }
1734
1284
  } catch { /* probe failure non-fatal */ }
1735
- replaySessionEntries();
1285
+ // A live reconnect keeps in-flight calls open (no fabricated end).
1286
+ // See change: fix-replay-fabricates-orphan-end-for-live-calls (D3).
1287
+ replaySessionEntries({ liveTailOpen: isLive(inst.cachedCtx, getBridgeState().isAgentStreaming) });
1736
1288
  // Flush subagent frames buffered while the socket was down (D1). Unlike
1737
1289
  // session_start, a transient WS reconnect keeps `sessionReady` true, so
1738
1290
  // the intercept routes those frames into the per-agent buffer; drain them
@@ -1744,13 +1296,14 @@ function initBridge(pi: ExtensionAPI) {
1744
1296
  // Client-side dedup by requestId prevents double-rendering. Shared with the
1745
1297
  // prompt_resync_request handler so the two frames cannot drift (D7).
1746
1298
  // See change: fix-pending-prompt-lost-on-replay.
1747
- if (promptBus) {
1748
- emitPendingPrompts(promptBus, (m) => connection.send(m as any), sessionId);
1299
+ if (inst.promptBus) {
1300
+ emitPendingPrompts(inst.promptBus, (m) => inst.connection.send(m as any), inst.sessionId);
1749
1301
  }
1750
- connection.send({ type: "replay_complete", sessionId });
1302
+ inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
1751
1303
  // If agent is mid-turn, send synthetic agent_start so server sets status to "streaming"
1304
+ // `synthetic` lets the server's end-of-session scan see past it (D4).
1752
1305
  if (getBridgeState().isAgentStreaming) {
1753
- connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
1306
+ inst.connection.send(mapEventToProtocol(inst.sessionId, { type: "agent_start", synthetic: true }));
1754
1307
  }
1755
1308
  // Extension UI System (Phase 1): re-probe modules after every
1756
1309
  // reconnect so the server-side cache stays accurate. The probe is
@@ -1773,43 +1326,61 @@ function initBridge(pi: ExtensionAPI) {
1773
1326
  onPostFlush: safe(() => {
1774
1327
  if (!isActive()) return; // Stale listener guard
1775
1328
  if (getBridgeState().isAgentStreaming) return;
1776
- connection.send({ type: "session_heartbeat", sessionId, agentRunning: false });
1329
+ inst.connection.send({ type: "session_heartbeat", sessionId: inst.sessionId, agentRunning: false });
1777
1330
  }),
1778
1331
  });
1779
1332
  // The lane's lifecycle hooks compare against this to ignore a moved-away origin.
1780
- const primaryConnection = connection;
1333
+ const primaryConnection = inst.connection;
1781
1334
 
1782
1335
  // Track connection so future bridge incarnations can disconnect it
1783
- getBridgeState().connections!.push(connection);
1336
+ getBridgeState().connections!.push(inst.connection);
1784
1337
 
1785
1338
  // See change: fix-terminal-session-dashboard-reload.
1786
- const terminalReload = createTerminalReload({ pi, getSessionId: () => sessionId });
1339
+ const terminalReload = createTerminalReload({ pi, getSessionId: () => inst.sessionId });
1787
1340
 
1788
- const commandHandler = createCommandHandler(pi, () => sessionId, {
1789
- getModelRegistry: () => cachedModelRegistry,
1341
+ const commandHandler = createCommandHandler(pi, () => inst.sessionId, {
1342
+ getModelRegistry: () => inst.cachedModelRegistry,
1343
+ // Selector-open re-sync of providers.json: heals a missed credentials_updated.
1344
+ // See change: refresh-models-on-provider-change (D1).
1345
+ reloadProviders: async () => { await reloadProviders(pi); },
1790
1346
  // Surface a session-id-mismatch drop server-side; the guard's own
1791
1347
  // `console.error` goes to /dev/null under the default
1792
1348
  // `keeperLog.capturePiOutput:false`.
1793
1349
  // See change: fix-spawn-correlation-ttl-coupling (D6).
1794
- reportInboundDrop: (drop) => connection.reportInboundDrop(drop),
1350
+ reportInboundDrop: (drop) => inst.connection.reportInboundDrop(drop),
1795
1351
  // AI-draft fork-subagent wiring (see change:
1796
1352
  // add-session-uncommitted-indicator-and-commit). Both degrade silently
1797
1353
  // to the draft ladder's lower rungs when unavailable.
1798
- getSessionContextText: () => buildSessionContextText(cachedCtx),
1354
+ getSessionContextText: () => buildSessionContextText(inst.cachedCtx),
1799
1355
  runDraftAgent: (seed: string, cwd: string) =>
1800
- runForkSubagentDraft(seed, cwd, () => cachedCtx?.model),
1356
+ runForkSubagentDraft(seed, cwd, () => inst.cachedCtx?.model),
1801
1357
  // Mirror server attach/detach pushes into BridgeContext.attachedChange so
1802
1358
  // the before_agent_start injector exposes it. See change:
1803
1359
  // inject-session-context-into-agent.
1360
+ // Dashboard system renames reach the namer BEFORE pi echoes them, so the
1361
+ // echo is not latched `user`. See change: investigate-auto-name-provenance-relabel (D3).
1362
+ onSystemRename: (name: string) => {
1363
+ const prevName = inst.lastSessionName;
1364
+ const rollbackNamer = getAutoNamer().noteSystemRename(name);
1365
+ inst.lastSessionName = name; // suppress the redundant plain name poll
1366
+ return () => {
1367
+ rollbackNamer();
1368
+ inst.lastSessionName = prevName;
1369
+ };
1370
+ },
1371
+ onUserRename: () => {
1372
+ // Only matters once a namer exists; never create one for a user rename.
1373
+ inst.autoNamer?.noteUserRename();
1374
+ },
1804
1375
  onAttachProposalChanged: (next: string | null) => {
1805
- attachedChange = next;
1376
+ inst.attachedChange = next;
1806
1377
  const s = getBridgeState();
1807
1378
  s.attachedChange = next;
1808
1379
  },
1809
1380
  setThinkingLevel: (level: string) => (pi as any).setThinkingLevel?.(level),
1810
1381
  getThinkingLevel: () => (pi as any).getThinkingLevel?.(),
1811
1382
  setModel: async (provider: string, modelId: string) => {
1812
- const registry = cachedModelRegistry;
1383
+ const registry = inst.cachedModelRegistry;
1813
1384
  if (!registry) return;
1814
1385
  const model = registry.find(provider, modelId);
1815
1386
  if (!model) return;
@@ -1828,8 +1399,8 @@ function initBridge(pi: ExtensionAPI) {
1828
1399
  // that. See change: honest-mid-turn-queue-surface (spec
1829
1400
  // mid-turn-prompt-queue: "Session shutdown invokes cachedCtx.shutdown
1830
1401
  // directly").
1831
- if (cachedCtx?.shutdown) {
1832
- cachedCtx.shutdown();
1402
+ if (inst.cachedCtx?.shutdown) {
1403
+ inst.cachedCtx.shutdown();
1833
1404
  }
1834
1405
  // Safety net: force exit after a short delay in case ctx.shutdown()
1835
1406
  // doesn't terminate (e.g. in RPC mode headless sessions)
@@ -1847,12 +1418,12 @@ function initBridge(pi: ExtensionAPI) {
1847
1418
  // must win — requesting AFTER abort() would leak a set latch onto a later
1848
1419
  // turn. Cleared on the next user prompt (noteUserPrompt) or terminal
1849
1420
  // agent_end. See change: unify-error-retry-lifecycle.
1850
- abortLatch.request(sessionId);
1421
+ abortLatch.request(inst.sessionId);
1851
1422
  // Install retry cancellation BEFORE invoking pi: abort() can dispatch
1852
1423
  // terminal events synchronously, and those belong to the cancelled chain.
1853
- retryTracker.noteAbort(sessionId);
1854
- if (cachedCtx?.abort) {
1855
- cachedCtx.abort();
1424
+ retryTracker.noteAbort(inst.sessionId);
1425
+ if (inst.cachedCtx?.abort) {
1426
+ inst.cachedCtx.abort();
1856
1427
  }
1857
1428
  },
1858
1429
  /**
@@ -1864,18 +1435,18 @@ function initBridge(pi: ExtensionAPI) {
1864
1435
  */
1865
1436
  rawAbort: () => {
1866
1437
  try {
1867
- cachedCtx?.abort?.();
1438
+ inst.cachedCtx?.abort?.();
1868
1439
  } catch (err) {
1869
1440
  console.warn("[dashboard] cachedCtx.abort threw in rawAbort:", err);
1870
1441
  }
1871
1442
  },
1872
1443
  isIdle: () => {
1873
- try { return cachedCtx?.isIdle?.() ?? false; } catch { return false; }
1444
+ try { return inst.cachedCtx?.isIdle?.() ?? false; } catch { return false; }
1874
1445
  },
1875
- eventSink: (msg) => connection.send(msg),
1446
+ eventSink: (msg) => inst.connection.send(msg),
1876
1447
  compact: (opts) => {
1877
- if (cachedCtx?.compact) {
1878
- cachedCtx.compact(opts);
1448
+ if (inst.cachedCtx?.compact) {
1449
+ inst.cachedCtx.compact(opts);
1879
1450
  }
1880
1451
  },
1881
1452
  // Terminal-hosted path only. Dashboard-spawned headless sessions are
@@ -1886,7 +1457,7 @@ function initBridge(pi: ExtensionAPI) {
1886
1457
  // See change: fix-terminal-session-dashboard-reload (D1/D3/D4).
1887
1458
  reload: terminalReload.reload,
1888
1459
  spawnNew: () => {
1889
- connection.send({ type: "spawn_new_session", sessionId, cwd: process.cwd() });
1460
+ inst.connection.send({ type: "spawn_new_session", sessionId: inst.sessionId, cwd: process.cwd() });
1890
1461
  },
1891
1462
  sessionPrompt: async (text, delivery, promptId) => {
1892
1463
  // Route slash commands: management events, flow:run, extension dispatch, then fallback.
@@ -1902,7 +1473,7 @@ function initBridge(pi: ExtensionAPI) {
1902
1473
  if (flowsList.some(f => f.name === cmdName)) {
1903
1474
  // Non-turn slash route: settle any optimistic idle bubble so it does
1904
1475
  // not hang to the 30s timeout. See change: optimistic-prompt-progress.
1905
- connection.send({ type: "prompt_received", sessionId, fresh: false });
1476
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
1906
1477
  pi.events.emit("flow:run", { flowName: cmdName, task: cmdArgs.trim() || undefined });
1907
1478
  return;
1908
1479
  }
@@ -1916,14 +1487,14 @@ function initBridge(pi: ExtensionAPI) {
1916
1487
  const handled = await tryDispatchExtensionCommand(
1917
1488
  pi,
1918
1489
  text,
1919
- sessionId,
1920
- (msg) => connection.send(msg),
1490
+ inst.sessionId,
1491
+ (msg) => inst.connection.send(msg),
1921
1492
  delivery,
1922
1493
  );
1923
1494
  if (handled) {
1924
1495
  // Non-turn dispatch route: settle optimistic idle bubble (no message_start
1925
1496
  // follows). See change: optimistic-prompt-progress.
1926
- connection.send({ type: "prompt_received", sessionId, fresh: false });
1497
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
1927
1498
  return;
1928
1499
  }
1929
1500
 
@@ -1934,24 +1505,26 @@ function initBridge(pi: ExtensionAPI) {
1934
1505
  pi,
1935
1506
  text,
1936
1507
  process.cwd(),
1937
- sessionId,
1938
- (msg) => connection.send(msg),
1508
+ inst.sessionId,
1509
+ (msg) => inst.connection.send(msg),
1939
1510
  );
1940
1511
  if (ranExec) {
1941
1512
  // Non-turn exec-template route: settle optimistic idle bubble.
1942
1513
  // See change: optimistic-prompt-progress.
1943
- connection.send({ type: "prompt_received", sessionId, fresh: false });
1514
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
1944
1515
  return;
1945
1516
  }
1946
1517
 
1947
1518
  // Fallback: route the user prompt based on delivery + streaming state.
1948
1519
  //
1949
1520
  // delivery="followUp" + streaming → buffer in bridgeFollowUp ONLY
1950
- // (pi never sees it until drain).
1521
+ // (pi never sees it until drain on
1522
+ // agent_settled).
1951
1523
  // delivery="steer" + streaming → pi.sendUserMessage({deliverAs:"steer"})
1952
1524
  // + shadow append via recordSteerSent.
1953
- // any delivery + idle → pi.sendUserMessage no deliverAs
1954
- // (fresh turn). No buffer push.
1525
+ // any delivery + idle → pi.sendUserMessage with {deliverAs}
1526
+ // (pi ignores it when idle and starts
1527
+ // a fresh turn). No buffer push.
1955
1528
  //
1956
1529
  // Capture pre-send streaming state BEFORE any pi call — idle sends
1957
1530
  // synchronously fire agent_start which flips isAgentStreaming.
@@ -1969,16 +1542,16 @@ function initBridge(pi: ExtensionAPI) {
1969
1542
  // See change: optimistic-prompt-progress,
1970
1543
  // fix-spawn-correlation-ttl-coupling (D7).
1971
1544
  const buffered = wasStreaming && deliverAs === "followUp";
1972
- connection.send({
1545
+ inst.connection.send({
1973
1546
  type: "prompt_received",
1974
- sessionId,
1547
+ sessionId: inst.sessionId,
1975
1548
  fresh: !wasStreaming,
1976
1549
  ...(promptId && !buffered ? { promptId } : {}),
1977
1550
  });
1978
1551
  const expanded = expandPromptTemplateFromDisk(text, process.cwd(), pi);
1979
1552
  if (buffered) {
1980
1553
  // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
1981
- // drain loop on agent_end will ship the entry as a fresh turn.
1554
+ // drain on agent_settled will ship the entry as a fresh turn.
1982
1555
  bufferFollowupSend(expanded);
1983
1556
  } else {
1984
1557
  // Idle send or steer send — forward to pi directly.
@@ -1992,12 +1565,13 @@ function initBridge(pi: ExtensionAPI) {
1992
1565
  // Clear only the abort latch before prompt routing. A streaming follow-up
1993
1566
  // may be buffered rather than start a run, so retry cancellation is released
1994
1567
  // only by the observed user message_start below.
1995
- noteUserPrompt: () => abortLatch.clear(sessionId),
1568
+ noteUserPrompt: () => abortLatch.clear(inst.sessionId),
1996
1569
  // Disarm a still-armed provider-retry chain so a manual retry's native
1997
1570
  // agent_start is not converted into a synthetic auto_retry_start.
1998
1571
  // See change: replace-dashboard-retry-command-with-protocol-message.
1999
- disarmRetryChain: () => retryTracker.noteExplicitRun(sessionId),
1572
+ disarmRetryChain: () => retryTracker.noteExplicitRun(inst.sessionId),
2000
1573
  });
1574
+ inst.commandHandler = commandHandler;
2001
1575
 
2002
1576
  // Reload support: only a command handler's ctx has `reload()`. The bridge
2003
1577
  // self-dispatches this command (dashboard reload, token arg); a human may
@@ -2039,7 +1613,7 @@ function initBridge(pi: ExtensionAPI) {
2039
1613
  console.error(`[dashboard] connect refused: ${resolved.reason}`);
2040
1614
  return;
2041
1615
  }
2042
- if (resolved.endpoint === dashboardUrl) {
1616
+ if (resolved.endpoint === inst.dashboardUrl) {
2043
1617
  console.error(`[dashboard] already on ${describeConnectTarget(parsed)}`);
2044
1618
  return;
2045
1619
  }
@@ -2060,25 +1634,28 @@ function initBridge(pi: ExtensionAPI) {
2060
1634
  let targetManager: ConnectionManager | undefined;
2061
1635
  const coordinator = createMoveCoordinator({
2062
1636
  origin: {
2063
- connect: () => connection.connect(),
2064
- disconnect: () => connection.disconnect(),
2065
- send: (m) => connection.send(m),
1637
+ connect: () => inst.connection.connect(),
1638
+ disconnect: () => inst.connection.disconnect(),
1639
+ send: (m) => inst.connection.send(m),
2066
1640
  get isConnected() {
2067
- return connection.isConnected;
1641
+ return inst.connection.isConnected;
2068
1642
  },
2069
1643
  // The coordinator never subscribes to the origin; only the target
2070
1644
  // answers the handshake.
2071
1645
  onMessage: () => {},
2072
1646
  },
2073
- sessionId,
2074
- sessionFile: lastSessionFile,
2075
- originEndpoint: dashboardUrl,
1647
+ sessionId: inst.sessionId,
1648
+ sessionFile: inst.lastSessionFile,
1649
+ originEndpoint: inst.dashboardUrl,
1650
+ onServerMessage: (m) => void pathGate.onServerMessage(m),
2076
1651
  connect: (url) => {
2077
1652
  let handler: (msg: unknown) => void = () => {};
2078
1653
  targetManager = new ConnectionManager({
2079
1654
  url,
2080
- headers: localTokenHeaders(url),
2081
- getSessionId: () => sessionId,
1655
+ outboundFilter: (m) => vaultForwardFilter.filter(m),
1656
+ planDial: (base) => localCredentialPlan(base),
1657
+ onIdentityFailure: (report) => appendIdentityLog(report),
1658
+ getSessionId: () => inst.sessionId,
2082
1659
  onMessage: (data) => {
2083
1660
  // Plugin lane replies resolve the caller's Promise only.
2084
1661
  if ((data as { type?: unknown } | null)?.type === "plugin_reply") {
@@ -2088,7 +1665,7 @@ function initBridge(pi: ExtensionAPI) {
2088
1665
  handler(data);
2089
1666
  },
2090
1667
  onClose: () => {
2091
- if (connection === targetManager) pluginLaneDown();
1668
+ if (inst.connection === targetManager) pluginLaneDown();
2092
1669
  },
2093
1670
  // The move REBINDS `connection` to this manager, so without this
2094
1671
  // every post-move force-close would be silent again.
@@ -2101,11 +1678,11 @@ function initBridge(pi: ExtensionAPI) {
2101
1678
  // provisional registration is announced, and a send before the
2102
1679
  // socket is live would be silently dropped.
2103
1680
  onOpen: () => {
2104
- if (connection === targetManager) pluginLaneUp();
1681
+ if (inst.connection === targetManager) pluginLaneUp();
2105
1682
  targetManager?.send({
2106
1683
  type: "session_register",
2107
1684
  extensionIdentity: bridgeExtensionIdentity(),
2108
- sessionId,
1685
+ sessionId: inst.sessionId,
2109
1686
  cwd: process.cwd(),
2110
1687
  source: "tui",
2111
1688
  pid: process.pid,
@@ -2136,19 +1713,19 @@ function initBridge(pi: ExtensionAPI) {
2136
1713
 
2137
1714
  if (!result.ok) {
2138
1715
  console.error(
2139
- `[dashboard] move to ${describeConnectTarget(parsed)} failed: ${result.cause} — still on ${dashboardUrl}`,
1716
+ `[dashboard] move to ${describeConnectTarget(parsed)} failed: ${result.cause} — still on ${inst.dashboardUrl}`,
2140
1717
  );
2141
1718
  return;
2142
1719
  }
2143
1720
 
2144
1721
  // Rebind: from here every `connection.send(...)` in this module reaches
2145
1722
  // the new dashboard.
2146
- if (targetManager) connection = targetManager;
1723
+ if (targetManager) inst.connection = targetManager;
2147
1724
  // The origin's close already took the plugin lane down; bring it up on
2148
1725
  // the target now that it is the current connection.
2149
- if (connection.isConnected) pluginLaneUp();
2150
- dashboardUrl = resolved.endpoint;
2151
- registeredInstanceId = expectInstanceId;
1726
+ if (inst.connection.isConnected) pluginLaneUp();
1727
+ inst.dashboardUrl = resolved.endpoint;
1728
+ inst.registeredInstanceId = expectInstanceId;
2152
1729
  console.error(`[dashboard] moved to ${describeConnectTarget(parsed)} (${expectInstanceId})`);
2153
1730
  },
2154
1731
  });
@@ -2179,8 +1756,8 @@ function initBridge(pi: ExtensionAPI) {
2179
1756
  pi.registerCommand("dashboard-where", {
2180
1757
  handler: async () => {
2181
1758
  const lines = [
2182
- `endpoint: ${dashboardUrl}`,
2183
- `instance: ${registeredInstanceId ?? "unverified"}`,
1759
+ `endpoint: ${inst.dashboardUrl}`,
1760
+ `instance: ${inst.registeredInstanceId ?? "unverified"}`,
2184
1761
  `pinned: ${endpointPinned ? "yes (explicit configuration)" : "no (resolved from the $HOME rendezvous record)"}`,
2185
1762
  `pr-probe: ${prStatus.invocations()} gh invocation(s) this bridge`,
2186
1763
  ];
@@ -2191,11 +1768,11 @@ function initBridge(pi: ExtensionAPI) {
2191
1768
  /** Sync local variables into BridgeContext for extracted module calls */
2192
1769
  function syncBc(): BridgeContext {
2193
1770
  return {
2194
- pi, connection, sessionId, attachedChange,
2195
- cachedCtx, cachedModelRegistry, cachedHasUI,
2196
- lastModel, lastThinkingLevel,
2197
- lastSessionFile, lastSessionDir, lastFirstMessage,
2198
- lastGitBranch, lastGitPrJson, lastSessionName,
1771
+ pi, connection: inst.connection, sessionId: inst.sessionId, attachedChange: inst.attachedChange,
1772
+ cachedCtx: inst.cachedCtx, cachedModelRegistry: inst.cachedModelRegistry, cachedHasUI: inst.cachedHasUI,
1773
+ lastModel: inst.lastModel, lastThinkingLevel: inst.lastThinkingLevel,
1774
+ lastSessionFile: inst.lastSessionFile, lastSessionDir: inst.lastSessionDir, lastFirstMessage: inst.lastFirstMessage,
1775
+ lastGitBranch, lastGitPrJson, lastSessionName: inst.lastSessionName,
2199
1776
  lastGitWorktreeJson,
2200
1777
  lastGitStatusJson,
2201
1778
  lastCwdMissing,
@@ -2206,32 +1783,37 @@ function initBridge(pi: ExtensionAPI) {
2206
1783
  gitTracker: polling.gitTracker ?? undefined,
2207
1784
  };
2208
1785
  }
1786
+ inst.syncBc = syncBc;
2209
1787
  /** Sync BridgeContext mutations back to local variables */
2210
1788
  function applyBc(bc: BridgeContext): void {
2211
- sessionId = bc.sessionId;
2212
- attachedChange = bc.attachedChange;
2213
- cachedCtx = bc.cachedCtx;
2214
- cachedModelRegistry = bc.cachedModelRegistry;
2215
- cachedHasUI = bc.cachedHasUI;
2216
- lastModel = bc.lastModel;
2217
- lastThinkingLevel = bc.lastThinkingLevel;
2218
- lastSessionFile = bc.lastSessionFile;
2219
- lastSessionDir = bc.lastSessionDir;
2220
- lastFirstMessage = bc.lastFirstMessage;
1789
+ inst.sessionId = bc.sessionId;
1790
+ inst.attachedChange = bc.attachedChange;
1791
+ inst.cachedCtx = bc.cachedCtx;
1792
+ inst.cachedModelRegistry = bc.cachedModelRegistry;
1793
+ inst.cachedHasUI = bc.cachedHasUI;
1794
+ inst.lastModel = bc.lastModel;
1795
+ inst.lastThinkingLevel = bc.lastThinkingLevel;
1796
+ inst.lastSessionFile = bc.lastSessionFile;
1797
+ inst.lastSessionDir = bc.lastSessionDir;
1798
+ inst.lastFirstMessage = bc.lastFirstMessage;
2221
1799
  lastGitBranch = bc.lastGitBranch;
2222
1800
  lastGitPrJson = bc.lastGitPrJson;
2223
- lastSessionName = bc.lastSessionName;
1801
+ inst.lastSessionName = bc.lastSessionName;
2224
1802
  lastGitWorktreeJson = bc.lastGitWorktreeJson;
2225
1803
  lastGitStatusJson = bc.lastGitStatusJson;
2226
1804
  lastCwdMissing = bc.lastCwdMissing;
2227
1805
  hasRegisteredOnce = bc.hasRegisteredOnce;
2228
1806
  }
1807
+ inst.applyBc = applyBc;
2229
1808
 
2230
1809
  // Local wrappers that sync bc around extracted module calls
2231
- function sendStateSync() { const bc = syncBc(); _sendStateSync(bc, getFlowsList); applyBc(bc); connection.noteRegistered(); }
2232
- function replaySessionEntries() { _replaySessionEntries(syncBc()); }
1810
+ function sendStateSync() { const bc = syncBc(); _sendStateSync(bc, getFlowsList); applyBc(bc); inst.connection.noteRegistered(); }
1811
+ function replaySessionEntries(opts?: { liveTailOpen?: boolean }) { _replaySessionEntries(syncBc(), opts); }
1812
+ inst.replaySessionEntries = replaySessionEntries;
2233
1813
  function sendModelUpdateIfChanged() { const bc = syncBc(); _sendModelUpdateIfChanged(bc); applyBc(bc); }
1814
+ inst.sendModelUpdateIfChanged = sendModelUpdateIfChanged;
2234
1815
  function sendSessionNameIfChanged() { const bc = syncBc(); _sendSessionNameIfChanged(bc); applyBc(bc); }
1816
+ inst.sendSessionNameIfChanged = sendSessionNameIfChanged;
2235
1817
 
2236
1818
  // ── add-auto-session-naming ──────────────────────────────────────────────
2237
1819
  // Stream through pi's OWN `ctx.modelRegistry`, not a bare-imported pi-ai
@@ -2247,7 +1829,7 @@ function initBridge(pi: ExtensionAPI) {
2247
1829
  // is captured lazily, so caching a miss would pin auto-naming off for the
2248
1830
  // whole session. See change: adopt-piai-factory-api-registry.
2249
1831
  async function loadStreamSimple(): Promise<StreamSimpleFn | undefined> {
2250
- const registry: any = cachedModelRegistry;
1832
+ const registry: any = inst.cachedModelRegistry;
2251
1833
  if (typeof registry?.streamSimple === "function") {
2252
1834
  return registry.streamSimple.bind(registry) as StreamSimpleFn;
2253
1835
  }
@@ -2264,40 +1846,41 @@ function initBridge(pi: ExtensionAPI) {
2264
1846
  // One namer per bridge (a bridge is a single pi session). Built lazily so it
2265
1847
  // captures the live `cachedCtx` / `cachedModelRegistry` at call time.
2266
1848
  function getAutoNamer(): AutoNamer {
2267
- if (autoNamer) return autoNamer;
2268
- autoNamer = createAutoNamer({
2269
- getAutoNameSessions: () => autoNameSessions,
1849
+ if (inst.autoNamer) return inst.autoNamer;
1850
+ inst.autoNamer = createAutoNamer({
1851
+ getAutoNameSessions: () => inst.autoNameSessions,
2270
1852
  resolveNamingModel,
2271
- getRegistry: () => cachedModelRegistry,
1853
+ getRegistry: () => inst.cachedModelRegistry,
2272
1854
  loadStreamSimple,
2273
- getTranscript: () => extractLatestTurnWindow(cachedCtx),
1855
+ getTranscript: () => extractLatestTurnWindow(inst.cachedCtx),
2274
1856
  applyName: (title: string) => {
2275
1857
  try { pi.setSessionName(title); } catch { /* ignore */ }
2276
- lastSessionName = title; // suppress the redundant plain name_update poll
2277
- connection.send({ type: "session_name_update", sessionId, name: title, nameSource: "auto" });
1858
+ inst.lastSessionName = title; // suppress the redundant plain name_update poll
1859
+ inst.connection.send({ type: "session_name_update", sessionId: inst.sessionId, name: title, nameSource: "auto" });
2278
1860
  },
2279
1861
  reportUserRename: (name: string) => {
2280
- connection.send({ type: "session_name_update", sessionId, name, nameSource: "user" });
1862
+ inst.connection.send({ type: "session_name_update", sessionId: inst.sessionId, name, nameSource: "user" });
2281
1863
  },
2282
1864
  emitError: (reason: string) => {
2283
- connection.send({ type: "auto_name_error", sessionId, reason });
1865
+ inst.connection.send({ type: "auto_name_error", sessionId: inst.sessionId, reason });
2284
1866
  },
2285
1867
  reportOutcome: ({ outcome, reason, modelRef }) => {
2286
- connection.send({
2287
- type: "auto_name_outcome", sessionId, outcome, reason, modelRef, at: Date.now(),
1868
+ inst.connection.send({
1869
+ type: "auto_name_outcome", sessionId: inst.sessionId, outcome, reason, modelRef, at: Date.now(),
2288
1870
  });
2289
1871
  },
2290
1872
  // Carried across reload AND persisted server-side into the session's
2291
1873
  // `.meta.json`, so "permanent" survives a process restart rather than
2292
1874
  // re-spending a full budget on every cold start (design D7).
2293
1875
  persistState: (state: PersistedNamerState) => {
2294
- namerState = state;
1876
+ inst.namerState = state;
2295
1877
  prev.namerState = state;
2296
- connection.send({ type: "auto_name_state", sessionId, state });
1878
+ inst.connection.send({ type: "auto_name_state", sessionId: inst.sessionId, state });
2297
1879
  },
2298
- }, namerState);
2299
- return autoNamer;
1880
+ }, inst.namerState);
1881
+ return inst.autoNamer;
2300
1882
  }
1883
+ inst.getAutoNamer = getAutoNamer;
2301
1884
 
2302
1885
  // Run one naming attempt after a terminal turn. Observing the current name
2303
1886
  // first catches a pre-existing / in-pi rename (external → permanent "user"
@@ -2312,594 +1895,23 @@ function initBridge(pi: ExtensionAPI) {
2312
1895
  // See change: fix-auto-naming-reasoning-model.
2313
1896
  function runAutoNameOnTurnEnd(): void {
2314
1897
  const namer = getAutoNamer();
2315
- if (autoNameSessions) namer.onObservedName(pi.getSessionName() ?? "");
1898
+ if (inst.autoNameSessions) namer.onObservedName(pi.getSessionName() ?? "");
2316
1899
  void namer.maybeName();
2317
1900
  }
1901
+ inst.runAutoNameOnTurnEnd = runAutoNameOnTurnEnd;
2318
1902
 
2319
1903
  function sendCwdMissingIfChanged(cwd: string) { const bc = syncBc(); _sendCwdMissingIfChanged(bc, cwd); applyBc(bc); }
1904
+ inst.sendCwdMissingIfChanged = sendCwdMissingIfChanged;
2320
1905
  function sendPiVersionIfChanged() { _sendPiVersionIfChanged(syncBc()); }
2321
-
2322
- // Forward all pi core events to the dashboard.
2323
- // Events with special enrichment logic:
2324
- const enrichedEventTypes = [
2325
- "agent_start",
2326
- "agent_end",
2327
- "agent_settled",
2328
- "turn_start",
2329
- "turn_end",
2330
- "message_start",
2331
- "message_update",
2332
- "message_end",
2333
- "tool_execution_start",
2334
- "tool_execution_update",
2335
- "tool_execution_end",
2336
- "session_compact",
2337
- "model_select",
2338
- "thinking_level_select",
2339
- ] as const;
2340
- // Pass-through events: forwarded as-is with no special handling.
2341
- // Unrecognized types render as expandable JSON cards in the dashboard.
2342
- const passThroughEventTypes = [
2343
- "tool_call",
2344
- "tool_result",
2345
- "user_bash",
2346
- "input",
2347
- "before_agent_start",
2348
- "resources_discover",
2349
- "session_before_switch",
2350
- "session_before_fork",
2351
- "session_before_compact",
2352
- "session_before_tree",
2353
- "session_tree",
2354
- // pi >= 0.84.3. Clears the server-side `compacting` latch on the failure
2355
- // path (see event-status-extraction.ts) — without it a failed or aborted
2356
- // compaction blocks every later reload of the session.
2357
- "session_compact_failed",
2358
- // pi >= 0.84.4. Brackets a BLOCKING `ctx.ui` prompt so the dashboard can
2359
- // tell "agent working" apart from "pi parked waiting on a user prompt".
2360
- // The 0.85.1 lockstep floor guarantees both events; the subscription is
2361
- // unconditional (no version gate, not merely inert below an old floor).
2362
- "ui_prompt_start",
2363
- "ui_prompt_end",
2364
- // pi >= 0.87. Fires before final settlement; no status effect (the agent
2365
- // may still continue). Forwarded without its `context` preview.
2366
- // See change: update-pi-core-1-0-adopt-apis (D5).
2367
- "agent_before_settle",
2368
- ] as const;
2369
- // Excluded from subscription (not forwarded):
2370
- // - `context`: carries full message arrays (very large)
2371
- // - `before_provider_request`: carries raw API payloads (very large)
2372
- // - `session_start`: dedicated handler → session_register protocol message
2373
- // - session change (new/fork/resume): handled inside session_start via event.reason
2374
- // - `session_shutdown`: dedicated handler → disconnect/cleanup
2375
- // - `cache_warming_decision`: dedicated observe-only handler → usage drain
2376
- // (`usage_recorded`), never `event_forward`. See change: count-non-message-usage.
2377
-
2378
- // Unified EventBus rename map for the emit intercept (flow + subagent events)
1906
+ inst.sendPiVersionIfChanged = sendPiVersionIfChanged;
1907
+ // Unified EventBus rename map (flow + subagent events): used by `sendEventForward` for the
1908
+ // channel→eventType rename and by `registerEventBusForwarding` for the per-channel subscription set.
2379
1909
  const EVENT_BUS_MAP: Record<string, string> = { ...FLOW_EVENT_MAP, ...SUBAGENT_EVENT_MAP };
2380
1910
 
2381
- for (const eventType of enrichedEventTypes) {
2382
- pi.on(eventType as any, safe(async (event: any, ctx: any) => {
2383
- // Bail out if a newer bridge instance has taken over
2384
- if (!isActive()) return;
2385
- // Always keep latest context for abort/shutdown
2386
- cachedCtx = ctx;
2387
- // Don't send events before session_start has established the correct session ID
2388
- if (!sessionReady) return;
2389
- // ── Flush choke point (D5) ──────────────────────────────────────────
2390
- // The invariant is "no non-`message_update` event may reach the wire while
2391
- // a text snapshot is parked". ONE statement here — before ANY branch, so
2392
- // it covers every early return below, including ones added later. Do not
2393
- // move it into a branch: a branch-scoped flush is exactly the bug this
2394
- // change exists to prevent.
2395
- // See change: coalesce-bridge-message-update-snapshots.
2396
- if (flushesParkedText(eventType)) coalescer.flush();
2397
- // Adaptive process-scan cadence hooks. See change: optimize-polling-hot-paths.
2398
- feedPollingEvent(eventType, event, polling);
2399
- // Track agent streaming state (survives reconnect/reload)
2400
- if (eventType === "agent_start") {
2401
- getBridgeState().isAgentStreaming = true;
2402
- // Abort latch (resumption hook): if a user abort is still latched when
2403
- // pi fires a fresh agent_start for the aborted turn (no intervening
2404
- // user prompt cleared it), abort again. See change:
2405
- // unify-error-retry-lifecycle.
2406
- if (abortLatch.shouldAbort(sessionId)) {
2407
- try { cachedCtx?.abort?.(); } catch { /* idempotent */ }
2408
- }
2409
- // Provider-retry synthesis: when this agent_start is the awaited retry
2410
- // attempt (a chain is armed), emit auto_retry_start so the surface
2411
- // flips waiting → in-flight. Deferred via setTimeout(0) so it lands on
2412
- // the wire AFTER this agent_start (the reducer defensively clears
2413
- // retryState on agent_start, so the synth must arrive next to re-set
2414
- // it). See change: retry-forever-with-stop-control (design D4).
2415
- const retryStart = retryTracker.observeAgentStart(sessionId);
2416
- if (retryStart) {
2417
- setTimeout(() => {
2418
- if (retryTracker.isRetrying(sessionId)) {
2419
- sendSyntheticRetryEvent(retryStart.eventType, retryStart.data);
2420
- }
2421
- }, 0);
2422
- }
2423
- }
2424
- if (eventType === "agent_settled") {
2425
- // Terminal settle (native pi, guaranteed at the 0.85.1 lockstep floor;
2426
- // fires once after the run loop). Clear streaming. This is the SOLE
2427
- // terminal signal for a retry chain: close it with auto_retry_end
2428
- // BEFORE forwarding the settle. The floor-pi synthesis path was
2429
- // retired with agent-settled.ts. See changes: adopt-pi-074-080-features
2430
- // (A.1), retry-forever-with-stop-control, update-pi-core-0-85-adopt-apis.
2431
- getBridgeState().isAgentStreaming = false;
2432
- abortLatch.clear(sessionId);
2433
- // Drain point. See change: count-non-message-usage.
2434
- drainUsage(ctx);
2435
- const retryEnd = retryTracker.observeAgentSettled(sessionId);
2436
- if (retryEnd) {
2437
- sendSyntheticRetryEvent(retryEnd.eventType, retryEnd.data);
2438
- }
2439
- }
2440
- if (eventType === "agent_end") {
2441
- getBridgeState().isAgentStreaming = false;
2442
- // Provider-retry synthesis: an error agent_end means an attempt just
2443
- // failed and (optimistically) another is coming — emit the WAITING
2444
- // signal (attempt + computed delay + nextAttemptAt) so the surface
2445
- // shows a live countdown during pi's sleep. The chain is NOT closed
2446
- // here; only agent_settled (above) terminates it. A non-error agent_end
2447
- // returns null. See change: retry-forever-with-stop-control (design D4).
2448
- const trackerSynth = retryTracker.observeAgentEnd(sessionId, event as any);
2449
- if (trackerSynth) {
2450
- sendSyntheticRetryEvent(trackerSynth.eventType, trackerSynth.data);
2451
- }
2452
- // Automatic session topic-naming: attempt on each terminal turn until
2453
- // the first success (or a permanent lockout). Non-blocking; all errors
2454
- // are handled inside the namer. See change: add-auto-session-naming.
2455
- runAutoNameOnTurnEnd();
2456
- // Bridge shadow follow-up queue: the per-entry drain matcher in
2457
- // the `message_start` handler removes each entry as pi delivers it
2458
- // (mirrors pi's internal `_processAgentEvent`). No bulk clear here
2459
- // — it would wipe entries the user adds DURING the drain window.
2460
- // See change: add-followup-edit-and-steer-cancel (per-entry-drain).
2461
-
2462
- // Bridge-owned follow-up drain: pop one entry from bridgeFollowUp
2463
- // and hand it to pi as a fresh turn (sendUserMessage no deliverAs).
2464
- // Scheduled via setTimeout (not queueMicrotask) so pi's
2465
- // finishRun() can flip isStreaming=false BEFORE we call back.
2466
- // The drain function itself polls ctx.isIdle() and retries up to
2467
- // ~2s if pi hasn't transitioned yet.
2468
- // See change: rework-mid-turn-prompt-queue (post-smoke fix #3).
2469
- setTimeout(() => drainFollowupQueue(0), 0);
2470
-
2471
- // Empty-actionable-turn guard: classify this turn's terminal shape.
2472
- // A thinking-only / empty `stop` (no visible text, no tool call, no
2473
- // error) would otherwise idle the session silently. Continue-or-
2474
- // surface instead. Normal / tool-call / truncated / error turns yield
2475
- // `none` and only reset the guard's per-session counter.
2476
- // See change: fix-gemini-subagent-silent-tool-schema-failure.
2477
- {
2478
- const agentMsgs = (event as any)?.messages;
2479
- const terminalMsg =
2480
- Array.isArray(agentMsgs) && agentMsgs.length > 0
2481
- ? (agentMsgs[agentMsgs.length - 1] as Record<string, unknown>)
2482
- : undefined;
2483
- if (terminalMsg?.role === "assistant") {
2484
- const actionability = classifyTurnActionability(terminalMsg as any);
2485
- const decision = emptyActionableGuard.observe(sessionId, actionability);
2486
- if (decision.action === "continue" && decision.nudge) {
2487
- // Only nudge when nothing else will already re-run the session
2488
- // (no user/system follow-up pending). A pending entry means the
2489
- // session is not idling, so the guard can safely no-op.
2490
- if (bridgeFollowUp.length === 0) {
2491
- enqueueSystemFollowup(decision.nudge);
2492
- }
2493
- } else if (decision.action === "surface") {
2494
- // Non-error status: the model returned only reasoning. Forward a
2495
- // structured, non-error notice so the server logs it to
2496
- // server.log and the dashboard card renders it (distinct from an
2497
- // error banner).
2498
- const model =
2499
- typeof terminalMsg.model === "string"
2500
- ? (terminalMsg.model as string)
2501
- : undefined;
2502
- const provider =
2503
- typeof terminalMsg.provider === "string"
2504
- ? (terminalMsg.provider as string)
2505
- : undefined;
2506
- connection.send({
2507
- type: "event_forward",
2508
- sessionId,
2509
- event: {
2510
- eventType: "empty_actionable_surface",
2511
- timestamp: Date.now(),
2512
- data: {
2513
- message: decision.reason ?? SURFACE_MESSAGE,
2514
- model: provider && model ? `${provider}/${model}` : model,
2515
- },
2516
- },
2517
- });
2518
- }
2519
- }
2520
- }
2521
-
2522
- }
2523
- // For model_select, enrich the event data with thinkingLevel
2524
- if (eventType === "model_select") {
2525
- const enriched = { ...event, thinkingLevel: (pi as any).getThinkingLevel?.() };
2526
- const msg = mapEventToProtocol(sessionId, enriched);
2527
- connection.send(msg);
2528
- // A TUI-initiated model change otherwise waits for the 30 s tick. The
2529
- // 50 ms deferral lets pi's ctx.model reflect the new model first (same
2530
- // as the dashboard-initiated setModel path). See change:
2531
- // optimize-polling-hot-paths (D8).
2532
- scheduleModelRecheckOnSelect(setRegisteredTimeout, sendModelUpdateIfChanged);
2533
- return;
2534
- }
2535
-
2536
- // Pi 0.71+ fires a dedicated thinking_level_select event when the
2537
- // thinking level changes alone (no model change). Push a model_update
2538
- // through the existing dedup gate so the dashboard reflects it
2539
- // immediately rather than waiting for the next model change.
2540
- // See change: adopt-pi-071-072-073-features.
2541
- if (eventType === "thinking_level_select") {
2542
- sendModelUpdateIfChanged();
2543
- return;
2544
- }
2545
-
2546
- // Graceful stop-after-turn: when latched, shut the session down cleanly
2547
- // at this turn boundary. Fall back to abort if shutdown is unavailable.
2548
- // Clear the flag BEFORE calling shutdown so a double-fired turn_end
2549
- // can't re-trigger. See change: adopt-pi-071-072-073-features.
2550
- if (eventType === "turn_end" && getBridgeState().shouldStopAfterTurn) {
2551
- getBridgeState().shouldStopAfterTurn = false;
2552
- try {
2553
- if (typeof (ctx as any)?.shutdown === "function") (ctx as any).shutdown();
2554
- else (ctx as any)?.abort?.();
2555
- } catch (err) {
2556
- console.error("[dashboard] stop-after-turn shutdown failed:", err);
2557
- }
2558
- }
2559
-
2560
- // For turn_end, enrich with contextUsage (pi-only API) so server can extract stats
2561
- if (eventType === "turn_end") {
2562
- const contextUsage = ctx.getContextUsage?.();
2563
- if (contextUsage) {
2564
- const enriched = { ...event, contextUsage };
2565
- const msg = mapEventToProtocol(sessionId, enriched);
2566
- connection.send(msg);
2567
- return;
2568
- }
2569
- }
2570
-
2571
- // For message_start: stamp a nonce on the event so the client reducer
2572
- // can correlate a later entry_persisted back-fill with this bubble.
2573
- // We do NOT attach entryId here — the message has no id yet on pi
2574
- // 0.69+ (persistence is deferred to message_end). See change:
2575
- // fix-per-message-fork.
2576
- //
2577
- // USER message_start sends are deferred via setTimeout(0) so they
2578
- // land on the wire AFTER any pending message_end deferrals (which
2579
- // also use setTimeout(0) — timer FIFO preserves order). Without this,
2580
- // a follow-up user message_start emitted synchronously by pi during
2581
- // an agent_end drain would arrive BEFORE the preceding assistant
2582
- // message_end, and the client reducer would append the user bubble
2583
- // above the assistant's final response. ASSISTANT message_start stays
2584
- // sync because message_update events fire sync and the reducer's
2585
- // streamingTextFlushed reset depends on message_start being processed
2586
- // first. See change: add-followup-edit-and-steer-cancel (chat-order).
2587
- if (eventType === "message_start") {
2588
- // Barrier, at ENTRY: bump the generation and open the identity BEFORE
2589
- // the `role === "custom"` early return below, so a custom message still
2590
- // closes out the previous identity's slot.
2591
- // See change: coalesce-bridge-message-update-snapshots (D4).
2592
- assistantMessageGen += 1;
2593
- coalescer.messageStart(
2594
- assistantMessageGen,
2595
- messageKeyOf(assistantMessageGen, (event as any).message),
2596
- (event as any).message,
2597
- );
2598
- // Custom messages are forwarded by wrapCustomPersistenceForCtx (pi's
2599
- // idle-path sendMessage emits message_start/end internally only, and
2600
- // the agent-loop path would double-forward here). See change:
2601
- // render-inline-reasoning-and-custom-entries (D2).
2602
- if ((event as any).message?.role === "custom") return;
2603
- // pi >= 0.86.0 makes the system prompt/tool loadout transcript-backed:
2604
- // `agent-loop.js` emits the first request's `role:"system"` message with
2605
- // every prompt `section` and the full `toolsAdded` declaration list as a
2606
- // `message_start`/`message_end` pair (~150 KB per message, so both
2607
- // events cost ~2x that per session). The client has no `role:"system"`
2608
- // arm, so forwarding it is pure wire cost with no render. Return AFTER
2609
- // the barrier above (same placement as `custom`) so the barrier's
2610
- // contract — every `message_start` opens an identity — is unchanged.
2611
- // No version gate: pi < 0.86 never emits the role, so this is inert
2612
- // there. See change: filter-system-role-message-forwarding (D2).
2613
- if ((event as any).message?.role === "system") return;
2614
- wrapAppendMessageForCtx(ctx);
2615
- // Lazy retry (review round 1): if session_start ran before the
2616
- // sessionManager exposed its persistence methods, the wrapper would
2617
- // never engage. Idempotent per-sm — re-invoking here repairs that.
2618
- wrapCustomPersistenceForCtx(ctx);
2619
- const messageRef = (event as any).message;
2620
- if (messageRef && typeof messageRef === "object") {
2621
- const nonce = nextNonce();
2622
- pendingNonces.set(messageRef as object, nonce);
2623
- const enriched = { ...event, nonce };
2624
- const msg = mapEventToProtocol(sessionId, enriched);
2625
- const role = (messageRef as any).role;
2626
- // Abort latch (resumption + clear hooks). A USER message_start is a
2627
- // deliberate new turn — clear the latch so it is never aborted. An
2628
- // ASSISTANT message_start while the latch is set is the aborted
2629
- // turn resuming a retry (no intervening user prompt) — abort again.
2630
- // See change: unify-error-retry-lifecycle.
2631
- if (role === "user") {
2632
- abortLatch.clear(sessionId);
2633
- retryTracker.noteExplicitRun(sessionId);
2634
- // A deliberate new user turn resets the empty-actionable guard's
2635
- // consecutive-continuation counter, so a stale count from a prior
2636
- // (possibly aborted) empty-actionable chain never shortens the next
2637
- // unrelated prompt's retry budget.
2638
- // See change: fix-gemini-subagent-silent-tool-schema-failure.
2639
- emptyActionableGuard.reset(sessionId);
2640
- } else if (abortLatch.shouldAbort(sessionId)) {
2641
- try { cachedCtx?.abort?.(); } catch { /* idempotent */ }
2642
- }
2643
- // NOTE: retry synthesis moved off `message_start`. pi ends a full
2644
- // agent turn per attempt, so the retry lifecycle is now driven by
2645
- // agent_start (in-flight) / agent_end (waiting) / agent_settled
2646
- // (terminal). See change: retry-forever-with-stop-control.
2647
- if (role === "user") {
2648
- // Per-entry shadow-queue drain matcher: mirror pi's internal
2649
- // logic (`_processAgentEvent` in pi-coding-agent
2650
- // agent-session.js). When pi delivers a queued user message,
2651
- // find its text in `bridgeSteering` first then `bridgeFollowUp`,
2652
- // remove the first occurrence, and emit a fresh `queue_update`.
2653
- //
2654
- // POST-rework-mid-turn-prompt-queue: the steer side is
2655
- // unchanged — pi still owns steering. The follow-up side is
2656
- // now reduced in scope: dashboard-buffered follow-ups never
2657
- // reach pi via {deliverAs:"followUp"} (the drain loop ships
2658
- // them as no-deliverAs fresh-turn sends, popped from the
2659
- // buffer BEFORE the pi call). So this matcher will splice
2660
- // bridgeFollowUp ONLY for:
2661
- // (a) TUI-queued follow-ups draining through pi's natural
2662
- // queue (text not in bridgeFollowUp → indexOf=-1 → no-op)
2663
- // (b) Any future code path that calls
2664
- // pi.sendUserMessage(_, {deliverAs:"followUp"}) directly
2665
- // (none exist in this codebase post-rework).
2666
- // The follow-up matcher is therefore defense-in-depth; cost is
2667
- // one indexOf per user message_start.
2668
- //
2669
- // See change: rework-mid-turn-prompt-queue (design.md D9, R7).
2670
- const text = extractUserMessageText(messageRef);
2671
- if (text) {
2672
- const sIdx = bridgeSteering.indexOf(text);
2673
- if (sIdx !== -1) {
2674
- bridgeSteering.splice(sIdx, 1);
2675
- emitQueueUpdate();
2676
- } else {
2677
- const fIdx = bridgeFollowUp.indexOfText(text);
2678
- if (fIdx !== -1) {
2679
- bridgeFollowUp.removeAt(fIdx);
2680
- emitQueueUpdate();
2681
- }
2682
- }
2683
- }
2684
- setTimeout(() => {
2685
- if (!isActive() || !sessionReady) return;
2686
- connection.send(msg);
2687
- }, 0);
2688
- } else {
2689
- connection.send(msg);
2690
- }
2691
- return;
2692
- }
2693
- }
2694
-
2695
- // For message_end: defer the SEND via setTimeout(0). Pi 0.69+ runs
2696
- // sessionManager.appendMessage AFTER the awaited extension dispatcher
2697
- // returns, so a queueMicrotask deferral is no longer enough. By the
2698
- // time the macrotask fires, appendMessage has run, pi has mutated
2699
- // event.message.id in place, and the wrapped appendMessage above has
2700
- // populated idByMessage. We also stamp a nonce so a downstream
2701
- // entry_persisted can correlate (covers user message_end where the
2702
- // earlier message_start nonce is what the reducer is waiting on).
2703
- // See change: fix-per-message-fork.
2704
- if (eventType === "message_end") {
2705
- // Barrier, at ENTRY and BEFORE the deferred send is scheduled below: the
2706
- // entry flush has already put the final snapshot on the wire, so closing
2707
- // here means any update arriving during the macrotask gap is dropped by
2708
- // the closed slot instead of landing after the `message_end`.
2709
- // See change: coalesce-bridge-message-update-snapshots (D4/D5).
2710
- // The generation this message was OPENED under, not the counter's
2711
- // current value: a message_end for a message whose start we saw must
2712
- // close ITS identity, never a newer one. Falls back to the current
2713
- // counter for a message this instance never saw open (reload mid-turn).
2714
- const endMessage = (event as any).message;
2715
- const endGen = coalescer.generationOf(endMessage, assistantMessageGen);
2716
- coalescer.messageEnd(endGen, messageKeyOf(endGen, endMessage));
2717
- // Custom messages are forwarded by wrapCustomPersistenceForCtx — see
2718
- // the message_start guard above. See change:
2719
- // render-inline-reasoning-and-custom-entries (D2).
2720
- if ((event as any).message?.role === "custom") return;
2721
- // Same pi >= 0.86.0 system-role drop as the `message_start` arm above,
2722
- // after the same barrier. See change:
2723
- // filter-system-role-message-forwarding (D2).
2724
- if ((event as any).message?.role === "system") return;
2725
- wrapAppendMessageForCtx(ctx);
2726
- const messageRef = (event as any).message;
2727
- const nonce = messageRef && typeof messageRef === "object"
2728
- ? (pendingNonces.get(messageRef as object) ?? nextNonce())
2729
- : nextNonce();
2730
- if (messageRef && typeof messageRef === "object" && !pendingNonces.has(messageRef as object)) {
2731
- pendingNonces.set(messageRef as object, nonce);
2732
- }
2733
- // Apply markdown image inliner to assistant content. Mutates
2734
- // event.message.content in place AND ships any new asset_register
2735
- // messages immediately so they precede the deferred message_end
2736
- // send below. See change: chat-markdown-local-images-and-math.
2737
- maybeInlineAssistantImages(event);
2738
- // Run the retry-tracker SYNCHRONOUSLY here, BEFORE the handler
2739
- // returns, so any synthesized retry event lands on the wire BEFORE
2740
- // the next `agent_end` (which pi fires synchronously back-to-back,
2741
- // see pi-coding-agent agent-session.js:298–331). The message_end
2742
- // body itself stays deferred for the entryId workaround
2743
- // (`fix-per-message-fork`); that does not affect retry-state ordering
2744
- // since the reducer's message_end arm does not touch
2745
- // retryState/lastError.
2746
- //
2747
- // Observe-based: an error message_end records a pending failure and
2748
- // emits NOTHING (the retry is confirmed only when pi starts a fresh
2749
- // assistant message_start). A non-error message_end that closes an
2750
- // in-flight chain emits auto_retry_end{success:true}. Billing/quota
2751
- // failures flow through this same path — pi treats them as terminal,
2752
- // so they settle via agent_end with no special-casing.
2753
- // See change: simplify-error-retry-single-card.
2754
- const synthetic = retryTracker.observeMessageEnd(sessionId, messageRef as any);
2755
- if (synthetic) {
2756
- sendSyntheticRetryEvent(synthetic.eventType, synthetic.data);
2757
- }
2758
- setTimeout(() => {
2759
- if (!isActive() || !sessionReady) return;
2760
- const entryId =
2761
- (messageRef && typeof messageRef === "object" && typeof messageRef.id === "string" ? messageRef.id : undefined)
2762
- ?? (messageRef ? idByMessage.get(messageRef as object) : undefined)
2763
- ?? ctx.sessionManager?.getLeafId?.();
2764
- const enriched = { ...event, entryId, nonce };
2765
- const protoMsg = mapEventToProtocol(sessionId, enriched);
2766
- connection.send(protoMsg);
2767
- }, 0);
2768
- return;
2769
- }
2770
-
2771
- // Text snapshots are COALESCED (D1–D3): one wire write per fixed window
2772
- // instead of one per source token. `offer` owns the family split and the
2773
- // closed-identity drop rule; the markdown-image inliner now runs inside the
2774
- // coalescer's send callback (once per flushed window, still ahead of the
2775
- // snapshot that references its assets). This branch returns, so the shared
2776
- // tail below never sees a `message_update`.
2777
- // See change: coalesce-bridge-message-update-snapshots (D6).
2778
- if (eventType === "message_update") {
2779
- // Resolve the message's OWN generation, so a late update for an already
2780
- // closed message still keys to that closed identity and is dropped —
2781
- // keying it under the counter's current value would fail open.
2782
- const updateMessage = (event as any)?.message;
2783
- coalescer.offer(event, coalescer.generationOf(updateMessage, assistantMessageGen));
2784
- return;
2785
- }
2786
-
2787
- // Inline path-referenced image tool results (e.g. browser `screenshot`)
2788
- // as type:"image" content blocks at capture time. Gated to the artifact-
2789
- // root allowlist (default agent-browser screenshot dir +
2790
- // AGENT_BROWSER_SCREENSHOT_DIR) so arbitrary tool-echoed paths are not
2791
- // read/disclosed. Over-cap / out-of-root / missing / non-image paths are
2792
- // left as text and fall back to the artifact route.
2793
- // See change: inline-agent-screenshot-artifacts.
2794
- if (eventType === "tool_execution_end") {
2795
- try {
2796
- const artifactRoots = resolveArtifactRoots({
2797
- homedir: os.homedir(),
2798
- env: process.env,
2799
- realpathSync: fs.realpathSync,
2800
- });
2801
- const inlined = inlineToolResultImages((event as any).result, {
2802
- readFile: inlinerReadFile,
2803
- isAllowedPath: (p) => isUnderArtifactRoot(p, artifactRoots, fs.realpathSync),
2804
- });
2805
- // Apply when a new image was inlined OR when the inliner rewrote the
2806
- // result (e.g. stripped a redundant path whose image the result
2807
- // already carried natively). The inliner returns the SAME reference
2808
- // when nothing changed, so an identity diff is a safe change signal.
2809
- if (inlined.result !== (event as any).result) {
2810
- (event as any).result = inlined.result;
2811
- }
2812
- } catch (err) {
2813
- console.error("[dashboard] tool-result image inline failed:", err);
2814
- }
2815
- // Forward the tool result's structured `details` to the client. pi's
2816
- // live tool_execution_end extension event exposes the full ToolResult
2817
- // ({ content, details }) on `event.result`, but only `result` is
2818
- // otherwise surfaced — the reducer reads a top-level `data.details`
2819
- // (the same field the replay path synthesizes from the persisted
2820
- // entry). Lift `result.details` to the event so renderers (e.g. the
2821
- // flow_agents list card) get a non-truncated structured payload LIVE,
2822
- // not only after a replay/refresh. No-op when result carries no
2823
- // details or already has a top-level details.
2824
- // See change: flow-agents-readable-list.
2825
- try {
2826
- const r = (event as any).result;
2827
- if (
2828
- !(event as any).details &&
2829
- r && typeof r === "object" && !Array.isArray(r) &&
2830
- (r as any).details && typeof (r as any).details === "object"
2831
- ) {
2832
- (event as any).details = (r as any).details;
2833
- }
2834
- } catch { /* non-fatal */ }
2835
- }
2836
-
2837
- // The `tool_execution_update` carrier is structurally disjoint from the
2838
- // EventBus path (pi core event → `pi.on()` → `connection.send`), but one
2839
- // `snapshotDetails()` object feeds both — so stripping one carrier only
2840
- // is a half-fix. `tool_execution_end` is terminal and stays fat.
2841
- // See change: reduce-subagent-details-payload (D2, task 3.8).
2842
- //
2843
- // `session_compact` is forwarded WITHOUT its `compactionEntry`. pi >= 0.86
2844
- // fills that entry's `systemMessage` with the same prompt-sections +
2845
- // tool-declaration checkpoint the system-role arms above drop, and carries
2846
- // the compaction `summary` beside it. No dashboard consumer reads either:
2847
- // the client renders the divider from the event's presence and the badge
2848
- // from `reason`/`willRetry`/`estimatedPostCompactionTokens`; the server
2849
- // uses the event only to clear the `compacting` latch. Redact on a COPY —
2850
- // pi hands the SAME event object to every subscribed extension, so a
2851
- // `delete event.compactionEntry` would strip the field from unrelated
2852
- // extensions too. The redaction stays OUT of `mapEventToProtocol` (which
2853
- // is generic over every forwarded type). No version gate: the field is
2854
- // simply omitted wherever it is absent.
2855
- // See change: filter-system-role-message-forwarding (D6/D7).
2856
- const forwardEvent =
2857
- eventType === "session_compact"
2858
- ? redactCompactionEntry(event as Record<string, unknown>)
2859
- : event;
2860
- const msg = mapEventToProtocol(sessionId, forwardEvent);
2861
- let heldByThrottle = false;
2862
- if (eventType === "tool_execution_update") {
2863
- msg.event.data = stripForForward(msg.event.data as Record<string, unknown>);
2864
- // Agent ticks only (allowlist predicate) — every other tool's update
2865
- // stream forwards 1:1. `offer` returns false when it has taken
2866
- // ownership of the frame and will send (or discard) it later.
2867
- // See change: reduce-bridge-tick-bandwidth (D2).
2868
- if (isSubagentTick(event) && typeof event.toolCallId === "string") {
2869
- heldByThrottle = !subagentTickThrottle.offer(event.toolCallId, msg, sessionId);
2870
- }
2871
- }
2872
- if (eventType === "tool_execution_end" && typeof event.toolCallId === "string") {
2873
- // Terminal: DISCARD any held tick rather than flushing it. This carrier
2874
- // never carries terminal state, so a held frame is a strictly stale
2875
- // intermediate snapshot; flushing it would race the overwrite that
2876
- // visibly re-opens a finished tool row. Runs before the send so no held
2877
- // frame can interleave after the end event.
2878
- subagentTickThrottle.onTerminal(event.toolCallId);
2879
- }
2880
- if (!heldByThrottle) connection.send(msg);
2881
-
2882
- // Native `agent_settled` (pi ≥ 0.80.4, guaranteed at the 0.85.1 floor) is
2883
- // the single terminal signal; the bridge forwards it above and the
2884
- // `agent_settled` handler closes the retry chain. The floor-pi synthesis
2885
- // path was retired once `piCompatibility.minimum` reached a version that
2886
- // emits natively. See change: update-pi-core-0-85-adopt-apis.
2887
- }));
2888
- }
1911
+ registerEnrichedForwarders(inst);
2889
1912
 
2890
1913
  // Pass-through events: forward with no enrichment
2891
- for (const eventType of passThroughEventTypes) {
2892
- pi.on(eventType as any, safe(async (event: any, ctx: any) => {
2893
- if (!isActive()) return;
2894
- cachedCtx = ctx;
2895
- if (!sessionReady) return;
2896
- // Same choke point as the enriched loop (D5).
2897
- coalescer.flush();
2898
- const forwarded = event?.type === "agent_before_settle" ? redactBeforeSettleContext(event) : event;
2899
- const msg = mapEventToProtocol(sessionId, forwarded);
2900
- connection.send(msg);
2901
- }));
2902
- }
1914
+ registerPassThroughForwarders(inst);
2903
1915
 
2904
1916
  // ── Subagent fan-out admission ────────────────────────────────────────────
2905
1917
  // Bounds concurrently in-flight `Agent` children so a wide fan-out on a loaded
@@ -2930,6 +1942,7 @@ function initBridge(pi: ExtensionAPI) {
2930
1942
  }
2931
1943
  },
2932
1944
  });
1945
+ inst.fanoutAdmission = fanoutAdmission;
2933
1946
  pi.on("tool_call", safe((event: any) => {
2934
1947
  if (!isActive()) return;
2935
1948
  return fanoutAdmission.onToolCall(event);
@@ -2971,15 +1984,7 @@ function initBridge(pi: ExtensionAPI) {
2971
1984
  // permanent lockout. The turn-end poll (runAutoNameOnTurnEnd) stays as a
2972
1985
  // fallback for pi builds that do not emit this event. See change:
2973
1986
  // adopt-pi-074-080-features (A.2).
2974
- try {
2975
- pi.on("session_info_changed" as any, safe(async (event: any) => {
2976
- if (!isActive() || !sessionReady) return;
2977
- const name = typeof event?.name === "string" ? event.name : pi.getSessionName();
2978
- if (typeof name === "string" && name.length > 0) {
2979
- getAutoNamer().onObservedName(name);
2980
- }
2981
- }));
2982
- } catch { /* older pi: no session_info_changed — poll fallback covers it */ }
1987
+ registerSessionInfoChanged(inst);
2983
1988
 
2984
1989
  // Auto-decide project_trust for dashboard-spawned headless sessions (pi
2985
1990
  // 0.79.0+). The event fires during resource-loader reload, BEFORE
@@ -2988,22 +1993,7 @@ function initBridge(pi: ExtensionAPI) {
2988
1993
  // per-event ctx inside try/catch (ctx.cwd throws after session replacement).
2989
1994
  // Any non-match — or a throw — defers to pi's default. See change:
2990
1995
  // adopt-pi-074-080-features (A.3).
2991
- try {
2992
- pi.on("project_trust" as any, safe((event: any, ctx: any) => {
2993
- // Return the pi trust decision. A newer bridge taking over, or any
2994
- // non-match, defers. `remember:false` = trust for THIS run only.
2995
- if (!isActive()) return { trusted: "undecided" };
2996
- const decision = decideProjectTrust({
2997
- dashboardSpawned,
2998
- isHeadless: isHeadlessRpcSession(),
2999
- eventCwd: readEventCwd(event, ctx),
3000
- activationCwd,
3001
- });
3002
- return decision === "trust"
3003
- ? { trusted: "yes", remember: false }
3004
- : { trusted: "undecided" };
3005
- }));
3006
- } catch { /* older pi: no project_trust event — no-op */ }
1996
+ registerProjectTrust(inst);
3007
1997
 
3008
1998
  // Per-turn system-prompt injector: splice dashboard session context
3009
1999
  // (sessionId, cwd, attached OpenSpec change) into the system prompt. Reads
@@ -3012,7 +2002,7 @@ function initBridge(pi: ExtensionAPI) {
3012
2002
  // chains { systemPrompt } results). See change: inject-session-context-into-agent.
3013
2003
  registerDashboardContextInjector(
3014
2004
  pi,
3015
- () => ({ sessionId, attachedChange }),
2005
+ () => ({ sessionId: inst.sessionId, attachedChange: inst.attachedChange }),
3016
2006
  isActive,
3017
2007
  );
3018
2008
 
@@ -3020,7 +2010,7 @@ function initBridge(pi: ExtensionAPI) {
3020
2010
  // pi-coding-agent 0.71+ — see _emitExtensionEvent allowlist). Bridge
3021
2011
  // tracks the shadow queues itself; drain happens on observed boundaries:
3022
2012
  // turn_end drains steering (pi's mode:"all" delivers all queued steers),
3023
- // agent_end drains follow-up (pi has no more tool calls).
2013
+ // agent_settled drains follow-up (pi is idle, no more tool calls).
3024
2014
  // See change: add-followup-edit-and-steer-cancel.
3025
2015
  // Bridge shadow steering queue: per-entry drain matcher in the
3026
2016
  // `message_start` handler removes each entry as pi delivers it. No bulk
@@ -3031,12 +2021,13 @@ function initBridge(pi: ExtensionAPI) {
3031
2021
  // get renamed via EVENT_BUS_MAP; unknown channels use the channel name.
3032
2022
  function sendEventForward(channel: string, data: Record<string, unknown>): void {
3033
2023
  const eventType = EVENT_BUS_MAP[channel] ?? channel;
3034
- connection.send({
2024
+ inst.connection.send({
3035
2025
  type: "event_forward",
3036
- sessionId,
2026
+ sessionId: inst.sessionId,
3037
2027
  event: { eventType, timestamp: Date.now(), data },
3038
2028
  });
3039
2029
  }
2030
+ inst.sendEventForward = sendEventForward;
3040
2031
 
3041
2032
  // Flush subagent frames buffered while the bridge was not ready (D1). Called
3042
2033
  // right after `sessionReady` flips true on (re-)register, in emission order.
@@ -3046,6 +2037,9 @@ function initBridge(pi: ExtensionAPI) {
3046
2037
  // `sendEventForward` directly, so a bus-path-only strip would leak every
3047
2038
  // buffered frame fat. See change: reduce-subagent-details-payload (X5).
3048
2039
  const flushed = flushBufferedSubagentFrames(subagentFrameBuffer, sendEventForward);
2040
+ // Plugin-declared latest/stream channels retained over the same gap flush
2041
+ // here too, in emission order. See change: add-plugin-bridge-contributions.
2042
+ pluginForwardRegistry.flush();
3049
2043
  if (flushed === 0) return;
3050
2044
  console.log(
3051
2045
  `[dashboard] flushed ${flushed} buffered subagent frame(s) on re-register` +
@@ -3053,6 +2047,7 @@ function initBridge(pi: ExtensionAPI) {
3053
2047
  ` flushed=${subagentFrameBuffer.stats.flushed})`,
3054
2048
  );
3055
2049
  }
2050
+ inst.flushPendingSubagentFrames = flushPendingSubagentFrames;
3056
2051
 
3057
2052
  // EventBus forwarding: ONE `pi.events.on` subscription per declared channel
3058
2053
  // (every key of EVENT_BUS_MAP). NOT an `emit` intercept — pi hands each
@@ -3065,9 +2060,9 @@ function initBridge(pi: ExtensionAPI) {
3065
2060
  pi.events,
3066
2061
  {
3067
2062
  sendEventForward,
3068
- isSessionReady: () => sessionReady,
2063
+ isSessionReady: () => inst.sessionReady,
3069
2064
  isActive,
3070
- isConnected: () => connection.isConnected,
2065
+ isConnected: () => inst.connection.isConnected,
3071
2066
  subagent: {
3072
2067
  isSubagentChannel: (channel) => SubagentFrameBuffer.isSubagentChannel(channel),
3073
2068
  markForwarded: (channel, data) => subagentFrameBuffer.markForwarded(channel, data),
@@ -3077,1012 +2072,32 @@ function initBridge(pi: ExtensionAPI) {
3077
2072
  },
3078
2073
  );
3079
2074
 
3080
- pi.on("session_start", safe(async (_event: any, ctx: any) => {
3081
-
3082
- // Bail out if a newer bridge instance has taken over
3083
- if (!isActive()) return;
3084
- const newSessionId = ctx.sessionManager.getSessionId();
3085
- pathGate.onSessionStart();
3086
- // Re-arm MCP registration for the (replacement) session; its mint below
3087
- // registers pi-dashboard again. See change: migrate-mcp-to-pi-builtin (D1).
3088
- mcpRegistrar.onSessionStart();
3089
-
3090
- // On session switch/fork (0.65.0+: event.reason replaces session_switch/session_fork events),
3091
- // unregister the old session before re-registering the new one.
3092
- const reason = _event?.reason;
3093
- // Synchronous compare-and-set BEFORE any await: this instance was loaded
3094
- // by a dashboard-requested reload → it owns the `/reload` `completed`,
3095
- // emitted after `replay_complete` below.
3096
- // See change: fix-terminal-session-dashboard-reload (D4).
3097
- const reloadDelivered = consumePendingReloadOnSessionStart(reason, newSessionId);
3098
- // Baseline + seed from ONE snapshot, before any register goes out: the
3099
- // drain forwards only entries appended after this point, and the register
3100
- // carries this snapshot's full totals. Undefined on a failed read.
3101
- // See change: count-non-message-usage.
3102
- let usageSeed: ReturnType<UsageDrain["baseline"]> | undefined;
3103
- try {
3104
- usageSeed = usageDrain.baseline(ctx.sessionManager);
3105
- } catch (err) {
3106
- console.error("[dashboard] usage baseline failed:", err);
3107
- }
3108
- const sessionChanged =
3109
- (reason === "new" || reason === "fork" || reason === "resume") && !!sessionId && sessionId !== newSessionId;
3110
- if (sessionChanged) {
3111
- // Clear any latched abort for the OUTGOING session id. Otherwise a
3112
- // latched old session that is resumed later would have its first
3113
- // legitimate turn aborted by the agent_start/message_start latch hooks.
3114
- // See change: unify-error-retry-lifecycle.
3115
- abortLatch.clear(sessionId);
3116
- handleSessionChange(ctx, usageSeed);
3117
- }
3118
-
3119
- cachedHasUI = ctx.hasUI;
3120
- cachedCtx = ctx;
3121
- sessionId = newSessionId;
3122
-
3123
- // Provision the openspec CLI: drop a shim on process.env.PATH so the
3124
- // generated openspec-* skills' bare `openspec` resolves in-session. Runs on
3125
- // init AND /reload (re-points the shim on extension upgrade); the PATH
3126
- // prepend is idempotent. Fail-soft: on hard failure, surface a
3127
- // dashboard-visible missing-tool signal. See change:
3128
- // provision-openspec-cli-in-sessions.
3129
- provisionOpenspecCli({
3130
- onMissingTool: (reason) => {
3131
- connection.send({
3132
- type: "event_forward",
3133
- sessionId,
3134
- event: {
3135
- eventType: "bash_output",
3136
- timestamp: Date.now(),
3137
- data: {
3138
- command: "openspec (session provisioning)",
3139
- output: reason,
3140
- exitCode: 127,
3141
- excludeFromContext: true,
3142
- missingTool: { kind: "missing-tool", toolName: "openspec" },
3143
- },
3144
- },
3145
- });
3146
- },
3147
- });
3148
-
3149
- // Wrap sessionManager.appendMessage so that future message_end events can
3150
- // recover the just-generated entry id, even when their setTimeout(0)
3151
- // fires before pi has finished mutating event.message in place. The
3152
- // helper is idempotent and re-wraps on session replacement.
3153
- // See change: fix-per-message-fork.
3154
- appendMessageWrapped = false;
3155
- lastWrappedSm = null;
3156
- wrapAppendMessageForCtx(ctx);
3157
- // Wrap the custom-persistence chokepoint BEFORE any events flow, so an
3158
- // extension appending at session_start is still forwarded. See change:
3159
- // render-inline-reasoning-and-custom-entries (D2).
3160
- customPersistenceWrapped = false;
3161
- customWrappedSm = null;
3162
- wrapCustomPersistenceForCtx(ctx);
3163
-
3164
- // Register ask_user at runtime (not at load time) to avoid static
3165
- // tool-name conflicts with other extensions like pi-flows.
3166
- registerAskUserTool(pi);
3167
-
3168
- // Register the canvas declare-tool (change: auto-canvas). Fire-and-forget
3169
- // UI intent; the server observes the forwarded tool call and drives the
3170
- // canvas. Runtime registration for the same conflict-avoidance reason.
3171
- registerCanvasTool(pi);
3172
-
3173
- // Register the agent-facing role/model tools (list_models, list_roles,
3174
- // update_roles). list_models reads the in-process session registry via a
3175
- // live getter so its refs match the human Model Selector exactly.
3176
- // See change: add-agent-role-model-tools.
3177
- registerRoleModelTools(pi, {
3178
- getRegistry: () => cachedModelRegistry,
3179
- // Live scope read at call time from the latest captured ctx (dynamic via
3180
- // Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
3181
- // See change: update-pi-core-0-83-adopt-apis.
3182
- getScopedModels: () => (cachedCtx as any)?.scopedModels,
3183
- });
3184
-
3185
- // Extract session file/dir early — needed for source detection and UI proxy
3186
- const sessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
3187
- const sessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
3188
- lastSessionFile = sessionFile;
3189
- lastSessionDir = sessionDir;
3190
-
3191
- // ── PromptBus setup ──
3192
- // Create bus with dashboard connection wiring.
3193
- // Replaces the old ui-proxy race pattern.
3194
- // Convert seconds → milliseconds for PromptBus.
3195
- // Values <= 0 (e.g. -1) are passed through as-is to signal infinite wait.
3196
- const askUserTimeoutMs = config.askUserPromptTimeoutSeconds > 0
3197
- ? config.askUserPromptTimeoutSeconds * 1000
3198
- : -1;
3199
- promptBus = new PromptBus({
3200
- timeoutMs: askUserTimeoutMs,
3201
- onDashboardRequest: (prompt, component, placement) => {
3202
- connection.send({
3203
- type: "prompt_request" as any,
3204
- sessionId,
3205
- promptId: prompt.id,
3206
- prompt: {
3207
- question: prompt.question,
3208
- type: prompt.type,
3209
- options: prompt.options,
3210
- defaultValue: prompt.defaultValue,
3211
- pipeline: prompt.pipeline,
3212
- metadata: prompt.metadata,
3213
- },
3214
- component,
3215
- placement,
3216
- });
3217
- },
3218
- onDashboardDismiss: (id) => {
3219
- connection.send({ type: "prompt_dismiss" as any, sessionId, promptId: id });
3220
- },
3221
- onDashboardCancel: (id) => {
3222
- connection.send({ type: "prompt_cancel" as any, sessionId, promptId: id });
3223
- },
3224
- });
3225
-
3226
- // Register built-in default adapter (always present, works without pi-flows)
3227
- promptBus.registerAdapter(new DashboardDefaultAdapter());
3228
-
3229
- // Capture original ctx.ui method references BEFORE patching
3230
- const originalNotify = ctx.ui.notify?.bind(ctx.ui);
3231
- const originals = {
3232
- select: ctx.ui.select?.bind(ctx.ui) as ((q: string, opts: string[], extra?: any) => Promise<string | undefined>) | undefined,
3233
- input: ctx.ui.input?.bind(ctx.ui) as ((q: string, placeholder?: string, extra?: any) => Promise<string | undefined>) | undefined,
3234
- confirm: ctx.ui.confirm?.bind(ctx.ui) as ((q: string, msg: string, extra?: any) => Promise<boolean>) | undefined,
3235
- editor: ctx.ui.editor?.bind(ctx.ui) as ((q: string, prefill?: string, extra?: any) => Promise<string | undefined>) | undefined,
3236
- // NOTE: the `custom` field is intentionally NOT captured here. A
3237
- // previous change (fix-multiselect-auto-cancel-on-dashboard) added a
3238
- // TUI multiselect arm that awaited the original ctx.ui.custom binding,
3239
- // but pi 0.70's RPC mode defines that primitive as a no-op (returns
3240
- // undefined synchronously), causing the TUI adapter to auto-cancel the
3241
- // dashboard-rendered dialog within one event-loop tick. The arm has
3242
- // been removed; see change fix-multiselect-tui-arm-self-cancel for full
3243
- // rationale. A repo lint (no-tui-multiselect-arm-regression.test.ts)
3244
- // prevents reintroduction by banning the co-occurrence of two
3245
- // substrings (the captured original binding and the TUI arm match).
3246
- };
3247
-
3248
- // Register TUI adapter — presents prompts in the terminal using original
3249
- // (unpatched) ctx.ui methods. Must be registered BEFORE patching ctx.ui.
3250
- if (ctx.hasUI) {
3251
- promptBus.registerAdapter(createTuiPromptAdapter(originals, promptBus));
3252
- }
3253
-
3254
- // Replace ctx.ui dialog methods with PromptBus wrappers.
3255
- // All extension commands that call ctx.ui.select/input/confirm/editor
3256
- // now route through the bus, which distributes to all registered adapters.
3257
- {
3258
- const bus = promptBus;
3259
- // Build a `metadata` envelope for bus.request that includes both
3260
- // `message` (existing) and `toolCallId` (new — added by change
3261
- // `fix-interactive-ui-reorder` so the client reducer can pair the
3262
- // resulting interactiveUi row with its parent toolResult row).
3263
- // Free-floating callers (slash commands, architect prompts) omit
3264
- // `opts.toolCallId` and the metadata field stays undefined.
3265
- const buildMeta = (
3266
- opts: any,
3267
- explicitMessage?: string,
3268
- ): Record<string, unknown> | undefined => {
3269
- const message = explicitMessage ?? opts?.message;
3270
- const toolCallId = opts?.toolCallId;
3271
- if (!message && !toolCallId) return undefined;
3272
- const meta: Record<string, unknown> = {};
3273
- if (message) meta.message = message;
3274
- if (toolCallId) meta.toolCallId = toolCallId;
3275
- return meta;
3276
- };
3277
-
3278
- (ctx.ui as any).select = (title: string, options: string[], opts?: any) =>
3279
- bus.request({ pipeline: "command", type: "select", question: title, options, metadata: buildMeta(opts) })
3280
- .then(r => r.cancelled ? undefined : r.answer);
3281
-
3282
- (ctx.ui as any).input = (title: string, placeholder?: string, opts?: any) =>
3283
- bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: buildMeta(opts) })
3284
- .then(r => r.cancelled ? undefined : r.answer);
3285
-
3286
- // Persist pasted images for an ask_user input answer to disk + emit one
3287
- // asset_register per new hash (dashboard thumbnail). Returns absolute
3288
- // paths the LLM can Read. Drops over per-image / cumulative caps.
3289
- // Closes over sessionId, connection, getEmittedAssetHashes (all in
3290
- // scope here). See change: add-ask-user-input-multiline-paste.
3291
- const persistAnswerImages = (
3292
- images: ImageContent[],
3293
- ): Array<{ path: string; mimeType: string; bytes: number }> => {
3294
- const out: Array<{ path: string; mimeType: string; bytes: number }> = [];
3295
- const emitted = getEmittedAssetHashes(sessionId);
3296
- let cumulative = 0;
3297
- for (const image of images) {
3298
- const persisted = persistAttachment({ sessionId, image });
3299
- if (!persisted) continue;
3300
- if (cumulative + persisted.bytes > ATTACH_MAX_PER_MESSAGE_BYTES) {
3301
- console.warn(`[bridge] ask_user image over cumulative cap dropped (${persisted.hash})`);
3302
- continue;
3303
- }
3304
- cumulative += persisted.bytes;
3305
- if (!emitted.has(persisted.hash)) {
3306
- emitted.add(persisted.hash);
3307
- connection.send({
3308
- type: "asset_register",
3309
- sessionId,
3310
- hash: persisted.hash,
3311
- mimeType: persisted.mimeType,
3312
- data: image.data,
3313
- });
3314
- }
3315
- out.push({ path: persisted.path, mimeType: persisted.mimeType, bytes: persisted.bytes });
3316
- }
3317
- return out;
3318
- };
3319
-
3320
- // ctx.ui.inputWithImages is NOT a built-in pi method. The ask_user tool
3321
- // calls it for method:"input" so pasted images survive (ctx.ui.input
3322
- // decodes to a bare string, dropping PromptResponse.images). Resolves
3323
- // to: undefined (cancel) | string (no images) | {value, attachments}
3324
- // (images). See change: add-ask-user-input-multiline-paste, design.md
3325
- // Decision 1.
3326
- (ctx.ui as any).inputWithImages = (title: string, placeholder?: string, opts?: any) =>
3327
- bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: buildMeta(opts) })
3328
- .then(r => {
3329
- if (r.cancelled) return undefined;
3330
- const atts = r.images?.length ? persistAnswerImages(r.images) : [];
3331
- return atts.length ? { value: r.answer ?? "", attachments: atts } : (r.answer ?? "");
3332
- });
3333
-
3334
- (ctx.ui as any).confirm = (title: string, message?: string, opts?: any) =>
3335
- bus.request({ pipeline: "command", type: "confirm", question: title, metadata: buildMeta(opts, message) })
3336
- .then(r => !r.cancelled && r.answer === "true");
3337
-
3338
- (ctx.ui as any).editor = (title: string, prefill?: string, opts?: any) =>
3339
- bus.request({ pipeline: "command", type: "editor", question: title, defaultValue: prefill, metadata: buildMeta(opts) })
3340
- .then(r => r.cancelled ? undefined : r.answer);
3341
-
3342
- // ── Multiselect ──────────────────────────────────────────────
3343
- // ctx.ui.multiselect is NOT a built-in pi method — we attach it here
3344
- // so that polyfillMultiselect (and any other consumer) routes through
3345
- // PromptBus. The dashboard adapter renders a real browser dialog via
3346
- // MultiselectRenderer; there is intentionally no TUI adapter arm for
3347
- // multiselect (pi 0.70 RPC mode's ctx.ui.custom is a no-op, so any TUI
3348
- // arm would auto-cancel the dashboard render in <1s). See changes
3349
- // fix-multiselect-auto-cancel-on-dashboard (initial bus routing) and
3350
- // fix-multiselect-tui-arm-self-cancel (TUI arm removal).
3351
- if (typeof (ctx.ui as any).multiselect === "function") {
3352
- // Defensive: future upstream pi may add a built-in multiselect.
3353
- // Override is intentional — the bus-routed version is what
3354
- // participates in PromptBus first-response-wins semantics.
3355
- // eslint-disable-next-line no-console
3356
- console.warn("[bridge] ctx.ui.multiselect already exists — overriding for PromptBus routing");
3357
- }
3358
- (ctx.ui as any).multiselect = (title: string, options: string[], opts?: any) =>
3359
- bus.request({
3360
- pipeline: "command",
3361
- type: "multiselect",
3362
- question: title,
3363
- options,
3364
- metadata: opts?.message ? { message: opts.message } : undefined,
3365
- }).then(decodeMultiselectAnswer);
3366
-
3367
- // ── Batch ────────────────────────────────────────────────────
3368
- // ctx.ui.batch is NOT a built-in pi method. The ask_user tool calls it
3369
- // to dispatch a multi-question batch as ONE bus request carrying
3370
- // `questions[]` in metadata; the dashboard renders a BatchRenderer
3371
- // wizard and returns one `{answers}` response (JSON-encoded in the bus
3372
- // `answer` string). Resolves to BatchAnswer[] on submit, or undefined on
3373
- // cancel. See change: redesign-ask-user-question-cards.
3374
- (ctx.ui as any).batch = (title: string, questions: unknown[], opts?: any) =>
3375
- bus.request({
3376
- pipeline: "command",
3377
- type: "batch",
3378
- question: title,
3379
- metadata: { ...(buildMeta(opts) ?? {}), questions },
3380
- }).then((r) => {
3381
- if (r.cancelled || r.answer == null) return undefined;
3382
- try {
3383
- const parsed = JSON.parse(r.answer);
3384
- if (!Array.isArray(parsed)) return undefined;
3385
- // Persist any input-step images and rewrite that answer to
3386
- // {value, attachments}, dropping the raw base64 `images`.
3387
- // See change: add-ask-user-input-multiline-paste.
3388
- return parsed.map((a: any) => {
3389
- if (a && typeof a === "object" && Array.isArray(a.images) && a.images.length) {
3390
- const atts = persistAnswerImages(a.images);
3391
- const { images: _drop, ...rest } = a;
3392
- return atts.length ? { ...rest, attachments: atts } : rest;
3393
- }
3394
- return a;
3395
- });
3396
- } catch {
3397
- return undefined;
3398
- }
3399
- });
3400
-
3401
- // Notify is fire-and-forget: call original + forward to dashboard on the
3402
- // dedicated `notify` channel. See change: split-notify-from-prompt-request.
3403
- (ctx.ui as any).notify = createNotifyProxy({
3404
- sessionId,
3405
- send: (msg) => connection.send(msg),
3406
- originalNotify,
3407
- });
3408
- }
3409
-
3410
- // Flip ctx.hasUI=true now that ctx.ui.* has been patched to route
3411
- // through PromptBus → dashboard. `cachedHasUI` (captured earlier at
3412
- // line ~1287) retains the pi-supplied original value, so
3413
- // `detectSessionSource` continues to classify dashboard-spawned RPC
3414
- // vs tmux correctly. Extensions that branch on `ctx.hasUI`
3415
- // (context-mode `/ctx-stats` / `/ctx-doctor`, pi-agent-browser auto-install)
3416
- // now take their UI-present branch and render output via the proxied
3417
- // `ctx.ui.notify`. See change: fix-bridge-hasui-for-headless-rpc.
3418
- flipHasUI(ctx);
3419
-
3420
- // Listen for adapter registrations from other extensions (e.g. pi-flows)
3421
- if (pi.events) {
3422
- pi.events.on("prompt:register-adapter", (adapter: any) => {
3423
- if (promptBus && adapter && typeof adapter.name === "string") {
3424
- promptBus.registerAdapter(adapter);
3425
- // Inject respond/cancel functions so cross-package adapters can talk back
3426
- if (typeof adapter.setRespond === "function") {
3427
- adapter.setRespond((response: any) => promptBus!.respond(response));
3428
- }
3429
- if (typeof adapter.setCancel === "function") {
3430
- adapter.setCancel((id: string) => promptBus!.cancel(id));
3431
- }
3432
- }
3433
- });
3434
-
3435
- // Expose bus request function for pi-flows to use via emitPromptAndAwait
3436
- pi.events.emit("prompt:set-bus-request", {
3437
- request: (options: any) => promptBus!.request(options),
3438
- });
3439
-
3440
- // Generic system-follow-up channel: any plugin bridge entry can request
3441
- // a system-originated continuation through the single drain path by
3442
- // emitting `dashboard:enqueue-followup`. Inert when no plugin emits it.
3443
- // See change: add-goal-continuation-plugin (Decision 2).
3444
- pi.events.on("dashboard:enqueue-followup", (payload: any) => {
3445
- if (payload && typeof payload.text === "string") {
3446
- enqueueSystemFollowup(payload.text);
3447
- }
3448
- });
3449
-
3450
- // Generic plugin bridge→server channel: a plugin bridge entry emits
3451
- // `dashboard:plugin-message` and the main bridge wraps it in a
3452
- // `plugin_pi_message` envelope over the extension WS. The server
3453
- // dispatches to handlers registered via
3454
- // `ServerPluginContext.registerPiHandler(messageType, handler)`.
3455
- // See change: add-goal-continuation-plugin.
3456
- pi.events.on("dashboard:plugin-message", (payload: any) => {
3457
- if (
3458
- payload &&
3459
- typeof payload.pluginId === "string" &&
3460
- typeof payload.messageType === "string"
3461
- ) {
3462
- connection.send({
3463
- type: "plugin_pi_message",
3464
- sessionId,
3465
- pluginId: payload.pluginId,
3466
- messageType: payload.messageType,
3467
- payload: payload.payload ?? null,
3468
- });
3469
- }
3470
- });
3471
- }
3472
-
3473
- // Connect first, then auto-start if needed.
3474
- // session_register must be buffered before any event_forward messages.
3475
- //
3476
- // (tasks 7.2/7.3) A REMOTE endpoint is challenged BEFORE the connection
3477
- // opens: across a network an address proves nothing, so the pinned Ed25519
3478
- // identity is the only thing that answers "is this my dashboard?" (D8).
3479
- // Local endpoints are unaffected — the socket/loopback token already
3480
- // authorises them — so this adds no latency to the common path.
3481
- if (isRemoteEndpoint(dashboardUrl)) {
3482
- const pinsFile = serverPinsPath();
3483
- const connectIfIdentityVerifies = async () => {
3484
- const verdict = await gateRemoteRegistration({
3485
- endpoint: dashboardUrl,
3486
- store: loadServerPins(pinsFile),
3487
- });
3488
- // Task 10.3: the cause is distinguishable in the log, not folded into
3489
- // a generic connection failure.
3490
- const line = `[dashboard] remote identity ${verdict.cause}: ${verdict.reason}`;
3491
- if (!verdict.allow) {
3492
- console.error(`${line} — not registering`);
3493
- return;
3494
- }
3495
- console.log(line);
3496
- // Only a VERIFIED identity gets its address remembered.
3497
- if (verdict.fingerprint) notePinEndpoint(pinsFile, verdict.fingerprint, dashboardUrl);
3498
- connection.connect();
3499
- };
3500
- // Guarded discard: a failure here must be OBSERVED, never take the host
3501
- // pi agent down.
3502
- void connectIfIdentityVerifies().catch((err) => console.error("[dashboard]", err));
3503
- } else {
3504
- connection.connect();
3505
- }
3506
- // Drain the buffered transport diagnostics through the live connection
3507
- // (task 10.5). `send()` buffers while the socket is down, which is the
3508
- // right behaviour here: the detail is self-describing, so a late delivery
3509
- // is still a true one.
3510
- transportDiagnostics.attach({
3511
- send: (m) => connection.send(m),
3512
- getSessionId: () => sessionId,
3513
- });
3514
-
3515
- // (task 3.8) Verify the instance answering at the recorded endpoint really
3516
- // is the one the record named. The socket's mode and the local token are
3517
- // both per-HOME, so a same-HOME impostor passes them — only the published
3518
- // `instanceId` distinguishes instances. Refusal is loud and does NOT fall
3519
- // back to a discovered substitute: that substitution is the bug.
3520
- if (
3521
- endpointChoice.available &&
3522
- endpointChoice.source === "rendezvous-record" &&
3523
- rendezvous?.instanceId
3524
- ) {
3525
- const verifyRecordedInstance = async () => {
3526
- const verdict = await verifyInstanceIdentity({
3527
- healthUrl: healthUrlForInstance(rendezvous.httpPort),
3528
- expectedInstanceId: rendezvous.instanceId,
3529
- });
3530
- if (verdict.adopt) {
3531
- registeredInstanceId = rendezvous.instanceId;
3532
- return;
3533
- }
3534
- // Only a CONFLICT justifies tearing the connection down. `disconnect()`
3535
- // sets `intentionalClose`, so nothing rearms the backoff loop and the
3536
- // session is dead until pi itself restarts — right for an impostor,
3537
- // catastrophic for an outage. `/api/health` is unreachable for seconds
3538
- // on every `POST /api/restart` while the gateway socket stays healthy,
3539
- // so treating silence as refusal would kill every bridge on the host on
3540
- // every rebuild. Unverified means we simply do not claim an identity.
3541
- if (!verdict.conflict) {
3542
- console.error(
3543
- `[dashboard] instance verification ${verdict.reason} — keeping the connection, identity unclaimed`,
3544
- );
3545
- registeredInstanceId = undefined;
3546
- return;
3547
- }
3548
- console.error(`[dashboard] instance verification ${verdict.reason} — disconnecting`);
3549
- registeredInstanceId = undefined;
3550
- try {
3551
- connection.disconnect();
3552
- } catch {
3553
- /* already down */
3554
- }
3555
- };
3556
- // Guarded discard: the verification runs alongside the connection and
3557
- // must never take the host pi agent down, but its failure must still be
3558
- // OBSERVED rather than dropped on the floor.
3559
- void verifyRecordedInstance().catch((err) => console.error("[dashboard]", err));
3560
- }
3561
-
3562
- // Extract first message (sessionFile/sessionDir already extracted above)
3563
- const firstMessage = extractFirstMessage(ctx);
3564
- lastFirstMessage = firstMessage;
3565
-
3566
- // Register session with initial model/thinkingLevel
3567
- lastSessionName = pi.getSessionName() ?? "";
3568
- const initialModel = getCurrentModelString(syncBc());
3569
- const initialThinkingLevel = (pi as any).getThinkingLevel?.() ?? undefined;
3570
- lastModel = initialModel;
3571
- lastThinkingLevel = initialThinkingLevel;
3572
-
3573
- // Include eventCount so server can skip event wipe on reconnect
3574
- let eventCount: number | undefined;
3575
- try {
3576
- const entries = ctx.sessionManager?.getBranch?.();
3577
- if (entries) eventCount = entries.length;
3578
- } catch { /* ignore */ }
3579
-
3580
- // See change: fix-dashboard-source-mislabelling — sent on every
3581
- // register so server can re-stamp source after restart. Derived from the
3582
- // capture-once boolean (token may already be scrubbed). See change:
3583
- // fix-spawn-token-env-leak.
3584
- // ctx.cwd is the guarded getter that throws once the session is replaced.
3585
- // Read it once, defensively — a throw here would skip session_register +
3586
- // the heartbeat/git timers, leaving a resumed session dead in the UI.
3587
- // See change: fix-bridge-resume-disconnect.
3588
- const startCwd = safeCwd(ctx);
3589
- const spawnToken = consumeSpawnToken();
3590
- connection.send({
3591
- type: "session_register",
3592
- extensionIdentity: bridgeExtensionIdentity(),
3593
- sessionId,
3594
- cwd: startCwd,
3595
- name: lastSessionName || undefined,
3596
- source: detectSessionSource(cachedHasUI, sessionFile),
3597
- model: initialModel,
3598
- thinkingLevel: initialThinkingLevel,
3599
- sessionFile,
3600
- sessionDir,
3601
- firstMessage,
3602
- eventCount,
3603
- // The ONLY channel by which the server learns this session's process for a
3604
- // non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
3605
- // so without this the server's record has no `pid` and shutdown has
3606
- // nothing to escalate to — the session was unregistered while a ~127 MB
3607
- // pi kept running (#452). The two `session_register` sends in
3608
- // session-sync.ts already carry it; this one, the FIRST register of a
3609
- // fresh session, did not.
3610
- // See change: fix-tmux-session-shutdown-leak (D6).
3611
- pid: process.pid,
3612
- // The spawn correlation token, echoed back so the server can match THIS
3613
- // register to the spawn that produced it. This is a fresh session's FIRST
3614
- // register, and it omitted the token entirely: tier-1 correlation never
3615
- // fired for a dashboard spawn, so the spawn watchdog could only match by
3616
- // cwd and reported false register-timeouts for concurrent spawns into one
3617
- // directory. Single-use — `consumeSpawnToken` scrubs the env.
3618
- // See change: fix-tmux-session-shutdown-leak (D5).
3619
- ...(spawnToken ? { spawnToken } : {}),
3620
- ...(dashboardSpawned ? { dashboardSpawned: true } : {}),
3621
- // Tri-state git-repo signal, computed at register time (authority).
3622
- // See change: gate-session-worktree-button-on-git.
3623
- isGitRepo: detectIsGitRepo(startCwd),
3624
- // Fact-forwarding: server decides auto-hide. See change:
3625
- // auto-hide-headless-worker-sessions.
3626
- ...buildVisibilityRegisterFields(cachedHasUI, process.env),
3627
- // Applied server-side only for an id it has no record of.
3628
- // See change: count-non-message-usage.
3629
- ...(usageSeed ? { usageSeed } : {}),
3630
- });
3631
-
3632
- // The register above just went out (live socket, or buffered for the
3633
- // open — either way the manager learns its last-registered endpoint for
3634
- // the migration gate's reversal target).
3635
- // See change: fix-bridge-mdns-migration-hijack (task 2.1).
3636
- connection.noteRegistered();
3637
-
3638
- // Allow event forwarding now that session_register is buffered
3639
- sessionReady = true;
3640
-
3641
- // D3: mint-on-registration. Ask the mcp-server plugin for this session's
3642
- // /mcp credential now that the socket is (re)registered — the reply
3643
- // arrives on the session-private lane (mcp_token_minted) and registers
3644
- // pi-dashboard with pi's built-in MCP, and re-registers after every
3645
- // reconnect, which is what makes a dashboard restart self-heal. Ordered
3646
- // after session_register on the SAME socket, so the server's
3647
- // connection-key attribution is already established when it arrives.
3648
- // See change: wire-mcp-session-token (D3/D5).
3649
- connection.send({
3650
- type: "plugin_pi_message",
3651
- sessionId,
3652
- pluginId: "mcp-server",
3653
- messageType: "mcp/mint-token",
3654
- payload: {},
3655
- });
3656
-
3657
- // Flush any subagent frames buffered during the not-ready window (D1) so a
3658
- // reconnect/discovery/reload gap self-heals instead of leaving a running
3659
- // subagent's detail empty. See change: fix-subagent-live-detail-reliability.
3660
- flushPendingSubagentFrames();
3661
-
3662
- // Replay full session history so the dashboard has all messages
3663
- replaySessionEntries();
3664
- connection.send({ type: "replay_complete", sessionId });
3665
- // After replay_complete: inside the replay window the server may drop
3666
- // forwarded events without insert or broadcast (`skipReplayInsert`).
3667
- // See change: fix-terminal-session-dashboard-reload (D4).
3668
- if (reloadDelivered) connection.send(reloadCompletedFeedback(sessionId));
3669
- // If agent is mid-turn (e.g. reload during streaming), send synthetic agent_start
3670
- if (getBridgeState().isAgentStreaming) {
3671
- connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
3672
- }
3673
-
3674
- // Send initial commands list
3675
- const commands = filterHiddenCommands(pi.getCommands());
3676
- connection.send({
3677
- type: "commands_list",
3678
- sessionId,
3679
- commands,
3680
- });
3681
-
3682
- // Send initial flows list
3683
- sendFlowsList();
3684
-
3685
- // Send available models
3686
- cachedModelRegistry = (ctx as any).modelRegistry;
3687
- if (cachedModelRegistry) {
3688
- try {
3689
- const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
3690
- connection.send({ type: "models_list", sessionId, models });
3691
- // See change: replace-hardcoded-provider-lists.
3692
- connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
3693
- } catch { /* modelRegistry not available */ }
3694
- }
3695
-
3696
- // Apply default model only on brand-new sessions (no prior message history)
3697
- // that were NOT launched with an explicit --model flag. Resume (--session) and
3698
- // fork (--fork) both load parent messages, so messageCount > 0 and we keep their
3699
- // existing model. Mirrors pi's own !hasExistingSession gate (sdk.js:106 —
3700
- // `existingSession.messages.length > 0`). NOT the raw getEntries() count: pi's
3701
- // sdk.js auto-appends model_change + thinking_level_change setup entries to a
3702
- // brand-new session BEFORE emitting session_start, so getEntries() is ≥ 2 even
3703
- // for a session with no user history. Only message entries count.
3704
- // The bridge runs inside the pi process, so process.argv is pi's argv — an
3705
- // explicit --model there is the spawner's resolved choice and the default
3706
- // never overrides it. The deferred retry below needs no separate guard: when
3707
- // the gate is false this never sets pendingDefaultModel, so onProviderChanged
3708
- // has nothing to re-apply.
3709
- // See changes: fix-resume-keeps-session-model,
3710
- // fix-default-model-new-session-entry-count,
3711
- // fix-default-model-clobbers-explicit-model (issue #595).
3712
- const entryCount = ctx.sessionManager.buildSessionContext?.()?.messages?.length ?? 0;
3713
- const freshConfig = loadConfig();
3714
- if (shouldApplyDefaultModel({
3715
- reason: _event?.reason,
3716
- entryCount,
3717
- hasModelRegistry: Boolean(cachedModelRegistry),
3718
- hasDefaultModel: Boolean(freshConfig.defaultModel),
3719
- hasExplicitModel: hasExplicitModelArg(process.argv),
3720
- })) {
3721
- pendingDefaultModel = applyDefaultModel();
3722
- }
3723
-
3724
- // Send initial roles
3725
- if (pi.events) {
3726
- const rolesData: any = {};
3727
- pi.events.emit("roles:get-all", rolesData);
3728
- if (rolesData.roles) {
3729
- connection.send({
3730
- type: "roles_list",
3731
- sessionId,
3732
- roles: rolesData.roles ?? {},
3733
- presets: rolesData.presets ?? [],
3734
- activePreset: rolesData.activePreset ?? null,
3735
- builtinRoleNames: rolesData.builtinRoleNames ?? [],
3736
- });
3737
- }
3738
- }
3739
-
3740
- // Discover or auto-start server (non-blocking — connection will reconnect)
3741
- //
3742
- // When a real launchServer() is about to run (not on mDNS/health-check
3743
- // paths), mount an animated TUI widget above the editor using pi-tui's
3744
- // Loader (a real Component, self-animating at 80ms, like pi-flows'
3745
- // architect-widget). The previous implementation used
3746
- // ctx.ui.setStatus(...) which only writes a footer string and relies on
3747
- // the TUI render loop being ticked elsewhere — on the cold-start path
3748
- // nothing else requests renders, so the spinner never animated and often
3749
- // never appeared. setWidget(key, factory, {placement:"aboveEditor"}) gives
3750
- // us a managed component that owns its own render loop and is always
3751
- // visible while the launch is in flight.
3752
- let spinnerTimer: NodeJS.Timeout | null = null;
3753
- let spinnerStart = 0;
3754
- let activeLoader: Loader | null = null;
3755
- const stopSpinner = () => {
3756
- // Release the interval BEFORE the guarded ctx.ui call, so a stale ctx
3757
- // still stops the 1s label refresh instead of leaking it.
3758
- if (spinnerTimer) {
3759
- clearInterval(spinnerTimer);
3760
- spinnerTimer = null;
3761
- }
3762
- activeLoader = null;
3763
- // This runs from `onLaunchEnd` AND from the terminal .then()/.catch()
3764
- // below, either of which can land after a session replacement/reload has
3765
- // invalidated `ctx`. See ui-stale-guard.ts.
3766
- runUiSafely(() => ctx.ui.setWidget("pi-dashboard-launch", undefined));
3767
- };
3768
- // Resolve the ports the auto-start chain uses (health check + launch)
3769
- // with the shared env → config.json → default precedence, so a session
3770
- // whose environment names the dashboard's real ports attaches to (or
3771
- // launches on) THOSE ports instead of a stale config/default — this is
3772
- // the split-brain fix: without it, a harness/container session with
3773
- // DASHBOARD_PORT in its env health-checked 8000, found nothing, and
3774
- // launched a competing dashboard on 8000. `config` is not mutated;
3775
- // `loadConfig()` stays untouched (design D1/D2).
3776
- // See change: fix-bridge-autostart-port-resolution.
3777
- autoStartServer({ ...config, ...resolveDashboardPorts(process.env, config) }, {
3778
- discoverDashboard,
3779
- isDashboardRunning,
3780
- launchServer,
3781
- notify: (msg, level) => runUiSafely(() => ctx.ui.notify(msg, level)),
3782
- onLaunchStart: () => {
3783
- spinnerStart = Date.now();
3784
- const buildMessage = () => {
3785
- const elapsed = Math.floor((Date.now() - spinnerStart) / 1000);
3786
- return `starting dashboard server … (${elapsed}s)`;
3787
- };
3788
- runUiSafely(() =>
3789
- ctx.ui.setWidget(
3790
- "pi-dashboard-launch",
3791
- (tui: unknown, theme: { fg: (role: string, s: string) => string }) => {
3792
- const loader = new Loader(
3793
- tui as ConstructorParameters<typeof Loader>[0],
3794
- (s: string) => theme.fg("accent", s),
3795
- (s: string) => theme.fg("muted", s),
3796
- buildMessage(),
3797
- );
3798
- activeLoader = loader;
3799
- // Loader has stop() but no dispose(); wire dispose so that
3800
- // setExtensionWidget's teardown stops the 80ms animation interval.
3801
- (loader as Loader & { dispose?: () => void }).dispose = () => loader.stop();
3802
- return loader;
3803
- },
3804
- { placement: "aboveEditor" },
3805
- ),
3806
- );
3807
- // Refresh the elapsed-seconds label every second. Frame animation is
3808
- // driven by the Loader's own 80ms interval.
3809
- spinnerTimer = setInterval(() => {
3810
- activeLoader?.setMessage(buildMessage());
3811
- }, 1000);
3812
- },
3813
- onLaunchEnd: () => {
3814
- stopSpinner();
3815
- },
3816
- // Register the spawned dashboard-server PID into `selfSpawnedPgids`
3817
- // synchronously, before the next 5 s process-scan tick. Keeps the
3818
- // dashboard's own `node` infrastructure out of the session-card
3819
- // process list. See change: tighten-process-list-ux.
3820
- onServerSpawned: (childPid: number) => {
3821
- selfSpawnedPgids.add(childPid);
3822
- },
3823
- // Honor the server's `server_restarting` quiesce window. While a
3824
- // deliberate restart/shutdown is in flight, skip the spawn step so we
3825
- // don't race the orchestrator. Discovery + reconnection still run.
3826
- // See change: fix-restart-bridge-auto-start-race.
3827
- shouldSuppressAutoStart: () => connection.shouldSuppressAutoStart(),
3828
- }).then((result) => {
3829
- stopSpinner(); // safety net — covers onLaunchEnd not firing
3830
- if (result.server && result.server.piPort !== config.piPort) {
3831
- const candidateUrl = `ws://${result.server.host === "localhost" ? "localhost" : result.server.host}:${result.server.piPort}`;
3832
- // fix-bridge-mdns-migration-hijack: a DISCOVERED candidate only
3833
- // SUGGESTS. Whether the connection follows it is decided — and
3834
- // recorded — by `ConnectionManager.retargetTo`, which refuses to
3835
- // drop an established, registered connection until the candidate has
3836
- // PROVEN reachable (`GET /api/health` → `{ok:true}`, D1), honours
3837
- // localhost preference against a remote candidate (D3), and returns
3838
- // to the last registered endpoint if the candidate dies after
3839
- // adoption (D2). The blanket refusal this replaces also blocked
3840
- // every LEGITIMATE migration (a server that really moved).
3841
- if (endpointPinned) {
3842
- // D3 (add-pi-gateway-transport-identity): a pinned endpoint
3843
- // refuses every re-target. The refusal stays on the record (10.2).
3844
- const decision = decideRetarget({
3845
- current: { endpoint: dashboardUrl, instanceId: registeredInstanceId },
3846
- candidate: { endpoint: candidateUrl },
3847
- pinned: true,
3848
- failed: false,
3849
- identityVerified: false,
3850
- });
3851
- const refusedDetail = `${dashboardUrl} -> ${candidateUrl}: ${decision.reason}`;
3852
- console.log(`[dashboard] re-target ${refusedDetail}`);
3853
- transportDiagnostics.record({ event: "retarget_refused", detail: refusedDetail });
3854
- return;
3855
- }
3856
- const trigger = `mdns discovery (${result.server.host}:${result.server.port}, gateway ${result.server.piPort})`;
3857
- // The health probe runs on the candidate's HTTP port — the record's
3858
- // `port`, not the gateway port — and completes BEFORE the incumbent
3859
- // is dropped (retargetTo owns that ordering).
3860
- const healthUrl = `http://${result.server.host}:${result.server.port}/api/health`;
3861
- connection
3862
- .retargetTo(candidateUrl, {
3863
- trigger,
3864
- verify: () => probeEndpointReachability({ healthUrl }),
3865
- })
3866
- .then((accepted) => {
3867
- console.log(`[dashboard] re-target ${dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);
3868
- })
3869
- .catch((err: unknown) => console.error("[dashboard] re-target decision failed:", err));
3870
- }
3871
- }).catch(() => { stopSpinner(); });
3872
-
3873
- // Send initial git info + the session's pi version. A session change already
3874
- // ran the first evaluation (and renewed the tracker) in handleSessionChange;
3875
- // doing it again would double the synchronous git work.
3876
- if (!sessionChanged) {
3877
- const gbc = syncBc();
3878
- renewGitTracker().evaluateFirst(gbc, startCwd);
3879
- applyBc(gbc);
3880
- }
3881
- sendCwdMissingIfChanged(startCwd);
3882
- sendPiVersionIfChanged();
3883
-
3884
- // Start metrics monitor and heartbeat
3885
- startMetricsMonitor();
3886
- heartbeatTimer = setInterval(() => {
3887
- if (!isActive()) return;
3888
- connection.send({
3889
- type: "session_heartbeat",
3890
- sessionId,
3891
- // Liveness truth for the server's status reconcile: `streaming` is
3892
- // otherwise a one-way latch and a single dropped `agent_end` sticks
3893
- // the card on `Thinking…` forever.
3894
- // `=== true` because the flag is optional and is `undefined` before
3895
- // the first turn: sent raw it would serialize away and read as "old
3896
- // bridge, no liveness truth" instead of "idle".
3897
- // See change: fix-stuck-streaming-status-latch.
3898
- agentRunning: getBridgeState().isAgentStreaming === true,
3899
- // Fold the bridge→server ring-buffer eviction count into the heartbeat
3900
- // so it reaches `/api/health`. See change:
3901
- // fix-stuck-tool-card-on-dropped-event.
3902
- metrics: {
3903
- ...collectMetrics(),
3904
- droppedBufferedFrames: connection.getDroppedBufferedCount(),
3905
- refusedInboundFrames: connection.getDroppedInboundCount(),
3906
- // Subagent-tick throttle counters ride the same transport, so the
3907
- // throttle's two information-loss modes are observable in production
3908
- // instead of only at L1. See change: reduce-bridge-tick-bandwidth (D6).
3909
- ...subagentTickThrottle.stats,
3910
- // Subagent fan-out admission counters ride the same transport, so a
3911
- // narrowed fan-out is observable instead of looking like a model that
3912
- // chose not to parallelize. See change:
3913
- // bound-subagent-fanout-under-host-pressure (D7).
3914
- ...fanoutAdmission.counters,
3915
- // Agent path gate counters (in-root decisions are counted, not logged).
3916
- pathGateInRoot: pathGate.counters.inRoot,
3917
- pathGateAsked: pathGate.counters.asked,
3918
- pathGateBlocked: pathGate.counters.blocked,
3919
- // Poll-cost counters (summed across sessions on /api/health).
3920
- // See change: optimize-polling-hot-paths.
3921
- ...pollCost,
3922
- },
3923
- });
3924
- }, HEARTBEAT_INTERVAL);
3925
- getBridgeState().timers!.push(heartbeatTimer);
3926
-
3927
- // Start git + name/model polling
3928
- startGitPollTimer(ctx);
3929
-
3930
- // Start the adaptive process scanner (detect stalled child processes).
3931
- // One async `ps -A` per scan; fast while the agent/tools run, idle
3932
- // otherwise. session_start re-runs: dispose the previous scheduler first so
3933
- // schedules never stack. See change: optimize-polling-hot-paths.
3934
- ensurePollingDisposable();
3935
- const scheduler = createProcessScanScheduler({
3936
- platform: process.platform,
3937
- setTimer: setRegisteredTimeout,
3938
- clearTimer: clearRegisteredTimeout,
3939
- scan: async () => {
3940
- if (!isActive()) return { changed: false };
3941
- const processes = await scanChildProcessesAsync(
3942
- process.pid,
3943
- trackedPgids,
3944
- PROCESS_MIN_ELAPSED_MS,
3945
- { excludedPgids: selfSpawnedPgids },
3946
- );
3947
- if (!isActive() || polling.processScan !== scheduler) return { changed: false };
3948
- const currentPids = JSON.stringify(processes.map((p) => p.pid).sort());
3949
- if (currentPids === previousProcessPids) return { changed: false };
3950
- previousProcessPids = currentPids;
3951
- connection.send({
3952
- type: "process_list",
3953
- sessionId,
3954
- processes: processes.map((p) => ({ pid: p.pid, pgid: p.pgid, command: p.command, elapsedMs: p.elapsedMs })),
3955
- });
3956
- return { changed: true };
3957
- },
3958
- });
3959
- polling.replaceProcessScan(scheduler);
3960
- scheduler.start();
3961
-
3962
- // Register flow event listeners (pi-flows emits these via pi.events)
3963
- registerFlowEventListeners(syncBc(), () => sessionReady, getFlowsList);
3964
-
3965
- // Extension UI System (Phase 1): subscribe to invalidate once per
3966
- // session, then run the discovery probe. The probe is synchronous
3967
- // and re-runs on every reconnect (see `onReconnect` callback above).
3968
- // See change: add-extension-ui-modal.
3969
- subscribeUiInvalidate(uiModulesBridgeCtx);
3970
- refreshUiModules(uiModulesBridgeCtx);
3971
- }));
3972
-
3973
- // Shared handler for session changes (new/fork/resume)
3974
- function handleSessionChange(ctx: any, usageSeed?: ReturnType<UsageDrain["baseline"]>) {
3975
- // Clear attachedChange on a real session switch (new/fork/resume): it is
3976
- // persisted globally + restored at activate, so without this the previous
3977
- // session's attached change would leak into the new session's prompt until
3978
- // the server replays. The server re-pushes the correct value for the new
3979
- // sessionId on its session_register. See change: inject-session-context-into-agent.
3980
- attachedChange = null;
3981
- getBridgeState().attachedChange = null;
3982
- // Drop retained subagent frames/snapshots on a real session switch — the
3983
- // new/fork/resumed session's subagents are unrelated to the outgoing one.
3984
- // See change: fix-subagent-live-detail-reliability.
3985
- subagentFrameBuffer.reset();
3986
- // Same disposal point for the tick throttle: clear every armed trailing
3987
- // timer and drop every held frame, so nothing from the outgoing session
3988
- // can fire against the new one.
3989
- // See change: reduce-bridge-tick-bandwidth (D3).
3990
- subagentTickThrottle.reset();
3991
- // A session boundary invalidates the CONTENT itself (unlike a reconnect), so
3992
- // drop any parked text snapshot and cancel its window rather than flushing
3993
- // it into the new session. See change:
3994
- // coalesce-bridge-message-update-snapshots (D8).
3995
- coalescer.clear();
3996
- // Clear the stop-after-turn latch so a new/fork/resumed session does not
3997
- // inherit the previous session's pending graceful-stop and shut down on
3998
- // its first turn_end. See change: adopt-pi-071-072-073-features.
3999
- getBridgeState().shouldStopAfterTurn = false;
4000
- // Drop the auto-namer and its carried state: it is a PER-SESSION state
4001
- // machine, so a new/fork/resumed session must not inherit the outgoing
4002
- // session's permanent stop, spent attempt budget or auto-named flag — it
4003
- // would report `stopped` / `already-named` without ever attempting to name.
4004
- // The server re-pushes the incoming session's own persisted state on its
4005
- // session_register. See change: fix-auto-naming-reasoning-model.
4006
- autoNamer = undefined;
4007
- namerState = undefined;
4008
- prev.namerState = undefined;
4009
- // Bridge shadow queues reset on session change so the new session
4010
- // starts with empty chips. See change: add-followup-edit-and-steer-cancel.
4011
- if (bridgeSteering.length > 0 || bridgeFollowUp.length > 0) {
4012
- bridgeSteering = [];
4013
- // Drops every entry AND its image bytes, releasing the byte budget.
4014
- bridgeFollowUp.reset();
4015
- emitQueueUpdate();
4016
- }
4017
- renewGitTracker();
4018
- const bc = syncBc();
4019
- _handleSessionChange(bc, ctx, getFlowsList, usageSeed);
4020
- applyBc(bc);
4021
- // A new session id needs its own `pi_version_update` (below-floor flag).
4022
- // After applyBc, so syncBc() carries the NEW session id.
4023
- // See change: update-pi-core-1-0-adopt-apis.
4024
- sendPiVersionIfChanged();
4025
-
4026
- // Restart polling timers
4027
- startGitPollTimer(ctx);
4028
- }
2075
+ // Plugin-declared bus channels: plugin bridges emit
2076
+ // `dashboard:register-event-forward`; `attach()` subscribes the listener and
2077
+ // then emits `dashboard:bridge-ready` so plugins that activated first
2078
+ // re-declare. Core names no plugin channel. See change:
2079
+ // add-plugin-bridge-contributions (D1/D2/D4).
2080
+ const pluginForwardRegistry = new PluginForwardRegistry(pi.events, {
2081
+ send: (eventType, data) =>
2082
+ inst.connection.send({
2083
+ type: "event_forward",
2084
+ sessionId: inst.sessionId,
2085
+ event: { eventType, timestamp: Date.now(), data },
2086
+ }),
2087
+ isSessionReady: () => inst.sessionReady,
2088
+ isActive,
2089
+ isConnected: () => inst.connection.isConnected,
2090
+ isCoreChannel: (channel) => channel in EVENT_BUS_MAP,
2091
+ });
2092
+ inst.pluginForwardRegistry = pluginForwardRegistry;
2093
+ pluginForwardRegistry.attach();
4029
2094
 
4030
- // Single source of truth for the git + name/model poll loop. Both session
4031
- // start and session change call this so the two timers can never drift.
4032
- // Caches ctx.cwd (the throwing getter) and clears any prior timer first.
4033
- function startGitPollTimer(ctx: any) {
4034
- if (gitPollTimer) clearInterval(gitPollTimer);
4035
- // safeCwd: startGitPollTimer runs inside handleSessionChange BEFORE
4036
- // connection.connect(); an un-guarded ctx.cwd throw here skips connect()
4037
- // (#393). See change: fix-bridge-resume-disconnect.
4038
- cachedCwd = safeCwd(ctx);
4039
- const pollState = createGitPollState();
4040
- gitPollTimer = setInterval(() => {
4041
- // runGitPollTick handles a rejecting git tick itself; this catch is the
4042
- // last line so the interval callback can never raise an unhandled rejection.
4043
- runGitPollTick({
4044
- isActive,
4045
- cachedCwd: () => cachedCwd,
4046
- tickGit: (cwd) => {
4047
- const gbc = syncBc();
4048
- polling.gitTracker?.tick(gbc, cwd);
4049
- applyBc(gbc);
4050
- },
4051
- sendCwdMissingIfChanged,
4052
- sendSessionNameIfChanged,
4053
- sendModelUpdateIfChanged,
4054
- sendPiVersionIfChanged: () => _sendPiVersionIfChanged(syncBc()),
4055
- state: pollState,
4056
- }).catch((err) => console.error("[dashboard] git poll tick failed:", err));
4057
- }, GIT_POLL_INTERVAL);
4058
- getBridgeState().timers!.push(gitPollTimer);
4059
- }
2095
+ registerSessionStart(inst);
4060
2096
 
4061
2097
  // session_switch and session_fork events removed in pi 0.65.0.
4062
2098
  // Now handled via session_start with event.reason ("new"|"fork"|"resume").
4063
2099
 
4064
- pi.on("turn_end", safe(async (event: any, ctx: any) => {
4065
- if (!isActive()) return;
4066
- cachedCtx = ctx;
4067
- if (!sessionReady) return;
4068
- // Drain point: compaction / usage entries recorded during the turn.
4069
- // See change: count-non-message-usage.
4070
- drainUsage(ctx);
4071
-
4072
- // Send firstMessage update after first turn if not previously sent
4073
- if (!lastFirstMessage) {
4074
- const firstMsg = extractFirstMessage(ctx);
4075
- if (firstMsg) {
4076
- lastFirstMessage = firstMsg;
4077
- connection.send({
4078
- type: "first_message_update",
4079
- sessionId,
4080
- firstMessage: firstMsg,
4081
- });
4082
- }
4083
- }
4084
-
4085
- }));
2100
+ registerTurnEnd(inst);
4086
2101
 
4087
2102
  // Control event (never `event_forward`): an idle cache refresh's usage
4088
2103
  // entry lands before the NEXT decision, so each decision is a drain point.
@@ -4094,68 +2109,22 @@ function initBridge(pi: ExtensionAPI) {
4094
2109
  drainUsage(ctx);
4095
2110
  }) as any);
4096
2111
 
4097
- pi.on("session_shutdown", safe(async (event: any, ctx: any) => {
4098
- if (!isActive()) return;
4099
- // Let the reloaded instance (fresh ExtensionAPI) pass the re-entry guard.
4100
- // See change: fix-terminal-session-dashboard-reload (D4).
4101
- releaseBridgeOwnerOnShutdown(getBridgeState(), event?.reason);
4102
- // Remove this session's pi-dashboard MCP registration (a reloaded
4103
- // instance re-registers on its own mint). See change: migrate-mcp-to-pi-builtin (D1).
4104
- mcpRegistrar.onSessionShutdown();
4105
- getBridgeState().isAgentStreaming = false;
4106
- stopMetricsMonitor();
4107
- if (heartbeatTimer) {
4108
- clearInterval(heartbeatTimer);
4109
- heartbeatTimer = null;
4110
- }
4111
- if (gitPollTimer) {
4112
- clearInterval(gitPollTimer);
4113
- gitPollTimer = null;
4114
- }
4115
- drainDisposables(getBridgeState());
4116
- // Flush undrained entry usage BEFORE session_unregister (which ends the
4117
- // session server-side), on every shutdown reason: quit, reload and
4118
- // session replacement (new/resume/fork). See change: count-non-message-usage.
4119
- sendShutdownUsageThenUnregister(
4120
- () => drainUsage(ctx),
4121
- () => connection.send({
4122
- type: "session_unregister",
4123
- sessionId,
4124
- }),
4125
- );
4126
-
4127
- // Drop retained subagent frames/snapshots on shutdown.
4128
- // See change: fix-subagent-live-detail-reliability.
4129
- subagentFrameBuffer.reset();
4130
- // See change: reduce-bridge-tick-bandwidth (D3).
4131
- subagentTickThrottle.reset();
4132
- // A shutdown is a session boundary: discard parked text, cancel the window.
4133
- // See change: coalesce-bridge-message-update-snapshots (D8).
4134
- coalescer.clear();
4135
-
4136
- // Best-effort: remove this session's pasted ask_user attachments.
4137
- // See change: add-ask-user-input-multiline-paste.
4138
- cleanupAttachmentsForSession(sessionId);
4139
-
4140
- // Give time for the unregister to send
4141
- await new Promise((resolve) => setTimeout(resolve, 100));
4142
- connection.disconnect();
4143
- }));
2112
+ registerSessionShutdown(inst);
4144
2113
 
4145
2114
  // Re-send models list when custom providers finish async discovery
4146
2115
  onProviderChanged(() => {
4147
2116
  if (!isActive()) return;
4148
- if (cachedModelRegistry && sessionReady) {
2117
+ if (inst.cachedModelRegistry && inst.sessionReady) {
4149
2118
  try {
4150
- const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
4151
- connection.send({ type: "models_list", sessionId, models });
2119
+ const models = filterByEnabledModels(inst.cachedModelRegistry.getAvailable().map(toModelInfo));
2120
+ inst.connection.send({ type: "models_list", sessionId: inst.sessionId, models });
4152
2121
  // See change: replace-hardcoded-provider-lists.
4153
- connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
2122
+ inst.connection.send({ type: "providers_list", sessionId: inst.sessionId, providers: buildProviderCatalogue() });
4154
2123
  } catch { /* ignore */ }
4155
2124
 
4156
2125
  // Retry pending default model — custom provider may now have its models
4157
- if (pendingDefaultModel) {
4158
- pendingDefaultModel = applyDefaultModel();
2126
+ if (inst.pendingDefaultModel) {
2127
+ inst.pendingDefaultModel = applyDefaultModel();
4159
2128
  }
4160
2129
  }
4161
2130
  });
@@ -4164,13 +2133,13 @@ function initBridge(pi: ExtensionAPI) {
4164
2133
  const state = getBridgeState();
4165
2134
  state.cleanup = () => {
4166
2135
  const s = getBridgeState();
4167
- s.sessionId = sessionId;
4168
- s.attachedChange = attachedChange;
4169
- s.ctx = cachedCtx;
4170
- s.modelRegistry = cachedModelRegistry;
4171
- s.hasUI = cachedHasUI;
4172
- if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
4173
- if (gitPollTimer) { clearInterval(gitPollTimer); gitPollTimer = null; }
2136
+ s.sessionId = inst.sessionId;
2137
+ s.attachedChange = inst.attachedChange;
2138
+ s.ctx = inst.cachedCtx;
2139
+ s.modelRegistry = inst.cachedModelRegistry;
2140
+ s.hasUI = inst.cachedHasUI;
2141
+ if (inst.heartbeatTimer) { clearInterval(inst.heartbeatTimer); inst.heartbeatTimer = null; }
2142
+ if (inst.gitPollTimer) { clearInterval(inst.gitPollTimer); inst.gitPollTimer = null; }
4174
2143
  drainDisposables(s);
4175
2144
  // Disable the admission sampler's private event-loop histogram. A bridge
4176
2145
  // re-init (/reload, session replacement) constructs a fresh sampler; without
@@ -4188,7 +2157,8 @@ function initBridge(pi: ExtensionAPI) {
4188
2157
  // Release our EventBus subscriptions. Nothing to "restore": the bridge no
4189
2158
  // longer replaces any host function. See change: fix-automation-run-lifecycle.
4190
2159
  disposeEventBusForwarding();
4191
- connection.disconnect();
2160
+ pluginForwardRegistry.dispose();
2161
+ inst.connection.disconnect();
4192
2162
  };
4193
2163
 
4194
2164
  // Reload is handled by session_start which fires on /reload too