@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
@@ -539,15 +539,13 @@ export function createCommandHandler(
539
539
  promptId?: string,
540
540
  ) => void | Promise<void>;
541
541
  /**
542
- * Bridge-shadow-queue hooks: called AFTER pi accepts the user message,
543
- * gated by `isStreaming()` captured BEFORE the send. The capture order
544
- * matters — `pi.sendUserMessage` on an idle session synchronously
545
- * triggers `agent_start`, which flips bridge state to streaming. Checking
546
- * AFTER the send would mis-record idle sends as chip entries.
547
- * Pi doesn't expose `queue_update` to extensions, so the bridge is the
548
- * source of truth. See change: add-followup-edit-and-steer-cancel.
542
+ * Bridge steer-buffer hook: called INSTEAD of a pi send for a steer that
543
+ * arrives while streaming, gated by `isStreaming()` captured BEFORE any pi
544
+ * call (an idle send flips streaming synchronously). The bridge holds the
545
+ * steer (cancellable) and acks `promptId` at hand-off.
546
+ * See change: bridge-owned-cancellable-steer.
549
547
  */
550
- onSteerSent?: (text: string) => void;
548
+ onSteerBuffered?: (text: string, images?: unknown, promptId?: string) => void;
551
549
  /**
552
550
  * `images` carries the attachments sent with a buffered follow-up. Passing
553
551
  * them is what makes the bridge buffer able to deliver them on drain;
@@ -930,7 +928,10 @@ export function createCommandHandler(
930
928
  // (pi never sees it until
931
929
  // drainFollowupQueue ships it
932
930
  // on agent_settled as a fresh turn).
933
- // delivery="steer" + streaming → forward to pi + shadow-record.
931
+ // delivery="steer" + streaming → ONLY notify the bridge steer
932
+ // buffer (held, cancellable; handed
933
+ // to pi at a completed turn_end or
934
+ // the settle drain).
934
935
  // any delivery + idle → forward to pi (fresh turn).
935
936
  //
936
937
  // Capture pre-send streaming state BEFORE any pi call — pi flips
@@ -946,7 +947,10 @@ export function createCommandHandler(
946
947
  // fresh:false → drop (raced mid-turn). Emitted BEFORE any pi call so
947
948
  // the snapshot is authoritative. See change: optimistic-prompt-progress.
948
949
  const da = msg.delivery ?? "followUp";
949
- const buffered = wasStreaming && da === "followUp";
950
+ // Separate routing flags (design D3, bridge-owned-cancellable-steer):
951
+ // one shared flag would route steers into the follow-up buffer.
952
+ const bufferFollowUp = wasStreaming && da === "followUp";
953
+ const bufferSteer = wasStreaming && da === "steer";
950
954
  // The streaming-verdict ack is unchanged and still emitted BEFORE any
951
955
  // pi call, so the snapshot stays authoritative. It carries the
952
956
  // `promptId` ONLY on the branch that actually hands the prompt to pi;
@@ -958,17 +962,20 @@ export function createCommandHandler(
958
962
  type: "prompt_received",
959
963
  sessionId,
960
964
  fresh: !wasStreaming,
961
- ...(msg.promptId && !buffered ? { promptId: msg.promptId } : {}),
965
+ ...(msg.promptId && !bufferFollowUp && !bufferSteer ? { promptId: msg.promptId } : {}),
962
966
  });
963
- if (buffered) {
967
+ if (bufferFollowUp) {
964
968
  // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
965
969
  // images ride into the buffer so the drain can deliver them.
966
970
  // See change: fix-bridge-followup-image-drop.
967
971
  options?.onFollowupSent?.(outgoing, msg.images);
972
+ } else if (bufferSteer) {
973
+ // Bridge-held steer: no pi call; the hand-off acks `promptId`.
974
+ // See change: bridge-owned-cancellable-steer.
975
+ options?.onSteerBuffered?.(outgoing, msg.images, msg.promptId);
968
976
  } else {
969
- // Idle or steer — forward to pi directly.
977
+ // Idle — forward to pi directly (fresh turn).
970
978
  sendUserMessageWithImages(pi, outgoing, msg.images, msg.delivery);
971
- if (wasStreaming && da === "steer") options?.onSteerSent?.(outgoing);
972
979
  }
973
980
  return undefined;
974
981
  }
@@ -1023,12 +1030,8 @@ export function createCommandHandler(
1023
1030
 
1024
1031
  case "request_commands": {
1025
1032
  const commands = filterHiddenCommands(pi.getCommands());
1026
- // Also send flows list alongside commands
1027
- if (options?.eventSink) {
1028
- const probe: any = {};
1029
- try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ }
1030
- options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] });
1031
- }
1033
+ // The flow list is plugin-owned (flows plugin catalog); core sends
1034
+ // only commands. See change: flows-dock-chip-and-panel-actions (D8).
1032
1035
  return {
1033
1036
  type: "commands_list",
1034
1037
  sessionId,
@@ -1200,16 +1203,6 @@ export function createCommandHandler(
1200
1203
  // State sync is handled by the bridge on reconnect
1201
1204
  return undefined;
1202
1205
 
1203
- case "request_flows_refresh": {
1204
- // Re-query pi-flows and send updated list
1205
- if (options?.eventSink) {
1206
- const probe: any = {};
1207
- try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ }
1208
- options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] });
1209
- }
1210
- return undefined;
1211
- }
1212
-
1213
1206
  case "list_sessions": {
1214
1207
  try {
1215
1208
  // Dynamic import to avoid hard dependency at module load
@@ -1591,7 +1584,9 @@ async function runBashCommand(
1591
1584
  // Spawn the resolved absolute path directly (no shell, no PATH dep).
1592
1585
  const result = await pi.exec(resolved.path, argv, { timeout: BASH_TIMEOUT });
1593
1586
  output = (result.stdout || "") + (result.stderr || "");
1594
- exitCode = result.exitCode ?? 0;
1587
+ // pi's ExecResult carries the exit status as `code` (no `exitCode`); a failed
1588
+ // or over-cap (`truncated`) run is nonzero. See change: update-pi-core-1-5-adopt-apis.
1589
+ exitCode = result.code ?? 0;
1595
1590
  } catch (err: any) {
1596
1591
  output = err?.message ?? "Command execution failed";
1597
1592
  exitCode = 1;
@@ -251,11 +251,45 @@ export interface ConnectionManagerOptions {
251
251
  const DROP_REPORT_LIMIT = 10;
252
252
  const DROP_REPORT_WINDOW_MS = 60_000;
253
253
 
254
+ /**
255
+ * Control frames the bounded send buffer never evicts for being old: the server
256
+ * ignores a session until its `session_register`, a lost `session_unregister`
257
+ * leaves the old session routable, and the rest seed per-session/dashboard state
258
+ * a flood must not erase. Deliberately NOT widened to one-shot sync frames
259
+ * (`session_name_update`, `first_message_update`, `usage_recorded`) nor
260
+ * `event_forward` (incl. `replay: true`). See change: fix-session-bridge-registration (D2).
261
+ */
262
+ const PINNED_FRAME_TYPES: ReadonlySet<string> = new Set([
263
+ "session_register",
264
+ "session_unregister",
265
+ "replay_complete",
266
+ "commands_list",
267
+ "models_list",
268
+ "providers_list",
269
+ ]);
270
+ /** Cap on buffered control frames; the oldest is evicted (and counted) beyond it. */
271
+ const MAX_CONTROL_FRAMES = 256;
272
+
273
+ /** A serialized outbound frame; `type` is read once at send time, never re-parsed. */
274
+ interface BufferedFrame {
275
+ data: string;
276
+ type: string;
277
+ /** Monotonic send order, so the two queues merge back into wire order on flush. */
278
+ seq: number;
279
+ }
280
+
254
281
  export class ConnectionManager {
255
282
  private url: string;
256
283
  private WS: any;
257
284
  private ws: any | null = null;
258
- private buffer: string[] = [];
285
+ /** Pinned control frames (<= MAX_CONTROL_FRAMES) and everything else (<= maxBufferSize), each FIFO. */
286
+ private controlQueue: BufferedFrame[] = [];
287
+ private otherQueue: Array<BufferedFrame | undefined> = [];
288
+ /** Index of the oldest live `otherQueue` entry (a head index, not `shift()`, so eviction never moves the queue). */
289
+ private otherHead = 0;
290
+ private bufferSeq = 0;
291
+ /** Evictions per frame type since the last flush (reported in the overflow warning). */
292
+ private droppedByType = new Map<string, number>();
259
293
  private maxBufferSize: number;
260
294
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
261
295
  private backoff = 0;
@@ -372,7 +406,17 @@ export class ConnectionManager {
372
406
  * including `send_prompt` — never dispatches.
373
407
  * See change: fix-optimistic-prompt-stuck-sending.
374
408
  */
375
- private static readonly IMMEDIATE_TYPES = new Set(["prompt_response", "server_restarting", "kill_process", "request_models"]);
409
+ private static readonly IMMEDIATE_TYPES = new Set([
410
+ "prompt_response",
411
+ "server_restarting",
412
+ "kill_process",
413
+ "request_models",
414
+ // A password / Cancel must never wait behind (or be dropped by) a full inbound pump.
415
+ // See change: add-sudo-credential-prompt.
416
+ "sudo_credential_response",
417
+ "sudo_credential_cancel",
418
+ "sudo_credential_forget",
419
+ ]);
376
420
 
377
421
  private static readonly INITIAL_BACKOFF = 1000;
378
422
  private static readonly MAX_BACKOFF = 30000;
@@ -575,7 +619,13 @@ export class ConnectionManager {
575
619
  }
576
620
 
577
621
  send(message: unknown): void {
578
- for (const frame of this.outbound(message)) this.sendOne(JSON.stringify(frame));
622
+ for (const frame of this.outbound(message)) this.sendOne(JSON.stringify(frame), ConnectionManager.frameType(frame));
623
+ }
624
+
625
+ /** Frame `type`, or `"unknown"` when absent / not a string (such frames are never pinned). */
626
+ private static frameType(frame: unknown): string {
627
+ const type = (frame as { type?: unknown } | null | undefined)?.type;
628
+ return typeof type === "string" ? type : "unknown";
579
629
  }
580
630
 
581
631
  /** Frames to put on the wire for `message`: itself, unless the outbound filter rewrites or adds frames. */
@@ -590,25 +640,26 @@ export class ConnectionManager {
590
640
  }
591
641
  }
592
642
 
593
- private sendOne(data: string): void {
643
+ private sendOne(data: string, type: string): void {
594
644
  if (this.ws?.readyState === 1) {
595
645
  try {
596
646
  this.ws.send(data);
597
647
  } catch {
598
648
  // Connection died between readyState check and send — buffer instead
599
- this.bufferMessage(data);
649
+ this.bufferMessage(data, type);
600
650
  }
601
651
  } else {
602
- this.bufferMessage(data);
652
+ this.bufferMessage(data, type);
603
653
  }
604
654
  }
605
655
 
606
656
  /**
607
657
  * Count of outgoing messages evicted from the bounded send buffer while the
608
- * WS was not OPEN (ring-buffer overflow). Silent before this change — an
609
- * evicted event never reaches the server store, leaves no seq gap, and is
610
- * only recovered by `replaySessionEntries()` on reconnect. Exposed for
611
- * observability. See change: fix-stuck-tool-card-on-dropped-event.
658
+ * WS was not OPEN (non-control ring overflow, or the control-frame cap).
659
+ * Silent before this change — an evicted event never reaches the server
660
+ * store, leaves no seq gap, and is only recovered by `replaySessionEntries()`
661
+ * on reconnect. Exposed for observability. Monotonic total (never reset on
662
+ * flush). See change: fix-stuck-tool-card-on-dropped-event.
612
663
  */
613
664
  private droppedBufferedCount = 0;
614
665
  private static readonly DROP_WARN_WINDOW_MS = 5_000;
@@ -718,28 +769,64 @@ export class ConnectionManager {
718
769
  this.draining = false;
719
770
  }
720
771
 
721
- private bufferMessage(data: string): void {
722
- this.buffer.push(data);
723
- if (this.buffer.length > this.maxBufferSize) {
724
- const evicted = this.buffer.shift();
725
- this.droppedBufferedCount++;
726
- let droppedType = "unknown";
727
- try {
728
- const parsed = JSON.parse(evicted ?? "");
729
- if (parsed && typeof parsed.type === "string") droppedType = parsed.type;
730
- } catch {
731
- // best-effort: leave "unknown"
732
- }
733
- const now = Date.now();
734
- if (now - this.lastDropWarnAt >= ConnectionManager.DROP_WARN_WINDOW_MS) {
735
- this.lastDropWarnAt = now;
736
- console.warn(
737
- `[bridge] dropped buffered message (ring overflow) hop=bridge→server droppedType=${droppedType} (total dropped=${this.droppedBufferedCount}, bufferSize=${this.maxBufferSize})`,
738
- );
772
+ /**
773
+ * Buffer a frame while the WS is not OPEN. Two FIFO queues: pinned control
774
+ * frames (capped at MAX_CONTROL_FRAMES) and everything else (capped at
775
+ * `maxBufferSize`). Overflow evicts only the oldest frame of the overflowing
776
+ * queue, in O(1) and without parsing — `type` was read once at send time.
777
+ */
778
+ private bufferMessage(data: string, type: string): void {
779
+ const frame: BufferedFrame = { data, type, seq: this.bufferSeq++ };
780
+ if (PINNED_FRAME_TYPES.has(type)) {
781
+ this.controlQueue.push(frame);
782
+ if (this.controlQueue.length > MAX_CONTROL_FRAMES) this.recordEviction(this.controlQueue.shift());
783
+ } else {
784
+ this.otherQueue.push(frame);
785
+ if (this.otherQueue.length - this.otherHead > this.maxBufferSize) {
786
+ const evicted = this.otherQueue[this.otherHead];
787
+ this.otherQueue[this.otherHead++] = undefined; // release the evicted frame now
788
+ // Compact once per `maxBufferSize` evictions: amortised O(1), array stays <= 2 * maxBufferSize.
789
+ if (this.otherHead >= this.maxBufferSize) {
790
+ this.otherQueue.splice(0, this.otherHead);
791
+ this.otherHead = 0;
792
+ }
793
+ this.recordEviction(evicted);
739
794
  }
740
795
  }
741
796
  }
742
797
 
798
+ private recordEviction(evicted: BufferedFrame | undefined): void {
799
+ const type = evicted?.type ?? "unknown";
800
+ this.droppedBufferedCount++;
801
+ this.droppedByType.set(type, (this.droppedByType.get(type) ?? 0) + 1);
802
+ const now = Date.now();
803
+ if (now - this.lastDropWarnAt >= ConnectionManager.DROP_WARN_WINDOW_MS) {
804
+ this.lastDropWarnAt = now;
805
+ const byType = [...this.droppedByType].map(([t, n]) => `${t}:${n}`).join(",");
806
+ console.warn(
807
+ `[bridge] dropped buffered message (ring overflow) hop=bridge→server droppedTypes=${byType} (total dropped=${this.droppedBufferedCount}, bufferSize=${this.maxBufferSize})`,
808
+ );
809
+ }
810
+ }
811
+
812
+ /** Take every retained frame in original send order (merge of the two queues by `seq`) and reset the per-type drop counts. */
813
+ private drainBuffer(): string[] {
814
+ const control = this.controlQueue;
815
+ const other = this.otherQueue.slice(this.otherHead) as BufferedFrame[];
816
+ this.controlQueue = [];
817
+ this.otherQueue = [];
818
+ this.otherHead = 0;
819
+ this.droppedByType.clear();
820
+ const out: string[] = [];
821
+ let c = 0;
822
+ let o = 0;
823
+ while (c < control.length || o < other.length) {
824
+ const takeControl = o >= other.length || (c < control.length && control[c].seq < other[o].seq);
825
+ out.push(takeControl ? control[c++].data : other[o++].data);
826
+ }
827
+ return out;
828
+ }
829
+
743
830
  get isConnected(): boolean {
744
831
  return this.ws?.readyState === 1;
745
832
  }
@@ -1019,6 +1106,10 @@ export class ConnectionManager {
1019
1106
  }
1020
1107
  return;
1021
1108
  }
1109
+ // Silence is measured from dial start: each dial (first or reconnect) gets
1110
+ // the full watchdogTimeout as its handshake budget, never the previous
1111
+ // socket's leftover silence, and a never-completing handshake still times out.
1112
+ this.lastMessageAt = Date.now();
1022
1113
 
1023
1114
  // Verify the server's identity on the upgrade response, BEFORE `open`: the
1024
1115
  // buffered `session_register` flushes in `onopen`, so nothing is sent to —
@@ -1103,8 +1194,7 @@ export class ConnectionManager {
1103
1194
  this.onOpen?.();
1104
1195
 
1105
1196
  // Flush buffer
1106
- const buffered = [...this.buffer];
1107
- this.buffer = [];
1197
+ const buffered = this.drainBuffer();
1108
1198
  for (const data of buffered) {
1109
1199
  this.ws?.send(data);
1110
1200
  }
@@ -1163,7 +1253,9 @@ export class ConnectionManager {
1163
1253
  this.ws = null;
1164
1254
  // Detach handlers to prevent re-entrant calls from ws.close()
1165
1255
  ws.onclose = null;
1166
- ws.onerror = null;
1256
+ // Swallow, never null: `ws` emits an async 'error' when close() hits a
1257
+ // CONNECTING socket; with no listener Node crashes pi (exit 1).
1258
+ ws.onerror = () => {};
1167
1259
  ws.onopen = null;
1168
1260
  ws.onmessage = null;
1169
1261
  try { ws.close(); } catch { /* ignore — may already be closed */ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Agent credential guard: blocks pi tool calls that read, write or list the
3
+ * dashboard credential files and pi's provider secrets, or that invoke the data key /
4
+ * decrypt. Protected set: `plugin-credentials.json`, `vault.json`, the data-key file and
5
+ * `PI_AGENT_SECRET_FILES` (`auth.json`, `mcp-auth.json`, `providers.json`,
6
+ * `system-one/auth.json`) of `~/.pi/agent` and `PI_CODING_AGENT_DIR`. Always on,
7
+ * no configuration, no switch (a switch is the first thing an injected prompt
8
+ * would ask for). Best-effort protection against ACCIDENTAL disclosure, not a
9
+ * sandbox: relative names from a nearby cwd, variable / string indirection,
10
+ * encoded strings and scripts written to disk are NOT detected.
11
+ *
12
+ * Two rule families, decided before the interactive path gate prompts:
13
+ * - path rules (`read`/`edit`/`write`/`ls`/`find`/`grep`): the canonical target
14
+ * (shared `tool-path-resolve` resolver, follows symlinks) is a protected file
15
+ * or a sibling `<name>.*`; `grep` is also blocked on a directory that DIRECTLY
16
+ * contains a protected file (rg reads hidden files). A missing/empty `path` on
17
+ * `grep`/`find`/`ls` is the session cwd, as in pi.
18
+ * - text rules (EVERY tool, built-in / extension / MCP): string values under the
19
+ * command-bearing fields only (`SCANNED_FIELDS`), never the `write`/`edit`
20
+ * content fields; path-like protected references (no bare basenames), the data
21
+ * key service + a keychain verb, `security dump-keychain`, `credentials decrypt`.
22
+ *
23
+ * Fail closed: an internal error blocks only the call being evaluated. Log lines
24
+ * name the tool and the rule id, never the command text or file content.
25
+ * See change: encrypt-credentials-at-rest (D12); harden-agent-tool-guards (D1).
26
+ */
27
+ import nodePath from "node:path";
28
+ import { PI_AGENT_SECRET_FILES } from "@blackbelt-technology/pi-dashboard-shared/agent-credential-files.js";
29
+ import {
30
+ CREDENTIAL_FILE_BASENAMES,
31
+ CREDENTIAL_KEYCHAIN_SERVICE,
32
+ DATA_KEY_FILE_ENV,
33
+ } from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
34
+ import {
35
+ canonicalizeTarget,
36
+ defaultResolveEnv,
37
+ type ResolveEnv,
38
+ resolveReadTarget,
39
+ resolveToolPath,
40
+ } from "./path-gate/resolve.js";
41
+
42
+ /** Rule ids carried by the `match=` token of the block log line. */
43
+ export type CredentialGuardRule = "path" | "grep-dir" | "text-path" | "text-keychain" | "text-dump" | "text-decrypt" | "depth";
44
+
45
+ export interface CredentialGuardDeps {
46
+ env: NodeJS.ProcessEnv;
47
+ homedir: string;
48
+ /** One line per block / error. Never receives command text or file content. */
49
+ log?: (line: string) => void;
50
+ /** Resolver environment (tests). Default: the real host with `homeDir` = `homedir`. */
51
+ resolveEnv?: ResolveEnv;
52
+ /** Canonicaliser (tests inject a throwing one). Default: shared `canonicalizeTarget`. */
53
+ canonicalize?: (absPath: string, env: ResolveEnv) => string;
54
+ }
55
+
56
+ export interface GuardEvent {
57
+ toolName?: string;
58
+ toolCallId?: string;
59
+ input?: unknown;
60
+ }
61
+
62
+ export interface GuardCtx {
63
+ cwd?: string;
64
+ hasUI?: boolean;
65
+ }
66
+
67
+ export type GuardResult = { block: true; reason: string } | undefined;
68
+
69
+ /** Tools decided by the path rule (their `path` argument is a filesystem target). */
70
+ const PATH_TOOLS = ["read", "edit", "write", "ls", "find", "grep"] as const;
71
+ /** Tools whose missing/empty `path` means the session cwd (pi's behaviour). */
72
+ const CWD_DEFAULT_TOOLS = ["grep", "find", "ls"] as const;
73
+ /** String values are scanned only under these field names (any depth). */
74
+ const SCANNED_FIELDS: ReadonlySet<string> = new Set([
75
+ "command", "script", "code", "args", "url", "path", "file", "filePath", "cwd", "pattern", "glob",
76
+ ]);
77
+ /** `write`/`edit` content fields: never scanned (their targets are covered by the path rule). */
78
+ const CONTENT_FIELDS: ReadonlySet<string> = new Set(["content", "newText", "oldText", "edits"]);
79
+ const CONTENT_TOOLS: ReadonlySet<string> = new Set(["write", "edit"]);
80
+ const MAX_DEPTH = 32;
81
+
82
+ const KEYCHAIN_VERBS = [
83
+ "find-generic-password",
84
+ "delete-generic-password",
85
+ "secret-tool",
86
+ "get-storedcredential",
87
+ "credentialmanager",
88
+ "cmdkey",
89
+ ] as const;
90
+ const DUMP_RE = /security\s+dump-keychain/i;
91
+ const DECRYPT_RE = /credentials\s+decrypt/i;
92
+
93
+ /** Path-like reference form: lowercase, `\` → `/`. */
94
+ const norm = (s: string): string => s.replaceAll("\\", "/").toLowerCase();
95
+ /** Path comparison form: NFC + lowercase (never fail open on a case-folding volume). */
96
+ const fold = (s: string): string => s.normalize("NFC").toLowerCase();
97
+ /** Tool names reach the log: keep only a short, harmless token. */
98
+ const safeName = (s: unknown): string => String(s ?? "unknown").replace(/[^\w.:-]/g, "_").slice(0, 64);
99
+
100
+ /** Collect scanned strings: any depth, only under a scanned field name. False when nested too deep. */
101
+ function collectScanned(value: unknown, scanned: boolean, skipContent: boolean, depth: number, out: string[]): boolean {
102
+ if (depth > MAX_DEPTH) return false;
103
+ if (typeof value === "string") {
104
+ if (scanned) out.push(value);
105
+ return true;
106
+ }
107
+ if (Array.isArray(value)) return value.every((v) => collectScanned(v, scanned, skipContent, depth + 1, out));
108
+ if (value && typeof value === "object") return collectFromObject(value as Record<string, unknown>, scanned, skipContent, depth, out);
109
+ return true;
110
+ }
111
+
112
+ function collectFromObject(obj: Record<string, unknown>, scanned: boolean, skipContent: boolean, depth: number, out: string[]): boolean {
113
+ for (const [k, v] of Object.entries(obj)) {
114
+ if (skipContent && CONTENT_FIELDS.has(k)) continue;
115
+ if (!collectScanned(v, scanned || SCANNED_FIELDS.has(k), skipContent, depth + 1, out)) return false;
116
+ }
117
+ return true;
118
+ }
119
+
120
+ /** The tool's path argument; a missing/empty `path` on grep/find/ls is the session cwd (pi's behaviour). */
121
+ function targetPathOf(tool: string, input: Record<string, unknown>, cwd: string): string | undefined {
122
+ const raw = input.path;
123
+ const missing = raw === undefined || raw === null || raw === "";
124
+ const raw2 = missing && (CWD_DEFAULT_TOOLS as readonly string[]).includes(tool) ? cwd : raw;
125
+ return typeof raw2 === "string" && raw2 !== "" ? raw2 : undefined; // else pi rejects it itself
126
+ }
127
+
128
+ export function createCredentialGuard(deps: CredentialGuardDeps) {
129
+ const log = deps.log ?? (() => {});
130
+ const canonicalize = deps.canonicalize ?? canonicalizeTarget;
131
+ const resolveEnv = (): ResolveEnv => deps.resolveEnv ?? { ...defaultResolveEnv(), homeDir: deps.homedir };
132
+
133
+ /** `PI_CODING_AGENT_DIR` as pi reads it: trimmed, a leading `~` expanded against the injected home. */
134
+ const configuredAgentDir = (): string | undefined => {
135
+ const raw = deps.env.PI_CODING_AGENT_DIR?.trim();
136
+ if (!raw) return undefined;
137
+ if (raw === "~") return deps.homedir;
138
+ return raw.startsWith("~/") || raw.startsWith("~\\") ? nodePath.join(deps.homedir, raw.slice(2)) : raw;
139
+ };
140
+
141
+ /** The files protected under an agent dir: plugin credentials + the provider secrets. */
142
+ const agentDirNames = (): string[] => [CREDENTIAL_FILE_BASENAMES["plugin-credentials"], ...PI_AGENT_SECRET_FILES];
143
+
144
+ /** Protected files under `~/.pi/agent` and `~/.pi/dashboard` (home-relative, always on). */
145
+ const homeProtected = (): string[] => [
146
+ ...agentDirNames().map((n) => nodePath.join(deps.homedir, ".pi", "agent", ...n.split("/"))),
147
+ nodePath.join(deps.homedir, ".pi", "dashboard", CREDENTIAL_FILE_BASENAMES.vault),
148
+ ];
149
+
150
+ /**
151
+ * Protected files named by the environment: `PI_CODING_AGENT_DIR` copies and the data-key
152
+ * file. Built from `deps.env` only, never from the path gate's `res.agentDir` (the guard
153
+ * has no access to it).
154
+ */
155
+ const envProtected = (): string[] => {
156
+ const out: string[] = [];
157
+ const agentDir = configuredAgentDir();
158
+ if (agentDir) for (const n of agentDirNames()) out.push(nodePath.resolve(agentDir, ...n.split("/")));
159
+ const keyFile = deps.env[DATA_KEY_FILE_ENV];
160
+ if (keyFile) out.push(nodePath.resolve(keyFile));
161
+ return out;
162
+ };
163
+
164
+ /** Protected files, lexical (env read per call: cheap, and always current). */
165
+ const protectedLexical = (): string[] => [...homeProtected(), ...envProtected()];
166
+
167
+ /**
168
+ * Canonical forms of the protected files. Each distinct directory is canonicalised once; a file
169
+ * that is not itself a symlink is `canonical(dir)/<name>` (identical to canonicalising the file:
170
+ * a missing or regular file adds nothing to its parent's real path), and a symlinked file takes the
171
+ * full `canonicalize` (it follows the link). Keeps the per-call cost flat as the protected set grows.
172
+ */
173
+ const canonicalProtected = (env: ResolveEnv): string[] => {
174
+ const dirs = new Map<string, string>();
175
+ return protectedLexical().map((file) => {
176
+ // `lexists` (non-throwing) first: most protected files do not exist, and a thrown ENOENT per file is the cost.
177
+ const isLink = env.isSymlink ? (env.lexists ? env.lexists(file) && env.isSymlink(file) : env.isSymlink(file)) : true;
178
+ if (isLink) return canonicalize(file, env);
179
+ const dir = env.path.dirname(file);
180
+ let real = dirs.get(dir);
181
+ if (real === undefined) {
182
+ real = canonicalize(dir, env);
183
+ dirs.set(dir, real);
184
+ }
185
+ return env.path.join(real, env.path.basename(file));
186
+ });
187
+ };
188
+
189
+ /**
190
+ * The env-configured paths AS WRITTEN (not resolved). On win32 a POSIX-style value
191
+ * (`/home/pi/.pi-key/data-key`) resolves to `D:\home\...`, which a command quoting
192
+ * the configured string never contains; text rules match both forms.
193
+ */
194
+ const configuredLexical = (): string[] => {
195
+ const out: string[] = [];
196
+ // Both spellings: a text mention may carry the literal `~/…` form or the expanded one.
197
+ for (const agentDir of new Set([deps.env.PI_CODING_AGENT_DIR?.trim(), configuredAgentDir()])) {
198
+ if (agentDir) for (const n of agentDirNames()) out.push(`${agentDir.replace(/[\\/]+$/, "")}/${n}`);
199
+ }
200
+ const keyFile = deps.env[DATA_KEY_FILE_ENV];
201
+ if (keyFile) out.push(keyFile);
202
+ return out;
203
+ };
204
+
205
+ const block = (tool: string, rule: CredentialGuardRule): GuardResult => {
206
+ log(`[credential-guard] blocked tool=${safeName(tool)} match=${rule}`);
207
+ return { block: true, reason: `credential_guard: ${safeName(tool)} targets dashboard credential storage` };
208
+ };
209
+
210
+ /** Path rule on one canonical target; `isGrep` adds the directory rule. */
211
+ function pathRule(canonical: string, protectedCanon: string[], isGrep: boolean): CredentialGuardRule | undefined {
212
+ const t = fold(canonical);
213
+ const dir = fold(nodePath.dirname(canonical));
214
+ const base = fold(nodePath.basename(canonical));
215
+ for (const p of protectedCanon) {
216
+ const pf = fold(p);
217
+ if (t === pf) return "path";
218
+ // sibling `<name>.*` in the same directory (lock, temp, .corrupt-*, .undecryptable-*)
219
+ if (dir === fold(nodePath.dirname(p)) && base.startsWith(`${fold(nodePath.basename(p))}.`)) return "path";
220
+ if (isGrep && t === fold(nodePath.dirname(p))) return "grep-dir";
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ function decidePath(tool: string, input: Record<string, unknown>, ctx: GuardCtx): CredentialGuardRule | undefined {
226
+ if (!(PATH_TOOLS as readonly string[]).includes(tool)) return undefined;
227
+ const cwd = ctx.cwd || process.cwd();
228
+ const raw = targetPathOf(tool, input, cwd);
229
+ if (raw === undefined) return undefined;
230
+ const env = resolveEnv();
231
+ const protectedCanon = canonicalProtected(env);
232
+ const resolved = resolveToolPath(raw, cwd, env);
233
+ const targets = [canonicalize(resolved, env)];
234
+ if (tool === "read") targets.push(canonicalize(resolveReadTarget(resolved, env), env));
235
+ for (const t of targets) {
236
+ const rule = pathRule(t, protectedCanon, tool === "grep");
237
+ if (rule) return rule;
238
+ }
239
+ return undefined;
240
+ }
241
+
242
+ function textRule(s: string, needles: string[]): CredentialGuardRule | undefined {
243
+ const n = norm(s);
244
+ if (needles.some((needle) => n.includes(needle))) return "text-path";
245
+ if (n.includes(CREDENTIAL_KEYCHAIN_SERVICE) && KEYCHAIN_VERBS.some((v) => n.includes(v))) return "text-keychain";
246
+ if (DUMP_RE.test(s)) return "text-dump";
247
+ if (DECRYPT_RE.test(s)) return "text-decrypt";
248
+ return undefined;
249
+ }
250
+
251
+ function decideText(tool: string, input: unknown): CredentialGuardRule | undefined {
252
+ const strings: string[] = [];
253
+ if (!collectScanned(input, false, CONTENT_TOOLS.has(tool), 0, strings)) return "depth";
254
+ if (strings.length === 0) return undefined;
255
+ // Explicit list (no index coupling to `protectedLexical()`): the literal `.pi/agent/<name>`
256
+ // and `.pi/dashboard/vault.json` references, the env-named paths, and the env paths as written.
257
+ const needles = [
258
+ ...agentDirNames().map((n) => `.pi/agent/${n}`),
259
+ `.pi/dashboard/${CREDENTIAL_FILE_BASENAMES.vault}`,
260
+ ...envProtected().map(norm),
261
+ ...configuredLexical().map(norm),
262
+ ];
263
+ for (const s of strings) {
264
+ const rule = textRule(s, needles);
265
+ if (rule) return rule;
266
+ }
267
+ return undefined;
268
+ }
269
+
270
+ function handler(event: GuardEvent, ctx: GuardCtx): GuardResult {
271
+ const tool = typeof event?.toolName === "string" ? event.toolName : "";
272
+ try {
273
+ const input = event?.input ?? {};
274
+ const asRecord = (input && typeof input === "object" ? input : {}) as Record<string, unknown>;
275
+ const rule = decidePath(tool, asRecord, ctx ?? {}) ?? decideText(tool, input);
276
+ return rule ? block(tool, rule) : undefined;
277
+ } catch {
278
+ // Fail closed for THIS call only; never log the error text (it may carry a path).
279
+ log(`[credential-guard] error tool=${safeName(tool)}`);
280
+ return { block: true, reason: `credential_guard: ${safeName(tool)} could not be checked` };
281
+ }
282
+ }
283
+
284
+ return { handler };
285
+ }
286
+
287
+ /**
288
+ * The `tool_call` handler `bridge.ts` registers: a no-op for a stale bridge
289
+ * instance (after /reload), otherwise the guard. Deliberately NOT wrapped in the
290
+ * fail-open `safe()`: the guard itself maps an internal error to a block.
291
+ */
292
+ export function createCredentialGuardToolCallHandler(
293
+ guard: ReturnType<typeof createCredentialGuard>,
294
+ isActive: () => boolean,
295
+ ): (event: GuardEvent, ctx: GuardCtx) => GuardResult {
296
+ return (event, ctx) => {
297
+ if (!isActive()) return undefined;
298
+ return guard.handler(event, ctx);
299
+ };
300
+ }