@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.md +85 -11
- package/docs/architecture.md +3020 -116
- package/package.json +31 -18
- package/packages/extension/package.json +10 -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 +504 -0
- package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
- package/packages/extension/src/bridge-handlers/instance.ts +229 -0
- package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -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-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +517 -2534
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +259 -16
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +294 -24
- package/packages/extension/src/dashboard-context-injector.ts +26 -47
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- 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/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +232 -17
- package/packages/extension/src/message-update-coalescer.ts +3 -1
- package/packages/extension/src/model-refresh.ts +88 -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/pinned-endpoint.ts +44 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +258 -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 +146 -38
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-manager.ts +5 -4
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +13 -6
- package/packages/extension/src/server-launcher.ts +11 -13
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-move.ts +19 -0
- package/packages/extension/src/session-sync.ts +73 -50
- 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 +404 -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 +79 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- 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 +82 -17
- 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-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
- package/packages/server/src/access/planes.ts +116 -2
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/refusal-ledger.ts +6 -6
- package/packages/server/src/access/yolo-session.ts +127 -14
- 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 +549 -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/agent-events/agent-event-hub.ts +158 -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/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +329 -97
- package/packages/server/src/auth/auth.ts +102 -11
- package/packages/server/src/auth/bearer-auth.ts +74 -12
- package/packages/server/src/auth/cors-origin.ts +86 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +111 -9
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -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-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +76 -22
- package/packages/server/src/auth/local-token.ts +16 -0
- package/packages/server/src/auth/localhost-guard.ts +298 -17
- package/packages/server/src/auth/nav-intent.ts +72 -0
- 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-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
- package/packages/server/src/auth/passkey/passkey-routes.ts +232 -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 +324 -0
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-registry.ts +35 -1
- package/packages/server/src/auth/provider-auth-storage.ts +61 -9
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/radius-override.ts +13 -0
- package/packages/server/src/auth/request-principal.ts +32 -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/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +197 -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/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- 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 +151 -6
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +138 -63
- 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/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +1063 -106
- package/packages/server/src/config-api.ts +166 -2
- package/packages/server/src/config-snapshot.ts +53 -1
- package/packages/server/src/directory-service.ts +545 -36
- 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 +349 -141
- package/packages/server/src/file-watch-manager.ts +187 -39
- package/packages/server/src/git-worktree/git-operations.ts +60 -15
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +91 -6
- 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 +31 -1
- 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 +10 -0
- package/packages/server/src/identity/ws-road-classification.ts +10 -0
- package/packages/server/src/known-server-moves.ts +196 -0
- package/packages/server/src/lib/browse-roots.ts +137 -0
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/digest-gate.ts +82 -0
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -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/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/purify.ts +13 -5
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-handler-target.ts +66 -0
- package/packages/server/src/lib/writable-md-target.ts +16 -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 +129 -6
- package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +461 -0
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +326 -34
- package/packages/server/src/live-server/live-static.ts +228 -0
- 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/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
- package/packages/server/src/openspec/openspec-poll-worker.ts +286 -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-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +1002 -0
- package/packages/server/src/package/installed-package-enricher.ts +38 -3
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- 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 +13 -5
- package/packages/server/src/pairing/browser-gateway.ts +292 -16
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/knock-admission.ts +277 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +188 -31
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- 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 +125 -7
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
- package/packages/server/src/pi/folder-commands.ts +141 -0
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- 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 +166 -33
- package/packages/server/src/pi/pi-gateway.ts +283 -29
- 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/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -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 +274 -6
- 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/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +620 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
- package/packages/server/src/routes/folder-project-routes.ts +105 -0
- package/packages/server/src/routes/git-routes.ts +334 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +433 -55
- package/packages/server/src/routes/live-server-routes.ts +438 -7
- package/packages/server/src/routes/local-proof-routes.ts +26 -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/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +636 -55
- package/packages/server/src/routes/package-health-routes.ts +140 -0
- package/packages/server/src/routes/package-routes.ts +86 -11
- package/packages/server/src/routes/pairing-routes.ts +303 -33
- 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/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +37 -7
- package/packages/server/src/routes/provider-routes.ts +29 -0
- package/packages/server/src/routes/resource-activation-routes.ts +33 -35
- package/packages/server/src/routes/session-routes.ts +100 -9
- package/packages/server/src/routes/system-routes.ts +286 -33
- package/packages/server/src/routes/tls-routes.ts +55 -0
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/routes/user-routes.ts +192 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- 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 +1537 -246
- 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/hydration-state.ts +148 -0
- package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
- package/packages/server/src/session/memory-session-manager.ts +60 -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/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- 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-load-worker.ts +11 -2
- 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/headless-pid-registry.ts +14 -9
- 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 +75 -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-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +94 -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/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-bindings.ts +101 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +424 -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/server/src/watch-files-handler.ts +66 -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 +533 -73
- package/packages/shared/src/canonical-subject.ts +27 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/card-sections.ts +185 -1
- package/packages/shared/src/chrome-profiles.ts +188 -0
- package/packages/shared/src/config.ts +817 -51
- package/packages/shared/src/containment-guard.ts +35 -0
- 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/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +9 -3
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- 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 +139 -2
- package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
- package/packages/shared/src/dashboard-starter.ts +30 -0
- package/packages/shared/src/display-name.ts +42 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +119 -134
- 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/live-server.ts +141 -0
- package/packages/shared/src/local-credential-proof.ts +219 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -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/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/md-table-cell.ts +11 -0
- package/packages/shared/src/mdns-discovery.ts +414 -45
- package/packages/shared/src/models-json-reader.ts +6 -0
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-design-evidence.ts +25 -1
- package/packages/shared/src/openspec-poller.ts +213 -11
- 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 +301 -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-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
- package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
- package/packages/shared/src/pi-trust-mirror.ts +354 -0
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/binary-lookup.ts +2 -194
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +210 -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 +99 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/runner.ts +46 -2
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- 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/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-name.ts +42 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/prompt-answer.ts +183 -0
- package/packages/shared/src/protocol.ts +172 -8
- package/packages/shared/src/question-types.ts +73 -0
- package/packages/shared/src/recommended-extensions.ts +98 -23
- package/packages/shared/src/recovery-timing.ts +39 -0
- package/packages/shared/src/redaction.ts +50 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +533 -3
- 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 +181 -0
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- 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/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-identity.ts +51 -15
- package/packages/shared/src/server-launcher.ts +21 -34
- package/packages/shared/src/server-pinning.ts +136 -2
- package/packages/shared/src/server-routes.ts +462 -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/session-ui-path.ts +11 -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-only-token.ts +16 -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 +31 -9
- 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/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/tunnel-provider.ts +3 -2
- package/packages/shared/src/types.ts +170 -9
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +88 -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 +136 -0
- package/tsconfig.base.json +1 -0
|
@@ -0,0 +1,1069 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi lifecycle handlers (`session_start`, `turn_end`, `session_shutdown`, `session_info_changed`, `project_trust`).
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `bridge.ts` (change: test-trust-audit, design D2). Receives the per-incarnation
|
|
5
|
+
* `BridgeInstance`; holds no module-level mutable state and never imports the bridge entry point.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { loadConfig, resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
9
|
+
import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
|
|
10
|
+
import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
11
|
+
import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
|
|
12
|
+
import { Loader } from "@earendil-works/pi-tui";
|
|
13
|
+
import { cleanupAttachmentsForSession, } from "../ask-user-attachments.js";
|
|
14
|
+
import { registerAskUserTool } from "../ask-user-tool.js";
|
|
15
|
+
import { extractFirstMessage, filterHiddenCommands, getCurrentModelString, isHeadlessRpcSession, safeCwd } from "../bridge-context.js";
|
|
16
|
+
import { hasExplicitModelArg, shouldApplyDefaultModel } from "../bridge-default-model-gate.js";
|
|
17
|
+
import { drainDisposables } from "../bridge-polling.js";
|
|
18
|
+
import { registerCanvasTool } from "../canvas-tool.js";
|
|
19
|
+
import { DashboardDefaultAdapter } from "../dashboard-default-adapter.js";
|
|
20
|
+
import { decideRetarget } from "../endpoint-resolution.js";
|
|
21
|
+
import { mapEventToProtocol } from "../event-forwarder.js";
|
|
22
|
+
import { bridgeExtensionIdentity } from "../extension-identity.js";
|
|
23
|
+
import { registerFlowEventListeners } from "../flow-event-wiring.js";
|
|
24
|
+
import { createGitPollState, runGitPollTick } from "../git-poll.js";
|
|
25
|
+
import { flipHasUI } from "../hasui-flip.js";
|
|
26
|
+
import { healthUrlForInstance, verifyInstanceIdentity } from "../instance-verification.js";
|
|
27
|
+
import { sendPiVersionIfChanged as _sendPiVersionIfChanged } from "../model-tracker.js";
|
|
28
|
+
import { provisionOpenspecCli } from "../openspec-cli-shim.js";
|
|
29
|
+
import { pollCost } from "../poll-cost.js";
|
|
30
|
+
import { collectMetrics, startMetricsMonitor, stopMetricsMonitor } from "../process-metrics.js";
|
|
31
|
+
import { createProcessScanScheduler } from "../process-scan-scheduler.js";
|
|
32
|
+
import { scanChildProcessesAsync } from "../process-scanner.js";
|
|
33
|
+
import { decideBridgeProjectTrust, type ProjectTrustDeps, readEventCwd } from "../project-trust.js";
|
|
34
|
+
import { createHttpLiveQuery, isRemoteBridge } from "../project-trust-live.js";
|
|
35
|
+
import { PromptBus } from "../prompt-bus.js";
|
|
36
|
+
import { buildProviderCatalogue, reloadProviders, toModelInfo } from "../provider-register.js";
|
|
37
|
+
import { gateRemoteRegistration, isRemoteEndpoint } from "../remote-registration-gate.js";
|
|
38
|
+
import { registerRoleModelTools } from "../role-model-tools.js";
|
|
39
|
+
import { autoStartServer } from "../server-auto-start.js";
|
|
40
|
+
import { launchServer } from "../server-launcher.js";
|
|
41
|
+
import { loadServerPins, notePinEndpoint, serverPinsPath } from "../server-pin-store.js";
|
|
42
|
+
import { verifyDiscoveredCandidate } from "../server-proof-probe.js";
|
|
43
|
+
import { handleSessionChange as _handleSessionChange, branchFingerprint, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
|
|
44
|
+
import { detectSessionSource } from "../source-detector.js";
|
|
45
|
+
import { consumePendingReloadOnSessionStart, releaseBridgeOwnerOnShutdown, reloadCompletedFeedback } from "../terminal-reload.js";
|
|
46
|
+
import { refreshUiModules, subscribeUiInvalidate } from "../ui-modules.js";
|
|
47
|
+
import { runUiSafely } from "../ui-stale-guard.js";
|
|
48
|
+
import { sendShutdownUsageThenUnregister, type UsageDrain } from "../usage-drain.js";
|
|
49
|
+
import { detectIsGitRepo } from "../vcs-info.js";
|
|
50
|
+
import { buildVisibilityRegisterFields } from "../visibility-intent.js";
|
|
51
|
+
import type { BridgeInstance } from "./instance.js";
|
|
52
|
+
import { patchUiForPromptBus } from "./ui-prompt-patch.js";
|
|
53
|
+
|
|
54
|
+
const HEARTBEAT_INTERVAL = 15_000;
|
|
55
|
+
const GIT_POLL_INTERVAL = 30_000;
|
|
56
|
+
// Platform-aware process scan cadence. Windows keeps the original 10 s /
|
|
57
|
+
// 30 s floor because PowerShell Get-CimInstance is expensive and can flash consoles;
|
|
58
|
+
// Unix uses 5 s / 5 s so legitimate bash subprocesses surface while still
|
|
59
|
+
// running. See change: tighten-process-list-ux.
|
|
60
|
+
const PROCESS_MIN_ELAPSED_MS = process.platform === "win32" ? 30_000 : 5_000; // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
|
|
61
|
+
|
|
62
|
+
/** Env var a plugin spawn uses to override `askUserPromptTimeoutSeconds` for one session. */
|
|
63
|
+
const ASK_USER_TIMEOUT_ENV = "PI_EXT_PI_DASHBOARD_ASK_USER_PROMPT_TIMEOUT_SECONDS";
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Effective PromptBus `timeoutMs`: a valid integer override from the environment
|
|
67
|
+
* wins over `configSeconds`; a value `<= 0` means infinite (returned as `-1`).
|
|
68
|
+
* A non-integer override is ignored with a warning; empty counts as absent.
|
|
69
|
+
* See change: add-pending-question-stack (D11).
|
|
70
|
+
*/
|
|
71
|
+
export function resolveAskUserTimeoutMs(
|
|
72
|
+
configSeconds: number,
|
|
73
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
74
|
+
warn: (msg: string) => void = (m) => console.warn(m),
|
|
75
|
+
): number {
|
|
76
|
+
let seconds = configSeconds;
|
|
77
|
+
const raw = env[ASK_USER_TIMEOUT_ENV]?.trim();
|
|
78
|
+
if (raw) {
|
|
79
|
+
if (/^-?\d+$/.test(raw)) seconds = Number.parseInt(raw, 10);
|
|
80
|
+
else warn(`[bridge] ignoring ${ASK_USER_TIMEOUT_ENV}=${JSON.stringify(raw)}: not an integer; using config`);
|
|
81
|
+
}
|
|
82
|
+
return seconds > 0 ? seconds * 1000 : -1;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Shared handler for session changes (new/fork/resume)
|
|
86
|
+
function handleSessionChange(inst: BridgeInstance, ctx: any, usageSeed?: ReturnType<UsageDrain["baseline"]>) {
|
|
87
|
+
// Clear attachedChange on a real session switch (new/fork/resume): it is
|
|
88
|
+
// persisted globally + restored at activate, so without this the previous
|
|
89
|
+
// session's attached change would leak into the new session's prompt until
|
|
90
|
+
// the server replays. The server re-pushes the correct value for the new
|
|
91
|
+
// sessionId on its session_register. See change: inject-session-context-into-agent.
|
|
92
|
+
inst.attachedChange = null;
|
|
93
|
+
inst.shared.attachedChange = null;
|
|
94
|
+
// Drop retained subagent frames/snapshots on a real session switch — the
|
|
95
|
+
// new/fork/resumed session's subagents are unrelated to the outgoing one.
|
|
96
|
+
// See change: fix-subagent-live-detail-reliability.
|
|
97
|
+
inst.subagentFrameBuffer.reset();
|
|
98
|
+
// Same disposal point for the tick throttle: clear every armed trailing
|
|
99
|
+
// timer and drop every held frame, so nothing from the outgoing session
|
|
100
|
+
// can fire against the new one.
|
|
101
|
+
// See change: reduce-bridge-tick-bandwidth (D3).
|
|
102
|
+
inst.subagentTickThrottle.reset();
|
|
103
|
+
// A session boundary invalidates the CONTENT itself (unlike a reconnect), so
|
|
104
|
+
// drop any parked text snapshot and cancel its window rather than flushing
|
|
105
|
+
// it into the new session. See change:
|
|
106
|
+
// coalesce-bridge-message-update-snapshots (D8).
|
|
107
|
+
inst.coalescer.clear();
|
|
108
|
+
// Clear the stop-after-turn latch so a new/fork/resumed session does not
|
|
109
|
+
// inherit the previous session's pending graceful-stop and shut down on
|
|
110
|
+
// its first turn_end. See change: adopt-pi-071-072-073-features.
|
|
111
|
+
inst.shared.shouldStopAfterTurn = false;
|
|
112
|
+
// Drop the auto-namer and its carried state: it is a PER-SESSION state
|
|
113
|
+
// machine, so a new/fork/resumed session must not inherit the outgoing
|
|
114
|
+
// session's permanent stop, spent attempt budget or auto-named flag — it
|
|
115
|
+
// would report `stopped` / `already-named` without ever attempting to name.
|
|
116
|
+
// The server re-pushes the incoming session's own persisted state on its
|
|
117
|
+
// session_register. See change: fix-auto-naming-reasoning-model.
|
|
118
|
+
inst.autoNamer = undefined;
|
|
119
|
+
inst.namerState = undefined;
|
|
120
|
+
inst.shared.namerState = undefined;
|
|
121
|
+
// Bridge shadow queues reset on session change so the new session
|
|
122
|
+
// starts with empty chips. See change: add-followup-edit-and-steer-cancel.
|
|
123
|
+
if (inst.bridgeSteering.length > 0 || inst.bridgeFollowUp.length > 0) {
|
|
124
|
+
inst.bridgeSteering = [];
|
|
125
|
+
// Drops every entry AND its image bytes, releasing the byte budget.
|
|
126
|
+
inst.bridgeFollowUp.reset();
|
|
127
|
+
inst.emitQueueUpdate();
|
|
128
|
+
}
|
|
129
|
+
inst.renewGitTracker();
|
|
130
|
+
const bc = inst.syncBc();
|
|
131
|
+
_handleSessionChange(bc, ctx, inst.getFlowsList, usageSeed);
|
|
132
|
+
inst.applyBc(bc);
|
|
133
|
+
// A new session id needs its own `pi_version_update` (below-floor flag).
|
|
134
|
+
// After applyBc, so syncBc() carries the NEW session id.
|
|
135
|
+
// See change: update-pi-core-1-0-adopt-apis.
|
|
136
|
+
inst.sendPiVersionIfChanged();
|
|
137
|
+
|
|
138
|
+
// Restart polling timers
|
|
139
|
+
startGitPollTimer(inst, ctx);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Single source of truth for the git + name/model poll loop. Both session
|
|
143
|
+
// start and session change call this so the two timers can never drift.
|
|
144
|
+
// Caches ctx.cwd (the throwing getter) and clears any prior timer first.
|
|
145
|
+
function startGitPollTimer(inst: BridgeInstance, ctx: any) {
|
|
146
|
+
if (inst.gitPollTimer) clearInterval(inst.gitPollTimer);
|
|
147
|
+
// safeCwd: startGitPollTimer runs inside handleSessionChange BEFORE
|
|
148
|
+
// connection.connect(); an un-guarded ctx.cwd throw here skips connect()
|
|
149
|
+
// (#393). See change: fix-bridge-resume-disconnect.
|
|
150
|
+
inst.cachedCwd = safeCwd(ctx);
|
|
151
|
+
const pollState = createGitPollState();
|
|
152
|
+
inst.gitPollTimer = setInterval(() => {
|
|
153
|
+
// runGitPollTick handles a rejecting git tick itself; this catch is the
|
|
154
|
+
// last line so the interval callback can never raise an unhandled rejection.
|
|
155
|
+
runGitPollTick({
|
|
156
|
+
isActive: inst.isActive,
|
|
157
|
+
cachedCwd: () => inst.cachedCwd,
|
|
158
|
+
tickGit: (cwd) => {
|
|
159
|
+
const gbc = inst.syncBc();
|
|
160
|
+
inst.polling.gitTracker?.tick(gbc, cwd);
|
|
161
|
+
inst.applyBc(gbc);
|
|
162
|
+
},
|
|
163
|
+
sendCwdMissingIfChanged: inst.sendCwdMissingIfChanged,
|
|
164
|
+
sendSessionNameIfChanged: inst.sendSessionNameIfChanged,
|
|
165
|
+
sendModelUpdateIfChanged: inst.sendModelUpdateIfChanged,
|
|
166
|
+
sendPiVersionIfChanged: () => _sendPiVersionIfChanged(inst.syncBc()),
|
|
167
|
+
state: pollState,
|
|
168
|
+
}).catch((err) => console.error("[dashboard] git poll tick failed:", err));
|
|
169
|
+
}, GIT_POLL_INTERVAL);
|
|
170
|
+
inst.shared.timers!.push(inst.gitPollTimer);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `session_info_changed`: relay a pi-side session rename to the dashboard. */
|
|
174
|
+
export function registerSessionInfoChanged(inst: BridgeInstance): void {
|
|
175
|
+
const pi = inst.pi;
|
|
176
|
+
try {
|
|
177
|
+
pi.on("session_info_changed" as any, inst.safe(async (event: any) => {
|
|
178
|
+
if (!inst.isActive() || !inst.sessionReady) return;
|
|
179
|
+
const name = typeof event?.name === "string" ? event.name : pi.getSessionName();
|
|
180
|
+
if (typeof name === "string" && name.length > 0) {
|
|
181
|
+
inst.getAutoNamer().onObservedName(name);
|
|
182
|
+
}
|
|
183
|
+
}));
|
|
184
|
+
} catch { /* older pi: no session_info_changed — poll fallback covers it */ }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* `project_trust`: trust-gate decision for the dashboard-spawned project.
|
|
189
|
+
*
|
|
190
|
+
* pi awaits this handler, so it may be asynchronous: on a snapshot miss the
|
|
191
|
+
* decision runs a live trust query bounded by `piTrustMirror.liveQueryTimeoutMs`
|
|
192
|
+
* (default 300 ms local / 1000 ms remote). The body has its own try/catch and
|
|
193
|
+
* every path resolves to `{ trusted: "undecided" }` or a per-run yes — it never
|
|
194
|
+
* relies on `safe()` or pi's runner to contain a failure. A bridge replaced while
|
|
195
|
+
* the query was pending (reload) answers undecided. See change: mirror-dashboard-trust-live-remote.
|
|
196
|
+
*/
|
|
197
|
+
export function registerProjectTrust(inst: BridgeInstance, overrides: Partial<ProjectTrustDeps> = {}): void {
|
|
198
|
+
const pi = inst.pi;
|
|
199
|
+
try {
|
|
200
|
+
pi.on("project_trust" as any, inst.safe(async (event: any, ctx: any) => {
|
|
201
|
+
// Return the pi trust decision. A newer bridge taking over, or any
|
|
202
|
+
// non-match, defers. `remember:false` = trust for THIS run only.
|
|
203
|
+
try {
|
|
204
|
+
if (!inst.isActive()) return { trusted: "undecided" };
|
|
205
|
+
const decision = await decideBridgeProjectTrust(
|
|
206
|
+
{
|
|
207
|
+
dashboardSpawned: inst.dashboardSpawned,
|
|
208
|
+
isHeadless: isHeadlessRpcSession(),
|
|
209
|
+
eventCwd: readEventCwd(event, ctx),
|
|
210
|
+
activationCwd: inst.activationCwd,
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
isRemoteBridge: () => isRemoteBridge(inst.dashboardUrl),
|
|
214
|
+
liveQuery: createHttpLiveQuery({
|
|
215
|
+
endpoint: () => inst.dashboardUrl,
|
|
216
|
+
httpPort: () => inst.rendezvous?.httpPort,
|
|
217
|
+
env: process.env,
|
|
218
|
+
}),
|
|
219
|
+
...overrides,
|
|
220
|
+
},
|
|
221
|
+
);
|
|
222
|
+
// The instance may have been replaced while the live query was pending.
|
|
223
|
+
if (!inst.isActive()) return { trusted: "undecided" };
|
|
224
|
+
return decision.trusted === "yes"
|
|
225
|
+
? { trusted: "yes", remember: false }
|
|
226
|
+
: { trusted: "undecided" };
|
|
227
|
+
} catch {
|
|
228
|
+
return { trusted: "undecided" };
|
|
229
|
+
}
|
|
230
|
+
}));
|
|
231
|
+
} catch { /* older pi: no project_trust event — no-op */ }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const VAULT_START_REASONS = new Set(["startup", "reload", "new", "resume", "fork"]);
|
|
235
|
+
|
|
236
|
+
/** `session_start`: register the session, build the PromptBus, patch `ctx.ui`, arm timers. */
|
|
237
|
+
export function registerSessionStart(inst: BridgeInstance): void {
|
|
238
|
+
const pi = inst.pi;
|
|
239
|
+
pi.on("session_start", inst.safe(async (_event: any, ctx: any) => {
|
|
240
|
+
|
|
241
|
+
// Bail out if a newer bridge instance has taken over
|
|
242
|
+
if (!inst.isActive()) return;
|
|
243
|
+
const newSessionId = ctx.sessionManager.getSessionId();
|
|
244
|
+
inst.pathGate.onSessionStart();
|
|
245
|
+
// Credential vault: resolve the project from THIS session's own cwd (never the
|
|
246
|
+
// launch directory) on every start reason; an unreadable cwd withdraws all.
|
|
247
|
+
// See change: add-credential-vault (D2, D3).
|
|
248
|
+
void inst.vaultDelivery
|
|
249
|
+
.onSessionStart({
|
|
250
|
+
reason: VAULT_START_REASONS.has(_event?.reason) ? _event.reason : "startup",
|
|
251
|
+
getCwd: () => ctx.sessionManager.getCwd(),
|
|
252
|
+
})
|
|
253
|
+
.catch(() => {});
|
|
254
|
+
// Re-arm MCP registration for the (replacement) session; its mint below
|
|
255
|
+
// registers pi-dashboard again. See change: migrate-mcp-to-pi-builtin (D1).
|
|
256
|
+
inst.mcpRegistrar.onSessionStart();
|
|
257
|
+
|
|
258
|
+
// On session switch/fork (0.65.0+: event.reason replaces session_switch/session_fork events),
|
|
259
|
+
// unregister the old session before re-registering the new one.
|
|
260
|
+
const reason = _event?.reason;
|
|
261
|
+
// Synchronous compare-and-set BEFORE any await: this instance was loaded
|
|
262
|
+
// by a dashboard-requested reload → it owns the `/reload` `completed`,
|
|
263
|
+
// emitted after `replay_complete` below.
|
|
264
|
+
// See change: fix-terminal-session-dashboard-reload (D4).
|
|
265
|
+
const reloadDelivered = consumePendingReloadOnSessionStart(reason, newSessionId);
|
|
266
|
+
// Baseline + seed from ONE snapshot, before any register goes out: the
|
|
267
|
+
// drain forwards only entries appended after this point, and the register
|
|
268
|
+
// carries this snapshot's full totals. Undefined on a failed read.
|
|
269
|
+
// See change: count-non-message-usage.
|
|
270
|
+
let usageSeed: ReturnType<UsageDrain["baseline"]> | undefined;
|
|
271
|
+
try {
|
|
272
|
+
usageSeed = inst.usageDrain.baseline(ctx.sessionManager);
|
|
273
|
+
} catch (err) {
|
|
274
|
+
console.error("[dashboard] usage baseline failed:", err);
|
|
275
|
+
}
|
|
276
|
+
const sessionChanged =
|
|
277
|
+
(reason === "new" || reason === "fork" || reason === "resume") && !!inst.sessionId && inst.sessionId !== newSessionId;
|
|
278
|
+
if (sessionChanged) {
|
|
279
|
+
// Clear any latched abort for the OUTGOING session id. Otherwise a
|
|
280
|
+
// latched old session that is resumed later would have its first
|
|
281
|
+
// legitimate turn aborted by the agent_start/message_start latch hooks.
|
|
282
|
+
// See change: unify-error-retry-lifecycle.
|
|
283
|
+
inst.abortLatch.clear(inst.sessionId);
|
|
284
|
+
handleSessionChange(inst, ctx, usageSeed);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
inst.cachedHasUI = ctx.hasUI;
|
|
288
|
+
inst.cachedCtx = ctx;
|
|
289
|
+
inst.sessionId = newSessionId;
|
|
290
|
+
|
|
291
|
+
// Provision the openspec CLI: drop a shim on process.env.PATH so the
|
|
292
|
+
// generated openspec-* skills' bare `openspec` resolves in-session. Runs on
|
|
293
|
+
// init AND /reload (re-points the shim on extension upgrade); the PATH
|
|
294
|
+
// prepend is idempotent. Fail-soft: on hard failure, surface a
|
|
295
|
+
// dashboard-visible missing-tool signal. See change:
|
|
296
|
+
// provision-openspec-cli-in-sessions.
|
|
297
|
+
provisionOpenspecCli({
|
|
298
|
+
onMissingTool: (reason) => {
|
|
299
|
+
inst.connection.send({
|
|
300
|
+
type: "event_forward",
|
|
301
|
+
sessionId: inst.sessionId,
|
|
302
|
+
event: {
|
|
303
|
+
eventType: "bash_output",
|
|
304
|
+
timestamp: Date.now(),
|
|
305
|
+
data: {
|
|
306
|
+
command: "openspec (session provisioning)",
|
|
307
|
+
output: reason,
|
|
308
|
+
exitCode: 127,
|
|
309
|
+
excludeFromContext: true,
|
|
310
|
+
missingTool: { kind: "missing-tool", toolName: "openspec" },
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// Wrap sessionManager.appendMessage so that future message_end events can
|
|
318
|
+
// recover the just-generated entry id, even when their setTimeout(0)
|
|
319
|
+
// fires before pi has finished mutating event.message in place. The
|
|
320
|
+
// helper is idempotent and re-wraps on session replacement.
|
|
321
|
+
// See change: fix-per-message-fork.
|
|
322
|
+
inst.appendMessageWrapped = false;
|
|
323
|
+
inst.lastWrappedSm = null;
|
|
324
|
+
inst.wrapAppendMessageForCtx(ctx);
|
|
325
|
+
// Wrap the custom-persistence chokepoint BEFORE any events flow, so an
|
|
326
|
+
// extension appending at session_start is still forwarded. See change:
|
|
327
|
+
// render-inline-reasoning-and-custom-entries (D2).
|
|
328
|
+
inst.customPersistenceWrapped = false;
|
|
329
|
+
inst.customWrappedSm = null;
|
|
330
|
+
inst.wrapCustomPersistenceForCtx(ctx);
|
|
331
|
+
|
|
332
|
+
// Register ask_user at runtime (not at load time) to avoid static
|
|
333
|
+
// tool-name conflicts with other extensions like pi-flows.
|
|
334
|
+
registerAskUserTool(pi);
|
|
335
|
+
|
|
336
|
+
// Register the canvas declare-tool (change: auto-canvas). Fire-and-forget
|
|
337
|
+
// UI intent; the server observes the forwarded tool call and drives the
|
|
338
|
+
// canvas. Runtime registration for the same conflict-avoidance reason.
|
|
339
|
+
registerCanvasTool(pi);
|
|
340
|
+
|
|
341
|
+
// Register the agent-facing role/model tools (list_models, list_roles,
|
|
342
|
+
// update_roles). list_models reads the in-process session registry via a
|
|
343
|
+
// live getter so its refs match the human Model Selector exactly.
|
|
344
|
+
// See change: add-agent-role-model-tools.
|
|
345
|
+
registerRoleModelTools(pi, {
|
|
346
|
+
getRegistry: () => inst.cachedModelRegistry,
|
|
347
|
+
// Live scope read at call time from the latest captured ctx (dynamic via
|
|
348
|
+
// Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
|
|
349
|
+
// See change: update-pi-core-0-83-adopt-apis.
|
|
350
|
+
getScopedModels: () => (inst.cachedCtx as any)?.scopedModels,
|
|
351
|
+
// Resync from global config before each read.
|
|
352
|
+
// See change: list-models-auto-resync (design D2).
|
|
353
|
+
reloadProviders: () => reloadProviders(pi),
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
// Extract session file/dir early — needed for source detection and UI proxy
|
|
357
|
+
const sessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
|
|
358
|
+
const sessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
|
|
359
|
+
inst.lastSessionFile = sessionFile;
|
|
360
|
+
inst.lastSessionDir = sessionDir;
|
|
361
|
+
|
|
362
|
+
// ── PromptBus setup ──
|
|
363
|
+
// Create bus with dashboard connection wiring.
|
|
364
|
+
// Replaces the old ui-proxy race pattern.
|
|
365
|
+
// Convert seconds → milliseconds for PromptBus.
|
|
366
|
+
// Values <= 0 (e.g. -1) are passed through as-is to signal infinite wait.
|
|
367
|
+
// A per-session env override (set by plugin spawns) wins over config.
|
|
368
|
+
// See change: add-pending-question-stack (D11).
|
|
369
|
+
const askUserTimeoutMs = resolveAskUserTimeoutMs(inst.config.askUserPromptTimeoutSeconds);
|
|
370
|
+
inst.promptBus = new PromptBus({
|
|
371
|
+
timeoutMs: askUserTimeoutMs,
|
|
372
|
+
onDashboardRequest: (prompt, component, placement) => {
|
|
373
|
+
inst.connection.send({
|
|
374
|
+
type: "prompt_request" as any,
|
|
375
|
+
sessionId: inst.sessionId,
|
|
376
|
+
promptId: prompt.id,
|
|
377
|
+
prompt: {
|
|
378
|
+
question: prompt.question,
|
|
379
|
+
type: prompt.type,
|
|
380
|
+
options: prompt.options,
|
|
381
|
+
defaultValue: prompt.defaultValue,
|
|
382
|
+
pipeline: prompt.pipeline,
|
|
383
|
+
metadata: prompt.metadata,
|
|
384
|
+
},
|
|
385
|
+
component,
|
|
386
|
+
placement,
|
|
387
|
+
});
|
|
388
|
+
},
|
|
389
|
+
onDashboardDismiss: (id) => {
|
|
390
|
+
inst.connection.send({ type: "prompt_dismiss" as any, sessionId: inst.sessionId, promptId: id });
|
|
391
|
+
},
|
|
392
|
+
onDashboardCancel: (id) => {
|
|
393
|
+
inst.connection.send({ type: "prompt_cancel" as any, sessionId: inst.sessionId, promptId: id });
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// Register built-in default adapter (always present, works without pi-flows)
|
|
398
|
+
inst.promptBus.registerAdapter(new DashboardDefaultAdapter());
|
|
399
|
+
|
|
400
|
+
patchUiForPromptBus(inst, ctx, inst.promptBus);
|
|
401
|
+
|
|
402
|
+
// Flip ctx.hasUI=true now that ctx.ui.* has been patched to route
|
|
403
|
+
// through PromptBus → dashboard. `cachedHasUI` (captured earlier at
|
|
404
|
+
// line ~1287) retains the pi-supplied original value, so
|
|
405
|
+
// `detectSessionSource` continues to classify dashboard-spawned RPC
|
|
406
|
+
// vs tmux correctly. Extensions that branch on `ctx.hasUI`
|
|
407
|
+
// (context-mode `/ctx-stats` / `/ctx-doctor`, pi-agent-browser auto-install)
|
|
408
|
+
// now take their UI-present branch and render output via the proxied
|
|
409
|
+
// `ctx.ui.notify`. See change: fix-bridge-hasui-for-headless-rpc.
|
|
410
|
+
flipHasUI(ctx);
|
|
411
|
+
|
|
412
|
+
// Listen for adapter registrations from other extensions (e.g. pi-flows)
|
|
413
|
+
if (pi.events) {
|
|
414
|
+
pi.events.on("prompt:register-adapter", (adapter: any) => {
|
|
415
|
+
if (inst.promptBus && adapter && typeof adapter.name === "string") {
|
|
416
|
+
inst.promptBus.registerAdapter(adapter);
|
|
417
|
+
// Inject respond/cancel functions so cross-package adapters can talk back
|
|
418
|
+
if (typeof adapter.setRespond === "function") {
|
|
419
|
+
adapter.setRespond((response: any) => inst.promptBus!.respond(response));
|
|
420
|
+
}
|
|
421
|
+
if (typeof adapter.setCancel === "function") {
|
|
422
|
+
adapter.setCancel((id: string) => inst.promptBus!.cancel(id));
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
// Expose bus request function for pi-flows to use via emitPromptAndAwait
|
|
428
|
+
pi.events.emit("prompt:set-bus-request", {
|
|
429
|
+
request: (options: any) => inst.promptBus!.request(options),
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
// Generic system-follow-up channel: any plugin bridge entry can request
|
|
433
|
+
// a system-originated continuation through the single drain path by
|
|
434
|
+
// emitting `dashboard:enqueue-followup`. Inert when no plugin emits it.
|
|
435
|
+
// See change: add-goal-continuation-plugin (Decision 2).
|
|
436
|
+
pi.events.on("dashboard:enqueue-followup", (payload: any) => {
|
|
437
|
+
if (payload && typeof payload.text === "string") {
|
|
438
|
+
inst.enqueueSystemFollowup(payload.text);
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
// Generic plugin bridge→server channel: a plugin bridge entry emits
|
|
443
|
+
// `dashboard:plugin-message` and the main bridge wraps it in a
|
|
444
|
+
// `plugin_pi_message` envelope over the extension WS. The server
|
|
445
|
+
// dispatches to handlers registered via
|
|
446
|
+
// `ServerPluginContext.registerPiHandler(messageType, handler)`.
|
|
447
|
+
// See change: add-goal-continuation-plugin.
|
|
448
|
+
pi.events.on("dashboard:plugin-message", (payload: any) => {
|
|
449
|
+
if (
|
|
450
|
+
payload &&
|
|
451
|
+
typeof payload.pluginId === "string" &&
|
|
452
|
+
typeof payload.messageType === "string"
|
|
453
|
+
) {
|
|
454
|
+
inst.connection.send({
|
|
455
|
+
type: "plugin_pi_message",
|
|
456
|
+
sessionId: inst.sessionId,
|
|
457
|
+
pluginId: payload.pluginId,
|
|
458
|
+
messageType: payload.messageType,
|
|
459
|
+
payload: payload.payload ?? null,
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Connect first, then auto-start if needed.
|
|
466
|
+
// session_register must be buffered before any event_forward messages.
|
|
467
|
+
//
|
|
468
|
+
// (tasks 7.2/7.3) A REMOTE endpoint is challenged BEFORE the connection
|
|
469
|
+
// opens: across a network an address proves nothing, so the pinned Ed25519
|
|
470
|
+
// identity is the only thing that answers "is this my dashboard?" (D8).
|
|
471
|
+
// Local endpoints are unaffected — the socket/loopback token already
|
|
472
|
+
// authorises them — so this adds no latency to the common path.
|
|
473
|
+
if (isRemoteEndpoint(inst.dashboardUrl)) {
|
|
474
|
+
const pinsFile = serverPinsPath();
|
|
475
|
+
const connectIfIdentityVerifies = async () => {
|
|
476
|
+
const verdict = await gateRemoteRegistration({
|
|
477
|
+
endpoint: inst.dashboardUrl,
|
|
478
|
+
store: loadServerPins(pinsFile),
|
|
479
|
+
env: process.env,
|
|
480
|
+
});
|
|
481
|
+
// Task 10.3: the cause is distinguishable in the log, not folded into
|
|
482
|
+
// a generic connection failure.
|
|
483
|
+
const line = `[dashboard] remote identity ${verdict.cause}: ${verdict.reason}`;
|
|
484
|
+
if (!verdict.allow) {
|
|
485
|
+
console.error(`${line} — not registering`);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
console.log(line);
|
|
489
|
+
// Only a VERIFIED identity gets its address remembered.
|
|
490
|
+
if (verdict.fingerprint) notePinEndpoint(pinsFile, verdict.fingerprint, inst.dashboardUrl);
|
|
491
|
+
inst.connection.connect();
|
|
492
|
+
};
|
|
493
|
+
// Guarded discard: a failure here must be OBSERVED, never take the host
|
|
494
|
+
// pi agent down.
|
|
495
|
+
void connectIfIdentityVerifies().catch((err) => console.error("[dashboard]", err));
|
|
496
|
+
} else {
|
|
497
|
+
inst.connection.connect();
|
|
498
|
+
}
|
|
499
|
+
// Drain the buffered transport diagnostics through the live connection
|
|
500
|
+
// (task 10.5). `send()` buffers while the socket is down, which is the
|
|
501
|
+
// right behaviour here: the detail is self-describing, so a late delivery
|
|
502
|
+
// is still a true one.
|
|
503
|
+
inst.transportDiagnostics.attach({
|
|
504
|
+
send: (m) => inst.connection.send(m),
|
|
505
|
+
getSessionId: () => inst.sessionId,
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
// (task 3.8) Verify the instance answering at the recorded endpoint really
|
|
509
|
+
// is the one the record named. The socket's mode and the local token are
|
|
510
|
+
// both per-HOME, so a same-HOME impostor passes them — only the published
|
|
511
|
+
// `instanceId` distinguishes instances. Refusal is loud and does NOT fall
|
|
512
|
+
// back to a discovered substitute: that substitution is the bug.
|
|
513
|
+
if (
|
|
514
|
+
inst.endpointChoice.available &&
|
|
515
|
+
inst.endpointChoice.source === "rendezvous-record" &&
|
|
516
|
+
inst.rendezvous?.instanceId
|
|
517
|
+
) {
|
|
518
|
+
// Alias: property narrowing on `inst.rendezvous` does not survive into the closure.
|
|
519
|
+
const rendezvous = inst.rendezvous;
|
|
520
|
+
const verifyRecordedInstance = async () => {
|
|
521
|
+
const verdict = await verifyInstanceIdentity({
|
|
522
|
+
healthUrl: healthUrlForInstance(rendezvous.httpPort),
|
|
523
|
+
expectedInstanceId: rendezvous.instanceId,
|
|
524
|
+
});
|
|
525
|
+
if (verdict.adopt) {
|
|
526
|
+
inst.registeredInstanceId = rendezvous.instanceId;
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
// Only a CONFLICT justifies tearing the connection down. `disconnect()`
|
|
530
|
+
// sets `intentionalClose`, so nothing rearms the backoff loop and the
|
|
531
|
+
// session is dead until pi itself restarts — right for an impostor,
|
|
532
|
+
// catastrophic for an outage. `/api/health` is unreachable for seconds
|
|
533
|
+
// on every `POST /api/restart` while the gateway socket stays healthy,
|
|
534
|
+
// so treating silence as refusal would kill every bridge on the host on
|
|
535
|
+
// every rebuild. Unverified means we simply do not claim an identity.
|
|
536
|
+
if (!verdict.conflict) {
|
|
537
|
+
console.error(
|
|
538
|
+
`[dashboard] instance verification ${verdict.reason} — keeping the connection, identity unclaimed`,
|
|
539
|
+
);
|
|
540
|
+
inst.registeredInstanceId = undefined;
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
console.error(`[dashboard] instance verification ${verdict.reason} — disconnecting`);
|
|
544
|
+
inst.registeredInstanceId = undefined;
|
|
545
|
+
try {
|
|
546
|
+
inst.connection.disconnect();
|
|
547
|
+
} catch {
|
|
548
|
+
/* already down */
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
// Guarded discard: the verification runs alongside the connection and
|
|
552
|
+
// must never take the host pi agent down, but its failure must still be
|
|
553
|
+
// OBSERVED rather than dropped on the floor.
|
|
554
|
+
void verifyRecordedInstance().catch((err) => console.error("[dashboard]", err));
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// Extract first message (sessionFile/sessionDir already extracted above)
|
|
558
|
+
const firstMessage = extractFirstMessage(ctx);
|
|
559
|
+
inst.lastFirstMessage = firstMessage;
|
|
560
|
+
|
|
561
|
+
// Register session with initial model/thinkingLevel
|
|
562
|
+
inst.lastSessionName = pi.getSessionName() ?? "";
|
|
563
|
+
const initialModel = getCurrentModelString(inst.syncBc());
|
|
564
|
+
const initialThinkingLevel = (pi as any).getThinkingLevel?.() ?? undefined;
|
|
565
|
+
inst.lastModel = initialModel;
|
|
566
|
+
inst.lastThinkingLevel = initialThinkingLevel;
|
|
567
|
+
|
|
568
|
+
// Include eventCount (+ leaf id, liveTailOpen) so server can skip event wipe
|
|
569
|
+
// on reconnect. `liveTailOpen` is computed ONCE and shared with the replay
|
|
570
|
+
// below. See change: fix-large-session-resume-replay (D7).
|
|
571
|
+
const { eventCount, leafEntryId } = branchFingerprint(ctx.sessionManager);
|
|
572
|
+
const liveTailOpen = isLive(ctx, inst.shared.isAgentStreaming);
|
|
573
|
+
|
|
574
|
+
// See change: fix-dashboard-source-mislabelling — sent on every
|
|
575
|
+
// register so server can re-stamp source after restart. Derived from the
|
|
576
|
+
// capture-once boolean (token may already be scrubbed). See change:
|
|
577
|
+
// fix-spawn-token-env-leak.
|
|
578
|
+
// ctx.cwd is the guarded getter that throws once the session is replaced.
|
|
579
|
+
// Read it once, defensively — a throw here would skip session_register +
|
|
580
|
+
// the heartbeat/git timers, leaving a resumed session dead in the UI.
|
|
581
|
+
// See change: fix-bridge-resume-disconnect.
|
|
582
|
+
const startCwd = safeCwd(ctx);
|
|
583
|
+
const spawnToken = consumeSpawnToken();
|
|
584
|
+
inst.connection.send({
|
|
585
|
+
type: "session_register",
|
|
586
|
+
extensionIdentity: bridgeExtensionIdentity(),
|
|
587
|
+
sessionId: inst.sessionId,
|
|
588
|
+
cwd: startCwd,
|
|
589
|
+
name: inst.lastSessionName || undefined,
|
|
590
|
+
source: detectSessionSource(inst.cachedHasUI, sessionFile),
|
|
591
|
+
model: initialModel,
|
|
592
|
+
thinkingLevel: initialThinkingLevel,
|
|
593
|
+
sessionFile,
|
|
594
|
+
sessionDir,
|
|
595
|
+
firstMessage,
|
|
596
|
+
eventCount,
|
|
597
|
+
...(leafEntryId !== undefined ? { leafEntryId } : {}),
|
|
598
|
+
liveTailOpen,
|
|
599
|
+
// The ONLY channel by which the server learns this session's process for a
|
|
600
|
+
// non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
|
|
601
|
+
// so without this the server's record has no `pid` and shutdown has
|
|
602
|
+
// nothing to escalate to — the session was unregistered while a ~127 MB
|
|
603
|
+
// pi kept running (#452). The two `session_register` sends in
|
|
604
|
+
// session-sync.ts already carry it; this one, the FIRST register of a
|
|
605
|
+
// fresh session, did not.
|
|
606
|
+
// See change: fix-tmux-session-shutdown-leak (D6).
|
|
607
|
+
pid: process.pid,
|
|
608
|
+
// See change: prove-vault-bridge-tls (D7).
|
|
609
|
+
...(inst.connection.certValidation ? { certValidation: "enforced" as const } : {}),
|
|
610
|
+
// The spawn correlation token, echoed back so the server can match THIS
|
|
611
|
+
// register to the spawn that produced it. This is a fresh session's FIRST
|
|
612
|
+
// register, and it omitted the token entirely: tier-1 correlation never
|
|
613
|
+
// fired for a dashboard spawn, so the spawn watchdog could only match by
|
|
614
|
+
// cwd and reported false register-timeouts for concurrent spawns into one
|
|
615
|
+
// directory. Single-use — `consumeSpawnToken` scrubs the env.
|
|
616
|
+
// See change: fix-tmux-session-shutdown-leak (D5).
|
|
617
|
+
...(spawnToken ? { spawnToken } : {}),
|
|
618
|
+
...(inst.dashboardSpawned ? { dashboardSpawned: true } : {}),
|
|
619
|
+
// Tri-state git-repo signal, computed at register time (authority).
|
|
620
|
+
// See change: gate-session-worktree-button-on-git.
|
|
621
|
+
isGitRepo: detectIsGitRepo(startCwd),
|
|
622
|
+
// Fact-forwarding: server decides auto-hide. See change:
|
|
623
|
+
// auto-hide-headless-worker-sessions.
|
|
624
|
+
...buildVisibilityRegisterFields(inst.cachedHasUI, process.env),
|
|
625
|
+
// Applied server-side only for an id it has no record of.
|
|
626
|
+
// See change: count-non-message-usage.
|
|
627
|
+
...(usageSeed ? { usageSeed } : {}),
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
// The register above just went out (live socket, or buffered for the
|
|
631
|
+
// open — either way the manager learns its last-registered endpoint for
|
|
632
|
+
// the migration gate's reversal target).
|
|
633
|
+
// See change: fix-bridge-mdns-migration-hijack (task 2.1).
|
|
634
|
+
inst.connection.noteRegistered();
|
|
635
|
+
|
|
636
|
+
// Allow event forwarding now that session_register is buffered
|
|
637
|
+
inst.sessionReady = true;
|
|
638
|
+
|
|
639
|
+
// D3: mint-on-registration. Ask the mcp-server plugin for this session's
|
|
640
|
+
// /mcp credential now that the socket is (re)registered — the reply
|
|
641
|
+
// arrives on the session-private lane (mcp_token_minted) and registers
|
|
642
|
+
// pi-dashboard with pi's built-in MCP, and re-registers after every
|
|
643
|
+
// reconnect, which is what makes a dashboard restart self-heal. Ordered
|
|
644
|
+
// after session_register on the SAME socket, so the server's
|
|
645
|
+
// connection-key attribution is already established when it arrives.
|
|
646
|
+
// See change: wire-mcp-session-token (D3/D5).
|
|
647
|
+
inst.connection.send({
|
|
648
|
+
type: "plugin_pi_message",
|
|
649
|
+
sessionId: inst.sessionId,
|
|
650
|
+
pluginId: "mcp-server",
|
|
651
|
+
messageType: "mcp/mint-token",
|
|
652
|
+
payload: {},
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
// Flush any subagent frames buffered during the not-ready window (D1) so a
|
|
656
|
+
// reconnect/discovery/reload gap self-heals instead of leaving a running
|
|
657
|
+
// subagent's detail empty. See change: fix-subagent-live-detail-reliability.
|
|
658
|
+
inst.flushPendingSubagentFrames();
|
|
659
|
+
|
|
660
|
+
// Replay full session history so the dashboard has all messages. A turn
|
|
661
|
+
// still running across a `/reload` keeps its in-flight calls open instead
|
|
662
|
+
// of getting a fabricated `session_ended` end. See change:
|
|
663
|
+
// fix-replay-fabricates-orphan-end-for-live-calls (D3).
|
|
664
|
+
inst.replaySessionEntries({ liveTailOpen });
|
|
665
|
+
inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
|
|
666
|
+
// After replay_complete: inside the replay window the server may drop
|
|
667
|
+
// forwarded events without insert or broadcast (`skipReplayInsert`).
|
|
668
|
+
// See change: fix-terminal-session-dashboard-reload (D4).
|
|
669
|
+
if (reloadDelivered) inst.connection.send(reloadCompletedFeedback(inst.sessionId));
|
|
670
|
+
// If agent is mid-turn (e.g. reload during streaming), send synthetic agent_start
|
|
671
|
+
if (inst.shared.isAgentStreaming) {
|
|
672
|
+
// `synthetic` lets the server's end-of-session open-call scan see past
|
|
673
|
+
// this re-announcement. See change: fix-replay-fabricates-orphan-end-for-live-calls (D4).
|
|
674
|
+
inst.connection.send(mapEventToProtocol(inst.sessionId, { type: "agent_start", synthetic: true }));
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// Send initial commands list
|
|
678
|
+
const commands = filterHiddenCommands(pi.getCommands());
|
|
679
|
+
inst.connection.send({
|
|
680
|
+
type: "commands_list",
|
|
681
|
+
sessionId: inst.sessionId,
|
|
682
|
+
commands,
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
// Send initial flows list
|
|
686
|
+
inst.sendFlowsList();
|
|
687
|
+
|
|
688
|
+
// Send available models
|
|
689
|
+
inst.cachedModelRegistry = (ctx as any).modelRegistry;
|
|
690
|
+
if (inst.cachedModelRegistry) {
|
|
691
|
+
try {
|
|
692
|
+
const models = filterByEnabledModels(inst.cachedModelRegistry.getAvailable().map(toModelInfo));
|
|
693
|
+
inst.connection.send({ type: "models_list", sessionId: inst.sessionId, models });
|
|
694
|
+
// See change: replace-hardcoded-provider-lists.
|
|
695
|
+
inst.connection.send({ type: "providers_list", sessionId: inst.sessionId, providers: buildProviderCatalogue() });
|
|
696
|
+
} catch { /* modelRegistry not available */ }
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// Apply default model only on brand-new sessions (no prior message history)
|
|
700
|
+
// that were NOT launched with an explicit --model flag. Resume (--session) and
|
|
701
|
+
// fork (--fork) both load parent messages, so messageCount > 0 and we keep their
|
|
702
|
+
// existing model. Mirrors pi's own !hasExistingSession gate (sdk.js:106 —
|
|
703
|
+
// `existingSession.messages.length > 0`). NOT the raw getEntries() count: pi's
|
|
704
|
+
// sdk.js auto-appends model_change + thinking_level_change setup entries to a
|
|
705
|
+
// brand-new session BEFORE emitting session_start, so getEntries() is ≥ 2 even
|
|
706
|
+
// for a session with no user history. Only message entries count.
|
|
707
|
+
// The bridge runs inside the pi process, so process.argv is pi's argv — an
|
|
708
|
+
// explicit --model there is the spawner's resolved choice and the default
|
|
709
|
+
// never overrides it. The deferred retry below needs no separate guard: when
|
|
710
|
+
// the gate is false this never sets pendingDefaultModel, so onProviderChanged
|
|
711
|
+
// has nothing to re-apply.
|
|
712
|
+
// See changes: fix-resume-keeps-session-model,
|
|
713
|
+
// fix-default-model-new-session-entry-count,
|
|
714
|
+
// fix-default-model-clobbers-explicit-model (issue #595).
|
|
715
|
+
const entryCount = ctx.sessionManager.buildSessionContext?.()?.messages?.length ?? 0;
|
|
716
|
+
const freshConfig = loadConfig();
|
|
717
|
+
if (shouldApplyDefaultModel({
|
|
718
|
+
reason: _event?.reason,
|
|
719
|
+
entryCount,
|
|
720
|
+
hasModelRegistry: Boolean(inst.cachedModelRegistry),
|
|
721
|
+
hasDefaultModel: Boolean(freshConfig.defaultModel),
|
|
722
|
+
hasExplicitModel: hasExplicitModelArg(process.argv),
|
|
723
|
+
})) {
|
|
724
|
+
inst.pendingDefaultModel = inst.applyDefaultModel();
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// Send initial roles
|
|
728
|
+
if (pi.events) {
|
|
729
|
+
const rolesData: any = {};
|
|
730
|
+
pi.events.emit("roles:get-all", rolesData);
|
|
731
|
+
if (rolesData.roles) {
|
|
732
|
+
inst.connection.send({
|
|
733
|
+
type: "roles_list",
|
|
734
|
+
sessionId: inst.sessionId,
|
|
735
|
+
roles: rolesData.roles ?? {},
|
|
736
|
+
presets: rolesData.presets ?? [],
|
|
737
|
+
activePreset: rolesData.activePreset ?? null,
|
|
738
|
+
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// Discover or auto-start server (non-blocking — connection will reconnect)
|
|
744
|
+
//
|
|
745
|
+
// When a real launchServer() is about to run (not on mDNS/health-check
|
|
746
|
+
// paths), mount an animated TUI widget above the editor using pi-tui's
|
|
747
|
+
// Loader (a real Component, self-animating at 80ms, like pi-flows'
|
|
748
|
+
// architect-widget). The previous implementation used
|
|
749
|
+
// ctx.ui.setStatus(...) which only writes a footer string and relies on
|
|
750
|
+
// the TUI render loop being ticked elsewhere — on the cold-start path
|
|
751
|
+
// nothing else requests renders, so the spinner never animated and often
|
|
752
|
+
// never appeared. setWidget(key, factory, {placement:"aboveEditor"}) gives
|
|
753
|
+
// us a managed component that owns its own render loop and is always
|
|
754
|
+
// visible while the launch is in flight.
|
|
755
|
+
let spinnerTimer: NodeJS.Timeout | null = null;
|
|
756
|
+
let spinnerStart = 0;
|
|
757
|
+
let activeLoader: Loader | null = null;
|
|
758
|
+
const stopSpinner = () => {
|
|
759
|
+
// Release the interval BEFORE the guarded ctx.ui call, so a stale ctx
|
|
760
|
+
// still stops the 1s label refresh instead of leaking it.
|
|
761
|
+
if (spinnerTimer) {
|
|
762
|
+
clearInterval(spinnerTimer);
|
|
763
|
+
spinnerTimer = null;
|
|
764
|
+
}
|
|
765
|
+
activeLoader = null;
|
|
766
|
+
// This runs from `onLaunchEnd` AND from the terminal .then()/.catch()
|
|
767
|
+
// below, either of which can land after a session replacement/reload has
|
|
768
|
+
// invalidated `ctx`. See ui-stale-guard.ts.
|
|
769
|
+
runUiSafely(() => ctx.ui.setWidget("pi-dashboard-launch", undefined));
|
|
770
|
+
};
|
|
771
|
+
// Resolve the ports the auto-start chain uses (health check + launch)
|
|
772
|
+
// with the shared env → config.json → default precedence, so a session
|
|
773
|
+
// whose environment names the dashboard's real ports attaches to (or
|
|
774
|
+
// launches on) THOSE ports instead of a stale config/default — this is
|
|
775
|
+
// the split-brain fix: without it, a harness/container session with
|
|
776
|
+
// DASHBOARD_PORT in its env health-checked 8000, found nothing, and
|
|
777
|
+
// launched a competing dashboard on 8000. `config` is not mutated;
|
|
778
|
+
// `loadConfig()` stays untouched (design D1/D2).
|
|
779
|
+
// See change: fix-bridge-autostart-port-resolution.
|
|
780
|
+
autoStartServer({ ...inst.config, ...resolveDashboardPorts(process.env, inst.config) }, {
|
|
781
|
+
discoverDashboard,
|
|
782
|
+
isDashboardRunning,
|
|
783
|
+
launchServer,
|
|
784
|
+
notify: (msg, level) => runUiSafely(() => ctx.ui.notify(msg, level)),
|
|
785
|
+
onLaunchStart: () => {
|
|
786
|
+
spinnerStart = Date.now();
|
|
787
|
+
const buildMessage = () => {
|
|
788
|
+
const elapsed = Math.floor((Date.now() - spinnerStart) / 1000);
|
|
789
|
+
return `starting dashboard server … (${elapsed}s)`;
|
|
790
|
+
};
|
|
791
|
+
runUiSafely(() =>
|
|
792
|
+
ctx.ui.setWidget(
|
|
793
|
+
"pi-dashboard-launch",
|
|
794
|
+
(tui: unknown, theme: { fg: (role: string, s: string) => string }) => {
|
|
795
|
+
const loader = new Loader(
|
|
796
|
+
tui as ConstructorParameters<typeof Loader>[0],
|
|
797
|
+
(s: string) => theme.fg("accent", s),
|
|
798
|
+
(s: string) => theme.fg("muted", s),
|
|
799
|
+
buildMessage(),
|
|
800
|
+
);
|
|
801
|
+
activeLoader = loader;
|
|
802
|
+
// Loader has stop() but no dispose(); wire dispose so that
|
|
803
|
+
// setExtensionWidget's teardown stops the 80ms animation interval.
|
|
804
|
+
(loader as Loader & { dispose?: () => void }).dispose = () => loader.stop();
|
|
805
|
+
return loader;
|
|
806
|
+
},
|
|
807
|
+
{ placement: "aboveEditor" },
|
|
808
|
+
),
|
|
809
|
+
);
|
|
810
|
+
// Refresh the elapsed-seconds label every second. Frame animation is
|
|
811
|
+
// driven by the Loader's own 80ms interval.
|
|
812
|
+
spinnerTimer = setInterval(() => {
|
|
813
|
+
activeLoader?.setMessage(buildMessage());
|
|
814
|
+
}, 1000);
|
|
815
|
+
},
|
|
816
|
+
onLaunchEnd: () => {
|
|
817
|
+
stopSpinner();
|
|
818
|
+
},
|
|
819
|
+
// Register the spawned dashboard-server PID into `selfSpawnedPgids`
|
|
820
|
+
// synchronously, before the next 5 s process-scan tick. Keeps the
|
|
821
|
+
// dashboard's own `node` infrastructure out of the session-card
|
|
822
|
+
// process list. See change: tighten-process-list-ux.
|
|
823
|
+
onServerSpawned: (childPid: number) => {
|
|
824
|
+
inst.selfSpawnedPgids.add(childPid);
|
|
825
|
+
},
|
|
826
|
+
// Honor the server's `server_restarting` quiesce window. While a
|
|
827
|
+
// deliberate restart/shutdown is in flight, skip the spawn step so we
|
|
828
|
+
// don't race the orchestrator. Discovery + reconnection still run.
|
|
829
|
+
// See change: fix-restart-bridge-auto-start-race.
|
|
830
|
+
shouldSuppressAutoStart: () => inst.connection.shouldSuppressAutoStart(),
|
|
831
|
+
}).then((result) => {
|
|
832
|
+
stopSpinner(); // safety net — covers onLaunchEnd not firing
|
|
833
|
+
if (result.server && result.server.piPort !== inst.config.piPort) {
|
|
834
|
+
const candidateUrl = `ws://${formatHostPort(result.server.host, result.server.piPort)}`;
|
|
835
|
+
// fix-bridge-mdns-migration-hijack: a DISCOVERED candidate only
|
|
836
|
+
// SUGGESTS. Whether the connection follows it is decided — and
|
|
837
|
+
// recorded — by `ConnectionManager.retargetTo`, which refuses to
|
|
838
|
+
// drop an established, registered connection until the candidate has
|
|
839
|
+
// PROVEN reachable (`GET /api/health` → `{ok:true}`, D1), honours
|
|
840
|
+
// localhost preference against a remote candidate (D3), and returns
|
|
841
|
+
// to the last registered endpoint if the candidate dies after
|
|
842
|
+
// adoption (D2). The blanket refusal this replaces also blocked
|
|
843
|
+
// every LEGITIMATE migration (a server that really moved).
|
|
844
|
+
if (inst.endpointPinned) {
|
|
845
|
+
// D3 (add-pi-gateway-transport-identity): a pinned endpoint
|
|
846
|
+
// refuses every re-target. The refusal stays on the record (10.2).
|
|
847
|
+
const decision = decideRetarget({
|
|
848
|
+
current: { endpoint: inst.dashboardUrl, instanceId: inst.registeredInstanceId },
|
|
849
|
+
candidate: { endpoint: candidateUrl },
|
|
850
|
+
pinned: true,
|
|
851
|
+
failed: false,
|
|
852
|
+
identityVerified: false,
|
|
853
|
+
});
|
|
854
|
+
const refusedDetail = `${inst.dashboardUrl} -> ${candidateUrl}: ${decision.reason}`;
|
|
855
|
+
console.log(`[dashboard] re-target ${refusedDetail}`);
|
|
856
|
+
inst.transportDiagnostics.record({ event: "retarget_refused", detail: refusedDetail });
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
const trigger = `mdns discovery (${result.server.host}:${result.server.port}, gateway ${result.server.piPort})`;
|
|
860
|
+
// The health probe runs on the candidate's HTTP port — the record's
|
|
861
|
+
// `port`, not the gateway port — and completes BEFORE the incumbent
|
|
862
|
+
// is dropped (retargetTo owns that ordering).
|
|
863
|
+
const healthUrl = `http://${formatHostPort(result.server.host, result.server.port)}/api/health`;
|
|
864
|
+
inst.connection
|
|
865
|
+
.retargetTo(candidateUrl, {
|
|
866
|
+
trigger,
|
|
867
|
+
// Reachable AND — when this bridge holds the local token — able to
|
|
868
|
+
// return a valid server counter-proof: a healthy answer is not an
|
|
869
|
+
// identity. A refusal keeps the established connection and is logged
|
|
870
|
+
// with its named cause. See change: harden-bridge-inbound-and-discovery (D19).
|
|
871
|
+
verify: () => verifyDiscoveredCandidate({ healthUrl, candidateUrl }),
|
|
872
|
+
})
|
|
873
|
+
.then((accepted) => {
|
|
874
|
+
console.log(`[dashboard] re-target ${inst.dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);
|
|
875
|
+
})
|
|
876
|
+
.catch((err: unknown) => console.error("[dashboard] re-target decision failed:", err));
|
|
877
|
+
}
|
|
878
|
+
}).catch(() => { stopSpinner(); });
|
|
879
|
+
|
|
880
|
+
// Send initial git info + the session's pi version. A session change already
|
|
881
|
+
// ran the first evaluation (and renewed the tracker) in handleSessionChange;
|
|
882
|
+
// doing it again would double the synchronous git work.
|
|
883
|
+
if (!sessionChanged) {
|
|
884
|
+
const gbc = inst.syncBc();
|
|
885
|
+
inst.renewGitTracker().evaluateFirst(gbc, startCwd);
|
|
886
|
+
inst.applyBc(gbc);
|
|
887
|
+
}
|
|
888
|
+
inst.sendCwdMissingIfChanged(startCwd);
|
|
889
|
+
inst.sendPiVersionIfChanged();
|
|
890
|
+
|
|
891
|
+
// Start metrics monitor and heartbeat
|
|
892
|
+
startMetricsMonitor();
|
|
893
|
+
inst.heartbeatTimer = setInterval(() => {
|
|
894
|
+
if (!inst.isActive()) return;
|
|
895
|
+
inst.vaultDelivery.tick();
|
|
896
|
+
inst.connection.send({
|
|
897
|
+
type: "session_heartbeat",
|
|
898
|
+
sessionId: inst.sessionId,
|
|
899
|
+
// Liveness truth for the server's status reconcile: `streaming` is
|
|
900
|
+
// otherwise a one-way latch and a single dropped `agent_end` sticks
|
|
901
|
+
// the card on `Thinking…` forever.
|
|
902
|
+
// `=== true` because the flag is optional and is `undefined` before
|
|
903
|
+
// the first turn: sent raw it would serialize away and read as "old
|
|
904
|
+
// bridge, no liveness truth" instead of "idle".
|
|
905
|
+
// See change: fix-stuck-streaming-status-latch.
|
|
906
|
+
agentRunning: inst.shared.isAgentStreaming === true,
|
|
907
|
+
// Fold the bridge→server ring-buffer eviction count into the heartbeat
|
|
908
|
+
// so it reaches `/api/health`. See change:
|
|
909
|
+
// fix-stuck-tool-card-on-dropped-event.
|
|
910
|
+
metrics: {
|
|
911
|
+
...collectMetrics(),
|
|
912
|
+
droppedBufferedFrames: inst.connection.getDroppedBufferedCount(),
|
|
913
|
+
refusedInboundFrames: inst.connection.getDroppedInboundCount(),
|
|
914
|
+
// Subagent-tick throttle counters ride the same transport, so the
|
|
915
|
+
// throttle's two information-loss modes are observable in production
|
|
916
|
+
// instead of only at L1. See change: reduce-bridge-tick-bandwidth (D6).
|
|
917
|
+
...inst.subagentTickThrottle.stats,
|
|
918
|
+
// Plugin event-forward registry counters. See change:
|
|
919
|
+
// add-plugin-bridge-contributions.
|
|
920
|
+
pluginForwardDeclared: inst.pluginForwardRegistry.stats.declared,
|
|
921
|
+
pluginForwardRejected:
|
|
922
|
+
inst.pluginForwardRegistry.stats.rejected + inst.pluginForwardRegistry.stats.rejectedDeclarations,
|
|
923
|
+
pluginForwardConflicts: inst.pluginForwardRegistry.stats.conflicts,
|
|
924
|
+
pluginForwardRetained: inst.pluginForwardRegistry.stats.buffer.retained,
|
|
925
|
+
pluginForwardDropped:
|
|
926
|
+
inst.pluginForwardRegistry.stats.buffer.dropped + inst.pluginForwardRegistry.stats.buffer.keyRejected,
|
|
927
|
+
// Subagent fan-out admission counters ride the same transport, so a
|
|
928
|
+
// narrowed fan-out is observable instead of looking like a model that
|
|
929
|
+
// chose not to parallelize. See change:
|
|
930
|
+
// bound-subagent-fanout-under-host-pressure (D7).
|
|
931
|
+
...inst.fanoutAdmission.counters,
|
|
932
|
+
// Agent path gate counters (in-root decisions are counted, not logged).
|
|
933
|
+
pathGateInRoot: inst.pathGate.counters.inRoot,
|
|
934
|
+
pathGateAsked: inst.pathGate.counters.asked,
|
|
935
|
+
pathGateBlocked: inst.pathGate.counters.blocked,
|
|
936
|
+
pathGateYoloAllowed: inst.pathGate.counters.yoloAllowed,
|
|
937
|
+
// Poll-cost counters (summed across sessions on /api/health).
|
|
938
|
+
// See change: optimize-polling-hot-paths.
|
|
939
|
+
...pollCost,
|
|
940
|
+
},
|
|
941
|
+
});
|
|
942
|
+
}, HEARTBEAT_INTERVAL);
|
|
943
|
+
inst.shared.timers!.push(inst.heartbeatTimer);
|
|
944
|
+
|
|
945
|
+
// Start git + name/model polling
|
|
946
|
+
startGitPollTimer(inst, ctx);
|
|
947
|
+
|
|
948
|
+
// Start the adaptive process scanner (detect stalled child processes).
|
|
949
|
+
// One async `ps -A` per scan; fast while the agent/tools run, idle
|
|
950
|
+
// otherwise. session_start re-runs: dispose the previous scheduler first so
|
|
951
|
+
// schedules never stack. See change: optimize-polling-hot-paths.
|
|
952
|
+
inst.ensurePollingDisposable();
|
|
953
|
+
const scheduler = createProcessScanScheduler({
|
|
954
|
+
platform: process.platform,
|
|
955
|
+
setTimer: inst.setRegisteredTimeout,
|
|
956
|
+
clearTimer: inst.clearRegisteredTimeout,
|
|
957
|
+
scan: async () => {
|
|
958
|
+
if (!inst.isActive()) return { changed: false };
|
|
959
|
+
const processes = await scanChildProcessesAsync(
|
|
960
|
+
process.pid,
|
|
961
|
+
inst.trackedPgids,
|
|
962
|
+
PROCESS_MIN_ELAPSED_MS,
|
|
963
|
+
{ excludedPgids: inst.selfSpawnedPgids },
|
|
964
|
+
);
|
|
965
|
+
if (!inst.isActive() || inst.polling.processScan !== scheduler) return { changed: false };
|
|
966
|
+
const currentPids = JSON.stringify(processes.map((p) => p.pid).sort());
|
|
967
|
+
if (currentPids === inst.previousProcessPids) return { changed: false };
|
|
968
|
+
inst.previousProcessPids = currentPids;
|
|
969
|
+
inst.connection.send({
|
|
970
|
+
type: "process_list",
|
|
971
|
+
sessionId: inst.sessionId,
|
|
972
|
+
processes: processes.map((p) => ({ pid: p.pid, pgid: p.pgid, command: p.command, elapsedMs: p.elapsedMs })),
|
|
973
|
+
});
|
|
974
|
+
return { changed: true };
|
|
975
|
+
},
|
|
976
|
+
});
|
|
977
|
+
inst.polling.replaceProcessScan(scheduler);
|
|
978
|
+
scheduler.start();
|
|
979
|
+
|
|
980
|
+
// Register flow event listeners (pi-flows emits these via pi.events)
|
|
981
|
+
registerFlowEventListeners(inst.syncBc(), () => inst.sessionReady, inst.getFlowsList);
|
|
982
|
+
|
|
983
|
+
// Extension UI System (Phase 1): subscribe to invalidate once per
|
|
984
|
+
// session, then run the discovery probe. The probe is synchronous
|
|
985
|
+
// and re-runs on every reconnect (see `onReconnect` callback above).
|
|
986
|
+
// See change: add-extension-ui-modal.
|
|
987
|
+
subscribeUiInvalidate(inst.uiModulesBridgeCtx);
|
|
988
|
+
refreshUiModules(inst.uiModulesBridgeCtx);
|
|
989
|
+
}));
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/** `turn_end`: stop-after-turn latch, auto-name, usage drain. */
|
|
993
|
+
export function registerTurnEnd(inst: BridgeInstance): void {
|
|
994
|
+
const pi = inst.pi;
|
|
995
|
+
pi.on("turn_end", inst.safe(async (event: any, ctx: any) => {
|
|
996
|
+
if (!inst.isActive()) return;
|
|
997
|
+
inst.cachedCtx = ctx;
|
|
998
|
+
if (!inst.sessionReady) return;
|
|
999
|
+
// Drain point: compaction / usage entries recorded during the turn.
|
|
1000
|
+
// See change: count-non-message-usage.
|
|
1001
|
+
inst.drainUsage(ctx);
|
|
1002
|
+
|
|
1003
|
+
// Send firstMessage update after first turn if not previously sent
|
|
1004
|
+
if (!inst.lastFirstMessage) {
|
|
1005
|
+
const firstMsg = extractFirstMessage(ctx);
|
|
1006
|
+
if (firstMsg) {
|
|
1007
|
+
inst.lastFirstMessage = firstMsg;
|
|
1008
|
+
inst.connection.send({
|
|
1009
|
+
type: "first_message_update",
|
|
1010
|
+
sessionId: inst.sessionId,
|
|
1011
|
+
firstMessage: firstMsg,
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
}));
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** `session_shutdown`: disconnect and clean up this incarnation. */
|
|
1020
|
+
export function registerSessionShutdown(inst: BridgeInstance): void {
|
|
1021
|
+
const pi = inst.pi;
|
|
1022
|
+
pi.on("session_shutdown", inst.safe(async (event: any, ctx: any) => {
|
|
1023
|
+
if (!inst.isActive()) return;
|
|
1024
|
+
// Let the reloaded instance (fresh ExtensionAPI) pass the re-entry guard.
|
|
1025
|
+
// See change: fix-terminal-session-dashboard-reload (D4).
|
|
1026
|
+
releaseBridgeOwnerOnShutdown(inst.shared, event?.reason);
|
|
1027
|
+
// Remove this session's pi-dashboard MCP registration (a reloaded
|
|
1028
|
+
// instance re-registers on its own mint). See change: migrate-mcp-to-pi-builtin (D1).
|
|
1029
|
+
inst.mcpRegistrar.onSessionShutdown();
|
|
1030
|
+
inst.shared.isAgentStreaming = false;
|
|
1031
|
+
stopMetricsMonitor();
|
|
1032
|
+
if (inst.heartbeatTimer) {
|
|
1033
|
+
clearInterval(inst.heartbeatTimer);
|
|
1034
|
+
inst.heartbeatTimer = null;
|
|
1035
|
+
}
|
|
1036
|
+
if (inst.gitPollTimer) {
|
|
1037
|
+
clearInterval(inst.gitPollTimer);
|
|
1038
|
+
inst.gitPollTimer = null;
|
|
1039
|
+
}
|
|
1040
|
+
drainDisposables(inst.shared);
|
|
1041
|
+
// Flush undrained entry usage BEFORE session_unregister (which ends the
|
|
1042
|
+
// session server-side), on every shutdown reason: quit, reload and
|
|
1043
|
+
// session replacement (new/resume/fork). See change: count-non-message-usage.
|
|
1044
|
+
sendShutdownUsageThenUnregister(
|
|
1045
|
+
() => inst.drainUsage(ctx),
|
|
1046
|
+
() => inst.connection.send({
|
|
1047
|
+
type: "session_unregister",
|
|
1048
|
+
sessionId: inst.sessionId,
|
|
1049
|
+
}),
|
|
1050
|
+
);
|
|
1051
|
+
|
|
1052
|
+
// Drop retained subagent frames/snapshots on shutdown.
|
|
1053
|
+
// See change: fix-subagent-live-detail-reliability.
|
|
1054
|
+
inst.subagentFrameBuffer.reset();
|
|
1055
|
+
// See change: reduce-bridge-tick-bandwidth (D3).
|
|
1056
|
+
inst.subagentTickThrottle.reset();
|
|
1057
|
+
// A shutdown is a session boundary: discard parked text, cancel the window.
|
|
1058
|
+
// See change: coalesce-bridge-message-update-snapshots (D8).
|
|
1059
|
+
inst.coalescer.clear();
|
|
1060
|
+
|
|
1061
|
+
// Best-effort: remove this session's pasted ask_user attachments.
|
|
1062
|
+
// See change: add-ask-user-input-multiline-paste.
|
|
1063
|
+
cleanupAttachmentsForSession(inst.sessionId);
|
|
1064
|
+
|
|
1065
|
+
// Give time for the unregister to send
|
|
1066
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1067
|
+
inst.connection.disconnect();
|
|
1068
|
+
}));
|
|
1069
|
+
}
|