@blackbelt-technology/pi-agent-dashboard 0.10.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 (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -5,21 +5,30 @@
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";
22
- import { mintBridgeTicket, readDeviceToken, withTicket } from "./bridge-ticket-client.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";
23
32
  import {
24
33
  createCommandHandler,
25
34
  tryExecSlashTemplate,
@@ -27,65 +36,63 @@ import {
27
36
  } from "./command-handler.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";
53
- import { localCredentialPlan } from "./local-token-header.js";
55
+ import { createInboundLimits } from "./inbound-limits.js";
56
+ import { localCredentialPlan, proofFailureLogCause } from "./local-token-header.js";
54
57
  import { inlineMessageText, type ReadFileOutcome } from "./markdown-image-inliner.js";
55
58
  import { createMcpDashboardRegistrar, type McpRegistrationApi, } from "./mcp-token-delivery.js";
56
- import { createPluginRequestClient, installPluginRequest } from "./plugin-request-client.js";
57
59
  import { COALESCE_WINDOW_MS, MessageUpdateCoalescer } from "./message-update-coalescer.js";
58
60
  import { resetReconnectCaches as _resetReconnectCaches, sendCwdMissingIfChanged as _sendCwdMissingIfChanged, sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendPiVersionIfChanged as _sendPiVersionIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged } from "./model-tracker.js";
59
61
  import { createPathGate } from "./path-gate/index.js";
60
62
  import { Suppression } from "./path-gate/suppression.js";
61
63
  import { emitPendingPrompts } from "./pending-prompt-emitter.js";
62
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";
63
70
  import { getOwnPgid, } from "./process-scanner.js";
64
71
  import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
65
- import { activate as activateProviderRegister, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
66
- import { httpBaseUrlFor, isRemoteEndpoint } from "./remote-registration-gate.js";
67
- import { RetryTracker } from "./retry-tracker.js";
72
+ import { activate as activateProviderRegister, awaitStartupProviderModels, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
73
+ import { createRemoteUpgradePreparer } from "./remote-upgrade-preparer.js";
74
+ import { installPiAiDelayFn, RetryTracker } from "./retry-tracker.js";
68
75
  import { activate as activateRoleManager, resolveNamingModel } from "./role-manager.js";
76
+ import { loadServerPins, serverPinsPath } from "./server-pin-store.js";
69
77
  import { replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, filterByEnabledModels, isLive } from "./session-sync.js";
70
78
  import { tryDispatchExtensionCommand } from "./slash-dispatch.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";
74
- import { SubagentFrameBuffer } from "./subagent-frame-buffer.js";
75
- import { stripForForward } from "./subagent-frame-strip.js";
76
- import { FanoutAdmissionGate, resolveAdmissionConfig } from "./subagent-fanout-admission.js";
77
- import { SaturationSampler } from "./subagent-saturation.js";
78
- 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";
79
90
  import { createTransportDiagnostics } from "./transport-diagnostics.js";
80
91
  import { refreshUiModules, type UiModulesBridgeCtx } from "./ui-modules.js";
81
- import { createInstance, type BridgeState } from "./bridge-handlers/instance.js";
92
+ import { drainUsageAndSend, makeCacheWarmingDecisionHandler, UsageDrain, } from "./usage-drain.js";
82
93
  import { createVaultDelivery } from "./vault-delivery.js";
83
94
  import { createVaultForwardFilter } from "./vault-forwarder.js";
84
95
  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";
89
96
 
90
97
  /**
91
98
  * Formats the state behind a watchdog force-close for `server.log`.
@@ -114,7 +121,13 @@ function getBridgeState(): BridgeState {
114
121
  return (process as any)[BRIDGE_KEY];
115
122
  }
116
123
 
117
- 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> {
118
131
  // Per-process opt-out, decided before ANY registration: an inert bridge
119
132
  // registers no tool/command/handler/MCP and never connects or auto-starts.
120
133
  // Dashboard spawns stamp PI_DASHBOARD_BRIDGE=on. See change: add-bridge-env-opt-out.
@@ -130,11 +143,23 @@ export default function (pi: ExtensionAPI) {
130
143
  // prefix was dropped in `add-agent-role-model-tools` (design D11).
131
144
  activateRoleManager(pi);
132
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
+
133
153
  // Anthropic-messages payload transforms (system prompt rewrite + tool
134
154
  // filter/remap) are handled by the installed @benvargas/pi-claude-code-use
135
155
  // package when present. No local duplication here.
136
156
 
137
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();
138
163
  } catch (err) {
139
164
  // Never crash the host pi agent — dashboard is non-essential
140
165
  console.error("[dashboard] Bridge init failed:", err);
@@ -151,9 +176,9 @@ function initBridge(pi: ExtensionAPI) {
151
176
  // If bridge is already active for a different pi instance (e.g. a subagent
152
177
  // loading extensions in the same process), skip initialization to avoid
153
178
  // invalidating the parent session's bridge connection and event forwarding.
154
- // `session_shutdown{reason:"reload"}` releases `prev.pi`, so the reloaded
155
- // main session (a fresh ExtensionAPI) is not mistaken for a subagent.
156
- // 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).
157
182
  // Re-init teardown (cleanup, connections, timers, disposables) runs only for a
158
183
  // genuine re-init; a subagent re-entry returns here untouched. Seam:
159
184
  // `bridge-polling.ts`. See change: optimize-polling-hot-paths (D11).
@@ -193,51 +218,28 @@ function initBridge(pi: ExtensionAPI) {
193
218
  // → inst.cachedCwd (BridgeInstance field; unset until assigned)
194
219
  inst.pendingDefaultModel = null; // non-null if default model not yet applied (custom provider not ready)
195
220
 
196
- /** 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
+ */
197
227
  function applyDefaultModel(): string | null {
198
- const freshConfig = loadConfig();
199
- if (!freshConfig.defaultModel || !inst.cachedModelRegistry) return null;
200
- const slashIdx = freshConfig.defaultModel.indexOf("/");
201
- if (slashIdx <= 0) return null;
202
- const provider = freshConfig.defaultModel.slice(0, slashIdx);
203
- const modelId = freshConfig.defaultModel.slice(slashIdx + 1);
204
- try {
205
- const found = inst.cachedModelRegistry.find(provider, modelId);
206
- if (found) {
207
- (pi as any).setModel(found).then(() => {
208
- // Apply the configured default thinking level alongside the default
209
- // model. setModel preserves the current level, so an explicit call is
210
- // required. pi.setThinkingLevel is synchronous and clamps the level to
211
- // the model's capabilities. Empty value = "do not override".
212
- // See change: add-default-thinking-level.
213
- const level = freshConfig.defaultThinkingLevel;
214
- if (level) (pi as any).setThinkingLevel?.(level);
215
- setTimeout(() => sendModelUpdateIfChanged(), 50);
216
- }).catch(() => {});
217
- return null; // applied
218
- }
219
- } catch { /* ignore */ }
220
- 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
+ });
221
237
  }
222
238
  inst.applyDefaultModel = applyDefaultModel;
223
239
 
224
- /** Query pi-flows for available flows via synchronous event RPC */
225
- function getFlowsList(): FlowInfo[] {
226
- const probe: any = {};
227
- try {
228
- pi.events?.emit("flow:list-flows", probe);
229
- } catch { /* ignore */ }
230
- return (probe.flows as FlowInfo[] | undefined) ?? [];
231
- }
232
- inst.getFlowsList = getFlowsList;
233
-
234
- /** Send flows_list message to the dashboard server */
235
- function sendFlowsList() {
236
- const flows = getFlowsList();
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 });
239
- }
240
- 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).
241
243
 
242
244
 
243
245
  inst.heartbeatTimer = null;
@@ -336,6 +338,7 @@ function initBridge(pi: ExtensionAPI) {
336
338
  // Global auto-naming toggle, relayed by the server via `preferences_update`.
337
339
  // Default true so a bridge that registers before the first push still names.
338
340
  inst.autoNameSessions = true;
341
+ inst.claudeSubscriptionCompat = false;
339
342
  // → inst.autoNamer (BridgeInstance field; unset until assigned)
340
343
  // The namer's durable state set is carried across reload as VALUES, never as
341
344
  // the namer object: its closures would retain a stale connection, session id
@@ -379,6 +382,9 @@ function initBridge(pi: ExtensionAPI) {
379
382
  // are sourced READ-ONLY from pi's retry settings for the display countdown;
380
383
  // the bridge never writes them. See change: retry-forever-with-stop-control.
381
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);
382
388
  inst.retryTracker = retryTracker;
383
389
  // Empty-actionable-turn guard: when a terminal turn is a clean-but-empty
384
390
  // `stop` (thinking-only, no text, no tool call), continue-or-surface instead
@@ -395,13 +401,6 @@ function initBridge(pi: ExtensionAPI) {
395
401
  const abortLatch = new AbortLatch();
396
402
  inst.abortLatch = abortLatch;
397
403
 
398
- // Subagent live-detail reliability: retain subagent frames emitted while the
399
- // bridge is not ready (buffer-and-flush on re-register, D1) and keep the
400
- // latest snapshot of each running subagent for the resync responder (D2).
401
- // See change: fix-subagent-live-detail-reliability.
402
- const subagentFrameBuffer = new SubagentFrameBuffer();
403
- inst.subagentFrameBuffer = subagentFrameBuffer;
404
-
405
404
  // Dashboard MCP server registration with pi's built-in MCP. The bearer lives
406
405
  // only in this registrar and pi's registration — never in process.env.
407
406
  // See change: migrate-mcp-to-pi-builtin (D1).
@@ -421,25 +420,6 @@ function initBridge(pi: ExtensionAPI) {
421
420
  });
422
421
  inst.mcpRegistrar = mcpRegistrar;
423
422
 
424
- // Bound the Agent-tick rate on the `tool_execution_update` carrier. That
425
- // carrier has no throttle anywhere on its path, so its rate is the
426
- // subagent's raw session-event rate; the sibling `subagents:*` carrier is
427
- // already coalesced to 250 ms by the producer and is what paces the LIVE
428
- // render, so this window costs replay staleness, not liveness.
429
- //
430
- // `windowMs` comes from the shared dashboard config, read once here at
431
- // bridge init (`0` = disabled, the byte-identical rollback path). `send` and
432
- // `canSend` deliberately resolve `connection` / `sessionReady` / `sessionId`
433
- // at CALL time: all three can move while a frame is held, and a captured
434
- // reference would send over a dead connection or under a stale session.
435
- // See change: reduce-bridge-tick-bandwidth (D2/D3/D4).
436
- const subagentTickThrottle = new SubagentTickThrottle<unknown>({
437
- windowMs: loadConfig().subagentTickThrottleMs,
438
- send: (msg) => inst.connection.send(msg),
439
- canSend: (frameSessionId) => isActive() && inst.sessionReady && frameSessionId === inst.sessionId,
440
- });
441
- inst.subagentTickThrottle = subagentTickThrottle;
442
-
443
423
  // Bound the bridge's per-token streaming cost. pi's `message_update` carries
444
424
  // the FULL accumulated text snapshot, so forwarding each one synchronously
445
425
  // paid a `JSON.stringify` per source token on pi's own event loop — O(N²)
@@ -500,10 +480,11 @@ function initBridge(pi: ExtensionAPI) {
500
480
 
501
481
  // Bridge-owned queue structures with TWO different ownership models:
502
482
  //
503
- // • bridgeSteering (pi-OWNED + SHADOW) — mirrors pi's Agent.steeringQueue.
504
- // Mutated only by `recordSteerSent` (on bridge-originated steer sends) +
505
- // drain-by-message_start-matcher (when pi delivers a queued steer entry,
506
- // 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.
507
488
  //
508
489
  // • bridgeFollowUp (BRIDGE-OWNED BUFFER) — authoritative store for
509
490
  // dashboard-originated follow-up entries while the agent is streaming.
@@ -519,11 +500,12 @@ function initBridge(pi: ExtensionAPI) {
519
500
  //
520
501
  // Both feed the same `queue_update` ExtensionToServerMessage.
521
502
  //
522
- // Steer is permanently pi-owned + display-only (steer drains too fast at
523
- // turn_end for mutation UI to matter; user direction).
524
- //
525
- // See change: rework-mid-turn-prompt-queue (spec mid-turn-prompt-queue).
526
- 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;
527
509
  const bridgeFollowUp = createFollowupBuffer();
528
510
  inst.bridgeFollowUp = bridgeFollowUp;
529
511
  function emitQueueUpdate(): void {
@@ -531,7 +513,7 @@ function initBridge(pi: ExtensionAPI) {
531
513
  inst.connection.send({
532
514
  type: "queue_update",
533
515
  sessionId: inst.sessionId,
534
- steering: [...inst.bridgeSteering],
516
+ steering: bridgeSteer.views(),
535
517
  // Views only: text + image COUNT. Image bytes never cross the wire.
536
518
  followUp: bridgeFollowUp.views(),
537
519
  });
@@ -555,14 +537,23 @@ function initBridge(pi: ExtensionAPI) {
555
537
  });
556
538
  }
557
539
  inst.sendCommandFeedback = sendCommandFeedback;
558
- function recordSteerSent(text: string): void {
559
- // Only record when the agent was actually streaming at send time. Idle
560
- // sends start a new turn directly — pi doesn't queue them, so the
561
- // shadow queue must not show a chip. See change: add-followup-edit-and-steer-cancel.
562
- if (!getBridgeState().isAgentStreaming) return;
563
- inst.bridgeSteering.push(text);
564
- 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 });
565
555
  }
556
+ inst.ackSteerDelivered = ackSteerDelivered;
566
557
  /**
567
558
  * Push a follow-up entry into the bridge-owned buffer.
568
559
  *
@@ -636,9 +627,11 @@ function initBridge(pi: ExtensionAPI) {
636
627
  try {
637
628
  drainOneFollowup({
638
629
  buffer: bridgeFollowUp,
630
+ steerBuffer: bridgeSteer,
639
631
  ctx: inst.cachedCtx,
640
632
  emitQueueUpdate,
641
633
  sendUserMessage: (content) => (pi.sendUserMessage as any)(content),
634
+ ackSteer: ackSteerDelivered,
642
635
  });
643
636
  } finally {
644
637
  isDraining = false;
@@ -889,9 +882,9 @@ function initBridge(pi: ExtensionAPI) {
889
882
  * - `appendCustomEntry` (pi.appendEntry) → `custom_entry` protocol event —
890
883
  * pi does not dispatch `entry_appended` to extensions at all.
891
884
  *
892
- * pi-flows' `flow-event` entries are excluded inside the shared mapper
893
- * (they are appended live by pi-flows itself; forwarding would
894
- * 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).
895
888
  */
896
889
  function wrapCustomPersistenceForCtx(ctx: any): void {
897
890
  const sm = ctx?.sessionManager;
@@ -907,7 +900,10 @@ function initBridge(pi: ExtensionAPI) {
907
900
  // its own flush. See change: coalesce-bridge-message-update-snapshots (D5).
908
901
  coalescer.flush();
909
902
  try {
910
- const forward = toCustomMessageForward({ customType, content, display, details, entryId });
903
+ const forward = toCustomMessageForward(
904
+ { customType, content, display, details, entryId },
905
+ inst.pluginForwardRegistry?.replayEntryTypes(),
906
+ );
911
907
  if (forward && inst.sessionReady && isActive()) {
912
908
  inst.connection.send({
913
909
  type: "event_forward",
@@ -930,7 +926,10 @@ function initBridge(pi: ExtensionAPI) {
930
926
  // Chat-row ordering: the second out-of-loop sink. See D5.
931
927
  coalescer.flush();
932
928
  try {
933
- 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
+ );
934
933
  if (forward && inst.sessionReady && isActive()) {
935
934
  inst.connection.send({
936
935
  type: "event_forward",
@@ -1034,27 +1033,24 @@ function initBridge(pi: ExtensionAPI) {
1034
1033
  inst.transportDiagnostics = transportDiagnostics;
1035
1034
  transportDiagnostics.record({ event: "endpoint_resolved", detail: endpointDetail });
1036
1035
 
1037
- /**
1038
- * Mint a fresh, single-use bridge ticket for a REMOTE endpoint.
1039
- *
1040
- * Returns undefined for a local endpoint (nothing to mint) and THROWS when a
1041
- * remote endpoint cannot be authorised, so ConnectionManager retries on its
1042
- * backoff rather than dialling a credential-less upgrade the gateway will
1043
- * refuse. The reason is logged once per attempt: "refused" here means the
1044
- * bearer is missing, unpaired or revoked, which is an operator problem and
1045
- * must not be reported as an unreachable dashboard.
1046
- */
1047
- async function prepareRemoteUpgrade(endpoint: string): Promise<{ url?: string } | undefined> {
1048
- if (!isRemoteEndpoint(endpoint)) return undefined;
1049
- const httpBase = httpBaseUrlFor(endpoint);
1050
- if (!httpBase) return undefined;
1051
- const minted = await mintBridgeTicket({ httpBase, token: readDeviceToken() });
1052
- if (!minted.ok) {
1053
- console.error(`[dashboard] bridge ticket ${minted.cause}: ${minted.reason}`);
1054
- throw new Error(minted.reason);
1055
- }
1056
- return { url: withTicket(endpoint, minted.ticket) };
1057
- }
1036
+ // Mint a bridge ticket per remote dial; origin + failure causes: see
1037
+ // `remote-upgrade-preparer.ts`. Log the resolved HTTP origin up front too
1038
+ // (D4), deduped with the per-dial log.
1039
+ // The bearer goes only to a PINNED endpoint: the one this bridge was configured
1040
+ // with (or the user explicitly moved to), or a pin-store `lastEndpoint`.
1041
+ // A discovery-only host is never pinned. See change: harden-bridge-inbound-and-discovery (D19).
1042
+ const configuredEndpoint = inst.dashboardUrl;
1043
+ const prepareRemoteUpgrade = createRemoteUpgradePreparer({
1044
+ env: process.env,
1045
+ log: console,
1046
+ record: (d) => transportDiagnostics.record(d),
1047
+ isPinned: (endpoint) =>
1048
+ isPinnedEndpoint(endpoint, {
1049
+ configured: [configuredEndpoint, inst.dashboardUrl],
1050
+ pins: loadServerPins(serverPinsPath()),
1051
+ }),
1052
+ });
1053
+ prepareRemoteUpgrade.noteOrigin(inst.dashboardUrl);
1058
1054
 
1059
1055
  // Long-lived ctx wrapper for the Extension UI System (Phase 1) — see
1060
1056
  // change: add-extension-ui-modal. `getSessionId` reads the closed-over
@@ -1117,12 +1113,22 @@ function initBridge(pi: ExtensionAPI) {
1117
1113
  });
1118
1114
  inst.pathGate = pathGate;
1119
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
+
1120
1125
  // Credential vault: applies the hub's granted env values to process.env and
1121
1126
  // reconciles on every connect and session_start. State lives on `process`, so
1122
1127
  // a reload keeps it. See change: add-credential-vault.
1123
1128
  const vaultDelivery = createVaultDelivery({
1124
1129
  send: (m) => inst.connection.sendIfOpen(m),
1125
1130
  sessionId: () => inst.sessionId ?? "",
1131
+ certValidation: () => inst.connection.certValidation,
1126
1132
  log: (line) => console.log(line),
1127
1133
  });
1128
1134
  inst.vaultDelivery = vaultDelivery;
@@ -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
  }
@@ -1197,7 +1264,7 @@ function initBridge(pi: ExtensionAPI) {
1197
1264
  // counter-proof before `open`. See change: loopback-credential-proof (D6, D7).
1198
1265
  planDial: (base) => localCredentialPlan(base),
1199
1266
  onIdentityFailure: (report) => {
1200
- console.error(`[dashboard] server identity check failed (${report.cause}) at ${report.endpoint}`);
1267
+ console.error(`[dashboard] server identity check failed (${proofFailureLogCause(report.cause)}) at ${report.endpoint}`);
1201
1268
  appendIdentityLog(report);
1202
1269
  },
1203
1270
  // Every accepted re-target (and every reversal) re-derives these from the
@@ -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(() => {
@@ -1265,7 +1337,14 @@ function initBridge(pi: ExtensionAPI) {
1265
1337
  const _bc = syncBc();
1266
1338
  _resetReconnectCaches(_bc);
1267
1339
  applyBc(_bc);
1268
- sendStateSync();
1340
+ // Computed ONCE: the register's `liveTailOpen` and the replay's are the
1341
+ // same value. See change: fix-large-session-resume-replay (D7).
1342
+ const liveTailOpen = isLive(inst.cachedCtx, getBridgeState().isAgentStreaming);
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();
1269
1348
  // The server does not persist `piVersion` / `piBelowFloor`; re-send now
1270
1349
  // rather than on the next poll tick. See change: update-pi-core-1-0-adopt-apis.
1271
1350
  sendPiVersionIfChanged();
@@ -1284,13 +1363,12 @@ function initBridge(pi: ExtensionAPI) {
1284
1363
  } catch { /* probe failure non-fatal */ }
1285
1364
  // A live reconnect keeps in-flight calls open (no fabricated end).
1286
1365
  // See change: fix-replay-fabricates-orphan-end-for-live-calls (D3).
1287
- replaySessionEntries({ liveTailOpen: isLive(inst.cachedCtx, getBridgeState().isAgentStreaming) });
1288
- // Flush subagent frames buffered while the socket was down (D1). Unlike
1289
- // session_start, a transient WS reconnect keeps `sessionReady` true, so
1290
- // the intercept routes those frames into the per-agent buffer; drain them
1291
- // now that the transport is open again. See change:
1292
- // fix-subagent-live-detail-reliability.
1293
- flushPendingSubagentFrames();
1366
+ replaySessionEntries({ liveTailOpen });
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();
1294
1372
  // Re-send pending PromptBus requests so dashboard dialogs survive browser refresh.
1295
1373
  // Synchronous within this tick to prevent TUI respond() from interleaving.
1296
1374
  // Client-side dedup by requestId prevents double-rendering. Shared with the
@@ -1338,7 +1416,15 @@ function initBridge(pi: ExtensionAPI) {
1338
1416
  // See change: fix-terminal-session-dashboard-reload.
1339
1417
  const terminalReload = createTerminalReload({ pi, getSessionId: () => inst.sessionId });
1340
1418
 
1419
+ // One limiter per bridge process: kept in the process-global state so a
1420
+ // `/reload` does not refill the prompt bucket. See change:
1421
+ // harden-bridge-inbound-and-discovery (D17).
1422
+ const bridgeState = getBridgeState();
1423
+ const inboundLimits = (bridgeState.inboundLimits ??= createInboundLimits());
1424
+ inst.inboundLimits = inboundLimits;
1425
+
1341
1426
  const commandHandler = createCommandHandler(pi, () => inst.sessionId, {
1427
+ limits: inboundLimits,
1342
1428
  getModelRegistry: () => inst.cachedModelRegistry,
1343
1429
  // Selector-open re-sync of providers.json: heals a missed credentials_updated.
1344
1430
  // See change: refresh-models-on-provider-change (D1).
@@ -1399,12 +1485,10 @@ function initBridge(pi: ExtensionAPI) {
1399
1485
  // that. See change: honest-mid-turn-queue-surface (spec
1400
1486
  // mid-turn-prompt-queue: "Session shutdown invokes cachedCtx.shutdown
1401
1487
  // directly").
1402
- if (inst.cachedCtx?.shutdown) {
1403
- inst.cachedCtx.shutdown();
1404
- }
1405
- // Safety net: force exit after a short delay in case ctx.shutdown()
1406
- // doesn't terminate (e.g. in RPC mode headless sessions)
1407
- 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);
1408
1492
  },
1409
1493
  abort: () => {
1410
1494
  // Pi.abort() cancels the turn; queues persist by design (pi ExtensionAPI
@@ -1457,27 +1541,14 @@ function initBridge(pi: ExtensionAPI) {
1457
1541
  // See change: fix-terminal-session-dashboard-reload (D1/D3/D4).
1458
1542
  reload: terminalReload.reload,
1459
1543
  spawnNew: () => {
1460
- 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()));
1461
1546
  },
1462
1547
  sessionPrompt: async (text, delivery, promptId) => {
1463
- // Route slash commands: management events, flow:run, extension dispatch, then fallback.
1464
- // See change: fix-extension-slash-commands-in-dashboard.
1465
- if (text.startsWith("/") && pi.events) {
1466
- const cmdText = text.slice(1);
1467
- const spaceIdx = cmdText.indexOf(" ");
1468
- const cmdName = spaceIdx === -1 ? cmdText : cmdText.slice(0, spaceIdx);
1469
- const cmdArgs = spaceIdx === -1 ? "" : cmdText.slice(spaceIdx + 1);
1470
-
1471
- // Flow fast-path: typed /<user-defined-flow-name> wins over extension dispatch.
1472
- const flowsList = getFlowsList();
1473
- if (flowsList.some(f => f.name === cmdName)) {
1474
- // Non-turn slash route: settle any optimistic idle bubble so it does
1475
- // not hang to the 30s timeout. See change: optimistic-prompt-progress.
1476
- inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
1477
- pi.events.emit("flow:run", { flowName: cmdName, task: cmdArgs.trim() || undefined });
1478
- return;
1479
- }
1480
- }
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).
1481
1552
 
1482
1553
  // Extension-command dispatch (routing step 9). When matched, the helper
1483
1554
  // emits its own command_feedback events and we MUST NOT fall through.
@@ -1507,6 +1578,7 @@ function initBridge(pi: ExtensionAPI) {
1507
1578
  process.cwd(),
1508
1579
  inst.sessionId,
1509
1580
  (msg) => inst.connection.send(msg),
1581
+ inst.inboundLimits,
1510
1582
  );
1511
1583
  if (ranExec) {
1512
1584
  // Non-turn exec-template route: settle optimistic idle bubble.
@@ -1520,8 +1592,9 @@ function initBridge(pi: ExtensionAPI) {
1520
1592
  // delivery="followUp" + streaming → buffer in bridgeFollowUp ONLY
1521
1593
  // (pi never sees it until drain on
1522
1594
  // agent_settled).
1523
- // delivery="steer" + streaming → pi.sendUserMessage({deliverAs:"steer"})
1524
- // + 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).
1525
1598
  // any delivery + idle → pi.sendUserMessage with {deliverAs}
1526
1599
  // (pi ignores it when idle and starts
1527
1600
  // a fresh turn). No buffer push.
@@ -1541,25 +1614,30 @@ function initBridge(pi: ExtensionAPI) {
1541
1614
  // buffered, and the non-turn routes above returned already.
1542
1615
  // See change: optimistic-prompt-progress,
1543
1616
  // fix-spawn-correlation-ttl-coupling (D7).
1544
- 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";
1545
1621
  inst.connection.send({
1546
1622
  type: "prompt_received",
1547
1623
  sessionId: inst.sessionId,
1548
1624
  fresh: !wasStreaming,
1549
- ...(promptId && !buffered ? { promptId } : {}),
1625
+ ...(promptId && !bufferFollowUp && !bufferSteer ? { promptId } : {}),
1550
1626
  });
1551
1627
  const expanded = expandPromptTemplateFromDisk(text, process.cwd(), pi);
1552
- if (buffered) {
1628
+ if (bufferFollowUp) {
1553
1629
  // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
1554
1630
  // drain on agent_settled will ship the entry as a fresh turn.
1555
1631
  bufferFollowupSend(expanded);
1632
+ } else if (bufferSteer) {
1633
+ // Held, cancellable; the hand-off acks `promptId`.
1634
+ bufferSteerSend(expanded, undefined, promptId);
1556
1635
  } else {
1557
- // Idle send or steer send — forward to pi directly.
1636
+ // Idle send — forward to pi directly (fresh turn).
1558
1637
  (pi.sendUserMessage as any)(expanded, { deliverAs });
1559
- if (wasStreaming && deliverAs === "steer") recordSteerSent(expanded);
1560
1638
  }
1561
1639
  },
1562
- onSteerSent: recordSteerSent,
1640
+ onSteerBuffered: bufferSteerSend,
1563
1641
  onFollowupSent: bufferFollowupSend,
1564
1642
  isStreaming: () => getBridgeState().isAgentStreaming === true,
1565
1643
  // Clear only the abort latch before prompt routing. A streaming follow-up
@@ -1686,7 +1764,9 @@ function initBridge(pi: ExtensionAPI) {
1686
1764
  cwd: process.cwd(),
1687
1765
  source: "tui",
1688
1766
  pid: process.pid,
1767
+ pidNamespace: processPidNamespace(),
1689
1768
  provisional: true,
1769
+ ...(targetManager?.certValidation ? { certValidation: "enforced" as const } : {}),
1690
1770
  });
1691
1771
  },
1692
1772
  });
@@ -1781,6 +1861,7 @@ function initBridge(pi: ExtensionAPI) {
1781
1861
  selfSpawnedPgids,
1782
1862
  prStatus,
1783
1863
  gitTracker: polling.gitTracker ?? undefined,
1864
+ replayEntryTypes: () => inst.pluginForwardRegistry?.replayEntryTypes() ?? new Set<string>(),
1784
1865
  };
1785
1866
  }
1786
1867
  inst.syncBc = syncBc;
@@ -1807,7 +1888,7 @@ function initBridge(pi: ExtensionAPI) {
1807
1888
  inst.applyBc = applyBc;
1808
1889
 
1809
1890
  // Local wrappers that sync bc around extracted module calls
1810
- function sendStateSync() { const bc = syncBc(); _sendStateSync(bc, getFlowsList); applyBc(bc); inst.connection.noteRegistered(); }
1891
+ function sendStateSync(opts?: { liveTailOpen?: boolean }) { const bc = syncBc(); _sendStateSync(bc, opts); applyBc(bc); inst.connection.noteRegistered(); }
1811
1892
  function replaySessionEntries(opts?: { liveTailOpen?: boolean }) { _replaySessionEntries(syncBc(), opts); }
1812
1893
  inst.replaySessionEntries = replaySessionEntries;
1813
1894
  function sendModelUpdateIfChanged() { const bc = syncBc(); _sendModelUpdateIfChanged(bc); applyBc(bc); }
@@ -1904,52 +1985,30 @@ function initBridge(pi: ExtensionAPI) {
1904
1985
  inst.sendCwdMissingIfChanged = sendCwdMissingIfChanged;
1905
1986
  function sendPiVersionIfChanged() { _sendPiVersionIfChanged(syncBc()); }
1906
1987
  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.
1909
- 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.
1910
1990
 
1911
1991
  registerEnrichedForwarders(inst);
1912
1992
 
1913
1993
  // Pass-through events: forward with no enrichment
1914
1994
  registerPassThroughForwarders(inst);
1915
1995
 
1916
- // ── Subagent fan-out admission ────────────────────────────────────────────
1917
- // Bounds concurrently in-flight `Agent` children so a wide fan-out on a loaded
1918
- // host cannot stall the parent's event loop until the process is reaped.
1919
- //
1920
- // Registered AFTER the pass-through loop above ON PURPOSE: `runner.emitToolCall`
1921
- // returns on the FIRST handler that answers a blocking result, so a gate
1922
- // registered earlier would starve the bridge's own `tool_call` forwarder — the
1923
- // dashboard would miss the refused call's `tool_call` while still seeing its
1924
- // `tool_execution_end`, and live UI and transcript would disagree. See D8.
1925
- //
1926
- // The result carries `block` + `reason` and NEVER `terminate`: a refusal is
1927
- // "not now" (re-issue after running children finish), not a task failure. The
1928
- // `block` decision itself lives in `subagent-fanout-admission.ts`. See change:
1929
- // bound-subagent-fanout-under-host-pressure (D2/D4/D5/D6/D7/D8).
1930
- const admissionSampler = new SaturationSampler();
1931
- const fanoutAdmission = new FanoutAdmissionGate({
1932
- resolveConfig: () => resolveAdmissionConfig(config),
1933
- saturation: admissionSampler,
1934
- // Refusals are ALSO written durably: the failure this mitigates ends with the
1935
- // process gone, so counters carried only by the live frame vanish in exactly
1936
- // the case that matters. Admissions write nothing (hot path, no FS I/O).
1937
- recordRefusal: (record) => {
1938
- try {
1939
- pi.appendEntry("subagent-admission-refused", record);
1940
- } catch (err) {
1941
- console.error("[dashboard] subagent-admission-refused entry failed:", err);
1942
- }
1943
- },
1944
- });
1945
- inst.fanoutAdmission = fanoutAdmission;
1946
- pi.on("tool_call", safe((event: any) => {
1947
- if (!isActive()) return;
1948
- return fanoutAdmission.onToolCall(event);
1949
- }));
1950
- // Agent path gate — registered AFTER the fan-out admission handler (and after the
1951
- // bridge's own forwarder) and deliberately NOT wrapped in the fail-open `safe()`:
1952
- // 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
1953
2012
  // (after reload) pass through. See change: ask-agent-file-access-in-chat (D1).
1954
2013
  pi.on("tool_call", ((event: any, ctx: any) => {
1955
2014
  if (!isActive()) return undefined;
@@ -1959,15 +2018,6 @@ function initBridge(pi: ExtensionAPI) {
1959
2018
  if (!isActive()) return;
1960
2019
  pathGate.onBeforeAgentStart(event);
1961
2020
  }));
1962
- // Release permits on `tool_execution_end` — the ONE signal pi emits on the
1963
- // normal, blocked AND aborted paths. NEVER `tool_result`: an aborted call
1964
- // skips the path that produces it, so a permit released there would leak on
1965
- // every Esc and eventually refuse all subagent work for the session. See D2.
1966
- pi.on("tool_execution_end", safe((event: any) => {
1967
- if (!isActive()) return;
1968
- fanoutAdmission.onExecutionEnd(event);
1969
- }));
1970
-
1971
2021
  // Generic custom entries/messages (pi.appendEntry / pi.sendMessage) are NOT
1972
2022
  // subscribed here: pi does NOT dispatch `entry_appended` to extensions, and
1973
2023
  // the idle-path sendMessage emits message_start/end to internal listeners
@@ -2017,44 +2067,19 @@ function initBridge(pi: ExtensionAPI) {
2017
2067
  // clear here — it would wipe entries the user adds DURING the drain.
2018
2068
  // See change: add-followup-edit-and-steer-cancel (per-entry-drain).
2019
2069
 
2020
- // Forward one EventBus frame as an `event_forward` message. Known channels
2021
- // 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).
2022
2071
  function sendEventForward(channel: string, data: Record<string, unknown>): void {
2023
- const eventType = EVENT_BUS_MAP[channel] ?? channel;
2024
2072
  inst.connection.send({
2025
2073
  type: "event_forward",
2026
2074
  sessionId: inst.sessionId,
2027
- event: { eventType, timestamp: Date.now(), data },
2075
+ event: { eventType: channel, timestamp: Date.now(), data },
2028
2076
  });
2029
2077
  }
2030
- inst.sendEventForward = sendEventForward;
2031
-
2032
- // Flush subagent frames buffered while the bridge was not ready (D1). Called
2033
- // right after `sessionReady` flips true on (re-)register, in emission order.
2034
- // See change: fix-subagent-live-detail-reliability.
2035
- function flushPendingSubagentFrames(): void {
2036
- // Drained intermediate frames are stripped too: this path calls
2037
- // `sendEventForward` directly, so a bus-path-only strip would leak every
2038
- // buffered frame fat. See change: reduce-subagent-details-payload (X5).
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();
2043
- if (flushed === 0) return;
2044
- console.log(
2045
- `[dashboard] flushed ${flushed} buffered subagent frame(s) on re-register` +
2046
- ` (forwarded=${subagentFrameBuffer.stats.forwarded} buffered=${subagentFrameBuffer.stats.buffered}` +
2047
- ` flushed=${subagentFrameBuffer.stats.flushed})`,
2048
- );
2049
- }
2050
- inst.flushPendingSubagentFrames = flushPendingSubagentFrames;
2051
2078
 
2052
2079
  // EventBus forwarding: ONE `pi.events.on` subscription per declared channel
2053
- // (every key of EVENT_BUS_MAP). NOT an `emit` intercept — pi hands each
2054
- // extension its own `events` facade, so patching OUR `emit` never observed
2055
- // pi-flows' or pi-subagents' emissions, and every live flow_*/subagent_*
2056
- // event was silently dropped (automation runs then hung until the max-age
2057
- // 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`.
2058
2083
  // See change: fix-automation-run-lifecycle.
2059
2084
  const disposeEventBusForwarding = registerEventBusForwarding(
2060
2085
  pi.events,
@@ -2063,12 +2088,6 @@ function initBridge(pi: ExtensionAPI) {
2063
2088
  isSessionReady: () => inst.sessionReady,
2064
2089
  isActive,
2065
2090
  isConnected: () => inst.connection.isConnected,
2066
- subagent: {
2067
- isSubagentChannel: (channel) => SubagentFrameBuffer.isSubagentChannel(channel),
2068
- markForwarded: (channel, data) => subagentFrameBuffer.markForwarded(channel, data),
2069
- buffer: (channel, data) => subagentFrameBuffer.buffer(channel, data),
2070
- stripForForward,
2071
- },
2072
2091
  },
2073
2092
  );
2074
2093
 
@@ -2078,18 +2097,25 @@ function initBridge(pi: ExtensionAPI) {
2078
2097
  // re-declare. Core names no plugin channel. See change:
2079
2098
  // add-plugin-bridge-contributions (D1/D2/D4).
2080
2099
  const pluginForwardRegistry = new PluginForwardRegistry(pi.events, {
2081
- send: (eventType, data) =>
2100
+ send: (eventType, data, pluginId) =>
2082
2101
  inst.connection.send({
2083
2102
  type: "event_forward",
2084
2103
  sessionId: inst.sessionId,
2085
2104
  event: { eventType, timestamp: Date.now(), data },
2105
+ // Stamp the declaring plugin so the server can verify ownership on ingest.
2106
+ pluginId,
2086
2107
  }),
2087
2108
  isSessionReady: () => inst.sessionReady,
2088
2109
  isActive,
2089
2110
  isConnected: () => inst.connection.isConnected,
2090
- isCoreChannel: (channel) => channel in EVENT_BUS_MAP,
2091
2111
  });
2092
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();
2093
2119
  pluginForwardRegistry.attach();
2094
2120
 
2095
2121
  registerSessionStart(inst);
@@ -2141,13 +2167,10 @@ function initBridge(pi: ExtensionAPI) {
2141
2167
  if (inst.heartbeatTimer) { clearInterval(inst.heartbeatTimer); inst.heartbeatTimer = null; }
2142
2168
  if (inst.gitPollTimer) { clearInterval(inst.gitPollTimer); inst.gitPollTimer = null; }
2143
2169
  drainDisposables(s);
2144
- // Disable the admission sampler's private event-loop histogram. A bridge
2145
- // re-init (/reload, session replacement) constructs a fresh sampler; without
2146
- // this the superseded 20 ms-resolution monitor runs until process exit.
2147
- admissionSampler.dispose();
2148
2170
 
2149
2171
  // Dev build & restart: rebuild client and stop server before reload
2150
- 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") {
2151
2174
  const __filename = fileURLToPath(import.meta.url);
2152
2175
  const __dirname = path.dirname(__filename);
2153
2176
  const packageRoot = path.resolve(__dirname, "..", "..");
@@ -2157,7 +2180,9 @@ function initBridge(pi: ExtensionAPI) {
2157
2180
  // Release our EventBus subscriptions. Nothing to "restore": the bridge no
2158
2181
  // longer replaces any host function. See change: fix-automation-run-lifecycle.
2159
2182
  disposeEventBusForwarding();
2183
+ disposeBaseReservation();
2160
2184
  pluginForwardRegistry.dispose();
2185
+ toolUpdateFilters.dispose();
2161
2186
  inst.connection.disconnect();
2162
2187
  };
2163
2188