@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.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 (576) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +85 -11
  3. package/docs/architecture.md +3020 -116
  4. package/package.json +31 -18
  5. package/packages/extension/package.json +10 -8
  6. package/packages/extension/src/ask-user-tool.ts +65 -3
  7. package/packages/extension/src/auto-session-namer.ts +190 -50
  8. package/packages/extension/src/bridge-handlers/dispatch.ts +504 -0
  9. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  10. package/packages/extension/src/bridge-handlers/instance.ts +229 -0
  11. package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -0
  12. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  13. package/packages/extension/src/bridge-identity-log.ts +45 -0
  14. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  15. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  16. package/packages/extension/src/bridge.ts +517 -2534
  17. package/packages/extension/src/canvas-tool.ts +2 -0
  18. package/packages/extension/src/command-handler.ts +259 -16
  19. package/packages/extension/src/connect-target.ts +23 -0
  20. package/packages/extension/src/connection.ts +294 -24
  21. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  22. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  25. package/packages/extension/src/flow-event-wiring.ts +1 -1
  26. package/packages/extension/src/followup-buffer.ts +1 -1
  27. package/packages/extension/src/followup-drain.ts +79 -0
  28. package/packages/extension/src/git-link-builder.ts +11 -2
  29. package/packages/extension/src/inbound-limits.ts +138 -0
  30. package/packages/extension/src/local-token-header.ts +232 -17
  31. package/packages/extension/src/message-update-coalescer.ts +3 -1
  32. package/packages/extension/src/model-refresh.ts +88 -0
  33. package/packages/extension/src/multiselect-list.ts +6 -2
  34. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  35. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  36. package/packages/extension/src/path-gate/decide.ts +15 -41
  37. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  38. package/packages/extension/src/path-gate/handler.ts +51 -2
  39. package/packages/extension/src/path-gate/index.ts +12 -1
  40. package/packages/extension/src/path-gate/resolve.ts +6 -124
  41. package/packages/extension/src/path-gate/roots.ts +4 -1
  42. package/packages/extension/src/path-gate/suppression.ts +4 -1
  43. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  44. package/packages/extension/src/pinned-endpoint.ts +44 -0
  45. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  46. package/packages/extension/src/project-trust-live.ts +143 -0
  47. package/packages/extension/src/project-trust.ts +258 -25
  48. package/packages/extension/src/prompt-expander.ts +5 -1
  49. package/packages/extension/src/prompt-meta.ts +64 -0
  50. package/packages/extension/src/provider-register.ts +146 -38
  51. package/packages/extension/src/remote-registration-gate.ts +21 -21
  52. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  53. package/packages/extension/src/role-manager.ts +5 -4
  54. package/packages/extension/src/role-model-tools.ts +47 -6
  55. package/packages/extension/src/server-auto-start.ts +13 -6
  56. package/packages/extension/src/server-launcher.ts +11 -13
  57. package/packages/extension/src/server-proof-probe.ts +117 -0
  58. package/packages/extension/src/session-move.ts +19 -0
  59. package/packages/extension/src/session-sync.ts +73 -50
  60. package/packages/extension/src/spawn-token.ts +46 -0
  61. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  62. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  63. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  64. package/packages/extension/src/vault-delivery.ts +404 -0
  65. package/packages/extension/src/vault-forwarder.ts +128 -0
  66. package/packages/extension/src/vault-masker.ts +165 -0
  67. package/packages/extension/src/vault-redaction.ts +181 -0
  68. package/packages/extension/src/vcs-info.ts +5 -2
  69. package/packages/server/bin/pi-dashboard.mjs +26 -89
  70. package/packages/server/package.json +29 -15
  71. package/packages/server/src/access/access-grants.ts +79 -8
  72. package/packages/server/src/access/access-health.ts +10 -0
  73. package/packages/server/src/access/access-plane.ts +5 -1
  74. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  75. package/packages/server/src/access/agent-grant.ts +1 -1
  76. package/packages/server/src/access/agent-yolo.ts +91 -0
  77. package/packages/server/src/access/containment-gate.ts +82 -17
  78. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  79. package/packages/server/src/access/cwd-verdict.ts +144 -0
  80. package/packages/server/src/access/grant-coordinator.ts +3 -1
  81. package/packages/server/src/access/pi-trust-live.ts +244 -0
  82. package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
  83. package/packages/server/src/access/planes.ts +116 -2
  84. package/packages/server/src/access/preview-egress-store.ts +153 -0
  85. package/packages/server/src/access/prompt-channel.ts +5 -0
  86. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  87. package/packages/server/src/access/provisioning.ts +763 -0
  88. package/packages/server/src/access/refusal-ledger.ts +6 -6
  89. package/packages/server/src/access/yolo-session.ts +127 -14
  90. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  91. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  92. package/packages/server/src/acp-bridge/acp-session-adapter.ts +549 -0
  93. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  94. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  95. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  96. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  97. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  98. package/packages/server/src/acp-bridge/main.ts +118 -0
  99. package/packages/server/src/acp-bridge/models.ts +33 -0
  100. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  101. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  102. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  103. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  104. package/packages/server/src/addons/addons-catalog.ts +408 -0
  105. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  106. package/packages/server/src/addons/addons-folder.ts +310 -0
  107. package/packages/server/src/addons/addons-service.ts +470 -0
  108. package/packages/server/src/addons/package-contents.ts +99 -0
  109. package/packages/server/src/addons/settings-entries.ts +120 -0
  110. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  111. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  112. package/packages/server/src/auth/approval-refusal.ts +87 -0
  113. package/packages/server/src/auth/audit-log.ts +80 -0
  114. package/packages/server/src/auth/auth-plugin.ts +329 -97
  115. package/packages/server/src/auth/auth.ts +102 -11
  116. package/packages/server/src/auth/bearer-auth.ts +74 -12
  117. package/packages/server/src/auth/cors-origin.ts +86 -29
  118. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  119. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  120. package/packages/server/src/auth/csp-report-store.ts +406 -0
  121. package/packages/server/src/auth/csp.ts +111 -9
  122. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  123. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  124. package/packages/server/src/auth/host-admission.ts +26 -0
  125. package/packages/server/src/auth/host-gate.ts +6 -1
  126. package/packages/server/src/auth/local-credential.ts +258 -0
  127. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  128. package/packages/server/src/auth/local-proof.ts +76 -22
  129. package/packages/server/src/auth/local-token.ts +16 -0
  130. package/packages/server/src/auth/localhost-guard.ts +298 -17
  131. package/packages/server/src/auth/nav-intent.ts +72 -0
  132. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  133. package/packages/server/src/auth/node-guard.ts +43 -0
  134. package/packages/server/src/auth/operate-required.ts +126 -0
  135. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  136. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  137. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  138. package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
  139. package/packages/server/src/auth/passkey/passkey-routes.ts +232 -0
  140. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  141. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  142. package/packages/server/src/auth/passkey/requester.ts +83 -0
  143. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  144. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  145. package/packages/server/src/auth/pi-legacy-credentials.ts +324 -0
  146. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  147. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  148. package/packages/server/src/auth/proven-tls.ts +45 -0
  149. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  150. package/packages/server/src/auth/provider-auth-storage.ts +61 -9
  151. package/packages/server/src/auth/radius-mcp.ts +1 -1
  152. package/packages/server/src/auth/radius-override.ts +13 -0
  153. package/packages/server/src/auth/request-principal.ts +32 -0
  154. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  155. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  156. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  157. package/packages/server/src/auth/secret-rotation.ts +246 -0
  158. package/packages/server/src/auth/secure-origin.ts +56 -0
  159. package/packages/server/src/auth/serve-app-host.ts +197 -0
  160. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  161. package/packages/server/src/auth/trust-mode.ts +83 -0
  162. package/packages/server/src/auth/ws-ticket.ts +39 -1
  163. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  164. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  165. package/packages/server/src/browse.ts +114 -2
  166. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  167. package/packages/server/src/browser-handlers/directory-handler.ts +151 -6
  168. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  169. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  170. package/packages/server/src/browser-handlers/session-action-handler.ts +138 -63
  171. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  172. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  173. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  174. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  175. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  176. package/packages/server/src/cli.ts +1063 -106
  177. package/packages/server/src/config-api.ts +166 -2
  178. package/packages/server/src/config-snapshot.ts +53 -1
  179. package/packages/server/src/directory-service.ts +545 -36
  180. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  181. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  182. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  183. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  184. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  185. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  186. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  187. package/packages/server/src/event-wiring.ts +349 -141
  188. package/packages/server/src/file-watch-manager.ts +187 -39
  189. package/packages/server/src/git-worktree/git-operations.ts +60 -15
  190. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  191. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  192. package/packages/server/src/git-worktree/worktree-init-trust.ts +91 -6
  193. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  194. package/packages/server/src/identity/host-resources.ts +3 -0
  195. package/packages/server/src/identity/http-road-classification.ts +31 -1
  196. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  197. package/packages/server/src/identity/plugin-identity.ts +19 -0
  198. package/packages/server/src/identity/policy-registry.ts +4 -1
  199. package/packages/server/src/identity/resolver-registry.ts +12 -3
  200. package/packages/server/src/identity/ws-message-scope.ts +10 -0
  201. package/packages/server/src/identity/ws-road-classification.ts +10 -0
  202. package/packages/server/src/known-server-moves.ts +196 -0
  203. package/packages/server/src/lib/browse-roots.ts +137 -0
  204. package/packages/server/src/lib/client-dist.ts +36 -21
  205. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  206. package/packages/server/src/lib/diagram-render.ts +4 -6
  207. package/packages/server/src/lib/digest-gate.ts +82 -0
  208. package/packages/server/src/lib/eml.ts +3 -8
  209. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  210. package/packages/server/src/lib/file-write-lock.ts +24 -0
  211. package/packages/server/src/lib/folder-project.ts +439 -0
  212. package/packages/server/src/lib/grep-worker.ts +23 -0
  213. package/packages/server/src/lib/grep.ts +93 -7
  214. package/packages/server/src/lib/index-html.ts +81 -0
  215. package/packages/server/src/lib/office-preview.ts +2 -3
  216. package/packages/server/src/lib/path-containment.ts +7 -0
  217. package/packages/server/src/lib/purify.ts +13 -5
  218. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  219. package/packages/server/src/lib/route-admission.ts +80 -0
  220. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  221. package/packages/server/src/lib/writable-md-target.ts +16 -1
  222. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  223. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  224. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  225. package/packages/server/src/lifecycle/recovery-server.ts +129 -6
  226. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  227. package/packages/server/src/live-server/capability-redact.ts +15 -0
  228. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  229. package/packages/server/src/live-server/live-capability.ts +461 -0
  230. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  231. package/packages/server/src/live-server/live-csp.ts +93 -0
  232. package/packages/server/src/live-server/live-egress.ts +435 -0
  233. package/packages/server/src/live-server/live-exposure.ts +149 -0
  234. package/packages/server/src/live-server/live-log.ts +21 -0
  235. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  236. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  237. package/packages/server/src/live-server/live-server-proxy.ts +326 -34
  238. package/packages/server/src/live-server/live-static.ts +228 -0
  239. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  240. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  241. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  242. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  243. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  244. package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
  245. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  246. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
  247. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
  248. package/packages/server/src/openspec/openspec-poll-worker.ts +286 -44
  249. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  250. package/packages/server/src/openspec/readiness.ts +9 -0
  251. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  252. package/packages/server/src/openspec/workflow-schema.ts +1002 -0
  253. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  254. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  255. package/packages/server/src/package/package-health-scanner.ts +133 -0
  256. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  257. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  258. package/packages/server/src/package/provider-probe.ts +13 -5
  259. package/packages/server/src/pairing/browser-gateway.ts +292 -16
  260. package/packages/server/src/pairing/device-token-services.ts +26 -0
  261. package/packages/server/src/pairing/knock-admission.ts +277 -0
  262. package/packages/server/src/pairing/paired-devices.ts +335 -22
  263. package/packages/server/src/pairing/pairing.ts +188 -31
  264. package/packages/server/src/pairing/socket-locality.ts +26 -0
  265. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  266. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  267. package/packages/server/src/peer-servers.ts +77 -0
  268. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  269. package/packages/server/src/persistence/boot-state.ts +48 -1
  270. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  271. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  272. package/packages/server/src/persistence/preferences-store.ts +125 -7
  273. package/packages/server/src/pi/bridge-channel.ts +33 -0
  274. package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
  275. package/packages/server/src/pi/folder-commands.ts +141 -0
  276. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  277. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  278. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  279. package/packages/server/src/pi/host-project-trust.ts +166 -33
  280. package/packages/server/src/pi/pi-gateway.ts +283 -29
  281. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  282. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  283. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  284. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  285. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  286. package/packages/server/src/pi/trust-challenges.ts +38 -0
  287. package/packages/server/src/pi-agent-settings.ts +701 -100
  288. package/packages/server/src/pi-settings-themes.ts +104 -0
  289. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  290. package/packages/server/src/plugin-event-seam.ts +116 -4
  291. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  292. package/packages/server/src/questions/brief-generator.ts +138 -0
  293. package/packages/server/src/questions/brief-model.ts +55 -0
  294. package/packages/server/src/questions/brief-policy.ts +36 -0
  295. package/packages/server/src/questions/brief-prompt.ts +92 -0
  296. package/packages/server/src/questions/brief-runtime.ts +50 -0
  297. package/packages/server/src/questions/question-answer.ts +55 -0
  298. package/packages/server/src/questions/question-broadcast.ts +106 -0
  299. package/packages/server/src/questions/question-files.ts +128 -0
  300. package/packages/server/src/questions/question-routes.ts +126 -0
  301. package/packages/server/src/questions/question-snapshot.ts +150 -0
  302. package/packages/server/src/questions/question-stack.ts +57 -0
  303. package/packages/server/src/questions/question-store.ts +477 -0
  304. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  305. package/packages/server/src/routes/access-routes.ts +274 -6
  306. package/packages/server/src/routes/acme-routes.ts +190 -0
  307. package/packages/server/src/routes/acp-routes.ts +16 -0
  308. package/packages/server/src/routes/addons-routes.ts +221 -0
  309. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  310. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  311. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  312. package/packages/server/src/routes/file-routes.ts +620 -209
  313. package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
  314. package/packages/server/src/routes/folder-project-routes.ts +105 -0
  315. package/packages/server/src/routes/git-routes.ts +334 -203
  316. package/packages/server/src/routes/grep-routes.ts +38 -14
  317. package/packages/server/src/routes/known-servers-routes.ts +433 -55
  318. package/packages/server/src/routes/live-server-routes.ts +438 -7
  319. package/packages/server/src/routes/local-proof-routes.ts +26 -7
  320. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  321. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  322. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  323. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  324. package/packages/server/src/routes/openspec-routes.ts +636 -55
  325. package/packages/server/src/routes/package-health-routes.ts +140 -0
  326. package/packages/server/src/routes/package-routes.ts +86 -11
  327. package/packages/server/src/routes/pairing-routes.ts +303 -33
  328. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  329. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  330. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  331. package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
  332. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  333. package/packages/server/src/routes/provider-auth-routes.ts +37 -7
  334. package/packages/server/src/routes/provider-routes.ts +29 -0
  335. package/packages/server/src/routes/resource-activation-routes.ts +33 -35
  336. package/packages/server/src/routes/session-routes.ts +100 -9
  337. package/packages/server/src/routes/system-routes.ts +286 -33
  338. package/packages/server/src/routes/tls-routes.ts +55 -0
  339. package/packages/server/src/routes/ui-link-base.ts +88 -0
  340. package/packages/server/src/routes/user-routes.ts +192 -0
  341. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  342. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  343. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  344. package/packages/server/src/server.ts +1537 -246
  345. package/packages/server/src/services/attached-driver.ts +175 -0
  346. package/packages/server/src/services/change-notifier.ts +55 -0
  347. package/packages/server/src/services/cli-service.ts +450 -0
  348. package/packages/server/src/services/command-runner.ts +92 -0
  349. package/packages/server/src/services/definitions-store.ts +121 -0
  350. package/packages/server/src/services/driver.ts +112 -0
  351. package/packages/server/src/services/health.ts +94 -0
  352. package/packages/server/src/services/leases.ts +117 -0
  353. package/packages/server/src/services/log-text.ts +97 -0
  354. package/packages/server/src/services/native-driver.ts +283 -0
  355. package/packages/server/src/services/oci-driver.ts +590 -0
  356. package/packages/server/src/services/output-capture.ts +183 -0
  357. package/packages/server/src/services/paths.ts +82 -0
  358. package/packages/server/src/services/ports.ts +26 -0
  359. package/packages/server/src/services/routes.ts +140 -0
  360. package/packages/server/src/services/runtime-detect.ts +108 -0
  361. package/packages/server/src/services/secret-delivery.ts +61 -0
  362. package/packages/server/src/services/secrets-resolver.ts +145 -0
  363. package/packages/server/src/services/secrets-store.ts +137 -0
  364. package/packages/server/src/services/service-manager.ts +1565 -0
  365. package/packages/server/src/services/start-record.ts +66 -0
  366. package/packages/server/src/services/state-machine.ts +241 -0
  367. package/packages/server/src/session/archive-sweeper.ts +92 -3
  368. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  369. package/packages/server/src/session/hydration-state.ts +148 -0
  370. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  371. package/packages/server/src/session/memory-session-manager.ts +60 -0
  372. package/packages/server/src/session/name-provenance.ts +102 -0
  373. package/packages/server/src/session/open-tool-calls.ts +15 -6
  374. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  375. package/packages/server/src/session/retained-transcript.ts +9 -2
  376. package/packages/server/src/session/session-api.ts +47 -12
  377. package/packages/server/src/session/session-archive.ts +56 -4
  378. package/packages/server/src/session/session-diff-cache.ts +11 -4
  379. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  380. package/packages/server/src/session/session-load-worker.ts +11 -2
  381. package/packages/server/src/session/session-scanner.ts +73 -3
  382. package/packages/server/src/session/session-to-meta.ts +15 -0
  383. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  384. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  385. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  386. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  387. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  388. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  389. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  390. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  391. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  392. package/packages/server/src/terminal/terminal-manager.ts +75 -1
  393. package/packages/server/src/tls/cert-files.ts +228 -0
  394. package/packages/server/src/tls/cert-manager.ts +703 -0
  395. package/packages/server/src/tls/cert-store.ts +69 -0
  396. package/packages/server/src/tls/source-registry.ts +71 -0
  397. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  398. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  399. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  400. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  401. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  402. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  403. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  404. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  405. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  406. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  407. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  408. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  409. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  410. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  411. package/packages/server/src/tls/tls-config-validation.ts +94 -0
  412. package/packages/server/src/tls/tls-listener.ts +351 -0
  413. package/packages/server/src/tls/types.ts +80 -0
  414. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  415. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  416. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  417. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  418. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  419. package/packages/server/src/vault/vault-bindings.ts +101 -0
  420. package/packages/server/src/vault/vault-delivery-hub.ts +424 -0
  421. package/packages/server/src/vault/vault-grants.ts +260 -0
  422. package/packages/server/src/vault/vault-import.ts +161 -0
  423. package/packages/server/src/vault/vault-permissions.ts +39 -0
  424. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  425. package/packages/server/src/vault/vault-projects.ts +156 -0
  426. package/packages/server/src/vault/vault-routes.ts +277 -0
  427. package/packages/server/src/vault/vault-store.ts +371 -0
  428. package/packages/server/src/watch-files-handler.ts +66 -0
  429. package/packages/shared/package.json +5 -2
  430. package/packages/shared/src/acp/acp-config.ts +123 -0
  431. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  432. package/packages/shared/src/acp/paths.ts +36 -0
  433. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  434. package/packages/shared/src/acp/update-model.ts +574 -0
  435. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  436. package/packages/shared/src/bind-reachability.ts +21 -2
  437. package/packages/shared/src/boot-state.ts +6 -0
  438. package/packages/shared/src/browser-host-identity.ts +49 -0
  439. package/packages/shared/src/browser-host-ipc.ts +107 -0
  440. package/packages/shared/src/browser-protocol.ts +533 -73
  441. package/packages/shared/src/canonical-subject.ts +27 -2
  442. package/packages/shared/src/canvas-declare.ts +27 -0
  443. package/packages/shared/src/card-sections.ts +185 -1
  444. package/packages/shared/src/chrome-profiles.ts +188 -0
  445. package/packages/shared/src/config.ts +817 -51
  446. package/packages/shared/src/containment-guard.ts +35 -0
  447. package/packages/shared/src/custom-event-groups.ts +5 -2
  448. package/packages/shared/src/cwd-guard.ts +381 -1
  449. package/packages/shared/src/dashboard-paths.ts +12 -0
  450. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  451. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  452. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  453. package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -0
  454. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  455. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  456. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  457. package/packages/shared/src/dashboard-plugin/index.ts +9 -3
  458. package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
  459. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  460. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  461. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  462. package/packages/shared/src/dashboard-plugin/slot-props.ts +139 -2
  463. package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
  464. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  465. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
  466. package/packages/shared/src/dashboard-starter.ts +30 -0
  467. package/packages/shared/src/display-name.ts +42 -0
  468. package/packages/shared/src/display-prefs.ts +13 -0
  469. package/packages/shared/src/doctor-core.ts +119 -134
  470. package/packages/shared/src/enabled-models-match.ts +47 -0
  471. package/packages/shared/src/event-forward-declaration.ts +187 -0
  472. package/packages/shared/src/file-kind.ts +54 -2
  473. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  474. package/packages/shared/src/grammar-types.ts +3 -1
  475. package/packages/shared/src/host-admission.ts +2 -1
  476. package/packages/shared/src/host-port.ts +34 -0
  477. package/packages/shared/src/launcher-origin.ts +26 -0
  478. package/packages/shared/src/live-server.ts +141 -0
  479. package/packages/shared/src/local-credential-proof.ts +219 -0
  480. package/packages/shared/src/local-proof-signal.ts +16 -0
  481. package/packages/shared/src/loopback-host.ts +26 -0
  482. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  483. package/packages/shared/src/markup-repair/types.ts +13 -0
  484. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  485. package/packages/shared/src/md-table-cell.ts +11 -0
  486. package/packages/shared/src/mdns-discovery.ts +414 -45
  487. package/packages/shared/src/models-json-reader.ts +6 -0
  488. package/packages/shared/src/nav-intent.ts +29 -0
  489. package/packages/shared/src/openspec-dependencies.ts +760 -0
  490. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  491. package/packages/shared/src/openspec-poller.ts +213 -11
  492. package/packages/shared/src/openspec-status-all.ts +393 -0
  493. package/packages/shared/src/operate-required.ts +29 -0
  494. package/packages/shared/src/pairing-knock-client.ts +301 -0
  495. package/packages/shared/src/pairing-knock.ts +71 -0
  496. package/packages/shared/src/pairing-refusal.ts +32 -0
  497. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  498. package/packages/shared/src/pi-settings-keys.ts +9 -0
  499. package/packages/shared/src/pi-settings-schema.ts +285 -0
  500. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  501. package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
  502. package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
  503. package/packages/shared/src/pi-trust-mirror.ts +354 -0
  504. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  505. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  506. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  507. package/packages/shared/src/platform/git-source.ts +88 -26
  508. package/packages/shared/src/platform/git.ts +210 -4
  509. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  510. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  511. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  512. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  513. package/packages/shared/src/platform/node-spawn.ts +1 -2
  514. package/packages/shared/src/platform/openspec.ts +129 -31
  515. package/packages/shared/src/platform/process-scan.ts +199 -1
  516. package/packages/shared/src/platform/process.ts +99 -4
  517. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  518. package/packages/shared/src/platform/runner.ts +46 -2
  519. package/packages/shared/src/platform/select-git-source.ts +7 -0
  520. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  521. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  522. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  523. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  524. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  525. package/packages/shared/src/preview-egress.ts +138 -0
  526. package/packages/shared/src/project-name.ts +42 -0
  527. package/packages/shared/src/project-root.ts +16 -0
  528. package/packages/shared/src/prompt-answer.ts +183 -0
  529. package/packages/shared/src/protocol.ts +172 -8
  530. package/packages/shared/src/question-types.ts +73 -0
  531. package/packages/shared/src/recommended-extensions.ts +98 -23
  532. package/packages/shared/src/recovery-timing.ts +39 -0
  533. package/packages/shared/src/redaction.ts +50 -0
  534. package/packages/shared/src/remote-credentials.ts +63 -0
  535. package/packages/shared/src/rest-api.ts +533 -3
  536. package/packages/shared/src/role-config-disk.ts +23 -0
  537. package/packages/shared/src/role-schema.ts +79 -0
  538. package/packages/shared/src/route-tiers.ts +181 -0
  539. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  540. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  541. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  542. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  543. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  544. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  545. package/packages/shared/src/safe-local-path.ts +24 -0
  546. package/packages/shared/src/sanitize-profiles.ts +98 -0
  547. package/packages/shared/src/server-identity.ts +51 -15
  548. package/packages/shared/src/server-launcher.ts +21 -34
  549. package/packages/shared/src/server-pinning.ts +136 -2
  550. package/packages/shared/src/server-routes.ts +462 -0
  551. package/packages/shared/src/services/offers.ts +114 -0
  552. package/packages/shared/src/services/schema.ts +628 -0
  553. package/packages/shared/src/services/status.ts +169 -0
  554. package/packages/shared/src/session-meta.ts +59 -2
  555. package/packages/shared/src/session-name.ts +8 -0
  556. package/packages/shared/src/session-ui-path.ts +11 -0
  557. package/packages/shared/src/skill-block-parser.ts +14 -0
  558. package/packages/shared/src/source-matching.ts +5 -1
  559. package/packages/shared/src/state-replay.ts +19 -0
  560. package/packages/shared/src/terminal-safe.ts +24 -0
  561. package/packages/shared/src/tls-only-token.ts +16 -0
  562. package/packages/shared/src/tls-status.ts +69 -0
  563. package/packages/shared/src/tool-path-resolve.ts +243 -0
  564. package/packages/shared/src/tool-registry/definitions.ts +31 -9
  565. package/packages/shared/src/tool-registry/index.ts +2 -2
  566. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  567. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  568. package/packages/shared/src/tunnel-provider.ts +3 -2
  569. package/packages/shared/src/types.ts +170 -9
  570. package/packages/shared/src/url-policy.ts +96 -0
  571. package/packages/shared/src/vault-delivery.ts +88 -0
  572. package/packages/shared/src/vault-origin.ts +51 -0
  573. package/packages/shared/src/vault-project-key.ts +53 -0
  574. package/packages/shared/src/worktree-init-hook.ts +69 -0
  575. package/packages/shared/src/ws-message-tiers.ts +136 -0
  576. package/tsconfig.base.json +1 -0
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import net from "node:net";
2
3
  import os from "node:os";
3
4
  import path from "node:path";
5
+ import readline from "node:readline";
4
6
  import { fileURLToPath } from "node:url";
5
7
  /**
6
8
  * PI Dashboard Server CLI
@@ -18,7 +20,19 @@ import { fileURLToPath } from "node:url";
18
20
  * pi-dashboard restart [flags] Restart daemon
19
21
  * pi-dashboard status Show daemon status
20
22
  * pi-dashboard runtime Print the resolved spawn runtime (diagnostic)
21
- * pi-dashboard open [--print] Open the dashboard in a browser with local proof (requireLocalProof)
23
+ * pi-dashboard open [--print] [--url <origin>]
24
+ * Open the dashboard in a browser with local proof (requireLocalProof).
25
+ * --url: a loopback origin on the configured port (e.g. http://127.0.0.1:8000)
26
+ * pi-dashboard pair list [--json]
27
+ * pi-dashboard pair approve [<pendingId>] [--code <8 digits>] [--name <label>] [--tier observe|control|operate]
28
+ * pi-dashboard pair deny <pendingId>
29
+ * Approve/deny a pending device pairing from this host. The code is read from a
30
+ * prompt or stdin; --code is visible in `ps`.
31
+ * pi-dashboard api <METHOD> <path> [--data <json>] [--port n]
32
+ * Call the running dashboard's REST API with a freshly minted local proof
33
+ * (what curl cannot do under the strict `requireLocalProof` default).
34
+ * Exit 0 on 2xx, 1 on any other status (body on stderr), 2 on usage error
35
+ * or server not running.
22
36
  *
23
37
  * Flags:
24
38
  * --port <n> HTTP port (default: 8000)
@@ -31,6 +45,10 @@ import { fileURLToPath } from "node:url";
31
45
  // caught and degraded into the recovery HTTP server instead of crashing
32
46
  // the process. The type-only import here is fully erased at runtime.
33
47
  import { ensureConfig, loadConfig, SERVER_STARTUP_DEADLINE_MS } from "@blackbelt-technology/pi-dashboard-shared/config.js";
48
+ import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
49
+ import { isLauncherOrigin } from "@blackbelt-technology/pi-dashboard-shared/launcher-origin.js";
50
+ import { isSafeLocalPath } from "@blackbelt-technology/pi-dashboard-shared/safe-local-path.js";
51
+ import { httpProofHeaders, localDialHost } from "@blackbelt-technology/pi-dashboard-shared/local-credential-proof.js";
34
52
  import {
35
53
  findPortHolders as platformFindPortHolders,
36
54
  isProcessAlive as platformIsProcessAlive,
@@ -39,21 +57,21 @@ import {
39
57
  } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
40
58
  import {
41
59
  EarlyExitError,
42
- JitiNotFoundError,
43
60
  launchDashboardServer,
44
61
  PortConflictError,
45
62
  } from "@blackbelt-technology/pi-dashboard-shared/server-launcher.js";
63
+ import { terminalSafe } from "@blackbelt-technology/pi-dashboard-shared/terminal-safe.js";
64
+ import { defaultLocalTokenDir, ensureLocalToken, readLocalTokenIfPresent } from "./auth/local-token.js";
46
65
  import { migrateSubagentTickThrottle } from "./config-api.js";
47
- import { ensureLocalToken, LOCAL_TOKEN_HEADER } from "./auth/local-token.js";
66
+ import { classifyDashboardPort, type PortClassification } from "./lifecycle/classify-dashboard-port.js";
48
67
  import {
49
68
  isModuleNotFoundError,
50
69
  parseModuleNotFoundError,
51
70
  startRecoveryServer,
52
71
  } from "./lifecycle/recovery-server.js";
72
+ import { collectOwnedPids, collectOwnership, type OwnerFacts, type Ownership, partitionHolders } from "./lifecycle/stop-ownership.js";
53
73
  import type { createServer as _CreateServerType, ServerConfig } from "./server.js";
54
- import { isServerRunning, readPid, removePid } from "./spawn-process/server-pid.js";
55
- import { collectOwnedPids, partitionHolders } from "./lifecycle/stop-ownership.js";
56
- import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
74
+ import { readPid, removePid } from "./spawn-process/server-pid.js";
57
75
 
58
76
  // Re-exports for back-compat — other modules / tests may import these from cli.
59
77
  export const parseNetstatListeners = platformParseNetstatListeners;
@@ -70,6 +88,7 @@ import {
70
88
  } from "@blackbelt-technology/pi-dashboard-shared/bridge-register.js";
71
89
  import { parseDashboardStarter } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
72
90
  import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
91
+ import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
73
92
  import {
74
93
  piEntryFromArgv,
75
94
  type ResolvedRuntime,
@@ -77,14 +96,52 @@ import {
77
96
  } from "@blackbelt-technology/pi-dashboard-shared/platform/spawn-runtime.js";
78
97
  import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
79
98
  import { getDefaultRegistry, ingestInstalledSkillTools, resolveInstallRoot } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
80
- import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
81
- import { assertNodeVersionSupported } from "./auth/node-guard.js";
99
+ import { assertNodeVersionSupported, warnTsLoaderState } from "./auth/node-guard.js";
82
100
  import { recordExitIntent } from "./persistence/boot-state.js";
83
101
  import { publishResolvedRuntime, readPublishedRuntimeBlock } from "./runtime-publication.js";
84
102
  import { resolveLiveSpawnRuntime } from "./runtime-resolution.js";
103
+ import { cmdService, localExecSecretsResolver } from "./services/cli-service.js";
104
+ import { defaultCommandRunner } from "./services/command-runner.js";
105
+ import { servicesPaths } from "./services/paths.js";
85
106
 
86
107
  const SUBCOMMANDS = ["start", "stop", "restart", "status", "runtime", "open"] as const;
87
108
  type Subcommand = (typeof SUBCOMMANDS)[number];
109
+ /** Words dispatched to their own command (before `parseArgs`), not to a daemon subcommand. */
110
+ const COMMAND_WORDS = ["token", "service", "pair", "login", "api"] as const;
111
+ type CommandWord = (typeof COMMAND_WORDS)[number];
112
+ /** Flags whose NEXT token is their value, never the subcommand word. */
113
+ const VALUE_FLAGS: ReadonlySet<string> = new Set(["--port", "--host", "--pi-port", "--url", "--data", "--code", "--name", "--tier"]);
114
+
115
+ /** The one-line usage printed for an unknown subcommand word (exit 2). */
116
+ 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)";
118
+
119
+ export type ArgvClass =
120
+ | { kind: "none" }
121
+ | { kind: "subcommand"; word: Subcommand; index: number }
122
+ | { kind: "command"; word: CommandWord; index: number }
123
+ | { kind: "unknown"; word: string; index: number };
124
+
125
+ /**
126
+ * The subcommand word: the FIRST positional that is not a flag value. `--port 9000 api GET /x`
127
+ * resolves to `api` (9000 is `--port`'s value). One scan serves `api`, `token`, `service`,
128
+ * `pair`, `login` and the daemon subcommands, so none of them can be missed behind a flag.
129
+ * A flag-only invocation has no word and runs in the foreground.
130
+ */
131
+ export function classifyArgv(args: readonly string[]): ArgvClass {
132
+ for (let i = 0; i < args.length; i++) {
133
+ const a = args[i] as string;
134
+ if (a === "--") break;
135
+ if (a.startsWith("-")) {
136
+ if (VALUE_FLAGS.has(a)) i++; // skip its value
137
+ continue;
138
+ }
139
+ if ((SUBCOMMANDS as readonly string[]).includes(a)) return { kind: "subcommand", word: a as Subcommand, index: i };
140
+ if ((COMMAND_WORDS as readonly string[]).includes(a)) return { kind: "command", word: a as CommandWord, index: i };
141
+ return { kind: "unknown", word: a, index: i };
142
+ }
143
+ return { kind: "none" };
144
+ }
88
145
 
89
146
  export interface ParsedArgs {
90
147
  subcommand: Subcommand | null;
@@ -242,6 +299,7 @@ export function buildConfig(
242
299
  */
243
300
  async function runForeground(config: ServerConfig): Promise<void> {
244
301
  assertNodeVersionSupported();
302
+ warnTsLoaderState();
245
303
 
246
304
  // Dynamic-import boundary for the main server module. If a top-level
247
305
  // dependency (fastify, toad-cache, readable-stream, …) is missing, the
@@ -254,6 +312,11 @@ async function runForeground(config: ServerConfig): Promise<void> {
254
312
  if (isModuleNotFoundError(err)) {
255
313
  await startRecoveryServer({
256
314
  port: config.port,
315
+ // Bind the configured host (loopback by default), never all interfaces;
316
+ // mutating actions are gated on loopback or the local token.
317
+ // See change: harden-server-capability-bounds (B9).
318
+ host: config.host,
319
+ localToken: readLocalTokenIfPresent(),
257
320
  error: err as Error,
258
321
  missingModule: parseModuleNotFoundError(err),
259
322
  });
@@ -382,27 +445,144 @@ async function runForeground(config: ServerConfig): Promise<void> {
382
445
  }
383
446
 
384
447
 
448
+ /** Injectable seams of `cmdStart` (tests); production passes none. */
449
+ export interface StartDeps {
450
+ classify: (config: ServerConfig) => Promise<PortClassification>;
451
+ launch: typeof launchDashboardServer;
452
+ killProcess: (pid: number, label: string) => Promise<boolean>;
453
+ isProcessAlive: (pid: number) => boolean;
454
+ exit: (code: number) => void;
455
+ }
456
+
457
+ /**
458
+ * Running-line suffix naming the desktop app as the server's starter, from the
459
+ * owner facts of one `/api/health` reply. Wording only, never a kill decision.
460
+ * See change: fix-cli-control-electron-server (design D8).
461
+ */
462
+ function ownerSuffix(facts: Pick<OwnerFacts, "launchSource" | "bootParentAlive">): string {
463
+ if (facts.launchSource !== "electron") return "";
464
+ return facts.bootParentAlive === false
465
+ ? " (started by the pi-dashboard desktop app, which is no longer running)"
466
+ : " (started by the pi-dashboard desktop app)";
467
+ }
468
+
469
+ /** One printed verdict + exit code for a classified port; shared by `start` and `status`. */
470
+ function portVerdict(
471
+ v: PortClassification,
472
+ config: { port: number },
473
+ ): { lines: string[]; stream: "log" | "error"; code: number } | null {
474
+ const at = (pid: number | undefined) => (pid === undefined ? "" : ` (pid ${pid})`);
475
+ switch (v.kind) {
476
+ case "owned":
477
+ return { lines: [`Dashboard server is already running (pid ${v.pid})${ownerSuffix(v)}`], stream: "log", code: 0 };
478
+ case "starting":
479
+ return { lines: [`Dashboard server is starting (pid ${v.pid})`], stream: "log", code: 0 };
480
+ case "unowned-dashboard":
481
+ return {
482
+ lines: [
483
+ `Port ${config.port} is served by a dashboard${at(v.pid)} that is not owned by this HOME.`,
484
+ "Use --port <n> to start a separate instance, or stop that dashboard from the HOME that started it.",
485
+ ],
486
+ stream: "error",
487
+ code: 1,
488
+ };
489
+ case "conflict":
490
+ return {
491
+ lines: [
492
+ `Port ${config.port} is occupied by another service (not the dashboard).`,
493
+ "Change the port in ~/.pi/dashboard/config.json or use --port <n>",
494
+ ],
495
+ stream: "error",
496
+ code: 1,
497
+ };
498
+ case "unresponsive":
499
+ return {
500
+ lines: [
501
+ `Dashboard server is running but not responding${at(v.pid)} on port ${config.port}.`,
502
+ "It may be overloaded or frozen. Not starting a second one. Run `pi-dashboard stop` to stop it, then start again.",
503
+ ],
504
+ stream: "error",
505
+ code: 1,
506
+ };
507
+ case "free":
508
+ return null;
509
+ }
510
+ }
511
+
512
+ /** Injectable seams of `cmdForeground` (tests); production passes none. */
513
+ export interface ForegroundDeps {
514
+ runForeground: (config: ServerConfig) => Promise<void>;
515
+ classify: (config: ServerConfig) => Promise<PortClassification>;
516
+ exit: (code: number) => void;
517
+ }
518
+
519
+ /**
520
+ * Bare `pi-dashboard`: run in the foreground. No classification runs before or
521
+ * during a successful start. When startup fails for ANY reason the resolved port
522
+ * is classified once (a failed start binds nothing, so the verdict is
523
+ * trustworthy whichever listener failed first). A dashboard answering, or a
524
+ * non-dashboard service, prints `start`'s verdict (with the desktop-app mention)
525
+ * instead of a stack trace; otherwise today's generic message. Always exits 1:
526
+ * `portVerdict` returns 0 for `owned`, which would turn a failed start into
527
+ * success, and an explicit exit also stops the attach-mode promotion timer.
528
+ * See change: fix-cli-control-electron-server (design D5).
529
+ */
530
+ export async function cmdForeground(config: ServerConfig, injected?: Partial<ForegroundDeps>): Promise<void> {
531
+ const d: ForegroundDeps = {
532
+ runForeground,
533
+ classify: (c) => classifyDashboardPort(c),
534
+ exit: (code) => process.exit(code),
535
+ ...injected,
536
+ };
537
+ try {
538
+ await d.runForeground(config);
539
+ } catch (startErr) {
540
+ let verdict: ReturnType<typeof portVerdict> = null;
541
+ try {
542
+ verdict = portVerdict(await d.classify(config), config);
543
+ } catch {
544
+ // classification is best-effort: fall back to the generic message
545
+ }
546
+ if (verdict) {
547
+ for (const line of verdict.lines) (verdict.stream === "log" ? console.log : console.error)(line);
548
+ } else {
549
+ console.error("Failed to start dashboard:", startErr);
550
+ }
551
+ d.exit(1);
552
+ }
553
+ }
554
+
385
555
  /**
386
556
  * Start the server as a detached background daemon.
557
+ *
558
+ * Classifies the port first (one read-only verdict shared with `status`), only
559
+ * launches when it is free, and prints "started" only when a post-readiness
560
+ * classification sees an owned dashboard reporting the pid this command
561
+ * spawned. See change: harden-dashboard-start-detection (D4).
387
562
  */
388
- async function cmdStart(config: ServerConfig): Promise<void> {
563
+ export async function cmdStart(config: ServerConfig, injected?: Partial<StartDeps>): Promise<void> {
389
564
  assertNodeVersionSupported();
390
- const running = await isServerRunning(config.port);
391
- if (running) {
392
- console.log(`Dashboard server is already running (pid ${running})`);
393
- return;
394
- }
565
+ const d: StartDeps = {
566
+ classify: (c) => classifyDashboardPort(c),
567
+ launch: launchDashboardServer,
568
+ killProcess,
569
+ isProcessAlive,
570
+ exit: (code) => process.exit(code),
571
+ ...injected,
572
+ };
573
+ const say = (verdict: { lines: string[]; stream: "log" | "error" }) => {
574
+ for (const line of verdict.lines) (verdict.stream === "log" ? console.log : console.error)(line);
575
+ };
395
576
 
396
- // Check if port is occupied by another service
397
- const portStatus = await isDashboardRunning(config.port);
398
- if (portStatus.portConflict) {
399
- console.error(`Port ${config.port} is occupied by another service (not the dashboard).`);
400
- console.error(`Change the port in ~/.pi/dashboard/config.json or use --port <n>`);
401
- process.exit(1);
577
+ const pre = portVerdict(await d.classify(config), config);
578
+ if (pre) {
579
+ say(pre);
580
+ if (pre.code !== 0) d.exit(pre.code);
581
+ return;
402
582
  }
403
583
 
404
584
  // Spawn ourselves in foreground mode (no subcommand) as a detached process.
405
- // All concerns below — jiti loader resolution, --import argv URL-wrapping,
585
+ // All concerns below — native TypeScript loader resolution, --import argv URL-wrapping,
406
586
  // env merge, log-file header, readiness polling, port-conflict / early-exit
407
587
  // detection — are owned by the shared `launchDashboardServer` primitive.
408
588
  const cliPath = fileURLToPath(import.meta.url);
@@ -415,8 +595,9 @@ async function cmdStart(config: ServerConfig): Promise<void> {
415
595
  const logDir = path.join(os.homedir(), ".pi", "dashboard");
416
596
  const logPath = path.join(logDir, "server.log");
417
597
 
598
+ let result: Awaited<ReturnType<typeof launchDashboardServer>>;
418
599
  try {
419
- const result = await launchDashboardServer({
600
+ result = await d.launch({
420
601
  cliPath,
421
602
  extraArgs: args,
422
603
  stdio: { logFile: logPath },
@@ -424,28 +605,57 @@ async function cmdStart(config: ServerConfig): Promise<void> {
424
605
  healthTimeoutMs: 30_000,
425
606
  port: config.port,
426
607
  });
427
- const reportedPid = result.reportedPid ?? readPid() ?? result.childPid;
428
- console.log(`Dashboard server started (pid ${reportedPid}) at http://localhost:${config.port}`);
429
608
  } catch (err: unknown) {
430
- if (err instanceof JitiNotFoundError) {
431
- console.error(`[pi-dashboard] ${err.message}`);
432
- process.exit(1);
609
+ // Any early exit — a foreground bind failure exits 1, only the recovery
610
+ // path exits 2 — is re-classified once: losing the bind race to a parallel
611
+ // start of this HOME is "already running", not a failure.
612
+ if (err instanceof PortConflictError || err instanceof EarlyExitError) {
613
+ const after = portVerdict(await d.classify(config), config);
614
+ if (after && (after.code === 0)) {
615
+ say(after);
616
+ return;
617
+ }
433
618
  }
434
619
  if (err instanceof PortConflictError) {
435
620
  console.error(`Port ${err.port} is occupied by another service (not the dashboard).`);
436
621
  console.error(`Change the port in ~/.pi/dashboard/config.json or use --port <n>`);
437
- process.exit(1);
622
+ d.exit(1);
623
+ return;
438
624
  }
439
625
  if (err instanceof EarlyExitError) {
440
626
  console.error(`Failed to start dashboard server (child process exited with code ${err.code})`);
441
627
  console.error(`Check logs at ${logPath}`);
442
- process.exit(1);
628
+ d.exit(1);
629
+ return;
443
630
  }
444
631
  const reason = err instanceof Error ? err.message : String(err);
445
632
  console.error(`Failed to start dashboard server (${reason})`);
446
633
  console.error(`Check logs at ${logPath}`);
447
- process.exit(1);
634
+ d.exit(1);
635
+ return;
448
636
  }
637
+
638
+ // The launcher's readiness probe dials `localhost`, which can reach a
639
+ // different socket than 127.0.0.1. Confirm with the classifier (full budget).
640
+ const post = await d.classify(config);
641
+ if (post.kind === "owned" && post.pid === result.childPid) {
642
+ console.log(`Dashboard server started (pid ${post.pid}) at http://localhost:${config.port}`);
643
+ return;
644
+ }
645
+
646
+ // Not confirmed: never leave a second, unconfirmed server behind.
647
+ if (d.isProcessAlive(result.childPid)) {
648
+ await d.killProcess(result.childPid, "Unconfirmed dashboard server");
649
+ }
650
+ const verdict = portVerdict(post, config);
651
+ if (verdict) {
652
+ say(verdict);
653
+ if (verdict.code !== 0) d.exit(verdict.code);
654
+ return;
655
+ }
656
+ console.error(`Failed to confirm the dashboard server on port ${config.port} (the process launched as pid ${result.childPid} is not serving it).`);
657
+ console.error(`Check logs at ${logPath}`);
658
+ d.exit(1);
449
659
  }
450
660
 
451
661
  /**
@@ -474,6 +684,59 @@ export interface StopDeps {
474
684
  removePid: () => void;
475
685
  isProcessAlive: (pid: number) => boolean;
476
686
  collectOwnedPids: (config: ServerConfig) => Promise<Set<number>>;
687
+ /** Owned pids plus the health-proven pid (with its owner facts). Defaults to wrapping `collectOwnedPids`. */
688
+ collectOwnership: (config: ServerConfig) => Promise<Ownership>;
689
+ /** `POST /api/shutdown` on the resolved dashboard. Rejects on a transport error. */
690
+ shutdownRequest: (config: ServerConfig) => Promise<ShutdownReply>;
691
+ /** Resolves true once `pid` is no longer alive, false after `timeoutMs`. */
692
+ waitForExit: (pid: number, timeoutMs: number) => Promise<boolean>;
693
+ }
694
+
695
+ /** Outcome of the announced-shutdown request. */
696
+ export interface ShutdownReply {
697
+ ok: boolean;
698
+ status: number;
699
+ detail?: string;
700
+ }
701
+
702
+ /** Bound of the wait for the process to exit after an accepted shutdown request (matches `killProcess`). */
703
+ const SHUTDOWN_WAIT_MS = 5000;
704
+
705
+ /**
706
+ * Announced shutdown: loopback `POST /api/shutdown` with a per-request local
707
+ * credential (accepted under `requireLocalProof`) and NO body, so the server
708
+ * records exit intent `"shutdown"` (never `"user-quit"`) and tells connected
709
+ * bridges to suppress auto-start. See change: fix-cli-control-electron-server (D4).
710
+ */
711
+ async function postShutdown(config: ServerConfig): Promise<ShutdownReply> {
712
+ const url = `${localBase(config)}/api/shutdown`;
713
+ const res = await fetch(url, {
714
+ method: "POST",
715
+ headers: localCredentialHeaders("POST", url),
716
+ signal: AbortSignal.timeout(5000),
717
+ });
718
+ if (res.ok) return { ok: true, status: res.status };
719
+ const detail = await res.text().catch(() => "");
720
+ return { ok: false, status: res.status, detail: detail.slice(0, 120) };
721
+ }
722
+
723
+ async function waitForPidExit(pid: number, timeoutMs: number): Promise<boolean> {
724
+ const deadline = Date.now() + timeoutMs;
725
+ while (Date.now() < deadline) {
726
+ if (!isProcessAlive(pid)) return true;
727
+ await new Promise((r) => setTimeout(r, 100));
728
+ }
729
+ return !isProcessAlive(pid);
730
+ }
731
+
732
+ /** Note printed after stopping a server the open desktop app started (D4/D8). */
733
+ function desktopAppNote(facts: OwnerFacts): string | null {
734
+ if (facts.launchSource !== "electron" || facts.bootParentAlive !== true) return null;
735
+ const app = typeof facts.bootParentPid === "number" ? `desktop app (pid ${facts.bootParentPid})` : "desktop app";
736
+ return (
737
+ `Note: this server was started by the pi-dashboard ${app}. The app stays open and shows its reconnect page: ` +
738
+ "use Start server there to bring the server back, or quit the app."
739
+ );
477
740
  }
478
741
 
479
742
  /**
@@ -493,21 +756,67 @@ export async function cmdStop(
493
756
  removePid,
494
757
  isProcessAlive,
495
758
  collectOwnedPids,
759
+ collectOwnership,
760
+ shutdownRequest: postShutdown,
761
+ waitForExit: waitForPidExit,
496
762
  ...injected,
497
763
  };
764
+ // An injected `collectOwnedPids` alone (older seams) means "no health proof".
765
+ if (injected?.collectOwnedPids && !injected.collectOwnership) {
766
+ const owned = injected.collectOwnedPids;
767
+ d.collectOwnership = async (c) => ({ owned: await owned(c), healthProven: null });
768
+ }
498
769
  // Evidence first: after the PID-file kill the health probe can no longer answer.
499
- const owned = await d.collectOwnedPids(config);
770
+ const { owned, healthProven } = await d.collectOwnership(config);
500
771
  const pid = d.readPid();
501
772
  let stopped = false;
773
+ let provenStopped = false;
774
+
775
+ // Terminate `target`. The health-proven pid goes through the announced
776
+ // `POST /api/shutdown` first (bridges suppress auto-start; exit intent
777
+ // `"shutdown"`); error, refusal or survival falls back to SIGTERM→SIGKILL.
778
+ const terminate = async (target: number, label: string): Promise<boolean> => {
779
+ const proven = healthProven !== null && healthProven.pid === target;
780
+ let ok = false;
781
+ if (proven) {
782
+ ok = await announcedStop(target, label);
783
+ }
784
+ if (!ok) ok = await d.killProcess(target, label);
785
+ if (proven && ok) provenStopped = true;
786
+ return ok;
787
+ };
788
+ const announcedStop = async (target: number, label: string): Promise<boolean> => {
789
+ try {
790
+ const reply = await d.shutdownRequest(config);
791
+ if (!reply.ok) {
792
+ console.log(
793
+ `Shutdown request refused (HTTP ${reply.status}${reply.detail ? ` ${reply.detail}` : ""}); falling back to SIGTERM`,
794
+ );
795
+ return false;
796
+ }
797
+ } catch (err) {
798
+ console.log(`Shutdown request failed (${(err as Error).message ?? err}); falling back to SIGTERM`);
799
+ return false;
800
+ }
801
+ if (await d.waitForExit(target, SHUTDOWN_WAIT_MS)) {
802
+ console.log(`${label} stopped (pid ${target})`);
803
+ return true;
804
+ }
805
+ console.log(`Server still running after the shutdown request (pid ${target}); falling back to SIGTERM`);
806
+ return false;
807
+ };
502
808
 
503
809
  // Try PID file first
504
810
  if (pid !== null) {
505
811
  if (d.isProcessAlive(pid)) {
506
- stopped = await d.killProcess(pid, "Dashboard server");
812
+ stopped = await terminate(pid, "Dashboard server");
507
813
  } else {
508
814
  console.log("Dashboard server is not running (cleaned up stale PID file)");
509
815
  }
510
- d.removePid();
816
+ // Only a dead pid's file is stale. A process that survived the kill keeps
817
+ // its pid file so the next `stop` / `status` can still find it.
818
+ // See change: harden-dashboard-start-detection (D3).
819
+ if (!d.isProcessAlive(pid)) d.removePid();
511
820
  }
512
821
 
513
822
  // Port sweep: ownership-scoped. Non-positive ports (ephemeral) are never inspected.
@@ -524,7 +833,7 @@ export async function cmdStop(
524
833
  const { owned: mine, foreign } = partitionHolders(holders, owned);
525
834
  for (const h of mine) {
526
835
  console.log(`Killing stale process ${h.pid} on port(s) ${h.ports.join(",")}`);
527
- await d.killProcess(h.pid, `Stale process on port ${h.ports.join(",")}`);
836
+ await terminate(h.pid, `Stale process on port ${h.ports.join(",")}`);
528
837
  }
529
838
  const dir = getDashboardConfigDir();
530
839
  for (const h of foreign) {
@@ -542,6 +851,10 @@ export async function cmdStop(
542
851
  if (!stopped && pid === null) {
543
852
  console.log("Dashboard server is not running");
544
853
  }
854
+ if (provenStopped && healthProven) {
855
+ const note = desktopAppNote(healthProven.health);
856
+ if (note) console.log(note);
857
+ }
545
858
  }
546
859
 
547
860
  /**
@@ -585,13 +898,15 @@ async function cmdRestartImpl(
585
898
  const status = await probe(config.port);
586
899
  if (status.running) {
587
900
  console.log(
588
- `[restart] dashboard running at http://localhost:${config.port}, delegating to /api/restart`,
901
+ `[restart] dashboard running at ${localBase(config)}, delegating to /api/restart`,
589
902
  );
590
903
  try {
591
- const res = await fetchFn(`http://localhost:${config.port}/api/restart`, {
904
+ const restartUrl = `${localBase(config)}/api/restart`;
905
+ const res = await fetchFn(restartUrl, {
592
906
  method: "POST",
593
- // The local token proves the caller is on this host (needed under requireLocalProof).
594
- headers: { "content-type": "application/json", ...localTokenHeader() },
907
+ // A per-request proof of the local token proves the caller is on this host
908
+ // (needed under requireLocalProof); the raw token never leaves this process.
909
+ headers: { "content-type": "application/json", ...localCredentialHeaders("POST", restartUrl) },
595
910
  body: JSON.stringify({ dev: !!config.dev }),
596
911
  });
597
912
  if (res.ok) {
@@ -643,7 +958,7 @@ function stripTrailingSlashes(u: string): string {
643
958
 
644
959
  export async function cmdTokenCreate(
645
960
  argv: string[],
646
- opts: { port: number },
961
+ opts: { port: number; host?: string },
647
962
  deps: TokenCreateDeps = {},
648
963
  ): Promise<number> {
649
964
  const out = deps.out ?? ((l: string) => console.log(l));
@@ -673,14 +988,17 @@ export async function cmdTokenCreate(
673
988
 
674
989
  const localToken = deps.localToken !== undefined ? deps.localToken : safeEnsureLocalToken();
675
990
  const base = `http://localhost:${opts.port}`;
991
+ // Requests dial the address LITERAL the proof is bound to; `base` is only printed.
992
+ const dial = localBase(opts);
676
993
 
677
994
  let minted: { token: string };
678
995
  try {
679
- const res = await fetchFn(`${base}/api/paired-devices`, {
996
+ const mintUrl = `${dial}/api/paired-devices`;
997
+ const res = await fetchFn(mintUrl, {
680
998
  method: "POST",
681
999
  headers: {
682
1000
  "content-type": "application/json",
683
- ...(localToken ? { [LOCAL_TOKEN_HEADER]: localToken } : {}),
1001
+ ...localCredentialHeaders("POST", mintUrl, localToken),
684
1002
  },
685
1003
  body: JSON.stringify({ label, ...(tier ? { tier } : {}) }),
686
1004
  });
@@ -704,8 +1022,9 @@ export async function cmdTokenCreate(
704
1022
  urls = [stripTrailingSlashes(url)];
705
1023
  } else {
706
1024
  try {
707
- const res = await fetchFn(`${base}/api/pair/reachable-urls`, {
708
- headers: { ...(localToken ? { [LOCAL_TOKEN_HEADER]: localToken } : {}) },
1025
+ const reachableUrl = `${dial}/api/pair/reachable-urls`;
1026
+ const res = await fetchFn(reachableUrl, {
1027
+ headers: { ...localCredentialHeaders("GET", reachableUrl, localToken) },
709
1028
  });
710
1029
  const json = (await res.json()) as { success: boolean; data?: string[] };
711
1030
  urls = (json.success && json.data ? json.data : []).map(stripTrailingSlashes);
@@ -732,7 +1051,7 @@ export async function cmdTokenCreate(
732
1051
  */
733
1052
  export async function cmdLogin(
734
1053
  argv: string[],
735
- opts: { port: number },
1054
+ opts: { port: number; host?: string },
736
1055
  deps: TokenCreateDeps = {},
737
1056
  ): Promise<number> {
738
1057
  const out = deps.out ?? ((l: string) => console.log(l));
@@ -749,9 +1068,10 @@ export async function cmdLogin(
749
1068
  }
750
1069
  const base = `http://localhost:${opts.port}`;
751
1070
  try {
752
- const res = await fetchFn(`${base}/api/identity/local-code`, {
1071
+ const codeUrl = `${localBase(opts)}/api/identity/local-code`;
1072
+ const res = await fetchFn(codeUrl, {
753
1073
  method: "POST",
754
- headers: { "content-type": "application/json", [LOCAL_TOKEN_HEADER]: localToken },
1074
+ headers: { "content-type": "application/json", ...localCredentialHeaders("POST", codeUrl, localToken) },
755
1075
  body: "{}",
756
1076
  // A server that accepts the connection but never answers must not hang recovery.
757
1077
  signal: AbortSignal.timeout(deps.timeoutMs ?? 5000),
@@ -765,7 +1085,30 @@ export async function cmdLogin(
765
1085
  err(`[login] failed to issue a code: ${json.error ?? "unknown error"}`);
766
1086
  return 1;
767
1087
  }
768
- out(`${base}/?pi_local=${encodeURIComponent(json.data.code)}`);
1088
+ // The browser that opens the link is a plain tab: under the strict `requireLocalProof` default it
1089
+ // cannot even redeem the code (`/api/identity/local-exchange` needs proof), so route it through the
1090
+ // local-proof bootstrap first — same as `pi-dashboard open` — and land on the `pi_local` link.
1091
+ // Falls back to the plain link when no proof code can be minted.
1092
+ const plain = `/?pi_local=${encodeURIComponent(json.data.code)}`;
1093
+ let link = `${base}${plain}`;
1094
+ try {
1095
+ const proofUrl = `${localBase(opts)}/api/local-proof`;
1096
+ const pr = await fetchFn(proofUrl, {
1097
+ method: "POST",
1098
+ headers: { "content-type": "application/json", ...localCredentialHeaders("POST", proofUrl, localToken) },
1099
+ body: "{}",
1100
+ signal: AbortSignal.timeout(deps.timeoutMs ?? 5000),
1101
+ });
1102
+ if (pr.ok) {
1103
+ const pj = (await pr.json()) as { success?: boolean; data?: { code?: string } };
1104
+ if (pj.success && typeof pj.data?.code === "string") {
1105
+ link = `${base}/auth/local-proof?code=${encodeURIComponent(pj.data.code)}&next=${encodeURIComponent(plain)}`;
1106
+ }
1107
+ }
1108
+ } catch {
1109
+ /* keep the plain link */
1110
+ }
1111
+ out(link);
769
1112
  out(`Open this link on this machine within ${json.data.expiresInSeconds} s (single-use). You sign in as the local operator (break-glass).`);
770
1113
  return 0;
771
1114
  } catch (e) {
@@ -774,9 +1117,123 @@ export async function cmdLogin(
774
1117
  }
775
1118
  }
776
1119
 
777
- function localTokenHeader(): Record<string, string> {
778
- const t = safeEnsureLocalToken();
779
- return t ? { [LOCAL_TOKEN_HEADER]: t } : {};
1120
+ /** HTTP methods `pi-dashboard api` accepts. */
1121
+ const API_METHODS: ReadonlySet<string> = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
1122
+
1123
+ export interface CmdApiDeps {
1124
+ fetchImpl?: typeof fetch;
1125
+ out?: (text: string) => void;
1126
+ err?: (line: string) => void;
1127
+ /** Local token; defaults to the on-disk one (created if absent — the server owns it). */
1128
+ localToken?: string | null;
1129
+ timeoutMs?: number;
1130
+ }
1131
+
1132
+ /**
1133
+ * `pi-dashboard api <METHOD> <path> [--data <json>] [--port n]` — call the running dashboard's REST
1134
+ * API from a shell with a freshly minted local proof, which a bare `curl` cannot do under the
1135
+ * strict `requireLocalProof` default. It dials the address literal `restart` dials, sends ONE proof
1136
+ * for this method + target, and never follows a redirect (a `Location` to another origin must not
1137
+ * receive the proof's request). The path is checked by the same predicate the OAuth return-URL
1138
+ * sanitiser uses, plus `#`; a rejected path sends nothing.
1139
+ *
1140
+ * Exit: 0 on 2xx (body on stdout) · 1 on any other status (body on stderr) · 2 on a usage error
1141
+ * or when the server is not running.
1142
+ * See change: close-container-loopback-impersonation (D4).
1143
+ */
1144
+ export async function cmdApi(
1145
+ argv: string[],
1146
+ opts: { port: number; host?: string },
1147
+ deps: CmdApiDeps = {},
1148
+ ): Promise<number> {
1149
+ const out = deps.out ?? ((t: string) => process.stdout.write(t.endsWith("\n") ? t : `${t}\n`));
1150
+ const err = deps.err ?? ((l: string) => console.error(l));
1151
+ const usage = (why: string): number => {
1152
+ err(`[api] ${why}`);
1153
+ err("usage: pi-dashboard api <GET|POST|PUT|PATCH|DELETE> </path> [--data <json>] [--port <n>]");
1154
+ return 2;
1155
+ };
1156
+
1157
+ const positionals: string[] = [];
1158
+ let data: string | undefined;
1159
+ for (let i = 0; i < argv.length; i++) {
1160
+ const a = argv[i] as string;
1161
+ if (a === "--data") {
1162
+ data = argv[++i];
1163
+ if (data === undefined) return usage("--data needs a JSON value");
1164
+ } else if (a.startsWith("-")) {
1165
+ if (VALUE_FLAGS.has(a)) i++; // --port/--host value: already applied by buildConfig
1166
+ } else {
1167
+ positionals.push(a);
1168
+ }
1169
+ }
1170
+ if (positionals.length !== 2) return usage("expected a method and a path");
1171
+ const method = (positionals[0] as string).toUpperCase();
1172
+ const target = positionals[1] as string;
1173
+ if (!API_METHODS.has(method)) return usage(`unsupported method ${terminalSafe(positionals[0] as string, 20)}`);
1174
+ if (!isSafeLocalPath(target) || target.includes("#")) return usage("path must be a same-origin path starting with a single '/' (no '#', no control characters)");
1175
+ if (data !== undefined) {
1176
+ try {
1177
+ JSON.parse(data);
1178
+ } catch {
1179
+ return usage("--data must be valid JSON");
1180
+ }
1181
+ }
1182
+
1183
+ const url = `${localBase(opts)}${target}`;
1184
+ const token = deps.localToken !== undefined ? deps.localToken : safeEnsureLocalToken();
1185
+ const fetchFn = deps.fetchImpl ?? fetch;
1186
+ let res: Response;
1187
+ try {
1188
+ res = await fetchFn(url, {
1189
+ method,
1190
+ redirect: "manual",
1191
+ headers: {
1192
+ ...(data !== undefined ? { "content-type": "application/json" } : {}),
1193
+ ...localCredentialHeaders(method, url, token),
1194
+ },
1195
+ ...(data !== undefined ? { body: data } : {}),
1196
+ signal: AbortSignal.timeout(deps.timeoutMs ?? 30_000),
1197
+ });
1198
+ } catch (e) {
1199
+ err(`[api] dashboard server not running at ${localBase(opts)} (${(e as Error).message ?? e})`);
1200
+ return 2;
1201
+ }
1202
+ const body = await res.text().catch(() => "");
1203
+ if (res.status >= 200 && res.status < 300) {
1204
+ if (body) out(body);
1205
+ return 0;
1206
+ }
1207
+ if (body) err(body);
1208
+ else err(`[api] HTTP ${res.status}`);
1209
+ return 1;
1210
+ }
1211
+
1212
+ /** The dial base for local calls: the address LITERAL the server's bind maps to, never `localhost`. */
1213
+ function localBase(c: { host?: string; port: number }): string {
1214
+ return `http://${localDialHost(c.host)}:${c.port}`;
1215
+ }
1216
+
1217
+ /**
1218
+ * `X-Pi-Local-Proof` for ONE request (a proof is single-use: bound to the dialled
1219
+ * address literal, the method and the request target). The raw token never leaves
1220
+ * this process. No token ⇒ no credential header.
1221
+ * See change: loopback-credential-proof (D10).
1222
+ */
1223
+ function localCredentialHeaders(
1224
+ method: string,
1225
+ url: string,
1226
+ token: string | null | undefined = safeEnsureLocalToken(),
1227
+ ): Record<string, string> {
1228
+ if (!token) return {};
1229
+ try {
1230
+ return httpProofHeaders(token, url, method);
1231
+ } catch (e) {
1232
+ // A proof binds an address LITERAL; a host-name bind (`config.host`) has none.
1233
+ // Send no credential (the server answers 401) rather than crash with a raw error.
1234
+ console.error(`[cli] cannot mint a local credential proof for ${url}: ${(e as Error).message}. Set "host" in config.json to an IP address.`);
1235
+ return {};
1236
+ }
780
1237
  }
781
1238
 
782
1239
  /**
@@ -805,11 +1262,26 @@ function openUrlInBrowser(url: string): void {
805
1262
  */
806
1263
  export async function cmdOpen(
807
1264
  config: ServerConfig,
808
- opts: { print?: boolean; out?: (s: string) => void; err?: (s: string) => void; fetchImpl?: typeof fetch; open?: (url: string) => void } = {},
1265
+ opts: {
1266
+ print?: boolean;
1267
+ /** Origin the browser is sent to (default `http://localhost:<port>`); see {@link validateOpenUrl}. */
1268
+ url?: string;
1269
+ out?: (s: string) => void;
1270
+ err?: (s: string) => void;
1271
+ fetchImpl?: typeof fetch;
1272
+ open?: (url: string) => void;
1273
+ } = {},
809
1274
  ): Promise<number> {
810
1275
  const out = opts.out ?? ((s: string) => console.log(s));
811
1276
  const err = opts.err ?? ((s: string) => console.error(s));
812
1277
  const fetchFn = opts.fetchImpl ?? fetch;
1278
+ // `--url` is validated BEFORE a token is touched or a code is minted: the code is a 60 s
1279
+ // bearer for a proof cookie, so it must never be aimed at a foreign origin.
1280
+ const checked = opts.url === undefined ? undefined : validateOpenUrl(opts.url, config.port);
1281
+ if (checked && !checked.ok) {
1282
+ err(`refusing --url: ${checked.reason}`);
1283
+ return 2;
1284
+ }
813
1285
  const base = `http://localhost:${config.port}`;
814
1286
  const token = safeEnsureLocalToken();
815
1287
  if (!token) {
@@ -818,9 +1290,10 @@ export async function cmdOpen(
818
1290
  }
819
1291
  let code: string | undefined;
820
1292
  try {
821
- const res = await fetchFn(`${base}/api/local-proof`, {
1293
+ const proofUrl = `${localBase(config)}/api/local-proof`;
1294
+ const res = await fetchFn(proofUrl, {
822
1295
  method: "POST",
823
- headers: { [LOCAL_TOKEN_HEADER]: token },
1296
+ headers: localCredentialHeaders("POST", proofUrl, token),
824
1297
  signal: AbortSignal.timeout(5000),
825
1298
  });
826
1299
  if (!res.ok) {
@@ -838,12 +1311,39 @@ export async function cmdOpen(
838
1311
  err("server returned no valid local-proof code");
839
1312
  return 1;
840
1313
  }
841
- const url = `${base}/auth/local-proof?code=${encodeURIComponent(code)}`;
1314
+ const launchBase = checked?.ok ? checked.origin : base;
1315
+ const url = `${launchBase}/auth/local-proof?code=${encodeURIComponent(code)}`;
842
1316
  out(url);
843
1317
  if (!opts.print) (opts.open ?? openUrlInBrowser)(url);
844
1318
  return 0;
845
1319
  }
846
1320
 
1321
+ /**
1322
+ * `pi-dashboard open --url` bound (D7): http/https, no userinfo / query / fragment,
1323
+ * path `/` at most, and a loopback host on the CONFIGURED server port
1324
+ * (`isLauncherOrigin`, the predicate the server's `authorize-browser` remedy uses).
1325
+ */
1326
+ function validateOpenUrl(raw: string, configPort: number): { ok: true; origin: string } | { ok: false; reason: string } {
1327
+ let u: URL;
1328
+ try {
1329
+ u = new URL(raw);
1330
+ } catch {
1331
+ return { ok: false, reason: "not a valid URL" };
1332
+ }
1333
+ if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, reason: "scheme must be http or https" };
1334
+ if (u.username || u.password) return { ok: false, reason: "the URL must not carry credentials (user:password@)" };
1335
+ if (raw.includes("?") || raw.includes("#")) return { ok: false, reason: "the URL must not carry a query or fragment" };
1336
+ if (u.pathname !== "/") return { ok: false, reason: "the URL must be an origin only (no path)" };
1337
+ const port = u.port || (u.protocol === "https:" ? "443" : "80");
1338
+ if (!isLauncherOrigin(u.hostname, port, configPort)) {
1339
+ return {
1340
+ ok: false,
1341
+ reason: `only a loopback origin on the configured port ${configPort} is accepted (open the dashboard on http://localhost:${configPort}, or run \`pi-dashboard pair approve\`)`,
1342
+ };
1343
+ }
1344
+ return { ok: true, origin: `${u.protocol}//${u.host}` };
1345
+ }
1346
+
847
1347
  function safeEnsureLocalToken(): string | null {
848
1348
  try {
849
1349
  return ensureLocalToken();
@@ -852,61 +1352,469 @@ function safeEnsureLocalToken(): string | null {
852
1352
  }
853
1353
  }
854
1354
 
1355
+ // ── `pi-dashboard pair` — host-side approval of a pending device ─────────────
1356
+ // Uses ONLY the existing routes (GET /api/pair/pending, POST /api/pair/approve-pending,
1357
+ // POST /api/pair/deny) with a single-use `X-Pi-Local-Proof` minted from the READ-ONLY
1358
+ // local token: no new route, no guard change, no authority beyond the token file.
1359
+ // See change: fix-pairing-approval-credential (D2, D3, D8, D9, D10, D12).
1360
+
1361
+ /** Exit status classes (D3 / P1). */
1362
+ const PAIR_EXIT = { usage: 2, credential: 1, refused: 3, unreachable: 4 } as const;
1363
+
1364
+ const PAIR_USAGE =
1365
+ "usage: pi-dashboard pair list [--json] | approve [<pendingId>] [--code <8 digits>] [--name <label>] [--tier observe|control|operate] | deny <pendingId>";
1366
+
1367
+ /** Print-boundary caps in Unicode code points (D8 / P4). `pendingId` is printed in full. */
1368
+ const PAIR_CAPS = { requesterName: 64, userAgent: 120, viaHost: 64, remoteAddress: 64 } as const;
1369
+ const PENDING_ID_CAP = Number.MAX_SAFE_INTEGER;
1370
+
1371
+ /** The pending-request fields the CLI reads; a confirm code is never one of them. */
1372
+ export interface PendingRowInput {
1373
+ pendingId: string;
1374
+ provenance?: string;
1375
+ requesterName?: string;
1376
+ unencrypted?: boolean;
1377
+ userAgent?: string;
1378
+ viaHost?: string;
1379
+ remoteAddress?: string;
1380
+ createdAt?: number;
1381
+ expiresAt?: number;
1382
+ attemptsLeft?: number;
1383
+ }
1384
+
1385
+ /** Whitelist + sanitise one pending entry (the only shape `list` ever prints or emits). */
1386
+ function sanitizePending(p: PendingRowInput): PendingRowInput {
1387
+ const str = (v: unknown, max: number): string | undefined => (typeof v === "string" ? terminalSafe(v, max) : undefined);
1388
+ const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
1389
+ const out: PendingRowInput = {
1390
+ pendingId: terminalSafe(p.pendingId, PENDING_ID_CAP),
1391
+ provenance: str(p.provenance, 16),
1392
+ requesterName: str(p.requesterName, PAIR_CAPS.requesterName),
1393
+ unencrypted: typeof p.unencrypted === "boolean" ? p.unencrypted : undefined,
1394
+ userAgent: str(p.userAgent, PAIR_CAPS.userAgent),
1395
+ viaHost: str(p.viaHost, PAIR_CAPS.viaHost),
1396
+ remoteAddress: str(p.remoteAddress, PAIR_CAPS.remoteAddress),
1397
+ createdAt: num(p.createdAt),
1398
+ expiresAt: num(p.expiresAt),
1399
+ attemptsLeft: num(p.attemptsLeft),
1400
+ };
1401
+ for (const k of Object.keys(out) as (keyof PendingRowInput)[]) if (out[k] === undefined) delete out[k];
1402
+ return out;
1403
+ }
1404
+
855
1405
  /**
856
- * Show server status.
1406
+ * Render one pending request for the terminal: the pendingId on its own line (in
1407
+ * full, the operator pastes it back), then one `key: value` line per field. Every
1408
+ * server-supplied string passes through `terminalSafe` (D8).
857
1409
  */
1410
+ export function formatPendingRow(p: PendingRowInput, now: number = Date.now()): string[] {
1411
+ const s = sanitizePending(p);
1412
+ const lines = [s.pendingId];
1413
+ const add = (k: string, v: string | number | undefined) => {
1414
+ if (v !== undefined) lines.push(` ${k}: ${v}`);
1415
+ };
1416
+ add("name", s.requesterName);
1417
+ add("provenance", s.provenance);
1418
+ add("user-agent", s.userAgent);
1419
+ add("address", s.remoteAddress);
1420
+ add("via", s.viaHost);
1421
+ if (s.unencrypted) add("transport", "unencrypted");
1422
+ if (s.expiresAt !== undefined) add("expires in", `${Math.max(0, Math.round((s.expiresAt - now) / 1000))}s`);
1423
+ add("attempts left", s.attemptsLeft);
1424
+ return lines;
1425
+ }
858
1426
 
859
- async function cmdStatus(port: number): Promise<void> {
860
- // 1. Try mDNS discovery first
1427
+ /** `stdin` seam: non-TTY input is read for its first line; `isTTY` selects the prompt. */
1428
+ export type PairStdin = AsyncIterable<unknown> & { isTTY?: boolean };
1429
+
1430
+ export interface PairDeps {
1431
+ fetchImpl?: typeof fetch;
1432
+ out?: (line: string) => void;
1433
+ err?: (line: string) => void;
1434
+ /** Interactive code prompt (TTY only); default reads a line from the terminal. */
1435
+ prompt?: (question: string) => Promise<string>;
1436
+ stdin?: PairStdin;
1437
+ /** Local-IPC token; `undefined` reads it (read-only) from `tokenDir`; `null` = unreadable. */
1438
+ localToken?: string | null;
1439
+ /** Directory holding the `token` file (default `~/.pi/dashboard/local`). */
1440
+ tokenDir?: string;
1441
+ /** Per-request bound (ms); default 5000, the same bound as the other CLI verbs. */
1442
+ timeoutMs?: number;
1443
+ now?: () => number;
1444
+ }
1445
+
1446
+ async function defaultPairPrompt(question: string): Promise<string> {
1447
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
861
1448
  try {
862
- const servers = await discoverDashboard(2000);
863
- const local = servers.find(s => s.isLocal);
864
- if (local) {
865
- // Verify via health check for uptime info
866
- try {
867
- const res = await fetch(`http://${local.host}:${local.port}/api/health`);
868
- if (res.ok) {
869
- const data = await res.json() as { pid: number; uptime: number };
870
- console.log(`Dashboard server is running (pid ${data.pid}) on ${local.host}:${local.port}, uptime ${data.uptime}s (discovered via mDNS)`);
871
- return;
872
- }
873
- } catch { /* fall through */ }
874
- console.log(`Dashboard server discovered via mDNS at ${local.host}:${local.port} (pid ${local.pid})`);
875
- return;
1449
+ return await new Promise<string>((resolve) => rl.question(question, resolve));
1450
+ } finally {
1451
+ rl.close();
1452
+ }
1453
+ }
1454
+
1455
+ /** First line of a non-terminal stdin; `null` at EOF with no bytes. Bounded, never waits past the line. */
1456
+ async function readFirstLine(stdin: AsyncIterable<unknown>): Promise<string | null> {
1457
+ let buf = "";
1458
+ for await (const chunk of stdin) {
1459
+ buf += typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
1460
+ const nl = buf.indexOf("\n");
1461
+ if (nl >= 0) return buf.slice(0, nl);
1462
+ if (buf.length > 1024) break;
1463
+ }
1464
+ return buf.length > 0 ? buf : null;
1465
+ }
1466
+
1467
+ /** Spaces and dashes stripped (P2); `null` unless exactly 8 decimal digits. */
1468
+ function normalizePairCode(raw: string): string | null {
1469
+ const stripped = raw.replace(/[\s-]/g, "");
1470
+ return /^\d{8}$/.test(stripped) ? stripped : null;
1471
+ }
1472
+
1473
+ interface PairArgs {
1474
+ verb: "list" | "approve" | "deny";
1475
+ pendingId?: string;
1476
+ json: boolean;
1477
+ code?: string;
1478
+ name?: string;
1479
+ tier?: string;
1480
+ }
1481
+
1482
+ /** Cross-option rules for a parsed `pair` command line; a string is a usage error message. */
1483
+ function checkPairArgs(a: PairArgs): string | null {
1484
+ if (a.json && a.verb !== "list") return "--json is only valid for `list`";
1485
+ if (a.verb === "list" && a.pendingId !== undefined) return "`list` takes no pendingId";
1486
+ if (a.verb !== "approve" && (a.code !== undefined || a.name !== undefined || a.tier !== undefined)) {
1487
+ return "--code, --name and --tier are only valid for `approve`";
1488
+ }
1489
+ if (a.verb === "deny" && a.pendingId === undefined) return "`deny` needs a pendingId";
1490
+ if (a.tier !== undefined && !(TOKEN_TIERS as readonly string[]).includes(a.tier)) {
1491
+ return `invalid --tier: ${terminalSafe(a.tier, 40)} (expected ${TOKEN_TIERS.join(" | ")})`;
1492
+ }
1493
+ if (a.name !== undefined && a.name.trim() === "") return "--name must not be empty";
1494
+ return null;
1495
+ }
1496
+
1497
+ const PAIR_VALUED_FLAGS = { "--code": "code", "--name": "name", "--tier": "tier" } as const;
1498
+
1499
+ /** Apply the option at `argv[i]`; returns the index of the last argv entry it consumed, or a usage error. */
1500
+ function applyPairOption(a: PairArgs, argv: string[], i: number): number | string {
1501
+ const arg = argv[i];
1502
+ if (arg === "--json") {
1503
+ a.json = true;
1504
+ return i;
1505
+ }
1506
+ if (arg in PAIR_VALUED_FLAGS) {
1507
+ const v = argv[i + 1];
1508
+ if (v === undefined) return `${arg} needs a value`;
1509
+ a[PAIR_VALUED_FLAGS[arg as keyof typeof PAIR_VALUED_FLAGS]] = v;
1510
+ return i + 1;
1511
+ }
1512
+ if (arg === "--port" || arg === "--host" || arg === "--pi-port") return i + 1; // consumed by buildConfig
1513
+ if (arg.startsWith("--")) return `unknown option: ${terminalSafe(arg, 40)}`;
1514
+ if (a.pendingId !== undefined) return "too many arguments";
1515
+ a.pendingId = arg;
1516
+ return i;
1517
+ }
1518
+
1519
+ /** Parse `pair` argv; a string is a usage error message. */
1520
+ function parsePairArgs(argv: string[]): PairArgs | string {
1521
+ const verb = argv[0];
1522
+ if (verb !== "list" && verb !== "approve" && verb !== "deny") {
1523
+ return verb === undefined ? "missing verb" : `unknown verb: ${terminalSafe(verb, 40)}`;
1524
+ }
1525
+ const a: PairArgs = { verb, json: false };
1526
+ for (let i = 1; i < argv.length; i++) {
1527
+ const next = applyPairOption(a, argv, i);
1528
+ if (typeof next === "string") return next;
1529
+ i = next;
1530
+ }
1531
+ return checkPairArgs(a) ?? a;
1532
+ }
1533
+
1534
+ class PairUnreachable extends Error {}
1535
+ class PairNoCredential extends Error {}
1536
+
1537
+ type PairCall = (method: "GET" | "POST", route: string, body?: unknown) => Promise<{ status: number; json: unknown }>;
1538
+
1539
+ /** One HTTP call per proof (a proof is single-use); no proof header ⇒ nothing is sent (D9). */
1540
+ function makePairCall(base: string, token: string, fetchFn: typeof fetch, timeoutMs: number): PairCall {
1541
+ return async (method, route, body) => {
1542
+ const url = `${base}${route}`;
1543
+ const proof = localCredentialHeaders(method, url, token);
1544
+ if (!proof["X-Pi-Local-Proof"]) throw new PairNoCredential();
1545
+ try {
1546
+ const res = await fetchFn(url, {
1547
+ method,
1548
+ headers: { ...(body === undefined ? {} : { "content-type": "application/json" }), ...proof },
1549
+ body: body === undefined ? undefined : JSON.stringify(body),
1550
+ signal: AbortSignal.timeout(timeoutMs),
1551
+ });
1552
+ return { status: res.status, json: await res.json().catch(() => null) };
1553
+ } catch (e) {
1554
+ throw new PairUnreachable(terminalSafe((e as Error)?.message ?? String(e), 120));
876
1555
  }
877
- } catch {
878
- // mDNS failed — fall through to PID file check
1556
+ };
1557
+ }
1558
+
1559
+ const PAIR_REFUSAL_TEXT: Record<string, string> = {
1560
+ locked_out: "[pair] locked out: too many wrong codes for this request; the device must request pairing again",
1561
+ expired: "[pair] the request has expired; the device must request pairing again",
1562
+ no_pending: "[pair] no such pending request (already approved, denied or expired)",
1563
+ };
1564
+
1565
+ /** The one distinct message per server-refused outcome (exit 3). */
1566
+ function pairRefusalMessage(status: number, json: unknown, tokenFile: string): string {
1567
+ const body = (json ?? {}) as { error?: unknown; attemptsLeft?: unknown };
1568
+ const reason = typeof body.error === "string" ? body.error : "";
1569
+ if (status === 401) {
1570
+ return `[pair] credential rejected (HTTP 401): the server did not accept this host's local credential; the token at ${tokenFile} may belong to a different server or user`;
1571
+ }
1572
+ if (reason === "mismatch") {
1573
+ const n = typeof body.attemptsLeft === "number" ? body.attemptsLeft : undefined;
1574
+ return `[pair] the code does not match${n === undefined ? "" : `; ${n} ${n === 1 ? "attempt" : "attempts"} left`}`;
879
1575
  }
1576
+ const known = PAIR_REFUSAL_TEXT[status === 429 ? "locked_out" : reason];
1577
+ return known ?? `[pair] server refused: HTTP ${status}${reason ? ` ${terminalSafe(reason, 120)}` : ""}`;
1578
+ }
880
1579
 
881
- // 2. Fallback: PID file + health check
882
- const pid = readPid();
1580
+ interface PairCtx {
1581
+ call: PairCall;
1582
+ out: (l: string) => void;
1583
+ err: (l: string) => void;
1584
+ deps: PairDeps;
1585
+ tokenFile: string;
1586
+ /** Print the refusal and return exit 3 for a non-2xx answer; `null` for a 2xx. */
1587
+ refuse: (r: { status: number; json: unknown }) => number | null;
1588
+ }
883
1589
 
884
- if (pid === null) {
885
- console.log("Dashboard server is not running");
886
- process.exit(1);
887
- return;
1590
+ /** Live pending entries from the server (`pendingId` is the only field required). */
1591
+ async function fetchPending(ctx: PairCtx): Promise<{ rows: PendingRowInput[] } | { exit: number }> {
1592
+ const r = await ctx.call("GET", "/api/pair/pending");
1593
+ const data = (r.json as { data?: unknown } | null)?.data;
1594
+ if (r.status < 200 || r.status >= 300 || !Array.isArray(data)) {
1595
+ return { exit: ctx.refuse({ status: r.status, json: r.json }) ?? PAIR_EXIT.refused };
888
1596
  }
1597
+ const isRow = (p: unknown): p is PendingRowInput => typeof p === "object" && p !== null && typeof (p as { pendingId?: unknown }).pendingId === "string";
1598
+ return { rows: data.filter(isRow) };
1599
+ }
889
1600
 
890
- if (!isProcessAlive(pid)) {
891
- removePid();
892
- console.log("Dashboard server is not running (cleaned up stale PID file)");
893
- process.exit(1);
894
- return;
1601
+ async function pairList(ctx: PairCtx, json: boolean): Promise<number> {
1602
+ const l = await fetchPending(ctx);
1603
+ if ("exit" in l) return l.exit;
1604
+ if (json) ctx.out(JSON.stringify(l.rows.map(sanitizePending), null, 2));
1605
+ else if (l.rows.length === 0) ctx.out("no pending pairing requests");
1606
+ else for (const row of l.rows) for (const line of formatPendingRow(row, ctx.deps.now?.())) ctx.out(line);
1607
+ return 0;
1608
+ }
1609
+
1610
+ async function pairDeny(ctx: PairCtx, pendingId: string): Promise<number> {
1611
+ const r = await ctx.call("POST", "/api/pair/deny", { pendingId });
1612
+ const refused = ctx.refuse(r);
1613
+ if (refused !== null) return refused;
1614
+ ctx.out(`denied ${terminalSafe(pendingId, PENDING_ID_CAP)}`);
1615
+ return 0;
1616
+ }
1617
+
1618
+ /** The single pending request's id, or an exit code after printing why none could be chosen. */
1619
+ async function resolveSinglePending(ctx: PairCtx): Promise<{ pendingId: string } | { exit: number }> {
1620
+ const l = await fetchPending(ctx);
1621
+ if ("exit" in l) return l;
1622
+ if (l.rows.length === 1) return { pendingId: l.rows[0].pendingId };
1623
+ ctx.err(l.rows.length === 0 ? "[pair] no pending pairing requests" : `[pair] ${l.rows.length} pending requests; pass the pendingId to approve`);
1624
+ for (const row of l.rows) for (const line of formatPendingRow(row, ctx.deps.now?.())) ctx.out(line);
1625
+ return { exit: PAIR_EXIT.usage };
1626
+ }
1627
+
1628
+ /** Prompt (TTY) or first stdin line (P3) → 8 digits, else `null`. */
1629
+ async function readPairCode(deps: PairDeps): Promise<string | null> {
1630
+ const stdin = deps.stdin ?? (process.stdin as PairStdin);
1631
+ const raw = stdin.isTTY
1632
+ ? await (deps.prompt ?? defaultPairPrompt)("Confirmation code shown on the device (8 digits): ")
1633
+ : await readFirstLine(stdin);
1634
+ return raw === null || raw === undefined ? null : normalizePairCode(raw);
1635
+ }
1636
+
1637
+ async function pairApprove(ctx: PairCtx, a: PairArgs, presetCode: string | undefined): Promise<number> {
1638
+ let pendingId = a.pendingId;
1639
+ if (pendingId === undefined) {
1640
+ const one = await resolveSinglePending(ctx);
1641
+ if ("exit" in one) return one.exit;
1642
+ pendingId = one.pendingId;
1643
+ }
1644
+ const code = presetCode ?? (await readPairCode(ctx.deps));
1645
+ if (code === null) {
1646
+ ctx.err("[pair] expected 8 digits for the confirmation code (none given on stdin or not 8 digits)");
1647
+ return PAIR_EXIT.usage;
1648
+ }
1649
+ const r = await ctx.call("POST", "/api/pair/approve-pending", {
1650
+ pendingId,
1651
+ confirmCode: code,
1652
+ ...(a.name === undefined ? {} : { label: a.name }),
1653
+ ...(a.tier === undefined ? {} : { tier: a.tier }),
1654
+ });
1655
+ const refused = ctx.refuse(r);
1656
+ if (refused !== null) return refused;
1657
+ const device = (r.json as { data?: { label?: unknown; tier?: unknown } } | null)?.data;
1658
+ const label = typeof device?.label === "string" ? terminalSafe(device.label, PAIR_CAPS.requesterName) : undefined;
1659
+ const tier = typeof device?.tier === "string" ? terminalSafe(device.tier, 16) : undefined;
1660
+ ctx.out(`approved${label ? ` "${label}"` : ""}${tier ? ` (${tier})` : ""}`);
1661
+ return 0;
1662
+ }
1663
+
1664
+ /**
1665
+ * Credential: READ the token (never create it) and require a dial host a proof can
1666
+ * bind to (D9). A host-name bind has no address literal, so it is refused upfront.
1667
+ */
1668
+ function pairCredential(opts: { host?: string }, deps: PairDeps): { token: string; tokenFile: string } | { message: string } {
1669
+ const tokenDir = deps.tokenDir ?? defaultLocalTokenDir();
1670
+ const tokenFile = path.join(tokenDir, "token");
1671
+ const token = deps.localToken !== undefined ? deps.localToken : readLocalTokenIfPresent(tokenDir);
1672
+ if (!token) {
1673
+ return { message: `[pair] cannot read the local token (${tokenFile}); run this on the host and as the OS user that runs the server` };
1674
+ }
1675
+ const bindHost = (opts.host ?? "").trim().replace(/^\[(.*)\]$/, "$1");
1676
+ if (bindHost !== "" && bindHost.toLowerCase() !== "localhost" && !net.isIP(bindHost)) {
1677
+ return { message: `[pair] server host "${terminalSafe(bindHost, 64)}" is a name, not an IP address; set "host" in config.json to an IP literal` };
895
1678
  }
1679
+ return { token, tokenFile };
1680
+ }
1681
+
1682
+ /** Everything `cmdPair` needs after the local (no-network) checks passed. */
1683
+ interface PairRun {
1684
+ parsed: PairArgs;
1685
+ presetCode: string | undefined;
1686
+ token: string;
1687
+ tokenFile: string;
1688
+ }
896
1689
 
897
- // Try health endpoint for richer info
1690
+ /** Local checks, in order: usage, `--code` shape, credential. A failure carries its message and exit status. */
1691
+ function preparePair(argv: string[], opts: { host?: string }, deps: PairDeps): PairRun | { message: string; exit: number } {
1692
+ const parsed = parsePairArgs(argv);
1693
+ if (typeof parsed === "string") return { message: `[pair] ${parsed}\n${PAIR_USAGE}`, exit: PAIR_EXIT.usage };
1694
+ // A malformed --code is refused locally — it must not spend one of the 5 shared attempts.
1695
+ const presetCode = parsed.code === undefined ? undefined : normalizePairCode(parsed.code);
1696
+ if (presetCode === null) return { message: "[pair] expected 8 digits for the confirmation code", exit: PAIR_EXIT.usage };
1697
+ const cred = pairCredential(opts, deps);
1698
+ if ("message" in cred) return { message: cred.message, exit: PAIR_EXIT.credential };
1699
+ return { parsed, presetCode, ...cred };
1700
+ }
1701
+
1702
+ /** Exit status for a transport-level failure of a `pair` request. */
1703
+ function pairFailureExit(e: unknown, base: string, host: string | undefined, err: (l: string) => void): number {
1704
+ if (e instanceof PairNoCredential) {
1705
+ err(`[pair] cannot derive a local credential for server host ${terminalSafe(host?.trim() || "(default)", 64)}; set "host" in config.json to an IP address`);
1706
+ return PAIR_EXIT.credential;
1707
+ }
1708
+ if (e instanceof PairUnreachable) {
1709
+ err(`[pair] server not running at ${base} (${e.message})`);
1710
+ return PAIR_EXIT.unreachable;
1711
+ }
1712
+ throw e;
1713
+ }
1714
+
1715
+ /**
1716
+ * `pi-dashboard pair list | approve | deny` (D2/D3). Returns the exit code:
1717
+ * 2 usage/input, 1 credential/config, 3 server refused, 4 server unreachable.
1718
+ */
1719
+ export async function cmdPair(argv: string[], opts: { port: number; host?: string }, deps: PairDeps = {}): Promise<number> {
1720
+ const out = deps.out ?? ((l: string) => console.log(l));
1721
+ const err = deps.err ?? ((l: string) => console.error(l));
1722
+
1723
+ const run = preparePair(argv, opts, deps);
1724
+ if ("exit" in run) {
1725
+ err(run.message);
1726
+ return run.exit;
1727
+ }
1728
+ const { parsed, presetCode, token, tokenFile } = run;
1729
+
1730
+ const base = localBase(opts);
1731
+ const ctx: PairCtx = {
1732
+ call: makePairCall(base, token, deps.fetchImpl ?? fetch, deps.timeoutMs ?? 5000),
1733
+ out,
1734
+ err,
1735
+ deps,
1736
+ tokenFile,
1737
+ refuse: (r) => {
1738
+ if (r.status >= 200 && r.status < 300) return null;
1739
+ err(pairRefusalMessage(r.status, r.json, tokenFile));
1740
+ return PAIR_EXIT.refused;
1741
+ },
1742
+ };
898
1743
  try {
899
- const res = await fetch(`http://localhost:${port}/api/health`);
900
- if (res.ok) {
901
- const data = await res.json() as { pid: number; uptime: number };
902
- console.log(`Dashboard server is running (pid ${data.pid}) on port ${port}, uptime ${data.uptime}s`);
903
- return;
904
- }
1744
+ if (parsed.verb === "list") return await pairList(ctx, parsed.json);
1745
+ if (parsed.verb === "deny") return await pairDeny(ctx, parsed.pendingId as string);
1746
+ return await pairApprove(ctx, parsed, presetCode);
1747
+ } catch (e) {
1748
+ return pairFailureExit(e, base, opts.host, err);
1749
+ }
1750
+ }
1751
+
1752
+ /** Injectable seams of `cmdStatus` (tests); production passes none. */
1753
+ export interface StatusDeps {
1754
+ classify: (config: ServerConfig) => Promise<PortClassification>;
1755
+ discover: typeof discoverDashboard;
1756
+ readPid: () => number | null;
1757
+ isProcessAlive: (pid: number) => boolean;
1758
+ exit: (code: number) => void;
1759
+ }
1760
+
1761
+ /**
1762
+ * Show server status for the RESOLVED port. mDNS contributes only a hostname
1763
+ * hint (a record on another port is ignored); the verdict and exit code come
1764
+ * from the same classifier as `start`.
1765
+ * See change: harden-dashboard-start-detection (D8).
1766
+ */
1767
+ export async function cmdStatus(
1768
+ config: Pick<ServerConfig, "port" | "piPort" | "host">,
1769
+ injected?: Partial<StatusDeps>,
1770
+ ): Promise<void> {
1771
+ const d: StatusDeps = {
1772
+ classify: (c) => classifyDashboardPort(c),
1773
+ discover: discoverDashboard,
1774
+ readPid,
1775
+ isProcessAlive,
1776
+ exit: (code) => process.exit(code),
1777
+ ...injected,
1778
+ };
1779
+
1780
+ let hostHint: string | null = null;
1781
+ try {
1782
+ const servers = await d.discover(2000);
1783
+ hostHint = servers.find((s) => s.isLocal && s.port === config.port)?.host ?? null;
905
1784
  } catch {
906
- // Fall back to basic info
1785
+ // mDNS failed — the classifier does not need it
907
1786
  }
908
1787
 
909
- console.log(`Dashboard server is running (pid ${pid}) on port ${port}`);
1788
+ const v = await d.classify(config as ServerConfig);
1789
+ switch (v.kind) {
1790
+ case "owned":
1791
+ console.log(
1792
+ `Dashboard server is running (pid ${v.pid}) on port ${config.port}${ownerSuffix(v)}` +
1793
+ (hostHint ? ` at ${hostHint}:${config.port} (discovered via mDNS)` : ""),
1794
+ );
1795
+ return;
1796
+ case "starting":
1797
+ console.log(`Dashboard server is starting (pid ${v.pid})`);
1798
+ return;
1799
+ case "free":
1800
+ console.log("Dashboard server is not running");
1801
+ d.exit(1);
1802
+ return;
1803
+ case "unresponsive": {
1804
+ // The lock metadata names the pid; fall back to a live pid file for the message only.
1805
+ const filePid = d.readPid();
1806
+ const pid = v.pid ?? (filePid !== null && d.isProcessAlive(filePid) ? filePid : undefined);
1807
+ const verdict = portVerdict({ kind: "unresponsive", pid }, config);
1808
+ if (verdict) for (const line of verdict.lines.slice(0, 1)) console.log(line);
1809
+ d.exit(1);
1810
+ return;
1811
+ }
1812
+ default: {
1813
+ const verdict = portVerdict(v, config);
1814
+ if (verdict) for (const line of verdict.lines) console.log(line);
1815
+ d.exit(verdict?.code ?? 1);
1816
+ }
1817
+ }
910
1818
  }
911
1819
 
912
1820
  /**
@@ -978,8 +1886,22 @@ function installCrashSafetyNet(): void {
978
1886
  });
979
1887
  }
980
1888
 
1889
+ /** Value following `flag` in argv; `""` when the flag is last (so a bare `--url` is refused, not ignored). */
1890
+ function flagValue(args: string[], flag: string): string | undefined {
1891
+ const i = args.indexOf(flag);
1892
+ return i === -1 ? undefined : (args[i + 1] ?? "");
1893
+ }
1894
+
981
1895
  async function main() {
982
1896
  installCrashSafetyNet();
1897
+ // Refuse an unknown subcommand word BEFORE anything is created or bound: an older binary fell
1898
+ // through to the foreground server for it. Flag-only invocations still run in the foreground.
1899
+ const early = classifyArgv(process.argv.slice(2));
1900
+ if (early.kind === "unknown") {
1901
+ console.error(`[cli] unknown subcommand '${terminalSafe(early.word, 40)}'`);
1902
+ console.error(CLI_USAGE);
1903
+ process.exit(2);
1904
+ }
983
1905
  ensureConfig();
984
1906
  // One-shot: rewrite a pre-flip materialized `subagentTickThrottleMs: 0`.
985
1907
  // Boot path only — `loadConfig` is a pure read called by every bridge
@@ -987,16 +1909,51 @@ async function main() {
987
1909
  migrateSubagentTickThrottle();
988
1910
 
989
1911
  const rawArgs = process.argv.slice(2);
990
- if (rawArgs[0] === "token") {
991
- const { flags } = parseArgs(rawArgs.slice(1));
992
- const config = buildConfig(flags);
993
- process.exit(await cmdTokenCreate(rawArgs.slice(1), { port: config.port }));
994
- }
995
-
996
- if (rawArgs[0] === "login") {
997
- const { flags } = parseArgs(rawArgs.slice(1));
998
- const config = buildConfig(flags);
999
- process.exit(await cmdLogin(rawArgs.slice(1), { port: config.port }));
1912
+ const cls = classifyArgv(rawArgs);
1913
+ if (cls.kind === "command") {
1914
+ // Everything but the command word: its own args plus any flags that came BEFORE it (`--port 9000 api …`).
1915
+ const rest = [...rawArgs.slice(0, cls.index), ...rawArgs.slice(cls.index + 1)];
1916
+ if (cls.word === "token") {
1917
+ const { flags } = parseArgs(rest);
1918
+ const config = buildConfig(flags);
1919
+ process.exit(await cmdTokenCreate(rest, { port: config.port, host: config.host }));
1920
+ }
1921
+ if (cls.word === "service") {
1922
+ // Managed services consumer contract. See change: add-service-registry-core.
1923
+ const { flags } = parseArgs(rest);
1924
+ const config = buildConfig(flags, () => {});
1925
+ const resolveBinary = (name: string) => {
1926
+ try {
1927
+ const r = getDefaultRegistry().resolve(name);
1928
+ return r.ok ? r.path : null;
1929
+ } catch {
1930
+ return null;
1931
+ }
1932
+ };
1933
+ process.exit(
1934
+ await cmdService(rest, {
1935
+ port: config.port,
1936
+ host: config.host,
1937
+ authHeaders: (method, target) => localCredentialHeaders(method, `${localBase(config)}${target}`),
1938
+ resolveExecSecrets: localExecSecretsResolver({ paths: servicesPaths(), run: defaultCommandRunner, resolveBinary }),
1939
+ }),
1940
+ );
1941
+ }
1942
+ if (cls.word === "pair") {
1943
+ // Host-side approval of a pending device. See change: fix-pairing-approval-credential.
1944
+ const { flags } = parseArgs(rest);
1945
+ const config = buildConfig(flags, () => {});
1946
+ process.exit(await cmdPair(rest, { port: config.port, host: config.host }));
1947
+ }
1948
+ if (cls.word === "login") {
1949
+ const { flags } = parseArgs(rest);
1950
+ const config = buildConfig(flags);
1951
+ process.exit(await cmdLogin(rest, { port: config.port, host: config.host }));
1952
+ }
1953
+ // api
1954
+ const { flags } = parseArgs(rest);
1955
+ const config = buildConfig(flags, () => {});
1956
+ process.exit(await cmdApi(rest, { port: config.port, host: config.host }));
1000
1957
  }
1001
1958
 
1002
1959
  const { subcommand, flags } = parseArgs(rawArgs);
@@ -1014,17 +1971,17 @@ async function main() {
1014
1971
  await cmdRestart(config);
1015
1972
  break;
1016
1973
  case "status":
1017
- await cmdStatus(config.port);
1974
+ await cmdStatus(config);
1018
1975
  break;
1019
1976
  case "runtime":
1020
1977
  cmdRuntime();
1021
1978
  break;
1022
1979
  case "open":
1023
- process.exit(await cmdOpen(config, { print: rawArgs.includes("--print") }));
1980
+ process.exit(await cmdOpen(config, { print: rawArgs.includes("--print"), url: flagValue(rawArgs, "--url") }));
1024
1981
  break;
1025
1982
  default:
1026
1983
  // No subcommand — run in foreground (backward compatible)
1027
- await runForeground(config);
1984
+ await cmdForeground(config);
1028
1985
  break;
1029
1986
  }
1030
1987
  }