@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
@@ -0,0 +1,555 @@
1
+ /**
2
+ * `pi-dashboard credentials status|decrypt|reset` (design D7, D8, D11; decisions
3
+ * G6, G10, G11). Local-only: no HTTP route, no value ever printed. Output carries
4
+ * file basenames, state tokens, reason codes and the key `kid` only; errors are
5
+ * reduced to an errno-style code (never a message that could echo content).
6
+ *
7
+ * - `status` read-only. Reads the keychain only when a credential file exists
8
+ * and NEVER creates a key.
9
+ * - `decrypt` rollback: refuse on any live server, confirm, hold BOTH store locks
10
+ * (plugin-credentials → vault) for the run, decode ALL files before
11
+ * writing ANY, rewrite each as 0600 plaintext.
12
+ * - `reset` key loss: same server check + confirm + locks; rename the LOCKED
13
+ * file(s) to `<basename>.undecryptable-<stamp>`; release the store
14
+ * locks; only THEN (keychain source, no key, no envelope left) create
15
+ * a key under `credential-key.lock`. Never creates a key file.
16
+ *
17
+ * Lock order matches the server (D4): store locks and the key-creation lock are
18
+ * never held together. See change: encrypt-credentials-at-rest (task 8.1).
19
+ */
20
+
21
+ import fs from "node:fs";
22
+ import os from "node:os";
23
+ import path from "node:path";
24
+ import readline from "node:readline";
25
+ import {
26
+ CREDENTIAL_FILE_BASENAMES,
27
+ CREDENTIAL_FILE_IDS,
28
+ type CredentialFileId,
29
+ DATA_KEY_FILE_ENV,
30
+ } from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
31
+ import { localDialHost } from "@blackbelt-technology/pi-dashboard-shared/local-credential-proof.js";
32
+ import { classify, type EnvelopeClass } from "../auth/credential-envelope.js";
33
+ import {
34
+ type CredentialFilesProbe,
35
+ type CredentialKeyState,
36
+ getCredentialCodec,
37
+ getCredentialKeyState,
38
+ type InitCredentialKeyOptions,
39
+ initCredentialKey,
40
+ resetCredentialKeyState,
41
+ } from "../auth/credential-key.js";
42
+ import { acquireLock, writeJsonAtomic } from "../auth/locked-json-file.js";
43
+ import { getLockPath, getMetaPath, type LockMetadata, readMetadata } from "../lifecycle/home-lock.js";
44
+ import { isProcessAlive as defaultIsProcessAlive, readPid } from "../spawn-process/server-pid.js";
45
+
46
+ export const CREDENTIALS_USAGE =
47
+ "usage: pi-dashboard credentials status | decrypt [--yes] | reset [--vault] [--plugin-credentials] [--yes]";
48
+
49
+ /** Exit codes: 0 ok, 1 refused or any file failed, 2 usage. */
50
+ const CREDENTIALS_EXIT = { ok: 0, failed: 1, usage: 2 } as const;
51
+
52
+ const LOCK_BUDGET_MS = 2_000;
53
+ const HEALTH_TIMEOUT_MS = 3_000;
54
+ /** Flags `buildConfig` consumes (and their values) that may precede the verb. */
55
+ const CONFIG_VALUE_FLAGS: ReadonlySet<string> = new Set(["--port", "--host", "--pi-port"]);
56
+
57
+ /** Injectable seams (tests); production passes none. */
58
+ export interface CredentialsDeps {
59
+ /** Default `os.homedir()`. */
60
+ homeDir?: string;
61
+ /** Default `process.env`. */
62
+ env?: NodeJS.ProcessEnv;
63
+ out?: (line: string) => void;
64
+ err?: (line: string) => void;
65
+ fetchImpl?: typeof fetch;
66
+ /** `/api/health` bound (ms). Default 3000. */
67
+ timeoutMs?: number;
68
+ /** Default: `<home>/.pi/dashboard/server.pid`. */
69
+ readPid?: () => number | null;
70
+ isProcessAlive?: (pid: number) => boolean;
71
+ /** Default: the per-HOME lock metadata under `<home>/.pi/dashboard`. */
72
+ readLockMeta?: () => LockMetadata | null;
73
+ /** Interactive confirmation: `isTTY` selects the prompt. Default `process.stdin`. */
74
+ stdin?: { isTTY?: boolean };
75
+ prompt?: (question: string) => Promise<string>;
76
+ /** Default `new Date()` (the `.undecryptable-<stamp>`). */
77
+ now?: () => Date;
78
+ /** Key-source seams forwarded to `initCredentialKey` (stub keychain / stub worker in tests, D9). */
79
+ keyOptions?: Pick<
80
+ InitCredentialKeyOptions,
81
+ "entryFactory" | "workerEntry" | "workerData" | "workerFactory" | "platform" | "deadlineMs" | "lockTarget"
82
+ >;
83
+ /** Test seam: runs once BOTH store locks are held, before any file is read. */
84
+ afterLocked?: () => void | Promise<void>;
85
+ }
86
+
87
+ type Verb = "status" | "decrypt" | "reset";
88
+ interface Parsed {
89
+ verb: Verb;
90
+ yes: boolean;
91
+ vault: boolean;
92
+ plugin: boolean;
93
+ }
94
+
95
+ interface Ctx {
96
+ home: string;
97
+ env: NodeJS.ProcessEnv;
98
+ out: (line: string) => void;
99
+ err: (line: string) => void;
100
+ deps: CredentialsDeps;
101
+ port: number;
102
+ host: string | undefined;
103
+ files: FileSpec[];
104
+ }
105
+
106
+ interface FileSpec {
107
+ id: CredentialFileId;
108
+ name: string;
109
+ file: string;
110
+ }
111
+
112
+ /** Lock order: plugin credentials first, then vault (D7). `CREDENTIAL_FILE_IDS` is already in that order. */
113
+ function credentialFiles(home: string): FileSpec[] {
114
+ const dirOf = (id: CredentialFileId) => (id === "vault" ? path.join(home, ".pi", "dashboard") : path.join(home, ".pi", "agent"));
115
+ return CREDENTIAL_FILE_IDS.map((id) => ({
116
+ id,
117
+ name: CREDENTIAL_FILE_BASENAMES[id],
118
+ file: path.join(dirOf(id), CREDENTIAL_FILE_BASENAMES[id]),
119
+ }));
120
+ }
121
+
122
+ // ── argv ────────────────────────────────────────────────────────────
123
+
124
+ const FLAG_KEYS: Readonly<Record<string, "yes" | "vault" | "plugin">> = {
125
+ "--yes": "yes",
126
+ "-y": "yes",
127
+ "--vault": "vault",
128
+ "--plugin-credentials": "plugin",
129
+ };
130
+ const isVerb = (v: string | undefined): v is Verb => v === "status" || v === "decrypt" || v === "reset";
131
+
132
+ type Scanned = { words: string[]; set: { yes: boolean; vault: boolean; plugin: boolean } } | { error: string };
133
+
134
+ function scanArgs(argv: readonly string[]): Scanned {
135
+ const set = { yes: false, vault: false, plugin: false };
136
+ const words: string[] = [];
137
+ for (let i = 0; i < argv.length; i++) {
138
+ const a = argv[i] as string;
139
+ if (CONFIG_VALUE_FLAGS.has(a)) { i++; continue; }
140
+ const key = FLAG_KEYS[a];
141
+ if (key) set[key] = true;
142
+ else if (a.startsWith("-")) return { error: `unknown flag '${a.slice(0, 40)}'` };
143
+ else words.push(a);
144
+ }
145
+ return { words, set };
146
+ }
147
+
148
+ function parseCredentialsArgs(argv: readonly string[]): Parsed | { error: string } {
149
+ const scanned = scanArgs(argv);
150
+ if ("error" in scanned) return scanned;
151
+ const { words, set } = scanned;
152
+ const verb = words[0];
153
+ if (words.length > 1) return { error: "expected exactly one verb" };
154
+ if (!isVerb(verb)) return { error: verb === undefined ? "missing verb" : `unknown verb '${verb.slice(0, 40)}'` };
155
+ if (verb === "status" && (set.yes || set.vault || set.plugin)) return { error: "status takes no flags" };
156
+ if (verb === "decrypt" && (set.vault || set.plugin)) return { error: "--vault/--plugin-credentials apply to reset only" };
157
+ return { verb, ...set };
158
+ }
159
+
160
+ // ── helpers ─────────────────────────────────────────────────────────
161
+
162
+ /** An errno-style code, never an error message (messages can echo paths or content). */
163
+ const codeOf = (e: unknown): string => {
164
+ const c = (e as { code?: unknown } | null)?.code;
165
+ return typeof c === "string" && /^[A-Z0-9_]{2,32}$/.test(c) ? c : "error";
166
+ };
167
+
168
+ function readBytes(file: string): Buffer | null {
169
+ try {
170
+ return fs.readFileSync(file);
171
+ } catch (e) {
172
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return null;
173
+ throw e;
174
+ }
175
+ }
176
+
177
+ function classOf(file: string): EnvelopeClass {
178
+ try {
179
+ return classify(readBytes(file));
180
+ } catch {
181
+ return "corrupt";
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Resolve the key for THIS command from a fresh singleton. `map` rewrites what the
187
+ * key module believes is on disk, so the command never triggers a creation it did
188
+ * not mean to (`status`/`decrypt`/`reset`'s first pass never create a key):
189
+ * - `plaintext→absent`: only envelopes make the module touch the keychain;
190
+ * - `plaintext→envelope`: any file counts, but a missing key is read-only `key_missing`;
191
+ * - `absent→plaintext`: the creating pass of `reset` (an envelope still blocks creation).
192
+ */
193
+ async function freshInit(ctx: Ctx, map: (c: EnvelopeClass) => EnvelopeClass): Promise<CredentialKeyState> {
194
+ // One-shot CLI process, but the singleton may carry an earlier state (tests, repeated runs).
195
+ resetCredentialKeyState();
196
+ const filesProbe = (): CredentialFilesProbe => {
197
+ const p = {} as CredentialFilesProbe;
198
+ for (const f of ctx.files) p[f.id] = map(classOf(f.file));
199
+ return p;
200
+ };
201
+ return initCredentialKey({
202
+ ...ctx.deps.keyOptions,
203
+ env: ctx.env,
204
+ homeDir: ctx.home,
205
+ filesProbe,
206
+ log: () => {},
207
+ });
208
+ }
209
+
210
+ // ── running-server check (D7 step 1, G11) ───────────────────────────
211
+
212
+ const isRefused = (e: unknown): boolean => {
213
+ const err = e as { code?: unknown; cause?: { code?: unknown } } | null;
214
+ return err?.code === "ECONNREFUSED" || err?.cause?.code === "ECONNREFUSED";
215
+ };
216
+
217
+ /**
218
+ * `null` = no live server. Any HTTP reply (401 included) refuses; ONLY a refused
219
+ * connection proceeds (timeout, reset or any other outcome cannot prove absence).
220
+ * A live pid named by `server.pid` or the per-HOME lock metadata also refuses,
221
+ * so a second dashboard on another port cannot re-encrypt the files afterwards.
222
+ */
223
+ async function liveServerRefusal(ctx: Ctx): Promise<string | null> {
224
+ const { deps } = ctx;
225
+ const alive = deps.isProcessAlive ?? defaultIsProcessAlive;
226
+ const pidPath = path.join(ctx.home, ".pi", "dashboard", "server.pid");
227
+ const pid = (deps.readPid ?? (() => readPid({ pidPath })))();
228
+ if (pid !== null && alive(pid)) {
229
+ return `[credentials] a dashboard server of this HOME is running (pid ${pid}); stop it first`;
230
+ }
231
+ const meta = (deps.readLockMeta ?? (() => readMetadata(getMetaPath(getLockPath(ctx.home)))))();
232
+ if (meta && Number.isInteger(meta.pid) && alive(meta.pid)) {
233
+ return `[credentials] a dashboard server of this HOME is running (pid ${meta.pid}, port ${meta.httpPort}); stop it first`;
234
+ }
235
+ if (!(ctx.port > 0)) return null; // port 0 (temp-HOME guard): nothing to dial
236
+ const url = `http://${localDialHost(ctx.host)}:${ctx.port}/api/health`;
237
+ try {
238
+ const res = await (deps.fetchImpl ?? fetch)(url, { signal: AbortSignal.timeout(deps.timeoutMs ?? HEALTH_TIMEOUT_MS) });
239
+ await res.body?.cancel().catch(() => undefined);
240
+ return `[credentials] a server answers on port ${ctx.port} (HTTP ${res.status}); stop it first`;
241
+ } catch (e) {
242
+ if (isRefused(e)) return null;
243
+ return `[credentials] cannot confirm that no server runs on port ${ctx.port} (${codeOf(e)}); stop it first`;
244
+ }
245
+ }
246
+
247
+ // ── confirmation ────────────────────────────────────────────────────
248
+
249
+ async function defaultPrompt(question: string): Promise<string> {
250
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
251
+ try {
252
+ return await new Promise<string>((resolve) => rl.question(question, resolve));
253
+ } finally {
254
+ rl.close();
255
+ }
256
+ }
257
+
258
+ /** `--yes`, or a `y`/`yes` answer on a TTY. No TTY and no `--yes` refuses. */
259
+ async function confirmed(ctx: Ctx, question: string, yes: boolean): Promise<boolean> {
260
+ if (yes) return true;
261
+ const stdin = ctx.deps.stdin ?? process.stdin;
262
+ if (!stdin.isTTY) {
263
+ ctx.err("[credentials] confirmation needed: run in a terminal or pass --yes; nothing changed");
264
+ return false;
265
+ }
266
+ const answer = (await (ctx.deps.prompt ?? defaultPrompt)(question)).trim().toLowerCase();
267
+ if (answer === "y" || answer === "yes") return true;
268
+ ctx.err("[credentials] aborted; nothing changed");
269
+ return false;
270
+ }
271
+
272
+ // ── store locks (plugin-credentials → vault) ────────────────────────
273
+
274
+ /**
275
+ * Hold BOTH store locks, in file order, for the whole of `fn`. Released in reverse.
276
+ * `fn` gets a probe naming a store whose lock was reported compromised (stale-stolen by
277
+ * another process): every write site checks it first and writes nothing more.
278
+ */
279
+ async function withStoreLocks(ctx: Ctx, fn: (compromised: () => string | undefined) => Promise<number>): Promise<number> {
280
+ const released: Array<() => Promise<void>> = [];
281
+ let compromised: string | undefined;
282
+ try {
283
+ for (const f of ctx.files) {
284
+ fs.mkdirSync(path.dirname(f.file), { recursive: true });
285
+ try {
286
+ released.push(
287
+ await acquireLock(f.file, LOCK_BUDGET_MS, () => {
288
+ compromised ??= f.name;
289
+ }),
290
+ );
291
+ } catch (e) {
292
+ ctx.err(`[credentials] cannot lock ${f.name} (${codeOf(e)}); is another process writing it? nothing changed`);
293
+ return CREDENTIALS_EXIT.failed;
294
+ }
295
+ }
296
+ await ctx.deps.afterLocked?.();
297
+ return await fn(() => compromised);
298
+ } finally {
299
+ for (const release of released.reverse()) {
300
+ try { await release(); } catch { /* ignore cleanup errors */ }
301
+ }
302
+ }
303
+ }
304
+
305
+ // ── status ──────────────────────────────────────────────────────────
306
+
307
+ function countSiblings(f: FileSpec, kind: "corrupt" | "undecryptable"): number {
308
+ try {
309
+ const prefix = `${f.name}.${kind}-`;
310
+ return fs.readdirSync(path.dirname(f.file)).filter((n) => n.startsWith(prefix)).length;
311
+ } catch {
312
+ return 0;
313
+ }
314
+ }
315
+
316
+ function fileStateLine(f: FileSpec): string {
317
+ let bytes: Buffer | null;
318
+ try {
319
+ bytes = readBytes(f.file);
320
+ } catch (e) {
321
+ return `${f.name}: unreadable ${codeOf(e)}`;
322
+ }
323
+ if (bytes === null) return `${f.name}: absent`;
324
+ const out = getCredentialCodec(f.id).decode(bytes);
325
+ if (out.kind === "absent") return `${f.name}: absent`;
326
+ if (out.kind === "locked") return `${f.name}: locked ${out.reason}`;
327
+ if (out.kind === "corrupt") return `${f.name}: corrupt`;
328
+ return `${f.name}: ${out.encrypted ? "encrypted" : "plaintext"}`;
329
+ }
330
+
331
+ async function runStatus(ctx: Ctx): Promise<number> {
332
+ const classes = ctx.files.map((f) => classOf(f.file));
333
+ // Any existing file makes the key module read the key; a missing key stays a read-only `key_missing`.
334
+ let st = await freshInit(ctx, (c) => (c === "plaintext" ? "envelope" : c));
335
+ const encryptedOnDisk = classes.some((c) => c === "envelope" || c === "unsupported" || c === "damaged");
336
+ const keyFile = Boolean(ctx.env[DATA_KEY_FILE_ENV]);
337
+ // Plaintext only and no key yet: the server creates it on its next start/write. Not a failure.
338
+ if (st.state === "unavailable" && st.reason === "key_missing" && !keyFile && !encryptedOnDisk) {
339
+ st = { state: "deferred", source: "keychain" };
340
+ }
341
+ const source = st.state === "deferred" ? "keychain" : st.state === "uninitialized" ? "keychain" : st.source;
342
+ const parts = [`source=${source}`, `state=${st.state}`];
343
+ if (st.state === "unavailable") parts.push(`reason=${st.reason}`);
344
+ if (st.state === "ready") parts.push(`kid=${st.kid}`);
345
+ ctx.out(parts.join(" "));
346
+ for (const f of ctx.files) ctx.out(fileStateLine(f));
347
+ const corrupt = ctx.files.reduce((n, f) => n + countSiblings(f, "corrupt"), 0);
348
+ const undecryptable = ctx.files.reduce((n, f) => n + countSiblings(f, "undecryptable"), 0);
349
+ ctx.out(`corrupt=${corrupt} undecryptable=${undecryptable}`);
350
+ return CREDENTIALS_EXIT.ok;
351
+ }
352
+
353
+ // ── decrypt ─────────────────────────────────────────────────────────
354
+
355
+ type DecryptPlan =
356
+ | { kind: "decrypt"; f: FileSpec; doc: Record<string, unknown> }
357
+ | { kind: "result"; f: FileSpec; line: string; failed: boolean }
358
+ | { kind: "blocked"; f: FileSpec; reason: string };
359
+
360
+ function planDecrypt(f: FileSpec): DecryptPlan {
361
+ let bytes: Buffer | null;
362
+ try {
363
+ bytes = readBytes(f.file);
364
+ } catch (e) {
365
+ return { kind: "blocked", f, reason: codeOf(e) };
366
+ }
367
+ if (bytes === null) return { kind: "result", f, line: `${f.name}: absent`, failed: false };
368
+ const out = getCredentialCodec(f.id).decode(bytes);
369
+ if (out.kind === "absent") return { kind: "result", f, line: `${f.name}: absent`, failed: false };
370
+ if (out.kind === "locked") return { kind: "blocked", f, reason: out.reason };
371
+ if (out.kind === "corrupt") return { kind: "result", f, line: `${f.name}: failed corrupt`, failed: true };
372
+ if (!out.encrypted) return { kind: "result", f, line: `${f.name}: already-plaintext`, failed: false };
373
+ return { kind: "decrypt", f, doc: out.data };
374
+ }
375
+
376
+ /** Atomic plaintext rewrite (0600). A failed rename must not leave a plaintext `.tmp` behind. */
377
+ function writePlaintext(f: FileSpec, doc: Record<string, unknown>): string | null {
378
+ try {
379
+ writeJsonAtomic(f.file, doc, 0o600);
380
+ return null;
381
+ } catch (e) {
382
+ try { fs.rmSync(`${f.file}.tmp`, { force: true }); } catch { /* best effort */ }
383
+ return codeOf(e);
384
+ }
385
+ }
386
+
387
+ async function runDecrypt(ctx: Ctx, parsed: Parsed): Promise<number> {
388
+ const refusal = await liveServerRefusal(ctx);
389
+ if (refusal) { ctx.err(refusal); return CREDENTIALS_EXIT.failed; }
390
+ if (!(await confirmed(ctx, "Rewrite the encrypted credential files as PLAINTEXT? [y/N] ", parsed.yes))) {
391
+ return CREDENTIALS_EXIT.failed;
392
+ }
393
+ // Only envelopes need the key; plaintext-only hosts never touch the keychain here.
394
+ await freshInit(ctx, (c) => (c === "plaintext" ? "absent" : c));
395
+ return withStoreLocks(ctx, async (compromised) =>
396
+ applyDecrypt(ctx, ctx.files.map(planDecrypt), compromised) ? CREDENTIALS_EXIT.failed : CREDENTIALS_EXIT.ok,
397
+ );
398
+ }
399
+
400
+ /**
401
+ * Report (and, only when EVERY file decoded, write) the plans. All-or-nothing:
402
+ * one blocked file means no write at all. Returns `true` when any file is not decrypted.
403
+ */
404
+ function applyDecrypt(ctx: Ctx, plans: DecryptPlan[], compromised: () => string | undefined): boolean {
405
+ const blocked = plans.some((p) => p.kind === "blocked");
406
+ let failed = blocked;
407
+ for (const p of plans) {
408
+ if (p.kind === "result") {
409
+ ctx.out(p.line);
410
+ failed ||= p.failed;
411
+ } else if (p.kind === "blocked") {
412
+ ctx.out(`${p.f.name}: failed ${p.reason}`);
413
+ } else if (blocked) {
414
+ ctx.out(`${p.f.name}: failed not-written`);
415
+ } else if (lockLost(ctx, p.f, compromised)) {
416
+ failed = true;
417
+ } else {
418
+ const code = writePlaintext(p.f, p.doc);
419
+ ctx.out(code === null ? `${p.f.name}: decrypted` : `${p.f.name}: failed ${code}`);
420
+ failed ||= code !== null;
421
+ }
422
+ }
423
+ return failed;
424
+ }
425
+
426
+ /** True (and reported) when a store lock was compromised: the caller writes nothing for `f`. */
427
+ function lockLost(ctx: Ctx, f: FileSpec, compromised: () => string | undefined): boolean {
428
+ const lost = compromised();
429
+ if (!lost) return false;
430
+ ctx.out(`${f.name}: failed lock-compromised`);
431
+ ctx.err(`[credentials] ${lost} lock compromised (another process took it); ${f.name} not written`);
432
+ return true;
433
+ }
434
+
435
+ // ── reset ───────────────────────────────────────────────────────────
436
+
437
+ /** `YYYYMMDDTHHMMSSZ` (G6). */
438
+ const stampOf = (d: Date): string => d.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
439
+
440
+ /** Rename `file` aside to `<file>.undecryptable-<stamp>[-N]`; returns the backup basename. Never overwrites. */
441
+ function renameAside(file: string, stamp: string): string {
442
+ const base = `${file}.undecryptable-${stamp}`;
443
+ let target = base;
444
+ for (let n = 1; fs.existsSync(target); n++) target = `${base}-${n}`;
445
+ fs.renameSync(file, target);
446
+ return path.basename(target);
447
+ }
448
+
449
+ function resetFile(ctx: Ctx, f: FileSpec, stamp: string): { line: string; renamed: boolean; failed: boolean } {
450
+ let bytes: Buffer | null;
451
+ try {
452
+ bytes = readBytes(f.file);
453
+ } catch (e) {
454
+ return { line: `${f.name}: failed ${codeOf(e)}`, renamed: false, failed: true };
455
+ }
456
+ const out = bytes === null ? { kind: "absent" as const } : getCredentialCodec(f.id).decode(bytes);
457
+ if (out.kind !== "locked") return { line: `${f.name}: not-locked`, renamed: false, failed: false };
458
+ try {
459
+ return { line: `${f.name}: reset (kept as ${renameAside(f.file, stamp)})`, renamed: true, failed: false };
460
+ } catch (e) {
461
+ return { line: `${f.name}: failed ${codeOf(e)}`, renamed: false, failed: true };
462
+ }
463
+ }
464
+
465
+ /** After the store locks are released: remedy for a key file, or create the keychain key (E76). */
466
+ async function afterReset(ctx: Ctx, first: CredentialKeyState): Promise<number> {
467
+ const keyFile = ctx.env[DATA_KEY_FILE_ENV];
468
+ if (keyFile) {
469
+ const st = getCredentialKeyState();
470
+ if (st.state !== "unavailable") return CREDENTIALS_EXIT.ok;
471
+ // The server never creates a key file. An insecure file may hold the right key: do not suggest overwriting it.
472
+ ctx.out(
473
+ st.reason === "key_file_insecure"
474
+ ? `chmod 600 ${keyFile}`
475
+ : `openssl rand -base64 32 > ${keyFile}; chmod 600 ${keyFile}`,
476
+ );
477
+ ctx.err(`[credentials] the key file is not usable (${st.reason}); the server refuses credential writes until it is`);
478
+ return CREDENTIALS_EXIT.failed;
479
+ }
480
+ if (first.state !== "unavailable") return CREDENTIALS_EXIT.ok; // a key exists (or nothing to resolve)
481
+ if (first.reason !== "key_missing") {
482
+ ctx.err(`[credentials] no key was created (${first.reason}); fix the key source and restart the server`);
483
+ return CREDENTIALS_EXIT.failed;
484
+ }
485
+ // Fresh singleton: creates under `credential-key.lock` unless an envelope still blocks creation.
486
+ const second = await freshInit(ctx, (c) => (c === "absent" ? "plaintext" : c));
487
+ if (second.state === "ready" && second.created) ctx.out("key: created");
488
+ else if (second.state === "unavailable" && second.reason !== "key_missing") {
489
+ ctx.err(`[credentials] no key was created (${second.reason}); fix the key source and restart the server`);
490
+ return CREDENTIALS_EXIT.failed;
491
+ }
492
+ return CREDENTIALS_EXIT.ok;
493
+ }
494
+
495
+ async function runReset(ctx: Ctx, parsed: Parsed): Promise<number> {
496
+ const refusal = await liveServerRefusal(ctx);
497
+ if (refusal) { ctx.err(refusal); return CREDENTIALS_EXIT.failed; }
498
+ if (!(await confirmed(ctx, "Rename the undecryptable credential file(s) aside? [y/N] ", parsed.yes))) {
499
+ return CREDENTIALS_EXIT.failed;
500
+ }
501
+ const both = !parsed.vault && !parsed.plugin;
502
+ const inScope = (f: FileSpec) => both || (f.id === "vault" ? parsed.vault : parsed.plugin);
503
+ let renamed = 0;
504
+ let failed = false;
505
+ const stamp = stampOf((ctx.deps.now ?? (() => new Date()))());
506
+ // First pass never creates a key: only an envelope makes the module read the keychain.
507
+ const first = await freshInit(ctx, (c) => (c === "plaintext" ? "absent" : c));
508
+ const locksCode = await withStoreLocks(ctx, async (compromised) => {
509
+ for (const f of ctx.files) {
510
+ if (!inScope(f)) continue;
511
+ if (lockLost(ctx, f, compromised)) {
512
+ failed = true;
513
+ continue;
514
+ }
515
+ const r = resetFile(ctx, f, stamp);
516
+ ctx.out(r.line);
517
+ if (r.renamed) renamed++;
518
+ failed ||= r.failed;
519
+ }
520
+ return CREDENTIALS_EXIT.ok;
521
+ });
522
+ // Store locks are released here (withStoreLocks' finally) BEFORE any key creation.
523
+ if (locksCode !== CREDENTIALS_EXIT.ok) return locksCode;
524
+ if (renamed === 0) return failed ? CREDENTIALS_EXIT.failed : CREDENTIALS_EXIT.ok;
525
+ const after = await afterReset(ctx, first);
526
+ return failed ? CREDENTIALS_EXIT.failed : after;
527
+ }
528
+
529
+ // ── entry ───────────────────────────────────────────────────────────
530
+
531
+ /** Returns the process exit code. `argv` = everything but the `credentials` word. */
532
+ export async function cmdCredentials(
533
+ argv: readonly string[],
534
+ opts: { port: number; host?: string },
535
+ deps: CredentialsDeps = {},
536
+ ): Promise<number> {
537
+ const out = deps.out ?? ((l: string) => console.log(l));
538
+ const err = deps.err ?? ((l: string) => console.error(l));
539
+ const parsed = parseCredentialsArgs(argv);
540
+ if ("error" in parsed) {
541
+ err(`[credentials] ${parsed.error}`);
542
+ err(CREDENTIALS_USAGE);
543
+ return CREDENTIALS_EXIT.usage;
544
+ }
545
+ const home = deps.homeDir ?? os.homedir();
546
+ const ctx: Ctx = { home, env: deps.env ?? process.env, out, err, deps, port: opts.port, host: opts.host, files: credentialFiles(home) };
547
+ try {
548
+ if (parsed.verb === "status") return await runStatus(ctx);
549
+ if (parsed.verb === "decrypt") return await runDecrypt(ctx, parsed);
550
+ return await runReset(ctx, parsed);
551
+ } catch (e) {
552
+ err(`[credentials] ${parsed.verb} failed (${codeOf(e)})`);
553
+ return CREDENTIALS_EXIT.failed;
554
+ }
555
+ }
@@ -62,8 +62,9 @@ import {
62
62
  } from "@blackbelt-technology/pi-dashboard-shared/server-launcher.js";
63
63
  import { terminalSafe } from "@blackbelt-technology/pi-dashboard-shared/terminal-safe.js";
64
64
  import { defaultLocalTokenDir, ensureLocalToken, readLocalTokenIfPresent } from "./auth/local-token.js";
65
- import { migrateSubagentTickThrottle } from "./config-api.js";
66
65
  import { classifyDashboardPort, type PortClassification } from "./lifecycle/classify-dashboard-port.js";
66
+ import { settleThenExit } from "./lifecycle/credential-exit-barrier.js";
67
+ import { createExitSignalHandler } from "./lifecycle/exit-signal.js";
67
68
  import {
68
69
  isModuleNotFoundError,
69
70
  parseModuleNotFoundError,
@@ -97,6 +98,7 @@ import {
97
98
  import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
98
99
  import { getDefaultRegistry, ingestInstalledSkillTools, resolveInstallRoot } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
99
100
  import { assertNodeVersionSupported, warnTsLoaderState } from "./auth/node-guard.js";
101
+ import { cmdCredentials } from "./cli/credentials-command.js";
100
102
  import { recordExitIntent } from "./persistence/boot-state.js";
101
103
  import { publishResolvedRuntime, readPublishedRuntimeBlock } from "./runtime-publication.js";
102
104
  import { resolveLiveSpawnRuntime } from "./runtime-resolution.js";
@@ -107,14 +109,14 @@ import { servicesPaths } from "./services/paths.js";
107
109
  const SUBCOMMANDS = ["start", "stop", "restart", "status", "runtime", "open"] as const;
108
110
  type Subcommand = (typeof SUBCOMMANDS)[number];
109
111
  /** Words dispatched to their own command (before `parseArgs`), not to a daemon subcommand. */
110
- const COMMAND_WORDS = ["token", "service", "pair", "login", "api"] as const;
112
+ const COMMAND_WORDS = ["token", "service", "pair", "login", "api", "credentials"] as const;
111
113
  type CommandWord = (typeof COMMAND_WORDS)[number];
112
114
  /** Flags whose NEXT token is their value, never the subcommand word. */
113
115
  const VALUE_FLAGS: ReadonlySet<string> = new Set(["--port", "--host", "--pi-port", "--url", "--data", "--code", "--name", "--tier"]);
114
116
 
115
117
  /** The one-line usage printed for an unknown subcommand word (exit 2). */
116
118
  export const CLI_USAGE =
117
- "usage: pi-dashboard [start|stop|restart|status|runtime|open|pair|token|service|login|api] [flags] (no word: run in the foreground)";
119
+ "usage: pi-dashboard [start|stop|restart|status|runtime|open|pair|token|service|login|api|credentials] [flags] (no word: run in the foreground)";
118
120
 
119
121
  export type ArgvClass =
120
122
  | { kind: "none" }
@@ -395,15 +397,16 @@ async function runForeground(config: ServerConfig): Promise<void> {
395
397
  // SIGTERM→SIGKILL ladder: `/api/restart` already recorded `"restart"` before
396
398
  // the ladder runs, so the later `"signal"` is a no-op.
397
399
  // See change: fix-recovery-exit-intent (D4).
398
- let signalHandled = false;
399
- const onExitSignal = (signal: NodeJS.Signals): void => {
400
- if (signalHandled) return;
401
- signalHandled = true;
402
- console.log(`[dashboard] ${signal} received — flushing and exiting`);
403
- try { recordExitIntent("signal"); } catch { /* best-effort */ }
404
- try { server.flush(); } catch { /* best-effort */ }
405
- process.exit(0);
406
- };
400
+ //
401
+ // Exit waits (bounded) for in-flight credential writes: a rotated OAuth
402
+ // single-use refresh token must not be cut off. The handler body lives in
403
+ // `lifecycle/exit-signal.ts`. See change: settle-server-credential-writes-on-exit.
404
+ const onExitSignal = createExitSignalHandler({
405
+ recordExitIntent: (intent) => recordExitIntent(intent),
406
+ flush: () => server.flush(),
407
+ settleThenExit,
408
+ log: (message) => console.log(message),
409
+ });
407
410
  process.on("SIGTERM", onExitSignal);
408
411
  process.on("SIGINT", onExitSignal);
409
412
 
@@ -1903,10 +1906,6 @@ async function main() {
1903
1906
  process.exit(2);
1904
1907
  }
1905
1908
  ensureConfig();
1906
- // One-shot: rewrite a pre-flip materialized `subagentTickThrottleMs: 0`.
1907
- // Boot path only — `loadConfig` is a pure read called by every bridge
1908
- // process. See change: heal-orphaned-tool-cards-on-session-end (design D5).
1909
- migrateSubagentTickThrottle();
1910
1909
 
1911
1910
  const rawArgs = process.argv.slice(2);
1912
1911
  const cls = classifyArgv(rawArgs);
@@ -1945,6 +1944,12 @@ async function main() {
1945
1944
  const config = buildConfig(flags, () => {});
1946
1945
  process.exit(await cmdPair(rest, { port: config.port, host: config.host }));
1947
1946
  }
1947
+ if (cls.word === "credentials") {
1948
+ // status | decrypt | reset: local-only, no value printed. See change: encrypt-credentials-at-rest (8.1).
1949
+ const { flags } = parseArgs(rest);
1950
+ const config = buildConfig(flags, () => {});
1951
+ process.exit(await cmdCredentials(rest, { port: config.port, host: config.host }));
1952
+ }
1948
1953
  if (cls.word === "login") {
1949
1954
  const { flags } = parseArgs(rest);
1950
1955
  const config = buildConfig(flags);