@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.
- package/README.md +38 -5
- package/docs/architecture.md +1673 -75
- package/package.json +23 -15
- package/packages/extension/package.json +8 -8
- package/packages/extension/src/ask-user-tool.ts +65 -3
- package/packages/extension/src/auto-session-namer.ts +190 -50
- package/packages/extension/src/bridge-handlers/dispatch.ts +450 -0
- package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
- package/packages/extension/src/bridge-handlers/instance.ts +220 -0
- package/packages/extension/src/bridge-handlers/lifecycle.ts +1030 -0
- package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
- package/packages/extension/src/bridge-identity-log.ts +45 -0
- package/packages/extension/src/bridge.ts +480 -2510
- package/packages/extension/src/command-handler.ts +180 -11
- package/packages/extension/src/connection.ts +265 -18
- package/packages/extension/src/dashboard-context-injector.ts +26 -47
- package/packages/extension/src/empty-actionable-guard.ts +8 -3
- package/packages/extension/src/flow-event-wiring.ts +1 -1
- package/packages/extension/src/followup-buffer.ts +1 -1
- package/packages/extension/src/followup-drain.ts +79 -0
- package/packages/extension/src/local-token-header.ts +161 -17
- package/packages/extension/src/message-update-coalescer.ts +3 -1
- package/packages/extension/src/model-refresh.ts +19 -0
- package/packages/extension/src/multiselect-list.ts +6 -2
- package/packages/extension/src/multiselect-polyfill.ts +2 -2
- package/packages/extension/src/openspec-cli-shim.ts +1 -1
- package/packages/extension/src/path-gate/decide.ts +15 -41
- package/packages/extension/src/path-gate/grant-cache.ts +3 -1
- package/packages/extension/src/path-gate/handler.ts +51 -2
- package/packages/extension/src/path-gate/index.ts +12 -1
- package/packages/extension/src/path-gate/resolve.ts +6 -124
- package/packages/extension/src/path-gate/roots.ts +4 -1
- package/packages/extension/src/path-gate/suppression.ts +4 -1
- package/packages/extension/src/path-gate/yolo-link.ts +104 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
- package/packages/extension/src/project-trust.ts +119 -25
- package/packages/extension/src/prompt-expander.ts +5 -1
- package/packages/extension/src/prompt-meta.ts +64 -0
- package/packages/extension/src/provider-register.ts +87 -20
- package/packages/extension/src/role-manager.ts +5 -4
- package/packages/extension/src/server-auto-start.ts +12 -5
- package/packages/extension/src/server-launcher.ts +11 -13
- package/packages/extension/src/session-move.ts +19 -0
- package/packages/extension/src/session-sync.ts +31 -38
- package/packages/extension/src/spawn-token.ts +46 -0
- package/packages/extension/src/stream-forward-buffer.ts +161 -0
- package/packages/extension/src/subagent-frame-buffer.ts +6 -2
- package/packages/extension/src/subagent-tick-throttle.ts +3 -1
- package/packages/extension/src/vault-delivery.ts +394 -0
- package/packages/extension/src/vault-forwarder.ts +128 -0
- package/packages/extension/src/vault-masker.ts +165 -0
- package/packages/extension/src/vault-redaction.ts +181 -0
- package/packages/extension/src/vcs-info.ts +5 -2
- package/packages/server/bin/pi-dashboard.mjs +26 -89
- package/packages/server/package.json +29 -15
- package/packages/server/src/access/access-grants.ts +18 -0
- package/packages/server/src/access/agent-confirm-registry.ts +31 -13
- package/packages/server/src/access/agent-grant.ts +1 -1
- package/packages/server/src/access/agent-yolo.ts +91 -0
- package/packages/server/src/access/containment-gate.ts +28 -1
- package/packages/server/src/access/cwd-admission-log.ts +46 -0
- package/packages/server/src/access/cwd-verdict.ts +144 -0
- package/packages/server/src/access/grant-coordinator.ts +3 -1
- package/packages/server/src/access/pi-trust-mirror-service.ts +374 -0
- package/packages/server/src/access/planes.ts +10 -1
- package/packages/server/src/access/refusal-ledger.ts +6 -6
- package/packages/server/src/access/yolo-session.ts +73 -12
- package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
- package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +544 -0
- package/packages/server/src/acp-bridge/child-env.ts +73 -0
- package/packages/server/src/acp-bridge/event-log.ts +194 -0
- package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
- package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
- package/packages/server/src/acp-bridge/local-host.ts +132 -0
- package/packages/server/src/acp-bridge/main.ts +118 -0
- package/packages/server/src/acp-bridge/models.ts +33 -0
- package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
- package/packages/server/src/acp-bridge/server-requests.ts +136 -0
- package/packages/server/src/acp-bridge/session-state.ts +127 -0
- package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
- package/packages/server/src/addons/addons-catalog.ts +408 -0
- package/packages/server/src/addons/addons-folder-service.ts +347 -0
- package/packages/server/src/addons/addons-folder.ts +310 -0
- package/packages/server/src/addons/addons-service.ts +470 -0
- package/packages/server/src/addons/package-contents.ts +99 -0
- package/packages/server/src/addons/settings-entries.ts +120 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
- package/packages/server/src/auth/approval-refusal.ts +87 -0
- package/packages/server/src/auth/auth-plugin.ts +292 -79
- package/packages/server/src/auth/auth.ts +78 -7
- package/packages/server/src/auth/bearer-auth.ts +23 -1
- package/packages/server/src/auth/cors-origin.ts +10 -0
- package/packages/server/src/auth/csp.ts +6 -0
- package/packages/server/src/auth/host-admission.ts +26 -0
- package/packages/server/src/auth/host-gate.ts +6 -1
- package/packages/server/src/auth/local-credential.ts +258 -0
- package/packages/server/src/auth/local-proof.ts +7 -4
- package/packages/server/src/auth/local-token.ts +16 -0
- package/packages/server/src/auth/localhost-guard.ts +251 -8
- package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
- package/packages/server/src/auth/node-guard.ts +43 -0
- package/packages/server/src/auth/operate-required.ts +126 -0
- package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
- package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +173 -0
- package/packages/server/src/auth/passkey/passkey-routes.ts +224 -0
- package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
- package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
- package/packages/server/src/auth/passkey/requester.ts +83 -0
- package/packages/server/src/auth/passkey/rp-context.ts +98 -0
- package/packages/server/src/auth/passkey/user-directory.ts +348 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +321 -0
- package/packages/server/src/auth/provider-auth-registry.ts +35 -1
- package/packages/server/src/auth/provider-auth-storage.ts +55 -8
- package/packages/server/src/auth/radius-override.ts +13 -0
- package/packages/server/src/auth/route-tier-gate.ts +27 -11
- package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
- package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
- package/packages/server/src/auth/serve-app-host.ts +97 -0
- package/packages/server/src/auth/trust-mode-boot.ts +93 -0
- package/packages/server/src/auth/trust-mode.ts +83 -0
- package/packages/server/src/auto-name-outcome-store.ts +4 -1
- package/packages/server/src/browse.ts +114 -2
- package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
- package/packages/server/src/browser-handlers/directory-handler.ts +128 -6
- package/packages/server/src/browser-handlers/session-action-handler.ts +129 -62
- package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
- package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
- package/packages/server/src/cli.ts +883 -97
- package/packages/server/src/config-api.ts +143 -1
- package/packages/server/src/config-snapshot.ts +5 -0
- package/packages/server/src/directory-service.ts +435 -32
- package/packages/server/src/embed-lifecycle/caps.ts +35 -4
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
- package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
- package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
- package/packages/server/src/event-wiring.ts +208 -35
- package/packages/server/src/file-watch-manager.ts +187 -39
- package/packages/server/src/git-worktree/git-operations.ts +16 -5
- package/packages/server/src/git-worktree/worktree-init-trust.ts +48 -5
- package/packages/server/src/git-worktree/worktree-init.ts +7 -56
- package/packages/server/src/identity/host-resources.ts +3 -0
- package/packages/server/src/identity/http-road-classification.ts +18 -0
- package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
- package/packages/server/src/identity/plugin-identity.ts +19 -0
- package/packages/server/src/identity/policy-registry.ts +4 -1
- package/packages/server/src/identity/resolver-registry.ts +12 -3
- package/packages/server/src/identity/ws-message-scope.ts +9 -0
- package/packages/server/src/identity/ws-road-classification.ts +9 -0
- package/packages/server/src/known-server-moves.ts +175 -0
- package/packages/server/src/lib/browse-roots.ts +36 -0
- package/packages/server/src/lib/digest-gate.ts +82 -0
- package/packages/server/src/lib/file-write-lock.ts +24 -0
- package/packages/server/src/lib/folder-project.ts +439 -0
- package/packages/server/src/lib/purify.ts +13 -5
- package/packages/server/src/lib/writable-handler-target.ts +66 -0
- package/packages/server/src/lib/writable-md-target.ts +12 -1
- package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
- package/packages/server/src/lifecycle/home-lock.ts +344 -130
- package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
- package/packages/server/src/lifecycle/recovery-server.ts +77 -1
- package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
- package/packages/server/src/live-server/live-capability.ts +254 -0
- package/packages/server/src/live-server/live-server-proxy.ts +173 -26
- package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
- package/packages/server/src/model-proxy/internal-registry.ts +6 -0
- package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +109 -16
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +132 -0
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +90 -35
- package/packages/server/src/openspec/openspec-poll-worker.ts +200 -44
- package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
- package/packages/server/src/openspec/readiness.ts +9 -0
- package/packages/server/src/openspec/workflow-schema.ts +1128 -0
- package/packages/server/src/package/installed-package-enricher.ts +38 -3
- package/packages/server/src/package/package-health-scanner.ts +133 -0
- package/packages/server/src/package/package-manager-wrapper.ts +18 -2
- package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
- package/packages/server/src/package/provider-probe.ts +5 -3
- package/packages/server/src/pairing/browser-gateway.ts +108 -8
- package/packages/server/src/pairing/knock-admission.ts +277 -0
- package/packages/server/src/pairing/pairing.ts +154 -27
- package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
- package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
- package/packages/server/src/peer-servers.ts +77 -0
- package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
- package/packages/server/src/persistence/boot-state.ts +48 -1
- package/packages/server/src/persistence/memory-event-store.ts +216 -237
- package/packages/server/src/persistence/meta-persistence.ts +12 -1
- package/packages/server/src/persistence/preferences-store.ts +116 -7
- package/packages/server/src/pi/bridge-upgrade-auth.ts +32 -21
- package/packages/server/src/pi/folder-commands.ts +141 -0
- package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
- package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
- package/packages/server/src/pi/host-project-trust.ts +158 -33
- package/packages/server/src/pi/pi-gateway.ts +93 -9
- package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
- package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
- package/packages/server/src/pi/session-skill-registry.ts +13 -3
- package/packages/server/src/pi/settings-write-lock.ts +32 -0
- package/packages/server/src/pi/trust-challenges.ts +38 -0
- package/packages/server/src/pi-agent-settings.ts +701 -100
- package/packages/server/src/pi-settings-themes.ts +104 -0
- package/packages/server/src/questions/brief-generator.ts +138 -0
- package/packages/server/src/questions/brief-model.ts +55 -0
- package/packages/server/src/questions/brief-policy.ts +36 -0
- package/packages/server/src/questions/brief-prompt.ts +92 -0
- package/packages/server/src/questions/brief-runtime.ts +50 -0
- package/packages/server/src/questions/question-answer.ts +55 -0
- package/packages/server/src/questions/question-broadcast.ts +106 -0
- package/packages/server/src/questions/question-files.ts +128 -0
- package/packages/server/src/questions/question-routes.ts +126 -0
- package/packages/server/src/questions/question-snapshot.ts +150 -0
- package/packages/server/src/questions/question-stack.ts +57 -0
- package/packages/server/src/questions/question-store.ts +477 -0
- package/packages/server/src/routes/access-prompt-routes.ts +5 -3
- package/packages/server/src/routes/access-routes.ts +123 -5
- package/packages/server/src/routes/acme-routes.ts +190 -0
- package/packages/server/src/routes/acp-routes.ts +16 -0
- package/packages/server/src/routes/addons-routes.ts +221 -0
- package/packages/server/src/routes/file-routes.ts +366 -75
- package/packages/server/src/routes/file-write-binary-routes.ts +473 -0
- package/packages/server/src/routes/folder-project-routes.ts +99 -0
- package/packages/server/src/routes/git-routes.ts +17 -2
- package/packages/server/src/routes/known-servers-routes.ts +333 -53
- package/packages/server/src/routes/live-server-routes.ts +72 -4
- package/packages/server/src/routes/local-proof-routes.ts +12 -7
- package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
- package/packages/server/src/routes/model-proxy-routes.ts +4 -2
- package/packages/server/src/routes/openspec-routes.ts +270 -40
- package/packages/server/src/routes/package-health-routes.ts +140 -0
- package/packages/server/src/routes/package-routes.ts +28 -1
- package/packages/server/src/routes/pairing-routes.ts +158 -24
- package/packages/server/src/routes/pi-retry-routes.ts +18 -2
- package/packages/server/src/routes/pi-settings-routes.ts +264 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +87 -27
- package/packages/server/src/routes/provider-auth-routes.ts +22 -5
- package/packages/server/src/routes/provider-routes.ts +29 -0
- package/packages/server/src/routes/resource-activation-routes.ts +16 -32
- package/packages/server/src/routes/session-routes.ts +49 -5
- package/packages/server/src/routes/system-routes.ts +207 -23
- package/packages/server/src/routes/tls-routes.ts +55 -0
- package/packages/server/src/routes/user-routes.ts +192 -0
- package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
- package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
- package/packages/server/src/server.ts +919 -139
- package/packages/server/src/services/attached-driver.ts +175 -0
- package/packages/server/src/services/change-notifier.ts +55 -0
- package/packages/server/src/services/cli-service.ts +450 -0
- package/packages/server/src/services/command-runner.ts +92 -0
- package/packages/server/src/services/definitions-store.ts +121 -0
- package/packages/server/src/services/driver.ts +112 -0
- package/packages/server/src/services/health.ts +94 -0
- package/packages/server/src/services/leases.ts +117 -0
- package/packages/server/src/services/log-text.ts +97 -0
- package/packages/server/src/services/native-driver.ts +283 -0
- package/packages/server/src/services/oci-driver.ts +590 -0
- package/packages/server/src/services/output-capture.ts +183 -0
- package/packages/server/src/services/paths.ts +82 -0
- package/packages/server/src/services/ports.ts +26 -0
- package/packages/server/src/services/routes.ts +140 -0
- package/packages/server/src/services/runtime-detect.ts +108 -0
- package/packages/server/src/services/secret-delivery.ts +61 -0
- package/packages/server/src/services/secrets-resolver.ts +145 -0
- package/packages/server/src/services/secrets-store.ts +137 -0
- package/packages/server/src/services/service-manager.ts +1565 -0
- package/packages/server/src/services/start-record.ts +66 -0
- package/packages/server/src/services/state-machine.ts +241 -0
- package/packages/server/src/session/archive-sweeper.ts +92 -3
- package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
- package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
- package/packages/server/src/session/memory-session-manager.ts +53 -0
- package/packages/server/src/session/name-provenance.ts +102 -0
- package/packages/server/src/session/open-tool-calls.ts +15 -6
- package/packages/server/src/session/session-api.ts +47 -12
- package/packages/server/src/session/session-archive.ts +56 -4
- package/packages/server/src/session/session-diff-cache.ts +11 -4
- package/packages/server/src/session/session-load-worker-pool.ts +4 -3
- package/packages/server/src/session/session-scanner.ts +73 -3
- package/packages/server/src/session/session-to-meta.ts +15 -0
- package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
- package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
- package/packages/server/src/spawn-process/process-manager.ts +164 -30
- package/packages/server/src/spawn-process/restart-helper.ts +9 -8
- package/packages/server/src/spawn-process/server-pid.ts +16 -7
- package/packages/server/src/spawn-process/session-terminator.ts +218 -0
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
- package/packages/server/src/terminal/terminal-manager.ts +67 -1
- package/packages/server/src/tls/cert-files.ts +228 -0
- package/packages/server/src/tls/cert-manager.ts +703 -0
- package/packages/server/src/tls/cert-store.ts +69 -0
- package/packages/server/src/tls/source-registry.ts +71 -0
- package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
- package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
- package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
- package/packages/server/src/tls/sources/acme/dns.ts +303 -0
- package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
- package/packages/server/src/tls/sources/acme/entry.ts +180 -0
- package/packages/server/src/tls/sources/acme/gc.ts +78 -0
- package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
- package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
- package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
- package/packages/server/src/tls/sources/acme/types.ts +72 -0
- package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
- package/packages/server/src/tls/tls-config-validation.ts +92 -0
- package/packages/server/src/tls/tls-listener.ts +351 -0
- package/packages/server/src/tls/types.ts +80 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
- package/packages/server/src/tunnel/tunnel-core.ts +4 -1
- package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
- package/packages/server/src/vault/vault-bindings.ts +101 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +294 -0
- package/packages/server/src/vault/vault-grants.ts +260 -0
- package/packages/server/src/vault/vault-import.ts +161 -0
- package/packages/server/src/vault/vault-permissions.ts +39 -0
- package/packages/server/src/vault/vault-plugin-read.ts +64 -0
- package/packages/server/src/vault/vault-projects.ts +156 -0
- package/packages/server/src/vault/vault-routes.ts +277 -0
- package/packages/server/src/vault/vault-store.ts +371 -0
- package/packages/shared/package.json +5 -2
- package/packages/shared/src/acp/acp-config.ts +123 -0
- package/packages/shared/src/acp/normalize-v1.ts +92 -0
- package/packages/shared/src/acp/paths.ts +36 -0
- package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
- package/packages/shared/src/acp/update-model.ts +574 -0
- package/packages/shared/src/anthropic-messages-source.ts +8 -0
- package/packages/shared/src/bind-reachability.ts +21 -2
- package/packages/shared/src/boot-state.ts +6 -0
- package/packages/shared/src/browser-host-identity.ts +49 -0
- package/packages/shared/src/browser-host-ipc.ts +107 -0
- package/packages/shared/src/browser-protocol.ts +385 -71
- package/packages/shared/src/canonical-subject.ts +27 -2
- package/packages/shared/src/card-sections.ts +185 -1
- package/packages/shared/src/chrome-profiles.ts +188 -0
- package/packages/shared/src/config.ts +473 -26
- package/packages/shared/src/custom-event-groups.ts +5 -2
- package/packages/shared/src/cwd-guard.ts +381 -1
- package/packages/shared/src/dashboard-paths.ts +12 -0
- package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +71 -0
- package/packages/shared/src/dashboard-plugin/index.ts +7 -3
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +106 -2
- package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
- package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +95 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +64 -4
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +22 -3
- package/packages/shared/src/dashboard-starter.ts +30 -0
- package/packages/shared/src/display-name.ts +42 -0
- package/packages/shared/src/doctor-core.ts +25 -107
- package/packages/shared/src/enabled-models-match.ts +47 -0
- package/packages/shared/src/event-forward-declaration.ts +187 -0
- package/packages/shared/src/file-kind.ts +54 -2
- package/packages/shared/src/git-worktree-helpers.ts +8 -4
- package/packages/shared/src/grammar-types.ts +3 -1
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/host-port.ts +34 -0
- package/packages/shared/src/launcher-origin.ts +26 -0
- package/packages/shared/src/local-credential-proof.ts +219 -0
- package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
- package/packages/shared/src/markup-repair/types.ts +13 -0
- package/packages/shared/src/md-table-cell.ts +11 -0
- package/packages/shared/src/mdns-discovery.ts +392 -42
- package/packages/shared/src/models-json-reader.ts +6 -0
- package/packages/shared/src/openspec-design-evidence.ts +25 -1
- package/packages/shared/src/openspec-poller.ts +210 -9
- package/packages/shared/src/openspec-status-all.ts +393 -0
- package/packages/shared/src/operate-required.ts +29 -0
- package/packages/shared/src/pairing-knock-client.ts +261 -0
- package/packages/shared/src/pairing-knock.ts +71 -0
- package/packages/shared/src/pairing-refusal.ts +32 -0
- package/packages/shared/src/path-containment-guard-name.ts +8 -0
- package/packages/shared/src/pi-settings-keys.ts +9 -0
- package/packages/shared/src/pi-settings-schema.ts +285 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +200 -0
- package/packages/shared/src/pi-trust-mirror-types.ts +57 -0
- package/packages/shared/src/pi-trust-mirror.ts +328 -0
- package/packages/shared/src/platform/binary-lookup.ts +2 -194
- package/packages/shared/src/platform/git.ts +204 -4
- package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
- package/packages/shared/src/platform/native-ts-register.mjs +22 -10
- package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
- package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
- package/packages/shared/src/platform/node-spawn.ts +1 -2
- package/packages/shared/src/platform/openspec.ts +129 -31
- package/packages/shared/src/platform/process-scan.ts +199 -1
- package/packages/shared/src/platform/process.ts +51 -0
- package/packages/shared/src/platform/runner.ts +46 -2
- package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
- package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
- package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
- package/packages/shared/src/plugin-bridge-register.ts +24 -1
- package/packages/shared/src/project-name.ts +42 -0
- package/packages/shared/src/prompt-answer.ts +183 -0
- package/packages/shared/src/protocol.ts +133 -8
- package/packages/shared/src/question-types.ts +73 -0
- package/packages/shared/src/recommended-extensions.ts +80 -23
- package/packages/shared/src/recovery-timing.ts +12 -0
- package/packages/shared/src/redaction.ts +50 -0
- package/packages/shared/src/rest-api.ts +484 -1
- package/packages/shared/src/role-config-disk.ts +23 -0
- package/packages/shared/src/role-schema.ts +79 -0
- package/packages/shared/src/route-tiers.ts +127 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
- package/packages/shared/src/server-identity.ts +51 -15
- package/packages/shared/src/server-launcher.ts +12 -33
- package/packages/shared/src/server-pinning.ts +81 -0
- package/packages/shared/src/services/offers.ts +114 -0
- package/packages/shared/src/services/schema.ts +628 -0
- package/packages/shared/src/services/status.ts +169 -0
- package/packages/shared/src/session-meta.ts +59 -2
- package/packages/shared/src/session-name.ts +8 -0
- package/packages/shared/src/skill-block-parser.ts +14 -0
- package/packages/shared/src/source-matching.ts +5 -1
- package/packages/shared/src/state-replay.ts +19 -0
- package/packages/shared/src/terminal-safe.ts +24 -0
- package/packages/shared/src/tls-status.ts +69 -0
- package/packages/shared/src/tool-path-resolve.ts +243 -0
- package/packages/shared/src/tool-registry/definitions.ts +26 -4
- package/packages/shared/src/tool-registry/index.ts +2 -2
- package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
- package/packages/shared/src/tunnel-provider.ts +3 -2
- package/packages/shared/src/types.ts +104 -9
- package/packages/shared/src/vault-delivery.ts +73 -0
- package/packages/shared/src/vault-origin.ts +51 -0
- package/packages/shared/src/vault-project-key.ts +53 -0
- package/packages/shared/src/worktree-init-hook.ts +69 -0
- package/packages/shared/src/ws-message-tiers.ts +135 -0
- package/tsconfig.base.json +1 -0
|
@@ -8,29 +8,31 @@ import os from "node:os";
|
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
10
10
|
import { fileURLToPath } from "node:url";
|
|
11
|
-
import { createGatedProviderAuth, createIsPiExtensionInstalled, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, resolvePluginEnabled } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
11
|
+
import { createGatedProviderAuth, createIsPiExtensionInstalled, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, resolvePluginEnabled } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
12
|
+
import {
|
|
13
|
+
createMcpClientConfigService,
|
|
14
|
+
createRealConfigIO,
|
|
15
|
+
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
12
16
|
import type { ExitIntent } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
|
|
13
17
|
import { isRecoveryAllowed } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
|
|
14
18
|
import { findBundledExtension, registerBridgeExtension } from "@blackbelt-technology/pi-dashboard-shared/bridge-register.js";
|
|
15
19
|
import type { PackageOperationCompleteMessage, ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
|
|
16
20
|
import type { AuthConfig, DashboardConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
17
|
-
import fastifyCookie from "@fastify/cookie";
|
|
18
|
-
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
19
21
|
import { CONFIG_DIR, CONFIG_FILE, getPluginConfig as getPluginConfigFromFile, loadConfig, resolvePublicBaseUrls, writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
20
|
-
import { createPushService, type PushService } from "./push/push-service.js";
|
|
21
|
-
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
22
22
|
import { CustomEventGroupsStore } from "@blackbelt-technology/pi-dashboard-shared/custom-event-groups-store.js";
|
|
23
|
-
import
|
|
23
|
+
import { parseFileHandlerClaimKey } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/file-handler.js";
|
|
24
24
|
import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
|
|
25
|
-
import {
|
|
25
|
+
import type { HostAction, HostResource, Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
|
|
26
|
+
import { advertiseDashboard, createBrowser, type DashboardBrowser, type DiscoveredServer, resolveAdvertisedAddresses, stopAdvertising } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
26
27
|
import { DEFAULT_MEMORY_LIMITS } from "@blackbelt-technology/pi-dashboard-shared/memory-limits.js";
|
|
27
28
|
import { setWindowsGitSourceSetting } from "@blackbelt-technology/pi-dashboard-shared/platform/git-source.js";
|
|
28
29
|
import {
|
|
29
|
-
reconcilePluginBridgePackages,
|
|
30
30
|
deregisterPluginBridge,
|
|
31
|
-
|
|
31
|
+
reconcilePluginBridgePackages,
|
|
32
|
+
syncPluginBridges,
|
|
32
33
|
} from "@blackbelt-technology/pi-dashboard-shared/plugin-bridge-register.js";
|
|
33
|
-
import {
|
|
34
|
+
import type { PluginRequestMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
35
|
+
import { RECOVERY_REATTACH_GRACE_MS, RECOVERY_SHUTDOWN_WINDOW_MS } from "@blackbelt-technology/pi-dashboard-shared/recovery-timing.js";
|
|
34
36
|
import {
|
|
35
37
|
deriveEffectiveSource,
|
|
36
38
|
deriveLocalIdentity,
|
|
@@ -38,40 +40,52 @@ import {
|
|
|
38
40
|
readRuntimeRequest,
|
|
39
41
|
readRuntimeState,
|
|
40
42
|
} from "@blackbelt-technology/pi-dashboard-shared/runtime-overlay/state.js";
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
43
|
+
import { createSemaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
|
|
44
|
+
import { proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
|
|
45
|
+
import { discoverServiceOffers } from "@blackbelt-technology/pi-dashboard-shared/services/offers.js";
|
|
46
|
+
import { isRecoveryCandidate, isShutdownWindowCandidate, mergeSessionMeta, type SessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
|
|
47
|
+
import { rank } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
|
|
48
|
+
import { getDefaultRegistry, resolveInstallRoot } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
|
|
43
49
|
import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
50
|
+
import { LIVE_PREVIEW_TIER, TERMINAL_TIER } from "@blackbelt-technology/pi-dashboard-shared/ws-message-tiers.js";
|
|
44
51
|
import compress from "@fastify/compress";
|
|
52
|
+
import fastifyCookie from "@fastify/cookie";
|
|
45
53
|
import cors from "@fastify/cors";
|
|
46
54
|
import rateLimit from "@fastify/rate-limit";
|
|
47
55
|
import fastifyStatic from "@fastify/static";
|
|
48
|
-
import Fastify from "fastify";
|
|
56
|
+
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
|
|
57
|
+
import { listGrants as listAccessGrants, setGrantsChangedListener } from "./access/access-grants.js";
|
|
49
58
|
import { snapshotAccessGrantHealth } from "./access/access-health.js";
|
|
50
59
|
import { AccessPlaneRegistry, isGrantPromptKilled } from "./access/access-plane.js";
|
|
51
60
|
import { shouldIssuePromptCapability } from "./access/capability-issuance.js";
|
|
52
61
|
import { createCorsDenialObserver } from "./access/cors-denial.js";
|
|
62
|
+
import { createIndeterminateLogger } from "./access/cwd-admission-log.js";
|
|
63
|
+
import { createCwdHold } from "./access/cwd-verdict.js";
|
|
53
64
|
import { installGrantCoordinator } from "./access/denial-hold.js";
|
|
54
65
|
import { GrantCoordinator } from "./access/grant-coordinator.js";
|
|
55
66
|
import { ensureGrantStoreId } from "./access/grant-store-id.js";
|
|
67
|
+
import { createPiTrustMirrorService, setPiTrustMirror } from "./access/pi-trust-mirror-service.js";
|
|
56
68
|
import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane } from "./access/planes.js";
|
|
57
69
|
import { promptChannelCount } from "./access/prompt-channel.js";
|
|
58
70
|
import { clearRefusal, isRefused, listRefusals, recordRefusal } from "./access/refusal-ledger.js";
|
|
59
71
|
import { sourceChannel } from "./access/source-channel.js";
|
|
60
72
|
import { YOLO_ENV } from "./access/yolo-env.js";
|
|
61
73
|
import { YoloController } from "./access/yolo-session.js";
|
|
74
|
+
import { scanAcpSessions } from "./acp-bridge/acp-restore.js";
|
|
75
|
+
import { stopAllLocalAcpSessions } from "./acp-bridge/local-host.js";
|
|
62
76
|
import { createFitWorkerPool } from "./attachments/fit-worker-pool.js";
|
|
63
77
|
import { resolveRedirectBase } from "./auth/auth.js";
|
|
64
|
-
import { authorizeWsUpgrade, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
78
|
+
import { authorizeWsUpgrade, buildLoginAvailable, effectiveSessionTier, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
65
79
|
import { registerBearerAuth, registerDeviceSessionRoutes } from "./auth/bearer-auth.js";
|
|
80
|
+
import { beginFlow, pluginFlowProvider } from "./auth/begin-flow.js";
|
|
66
81
|
import {
|
|
67
82
|
computeBindReachability,
|
|
68
83
|
formatBindReachabilityWarning,
|
|
69
84
|
initBindReachability,
|
|
70
85
|
} from "./auth/bind-reachability-service.js";
|
|
71
|
-
import { registerLocalProofRoutes } from "./routes/local-proof-routes.js";
|
|
72
|
-
import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
|
|
73
86
|
import { decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
74
87
|
import {
|
|
88
|
+
CORS_ALLOWED_METHODS,
|
|
75
89
|
type CorsOriginOptions,
|
|
76
90
|
isCorsOriginAllowed,
|
|
77
91
|
isPluginWsOriginAdmitted,
|
|
@@ -89,24 +103,32 @@ import {
|
|
|
89
103
|
resolveHostGateMode,
|
|
90
104
|
} from "./auth/host-gate.js";
|
|
91
105
|
import { ensureServerIdentity } from "./auth/identity.js";
|
|
92
|
-
import {
|
|
106
|
+
import { createLocalCredentialVerifier, hasLocalCredential, listenWithProofFloor } from "./auth/local-credential.js";
|
|
107
|
+
import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
|
|
108
|
+
import { ensureLocalToken } from "./auth/local-token.js";
|
|
93
109
|
import {
|
|
110
|
+
createLanInterfaceProvider,
|
|
94
111
|
createNetworkGuard,
|
|
95
112
|
createNetworkGuardHook,
|
|
96
113
|
isPluginScopePeerLocal,
|
|
97
114
|
noteTrustedList,
|
|
115
|
+
parseGuardTarget,
|
|
98
116
|
setNetworkDenialObserver,
|
|
99
117
|
} from "./auth/localhost-guard.js";
|
|
100
118
|
import { createMutationOriginGate } from "./auth/mutation-origin-gate.js";
|
|
119
|
+
import { PasskeyService } from "./auth/passkey/passkey-service.js";
|
|
120
|
+
import { resolveRpContext } from "./auth/passkey/rp-context.js";
|
|
121
|
+
import { UserDirectory } from "./auth/passkey/user-directory.js";
|
|
122
|
+
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
123
|
+
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
101
124
|
import { setOAuthRegistryRuntimeSource } from "./auth/provider-auth-registry.js";
|
|
102
125
|
import { readAuthJson } from "./auth/provider-auth-storage.js";
|
|
103
|
-
import {
|
|
104
|
-
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
105
|
-
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
106
|
-
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
107
|
-
import type { PluginRequestMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
126
|
+
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
108
127
|
import { createRouteTierGate } from "./auth/route-tier-gate.js";
|
|
128
|
+
import { createHostServeApp } from "./auth/serve-app-host.js";
|
|
109
129
|
import { mintSpawnToken } from "./auth/spawn-token.js";
|
|
130
|
+
import { admissionTrustedNetworks, effectiveTrustMode } from "./auth/trust-mode.js";
|
|
131
|
+
import { decideBootTrustMode } from "./auth/trust-mode-boot.js";
|
|
110
132
|
import {
|
|
111
133
|
type CoreWsRouteScope,
|
|
112
134
|
extractTicket,
|
|
@@ -127,49 +149,61 @@ import { runLifecycleAction } from "./browser-handlers/session-lifecycle.js";
|
|
|
127
149
|
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
128
150
|
import { readRawConfig, writeConfigPartial } from "./config-api.js";
|
|
129
151
|
import {
|
|
152
|
+
liveAcceptLanRequests,
|
|
130
153
|
liveAllowedHosts,
|
|
131
154
|
liveCorsAllowedOrigins,
|
|
132
155
|
liveHostGateMode,
|
|
133
|
-
liveRequireLocalProof,
|
|
134
156
|
livePublicBaseUrls,
|
|
157
|
+
liveRequireLocalProof,
|
|
135
158
|
liveTrustedNetworks,
|
|
136
159
|
rawConfigHasHostGateMode,
|
|
137
160
|
} from "./config-snapshot.js";
|
|
138
161
|
// pending-load-manager removed — server loads sessions directly via DirectoryService
|
|
139
162
|
import { createDirectoryService, type DirectoryService } from "./directory-service.js";
|
|
140
163
|
import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycle-controller.js";
|
|
164
|
+
import { createPluginSessionCloseApi, createSessionCloserRegistry } from "./embed-lifecycle/plugin-session-close.js";
|
|
141
165
|
import { wireEvents } from "./event-wiring.js";
|
|
142
166
|
import { createFileWatchManager } from "./file-watch-manager.js";
|
|
143
167
|
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
168
|
+
import { listPersistedTrust as listPersistedWorktreeTrust, setTrustChangedListener } from "./git-worktree/worktree-init-trust.js";
|
|
144
169
|
import { identityDisarmedWarning, isIdentityEnforced } from "./identity/activation.js";
|
|
170
|
+
import { buildAuthContext } from "./identity/auth-context.js";
|
|
171
|
+
import { type BootstrapGrants, DENY_ALL_GRANTS, decideBootstrapGrants } from "./identity/bootstrap-grants.js";
|
|
172
|
+
import { BreakGlass } from "./identity/break-glass.js";
|
|
145
173
|
import { browserLoginAuthStatus } from "./identity/browser-login-auth-status.js";
|
|
146
174
|
import { BrowserLoginConfigRegistry, publicLoginConfig, sanitizeBrowserLoginConfig } from "./identity/browser-login-config-registry.js";
|
|
175
|
+
import { dispatchResolvers } from "./identity/dispatch.js";
|
|
176
|
+
import { HostActions, hostResource } from "./identity/host-resources.js";
|
|
147
177
|
import { identityFloorAllows } from "./identity/identity-floor.js";
|
|
178
|
+
import { identityMe } from "./identity/identity-me.js";
|
|
148
179
|
import { IdentityRegistrationTracker, releaseFailedIdentityRegistrations } from "./identity/identity-registration-tracker.js";
|
|
149
|
-
import { PolicyRegistry } from "./identity/policy-registry.js";
|
|
150
180
|
import { createIdentityRoadGate } from "./identity/identity-road-gate.js";
|
|
151
|
-
import {
|
|
152
|
-
import {
|
|
181
|
+
import { createPluginIdentity } from "./identity/plugin-identity.js";
|
|
182
|
+
import { PolicyRegistry } from "./identity/policy-registry.js";
|
|
153
183
|
import { registerResolverHook } from "./identity/resolver-hook.js";
|
|
154
184
|
import { ResolverRegistry } from "./identity/resolver-registry.js";
|
|
155
|
-
import {
|
|
156
|
-
import {
|
|
157
|
-
import { BreakGlass } from "./identity/break-glass.js";
|
|
158
|
-
import { dispatchResolvers } from "./identity/dispatch.js";
|
|
159
|
-
import { createPluginIdentity } from "./identity/plugin-identity.js";
|
|
185
|
+
import { getRouteOwnerRegistry } from "./identity/route-owner-registry.js";
|
|
186
|
+
import { canAccessSession, isLocalOperator, markLocalOperator, sessionPrincipalOf } from "./identity/session-access.js";
|
|
160
187
|
import { scheduleAtExpiry } from "./identity/socket-lifetime.js";
|
|
161
188
|
import { authorizeRoadUpgrade } from "./identity/upgrade-gate.js";
|
|
162
|
-
import {
|
|
163
|
-
import { canAccessSession, isLocalOperator, markLocalOperator, sessionPrincipalOf } from "./identity/session-access.js";
|
|
189
|
+
import { createKnownServerMoves } from "./known-server-moves.js";
|
|
164
190
|
import {
|
|
165
191
|
clientBuildDiagnostic,
|
|
166
192
|
clientBuildSnapshotFor,
|
|
167
193
|
resolveStaticClientDir,
|
|
168
194
|
} from "./lib/client-dist.js";
|
|
195
|
+
import { collectRuleSources } from "./lib/folder-project.js";
|
|
169
196
|
import { bootParentPid, isBootParentProvablyDead } from "./lifecycle/boot-parent-liveness.js";
|
|
170
197
|
import { runBoundedStartup } from "./lifecycle/bounded-startup.js";
|
|
171
198
|
import { startEphemeralParentWatch } from "./lifecycle/ephemeral-parent-watch.js";
|
|
172
199
|
import { ensureInstanceId } from "./lifecycle/instance-id.js";
|
|
200
|
+
import {
|
|
201
|
+
createLiveCapabilityHook,
|
|
202
|
+
LiveCapabilityStore,
|
|
203
|
+
parseCapabilityPath,
|
|
204
|
+
redactCapability,
|
|
205
|
+
sessionKeyOf,
|
|
206
|
+
} from "./live-server/live-capability.js";
|
|
173
207
|
import { createLiveServerManager } from "./live-server/live-server-manager.js";
|
|
174
208
|
import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
175
209
|
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
@@ -181,10 +215,15 @@ import { getServerModelRuntime } from "./model-proxy/server-model-runtime.js";
|
|
|
181
215
|
import { callPiAiStreamSimple } from "./model-proxy/streamer.js";
|
|
182
216
|
import { currentGlobalWorkflowSignature } from "./openspec/global-signature.js";
|
|
183
217
|
import { createOpenSpecGroupStore, joinGroupIdsToOpenSpecData } from "./openspec/openspec-group-store.js";
|
|
218
|
+
import { fetchPackageMeta } from "./package/npm-search-proxy.js";
|
|
219
|
+
import { logPackageHealthAtBoot } from "./package/package-health-scanner.js";
|
|
184
220
|
import { type OperationResult, PackageManagerWrapper } from "./package/package-manager-wrapper.js";
|
|
185
221
|
import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
|
|
222
|
+
import { createRequestAccessAvailable, type KnockPeerDeps } from "./pairing/knock-admission.js";
|
|
186
223
|
import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
|
|
187
224
|
import { PairingManager, wirePendingHint } from "./pairing/pairing.js";
|
|
225
|
+
import type { TieredSocket } from "./pairing/ws-tier-gate.js";
|
|
226
|
+
import { buildSelfServer, wirePeerServers } from "./peer-servers.js";
|
|
188
227
|
import { createPendingArchiveIntentRegistry } from "./pending/pending-archive-intent-registry.js";
|
|
189
228
|
import { createPendingAttachRegistry } from "./pending/pending-attach-registry.js";
|
|
190
229
|
import { createPendingClientCorrelations } from "./pending/pending-client-correlations.js";
|
|
@@ -195,30 +234,42 @@ import { createPendingPrincipalOwnerRegistry } from "./pending/pending-principal
|
|
|
195
234
|
import { createPendingPromptAcks } from "./pending/pending-prompt-acks.js";
|
|
196
235
|
import { createPendingResumeIntentRegistry } from "./pending/pending-resume-intent-registry.js";
|
|
197
236
|
import { createPendingWorktreeBaseRegistry } from "./pending/pending-worktree-base-registry.js";
|
|
198
|
-
import { recordExitIntent, resolveExitIntent, stampBootStart } from "./persistence/boot-state.js";
|
|
237
|
+
import { recordExitIntent, resolveExitIntent, resolveExitRecord, stampBootStart } from "./persistence/boot-state.js";
|
|
199
238
|
import { createMemoryEventStore, DEFAULT_MAX_EVENT_DATA_SIZE, DEFAULT_MAX_STRING_SIZE, type EventStore } from "./persistence/memory-event-store.js";
|
|
200
239
|
import { createMetaPersistence } from "./persistence/meta-persistence.js";
|
|
201
240
|
import { migrateCustomEntryFallbackOverrides } from "./persistence/migrate-custom-entry-fallback.js";
|
|
202
241
|
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
203
242
|
import { createPreferencesStore } from "./persistence/preferences-store.js";
|
|
204
|
-
import {
|
|
243
|
+
import { loadHostProjectTrustService } from "./pi/host-project-trust.js";
|
|
205
244
|
import { PiCoreChecker } from "./pi/pi-core-checker.js";
|
|
206
245
|
import { PiCoreUpdater } from "./pi/pi-core-updater.js";
|
|
207
246
|
import { createPiGateway } from "./pi/pi-gateway.js";
|
|
247
|
+
import { listGlobalSkills } from "./pi/pi-resource-scanner.js";
|
|
248
|
+
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
208
249
|
import { pluginIntentCache } from "./plugin-intent-cache.js";
|
|
250
|
+
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
251
|
+
import { createPushService, type PushService } from "./push/push-service.js";
|
|
252
|
+
import type { SessionPresence } from "./questions/question-files.js";
|
|
253
|
+
import { registerQuestionRoutes } from "./questions/question-routes.js";
|
|
254
|
+
import { createQuestionStack, persistedPresence } from "./questions/question-stack.js";
|
|
209
255
|
import { registerAccessPromptRoutes } from "./routes/access-prompt-routes.js";
|
|
210
256
|
import { registerAccessRoutes } from "./routes/access-routes.js";
|
|
257
|
+
import { registerAcpRoutes } from "./routes/acp-routes.js";
|
|
258
|
+
import { registerAddonsRoutes } from "./routes/addons-routes.js";
|
|
211
259
|
import { registerAttachmentRoutes } from "./routes/attachment-routes.js";
|
|
212
260
|
import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
|
|
213
261
|
import { registerCustomEventGroupsRoutes } from "./routes/custom-event-groups-routes.js";
|
|
214
262
|
import { registerDoctorRoutes } from "./routes/doctor-routes.js";
|
|
215
263
|
import { registerFileRoutes } from "./routes/file-routes.js";
|
|
264
|
+
import { registerFolderProjectRoutes } from "./routes/folder-project-routes.js";
|
|
216
265
|
import { registerGitRoutes } from "./routes/git-routes.js";
|
|
217
266
|
import { registerGrepRoutes } from "./routes/grep-routes.js";
|
|
218
267
|
import { registerHostGateRoutes } from "./routes/host-gate-routes.js";
|
|
219
268
|
import { registerKnownServersRoutes } from "./routes/known-servers-routes.js";
|
|
220
269
|
import { registerLiveServerRoutes } from "./routes/live-server-routes.js";
|
|
270
|
+
import { registerLocalProofRoutes } from "./routes/local-proof-routes.js";
|
|
221
271
|
import { registerManifestRoute } from "./routes/manifest-route.js";
|
|
272
|
+
import { registerMermaidRepairRoutes } from "./routes/mermaid-repair-routes.js";
|
|
222
273
|
import { registerModelProxyApiKeyRoutes } from "./routes/model-proxy-api-key-routes.js";
|
|
223
274
|
import { registerModelProxyDiagnosticsRoutes } from "./routes/model-proxy-diagnostics-routes.js";
|
|
224
275
|
import { registerModelProxyRefreshRoutes } from "./routes/model-proxy-refresh-routes.js";
|
|
@@ -227,46 +278,56 @@ import { registerModelsIntrospectionRoute } from "./routes/models-introspection-
|
|
|
227
278
|
import { registerNodeRuntimeRoutes } from "./routes/node-runtime-routes.js";
|
|
228
279
|
import { registerOpenSpecGroupRoutes } from "./routes/openspec-group-routes.js";
|
|
229
280
|
import { registerOpenSpecRoutes } from "./routes/openspec-routes.js";
|
|
281
|
+
import { registerPackageHealthRoutes } from "./routes/package-health-routes.js";
|
|
230
282
|
import { registerPackageRoutes } from "./routes/package-routes.js";
|
|
231
283
|
import { PUBLIC_PAIRING_PREFIXES, registerPairingRoutes } from "./routes/pairing-routes.js";
|
|
232
284
|
import { registerPiChangelogRoutes } from "./routes/pi-changelog-routes.js";
|
|
233
285
|
import { registerPiCoreRoutes } from "./routes/pi-core-routes.js";
|
|
234
286
|
import { registerPiRetryRoutes } from "./routes/pi-retry-routes.js";
|
|
235
287
|
import { registerPiRuntimeRoutes } from "./routes/pi-runtime-routes.js";
|
|
236
|
-
import {
|
|
288
|
+
import { registerPiSettingsRoutes } from "./routes/pi-settings-routes.js";
|
|
289
|
+
import { registerPluginActivationRoutes, setPluginsEnabled } from "./routes/plugin-activation-routes.js";
|
|
237
290
|
import { registerPluginConfigRoutes } from "./routes/plugin-config-routes.js";
|
|
238
291
|
import { registerPreferencesAutoNameRoutes } from "./routes/preferences-auto-name-routes.js";
|
|
239
292
|
import { registerPreferencesDisplayRoutes } from "./routes/preferences-display-routes.js";
|
|
240
293
|
import { registerPreferencesWorktreeInitRoutes } from "./routes/preferences-worktree-init-routes.js";
|
|
241
|
-
import {
|
|
242
|
-
createMcpClientConfigService,
|
|
243
|
-
createRealConfigIO,
|
|
244
|
-
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
245
|
-
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
246
294
|
import { registerProviderAuthRoutes } from "./routes/provider-auth-routes.js";
|
|
247
295
|
import { registerProviderRoutes } from "./routes/provider-routes.js";
|
|
296
|
+
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
248
297
|
import { invalidateRecommendedCache, registerRecommendedRoutes } from "./routes/recommended-routes.js";
|
|
249
298
|
import { registerResourceActivationRoutes } from "./routes/resource-activation-routes.js";
|
|
250
299
|
import { registerRuntimeRoutes } from "./routes/runtime-routes.js";
|
|
251
|
-
import { registerSessionRoutes } from "./routes/session-routes.js";
|
|
300
|
+
import { registerSessionRoutes, type ToolResultStats } from "./routes/session-routes.js";
|
|
252
301
|
import { registerSystemRoutes } from "./routes/system-routes.js";
|
|
302
|
+
import { registerTlsRoutes } from "./routes/tls-routes.js";
|
|
303
|
+
import { registerAcmeRoutes } from "./routes/acme-routes.js";
|
|
304
|
+
import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
|
|
305
|
+
import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
|
|
306
|
+
import { acmeGc } from "./tls/sources/acme/gc.js";
|
|
253
307
|
import { registerToolRoutes } from "./routes/tool-routes.js";
|
|
308
|
+
import { registerUserRoutes } from "./routes/user-routes.js";
|
|
254
309
|
import {
|
|
255
310
|
dispatchReload as dispatchReloadRaw,
|
|
256
311
|
reloadTargetSessionIds,
|
|
257
312
|
} from "./rpc-keeper/dispatch-reload.js";
|
|
258
313
|
import { activeExtensionFromEnv, createExtensionReloadGuard } from "./runtime-overlay/extension-reload.js";
|
|
259
|
-
import {
|
|
314
|
+
import { buildRuntimeDoctorCheck, bundledFallbackIntact } from "./runtime-overlay/runtime-doctor.js";
|
|
260
315
|
import { buildRuntimeHealth, type RuntimeHealth } from "./runtime-overlay/runtime-health.js";
|
|
261
316
|
import { createStagerDeps, runtimeReleaseFeeds } from "./runtime-overlay/runtime-io.js";
|
|
262
317
|
import { stageRuntime } from "./runtime-overlay/runtime-stager.js";
|
|
263
318
|
import { RuntimeUpdateChecker } from "./runtime-overlay/runtime-update-checker.js";
|
|
264
319
|
import { startServerHeapTelemetry } from "./server-heap-telemetry.js";
|
|
320
|
+
import { defaultCommandRunner } from "./services/command-runner.js";
|
|
321
|
+
import { servicesPaths } from "./services/paths.js";
|
|
322
|
+
import { registerServiceRoutes } from "./services/routes.js";
|
|
323
|
+
import { ServiceManager } from "./services/service-manager.js";
|
|
265
324
|
import { createArchiveSweeper } from "./session/archive-sweeper.js";
|
|
266
325
|
import { CustomEventGroupMatcher } from "./session/custom-event-group-matcher.js";
|
|
267
326
|
import { CustomEventGroupResolver } from "./session/custom-event-group-resolver.js";
|
|
268
327
|
import { deriveEndedAt } from "./session/derive-ended-at.js";
|
|
328
|
+
import { createInFlightToolCalls } from "./session/in-flight-tool-calls.js";
|
|
269
329
|
import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
|
|
330
|
+
import { systemRenameUpdates } from "./session/name-provenance.js";
|
|
270
331
|
import { applyPluginRef } from "./session/plugin-refs.js";
|
|
271
332
|
import { applyReattachPolicy } from "./session/reattach-placement.js";
|
|
272
333
|
import { reconcileSessionOrder } from "./session/reconcile-session-order.js";
|
|
@@ -276,18 +337,34 @@ import { registerSessionApi } from "./session/session-api.js";
|
|
|
276
337
|
import { createSessionArchive } from "./session/session-archive.js";
|
|
277
338
|
import { discoverAndBroadcastSessions } from "./session/session-bootstrap.js";
|
|
278
339
|
import { createSessionOrderManager, type SessionOrderManager } from "./session/session-order-manager.js";
|
|
279
|
-
import {
|
|
340
|
+
import { originOf } from "./session/session-origin.js";
|
|
341
|
+
import { bootScanAllSessions } from "./session/session-scanner.js";
|
|
280
342
|
import { sessionToMeta } from "./session/session-to-meta.js";
|
|
343
|
+
import { createAbortSpawnedRun } from "./spawn-process/abort-spawned-run.js";
|
|
344
|
+
import { setLocalAcpHost, spawnAcpSession, validatePluginAcpSpawn } from "./spawn-process/acp-spawn.js";
|
|
281
345
|
import { CwdPolicyRegistry } from "./spawn-process/cwd-policy.js";
|
|
282
346
|
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
283
347
|
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
284
348
|
import { getKeeperManager, setCwdPolicyRegistry, spawnPiSession } from "./spawn-process/process-manager.js";
|
|
285
349
|
import { removePid, writePid } from "./spawn-process/server-pid.js";
|
|
350
|
+
import { createSessionTerminator } from "./spawn-process/session-terminator.js";
|
|
351
|
+
import { registerSpawnEnvContributorForPlugin, setSpawnEnvPluginEnabledCheck } from "./spawn-process/spawn-env-contributors.js";
|
|
286
352
|
import { armSpawnWatchdog } from "./spawn-process/spawn-register-watchdog.js";
|
|
287
353
|
import { createTerminalGateway } from "./terminal/terminal-gateway.js";
|
|
288
354
|
import { createTerminalManager, deriveTranscriptCapBytes } from "./terminal/terminal-manager.js";
|
|
355
|
+
import {
|
|
356
|
+
MAIN_CONNECTION_TIMEOUT_MS,
|
|
357
|
+
MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
358
|
+
TlsListener,
|
|
359
|
+
} from "./tls/tls-listener.js";
|
|
289
360
|
import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, liveTunnelOrigins, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
|
|
290
361
|
import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
|
|
362
|
+
import { createVaultDeliveryHub } from "./vault/vault-delivery-hub.js";
|
|
363
|
+
import { createVaultImport, defaultKnownLocations } from "./vault/vault-import.js";
|
|
364
|
+
import { createPluginVaultReader } from "./vault/vault-plugin-read.js";
|
|
365
|
+
import { createVaultProjects } from "./vault/vault-projects.js";
|
|
366
|
+
import { createVaultManageGuard, registerVaultRoutes } from "./vault/vault-routes.js";
|
|
367
|
+
import { createVaultStore } from "./vault/vault-store.js";
|
|
291
368
|
|
|
292
369
|
export interface ServerConfig {
|
|
293
370
|
port: number;
|
|
@@ -423,6 +500,8 @@ export interface DashboardServer {
|
|
|
423
500
|
browserGateway: BrowserGateway;
|
|
424
501
|
/** Resolved HTTP port after start() (useful for port:0 in tests). Returns null if not listening. */
|
|
425
502
|
httpPort(): number | null;
|
|
503
|
+
/** The optional TLS listener (off by default). See change: add-tailscale-cert-tls. */
|
|
504
|
+
readonly tls: TlsListener;
|
|
426
505
|
/** Resolved pi gateway port after start(). Returns null if not listening. */
|
|
427
506
|
piPort(): number | null;
|
|
428
507
|
/**
|
|
@@ -478,7 +557,31 @@ function resolvedPiVersion(): string | undefined {
|
|
|
478
557
|
/** Plugin frames that are NOT domain events: replay-cached UI intents and settings echoes. */
|
|
479
558
|
const NON_DOMAIN_PLUGIN_FRAMES: ReadonlySet<string> = new Set(["plugin_intents", "plugin_config_update"]);
|
|
480
559
|
|
|
560
|
+
/**
|
|
561
|
+
* "Also trust this folder in pi": stored with the entry an allow-always just wrote
|
|
562
|
+
* (filesystem → persisted grant; cwd → pin). Best-effort — the grant itself already
|
|
563
|
+
* stands. See change: mirror-dashboard-trust-to-pi.
|
|
564
|
+
*/
|
|
565
|
+
function storePiTrustChoiceOfVerdict(
|
|
566
|
+
mirror: ReturnType<typeof createPiTrustMirrorService>,
|
|
567
|
+
msg: { verdict: string; plane: string; subject: string; piTrust?: boolean },
|
|
568
|
+
): void {
|
|
569
|
+
if (msg.verdict !== "allow-always" || typeof msg.piTrust !== "boolean") return;
|
|
570
|
+
const kind = msg.plane === "filesystem" ? "accessGrants" : msg.plane === "cwd" ? "pinned" : null;
|
|
571
|
+
if (!kind) return;
|
|
572
|
+
try {
|
|
573
|
+
mirror.setChoice(kind, msg.subject, msg.piTrust);
|
|
574
|
+
mirror.refresh();
|
|
575
|
+
} catch (err) {
|
|
576
|
+
console.warn(`[pi-trust-mirror] could not store the pi-trust choice: ${(err as Error)?.message}`);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
481
580
|
export async function createServer(config: ServerConfig): Promise<DashboardServer> {
|
|
581
|
+
// Decide the network trust mode ONCE, before any hook is installed and before
|
|
582
|
+
// the server listens (so no operator write can race it). Never re-derived
|
|
583
|
+
// from the list afterwards. See change: retire-trusted-networks-bypass (D2).
|
|
584
|
+
decideBootTrustMode();
|
|
482
585
|
// Ensure bridge extension is registered in pi's global settings
|
|
483
586
|
// (needed for bundled installs where pi can't discover it from package.json)
|
|
484
587
|
//
|
|
@@ -595,6 +698,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
595
698
|
// Local-IPC allowlist token (D10, narrowed): affirmative genuine-local trust
|
|
596
699
|
// for same-host process callers, independent of the forgeable loopback IP.
|
|
597
700
|
const localToken = ensureLocalToken();
|
|
701
|
+
// Endpoint-bound proof of possession, verified ONCE per request at the listener
|
|
702
|
+
// edge; every exemption site reads the stamped verdict via `hasLocalCredential`.
|
|
703
|
+
// `acceptLegacyToken` keeps the deprecated raw `X-Pi-Local-Token` admitted
|
|
704
|
+
// until the 1.0.0 horizon shared with the D10b grace. See change:
|
|
705
|
+
// loopback-credential-proof (D4, D9).
|
|
706
|
+
const localCredential = createLocalCredentialVerifier({ token: localToken, acceptLegacyToken: true });
|
|
707
|
+
// Taken immediately BEFORE each successful bind: a proof minted earlier cannot
|
|
708
|
+
// be for this listener (D3). 0 until `fastify.listen` runs (inject() in tests).
|
|
709
|
+
let httpBoundAt = 0;
|
|
710
|
+
// Same contract for the optional TLS listener (its own bind, its own floor). See change: add-tailscale-cert-tls.
|
|
711
|
+
let tlsBoundAt = 0;
|
|
598
712
|
// Strict local-proof context (`requireLocalProof`, live config read). Threaded to
|
|
599
713
|
// every genuinely-local admission site. See change: harden-trust-and-credential-boundaries (D2).
|
|
600
714
|
const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof);
|
|
@@ -607,6 +721,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
607
721
|
const tunnelUrl = getTunnelUrl();
|
|
608
722
|
if (tunnelUrl) urls.push(tunnelUrl);
|
|
609
723
|
urls.push(...resolvePublicBaseUrls(loadConfig()));
|
|
724
|
+
// Certificate-backed names of the TLS listener (https only; the https/wss
|
|
725
|
+
// gate in `reachableUrls()` still applies). See change: add-tailscale-cert-tls (D5).
|
|
726
|
+
urls.push(...tlsListener.tlsListenerUrls().map((e) => e.url));
|
|
610
727
|
// Test-only (PI_E2E_SEED): expose the loopback http origin so the
|
|
611
728
|
// Playwright/Docker harness can pair over http://localhost (a genuine
|
|
612
729
|
// secure context) without TLS. `reachableUrls()` re-gates it behind the
|
|
@@ -638,6 +755,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
638
755
|
sessionManager,
|
|
639
756
|
metaPersistence,
|
|
640
757
|
getPinnedDirs: () => preferencesStore.getPinnedDirectories(),
|
|
758
|
+
// Fileless eviction (manual archive / supersede) has no file to reload the
|
|
759
|
+
// events from. `eventStore` is built later; the closure runs after boot.
|
|
760
|
+
// See change: fix-orphaned-ended-session-archive.
|
|
761
|
+
deleteEvents: (id) => { eventStore.deleteEventsForSession(id); },
|
|
641
762
|
});
|
|
642
763
|
const pendingArchiveIntents = createPendingArchiveIntentRegistry();
|
|
643
764
|
// Stable per-boot id stamped into the liveness marker so cold start can
|
|
@@ -670,7 +791,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
670
791
|
|
|
671
792
|
// Restore sessions from per-session .meta.json files (scans ~/.pi/agent/sessions/)
|
|
672
793
|
const scanStartedAt = Date.now();
|
|
673
|
-
|
|
794
|
+
// Boot scan + the service-session backfill (declared leg every boot,
|
|
795
|
+
// one-shot legacy leg stamped in boot-state.json).
|
|
796
|
+
// See change: archive-service-sessions-on-end.
|
|
797
|
+
const scanResult = bootScanAllSessions();
|
|
798
|
+
// Ended ACP sessions live outside the pi sessions dir; restore them as ended.
|
|
799
|
+
// See change: add-acp-session-driver (D12).
|
|
800
|
+
scanResult.sessions.push(...scanAcpSessions());
|
|
674
801
|
const scanMs = Date.now() - scanStartedAt;
|
|
675
802
|
// Seed the archive index from the boot scan: migrated + already-archived
|
|
676
803
|
// rows are indexed, never restored. The one-shot ended+hidden migration and
|
|
@@ -683,6 +810,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
683
810
|
`${scanResult.migrated} migrated, ${scanResult.agedOut} aged-out (${scanMs} ms)`,
|
|
684
811
|
);
|
|
685
812
|
}
|
|
813
|
+
if (scanResult.serviceArchived > 0) {
|
|
814
|
+
console.info(`[archive] service-end-backfill archived ${scanResult.serviceArchived} session(s)`);
|
|
815
|
+
}
|
|
686
816
|
// Interrupted-session recovery candidates discovered on cold start. A
|
|
687
817
|
// candidate (`live===true && status!=="ended"`, see isRecoveryCandidate)
|
|
688
818
|
// was running when the host died. Candidates are NORMALIZED to `ended` on
|
|
@@ -695,7 +825,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
695
825
|
// See change: fix-recovery-offer-dismiss-and-phantom-reopen.
|
|
696
826
|
const recoveryMode = loadConfig().reopenSessionsAfterShutdown;
|
|
697
827
|
const recoveryCandidates: DashboardSession[] = [];
|
|
828
|
+
// Pre-normalization liveness for the question-file boot sweep (cold start forces
|
|
829
|
+
// `ended` below). See change: add-pending-question-stack (D6).
|
|
830
|
+
const persistedSessionPresence = new Map<string, SessionPresence>();
|
|
698
831
|
for (const session of scanResult.sessions) {
|
|
832
|
+
persistedSessionPresence.set(session.id, persistedPresence(session));
|
|
699
833
|
const restored = { ...session, dataUnavailable: true };
|
|
700
834
|
// Positive `exitIntent` gate: a boot that ended by `/api/restart` or
|
|
701
835
|
// `/api/shutdown` left its sessions RUNNING and told every bridge to stay
|
|
@@ -703,13 +837,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
703
837
|
// reattach — after any window that could retract them. Suppress outright,
|
|
704
838
|
// with no timing dependency. See change: fix-recovery-exit-intent.
|
|
705
839
|
const ownerIntent = resolveExitIntent(session.liveEpoch);
|
|
706
|
-
|
|
840
|
+
// ACP sessions are never recovery candidates: nothing can resume one (D15).
|
|
841
|
+
const isAcp = session.driver === "acp";
|
|
842
|
+
const diskCandidate = !isAcp && recoveryMode !== "off" && isRecoveryCandidate({
|
|
707
843
|
live: session.live,
|
|
708
844
|
status: session.status,
|
|
709
845
|
closedReason: session.closedReason,
|
|
710
846
|
recover: session.recover,
|
|
711
847
|
});
|
|
712
|
-
|
|
848
|
+
// Shutdown-window path: on a host shutdown pi exits gracefully and its
|
|
849
|
+
// bridge unregisters BEFORE this server is signalled, so the session is
|
|
850
|
+
// `live:false` on disk and the path above cannot see it. Evaluated on the
|
|
851
|
+
// scanned (pre-normalization) session; its evidence is consumed right
|
|
852
|
+
// here in EVERY mode, so it qualifies on at most one cold start.
|
|
853
|
+
// See change: fix-recovery-pi-signal-unregister (D3, D5, D6).
|
|
854
|
+
const ownerBoot = session.live === true || isAcp ? undefined : resolveExitRecord(session.liveEpoch);
|
|
855
|
+
const windowMatch = !isAcp && isShutdownWindowCandidate(session, ownerBoot, RECOVERY_SHUTDOWN_WINDOW_MS);
|
|
856
|
+
if (windowMatch && session.sessionFile) {
|
|
857
|
+
metaPersistence.setLiveness(session.sessionFile, { live: false, closedReason: session.closedReason });
|
|
858
|
+
}
|
|
859
|
+
const windowCandidate = windowMatch && recoveryMode !== "off";
|
|
860
|
+
if (windowCandidate && ownerBoot && session.endedAt !== undefined) {
|
|
861
|
+
console.info(
|
|
862
|
+
`[recovery] ${session.id}: shutdown-window (ended ${((ownerBoot.at - session.endedAt) / 1000).toFixed(1)}s ` +
|
|
863
|
+
`before boot ${ownerBoot.bootId} exit via ${ownerBoot.exitIntent})`,
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
const candidate = (diskCandidate && isRecoveryAllowed(ownerIntent)) || windowCandidate;
|
|
713
867
|
if (diskCandidate && !candidate) {
|
|
714
868
|
console.info(
|
|
715
869
|
`[recovery] ${session.id}: suppressed-by-intent (boot ${session.liveEpoch} exited via ${ownerIntent})`,
|
|
@@ -1056,6 +1210,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1056
1210
|
// Optional second-port Fastify instance for model proxy (/v1/*)
|
|
1057
1211
|
let secondFastify: Awaited<ReturnType<typeof import("fastify").default>> | null = null;
|
|
1058
1212
|
const peerServers = new Map<string, DiscoveredServer>();
|
|
1213
|
+
// Verified move suggestions for renamed known servers (in memory only).
|
|
1214
|
+
// See change: stabilize-mdns-server-identity.
|
|
1215
|
+
const knownServerMoves = createKnownServerMoves({
|
|
1216
|
+
loadKnown: () => loadConfig().knownServers,
|
|
1217
|
+
prove: (baseUrl) => proveServerIdentity(baseUrl, { timeoutMs: 2000 }),
|
|
1218
|
+
});
|
|
1059
1219
|
|
|
1060
1220
|
/** This process's place in the per-HOME rendezvous (task 2.0a). */
|
|
1061
1221
|
let homeRendezvous: import("./lifecycle/home-rendezvous.js").HomeRendezvous | null = null;
|
|
@@ -1081,7 +1241,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1081
1241
|
// A loopback bridge that presents the local token is authorised on its
|
|
1082
1242
|
// own credential rather than on the grace — the only local credential
|
|
1083
1243
|
// Windows has, since it gets no unix socket (D6, task 5.3).
|
|
1084
|
-
|
|
1244
|
+
verifyCredential: localCredential,
|
|
1085
1245
|
},
|
|
1086
1246
|
// Bridge-silence verdict. The browser cannot observe silence itself — it
|
|
1087
1247
|
// receives `processMetrics` once, in the connect snapshot, and nothing
|
|
@@ -1172,7 +1332,22 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1172
1332
|
// Live-server-preview manager (loopback dev-server allowlist + proxy).
|
|
1173
1333
|
const liveServerManager = createLiveServerManager(preferencesStore);
|
|
1174
1334
|
|
|
1175
|
-
|
|
1335
|
+
// ACP host A (in-process): attach virtual connections to THIS gateway.
|
|
1336
|
+
// See change: add-acp-session-driver (D1).
|
|
1337
|
+
setLocalAcpHost({ attachLocalConnection: (socket) => piGateway.attachLocalConnection(socket), log: (line) => console.error(line) });
|
|
1338
|
+
|
|
1339
|
+
// Pending-question stack: snapshot + brief per open question, durable across restart.
|
|
1340
|
+
// Boot: load persisted question files, then drop those of unknown/ended sessions
|
|
1341
|
+
// (no timer sweep). See change: add-pending-question-stack (D6).
|
|
1342
|
+
const { store: questionStore } = createQuestionStack({
|
|
1343
|
+
eventStore,
|
|
1344
|
+
sessionManager,
|
|
1345
|
+
getConfig: () => loadConfig().questions,
|
|
1346
|
+
});
|
|
1347
|
+
questionStore.loadPersisted();
|
|
1348
|
+
questionStore.sweepAtBoot((sessionId) => persistedSessionPresence.get(sessionId) ?? "unknown");
|
|
1349
|
+
|
|
1350
|
+
const browserGateway = createBrowserGateway(sessionManager, eventStore, piGateway, undefined, pendingForkRegistry, sessionOrderManager, preferencesStore, directoryService, terminalManager, pendingDashboardSpawns, config.maxWsBufferBytes, pendingAttachRegistry, pendingInitialPromptRegistry, pendingResumeIntents, pendingClientCorrelations, pendingWorktreeBaseRegistry, metaPersistence, fitWorkerPool, config.maxReplayEvents, config.replayWindowMode, sessionArchive, pendingArchiveIntents, remoteTranscriptStore, pendingPrincipalOwnerRegistry, identityEnforced, undefined, questionStore);
|
|
1176
1351
|
// App-wide pairing approval dialog: a content-free hint on every pending
|
|
1177
1352
|
// change; operator browsers refetch the guarded list (D1).
|
|
1178
1353
|
// See change: add-pairing-approval-dialog.
|
|
@@ -1230,15 +1405,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1230
1405
|
|
|
1231
1406
|
// Send this server + discovered peers to new browser connections
|
|
1232
1407
|
browserGateway.onConnect = (ws) => {
|
|
1233
|
-
const selfServer
|
|
1408
|
+
const selfServer = buildSelfServer({
|
|
1234
1409
|
host: selfHostname,
|
|
1235
1410
|
port: config.port,
|
|
1236
1411
|
piPort: config.piPort,
|
|
1237
1412
|
version: pkgVersion,
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
};
|
|
1413
|
+
fingerprint: serverIdentity.fingerprint,
|
|
1414
|
+
name: loadConfig().dashboardName || selfHostname.replace(/\.local$/i, ""),
|
|
1415
|
+
});
|
|
1242
1416
|
const all = [selfServer, ...Array.from(peerServers.values())];
|
|
1243
1417
|
browserGateway.sendToClient(ws, { type: "servers_discovered", servers: all });
|
|
1244
1418
|
if (pendingRecoveryOffer) browserGateway.sendToClient(ws, pendingRecoveryOffer);
|
|
@@ -1360,11 +1534,64 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1360
1534
|
for (const d of preferencesStore.getPinnedDirectories()) set.add(d);
|
|
1361
1535
|
return [...set];
|
|
1362
1536
|
});
|
|
1537
|
+
// `indeterminate` plugin cwd admissions (a git probe that did not complete)
|
|
1538
|
+
// are worth a log line — today they are invisible — but throttled per cwd and
|
|
1539
|
+
// LRU-bounded. Plugins pass this as `admitCwd`'s `onIndeterminate`.
|
|
1540
|
+
// See change: harden-plugin-cwd-admission (D7).
|
|
1541
|
+
const cwdAdmissionLogger = createIndeterminateLogger({ warn: (m) => console.warn(m) });
|
|
1542
|
+
pluginServiceRegistry.set("host.cwdAdmissionOnIndeterminate", cwdAdmissionLogger);
|
|
1363
1543
|
// pi's project-trust rule as a SESSION applies it (recorded decision, else
|
|
1364
1544
|
// `defaultProjectTrust`), consumed by mcp-client to decide whether a
|
|
1365
1545
|
// folder's `.pi/mcp.json` is active. Resolved once; an unresolvable pi reads
|
|
1366
1546
|
// every project as untrusted. See change: migrate-mcp-to-pi-builtin (D3).
|
|
1367
|
-
|
|
1547
|
+
// Durable dashboard trust is mirrored into pi's `project_trust` through a
|
|
1548
|
+
// server-written snapshot (rebuilt now from the persisted stores, so a crash
|
|
1549
|
+
// between a revoke's two writes heals at boot). See change: mirror-dashboard-trust-to-pi.
|
|
1550
|
+
const piTrustMirror = createPiTrustMirrorService({
|
|
1551
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
1552
|
+
listPinned: () => preferencesStore.getPinnedDirectories(),
|
|
1553
|
+
listWorkspaceFolders: () => preferencesStore.getWorkspaces().flatMap((w) => w.folders),
|
|
1554
|
+
listWorktreeTrust: listPersistedWorktreeTrust,
|
|
1555
|
+
listPersistedGrants: () => listAccessGrants().filter((g) => g.scope === "project"),
|
|
1556
|
+
});
|
|
1557
|
+
setPiTrustMirror(piTrustMirror);
|
|
1558
|
+
try {
|
|
1559
|
+
piTrustMirror.rebuildAtBoot();
|
|
1560
|
+
} catch (err) {
|
|
1561
|
+
console.warn(`[pi-trust-mirror] boot snapshot rebuild failed: ${(err as Error)?.message}`);
|
|
1562
|
+
}
|
|
1563
|
+
// Any source change refreshes the snapshot (coalesced); operator revokes additionally
|
|
1564
|
+
// go through the ordered `revoke` path in their handlers.
|
|
1565
|
+
let mirrorRefreshQueued = false;
|
|
1566
|
+
const queueMirrorRefresh = (): void => {
|
|
1567
|
+
if (mirrorRefreshQueued) return;
|
|
1568
|
+
mirrorRefreshQueued = true;
|
|
1569
|
+
setImmediate(() => {
|
|
1570
|
+
mirrorRefreshQueued = false;
|
|
1571
|
+
piTrustMirror.refresh();
|
|
1572
|
+
});
|
|
1573
|
+
};
|
|
1574
|
+
preferencesStore.onPinsChanged?.(queueMirrorRefresh);
|
|
1575
|
+
preferencesStore.onWorkspacesChanged(queueMirrorRefresh);
|
|
1576
|
+
setGrantsChangedListener(queueMirrorRefresh);
|
|
1577
|
+
setTrustChangedListener(queueMirrorRefresh);
|
|
1578
|
+
const hostProjectTrust = await loadHostProjectTrustService();
|
|
1579
|
+
pluginServiceRegistry.set("host.isProjectTrusted", hostProjectTrust.isProjectTrusted);
|
|
1580
|
+
pluginServiceRegistry.set("host.projectTrustSource", hostProjectTrust.projectTrustSource);
|
|
1581
|
+
pluginServiceRegistry.set("host.piTrustCoverInteractive", () => loadConfig().piTrustMirror.coverInteractive);
|
|
1582
|
+
// cwd-policy as the spawn funnel composes it, so the team plugin can refuse a
|
|
1583
|
+
// start whose skill set the policy would narrow. See change: add-team-skill-access (D7).
|
|
1584
|
+
pluginServiceRegistry.set("host.resolveCwdPolicy", (cwd: string) => cwdPolicyRegistry.resolve(cwd));
|
|
1585
|
+
// Operator-visible (global + global-package) skills for the team plugin's
|
|
1586
|
+
// admin skill picker. Never project-local. See change: add-team-skill-access (D11).
|
|
1587
|
+
pluginServiceRegistry.set("host.listOperatorSkills", async () =>
|
|
1588
|
+
listGlobalSkills(path.join(os.homedir(), ".pi", "agent")).map((s) => ({
|
|
1589
|
+
name: s.name,
|
|
1590
|
+
description: s.description ?? "",
|
|
1591
|
+
path: path.dirname(s.filePath),
|
|
1592
|
+
source: "global" as const,
|
|
1593
|
+
})),
|
|
1594
|
+
);
|
|
1368
1595
|
// Host services consumed by mcp-server-plugin. Registered HERE because the
|
|
1369
1596
|
// plugin must verify a device bearer WITHOUT going through the global
|
|
1370
1597
|
// `onRequest` hook — `/mcp` deliberately does not trust
|
|
@@ -1492,7 +1719,43 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1492
1719
|
// Name the grant store this dashboard writes (exclusive-create, never overwritten);
|
|
1493
1720
|
// announced to each bridge on registration. See change: ask-agent-file-access-in-chat.
|
|
1494
1721
|
ensureGrantStoreId();
|
|
1722
|
+
// Live-only in-flight hint + route answer counters shared by the event wiring,
|
|
1723
|
+
// the tool-result route and `/api/health`. See change:
|
|
1724
|
+
// distinguish-tool-result-pending-vs-gone (D2, D6).
|
|
1725
|
+
const inFlightToolCalls = createInFlightToolCalls();
|
|
1726
|
+
const toolResultStats: ToolResultStats = { pending: 0, gone: 0 };
|
|
1727
|
+
// Credential vault: store + delivery hub. The hub answers bridge sync
|
|
1728
|
+
// requests and pushes on every vault write / config change; values travel only
|
|
1729
|
+
// on the session-private bridge lane. See change: add-credential-vault.
|
|
1730
|
+
const vaultStore = createVaultStore();
|
|
1731
|
+
// ACME DNS-01 certificate source: solver secrets live in this vault (kind `tls-solver`).
|
|
1732
|
+
// GC of orphaned namespaces/account keys runs once at start. See change: add-acme-dns01-certs.
|
|
1733
|
+
configureAcmeRuntime({ credentials: createAcmeCredentials(vaultStore) });
|
|
1734
|
+
acmeGc().catch(() => undefined);
|
|
1735
|
+
// Remembered projects for the vault project picker; a sibling of vault.json, created on the first recorded project.
|
|
1736
|
+
const vaultProjects = createVaultProjects({ file: path.join(path.dirname(vaultStore.filePath), "vault-projects.json") });
|
|
1737
|
+
const vaultDelivery = createVaultDeliveryHub({
|
|
1738
|
+
store: vaultStore,
|
|
1739
|
+
projects: vaultProjects,
|
|
1740
|
+
getOrigin: (sessionId) => {
|
|
1741
|
+
const session = sessionManager.get(sessionId);
|
|
1742
|
+
return session ? originOf(session) : undefined;
|
|
1743
|
+
},
|
|
1744
|
+
send: (sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
1745
|
+
isSessionConnected: (sessionId) => piGateway.getConnectedSessionIds().includes(sessionId),
|
|
1746
|
+
isDeliveryEnabled: () => loadConfig().vault.deliveryEnabled,
|
|
1747
|
+
getGraceHours: () => loadConfig().vault.offlineGraceHours,
|
|
1748
|
+
});
|
|
1495
1749
|
wireEvents({
|
|
1750
|
+
inFlightToolCalls,
|
|
1751
|
+
vaultDelivery,
|
|
1752
|
+
// Lazy: `yolo` is constructed further down; a pre-init call throws and the
|
|
1753
|
+
// handler declines. See change: yolo-covers-agent-path-gate.
|
|
1754
|
+
decideAgentPath: (p) =>
|
|
1755
|
+
yolo.decideAgentPath({
|
|
1756
|
+
path: p,
|
|
1757
|
+
hostGateMode: resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
1758
|
+
}),
|
|
1496
1759
|
onBridgeRegister: (sid, identity) => {
|
|
1497
1760
|
const outcome = extensionReloadGuard.onRegister(sid, identity);
|
|
1498
1761
|
if (outcome !== "skipped") {
|
|
@@ -1533,6 +1796,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1533
1796
|
customEventGroupResolver,
|
|
1534
1797
|
sessionArchive,
|
|
1535
1798
|
pendingArchiveIntents,
|
|
1799
|
+
// On-end archive of declared-disposable sessions. See change: archive-service-sessions-on-end.
|
|
1800
|
+
archiveSweeper,
|
|
1536
1801
|
});
|
|
1537
1802
|
|
|
1538
1803
|
// Auto-shutdown idle timer
|
|
@@ -1556,8 +1821,36 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1556
1821
|
|
|
1557
1822
|
const fastify = Fastify({
|
|
1558
1823
|
logger: false,
|
|
1559
|
-
keepAliveTimeout:
|
|
1560
|
-
connectionTimeout:
|
|
1824
|
+
keepAliveTimeout: MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
1825
|
+
connectionTimeout: MAIN_CONNECTION_TIMEOUT_MS,
|
|
1826
|
+
// Add-ons feature ids embed a local package's absolute path (`pkg:local:/…`), which exceeds
|
|
1827
|
+
// find-my-way's default 100-char param limit (414). See change: addons-hub-folder-view.
|
|
1828
|
+
maxParamLength: 1024,
|
|
1829
|
+
});
|
|
1830
|
+
|
|
1831
|
+
// Optional native TLS listener (off by default): a second `https.Server` that
|
|
1832
|
+
// dispatches into THIS Fastify instance — one route table, one gate chain, one
|
|
1833
|
+
// upgrade switch, two transports. Reconciled after `listen`; failure-isolated.
|
|
1834
|
+
// See change: add-tailscale-cert-tls (D1).
|
|
1835
|
+
let tlsUpgrade: ((req: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer) => void) | null = null;
|
|
1836
|
+
const tlsListener = new TlsListener({
|
|
1837
|
+
dataRoot: path.join(os.homedir(), ".pi", "dashboard", "tls"),
|
|
1838
|
+
getTlsConfig: () => loadConfig().tls,
|
|
1839
|
+
beforeBind: (at) => {
|
|
1840
|
+
tlsBoundAt = at;
|
|
1841
|
+
},
|
|
1842
|
+
dispatch: {
|
|
1843
|
+
request: (req, res) => {
|
|
1844
|
+
fastify.server.emit("request", req, res);
|
|
1845
|
+
},
|
|
1846
|
+
upgrade: (req, socket, head) => {
|
|
1847
|
+
if (tlsUpgrade) tlsUpgrade(req, socket, head);
|
|
1848
|
+
else socket.destroy();
|
|
1849
|
+
},
|
|
1850
|
+
clientError: (err, socket) => {
|
|
1851
|
+
fastify.server.emit("clientError", err, socket);
|
|
1852
|
+
},
|
|
1853
|
+
},
|
|
1561
1854
|
});
|
|
1562
1855
|
|
|
1563
1856
|
// Route inventory (test-only): fires as each route registers, before listen,
|
|
@@ -1568,6 +1861,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1568
1861
|
fastify.addHook("onRoute", (route) => collect({ method: route.method, url: route.url }));
|
|
1569
1862
|
}
|
|
1570
1863
|
|
|
1864
|
+
// Local credential edge stamp: registered BEFORE every other hook (including
|
|
1865
|
+
// the rate limiter) so no later hook can read an unverified request.
|
|
1866
|
+
// See change: loopback-credential-proof (D4).
|
|
1867
|
+
fastify.addHook("onRequest", async (request) => {
|
|
1868
|
+
localCredential.stamp(request.raw, {
|
|
1869
|
+
kind: "http",
|
|
1870
|
+
boundAt: (request.raw.socket as import("node:tls").TLSSocket).encrypted ? tlsBoundAt : httpBoundAt,
|
|
1871
|
+
});
|
|
1872
|
+
});
|
|
1873
|
+
|
|
1571
1874
|
// Global rate limiter. Two jobs: a real remote-caller ceiling, and making the
|
|
1572
1875
|
// app recognizable to static analysis (`js/missing-rate-limiting` otherwise
|
|
1573
1876
|
// flags every authenticated route handler). Loopback is allow-listed so
|
|
@@ -1617,6 +1920,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1617
1920
|
// config-override-oauth-redirect-base (D15).
|
|
1618
1921
|
const corsAllowedOrigins = () => liveCorsAllowedOrigins(config.corsAllowedOrigins ?? []);
|
|
1619
1922
|
const corsTrustedNetworks = () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []);
|
|
1923
|
+
// The ONE live, mode-dependent admission list (`[]` under `pair`) every
|
|
1924
|
+
// admission site reads per request — never a boot copy.
|
|
1925
|
+
// See change: retire-trusted-networks-bypass (D1).
|
|
1926
|
+
const admissionList = () => admissionTrustedNetworks(config.resolvedTrustedNetworks ?? []);
|
|
1620
1927
|
// Host-admission gate (issue #637, design D1/D4/D6) — the DNS-rebinding
|
|
1621
1928
|
// defence. Under rebinding the attacker page is SAME-ORIGIN with the
|
|
1622
1929
|
// dashboard, so its GETs carry no Origin and its peer is loopback: every
|
|
@@ -1649,6 +1956,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1649
1956
|
// IP bind is already covered by the IP-literal rule; this matters when
|
|
1650
1957
|
// the bind is a NAME.
|
|
1651
1958
|
bindHost: config.host,
|
|
1959
|
+
// Exact certificate names of the TLS listener (empty unless enabled + bound).
|
|
1960
|
+
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
1652
1961
|
},
|
|
1653
1962
|
...resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()),
|
|
1654
1963
|
});
|
|
@@ -1675,6 +1984,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1675
1984
|
allowedHosts: liveAllowedHosts(),
|
|
1676
1985
|
publicBaseUrls: livePublicBaseUrls(),
|
|
1677
1986
|
bindHost: config.host,
|
|
1987
|
+
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
1678
1988
|
// Env-over-config, resolved the SAME way as the hook (D4): a mixed state
|
|
1679
1989
|
// (env=report + config=enforce) must keep the Origin gate's report-only
|
|
1680
1990
|
// behaviour in step with the hook, else the escape hatch only half-engages.
|
|
@@ -1696,7 +2006,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1696
2006
|
grantPlanes.register(createFilesystemPlane());
|
|
1697
2007
|
grantPlanes.register(createCwdPlane({ pinDirectory: (dir) => preferencesStore.pinDirectory(dir) }));
|
|
1698
2008
|
grantPlanes.register(
|
|
1699
|
-
createNetworkPlane({
|
|
2009
|
+
createNetworkPlane({
|
|
2010
|
+
readTrustedNetworks: () => loadConfig().trustedNetworks ?? [],
|
|
2011
|
+
writeConfigPartial,
|
|
2012
|
+
networkTrustActive: () => effectiveTrustMode().mode === "legacy",
|
|
2013
|
+
}),
|
|
1700
2014
|
);
|
|
1701
2015
|
grantPlanes.register(
|
|
1702
2016
|
createCorsPlane({ readRawCors: () => (readRawConfig().cors ?? {}) as Record<string, unknown>, writeConfigPartial }),
|
|
@@ -1732,11 +2046,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1732
2046
|
});
|
|
1733
2047
|
installGrantCoordinator(grantCoordinator);
|
|
1734
2048
|
browserGateway.registerHandler("grant_response", (msg) => {
|
|
1735
|
-
grantCoordinator
|
|
1736
|
-
|
|
1737
|
-
|
|
2049
|
+
grantCoordinator
|
|
2050
|
+
.onResponse(msg)
|
|
2051
|
+
.then(() => storePiTrustChoiceOfVerdict(piTrustMirror, msg))
|
|
2052
|
+
.catch((err: unknown) => {
|
|
2053
|
+
console.error(`[access-grant] grant_response failed: ${(err as Error)?.message ?? err}`);
|
|
2054
|
+
});
|
|
1738
2055
|
});
|
|
1739
2056
|
setNetworkDenialObserver((request) => {
|
|
2057
|
+
// `pair`: a network match grants nothing, so a denial is not a trust request
|
|
2058
|
+
// — the block event is still recorded (by the guard), but no network prompt
|
|
2059
|
+
// is raised; the operator is asked when the device knocks.
|
|
2060
|
+
// See change: retire-trusted-networks-bypass (D6).
|
|
2061
|
+
if (effectiveTrustMode().mode === "pair") return;
|
|
1740
2062
|
grantCoordinator.onDenial(
|
|
1741
2063
|
{
|
|
1742
2064
|
plane: "network",
|
|
@@ -1783,6 +2105,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1783
2105
|
cb(null, isCorsOriginAllowed(origin ?? undefined, corsOpts()));
|
|
1784
2106
|
},
|
|
1785
2107
|
credentials: true,
|
|
2108
|
+
methods: CORS_ALLOWED_METHODS,
|
|
1786
2109
|
});
|
|
1787
2110
|
// Close the rate-limiter's log window on a timer so the `suppressed <n>`
|
|
1788
2111
|
// summary lands even when no further refusal arrives (D5). Unref'd: a
|
|
@@ -1817,6 +2140,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1817
2140
|
// Bearer device-auth branch — registered BEFORE the OAuth plugin so its
|
|
1818
2141
|
// onRequest hook runs first and OAuth can early-return when already
|
|
1819
2142
|
// authenticated. Additive (D5/D7); independent of whether OAuth is on.
|
|
2143
|
+
// Live-preview capability paths (change: retire-trusted-networks-bypass, D5).
|
|
2144
|
+
// The hook runs BEFORE the bearer / OAuth / identity hooks: a preview request
|
|
2145
|
+
// carries no cookie (opaque-origin frame), so it would otherwise be refused
|
|
2146
|
+
// there. It admits ONLY a valid `/live/<id>/~c/<token>/…` raw path.
|
|
2147
|
+
// Liveness is re-checked at every use, so a revoked device, an ended session
|
|
2148
|
+
// or a removed target is refused on its next request.
|
|
2149
|
+
const liveCapabilities = new LiveCapabilityStore({
|
|
2150
|
+
isTargetLive: (id) => liveServerManager.get(id) !== undefined,
|
|
2151
|
+
isPrincipalLive: (p) => {
|
|
2152
|
+
if (p.identityExpiresAt !== undefined && p.identityExpiresAt <= Date.now()) return false;
|
|
2153
|
+
// Minted on network trust alone: only valid while network trust still authenticates.
|
|
2154
|
+
if (p.kind === "network") return effectiveTrustMode().mode === "legacy";
|
|
2155
|
+
if (p.kind === "device") return pairedDeviceRegistry.list().some((d) => d.id === p.deviceId);
|
|
2156
|
+
if (p.kind === "session" && p.session) return effectiveSessionTier(p.session, passkeyService) !== null;
|
|
2157
|
+
return true;
|
|
2158
|
+
},
|
|
2159
|
+
});
|
|
2160
|
+
fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities));
|
|
1820
2161
|
registerBearerAuth(fastify, { registry: pairedDeviceRegistry });
|
|
1821
2162
|
registerDeviceSessionRoutes(fastify, {
|
|
1822
2163
|
registry: pairedDeviceRegistry,
|
|
@@ -1881,7 +2222,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1881
2222
|
fastify.addHook("onRequest", async (request, reply) => {
|
|
1882
2223
|
const enforced = identityEnforced();
|
|
1883
2224
|
const hasPrincipal = (request as { principal?: unknown }).principal != null;
|
|
1884
|
-
const hasLocalToken =
|
|
2225
|
+
const hasLocalToken = hasLocalCredential(request.headers);
|
|
1885
2226
|
const allowed = identityFloorAllows({ enforced, path: request.url, method: request.method, hasPrincipal, hasLocalToken });
|
|
1886
2227
|
if (!allowed) return reply.code(401).send({ success: false, error: "sign_in_required" });
|
|
1887
2228
|
// D23 break-glass (local-token part): the host-only token with no
|
|
@@ -1894,15 +2235,35 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1894
2235
|
}
|
|
1895
2236
|
}
|
|
1896
2237
|
});
|
|
2238
|
+
// Native passkey users (user directory + WebAuthn ceremonies). Always
|
|
2239
|
+
// constructed (cheap: one small file read) so `/api/users` can report
|
|
2240
|
+
// "disabled"; inert until `auth.passkeys.enabled`, which the auth plugin
|
|
2241
|
+
// applies at register and on every reload. The RP context is the SAME
|
|
2242
|
+
// redirect-base resolution OAuth uses. See change: add-passkey-user-auth.
|
|
2243
|
+
const passkeyService = new PasskeyService({
|
|
2244
|
+
directory: new UserDirectory(),
|
|
2245
|
+
getRpContext: (override) => resolveRpContext(config.port, override),
|
|
2246
|
+
});
|
|
2247
|
+
passkeyService.configure(config.authConfig);
|
|
2248
|
+
let oauthLoginAccessor: (() => boolean) | null = null;
|
|
1897
2249
|
if (config.authConfig) {
|
|
1898
|
-
await registerAuthPlugin(fastify, {
|
|
2250
|
+
oauthLoginAccessor = (await registerAuthPlugin(fastify, {
|
|
1899
2251
|
authConfig: config.authConfig,
|
|
1900
2252
|
port: config.port,
|
|
1901
2253
|
resolvedTrustedNetworks: config.resolvedTrustedNetworks,
|
|
2254
|
+
readAdmissionTrustedNetworks: admissionList,
|
|
2255
|
+
onSessionEnd: (cookie) => liveCapabilities.revokeBySessionKey(sessionKeyOf(cookie)),
|
|
1902
2256
|
localToken,
|
|
1903
2257
|
localTrust,
|
|
1904
|
-
|
|
2258
|
+
passkeys: passkeyService,
|
|
2259
|
+
})).hasUsableOAuthProvider;
|
|
1905
2260
|
}
|
|
2261
|
+
// Live "is a usable login method configured" (drives the `sign-in` remedy of an
|
|
2262
|
+
// `operate_required` refusal). See change: surface-operate-required-remedy.
|
|
2263
|
+
const loginAvailable = buildLoginAvailable(oauthLoginAccessor, passkeyService, {
|
|
2264
|
+
enforced: identityEnforced,
|
|
2265
|
+
loginConfigs: () => browserLoginConfigRegistry.list(),
|
|
2266
|
+
});
|
|
1906
2267
|
// `/auth/status` is what the client's WS-refusal handler polls to tell
|
|
1907
2268
|
// `auth_required` (→ browser login gate, D16/H5) from a plain `offline`.
|
|
1908
2269
|
// Registered whenever the legacy cookie plugin did not register one — no
|
|
@@ -1938,7 +2299,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1938
2299
|
// prints `http://localhost:<port>/?pi_local=<code>`; the browser exchanges it
|
|
1939
2300
|
// like `#pi_handoff` and keeps the bearer in memory (no cookies, D22).
|
|
1940
2301
|
fastify.post("/api/identity/local-code", async (request, reply) => {
|
|
1941
|
-
if (!
|
|
2302
|
+
if (!hasLocalCredential(request.headers)) {
|
|
1942
2303
|
reply.code(401);
|
|
1943
2304
|
return { success: false as const, error: "local_token_required" };
|
|
1944
2305
|
}
|
|
@@ -1989,7 +2350,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1989
2350
|
fastify.addHook(
|
|
1990
2351
|
"onRequest",
|
|
1991
2352
|
createRouteTierGate({
|
|
1992
|
-
getTrustedNetworks:
|
|
2353
|
+
getTrustedNetworks: admissionList,
|
|
1993
2354
|
localTrust,
|
|
1994
2355
|
}),
|
|
1995
2356
|
);
|
|
@@ -1998,7 +2359,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1998
2359
|
// runtime admits without a restart. Created BEFORE registerSessionApi so the
|
|
1999
2360
|
// new lifecycle/extension-ui routes can carry it as a preHandler.
|
|
2000
2361
|
const networkGuard = createNetworkGuard(
|
|
2001
|
-
|
|
2362
|
+
admissionList,
|
|
2002
2363
|
{ localToken, localTrust },
|
|
2003
2364
|
);
|
|
2004
2365
|
|
|
@@ -2032,7 +2393,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2032
2393
|
metaPersistence,
|
|
2033
2394
|
}),
|
|
2034
2395
|
}, extras ?? {}),
|
|
2035
|
-
getTrustedNetworks:
|
|
2396
|
+
getTrustedNetworks: admissionList,
|
|
2036
2397
|
});
|
|
2037
2398
|
|
|
2038
2399
|
// Register route modules
|
|
@@ -2072,6 +2433,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2072
2433
|
sessionManager,
|
|
2073
2434
|
eventStore,
|
|
2074
2435
|
networkGuard,
|
|
2436
|
+
isToolInFlight: inFlightToolCalls.isInFlight,
|
|
2437
|
+
toolResultStats,
|
|
2075
2438
|
sessionArchive,
|
|
2076
2439
|
remoteTranscriptStore,
|
|
2077
2440
|
isResolverActive: identityEnforced,
|
|
@@ -2092,22 +2455,37 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2092
2455
|
// connected session so a saved policy applies without a manual restart
|
|
2093
2456
|
// (pi reads its settings only at session construction). See change:
|
|
2094
2457
|
// retry-forever-with-stop-control.
|
|
2095
|
-
|
|
2458
|
+
const reloadConnectedSessions = () => {
|
|
2459
|
+
// Fire-and-forget by contract (the route answers with the target count,
|
|
2460
|
+
// not per-session outcomes), but the rejection is OWNED: `dispatchReload`
|
|
2461
|
+
// reports failures as terminal `command_feedback`, so a throw here is a
|
|
2462
|
+
// bug and must be logged rather than becoming an unhandled rejection.
|
|
2463
|
+
const ids = reloadFanOutTargets();
|
|
2464
|
+
for (const id of ids) {
|
|
2465
|
+
dispatchReload(id).catch((err) => {
|
|
2466
|
+
console.error(`[dashboard] pi-settings reload fan-out failed for ${id}:`, err);
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
return ids.length;
|
|
2470
|
+
};
|
|
2471
|
+
registerPiRetryRoutes(fastify, { networkGuard, reloadConnectedSessions });
|
|
2472
|
+
// On-demand AI mermaid repair (opt-in via `mermaidRepair` config; 404 when off).
|
|
2473
|
+
// See change: add-mermaid-ai-repair.
|
|
2474
|
+
registerMermaidRepairRoutes(fastify, {
|
|
2096
2475
|
networkGuard,
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
for (const id of ids) {
|
|
2104
|
-
dispatchReload(id).catch((err) => {
|
|
2105
|
-
console.error(`[dashboard] retry-policy reload fan-out failed for ${id}:`, err);
|
|
2106
|
-
});
|
|
2476
|
+
getConfig: () => loadConfig().mermaidRepair,
|
|
2477
|
+
getRegistry: async () => {
|
|
2478
|
+
try {
|
|
2479
|
+
return await getModelRegistry();
|
|
2480
|
+
} catch {
|
|
2481
|
+
return null;
|
|
2107
2482
|
}
|
|
2108
|
-
return ids.length;
|
|
2109
2483
|
},
|
|
2484
|
+
getStreamSimple: getStreamSimpleFn,
|
|
2110
2485
|
});
|
|
2486
|
+
// pi global settings.json editor (typed form + raw JSON) and the
|
|
2487
|
+
// default-model mirror/drift repair. See change: edit-pi-agent-settings.
|
|
2488
|
+
registerPiSettingsRoutes(fastify, { networkGuard, reloadConnectedSessions, readDashboardConfig: loadConfig });
|
|
2111
2489
|
registerGitRoutes(fastify, {
|
|
2112
2490
|
networkGuard, sessionManager, browserGateway, worktreeInitRegistry,
|
|
2113
2491
|
sendToSession: (id, msg) => piGateway.sendToSession(id, msg),
|
|
@@ -2137,11 +2515,70 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2137
2515
|
const cwd = typeof msg?.cwd === "string" ? msg.cwd : undefined;
|
|
2138
2516
|
if (cwd) worktreeInitRegistry.unsubscribeCwd(cwd, ws);
|
|
2139
2517
|
});
|
|
2140
|
-
registerFileRoutes(fastify, {
|
|
2518
|
+
registerFileRoutes(fastify, {
|
|
2519
|
+
sessionManager,
|
|
2520
|
+
preferencesStore,
|
|
2521
|
+
networkGuard,
|
|
2522
|
+
// Plugin file-handler seams for POST /api/file/write-binary: live claim registry
|
|
2523
|
+
// (read at request time: enabled + server entry loaded), registered validators,
|
|
2524
|
+
// bounded worker pool. See change: add-editor-pane-file-handlers (D4).
|
|
2525
|
+
fileHandlers: {
|
|
2526
|
+
resolveClaim: (key) => {
|
|
2527
|
+
const ref = parseFileHandlerClaimKey(key);
|
|
2528
|
+
if (!ref) return undefined;
|
|
2529
|
+
const plugin = discoverPlugins().find((p) => p.manifest.id === ref.pluginId);
|
|
2530
|
+
if (!plugin || !fixtureEntryAllowed(plugin.manifest)) return undefined;
|
|
2531
|
+
const claim = plugin.manifest.claims.find((c) => c.slot === "editor-pane-file-handler" && c.id === ref.claimId);
|
|
2532
|
+
if (!claim) return undefined;
|
|
2533
|
+
return {
|
|
2534
|
+
pluginId: ref.pluginId,
|
|
2535
|
+
claim,
|
|
2536
|
+
enabled: resolvePluginEnabled(
|
|
2537
|
+
getPluginConfigFromFile(loadConfig(), ref.pluginId) as Record<string, unknown>,
|
|
2538
|
+
plugin.manifest.defaultEnabled,
|
|
2539
|
+
),
|
|
2540
|
+
serverLoaded: getPluginStatusStore().getStatus(ref.pluginId)?.loaded === true,
|
|
2541
|
+
};
|
|
2542
|
+
},
|
|
2543
|
+
getValidator: (pluginId, claimId) => getFileValidatorRegistry().get(pluginId, claimId),
|
|
2544
|
+
validatorPool: getFileValidatorPool(),
|
|
2545
|
+
},
|
|
2546
|
+
});
|
|
2141
2547
|
registerGrepRoutes(fastify, { sessionManager, networkGuard });
|
|
2548
|
+
// Folder project identity (declared file + plugin marker rules). Rules come
|
|
2549
|
+
// only from plugins that are loaded + enabled + fixture-allowed, read per
|
|
2550
|
+
// request. See change: add-project-scoped-apps.
|
|
2551
|
+
registerFolderProjectRoutes(fastify, {
|
|
2552
|
+
networkGuard,
|
|
2553
|
+
knownCwds: () => [
|
|
2554
|
+
...sessionManager.listAll().map((s) => s.cwd),
|
|
2555
|
+
...preferencesStore.getPinnedDirectories(),
|
|
2556
|
+
],
|
|
2557
|
+
getRuleSources: () => {
|
|
2558
|
+
const cfg = loadConfig();
|
|
2559
|
+
const store = getPluginStatusStore();
|
|
2560
|
+
return collectRuleSources(discoverPlugins(), {
|
|
2561
|
+
fixtureAllowed: (m) => fixtureEntryAllowed(m),
|
|
2562
|
+
isLoaded: (id) => store.getStatus(id)?.loaded === true,
|
|
2563
|
+
isEnabled: (m) => resolvePluginEnabled(getPluginConfigFromFile(cfg, m.id), m.defaultEnabled),
|
|
2564
|
+
});
|
|
2565
|
+
},
|
|
2566
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2567
|
+
onTruncated: (cwd) => console.debug(`[folder-project] detection truncated for ${cwd}`),
|
|
2568
|
+
});
|
|
2142
2569
|
// Settings → Access review surface + the one endpoint that can create a
|
|
2143
2570
|
// filesystem grant. See change: add-access-grants-and-review.
|
|
2144
2571
|
registerAccessRoutes(fastify, { networkGuard, preferencesStore, writeConfigPartial });
|
|
2572
|
+
// Pending-question stack REST roads (list/detail/answer/summarize); the answer
|
|
2573
|
+
// claim is shared with the browser `prompt_response` road.
|
|
2574
|
+
// See change: add-pending-question-stack (D8, D9).
|
|
2575
|
+
registerQuestionRoutes(fastify, {
|
|
2576
|
+
networkGuard,
|
|
2577
|
+
store: questionStore,
|
|
2578
|
+
sendToSession: (sessionId, msg) => piGateway.sendToSession(sessionId, msg as never),
|
|
2579
|
+
isResolverActive: identityEnforced,
|
|
2580
|
+
ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
|
|
2581
|
+
});
|
|
2145
2582
|
registerAccessPromptRoutes(fastify, {
|
|
2146
2583
|
networkGuard,
|
|
2147
2584
|
coordinator: grantCoordinator,
|
|
@@ -2168,6 +2605,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2168
2605
|
preferencesStore,
|
|
2169
2606
|
directoryService,
|
|
2170
2607
|
networkGuard,
|
|
2608
|
+
piGateway,
|
|
2609
|
+
// Live (per-request) config for the workflow-schema gates + new-project default.
|
|
2610
|
+
getOpenSpecConfig: () => loadConfig().openspec,
|
|
2611
|
+
// Own bounded pool for the workflow-schema `newer`/`conflict` validate: the
|
|
2612
|
+
// directory service's semaphore is not exposed. See change: add-pi-spec-driven-schema.
|
|
2613
|
+
spawnSemaphore: createSemaphore(loadConfig().openspec.maxConcurrentSpawns),
|
|
2171
2614
|
onOpenSpecChanged: (cwd) => {
|
|
2172
2615
|
const data = directoryService.getOpenSpecData(cwd);
|
|
2173
2616
|
if (data) browserGateway.broadcastToAll({ type: "openspec_update", cwd, data });
|
|
@@ -2205,14 +2648,49 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2205
2648
|
// Reclaims the automation-produced ephemeral sessions #383 is about; the
|
|
2206
2649
|
// acquire registry + caps are shared-layer modules the embed front constructs.
|
|
2207
2650
|
// See change: add-embed-session-lifecycle.
|
|
2651
|
+
// ONE terminator behind every unattended kill (reaper, caps, automation stop):
|
|
2652
|
+
// strategy-agnostic (keys on session.pid, not the headless registry).
|
|
2653
|
+
// See change: fix-session-reclaim-tmux.
|
|
2654
|
+
const sessionTerminator = createSessionTerminator({
|
|
2655
|
+
sessionManager,
|
|
2656
|
+
headlessPidRegistry: browserGateway.headlessPidRegistry,
|
|
2657
|
+
});
|
|
2658
|
+
const abortSpawnedRunImpl = createAbortSpawnedRun({
|
|
2659
|
+
terminate: sessionTerminator.terminate,
|
|
2660
|
+
sendShutdownHint: (sessionId) => piGateway.sendToSession(sessionId, { type: "shutdown", sessionId }),
|
|
2661
|
+
recordReclaimFailure: () => embedLifecycle.metrics.recordReclaimFailure(),
|
|
2662
|
+
});
|
|
2663
|
+
// Plugin session-close hook: closer registry + close requests, shared by
|
|
2664
|
+
// the reaper and every plugin's ctx. See change: add-session-close-plugin-hook.
|
|
2665
|
+
const sessionClosers = createSessionCloserRegistry();
|
|
2666
|
+
const markArchiveOnEnd = (id: string, value = true): void => {
|
|
2667
|
+
sessionManager.update(id, { archiveOnEnd: value });
|
|
2668
|
+
const file = sessionManager.get(id)?.sessionFile;
|
|
2669
|
+
if (file) {
|
|
2670
|
+
try {
|
|
2671
|
+
mergeSessionMeta(file, { archiveOnEnd: value });
|
|
2672
|
+
} catch { /* best-effort */ }
|
|
2673
|
+
}
|
|
2674
|
+
};
|
|
2208
2675
|
const embedLifecycle = createEmbedLifecycleController({
|
|
2676
|
+
closers: sessionClosers,
|
|
2677
|
+
markArchiveOnEnd,
|
|
2678
|
+
// Same enabled predicate as the server-entry loader: a disabled owner's
|
|
2679
|
+
// closer is never consulted (no closer ⇒ close).
|
|
2680
|
+
isPluginEnabled: (pluginId) =>
|
|
2681
|
+
resolvePluginEnabled(
|
|
2682
|
+
getPluginConfigFromFile(loadConfig(), pluginId) as Record<string, unknown>,
|
|
2683
|
+
discoverPlugins().find((p) => p.manifest.id === pluginId)?.manifest.defaultEnabled,
|
|
2684
|
+
),
|
|
2209
2685
|
config: () => loadConfig().embedLifecycle,
|
|
2210
2686
|
listSessions: () => sessionManager.listAll(),
|
|
2211
2687
|
getSubscriberCount: (id) => browserGateway.getSubscriberCount(id),
|
|
2212
2688
|
listTerminalCwds: () => terminalManager.list().map((t) => t.cwd),
|
|
2213
2689
|
hasPendingUiRequest: (id) => browserGateway.hasPendingUiRequest(id),
|
|
2214
2690
|
hasPendingPromptRequests: (id) => browserGateway.hasPendingPromptRequests(id),
|
|
2215
|
-
|
|
2691
|
+
// graceMs 0: killProcess is itself SIGTERM → 2 s → SIGKILL (design D2).
|
|
2692
|
+
terminate: (id) =>
|
|
2693
|
+
sessionTerminator.terminate(id, { graceMs: 0, verifyIdentity: true, stampManualClose: true }),
|
|
2216
2694
|
sendStopAfterTurn: (id) =>
|
|
2217
2695
|
piGateway.sendToSession(id, { type: "stop_after_turn", sessionId: id }),
|
|
2218
2696
|
});
|
|
@@ -2239,7 +2717,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2239
2717
|
console.log("[dashboard] No client build found — running in API-only mode");
|
|
2240
2718
|
}
|
|
2241
2719
|
|
|
2242
|
-
|
|
2720
|
+
registerAcpRoutes(fastify);
|
|
2721
|
+
registerTlsRoutes(fastify, { networkGuard, listener: tlsListener });
|
|
2722
|
+
registerSystemRoutes(fastify, { onVaultConfigChanged: () => void vaultDelivery.pushNow(), tls: tlsListener, sessionManager, preferencesStore, metaPersistence, config, networkGuard, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, clientDir, clientBuild, readTrustedNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []), readAccessGrants: () => snapshotAccessGrantHealth({ coordinator: grantCoordinator, yolo, refusalCount: () => listRefusals().length, promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true, killSwitch: () => isGrantPromptKilled(), hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode, operatorChannels: () => promptChannelCount() }), keeperLogStats: { get: () => getKeeperManager().getKeeperLogStats() }, readPushErrors: pushService ? () => pushService?.errors ?? [] : pushInitError ? () => [pushInitError as string] : undefined });
|
|
2243
2723
|
registerHostGateRoutes(fastify, { getCtx: getHostGateCtx, state: hostGateState, networkGuard });
|
|
2244
2724
|
// GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
|
|
2245
2725
|
// Assigned by the runtime-overlay block below; read lazily per request.
|
|
@@ -2260,6 +2740,72 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2260
2740
|
});
|
|
2261
2741
|
registerPushRoutes(fastify, { getPush: () => pushService });
|
|
2262
2742
|
registerToolRoutes(fastify, { registry: getDefaultRegistry(), networkGuard });
|
|
2743
|
+
// Managed services: definitions + offers + lifecycle + secrets. Boot is
|
|
2744
|
+
// adoption only (no probes, no network I/O), and a no-op without
|
|
2745
|
+
// services.json. See change: add-service-registry-core.
|
|
2746
|
+
const serviceManager = new ServiceManager({
|
|
2747
|
+
paths: servicesPaths(),
|
|
2748
|
+
run: defaultCommandRunner,
|
|
2749
|
+
resolveBinary: (name) => {
|
|
2750
|
+
try {
|
|
2751
|
+
const r = getDefaultRegistry().resolve(name);
|
|
2752
|
+
return r.ok ? r.path : null;
|
|
2753
|
+
} catch {
|
|
2754
|
+
return null;
|
|
2755
|
+
}
|
|
2756
|
+
},
|
|
2757
|
+
discoverOffers: () => discoverServiceOffers(resolveInstallRoot(fileURLToPath(import.meta.url))),
|
|
2758
|
+
// Content-free hint (type only): Settings → Services refetches `GET /api/services`.
|
|
2759
|
+
// The manager coalesces to ≤ 1 per 500 ms. See change: add-services-settings-ui.
|
|
2760
|
+
onChange: () => browserGateway.broadcastToAll({ type: "services_changed" }),
|
|
2761
|
+
});
|
|
2762
|
+
// The knock's pre-switch gate state, built ONCE: the pairing routes and the
|
|
2763
|
+
// `request-access` remedy of vault / services refusals read the same Host
|
|
2764
|
+
// admission and the same cached LAN-interface list, so the remedy cannot drift
|
|
2765
|
+
// from the knock. See change: add-request-access-remedy (D1, D2, D4).
|
|
2766
|
+
const knockPeerDeps: KnockPeerDeps = {
|
|
2767
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
2768
|
+
getLanInterfaces: createLanInterfaceProvider({ bindHost: config.host }),
|
|
2769
|
+
// The RAW configured list (not the admission list): knock eligibility, read
|
|
2770
|
+
// live in both trust modes. See change: retire-trusted-networks-bypass (D7).
|
|
2771
|
+
getKnockEligibleNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []),
|
|
2772
|
+
};
|
|
2773
|
+
const requestAccessAvailable = createRequestAccessAvailable(knockPeerDeps, localTrust);
|
|
2774
|
+
registerServiceRoutes(fastify, {
|
|
2775
|
+
manager: serviceManager,
|
|
2776
|
+
networkGuard,
|
|
2777
|
+
localTrust,
|
|
2778
|
+
loginAvailable,
|
|
2779
|
+
requestAccessAvailable,
|
|
2780
|
+
getTrustedNetworks: admissionList,
|
|
2781
|
+
});
|
|
2782
|
+
// Credential vault: hub-owned accounts, bindings and per-project grants.
|
|
2783
|
+
// Management routes need operate authority or local trust; values never leave
|
|
2784
|
+
// through them. See change: add-credential-vault.
|
|
2785
|
+
registerVaultRoutes(fastify, {
|
|
2786
|
+
store: vaultStore,
|
|
2787
|
+
importer: createVaultImport({ store: vaultStore, candidates: () => defaultKnownLocations() }),
|
|
2788
|
+
networkGuard,
|
|
2789
|
+
localTrust,
|
|
2790
|
+
loginAvailable,
|
|
2791
|
+
requestAccessAvailable,
|
|
2792
|
+
hostPolicy: policyRegistry,
|
|
2793
|
+
listOpenProjects: () => vaultDelivery.listOpenProjects(),
|
|
2794
|
+
projects: vaultProjects,
|
|
2795
|
+
getSessionBindingState: (sessionId) => vaultDelivery.getSessionState(sessionId),
|
|
2796
|
+
getPluginDeclarations: () =>
|
|
2797
|
+
discoverPlugins()
|
|
2798
|
+
.filter((p) => (p.manifest.vaultBindings?.length ?? 0) > 0)
|
|
2799
|
+
.map((p) => ({ pluginId: p.manifest.id, displayName: p.manifest.displayName, declared: p.manifest.vaultBindings ?? [] })),
|
|
2800
|
+
});
|
|
2801
|
+
// ACME certificate sources: per-entry config routes + vault-backed solver credentials
|
|
2802
|
+
// (the credentials route answers exactly like a vault management route).
|
|
2803
|
+
// See change: add-acme-dns01-certs.
|
|
2804
|
+
registerAcmeRoutes(fastify, {
|
|
2805
|
+
networkGuard,
|
|
2806
|
+
manageGuard: createVaultManageGuard({ localTrust, loginAvailable, requestAccessAvailable, hostPolicy: policyRegistry }),
|
|
2807
|
+
listener: tlsListener,
|
|
2808
|
+
});
|
|
2263
2809
|
// Pi runtime discovery + atomic dual selection. See change: select-pi-runtime-install.
|
|
2264
2810
|
registerPiRuntimeRoutes(fastify, { registry: getDefaultRegistry(), networkGuard });
|
|
2265
2811
|
// Node family discovery + atomic triple selection (node+npm+npx).
|
|
@@ -2357,6 +2903,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2357
2903
|
});
|
|
2358
2904
|
|
|
2359
2905
|
registerPackageRoutes(fastify, { packageManagerWrapper });
|
|
2906
|
+
registerPackageHealthRoutes(fastify, { packageManagerWrapper });
|
|
2360
2907
|
registerResourceActivationRoutes(fastify, {
|
|
2361
2908
|
networkGuard,
|
|
2362
2909
|
piGateway,
|
|
@@ -2482,8 +3029,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2482
3029
|
]);
|
|
2483
3030
|
|
|
2484
3031
|
// Live-server-preview routes + reverse proxy (main-origin /live/:id/*).
|
|
2485
|
-
registerLiveServerRoutes(fastify, liveServerManager, { networkGuard });
|
|
2486
|
-
registerLiveServerProxy(fastify, liveServerManager);
|
|
3032
|
+
registerLiveServerRoutes(fastify, liveServerManager, { networkGuard, capabilities: liveCapabilities });
|
|
3033
|
+
registerLiveServerProxy(fastify, liveServerManager, { isDeviceBearer: (token) => pairedDeviceRegistry.verify(token) !== null });
|
|
2487
3034
|
|
|
2488
3035
|
// ONE model runtime for the provider-auth flow listing AND the model proxy,
|
|
2489
3036
|
// injected so auth/ never imports model-proxy/.
|
|
@@ -2523,7 +3070,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2523
3070
|
}
|
|
2524
3071
|
},
|
|
2525
3072
|
});
|
|
2526
|
-
registerKnownServersRoutes(fastify, {
|
|
3073
|
+
registerKnownServersRoutes(fastify, {
|
|
3074
|
+
networkGuard,
|
|
3075
|
+
getPeerServers: () => peerServers,
|
|
3076
|
+
localToken,
|
|
3077
|
+
localTrust,
|
|
3078
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
3079
|
+
moves: knownServerMoves,
|
|
3080
|
+
});
|
|
2527
3081
|
registerLocalProofRoutes(fastify, { codes: localProofCodes, ctx: localTrust });
|
|
2528
3082
|
registerPairingRoutes(fastify, {
|
|
2529
3083
|
networkGuard,
|
|
@@ -2532,13 +3086,28 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2532
3086
|
registry: pairedDeviceRegistry,
|
|
2533
3087
|
localToken,
|
|
2534
3088
|
localTrust,
|
|
2535
|
-
hostAdmission:
|
|
3089
|
+
hostAdmission: knockPeerDeps.hostAdmission,
|
|
3090
|
+
// Shared "is a login method configured" thunk (same instance as vault/services): drives the `sign-in` remedy.
|
|
3091
|
+
loginAvailable,
|
|
2536
3092
|
// Public (tunnel + configured public) base URLs, already TLS-gated.
|
|
2537
3093
|
getReachableUrls: () => pairingManager.reachableUrls(),
|
|
2538
3094
|
getPort: () => {
|
|
2539
3095
|
const addr = fastify.server.address();
|
|
2540
3096
|
return typeof addr === "object" && addr !== null ? addr.port : config.port;
|
|
2541
3097
|
},
|
|
3098
|
+
// LAN knock pairing: the switch is read LIVE per request (no restart), and
|
|
3099
|
+
// the on-link gate scores the peer against the interfaces the bind covers.
|
|
3100
|
+
// See change: add-lan-knock-pairing.
|
|
3101
|
+
getAcceptLanRequests: liveAcceptLanRequests,
|
|
3102
|
+
getLanInterfaces: knockPeerDeps.getLanInterfaces,
|
|
3103
|
+
getKnockEligibleNetworks: knockPeerDeps.getKnockEligibleNetworks,
|
|
3104
|
+
});
|
|
3105
|
+
// Operator user directory (passkeys). See change: add-passkey-user-auth.
|
|
3106
|
+
registerUserRoutes(fastify, {
|
|
3107
|
+
service: passkeyService,
|
|
3108
|
+
localToken,
|
|
3109
|
+
localTrust,
|
|
3110
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
2542
3111
|
});
|
|
2543
3112
|
// Mint a single-use WS ticket (D11). Authenticated (networkGuard: cookie,
|
|
2544
3113
|
// trusted network, or Authorization: Bearer). The ticket is bound to a WS
|
|
@@ -2619,6 +3188,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2619
3188
|
networkGuard,
|
|
2620
3189
|
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
2621
3190
|
});
|
|
3191
|
+
// Add-ons hub: feature catalog + combined feature toggle. See change: addons-hub-feature-catalog.
|
|
3192
|
+
registerAddonsRoutes(fastify, {
|
|
3193
|
+
networkGuard,
|
|
3194
|
+
packageManagerWrapper,
|
|
3195
|
+
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3196
|
+
knownDirectories: () => directoryService.knownDirectories(),
|
|
3197
|
+
lookupNpm: (name) => fetchPackageMeta(name),
|
|
3198
|
+
setPluginsEnabled,
|
|
3199
|
+
// Fastify here runs with logger:false, so its log would drop every toggle line.
|
|
3200
|
+
log: { info: (m) => console.log(m), warn: (m) => console.warn(m), error: (m) => console.error(m) },
|
|
3201
|
+
});
|
|
2622
3202
|
registerProviderRoutes(fastify, { networkGuard, piGateway, browserGateway, port: config.port });
|
|
2623
3203
|
|
|
2624
3204
|
// ── Model Proxy ───────────────────────────────────────────────────
|
|
@@ -2693,7 +3273,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2693
3273
|
createNetworkGuardHook({
|
|
2694
3274
|
// Live thunk, never a boot snapshot: a CIDR added at runtime admits
|
|
2695
3275
|
// without a restart (D15). Mirrors the per-route guard at 1499.
|
|
2696
|
-
trustedNetworks:
|
|
3276
|
+
trustedNetworks: admissionList,
|
|
2697
3277
|
localToken,
|
|
2698
3278
|
localTrust,
|
|
2699
3279
|
getBypassUrls: () => config.authConfig?.bypassUrls ?? [],
|
|
@@ -2752,6 +3332,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2752
3332
|
});
|
|
2753
3333
|
}
|
|
2754
3334
|
|
|
3335
|
+
// An unmatched `/api` path is a JSON 404 in every mode, never `index.html` (or a
|
|
3336
|
+
// Vite proxy hop: Vite proxies `/api` straight back here). The guard's own two path
|
|
3337
|
+
// views decide, so an encoded or dotted spelling cannot reach the SPA shell either; an
|
|
3338
|
+
// unparseable target gets the same answer. See change: retro-ux-credential-vault (D7).
|
|
3339
|
+
const replyIfApiNotFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply | undefined => {
|
|
3340
|
+
const target = parseGuardTarget(request.url);
|
|
3341
|
+
const underApi = (p: string) => p === "/api" || p.startsWith("/api/");
|
|
3342
|
+
if (target && !underApi(target.raw) && !underApi(target.resolved)) return undefined;
|
|
3343
|
+
const rawPath = request.url.split(/[?#]/, 1)[0].slice(0, 200);
|
|
3344
|
+
return reply.code(404).send({ success: false, error: "not_found", message: `No API route for ${request.method} ${rawPath}` });
|
|
3345
|
+
};
|
|
3346
|
+
|
|
2755
3347
|
if (config.dev) {
|
|
2756
3348
|
// Dev mode: proxy to Vite dev server, fall back to production build
|
|
2757
3349
|
const VITE_PORTS = [3000, 5173, 5174];
|
|
@@ -2771,6 +3363,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2771
3363
|
|
|
2772
3364
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
2773
3365
|
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3366
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3367
|
+
if (apiMiss) return apiMiss;
|
|
2774
3368
|
// Try Vite proxy first
|
|
2775
3369
|
if (!vitePort) vitePort = await detectVitePort();
|
|
2776
3370
|
if (vitePort) {
|
|
@@ -2794,12 +3388,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2794
3388
|
});
|
|
2795
3389
|
} else if (hasProductionBuild) {
|
|
2796
3390
|
// Production mode: SPA fallback
|
|
2797
|
-
fastify.setNotFoundHandler(async (
|
|
3391
|
+
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3392
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3393
|
+
if (apiMiss) return apiMiss;
|
|
2798
3394
|
reply.header("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
2799
3395
|
return reply.sendFile("index.html");
|
|
2800
3396
|
});
|
|
2801
3397
|
} else {
|
|
2802
|
-
fastify.setNotFoundHandler(async (
|
|
3398
|
+
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3399
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3400
|
+
if (apiMiss) return apiMiss;
|
|
2803
3401
|
return reply.code(500).send({ error: "No client build found. Run `npm run build` first." });
|
|
2804
3402
|
});
|
|
2805
3403
|
}
|
|
@@ -2822,6 +3420,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2822
3420
|
if (addr && typeof addr === "object") return addr.port;
|
|
2823
3421
|
return null;
|
|
2824
3422
|
},
|
|
3423
|
+
tls: tlsListener,
|
|
2825
3424
|
piPort() {
|
|
2826
3425
|
// TCP only: a UDS listener has no port, and callers of `piPort()` are
|
|
2827
3426
|
// building `ws://host:<port>` URLs. Socket-transport callers read
|
|
@@ -2846,10 +3445,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2846
3445
|
// captured zombie held. `stop()` also clears `pingTimer`, which is
|
|
2847
3446
|
// what actually lets the process exit.
|
|
2848
3447
|
try { piGateway.stop(); } catch { /* ignore */ }
|
|
3448
|
+
// After the gateway: bridge teardown ends sessions (→ schedule);
|
|
3449
|
+
// stop() clears pending grace timers and latches the sweeper.
|
|
3450
|
+
// See change: archive-service-sessions-on-end.
|
|
3451
|
+
archiveSweeper.stop();
|
|
2849
3452
|
if (secondFastify) {
|
|
2850
3453
|
try { await secondFastify.close(); } catch { /* ignore */ }
|
|
2851
3454
|
secondFastify = null;
|
|
2852
3455
|
}
|
|
3456
|
+
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
2853
3457
|
try { await fastify.close(); } catch { /* ignore */ }
|
|
2854
3458
|
},
|
|
2855
3459
|
});
|
|
@@ -2900,6 +3504,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2900
3504
|
// setSpawnDashboardPiPort in process-manager.ts.
|
|
2901
3505
|
{
|
|
2902
3506
|
const { setSpawnDashboardPiPort } = await import("./spawn-process/process-manager.js");
|
|
3507
|
+
// The bind host is supplied below, once the listener policy is known: the
|
|
3508
|
+
// gateway's ACTUAL TCP host is not always `config.host`.
|
|
3509
|
+
// See change: harden-credential-proof-binding.
|
|
2903
3510
|
setSpawnDashboardPiPort(config.piPort);
|
|
2904
3511
|
// Pin spawned sessions to the transport actually served (read lazily,
|
|
2905
3512
|
// after the gateway starts) — never to another instance's socket.
|
|
@@ -2930,6 +3537,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2930
3537
|
piPort: config.piPort,
|
|
2931
3538
|
version: pkgVersion,
|
|
2932
3539
|
identity: ensureInstanceId(undefined, config.piPort),
|
|
3540
|
+
bindHost: config.host,
|
|
2933
3541
|
// NO signal handlers. `installReleaseHandlers` ends in
|
|
2934
3542
|
// `process.exit(0)`, and `cli.ts` already owns SIGTERM/SIGINT
|
|
2935
3543
|
// (`recordExitIntent` → `flush` → exit). A second exit-forcing
|
|
@@ -2955,7 +3563,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2955
3563
|
const { resolveLocalGatewayEndpoint } = await import(
|
|
2956
3564
|
"@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js"
|
|
2957
3565
|
);
|
|
2958
|
-
const { decideGatewayListeners, isTcpOptIn } = await import("./pi/gateway-transport-policy.js");
|
|
3566
|
+
const { decideGatewayListeners, isTcpOptIn, spawnDialHost } = await import("./pi/gateway-transport-policy.js");
|
|
2959
3567
|
const policy = decideGatewayListeners({
|
|
2960
3568
|
local: resolveLocalGatewayEndpoint(undefined, config.piPort),
|
|
2961
3569
|
tcpOptIn: config.gatewayTcp ?? isTcpOptIn(process.env),
|
|
@@ -2963,6 +3571,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2963
3571
|
piPort: config.piPort,
|
|
2964
3572
|
});
|
|
2965
3573
|
console.log(`[pi-gateway] ${policy.reason}`);
|
|
3574
|
+
// Spawned bridges dial — and on a loopback host demand the counter-proof
|
|
3575
|
+
// from — the host the gateway really binds (`policy.tcp.host`; 127.0.0.1 on
|
|
3576
|
+
// the fallback path), never the HTTP bind host.
|
|
3577
|
+
{
|
|
3578
|
+
const { setSpawnDashboardPiPort } = await import("./spawn-process/process-manager.js");
|
|
3579
|
+
setSpawnDashboardPiPort(config.piPort, spawnDialHost(policy));
|
|
3580
|
+
}
|
|
2966
3581
|
const { startGatewayListeners } = await import("./pi/gateway-listeners.js");
|
|
2967
3582
|
await startGatewayListeners(piGateway, policy, { piPort: config.piPort });
|
|
2968
3583
|
}
|
|
@@ -2978,6 +3593,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2978
3593
|
// registering during its activation is immediately routable.
|
|
2979
3594
|
const wsRouteRegistry = getWsRouteRegistry();
|
|
2980
3595
|
setPluginScopeResolver((path) => wsRouteRegistry.resolveScope(path));
|
|
3596
|
+
// Spawn-env contributors of a plugin disabled in config are skipped at
|
|
3597
|
+
// each spawn (the loader has no teardown hook). Same predicate as the
|
|
3598
|
+
// loader's `isEnabled` below. See change: add-context-mode-settings-plugin.
|
|
3599
|
+
setSpawnEnvPluginEnabledCheck((pluginId) => {
|
|
3600
|
+
const pluginCfg = getPluginConfigFromFile(loadConfig(), pluginId) as Record<string, unknown>;
|
|
3601
|
+
const manifest = discoverPlugins().find((p) => p.manifest.id === pluginId)?.manifest;
|
|
3602
|
+
return resolvePluginEnabled(pluginCfg, manifest?.defaultEnabled);
|
|
3603
|
+
});
|
|
2981
3604
|
try {
|
|
2982
3605
|
await loadServerEntries({
|
|
2983
3606
|
isEnabled: (pluginId) => {
|
|
@@ -3003,6 +3626,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3003
3626
|
{
|
|
3004
3627
|
fastify,
|
|
3005
3628
|
isPiExtensionInstalled,
|
|
3629
|
+
// pi-resources seams (design D4/D5). Default read mirrors
|
|
3630
|
+
// `GET /api/pi-resources` (SWR); `fresh` = a scan started after
|
|
3631
|
+
// the call. Raw scan, no provenance join. See change: add-skill-atlas-screen.
|
|
3632
|
+
getPiResources: async (cwd?: string, opts?: { fresh?: boolean }) => {
|
|
3633
|
+
const key = cwd ?? process.cwd();
|
|
3634
|
+
if (opts?.fresh) return directoryService.refreshPiResourcesFresh(key);
|
|
3635
|
+
const cached = directoryService.getPiResources(key);
|
|
3636
|
+
if (cached?.stale) void directoryService.refreshPiResources(key).catch(() => { /* next read retries */ });
|
|
3637
|
+
return cached?.data ?? directoryService.refreshPiResources(key);
|
|
3638
|
+
},
|
|
3639
|
+
onPiResourcesInvalidated: (handler: (cwd: string | undefined) => void) =>
|
|
3640
|
+
directoryService.onPiResourcesInvalidated(handler),
|
|
3006
3641
|
sessionManager: {
|
|
3007
3642
|
listActive: () => sessionManager.listActive(),
|
|
3008
3643
|
listAll: () => sessionManager.listAll(),
|
|
@@ -3099,6 +3734,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3099
3734
|
// the ref below. The mapper is total (never throws) and
|
|
3100
3735
|
// sanitizes untrusted plugin input. See change:
|
|
3101
3736
|
// add-plugin-spawn-scope (D7).
|
|
3737
|
+
// ACP agent spawn: validate BEFORE anything is filed or spawned (pi-only
|
|
3738
|
+
// options rejected, unknown agent rejected). See change: add-acp-session-driver (D14).
|
|
3739
|
+
const acpRejection = validatePluginAcpSpawn(opts);
|
|
3740
|
+
if (acpRejection) return { success: false, message: acpRejection };
|
|
3102
3741
|
const sessionOptions = pluginSpawnToSessionOptions(opts);
|
|
3103
3742
|
// Honour a caller-supplied spawn token VERBATIM (trusted-only
|
|
3104
3743
|
// — this code only runs past the trusted gate). A token
|
|
@@ -3154,7 +3793,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3154
3793
|
);
|
|
3155
3794
|
}
|
|
3156
3795
|
try {
|
|
3157
|
-
const result =
|
|
3796
|
+
const result =
|
|
3797
|
+
typeof opts.agent === "string"
|
|
3798
|
+
? await spawnAcpSession(opts.cwd, { agent: opts.agent, spawnToken })
|
|
3799
|
+
: await spawnPiSession(opts.cwd, { ...sessionOptions, spawnToken });
|
|
3158
3800
|
// Plugin/automation spawn: transport-less, reclaim required.
|
|
3159
3801
|
armSpawnWatchdog(opts.cwd, "headless", result);
|
|
3160
3802
|
if (result.process && result.pid) {
|
|
@@ -3184,6 +3826,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3184
3826
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
3185
3827
|
}
|
|
3186
3828
|
},
|
|
3829
|
+
// Spawn-env contributor hook. Trusted-gated like `spawnSession`
|
|
3830
|
+
// (policy, not a sandbox); untrusted plugins get a no-op.
|
|
3831
|
+
// See change: add-context-mode-settings-plugin.
|
|
3832
|
+
registerSpawnEnvContributor: (fn, opts) =>
|
|
3833
|
+
registerSpawnEnvContributorForPlugin(plugin.manifest, fn, opts),
|
|
3187
3834
|
// Session-abort hook. Gated to first-party/trusted plugins
|
|
3188
3835
|
// (priority <= 100), mirroring `spawnSession`. Untrusted plugins
|
|
3189
3836
|
// get a hook that returns false without sending anything.
|
|
@@ -3205,31 +3852,32 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3205
3852
|
return true;
|
|
3206
3853
|
},
|
|
3207
3854
|
// Terminate an automation run's spawned session. Same trust
|
|
3208
|
-
// gate as spawnSession/abortSession.
|
|
3209
|
-
//
|
|
3210
|
-
//
|
|
3211
|
-
//
|
|
3212
|
-
//
|
|
3213
|
-
|
|
3214
|
-
// See change: fix-automation-stop-zombie-runs.
|
|
3215
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
3216
|
-
abortSpawnedRun: async ({ sessionId, spawnToken, graceful }) => {
|
|
3855
|
+
// gate as spawnSession/abortSession. Both branches resolve through
|
|
3856
|
+
// the ONE shared terminator (`createAbortSpawnedRun`): `graceful`
|
|
3857
|
+
// sends a clean-exit hint first; the spawn token reclaims a run
|
|
3858
|
+
// not yet registered.
|
|
3859
|
+
// See change: fix-automation-stop-zombie-runs, fix-session-reclaim-tmux.
|
|
3860
|
+
abortSpawnedRun: async (args) => {
|
|
3217
3861
|
const trusted = (plugin.manifest.priority ?? 1000) <= 100;
|
|
3218
3862
|
if (!trusted) return false;
|
|
3219
|
-
|
|
3220
|
-
if (graceful && sessionId) {
|
|
3221
|
-
piGateway.sendToSession(sessionId, { type: "shutdown", sessionId });
|
|
3222
|
-
return reg.killBySessionId(sessionId);
|
|
3223
|
-
}
|
|
3224
|
-
if (sessionId) {
|
|
3225
|
-
const killed = await reg.killBySessionId(sessionId);
|
|
3226
|
-
if (killed) return true;
|
|
3227
|
-
if (spawnToken) return reg.killByToken(spawnToken);
|
|
3228
|
-
return false;
|
|
3229
|
-
}
|
|
3230
|
-
if (spawnToken) return reg.killByToken(spawnToken);
|
|
3231
|
-
return false;
|
|
3863
|
+
return abortSpawnedRunImpl(args);
|
|
3232
3864
|
},
|
|
3865
|
+
// Plugin session-close hook: closer + close requests for sessions
|
|
3866
|
+
// this plugin declared. Same trust gate as spawnSession.
|
|
3867
|
+
// See change: add-session-close-plugin-hook.
|
|
3868
|
+
...createPluginSessionCloseApi(
|
|
3869
|
+
{
|
|
3870
|
+
registry: sessionClosers,
|
|
3871
|
+
getSession: (id) => sessionManager.get(id),
|
|
3872
|
+
// Same confirmed shutdown-hint + shared-terminator path as a
|
|
3873
|
+
// graceful abortSpawnedRun (failures counted there).
|
|
3874
|
+
closeNow: (id) => abortSpawnedRunImpl({ sessionId: id, graceful: true }),
|
|
3875
|
+
markArchiveOnEnd,
|
|
3876
|
+
onCloseRequest: () => embedLifecycle.metrics.recordPluginCloseRequest(),
|
|
3877
|
+
},
|
|
3878
|
+
plugin.manifest.id,
|
|
3879
|
+
(plugin.manifest.priority ?? 1000) <= 100,
|
|
3880
|
+
),
|
|
3233
3881
|
// Pin a tightening cwd capability floor. Same trust gate as
|
|
3234
3882
|
// spawnSession (priority <= 100). Untrusted plugins get a no-op
|
|
3235
3883
|
// so a forged manifest cannot constrain unrelated sessions.
|
|
@@ -3241,6 +3889,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3241
3889
|
if (!trusted) return;
|
|
3242
3890
|
cwdPolicyRegistry.register(plugin.manifest.id, cwd, policy);
|
|
3243
3891
|
},
|
|
3892
|
+
// Raise the `cwd` access dialog for a user-initiated write whose cwd
|
|
3893
|
+
// the plugin's guard refused. Same trust gate as registerCwdPolicy
|
|
3894
|
+
// (priority <= 100); an untrusted plugin's hook resolves `refuse`
|
|
3895
|
+
// without raising anything. See change: harden-plugin-cwd-admission.
|
|
3896
|
+
holdCwdDenial: createCwdHold({
|
|
3897
|
+
pluginId: plugin.manifest.id,
|
|
3898
|
+
trusted: (plugin.manifest.priority ?? 1000) <= 100,
|
|
3899
|
+
known: pluginServiceRegistry.get("host.knownFolderCwds") as () => string[],
|
|
3900
|
+
logger: { warn: (m) => console.warn(m) },
|
|
3901
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
3902
|
+
}),
|
|
3244
3903
|
// Remove the caller's own cwd policy (owner-scoped, idempotent).
|
|
3245
3904
|
// No-op for untrusted plugins. See change: add-plugin-spawn-scope.
|
|
3246
3905
|
unregisterCwdPolicy: (cwd) => {
|
|
@@ -3274,10 +3933,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3274
3933
|
// Empty names never reach here (rejected above, E9) — the
|
|
3275
3934
|
// host's old `name || undefined` normalization is dead by
|
|
3276
3935
|
// design; see relocate-goal-product-to-plugin (D1-#4 note).
|
|
3277
|
-
|
|
3936
|
+
// A plugin rename is a SYSTEM rename: it overwrites the name but never
|
|
3937
|
+
// downgrades `user`. See change: investigate-auto-name-provenance-relabel.
|
|
3938
|
+
const updates = systemRenameUpdates(sessionManager.get(sessionId), name);
|
|
3278
3939
|
sessionManager.update(sessionId, updates);
|
|
3279
3940
|
browserGateway.broadcastSessionUpdated(sessionId, updates);
|
|
3280
|
-
piGateway.sendToSession(sessionId, { type: "rename_session", sessionId, name });
|
|
3941
|
+
piGateway.sendToSession(sessionId, { type: "rename_session", sessionId, name, origin: "system" });
|
|
3281
3942
|
return true;
|
|
3282
3943
|
},
|
|
3283
3944
|
// Merge a plugin-owned ref onto a session — post-spawn sibling
|
|
@@ -3350,6 +4011,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3350
4011
|
// this is NOT trust-gated. See change:
|
|
3351
4012
|
// relocate-goal-product-to-plugin (D1-#7).
|
|
3352
4013
|
networkGuard,
|
|
4014
|
+
// `ctx.serveApp`: trust-gated (bundled plugin dir OR `auth.capabilityRoutePlugins`),
|
|
4015
|
+
// mounts `/apps/<appId>/`. See change: add-plugin-capability-routes (D2, D5).
|
|
4016
|
+
serveApp: createHostServeApp({
|
|
4017
|
+
fastify,
|
|
4018
|
+
plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id },
|
|
4019
|
+
readConfiguredIds: () => loadConfig().auth?.capabilityRoutePlugins ?? [],
|
|
4020
|
+
}),
|
|
3353
4021
|
// Emit a configured pi event into a session (relayed as a
|
|
3354
4022
|
// `plugin_emit_event` control message; the in-session bridge
|
|
3355
4023
|
// re-emits it on pi.events). Same trust gate as abortSession.
|
|
@@ -3444,6 +4112,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3444
4112
|
// the calling plugin's manifest id. See change:
|
|
3445
4113
|
// expose-plugin-credential-and-oauth-seams (D2, D3, D7).
|
|
3446
4114
|
pluginCredentials: (id) => createPluginCredentialStore(id),
|
|
4115
|
+
// Declared + user-approved vault reads, bound to this plugin's manifest.
|
|
4116
|
+
// See change: add-credential-vault (D4).
|
|
4117
|
+
pluginVault: (id) => createPluginVaultReader(vaultStore, id, plugin.manifest.vaultBindings ?? []),
|
|
3447
4118
|
startPluginOAuthFlow: async (id, opts) => {
|
|
3448
4119
|
const res = await beginFlow({
|
|
3449
4120
|
provider: pluginFlowProvider(id, opts.key),
|
|
@@ -3517,6 +4188,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3517
4188
|
resolveUpgrade: resolveUpgradePrincipal,
|
|
3518
4189
|
policy: policyRegistry,
|
|
3519
4190
|
pluginDataRoot: (pid) => path.join(os.homedir(), ".pi", "dashboard", "plugins", pid),
|
|
4191
|
+
localTrust,
|
|
3520
4192
|
}),
|
|
3521
4193
|
registerBrowserLoginConfig: (loginConfig) => {
|
|
3522
4194
|
const id = plugin.manifest.id;
|
|
@@ -3538,6 +4210,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3538
4210
|
},
|
|
3539
4211
|
},
|
|
3540
4212
|
plugin.manifest.id,
|
|
4213
|
+
// Own editor-pane-tab prefixes gate `ctx.openEditorTab`. See change: add-browser-editor-pane-tab (D5).
|
|
4214
|
+
plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-tab" && c.pathPrefix ? [c.pathPrefix] : [])),
|
|
4215
|
+
// Own file-handler edit claims + package dir gate `ctx.registerFileValidator`. See change: add-editor-pane-file-handlers (D4).
|
|
4216
|
+
{
|
|
4217
|
+
packageDir: plugin.packageDir,
|
|
4218
|
+
editClaimIds: plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-file-handler" && c.mode === "edit" && c.id ? [c.id] : [])),
|
|
4219
|
+
},
|
|
3541
4220
|
)),
|
|
3542
4221
|
});
|
|
3543
4222
|
} catch (err) {
|
|
@@ -3547,8 +4226,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3547
4226
|
routeOwners.end();
|
|
3548
4227
|
}
|
|
3549
4228
|
|
|
4229
|
+
// Named so the optional TLS listener shares this exact switch (one upgrade
|
|
4230
|
+
// path, two transports). See change: add-tailscale-cert-tls (D1).
|
|
3550
4231
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
3551
|
-
|
|
4232
|
+
const onUpgrade = (request: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer): void => {
|
|
4233
|
+
// Stamp the local-credential verdict FIRST (before the Host/Origin gates):
|
|
4234
|
+
// everything below reads it via `hasLocalCredential(request.headers)`.
|
|
4235
|
+
// The proof floor is per transport: a TLS socket is stamped against the
|
|
4236
|
+
// TLS listener's own bind time, so a proof for the main port never
|
|
4237
|
+
// verifies here. See change: add-tailscale-cert-tls (D1).
|
|
4238
|
+
localCredential.stamp(request, {
|
|
4239
|
+
kind: "http",
|
|
4240
|
+
boundAt: (socket as import("node:tls").TLSSocket).encrypted ? tlsBoundAt : httpBoundAt,
|
|
4241
|
+
});
|
|
3552
4242
|
// Ephemeral single-use ticket (D11) bound to the requested WS route
|
|
3553
4243
|
// scope. The one cheap read BEFORE the first gate — the host-admission
|
|
3554
4244
|
// log line names the scope.
|
|
@@ -3574,7 +4264,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3574
4264
|
|
|
3575
4265
|
// Access check for WebSocket upgrades
|
|
3576
4266
|
const remoteAddress = request.socket.remoteAddress || "";
|
|
3577
|
-
|
|
4267
|
+
// Live admission list per upgrade (empty under `pair`) — NOT the boot
|
|
4268
|
+
// value. See change: retire-trusted-networks-bypass (D1).
|
|
4269
|
+
const trusted = admissionList();
|
|
3578
4270
|
const secWsProtocol = request.headers["sec-websocket-protocol"] as string | undefined;
|
|
3579
4271
|
|
|
3580
4272
|
// ── Plugin-owned WS routes (change: add-browser-relay D1) ──────────
|
|
@@ -3683,6 +4375,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3683
4375
|
// principal-bearing ticket — they were the legacy loopback / local-token /
|
|
3684
4376
|
// trusted-network / principal-less-ticket allowances that bypassed it.
|
|
3685
4377
|
const requireIdentityTicket = (scope === "browser" || scope === "terminal" || scope === "live") && identityEnforced();
|
|
4378
|
+
// A live-scope upgrade may be admitted by a validated capability path
|
|
4379
|
+
// (token read from the path segment only — never query/subprotocol).
|
|
4380
|
+
// Any other scope ignores it entirely. See change: retire-trusted-networks-bypass (D5).
|
|
4381
|
+
const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
|
|
4382
|
+
const liveCapPrincipal = liveCap ? liveCapabilities.validate(liveCap.targetId, liveCap.token) : null;
|
|
3686
4383
|
const upgradeAuth = authorizeWsUpgrade({
|
|
3687
4384
|
cookieHeader: request.headers.cookie,
|
|
3688
4385
|
remoteAddress,
|
|
@@ -3695,7 +4392,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3695
4392
|
localToken,
|
|
3696
4393
|
localTrust,
|
|
3697
4394
|
requireIdentityTicket,
|
|
4395
|
+
liveCapability: liveCapPrincipal
|
|
4396
|
+
? { identity: liveCapPrincipal.identity, identityExpiresAt: liveCapPrincipal.identityExpiresAt }
|
|
4397
|
+
: null,
|
|
4398
|
+
// A revoked / disabled passkey user's cookie opens no socket (D4).
|
|
4399
|
+
isSessionLive: (p) => effectiveSessionTier(p, passkeyService) !== null,
|
|
3698
4400
|
});
|
|
4401
|
+
// Cookie-session sockets carry the session's LIVE tier (passkey users
|
|
4402
|
+
// re-read the directory). Terminals need operate, live previews
|
|
4403
|
+
// control; browser messages are gated per type in the gateway.
|
|
4404
|
+
// See change: add-passkey-user-auth.
|
|
4405
|
+
const sessionPayload = upgradeAuth.ok ? upgradeAuth.session : undefined;
|
|
4406
|
+
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService) : undefined;
|
|
4407
|
+
const roadTier = scope === "terminal" ? TERMINAL_TIER : scope === "live" ? LIVE_PREVIEW_TIER : undefined;
|
|
4408
|
+
if (sessionTierOf && roadTier) {
|
|
4409
|
+
const t = sessionTierOf();
|
|
4410
|
+
if (t === null || rank(t) < rank(roadTier)) {
|
|
4411
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4412
|
+
socket.destroy();
|
|
4413
|
+
return;
|
|
4414
|
+
}
|
|
4415
|
+
}
|
|
3699
4416
|
if (!upgradeAuth.ok) {
|
|
3700
4417
|
// 401 when an auth secret is configured (cookie realm), else 403 for
|
|
3701
4418
|
// the no-auth allowances — preserving the prior status semantics.
|
|
@@ -3763,6 +4480,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3763
4480
|
bound.principalExpiresAt = upgradeAuth.principalExpiresAt;
|
|
3764
4481
|
}
|
|
3765
4482
|
if (grants) (ws as { bootstrapGrants?: BootstrapGrants }).bootstrapGrants = grants;
|
|
4483
|
+
if (sessionTierOf) (ws as TieredSocket).sessionTier = sessionTierOf;
|
|
3766
4484
|
browserGateway.wss.emit("connection", ws, request);
|
|
3767
4485
|
});
|
|
3768
4486
|
if (identityEnforced() && policyRegistry.hasPolicy()) {
|
|
@@ -3804,18 +4522,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3804
4522
|
case "live": {
|
|
3805
4523
|
// Review B2 (policy `live.read` before the upgrade) + B1 (a proxied
|
|
3806
4524
|
// dev-server socket must not outlive the ticket's principal).
|
|
3807
|
-
gateRoadUpgrade(HostActions.liveRead, { kind: "live", route: (request.url ?? "").split("?")[0] }, () => {
|
|
4525
|
+
gateRoadUpgrade(HostActions.liveRead, { kind: "live", route: redactCapability((request.url ?? "").split("?")[0]) }, () => {
|
|
3808
4526
|
// Chunked past the 32-bit timer cap (`scheduleAtExpiry`), released on close.
|
|
3809
4527
|
const cancelExpiry = scheduleAtExpiry(upgradeAuth.principalExpiresAt, () => socket.destroy());
|
|
3810
4528
|
socket.once("close", cancelExpiry);
|
|
3811
|
-
handleLiveServerUpgrade(liveServerManager, request, socket, head
|
|
4529
|
+
handleLiveServerUpgrade(liveServerManager, request, socket, head, {
|
|
4530
|
+
isDeviceBearer: (token) => pairedDeviceRegistry.verify(token) !== null,
|
|
4531
|
+
capabilityPrefix: liveCapPrincipal && liveCap ? liveCap.prefix : undefined,
|
|
4532
|
+
});
|
|
3812
4533
|
});
|
|
3813
4534
|
break;
|
|
3814
4535
|
}
|
|
3815
4536
|
default:
|
|
3816
4537
|
socket.destroy();
|
|
3817
4538
|
}
|
|
3818
|
-
}
|
|
4539
|
+
};
|
|
4540
|
+
fastify.server.on("upgrade", onUpgrade);
|
|
4541
|
+
tlsUpgrade = onUpgrade;
|
|
3819
4542
|
|
|
3820
4543
|
// Identity-plane arming (D1/D8/D9/D21). Runs AFTER plugins have loaded
|
|
3821
4544
|
// (outside the loader try, so a loader throw cannot skip it) and BEFORE
|
|
@@ -3842,9 +4565,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3842
4565
|
}
|
|
3843
4566
|
}
|
|
3844
4567
|
|
|
3845
|
-
|
|
4568
|
+
// The proof floor is taken after readiness, immediately before the bind.
|
|
4569
|
+
await listenWithProofFloor(fastify, (at) => (httpBoundAt = at), { port: config.port, host: config.host });
|
|
3846
4570
|
writePid(process.pid);
|
|
3847
4571
|
console.log(`Dashboard server running at http://${config.host}:${config.port}`);
|
|
4572
|
+
// Optional TLS listener: only after Fastify is ready and the main listen resolved.
|
|
4573
|
+
// Failure-isolated — a TLS problem never affects the main listener.
|
|
4574
|
+
// See change: add-tailscale-cert-tls (D1, D7).
|
|
4575
|
+
void tlsListener.markReady().catch((err: unknown) => {
|
|
4576
|
+
console.warn(`[tls] listener start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
4577
|
+
});
|
|
4578
|
+
|
|
4579
|
+
// Managed services: adoption + scheduler only once the server really
|
|
4580
|
+
// started (a created-but-never-started server touches nothing). Boot is
|
|
4581
|
+
// adoption only and a no-op without services.json; never blocks startup.
|
|
4582
|
+
// See change: add-service-registry-core.
|
|
4583
|
+
// The scheduler starts whether or not adoption succeeded: lease sweeps,
|
|
4584
|
+
// leased re-probes and idle-stop must run regardless.
|
|
4585
|
+
serviceManager
|
|
4586
|
+
.boot()
|
|
4587
|
+
.catch((err: unknown) => console.warn(`[services] boot adoption failed: ${(err as Error).message}`))
|
|
4588
|
+
.finally(() => serviceManager.startScheduler());
|
|
3848
4589
|
|
|
3849
4590
|
// Bind-vs-trust reachability. A loopback or specific-NIC bind silently
|
|
3850
4591
|
// voids a trusted network outside its range: the TCP connection is
|
|
@@ -3916,12 +4657,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3916
4657
|
// The verdict names skips honestly: a loopback-bound server must not
|
|
3917
4658
|
// log "advertising" when nothing was published. (CodeRabbit review,
|
|
3918
4659
|
// fix-bridge-mdns-migration-hijack.)
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
4660
|
+
// advertiseDashboard logs the verdict itself (loopback skip, no
|
|
4661
|
+
// advertisable address, or the derived instance name + addresses).
|
|
4662
|
+
advertiseDashboard(config.port, config.piPort, {
|
|
4663
|
+
bindHost: config.host,
|
|
4664
|
+
addresses: await resolveAdvertisedAddresses(config.host),
|
|
4665
|
+
fingerprint: serverIdentity.fingerprint,
|
|
4666
|
+
version: pkgVersion,
|
|
4667
|
+
name: () => loadConfig().dashboardName || "",
|
|
4668
|
+
resolveAddresses: () => resolveAdvertisedAddresses(config.host),
|
|
4669
|
+
});
|
|
3925
4670
|
}
|
|
3926
4671
|
} catch (err) {
|
|
3927
4672
|
console.warn(`mDNS advertisement failed (will continue without):`, err);
|
|
@@ -3933,15 +4678,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3933
4678
|
// skip peer discovery entirely
|
|
3934
4679
|
} else {
|
|
3935
4680
|
mdnsBrowser = createBrowser();
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
3944
|
-
|
|
4681
|
+
wirePeerServers({
|
|
4682
|
+
browser: mdnsBrowser,
|
|
4683
|
+
peers: peerServers,
|
|
4684
|
+
self: () => ({
|
|
4685
|
+
host: selfHostname,
|
|
4686
|
+
port: config.port,
|
|
4687
|
+
piPort: config.piPort,
|
|
4688
|
+
version: pkgVersion,
|
|
4689
|
+
fingerprint: serverIdentity.fingerprint,
|
|
4690
|
+
name: loadConfig().dashboardName || selfHostname.replace(/\.local$/i, ""),
|
|
4691
|
+
}),
|
|
4692
|
+
broadcast: (servers) => browserGateway.broadcast({ type: "servers_updated", servers }),
|
|
4693
|
+
moves: knownServerMoves,
|
|
3945
4694
|
});
|
|
3946
4695
|
}
|
|
3947
4696
|
} catch (err) {
|
|
@@ -4029,9 +4778,20 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4029
4778
|
// or they would land in every pi session's tool list.
|
|
4030
4779
|
// See change: expose-plugin-credential-and-oauth-seams (D8).
|
|
4031
4780
|
.filter(p => fixtureEntryAllowed(p.manifest))
|
|
4032
|
-
|
|
4781
|
+
// A disabled plugin's bridge is deregistered (both registries) and an
|
|
4782
|
+
// enabled one registered — same predicate as the server-entry loader.
|
|
4783
|
+
// The toggle route answers `restartRequired`, so this boot pass is
|
|
4784
|
+
// where a toggle lands. See change: add-plugin-bridge-contributions (D13).
|
|
4785
|
+
.map(p => ({
|
|
4786
|
+
pluginId: p.manifest.id,
|
|
4787
|
+
bridgePath: p.bridgeEntryPath!,
|
|
4788
|
+
enabled: resolvePluginEnabled(
|
|
4789
|
+
getPluginConfigFromFile(loadConfig(), p.manifest.id) as Record<string, unknown>,
|
|
4790
|
+
p.manifest.defaultEnabled,
|
|
4791
|
+
),
|
|
4792
|
+
}));
|
|
4033
4793
|
if (pluginsWithBridges.length) {
|
|
4034
|
-
const results =
|
|
4794
|
+
const results = syncPluginBridges(pluginsWithBridges);
|
|
4035
4795
|
for (const [id, result] of Object.entries(results)) {
|
|
4036
4796
|
if (result.type === 'conflict') {
|
|
4037
4797
|
const store = getPluginStatusStore();
|
|
@@ -4064,6 +4824,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4064
4824
|
console.warn("[plugin-bridge] Reconciliation failed (non-fatal):", err);
|
|
4065
4825
|
}
|
|
4066
4826
|
|
|
4827
|
+
// Log-only health scan of settings.json packages[] (never mutates, never
|
|
4828
|
+
// throws). Not awaited: cold listConfiguredPackages can take seconds on
|
|
4829
|
+
// Windows and boot must not wait on a diagnostic. See change: add-package-health-cleanup.
|
|
4830
|
+
logPackageHealthAtBoot({ listInstalled: () => packageManagerWrapper.listInstalled("global") }).catch((err) =>
|
|
4831
|
+
console.warn("[package-health] boot scan failed (non-fatal):", err),
|
|
4832
|
+
);
|
|
4833
|
+
|
|
4067
4834
|
idleTimer.start();
|
|
4068
4835
|
// Arm the ephemeral boot-parent watch (D5) — a no-op unless --ephemeral
|
|
4069
4836
|
// was passed. Its interval IS the stated exit-latency bound.
|
|
@@ -4204,6 +4971,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4204
4971
|
// wiring above; unref'd, so this is leak-hygiene not liveness).
|
|
4205
4972
|
clearInterval(hostGateFlushTimer);
|
|
4206
4973
|
directoryService.stopPolling();
|
|
4974
|
+
// ACP host A: end in-process sessions through the gateway (unregister →
|
|
4975
|
+
// ended + persisted with `driver:"acp"`), killing their agents, BEFORE the
|
|
4976
|
+
// headless sweep. See change: add-acp-session-driver (D1).
|
|
4977
|
+
await stopAllLocalAcpSessions();
|
|
4978
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
4207
4979
|
// SIGTERMs every dashboard-spawned pi: after this the sessions below are
|
|
4208
4980
|
// GONE and can never reattach.
|
|
4209
4981
|
browserGateway.shutdownHeadlessProcesses();
|
|
@@ -4237,6 +5009,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4237
5009
|
}
|
|
4238
5010
|
pendingForkRegistry.dispose();
|
|
4239
5011
|
pairingManager.dispose();
|
|
5012
|
+
vaultDelivery.dispose();
|
|
4240
5013
|
// Every pending ack holds a timer; a create/stop cycle must not leak them.
|
|
4241
5014
|
// See change: fix-spawn-correlation-ttl-coupling (D7).
|
|
4242
5015
|
pendingPromptAcks.dispose();
|
|
@@ -4260,6 +5033,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4260
5033
|
}
|
|
4261
5034
|
homeRendezvous = null;
|
|
4262
5035
|
piGateway.stop();
|
|
5036
|
+
// Clears pending on-end archive timers + latches the sweeper; after the
|
|
5037
|
+
// gateway so sessions it ends cannot re-arm one.
|
|
5038
|
+
// See change: archive-service-sessions-on-end.
|
|
5039
|
+
archiveSweeper.stop();
|
|
5040
|
+
serviceManager.dispose();
|
|
4263
5041
|
for (const client of browserGateway.wss.clients) {
|
|
4264
5042
|
client.terminate();
|
|
4265
5043
|
}
|
|
@@ -4277,6 +5055,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4277
5055
|
try { await secondFastify.close(); } catch { /* ignore */ }
|
|
4278
5056
|
secondFastify = null;
|
|
4279
5057
|
}
|
|
5058
|
+
// The TLS listener (and its open connections) closes with the server.
|
|
5059
|
+
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
4280
5060
|
await fastify.close();
|
|
4281
5061
|
},
|
|
4282
5062
|
};
|