@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
|
@@ -5,126 +5,89 @@
|
|
|
5
5
|
* forwards all pi events, and relays commands back.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { appendIdentityLog } from "./bridge-identity-log.js";
|
|
8
9
|
import { bridgeExtensionIdentity } from "./extension-identity.js";
|
|
9
10
|
import fs from "node:fs";
|
|
10
|
-
import os from "node:os";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
-
import { ensureConfig, loadConfig,
|
|
13
|
+
import { ensureConfig, loadConfig, } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
14
14
|
import { shouldActivateBridge } from "./bridge-activation.js";
|
|
15
|
-
import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
16
|
-
import type {
|
|
17
|
-
ServerToExtensionMessage,
|
|
18
|
-
TranscriptRequestMessage,
|
|
19
|
-
} from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
20
15
|
import { rendezvousEndpoint } from "@blackbelt-technology/pi-dashboard-shared/rendezvous.js";
|
|
21
|
-
import {
|
|
22
|
-
import { decideTranscriptRequest } from "@blackbelt-technology/pi-dashboard-shared/transcript-request-guard.js";
|
|
23
|
-
import type { FlowInfo, ImageContent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
16
|
+
import type { FlowInfo, } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
24
17
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
25
|
-
import { Loader } from "@earendil-works/pi-tui";
|
|
26
18
|
import { AbortLatch } from "./abort-latch.js";
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
MAX_PER_MESSAGE_BYTES as ATTACH_MAX_PER_MESSAGE_BYTES,
|
|
30
|
-
cleanupAttachmentsForSession,
|
|
31
|
-
persistAttachment,
|
|
32
|
-
} from "./ask-user-attachments.js";
|
|
33
|
-
import { registerAskUserTool } from "./ask-user-tool.js";
|
|
34
|
-
import { type AutoNamer, adoptRestoredNamerState, createAutoNamer, type PersistedNamerState, type StreamSimpleFn } from "./auto-session-namer.js";
|
|
19
|
+
import { type AutoNamer, createAutoNamer, type PersistedNamerState, type StreamSimpleFn } from "./auto-session-namer.js";
|
|
35
20
|
import type { BridgeContext } from "./bridge-context.js";
|
|
36
|
-
import {
|
|
37
|
-
import { hasExplicitModelArg, shouldApplyDefaultModel } from "./bridge-default-model-gate.js";
|
|
38
|
-
import { mintBridgeTicket, readDeviceToken, withTicket } from "./bridge-ticket-client.js";
|
|
39
|
-
import { registerCanvasTool } from "./canvas-tool.js";
|
|
21
|
+
import { extractLatestTurnWindow, } from "./bridge-context.js";
|
|
40
22
|
import {
|
|
41
|
-
buildUserMessageContent,
|
|
42
23
|
createCommandHandler,
|
|
43
24
|
tryExecSlashTemplate,
|
|
44
25
|
validateImages,
|
|
45
26
|
} from "./command-handler.js";
|
|
27
|
+
import { createInboundLimits } from "./inbound-limits.js";
|
|
46
28
|
import { buildSessionContextText, runForkSubagentDraft } from "./commit-draft-agent.js";
|
|
47
29
|
import { ConnectionManager, type WatchdogFireInfo } from "./connection.js";
|
|
48
30
|
import {
|
|
49
|
-
consumePendingReloadOnSessionStart,
|
|
50
31
|
createTerminalReload,
|
|
51
32
|
isBridgeReentry,
|
|
52
33
|
RELOAD_COMMAND_NAME,
|
|
53
|
-
releaseBridgeOwnerOnShutdown,
|
|
54
|
-
reloadCompletedFeedback,
|
|
55
34
|
} from "./terminal-reload.js";
|
|
56
35
|
import { toCustomEntryForward, toCustomMessageForward } from "./custom-entry-forward.js";
|
|
57
36
|
import { registerDashboardContextInjector } from "./dashboard-context-injector.js";
|
|
58
|
-
import { DashboardDefaultAdapter } from "./dashboard-default-adapter.js";
|
|
59
37
|
import { runDevBuild } from "./dev-build.js";
|
|
60
|
-
import { EmptyActionableGuard,
|
|
38
|
+
import { EmptyActionableGuard, } from "./empty-actionable-guard.js";
|
|
61
39
|
import { resolveGuardConfig } from "./empty-actionable-guard-config.js";
|
|
62
|
-
import {
|
|
63
|
-
import { mapEventToProtocol,
|
|
40
|
+
import { instanceIdFileForSocket, resolveEndpoint } from "./endpoint-resolution.js";
|
|
41
|
+
import { mapEventToProtocol, } from "./event-forwarder.js";
|
|
64
42
|
import {
|
|
65
43
|
FLOW_EVENT_MAP,
|
|
66
44
|
registerEventBusForwarding,
|
|
67
|
-
registerFlowEventListeners,
|
|
68
45
|
SUBAGENT_EVENT_MAP,
|
|
69
46
|
} from "./flow-event-wiring.js";
|
|
70
47
|
import { createFollowupBuffer } from "./followup-buffer.js";
|
|
71
|
-
import {
|
|
72
|
-
import {
|
|
48
|
+
import { drainOneFollowup } from "./followup-drain.js";
|
|
49
|
+
import { createPollingHolder, drainDisposables, ensureDisposable, teardownPreviousIncarnation } from "./bridge-polling.js";
|
|
73
50
|
import { createGitTracker, type GitTracker } from "./git-tracker.js";
|
|
74
51
|
import { createPrStatusScheduler, type PrStatusScheduler } from "./pr-status.js";
|
|
75
52
|
import * as git from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
|
|
76
|
-
import {
|
|
77
|
-
import {
|
|
78
|
-
import {
|
|
53
|
+
import { localCredentialPlan, proofFailureLogCause } from "./local-token-header.js";
|
|
54
|
+
import { isPinnedEndpoint } from "./pinned-endpoint.js";
|
|
55
|
+
import { loadServerPins, serverPinsPath } from "./server-pin-store.js";
|
|
79
56
|
import { inlineMessageText, type ReadFileOutcome } from "./markdown-image-inliner.js";
|
|
80
|
-
import { createMcpDashboardRegistrar, type McpRegistrationApi,
|
|
57
|
+
import { createMcpDashboardRegistrar, type McpRegistrationApi, } from "./mcp-token-delivery.js";
|
|
81
58
|
import { createPluginRequestClient, installPluginRequest } from "./plugin-request-client.js";
|
|
82
|
-
import { COALESCE_WINDOW_MS,
|
|
83
|
-
import { reportRefresh } from "./model-refresh.js";
|
|
59
|
+
import { COALESCE_WINDOW_MS, MessageUpdateCoalescer } from "./message-update-coalescer.js";
|
|
84
60
|
import { resetReconnectCaches as _resetReconnectCaches, sendCwdMissingIfChanged as _sendCwdMissingIfChanged, sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendPiVersionIfChanged as _sendPiVersionIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged } from "./model-tracker.js";
|
|
85
|
-
import { decodeMultiselectAnswer } from "./multiselect-decode.js";
|
|
86
|
-
import { createNotifyProxy } from "./notify-proxy.js";
|
|
87
|
-
import { provisionOpenspecCli } from "./openspec-cli-shim.js";
|
|
88
61
|
import { createPathGate } from "./path-gate/index.js";
|
|
89
62
|
import { Suppression } from "./path-gate/suppression.js";
|
|
90
63
|
import { emitPendingPrompts } from "./pending-prompt-emitter.js";
|
|
91
64
|
import { readPiRetrySettings } from "./pi-retry-settings.js";
|
|
92
|
-
import {
|
|
93
|
-
import { getOwnPgid, scanChildProcessesAsync } from "./process-scanner.js";
|
|
94
|
-
import { createProcessScanScheduler } from "./process-scan-scheduler.js";
|
|
95
|
-
import { pollCost } from "./poll-cost.js";
|
|
96
|
-
import { decideProjectTrust, readEventCwd } from "./project-trust.js";
|
|
97
|
-
import { PromptBus } from "./prompt-bus.js";
|
|
65
|
+
import { getOwnPgid, } from "./process-scanner.js";
|
|
98
66
|
import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
|
|
99
67
|
import { activate as activateProviderRegister, buildProviderCatalogue, onProviderChanged, reloadProviders, toModelInfo } from "./provider-register.js";
|
|
100
|
-
import {
|
|
68
|
+
import { createRemoteUpgradePreparer } from "./remote-upgrade-preparer.js";
|
|
101
69
|
import { RetryTracker } from "./retry-tracker.js";
|
|
102
|
-
import { activate as activateRoleManager,
|
|
103
|
-
import {
|
|
104
|
-
import { autoStartServer } from "./server-auto-start.js";
|
|
105
|
-
import { launchServer } from "./server-launcher.js";
|
|
106
|
-
import { loadServerPins, notePinEndpoint, serverPinsPath } from "./server-pin-store.js";
|
|
107
|
-
import { handleSessionChange as _handleSessionChange, replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, consumeSpawnToken, filterByEnabledModels } from "./session-sync.js";
|
|
70
|
+
import { activate as activateRoleManager, resolveNamingModel } from "./role-manager.js";
|
|
71
|
+
import { replaySessionEntries as _replaySessionEntries, sendStateSync as _sendStateSync, filterByEnabledModels, isLive } from "./session-sync.js";
|
|
108
72
|
import { tryDispatchExtensionCommand } from "./slash-dispatch.js";
|
|
109
|
-
import { UsageDrain, drainUsageAndSend, makeCacheWarmingDecisionHandler,
|
|
110
|
-
import {
|
|
111
|
-
import {
|
|
73
|
+
import { UsageDrain, drainUsageAndSend, makeCacheWarmingDecisionHandler, } from "./usage-drain.js";
|
|
74
|
+
import { flushBufferedSubagentFrames, } from "./subagent-forward-sites.js";
|
|
75
|
+
import { PluginForwardRegistry } from "./plugin-event-forward-registry.js";
|
|
112
76
|
import { SubagentFrameBuffer } from "./subagent-frame-buffer.js";
|
|
113
77
|
import { stripForForward } from "./subagent-frame-strip.js";
|
|
114
78
|
import { FanoutAdmissionGate, resolveAdmissionConfig } from "./subagent-fanout-admission.js";
|
|
115
79
|
import { SaturationSampler } from "./subagent-saturation.js";
|
|
116
|
-
import {
|
|
117
|
-
import { inlineToolResultImages } from "./tool-result-image-inliner.js";
|
|
118
|
-
import { readTranscriptChunk, type TranscriptCursor } from "./transcript-backfill.js";
|
|
80
|
+
import { SubagentTickThrottle } from "./subagent-tick-throttle.js";
|
|
119
81
|
import { createTransportDiagnostics } from "./transport-diagnostics.js";
|
|
120
|
-
import {
|
|
121
|
-
import {
|
|
122
|
-
import {
|
|
123
|
-
import {
|
|
124
|
-
import {
|
|
125
|
-
import {
|
|
126
|
-
|
|
127
|
-
|
|
82
|
+
import { refreshUiModules, type UiModulesBridgeCtx } from "./ui-modules.js";
|
|
83
|
+
import { createInstance, type BridgeState } from "./bridge-handlers/instance.js";
|
|
84
|
+
import { createVaultDelivery } from "./vault-delivery.js";
|
|
85
|
+
import { createVaultForwardFilter } from "./vault-forwarder.js";
|
|
86
|
+
import { createVaultRedaction } from "./vault-redaction.js";
|
|
87
|
+
import { captureSpawnTokenAtActivation } from "./spawn-token.js";
|
|
88
|
+
import { registerSessionInfoChanged, registerProjectTrust, registerSessionStart, registerTurnEnd, registerSessionShutdown } from "./bridge-handlers/lifecycle.js";
|
|
89
|
+
import { registerEnrichedForwarders, registerPassThroughForwarders } from "./bridge-handlers/forwarders.js";
|
|
90
|
+
import { handleInboundMessage } from "./bridge-handlers/dispatch.js";
|
|
128
91
|
|
|
129
92
|
/**
|
|
130
93
|
* Formats the state behind a watchdog force-close for `server.log`.
|
|
@@ -139,72 +102,13 @@ function formatWatchdogFire(w: WatchdogFireInfo): string {
|
|
|
139
102
|
`readyState=${w.readyState} inboundQueue=${w.inboundQueueDepth} ` +
|
|
140
103
|
`refusedInbound=${w.refusedInbound} maxTickDrift=${w.maxTickDriftMs}ms`
|
|
141
104
|
);
|
|
142
|
-
}
|
|
143
|
-
const GIT_POLL_INTERVAL = 30_000;
|
|
144
|
-
// Platform-aware process scan cadence. Windows keeps the original 10 s /
|
|
145
|
-
// 30 s floor because PowerShell Get-CimInstance is expensive and can flash consoles;
|
|
146
|
-
// Unix uses 5 s / 5 s so legitimate bash subprocesses surface while still
|
|
147
|
-
// running. See change: tighten-process-list-ux.
|
|
148
|
-
const PROCESS_MIN_ELAPSED_MS = process.platform === "win32" ? 30_000 : 5_000; // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
|
|
105
|
+
} // platform-branch-ok: Windows-safe default (costly PowerShell Get-CimInstance)
|
|
149
106
|
|
|
150
107
|
|
|
151
108
|
|
|
152
109
|
// Use `process` (not `globalThis`) to survive jiti module cache invalidation
|
|
153
110
|
// AND to share state across isolated extension contexts (vm sandboxes).
|
|
154
111
|
const BRIDGE_KEY = "__pi_dashboard_bridge__";
|
|
155
|
-
interface BridgeState {
|
|
156
|
-
cleanup?: () => void;
|
|
157
|
-
sessionId?: string;
|
|
158
|
-
ctx?: any;
|
|
159
|
-
modelRegistry?: any;
|
|
160
|
-
hasUI?: boolean;
|
|
161
|
-
/** Monotonic generation counter — stale listeners bail out when mismatched */
|
|
162
|
-
generation?: number;
|
|
163
|
-
/** Path-gate denial map; process-global so a /reload keeps the 120 s suppression. */
|
|
164
|
-
pathGateSuppression?: Suppression;
|
|
165
|
-
/** The pi instance that owns the bridge (used to detect subagent re-entry) */
|
|
166
|
-
pi?: ExtensionAPI;
|
|
167
|
-
/** All connection instances from any bridge incarnation (for cleanup) */
|
|
168
|
-
connections?: ConnectionManager[];
|
|
169
|
-
/** All interval timers from any bridge incarnation (for cleanup) */
|
|
170
|
-
timers?: ReturnType<typeof setInterval>[];
|
|
171
|
-
/**
|
|
172
|
-
* Teardown callbacks for schedulers/watchers owned by a bridge incarnation
|
|
173
|
-
* (process-scan scheduler, git probe scheduler, git-dir watcher). Drained on
|
|
174
|
-
* re-init, `state.cleanup` and `session_shutdown`.
|
|
175
|
-
* See change: optimize-polling-hot-paths.
|
|
176
|
-
*/
|
|
177
|
-
disposables?: Array<() => void>;
|
|
178
|
-
/** True when the agent is currently in a turn (between agent_start and agent_end) */
|
|
179
|
-
isAgentStreaming?: boolean;
|
|
180
|
-
/**
|
|
181
|
-
* The auto-namer's durable state set, carried across reload as VALUES. The
|
|
182
|
-
* namer OBJECT is deliberately not carried: its closures would hold a stale
|
|
183
|
-
* connection, session id and ctx. See change: fix-auto-naming-reasoning-model.
|
|
184
|
-
*/
|
|
185
|
-
namerState?: PersistedNamerState;
|
|
186
|
-
/**
|
|
187
|
-
* Capture-once "was this pi dashboard-spawned?" boolean. Set on first bridge
|
|
188
|
-
* activation from `!!process.env.PI_DASHBOARD_SPAWN_TOKEN` BEFORE the token is
|
|
189
|
-
* scrubbed; persisted here so reload/reattach keeps the value after the env
|
|
190
|
-
* var is gone. See change: fix-spawn-token-env-leak.
|
|
191
|
-
*/
|
|
192
|
-
dashboardSpawned?: boolean;
|
|
193
|
-
/**
|
|
194
|
-
* Dashboard-attached OpenSpec change name persisted across reload so the
|
|
195
|
-
* `before_agent_start` injector keeps the fragment after `npm run reload`
|
|
196
|
-
* even before the server re-replays on `session_register`. `null`/absent
|
|
197
|
-
* when no change attached. See change: inject-session-context-into-agent.
|
|
198
|
-
*/
|
|
199
|
-
attachedChange?: string | null;
|
|
200
|
-
/**
|
|
201
|
-
* Graceful stop-after-turn latch (pi 0.72+). Set true on a `stop_after_turn`
|
|
202
|
-
* message; the next `turn_end` calls cachedCtx.shutdown() (fallback abort)
|
|
203
|
-
* and clears the flag. Idempotent: repeated sets while pending are no-ops.
|
|
204
|
-
* See change: adopt-pi-071-072-073-features.
|
|
205
|
-
*/
|
|
206
|
-
shouldStopAfterTurn?: boolean;
|
|
207
|
-
}
|
|
208
112
|
function getBridgeState(): BridgeState {
|
|
209
113
|
if (!(process as any)[BRIDGE_KEY]) {
|
|
210
114
|
(process as any)[BRIDGE_KEY] = {};
|
|
@@ -263,43 +167,44 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
263
167
|
const generation = (prev.generation ?? 0) + 1;
|
|
264
168
|
prev.generation = generation;
|
|
265
169
|
prev.pi = pi;
|
|
170
|
+
const inst = createInstance(pi, generation, prev);
|
|
266
171
|
/** Return true if this bridge instance is still the active one */
|
|
267
|
-
|
|
268
|
-
return getBridgeState().generation === generation;
|
|
269
|
-
}
|
|
172
|
+
const isActive = (): boolean => inst.isActive();
|
|
270
173
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
174
|
+
inst.sessionId = prev.sessionId ?? crypto.randomUUID();
|
|
175
|
+
inst.attachedChange = prev.attachedChange ?? null;
|
|
176
|
+
inst.sessionReady = false; // true after session_start has run
|
|
274
177
|
// Non-message usage drain cursor (usage / compaction / branch_summary
|
|
275
178
|
// entries → `usage_recorded`). Baselined at every session_start (init,
|
|
276
179
|
// reload, new/fork/resume) from the same snapshot as `usageSeed`; a
|
|
277
180
|
// reconnect never touches it. See change: count-non-message-usage.
|
|
278
181
|
const usageDrain = new UsageDrain();
|
|
182
|
+
inst.usageDrain = usageDrain;
|
|
279
183
|
function drainUsage(ctx: any): void {
|
|
280
|
-
if (!sessionReady) return;
|
|
281
|
-
drainUsageAndSend(usageDrain, (ctx ?? cachedCtx)?.sessionManager, (m) => connection.send(m));
|
|
184
|
+
if (!inst.sessionReady) return;
|
|
185
|
+
drainUsageAndSend(usageDrain, (ctx ?? inst.cachedCtx)?.sessionManager, (m) => inst.connection.send(m));
|
|
282
186
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
187
|
+
inst.drainUsage = drainUsage;
|
|
188
|
+
// → inst.lastSessionFile (BridgeInstance field; unset until assigned)
|
|
189
|
+
// → inst.lastSessionDir (BridgeInstance field; unset until assigned)
|
|
190
|
+
// → inst.lastFirstMessage (BridgeInstance field; unset until assigned)
|
|
286
191
|
// ctx.cwd is a guarded getter on ExtensionRunner that throws once the session
|
|
287
192
|
// is replaced (new/fork/resume/reload). Poll timers must read this cached copy
|
|
288
193
|
// instead of the captured ctx, or they crash the host after a session change.
|
|
289
194
|
// See change: fix-stale-ctx-cwd-crash.
|
|
290
|
-
|
|
291
|
-
|
|
195
|
+
// → inst.cachedCwd (BridgeInstance field; unset until assigned)
|
|
196
|
+
inst.pendingDefaultModel = null; // non-null if default model not yet applied (custom provider not ready)
|
|
292
197
|
|
|
293
198
|
/** Try to apply the default model from config. Returns the model string if not found (pending), null if applied or no default. */
|
|
294
199
|
function applyDefaultModel(): string | null {
|
|
295
200
|
const freshConfig = loadConfig();
|
|
296
|
-
if (!freshConfig.defaultModel || !cachedModelRegistry) return null;
|
|
201
|
+
if (!freshConfig.defaultModel || !inst.cachedModelRegistry) return null;
|
|
297
202
|
const slashIdx = freshConfig.defaultModel.indexOf("/");
|
|
298
203
|
if (slashIdx <= 0) return null;
|
|
299
204
|
const provider = freshConfig.defaultModel.slice(0, slashIdx);
|
|
300
205
|
const modelId = freshConfig.defaultModel.slice(slashIdx + 1);
|
|
301
206
|
try {
|
|
302
|
-
const found = cachedModelRegistry.find(provider, modelId);
|
|
207
|
+
const found = inst.cachedModelRegistry.find(provider, modelId);
|
|
303
208
|
if (found) {
|
|
304
209
|
(pi as any).setModel(found).then(() => {
|
|
305
210
|
// Apply the configured default thinking level alongside the default
|
|
@@ -316,6 +221,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
316
221
|
} catch { /* ignore */ }
|
|
317
222
|
return freshConfig.defaultModel; // not found yet — pending
|
|
318
223
|
}
|
|
224
|
+
inst.applyDefaultModel = applyDefaultModel;
|
|
319
225
|
|
|
320
226
|
/** Query pi-flows for available flows via synchronous event RPC */
|
|
321
227
|
function getFlowsList(): FlowInfo[] {
|
|
@@ -325,30 +231,35 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
325
231
|
} catch { /* ignore */ }
|
|
326
232
|
return (probe.flows as FlowInfo[] | undefined) ?? [];
|
|
327
233
|
}
|
|
234
|
+
inst.getFlowsList = getFlowsList;
|
|
328
235
|
|
|
329
236
|
/** Send flows_list message to the dashboard server */
|
|
330
237
|
function sendFlowsList() {
|
|
331
238
|
const flows = getFlowsList();
|
|
332
|
-
console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${sessionId.slice(0,8)}`);
|
|
333
|
-
connection.send({ type: "flows_list", sessionId, flows });
|
|
239
|
+
console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${inst.sessionId.slice(0,8)}`);
|
|
240
|
+
inst.connection.send({ type: "flows_list", sessionId: inst.sessionId, flows });
|
|
334
241
|
}
|
|
242
|
+
inst.sendFlowsList = sendFlowsList;
|
|
335
243
|
|
|
336
244
|
|
|
337
|
-
|
|
338
|
-
|
|
245
|
+
inst.heartbeatTimer = null;
|
|
246
|
+
inst.gitPollTimer = null;
|
|
339
247
|
// Adaptive async process-scan scheduler (replaces the fixed setInterval).
|
|
340
248
|
// See change: optimize-polling-hot-paths.
|
|
341
249
|
const polling = createPollingHolder();
|
|
250
|
+
inst.polling = polling;
|
|
342
251
|
// Per-session git tracker (facts cache, HEAD branch, async status probe);
|
|
343
252
|
// renewed at every session_start / session change. See change:
|
|
344
253
|
// optimize-polling-hot-paths.
|
|
345
|
-
|
|
346
|
-
const trackedPgids = new Set<number>();
|
|
254
|
+
inst.previousProcessPids = ""; // JSON-stringified PID set for diff
|
|
255
|
+
const trackedPgids = new Set<number>();
|
|
256
|
+
inst.trackedPgids = trackedPgids; // PGIDs captured during bash tool calls
|
|
347
257
|
// PIDs of subprocesses the bridge has spawned itself (dashboard server,
|
|
348
258
|
// RPC keeper). Threaded into `scanChildProcesses` as `excludedPgids` so
|
|
349
259
|
// bridge infrastructure never surfaces in the process list.
|
|
350
260
|
// See change: tighten-process-list-ux.
|
|
351
261
|
const selfSpawnedPgids = new Set<number>();
|
|
262
|
+
inst.selfSpawnedPgids = selfSpawnedPgids;
|
|
352
263
|
// Seed pi's OWN process-group id so pi-self + same-group plugin/MCP
|
|
353
264
|
// sidecars (context-mode bun, etc.) never enter `trackedPgids` or the
|
|
354
265
|
// process list. Cached one-shot `ps` lookup; no-op on Windows.
|
|
@@ -379,10 +290,12 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
379
290
|
getBridgeState().timers!.push(timer as unknown as ReturnType<typeof setInterval>);
|
|
380
291
|
return timer;
|
|
381
292
|
};
|
|
293
|
+
inst.setRegisteredTimeout = setRegisteredTimeout;
|
|
382
294
|
const clearRegisteredTimeout = (timer: ReturnType<typeof setTimeout>): void => {
|
|
383
295
|
clearTimeout(timer);
|
|
384
296
|
unregisterTimer(timer);
|
|
385
297
|
};
|
|
298
|
+
inst.clearRegisteredTimeout = clearRegisteredTimeout;
|
|
386
299
|
const registerDisposable = (fn: () => void): void => {
|
|
387
300
|
(getBridgeState().disposables ??= []).push(fn);
|
|
388
301
|
};
|
|
@@ -390,6 +303,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
390
303
|
// and empties the list, and this incarnation may start a new session after it.
|
|
391
304
|
const disposePolling = () => polling.disposeAll();
|
|
392
305
|
const ensurePollingDisposable = () => ensureDisposable(getBridgeState(), disposePolling);
|
|
306
|
+
inst.ensurePollingDisposable = ensurePollingDisposable;
|
|
393
307
|
ensurePollingDisposable();
|
|
394
308
|
/** Dispose the previous tracker and start a fresh one for the incoming session. */
|
|
395
309
|
function renewGitTracker(): GitTracker {
|
|
@@ -402,6 +316,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
402
316
|
clearTimer: clearRegisteredTimeout,
|
|
403
317
|
}));
|
|
404
318
|
}
|
|
319
|
+
inst.renewGitTracker = renewGitTracker;
|
|
405
320
|
const prStatus: PrStatusScheduler = createPrStatusScheduler({
|
|
406
321
|
probe: (cwd) => git.prStatusAsync({ cwd }),
|
|
407
322
|
// A reload starts a new bridge incarnation; the old scheduler must not
|
|
@@ -414,26 +329,27 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
414
329
|
setTimer: setRegisteredTimeout,
|
|
415
330
|
clearTimer: clearRegisteredTimeout,
|
|
416
331
|
});
|
|
332
|
+
inst.prStatus = prStatus;
|
|
417
333
|
let lastGitWorktreeJson: string | undefined; // see change: add-worktree-spawn-dialog
|
|
418
334
|
let lastGitStatusJson: string | undefined; // see change: add-session-uncommitted-indicator-and-commit
|
|
419
335
|
let lastCwdMissing: boolean | undefined; // see change: add-worktree-lifecycle-actions
|
|
420
|
-
|
|
336
|
+
// → inst.lastSessionName (BridgeInstance field; unset until assigned)
|
|
421
337
|
// ── add-auto-session-naming ────────────────────────────────────────────
|
|
422
338
|
// Global auto-naming toggle, relayed by the server via `preferences_update`.
|
|
423
339
|
// Default true so a bridge that registers before the first push still names.
|
|
424
|
-
|
|
425
|
-
|
|
340
|
+
inst.autoNameSessions = true;
|
|
341
|
+
// → inst.autoNamer (BridgeInstance field; unset until assigned)
|
|
426
342
|
// The namer's durable state set is carried across reload as VALUES, never as
|
|
427
343
|
// the namer object: its closures would retain a stale connection, session id
|
|
428
344
|
// and ctx. See change: fix-auto-naming-reasoning-model (design D7).
|
|
429
|
-
|
|
345
|
+
inst.namerState = prev.namerState;
|
|
430
346
|
// Lazily-loaded pi-ai streamSimple (null = load attempted and failed).
|
|
431
347
|
let piAiStreamSimple: StreamSimpleFn | null | undefined;
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
348
|
+
inst.cachedHasUI = prev.hasUI;
|
|
349
|
+
inst.cachedModelRegistry = prev.modelRegistry;
|
|
350
|
+
inst.cachedCtx = prev.ctx;
|
|
351
|
+
// → inst.lastModel (BridgeInstance field; unset until assigned)
|
|
352
|
+
// → inst.lastThinkingLevel (BridgeInstance field; unset until assigned)
|
|
437
353
|
let hasRegisteredOnce = false; // see change: reattach-move-to-front
|
|
438
354
|
// Capture-once "was this pi dashboard-spawned?" boolean, read BEFORE the
|
|
439
355
|
// single-use `PI_DASHBOARD_SPAWN_TOKEN` is scrubbed on first register.
|
|
@@ -441,9 +357,12 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
441
357
|
// this module after the env was scrubbed — keeps the correct value instead
|
|
442
358
|
// of regressing to false. See change: fix-spawn-token-env-leak.
|
|
443
359
|
if (prev.dashboardSpawned === undefined) {
|
|
444
|
-
|
|
360
|
+
// Reads AND scrubs the token here (not at first register): nested pi the
|
|
361
|
+
// agent starts later never inherits it. See change: mirror-dashboard-trust-to-pi.
|
|
362
|
+
prev.dashboardSpawned = captureSpawnTokenAtActivation();
|
|
445
363
|
}
|
|
446
364
|
const dashboardSpawned = prev.dashboardSpawned;
|
|
365
|
+
inst.dashboardSpawned = dashboardSpawned;
|
|
447
366
|
|
|
448
367
|
// Capture the cwd at bridge ACTIVATION (module scope). `project_trust` fires
|
|
449
368
|
// during resource-loader reload — BEFORE `session_start` reaches extension
|
|
@@ -451,8 +370,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
451
370
|
// when the trust handler runs. For a fresh headless spawn this IS the
|
|
452
371
|
// dashboard-provided spawn cwd. See change: adopt-pi-074-080-features (A.3).
|
|
453
372
|
const activationCwd = process.cwd();
|
|
373
|
+
inst.activationCwd = activationCwd;
|
|
454
374
|
|
|
455
|
-
|
|
375
|
+
// → inst.promptBus (BridgeInstance field; unset until assigned)
|
|
456
376
|
|
|
457
377
|
// Provider-retry synthesis tracker. pi's ExtensionAPI does not expose
|
|
458
378
|
// `auto_retry_*` events, so the bridge synthesizes them by OBSERVING pi's
|
|
@@ -461,35 +381,39 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
461
381
|
// are sourced READ-ONLY from pi's retry settings for the display countdown;
|
|
462
382
|
// the bridge never writes them. See change: retry-forever-with-stop-control.
|
|
463
383
|
const retryTracker = new RetryTracker(readPiRetrySettings({ cwd: activationCwd }));
|
|
384
|
+
inst.retryTracker = retryTracker;
|
|
464
385
|
// Empty-actionable-turn guard: when a terminal turn is a clean-but-empty
|
|
465
386
|
// `stop` (thinking-only, no text, no tool call), continue-or-surface instead
|
|
466
387
|
// of idling silently. Provider-agnostic. See change:
|
|
467
388
|
// fix-gemini-subagent-silent-tool-schema-failure.
|
|
468
389
|
const guardConfig = resolveGuardConfig();
|
|
469
390
|
const emptyActionableGuard = new EmptyActionableGuard(guardConfig.mode, guardConfig.retryCap);
|
|
391
|
+
inst.emptyActionableGuard = emptyActionableGuard;
|
|
470
392
|
// Abort latch: keeps a user abort latched so a provider backoff that
|
|
471
393
|
// outlives the 2 s persistent-abort scheduler still stops pi's retry.
|
|
472
394
|
// Set on abort; cleared on a new user prompt or terminal agent_end; honored
|
|
473
395
|
// on every observed resumption of the aborted turn. See change:
|
|
474
396
|
// unify-error-retry-lifecycle (design D3b).
|
|
475
397
|
const abortLatch = new AbortLatch();
|
|
398
|
+
inst.abortLatch = abortLatch;
|
|
476
399
|
|
|
477
400
|
// Subagent live-detail reliability: retain subagent frames emitted while the
|
|
478
401
|
// bridge is not ready (buffer-and-flush on re-register, D1) and keep the
|
|
479
402
|
// latest snapshot of each running subagent for the resync responder (D2).
|
|
480
403
|
// See change: fix-subagent-live-detail-reliability.
|
|
481
404
|
const subagentFrameBuffer = new SubagentFrameBuffer();
|
|
405
|
+
inst.subagentFrameBuffer = subagentFrameBuffer;
|
|
482
406
|
|
|
483
407
|
// Dashboard MCP server registration with pi's built-in MCP. The bearer lives
|
|
484
408
|
// only in this registrar and pi's registration — never in process.env.
|
|
485
409
|
// See change: migrate-mcp-to-pi-builtin (D1).
|
|
486
410
|
const mcpRegistrar = createMcpDashboardRegistrar({
|
|
487
411
|
pi: pi as unknown as McpRegistrationApi,
|
|
488
|
-
sessionId: () => sessionId,
|
|
412
|
+
sessionId: () => inst.sessionId,
|
|
489
413
|
reportUnavailable: (reason) => {
|
|
490
|
-
connection.send({
|
|
414
|
+
inst.connection.send({
|
|
491
415
|
type: "plugin_pi_message",
|
|
492
|
-
sessionId,
|
|
416
|
+
sessionId: inst.sessionId,
|
|
493
417
|
pluginId: "mcp-server",
|
|
494
418
|
messageType: "mcp/registration-unavailable",
|
|
495
419
|
payload: { reason },
|
|
@@ -497,6 +421,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
497
421
|
},
|
|
498
422
|
log: console,
|
|
499
423
|
});
|
|
424
|
+
inst.mcpRegistrar = mcpRegistrar;
|
|
500
425
|
|
|
501
426
|
// Bound the Agent-tick rate on the `tool_execution_update` carrier. That
|
|
502
427
|
// carrier has no throttle anywhere on its path, so its rate is the
|
|
@@ -512,9 +437,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
512
437
|
// See change: reduce-bridge-tick-bandwidth (D2/D3/D4).
|
|
513
438
|
const subagentTickThrottle = new SubagentTickThrottle<unknown>({
|
|
514
439
|
windowMs: loadConfig().subagentTickThrottleMs,
|
|
515
|
-
send: (msg) => connection.send(msg),
|
|
516
|
-
canSend: (frameSessionId) => isActive() && sessionReady && frameSessionId === sessionId,
|
|
440
|
+
send: (msg) => inst.connection.send(msg),
|
|
441
|
+
canSend: (frameSessionId) => isActive() && inst.sessionReady && frameSessionId === inst.sessionId,
|
|
517
442
|
});
|
|
443
|
+
inst.subagentTickThrottle = subagentTickThrottle;
|
|
518
444
|
|
|
519
445
|
// Bound the bridge's per-token streaming cost. pi's `message_update` carries
|
|
520
446
|
// the FULL accumulated text snapshot, so forwarding each one synchronously
|
|
@@ -533,11 +459,11 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
533
459
|
// See change: coalesce-bridge-message-update-snapshots (D1–D7).
|
|
534
460
|
const coalescer = new MessageUpdateCoalescer<Record<string, unknown>>({
|
|
535
461
|
windowMs: COALESCE_WINDOW_MS,
|
|
536
|
-
isActive: () => isActive() && sessionReady,
|
|
462
|
+
isActive: () => isActive() && inst.sessionReady,
|
|
537
463
|
send: (event) => {
|
|
538
|
-
if (!isActive() || !sessionReady) return;
|
|
464
|
+
if (!isActive() || !inst.sessionReady) return;
|
|
539
465
|
maybeInlineAssistantImages(event);
|
|
540
|
-
connection.send(mapEventToProtocol(sessionId, event));
|
|
466
|
+
inst.connection.send(mapEventToProtocol(inst.sessionId, event));
|
|
541
467
|
},
|
|
542
468
|
setTimer: (fn, ms) => {
|
|
543
469
|
const timer = setTimeout(fn, ms);
|
|
@@ -551,6 +477,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
551
477
|
if (index !== -1) timers!.splice(index, 1);
|
|
552
478
|
},
|
|
553
479
|
});
|
|
480
|
+
inst.coalescer = coalescer;
|
|
554
481
|
|
|
555
482
|
// Per-message generation for the coalescing barrier. Distinct from the
|
|
556
483
|
// bridge-instance `generation` above, which only changes on `initBridge` and
|
|
@@ -564,13 +491,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
564
491
|
// generation of its own — an update can only be stamped with the counter's
|
|
565
492
|
// current value.
|
|
566
493
|
// See change: coalesce-bridge-message-update-snapshots (D4).
|
|
567
|
-
|
|
494
|
+
inst.assistantMessageGen = 0;
|
|
568
495
|
|
|
569
496
|
/**
|
|
570
497
|
* Identity of a message for the barrier: `<gen>:<role>:<timestamp>`.
|
|
571
498
|
* `message.id` is unusable — pi stamps it only at post-handler persistence.
|
|
572
499
|
*/
|
|
573
500
|
const messageKeyOf = (gen: number, message: unknown): string => coalescer.keyOf(gen, message);
|
|
501
|
+
inst.messageKeyOf = messageKeyOf;
|
|
574
502
|
|
|
575
503
|
// Bridge-owned queue structures with TWO different ownership models:
|
|
576
504
|
//
|
|
@@ -582,7 +510,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
582
510
|
// • bridgeFollowUp (BRIDGE-OWNED BUFFER) — authoritative store for
|
|
583
511
|
// dashboard-originated follow-up entries while the agent is streaming.
|
|
584
512
|
// Pi never sees these entries until `drainFollowupQueue()` ships them
|
|
585
|
-
// one-at-a-time on `
|
|
513
|
+
// one-at-a-time on `agent_settled`. Mutated by `bufferFollowupSend`,
|
|
586
514
|
// `drainFollowupQueue`, and the four mutation handlers (edit / remove /
|
|
587
515
|
// promote / clear).
|
|
588
516
|
//
|
|
@@ -597,28 +525,30 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
597
525
|
// turn_end for mutation UI to matter; user direction).
|
|
598
526
|
//
|
|
599
527
|
// See change: rework-mid-turn-prompt-queue (spec mid-turn-prompt-queue).
|
|
600
|
-
|
|
528
|
+
inst.bridgeSteering = [];
|
|
601
529
|
const bridgeFollowUp = createFollowupBuffer();
|
|
530
|
+
inst.bridgeFollowUp = bridgeFollowUp;
|
|
602
531
|
function emitQueueUpdate(): void {
|
|
603
|
-
if (!isActive() || !sessionReady) return;
|
|
604
|
-
connection.send({
|
|
532
|
+
if (!isActive() || !inst.sessionReady) return;
|
|
533
|
+
inst.connection.send({
|
|
605
534
|
type: "queue_update",
|
|
606
|
-
sessionId,
|
|
607
|
-
steering: [...bridgeSteering],
|
|
535
|
+
sessionId: inst.sessionId,
|
|
536
|
+
steering: [...inst.bridgeSteering],
|
|
608
537
|
// Views only: text + image COUNT. Image bytes never cross the wire.
|
|
609
538
|
followUp: bridgeFollowUp.views(),
|
|
610
539
|
});
|
|
611
540
|
}
|
|
541
|
+
inst.emitQueueUpdate = emitQueueUpdate;
|
|
612
542
|
/**
|
|
613
543
|
* Surface a refusal to the user. Every follow-up refusal path emits one:
|
|
614
544
|
* a bare `console.warn` is invisible in the dashboard, which is the same
|
|
615
545
|
* defect class this change exists to fix (design D4).
|
|
616
546
|
*/
|
|
617
547
|
function sendCommandFeedback(command: string, message: string): void {
|
|
618
|
-
if (!isActive() || !sessionReady) return;
|
|
619
|
-
connection.send({
|
|
548
|
+
if (!isActive() || !inst.sessionReady) return;
|
|
549
|
+
inst.connection.send({
|
|
620
550
|
type: "event_forward",
|
|
621
|
-
sessionId,
|
|
551
|
+
sessionId: inst.sessionId,
|
|
622
552
|
event: {
|
|
623
553
|
eventType: "command_feedback",
|
|
624
554
|
timestamp: Date.now(),
|
|
@@ -626,12 +556,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
626
556
|
},
|
|
627
557
|
});
|
|
628
558
|
}
|
|
559
|
+
inst.sendCommandFeedback = sendCommandFeedback;
|
|
629
560
|
function recordSteerSent(text: string): void {
|
|
630
561
|
// Only record when the agent was actually streaming at send time. Idle
|
|
631
562
|
// sends start a new turn directly — pi doesn't queue them, so the
|
|
632
563
|
// shadow queue must not show a chip. See change: add-followup-edit-and-steer-cancel.
|
|
633
564
|
if (!getBridgeState().isAgentStreaming) return;
|
|
634
|
-
bridgeSteering.push(text);
|
|
565
|
+
inst.bridgeSteering.push(text);
|
|
635
566
|
emitQueueUpdate();
|
|
636
567
|
}
|
|
637
568
|
/**
|
|
@@ -677,109 +608,57 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
677
608
|
}
|
|
678
609
|
emitQueueUpdate();
|
|
679
610
|
}
|
|
611
|
+
let isDraining = false;
|
|
680
612
|
/**
|
|
681
|
-
* Drain
|
|
682
|
-
*
|
|
613
|
+
* Drain the bridge-owned follow-up buffer: on `agent_settled` (and from
|
|
614
|
+
* `enqueueSystemFollowup`), pop the front of `bridgeFollowUp` and ship it to
|
|
615
|
+
* pi as a fresh-turn `sendUserMessage` (no `deliverAs`). Pop-before-send
|
|
683
616
|
* invariant: the entry is shifted off the buffer BEFORE the pi call. If
|
|
684
617
|
* `pi.sendUserMessage` throws, the entry is LOST by design (double-shipping
|
|
685
618
|
* is worse than dropping).
|
|
686
619
|
*
|
|
687
|
-
* Gates (
|
|
688
|
-
* non-empty buffer.
|
|
620
|
+
* Gates (the pure sequence in `followup-drain.ts`): re-entrancy lock (here),
|
|
621
|
+
* non-empty buffer, pi.hasPendingMessages, idle. A false `isIdle()` returns
|
|
622
|
+
* without popping and without re-scheduling: pi clears its run-active flag
|
|
623
|
+
* BEFORE it emits `agent_settled`, so a drain scheduled from the settle sees
|
|
624
|
+
* an idle session unless another run already started, and then the next
|
|
625
|
+
* `agent_settled` drains. One entry per settle — the next settle re-enters
|
|
689
626
|
* this function for the next entry (natural serialization).
|
|
690
627
|
*
|
|
691
|
-
*
|
|
692
|
-
|
|
693
|
-
let isDraining = false;
|
|
694
|
-
/**
|
|
695
|
-
* Drain the bridge-owned follow-up buffer by handing one entry to pi
|
|
696
|
-
* as a fresh-turn `sendUserMessage` (no `deliverAs`).
|
|
697
|
-
*
|
|
698
|
-
* Why no `deliverAs`: pi's agent loop calls `getFollowUpMessages()` only
|
|
699
|
-
* while the loop is active. Once `agent_end` fires and the loop's
|
|
700
|
-
* `executor` returns, pi's `finishRun()` flips `isStreaming = false` and
|
|
701
|
-
* `activeRun = undefined`. After that point, anything queued into pi's
|
|
702
|
-
* internal followUpQueue NEVER drains — pi has stopped reading it.
|
|
703
|
-
* (Verified at pi-coding-agent pi-agent-core/agent.js: `finishRun()` clears
|
|
704
|
-
* `isStreaming` + `activeRun`, and `getFollowUpMessages` is only supplied to
|
|
705
|
-
* the loop while a run is active. Re-verified against pi 0.84.1 — behaviour
|
|
706
|
-
* unchanged, line numbers moved. See change: update-pi-core-0-84-adopt-apis.)
|
|
628
|
+
* Why no `deliverAs`: once the run has settled pi no longer reads its
|
|
629
|
+
* follow-up queue, so a `{deliverAs:"followUp"}` entry would never drain.
|
|
707
630
|
*
|
|
708
|
-
*
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
* - once truly idle, sendUserMessage(entry) starts a fresh turn
|
|
712
|
-
*
|
|
713
|
-
* See change: rework-mid-turn-prompt-queue (post-smoke fix #3).
|
|
631
|
+
* See changes: rework-mid-turn-prompt-queue (design.md D2),
|
|
632
|
+
* update-pi-core-1-3-adopt-apis (design D4: agent_settled trigger, no
|
|
633
|
+
* idle-retry loop).
|
|
714
634
|
*/
|
|
715
|
-
function drainFollowupQueue(
|
|
635
|
+
function drainFollowupQueue(): void {
|
|
716
636
|
if (isDraining) return;
|
|
717
|
-
if (bridgeFollowUp.length === 0) return;
|
|
718
|
-
|
|
719
|
-
// TUI-coexistence gate: if pi has its own queued items (TUI alt+enter
|
|
720
|
-
// sends), wait for pi to drain those first via its own loop. The
|
|
721
|
-
// method lives on `ctx` (verified at pi 0.76.0 extensions/types.d.ts:227).
|
|
722
|
-
if (typeof cachedCtx?.hasPendingMessages === "function") {
|
|
723
|
-
try {
|
|
724
|
-
if (cachedCtx.hasPendingMessages()) return;
|
|
725
|
-
} catch { /* probe failure non-fatal */ }
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
// Idle gate: pi flips isStreaming=false in finishRun() AFTER the
|
|
729
|
-
// executor returns from runAgentLoop. queueMicrotask runs inside the
|
|
730
|
-
// executor (too early), so we use setTimeout to escape the loop AND
|
|
731
|
-
// poll for isIdle with bounded retries.
|
|
732
|
-
const idle = (() => {
|
|
733
|
-
try { return cachedCtx?.isIdle?.() === true; } catch { return false; }
|
|
734
|
-
})();
|
|
735
|
-
if (!idle) {
|
|
736
|
-
if (retryCount < 20) { // ~2s total (20 × 100ms)
|
|
737
|
-
setTimeout(() => drainFollowupQueue(retryCount + 1), 100);
|
|
738
|
-
} else {
|
|
739
|
-
console.warn("[dashboard] drainFollowupQueue: pi never idled after 2s; giving up");
|
|
740
|
-
}
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
|
|
744
637
|
isDraining = true;
|
|
745
638
|
try {
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
// pi.sendUserMessage starts a new run via Agent.prompt().
|
|
753
|
-
//
|
|
754
|
-
// NO send options, deliberately: `{deliverAs:"followUp"}` here is a
|
|
755
|
-
// known-broken path (pi has already exited `getFollowUpMessages()`, so
|
|
756
|
-
// the entry would never drain). `buildUserMessageContent` supplies the
|
|
757
|
-
// content shape WITHOUT inheriting the steer/idle send options.
|
|
758
|
-
// See change: fix-bridge-followup-image-drop (design D6).
|
|
759
|
-
try {
|
|
760
|
-
(pi.sendUserMessage as any)(buildUserMessageContent(entry.text, entry.images));
|
|
761
|
-
} catch (err) {
|
|
762
|
-
console.warn(
|
|
763
|
-
"[dashboard] drainFollowupQueue: pi.sendUserMessage threw — entry lost:",
|
|
764
|
-
err,
|
|
765
|
-
);
|
|
766
|
-
// INTENTIONAL: no re-push. Double-shipping is worse than dropping.
|
|
767
|
-
}
|
|
639
|
+
drainOneFollowup({
|
|
640
|
+
buffer: bridgeFollowUp,
|
|
641
|
+
ctx: inst.cachedCtx,
|
|
642
|
+
emitQueueUpdate,
|
|
643
|
+
sendUserMessage: (content) => (pi.sendUserMessage as any)(content),
|
|
644
|
+
});
|
|
768
645
|
} finally {
|
|
769
646
|
isDraining = false;
|
|
770
647
|
}
|
|
771
648
|
}
|
|
649
|
+
inst.drainFollowupQueue = drainFollowupQueue;
|
|
772
650
|
/**
|
|
773
651
|
* System-originated follow-up enqueue. Unlike `bufferFollowupSend`, this
|
|
774
652
|
* does NOT gate on `isAgentStreaming` — it is called by plugin bridges
|
|
775
|
-
* (via the `dashboard:enqueue-followup` pi.event) AFTER
|
|
776
|
-
* fired, by which point `isAgentStreaming` is already `false`
|
|
777
|
-
* streaming gate would silently discard the entry.
|
|
653
|
+
* (via the `dashboard:enqueue-followup` pi.event) AFTER the run's terminal
|
|
654
|
+
* events have fired, by which point `isAgentStreaming` is already `false`
|
|
655
|
+
* and the streaming gate would silently discard the entry.
|
|
778
656
|
*
|
|
779
657
|
* Routes through the SINGLE existing `drainFollowupQueue` path so a
|
|
780
658
|
* plugin-requested continuation cannot race or double-inject against
|
|
781
659
|
* user follow-ups: both share the one `bridgeFollowUp` buffer and the
|
|
782
|
-
* `isDraining` lock, shipping one entry per
|
|
660
|
+
* `isDraining` lock, shipping one entry per settle. It ships at once when
|
|
661
|
+
* the session is idle, otherwise on the next `agent_settled`.
|
|
783
662
|
*
|
|
784
663
|
* Text-only by design — the plugin path has no image source — so it wraps
|
|
785
664
|
* into a `{ text }` entry. Subject to BOTH buffer bounds, with the refusal
|
|
@@ -787,9 +666,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
787
666
|
* nudge is a lost plugin continuation, and attributing it to `send_prompt`
|
|
788
667
|
* would misreport a programmatic refusal as a user action (design D8).
|
|
789
668
|
*
|
|
790
|
-
* Schedules `drainFollowupQueue(
|
|
669
|
+
* Schedules `drainFollowupQueue()` via
|
|
791
670
|
* `setTimeout(…, 0)` so the drain re-runs AFTER the async judge verdict
|
|
792
|
-
* resolves (the bridge's own `
|
|
671
|
+
* resolves (the bridge's own `agent_settled` drain already ran against an
|
|
793
672
|
* empty buffer by then).
|
|
794
673
|
*
|
|
795
674
|
* Generic infrastructure — not goal-specific. See change:
|
|
@@ -804,8 +683,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
804
683
|
return;
|
|
805
684
|
}
|
|
806
685
|
emitQueueUpdate();
|
|
807
|
-
setTimeout(() => drainFollowupQueue(
|
|
686
|
+
setTimeout(() => drainFollowupQueue(), 0);
|
|
808
687
|
}
|
|
688
|
+
inst.enqueueSystemFollowup = enqueueSystemFollowup;
|
|
809
689
|
/**
|
|
810
690
|
* Mirror of pi's `_getUserMessageText` (pi-coding-agent agent-session.js).
|
|
811
691
|
* Used by the per-entry shadow-queue drain matcher in the `message_start`
|
|
@@ -822,6 +702,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
822
702
|
.map((c: any) => c.text ?? "")
|
|
823
703
|
.join("");
|
|
824
704
|
}
|
|
705
|
+
inst.extractUserMessageText = extractUserMessageText;
|
|
825
706
|
|
|
826
707
|
// rewriteFollowupQueue removed. The clear-then-replay strategy was broken
|
|
827
708
|
// by construction (pi.clearFollowUpQueue is not on the ExtensionAPI, so the
|
|
@@ -830,16 +711,17 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
830
711
|
|
|
831
712
|
/** Forward a synthesized auto_retry_* event using the standard event_forward shape. */
|
|
832
713
|
const sendSyntheticRetryEvent = (eventType: string, data: Record<string, unknown>): void => {
|
|
833
|
-
if (!isActive() || !sessionReady) return;
|
|
714
|
+
if (!isActive() || !inst.sessionReady) return;
|
|
834
715
|
// A synthesized retry event renders as a chat row, so a parked snapshot must
|
|
835
716
|
// still land first. See change: coalesce-bridge-message-update-snapshots (D5).
|
|
836
717
|
coalescer.flush();
|
|
837
|
-
connection.send({
|
|
718
|
+
inst.connection.send({
|
|
838
719
|
type: "event_forward",
|
|
839
|
-
sessionId,
|
|
720
|
+
sessionId: inst.sessionId,
|
|
840
721
|
event: { eventType, timestamp: Date.now(), data },
|
|
841
722
|
});
|
|
842
723
|
};
|
|
724
|
+
inst.sendSyntheticRetryEvent = sendSyntheticRetryEvent;
|
|
843
725
|
|
|
844
726
|
// ── Per-message entry id tracking (for fix-per-message-fork) ──
|
|
845
727
|
// Pi 0.69+ awaits extension handlers BEFORE sessionManager.appendMessage runs,
|
|
@@ -854,11 +736,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
854
736
|
// back-fill user-message ChatMessage.entryId.
|
|
855
737
|
// See change: fix-per-message-fork.
|
|
856
738
|
const idByMessage = new WeakMap<object, string>();
|
|
739
|
+
inst.idByMessage = idByMessage;
|
|
857
740
|
const pendingNonces = new WeakMap<object, string>();
|
|
741
|
+
inst.pendingNonces = pendingNonces;
|
|
858
742
|
let nonceCounter = 0;
|
|
859
743
|
const nextNonce = (): string => `n-${++nonceCounter}-${Date.now()}`;
|
|
860
|
-
|
|
861
|
-
|
|
744
|
+
inst.nextNonce = nextNonce;
|
|
745
|
+
inst.appendMessageWrapped = false;
|
|
746
|
+
inst.lastWrappedSm = null;
|
|
862
747
|
|
|
863
748
|
// ---------------------------------------------------------------------
|
|
864
749
|
// Markdown-image inliner state (chat-markdown-local-images-and-math).
|
|
@@ -876,6 +761,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
876
761
|
}
|
|
877
762
|
return s;
|
|
878
763
|
}
|
|
764
|
+
inst.getEmittedAssetHashes = getEmittedAssetHashes;
|
|
879
765
|
|
|
880
766
|
/**
|
|
881
767
|
* Synchronous fs probe + read for the inliner. Wraps `fs.statSync` /
|
|
@@ -899,6 +785,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
899
785
|
return { ok: false, kind: "EOTHER" };
|
|
900
786
|
}
|
|
901
787
|
}
|
|
788
|
+
inst.inlinerReadFile = inlinerReadFile;
|
|
902
789
|
|
|
903
790
|
/**
|
|
904
791
|
* Apply the markdown-image inliner to an assistant message_update /
|
|
@@ -914,8 +801,8 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
914
801
|
if (msg.role !== "assistant") return;
|
|
915
802
|
// Use the *current* live cwd if available; fall back to the bridge
|
|
916
803
|
// process cwd. The inliner resolves relative `./pic.png` against this.
|
|
917
|
-
const cwd = (cachedCtx?.cwd as string | undefined) ?? process.cwd();
|
|
918
|
-
const alreadyEmitted = getEmittedAssetHashes(sessionId);
|
|
804
|
+
const cwd = (inst.cachedCtx?.cwd as string | undefined) ?? process.cwd();
|
|
805
|
+
const alreadyEmitted = getEmittedAssetHashes(inst.sessionId);
|
|
919
806
|
const allAssets: { hash: string; mimeType: string; data: string }[] = [];
|
|
920
807
|
|
|
921
808
|
const rewriteOne = (text: string): string => {
|
|
@@ -940,15 +827,16 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
940
827
|
|
|
941
828
|
// Send each new asset BEFORE the (rewritten) message event lands.
|
|
942
829
|
for (const a of allAssets) {
|
|
943
|
-
connection.send({
|
|
830
|
+
inst.connection.send({
|
|
944
831
|
type: "asset_register",
|
|
945
|
-
sessionId,
|
|
832
|
+
sessionId: inst.sessionId,
|
|
946
833
|
hash: a.hash,
|
|
947
834
|
mimeType: a.mimeType,
|
|
948
835
|
data: a.data,
|
|
949
836
|
});
|
|
950
837
|
}
|
|
951
838
|
}
|
|
839
|
+
inst.maybeInlineAssistantImages = maybeInlineAssistantImages;
|
|
952
840
|
|
|
953
841
|
/**
|
|
954
842
|
* Wrap ctx.sessionManager.appendMessage once per session so that when pi
|
|
@@ -959,7 +847,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
959
847
|
const sm = ctx?.sessionManager;
|
|
960
848
|
if (!sm || typeof sm.appendMessage !== "function") return;
|
|
961
849
|
// Re-wrap when sessionManager identity changes (session replacement).
|
|
962
|
-
if (sm === lastWrappedSm && appendMessageWrapped) return;
|
|
850
|
+
if (sm === inst.lastWrappedSm && inst.appendMessageWrapped) return;
|
|
963
851
|
const original = sm.appendMessage.bind(sm);
|
|
964
852
|
sm.appendMessage = (msg: any, ...rest: any[]) => {
|
|
965
853
|
const result = original(msg, ...rest);
|
|
@@ -967,13 +855,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
967
855
|
if (msg && typeof msg === "object" && typeof msg.id === "string") {
|
|
968
856
|
idByMessage.set(msg as object, msg.id);
|
|
969
857
|
const nonce = pendingNonces.get(msg as object);
|
|
970
|
-
if (nonce && sessionReady && isActive()) {
|
|
858
|
+
if (nonce && inst.sessionReady && isActive()) {
|
|
971
859
|
const ev = {
|
|
972
860
|
type: "entry_persisted",
|
|
973
861
|
entryId: msg.id,
|
|
974
862
|
nonce,
|
|
975
863
|
};
|
|
976
|
-
connection.send(mapEventToProtocol(sessionId, ev));
|
|
864
|
+
inst.connection.send(mapEventToProtocol(inst.sessionId, ev));
|
|
977
865
|
pendingNonces.delete(msg as object);
|
|
978
866
|
}
|
|
979
867
|
}
|
|
@@ -982,12 +870,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
982
870
|
}
|
|
983
871
|
return result;
|
|
984
872
|
};
|
|
985
|
-
lastWrappedSm = sm;
|
|
986
|
-
appendMessageWrapped = true;
|
|
873
|
+
inst.lastWrappedSm = sm;
|
|
874
|
+
inst.appendMessageWrapped = true;
|
|
987
875
|
}
|
|
876
|
+
inst.wrapAppendMessageForCtx = wrapAppendMessageForCtx;
|
|
988
877
|
|
|
989
|
-
|
|
990
|
-
|
|
878
|
+
inst.customPersistenceWrapped = false;
|
|
879
|
+
inst.customWrappedSm = null;
|
|
991
880
|
|
|
992
881
|
/**
|
|
993
882
|
* Wrap the sessionManager custom-persistence methods so the bridge can
|
|
@@ -1012,7 +901,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1012
901
|
return;
|
|
1013
902
|
}
|
|
1014
903
|
// Re-wrap when sessionManager identity changes (session replacement).
|
|
1015
|
-
if (sm === customWrappedSm && customPersistenceWrapped) return;
|
|
904
|
+
if (sm === inst.customWrappedSm && inst.customPersistenceWrapped) return;
|
|
1016
905
|
const origMessage = sm.appendCustomMessageEntry.bind(sm);
|
|
1017
906
|
sm.appendCustomMessageEntry = (customType: any, content: any, display: any, details: any) => {
|
|
1018
907
|
const entryId = origMessage(customType, content, display, details);
|
|
@@ -1021,10 +910,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1021
910
|
coalescer.flush();
|
|
1022
911
|
try {
|
|
1023
912
|
const forward = toCustomMessageForward({ customType, content, display, details, entryId });
|
|
1024
|
-
if (forward && sessionReady && isActive()) {
|
|
1025
|
-
connection.send({
|
|
913
|
+
if (forward && inst.sessionReady && isActive()) {
|
|
914
|
+
inst.connection.send({
|
|
1026
915
|
type: "event_forward",
|
|
1027
|
-
sessionId,
|
|
916
|
+
sessionId: inst.sessionId,
|
|
1028
917
|
event: {
|
|
1029
918
|
eventType: "message_end",
|
|
1030
919
|
timestamp: Date.now(),
|
|
@@ -1044,10 +933,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1044
933
|
coalescer.flush();
|
|
1045
934
|
try {
|
|
1046
935
|
const forward = toCustomEntryForward({ type: "custom", customType, data, id: entryId });
|
|
1047
|
-
if (forward && sessionReady && isActive()) {
|
|
1048
|
-
connection.send({
|
|
936
|
+
if (forward && inst.sessionReady && isActive()) {
|
|
937
|
+
inst.connection.send({
|
|
1049
938
|
type: "event_forward",
|
|
1050
|
-
sessionId,
|
|
939
|
+
sessionId: inst.sessionId,
|
|
1051
940
|
event: {
|
|
1052
941
|
eventType: "custom_entry",
|
|
1053
942
|
timestamp: Date.now(),
|
|
@@ -1060,9 +949,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1060
949
|
}
|
|
1061
950
|
return entryId;
|
|
1062
951
|
};
|
|
1063
|
-
customWrappedSm = sm;
|
|
1064
|
-
customPersistenceWrapped = true;
|
|
952
|
+
inst.customWrappedSm = sm;
|
|
953
|
+
inst.customPersistenceWrapped = true;
|
|
1065
954
|
}
|
|
955
|
+
inst.wrapCustomPersistenceForCtx = wrapCustomPersistenceForCtx;
|
|
1066
956
|
|
|
1067
957
|
/** Wrap a callback so errors log instead of crashing the host pi agent. */
|
|
1068
958
|
function safe<T extends (...args: any[]) => any>(fn: T): T {
|
|
@@ -1080,26 +970,30 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1080
970
|
}
|
|
1081
971
|
}) as T;
|
|
1082
972
|
}
|
|
973
|
+
inst.safe = safe;
|
|
1083
974
|
|
|
1084
975
|
// Load config to determine WebSocket URL
|
|
1085
976
|
ensureConfig();
|
|
1086
977
|
const config = loadConfig();
|
|
978
|
+
inst.config = config;
|
|
1087
979
|
// The ONE place an endpoint is chosen (D3, task 3.1). Explicit configuration
|
|
1088
980
|
// is pinned and outranks everything; the HOME-derived rendezvous record is
|
|
1089
981
|
// the default; discovery may only suggest. The legacy
|
|
1090
982
|
// `ws://localhost:<configured piPort>` is the last resort, kept so a new
|
|
1091
983
|
// bridge still works against a dashboard that predates the record (task 8.3).
|
|
1092
984
|
const rendezvous = rendezvousEndpoint();
|
|
985
|
+
inst.rendezvous = rendezvous;
|
|
1093
986
|
const endpointChoice = resolveEndpoint({
|
|
1094
987
|
socketEnv: process.env.PI_DASHBOARD_SOCKET,
|
|
1095
988
|
urlEnv: process.env.PI_DASHBOARD_URL,
|
|
1096
989
|
record: rendezvous ?? undefined,
|
|
1097
990
|
});
|
|
991
|
+
inst.endpointChoice = endpointChoice;
|
|
1098
992
|
// The instance this bridge believes it is talking to (task 3.4). Any
|
|
1099
993
|
// re-target is judged against THIS id, not against the endpoint string —
|
|
1100
994
|
// the same instance may legitimately move, and a different instance may
|
|
1101
995
|
// legitimately answer at the same endpoint.
|
|
1102
|
-
|
|
996
|
+
inst.registeredInstanceId = endpointChoice.available
|
|
1103
997
|
? endpointChoice.instanceId
|
|
1104
998
|
: undefined;
|
|
1105
999
|
// A socket-pinned bridge learns its instance from the FILESYSTEM, beside the
|
|
@@ -1110,12 +1004,12 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1110
1004
|
// socket. Best-effort: a missing or unreadable file leaves the id unset,
|
|
1111
1005
|
// which is the honest answer and exactly today's behaviour.
|
|
1112
1006
|
// See change: add-pi-gateway-transport-identity (task 9.6).
|
|
1113
|
-
if (registeredInstanceId === undefined && endpointChoice.available && process.env.PI_DASHBOARD_SOCKET) {
|
|
1007
|
+
if (inst.registeredInstanceId === undefined && endpointChoice.available && process.env.PI_DASHBOARD_SOCKET) {
|
|
1114
1008
|
const idFile = instanceIdFileForSocket(process.env.PI_DASHBOARD_SOCKET);
|
|
1115
1009
|
if (idFile) {
|
|
1116
1010
|
try {
|
|
1117
1011
|
const id = fs.readFileSync(idFile, "utf8").trim();
|
|
1118
|
-
if (id) registeredInstanceId = id;
|
|
1012
|
+
if (id) inst.registeredInstanceId = id;
|
|
1119
1013
|
} catch {
|
|
1120
1014
|
/* absent or unreadable — stay unverified rather than guess */
|
|
1121
1015
|
}
|
|
@@ -1124,43 +1018,42 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1124
1018
|
// `let`: a completed move re-points this, so diagnostics and `/dashboard-where`
|
|
1125
1019
|
// report where the session actually IS rather than where it started.
|
|
1126
1020
|
// biome-ignore lint/style/useConst: reassigned by the move command.
|
|
1127
|
-
|
|
1021
|
+
inst.dashboardUrl = endpointChoice.available
|
|
1128
1022
|
? endpointChoice.url
|
|
1129
1023
|
: `ws://localhost:${config.piPort}`;
|
|
1130
1024
|
// Pinned endpoints refuse every re-target, including a discovered one (D3).
|
|
1131
1025
|
const endpointPinned = endpointChoice.available && endpointChoice.pinned;
|
|
1026
|
+
inst.endpointPinned = endpointPinned;
|
|
1132
1027
|
// Task 10.1: log the winning precedence rule, or diagnosing "it connected to
|
|
1133
1028
|
// the wrong dashboard" means guessing which source won.
|
|
1134
|
-
const endpointDetail = `${dashboardUrl} (source=${
|
|
1029
|
+
const endpointDetail = `${inst.dashboardUrl} (source=${
|
|
1135
1030
|
endpointChoice.available ? endpointChoice.source : "legacy-config-piPort"
|
|
1136
1031
|
} pinned=${endpointPinned})`;
|
|
1137
1032
|
console.log(`[dashboard] endpoint ${endpointDetail}`);
|
|
1138
1033
|
// ...and again over the wire, because the line above is discarded under the
|
|
1139
1034
|
// default `capturePiOutput:false` (task 10.5).
|
|
1140
1035
|
const transportDiagnostics = createTransportDiagnostics();
|
|
1036
|
+
inst.transportDiagnostics = transportDiagnostics;
|
|
1141
1037
|
transportDiagnostics.record({ event: "endpoint_resolved", detail: endpointDetail });
|
|
1142
1038
|
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
}
|
|
1162
|
-
return { url: withTicket(endpoint, minted.ticket) };
|
|
1163
|
-
}
|
|
1039
|
+
// Mint a bridge ticket per remote dial; origin + failure causes: see
|
|
1040
|
+
// `remote-upgrade-preparer.ts`. Log the resolved HTTP origin up front too
|
|
1041
|
+
// (D4), deduped with the per-dial log.
|
|
1042
|
+
// The bearer goes only to a PINNED endpoint: the one this bridge was configured
|
|
1043
|
+
// with (or the user explicitly moved to), or a pin-store `lastEndpoint`.
|
|
1044
|
+
// A discovery-only host is never pinned. See change: harden-bridge-inbound-and-discovery (D19).
|
|
1045
|
+
const configuredEndpoint = inst.dashboardUrl;
|
|
1046
|
+
const prepareRemoteUpgrade = createRemoteUpgradePreparer({
|
|
1047
|
+
env: process.env,
|
|
1048
|
+
log: console,
|
|
1049
|
+
record: (d) => transportDiagnostics.record(d),
|
|
1050
|
+
isPinned: (endpoint) =>
|
|
1051
|
+
isPinnedEndpoint(endpoint, {
|
|
1052
|
+
configured: [configuredEndpoint, inst.dashboardUrl],
|
|
1053
|
+
pins: loadServerPins(serverPinsPath()),
|
|
1054
|
+
}),
|
|
1055
|
+
});
|
|
1056
|
+
prepareRemoteUpgrade.noteOrigin(inst.dashboardUrl);
|
|
1164
1057
|
|
|
1165
1058
|
// Long-lived ctx wrapper for the Extension UI System (Phase 1) — see
|
|
1166
1059
|
// change: add-extension-ui-modal. `getSessionId` reads the closed-over
|
|
@@ -1168,9 +1061,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1168
1061
|
// mutated when `event.reason ∈ {"new","fork","resume"}` fires).
|
|
1169
1062
|
const uiModulesBridgeCtx: UiModulesBridgeCtx = {
|
|
1170
1063
|
pi: pi as any,
|
|
1171
|
-
connection: { send: (msg: unknown) => connection.send(msg) },
|
|
1172
|
-
getSessionId: () => sessionId,
|
|
1064
|
+
connection: { send: (msg: unknown) => inst.connection.send(msg) },
|
|
1065
|
+
getSessionId: () => inst.sessionId,
|
|
1173
1066
|
};
|
|
1067
|
+
inst.uiModulesBridgeCtx = uiModulesBridgeCtx;
|
|
1174
1068
|
|
|
1175
1069
|
// `let`, not `const`: a completed move REBINDS this to the target's
|
|
1176
1070
|
// connection, and every closure in this module captured the BINDING rather
|
|
@@ -1181,7 +1075,8 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1181
1075
|
// installed only while the socket is open; a close fails pending calls
|
|
1182
1076
|
// `disconnected`. See change: expose-plugin-credential-and-oauth-seams (D7).
|
|
1183
1077
|
// Non-buffering send: a request must never be replayed after a reconnect.
|
|
1184
|
-
const pluginRequests = createPluginRequestClient({ send: (m) => connection.sendIfOpen(m) });
|
|
1078
|
+
const pluginRequests = createPluginRequestClient({ send: (m) => inst.connection.sendIfOpen(m) });
|
|
1079
|
+
inst.pluginRequests = pluginRequests;
|
|
1185
1080
|
let uninstallPluginRequest: (() => void) | null = null;
|
|
1186
1081
|
const pluginLaneUp = (): void => {
|
|
1187
1082
|
uninstallPluginRequest?.();
|
|
@@ -1198,14 +1093,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1198
1093
|
// See change: ask-agent-file-access-in-chat.
|
|
1199
1094
|
const pathGate = createPathGate({
|
|
1200
1095
|
suppression: (getBridgeState().pathGateSuppression ??= new Suppression()),
|
|
1201
|
-
getSessionId: () => sessionId,
|
|
1202
|
-
getPromptBus: () => promptBus,
|
|
1203
|
-
send: (m) => connection.sendIfOpen(m),
|
|
1096
|
+
getSessionId: () => inst.sessionId,
|
|
1097
|
+
getPromptBus: () => inst.promptBus,
|
|
1098
|
+
send: (m) => inst.connection.sendIfOpen(m),
|
|
1204
1099
|
readConfig: () => loadConfig().agentPathGate,
|
|
1205
|
-
getCwd: () => cachedCwd ?? process.cwd(),
|
|
1100
|
+
getCwd: () => inst.cachedCwd ?? process.cwd(),
|
|
1206
1101
|
getSessionDir: () => {
|
|
1207
1102
|
try {
|
|
1208
|
-
return cachedCtx?.sessionManager?.getSessionDir?.();
|
|
1103
|
+
return inst.cachedCtx?.sessionManager?.getSessionDir?.();
|
|
1209
1104
|
} catch {
|
|
1210
1105
|
return undefined;
|
|
1211
1106
|
}
|
|
@@ -1213,15 +1108,72 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1213
1108
|
log: (line) => console.log(line),
|
|
1214
1109
|
notify: (message) => {
|
|
1215
1110
|
try {
|
|
1216
|
-
cachedCtx?.ui?.notify?.(message, "warning");
|
|
1111
|
+
inst.cachedCtx?.ui?.notify?.(message, "warning");
|
|
1217
1112
|
} catch {
|
|
1218
1113
|
/* best effort */
|
|
1219
1114
|
}
|
|
1220
1115
|
},
|
|
1221
1116
|
});
|
|
1117
|
+
inst.pathGate = pathGate;
|
|
1118
|
+
|
|
1119
|
+
// Credential vault: applies the hub's granted env values to process.env and
|
|
1120
|
+
// reconciles on every connect and session_start. State lives on `process`, so
|
|
1121
|
+
// a reload keeps it. See change: add-credential-vault.
|
|
1122
|
+
const vaultDelivery = createVaultDelivery({
|
|
1123
|
+
send: (m) => inst.connection.sendIfOpen(m),
|
|
1124
|
+
sessionId: () => inst.sessionId ?? "",
|
|
1125
|
+
certValidation: () => inst.connection.certValidation,
|
|
1126
|
+
log: (line) => console.log(line),
|
|
1127
|
+
});
|
|
1128
|
+
inst.vaultDelivery = vaultDelivery;
|
|
1129
|
+
// Redaction: the value set is vaultDelivery's process-global redaction registry,
|
|
1130
|
+
// so a reload and a nested pi mask the same values. The forward filter masks
|
|
1131
|
+
// every outgoing event_forward frame on a copy (with tail hold-back) and is
|
|
1132
|
+
// installed at the connection, so no plaintext value reaches the send buffer.
|
|
1133
|
+
const vaultRedaction = createVaultRedaction({
|
|
1134
|
+
getState: () => vaultDelivery.redactionState(),
|
|
1135
|
+
createLocalBashOperations: async () => {
|
|
1136
|
+
try {
|
|
1137
|
+
const pkg: any = await import("@earendil-works/pi-coding-agent");
|
|
1138
|
+
const create: (() => unknown) | undefined = pkg.createLocalBashOperations ?? pkg.default?.createLocalBashOperations;
|
|
1139
|
+
return create?.() as any;
|
|
1140
|
+
} catch {
|
|
1141
|
+
return undefined; // the forwarded copy is still masked
|
|
1142
|
+
}
|
|
1143
|
+
},
|
|
1144
|
+
log: (line) => console.log(line),
|
|
1145
|
+
});
|
|
1146
|
+
const vaultForwardFilter = createVaultForwardFilter(vaultRedaction.masker);
|
|
1147
|
+
// tool_result / message_end / user_bash: masked before pi records the result.
|
|
1148
|
+
// Fail CLOSED: if masking throws, the output is withheld rather than passed raw.
|
|
1149
|
+
pi.on("tool_result", async (event: any) => {
|
|
1150
|
+
try {
|
|
1151
|
+
return (await vaultRedaction.toolResult(event)) as any;
|
|
1152
|
+
} catch {
|
|
1153
|
+
return { content: [{ type: "text", text: "[output withheld: vault redaction failed]" }], details: undefined, structuredContent: undefined } as any;
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
pi.on("message_end", (event: any) => {
|
|
1157
|
+
try {
|
|
1158
|
+
return vaultRedaction.messageEnd(event) as any;
|
|
1159
|
+
} catch {
|
|
1160
|
+
// Fail CLOSED like tool_result: record a placeholder, keep the role.
|
|
1161
|
+
const message = event?.message;
|
|
1162
|
+
if (!message || typeof message !== "object") return undefined;
|
|
1163
|
+
return { message: { ...message, content: [{ type: "text", text: "[message withheld: vault redaction failed]" }] } } as any;
|
|
1164
|
+
}
|
|
1165
|
+
});
|
|
1166
|
+
pi.on("user_bash", async () => {
|
|
1167
|
+
try {
|
|
1168
|
+
return (await vaultRedaction.userBash()) as any;
|
|
1169
|
+
} catch {
|
|
1170
|
+
return undefined;
|
|
1171
|
+
}
|
|
1172
|
+
});
|
|
1222
1173
|
|
|
1223
|
-
|
|
1224
|
-
url: dashboardUrl,
|
|
1174
|
+
inst.connection = new ConnectionManager({
|
|
1175
|
+
url: inst.dashboardUrl,
|
|
1176
|
+
outboundFilter: (m) => vaultForwardFilter.filter(m),
|
|
1225
1177
|
// fix-bridge-mdns-migration-hijack (D5): every migration decision —
|
|
1226
1178
|
// accepted or refused, including a reversibility fallback — is reported
|
|
1227
1179
|
// through this single chokepoint. `console.log` serves capture-enabled
|
|
@@ -1236,24 +1188,31 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1236
1188
|
detail,
|
|
1237
1189
|
});
|
|
1238
1190
|
},
|
|
1239
|
-
// D6 (task 5.3): a LOOPBACK TCP dial carries
|
|
1240
|
-
//
|
|
1241
|
-
//
|
|
1242
|
-
//
|
|
1243
|
-
|
|
1191
|
+
// D6 (task 5.3): a LOOPBACK TCP dial carries a PROOF of possession of this
|
|
1192
|
+
// HOME's local token (never the token), bound to the address actually
|
|
1193
|
+
// reached — the credential that replaces the socket's file mode where there
|
|
1194
|
+
// is no socket (Windows, or a sun_path fallback). Planned per dial, so each
|
|
1195
|
+
// attempt has a fresh nonce; nothing is planned over a socket or for a
|
|
1196
|
+
// remote endpoint. A bridge MARKED by its spawner also verifies the server
|
|
1197
|
+
// counter-proof before `open`. See change: loopback-credential-proof (D6, D7).
|
|
1198
|
+
planDial: (base) => localCredentialPlan(base),
|
|
1199
|
+
onIdentityFailure: (report) => {
|
|
1200
|
+
console.error(`[dashboard] server identity check failed (${proofFailureLogCause(report.cause)}) at ${report.endpoint}`);
|
|
1201
|
+
appendIdentityLog(report);
|
|
1202
|
+
},
|
|
1244
1203
|
// Every accepted re-target (and every reversal) re-derives these from the
|
|
1245
|
-
// endpoint actually being dialled — a loopback
|
|
1204
|
+
// endpoint actually being dialled — a loopback proof must never ride a
|
|
1246
1205
|
// dial to a discovered remote host, and a remote candidate needs its own
|
|
1247
1206
|
// bridge ticket. (CodeRabbit review, fix-bridge-mdns-migration-hijack.)
|
|
1248
1207
|
credentialsFor: (u) => ({
|
|
1249
|
-
|
|
1208
|
+
planDial: (base) => localCredentialPlan(base),
|
|
1250
1209
|
prepare: () => prepareRemoteUpgrade(u),
|
|
1251
1210
|
}),
|
|
1252
1211
|
// A REMOTE endpoint needs a bridge ticket per attempt (§6 made TCP bridge
|
|
1253
1212
|
// auth mandatory). Local dials — unix socket or loopback — are authorised
|
|
1254
1213
|
// by file mode or the local token and mint nothing.
|
|
1255
1214
|
// See change: add-pi-gateway-transport-identity (D10b).
|
|
1256
|
-
prepareConnect: () => prepareRemoteUpgrade(dashboardUrl),
|
|
1215
|
+
prepareConnect: () => prepareRemoteUpgrade(inst.dashboardUrl),
|
|
1257
1216
|
// Attribute every force-close. `record` flushes through the live socket
|
|
1258
1217
|
// when one is still OPEN (the callback runs BEFORE teardown) and falls
|
|
1259
1218
|
// back to the buffer otherwise, so the report survives either way.
|
|
@@ -1265,444 +1224,35 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1265
1224
|
// Routing field for a drop report — the reporting bridge's OWN session,
|
|
1266
1225
|
// never the id the dropped message named.
|
|
1267
1226
|
// See change: fix-spawn-correlation-ttl-coupling (D6).
|
|
1268
|
-
getSessionId: () => sessionId,
|
|
1227
|
+
getSessionId: () => inst.sessionId,
|
|
1269
1228
|
// Lane lifecycle follows the CURRENT connection only: after a
|
|
1270
1229
|
// `/dashboard-connect` move, `connection` is rebound to the target.
|
|
1271
1230
|
onOpen: () => {
|
|
1272
|
-
if (!isActive() || connection !== primaryConnection) return;
|
|
1231
|
+
if (!isActive() || inst.connection !== primaryConnection) return;
|
|
1273
1232
|
pluginLaneUp();
|
|
1233
|
+
vaultDelivery.onOpen();
|
|
1234
|
+
// `onReconnect` skips the FIRST open, so plugin latest/stream messages
|
|
1235
|
+
// retained before it would wait for the next emission. Drain after the
|
|
1236
|
+
// manager flushes its buffered register frame (microtask).
|
|
1237
|
+
// See change: add-plugin-bridge-contributions.
|
|
1238
|
+
queueMicrotask(() => {
|
|
1239
|
+
if (!isActive() || inst.connection !== primaryConnection) return;
|
|
1240
|
+
try {
|
|
1241
|
+
pluginForwardRegistry.flush();
|
|
1242
|
+
} catch {
|
|
1243
|
+
/* registry not yet initialised (declared later in initBridge) */
|
|
1244
|
+
}
|
|
1245
|
+
});
|
|
1274
1246
|
},
|
|
1275
1247
|
onClose: () => {
|
|
1276
|
-
if (connection !== primaryConnection) return;
|
|
1248
|
+
if (inst.connection !== primaryConnection) return;
|
|
1277
1249
|
pluginLaneDown();
|
|
1278
1250
|
pathGate.reset();
|
|
1251
|
+
vaultDelivery.onClose();
|
|
1279
1252
|
},
|
|
1280
1253
|
onMessage: safe(async (data: unknown) => {
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
// D12: the dashboard asking for a slice of THIS session's transcript.
|
|
1284
|
-
// Guarded before any filesystem touch — a request naming a path, or
|
|
1285
|
-
// another session, never reaches the reader. See change:
|
|
1286
|
-
// add-pi-gateway-transport-identity (tasks 11.3/11.4/11.6).
|
|
1287
|
-
if ((msg as any).type === "transcript_request") {
|
|
1288
|
-
const req = msg as unknown as TranscriptRequestMessage;
|
|
1289
|
-
const verdict = decideTranscriptRequest({
|
|
1290
|
-
request: req as never,
|
|
1291
|
-
ownSessionId: sessionId,
|
|
1292
|
-
});
|
|
1293
|
-
if (!verdict.allow) {
|
|
1294
|
-
console.warn(`[dashboard] transcript request refused: ${verdict.reason}`);
|
|
1295
|
-
connection.send({
|
|
1296
|
-
type: "transcript_chunk",
|
|
1297
|
-
// Echo the caller's id: routing is the connection, and the server
|
|
1298
|
-
// must be able to correlate a refusal with what it asked for.
|
|
1299
|
-
sessionId: req.sessionId,
|
|
1300
|
-
entries: [],
|
|
1301
|
-
complete: false,
|
|
1302
|
-
restarted: false,
|
|
1303
|
-
refused: { cause: verdict.cause, reason: verdict.reason },
|
|
1304
|
-
});
|
|
1305
|
-
return;
|
|
1306
|
-
}
|
|
1307
|
-
if (!lastSessionFile) return;
|
|
1308
|
-
const chunk = readTranscriptChunk(
|
|
1309
|
-
lastSessionFile,
|
|
1310
|
-
req.cursor as TranscriptCursor | undefined,
|
|
1311
|
-
{ maxBytes: req.maxBytes },
|
|
1312
|
-
);
|
|
1313
|
-
connection.send({
|
|
1314
|
-
type: "transcript_chunk",
|
|
1315
|
-
sessionId: req.sessionId,
|
|
1316
|
-
entries: chunk.entries,
|
|
1317
|
-
cursor: chunk.cursor,
|
|
1318
|
-
complete: chunk.complete,
|
|
1319
|
-
restarted: chunk.restarted,
|
|
1320
|
-
});
|
|
1321
|
-
return;
|
|
1322
|
-
}
|
|
1323
|
-
// Extension UI System (Phase 1): browser-originated action / data
|
|
1324
|
-
// request. Re-emit on pi.events; the listener either populates
|
|
1325
|
-
// data.items synchronously or calls _reply asynchronously.
|
|
1326
|
-
// See change: add-extension-ui-modal.
|
|
1327
|
-
if ((msg as any).type === "ui_management") {
|
|
1328
|
-
handleUiManagement(uiModulesBridgeCtx, msg as any);
|
|
1329
|
-
return;
|
|
1330
|
-
}
|
|
1331
|
-
// Server announced a deliberate restart/shutdown. Pause the auto-start
|
|
1332
|
-
// spawn step in `server-auto-start.ts` for `quiesceMs` so we don't
|
|
1333
|
-
// race the orchestrator that's about to bring up the replacement.
|
|
1334
|
-
// Discovery + reconnection still run via the normal backoff path.
|
|
1335
|
-
// See change: fix-restart-bridge-auto-start-race.
|
|
1336
|
-
if ((msg as any).type === "server_restarting") {
|
|
1337
|
-
const reason = (msg as any).reason;
|
|
1338
|
-
const quiesceMs = (msg as any).quiesceMs;
|
|
1339
|
-
if (typeof quiesceMs === "number" && quiesceMs > 0) {
|
|
1340
|
-
connection.pauseAutoStart(quiesceMs);
|
|
1341
|
-
console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${quiesceMs})`);
|
|
1342
|
-
}
|
|
1343
|
-
return;
|
|
1344
|
-
}
|
|
1345
|
-
// Legacy extension_ui_response removed — now handled by prompt_response → promptBus.respond()
|
|
1346
|
-
if (msg.type === "plugin_reply") {
|
|
1347
|
-
// Resolves the caller's Promise only — never re-emitted on pi.events.
|
|
1348
|
-
pluginRequests.handleReply(msg);
|
|
1349
|
-
return;
|
|
1350
|
-
}
|
|
1351
|
-
// Agent path gate: grant-store identity + grant results (never re-emitted).
|
|
1352
|
-
if (pathGate.onServerMessage(msg as { type?: string })) return;
|
|
1353
|
-
if (msg.type === "mcp_token_minted") {
|
|
1354
|
-
// The minted MCP bearer (+ /mcp url) arrives on the session-private
|
|
1355
|
-
// lane and is registered with pi's built-in MCP — never placed in
|
|
1356
|
-
// process.env, a log line, or pi.events.
|
|
1357
|
-
// See change: migrate-mcp-to-pi-builtin (D1).
|
|
1358
|
-
mcpRegistrar.onMinted(msg as McpTokenMintedPayload);
|
|
1359
|
-
return;
|
|
1360
|
-
}
|
|
1361
|
-
// Reload auth credentials when dashboard notifies of changes
|
|
1362
|
-
if (msg.type === "credentials_updated") {
|
|
1363
|
-
try {
|
|
1364
|
-
// Hot-reload providers.json diff BEFORE refreshing the registry,
|
|
1365
|
-
// so any newly added providers are registered before getAvailable() runs.
|
|
1366
|
-
const diff = await reloadProviders(pi).catch((err) => {
|
|
1367
|
-
console.error("[dashboard] reloadProviders failed:", err);
|
|
1368
|
-
return { added: [], removed: [], changed: [] };
|
|
1369
|
-
});
|
|
1370
|
-
if (diff.added.length || diff.removed.length || diff.changed.length) {
|
|
1371
|
-
console.log(
|
|
1372
|
-
`[dashboard] hot-reloaded providers: added=${JSON.stringify(diff.added)} removed=${JSON.stringify(diff.removed)} changed=${JSON.stringify(diff.changed)}`,
|
|
1373
|
-
);
|
|
1374
|
-
}
|
|
1375
|
-
cachedModelRegistry?.authStorage?.reload?.();
|
|
1376
|
-
// pi 0.84.0: refresh() takes ModelsRefreshOptions and returns
|
|
1377
|
-
// { aborted, errors }. Await + inspect it so getAvailable() below
|
|
1378
|
-
// sees the refreshed catalogue and a per-provider failure is
|
|
1379
|
-
// reported rather than silently dropped. Scope the refresh to the
|
|
1380
|
-
// providers this reload actually touched -- an unrelated provider's
|
|
1381
|
-
// catalogue has no reason to be re-fetched because one credential
|
|
1382
|
-
// changed. Empty scope (removals only) => refresh nothing.
|
|
1383
|
-
// See change: update-pi-core-0-84-adopt-apis.
|
|
1384
|
-
const touched = [...new Set([...diff.added, ...diff.changed])];
|
|
1385
|
-
if (touched.length > 0) {
|
|
1386
|
-
await reportRefresh(
|
|
1387
|
-
cachedModelRegistry?.refresh?.({ providers: touched }),
|
|
1388
|
-
`credentials reload refresh (${touched.join(", ")})`,
|
|
1389
|
-
);
|
|
1390
|
-
}
|
|
1391
|
-
} catch (err) { console.error("[dashboard] credentials reload failed:", err); }
|
|
1392
|
-
// Push updated models list to dashboard client
|
|
1393
|
-
if (cachedModelRegistry && sessionReady) {
|
|
1394
|
-
try {
|
|
1395
|
-
const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
|
|
1396
|
-
connection.send({ type: "models_list", sessionId, models });
|
|
1397
|
-
// See change: replace-hardcoded-provider-lists.
|
|
1398
|
-
connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
|
|
1399
|
-
} catch (err) { console.error("[dashboard] models_list push failed:", err); }
|
|
1400
|
-
}
|
|
1401
|
-
return;
|
|
1402
|
-
}
|
|
1403
|
-
// Auto-naming toggle relay: store the pushed value so the namer gates on
|
|
1404
|
-
// the current preference. See change: add-auto-session-naming.
|
|
1405
|
-
if (msg.type === "preferences_update") {
|
|
1406
|
-
if (typeof (msg as any).autoNameSessions === "boolean") {
|
|
1407
|
-
autoNameSessions = (msg as any).autoNameSessions;
|
|
1408
|
-
}
|
|
1409
|
-
return;
|
|
1410
|
-
}
|
|
1411
|
-
// Persisted stop state pushed at register, so a permanent stop survives a
|
|
1412
|
-
// PROCESS restart. Only the STOP fields are adopted. `nameSource`,
|
|
1413
|
-
// `lastSelfApplied` and `hasAutoName` are deliberately NOT restored:
|
|
1414
|
-
// reinstating them would change the behaviour of the separate auto→`user`
|
|
1415
|
-
// relabel bug, which has a different root cause and is tracked on its own
|
|
1416
|
-
// (design D8b, change: investigate-auto-name-provenance-relabel). They are
|
|
1417
|
-
// still carried across an in-process RELOAD via `prev.namerState`.
|
|
1418
|
-
// See change: fix-auto-naming-reasoning-model (design D7).
|
|
1419
|
-
if (msg.type === "auto_name_state_restore") {
|
|
1420
|
-
const adopted = adoptRestoredNamerState((msg as any).state);
|
|
1421
|
-
if (adopted && !autoNamer) {
|
|
1422
|
-
namerState = adopted;
|
|
1423
|
-
prev.namerState = adopted;
|
|
1424
|
-
}
|
|
1425
|
-
return;
|
|
1426
|
-
}
|
|
1427
|
-
// Graceful stop-after-turn: latch a per-session flag; the next turn_end
|
|
1428
|
-
// shuts the session down cleanly. Idempotent. See change:
|
|
1429
|
-
// adopt-pi-071-072-073-features.
|
|
1430
|
-
if (msg.type === "stop_after_turn") {
|
|
1431
|
-
getBridgeState().shouldStopAfterTurn = true;
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
// Forced PR-status probe after a worktree Push / Open PR. The server
|
|
1435
|
-
// only targets bridges whose cwd is inside the worktree. See change:
|
|
1436
|
-
// redesign-composer-session-strip (D5).
|
|
1437
|
-
if (routeGitInfoRefresh(msg, { prStatus, gitTracker: polling.gitTracker })) return;
|
|
1438
|
-
// Route flow management actions from dashboard buttons
|
|
1439
|
-
if (msg.type === "flow_management" && pi.events) {
|
|
1440
|
-
if (msg.action === "run") {
|
|
1441
|
-
pi.events.emit("flow:run", { flowName: msg.flowName, task: msg.task || undefined });
|
|
1442
|
-
} else if (msg.action === "set-edit-mode") {
|
|
1443
|
-
// Edit-mode toggle (rework-flows-plugin-for-new-pi-flows). pi-flows
|
|
1444
|
-
// persists flows.editFlow, syncs skill visibility, reloads.
|
|
1445
|
-
// /flows:new + /flows:edit removed upstream — authoring is now the
|
|
1446
|
-
// edit-flow skill via send_prompt from the dashboard.
|
|
1447
|
-
if (typeof (msg as { enabled?: unknown }).enabled === "boolean") {
|
|
1448
|
-
pi.events.emit("flow:set-edit-mode", { enabled: (msg as { enabled: boolean }).enabled });
|
|
1449
|
-
}
|
|
1450
|
-
} else if (msg.action === "delete") {
|
|
1451
|
-
// Dashboard already confirmed upfront — delete directly
|
|
1452
|
-
pi.events.emit("flow:delete-request", { flowName: msg.flowName });
|
|
1453
|
-
pi.events.emit("flow:notify", { message: `Flow "${msg.flowName}" deleted.`, level: "info" });
|
|
1454
|
-
}
|
|
1455
|
-
return;
|
|
1456
|
-
}
|
|
1457
|
-
// Route role management from dashboard
|
|
1458
|
-
if (msg.type === "role_set" && pi.events) {
|
|
1459
|
-
const data: any = { role: (msg as any).role, modelId: (msg as any).modelId };
|
|
1460
|
-
pi.events.emit("roles:set", data);
|
|
1461
|
-
if (data.success) {
|
|
1462
|
-
const rolesData: any = {};
|
|
1463
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1464
|
-
connection.send({
|
|
1465
|
-
type: "roles_list",
|
|
1466
|
-
sessionId,
|
|
1467
|
-
roles: rolesData.roles ?? {},
|
|
1468
|
-
presets: rolesData.presets ?? [],
|
|
1469
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1470
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1471
|
-
});
|
|
1472
|
-
}
|
|
1473
|
-
return;
|
|
1474
|
-
}
|
|
1475
|
-
if (msg.type === "role_preset_load" && pi.events) {
|
|
1476
|
-
const data: any = { name: (msg as any).presetName };
|
|
1477
|
-
pi.events.emit("roles:preset-load", data);
|
|
1478
|
-
if (data.success) {
|
|
1479
|
-
const rolesData: any = {};
|
|
1480
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1481
|
-
connection.send({
|
|
1482
|
-
type: "roles_list",
|
|
1483
|
-
sessionId,
|
|
1484
|
-
roles: rolesData.roles ?? {},
|
|
1485
|
-
presets: rolesData.presets ?? [],
|
|
1486
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1487
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1488
|
-
});
|
|
1489
|
-
}
|
|
1490
|
-
return;
|
|
1491
|
-
}
|
|
1492
|
-
if (msg.type === "role_preset_save" && pi.events) {
|
|
1493
|
-
const data: any = { name: (msg as any).presetName };
|
|
1494
|
-
pi.events.emit("roles:preset-save", data);
|
|
1495
|
-
if (data.success) {
|
|
1496
|
-
const rolesData: any = {};
|
|
1497
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1498
|
-
connection.send({
|
|
1499
|
-
type: "roles_list",
|
|
1500
|
-
sessionId,
|
|
1501
|
-
roles: rolesData.roles ?? {},
|
|
1502
|
-
presets: rolesData.presets ?? [],
|
|
1503
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1504
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1505
|
-
});
|
|
1506
|
-
}
|
|
1507
|
-
return;
|
|
1508
|
-
}
|
|
1509
|
-
if (msg.type === "role_preset_delete" && pi.events) {
|
|
1510
|
-
const data: any = { name: (msg as any).presetName };
|
|
1511
|
-
pi.events.emit("roles:preset-delete", data);
|
|
1512
|
-
if (data.success) {
|
|
1513
|
-
const rolesData: any = {};
|
|
1514
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1515
|
-
connection.send({
|
|
1516
|
-
type: "roles_list",
|
|
1517
|
-
sessionId,
|
|
1518
|
-
roles: rolesData.roles ?? {},
|
|
1519
|
-
presets: rolesData.presets ?? [],
|
|
1520
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1521
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1522
|
-
});
|
|
1523
|
-
}
|
|
1524
|
-
return;
|
|
1525
|
-
}
|
|
1526
|
-
// Remove a CUSTOM role: purge from schema + active map + every preset.
|
|
1527
|
-
// Built-ins are rejected server-side in the roles:remove handler.
|
|
1528
|
-
// Mirrors the role_set routing block. See change: add-custom-roles-ui.
|
|
1529
|
-
if (msg.type === "role_remove" && pi.events) {
|
|
1530
|
-
const data: any = { role: (msg as any).role };
|
|
1531
|
-
pi.events.emit("roles:remove", data);
|
|
1532
|
-
if (data.success) {
|
|
1533
|
-
const rolesData: any = {};
|
|
1534
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1535
|
-
connection.send({
|
|
1536
|
-
type: "roles_list",
|
|
1537
|
-
sessionId,
|
|
1538
|
-
roles: rolesData.roles ?? {},
|
|
1539
|
-
presets: rolesData.presets ?? [],
|
|
1540
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1541
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1542
|
-
});
|
|
1543
|
-
}
|
|
1544
|
-
return;
|
|
1545
|
-
}
|
|
1546
|
-
if (msg.type === "request_roles" && pi.events) {
|
|
1547
|
-
const rolesData: any = {};
|
|
1548
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
1549
|
-
connection.send({
|
|
1550
|
-
type: "roles_list",
|
|
1551
|
-
sessionId,
|
|
1552
|
-
roles: rolesData.roles ?? {},
|
|
1553
|
-
presets: rolesData.presets ?? [],
|
|
1554
|
-
activePreset: rolesData.activePreset ?? null,
|
|
1555
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
1556
|
-
});
|
|
1557
|
-
return;
|
|
1558
|
-
}
|
|
1559
|
-
// Route PromptBus responses from dashboard client
|
|
1560
|
-
if (msg.type === "prompt_response" && promptBus) {
|
|
1561
|
-
promptBus.respond({
|
|
1562
|
-
id: (msg as any).promptId,
|
|
1563
|
-
answer: (msg as any).answer,
|
|
1564
|
-
cancelled: (msg as any).cancelled,
|
|
1565
|
-
source: (msg as any).source ?? "dashboard-default",
|
|
1566
|
-
// Optional pasted images for method:"input".
|
|
1567
|
-
// See change: add-ask-user-input-multiline-paste.
|
|
1568
|
-
images: (msg as any).images,
|
|
1569
|
-
});
|
|
1570
|
-
return;
|
|
1571
|
-
}
|
|
1572
|
-
// Legacy architect_prompt_response routing REMOVED.
|
|
1573
|
-
// Previously routed to flow:prompt-response + cancelAllPending().
|
|
1574
|
-
// Now handled by PromptBus: dashboard sends prompt_response,
|
|
1575
|
-
// bus calls respond(), adapters get onResponse() for cross-cancellation.
|
|
1576
|
-
// Route flow control messages to pi-flows via pi.events
|
|
1577
|
-
// Generic plugin-registered event emission. A dashboard plugin action
|
|
1578
|
-
// (e.g. automation) emits a configured event INTO this session; the
|
|
1579
|
-
// bridge relays it onto pi.events. Decoupled: the bridge does not know
|
|
1580
|
-
// which events exist. See change: automation-emit-configured-event.
|
|
1581
|
-
if (msg.type === "plugin_emit_event" && pi.events) {
|
|
1582
|
-
const eventType = (msg as { eventType?: unknown }).eventType;
|
|
1583
|
-
if (typeof eventType === "string" && eventType.length > 0) {
|
|
1584
|
-
const data = (msg as { data?: unknown }).data;
|
|
1585
|
-
pi.events.emit(eventType, data && typeof data === "object" ? (data as Record<string, unknown>) : {});
|
|
1586
|
-
}
|
|
1587
|
-
return;
|
|
1588
|
-
}
|
|
1589
|
-
// Subagent resync (D2): reply with the latest retained snapshot of a
|
|
1590
|
-
// running subagent as a synthetic subagent_started event_forward. No-op
|
|
1591
|
-
// for an unknown/finished agent (durable completed-case backfill covers
|
|
1592
|
-
// those). See change: fix-subagent-live-detail-reliability.
|
|
1593
|
-
if (msg.type === "subagent_resync_request") {
|
|
1594
|
-
// The incoming id may be EITHER a v4 agentId or a v7 runner
|
|
1595
|
-
// agentSessionId (from a deep-link route); resync() resolves both.
|
|
1596
|
-
// See change: resolve-subagent-inspector-by-session-id (D3/D4).
|
|
1597
|
-
const requestedId = (msg as { agentId?: unknown }).agentId;
|
|
1598
|
-
if (typeof requestedId === "string" && requestedId.length > 0) {
|
|
1599
|
-
// The reply is NEVER stripped: it IS the pull model's answer and
|
|
1600
|
-
// carries the full timeline for a RUNNING agent — exactly the shape a
|
|
1601
|
-
// strip inside `sendEventForward` would have destroyed.
|
|
1602
|
-
// See change: reduce-subagent-details-payload (X6).
|
|
1603
|
-
const echoId = (msg as { requestId?: unknown }).requestId;
|
|
1604
|
-
const resolvedAgentId = serveSubagentResync(
|
|
1605
|
-
subagentFrameBuffer,
|
|
1606
|
-
requestedId,
|
|
1607
|
-
sendEventForward,
|
|
1608
|
-
() => sessionReady && isActive(),
|
|
1609
|
-
typeof echoId === "string" && echoId.length > 0 ? echoId : undefined,
|
|
1610
|
-
(msg as { reason?: "open" | "cadence" }).reason,
|
|
1611
|
-
);
|
|
1612
|
-
console.log(
|
|
1613
|
-
resolvedAgentId
|
|
1614
|
-
? `[dashboard] served subagent resync for id=${requestedId} (resolved agentId=${resolvedAgentId})`
|
|
1615
|
-
: `[dashboard] subagent resync no-op (unknown/finished/not-ready) id=${requestedId}`,
|
|
1616
|
-
);
|
|
1617
|
-
}
|
|
1618
|
-
return;
|
|
1619
|
-
}
|
|
1620
|
-
// Prompt resync (fix B, extension half): a browser asked the bridge to
|
|
1621
|
-
// re-emit every prompt it is still awaiting an answer for — the bus's
|
|
1622
|
-
// pending set is the source of truth, NOT the server's derived registry
|
|
1623
|
-
// (D6). Each frame echoes the requester token so the server unicasts it
|
|
1624
|
-
// back to the asking browser as a critical frame. Empty pending set →
|
|
1625
|
-
// zero frames, no error (E10); a malformed token degrades to tokenless.
|
|
1626
|
-
// See change: fix-pending-prompt-lost-on-replay (design D5/D6/D7).
|
|
1627
|
-
if (msg.type === "prompt_resync_request") {
|
|
1628
|
-
const echoId = (msg as { requestId?: unknown }).requestId;
|
|
1629
|
-
const token = typeof echoId === "string" && echoId.length > 0 ? echoId : undefined;
|
|
1630
|
-
if (promptBus) {
|
|
1631
|
-
emitPendingPrompts(promptBus, (m) => connection.send(m as any), sessionId, token);
|
|
1632
|
-
}
|
|
1633
|
-
return;
|
|
1634
|
-
}
|
|
1635
|
-
if (msg.type === "flow_control" && pi.events) {
|
|
1636
|
-
if (msg.action === "abort") {
|
|
1637
|
-
pi.events.emit("flow:abort", {});
|
|
1638
|
-
// Also abort architect if running (mutually exclusive with flow execution;
|
|
1639
|
-
// the irrelevant emit is a no-op due to guard checks on both listeners)
|
|
1640
|
-
pi.events.emit("flow:architect-abort", {});
|
|
1641
|
-
} else if (msg.action === "toggle_autonomous") {
|
|
1642
|
-
pi.events.emit("flow:toggle-autonomous", {});
|
|
1643
|
-
} else if (msg.action === "dismiss_summary") {
|
|
1644
|
-
pi.events.emit("flow:summary-dismissed", {});
|
|
1645
|
-
}
|
|
1646
|
-
return;
|
|
1647
|
-
}
|
|
1648
|
-
// ── Follow-up queue mutation (bridge-owned buffer) ─────────────────
|
|
1649
|
-
//
|
|
1650
|
-
// These four handlers mutate `bridgeFollowUp` only. NONE of them
|
|
1651
|
-
// call pi.sendUserMessage, pi.clear*Queue, or any other pi method.
|
|
1652
|
-
// The bridge owns the buffer; pi never sees these entries until the
|
|
1653
|
-
// drain loop ships them on agent_end as fresh-turn sendUserMessage.
|
|
1654
|
-
//
|
|
1655
|
-
// The OLD pi-mutation handler set from Phase 3 (clear_steering_queue,
|
|
1656
|
-
// clear_followup_slot, edit_followup_slot) is GONE forever — pi's
|
|
1657
|
-
// ExtensionAPI exposes no clear*Queue primitives (verified through
|
|
1658
|
-
// pi 0.76.0). Steer mutation will never be exposed (steer drains too
|
|
1659
|
-
// fast for it to matter; user direction).
|
|
1660
|
-
//
|
|
1661
|
-
// See change: rework-mid-turn-prompt-queue (design.md D3).
|
|
1662
|
-
if (msg.type === "edit_followup_entry") {
|
|
1663
|
-
const { index, text } = msg as { type: string; index: number; text: string };
|
|
1664
|
-
// Text-only edit: the entry's images are PRESERVED (design D5). Gated
|
|
1665
|
-
// on the byte ceiling because the inline editor can grow text without
|
|
1666
|
-
// bound; a refused edit leaves the entry untouched and emits no
|
|
1667
|
-
// `queue_update`. See change: fix-bridge-followup-image-drop.
|
|
1668
|
-
const edited = bridgeFollowUp.editText(index, text);
|
|
1669
|
-
if (!edited.ok) {
|
|
1670
|
-
sendCommandFeedback("edit_followup_entry", edited.message);
|
|
1671
|
-
return;
|
|
1672
|
-
}
|
|
1673
|
-
emitQueueUpdate();
|
|
1674
|
-
return;
|
|
1675
|
-
}
|
|
1676
|
-
if (msg.type === "remove_followup_entry") {
|
|
1677
|
-
const { index } = msg as { type: string; index: number };
|
|
1678
|
-
if (!bridgeFollowUp.removeAt(index)) {
|
|
1679
|
-
sendCommandFeedback("remove_followup_entry", "Index out of range");
|
|
1680
|
-
return;
|
|
1681
|
-
}
|
|
1682
|
-
emitQueueUpdate();
|
|
1683
|
-
return;
|
|
1684
|
-
}
|
|
1685
|
-
if (msg.type === "promote_followup_entry") {
|
|
1686
|
-
const { index } = msg as { type: string; index: number };
|
|
1687
|
-
// Silent no-op for index 0 or invalid — no emit (D3). Carries images.
|
|
1688
|
-
if (bridgeFollowUp.promote(index)) emitQueueUpdate();
|
|
1689
|
-
return;
|
|
1690
|
-
}
|
|
1691
|
-
if (msg.type === "clear_followup_entries") {
|
|
1692
|
-
const { indices } = msg as { type: string; indices: number[] | "all" };
|
|
1693
|
-
const mutated =
|
|
1694
|
-
indices === "all" ? bridgeFollowUp.clearAll() : bridgeFollowUp.clearIndices(indices);
|
|
1695
|
-
if (mutated) emitQueueUpdate();
|
|
1696
|
-
return;
|
|
1697
|
-
}
|
|
1698
|
-
const response = await commandHandler.handle(msg);
|
|
1699
|
-
if (response) connection.send(response);
|
|
1700
|
-
// Immediately send model/thinking update after handling set_thinking_level
|
|
1701
|
-
if (msg.type === "set_thinking_level") {
|
|
1702
|
-
// Small delay to let pi process the level change
|
|
1703
|
-
setTimeout(() => sendModelUpdateIfChanged(), 50);
|
|
1704
|
-
}
|
|
1705
|
-
}),
|
|
1254
|
+
return handleInboundMessage(inst, data);
|
|
1255
|
+
}),
|
|
1706
1256
|
onReconnect: safe(() => {
|
|
1707
1257
|
if (!isActive()) return; // Stale listener guard
|
|
1708
1258
|
// A reconnect is a TRANSPORT boundary, not a session boundary: the live
|
|
@@ -1715,7 +1265,10 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1715
1265
|
const _bc = syncBc();
|
|
1716
1266
|
_resetReconnectCaches(_bc);
|
|
1717
1267
|
applyBc(_bc);
|
|
1718
|
-
|
|
1268
|
+
// Computed ONCE: the register's `liveTailOpen` and the replay's are the
|
|
1269
|
+
// same value. See change: fix-large-session-resume-replay (D7).
|
|
1270
|
+
const liveTailOpen = isLive(inst.cachedCtx, getBridgeState().isAgentStreaming);
|
|
1271
|
+
sendStateSync({ liveTailOpen });
|
|
1719
1272
|
// The server does not persist `piVersion` / `piBelowFloor`; re-send now
|
|
1720
1273
|
// rather than on the next poll tick. See change: update-pi-core-1-0-adopt-apis.
|
|
1721
1274
|
sendPiVersionIfChanged();
|
|
@@ -1723,7 +1276,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1723
1276
|
// doesn't have direct ctx here, so we walk the active session.
|
|
1724
1277
|
try {
|
|
1725
1278
|
const activeId = (pi as any).getCurrentSessionId?.();
|
|
1726
|
-
const activeCtx = activeId ? (pi as any).getCtx?.(activeId) : (cachedCtx as any);
|
|
1279
|
+
const activeCtx = activeId ? (pi as any).getCtx?.(activeId) : (inst.cachedCtx as any);
|
|
1727
1280
|
if (activeCtx?.cwd) {
|
|
1728
1281
|
// First evaluation again: the server lost its git state with the connection.
|
|
1729
1282
|
const gbc = syncBc();
|
|
@@ -1732,7 +1285,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1732
1285
|
sendCwdMissingIfChanged(activeCtx.cwd);
|
|
1733
1286
|
}
|
|
1734
1287
|
} catch { /* probe failure non-fatal */ }
|
|
1735
|
-
|
|
1288
|
+
// A live reconnect keeps in-flight calls open (no fabricated end).
|
|
1289
|
+
// See change: fix-replay-fabricates-orphan-end-for-live-calls (D3).
|
|
1290
|
+
replaySessionEntries({ liveTailOpen });
|
|
1736
1291
|
// Flush subagent frames buffered while the socket was down (D1). Unlike
|
|
1737
1292
|
// session_start, a transient WS reconnect keeps `sessionReady` true, so
|
|
1738
1293
|
// the intercept routes those frames into the per-agent buffer; drain them
|
|
@@ -1744,13 +1299,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1744
1299
|
// Client-side dedup by requestId prevents double-rendering. Shared with the
|
|
1745
1300
|
// prompt_resync_request handler so the two frames cannot drift (D7).
|
|
1746
1301
|
// See change: fix-pending-prompt-lost-on-replay.
|
|
1747
|
-
if (promptBus) {
|
|
1748
|
-
emitPendingPrompts(promptBus, (m) => connection.send(m as any), sessionId);
|
|
1302
|
+
if (inst.promptBus) {
|
|
1303
|
+
emitPendingPrompts(inst.promptBus, (m) => inst.connection.send(m as any), inst.sessionId);
|
|
1749
1304
|
}
|
|
1750
|
-
connection.send({ type: "replay_complete", sessionId });
|
|
1305
|
+
inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
|
|
1751
1306
|
// If agent is mid-turn, send synthetic agent_start so server sets status to "streaming"
|
|
1307
|
+
// `synthetic` lets the server's end-of-session scan see past it (D4).
|
|
1752
1308
|
if (getBridgeState().isAgentStreaming) {
|
|
1753
|
-
connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
|
|
1309
|
+
inst.connection.send(mapEventToProtocol(inst.sessionId, { type: "agent_start", synthetic: true }));
|
|
1754
1310
|
}
|
|
1755
1311
|
// Extension UI System (Phase 1): re-probe modules after every
|
|
1756
1312
|
// reconnect so the server-side cache stays accurate. The probe is
|
|
@@ -1773,43 +1329,69 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1773
1329
|
onPostFlush: safe(() => {
|
|
1774
1330
|
if (!isActive()) return; // Stale listener guard
|
|
1775
1331
|
if (getBridgeState().isAgentStreaming) return;
|
|
1776
|
-
connection.send({ type: "session_heartbeat", sessionId, agentRunning: false });
|
|
1332
|
+
inst.connection.send({ type: "session_heartbeat", sessionId: inst.sessionId, agentRunning: false });
|
|
1777
1333
|
}),
|
|
1778
1334
|
});
|
|
1779
1335
|
// The lane's lifecycle hooks compare against this to ignore a moved-away origin.
|
|
1780
|
-
const primaryConnection = connection;
|
|
1336
|
+
const primaryConnection = inst.connection;
|
|
1781
1337
|
|
|
1782
1338
|
// Track connection so future bridge incarnations can disconnect it
|
|
1783
|
-
getBridgeState().connections!.push(connection);
|
|
1339
|
+
getBridgeState().connections!.push(inst.connection);
|
|
1784
1340
|
|
|
1785
1341
|
// See change: fix-terminal-session-dashboard-reload.
|
|
1786
|
-
const terminalReload = createTerminalReload({ pi, getSessionId: () => sessionId });
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1342
|
+
const terminalReload = createTerminalReload({ pi, getSessionId: () => inst.sessionId });
|
|
1343
|
+
|
|
1344
|
+
// One limiter per bridge process: kept in the process-global state so a
|
|
1345
|
+
// `/reload` does not refill the prompt bucket. See change:
|
|
1346
|
+
// harden-bridge-inbound-and-discovery (D17).
|
|
1347
|
+
const bridgeState = getBridgeState();
|
|
1348
|
+
const inboundLimits = (bridgeState.inboundLimits ??= createInboundLimits());
|
|
1349
|
+
inst.inboundLimits = inboundLimits;
|
|
1350
|
+
|
|
1351
|
+
const commandHandler = createCommandHandler(pi, () => inst.sessionId, {
|
|
1352
|
+
limits: inboundLimits,
|
|
1353
|
+
getModelRegistry: () => inst.cachedModelRegistry,
|
|
1354
|
+
// Selector-open re-sync of providers.json: heals a missed credentials_updated.
|
|
1355
|
+
// See change: refresh-models-on-provider-change (D1).
|
|
1356
|
+
reloadProviders: async () => { await reloadProviders(pi); },
|
|
1790
1357
|
// Surface a session-id-mismatch drop server-side; the guard's own
|
|
1791
1358
|
// `console.error` goes to /dev/null under the default
|
|
1792
1359
|
// `keeperLog.capturePiOutput:false`.
|
|
1793
1360
|
// See change: fix-spawn-correlation-ttl-coupling (D6).
|
|
1794
|
-
reportInboundDrop: (drop) => connection.reportInboundDrop(drop),
|
|
1361
|
+
reportInboundDrop: (drop) => inst.connection.reportInboundDrop(drop),
|
|
1795
1362
|
// AI-draft fork-subagent wiring (see change:
|
|
1796
1363
|
// add-session-uncommitted-indicator-and-commit). Both degrade silently
|
|
1797
1364
|
// to the draft ladder's lower rungs when unavailable.
|
|
1798
|
-
getSessionContextText: () => buildSessionContextText(cachedCtx),
|
|
1365
|
+
getSessionContextText: () => buildSessionContextText(inst.cachedCtx),
|
|
1799
1366
|
runDraftAgent: (seed: string, cwd: string) =>
|
|
1800
|
-
runForkSubagentDraft(seed, cwd, () => cachedCtx?.model),
|
|
1367
|
+
runForkSubagentDraft(seed, cwd, () => inst.cachedCtx?.model),
|
|
1801
1368
|
// Mirror server attach/detach pushes into BridgeContext.attachedChange so
|
|
1802
1369
|
// the before_agent_start injector exposes it. See change:
|
|
1803
1370
|
// inject-session-context-into-agent.
|
|
1371
|
+
// Dashboard system renames reach the namer BEFORE pi echoes them, so the
|
|
1372
|
+
// echo is not latched `user`. See change: investigate-auto-name-provenance-relabel (D3).
|
|
1373
|
+
onSystemRename: (name: string) => {
|
|
1374
|
+
const prevName = inst.lastSessionName;
|
|
1375
|
+
const rollbackNamer = getAutoNamer().noteSystemRename(name);
|
|
1376
|
+
inst.lastSessionName = name; // suppress the redundant plain name poll
|
|
1377
|
+
return () => {
|
|
1378
|
+
rollbackNamer();
|
|
1379
|
+
inst.lastSessionName = prevName;
|
|
1380
|
+
};
|
|
1381
|
+
},
|
|
1382
|
+
onUserRename: () => {
|
|
1383
|
+
// Only matters once a namer exists; never create one for a user rename.
|
|
1384
|
+
inst.autoNamer?.noteUserRename();
|
|
1385
|
+
},
|
|
1804
1386
|
onAttachProposalChanged: (next: string | null) => {
|
|
1805
|
-
attachedChange = next;
|
|
1387
|
+
inst.attachedChange = next;
|
|
1806
1388
|
const s = getBridgeState();
|
|
1807
1389
|
s.attachedChange = next;
|
|
1808
1390
|
},
|
|
1809
1391
|
setThinkingLevel: (level: string) => (pi as any).setThinkingLevel?.(level),
|
|
1810
1392
|
getThinkingLevel: () => (pi as any).getThinkingLevel?.(),
|
|
1811
1393
|
setModel: async (provider: string, modelId: string) => {
|
|
1812
|
-
const registry = cachedModelRegistry;
|
|
1394
|
+
const registry = inst.cachedModelRegistry;
|
|
1813
1395
|
if (!registry) return;
|
|
1814
1396
|
const model = registry.find(provider, modelId);
|
|
1815
1397
|
if (!model) return;
|
|
@@ -1828,8 +1410,8 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1828
1410
|
// that. See change: honest-mid-turn-queue-surface (spec
|
|
1829
1411
|
// mid-turn-prompt-queue: "Session shutdown invokes cachedCtx.shutdown
|
|
1830
1412
|
// directly").
|
|
1831
|
-
if (cachedCtx?.shutdown) {
|
|
1832
|
-
cachedCtx.shutdown();
|
|
1413
|
+
if (inst.cachedCtx?.shutdown) {
|
|
1414
|
+
inst.cachedCtx.shutdown();
|
|
1833
1415
|
}
|
|
1834
1416
|
// Safety net: force exit after a short delay in case ctx.shutdown()
|
|
1835
1417
|
// doesn't terminate (e.g. in RPC mode headless sessions)
|
|
@@ -1847,12 +1429,12 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1847
1429
|
// must win — requesting AFTER abort() would leak a set latch onto a later
|
|
1848
1430
|
// turn. Cleared on the next user prompt (noteUserPrompt) or terminal
|
|
1849
1431
|
// agent_end. See change: unify-error-retry-lifecycle.
|
|
1850
|
-
abortLatch.request(sessionId);
|
|
1432
|
+
abortLatch.request(inst.sessionId);
|
|
1851
1433
|
// Install retry cancellation BEFORE invoking pi: abort() can dispatch
|
|
1852
1434
|
// terminal events synchronously, and those belong to the cancelled chain.
|
|
1853
|
-
retryTracker.noteAbort(sessionId);
|
|
1854
|
-
if (cachedCtx?.abort) {
|
|
1855
|
-
cachedCtx.abort();
|
|
1435
|
+
retryTracker.noteAbort(inst.sessionId);
|
|
1436
|
+
if (inst.cachedCtx?.abort) {
|
|
1437
|
+
inst.cachedCtx.abort();
|
|
1856
1438
|
}
|
|
1857
1439
|
},
|
|
1858
1440
|
/**
|
|
@@ -1864,18 +1446,18 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1864
1446
|
*/
|
|
1865
1447
|
rawAbort: () => {
|
|
1866
1448
|
try {
|
|
1867
|
-
cachedCtx?.abort?.();
|
|
1449
|
+
inst.cachedCtx?.abort?.();
|
|
1868
1450
|
} catch (err) {
|
|
1869
1451
|
console.warn("[dashboard] cachedCtx.abort threw in rawAbort:", err);
|
|
1870
1452
|
}
|
|
1871
1453
|
},
|
|
1872
1454
|
isIdle: () => {
|
|
1873
|
-
try { return cachedCtx?.isIdle?.() ?? false; } catch { return false; }
|
|
1455
|
+
try { return inst.cachedCtx?.isIdle?.() ?? false; } catch { return false; }
|
|
1874
1456
|
},
|
|
1875
|
-
eventSink: (msg) => connection.send(msg),
|
|
1457
|
+
eventSink: (msg) => inst.connection.send(msg),
|
|
1876
1458
|
compact: (opts) => {
|
|
1877
|
-
if (cachedCtx?.compact) {
|
|
1878
|
-
cachedCtx.compact(opts);
|
|
1459
|
+
if (inst.cachedCtx?.compact) {
|
|
1460
|
+
inst.cachedCtx.compact(opts);
|
|
1879
1461
|
}
|
|
1880
1462
|
},
|
|
1881
1463
|
// Terminal-hosted path only. Dashboard-spawned headless sessions are
|
|
@@ -1886,7 +1468,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1886
1468
|
// See change: fix-terminal-session-dashboard-reload (D1/D3/D4).
|
|
1887
1469
|
reload: terminalReload.reload,
|
|
1888
1470
|
spawnNew: () => {
|
|
1889
|
-
connection.send({ type: "spawn_new_session", sessionId, cwd: process.cwd() });
|
|
1471
|
+
inst.connection.send({ type: "spawn_new_session", sessionId: inst.sessionId, cwd: process.cwd() });
|
|
1890
1472
|
},
|
|
1891
1473
|
sessionPrompt: async (text, delivery, promptId) => {
|
|
1892
1474
|
// Route slash commands: management events, flow:run, extension dispatch, then fallback.
|
|
@@ -1902,7 +1484,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1902
1484
|
if (flowsList.some(f => f.name === cmdName)) {
|
|
1903
1485
|
// Non-turn slash route: settle any optimistic idle bubble so it does
|
|
1904
1486
|
// not hang to the 30s timeout. See change: optimistic-prompt-progress.
|
|
1905
|
-
connection.send({ type: "prompt_received", sessionId, fresh: false });
|
|
1487
|
+
inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
|
|
1906
1488
|
pi.events.emit("flow:run", { flowName: cmdName, task: cmdArgs.trim() || undefined });
|
|
1907
1489
|
return;
|
|
1908
1490
|
}
|
|
@@ -1916,14 +1498,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1916
1498
|
const handled = await tryDispatchExtensionCommand(
|
|
1917
1499
|
pi,
|
|
1918
1500
|
text,
|
|
1919
|
-
sessionId,
|
|
1920
|
-
(msg) => connection.send(msg),
|
|
1501
|
+
inst.sessionId,
|
|
1502
|
+
(msg) => inst.connection.send(msg),
|
|
1921
1503
|
delivery,
|
|
1922
1504
|
);
|
|
1923
1505
|
if (handled) {
|
|
1924
1506
|
// Non-turn dispatch route: settle optimistic idle bubble (no message_start
|
|
1925
1507
|
// follows). See change: optimistic-prompt-progress.
|
|
1926
|
-
connection.send({ type: "prompt_received", sessionId, fresh: false });
|
|
1508
|
+
inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
|
|
1927
1509
|
return;
|
|
1928
1510
|
}
|
|
1929
1511
|
|
|
@@ -1934,24 +1516,27 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1934
1516
|
pi,
|
|
1935
1517
|
text,
|
|
1936
1518
|
process.cwd(),
|
|
1937
|
-
sessionId,
|
|
1938
|
-
(msg) => connection.send(msg),
|
|
1519
|
+
inst.sessionId,
|
|
1520
|
+
(msg) => inst.connection.send(msg),
|
|
1521
|
+
inst.inboundLimits,
|
|
1939
1522
|
);
|
|
1940
1523
|
if (ranExec) {
|
|
1941
1524
|
// Non-turn exec-template route: settle optimistic idle bubble.
|
|
1942
1525
|
// See change: optimistic-prompt-progress.
|
|
1943
|
-
connection.send({ type: "prompt_received", sessionId, fresh: false });
|
|
1526
|
+
inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false });
|
|
1944
1527
|
return;
|
|
1945
1528
|
}
|
|
1946
1529
|
|
|
1947
1530
|
// Fallback: route the user prompt based on delivery + streaming state.
|
|
1948
1531
|
//
|
|
1949
1532
|
// delivery="followUp" + streaming → buffer in bridgeFollowUp ONLY
|
|
1950
|
-
// (pi never sees it until drain
|
|
1533
|
+
// (pi never sees it until drain on
|
|
1534
|
+
// agent_settled).
|
|
1951
1535
|
// delivery="steer" + streaming → pi.sendUserMessage({deliverAs:"steer"})
|
|
1952
1536
|
// + shadow append via recordSteerSent.
|
|
1953
|
-
// any delivery + idle → pi.sendUserMessage
|
|
1954
|
-
// (
|
|
1537
|
+
// any delivery + idle → pi.sendUserMessage with {deliverAs}
|
|
1538
|
+
// (pi ignores it when idle and starts
|
|
1539
|
+
// a fresh turn). No buffer push.
|
|
1955
1540
|
//
|
|
1956
1541
|
// Capture pre-send streaming state BEFORE any pi call — idle sends
|
|
1957
1542
|
// synchronously fire agent_start which flips isAgentStreaming.
|
|
@@ -1969,16 +1554,16 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1969
1554
|
// See change: optimistic-prompt-progress,
|
|
1970
1555
|
// fix-spawn-correlation-ttl-coupling (D7).
|
|
1971
1556
|
const buffered = wasStreaming && deliverAs === "followUp";
|
|
1972
|
-
connection.send({
|
|
1557
|
+
inst.connection.send({
|
|
1973
1558
|
type: "prompt_received",
|
|
1974
|
-
sessionId,
|
|
1559
|
+
sessionId: inst.sessionId,
|
|
1975
1560
|
fresh: !wasStreaming,
|
|
1976
1561
|
...(promptId && !buffered ? { promptId } : {}),
|
|
1977
1562
|
});
|
|
1978
1563
|
const expanded = expandPromptTemplateFromDisk(text, process.cwd(), pi);
|
|
1979
1564
|
if (buffered) {
|
|
1980
1565
|
// Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
|
|
1981
|
-
// drain
|
|
1566
|
+
// drain on agent_settled will ship the entry as a fresh turn.
|
|
1982
1567
|
bufferFollowupSend(expanded);
|
|
1983
1568
|
} else {
|
|
1984
1569
|
// Idle send or steer send — forward to pi directly.
|
|
@@ -1992,12 +1577,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
1992
1577
|
// Clear only the abort latch before prompt routing. A streaming follow-up
|
|
1993
1578
|
// may be buffered rather than start a run, so retry cancellation is released
|
|
1994
1579
|
// only by the observed user message_start below.
|
|
1995
|
-
noteUserPrompt: () => abortLatch.clear(sessionId),
|
|
1580
|
+
noteUserPrompt: () => abortLatch.clear(inst.sessionId),
|
|
1996
1581
|
// Disarm a still-armed provider-retry chain so a manual retry's native
|
|
1997
1582
|
// agent_start is not converted into a synthetic auto_retry_start.
|
|
1998
1583
|
// See change: replace-dashboard-retry-command-with-protocol-message.
|
|
1999
|
-
disarmRetryChain: () => retryTracker.noteExplicitRun(sessionId),
|
|
1584
|
+
disarmRetryChain: () => retryTracker.noteExplicitRun(inst.sessionId),
|
|
2000
1585
|
});
|
|
1586
|
+
inst.commandHandler = commandHandler;
|
|
2001
1587
|
|
|
2002
1588
|
// Reload support: only a command handler's ctx has `reload()`. The bridge
|
|
2003
1589
|
// self-dispatches this command (dashboard reload, token arg); a human may
|
|
@@ -2039,7 +1625,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2039
1625
|
console.error(`[dashboard] connect refused: ${resolved.reason}`);
|
|
2040
1626
|
return;
|
|
2041
1627
|
}
|
|
2042
|
-
if (resolved.endpoint === dashboardUrl) {
|
|
1628
|
+
if (resolved.endpoint === inst.dashboardUrl) {
|
|
2043
1629
|
console.error(`[dashboard] already on ${describeConnectTarget(parsed)}`);
|
|
2044
1630
|
return;
|
|
2045
1631
|
}
|
|
@@ -2060,25 +1646,28 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2060
1646
|
let targetManager: ConnectionManager | undefined;
|
|
2061
1647
|
const coordinator = createMoveCoordinator({
|
|
2062
1648
|
origin: {
|
|
2063
|
-
connect: () => connection.connect(),
|
|
2064
|
-
disconnect: () => connection.disconnect(),
|
|
2065
|
-
send: (m) => connection.send(m),
|
|
1649
|
+
connect: () => inst.connection.connect(),
|
|
1650
|
+
disconnect: () => inst.connection.disconnect(),
|
|
1651
|
+
send: (m) => inst.connection.send(m),
|
|
2066
1652
|
get isConnected() {
|
|
2067
|
-
return connection.isConnected;
|
|
1653
|
+
return inst.connection.isConnected;
|
|
2068
1654
|
},
|
|
2069
1655
|
// The coordinator never subscribes to the origin; only the target
|
|
2070
1656
|
// answers the handshake.
|
|
2071
1657
|
onMessage: () => {},
|
|
2072
1658
|
},
|
|
2073
|
-
sessionId,
|
|
2074
|
-
sessionFile: lastSessionFile,
|
|
2075
|
-
originEndpoint: dashboardUrl,
|
|
1659
|
+
sessionId: inst.sessionId,
|
|
1660
|
+
sessionFile: inst.lastSessionFile,
|
|
1661
|
+
originEndpoint: inst.dashboardUrl,
|
|
1662
|
+
onServerMessage: (m) => void pathGate.onServerMessage(m),
|
|
2076
1663
|
connect: (url) => {
|
|
2077
1664
|
let handler: (msg: unknown) => void = () => {};
|
|
2078
1665
|
targetManager = new ConnectionManager({
|
|
2079
1666
|
url,
|
|
2080
|
-
|
|
2081
|
-
|
|
1667
|
+
outboundFilter: (m) => vaultForwardFilter.filter(m),
|
|
1668
|
+
planDial: (base) => localCredentialPlan(base),
|
|
1669
|
+
onIdentityFailure: (report) => appendIdentityLog(report),
|
|
1670
|
+
getSessionId: () => inst.sessionId,
|
|
2082
1671
|
onMessage: (data) => {
|
|
2083
1672
|
// Plugin lane replies resolve the caller's Promise only.
|
|
2084
1673
|
if ((data as { type?: unknown } | null)?.type === "plugin_reply") {
|
|
@@ -2088,7 +1677,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2088
1677
|
handler(data);
|
|
2089
1678
|
},
|
|
2090
1679
|
onClose: () => {
|
|
2091
|
-
if (connection === targetManager) pluginLaneDown();
|
|
1680
|
+
if (inst.connection === targetManager) pluginLaneDown();
|
|
2092
1681
|
},
|
|
2093
1682
|
// The move REBINDS `connection` to this manager, so without this
|
|
2094
1683
|
// every post-move force-close would be silent again.
|
|
@@ -2101,15 +1690,16 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2101
1690
|
// provisional registration is announced, and a send before the
|
|
2102
1691
|
// socket is live would be silently dropped.
|
|
2103
1692
|
onOpen: () => {
|
|
2104
|
-
if (connection === targetManager) pluginLaneUp();
|
|
1693
|
+
if (inst.connection === targetManager) pluginLaneUp();
|
|
2105
1694
|
targetManager?.send({
|
|
2106
1695
|
type: "session_register",
|
|
2107
1696
|
extensionIdentity: bridgeExtensionIdentity(),
|
|
2108
|
-
sessionId,
|
|
1697
|
+
sessionId: inst.sessionId,
|
|
2109
1698
|
cwd: process.cwd(),
|
|
2110
1699
|
source: "tui",
|
|
2111
1700
|
pid: process.pid,
|
|
2112
1701
|
provisional: true,
|
|
1702
|
+
...(targetManager?.certValidation ? { certValidation: "enforced" as const } : {}),
|
|
2113
1703
|
});
|
|
2114
1704
|
},
|
|
2115
1705
|
});
|
|
@@ -2136,19 +1726,19 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2136
1726
|
|
|
2137
1727
|
if (!result.ok) {
|
|
2138
1728
|
console.error(
|
|
2139
|
-
`[dashboard] move to ${describeConnectTarget(parsed)} failed: ${result.cause} — still on ${dashboardUrl}`,
|
|
1729
|
+
`[dashboard] move to ${describeConnectTarget(parsed)} failed: ${result.cause} — still on ${inst.dashboardUrl}`,
|
|
2140
1730
|
);
|
|
2141
1731
|
return;
|
|
2142
1732
|
}
|
|
2143
1733
|
|
|
2144
1734
|
// Rebind: from here every `connection.send(...)` in this module reaches
|
|
2145
1735
|
// the new dashboard.
|
|
2146
|
-
if (targetManager) connection = targetManager;
|
|
1736
|
+
if (targetManager) inst.connection = targetManager;
|
|
2147
1737
|
// The origin's close already took the plugin lane down; bring it up on
|
|
2148
1738
|
// the target now that it is the current connection.
|
|
2149
|
-
if (connection.isConnected) pluginLaneUp();
|
|
2150
|
-
dashboardUrl = resolved.endpoint;
|
|
2151
|
-
registeredInstanceId = expectInstanceId;
|
|
1739
|
+
if (inst.connection.isConnected) pluginLaneUp();
|
|
1740
|
+
inst.dashboardUrl = resolved.endpoint;
|
|
1741
|
+
inst.registeredInstanceId = expectInstanceId;
|
|
2152
1742
|
console.error(`[dashboard] moved to ${describeConnectTarget(parsed)} (${expectInstanceId})`);
|
|
2153
1743
|
},
|
|
2154
1744
|
});
|
|
@@ -2179,8 +1769,8 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2179
1769
|
pi.registerCommand("dashboard-where", {
|
|
2180
1770
|
handler: async () => {
|
|
2181
1771
|
const lines = [
|
|
2182
|
-
`endpoint: ${dashboardUrl}`,
|
|
2183
|
-
`instance: ${registeredInstanceId ?? "unverified"}`,
|
|
1772
|
+
`endpoint: ${inst.dashboardUrl}`,
|
|
1773
|
+
`instance: ${inst.registeredInstanceId ?? "unverified"}`,
|
|
2184
1774
|
`pinned: ${endpointPinned ? "yes (explicit configuration)" : "no (resolved from the $HOME rendezvous record)"}`,
|
|
2185
1775
|
`pr-probe: ${prStatus.invocations()} gh invocation(s) this bridge`,
|
|
2186
1776
|
];
|
|
@@ -2191,11 +1781,11 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2191
1781
|
/** Sync local variables into BridgeContext for extracted module calls */
|
|
2192
1782
|
function syncBc(): BridgeContext {
|
|
2193
1783
|
return {
|
|
2194
|
-
pi, connection, sessionId, attachedChange,
|
|
2195
|
-
cachedCtx, cachedModelRegistry, cachedHasUI,
|
|
2196
|
-
lastModel, lastThinkingLevel,
|
|
2197
|
-
lastSessionFile, lastSessionDir, lastFirstMessage,
|
|
2198
|
-
lastGitBranch, lastGitPrJson, lastSessionName,
|
|
1784
|
+
pi, connection: inst.connection, sessionId: inst.sessionId, attachedChange: inst.attachedChange,
|
|
1785
|
+
cachedCtx: inst.cachedCtx, cachedModelRegistry: inst.cachedModelRegistry, cachedHasUI: inst.cachedHasUI,
|
|
1786
|
+
lastModel: inst.lastModel, lastThinkingLevel: inst.lastThinkingLevel,
|
|
1787
|
+
lastSessionFile: inst.lastSessionFile, lastSessionDir: inst.lastSessionDir, lastFirstMessage: inst.lastFirstMessage,
|
|
1788
|
+
lastGitBranch, lastGitPrJson, lastSessionName: inst.lastSessionName,
|
|
2199
1789
|
lastGitWorktreeJson,
|
|
2200
1790
|
lastGitStatusJson,
|
|
2201
1791
|
lastCwdMissing,
|
|
@@ -2206,32 +1796,37 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2206
1796
|
gitTracker: polling.gitTracker ?? undefined,
|
|
2207
1797
|
};
|
|
2208
1798
|
}
|
|
1799
|
+
inst.syncBc = syncBc;
|
|
2209
1800
|
/** Sync BridgeContext mutations back to local variables */
|
|
2210
1801
|
function applyBc(bc: BridgeContext): void {
|
|
2211
|
-
sessionId = bc.sessionId;
|
|
2212
|
-
attachedChange = bc.attachedChange;
|
|
2213
|
-
cachedCtx = bc.cachedCtx;
|
|
2214
|
-
cachedModelRegistry = bc.cachedModelRegistry;
|
|
2215
|
-
cachedHasUI = bc.cachedHasUI;
|
|
2216
|
-
lastModel = bc.lastModel;
|
|
2217
|
-
lastThinkingLevel = bc.lastThinkingLevel;
|
|
2218
|
-
lastSessionFile = bc.lastSessionFile;
|
|
2219
|
-
lastSessionDir = bc.lastSessionDir;
|
|
2220
|
-
lastFirstMessage = bc.lastFirstMessage;
|
|
1802
|
+
inst.sessionId = bc.sessionId;
|
|
1803
|
+
inst.attachedChange = bc.attachedChange;
|
|
1804
|
+
inst.cachedCtx = bc.cachedCtx;
|
|
1805
|
+
inst.cachedModelRegistry = bc.cachedModelRegistry;
|
|
1806
|
+
inst.cachedHasUI = bc.cachedHasUI;
|
|
1807
|
+
inst.lastModel = bc.lastModel;
|
|
1808
|
+
inst.lastThinkingLevel = bc.lastThinkingLevel;
|
|
1809
|
+
inst.lastSessionFile = bc.lastSessionFile;
|
|
1810
|
+
inst.lastSessionDir = bc.lastSessionDir;
|
|
1811
|
+
inst.lastFirstMessage = bc.lastFirstMessage;
|
|
2221
1812
|
lastGitBranch = bc.lastGitBranch;
|
|
2222
1813
|
lastGitPrJson = bc.lastGitPrJson;
|
|
2223
|
-
lastSessionName = bc.lastSessionName;
|
|
1814
|
+
inst.lastSessionName = bc.lastSessionName;
|
|
2224
1815
|
lastGitWorktreeJson = bc.lastGitWorktreeJson;
|
|
2225
1816
|
lastGitStatusJson = bc.lastGitStatusJson;
|
|
2226
1817
|
lastCwdMissing = bc.lastCwdMissing;
|
|
2227
1818
|
hasRegisteredOnce = bc.hasRegisteredOnce;
|
|
2228
1819
|
}
|
|
1820
|
+
inst.applyBc = applyBc;
|
|
2229
1821
|
|
|
2230
1822
|
// Local wrappers that sync bc around extracted module calls
|
|
2231
|
-
function sendStateSync() { const bc = syncBc(); _sendStateSync(bc, getFlowsList); applyBc(bc); connection.noteRegistered(); }
|
|
2232
|
-
function replaySessionEntries() { _replaySessionEntries(syncBc()); }
|
|
1823
|
+
function sendStateSync(opts?: { liveTailOpen?: boolean }) { const bc = syncBc(); _sendStateSync(bc, getFlowsList, opts); applyBc(bc); inst.connection.noteRegistered(); }
|
|
1824
|
+
function replaySessionEntries(opts?: { liveTailOpen?: boolean }) { _replaySessionEntries(syncBc(), opts); }
|
|
1825
|
+
inst.replaySessionEntries = replaySessionEntries;
|
|
2233
1826
|
function sendModelUpdateIfChanged() { const bc = syncBc(); _sendModelUpdateIfChanged(bc); applyBc(bc); }
|
|
1827
|
+
inst.sendModelUpdateIfChanged = sendModelUpdateIfChanged;
|
|
2234
1828
|
function sendSessionNameIfChanged() { const bc = syncBc(); _sendSessionNameIfChanged(bc); applyBc(bc); }
|
|
1829
|
+
inst.sendSessionNameIfChanged = sendSessionNameIfChanged;
|
|
2235
1830
|
|
|
2236
1831
|
// ── add-auto-session-naming ──────────────────────────────────────────────
|
|
2237
1832
|
// Stream through pi's OWN `ctx.modelRegistry`, not a bare-imported pi-ai
|
|
@@ -2247,7 +1842,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2247
1842
|
// is captured lazily, so caching a miss would pin auto-naming off for the
|
|
2248
1843
|
// whole session. See change: adopt-piai-factory-api-registry.
|
|
2249
1844
|
async function loadStreamSimple(): Promise<StreamSimpleFn | undefined> {
|
|
2250
|
-
const registry: any = cachedModelRegistry;
|
|
1845
|
+
const registry: any = inst.cachedModelRegistry;
|
|
2251
1846
|
if (typeof registry?.streamSimple === "function") {
|
|
2252
1847
|
return registry.streamSimple.bind(registry) as StreamSimpleFn;
|
|
2253
1848
|
}
|
|
@@ -2264,40 +1859,41 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2264
1859
|
// One namer per bridge (a bridge is a single pi session). Built lazily so it
|
|
2265
1860
|
// captures the live `cachedCtx` / `cachedModelRegistry` at call time.
|
|
2266
1861
|
function getAutoNamer(): AutoNamer {
|
|
2267
|
-
if (autoNamer) return autoNamer;
|
|
2268
|
-
autoNamer = createAutoNamer({
|
|
2269
|
-
getAutoNameSessions: () => autoNameSessions,
|
|
1862
|
+
if (inst.autoNamer) return inst.autoNamer;
|
|
1863
|
+
inst.autoNamer = createAutoNamer({
|
|
1864
|
+
getAutoNameSessions: () => inst.autoNameSessions,
|
|
2270
1865
|
resolveNamingModel,
|
|
2271
|
-
getRegistry: () => cachedModelRegistry,
|
|
1866
|
+
getRegistry: () => inst.cachedModelRegistry,
|
|
2272
1867
|
loadStreamSimple,
|
|
2273
|
-
getTranscript: () => extractLatestTurnWindow(cachedCtx),
|
|
1868
|
+
getTranscript: () => extractLatestTurnWindow(inst.cachedCtx),
|
|
2274
1869
|
applyName: (title: string) => {
|
|
2275
1870
|
try { pi.setSessionName(title); } catch { /* ignore */ }
|
|
2276
|
-
lastSessionName = title; // suppress the redundant plain name_update poll
|
|
2277
|
-
connection.send({ type: "session_name_update", sessionId, name: title, nameSource: "auto" });
|
|
1871
|
+
inst.lastSessionName = title; // suppress the redundant plain name_update poll
|
|
1872
|
+
inst.connection.send({ type: "session_name_update", sessionId: inst.sessionId, name: title, nameSource: "auto" });
|
|
2278
1873
|
},
|
|
2279
1874
|
reportUserRename: (name: string) => {
|
|
2280
|
-
connection.send({ type: "session_name_update", sessionId, name, nameSource: "user" });
|
|
1875
|
+
inst.connection.send({ type: "session_name_update", sessionId: inst.sessionId, name, nameSource: "user" });
|
|
2281
1876
|
},
|
|
2282
1877
|
emitError: (reason: string) => {
|
|
2283
|
-
connection.send({ type: "auto_name_error", sessionId, reason });
|
|
1878
|
+
inst.connection.send({ type: "auto_name_error", sessionId: inst.sessionId, reason });
|
|
2284
1879
|
},
|
|
2285
1880
|
reportOutcome: ({ outcome, reason, modelRef }) => {
|
|
2286
|
-
connection.send({
|
|
2287
|
-
type: "auto_name_outcome", sessionId, outcome, reason, modelRef, at: Date.now(),
|
|
1881
|
+
inst.connection.send({
|
|
1882
|
+
type: "auto_name_outcome", sessionId: inst.sessionId, outcome, reason, modelRef, at: Date.now(),
|
|
2288
1883
|
});
|
|
2289
1884
|
},
|
|
2290
1885
|
// Carried across reload AND persisted server-side into the session's
|
|
2291
1886
|
// `.meta.json`, so "permanent" survives a process restart rather than
|
|
2292
1887
|
// re-spending a full budget on every cold start (design D7).
|
|
2293
1888
|
persistState: (state: PersistedNamerState) => {
|
|
2294
|
-
namerState = state;
|
|
1889
|
+
inst.namerState = state;
|
|
2295
1890
|
prev.namerState = state;
|
|
2296
|
-
connection.send({ type: "auto_name_state", sessionId, state });
|
|
1891
|
+
inst.connection.send({ type: "auto_name_state", sessionId: inst.sessionId, state });
|
|
2297
1892
|
},
|
|
2298
|
-
}, namerState);
|
|
2299
|
-
return autoNamer;
|
|
1893
|
+
}, inst.namerState);
|
|
1894
|
+
return inst.autoNamer;
|
|
2300
1895
|
}
|
|
1896
|
+
inst.getAutoNamer = getAutoNamer;
|
|
2301
1897
|
|
|
2302
1898
|
// Run one naming attempt after a terminal turn. Observing the current name
|
|
2303
1899
|
// first catches a pre-existing / in-pi rename (external → permanent "user"
|
|
@@ -2312,594 +1908,23 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2312
1908
|
// See change: fix-auto-naming-reasoning-model.
|
|
2313
1909
|
function runAutoNameOnTurnEnd(): void {
|
|
2314
1910
|
const namer = getAutoNamer();
|
|
2315
|
-
if (autoNameSessions) namer.onObservedName(pi.getSessionName() ?? "");
|
|
1911
|
+
if (inst.autoNameSessions) namer.onObservedName(pi.getSessionName() ?? "");
|
|
2316
1912
|
void namer.maybeName();
|
|
2317
1913
|
}
|
|
1914
|
+
inst.runAutoNameOnTurnEnd = runAutoNameOnTurnEnd;
|
|
2318
1915
|
|
|
2319
1916
|
function sendCwdMissingIfChanged(cwd: string) { const bc = syncBc(); _sendCwdMissingIfChanged(bc, cwd); applyBc(bc); }
|
|
1917
|
+
inst.sendCwdMissingIfChanged = sendCwdMissingIfChanged;
|
|
2320
1918
|
function sendPiVersionIfChanged() { _sendPiVersionIfChanged(syncBc()); }
|
|
2321
|
-
|
|
2322
|
-
//
|
|
2323
|
-
//
|
|
2324
|
-
const enrichedEventTypes = [
|
|
2325
|
-
"agent_start",
|
|
2326
|
-
"agent_end",
|
|
2327
|
-
"agent_settled",
|
|
2328
|
-
"turn_start",
|
|
2329
|
-
"turn_end",
|
|
2330
|
-
"message_start",
|
|
2331
|
-
"message_update",
|
|
2332
|
-
"message_end",
|
|
2333
|
-
"tool_execution_start",
|
|
2334
|
-
"tool_execution_update",
|
|
2335
|
-
"tool_execution_end",
|
|
2336
|
-
"session_compact",
|
|
2337
|
-
"model_select",
|
|
2338
|
-
"thinking_level_select",
|
|
2339
|
-
] as const;
|
|
2340
|
-
// Pass-through events: forwarded as-is with no special handling.
|
|
2341
|
-
// Unrecognized types render as expandable JSON cards in the dashboard.
|
|
2342
|
-
const passThroughEventTypes = [
|
|
2343
|
-
"tool_call",
|
|
2344
|
-
"tool_result",
|
|
2345
|
-
"user_bash",
|
|
2346
|
-
"input",
|
|
2347
|
-
"before_agent_start",
|
|
2348
|
-
"resources_discover",
|
|
2349
|
-
"session_before_switch",
|
|
2350
|
-
"session_before_fork",
|
|
2351
|
-
"session_before_compact",
|
|
2352
|
-
"session_before_tree",
|
|
2353
|
-
"session_tree",
|
|
2354
|
-
// pi >= 0.84.3. Clears the server-side `compacting` latch on the failure
|
|
2355
|
-
// path (see event-status-extraction.ts) — without it a failed or aborted
|
|
2356
|
-
// compaction blocks every later reload of the session.
|
|
2357
|
-
"session_compact_failed",
|
|
2358
|
-
// pi >= 0.84.4. Brackets a BLOCKING `ctx.ui` prompt so the dashboard can
|
|
2359
|
-
// tell "agent working" apart from "pi parked waiting on a user prompt".
|
|
2360
|
-
// The 0.85.1 lockstep floor guarantees both events; the subscription is
|
|
2361
|
-
// unconditional (no version gate, not merely inert below an old floor).
|
|
2362
|
-
"ui_prompt_start",
|
|
2363
|
-
"ui_prompt_end",
|
|
2364
|
-
// pi >= 0.87. Fires before final settlement; no status effect (the agent
|
|
2365
|
-
// may still continue). Forwarded without its `context` preview.
|
|
2366
|
-
// See change: update-pi-core-1-0-adopt-apis (D5).
|
|
2367
|
-
"agent_before_settle",
|
|
2368
|
-
] as const;
|
|
2369
|
-
// Excluded from subscription (not forwarded):
|
|
2370
|
-
// - `context`: carries full message arrays (very large)
|
|
2371
|
-
// - `before_provider_request`: carries raw API payloads (very large)
|
|
2372
|
-
// - `session_start`: dedicated handler → session_register protocol message
|
|
2373
|
-
// - session change (new/fork/resume): handled inside session_start via event.reason
|
|
2374
|
-
// - `session_shutdown`: dedicated handler → disconnect/cleanup
|
|
2375
|
-
// - `cache_warming_decision`: dedicated observe-only handler → usage drain
|
|
2376
|
-
// (`usage_recorded`), never `event_forward`. See change: count-non-message-usage.
|
|
2377
|
-
|
|
2378
|
-
// Unified EventBus rename map for the emit intercept (flow + subagent events)
|
|
1919
|
+
inst.sendPiVersionIfChanged = sendPiVersionIfChanged;
|
|
1920
|
+
// Unified EventBus rename map (flow + subagent events): used by `sendEventForward` for the
|
|
1921
|
+
// channel→eventType rename and by `registerEventBusForwarding` for the per-channel subscription set.
|
|
2379
1922
|
const EVENT_BUS_MAP: Record<string, string> = { ...FLOW_EVENT_MAP, ...SUBAGENT_EVENT_MAP };
|
|
2380
1923
|
|
|
2381
|
-
|
|
2382
|
-
pi.on(eventType as any, safe(async (event: any, ctx: any) => {
|
|
2383
|
-
// Bail out if a newer bridge instance has taken over
|
|
2384
|
-
if (!isActive()) return;
|
|
2385
|
-
// Always keep latest context for abort/shutdown
|
|
2386
|
-
cachedCtx = ctx;
|
|
2387
|
-
// Don't send events before session_start has established the correct session ID
|
|
2388
|
-
if (!sessionReady) return;
|
|
2389
|
-
// ── Flush choke point (D5) ──────────────────────────────────────────
|
|
2390
|
-
// The invariant is "no non-`message_update` event may reach the wire while
|
|
2391
|
-
// a text snapshot is parked". ONE statement here — before ANY branch, so
|
|
2392
|
-
// it covers every early return below, including ones added later. Do not
|
|
2393
|
-
// move it into a branch: a branch-scoped flush is exactly the bug this
|
|
2394
|
-
// change exists to prevent.
|
|
2395
|
-
// See change: coalesce-bridge-message-update-snapshots.
|
|
2396
|
-
if (flushesParkedText(eventType)) coalescer.flush();
|
|
2397
|
-
// Adaptive process-scan cadence hooks. See change: optimize-polling-hot-paths.
|
|
2398
|
-
feedPollingEvent(eventType, event, polling);
|
|
2399
|
-
// Track agent streaming state (survives reconnect/reload)
|
|
2400
|
-
if (eventType === "agent_start") {
|
|
2401
|
-
getBridgeState().isAgentStreaming = true;
|
|
2402
|
-
// Abort latch (resumption hook): if a user abort is still latched when
|
|
2403
|
-
// pi fires a fresh agent_start for the aborted turn (no intervening
|
|
2404
|
-
// user prompt cleared it), abort again. See change:
|
|
2405
|
-
// unify-error-retry-lifecycle.
|
|
2406
|
-
if (abortLatch.shouldAbort(sessionId)) {
|
|
2407
|
-
try { cachedCtx?.abort?.(); } catch { /* idempotent */ }
|
|
2408
|
-
}
|
|
2409
|
-
// Provider-retry synthesis: when this agent_start is the awaited retry
|
|
2410
|
-
// attempt (a chain is armed), emit auto_retry_start so the surface
|
|
2411
|
-
// flips waiting → in-flight. Deferred via setTimeout(0) so it lands on
|
|
2412
|
-
// the wire AFTER this agent_start (the reducer defensively clears
|
|
2413
|
-
// retryState on agent_start, so the synth must arrive next to re-set
|
|
2414
|
-
// it). See change: retry-forever-with-stop-control (design D4).
|
|
2415
|
-
const retryStart = retryTracker.observeAgentStart(sessionId);
|
|
2416
|
-
if (retryStart) {
|
|
2417
|
-
setTimeout(() => {
|
|
2418
|
-
if (retryTracker.isRetrying(sessionId)) {
|
|
2419
|
-
sendSyntheticRetryEvent(retryStart.eventType, retryStart.data);
|
|
2420
|
-
}
|
|
2421
|
-
}, 0);
|
|
2422
|
-
}
|
|
2423
|
-
}
|
|
2424
|
-
if (eventType === "agent_settled") {
|
|
2425
|
-
// Terminal settle (native pi, guaranteed at the 0.85.1 lockstep floor;
|
|
2426
|
-
// fires once after the run loop). Clear streaming. This is the SOLE
|
|
2427
|
-
// terminal signal for a retry chain: close it with auto_retry_end
|
|
2428
|
-
// BEFORE forwarding the settle. The floor-pi synthesis path was
|
|
2429
|
-
// retired with agent-settled.ts. See changes: adopt-pi-074-080-features
|
|
2430
|
-
// (A.1), retry-forever-with-stop-control, update-pi-core-0-85-adopt-apis.
|
|
2431
|
-
getBridgeState().isAgentStreaming = false;
|
|
2432
|
-
abortLatch.clear(sessionId);
|
|
2433
|
-
// Drain point. See change: count-non-message-usage.
|
|
2434
|
-
drainUsage(ctx);
|
|
2435
|
-
const retryEnd = retryTracker.observeAgentSettled(sessionId);
|
|
2436
|
-
if (retryEnd) {
|
|
2437
|
-
sendSyntheticRetryEvent(retryEnd.eventType, retryEnd.data);
|
|
2438
|
-
}
|
|
2439
|
-
}
|
|
2440
|
-
if (eventType === "agent_end") {
|
|
2441
|
-
getBridgeState().isAgentStreaming = false;
|
|
2442
|
-
// Provider-retry synthesis: an error agent_end means an attempt just
|
|
2443
|
-
// failed and (optimistically) another is coming — emit the WAITING
|
|
2444
|
-
// signal (attempt + computed delay + nextAttemptAt) so the surface
|
|
2445
|
-
// shows a live countdown during pi's sleep. The chain is NOT closed
|
|
2446
|
-
// here; only agent_settled (above) terminates it. A non-error agent_end
|
|
2447
|
-
// returns null. See change: retry-forever-with-stop-control (design D4).
|
|
2448
|
-
const trackerSynth = retryTracker.observeAgentEnd(sessionId, event as any);
|
|
2449
|
-
if (trackerSynth) {
|
|
2450
|
-
sendSyntheticRetryEvent(trackerSynth.eventType, trackerSynth.data);
|
|
2451
|
-
}
|
|
2452
|
-
// Automatic session topic-naming: attempt on each terminal turn until
|
|
2453
|
-
// the first success (or a permanent lockout). Non-blocking; all errors
|
|
2454
|
-
// are handled inside the namer. See change: add-auto-session-naming.
|
|
2455
|
-
runAutoNameOnTurnEnd();
|
|
2456
|
-
// Bridge shadow follow-up queue: the per-entry drain matcher in
|
|
2457
|
-
// the `message_start` handler removes each entry as pi delivers it
|
|
2458
|
-
// (mirrors pi's internal `_processAgentEvent`). No bulk clear here
|
|
2459
|
-
// — it would wipe entries the user adds DURING the drain window.
|
|
2460
|
-
// See change: add-followup-edit-and-steer-cancel (per-entry-drain).
|
|
2461
|
-
|
|
2462
|
-
// Bridge-owned follow-up drain: pop one entry from bridgeFollowUp
|
|
2463
|
-
// and hand it to pi as a fresh turn (sendUserMessage no deliverAs).
|
|
2464
|
-
// Scheduled via setTimeout (not queueMicrotask) so pi's
|
|
2465
|
-
// finishRun() can flip isStreaming=false BEFORE we call back.
|
|
2466
|
-
// The drain function itself polls ctx.isIdle() and retries up to
|
|
2467
|
-
// ~2s if pi hasn't transitioned yet.
|
|
2468
|
-
// See change: rework-mid-turn-prompt-queue (post-smoke fix #3).
|
|
2469
|
-
setTimeout(() => drainFollowupQueue(0), 0);
|
|
2470
|
-
|
|
2471
|
-
// Empty-actionable-turn guard: classify this turn's terminal shape.
|
|
2472
|
-
// A thinking-only / empty `stop` (no visible text, no tool call, no
|
|
2473
|
-
// error) would otherwise idle the session silently. Continue-or-
|
|
2474
|
-
// surface instead. Normal / tool-call / truncated / error turns yield
|
|
2475
|
-
// `none` and only reset the guard's per-session counter.
|
|
2476
|
-
// See change: fix-gemini-subagent-silent-tool-schema-failure.
|
|
2477
|
-
{
|
|
2478
|
-
const agentMsgs = (event as any)?.messages;
|
|
2479
|
-
const terminalMsg =
|
|
2480
|
-
Array.isArray(agentMsgs) && agentMsgs.length > 0
|
|
2481
|
-
? (agentMsgs[agentMsgs.length - 1] as Record<string, unknown>)
|
|
2482
|
-
: undefined;
|
|
2483
|
-
if (terminalMsg?.role === "assistant") {
|
|
2484
|
-
const actionability = classifyTurnActionability(terminalMsg as any);
|
|
2485
|
-
const decision = emptyActionableGuard.observe(sessionId, actionability);
|
|
2486
|
-
if (decision.action === "continue" && decision.nudge) {
|
|
2487
|
-
// Only nudge when nothing else will already re-run the session
|
|
2488
|
-
// (no user/system follow-up pending). A pending entry means the
|
|
2489
|
-
// session is not idling, so the guard can safely no-op.
|
|
2490
|
-
if (bridgeFollowUp.length === 0) {
|
|
2491
|
-
enqueueSystemFollowup(decision.nudge);
|
|
2492
|
-
}
|
|
2493
|
-
} else if (decision.action === "surface") {
|
|
2494
|
-
// Non-error status: the model returned only reasoning. Forward a
|
|
2495
|
-
// structured, non-error notice so the server logs it to
|
|
2496
|
-
// server.log and the dashboard card renders it (distinct from an
|
|
2497
|
-
// error banner).
|
|
2498
|
-
const model =
|
|
2499
|
-
typeof terminalMsg.model === "string"
|
|
2500
|
-
? (terminalMsg.model as string)
|
|
2501
|
-
: undefined;
|
|
2502
|
-
const provider =
|
|
2503
|
-
typeof terminalMsg.provider === "string"
|
|
2504
|
-
? (terminalMsg.provider as string)
|
|
2505
|
-
: undefined;
|
|
2506
|
-
connection.send({
|
|
2507
|
-
type: "event_forward",
|
|
2508
|
-
sessionId,
|
|
2509
|
-
event: {
|
|
2510
|
-
eventType: "empty_actionable_surface",
|
|
2511
|
-
timestamp: Date.now(),
|
|
2512
|
-
data: {
|
|
2513
|
-
message: decision.reason ?? SURFACE_MESSAGE,
|
|
2514
|
-
model: provider && model ? `${provider}/${model}` : model,
|
|
2515
|
-
},
|
|
2516
|
-
},
|
|
2517
|
-
});
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
}
|
|
2521
|
-
|
|
2522
|
-
}
|
|
2523
|
-
// For model_select, enrich the event data with thinkingLevel
|
|
2524
|
-
if (eventType === "model_select") {
|
|
2525
|
-
const enriched = { ...event, thinkingLevel: (pi as any).getThinkingLevel?.() };
|
|
2526
|
-
const msg = mapEventToProtocol(sessionId, enriched);
|
|
2527
|
-
connection.send(msg);
|
|
2528
|
-
// A TUI-initiated model change otherwise waits for the 30 s tick. The
|
|
2529
|
-
// 50 ms deferral lets pi's ctx.model reflect the new model first (same
|
|
2530
|
-
// as the dashboard-initiated setModel path). See change:
|
|
2531
|
-
// optimize-polling-hot-paths (D8).
|
|
2532
|
-
scheduleModelRecheckOnSelect(setRegisteredTimeout, sendModelUpdateIfChanged);
|
|
2533
|
-
return;
|
|
2534
|
-
}
|
|
2535
|
-
|
|
2536
|
-
// Pi 0.71+ fires a dedicated thinking_level_select event when the
|
|
2537
|
-
// thinking level changes alone (no model change). Push a model_update
|
|
2538
|
-
// through the existing dedup gate so the dashboard reflects it
|
|
2539
|
-
// immediately rather than waiting for the next model change.
|
|
2540
|
-
// See change: adopt-pi-071-072-073-features.
|
|
2541
|
-
if (eventType === "thinking_level_select") {
|
|
2542
|
-
sendModelUpdateIfChanged();
|
|
2543
|
-
return;
|
|
2544
|
-
}
|
|
2545
|
-
|
|
2546
|
-
// Graceful stop-after-turn: when latched, shut the session down cleanly
|
|
2547
|
-
// at this turn boundary. Fall back to abort if shutdown is unavailable.
|
|
2548
|
-
// Clear the flag BEFORE calling shutdown so a double-fired turn_end
|
|
2549
|
-
// can't re-trigger. See change: adopt-pi-071-072-073-features.
|
|
2550
|
-
if (eventType === "turn_end" && getBridgeState().shouldStopAfterTurn) {
|
|
2551
|
-
getBridgeState().shouldStopAfterTurn = false;
|
|
2552
|
-
try {
|
|
2553
|
-
if (typeof (ctx as any)?.shutdown === "function") (ctx as any).shutdown();
|
|
2554
|
-
else (ctx as any)?.abort?.();
|
|
2555
|
-
} catch (err) {
|
|
2556
|
-
console.error("[dashboard] stop-after-turn shutdown failed:", err);
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
|
|
2560
|
-
// For turn_end, enrich with contextUsage (pi-only API) so server can extract stats
|
|
2561
|
-
if (eventType === "turn_end") {
|
|
2562
|
-
const contextUsage = ctx.getContextUsage?.();
|
|
2563
|
-
if (contextUsage) {
|
|
2564
|
-
const enriched = { ...event, contextUsage };
|
|
2565
|
-
const msg = mapEventToProtocol(sessionId, enriched);
|
|
2566
|
-
connection.send(msg);
|
|
2567
|
-
return;
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
|
|
2571
|
-
// For message_start: stamp a nonce on the event so the client reducer
|
|
2572
|
-
// can correlate a later entry_persisted back-fill with this bubble.
|
|
2573
|
-
// We do NOT attach entryId here — the message has no id yet on pi
|
|
2574
|
-
// 0.69+ (persistence is deferred to message_end). See change:
|
|
2575
|
-
// fix-per-message-fork.
|
|
2576
|
-
//
|
|
2577
|
-
// USER message_start sends are deferred via setTimeout(0) so they
|
|
2578
|
-
// land on the wire AFTER any pending message_end deferrals (which
|
|
2579
|
-
// also use setTimeout(0) — timer FIFO preserves order). Without this,
|
|
2580
|
-
// a follow-up user message_start emitted synchronously by pi during
|
|
2581
|
-
// an agent_end drain would arrive BEFORE the preceding assistant
|
|
2582
|
-
// message_end, and the client reducer would append the user bubble
|
|
2583
|
-
// above the assistant's final response. ASSISTANT message_start stays
|
|
2584
|
-
// sync because message_update events fire sync and the reducer's
|
|
2585
|
-
// streamingTextFlushed reset depends on message_start being processed
|
|
2586
|
-
// first. See change: add-followup-edit-and-steer-cancel (chat-order).
|
|
2587
|
-
if (eventType === "message_start") {
|
|
2588
|
-
// Barrier, at ENTRY: bump the generation and open the identity BEFORE
|
|
2589
|
-
// the `role === "custom"` early return below, so a custom message still
|
|
2590
|
-
// closes out the previous identity's slot.
|
|
2591
|
-
// See change: coalesce-bridge-message-update-snapshots (D4).
|
|
2592
|
-
assistantMessageGen += 1;
|
|
2593
|
-
coalescer.messageStart(
|
|
2594
|
-
assistantMessageGen,
|
|
2595
|
-
messageKeyOf(assistantMessageGen, (event as any).message),
|
|
2596
|
-
(event as any).message,
|
|
2597
|
-
);
|
|
2598
|
-
// Custom messages are forwarded by wrapCustomPersistenceForCtx (pi's
|
|
2599
|
-
// idle-path sendMessage emits message_start/end internally only, and
|
|
2600
|
-
// the agent-loop path would double-forward here). See change:
|
|
2601
|
-
// render-inline-reasoning-and-custom-entries (D2).
|
|
2602
|
-
if ((event as any).message?.role === "custom") return;
|
|
2603
|
-
// pi >= 0.86.0 makes the system prompt/tool loadout transcript-backed:
|
|
2604
|
-
// `agent-loop.js` emits the first request's `role:"system"` message with
|
|
2605
|
-
// every prompt `section` and the full `toolsAdded` declaration list as a
|
|
2606
|
-
// `message_start`/`message_end` pair (~150 KB per message, so both
|
|
2607
|
-
// events cost ~2x that per session). The client has no `role:"system"`
|
|
2608
|
-
// arm, so forwarding it is pure wire cost with no render. Return AFTER
|
|
2609
|
-
// the barrier above (same placement as `custom`) so the barrier's
|
|
2610
|
-
// contract — every `message_start` opens an identity — is unchanged.
|
|
2611
|
-
// No version gate: pi < 0.86 never emits the role, so this is inert
|
|
2612
|
-
// there. See change: filter-system-role-message-forwarding (D2).
|
|
2613
|
-
if ((event as any).message?.role === "system") return;
|
|
2614
|
-
wrapAppendMessageForCtx(ctx);
|
|
2615
|
-
// Lazy retry (review round 1): if session_start ran before the
|
|
2616
|
-
// sessionManager exposed its persistence methods, the wrapper would
|
|
2617
|
-
// never engage. Idempotent per-sm — re-invoking here repairs that.
|
|
2618
|
-
wrapCustomPersistenceForCtx(ctx);
|
|
2619
|
-
const messageRef = (event as any).message;
|
|
2620
|
-
if (messageRef && typeof messageRef === "object") {
|
|
2621
|
-
const nonce = nextNonce();
|
|
2622
|
-
pendingNonces.set(messageRef as object, nonce);
|
|
2623
|
-
const enriched = { ...event, nonce };
|
|
2624
|
-
const msg = mapEventToProtocol(sessionId, enriched);
|
|
2625
|
-
const role = (messageRef as any).role;
|
|
2626
|
-
// Abort latch (resumption + clear hooks). A USER message_start is a
|
|
2627
|
-
// deliberate new turn — clear the latch so it is never aborted. An
|
|
2628
|
-
// ASSISTANT message_start while the latch is set is the aborted
|
|
2629
|
-
// turn resuming a retry (no intervening user prompt) — abort again.
|
|
2630
|
-
// See change: unify-error-retry-lifecycle.
|
|
2631
|
-
if (role === "user") {
|
|
2632
|
-
abortLatch.clear(sessionId);
|
|
2633
|
-
retryTracker.noteExplicitRun(sessionId);
|
|
2634
|
-
// A deliberate new user turn resets the empty-actionable guard's
|
|
2635
|
-
// consecutive-continuation counter, so a stale count from a prior
|
|
2636
|
-
// (possibly aborted) empty-actionable chain never shortens the next
|
|
2637
|
-
// unrelated prompt's retry budget.
|
|
2638
|
-
// See change: fix-gemini-subagent-silent-tool-schema-failure.
|
|
2639
|
-
emptyActionableGuard.reset(sessionId);
|
|
2640
|
-
} else if (abortLatch.shouldAbort(sessionId)) {
|
|
2641
|
-
try { cachedCtx?.abort?.(); } catch { /* idempotent */ }
|
|
2642
|
-
}
|
|
2643
|
-
// NOTE: retry synthesis moved off `message_start`. pi ends a full
|
|
2644
|
-
// agent turn per attempt, so the retry lifecycle is now driven by
|
|
2645
|
-
// agent_start (in-flight) / agent_end (waiting) / agent_settled
|
|
2646
|
-
// (terminal). See change: retry-forever-with-stop-control.
|
|
2647
|
-
if (role === "user") {
|
|
2648
|
-
// Per-entry shadow-queue drain matcher: mirror pi's internal
|
|
2649
|
-
// logic (`_processAgentEvent` in pi-coding-agent
|
|
2650
|
-
// agent-session.js). When pi delivers a queued user message,
|
|
2651
|
-
// find its text in `bridgeSteering` first then `bridgeFollowUp`,
|
|
2652
|
-
// remove the first occurrence, and emit a fresh `queue_update`.
|
|
2653
|
-
//
|
|
2654
|
-
// POST-rework-mid-turn-prompt-queue: the steer side is
|
|
2655
|
-
// unchanged — pi still owns steering. The follow-up side is
|
|
2656
|
-
// now reduced in scope: dashboard-buffered follow-ups never
|
|
2657
|
-
// reach pi via {deliverAs:"followUp"} (the drain loop ships
|
|
2658
|
-
// them as no-deliverAs fresh-turn sends, popped from the
|
|
2659
|
-
// buffer BEFORE the pi call). So this matcher will splice
|
|
2660
|
-
// bridgeFollowUp ONLY for:
|
|
2661
|
-
// (a) TUI-queued follow-ups draining through pi's natural
|
|
2662
|
-
// queue (text not in bridgeFollowUp → indexOf=-1 → no-op)
|
|
2663
|
-
// (b) Any future code path that calls
|
|
2664
|
-
// pi.sendUserMessage(_, {deliverAs:"followUp"}) directly
|
|
2665
|
-
// (none exist in this codebase post-rework).
|
|
2666
|
-
// The follow-up matcher is therefore defense-in-depth; cost is
|
|
2667
|
-
// one indexOf per user message_start.
|
|
2668
|
-
//
|
|
2669
|
-
// See change: rework-mid-turn-prompt-queue (design.md D9, R7).
|
|
2670
|
-
const text = extractUserMessageText(messageRef);
|
|
2671
|
-
if (text) {
|
|
2672
|
-
const sIdx = bridgeSteering.indexOf(text);
|
|
2673
|
-
if (sIdx !== -1) {
|
|
2674
|
-
bridgeSteering.splice(sIdx, 1);
|
|
2675
|
-
emitQueueUpdate();
|
|
2676
|
-
} else {
|
|
2677
|
-
const fIdx = bridgeFollowUp.indexOfText(text);
|
|
2678
|
-
if (fIdx !== -1) {
|
|
2679
|
-
bridgeFollowUp.removeAt(fIdx);
|
|
2680
|
-
emitQueueUpdate();
|
|
2681
|
-
}
|
|
2682
|
-
}
|
|
2683
|
-
}
|
|
2684
|
-
setTimeout(() => {
|
|
2685
|
-
if (!isActive() || !sessionReady) return;
|
|
2686
|
-
connection.send(msg);
|
|
2687
|
-
}, 0);
|
|
2688
|
-
} else {
|
|
2689
|
-
connection.send(msg);
|
|
2690
|
-
}
|
|
2691
|
-
return;
|
|
2692
|
-
}
|
|
2693
|
-
}
|
|
2694
|
-
|
|
2695
|
-
// For message_end: defer the SEND via setTimeout(0). Pi 0.69+ runs
|
|
2696
|
-
// sessionManager.appendMessage AFTER the awaited extension dispatcher
|
|
2697
|
-
// returns, so a queueMicrotask deferral is no longer enough. By the
|
|
2698
|
-
// time the macrotask fires, appendMessage has run, pi has mutated
|
|
2699
|
-
// event.message.id in place, and the wrapped appendMessage above has
|
|
2700
|
-
// populated idByMessage. We also stamp a nonce so a downstream
|
|
2701
|
-
// entry_persisted can correlate (covers user message_end where the
|
|
2702
|
-
// earlier message_start nonce is what the reducer is waiting on).
|
|
2703
|
-
// See change: fix-per-message-fork.
|
|
2704
|
-
if (eventType === "message_end") {
|
|
2705
|
-
// Barrier, at ENTRY and BEFORE the deferred send is scheduled below: the
|
|
2706
|
-
// entry flush has already put the final snapshot on the wire, so closing
|
|
2707
|
-
// here means any update arriving during the macrotask gap is dropped by
|
|
2708
|
-
// the closed slot instead of landing after the `message_end`.
|
|
2709
|
-
// See change: coalesce-bridge-message-update-snapshots (D4/D5).
|
|
2710
|
-
// The generation this message was OPENED under, not the counter's
|
|
2711
|
-
// current value: a message_end for a message whose start we saw must
|
|
2712
|
-
// close ITS identity, never a newer one. Falls back to the current
|
|
2713
|
-
// counter for a message this instance never saw open (reload mid-turn).
|
|
2714
|
-
const endMessage = (event as any).message;
|
|
2715
|
-
const endGen = coalescer.generationOf(endMessage, assistantMessageGen);
|
|
2716
|
-
coalescer.messageEnd(endGen, messageKeyOf(endGen, endMessage));
|
|
2717
|
-
// Custom messages are forwarded by wrapCustomPersistenceForCtx — see
|
|
2718
|
-
// the message_start guard above. See change:
|
|
2719
|
-
// render-inline-reasoning-and-custom-entries (D2).
|
|
2720
|
-
if ((event as any).message?.role === "custom") return;
|
|
2721
|
-
// Same pi >= 0.86.0 system-role drop as the `message_start` arm above,
|
|
2722
|
-
// after the same barrier. See change:
|
|
2723
|
-
// filter-system-role-message-forwarding (D2).
|
|
2724
|
-
if ((event as any).message?.role === "system") return;
|
|
2725
|
-
wrapAppendMessageForCtx(ctx);
|
|
2726
|
-
const messageRef = (event as any).message;
|
|
2727
|
-
const nonce = messageRef && typeof messageRef === "object"
|
|
2728
|
-
? (pendingNonces.get(messageRef as object) ?? nextNonce())
|
|
2729
|
-
: nextNonce();
|
|
2730
|
-
if (messageRef && typeof messageRef === "object" && !pendingNonces.has(messageRef as object)) {
|
|
2731
|
-
pendingNonces.set(messageRef as object, nonce);
|
|
2732
|
-
}
|
|
2733
|
-
// Apply markdown image inliner to assistant content. Mutates
|
|
2734
|
-
// event.message.content in place AND ships any new asset_register
|
|
2735
|
-
// messages immediately so they precede the deferred message_end
|
|
2736
|
-
// send below. See change: chat-markdown-local-images-and-math.
|
|
2737
|
-
maybeInlineAssistantImages(event);
|
|
2738
|
-
// Run the retry-tracker SYNCHRONOUSLY here, BEFORE the handler
|
|
2739
|
-
// returns, so any synthesized retry event lands on the wire BEFORE
|
|
2740
|
-
// the next `agent_end` (which pi fires synchronously back-to-back,
|
|
2741
|
-
// see pi-coding-agent agent-session.js:298–331). The message_end
|
|
2742
|
-
// body itself stays deferred for the entryId workaround
|
|
2743
|
-
// (`fix-per-message-fork`); that does not affect retry-state ordering
|
|
2744
|
-
// since the reducer's message_end arm does not touch
|
|
2745
|
-
// retryState/lastError.
|
|
2746
|
-
//
|
|
2747
|
-
// Observe-based: an error message_end records a pending failure and
|
|
2748
|
-
// emits NOTHING (the retry is confirmed only when pi starts a fresh
|
|
2749
|
-
// assistant message_start). A non-error message_end that closes an
|
|
2750
|
-
// in-flight chain emits auto_retry_end{success:true}. Billing/quota
|
|
2751
|
-
// failures flow through this same path — pi treats them as terminal,
|
|
2752
|
-
// so they settle via agent_end with no special-casing.
|
|
2753
|
-
// See change: simplify-error-retry-single-card.
|
|
2754
|
-
const synthetic = retryTracker.observeMessageEnd(sessionId, messageRef as any);
|
|
2755
|
-
if (synthetic) {
|
|
2756
|
-
sendSyntheticRetryEvent(synthetic.eventType, synthetic.data);
|
|
2757
|
-
}
|
|
2758
|
-
setTimeout(() => {
|
|
2759
|
-
if (!isActive() || !sessionReady) return;
|
|
2760
|
-
const entryId =
|
|
2761
|
-
(messageRef && typeof messageRef === "object" && typeof messageRef.id === "string" ? messageRef.id : undefined)
|
|
2762
|
-
?? (messageRef ? idByMessage.get(messageRef as object) : undefined)
|
|
2763
|
-
?? ctx.sessionManager?.getLeafId?.();
|
|
2764
|
-
const enriched = { ...event, entryId, nonce };
|
|
2765
|
-
const protoMsg = mapEventToProtocol(sessionId, enriched);
|
|
2766
|
-
connection.send(protoMsg);
|
|
2767
|
-
}, 0);
|
|
2768
|
-
return;
|
|
2769
|
-
}
|
|
2770
|
-
|
|
2771
|
-
// Text snapshots are COALESCED (D1–D3): one wire write per fixed window
|
|
2772
|
-
// instead of one per source token. `offer` owns the family split and the
|
|
2773
|
-
// closed-identity drop rule; the markdown-image inliner now runs inside the
|
|
2774
|
-
// coalescer's send callback (once per flushed window, still ahead of the
|
|
2775
|
-
// snapshot that references its assets). This branch returns, so the shared
|
|
2776
|
-
// tail below never sees a `message_update`.
|
|
2777
|
-
// See change: coalesce-bridge-message-update-snapshots (D6).
|
|
2778
|
-
if (eventType === "message_update") {
|
|
2779
|
-
// Resolve the message's OWN generation, so a late update for an already
|
|
2780
|
-
// closed message still keys to that closed identity and is dropped —
|
|
2781
|
-
// keying it under the counter's current value would fail open.
|
|
2782
|
-
const updateMessage = (event as any)?.message;
|
|
2783
|
-
coalescer.offer(event, coalescer.generationOf(updateMessage, assistantMessageGen));
|
|
2784
|
-
return;
|
|
2785
|
-
}
|
|
2786
|
-
|
|
2787
|
-
// Inline path-referenced image tool results (e.g. browser `screenshot`)
|
|
2788
|
-
// as type:"image" content blocks at capture time. Gated to the artifact-
|
|
2789
|
-
// root allowlist (default agent-browser screenshot dir +
|
|
2790
|
-
// AGENT_BROWSER_SCREENSHOT_DIR) so arbitrary tool-echoed paths are not
|
|
2791
|
-
// read/disclosed. Over-cap / out-of-root / missing / non-image paths are
|
|
2792
|
-
// left as text and fall back to the artifact route.
|
|
2793
|
-
// See change: inline-agent-screenshot-artifacts.
|
|
2794
|
-
if (eventType === "tool_execution_end") {
|
|
2795
|
-
try {
|
|
2796
|
-
const artifactRoots = resolveArtifactRoots({
|
|
2797
|
-
homedir: os.homedir(),
|
|
2798
|
-
env: process.env,
|
|
2799
|
-
realpathSync: fs.realpathSync,
|
|
2800
|
-
});
|
|
2801
|
-
const inlined = inlineToolResultImages((event as any).result, {
|
|
2802
|
-
readFile: inlinerReadFile,
|
|
2803
|
-
isAllowedPath: (p) => isUnderArtifactRoot(p, artifactRoots, fs.realpathSync),
|
|
2804
|
-
});
|
|
2805
|
-
// Apply when a new image was inlined OR when the inliner rewrote the
|
|
2806
|
-
// result (e.g. stripped a redundant path whose image the result
|
|
2807
|
-
// already carried natively). The inliner returns the SAME reference
|
|
2808
|
-
// when nothing changed, so an identity diff is a safe change signal.
|
|
2809
|
-
if (inlined.result !== (event as any).result) {
|
|
2810
|
-
(event as any).result = inlined.result;
|
|
2811
|
-
}
|
|
2812
|
-
} catch (err) {
|
|
2813
|
-
console.error("[dashboard] tool-result image inline failed:", err);
|
|
2814
|
-
}
|
|
2815
|
-
// Forward the tool result's structured `details` to the client. pi's
|
|
2816
|
-
// live tool_execution_end extension event exposes the full ToolResult
|
|
2817
|
-
// ({ content, details }) on `event.result`, but only `result` is
|
|
2818
|
-
// otherwise surfaced — the reducer reads a top-level `data.details`
|
|
2819
|
-
// (the same field the replay path synthesizes from the persisted
|
|
2820
|
-
// entry). Lift `result.details` to the event so renderers (e.g. the
|
|
2821
|
-
// flow_agents list card) get a non-truncated structured payload LIVE,
|
|
2822
|
-
// not only after a replay/refresh. No-op when result carries no
|
|
2823
|
-
// details or already has a top-level details.
|
|
2824
|
-
// See change: flow-agents-readable-list.
|
|
2825
|
-
try {
|
|
2826
|
-
const r = (event as any).result;
|
|
2827
|
-
if (
|
|
2828
|
-
!(event as any).details &&
|
|
2829
|
-
r && typeof r === "object" && !Array.isArray(r) &&
|
|
2830
|
-
(r as any).details && typeof (r as any).details === "object"
|
|
2831
|
-
) {
|
|
2832
|
-
(event as any).details = (r as any).details;
|
|
2833
|
-
}
|
|
2834
|
-
} catch { /* non-fatal */ }
|
|
2835
|
-
}
|
|
2836
|
-
|
|
2837
|
-
// The `tool_execution_update` carrier is structurally disjoint from the
|
|
2838
|
-
// EventBus path (pi core event → `pi.on()` → `connection.send`), but one
|
|
2839
|
-
// `snapshotDetails()` object feeds both — so stripping one carrier only
|
|
2840
|
-
// is a half-fix. `tool_execution_end` is terminal and stays fat.
|
|
2841
|
-
// See change: reduce-subagent-details-payload (D2, task 3.8).
|
|
2842
|
-
//
|
|
2843
|
-
// `session_compact` is forwarded WITHOUT its `compactionEntry`. pi >= 0.86
|
|
2844
|
-
// fills that entry's `systemMessage` with the same prompt-sections +
|
|
2845
|
-
// tool-declaration checkpoint the system-role arms above drop, and carries
|
|
2846
|
-
// the compaction `summary` beside it. No dashboard consumer reads either:
|
|
2847
|
-
// the client renders the divider from the event's presence and the badge
|
|
2848
|
-
// from `reason`/`willRetry`/`estimatedPostCompactionTokens`; the server
|
|
2849
|
-
// uses the event only to clear the `compacting` latch. Redact on a COPY —
|
|
2850
|
-
// pi hands the SAME event object to every subscribed extension, so a
|
|
2851
|
-
// `delete event.compactionEntry` would strip the field from unrelated
|
|
2852
|
-
// extensions too. The redaction stays OUT of `mapEventToProtocol` (which
|
|
2853
|
-
// is generic over every forwarded type). No version gate: the field is
|
|
2854
|
-
// simply omitted wherever it is absent.
|
|
2855
|
-
// See change: filter-system-role-message-forwarding (D6/D7).
|
|
2856
|
-
const forwardEvent =
|
|
2857
|
-
eventType === "session_compact"
|
|
2858
|
-
? redactCompactionEntry(event as Record<string, unknown>)
|
|
2859
|
-
: event;
|
|
2860
|
-
const msg = mapEventToProtocol(sessionId, forwardEvent);
|
|
2861
|
-
let heldByThrottle = false;
|
|
2862
|
-
if (eventType === "tool_execution_update") {
|
|
2863
|
-
msg.event.data = stripForForward(msg.event.data as Record<string, unknown>);
|
|
2864
|
-
// Agent ticks only (allowlist predicate) — every other tool's update
|
|
2865
|
-
// stream forwards 1:1. `offer` returns false when it has taken
|
|
2866
|
-
// ownership of the frame and will send (or discard) it later.
|
|
2867
|
-
// See change: reduce-bridge-tick-bandwidth (D2).
|
|
2868
|
-
if (isSubagentTick(event) && typeof event.toolCallId === "string") {
|
|
2869
|
-
heldByThrottle = !subagentTickThrottle.offer(event.toolCallId, msg, sessionId);
|
|
2870
|
-
}
|
|
2871
|
-
}
|
|
2872
|
-
if (eventType === "tool_execution_end" && typeof event.toolCallId === "string") {
|
|
2873
|
-
// Terminal: DISCARD any held tick rather than flushing it. This carrier
|
|
2874
|
-
// never carries terminal state, so a held frame is a strictly stale
|
|
2875
|
-
// intermediate snapshot; flushing it would race the overwrite that
|
|
2876
|
-
// visibly re-opens a finished tool row. Runs before the send so no held
|
|
2877
|
-
// frame can interleave after the end event.
|
|
2878
|
-
subagentTickThrottle.onTerminal(event.toolCallId);
|
|
2879
|
-
}
|
|
2880
|
-
if (!heldByThrottle) connection.send(msg);
|
|
2881
|
-
|
|
2882
|
-
// Native `agent_settled` (pi ≥ 0.80.4, guaranteed at the 0.85.1 floor) is
|
|
2883
|
-
// the single terminal signal; the bridge forwards it above and the
|
|
2884
|
-
// `agent_settled` handler closes the retry chain. The floor-pi synthesis
|
|
2885
|
-
// path was retired once `piCompatibility.minimum` reached a version that
|
|
2886
|
-
// emits natively. See change: update-pi-core-0-85-adopt-apis.
|
|
2887
|
-
}));
|
|
2888
|
-
}
|
|
1924
|
+
registerEnrichedForwarders(inst);
|
|
2889
1925
|
|
|
2890
1926
|
// Pass-through events: forward with no enrichment
|
|
2891
|
-
|
|
2892
|
-
pi.on(eventType as any, safe(async (event: any, ctx: any) => {
|
|
2893
|
-
if (!isActive()) return;
|
|
2894
|
-
cachedCtx = ctx;
|
|
2895
|
-
if (!sessionReady) return;
|
|
2896
|
-
// Same choke point as the enriched loop (D5).
|
|
2897
|
-
coalescer.flush();
|
|
2898
|
-
const forwarded = event?.type === "agent_before_settle" ? redactBeforeSettleContext(event) : event;
|
|
2899
|
-
const msg = mapEventToProtocol(sessionId, forwarded);
|
|
2900
|
-
connection.send(msg);
|
|
2901
|
-
}));
|
|
2902
|
-
}
|
|
1927
|
+
registerPassThroughForwarders(inst);
|
|
2903
1928
|
|
|
2904
1929
|
// ── Subagent fan-out admission ────────────────────────────────────────────
|
|
2905
1930
|
// Bounds concurrently in-flight `Agent` children so a wide fan-out on a loaded
|
|
@@ -2930,6 +1955,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2930
1955
|
}
|
|
2931
1956
|
},
|
|
2932
1957
|
});
|
|
1958
|
+
inst.fanoutAdmission = fanoutAdmission;
|
|
2933
1959
|
pi.on("tool_call", safe((event: any) => {
|
|
2934
1960
|
if (!isActive()) return;
|
|
2935
1961
|
return fanoutAdmission.onToolCall(event);
|
|
@@ -2971,15 +1997,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2971
1997
|
// permanent lockout. The turn-end poll (runAutoNameOnTurnEnd) stays as a
|
|
2972
1998
|
// fallback for pi builds that do not emit this event. See change:
|
|
2973
1999
|
// adopt-pi-074-080-features (A.2).
|
|
2974
|
-
|
|
2975
|
-
pi.on("session_info_changed" as any, safe(async (event: any) => {
|
|
2976
|
-
if (!isActive() || !sessionReady) return;
|
|
2977
|
-
const name = typeof event?.name === "string" ? event.name : pi.getSessionName();
|
|
2978
|
-
if (typeof name === "string" && name.length > 0) {
|
|
2979
|
-
getAutoNamer().onObservedName(name);
|
|
2980
|
-
}
|
|
2981
|
-
}));
|
|
2982
|
-
} catch { /* older pi: no session_info_changed — poll fallback covers it */ }
|
|
2000
|
+
registerSessionInfoChanged(inst);
|
|
2983
2001
|
|
|
2984
2002
|
// Auto-decide project_trust for dashboard-spawned headless sessions (pi
|
|
2985
2003
|
// 0.79.0+). The event fires during resource-loader reload, BEFORE
|
|
@@ -2988,22 +2006,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
2988
2006
|
// per-event ctx inside try/catch (ctx.cwd throws after session replacement).
|
|
2989
2007
|
// Any non-match — or a throw — defers to pi's default. See change:
|
|
2990
2008
|
// adopt-pi-074-080-features (A.3).
|
|
2991
|
-
|
|
2992
|
-
pi.on("project_trust" as any, safe((event: any, ctx: any) => {
|
|
2993
|
-
// Return the pi trust decision. A newer bridge taking over, or any
|
|
2994
|
-
// non-match, defers. `remember:false` = trust for THIS run only.
|
|
2995
|
-
if (!isActive()) return { trusted: "undecided" };
|
|
2996
|
-
const decision = decideProjectTrust({
|
|
2997
|
-
dashboardSpawned,
|
|
2998
|
-
isHeadless: isHeadlessRpcSession(),
|
|
2999
|
-
eventCwd: readEventCwd(event, ctx),
|
|
3000
|
-
activationCwd,
|
|
3001
|
-
});
|
|
3002
|
-
return decision === "trust"
|
|
3003
|
-
? { trusted: "yes", remember: false }
|
|
3004
|
-
: { trusted: "undecided" };
|
|
3005
|
-
}));
|
|
3006
|
-
} catch { /* older pi: no project_trust event — no-op */ }
|
|
2009
|
+
registerProjectTrust(inst);
|
|
3007
2010
|
|
|
3008
2011
|
// Per-turn system-prompt injector: splice dashboard session context
|
|
3009
2012
|
// (sessionId, cwd, attached OpenSpec change) into the system prompt. Reads
|
|
@@ -3012,7 +2015,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3012
2015
|
// chains { systemPrompt } results). See change: inject-session-context-into-agent.
|
|
3013
2016
|
registerDashboardContextInjector(
|
|
3014
2017
|
pi,
|
|
3015
|
-
() => ({ sessionId, attachedChange }),
|
|
2018
|
+
() => ({ sessionId: inst.sessionId, attachedChange: inst.attachedChange }),
|
|
3016
2019
|
isActive,
|
|
3017
2020
|
);
|
|
3018
2021
|
|
|
@@ -3020,7 +2023,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3020
2023
|
// pi-coding-agent 0.71+ — see _emitExtensionEvent allowlist). Bridge
|
|
3021
2024
|
// tracks the shadow queues itself; drain happens on observed boundaries:
|
|
3022
2025
|
// turn_end drains steering (pi's mode:"all" delivers all queued steers),
|
|
3023
|
-
//
|
|
2026
|
+
// agent_settled drains follow-up (pi is idle, no more tool calls).
|
|
3024
2027
|
// See change: add-followup-edit-and-steer-cancel.
|
|
3025
2028
|
// Bridge shadow steering queue: per-entry drain matcher in the
|
|
3026
2029
|
// `message_start` handler removes each entry as pi delivers it. No bulk
|
|
@@ -3031,12 +2034,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3031
2034
|
// get renamed via EVENT_BUS_MAP; unknown channels use the channel name.
|
|
3032
2035
|
function sendEventForward(channel: string, data: Record<string, unknown>): void {
|
|
3033
2036
|
const eventType = EVENT_BUS_MAP[channel] ?? channel;
|
|
3034
|
-
connection.send({
|
|
2037
|
+
inst.connection.send({
|
|
3035
2038
|
type: "event_forward",
|
|
3036
|
-
sessionId,
|
|
2039
|
+
sessionId: inst.sessionId,
|
|
3037
2040
|
event: { eventType, timestamp: Date.now(), data },
|
|
3038
2041
|
});
|
|
3039
2042
|
}
|
|
2043
|
+
inst.sendEventForward = sendEventForward;
|
|
3040
2044
|
|
|
3041
2045
|
// Flush subagent frames buffered while the bridge was not ready (D1). Called
|
|
3042
2046
|
// right after `sessionReady` flips true on (re-)register, in emission order.
|
|
@@ -3046,6 +2050,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3046
2050
|
// `sendEventForward` directly, so a bus-path-only strip would leak every
|
|
3047
2051
|
// buffered frame fat. See change: reduce-subagent-details-payload (X5).
|
|
3048
2052
|
const flushed = flushBufferedSubagentFrames(subagentFrameBuffer, sendEventForward);
|
|
2053
|
+
// Plugin-declared latest/stream channels retained over the same gap flush
|
|
2054
|
+
// here too, in emission order. See change: add-plugin-bridge-contributions.
|
|
2055
|
+
pluginForwardRegistry.flush();
|
|
3049
2056
|
if (flushed === 0) return;
|
|
3050
2057
|
console.log(
|
|
3051
2058
|
`[dashboard] flushed ${flushed} buffered subagent frame(s) on re-register` +
|
|
@@ -3053,6 +2060,7 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3053
2060
|
` flushed=${subagentFrameBuffer.stats.flushed})`,
|
|
3054
2061
|
);
|
|
3055
2062
|
}
|
|
2063
|
+
inst.flushPendingSubagentFrames = flushPendingSubagentFrames;
|
|
3056
2064
|
|
|
3057
2065
|
// EventBus forwarding: ONE `pi.events.on` subscription per declared channel
|
|
3058
2066
|
// (every key of EVENT_BUS_MAP). NOT an `emit` intercept — pi hands each
|
|
@@ -3065,9 +2073,9 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3065
2073
|
pi.events,
|
|
3066
2074
|
{
|
|
3067
2075
|
sendEventForward,
|
|
3068
|
-
isSessionReady: () => sessionReady,
|
|
2076
|
+
isSessionReady: () => inst.sessionReady,
|
|
3069
2077
|
isActive,
|
|
3070
|
-
isConnected: () => connection.isConnected,
|
|
2078
|
+
isConnected: () => inst.connection.isConnected,
|
|
3071
2079
|
subagent: {
|
|
3072
2080
|
isSubagentChannel: (channel) => SubagentFrameBuffer.isSubagentChannel(channel),
|
|
3073
2081
|
markForwarded: (channel, data) => subagentFrameBuffer.markForwarded(channel, data),
|
|
@@ -3077,1012 +2085,32 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
3077
2085
|
},
|
|
3078
2086
|
);
|
|
3079
2087
|
|
|
3080
|
-
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
// drain forwards only entries appended after this point, and the register
|
|
3100
|
-
// carries this snapshot's full totals. Undefined on a failed read.
|
|
3101
|
-
// See change: count-non-message-usage.
|
|
3102
|
-
let usageSeed: ReturnType<UsageDrain["baseline"]> | undefined;
|
|
3103
|
-
try {
|
|
3104
|
-
usageSeed = usageDrain.baseline(ctx.sessionManager);
|
|
3105
|
-
} catch (err) {
|
|
3106
|
-
console.error("[dashboard] usage baseline failed:", err);
|
|
3107
|
-
}
|
|
3108
|
-
const sessionChanged =
|
|
3109
|
-
(reason === "new" || reason === "fork" || reason === "resume") && !!sessionId && sessionId !== newSessionId;
|
|
3110
|
-
if (sessionChanged) {
|
|
3111
|
-
// Clear any latched abort for the OUTGOING session id. Otherwise a
|
|
3112
|
-
// latched old session that is resumed later would have its first
|
|
3113
|
-
// legitimate turn aborted by the agent_start/message_start latch hooks.
|
|
3114
|
-
// See change: unify-error-retry-lifecycle.
|
|
3115
|
-
abortLatch.clear(sessionId);
|
|
3116
|
-
handleSessionChange(ctx, usageSeed);
|
|
3117
|
-
}
|
|
3118
|
-
|
|
3119
|
-
cachedHasUI = ctx.hasUI;
|
|
3120
|
-
cachedCtx = ctx;
|
|
3121
|
-
sessionId = newSessionId;
|
|
3122
|
-
|
|
3123
|
-
// Provision the openspec CLI: drop a shim on process.env.PATH so the
|
|
3124
|
-
// generated openspec-* skills' bare `openspec` resolves in-session. Runs on
|
|
3125
|
-
// init AND /reload (re-points the shim on extension upgrade); the PATH
|
|
3126
|
-
// prepend is idempotent. Fail-soft: on hard failure, surface a
|
|
3127
|
-
// dashboard-visible missing-tool signal. See change:
|
|
3128
|
-
// provision-openspec-cli-in-sessions.
|
|
3129
|
-
provisionOpenspecCli({
|
|
3130
|
-
onMissingTool: (reason) => {
|
|
3131
|
-
connection.send({
|
|
3132
|
-
type: "event_forward",
|
|
3133
|
-
sessionId,
|
|
3134
|
-
event: {
|
|
3135
|
-
eventType: "bash_output",
|
|
3136
|
-
timestamp: Date.now(),
|
|
3137
|
-
data: {
|
|
3138
|
-
command: "openspec (session provisioning)",
|
|
3139
|
-
output: reason,
|
|
3140
|
-
exitCode: 127,
|
|
3141
|
-
excludeFromContext: true,
|
|
3142
|
-
missingTool: { kind: "missing-tool", toolName: "openspec" },
|
|
3143
|
-
},
|
|
3144
|
-
},
|
|
3145
|
-
});
|
|
3146
|
-
},
|
|
3147
|
-
});
|
|
3148
|
-
|
|
3149
|
-
// Wrap sessionManager.appendMessage so that future message_end events can
|
|
3150
|
-
// recover the just-generated entry id, even when their setTimeout(0)
|
|
3151
|
-
// fires before pi has finished mutating event.message in place. The
|
|
3152
|
-
// helper is idempotent and re-wraps on session replacement.
|
|
3153
|
-
// See change: fix-per-message-fork.
|
|
3154
|
-
appendMessageWrapped = false;
|
|
3155
|
-
lastWrappedSm = null;
|
|
3156
|
-
wrapAppendMessageForCtx(ctx);
|
|
3157
|
-
// Wrap the custom-persistence chokepoint BEFORE any events flow, so an
|
|
3158
|
-
// extension appending at session_start is still forwarded. See change:
|
|
3159
|
-
// render-inline-reasoning-and-custom-entries (D2).
|
|
3160
|
-
customPersistenceWrapped = false;
|
|
3161
|
-
customWrappedSm = null;
|
|
3162
|
-
wrapCustomPersistenceForCtx(ctx);
|
|
3163
|
-
|
|
3164
|
-
// Register ask_user at runtime (not at load time) to avoid static
|
|
3165
|
-
// tool-name conflicts with other extensions like pi-flows.
|
|
3166
|
-
registerAskUserTool(pi);
|
|
3167
|
-
|
|
3168
|
-
// Register the canvas declare-tool (change: auto-canvas). Fire-and-forget
|
|
3169
|
-
// UI intent; the server observes the forwarded tool call and drives the
|
|
3170
|
-
// canvas. Runtime registration for the same conflict-avoidance reason.
|
|
3171
|
-
registerCanvasTool(pi);
|
|
3172
|
-
|
|
3173
|
-
// Register the agent-facing role/model tools (list_models, list_roles,
|
|
3174
|
-
// update_roles). list_models reads the in-process session registry via a
|
|
3175
|
-
// live getter so its refs match the human Model Selector exactly.
|
|
3176
|
-
// See change: add-agent-role-model-tools.
|
|
3177
|
-
registerRoleModelTools(pi, {
|
|
3178
|
-
getRegistry: () => cachedModelRegistry,
|
|
3179
|
-
// Live scope read at call time from the latest captured ctx (dynamic via
|
|
3180
|
-
// Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
|
|
3181
|
-
// See change: update-pi-core-0-83-adopt-apis.
|
|
3182
|
-
getScopedModels: () => (cachedCtx as any)?.scopedModels,
|
|
3183
|
-
});
|
|
3184
|
-
|
|
3185
|
-
// Extract session file/dir early — needed for source detection and UI proxy
|
|
3186
|
-
const sessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
|
|
3187
|
-
const sessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
|
|
3188
|
-
lastSessionFile = sessionFile;
|
|
3189
|
-
lastSessionDir = sessionDir;
|
|
3190
|
-
|
|
3191
|
-
// ── PromptBus setup ──
|
|
3192
|
-
// Create bus with dashboard connection wiring.
|
|
3193
|
-
// Replaces the old ui-proxy race pattern.
|
|
3194
|
-
// Convert seconds → milliseconds for PromptBus.
|
|
3195
|
-
// Values <= 0 (e.g. -1) are passed through as-is to signal infinite wait.
|
|
3196
|
-
const askUserTimeoutMs = config.askUserPromptTimeoutSeconds > 0
|
|
3197
|
-
? config.askUserPromptTimeoutSeconds * 1000
|
|
3198
|
-
: -1;
|
|
3199
|
-
promptBus = new PromptBus({
|
|
3200
|
-
timeoutMs: askUserTimeoutMs,
|
|
3201
|
-
onDashboardRequest: (prompt, component, placement) => {
|
|
3202
|
-
connection.send({
|
|
3203
|
-
type: "prompt_request" as any,
|
|
3204
|
-
sessionId,
|
|
3205
|
-
promptId: prompt.id,
|
|
3206
|
-
prompt: {
|
|
3207
|
-
question: prompt.question,
|
|
3208
|
-
type: prompt.type,
|
|
3209
|
-
options: prompt.options,
|
|
3210
|
-
defaultValue: prompt.defaultValue,
|
|
3211
|
-
pipeline: prompt.pipeline,
|
|
3212
|
-
metadata: prompt.metadata,
|
|
3213
|
-
},
|
|
3214
|
-
component,
|
|
3215
|
-
placement,
|
|
3216
|
-
});
|
|
3217
|
-
},
|
|
3218
|
-
onDashboardDismiss: (id) => {
|
|
3219
|
-
connection.send({ type: "prompt_dismiss" as any, sessionId, promptId: id });
|
|
3220
|
-
},
|
|
3221
|
-
onDashboardCancel: (id) => {
|
|
3222
|
-
connection.send({ type: "prompt_cancel" as any, sessionId, promptId: id });
|
|
3223
|
-
},
|
|
3224
|
-
});
|
|
3225
|
-
|
|
3226
|
-
// Register built-in default adapter (always present, works without pi-flows)
|
|
3227
|
-
promptBus.registerAdapter(new DashboardDefaultAdapter());
|
|
3228
|
-
|
|
3229
|
-
// Capture original ctx.ui method references BEFORE patching
|
|
3230
|
-
const originalNotify = ctx.ui.notify?.bind(ctx.ui);
|
|
3231
|
-
const originals = {
|
|
3232
|
-
select: ctx.ui.select?.bind(ctx.ui) as ((q: string, opts: string[], extra?: any) => Promise<string | undefined>) | undefined,
|
|
3233
|
-
input: ctx.ui.input?.bind(ctx.ui) as ((q: string, placeholder?: string, extra?: any) => Promise<string | undefined>) | undefined,
|
|
3234
|
-
confirm: ctx.ui.confirm?.bind(ctx.ui) as ((q: string, msg: string, extra?: any) => Promise<boolean>) | undefined,
|
|
3235
|
-
editor: ctx.ui.editor?.bind(ctx.ui) as ((q: string, prefill?: string, extra?: any) => Promise<string | undefined>) | undefined,
|
|
3236
|
-
// NOTE: the `custom` field is intentionally NOT captured here. A
|
|
3237
|
-
// previous change (fix-multiselect-auto-cancel-on-dashboard) added a
|
|
3238
|
-
// TUI multiselect arm that awaited the original ctx.ui.custom binding,
|
|
3239
|
-
// but pi 0.70's RPC mode defines that primitive as a no-op (returns
|
|
3240
|
-
// undefined synchronously), causing the TUI adapter to auto-cancel the
|
|
3241
|
-
// dashboard-rendered dialog within one event-loop tick. The arm has
|
|
3242
|
-
// been removed; see change fix-multiselect-tui-arm-self-cancel for full
|
|
3243
|
-
// rationale. A repo lint (no-tui-multiselect-arm-regression.test.ts)
|
|
3244
|
-
// prevents reintroduction by banning the co-occurrence of two
|
|
3245
|
-
// substrings (the captured original binding and the TUI arm match).
|
|
3246
|
-
};
|
|
3247
|
-
|
|
3248
|
-
// Register TUI adapter — presents prompts in the terminal using original
|
|
3249
|
-
// (unpatched) ctx.ui methods. Must be registered BEFORE patching ctx.ui.
|
|
3250
|
-
if (ctx.hasUI) {
|
|
3251
|
-
promptBus.registerAdapter(createTuiPromptAdapter(originals, promptBus));
|
|
3252
|
-
}
|
|
3253
|
-
|
|
3254
|
-
// Replace ctx.ui dialog methods with PromptBus wrappers.
|
|
3255
|
-
// All extension commands that call ctx.ui.select/input/confirm/editor
|
|
3256
|
-
// now route through the bus, which distributes to all registered adapters.
|
|
3257
|
-
{
|
|
3258
|
-
const bus = promptBus;
|
|
3259
|
-
// Build a `metadata` envelope for bus.request that includes both
|
|
3260
|
-
// `message` (existing) and `toolCallId` (new — added by change
|
|
3261
|
-
// `fix-interactive-ui-reorder` so the client reducer can pair the
|
|
3262
|
-
// resulting interactiveUi row with its parent toolResult row).
|
|
3263
|
-
// Free-floating callers (slash commands, architect prompts) omit
|
|
3264
|
-
// `opts.toolCallId` and the metadata field stays undefined.
|
|
3265
|
-
const buildMeta = (
|
|
3266
|
-
opts: any,
|
|
3267
|
-
explicitMessage?: string,
|
|
3268
|
-
): Record<string, unknown> | undefined => {
|
|
3269
|
-
const message = explicitMessage ?? opts?.message;
|
|
3270
|
-
const toolCallId = opts?.toolCallId;
|
|
3271
|
-
if (!message && !toolCallId) return undefined;
|
|
3272
|
-
const meta: Record<string, unknown> = {};
|
|
3273
|
-
if (message) meta.message = message;
|
|
3274
|
-
if (toolCallId) meta.toolCallId = toolCallId;
|
|
3275
|
-
return meta;
|
|
3276
|
-
};
|
|
3277
|
-
|
|
3278
|
-
(ctx.ui as any).select = (title: string, options: string[], opts?: any) =>
|
|
3279
|
-
bus.request({ pipeline: "command", type: "select", question: title, options, metadata: buildMeta(opts) })
|
|
3280
|
-
.then(r => r.cancelled ? undefined : r.answer);
|
|
3281
|
-
|
|
3282
|
-
(ctx.ui as any).input = (title: string, placeholder?: string, opts?: any) =>
|
|
3283
|
-
bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: buildMeta(opts) })
|
|
3284
|
-
.then(r => r.cancelled ? undefined : r.answer);
|
|
3285
|
-
|
|
3286
|
-
// Persist pasted images for an ask_user input answer to disk + emit one
|
|
3287
|
-
// asset_register per new hash (dashboard thumbnail). Returns absolute
|
|
3288
|
-
// paths the LLM can Read. Drops over per-image / cumulative caps.
|
|
3289
|
-
// Closes over sessionId, connection, getEmittedAssetHashes (all in
|
|
3290
|
-
// scope here). See change: add-ask-user-input-multiline-paste.
|
|
3291
|
-
const persistAnswerImages = (
|
|
3292
|
-
images: ImageContent[],
|
|
3293
|
-
): Array<{ path: string; mimeType: string; bytes: number }> => {
|
|
3294
|
-
const out: Array<{ path: string; mimeType: string; bytes: number }> = [];
|
|
3295
|
-
const emitted = getEmittedAssetHashes(sessionId);
|
|
3296
|
-
let cumulative = 0;
|
|
3297
|
-
for (const image of images) {
|
|
3298
|
-
const persisted = persistAttachment({ sessionId, image });
|
|
3299
|
-
if (!persisted) continue;
|
|
3300
|
-
if (cumulative + persisted.bytes > ATTACH_MAX_PER_MESSAGE_BYTES) {
|
|
3301
|
-
console.warn(`[bridge] ask_user image over cumulative cap dropped (${persisted.hash})`);
|
|
3302
|
-
continue;
|
|
3303
|
-
}
|
|
3304
|
-
cumulative += persisted.bytes;
|
|
3305
|
-
if (!emitted.has(persisted.hash)) {
|
|
3306
|
-
emitted.add(persisted.hash);
|
|
3307
|
-
connection.send({
|
|
3308
|
-
type: "asset_register",
|
|
3309
|
-
sessionId,
|
|
3310
|
-
hash: persisted.hash,
|
|
3311
|
-
mimeType: persisted.mimeType,
|
|
3312
|
-
data: image.data,
|
|
3313
|
-
});
|
|
3314
|
-
}
|
|
3315
|
-
out.push({ path: persisted.path, mimeType: persisted.mimeType, bytes: persisted.bytes });
|
|
3316
|
-
}
|
|
3317
|
-
return out;
|
|
3318
|
-
};
|
|
3319
|
-
|
|
3320
|
-
// ctx.ui.inputWithImages is NOT a built-in pi method. The ask_user tool
|
|
3321
|
-
// calls it for method:"input" so pasted images survive (ctx.ui.input
|
|
3322
|
-
// decodes to a bare string, dropping PromptResponse.images). Resolves
|
|
3323
|
-
// to: undefined (cancel) | string (no images) | {value, attachments}
|
|
3324
|
-
// (images). See change: add-ask-user-input-multiline-paste, design.md
|
|
3325
|
-
// Decision 1.
|
|
3326
|
-
(ctx.ui as any).inputWithImages = (title: string, placeholder?: string, opts?: any) =>
|
|
3327
|
-
bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: buildMeta(opts) })
|
|
3328
|
-
.then(r => {
|
|
3329
|
-
if (r.cancelled) return undefined;
|
|
3330
|
-
const atts = r.images?.length ? persistAnswerImages(r.images) : [];
|
|
3331
|
-
return atts.length ? { value: r.answer ?? "", attachments: atts } : (r.answer ?? "");
|
|
3332
|
-
});
|
|
3333
|
-
|
|
3334
|
-
(ctx.ui as any).confirm = (title: string, message?: string, opts?: any) =>
|
|
3335
|
-
bus.request({ pipeline: "command", type: "confirm", question: title, metadata: buildMeta(opts, message) })
|
|
3336
|
-
.then(r => !r.cancelled && r.answer === "true");
|
|
3337
|
-
|
|
3338
|
-
(ctx.ui as any).editor = (title: string, prefill?: string, opts?: any) =>
|
|
3339
|
-
bus.request({ pipeline: "command", type: "editor", question: title, defaultValue: prefill, metadata: buildMeta(opts) })
|
|
3340
|
-
.then(r => r.cancelled ? undefined : r.answer);
|
|
3341
|
-
|
|
3342
|
-
// ── Multiselect ──────────────────────────────────────────────
|
|
3343
|
-
// ctx.ui.multiselect is NOT a built-in pi method — we attach it here
|
|
3344
|
-
// so that polyfillMultiselect (and any other consumer) routes through
|
|
3345
|
-
// PromptBus. The dashboard adapter renders a real browser dialog via
|
|
3346
|
-
// MultiselectRenderer; there is intentionally no TUI adapter arm for
|
|
3347
|
-
// multiselect (pi 0.70 RPC mode's ctx.ui.custom is a no-op, so any TUI
|
|
3348
|
-
// arm would auto-cancel the dashboard render in <1s). See changes
|
|
3349
|
-
// fix-multiselect-auto-cancel-on-dashboard (initial bus routing) and
|
|
3350
|
-
// fix-multiselect-tui-arm-self-cancel (TUI arm removal).
|
|
3351
|
-
if (typeof (ctx.ui as any).multiselect === "function") {
|
|
3352
|
-
// Defensive: future upstream pi may add a built-in multiselect.
|
|
3353
|
-
// Override is intentional — the bus-routed version is what
|
|
3354
|
-
// participates in PromptBus first-response-wins semantics.
|
|
3355
|
-
// eslint-disable-next-line no-console
|
|
3356
|
-
console.warn("[bridge] ctx.ui.multiselect already exists — overriding for PromptBus routing");
|
|
3357
|
-
}
|
|
3358
|
-
(ctx.ui as any).multiselect = (title: string, options: string[], opts?: any) =>
|
|
3359
|
-
bus.request({
|
|
3360
|
-
pipeline: "command",
|
|
3361
|
-
type: "multiselect",
|
|
3362
|
-
question: title,
|
|
3363
|
-
options,
|
|
3364
|
-
metadata: opts?.message ? { message: opts.message } : undefined,
|
|
3365
|
-
}).then(decodeMultiselectAnswer);
|
|
3366
|
-
|
|
3367
|
-
// ── Batch ────────────────────────────────────────────────────
|
|
3368
|
-
// ctx.ui.batch is NOT a built-in pi method. The ask_user tool calls it
|
|
3369
|
-
// to dispatch a multi-question batch as ONE bus request carrying
|
|
3370
|
-
// `questions[]` in metadata; the dashboard renders a BatchRenderer
|
|
3371
|
-
// wizard and returns one `{answers}` response (JSON-encoded in the bus
|
|
3372
|
-
// `answer` string). Resolves to BatchAnswer[] on submit, or undefined on
|
|
3373
|
-
// cancel. See change: redesign-ask-user-question-cards.
|
|
3374
|
-
(ctx.ui as any).batch = (title: string, questions: unknown[], opts?: any) =>
|
|
3375
|
-
bus.request({
|
|
3376
|
-
pipeline: "command",
|
|
3377
|
-
type: "batch",
|
|
3378
|
-
question: title,
|
|
3379
|
-
metadata: { ...(buildMeta(opts) ?? {}), questions },
|
|
3380
|
-
}).then((r) => {
|
|
3381
|
-
if (r.cancelled || r.answer == null) return undefined;
|
|
3382
|
-
try {
|
|
3383
|
-
const parsed = JSON.parse(r.answer);
|
|
3384
|
-
if (!Array.isArray(parsed)) return undefined;
|
|
3385
|
-
// Persist any input-step images and rewrite that answer to
|
|
3386
|
-
// {value, attachments}, dropping the raw base64 `images`.
|
|
3387
|
-
// See change: add-ask-user-input-multiline-paste.
|
|
3388
|
-
return parsed.map((a: any) => {
|
|
3389
|
-
if (a && typeof a === "object" && Array.isArray(a.images) && a.images.length) {
|
|
3390
|
-
const atts = persistAnswerImages(a.images);
|
|
3391
|
-
const { images: _drop, ...rest } = a;
|
|
3392
|
-
return atts.length ? { ...rest, attachments: atts } : rest;
|
|
3393
|
-
}
|
|
3394
|
-
return a;
|
|
3395
|
-
});
|
|
3396
|
-
} catch {
|
|
3397
|
-
return undefined;
|
|
3398
|
-
}
|
|
3399
|
-
});
|
|
3400
|
-
|
|
3401
|
-
// Notify is fire-and-forget: call original + forward to dashboard on the
|
|
3402
|
-
// dedicated `notify` channel. See change: split-notify-from-prompt-request.
|
|
3403
|
-
(ctx.ui as any).notify = createNotifyProxy({
|
|
3404
|
-
sessionId,
|
|
3405
|
-
send: (msg) => connection.send(msg),
|
|
3406
|
-
originalNotify,
|
|
3407
|
-
});
|
|
3408
|
-
}
|
|
3409
|
-
|
|
3410
|
-
// Flip ctx.hasUI=true now that ctx.ui.* has been patched to route
|
|
3411
|
-
// through PromptBus → dashboard. `cachedHasUI` (captured earlier at
|
|
3412
|
-
// line ~1287) retains the pi-supplied original value, so
|
|
3413
|
-
// `detectSessionSource` continues to classify dashboard-spawned RPC
|
|
3414
|
-
// vs tmux correctly. Extensions that branch on `ctx.hasUI`
|
|
3415
|
-
// (context-mode `/ctx-stats` / `/ctx-doctor`, pi-agent-browser auto-install)
|
|
3416
|
-
// now take their UI-present branch and render output via the proxied
|
|
3417
|
-
// `ctx.ui.notify`. See change: fix-bridge-hasui-for-headless-rpc.
|
|
3418
|
-
flipHasUI(ctx);
|
|
3419
|
-
|
|
3420
|
-
// Listen for adapter registrations from other extensions (e.g. pi-flows)
|
|
3421
|
-
if (pi.events) {
|
|
3422
|
-
pi.events.on("prompt:register-adapter", (adapter: any) => {
|
|
3423
|
-
if (promptBus && adapter && typeof adapter.name === "string") {
|
|
3424
|
-
promptBus.registerAdapter(adapter);
|
|
3425
|
-
// Inject respond/cancel functions so cross-package adapters can talk back
|
|
3426
|
-
if (typeof adapter.setRespond === "function") {
|
|
3427
|
-
adapter.setRespond((response: any) => promptBus!.respond(response));
|
|
3428
|
-
}
|
|
3429
|
-
if (typeof adapter.setCancel === "function") {
|
|
3430
|
-
adapter.setCancel((id: string) => promptBus!.cancel(id));
|
|
3431
|
-
}
|
|
3432
|
-
}
|
|
3433
|
-
});
|
|
3434
|
-
|
|
3435
|
-
// Expose bus request function for pi-flows to use via emitPromptAndAwait
|
|
3436
|
-
pi.events.emit("prompt:set-bus-request", {
|
|
3437
|
-
request: (options: any) => promptBus!.request(options),
|
|
3438
|
-
});
|
|
3439
|
-
|
|
3440
|
-
// Generic system-follow-up channel: any plugin bridge entry can request
|
|
3441
|
-
// a system-originated continuation through the single drain path by
|
|
3442
|
-
// emitting `dashboard:enqueue-followup`. Inert when no plugin emits it.
|
|
3443
|
-
// See change: add-goal-continuation-plugin (Decision 2).
|
|
3444
|
-
pi.events.on("dashboard:enqueue-followup", (payload: any) => {
|
|
3445
|
-
if (payload && typeof payload.text === "string") {
|
|
3446
|
-
enqueueSystemFollowup(payload.text);
|
|
3447
|
-
}
|
|
3448
|
-
});
|
|
3449
|
-
|
|
3450
|
-
// Generic plugin bridge→server channel: a plugin bridge entry emits
|
|
3451
|
-
// `dashboard:plugin-message` and the main bridge wraps it in a
|
|
3452
|
-
// `plugin_pi_message` envelope over the extension WS. The server
|
|
3453
|
-
// dispatches to handlers registered via
|
|
3454
|
-
// `ServerPluginContext.registerPiHandler(messageType, handler)`.
|
|
3455
|
-
// See change: add-goal-continuation-plugin.
|
|
3456
|
-
pi.events.on("dashboard:plugin-message", (payload: any) => {
|
|
3457
|
-
if (
|
|
3458
|
-
payload &&
|
|
3459
|
-
typeof payload.pluginId === "string" &&
|
|
3460
|
-
typeof payload.messageType === "string"
|
|
3461
|
-
) {
|
|
3462
|
-
connection.send({
|
|
3463
|
-
type: "plugin_pi_message",
|
|
3464
|
-
sessionId,
|
|
3465
|
-
pluginId: payload.pluginId,
|
|
3466
|
-
messageType: payload.messageType,
|
|
3467
|
-
payload: payload.payload ?? null,
|
|
3468
|
-
});
|
|
3469
|
-
}
|
|
3470
|
-
});
|
|
3471
|
-
}
|
|
3472
|
-
|
|
3473
|
-
// Connect first, then auto-start if needed.
|
|
3474
|
-
// session_register must be buffered before any event_forward messages.
|
|
3475
|
-
//
|
|
3476
|
-
// (tasks 7.2/7.3) A REMOTE endpoint is challenged BEFORE the connection
|
|
3477
|
-
// opens: across a network an address proves nothing, so the pinned Ed25519
|
|
3478
|
-
// identity is the only thing that answers "is this my dashboard?" (D8).
|
|
3479
|
-
// Local endpoints are unaffected — the socket/loopback token already
|
|
3480
|
-
// authorises them — so this adds no latency to the common path.
|
|
3481
|
-
if (isRemoteEndpoint(dashboardUrl)) {
|
|
3482
|
-
const pinsFile = serverPinsPath();
|
|
3483
|
-
const connectIfIdentityVerifies = async () => {
|
|
3484
|
-
const verdict = await gateRemoteRegistration({
|
|
3485
|
-
endpoint: dashboardUrl,
|
|
3486
|
-
store: loadServerPins(pinsFile),
|
|
3487
|
-
});
|
|
3488
|
-
// Task 10.3: the cause is distinguishable in the log, not folded into
|
|
3489
|
-
// a generic connection failure.
|
|
3490
|
-
const line = `[dashboard] remote identity ${verdict.cause}: ${verdict.reason}`;
|
|
3491
|
-
if (!verdict.allow) {
|
|
3492
|
-
console.error(`${line} — not registering`);
|
|
3493
|
-
return;
|
|
3494
|
-
}
|
|
3495
|
-
console.log(line);
|
|
3496
|
-
// Only a VERIFIED identity gets its address remembered.
|
|
3497
|
-
if (verdict.fingerprint) notePinEndpoint(pinsFile, verdict.fingerprint, dashboardUrl);
|
|
3498
|
-
connection.connect();
|
|
3499
|
-
};
|
|
3500
|
-
// Guarded discard: a failure here must be OBSERVED, never take the host
|
|
3501
|
-
// pi agent down.
|
|
3502
|
-
void connectIfIdentityVerifies().catch((err) => console.error("[dashboard]", err));
|
|
3503
|
-
} else {
|
|
3504
|
-
connection.connect();
|
|
3505
|
-
}
|
|
3506
|
-
// Drain the buffered transport diagnostics through the live connection
|
|
3507
|
-
// (task 10.5). `send()` buffers while the socket is down, which is the
|
|
3508
|
-
// right behaviour here: the detail is self-describing, so a late delivery
|
|
3509
|
-
// is still a true one.
|
|
3510
|
-
transportDiagnostics.attach({
|
|
3511
|
-
send: (m) => connection.send(m),
|
|
3512
|
-
getSessionId: () => sessionId,
|
|
3513
|
-
});
|
|
3514
|
-
|
|
3515
|
-
// (task 3.8) Verify the instance answering at the recorded endpoint really
|
|
3516
|
-
// is the one the record named. The socket's mode and the local token are
|
|
3517
|
-
// both per-HOME, so a same-HOME impostor passes them — only the published
|
|
3518
|
-
// `instanceId` distinguishes instances. Refusal is loud and does NOT fall
|
|
3519
|
-
// back to a discovered substitute: that substitution is the bug.
|
|
3520
|
-
if (
|
|
3521
|
-
endpointChoice.available &&
|
|
3522
|
-
endpointChoice.source === "rendezvous-record" &&
|
|
3523
|
-
rendezvous?.instanceId
|
|
3524
|
-
) {
|
|
3525
|
-
const verifyRecordedInstance = async () => {
|
|
3526
|
-
const verdict = await verifyInstanceIdentity({
|
|
3527
|
-
healthUrl: healthUrlForInstance(rendezvous.httpPort),
|
|
3528
|
-
expectedInstanceId: rendezvous.instanceId,
|
|
3529
|
-
});
|
|
3530
|
-
if (verdict.adopt) {
|
|
3531
|
-
registeredInstanceId = rendezvous.instanceId;
|
|
3532
|
-
return;
|
|
3533
|
-
}
|
|
3534
|
-
// Only a CONFLICT justifies tearing the connection down. `disconnect()`
|
|
3535
|
-
// sets `intentionalClose`, so nothing rearms the backoff loop and the
|
|
3536
|
-
// session is dead until pi itself restarts — right for an impostor,
|
|
3537
|
-
// catastrophic for an outage. `/api/health` is unreachable for seconds
|
|
3538
|
-
// on every `POST /api/restart` while the gateway socket stays healthy,
|
|
3539
|
-
// so treating silence as refusal would kill every bridge on the host on
|
|
3540
|
-
// every rebuild. Unverified means we simply do not claim an identity.
|
|
3541
|
-
if (!verdict.conflict) {
|
|
3542
|
-
console.error(
|
|
3543
|
-
`[dashboard] instance verification ${verdict.reason} — keeping the connection, identity unclaimed`,
|
|
3544
|
-
);
|
|
3545
|
-
registeredInstanceId = undefined;
|
|
3546
|
-
return;
|
|
3547
|
-
}
|
|
3548
|
-
console.error(`[dashboard] instance verification ${verdict.reason} — disconnecting`);
|
|
3549
|
-
registeredInstanceId = undefined;
|
|
3550
|
-
try {
|
|
3551
|
-
connection.disconnect();
|
|
3552
|
-
} catch {
|
|
3553
|
-
/* already down */
|
|
3554
|
-
}
|
|
3555
|
-
};
|
|
3556
|
-
// Guarded discard: the verification runs alongside the connection and
|
|
3557
|
-
// must never take the host pi agent down, but its failure must still be
|
|
3558
|
-
// OBSERVED rather than dropped on the floor.
|
|
3559
|
-
void verifyRecordedInstance().catch((err) => console.error("[dashboard]", err));
|
|
3560
|
-
}
|
|
3561
|
-
|
|
3562
|
-
// Extract first message (sessionFile/sessionDir already extracted above)
|
|
3563
|
-
const firstMessage = extractFirstMessage(ctx);
|
|
3564
|
-
lastFirstMessage = firstMessage;
|
|
3565
|
-
|
|
3566
|
-
// Register session with initial model/thinkingLevel
|
|
3567
|
-
lastSessionName = pi.getSessionName() ?? "";
|
|
3568
|
-
const initialModel = getCurrentModelString(syncBc());
|
|
3569
|
-
const initialThinkingLevel = (pi as any).getThinkingLevel?.() ?? undefined;
|
|
3570
|
-
lastModel = initialModel;
|
|
3571
|
-
lastThinkingLevel = initialThinkingLevel;
|
|
3572
|
-
|
|
3573
|
-
// Include eventCount so server can skip event wipe on reconnect
|
|
3574
|
-
let eventCount: number | undefined;
|
|
3575
|
-
try {
|
|
3576
|
-
const entries = ctx.sessionManager?.getBranch?.();
|
|
3577
|
-
if (entries) eventCount = entries.length;
|
|
3578
|
-
} catch { /* ignore */ }
|
|
3579
|
-
|
|
3580
|
-
// See change: fix-dashboard-source-mislabelling — sent on every
|
|
3581
|
-
// register so server can re-stamp source after restart. Derived from the
|
|
3582
|
-
// capture-once boolean (token may already be scrubbed). See change:
|
|
3583
|
-
// fix-spawn-token-env-leak.
|
|
3584
|
-
// ctx.cwd is the guarded getter that throws once the session is replaced.
|
|
3585
|
-
// Read it once, defensively — a throw here would skip session_register +
|
|
3586
|
-
// the heartbeat/git timers, leaving a resumed session dead in the UI.
|
|
3587
|
-
// See change: fix-bridge-resume-disconnect.
|
|
3588
|
-
const startCwd = safeCwd(ctx);
|
|
3589
|
-
const spawnToken = consumeSpawnToken();
|
|
3590
|
-
connection.send({
|
|
3591
|
-
type: "session_register",
|
|
3592
|
-
extensionIdentity: bridgeExtensionIdentity(),
|
|
3593
|
-
sessionId,
|
|
3594
|
-
cwd: startCwd,
|
|
3595
|
-
name: lastSessionName || undefined,
|
|
3596
|
-
source: detectSessionSource(cachedHasUI, sessionFile),
|
|
3597
|
-
model: initialModel,
|
|
3598
|
-
thinkingLevel: initialThinkingLevel,
|
|
3599
|
-
sessionFile,
|
|
3600
|
-
sessionDir,
|
|
3601
|
-
firstMessage,
|
|
3602
|
-
eventCount,
|
|
3603
|
-
// The ONLY channel by which the server learns this session's process for a
|
|
3604
|
-
// non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
|
|
3605
|
-
// so without this the server's record has no `pid` and shutdown has
|
|
3606
|
-
// nothing to escalate to — the session was unregistered while a ~127 MB
|
|
3607
|
-
// pi kept running (#452). The two `session_register` sends in
|
|
3608
|
-
// session-sync.ts already carry it; this one, the FIRST register of a
|
|
3609
|
-
// fresh session, did not.
|
|
3610
|
-
// See change: fix-tmux-session-shutdown-leak (D6).
|
|
3611
|
-
pid: process.pid,
|
|
3612
|
-
// The spawn correlation token, echoed back so the server can match THIS
|
|
3613
|
-
// register to the spawn that produced it. This is a fresh session's FIRST
|
|
3614
|
-
// register, and it omitted the token entirely: tier-1 correlation never
|
|
3615
|
-
// fired for a dashboard spawn, so the spawn watchdog could only match by
|
|
3616
|
-
// cwd and reported false register-timeouts for concurrent spawns into one
|
|
3617
|
-
// directory. Single-use — `consumeSpawnToken` scrubs the env.
|
|
3618
|
-
// See change: fix-tmux-session-shutdown-leak (D5).
|
|
3619
|
-
...(spawnToken ? { spawnToken } : {}),
|
|
3620
|
-
...(dashboardSpawned ? { dashboardSpawned: true } : {}),
|
|
3621
|
-
// Tri-state git-repo signal, computed at register time (authority).
|
|
3622
|
-
// See change: gate-session-worktree-button-on-git.
|
|
3623
|
-
isGitRepo: detectIsGitRepo(startCwd),
|
|
3624
|
-
// Fact-forwarding: server decides auto-hide. See change:
|
|
3625
|
-
// auto-hide-headless-worker-sessions.
|
|
3626
|
-
...buildVisibilityRegisterFields(cachedHasUI, process.env),
|
|
3627
|
-
// Applied server-side only for an id it has no record of.
|
|
3628
|
-
// See change: count-non-message-usage.
|
|
3629
|
-
...(usageSeed ? { usageSeed } : {}),
|
|
3630
|
-
});
|
|
3631
|
-
|
|
3632
|
-
// The register above just went out (live socket, or buffered for the
|
|
3633
|
-
// open — either way the manager learns its last-registered endpoint for
|
|
3634
|
-
// the migration gate's reversal target).
|
|
3635
|
-
// See change: fix-bridge-mdns-migration-hijack (task 2.1).
|
|
3636
|
-
connection.noteRegistered();
|
|
3637
|
-
|
|
3638
|
-
// Allow event forwarding now that session_register is buffered
|
|
3639
|
-
sessionReady = true;
|
|
3640
|
-
|
|
3641
|
-
// D3: mint-on-registration. Ask the mcp-server plugin for this session's
|
|
3642
|
-
// /mcp credential now that the socket is (re)registered — the reply
|
|
3643
|
-
// arrives on the session-private lane (mcp_token_minted) and registers
|
|
3644
|
-
// pi-dashboard with pi's built-in MCP, and re-registers after every
|
|
3645
|
-
// reconnect, which is what makes a dashboard restart self-heal. Ordered
|
|
3646
|
-
// after session_register on the SAME socket, so the server's
|
|
3647
|
-
// connection-key attribution is already established when it arrives.
|
|
3648
|
-
// See change: wire-mcp-session-token (D3/D5).
|
|
3649
|
-
connection.send({
|
|
3650
|
-
type: "plugin_pi_message",
|
|
3651
|
-
sessionId,
|
|
3652
|
-
pluginId: "mcp-server",
|
|
3653
|
-
messageType: "mcp/mint-token",
|
|
3654
|
-
payload: {},
|
|
3655
|
-
});
|
|
3656
|
-
|
|
3657
|
-
// Flush any subagent frames buffered during the not-ready window (D1) so a
|
|
3658
|
-
// reconnect/discovery/reload gap self-heals instead of leaving a running
|
|
3659
|
-
// subagent's detail empty. See change: fix-subagent-live-detail-reliability.
|
|
3660
|
-
flushPendingSubagentFrames();
|
|
3661
|
-
|
|
3662
|
-
// Replay full session history so the dashboard has all messages
|
|
3663
|
-
replaySessionEntries();
|
|
3664
|
-
connection.send({ type: "replay_complete", sessionId });
|
|
3665
|
-
// After replay_complete: inside the replay window the server may drop
|
|
3666
|
-
// forwarded events without insert or broadcast (`skipReplayInsert`).
|
|
3667
|
-
// See change: fix-terminal-session-dashboard-reload (D4).
|
|
3668
|
-
if (reloadDelivered) connection.send(reloadCompletedFeedback(sessionId));
|
|
3669
|
-
// If agent is mid-turn (e.g. reload during streaming), send synthetic agent_start
|
|
3670
|
-
if (getBridgeState().isAgentStreaming) {
|
|
3671
|
-
connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
|
|
3672
|
-
}
|
|
3673
|
-
|
|
3674
|
-
// Send initial commands list
|
|
3675
|
-
const commands = filterHiddenCommands(pi.getCommands());
|
|
3676
|
-
connection.send({
|
|
3677
|
-
type: "commands_list",
|
|
3678
|
-
sessionId,
|
|
3679
|
-
commands,
|
|
3680
|
-
});
|
|
3681
|
-
|
|
3682
|
-
// Send initial flows list
|
|
3683
|
-
sendFlowsList();
|
|
3684
|
-
|
|
3685
|
-
// Send available models
|
|
3686
|
-
cachedModelRegistry = (ctx as any).modelRegistry;
|
|
3687
|
-
if (cachedModelRegistry) {
|
|
3688
|
-
try {
|
|
3689
|
-
const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
|
|
3690
|
-
connection.send({ type: "models_list", sessionId, models });
|
|
3691
|
-
// See change: replace-hardcoded-provider-lists.
|
|
3692
|
-
connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
|
|
3693
|
-
} catch { /* modelRegistry not available */ }
|
|
3694
|
-
}
|
|
3695
|
-
|
|
3696
|
-
// Apply default model only on brand-new sessions (no prior message history)
|
|
3697
|
-
// that were NOT launched with an explicit --model flag. Resume (--session) and
|
|
3698
|
-
// fork (--fork) both load parent messages, so messageCount > 0 and we keep their
|
|
3699
|
-
// existing model. Mirrors pi's own !hasExistingSession gate (sdk.js:106 —
|
|
3700
|
-
// `existingSession.messages.length > 0`). NOT the raw getEntries() count: pi's
|
|
3701
|
-
// sdk.js auto-appends model_change + thinking_level_change setup entries to a
|
|
3702
|
-
// brand-new session BEFORE emitting session_start, so getEntries() is ≥ 2 even
|
|
3703
|
-
// for a session with no user history. Only message entries count.
|
|
3704
|
-
// The bridge runs inside the pi process, so process.argv is pi's argv — an
|
|
3705
|
-
// explicit --model there is the spawner's resolved choice and the default
|
|
3706
|
-
// never overrides it. The deferred retry below needs no separate guard: when
|
|
3707
|
-
// the gate is false this never sets pendingDefaultModel, so onProviderChanged
|
|
3708
|
-
// has nothing to re-apply.
|
|
3709
|
-
// See changes: fix-resume-keeps-session-model,
|
|
3710
|
-
// fix-default-model-new-session-entry-count,
|
|
3711
|
-
// fix-default-model-clobbers-explicit-model (issue #595).
|
|
3712
|
-
const entryCount = ctx.sessionManager.buildSessionContext?.()?.messages?.length ?? 0;
|
|
3713
|
-
const freshConfig = loadConfig();
|
|
3714
|
-
if (shouldApplyDefaultModel({
|
|
3715
|
-
reason: _event?.reason,
|
|
3716
|
-
entryCount,
|
|
3717
|
-
hasModelRegistry: Boolean(cachedModelRegistry),
|
|
3718
|
-
hasDefaultModel: Boolean(freshConfig.defaultModel),
|
|
3719
|
-
hasExplicitModel: hasExplicitModelArg(process.argv),
|
|
3720
|
-
})) {
|
|
3721
|
-
pendingDefaultModel = applyDefaultModel();
|
|
3722
|
-
}
|
|
3723
|
-
|
|
3724
|
-
// Send initial roles
|
|
3725
|
-
if (pi.events) {
|
|
3726
|
-
const rolesData: any = {};
|
|
3727
|
-
pi.events.emit("roles:get-all", rolesData);
|
|
3728
|
-
if (rolesData.roles) {
|
|
3729
|
-
connection.send({
|
|
3730
|
-
type: "roles_list",
|
|
3731
|
-
sessionId,
|
|
3732
|
-
roles: rolesData.roles ?? {},
|
|
3733
|
-
presets: rolesData.presets ?? [],
|
|
3734
|
-
activePreset: rolesData.activePreset ?? null,
|
|
3735
|
-
builtinRoleNames: rolesData.builtinRoleNames ?? [],
|
|
3736
|
-
});
|
|
3737
|
-
}
|
|
3738
|
-
}
|
|
3739
|
-
|
|
3740
|
-
// Discover or auto-start server (non-blocking — connection will reconnect)
|
|
3741
|
-
//
|
|
3742
|
-
// When a real launchServer() is about to run (not on mDNS/health-check
|
|
3743
|
-
// paths), mount an animated TUI widget above the editor using pi-tui's
|
|
3744
|
-
// Loader (a real Component, self-animating at 80ms, like pi-flows'
|
|
3745
|
-
// architect-widget). The previous implementation used
|
|
3746
|
-
// ctx.ui.setStatus(...) which only writes a footer string and relies on
|
|
3747
|
-
// the TUI render loop being ticked elsewhere — on the cold-start path
|
|
3748
|
-
// nothing else requests renders, so the spinner never animated and often
|
|
3749
|
-
// never appeared. setWidget(key, factory, {placement:"aboveEditor"}) gives
|
|
3750
|
-
// us a managed component that owns its own render loop and is always
|
|
3751
|
-
// visible while the launch is in flight.
|
|
3752
|
-
let spinnerTimer: NodeJS.Timeout | null = null;
|
|
3753
|
-
let spinnerStart = 0;
|
|
3754
|
-
let activeLoader: Loader | null = null;
|
|
3755
|
-
const stopSpinner = () => {
|
|
3756
|
-
// Release the interval BEFORE the guarded ctx.ui call, so a stale ctx
|
|
3757
|
-
// still stops the 1s label refresh instead of leaking it.
|
|
3758
|
-
if (spinnerTimer) {
|
|
3759
|
-
clearInterval(spinnerTimer);
|
|
3760
|
-
spinnerTimer = null;
|
|
3761
|
-
}
|
|
3762
|
-
activeLoader = null;
|
|
3763
|
-
// This runs from `onLaunchEnd` AND from the terminal .then()/.catch()
|
|
3764
|
-
// below, either of which can land after a session replacement/reload has
|
|
3765
|
-
// invalidated `ctx`. See ui-stale-guard.ts.
|
|
3766
|
-
runUiSafely(() => ctx.ui.setWidget("pi-dashboard-launch", undefined));
|
|
3767
|
-
};
|
|
3768
|
-
// Resolve the ports the auto-start chain uses (health check + launch)
|
|
3769
|
-
// with the shared env → config.json → default precedence, so a session
|
|
3770
|
-
// whose environment names the dashboard's real ports attaches to (or
|
|
3771
|
-
// launches on) THOSE ports instead of a stale config/default — this is
|
|
3772
|
-
// the split-brain fix: without it, a harness/container session with
|
|
3773
|
-
// DASHBOARD_PORT in its env health-checked 8000, found nothing, and
|
|
3774
|
-
// launched a competing dashboard on 8000. `config` is not mutated;
|
|
3775
|
-
// `loadConfig()` stays untouched (design D1/D2).
|
|
3776
|
-
// See change: fix-bridge-autostart-port-resolution.
|
|
3777
|
-
autoStartServer({ ...config, ...resolveDashboardPorts(process.env, config) }, {
|
|
3778
|
-
discoverDashboard,
|
|
3779
|
-
isDashboardRunning,
|
|
3780
|
-
launchServer,
|
|
3781
|
-
notify: (msg, level) => runUiSafely(() => ctx.ui.notify(msg, level)),
|
|
3782
|
-
onLaunchStart: () => {
|
|
3783
|
-
spinnerStart = Date.now();
|
|
3784
|
-
const buildMessage = () => {
|
|
3785
|
-
const elapsed = Math.floor((Date.now() - spinnerStart) / 1000);
|
|
3786
|
-
return `starting dashboard server … (${elapsed}s)`;
|
|
3787
|
-
};
|
|
3788
|
-
runUiSafely(() =>
|
|
3789
|
-
ctx.ui.setWidget(
|
|
3790
|
-
"pi-dashboard-launch",
|
|
3791
|
-
(tui: unknown, theme: { fg: (role: string, s: string) => string }) => {
|
|
3792
|
-
const loader = new Loader(
|
|
3793
|
-
tui as ConstructorParameters<typeof Loader>[0],
|
|
3794
|
-
(s: string) => theme.fg("accent", s),
|
|
3795
|
-
(s: string) => theme.fg("muted", s),
|
|
3796
|
-
buildMessage(),
|
|
3797
|
-
);
|
|
3798
|
-
activeLoader = loader;
|
|
3799
|
-
// Loader has stop() but no dispose(); wire dispose so that
|
|
3800
|
-
// setExtensionWidget's teardown stops the 80ms animation interval.
|
|
3801
|
-
(loader as Loader & { dispose?: () => void }).dispose = () => loader.stop();
|
|
3802
|
-
return loader;
|
|
3803
|
-
},
|
|
3804
|
-
{ placement: "aboveEditor" },
|
|
3805
|
-
),
|
|
3806
|
-
);
|
|
3807
|
-
// Refresh the elapsed-seconds label every second. Frame animation is
|
|
3808
|
-
// driven by the Loader's own 80ms interval.
|
|
3809
|
-
spinnerTimer = setInterval(() => {
|
|
3810
|
-
activeLoader?.setMessage(buildMessage());
|
|
3811
|
-
}, 1000);
|
|
3812
|
-
},
|
|
3813
|
-
onLaunchEnd: () => {
|
|
3814
|
-
stopSpinner();
|
|
3815
|
-
},
|
|
3816
|
-
// Register the spawned dashboard-server PID into `selfSpawnedPgids`
|
|
3817
|
-
// synchronously, before the next 5 s process-scan tick. Keeps the
|
|
3818
|
-
// dashboard's own `node` infrastructure out of the session-card
|
|
3819
|
-
// process list. See change: tighten-process-list-ux.
|
|
3820
|
-
onServerSpawned: (childPid: number) => {
|
|
3821
|
-
selfSpawnedPgids.add(childPid);
|
|
3822
|
-
},
|
|
3823
|
-
// Honor the server's `server_restarting` quiesce window. While a
|
|
3824
|
-
// deliberate restart/shutdown is in flight, skip the spawn step so we
|
|
3825
|
-
// don't race the orchestrator. Discovery + reconnection still run.
|
|
3826
|
-
// See change: fix-restart-bridge-auto-start-race.
|
|
3827
|
-
shouldSuppressAutoStart: () => connection.shouldSuppressAutoStart(),
|
|
3828
|
-
}).then((result) => {
|
|
3829
|
-
stopSpinner(); // safety net — covers onLaunchEnd not firing
|
|
3830
|
-
if (result.server && result.server.piPort !== config.piPort) {
|
|
3831
|
-
const candidateUrl = `ws://${result.server.host === "localhost" ? "localhost" : result.server.host}:${result.server.piPort}`;
|
|
3832
|
-
// fix-bridge-mdns-migration-hijack: a DISCOVERED candidate only
|
|
3833
|
-
// SUGGESTS. Whether the connection follows it is decided — and
|
|
3834
|
-
// recorded — by `ConnectionManager.retargetTo`, which refuses to
|
|
3835
|
-
// drop an established, registered connection until the candidate has
|
|
3836
|
-
// PROVEN reachable (`GET /api/health` → `{ok:true}`, D1), honours
|
|
3837
|
-
// localhost preference against a remote candidate (D3), and returns
|
|
3838
|
-
// to the last registered endpoint if the candidate dies after
|
|
3839
|
-
// adoption (D2). The blanket refusal this replaces also blocked
|
|
3840
|
-
// every LEGITIMATE migration (a server that really moved).
|
|
3841
|
-
if (endpointPinned) {
|
|
3842
|
-
// D3 (add-pi-gateway-transport-identity): a pinned endpoint
|
|
3843
|
-
// refuses every re-target. The refusal stays on the record (10.2).
|
|
3844
|
-
const decision = decideRetarget({
|
|
3845
|
-
current: { endpoint: dashboardUrl, instanceId: registeredInstanceId },
|
|
3846
|
-
candidate: { endpoint: candidateUrl },
|
|
3847
|
-
pinned: true,
|
|
3848
|
-
failed: false,
|
|
3849
|
-
identityVerified: false,
|
|
3850
|
-
});
|
|
3851
|
-
const refusedDetail = `${dashboardUrl} -> ${candidateUrl}: ${decision.reason}`;
|
|
3852
|
-
console.log(`[dashboard] re-target ${refusedDetail}`);
|
|
3853
|
-
transportDiagnostics.record({ event: "retarget_refused", detail: refusedDetail });
|
|
3854
|
-
return;
|
|
3855
|
-
}
|
|
3856
|
-
const trigger = `mdns discovery (${result.server.host}:${result.server.port}, gateway ${result.server.piPort})`;
|
|
3857
|
-
// The health probe runs on the candidate's HTTP port — the record's
|
|
3858
|
-
// `port`, not the gateway port — and completes BEFORE the incumbent
|
|
3859
|
-
// is dropped (retargetTo owns that ordering).
|
|
3860
|
-
const healthUrl = `http://${result.server.host}:${result.server.port}/api/health`;
|
|
3861
|
-
connection
|
|
3862
|
-
.retargetTo(candidateUrl, {
|
|
3863
|
-
trigger,
|
|
3864
|
-
verify: () => probeEndpointReachability({ healthUrl }),
|
|
3865
|
-
})
|
|
3866
|
-
.then((accepted) => {
|
|
3867
|
-
console.log(`[dashboard] re-target ${dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);
|
|
3868
|
-
})
|
|
3869
|
-
.catch((err: unknown) => console.error("[dashboard] re-target decision failed:", err));
|
|
3870
|
-
}
|
|
3871
|
-
}).catch(() => { stopSpinner(); });
|
|
3872
|
-
|
|
3873
|
-
// Send initial git info + the session's pi version. A session change already
|
|
3874
|
-
// ran the first evaluation (and renewed the tracker) in handleSessionChange;
|
|
3875
|
-
// doing it again would double the synchronous git work.
|
|
3876
|
-
if (!sessionChanged) {
|
|
3877
|
-
const gbc = syncBc();
|
|
3878
|
-
renewGitTracker().evaluateFirst(gbc, startCwd);
|
|
3879
|
-
applyBc(gbc);
|
|
3880
|
-
}
|
|
3881
|
-
sendCwdMissingIfChanged(startCwd);
|
|
3882
|
-
sendPiVersionIfChanged();
|
|
3883
|
-
|
|
3884
|
-
// Start metrics monitor and heartbeat
|
|
3885
|
-
startMetricsMonitor();
|
|
3886
|
-
heartbeatTimer = setInterval(() => {
|
|
3887
|
-
if (!isActive()) return;
|
|
3888
|
-
connection.send({
|
|
3889
|
-
type: "session_heartbeat",
|
|
3890
|
-
sessionId,
|
|
3891
|
-
// Liveness truth for the server's status reconcile: `streaming` is
|
|
3892
|
-
// otherwise a one-way latch and a single dropped `agent_end` sticks
|
|
3893
|
-
// the card on `Thinking…` forever.
|
|
3894
|
-
// `=== true` because the flag is optional and is `undefined` before
|
|
3895
|
-
// the first turn: sent raw it would serialize away and read as "old
|
|
3896
|
-
// bridge, no liveness truth" instead of "idle".
|
|
3897
|
-
// See change: fix-stuck-streaming-status-latch.
|
|
3898
|
-
agentRunning: getBridgeState().isAgentStreaming === true,
|
|
3899
|
-
// Fold the bridge→server ring-buffer eviction count into the heartbeat
|
|
3900
|
-
// so it reaches `/api/health`. See change:
|
|
3901
|
-
// fix-stuck-tool-card-on-dropped-event.
|
|
3902
|
-
metrics: {
|
|
3903
|
-
...collectMetrics(),
|
|
3904
|
-
droppedBufferedFrames: connection.getDroppedBufferedCount(),
|
|
3905
|
-
refusedInboundFrames: connection.getDroppedInboundCount(),
|
|
3906
|
-
// Subagent-tick throttle counters ride the same transport, so the
|
|
3907
|
-
// throttle's two information-loss modes are observable in production
|
|
3908
|
-
// instead of only at L1. See change: reduce-bridge-tick-bandwidth (D6).
|
|
3909
|
-
...subagentTickThrottle.stats,
|
|
3910
|
-
// Subagent fan-out admission counters ride the same transport, so a
|
|
3911
|
-
// narrowed fan-out is observable instead of looking like a model that
|
|
3912
|
-
// chose not to parallelize. See change:
|
|
3913
|
-
// bound-subagent-fanout-under-host-pressure (D7).
|
|
3914
|
-
...fanoutAdmission.counters,
|
|
3915
|
-
// Agent path gate counters (in-root decisions are counted, not logged).
|
|
3916
|
-
pathGateInRoot: pathGate.counters.inRoot,
|
|
3917
|
-
pathGateAsked: pathGate.counters.asked,
|
|
3918
|
-
pathGateBlocked: pathGate.counters.blocked,
|
|
3919
|
-
// Poll-cost counters (summed across sessions on /api/health).
|
|
3920
|
-
// See change: optimize-polling-hot-paths.
|
|
3921
|
-
...pollCost,
|
|
3922
|
-
},
|
|
3923
|
-
});
|
|
3924
|
-
}, HEARTBEAT_INTERVAL);
|
|
3925
|
-
getBridgeState().timers!.push(heartbeatTimer);
|
|
3926
|
-
|
|
3927
|
-
// Start git + name/model polling
|
|
3928
|
-
startGitPollTimer(ctx);
|
|
3929
|
-
|
|
3930
|
-
// Start the adaptive process scanner (detect stalled child processes).
|
|
3931
|
-
// One async `ps -A` per scan; fast while the agent/tools run, idle
|
|
3932
|
-
// otherwise. session_start re-runs: dispose the previous scheduler first so
|
|
3933
|
-
// schedules never stack. See change: optimize-polling-hot-paths.
|
|
3934
|
-
ensurePollingDisposable();
|
|
3935
|
-
const scheduler = createProcessScanScheduler({
|
|
3936
|
-
platform: process.platform,
|
|
3937
|
-
setTimer: setRegisteredTimeout,
|
|
3938
|
-
clearTimer: clearRegisteredTimeout,
|
|
3939
|
-
scan: async () => {
|
|
3940
|
-
if (!isActive()) return { changed: false };
|
|
3941
|
-
const processes = await scanChildProcessesAsync(
|
|
3942
|
-
process.pid,
|
|
3943
|
-
trackedPgids,
|
|
3944
|
-
PROCESS_MIN_ELAPSED_MS,
|
|
3945
|
-
{ excludedPgids: selfSpawnedPgids },
|
|
3946
|
-
);
|
|
3947
|
-
if (!isActive() || polling.processScan !== scheduler) return { changed: false };
|
|
3948
|
-
const currentPids = JSON.stringify(processes.map((p) => p.pid).sort());
|
|
3949
|
-
if (currentPids === previousProcessPids) return { changed: false };
|
|
3950
|
-
previousProcessPids = currentPids;
|
|
3951
|
-
connection.send({
|
|
3952
|
-
type: "process_list",
|
|
3953
|
-
sessionId,
|
|
3954
|
-
processes: processes.map((p) => ({ pid: p.pid, pgid: p.pgid, command: p.command, elapsedMs: p.elapsedMs })),
|
|
3955
|
-
});
|
|
3956
|
-
return { changed: true };
|
|
3957
|
-
},
|
|
3958
|
-
});
|
|
3959
|
-
polling.replaceProcessScan(scheduler);
|
|
3960
|
-
scheduler.start();
|
|
3961
|
-
|
|
3962
|
-
// Register flow event listeners (pi-flows emits these via pi.events)
|
|
3963
|
-
registerFlowEventListeners(syncBc(), () => sessionReady, getFlowsList);
|
|
3964
|
-
|
|
3965
|
-
// Extension UI System (Phase 1): subscribe to invalidate once per
|
|
3966
|
-
// session, then run the discovery probe. The probe is synchronous
|
|
3967
|
-
// and re-runs on every reconnect (see `onReconnect` callback above).
|
|
3968
|
-
// See change: add-extension-ui-modal.
|
|
3969
|
-
subscribeUiInvalidate(uiModulesBridgeCtx);
|
|
3970
|
-
refreshUiModules(uiModulesBridgeCtx);
|
|
3971
|
-
}));
|
|
3972
|
-
|
|
3973
|
-
// Shared handler for session changes (new/fork/resume)
|
|
3974
|
-
function handleSessionChange(ctx: any, usageSeed?: ReturnType<UsageDrain["baseline"]>) {
|
|
3975
|
-
// Clear attachedChange on a real session switch (new/fork/resume): it is
|
|
3976
|
-
// persisted globally + restored at activate, so without this the previous
|
|
3977
|
-
// session's attached change would leak into the new session's prompt until
|
|
3978
|
-
// the server replays. The server re-pushes the correct value for the new
|
|
3979
|
-
// sessionId on its session_register. See change: inject-session-context-into-agent.
|
|
3980
|
-
attachedChange = null;
|
|
3981
|
-
getBridgeState().attachedChange = null;
|
|
3982
|
-
// Drop retained subagent frames/snapshots on a real session switch — the
|
|
3983
|
-
// new/fork/resumed session's subagents are unrelated to the outgoing one.
|
|
3984
|
-
// See change: fix-subagent-live-detail-reliability.
|
|
3985
|
-
subagentFrameBuffer.reset();
|
|
3986
|
-
// Same disposal point for the tick throttle: clear every armed trailing
|
|
3987
|
-
// timer and drop every held frame, so nothing from the outgoing session
|
|
3988
|
-
// can fire against the new one.
|
|
3989
|
-
// See change: reduce-bridge-tick-bandwidth (D3).
|
|
3990
|
-
subagentTickThrottle.reset();
|
|
3991
|
-
// A session boundary invalidates the CONTENT itself (unlike a reconnect), so
|
|
3992
|
-
// drop any parked text snapshot and cancel its window rather than flushing
|
|
3993
|
-
// it into the new session. See change:
|
|
3994
|
-
// coalesce-bridge-message-update-snapshots (D8).
|
|
3995
|
-
coalescer.clear();
|
|
3996
|
-
// Clear the stop-after-turn latch so a new/fork/resumed session does not
|
|
3997
|
-
// inherit the previous session's pending graceful-stop and shut down on
|
|
3998
|
-
// its first turn_end. See change: adopt-pi-071-072-073-features.
|
|
3999
|
-
getBridgeState().shouldStopAfterTurn = false;
|
|
4000
|
-
// Drop the auto-namer and its carried state: it is a PER-SESSION state
|
|
4001
|
-
// machine, so a new/fork/resumed session must not inherit the outgoing
|
|
4002
|
-
// session's permanent stop, spent attempt budget or auto-named flag — it
|
|
4003
|
-
// would report `stopped` / `already-named` without ever attempting to name.
|
|
4004
|
-
// The server re-pushes the incoming session's own persisted state on its
|
|
4005
|
-
// session_register. See change: fix-auto-naming-reasoning-model.
|
|
4006
|
-
autoNamer = undefined;
|
|
4007
|
-
namerState = undefined;
|
|
4008
|
-
prev.namerState = undefined;
|
|
4009
|
-
// Bridge shadow queues reset on session change so the new session
|
|
4010
|
-
// starts with empty chips. See change: add-followup-edit-and-steer-cancel.
|
|
4011
|
-
if (bridgeSteering.length > 0 || bridgeFollowUp.length > 0) {
|
|
4012
|
-
bridgeSteering = [];
|
|
4013
|
-
// Drops every entry AND its image bytes, releasing the byte budget.
|
|
4014
|
-
bridgeFollowUp.reset();
|
|
4015
|
-
emitQueueUpdate();
|
|
4016
|
-
}
|
|
4017
|
-
renewGitTracker();
|
|
4018
|
-
const bc = syncBc();
|
|
4019
|
-
_handleSessionChange(bc, ctx, getFlowsList, usageSeed);
|
|
4020
|
-
applyBc(bc);
|
|
4021
|
-
// A new session id needs its own `pi_version_update` (below-floor flag).
|
|
4022
|
-
// After applyBc, so syncBc() carries the NEW session id.
|
|
4023
|
-
// See change: update-pi-core-1-0-adopt-apis.
|
|
4024
|
-
sendPiVersionIfChanged();
|
|
4025
|
-
|
|
4026
|
-
// Restart polling timers
|
|
4027
|
-
startGitPollTimer(ctx);
|
|
4028
|
-
}
|
|
2088
|
+
// Plugin-declared bus channels: plugin bridges emit
|
|
2089
|
+
// `dashboard:register-event-forward`; `attach()` subscribes the listener and
|
|
2090
|
+
// then emits `dashboard:bridge-ready` so plugins that activated first
|
|
2091
|
+
// re-declare. Core names no plugin channel. See change:
|
|
2092
|
+
// add-plugin-bridge-contributions (D1/D2/D4).
|
|
2093
|
+
const pluginForwardRegistry = new PluginForwardRegistry(pi.events, {
|
|
2094
|
+
send: (eventType, data) =>
|
|
2095
|
+
inst.connection.send({
|
|
2096
|
+
type: "event_forward",
|
|
2097
|
+
sessionId: inst.sessionId,
|
|
2098
|
+
event: { eventType, timestamp: Date.now(), data },
|
|
2099
|
+
}),
|
|
2100
|
+
isSessionReady: () => inst.sessionReady,
|
|
2101
|
+
isActive,
|
|
2102
|
+
isConnected: () => inst.connection.isConnected,
|
|
2103
|
+
isCoreChannel: (channel) => channel in EVENT_BUS_MAP,
|
|
2104
|
+
});
|
|
2105
|
+
inst.pluginForwardRegistry = pluginForwardRegistry;
|
|
2106
|
+
pluginForwardRegistry.attach();
|
|
4029
2107
|
|
|
4030
|
-
|
|
4031
|
-
// start and session change call this so the two timers can never drift.
|
|
4032
|
-
// Caches ctx.cwd (the throwing getter) and clears any prior timer first.
|
|
4033
|
-
function startGitPollTimer(ctx: any) {
|
|
4034
|
-
if (gitPollTimer) clearInterval(gitPollTimer);
|
|
4035
|
-
// safeCwd: startGitPollTimer runs inside handleSessionChange BEFORE
|
|
4036
|
-
// connection.connect(); an un-guarded ctx.cwd throw here skips connect()
|
|
4037
|
-
// (#393). See change: fix-bridge-resume-disconnect.
|
|
4038
|
-
cachedCwd = safeCwd(ctx);
|
|
4039
|
-
const pollState = createGitPollState();
|
|
4040
|
-
gitPollTimer = setInterval(() => {
|
|
4041
|
-
// runGitPollTick handles a rejecting git tick itself; this catch is the
|
|
4042
|
-
// last line so the interval callback can never raise an unhandled rejection.
|
|
4043
|
-
runGitPollTick({
|
|
4044
|
-
isActive,
|
|
4045
|
-
cachedCwd: () => cachedCwd,
|
|
4046
|
-
tickGit: (cwd) => {
|
|
4047
|
-
const gbc = syncBc();
|
|
4048
|
-
polling.gitTracker?.tick(gbc, cwd);
|
|
4049
|
-
applyBc(gbc);
|
|
4050
|
-
},
|
|
4051
|
-
sendCwdMissingIfChanged,
|
|
4052
|
-
sendSessionNameIfChanged,
|
|
4053
|
-
sendModelUpdateIfChanged,
|
|
4054
|
-
sendPiVersionIfChanged: () => _sendPiVersionIfChanged(syncBc()),
|
|
4055
|
-
state: pollState,
|
|
4056
|
-
}).catch((err) => console.error("[dashboard] git poll tick failed:", err));
|
|
4057
|
-
}, GIT_POLL_INTERVAL);
|
|
4058
|
-
getBridgeState().timers!.push(gitPollTimer);
|
|
4059
|
-
}
|
|
2108
|
+
registerSessionStart(inst);
|
|
4060
2109
|
|
|
4061
2110
|
// session_switch and session_fork events removed in pi 0.65.0.
|
|
4062
2111
|
// Now handled via session_start with event.reason ("new"|"fork"|"resume").
|
|
4063
2112
|
|
|
4064
|
-
|
|
4065
|
-
if (!isActive()) return;
|
|
4066
|
-
cachedCtx = ctx;
|
|
4067
|
-
if (!sessionReady) return;
|
|
4068
|
-
// Drain point: compaction / usage entries recorded during the turn.
|
|
4069
|
-
// See change: count-non-message-usage.
|
|
4070
|
-
drainUsage(ctx);
|
|
4071
|
-
|
|
4072
|
-
// Send firstMessage update after first turn if not previously sent
|
|
4073
|
-
if (!lastFirstMessage) {
|
|
4074
|
-
const firstMsg = extractFirstMessage(ctx);
|
|
4075
|
-
if (firstMsg) {
|
|
4076
|
-
lastFirstMessage = firstMsg;
|
|
4077
|
-
connection.send({
|
|
4078
|
-
type: "first_message_update",
|
|
4079
|
-
sessionId,
|
|
4080
|
-
firstMessage: firstMsg,
|
|
4081
|
-
});
|
|
4082
|
-
}
|
|
4083
|
-
}
|
|
4084
|
-
|
|
4085
|
-
}));
|
|
2113
|
+
registerTurnEnd(inst);
|
|
4086
2114
|
|
|
4087
2115
|
// Control event (never `event_forward`): an idle cache refresh's usage
|
|
4088
2116
|
// entry lands before the NEXT decision, so each decision is a drain point.
|
|
@@ -4094,68 +2122,22 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
4094
2122
|
drainUsage(ctx);
|
|
4095
2123
|
}) as any);
|
|
4096
2124
|
|
|
4097
|
-
|
|
4098
|
-
if (!isActive()) return;
|
|
4099
|
-
// Let the reloaded instance (fresh ExtensionAPI) pass the re-entry guard.
|
|
4100
|
-
// See change: fix-terminal-session-dashboard-reload (D4).
|
|
4101
|
-
releaseBridgeOwnerOnShutdown(getBridgeState(), event?.reason);
|
|
4102
|
-
// Remove this session's pi-dashboard MCP registration (a reloaded
|
|
4103
|
-
// instance re-registers on its own mint). See change: migrate-mcp-to-pi-builtin (D1).
|
|
4104
|
-
mcpRegistrar.onSessionShutdown();
|
|
4105
|
-
getBridgeState().isAgentStreaming = false;
|
|
4106
|
-
stopMetricsMonitor();
|
|
4107
|
-
if (heartbeatTimer) {
|
|
4108
|
-
clearInterval(heartbeatTimer);
|
|
4109
|
-
heartbeatTimer = null;
|
|
4110
|
-
}
|
|
4111
|
-
if (gitPollTimer) {
|
|
4112
|
-
clearInterval(gitPollTimer);
|
|
4113
|
-
gitPollTimer = null;
|
|
4114
|
-
}
|
|
4115
|
-
drainDisposables(getBridgeState());
|
|
4116
|
-
// Flush undrained entry usage BEFORE session_unregister (which ends the
|
|
4117
|
-
// session server-side), on every shutdown reason: quit, reload and
|
|
4118
|
-
// session replacement (new/resume/fork). See change: count-non-message-usage.
|
|
4119
|
-
sendShutdownUsageThenUnregister(
|
|
4120
|
-
() => drainUsage(ctx),
|
|
4121
|
-
() => connection.send({
|
|
4122
|
-
type: "session_unregister",
|
|
4123
|
-
sessionId,
|
|
4124
|
-
}),
|
|
4125
|
-
);
|
|
4126
|
-
|
|
4127
|
-
// Drop retained subagent frames/snapshots on shutdown.
|
|
4128
|
-
// See change: fix-subagent-live-detail-reliability.
|
|
4129
|
-
subagentFrameBuffer.reset();
|
|
4130
|
-
// See change: reduce-bridge-tick-bandwidth (D3).
|
|
4131
|
-
subagentTickThrottle.reset();
|
|
4132
|
-
// A shutdown is a session boundary: discard parked text, cancel the window.
|
|
4133
|
-
// See change: coalesce-bridge-message-update-snapshots (D8).
|
|
4134
|
-
coalescer.clear();
|
|
4135
|
-
|
|
4136
|
-
// Best-effort: remove this session's pasted ask_user attachments.
|
|
4137
|
-
// See change: add-ask-user-input-multiline-paste.
|
|
4138
|
-
cleanupAttachmentsForSession(sessionId);
|
|
4139
|
-
|
|
4140
|
-
// Give time for the unregister to send
|
|
4141
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
4142
|
-
connection.disconnect();
|
|
4143
|
-
}));
|
|
2125
|
+
registerSessionShutdown(inst);
|
|
4144
2126
|
|
|
4145
2127
|
// Re-send models list when custom providers finish async discovery
|
|
4146
2128
|
onProviderChanged(() => {
|
|
4147
2129
|
if (!isActive()) return;
|
|
4148
|
-
if (cachedModelRegistry && sessionReady) {
|
|
2130
|
+
if (inst.cachedModelRegistry && inst.sessionReady) {
|
|
4149
2131
|
try {
|
|
4150
|
-
const models = filterByEnabledModels(cachedModelRegistry.getAvailable().map(toModelInfo));
|
|
4151
|
-
connection.send({ type: "models_list", sessionId, models });
|
|
2132
|
+
const models = filterByEnabledModels(inst.cachedModelRegistry.getAvailable().map(toModelInfo));
|
|
2133
|
+
inst.connection.send({ type: "models_list", sessionId: inst.sessionId, models });
|
|
4152
2134
|
// See change: replace-hardcoded-provider-lists.
|
|
4153
|
-
connection.send({ type: "providers_list", sessionId, providers: buildProviderCatalogue() });
|
|
2135
|
+
inst.connection.send({ type: "providers_list", sessionId: inst.sessionId, providers: buildProviderCatalogue() });
|
|
4154
2136
|
} catch { /* ignore */ }
|
|
4155
2137
|
|
|
4156
2138
|
// Retry pending default model — custom provider may now have its models
|
|
4157
|
-
if (pendingDefaultModel) {
|
|
4158
|
-
pendingDefaultModel = applyDefaultModel();
|
|
2139
|
+
if (inst.pendingDefaultModel) {
|
|
2140
|
+
inst.pendingDefaultModel = applyDefaultModel();
|
|
4159
2141
|
}
|
|
4160
2142
|
}
|
|
4161
2143
|
});
|
|
@@ -4164,13 +2146,13 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
4164
2146
|
const state = getBridgeState();
|
|
4165
2147
|
state.cleanup = () => {
|
|
4166
2148
|
const s = getBridgeState();
|
|
4167
|
-
s.sessionId = sessionId;
|
|
4168
|
-
s.attachedChange = attachedChange;
|
|
4169
|
-
s.ctx = cachedCtx;
|
|
4170
|
-
s.modelRegistry = cachedModelRegistry;
|
|
4171
|
-
s.hasUI = cachedHasUI;
|
|
4172
|
-
if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
|
|
4173
|
-
if (gitPollTimer) { clearInterval(gitPollTimer); gitPollTimer = null; }
|
|
2149
|
+
s.sessionId = inst.sessionId;
|
|
2150
|
+
s.attachedChange = inst.attachedChange;
|
|
2151
|
+
s.ctx = inst.cachedCtx;
|
|
2152
|
+
s.modelRegistry = inst.cachedModelRegistry;
|
|
2153
|
+
s.hasUI = inst.cachedHasUI;
|
|
2154
|
+
if (inst.heartbeatTimer) { clearInterval(inst.heartbeatTimer); inst.heartbeatTimer = null; }
|
|
2155
|
+
if (inst.gitPollTimer) { clearInterval(inst.gitPollTimer); inst.gitPollTimer = null; }
|
|
4174
2156
|
drainDisposables(s);
|
|
4175
2157
|
// Disable the admission sampler's private event-loop histogram. A bridge
|
|
4176
2158
|
// re-init (/reload, session replacement) constructs a fresh sampler; without
|
|
@@ -4188,7 +2170,8 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
4188
2170
|
// Release our EventBus subscriptions. Nothing to "restore": the bridge no
|
|
4189
2171
|
// longer replaces any host function. See change: fix-automation-run-lifecycle.
|
|
4190
2172
|
disposeEventBusForwarding();
|
|
4191
|
-
|
|
2173
|
+
pluginForwardRegistry.dispose();
|
|
2174
|
+
inst.connection.disconnect();
|
|
4192
2175
|
};
|
|
4193
2176
|
|
|
4194
2177
|
// Reload is handled by session_start which fires on /reload too
|