@blackbelt-technology/pi-agent-dashboard 0.11.0 → 0.12.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 (337) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +17 -12
  3. package/docs/architecture.md +973 -224
  4. package/package.json +29 -18
  5. package/packages/extension/package.json +16 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +21 -12
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge.ts +272 -260
  13. package/packages/extension/src/command-handler.ts +26 -31
  14. package/packages/extension/src/connection.ts +123 -31
  15. package/packages/extension/src/credential-guard.ts +300 -0
  16. package/packages/extension/src/custom-entry-forward.ts +27 -18
  17. package/packages/extension/src/default-model-apply.ts +83 -0
  18. package/packages/extension/src/flow-event-wiring.ts +19 -95
  19. package/packages/extension/src/followup-drain.ts +19 -5
  20. package/packages/extension/src/path-gate/decide.ts +68 -5
  21. package/packages/extension/src/path-gate/handler.ts +16 -8
  22. package/packages/extension/src/path-gate/index.ts +2 -2
  23. package/packages/extension/src/path-gate/roots.ts +15 -3
  24. package/packages/extension/src/path-gate/suppression.ts +3 -0
  25. package/packages/extension/src/pi-env.d.ts +8 -1
  26. package/packages/extension/src/pi-retry-settings.ts +11 -2
  27. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  28. package/packages/extension/src/preview-path-link.ts +151 -0
  29. package/packages/extension/src/project-init/scaffold.ts +98 -35
  30. package/packages/extension/src/project-trust.ts +24 -15
  31. package/packages/extension/src/provider-model-cache.ts +118 -0
  32. package/packages/extension/src/provider-register.ts +428 -28
  33. package/packages/extension/src/retry-tracker.ts +90 -7
  34. package/packages/extension/src/role-manager.ts +4 -2
  35. package/packages/extension/src/role-model-tools.ts +21 -4
  36. package/packages/extension/src/server-auto-start.ts +68 -2
  37. package/packages/extension/src/server-launcher.ts +26 -8
  38. package/packages/extension/src/session-sync.ts +11 -12
  39. package/packages/extension/src/spawn-new-session.ts +22 -0
  40. package/packages/extension/src/steer-buffer.ts +164 -0
  41. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  42. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  43. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  44. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  45. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  46. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  47. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  48. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  49. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  50. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  51. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  52. package/packages/extension/src/terminal-reload.ts +19 -5
  53. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  54. package/packages/extension/src/vault-redaction.ts +4 -3
  55. package/packages/server/package.json +17 -14
  56. package/packages/server/src/access/access-denials.ts +8 -0
  57. package/packages/server/src/access/access-grants.ts +244 -58
  58. package/packages/server/src/access/access-plane.ts +7 -0
  59. package/packages/server/src/access/containment-gate.ts +66 -21
  60. package/packages/server/src/access/denial-hold.ts +3 -0
  61. package/packages/server/src/access/grant-coordinator.ts +17 -1
  62. package/packages/server/src/access/named-grant.ts +3 -0
  63. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
  65. package/packages/server/src/access/planes.ts +1 -0
  66. package/packages/server/src/access/verified-read.ts +24 -7
  67. package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
  68. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  69. package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
  70. package/packages/server/src/auth/audit-log.ts +28 -0
  71. package/packages/server/src/auth/auth-plugin.ts +188 -15
  72. package/packages/server/src/auth/auth.ts +80 -0
  73. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  74. package/packages/server/src/auth/cors-origin.ts +14 -1
  75. package/packages/server/src/auth/credential-envelope.ts +233 -0
  76. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  77. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  78. package/packages/server/src/auth/credential-key.ts +479 -0
  79. package/packages/server/src/auth/credential-migration.ts +162 -0
  80. package/packages/server/src/auth/csp-report-paths.ts +0 -5
  81. package/packages/server/src/auth/csp.ts +74 -36
  82. package/packages/server/src/auth/device-proof.ts +202 -0
  83. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  84. package/packages/server/src/auth/host-admission.ts +7 -0
  85. package/packages/server/src/auth/host-gate.ts +13 -2
  86. package/packages/server/src/auth/localhost-guard.ts +50 -23
  87. package/packages/server/src/auth/locked-json-file.ts +68 -6
  88. package/packages/server/src/auth/models-json-store.ts +269 -0
  89. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  90. package/packages/server/src/auth/node-guard.ts +36 -49
  91. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  92. package/packages/server/src/auth/provider-auth-storage.ts +208 -11
  93. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  94. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  95. package/packages/server/src/auth/provider-key-file.ts +71 -0
  96. package/packages/server/src/auth/provider-readiness.ts +91 -0
  97. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  98. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  99. package/packages/server/src/auth/ws-ticket.ts +1 -1
  100. package/packages/server/src/browse.ts +73 -20
  101. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  102. package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
  103. package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
  104. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  105. package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
  106. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  107. package/packages/server/src/cli/credentials-command.ts +555 -0
  108. package/packages/server/src/cli.ts +21 -16
  109. package/packages/server/src/config-api.ts +34 -38
  110. package/packages/server/src/config-snapshot.ts +149 -0
  111. package/packages/server/src/directory-service.ts +33 -14
  112. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  113. package/packages/server/src/event-wiring.ts +181 -101
  114. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  115. package/packages/server/src/git-worktree/git-operations.ts +1 -1
  116. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  117. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  118. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  119. package/packages/server/src/identity/http-road-classification.ts +5 -1
  120. package/packages/server/src/identity/identity-floor.ts +5 -2
  121. package/packages/server/src/identity/ws-message-scope.ts +10 -3
  122. package/packages/server/src/identity/ws-road-classification.ts +2 -1
  123. package/packages/server/src/lib/browse-roots.ts +13 -2
  124. package/packages/server/src/lib/content-disposition.ts +20 -0
  125. package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
  126. package/packages/server/src/lib/eml.ts +2 -2
  127. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  128. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  129. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  130. package/packages/server/src/lib/grep.ts +4 -1
  131. package/packages/server/src/lib/index-html.ts +2 -2
  132. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  133. package/packages/server/src/lib/office-preview.ts +47 -10
  134. package/packages/server/src/lib/path-containment.ts +45 -12
  135. package/packages/server/src/lib/resolve-file-mention.ts +230 -38
  136. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  137. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  138. package/packages/server/src/lib/writable-md-target.ts +22 -0
  139. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  140. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  141. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  142. package/packages/server/src/live-server/capability-redact.ts +21 -5
  143. package/packages/server/src/live-server/live-capability.ts +416 -52
  144. package/packages/server/src/live-server/live-csp-report.ts +1 -1
  145. package/packages/server/src/live-server/live-csp.ts +64 -16
  146. package/packages/server/src/live-server/live-log.ts +5 -1
  147. package/packages/server/src/live-server/live-server-manager.ts +11 -0
  148. package/packages/server/src/live-server/live-server-proxy.ts +268 -52
  149. package/packages/server/src/live-server/live-static.ts +4 -1
  150. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  151. package/packages/server/src/live-server/preview-observe.ts +53 -0
  152. package/packages/server/src/live-server/preview-origin.ts +182 -0
  153. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  154. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  155. package/packages/server/src/live-server/preview-path.ts +40 -0
  156. package/packages/server/src/live-server/preview-pool.ts +385 -0
  157. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  158. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  159. package/packages/server/src/live-server/preview-tier.ts +217 -0
  160. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  161. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  162. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  163. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  164. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  165. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  166. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  167. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  168. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  169. package/packages/server/src/openspec/readiness.ts +1 -1
  170. package/packages/server/src/package/provider-probe.ts +194 -5
  171. package/packages/server/src/pairing/browser-gateway.ts +140 -42
  172. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  173. package/packages/server/src/pairing/paired-devices.ts +370 -8
  174. package/packages/server/src/pairing/pairing.ts +69 -7
  175. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  176. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  177. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  178. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  179. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  180. package/packages/server/src/persistence/preferences-store.ts +52 -2
  181. package/packages/server/src/pi/bridge-contention.ts +84 -2
  182. package/packages/server/src/pi/host-project-trust.ts +15 -9
  183. package/packages/server/src/pi/pi-gateway.ts +208 -21
  184. package/packages/server/src/pi/provisional-registration.ts +4 -1
  185. package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
  186. package/packages/server/src/pi-agent-settings.ts +95 -301
  187. package/packages/server/src/pi-default-remirror.ts +89 -0
  188. package/packages/server/src/plugin-append-event.ts +35 -0
  189. package/packages/server/src/plugin-entry-stats.ts +61 -0
  190. package/packages/server/src/plugin-local-request.ts +207 -0
  191. package/packages/server/src/plugin-ownership.ts +111 -0
  192. package/packages/server/src/plugin-policy-registry.ts +297 -0
  193. package/packages/server/src/plugin-request-lane.ts +92 -16
  194. package/packages/server/src/preferences-relay.ts +20 -0
  195. package/packages/server/src/project-seed.ts +347 -0
  196. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  197. package/packages/server/src/questions/question-store.ts +3 -2
  198. package/packages/server/src/routes/access-routes.ts +23 -6
  199. package/packages/server/src/routes/acme-routes.ts +14 -4
  200. package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
  201. package/packages/server/src/routes/file-routes.ts +327 -86
  202. package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
  203. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  204. package/packages/server/src/routes/git-routes.ts +29 -78
  205. package/packages/server/src/routes/grep-routes.ts +26 -0
  206. package/packages/server/src/routes/live-server-routes.ts +198 -4
  207. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  208. package/packages/server/src/routes/openspec-routes.ts +17 -3
  209. package/packages/server/src/routes/pairing-routes.ts +200 -11
  210. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  211. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  212. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  213. package/packages/server/src/routes/provider-auth-routes.ts +167 -9
  214. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  215. package/packages/server/src/routes/provider-routes.ts +348 -86
  216. package/packages/server/src/routes/session-routes.ts +25 -22
  217. package/packages/server/src/routes/system-routes.ts +87 -39
  218. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  219. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  220. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  221. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  222. package/packages/server/src/server.ts +512 -175
  223. package/packages/server/src/services/cli-service.ts +59 -10
  224. package/packages/server/src/services/secrets-resolver.ts +46 -30
  225. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  226. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  227. package/packages/server/src/session/death-reason.ts +11 -7
  228. package/packages/server/src/session/event-status-extraction.ts +5 -1
  229. package/packages/server/src/session/memory-session-manager.ts +24 -2
  230. package/packages/server/src/session/open-tool-calls.ts +81 -47
  231. package/packages/server/src/session/pid-target.ts +127 -0
  232. package/packages/server/src/session/replay-compaction.ts +18 -5
  233. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  234. package/packages/server/src/session/server-pid-context.ts +14 -0
  235. package/packages/server/src/session/session-api.ts +78 -29
  236. package/packages/server/src/session/session-archive.ts +7 -0
  237. package/packages/server/src/session/session-bootstrap.ts +9 -54
  238. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  239. package/packages/server/src/session/session-load-worker.ts +22 -3
  240. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  241. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  242. package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
  243. package/packages/server/src/spawn-process/link-register.ts +42 -0
  244. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  245. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  246. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  247. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  248. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  249. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  250. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  251. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  252. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  253. package/packages/server/src/sudo-credential/relay.ts +337 -0
  254. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  255. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  256. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  257. package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
  258. package/packages/server/src/vault/vault-routes.ts +9 -2
  259. package/packages/server/src/vault/vault-store.ts +87 -24
  260. package/packages/server/vendor/xlsx/LICENSE +201 -0
  261. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  262. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  263. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  264. package/packages/shared/package.json +4 -2
  265. package/packages/shared/src/agent-credential-files.ts +32 -0
  266. package/packages/shared/src/browser-protocol.ts +137 -57
  267. package/packages/shared/src/canvas-detect.ts +1 -1
  268. package/packages/shared/src/canvas-types.ts +2 -2
  269. package/packages/shared/src/config.ts +73 -136
  270. package/packages/shared/src/containment-guard.ts +14 -4
  271. package/packages/shared/src/credential-encryption.ts +87 -0
  272. package/packages/shared/src/custom-event-groups.ts +2 -0
  273. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  274. package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
  275. package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
  276. package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
  277. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  278. package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
  279. package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
  280. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
  281. package/packages/shared/src/device-key-proof.ts +309 -0
  282. package/packages/shared/src/event-forward-declaration.ts +85 -12
  283. package/packages/shared/src/forbidden-subjects.ts +126 -14
  284. package/packages/shared/src/heap-limits.ts +0 -30
  285. package/packages/shared/src/host-admission.ts +2 -1
  286. package/packages/shared/src/index.ts +7 -6
  287. package/packages/shared/src/live-server.ts +20 -0
  288. package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
  289. package/packages/shared/src/models-json-reader.ts +41 -0
  290. package/packages/shared/src/network-denial-signal.ts +15 -0
  291. package/packages/shared/src/node-version.ts +63 -60
  292. package/packages/shared/src/pairing-knock-client.ts +92 -8
  293. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  294. package/packages/shared/src/pi-path-compare.ts +31 -0
  295. package/packages/shared/src/pi-settings-schema.ts +52 -9
  296. package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
  297. package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
  298. package/packages/shared/src/pi-trust-mirror.ts +18 -8
  299. package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
  300. package/packages/shared/src/pid-namespace.ts +86 -0
  301. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  302. package/packages/shared/src/platform/process.ts +404 -1
  303. package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
  304. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  305. package/packages/shared/src/preview-egress.ts +56 -2
  306. package/packages/shared/src/preview-origins.ts +398 -0
  307. package/packages/shared/src/prompt-answer.ts +9 -5
  308. package/packages/shared/src/protocol.ts +147 -85
  309. package/packages/shared/src/provider-env-catalog.ts +413 -0
  310. package/packages/shared/src/provider-overrides.ts +112 -0
  311. package/packages/shared/src/question-types.ts +6 -0
  312. package/packages/shared/src/recommended-extensions.ts +79 -26
  313. package/packages/shared/src/renderer-by-ext.ts +5 -2
  314. package/packages/shared/src/rest-api.ts +93 -3
  315. package/packages/shared/src/role-schema.ts +24 -0
  316. package/packages/shared/src/route-tiers.ts +94 -3
  317. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  318. package/packages/shared/src/secret-patterns.ts +49 -0
  319. package/packages/shared/src/source-matching.ts +2 -2
  320. package/packages/shared/src/state-replay.ts +40 -24
  321. package/packages/shared/src/sudo-credential.ts +71 -0
  322. package/packages/shared/src/tool-path-resolve.ts +16 -1
  323. package/packages/shared/src/tool-registry/strategies.ts +1 -1
  324. package/packages/shared/src/tool-workdir.ts +56 -0
  325. package/packages/shared/src/trusted-types-mode.ts +72 -0
  326. package/packages/shared/src/types.ts +68 -109
  327. package/packages/shared/src/vertex-regions.ts +81 -0
  328. package/packages/shared/src/ws-message-tiers.ts +10 -3
  329. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  330. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  331. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  332. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  333. package/packages/extension/src/subagent-saturation.ts +0 -196
  334. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  335. package/packages/shared/src/anthropic-messages-source.ts +0 -8
  336. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
  337. package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
@@ -5,89 +5,94 @@
5
5
  * forwards all pi events, and relays commands back.
6
6
  */
7
7
 
8
- import { appendIdentityLog } from "./bridge-identity-log.js";
9
- import { bridgeExtensionIdentity } from "./extension-identity.js";
8
+ import { randomUUID } from "node:crypto";
10
9
  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
13
  import { ensureConfig, loadConfig, } from "@blackbelt-technology/pi-dashboard-shared/config.js";
14
- import { shouldActivateBridge } from "./bridge-activation.js";
14
+ import { claudeCompatExtension } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/claude-compat.js";
15
+ import { processPidNamespace } from "@blackbelt-technology/pi-dashboard-shared/pid-namespace.js";
16
+ import * as git from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
15
17
  import { rendezvousEndpoint } from "@blackbelt-technology/pi-dashboard-shared/rendezvous.js";
16
- import type { FlowInfo, } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import { readRoleConfigFromDisk } from "@blackbelt-technology/pi-dashboard-shared/role-config-disk.js";
17
19
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
20
  import { AbortLatch } from "./abort-latch.js";
19
21
  import { type AutoNamer, createAutoNamer, type PersistedNamerState, type StreamSimpleFn } from "./auto-session-namer.js";
22
+ import { shouldActivateBridge } from "./bridge-activation.js";
20
23
  import type { BridgeContext } from "./bridge-context.js";
21
24
  import { extractLatestTurnWindow, } from "./bridge-context.js";
25
+ import { handleInboundMessage } from "./bridge-handlers/dispatch.js";
26
+ import { registerEnrichedForwarders, registerPassThroughForwarders } from "./bridge-handlers/forwarders.js";
27
+ import { type BridgeState, createInstance } from "./bridge-handlers/instance.js";
28
+ import { registerProjectTrust, registerSessionInfoChanged, registerSessionShutdown, registerSessionStart, registerTurnEnd } from "./bridge-handlers/lifecycle.js";
29
+ import { appendIdentityLog } from "./bridge-identity-log.js";
30
+ import { createPollingHolder, drainDisposables, ensureDisposable, teardownPreviousIncarnation } from "./bridge-polling.js";
31
+ import { runBridgeShutdown } from "./bridge-shutdown.js";
22
32
  import {
23
33
  createCommandHandler,
24
34
  tryExecSlashTemplate,
25
35
  validateImages,
26
36
  } from "./command-handler.js";
27
- import { createInboundLimits } from "./inbound-limits.js";
28
37
  import { buildSessionContextText, runForkSubagentDraft } from "./commit-draft-agent.js";
29
38
  import { ConnectionManager, type WatchdogFireInfo } from "./connection.js";
30
- import {
31
- createTerminalReload,
32
- isBridgeReentry,
33
- RELOAD_COMMAND_NAME,
34
- } from "./terminal-reload.js";
39
+ import { createCredentialGuard, createCredentialGuardToolCallHandler } from "./credential-guard.js";
35
40
  import { toCustomEntryForward, toCustomMessageForward } from "./custom-entry-forward.js";
36
41
  import { registerDashboardContextInjector } from "./dashboard-context-injector.js";
42
+ import { applyDefaultModel as applyDefaultModelFromConfig } from "./default-model-apply.js";
37
43
  import { runDevBuild } from "./dev-build.js";
38
44
  import { EmptyActionableGuard, } from "./empty-actionable-guard.js";
39
45
  import { resolveGuardConfig } from "./empty-actionable-guard-config.js";
40
46
  import { instanceIdFileForSocket, resolveEndpoint } from "./endpoint-resolution.js";
41
47
  import { mapEventToProtocol, } from "./event-forwarder.js";
48
+ import { bridgeExtensionIdentity } from "./extension-identity.js";
42
49
  import {
43
- FLOW_EVENT_MAP,
44
50
  registerEventBusForwarding,
45
- SUBAGENT_EVENT_MAP,
46
51
  } from "./flow-event-wiring.js";
47
52
  import { createFollowupBuffer } from "./followup-buffer.js";
48
53
  import { drainOneFollowup } from "./followup-drain.js";
49
- import { createPollingHolder, drainDisposables, ensureDisposable, teardownPreviousIncarnation } from "./bridge-polling.js";
50
54
  import { createGitTracker, type GitTracker } from "./git-tracker.js";
51
- import { createPrStatusScheduler, type PrStatusScheduler } from "./pr-status.js";
52
- import * as git from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
55
+ import { createInboundLimits } from "./inbound-limits.js";
53
56
  import { localCredentialPlan, proofFailureLogCause } from "./local-token-header.js";
54
- import { isPinnedEndpoint } from "./pinned-endpoint.js";
55
- import { loadServerPins, serverPinsPath } from "./server-pin-store.js";
56
57
  import { inlineMessageText, type ReadFileOutcome } from "./markdown-image-inliner.js";
57
58
  import { createMcpDashboardRegistrar, type McpRegistrationApi, } from "./mcp-token-delivery.js";
58
- import { createPluginRequestClient, installPluginRequest } from "./plugin-request-client.js";
59
59
  import { COALESCE_WINDOW_MS, MessageUpdateCoalescer } from "./message-update-coalescer.js";
60
60
  import { resetReconnectCaches as _resetReconnectCaches, sendCwdMissingIfChanged as _sendCwdMissingIfChanged, sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendPiVersionIfChanged as _sendPiVersionIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged } from "./model-tracker.js";
61
61
  import { createPathGate } from "./path-gate/index.js";
62
62
  import { Suppression } from "./path-gate/suppression.js";
63
63
  import { emitPendingPrompts } from "./pending-prompt-emitter.js";
64
64
  import { readPiRetrySettings } from "./pi-retry-settings.js";
65
+ import { isPinnedEndpoint } from "./pinned-endpoint.js";
66
+ import { PluginForwardRegistry } from "./plugin-event-forward-registry.js";
67
+ import { createPluginRequestClient, installPluginRequest } from "./plugin-request-client.js";
68
+ import { createPrStatusScheduler, type PrStatusScheduler } from "./pr-status.js";
69
+ import { createPreviewPathLink, installBaseReservationListener } from "./preview-path-link.js";
65
70
  import { getOwnPgid, } from "./process-scanner.js";
66
71
  import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
67
- import { activate as activateProviderRegister, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
72
+ import { activate as activateProviderRegister, awaitStartupProviderModels, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
68
73
  import { createRemoteUpgradePreparer } from "./remote-upgrade-preparer.js";
69
- import { RetryTracker } from "./retry-tracker.js";
74
+ import { installPiAiDelayFn, RetryTracker } from "./retry-tracker.js";
70
75
  import { activate as activateRoleManager, resolveNamingModel } from "./role-manager.js";
76
+ import { loadServerPins, serverPinsPath } from "./server-pin-store.js";
71
77
  import { replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, filterByEnabledModels, isLive } from "./session-sync.js";
72
78
  import { tryDispatchExtensionCommand } from "./slash-dispatch.js";
73
- import { UsageDrain, drainUsageAndSend, makeCacheWarmingDecisionHandler, } from "./usage-drain.js";
74
- import { flushBufferedSubagentFrames, } from "./subagent-forward-sites.js";
75
- import { PluginForwardRegistry } from "./plugin-event-forward-registry.js";
76
- import { SubagentFrameBuffer } from "./subagent-frame-buffer.js";
77
- import { stripForForward } from "./subagent-frame-strip.js";
78
- import { FanoutAdmissionGate, resolveAdmissionConfig } from "./subagent-fanout-admission.js";
79
- import { SaturationSampler } from "./subagent-saturation.js";
80
- import { SubagentTickThrottle } from "./subagent-tick-throttle.js";
79
+ import { buildSpawnNewSessionMessage } from "./spawn-new-session.js";
80
+ import { captureSpawnTokenAtActivation } from "./spawn-token.js";
81
+ import { admitSteer, createSteerBuffer } from "./steer-buffer.js";
82
+ import { ToolUpdateFilterRegistry } from "./tool-update-filter-registry.js";
83
+ import { createSudoAskpass, createSudoConfigReader } from "./sudo-askpass/index.js";
84
+ import { sudoMaskState } from "./sudo-askpass/sudo-mask-registry.js";
85
+ import {
86
+ createTerminalReload,
87
+ isBridgeReentry,
88
+ RELOAD_COMMAND_NAME,
89
+ } from "./terminal-reload.js";
81
90
  import { createTransportDiagnostics } from "./transport-diagnostics.js";
82
91
  import { refreshUiModules, type UiModulesBridgeCtx } from "./ui-modules.js";
83
- import { createInstance, type BridgeState } from "./bridge-handlers/instance.js";
92
+ import { drainUsageAndSend, makeCacheWarmingDecisionHandler, UsageDrain, } from "./usage-drain.js";
84
93
  import { createVaultDelivery } from "./vault-delivery.js";
85
94
  import { createVaultForwardFilter } from "./vault-forwarder.js";
86
95
  import { createVaultRedaction } from "./vault-redaction.js";
87
- import { captureSpawnTokenAtActivation } from "./spawn-token.js";
88
- import { registerSessionInfoChanged, registerProjectTrust, registerSessionStart, registerTurnEnd, registerSessionShutdown } from "./bridge-handlers/lifecycle.js";
89
- import { registerEnrichedForwarders, registerPassThroughForwarders } from "./bridge-handlers/forwarders.js";
90
- import { handleInboundMessage } from "./bridge-handlers/dispatch.js";
91
96
 
92
97
  /**
93
98
  * Formats the state behind a watchdog force-close for `server.log`.
@@ -116,7 +121,13 @@ function getBridgeState(): BridgeState {
116
121
  return (process as any)[BRIDGE_KEY];
117
122
  }
118
123
 
119
- export default function (pi: ExtensionAPI) {
124
+ // Async: everything below runs synchronously up to the final `await`, so
125
+ // callers that do not await still see every registration immediately. pi
126
+ // awaits the factory before resolving `--model`, so the custom-provider models
127
+ // registered (cache) or discovered (bounded, `--model` provider only) during
128
+ // activation are flushed first. See change:
129
+ // register-custom-provider-models-at-activation (D1).
130
+ export default async function (pi: ExtensionAPI): Promise<void> {
120
131
  // Per-process opt-out, decided before ANY registration: an inert bridge
121
132
  // registers no tool/command/handler/MCP and never connects or auto-starts.
122
133
  // Dashboard spawns stamp PI_DASHBOARD_BRIDGE=on. See change: add-bridge-env-opt-out.
@@ -132,11 +143,23 @@ export default function (pi: ExtensionAPI) {
132
143
  // prefix was dropped in `add-agent-role-model-tools` (design D11).
133
144
  activateRoleManager(pi);
134
145
 
146
+ // Claude subscription compat rewrite on EVERY pi this extension loads
147
+ // into — main sessions and subagent children alike — reading the switch
148
+ // value the connected bridge mirrors process-globally. Runs before the
149
+ // re-entry guard so children get it too. See change:
150
+ // seed-claude-compat-on-upgrade.
151
+ claudeCompatExtension(() => getBridgeState().claudeSubscriptionCompat === true)(pi as never);
152
+
135
153
  // Anthropic-messages payload transforms (system prompt rewrite + tool
136
154
  // filter/remap) are handled by the installed @benvargas/pi-claude-code-use
137
155
  // package when present. No local duplication here.
138
156
 
139
157
  initBridge(pi);
158
+
159
+ // LAST step: a rejection here would make pi discard every queued
160
+ // registration of this factory, so it is caught below (and the promise
161
+ // itself never rejects).
162
+ return await awaitStartupProviderModels();
140
163
  } catch (err) {
141
164
  // Never crash the host pi agent — dashboard is non-essential
142
165
  console.error("[dashboard] Bridge init failed:", err);
@@ -153,9 +176,9 @@ function initBridge(pi: ExtensionAPI) {
153
176
  // If bridge is already active for a different pi instance (e.g. a subagent
154
177
  // loading extensions in the same process), skip initialization to avoid
155
178
  // invalidating the parent session's bridge connection and event forwarding.
156
- // `session_shutdown{reason:"reload"}` releases `prev.pi`, so the reloaded
157
- // main session (a fresh ExtensionAPI) is not mistaken for a subagent.
158
- // See change: fix-terminal-session-dashboard-reload (D4).
179
+ // `session_shutdown{reason: reload|new|resume|fork}` releases `prev.pi`, so the
180
+ // replacement main session (a fresh ExtensionAPI) is not mistaken for a subagent.
181
+ // See change: fix-terminal-session-dashboard-reload (D4), fix-session-bridge-registration (D1).
159
182
  // Re-init teardown (cleanup, connections, timers, disposables) runs only for a
160
183
  // genuine re-init; a subagent re-entry returns here untouched. Seam:
161
184
  // `bridge-polling.ts`. See change: optimize-polling-hot-paths (D11).
@@ -195,51 +218,28 @@ function initBridge(pi: ExtensionAPI) {
195
218
  // → inst.cachedCwd (BridgeInstance field; unset until assigned)
196
219
  inst.pendingDefaultModel = null; // non-null if default model not yet applied (custom provider not ready)
197
220
 
198
- /** Try to apply the default model from config. Returns the model string if not found (pending), null if applied or no default. */
221
+ /**
222
+ * Try to apply the default model from config. Returns the model string if not
223
+ * found (pending), null if applied or no default. An `@role` default resolves
224
+ * against the current role map on every call (startup + pending retry).
225
+ * See change: add-default-thinking-level, default-model-follows-role.
226
+ */
199
227
  function applyDefaultModel(): string | null {
200
- const freshConfig = loadConfig();
201
- if (!freshConfig.defaultModel || !inst.cachedModelRegistry) return null;
202
- const slashIdx = freshConfig.defaultModel.indexOf("/");
203
- if (slashIdx <= 0) return null;
204
- const provider = freshConfig.defaultModel.slice(0, slashIdx);
205
- const modelId = freshConfig.defaultModel.slice(slashIdx + 1);
206
- try {
207
- const found = inst.cachedModelRegistry.find(provider, modelId);
208
- if (found) {
209
- (pi as any).setModel(found).then(() => {
210
- // Apply the configured default thinking level alongside the default
211
- // model. setModel preserves the current level, so an explicit call is
212
- // required. pi.setThinkingLevel is synchronous and clamps the level to
213
- // the model's capabilities. Empty value = "do not override".
214
- // See change: add-default-thinking-level.
215
- const level = freshConfig.defaultThinkingLevel;
216
- if (level) (pi as any).setThinkingLevel?.(level);
217
- setTimeout(() => sendModelUpdateIfChanged(), 50);
218
- }).catch(() => {});
219
- return null; // applied
220
- }
221
- } catch { /* ignore */ }
222
- return freshConfig.defaultModel; // not found yet — pending
228
+ return applyDefaultModelFromConfig({
229
+ loadConfig,
230
+ readRoles: () => readRoleConfigFromDisk(),
231
+ registry: inst.cachedModelRegistry,
232
+ setModel: (m) => (pi as any).setModel(m),
233
+ setThinkingLevel: (level) => (pi as any).setThinkingLevel?.(level),
234
+ onApplied: () => setTimeout(() => sendModelUpdateIfChanged(), 50),
235
+ log: (msg) => console.log(msg),
236
+ });
223
237
  }
224
238
  inst.applyDefaultModel = applyDefaultModel;
225
239
 
226
- /** Query pi-flows for available flows via synchronous event RPC */
227
- function getFlowsList(): FlowInfo[] {
228
- const probe: any = {};
229
- try {
230
- pi.events?.emit("flow:list-flows", probe);
231
- } catch { /* ignore */ }
232
- return (probe.flows as FlowInfo[] | undefined) ?? [];
233
- }
234
- inst.getFlowsList = getFlowsList;
235
-
236
- /** Send flows_list message to the dashboard server */
237
- function sendFlowsList() {
238
- const flows = getFlowsList();
239
- console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${inst.sessionId.slice(0,8)}`);
240
- inst.connection.send({ type: "flows_list", sessionId: inst.sessionId, flows });
241
- }
242
- inst.sendFlowsList = sendFlowsList;
240
+ // The flow list is plugin-owned (flows plugin bridge publishes a catalog
241
+ // event); core no longer probes or sends it. See change:
242
+ // flows-dock-chip-and-panel-actions (D8).
243
243
 
244
244
 
245
245
  inst.heartbeatTimer = null;
@@ -338,6 +338,7 @@ function initBridge(pi: ExtensionAPI) {
338
338
  // Global auto-naming toggle, relayed by the server via `preferences_update`.
339
339
  // Default true so a bridge that registers before the first push still names.
340
340
  inst.autoNameSessions = true;
341
+ inst.claudeSubscriptionCompat = false;
341
342
  // → inst.autoNamer (BridgeInstance field; unset until assigned)
342
343
  // The namer's durable state set is carried across reload as VALUES, never as
343
344
  // the namer object: its closures would retain a stale connection, session id
@@ -381,6 +382,9 @@ function initBridge(pi: ExtensionAPI) {
381
382
  // are sourced READ-ONLY from pi's retry settings for the display countdown;
382
383
  // the bridge never writes them. See change: retry-forever-with-stop-control.
383
384
  const retryTracker = new RetryTracker(readPiRetrySettings({ cwd: activationCwd }));
385
+ // Prefer pi-ai's own capped `retryDelayMs` for the countdown; the local mirror
386
+ // covers the async gap and a missing peer. See change: fix-retry-delay-cap.
387
+ installPiAiDelayFn(retryTracker);
384
388
  inst.retryTracker = retryTracker;
385
389
  // Empty-actionable-turn guard: when a terminal turn is a clean-but-empty
386
390
  // `stop` (thinking-only, no text, no tool call), continue-or-surface instead
@@ -397,13 +401,6 @@ function initBridge(pi: ExtensionAPI) {
397
401
  const abortLatch = new AbortLatch();
398
402
  inst.abortLatch = abortLatch;
399
403
 
400
- // Subagent live-detail reliability: retain subagent frames emitted while the
401
- // bridge is not ready (buffer-and-flush on re-register, D1) and keep the
402
- // latest snapshot of each running subagent for the resync responder (D2).
403
- // See change: fix-subagent-live-detail-reliability.
404
- const subagentFrameBuffer = new SubagentFrameBuffer();
405
- inst.subagentFrameBuffer = subagentFrameBuffer;
406
-
407
404
  // Dashboard MCP server registration with pi's built-in MCP. The bearer lives
408
405
  // only in this registrar and pi's registration — never in process.env.
409
406
  // See change: migrate-mcp-to-pi-builtin (D1).
@@ -423,25 +420,6 @@ function initBridge(pi: ExtensionAPI) {
423
420
  });
424
421
  inst.mcpRegistrar = mcpRegistrar;
425
422
 
426
- // Bound the Agent-tick rate on the `tool_execution_update` carrier. That
427
- // carrier has no throttle anywhere on its path, so its rate is the
428
- // subagent's raw session-event rate; the sibling `subagents:*` carrier is
429
- // already coalesced to 250 ms by the producer and is what paces the LIVE
430
- // render, so this window costs replay staleness, not liveness.
431
- //
432
- // `windowMs` comes from the shared dashboard config, read once here at
433
- // bridge init (`0` = disabled, the byte-identical rollback path). `send` and
434
- // `canSend` deliberately resolve `connection` / `sessionReady` / `sessionId`
435
- // at CALL time: all three can move while a frame is held, and a captured
436
- // reference would send over a dead connection or under a stale session.
437
- // See change: reduce-bridge-tick-bandwidth (D2/D3/D4).
438
- const subagentTickThrottle = new SubagentTickThrottle<unknown>({
439
- windowMs: loadConfig().subagentTickThrottleMs,
440
- send: (msg) => inst.connection.send(msg),
441
- canSend: (frameSessionId) => isActive() && inst.sessionReady && frameSessionId === inst.sessionId,
442
- });
443
- inst.subagentTickThrottle = subagentTickThrottle;
444
-
445
423
  // Bound the bridge's per-token streaming cost. pi's `message_update` carries
446
424
  // the FULL accumulated text snapshot, so forwarding each one synchronously
447
425
  // paid a `JSON.stringify` per source token on pi's own event loop — O(N²)
@@ -502,10 +480,11 @@ function initBridge(pi: ExtensionAPI) {
502
480
 
503
481
  // Bridge-owned queue structures with TWO different ownership models:
504
482
  //
505
- // • bridgeSteering (pi-OWNED + SHADOW) — mirrors pi's Agent.steeringQueue.
506
- // Mutated only by `recordSteerSent` (on bridge-originated steer sends) +
507
- // drain-by-message_start-matcher (when pi delivers a queued steer entry,
508
- // the matching text is spliced).
483
+ // • bridgeSteer (BRIDGE-OWNED BUFFER) — dashboard-originated steers held
484
+ // while the agent streams, cancellable until handed to pi. Handed off in
485
+ // the awaited `turn_end` handler on completed turns (before pi drains its
486
+ // steering queue), else shipped by the settle drain ahead of follow-ups.
487
+ // State lives in `steer-buffer.ts`. See change: bridge-owned-cancellable-steer.
509
488
  //
510
489
  // • bridgeFollowUp (BRIDGE-OWNED BUFFER) — authoritative store for
511
490
  // dashboard-originated follow-up entries while the agent is streaming.
@@ -521,11 +500,12 @@ function initBridge(pi: ExtensionAPI) {
521
500
  //
522
501
  // Both feed the same `queue_update` ExtensionToServerMessage.
523
502
  //
524
- // Steer is permanently pi-owned + display-only (steer drains too fast at
525
- // turn_end for mutation UI to matter; user direction).
526
- //
527
- // See change: rework-mid-turn-prompt-queue (spec mid-turn-prompt-queue).
528
- inst.bridgeSteering = [];
503
+ // See change: rework-mid-turn-prompt-queue (spec mid-turn-prompt-queue),
504
+ // bridge-owned-cancellable-steer.
505
+ // Fresh nonce per bridge instance: steer ids are never reused across
506
+ // bridge lifetimes (a reload mints a new nonce).
507
+ inst.bridgeSteer = createSteerBuffer(randomUUID().slice(0, 8));
508
+ const bridgeSteer = inst.bridgeSteer;
529
509
  const bridgeFollowUp = createFollowupBuffer();
530
510
  inst.bridgeFollowUp = bridgeFollowUp;
531
511
  function emitQueueUpdate(): void {
@@ -533,7 +513,7 @@ function initBridge(pi: ExtensionAPI) {
533
513
  inst.connection.send({
534
514
  type: "queue_update",
535
515
  sessionId: inst.sessionId,
536
- steering: [...inst.bridgeSteering],
516
+ steering: bridgeSteer.views(),
537
517
  // Views only: text + image COUNT. Image bytes never cross the wire.
538
518
  followUp: bridgeFollowUp.views(),
539
519
  });
@@ -557,14 +537,23 @@ function initBridge(pi: ExtensionAPI) {
557
537
  });
558
538
  }
559
539
  inst.sendCommandFeedback = sendCommandFeedback;
560
- function recordSteerSent(text: string): void {
561
- // Only record when the agent was actually streaming at send time. Idle
562
- // sends start a new turn directly — pi doesn't queue them, so the
563
- // shadow queue must not show a chip. See change: add-followup-edit-and-steer-cancel.
564
- if (!getBridgeState().isAgentStreaming) return;
565
- inst.bridgeSteering.push(text);
566
- emitQueueUpdate();
540
+ /**
541
+ * Hold a streaming steer in the bridge-owned steer buffer INSTEAD of
542
+ * handing it to pi. Callers gate on the capture-before-send streaming
543
+ * verdict; idle steers go to pi directly. `admitSteer` validates images
544
+ * (follow-up path + feedback); refusal is whole-entry. `promptId` rides the
545
+ * entry and is acked only when the steer reaches pi.
546
+ * See change: bridge-owned-cancellable-steer (D1, D3, D6).
547
+ */
548
+ function bufferSteerSend(text: string, images?: unknown, promptId?: string): void {
549
+ admitSteer(bridgeSteer, { text, images, promptId }, { sendCommandFeedback, emitQueueUpdate });
550
+ }
551
+ /** Ack a steer's `promptId` once it has been handed to pi. */
552
+ function ackSteerDelivered(promptId: string | undefined): void {
553
+ if (!promptId || !isActive() || !inst.sessionReady) return;
554
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false, promptId });
567
555
  }
556
+ inst.ackSteerDelivered = ackSteerDelivered;
568
557
  /**
569
558
  * Push a follow-up entry into the bridge-owned buffer.
570
559
  *
@@ -638,9 +627,11 @@ function initBridge(pi: ExtensionAPI) {
638
627
  try {
639
628
  drainOneFollowup({
640
629
  buffer: bridgeFollowUp,
630
+ steerBuffer: bridgeSteer,
641
631
  ctx: inst.cachedCtx,
642
632
  emitQueueUpdate,
643
633
  sendUserMessage: (content) => (pi.sendUserMessage as any)(content),
634
+ ackSteer: ackSteerDelivered,
644
635
  });
645
636
  } finally {
646
637
  isDraining = false;
@@ -891,9 +882,9 @@ function initBridge(pi: ExtensionAPI) {
891
882
  * - `appendCustomEntry` (pi.appendEntry) → `custom_entry` protocol event —
892
883
  * pi does not dispatch `entry_appended` to extensions at all.
893
884
  *
894
- * pi-flows' `flow-event` entries are excluded inside the shared mapper
895
- * (they are appended live by pi-flows itself; forwarding would
896
- * double-render beside the dedicated flow card).
885
+ * Plugin-declared entry types (`replayEntryTypes` in a plugin bridge's
886
+ * forward declaration) are excluded inside the shared mapper (the owning
887
+ * plugin renders them from its live events; forwarding would double-render).
897
888
  */
898
889
  function wrapCustomPersistenceForCtx(ctx: any): void {
899
890
  const sm = ctx?.sessionManager;
@@ -909,7 +900,10 @@ function initBridge(pi: ExtensionAPI) {
909
900
  // its own flush. See change: coalesce-bridge-message-update-snapshots (D5).
910
901
  coalescer.flush();
911
902
  try {
912
- const forward = toCustomMessageForward({ customType, content, display, details, entryId });
903
+ const forward = toCustomMessageForward(
904
+ { customType, content, display, details, entryId },
905
+ inst.pluginForwardRegistry?.replayEntryTypes(),
906
+ );
913
907
  if (forward && inst.sessionReady && isActive()) {
914
908
  inst.connection.send({
915
909
  type: "event_forward",
@@ -932,7 +926,10 @@ function initBridge(pi: ExtensionAPI) {
932
926
  // Chat-row ordering: the second out-of-loop sink. See D5.
933
927
  coalescer.flush();
934
928
  try {
935
- const forward = toCustomEntryForward({ type: "custom", customType, data, id: entryId });
929
+ const forward = toCustomEntryForward(
930
+ { type: "custom", customType, data, id: entryId },
931
+ inst.pluginForwardRegistry?.replayEntryTypes(),
932
+ );
936
933
  if (forward && inst.sessionReady && isActive()) {
937
934
  inst.connection.send({
938
935
  type: "event_forward",
@@ -1116,6 +1113,15 @@ function initBridge(pi: ExtensionAPI) {
1116
1113
  });
1117
1114
  inst.pathGate = pathGate;
1118
1115
 
1116
+ // Reserve-path pair (D9): the neutral `mock-site:base-reservation` probe is answered by the server's decision.
1117
+ // See change: serve-live-previews-on-capability-origin.
1118
+ const previewPathLink = createPreviewPathLink({
1119
+ send: (m) => inst.connection.sendIfOpen(m),
1120
+ sessionId: () => inst.sessionId ?? "",
1121
+ });
1122
+ inst.previewPathLink = previewPathLink;
1123
+ const disposeBaseReservation = installBaseReservationListener(pi.events, () => (isActive() ? previewPathLink : undefined));
1124
+
1119
1125
  // Credential vault: applies the hub's granted env values to process.env and
1120
1126
  // reconciles on every connect and session_start. State lives on `process`, so
1121
1127
  // a reload keeps it. See change: add-credential-vault.
@@ -1131,7 +1137,12 @@ function initBridge(pi: ExtensionAPI) {
1131
1137
  // every outgoing event_forward frame on a copy (with tail hold-back) and is
1132
1138
  // installed at the connection, so no plaintext value reaches the send buffer.
1133
1139
  const vaultRedaction = createVaultRedaction({
1134
- getState: () => vaultDelivery.redactionState(),
1140
+ // Vault values plus operator-entered sudo passwords (append-only registry).
1141
+ getState: () => {
1142
+ const vault = vaultDelivery.redactionState();
1143
+ const sudo = sudoMaskState();
1144
+ return { version: vault.version + sudo.version, entries: [...vault.entries, ...sudo.entries] };
1145
+ },
1135
1146
  createLocalBashOperations: async () => {
1136
1147
  try {
1137
1148
  const pkg: any = await import("@earendil-works/pi-coding-agent");
@@ -1163,9 +1174,65 @@ function initBridge(pi: ExtensionAPI) {
1163
1174
  return { message: { ...message, content: [{ type: "text", text: "[message withheld: vault redaction failed]" }] } } as any;
1164
1175
  }
1165
1176
  });
1177
+ // Sudo credential prompt: installs an askpass wrapper while the server advertises
1178
+ // `sudo-credential` (observed on `dashboard_identity`), asks the operator through
1179
+ // the server relay and answers the helper. Never logs or stores the password
1180
+ // beyond a zeroable in-memory cache. See change: add-sudo-credential-prompt.
1181
+ const sudoAskpass = createSudoAskpass({
1182
+ send: (m) => inst.connection.sendIfOpen(m),
1183
+ sessionId: () => inst.sessionId ?? "",
1184
+ isConnected: () => inst.connection?.isConnected === true,
1185
+ readConfig: createSudoConfigReader({
1186
+ load: () => loadConfig().sudoCredentialPrompt,
1187
+ mtimeMs: () => {
1188
+ try {
1189
+ return fs.statSync(path.join(os.homedir(), ".pi", "dashboard", "config.json")).mtimeMs;
1190
+ } catch {
1191
+ return undefined;
1192
+ }
1193
+ },
1194
+ }),
1195
+ log: (line) => console.log(line),
1196
+ });
1197
+ // A Settings change applies live: re-evaluate the install predicate on a cheap tick.
1198
+ {
1199
+ const sudoTick = setInterval(() => {
1200
+ if (isActive()) sudoAskpass.reconcile();
1201
+ }, 2000);
1202
+ sudoTick.unref?.();
1203
+ getBridgeState().timers!.push(sudoTick);
1204
+ }
1205
+ pi.on("tool_execution_start", (event: any) => {
1206
+ try {
1207
+ if (isActive()) sudoAskpass.toolExecutionStart(event);
1208
+ } catch {
1209
+ /* the gate input is best effort; a failure leaves the gate closed */
1210
+ }
1211
+ });
1212
+ pi.on("tool_execution_end", (event: any) => {
1213
+ try {
1214
+ sudoAskpass.toolExecutionEnd(event);
1215
+ } catch {
1216
+ /* see above */
1217
+ }
1218
+ });
1219
+ pi.on("session_shutdown", () => {
1220
+ try {
1221
+ sudoAskpass.shutdown();
1222
+ } catch {
1223
+ /* best effort: the process-exit hook removes the directory */
1224
+ }
1225
+ });
1166
1226
  pi.on("user_bash", async () => {
1167
1227
  try {
1168
- return (await vaultRedaction.userBash()) as any;
1228
+ // While the askpass wrapper is installed the `!` command is always wrapped (the
1229
+ // password is registered mid-command, after this event) and tracked, so the
1230
+ // gate opens for it. No operations while installed = untracked: gate closed
1231
+ // for that command, never run unwrapped with the gate open (D7).
1232
+ const installed = sudoAskpass.featureInstalled();
1233
+ const result = await vaultRedaction.userBash({ always: installed });
1234
+ if (!installed || !result) return result as any;
1235
+ return { operations: sudoAskpass.trackUserBash(result.operations) } as any;
1169
1236
  } catch {
1170
1237
  return undefined;
1171
1238
  }
@@ -1231,6 +1298,7 @@ function initBridge(pi: ExtensionAPI) {
1231
1298
  if (!isActive() || inst.connection !== primaryConnection) return;
1232
1299
  pluginLaneUp();
1233
1300
  vaultDelivery.onOpen();
1301
+ sudoAskpass.onOpen();
1234
1302
  // `onReconnect` skips the FIRST open, so plugin latest/stream messages
1235
1303
  // retained before it would wait for the next emission. Drain after the
1236
1304
  // manager flushes its buffered register frame (microtask).
@@ -1248,9 +1316,13 @@ function initBridge(pi: ExtensionAPI) {
1248
1316
  if (inst.connection !== primaryConnection) return;
1249
1317
  pluginLaneDown();
1250
1318
  pathGate.reset();
1319
+ previewPathLink.reset();
1251
1320
  vaultDelivery.onClose();
1321
+ sudoAskpass.onClose();
1252
1322
  },
1253
1323
  onMessage: safe(async (data: unknown) => {
1324
+ // Sudo prompt answers are consumed here (never re-emitted); the identity is only observed.
1325
+ if (isActive() && sudoAskpass.onServerMessage(data)) return;
1254
1326
  return handleInboundMessage(inst, data);
1255
1327
  }),
1256
1328
  onReconnect: safe(() => {
@@ -1269,6 +1341,10 @@ function initBridge(pi: ExtensionAPI) {
1269
1341
  // same value. See change: fix-large-session-resume-replay (D7).
1270
1342
  const liveTailOpen = isLive(inst.cachedCtx, getBridgeState().isAgentStreaming);
1271
1343
  sendStateSync({ liveTailOpen });
1344
+ // Re-announce the bridge's queues on every re-register so the server
1345
+ // cache never shows a previous bridge's steers. See change:
1346
+ // bridge-owned-cancellable-steer (D7).
1347
+ emitQueueUpdate();
1272
1348
  // The server does not persist `piVersion` / `piBelowFloor`; re-send now
1273
1349
  // rather than on the next poll tick. See change: update-pi-core-1-0-adopt-apis.
1274
1350
  sendPiVersionIfChanged();
@@ -1288,12 +1364,11 @@ function initBridge(pi: ExtensionAPI) {
1288
1364
  // A live reconnect keeps in-flight calls open (no fabricated end).
1289
1365
  // See change: fix-replay-fabricates-orphan-end-for-live-calls (D3).
1290
1366
  replaySessionEntries({ liveTailOpen });
1291
- // Flush subagent frames buffered while the socket was down (D1). Unlike
1292
- // session_start, a transient WS reconnect keeps `sessionReady` true, so
1293
- // the intercept routes those frames into the per-agent buffer; drain them
1294
- // now that the transport is open again. See change:
1295
- // fix-subagent-live-detail-reliability.
1296
- flushPendingSubagentFrames();
1367
+ // Flush plugin latest/stream messages retained while the socket was down.
1368
+ // Unlike session_start, a transient WS reconnect keeps `sessionReady` true,
1369
+ // so they sit in the registry's buffer; drain them now that the transport
1370
+ // is open again. See change: add-plugin-bridge-contributions.
1371
+ pluginForwardRegistry.flush();
1297
1372
  // Re-send pending PromptBus requests so dashboard dialogs survive browser refresh.
1298
1373
  // Synchronous within this tick to prevent TUI respond() from interleaving.
1299
1374
  // Client-side dedup by requestId prevents double-rendering. Shared with the
@@ -1410,12 +1485,10 @@ function initBridge(pi: ExtensionAPI) {
1410
1485
  // that. See change: honest-mid-turn-queue-surface (spec
1411
1486
  // mid-turn-prompt-queue: "Session shutdown invokes cachedCtx.shutdown
1412
1487
  // directly").
1413
- if (inst.cachedCtx?.shutdown) {
1414
- inst.cachedCtx.shutdown();
1415
- }
1416
- // Safety net: force exit after a short delay in case ctx.shutdown()
1417
- // doesn't terminate (e.g. in RPC mode headless sessions)
1418
- setTimeout(() => process.exit(0), 500);
1488
+ // pi 1.5.1+ exits on its own when idle and its dispose() waits for a
1489
+ // credential write, so the safety-net exit leaves it BRIDGE_SHUTDOWN_FALLBACK_MS.
1490
+ // See change: update-pi-core-1-6-adopt-apis.
1491
+ runBridgeShutdown(inst.cachedCtx);
1419
1492
  },
1420
1493
  abort: () => {
1421
1494
  // Pi.abort() cancels the turn; queues persist by design (pi ExtensionAPI
@@ -1468,27 +1541,14 @@ function initBridge(pi: ExtensionAPI) {
1468
1541
  // See change: fix-terminal-session-dashboard-reload (D1/D3/D4).
1469
1542
  reload: terminalReload.reload,
1470
1543
  spawnNew: () => {
1471
- inst.connection.send({ type: "spawn_new_session", sessionId: inst.sessionId, cwd: process.cwd() });
1544
+ // Inherits the current model + thinking level. See change: add-spawn-model-choice (D5).
1545
+ inst.connection.send(buildSpawnNewSessionMessage(inst.sessionId, process.cwd(), () => syncBc()));
1472
1546
  },
1473
1547
  sessionPrompt: async (text, delivery, promptId) => {
1474
- // Route slash commands: management events, flow:run, extension dispatch, then fallback.
1475
- // See change: fix-extension-slash-commands-in-dashboard.
1476
- if (text.startsWith("/") && pi.events) {
1477
- const cmdText = text.slice(1);
1478
- const spaceIdx = cmdText.indexOf(" ");
1479
- const cmdName = spaceIdx === -1 ? cmdText : cmdText.slice(0, spaceIdx);
1480
- const cmdArgs = spaceIdx === -1 ? "" : cmdText.slice(spaceIdx + 1);
1481
-
1482
- // Flow fast-path: typed /<user-defined-flow-name> wins over extension dispatch.
1483
- const flowsList = getFlowsList();
1484
- if (flowsList.some(f => f.name === cmdName)) {
1485
- // Non-turn slash route: settle any optimistic idle bubble so it does
1486
- // not hang to the 30s timeout. See change: optimistic-prompt-progress.
1487
- inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
1488
- pi.events.emit("flow:run", { flowName: cmdName, task: cmdArgs.trim() || undefined });
1489
- return;
1490
- }
1491
- }
1548
+ // Route slash commands: extension dispatch, then fallback. A typed
1549
+ // `/<flow-name>` is pi-flows' own registered command, dispatched like any
1550
+ // extension command (the bridge's flow fast-path is gone). See change:
1551
+ // fix-extension-slash-commands-in-dashboard; flows-dock-chip-and-panel-actions (D8).
1492
1552
 
1493
1553
  // Extension-command dispatch (routing step 9). When matched, the helper
1494
1554
  // emits its own command_feedback events and we MUST NOT fall through.
@@ -1532,8 +1592,9 @@ function initBridge(pi: ExtensionAPI) {
1532
1592
  // delivery="followUp" + streaming → buffer in bridgeFollowUp ONLY
1533
1593
  // (pi never sees it until drain on
1534
1594
  // agent_settled).
1535
- // delivery="steer" + streaming → pi.sendUserMessage({deliverAs:"steer"})
1536
- // + shadow append via recordSteerSent.
1595
+ // delivery="steer" + streaming → buffer in bridgeSteer ONLY (handed
1596
+ // to pi at a completed turn_end or
1597
+ // the settle drain; cancellable until).
1537
1598
  // any delivery + idle → pi.sendUserMessage with {deliverAs}
1538
1599
  // (pi ignores it when idle and starts
1539
1600
  // a fresh turn). No buffer push.
@@ -1553,25 +1614,30 @@ function initBridge(pi: ExtensionAPI) {
1553
1614
  // buffered, and the non-turn routes above returned already.
1554
1615
  // See change: optimistic-prompt-progress,
1555
1616
  // fix-spawn-correlation-ttl-coupling (D7).
1556
- const buffered = wasStreaming && deliverAs === "followUp";
1617
+ // Two separate routing flags (design D3): extending one `buffered` flag
1618
+ // would route steers into bridgeFollowUp.
1619
+ const bufferFollowUp = wasStreaming && deliverAs === "followUp";
1620
+ const bufferSteer = wasStreaming && deliverAs === "steer";
1557
1621
  inst.connection.send({
1558
1622
  type: "prompt_received",
1559
1623
  sessionId: inst.sessionId,
1560
1624
  fresh: !wasStreaming,
1561
- ...(promptId && !buffered ? { promptId } : {}),
1625
+ ...(promptId && !bufferFollowUp && !bufferSteer ? { promptId } : {}),
1562
1626
  });
1563
1627
  const expanded = expandPromptTemplateFromDisk(text, process.cwd(), pi);
1564
- if (buffered) {
1628
+ if (bufferFollowUp) {
1565
1629
  // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
1566
1630
  // drain on agent_settled will ship the entry as a fresh turn.
1567
1631
  bufferFollowupSend(expanded);
1632
+ } else if (bufferSteer) {
1633
+ // Held, cancellable; the hand-off acks `promptId`.
1634
+ bufferSteerSend(expanded, undefined, promptId);
1568
1635
  } else {
1569
- // Idle send or steer send — forward to pi directly.
1636
+ // Idle send — forward to pi directly (fresh turn).
1570
1637
  (pi.sendUserMessage as any)(expanded, { deliverAs });
1571
- if (wasStreaming && deliverAs === "steer") recordSteerSent(expanded);
1572
1638
  }
1573
1639
  },
1574
- onSteerSent: recordSteerSent,
1640
+ onSteerBuffered: bufferSteerSend,
1575
1641
  onFollowupSent: bufferFollowupSend,
1576
1642
  isStreaming: () => getBridgeState().isAgentStreaming === true,
1577
1643
  // Clear only the abort latch before prompt routing. A streaming follow-up
@@ -1698,6 +1764,7 @@ function initBridge(pi: ExtensionAPI) {
1698
1764
  cwd: process.cwd(),
1699
1765
  source: "tui",
1700
1766
  pid: process.pid,
1767
+ pidNamespace: processPidNamespace(),
1701
1768
  provisional: true,
1702
1769
  ...(targetManager?.certValidation ? { certValidation: "enforced" as const } : {}),
1703
1770
  });
@@ -1794,6 +1861,7 @@ function initBridge(pi: ExtensionAPI) {
1794
1861
  selfSpawnedPgids,
1795
1862
  prStatus,
1796
1863
  gitTracker: polling.gitTracker ?? undefined,
1864
+ replayEntryTypes: () => inst.pluginForwardRegistry?.replayEntryTypes() ?? new Set<string>(),
1797
1865
  };
1798
1866
  }
1799
1867
  inst.syncBc = syncBc;
@@ -1820,7 +1888,7 @@ function initBridge(pi: ExtensionAPI) {
1820
1888
  inst.applyBc = applyBc;
1821
1889
 
1822
1890
  // Local wrappers that sync bc around extracted module calls
1823
- function sendStateSync(opts?: { liveTailOpen?: boolean }) { const bc = syncBc(); _sendStateSync(bc, getFlowsList, opts); applyBc(bc); inst.connection.noteRegistered(); }
1891
+ function sendStateSync(opts?: { liveTailOpen?: boolean }) { const bc = syncBc(); _sendStateSync(bc, opts); applyBc(bc); inst.connection.noteRegistered(); }
1824
1892
  function replaySessionEntries(opts?: { liveTailOpen?: boolean }) { _replaySessionEntries(syncBc(), opts); }
1825
1893
  inst.replaySessionEntries = replaySessionEntries;
1826
1894
  function sendModelUpdateIfChanged() { const bc = syncBc(); _sendModelUpdateIfChanged(bc); applyBc(bc); }
@@ -1917,52 +1985,30 @@ function initBridge(pi: ExtensionAPI) {
1917
1985
  inst.sendCwdMissingIfChanged = sendCwdMissingIfChanged;
1918
1986
  function sendPiVersionIfChanged() { _sendPiVersionIfChanged(syncBc()); }
1919
1987
  inst.sendPiVersionIfChanged = sendPiVersionIfChanged;
1920
- // Unified EventBus rename map (flow + subagent events): used by `sendEventForward` for the
1921
- // channel→eventType rename and by `registerEventBusForwarding` for the per-channel subscription set.
1922
- const EVENT_BUS_MAP: Record<string, string> = { ...FLOW_EVENT_MAP, ...SUBAGENT_EVENT_MAP };
1988
+ // Core maps no plugin channel (subagent and flow channels are declared by their
1989
+ // plugin bridges through the forward registry below). See change: move-subagents-to-plugin.
1923
1990
 
1924
1991
  registerEnrichedForwarders(inst);
1925
1992
 
1926
1993
  // Pass-through events: forward with no enrichment
1927
1994
  registerPassThroughForwarders(inst);
1928
1995
 
1929
- // ── Subagent fan-out admission ────────────────────────────────────────────
1930
- // Bounds concurrently in-flight `Agent` children so a wide fan-out on a loaded
1931
- // host cannot stall the parent's event loop until the process is reaped.
1932
- //
1933
- // Registered AFTER the pass-through loop above ON PURPOSE: `runner.emitToolCall`
1934
- // returns on the FIRST handler that answers a blocking result, so a gate
1935
- // registered earlier would starve the bridge's own `tool_call` forwarder — the
1936
- // dashboard would miss the refused call's `tool_call` while still seeing its
1937
- // `tool_execution_end`, and live UI and transcript would disagree. See D8.
1938
- //
1939
- // The result carries `block` + `reason` and NEVER `terminate`: a refusal is
1940
- // "not now" (re-issue after running children finish), not a task failure. The
1941
- // `block` decision itself lives in `subagent-fanout-admission.ts`. See change:
1942
- // bound-subagent-fanout-under-host-pressure (D2/D4/D5/D6/D7/D8).
1943
- const admissionSampler = new SaturationSampler();
1944
- const fanoutAdmission = new FanoutAdmissionGate({
1945
- resolveConfig: () => resolveAdmissionConfig(config),
1946
- saturation: admissionSampler,
1947
- // Refusals are ALSO written durably: the failure this mitigates ends with the
1948
- // process gone, so counters carried only by the live frame vanish in exactly
1949
- // the case that matters. Admissions write nothing (hot path, no FS I/O).
1950
- recordRefusal: (record) => {
1951
- try {
1952
- pi.appendEntry("subagent-admission-refused", record);
1953
- } catch (err) {
1954
- console.error("[dashboard] subagent-admission-refused entry failed:", err);
1955
- }
1956
- },
1957
- });
1958
- inst.fanoutAdmission = fanoutAdmission;
1959
- pi.on("tool_call", safe((event: any) => {
1960
- if (!isActive()) return;
1961
- return fanoutAdmission.onToolCall(event);
1962
- }));
1963
- // Agent path gate — registered AFTER the fan-out admission handler (and after the
1964
- // bridge's own forwarder) and deliberately NOT wrapped in the fail-open `safe()`:
1965
- // its own try/catch maps any internal error to a block. Stale bridge instances
1996
+ // No dashboard-side subagent admission: the subagents producer's `maxConcurrent`
1997
+ // semaphore is the ONE concurrency limit and queues the excess instead of
1998
+ // refusing it. See change: subagent-queue-visibility (D6).
1999
+
2000
+ // Agent credential guard — always on, no setting. Registered BEFORE the path gate so a
2001
+ // blocked call never shows a gate prompt and a grant / YOLO / gate-off cannot override it.
2002
+ // Deliberately NOT wrapped in the fail-open `safe()`: the guard maps an internal error to a
2003
+ // block of that one call. Stale bridge instances (after reload) pass through.
2004
+ // See change: encrypt-credentials-at-rest (D12).
2005
+ const credentialGuardHandler = createCredentialGuardToolCallHandler(
2006
+ createCredentialGuard({ env: process.env, homedir: os.homedir(), log: (line) => console.log(line) }),
2007
+ isActive,
2008
+ );
2009
+ pi.on("tool_call", credentialGuardHandler as any);
2010
+ // Agent path gate — registered AFTER the bridge's own forwarder and deliberately
2011
+ // NOT wrapped in the fail-open `safe()`: its own try/catch maps any internal error to a block. Stale bridge instances
1966
2012
  // (after reload) pass through. See change: ask-agent-file-access-in-chat (D1).
1967
2013
  pi.on("tool_call", ((event: any, ctx: any) => {
1968
2014
  if (!isActive()) return undefined;
@@ -1972,15 +2018,6 @@ function initBridge(pi: ExtensionAPI) {
1972
2018
  if (!isActive()) return;
1973
2019
  pathGate.onBeforeAgentStart(event);
1974
2020
  }));
1975
- // Release permits on `tool_execution_end` — the ONE signal pi emits on the
1976
- // normal, blocked AND aborted paths. NEVER `tool_result`: an aborted call
1977
- // skips the path that produces it, so a permit released there would leak on
1978
- // every Esc and eventually refuse all subagent work for the session. See D2.
1979
- pi.on("tool_execution_end", safe((event: any) => {
1980
- if (!isActive()) return;
1981
- fanoutAdmission.onExecutionEnd(event);
1982
- }));
1983
-
1984
2021
  // Generic custom entries/messages (pi.appendEntry / pi.sendMessage) are NOT
1985
2022
  // subscribed here: pi does NOT dispatch `entry_appended` to extensions, and
1986
2023
  // the idle-path sendMessage emits message_start/end to internal listeners
@@ -2030,44 +2067,19 @@ function initBridge(pi: ExtensionAPI) {
2030
2067
  // clear here — it would wipe entries the user adds DURING the drain.
2031
2068
  // See change: add-followup-edit-and-steer-cancel (per-entry-drain).
2032
2069
 
2033
- // Forward one EventBus frame as an `event_forward` message. Known channels
2034
- // get renamed via EVENT_BUS_MAP; unknown channels use the channel name.
2070
+ // Forward one EventBus frame as an `event_forward` message (channel name as type).
2035
2071
  function sendEventForward(channel: string, data: Record<string, unknown>): void {
2036
- const eventType = EVENT_BUS_MAP[channel] ?? channel;
2037
2072
  inst.connection.send({
2038
2073
  type: "event_forward",
2039
2074
  sessionId: inst.sessionId,
2040
- event: { eventType, timestamp: Date.now(), data },
2075
+ event: { eventType: channel, timestamp: Date.now(), data },
2041
2076
  });
2042
2077
  }
2043
- inst.sendEventForward = sendEventForward;
2044
-
2045
- // Flush subagent frames buffered while the bridge was not ready (D1). Called
2046
- // right after `sessionReady` flips true on (re-)register, in emission order.
2047
- // See change: fix-subagent-live-detail-reliability.
2048
- function flushPendingSubagentFrames(): void {
2049
- // Drained intermediate frames are stripped too: this path calls
2050
- // `sendEventForward` directly, so a bus-path-only strip would leak every
2051
- // buffered frame fat. See change: reduce-subagent-details-payload (X5).
2052
- const flushed = flushBufferedSubagentFrames(subagentFrameBuffer, sendEventForward);
2053
- // Plugin-declared latest/stream channels retained over the same gap flush
2054
- // here too, in emission order. See change: add-plugin-bridge-contributions.
2055
- pluginForwardRegistry.flush();
2056
- if (flushed === 0) return;
2057
- console.log(
2058
- `[dashboard] flushed ${flushed} buffered subagent frame(s) on re-register` +
2059
- ` (forwarded=${subagentFrameBuffer.stats.forwarded} buffered=${subagentFrameBuffer.stats.buffered}` +
2060
- ` flushed=${subagentFrameBuffer.stats.flushed})`,
2061
- );
2062
- }
2063
- inst.flushPendingSubagentFrames = flushPendingSubagentFrames;
2064
2078
 
2065
2079
  // EventBus forwarding: ONE `pi.events.on` subscription per declared channel
2066
- // (every key of EVENT_BUS_MAP). NOT an `emit` intercept — pi hands each
2067
- // extension its own `events` facade, so patching OUR `emit` never observed
2068
- // pi-flows' or pi-subagents' emissions, and every live flow_*/subagent_*
2069
- // event was silently dropped (automation runs then hung until the max-age
2070
- // reaper). The gating + subagent-buffer semantics live in `forwardBusEvent`.
2080
+ // (every key of the core rename map — currently empty). NOT an `emit`
2081
+ // intercept — pi hands each extension its own `events` facade, so patching OUR
2082
+ // `emit` never observed foreign emissions. The gating lives in `forwardBusEvent`.
2071
2083
  // See change: fix-automation-run-lifecycle.
2072
2084
  const disposeEventBusForwarding = registerEventBusForwarding(
2073
2085
  pi.events,
@@ -2076,12 +2088,6 @@ function initBridge(pi: ExtensionAPI) {
2076
2088
  isSessionReady: () => inst.sessionReady,
2077
2089
  isActive,
2078
2090
  isConnected: () => inst.connection.isConnected,
2079
- subagent: {
2080
- isSubagentChannel: (channel) => SubagentFrameBuffer.isSubagentChannel(channel),
2081
- markForwarded: (channel, data) => subagentFrameBuffer.markForwarded(channel, data),
2082
- buffer: (channel, data) => subagentFrameBuffer.buffer(channel, data),
2083
- stripForForward,
2084
- },
2085
2091
  },
2086
2092
  );
2087
2093
 
@@ -2091,18 +2097,25 @@ function initBridge(pi: ExtensionAPI) {
2091
2097
  // re-declare. Core names no plugin channel. See change:
2092
2098
  // add-plugin-bridge-contributions (D1/D2/D4).
2093
2099
  const pluginForwardRegistry = new PluginForwardRegistry(pi.events, {
2094
- send: (eventType, data) =>
2100
+ send: (eventType, data, pluginId) =>
2095
2101
  inst.connection.send({
2096
2102
  type: "event_forward",
2097
2103
  sessionId: inst.sessionId,
2098
2104
  event: { eventType, timestamp: Date.now(), data },
2105
+ // Stamp the declaring plugin so the server can verify ownership on ingest.
2106
+ pluginId,
2099
2107
  }),
2100
2108
  isSessionReady: () => inst.sessionReady,
2101
2109
  isActive,
2102
2110
  isConnected: () => inst.connection.isConnected,
2103
- isCoreChannel: (channel) => channel in EVENT_BUS_MAP,
2104
2111
  });
2105
2112
  inst.pluginForwardRegistry = pluginForwardRegistry;
2113
+ // Per-tool `tool_execution_update` filters declared by plugin bridges (D5).
2114
+ // Attach BEFORE the forward registry announces `dashboard:bridge-ready`, so a
2115
+ // plugin re-declaring on that signal reaches both listeners.
2116
+ const toolUpdateFilters = new ToolUpdateFilterRegistry(pi.events);
2117
+ inst.toolUpdateFilters = toolUpdateFilters;
2118
+ toolUpdateFilters.attach();
2106
2119
  pluginForwardRegistry.attach();
2107
2120
 
2108
2121
  registerSessionStart(inst);
@@ -2154,13 +2167,10 @@ function initBridge(pi: ExtensionAPI) {
2154
2167
  if (inst.heartbeatTimer) { clearInterval(inst.heartbeatTimer); inst.heartbeatTimer = null; }
2155
2168
  if (inst.gitPollTimer) { clearInterval(inst.gitPollTimer); inst.gitPollTimer = null; }
2156
2169
  drainDisposables(s);
2157
- // Disable the admission sampler's private event-loop histogram. A bridge
2158
- // re-init (/reload, session replacement) constructs a fresh sampler; without
2159
- // this the superseded 20 ms-resolution monitor runs until process exit.
2160
- admissionSampler.dispose();
2161
2170
 
2162
2171
  // Dev build & restart: rebuild client and stop server before reload
2163
- if (config.devBuildOnReload) {
2172
+ // `/reload` only: a new/resume/fork session switch tears down too but must not rebuild or stop the server.
2173
+ if (config.devBuildOnReload && s.shutdownReason === "reload") {
2164
2174
  const __filename = fileURLToPath(import.meta.url);
2165
2175
  const __dirname = path.dirname(__filename);
2166
2176
  const packageRoot = path.resolve(__dirname, "..", "..");
@@ -2170,7 +2180,9 @@ function initBridge(pi: ExtensionAPI) {
2170
2180
  // Release our EventBus subscriptions. Nothing to "restore": the bridge no
2171
2181
  // longer replaces any host function. See change: fix-automation-run-lifecycle.
2172
2182
  disposeEventBusForwarding();
2183
+ disposeBaseReservation();
2173
2184
  pluginForwardRegistry.dispose();
2185
+ toolUpdateFilters.dispose();
2174
2186
  inst.connection.disconnect();
2175
2187
  };
2176
2188