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