@blackbelt-technology/pi-agent-dashboard 0.8.0 → 0.9.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 +11 -45
- package/README.md +39 -26
- package/docs/architecture.md +1968 -174
- package/package.json +33 -29
- package/packages/extension/package.json +19 -16
- package/packages/extension/src/ask-user-tool.ts +4 -0
- package/packages/extension/src/bridge-activation.ts +26 -0
- package/packages/extension/src/bridge-context.ts +21 -19
- package/packages/extension/src/bridge-default-model-gate.ts +38 -0
- package/packages/extension/src/bridge-polling.ts +148 -0
- package/packages/extension/src/bridge.ts +954 -248
- package/packages/extension/src/canvas-tool.ts +5 -0
- package/packages/extension/src/command-handler.ts +77 -31
- package/packages/extension/src/connection.ts +481 -16
- package/packages/extension/src/custom-entry-forward.ts +92 -0
- package/packages/extension/src/endpoint-resolution.ts +32 -0
- package/packages/extension/src/event-forwarder.ts +42 -0
- package/packages/extension/src/extension-identity.ts +59 -0
- package/packages/extension/src/git-dir-watcher.ts +79 -0
- package/packages/extension/src/git-poll.ts +45 -12
- package/packages/extension/src/git-probe-scheduler.ts +119 -0
- package/packages/extension/src/git-tracker.ts +284 -0
- package/packages/extension/src/instance-verification.ts +31 -0
- package/packages/extension/src/mcp-token-delivery.ts +147 -0
- package/packages/extension/src/message-update-coalescer.ts +340 -0
- package/packages/extension/src/model-tracker.ts +118 -35
- package/packages/extension/src/notify-proxy.ts +3 -0
- package/packages/extension/src/path-gate/decide.ts +149 -0
- package/packages/extension/src/path-gate/grant-cache.ts +71 -0
- package/packages/extension/src/path-gate/grant-link.ts +108 -0
- package/packages/extension/src/path-gate/handler.ts +307 -0
- package/packages/extension/src/path-gate/index.ts +155 -0
- package/packages/extension/src/path-gate/resolve.ts +126 -0
- package/packages/extension/src/path-gate/roots.ts +137 -0
- package/packages/extension/src/path-gate/suppression.ts +27 -0
- package/packages/extension/src/pending-prompt-emitter.ts +59 -0
- package/packages/extension/src/pi-env.d.ts +2 -10
- package/packages/extension/src/plugin-request-client.ts +114 -0
- package/packages/extension/src/poll-cost.ts +40 -0
- package/packages/extension/src/pr-status.ts +338 -0
- package/packages/extension/src/process-metrics.ts +77 -1
- package/packages/extension/src/process-scan-scheduler.ts +137 -0
- package/packages/extension/src/process-scanner.ts +226 -247
- package/packages/extension/src/project-init/dox-kb-config.ts +3 -0
- package/packages/extension/src/project-init/scaffold.ts +1 -4
- package/packages/extension/src/project-init/seed-doctrine.ts +23 -60
- package/packages/extension/src/prompt-bus.ts +13 -0
- package/packages/extension/src/provider-register.ts +6 -0
- package/packages/extension/src/retry-tracker.ts +0 -7
- package/packages/extension/src/role-manager.ts +22 -95
- package/packages/extension/src/role-model-tools.ts +6 -0
- package/packages/extension/src/server-auto-start.ts +192 -23
- package/packages/extension/src/server-launcher.ts +70 -34
- package/packages/extension/src/session-move.ts +4 -4
- package/packages/extension/src/session-sync.ts +51 -15
- package/packages/extension/src/slash-dispatch.ts +66 -81
- package/packages/extension/src/subagent-fanout-admission.ts +234 -0
- package/packages/extension/src/subagent-saturation.ts +196 -0
- package/packages/extension/src/terminal-reload.ts +298 -0
- package/packages/extension/src/tui-prompt-adapter.ts +13 -1
- package/packages/extension/src/usage-drain.ts +167 -0
- package/packages/extension/src/vcs-info.ts +261 -63
- package/packages/server/bin/pi-dashboard.mjs +147 -26
- package/packages/server/package.json +47 -12
- package/packages/server/src/access/access-denials.ts +91 -0
- package/packages/server/src/access/access-grants.ts +398 -0
- package/packages/server/src/access/access-health.ts +77 -0
- package/packages/server/src/access/access-plane.ts +192 -0
- package/packages/server/src/access/agent-confirm-registry.ts +102 -0
- package/packages/server/src/access/agent-grant.ts +73 -0
- package/packages/server/src/access/ancestor-ladder.ts +151 -0
- package/packages/server/src/access/canonical-subject.ts +2 -0
- package/packages/server/src/access/capability-issuance.ts +105 -0
- package/packages/server/src/access/containment-gate.ts +310 -0
- package/packages/server/src/access/cors-denial.ts +45 -0
- package/packages/server/src/access/denial-hold.ts +73 -0
- package/packages/server/src/access/forbidden-subjects.ts +2 -0
- package/packages/server/src/access/grant-coordinator.ts +404 -0
- package/packages/server/src/access/grant-store-id.ts +62 -0
- package/packages/server/src/access/hold-request.ts +49 -0
- package/packages/server/src/access/named-grant.ts +73 -0
- package/packages/server/src/access/pending-grant-registry.ts +504 -0
- package/packages/server/src/access/planes.ts +194 -0
- package/packages/server/src/access/prompt-channel.ts +131 -0
- package/packages/server/src/access/refusal-ledger.ts +153 -0
- package/packages/server/src/access/source-channel.ts +33 -0
- package/packages/server/src/access/verified-read.ts +170 -0
- package/packages/server/src/access/yolo-env.ts +60 -0
- package/packages/server/src/access/yolo-session.ts +257 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +33 -10
- package/packages/server/src/auth/auth-plugin.ts +212 -33
- package/packages/server/src/auth/auth.ts +2 -2
- package/packages/server/src/auth/bearer-auth.ts +74 -5
- package/packages/server/src/auth/begin-flow.ts +165 -0
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +9 -5
- package/packages/server/src/auth/bypass-urls.ts +22 -0
- package/packages/server/src/auth/cors-origin.ts +215 -16
- package/packages/server/src/auth/dashboard-credential-store.ts +301 -0
- package/packages/server/src/auth/host-admission.ts +106 -0
- package/packages/server/src/auth/host-gate.ts +378 -0
- package/packages/server/src/auth/local-proof.ts +105 -0
- package/packages/server/src/auth/localhost-guard.ts +670 -33
- package/packages/server/src/auth/locked-json-file.ts +316 -0
- package/packages/server/src/auth/loopback.ts +25 -2
- package/packages/server/src/auth/mutation-origin-gate.ts +55 -0
- package/packages/server/src/auth/node-guard.ts +35 -6
- package/packages/server/src/auth/pi-oauth-types.ts +107 -0
- package/packages/server/src/auth/plugin-credential-store.ts +206 -0
- package/packages/server/src/auth/provider-auth-adapter.ts +557 -0
- package/packages/server/src/auth/provider-auth-handlers.ts +15 -287
- package/packages/server/src/auth/provider-auth-registry.ts +234 -0
- package/packages/server/src/auth/provider-auth-storage.ts +404 -84
- package/packages/server/src/auth/radius-mcp.ts +189 -0
- package/packages/server/src/auth/radius-override.ts +103 -0
- package/packages/server/src/auth/route-tier-gate.ts +126 -0
- package/packages/server/src/auth/ws-ticket.ts +82 -11
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +81 -0
- package/packages/server/src/browser-handlers/directory-handler.ts +179 -5
- package/packages/server/src/browser-handlers/handler-context.ts +39 -0
- package/packages/server/src/browser-handlers/session-action-handler.ts +148 -45
- package/packages/server/src/browser-handlers/session-lifecycle.ts +67 -0
- package/packages/server/src/browser-handlers/session-meta-handler.ts +149 -44
- package/packages/server/src/browser-handlers/subscription-handler.ts +216 -24
- package/packages/server/src/browser-handlers/terminal-handler.ts +46 -2
- package/packages/server/src/changelog/changelog-parser.ts +1 -1
- package/packages/server/src/changelog/changelog-remote.ts +2 -2
- package/packages/server/src/cli.ts +484 -31
- package/packages/server/src/config-api.ts +112 -3
- package/packages/server/src/config-snapshot.ts +73 -2
- package/packages/server/src/directory-service.ts +728 -65
- package/packages/server/src/event-wiring.ts +693 -217
- package/packages/server/src/git-worktree/git-operations.ts +509 -231
- package/packages/server/src/git-worktree/git-worktree-compose.ts +15 -4
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts +6 -0
- package/packages/server/src/git-worktree/git-worktree.ts +19 -5
- package/packages/server/src/git-worktree/worktree-init-trust.ts +37 -0
- package/packages/server/src/git-worktree/worktree-init.ts +17 -5
- package/packages/server/src/identity/activation.ts +69 -0
- package/packages/server/src/identity/auth-context.ts +78 -0
- package/packages/server/src/identity/bootstrap-grants.ts +94 -0
- package/packages/server/src/identity/break-glass.ts +76 -0
- package/packages/server/src/identity/browser-login-auth-status.ts +46 -0
- package/packages/server/src/identity/browser-login-config-registry.ts +151 -0
- package/packages/server/src/identity/dispatch.ts +115 -0
- package/packages/server/src/identity/domain-fanout.ts +78 -0
- package/packages/server/src/identity/host-access.ts +47 -0
- package/packages/server/src/identity/host-resources.ts +63 -0
- package/packages/server/src/identity/http-road-classification.ts +181 -0
- package/packages/server/src/identity/identity-floor.ts +44 -0
- package/packages/server/src/identity/identity-me.ts +56 -0
- package/packages/server/src/identity/identity-registration-tracker.ts +66 -0
- package/packages/server/src/identity/identity-road-gate.ts +73 -0
- package/packages/server/src/identity/plugin-identity.ts +98 -0
- package/packages/server/src/identity/policy-registry.ts +181 -0
- package/packages/server/src/identity/principal-guard.ts +92 -0
- package/packages/server/src/identity/resolver-hook.ts +123 -0
- package/packages/server/src/identity/resolver-registry.ts +106 -0
- package/packages/server/src/identity/route-owner-registry.ts +49 -0
- package/packages/server/src/identity/session-access.ts +138 -0
- package/packages/server/src/identity/socket-lifetime.ts +132 -0
- package/packages/server/src/identity/upgrade-gate.ts +35 -0
- package/packages/server/src/identity/ws-message-scope.ts +149 -0
- package/packages/server/src/identity/ws-road-classification.ts +116 -0
- package/packages/server/src/lib/client-dist.ts +162 -0
- package/packages/server/src/lib/diagram-render.ts +214 -0
- package/packages/server/src/lib/eml.ts +34 -14
- package/packages/server/src/lib/office-preview.ts +8 -7
- package/packages/server/src/lib/path-containment.ts +101 -58
- package/packages/server/src/lib/purify.ts +30 -0
- package/packages/server/src/lib/resolve-file-mention.ts +5 -2
- package/packages/server/src/lib/writable-md-target.ts +6 -3
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +52 -7
- package/packages/server/src/lifecycle/ephemeral-parent-watch.ts +118 -0
- package/packages/server/src/lifecycle/instance-id.ts +9 -0
- package/packages/server/src/lifecycle/recovery-server.ts +3 -3
- package/packages/server/src/lifecycle/stop-ownership.ts +115 -0
- package/packages/server/src/model-proxy/auth-gate.ts +7 -0
- package/packages/server/src/model-proxy/internal-auth-storage.ts +121 -164
- package/packages/server/src/model-proxy/internal-registry.ts +166 -29
- package/packages/server/src/model-proxy/oauth-compat.ts +10 -4
- package/packages/server/src/model-proxy/registry-singleton.ts +70 -37
- package/packages/server/src/model-proxy/server-model-runtime.ts +140 -0
- package/packages/server/src/model-proxy/streamer.ts +59 -26
- package/packages/server/src/openspec/global-signature.ts +20 -0
- package/packages/server/src/openspec/readiness.ts +85 -0
- package/packages/server/src/package/package-manager-wrapper.ts +68 -4
- package/packages/server/src/package/provider-catalogue-cache.ts +21 -0
- package/packages/server/src/package/provider-probe.ts +33 -0
- package/packages/server/src/pairing/browser-gateway.ts +1574 -68
- package/packages/server/src/pairing/paired-devices.ts +55 -6
- package/packages/server/src/pairing/pairing.ts +253 -13
- package/packages/server/src/pairing/subagent-resync-routing.ts +13 -0
- package/packages/server/src/pending/pending-archive-intent-registry.ts +71 -0
- package/packages/server/src/pending/pending-plugin-ref-registry.ts +249 -0
- package/packages/server/src/pending/pending-principal-owner-registry.ts +98 -0
- package/packages/server/src/persistence/json-store.ts +8 -2
- package/packages/server/src/persistence/memory-event-store.ts +634 -40
- package/packages/server/src/persistence/meta-persistence.ts +25 -2
- package/packages/server/src/persistence/migrate-custom-entry-fallback.ts +60 -0
- package/packages/server/src/persistence/preferences-store.ts +446 -8
- package/packages/server/src/pi/bridge-upgrade-auth.ts +19 -1
- package/packages/server/src/pi/gateway-listeners.ts +75 -0
- package/packages/server/src/pi/gateway-socket-bind.ts +178 -48
- package/packages/server/src/pi/host-project-trust.ts +62 -0
- package/packages/server/src/pi/pi-core-checker.ts +13 -69
- package/packages/server/src/pi/pi-core-updater.ts +6 -2
- package/packages/server/src/pi/pi-gateway.ts +259 -73
- package/packages/server/src/pi/pi-resources-watcher.ts +183 -0
- package/packages/server/src/pi/pi-runtime.ts +1 -1
- package/packages/server/src/pi/pi-version-skew.ts +56 -9
- package/packages/server/src/plugin-event-seam.ts +39 -0
- package/packages/server/src/plugin-request-lane.ts +87 -0
- package/packages/server/src/push/build-push-payload.ts +64 -0
- package/packages/server/src/push/push-dispatcher.ts +192 -0
- package/packages/server/src/push/push-service.ts +88 -0
- package/packages/server/src/push/push-token-display.ts +29 -0
- package/packages/server/src/push/push-token-registry.ts +184 -0
- package/packages/server/src/push/push-transports/fcm.ts +128 -0
- package/packages/server/src/push/push-transports/types.ts +67 -0
- package/packages/server/src/push/push-transports/web-push.ts +71 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +164 -0
- package/packages/server/src/push/push-transports/webhook.ts +79 -0
- package/packages/server/src/push/push-vapid.ts +35 -0
- package/packages/server/src/routes/access-prompt-routes.ts +264 -0
- package/packages/server/src/routes/access-routes.ts +429 -0
- package/packages/server/src/routes/custom-event-groups-routes.ts +34 -0
- package/packages/server/src/routes/doctor-routes.ts +63 -9
- package/packages/server/src/routes/file-routes.ts +374 -62
- package/packages/server/src/routes/git-routes.ts +88 -22
- package/packages/server/src/routes/grep-routes.ts +13 -3
- package/packages/server/src/routes/host-gate-routes.ts +25 -0
- package/packages/server/src/routes/local-proof-routes.ts +49 -0
- package/packages/server/src/routes/model-proxy-diagnostics-routes.ts +5 -1
- package/packages/server/src/routes/model-proxy-routes.ts +352 -251
- package/packages/server/src/routes/node-runtime-routes.ts +165 -0
- package/packages/server/src/routes/openspec-group-routes.ts +16 -6
- package/packages/server/src/routes/openspec-routes.ts +214 -1
- package/packages/server/src/routes/pairing-routes.ts +314 -13
- package/packages/server/src/routes/pi-core-routes.ts +4 -3
- package/packages/server/src/routes/plugin-activation-routes.ts +129 -42
- package/packages/server/src/routes/plugin-config-routes.ts +22 -14
- package/packages/server/src/routes/provider-auth-routes.ts +241 -182
- package/packages/server/src/routes/provider-routes.ts +367 -25
- package/packages/server/src/routes/push-routes.ts +176 -0
- package/packages/server/src/routes/recommended-routes.ts +28 -15
- package/packages/server/src/routes/runtime-routes.ts +283 -0
- package/packages/server/src/routes/session-routes.ts +326 -15
- package/packages/server/src/routes/system-routes.ts +462 -81
- package/packages/server/src/rpc-keeper/dispatch-reload.ts +130 -3
- package/packages/server/src/rpc-keeper/keeper-log-rotation.cjs +189 -0
- package/packages/server/src/rpc-keeper/keeper-manager.ts +234 -76
- package/packages/server/src/rpc-keeper/keeper.cjs +75 -0
- package/packages/server/src/runtime-overlay/extension-reload.ts +154 -0
- package/packages/server/src/runtime-overlay/runtime-doctor.ts +58 -0
- package/packages/server/src/runtime-overlay/runtime-health.ts +129 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +140 -0
- package/packages/server/src/runtime-overlay/runtime-stager.ts +283 -0
- package/packages/server/src/runtime-overlay/runtime-update-checker.ts +158 -0
- package/packages/server/src/runtime-publication.ts +134 -0
- package/packages/server/src/runtime-resolution.ts +42 -0
- package/packages/server/src/server-heap-telemetry.ts +89 -0
- package/packages/server/src/server.ts +1952 -483
- package/packages/server/src/session/active-sessions-in-cwd.ts +22 -0
- package/packages/server/src/session/archive-sweeper.ts +112 -0
- package/packages/server/src/session/custom-event-group-annotation.ts +58 -0
- package/packages/server/src/session/custom-event-group-matcher-worker.ts +40 -0
- package/packages/server/src/session/custom-event-group-matcher.ts +242 -0
- package/packages/server/src/session/custom-event-group-resolver.ts +85 -0
- package/packages/server/src/session/death-reason.ts +34 -0
- package/packages/server/src/session/event-status-extraction.ts +73 -0
- package/packages/server/src/session/host-pressure-tracker.ts +121 -0
- package/packages/server/src/session/memory-session-manager.ts +286 -5
- package/packages/server/src/session/open-tool-calls.ts +146 -0
- package/packages/server/src/session/plugin-refs.ts +133 -0
- package/packages/server/src/session/remote-transcript-store.ts +159 -9
- package/packages/server/src/session/retained-transcript.ts +251 -0
- package/packages/server/src/session/session-api.ts +158 -20
- package/packages/server/src/session/session-archive.ts +418 -0
- package/packages/server/src/session/session-bootstrap.ts +14 -3
- package/packages/server/src/session/session-diff-cache.ts +55 -11
- package/packages/server/src/session/session-diff-source.ts +283 -0
- package/packages/server/src/session/session-diff.ts +106 -15
- package/packages/server/src/session/session-discovery.ts +2 -13
- package/packages/server/src/session/session-file-reader.ts +83 -3
- package/packages/server/src/session/session-load-worker.ts +49 -4
- package/packages/server/src/session/session-scanner.ts +232 -16
- package/packages/server/src/session/session-stats-reader.ts +10 -13
- package/packages/server/src/session/session-to-meta.ts +43 -0
- package/packages/server/src/spawn-process/cwd-policy.ts +360 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +67 -47
- package/packages/server/src/spawn-process/heap-args.ts +163 -0
- package/packages/server/src/spawn-process/process-manager.ts +432 -39
- package/packages/server/src/spawn-process/restart-helper.ts +33 -2
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +1 -1
- package/packages/server/src/system-open-capability.ts +5 -24
- package/packages/server/src/terminal/terminal-gateway.ts +38 -3
- package/packages/server/src/terminal/terminal-manager.ts +20 -4
- package/packages/server/src/tunnel/tunnel-block-events.ts +55 -5
- package/packages/server/src/tunnel/tunnel-core.ts +36 -3
- package/packages/server/src/tunnel/tunnel-endpoints.ts +14 -1
- package/packages/server/src/tunnel/tunnel-readiness.ts +11 -0
- package/packages/server/src/tunnel/tunnel.ts +127 -1
- package/packages/server/src/tunnel-providers/tailscale.ts +49 -5
- package/packages/server/src/tunnel-providers/zrok.ts +6 -2
- package/packages/shared/package.json +11 -2
- package/packages/shared/src/boot-state.ts +11 -2
- package/packages/shared/src/bridge-register.ts +24 -6
- package/packages/shared/src/browser-protocol.ts +618 -21
- package/packages/shared/src/canonical-subject.ts +163 -0
- package/packages/shared/src/card-sections.ts +102 -0
- package/packages/shared/src/config.ts +922 -4
- package/packages/shared/src/custom-event-groups-store.ts +215 -0
- package/packages/shared/src/custom-event-groups.ts +81 -0
- package/packages/shared/src/cwd-guard.ts +97 -0
- package/packages/shared/src/dashboard-paths.ts +14 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +44 -1
- package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +21 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +45 -0
- package/packages/shared/src/display-prefs.ts +124 -3
- package/packages/shared/src/doctor-core.ts +371 -22
- package/packages/shared/src/electron-restart.ts +15 -0
- package/packages/shared/src/file-kind.ts +25 -1
- package/packages/shared/src/forbidden-subjects.ts +186 -0
- package/packages/shared/src/heap-flags.ts +244 -0
- package/packages/shared/src/heap-limits.ts +159 -0
- package/packages/shared/src/host-admission.ts +124 -0
- package/packages/shared/src/host-pressure.ts +24 -0
- package/packages/shared/src/identity.ts +179 -0
- package/packages/shared/src/launch-source-types.ts +8 -2
- package/packages/shared/src/legacy-managed-dir.ts +99 -14
- package/packages/shared/src/mdns-discovery.ts +91 -2
- package/packages/shared/src/memory-limits.ts +51 -0
- package/packages/shared/src/node-installs/candidates.ts +296 -0
- package/packages/shared/src/node-installs/child-path.ts +79 -0
- package/packages/shared/src/node-installs/coherence.ts +160 -0
- package/packages/shared/src/node-installs/index.ts +42 -0
- package/packages/shared/src/node-installs/select.ts +158 -0
- package/packages/shared/src/node-installs/vm-roots.ts +92 -0
- package/packages/shared/src/node-version.ts +68 -8
- package/packages/shared/src/openspec-poller.ts +35 -6
- package/packages/shared/src/pi-installs/candidates.ts +13 -7
- package/packages/shared/src/pi-installs/index.ts +1 -0
- package/packages/shared/src/pi-package-resolver.ts +29 -7
- package/packages/shared/src/platform/binary-lookup.ts +13 -9
- package/packages/shared/src/platform/check-rollup.ts +74 -0
- package/packages/shared/src/platform/env-path-key.ts +55 -0
- package/packages/shared/src/platform/exec.ts +32 -5
- package/packages/shared/src/platform/git.ts +671 -23
- package/packages/shared/src/platform/index.ts +13 -10
- package/packages/shared/src/platform/native-module-abi.ts +540 -0
- package/packages/shared/src/platform/native-ts-hooks.mjs +90 -0
- package/packages/shared/src/platform/native-ts-register.mjs +18 -0
- package/packages/shared/src/platform/node-spawn.ts +19 -0
- package/packages/shared/src/platform/openspec.ts +70 -4
- package/packages/shared/src/platform/paths.ts +54 -0
- package/packages/shared/src/platform/process.ts +74 -0
- package/packages/shared/src/platform/runner.ts +84 -12
- package/packages/shared/src/platform/spawn-mechanism.ts +59 -6
- package/packages/shared/src/platform/spawn-runtime.ts +974 -0
- package/packages/shared/src/platform/system-open.ts +46 -0
- package/packages/shared/src/platform/ts-loader-select.d.mts +10 -0
- package/packages/shared/src/platform/ts-loader-select.mjs +84 -0
- package/packages/shared/src/protocol.ts +320 -21
- package/packages/shared/src/recommended-extensions.ts +22 -31
- package/packages/shared/src/renderer-by-ext.ts +6 -1
- package/packages/shared/src/rest-api.ts +219 -19
- package/packages/shared/src/role-schema.ts +201 -0
- package/packages/shared/src/route-tiers.ts +377 -0
- package/packages/shared/src/runtime-overlay/compat.ts +91 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +22 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +63 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +10 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +71 -0
- package/packages/shared/src/runtime-overlay/state.ts +268 -0
- package/packages/shared/src/server-identity.ts +39 -10
- package/packages/shared/src/server-launcher.ts +29 -6
- package/packages/shared/src/session-group-by.ts +50 -0
- package/packages/shared/src/session-meta.ts +97 -8
- package/packages/shared/src/state-replay.ts +126 -14
- package/packages/shared/src/terminal-types.ts +7 -0
- package/packages/shared/src/tiers.ts +47 -0
- package/packages/shared/src/tool-registry/default-registry.ts +76 -0
- package/packages/shared/src/tool-registry/definitions.ts +241 -18
- package/packages/shared/src/tool-registry/ensure-cli.ts +138 -0
- package/packages/shared/src/tool-registry/ensure.ts +200 -0
- package/packages/shared/src/tool-registry/index.ts +16 -40
- package/packages/shared/src/tool-registry/pi-tools.ts +258 -0
- package/packages/shared/src/tool-registry/registry.ts +21 -7
- package/packages/shared/src/tool-registry/strategies.ts +230 -3
- package/packages/shared/src/tool-registry/types.ts +57 -5
- package/packages/shared/src/transcript-request-guard.ts +83 -0
- package/packages/shared/src/tunnel-provider.ts +6 -0
- package/packages/shared/src/types.ts +247 -14
- package/packages/shared/src/usage-totals.ts +127 -0
- package/tsconfig.base.json +27 -0
- package/packages/extension/src/AGENTS.md +0 -79
- package/packages/extension/src/__tests__/abort-latch.test.ts +0 -97
- package/packages/extension/src/__tests__/agent-settled.test.ts +0 -112
- package/packages/extension/src/__tests__/artifact-roots.test.ts +0 -83
- package/packages/extension/src/__tests__/ask-user-attachments.test.ts +0 -106
- package/packages/extension/src/__tests__/ask-user-schema-discriminator.test.ts +0 -141
- package/packages/extension/src/__tests__/ask-user-tool.test.ts +0 -571
- package/packages/extension/src/__tests__/auto-session-namer.test.ts +0 -1126
- package/packages/extension/src/__tests__/autostart-guard.test.ts +0 -103
- package/packages/extension/src/__tests__/autostart-lock.test.ts +0 -167
- package/packages/extension/src/__tests__/bridge-context-window.test.ts +0 -126
- package/packages/extension/src/__tests__/bridge-default-model-apply.test.ts +0 -242
- package/packages/extension/src/__tests__/bridge-default-model-gate.test.ts +0 -50
- package/packages/extension/src/__tests__/bridge-default-thinking-level-apply.test.ts +0 -131
- package/packages/extension/src/__tests__/bridge-entry-id-pi-070.test.ts +0 -174
- package/packages/extension/src/__tests__/bridge-followup-chat-order.test.ts +0 -215
- package/packages/extension/src/__tests__/bridge-followup-drain-entries.test.ts +0 -121
- package/packages/extension/src/__tests__/bridge-followup-multi-entry.test.ts +0 -202
- package/packages/extension/src/__tests__/bridge-followup-mutation.test.ts +0 -217
- package/packages/extension/src/__tests__/bridge-followup-queue-drain.test.ts +0 -266
- package/packages/extension/src/__tests__/bridge-hasui-flip.test.ts +0 -109
- package/packages/extension/src/__tests__/bridge-no-queue-mutation.test.ts +0 -112
- package/packages/extension/src/__tests__/bridge-plugin-emit-event.test.ts +0 -44
- package/packages/extension/src/__tests__/bridge-queue-update-forward.test.ts +0 -218
- package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +0 -333
- package/packages/extension/src/__tests__/bridge-shadow-queue-gate.test.ts +0 -299
- package/packages/extension/src/__tests__/bridge-shutdown-reset.test.ts +0 -159
- package/packages/extension/src/__tests__/bridge-slash-command-routing.test.ts +0 -458
- package/packages/extension/src/__tests__/bridge-stop-after-turn.test.ts +0 -72
- package/packages/extension/src/__tests__/bridge-system-followup.test.ts +0 -163
- package/packages/extension/src/__tests__/bridge-thinking-level-select.test.ts +0 -68
- package/packages/extension/src/__tests__/bridge-ticket-client.test.ts +0 -92
- package/packages/extension/src/__tests__/browser-skill-registered.test.ts +0 -84
- package/packages/extension/src/__tests__/build-provider-catalogue.test.ts +0 -210
- package/packages/extension/src/__tests__/command-handler.test.ts +0 -1620
- package/packages/extension/src/__tests__/command-path-mapping.test.ts +0 -77
- package/packages/extension/src/__tests__/commit-draft-agent-session.test.ts +0 -129
- package/packages/extension/src/__tests__/commit-draft.test.ts +0 -100
- package/packages/extension/src/__tests__/connect-target.test.ts +0 -154
- package/packages/extension/src/__tests__/connection-dropped-frames.test.ts +0 -78
- package/packages/extension/src/__tests__/connection-inbound-drop-report.test.ts +0 -256
- package/packages/extension/src/__tests__/connection-inbound-pump.test.ts +0 -661
- package/packages/extension/src/__tests__/connection-register-rejected.test.ts +0 -128
- package/packages/extension/src/__tests__/connection-suppress-auto-start.test.ts +0 -106
- package/packages/extension/src/__tests__/connection.test.ts +0 -543
- package/packages/extension/src/__tests__/credentials-updated.test.ts +0 -26
- package/packages/extension/src/__tests__/custom-provider-apikey-roundtrip.test.ts +0 -173
- package/packages/extension/src/__tests__/cwd-missing-probe.test.ts +0 -82
- package/packages/extension/src/__tests__/dashboard-commands-shipped.test.ts +0 -53
- package/packages/extension/src/__tests__/dashboard-context-injector.test.ts +0 -190
- package/packages/extension/src/__tests__/dashboard-default-adapter.test.ts +0 -77
- package/packages/extension/src/__tests__/dev-build.test.ts +0 -79
- package/packages/extension/src/__tests__/doctor/checks.test.ts +0 -85
- package/packages/extension/src/__tests__/doctor/modules.test.ts +0 -65
- package/packages/extension/src/__tests__/doctor/provenance-hash.test.ts +0 -94
- package/packages/extension/src/__tests__/doctor/router.test.ts +0 -147
- package/packages/extension/src/__tests__/empty-actionable-guard-config.test.ts +0 -32
- package/packages/extension/src/__tests__/empty-actionable-guard.test.ts +0 -73
- package/packages/extension/src/__tests__/endpoint-resolution.test.ts +0 -179
- package/packages/extension/src/__tests__/enrich-model-metadata.test.ts +0 -348
- package/packages/extension/src/__tests__/event-forwarder.test.ts +0 -119
- package/packages/extension/src/__tests__/eventbus-foreign-emit-forwarding.test.ts +0 -177
- package/packages/extension/src/__tests__/extension-slash-command-detection.test.ts +0 -143
- package/packages/extension/src/__tests__/filter-enabled-models.test.ts +0 -151
- package/packages/extension/src/__tests__/fixtures/turn-actionability-fixtures.ts +0 -69
- package/packages/extension/src/__tests__/followup-buffer.test.ts +0 -309
- package/packages/extension/src/__tests__/followup-content.test.ts +0 -125
- package/packages/extension/src/__tests__/fork-entryid-timing.test.ts +0 -88
- package/packages/extension/src/__tests__/git-info-status.test.ts +0 -73
- package/packages/extension/src/__tests__/git-link-builder.test.ts +0 -102
- package/packages/extension/src/__tests__/git-poll.test.ts +0 -69
- package/packages/extension/src/__tests__/helpers/settle-prompts.ts +0 -42
- package/packages/extension/src/__tests__/instance-verification.test.ts +0 -171
- package/packages/extension/src/__tests__/local-token-header.test.ts +0 -67
- package/packages/extension/src/__tests__/markdown-image-inliner.test.ts +0 -392
- package/packages/extension/src/__tests__/model-refresh-timeout.test.ts +0 -61
- package/packages/extension/src/__tests__/model-resolve.test.ts +0 -379
- package/packages/extension/src/__tests__/multiselect-dashboard-routing.test.ts +0 -203
- package/packages/extension/src/__tests__/multiselect-list.test.ts +0 -137
- package/packages/extension/src/__tests__/multiselect-polyfill.test.ts +0 -92
- package/packages/extension/src/__tests__/no-session-replacement-calls.test.ts +0 -99
- package/packages/extension/src/__tests__/no-tui-multiselect-arm-regression.test.ts +0 -81
- package/packages/extension/src/__tests__/openspec-activity-detector.test.ts +0 -401
- package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +0 -145
- package/packages/extension/src/__tests__/openspec-poller.test.ts +0 -124
- package/packages/extension/src/__tests__/pi-retry-settings.test.ts +0 -66
- package/packages/extension/src/__tests__/pi-version-tracker.test.ts +0 -178
- package/packages/extension/src/__tests__/process-metrics.test.ts +0 -47
- package/packages/extension/src/__tests__/process-scanner-kill.test.ts +0 -61
- package/packages/extension/src/__tests__/process-scanner.test.ts +0 -292
- package/packages/extension/src/__tests__/project-init-detect-stack.test.ts +0 -61
- package/packages/extension/src/__tests__/project-init-dox-kb-config.test.ts +0 -53
- package/packages/extension/src/__tests__/project-init-profiles.test.ts +0 -84
- package/packages/extension/src/__tests__/project-init-scaffold.test.ts +0 -139
- package/packages/extension/src/__tests__/project-init-seed-doctrine.test.ts +0 -100
- package/packages/extension/src/__tests__/project-trust.test.ts +0 -92
- package/packages/extension/src/__tests__/prompt-bus-inflight-settle.test.ts +0 -133
- package/packages/extension/src/__tests__/prompt-bus-wiring.test.ts +0 -888
- package/packages/extension/src/__tests__/prompt-bus.test.ts +0 -528
- package/packages/extension/src/__tests__/prompt-expander.test.ts +0 -398
- package/packages/extension/src/__tests__/provider-register-native-models.test.ts +0 -182
- package/packages/extension/src/__tests__/provider-register-reload.test.ts +0 -713
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +0 -141
- package/packages/extension/src/__tests__/remote-registration-gate.test.ts +0 -113
- package/packages/extension/src/__tests__/removed-typebox-api-audit.test.ts +0 -51
- package/packages/extension/src/__tests__/request-models-refresh-errors.test.ts +0 -132
- package/packages/extension/src/__tests__/retry-tracker.test.ts +0 -494
- package/packages/extension/src/__tests__/role-manager.test.ts +0 -642
- package/packages/extension/src/__tests__/role-model-tools-registry-readiness.test.ts +0 -114
- package/packages/extension/src/__tests__/role-model-tools-scoped-models.test.ts +0 -83
- package/packages/extension/src/__tests__/role-model-tools.test.ts +0 -229
- package/packages/extension/src/__tests__/search-files-completeness.test.ts +0 -111
- package/packages/extension/src/__tests__/search-files-ranking.test.ts +0 -168
- package/packages/extension/src/__tests__/server-auto-start-guarded.test.ts +0 -266
- package/packages/extension/src/__tests__/server-auto-start.test.ts +0 -391
- package/packages/extension/src/__tests__/server-launcher-launch.test.ts +0 -96
- package/packages/extension/src/__tests__/server-launcher.test.ts +0 -101
- package/packages/extension/src/__tests__/server-pin-store.test.ts +0 -123
- package/packages/extension/src/__tests__/server-probe.test.ts +0 -25
- package/packages/extension/src/__tests__/session-move.test.ts +0 -521
- package/packages/extension/src/__tests__/session-register-carries-pid.test.ts +0 -98
- package/packages/extension/src/__tests__/session-switch.test.ts +0 -139
- package/packages/extension/src/__tests__/session-sync.test.ts +0 -243
- package/packages/extension/src/__tests__/single-derivation-guard.test.ts +0 -39
- package/packages/extension/src/__tests__/source-detector.test.ts +0 -88
- package/packages/extension/src/__tests__/stats-extractor.test.ts +0 -92
- package/packages/extension/src/__tests__/subagent-forward-sites.test.ts +0 -199
- package/packages/extension/src/__tests__/subagent-frame-buffer.test.ts +0 -239
- package/packages/extension/src/__tests__/subagent-frame-strip.test.ts +0 -179
- package/packages/extension/src/__tests__/subagent-tick-growth.test.ts +0 -94
- package/packages/extension/src/__tests__/subagent-tick-throttle.test.ts +0 -402
- package/packages/extension/src/__tests__/tool-result-image-inliner.test.ts +0 -206
- package/packages/extension/src/__tests__/transcript-backfill.test.ts +0 -148
- package/packages/extension/src/__tests__/transcript-request-guard.test.ts +0 -102
- package/packages/extension/src/__tests__/transport-diagnostics.test.ts +0 -93
- package/packages/extension/src/__tests__/tui-prompt-adapter.test.ts +0 -220
- package/packages/extension/src/__tests__/turn-actionability.test.ts +0 -105
- package/packages/extension/src/__tests__/typebox-nullable-array-validation.test.ts +0 -40
- package/packages/extension/src/__tests__/ui-decorators.test.ts +0 -309
- package/packages/extension/src/__tests__/ui-modules.test.ts +0 -293
- package/packages/extension/src/__tests__/ui-stale-guard.test.ts +0 -181
- package/packages/extension/src/__tests__/vcs-info.test.ts +0 -265
- package/packages/extension/src/__tests__/visibility-intent.test.ts +0 -43
- package/packages/extension/src/__tests__/watchdog.test.ts +0 -161
- package/packages/extension/src/abort-latch.ts.AGENTS.md +0 -5
- package/packages/extension/src/agent-settled.ts +0 -90
- package/packages/extension/src/agent-settled.ts.AGENTS.md +0 -3
- package/packages/extension/src/artifact-roots.ts.AGENTS.md +0 -3
- package/packages/extension/src/ask-user-attachments.ts.AGENTS.md +0 -3
- package/packages/extension/src/ask-user-tool.ts.AGENTS.md +0 -3
- package/packages/extension/src/auto-session-namer.ts.AGENTS.md +0 -3
- package/packages/extension/src/bridge-context.ts.AGENTS.md +0 -3
- package/packages/extension/src/bridge-default-model-gate.ts.AGENTS.md +0 -3
- package/packages/extension/src/bridge.ts.AGENTS.md +0 -6
- package/packages/extension/src/command-handler.ts.AGENTS.md +0 -5
- package/packages/extension/src/commit-draft-agent.ts.AGENTS.md +0 -3
- package/packages/extension/src/commit-draft.ts.AGENTS.md +0 -3
- package/packages/extension/src/connection.ts.AGENTS.md +0 -6
- package/packages/extension/src/dashboard-context-injector.ts.AGENTS.md +0 -3
- package/packages/extension/src/dashboard-default-adapter.ts.AGENTS.md +0 -3
- package/packages/extension/src/dev-build.ts.AGENTS.md +0 -3
- package/packages/extension/src/empty-actionable-guard-config.ts.AGENTS.md +0 -3
- package/packages/extension/src/empty-actionable-guard.ts.AGENTS.md +0 -3
- package/packages/extension/src/endpoint-resolution.ts.AGENTS.md +0 -11
- package/packages/extension/src/event-forwarder.ts.AGENTS.md +0 -3
- package/packages/extension/src/flow-event-wiring.ts.AGENTS.md +0 -5
- package/packages/extension/src/git-link-builder.ts.AGENTS.md +0 -3
- package/packages/extension/src/git-poll.ts.AGENTS.md +0 -3
- package/packages/extension/src/hasui-flip.ts.AGENTS.md +0 -3
- package/packages/extension/src/markdown-image-inliner.ts.AGENTS.md +0 -3
- package/packages/extension/src/model-tracker.ts.AGENTS.md +0 -3
- package/packages/extension/src/multiselect-decode.ts.AGENTS.md +0 -3
- package/packages/extension/src/multiselect-list.ts.AGENTS.md +0 -3
- package/packages/extension/src/multiselect-polyfill.ts.AGENTS.md +0 -3
- package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +0 -7
- package/packages/extension/src/process-metrics.ts.AGENTS.md +0 -3
- package/packages/extension/src/process-scanner.ts.AGENTS.md +0 -3
- package/packages/extension/src/project-init/AGENTS.md +0 -12
- package/packages/extension/src/project-trust.ts.AGENTS.md +0 -3
- package/packages/extension/src/prompt-bus.ts.AGENTS.md +0 -3
- package/packages/extension/src/prompt-expander.ts.AGENTS.md +0 -3
- package/packages/extension/src/provider-register.ts.AGENTS.md +0 -3
- package/packages/extension/src/retry-tracker.ts.AGENTS.md +0 -9
- package/packages/extension/src/role-manager.ts.AGENTS.md +0 -3
- package/packages/extension/src/role-model-tools.ts.AGENTS.md +0 -3
- package/packages/extension/src/server-auto-start.ts.AGENTS.md +0 -5
- package/packages/extension/src/server-launcher.ts.AGENTS.md +0 -3
- package/packages/extension/src/session-sync.ts.AGENTS.md +0 -3
- package/packages/extension/src/slash-dispatch.ts.AGENTS.md +0 -3
- package/packages/extension/src/source-detector.ts.AGENTS.md +0 -3
- package/packages/extension/src/subagent-frame-buffer.ts.AGENTS.md +0 -3
- package/packages/extension/src/tool-result-image-inliner.ts.AGENTS.md +0 -3
- package/packages/extension/src/transcript-request-guard.ts +0 -76
- package/packages/extension/src/tui-prompt-adapter.ts.AGENTS.md +0 -3
- package/packages/extension/src/turn-actionability.ts.AGENTS.md +0 -3
- package/packages/extension/src/ui-modules.ts.AGENTS.md +0 -3
- package/packages/extension/src/vcs-info.ts.AGENTS.md +0 -3
- package/packages/extension/src/visibility-intent.ts.AGENTS.md +0 -3
- package/packages/server/src/AGENTS.md +0 -22
- package/packages/server/src/__tests__/active-sessions-in-cwd.test.ts +0 -97
- package/packages/server/src/__tests__/attach-proposal-replay.test.ts +0 -92
- package/packages/server/src/__tests__/auth-plugin.test.ts +0 -181
- package/packages/server/src/__tests__/auth-provider-delete.test.ts +0 -233
- package/packages/server/src/__tests__/auth-redirect-base.test.ts +0 -659
- package/packages/server/src/__tests__/auth.test.ts +0 -259
- package/packages/server/src/__tests__/auto-attach-locality.test.ts +0 -338
- package/packages/server/src/__tests__/auto-attach-slug-defense.test.ts +0 -101
- package/packages/server/src/__tests__/auto-attach.test.ts +0 -302
- package/packages/server/src/__tests__/auto-name-outcomes-route.test.ts +0 -60
- package/packages/server/src/__tests__/auto-resume.test.ts +0 -135
- package/packages/server/src/__tests__/auto-shutdown.test.ts +0 -134
- package/packages/server/src/__tests__/automation-session-close.test.ts +0 -73
- package/packages/server/src/__tests__/bearer-auth.test.ts +0 -67
- package/packages/server/src/__tests__/boot-async-owners.test.ts +0 -107
- package/packages/server/src/__tests__/boot-parent-liveness.test.ts +0 -48
- package/packages/server/src/__tests__/boot-state.test.ts +0 -121
- package/packages/server/src/__tests__/bounded-startup.test.ts +0 -150
- package/packages/server/src/__tests__/bridge-contention.test.ts +0 -300
- package/packages/server/src/__tests__/bridge-local-token-upgrade.test.ts +0 -106
- package/packages/server/src/__tests__/bridge-register-nondestructive.test.ts +0 -108
- package/packages/server/src/__tests__/bridge-ticket-eligibility.test.ts +0 -116
- package/packages/server/src/__tests__/bridge-ticket-scope.test.ts +0 -114
- package/packages/server/src/__tests__/bridge-upgrade-auth.test.ts +0 -327
- package/packages/server/src/__tests__/browse-endpoint.test.ts +0 -616
- package/packages/server/src/__tests__/browser-gateway-broadcast-serialize-once.test.ts +0 -144
- package/packages/server/src/__tests__/browser-gateway-dropped-frames.test.ts +0 -96
- package/packages/server/src/__tests__/browser-gateway-handler-errors.test.ts +0 -129
- package/packages/server/src/__tests__/browser-gateway-load.test.ts +0 -521
- package/packages/server/src/__tests__/browser-gateway-plugin-action-fanout.test.ts +0 -113
- package/packages/server/src/__tests__/browser-gateway-register-handler.test.ts +0 -171
- package/packages/server/src/__tests__/browser-gateway-retry-session.test.ts +0 -91
- package/packages/server/src/__tests__/browser-gateway-role-remove.test.ts +0 -68
- package/packages/server/src/__tests__/browser-gateway-shutdown-reject.test.ts +0 -112
- package/packages/server/src/__tests__/browser-gateway-snapshot-on-connect.test.ts +0 -299
- package/packages/server/src/__tests__/build-auth-status.test.ts +0 -190
- package/packages/server/src/__tests__/bulk-archive-handler.test.ts +0 -15
- package/packages/server/src/__tests__/canvas-accumulator.test.ts +0 -187
- package/packages/server/src/__tests__/canvas-settings.test.ts +0 -68
- package/packages/server/src/__tests__/changelog-fs.test.ts +0 -231
- package/packages/server/src/__tests__/changelog-parser.test.ts +0 -220
- package/packages/server/src/__tests__/changelog-remote.test.ts +0 -193
- package/packages/server/src/__tests__/cli-env-no-clobber.test.ts +0 -46
- package/packages/server/src/__tests__/cli-no-bootstrap-references.test.ts +0 -69
- package/packages/server/src/__tests__/cli-parse.test.ts +0 -199
- package/packages/server/src/__tests__/cli-restart.test.ts +0 -78
- package/packages/server/src/__tests__/cli-signal-forwarding.test.ts +0 -97
- package/packages/server/src/__tests__/cli-version.test.ts +0 -151
- package/packages/server/src/__tests__/client-discovery.test.ts +0 -39
- package/packages/server/src/__tests__/cold-boot-openspec-broadcast.test.ts +0 -161
- package/packages/server/src/__tests__/cold-start-recovery-exempt.test.ts +0 -94
- package/packages/server/src/__tests__/collapse-replay-equivalence.test.ts +0 -296
- package/packages/server/src/__tests__/commit-draft-relay.test.ts +0 -61
- package/packages/server/src/__tests__/concurrent-launch.test.ts +0 -111
- package/packages/server/src/__tests__/config-api.test.ts +0 -473
- package/packages/server/src/__tests__/contention-performance.test.ts +0 -190
- package/packages/server/src/__tests__/contention-prompt-and-resume-guard.test.ts +0 -234
- package/packages/server/src/__tests__/contention-refusal-side-effects.test.ts +0 -194
- package/packages/server/src/__tests__/contention-resume-guard-api.test.ts +0 -363
- package/packages/server/src/__tests__/cors.test.ts +0 -344
- package/packages/server/src/__tests__/crash-recovery.test.ts +0 -89
- package/packages/server/src/__tests__/csp.test.ts +0 -71
- package/packages/server/src/__tests__/cwd-missing-handling.test.ts +0 -101
- package/packages/server/src/__tests__/dashboard-source-decision.test.ts +0 -156
- package/packages/server/src/__tests__/decorate-goals-spend.test.ts +0 -79
- package/packages/server/src/__tests__/directory-service-eventloop-turns.test.ts +0 -211
- package/packages/server/src/__tests__/directory-service-folderhead-async.test.ts +0 -145
- package/packages/server/src/__tests__/directory-service-known-dirs.test.ts +0 -125
- package/packages/server/src/__tests__/directory-service-openspec-enabled.test.ts +0 -212
- package/packages/server/src/__tests__/directory-service-pending-emit.test.ts +0 -226
- package/packages/server/src/__tests__/directory-service-refresh-force.test.ts +0 -188
- package/packages/server/src/__tests__/directory-service-specs-mtime.test.ts +0 -352
- package/packages/server/src/__tests__/directory-service-toctou.test.ts +0 -322
- package/packages/server/src/__tests__/directory-service-watcher-dedup.test.ts +0 -166
- package/packages/server/src/__tests__/directory-service.test.ts +0 -667
- package/packages/server/src/__tests__/dispatch-extension-command-router.test.ts +0 -179
- package/packages/server/src/__tests__/dispatch-reload-rollout.test.ts +0 -99
- package/packages/server/src/__tests__/doctor-route.test.ts +0 -333
- package/packages/server/src/__tests__/draining-ws.test.ts +0 -131
- package/packages/server/src/__tests__/e2e/model-proxy-google-flash.test.ts +0 -184
- package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +0 -44
- package/packages/server/src/__tests__/eml-cache.test.ts +0 -60
- package/packages/server/src/__tests__/ended-session-endedat.test.ts +0 -302
- package/packages/server/src/__tests__/event-status-extraction.test.ts +0 -155
- package/packages/server/src/__tests__/event-wiring-is-git-repo.test.ts +0 -128
- package/packages/server/src/__tests__/event-wiring-process-classify.test.ts +0 -122
- package/packages/server/src/__tests__/event-wiring-providers-list.test.ts +0 -152
- package/packages/server/src/__tests__/event-wiring-queue-state.test.ts +0 -292
- package/packages/server/src/__tests__/event-wiring-resume-clear.test.ts +0 -103
- package/packages/server/src/__tests__/event-wiring-roles-list-builtin.test.ts +0 -90
- package/packages/server/src/__tests__/event-wiring-source-stamp.test.ts +0 -180
- package/packages/server/src/__tests__/event-wiring-worktree-rekey.test.ts +0 -157
- package/packages/server/src/__tests__/eventloop-sampler.test.ts +0 -111
- package/packages/server/src/__tests__/eventloop-spike-metrics.test.ts +0 -60
- package/packages/server/src/__tests__/exit-intent-paths.test.ts +0 -73
- package/packages/server/src/__tests__/extension-register-appimage.test.ts +0 -43
- package/packages/server/src/__tests__/extension-register.test.ts +0 -67
- package/packages/server/src/__tests__/faux-agent-ticks.unit.test.ts +0 -287
- package/packages/server/src/__tests__/faux-echo-system-context.unit.test.ts +0 -31
- package/packages/server/src/__tests__/faux-router.unit.test.ts +0 -71
- package/packages/server/src/__tests__/faux-session.integration.test.ts +0 -316
- package/packages/server/src/__tests__/file-absolute-containment.test.ts +0 -224
- package/packages/server/src/__tests__/file-artifact-serving.test.ts +0 -189
- package/packages/server/src/__tests__/file-endpoint.test.ts +0 -49
- package/packages/server/src/__tests__/file-kind-endpoint.test.ts +0 -133
- package/packages/server/src/__tests__/file-raw-render-endpoints.test.ts +0 -936
- package/packages/server/src/__tests__/file-tree-endpoint.test.ts +0 -90
- package/packages/server/src/__tests__/file-watch-manager.test.ts +0 -88
- package/packages/server/src/__tests__/file-write-endpoint.test.ts +0 -222
- package/packages/server/src/__tests__/find-port-holders.test.ts +0 -94
- package/packages/server/src/__tests__/fix-pty-permissions.test.ts +0 -59
- package/packages/server/src/__tests__/fixtures/fork-jsonl-roundtrip.jsonl +0 -8
- package/packages/server/src/__tests__/fixtures/pi-changelog-slice.md +0 -180
- package/packages/server/src/__tests__/fixtures/replay-streams.ts +0 -219
- package/packages/server/src/__tests__/folder-head-integration.test.ts +0 -328
- package/packages/server/src/__tests__/folder-head-poll.test.ts +0 -308
- package/packages/server/src/__tests__/folder-head-watcher.test.ts +0 -133
- package/packages/server/src/__tests__/force-kill-handler.test.ts +0 -159
- package/packages/server/src/__tests__/fork-empty-session-preflight.test.ts +0 -272
- package/packages/server/src/__tests__/fork-jsonl-roundtrip.test.ts +0 -49
- package/packages/server/src/__tests__/forwarded-ip-trust.test.ts +0 -136
- package/packages/server/src/__tests__/gateway-listener-wiring.test.ts +0 -81
- package/packages/server/src/__tests__/gateway-socket-bind.test.ts +0 -272
- package/packages/server/src/__tests__/gateway-transport-policy.test.ts +0 -64
- package/packages/server/src/__tests__/genuine-local.test.ts +0 -96
- package/packages/server/src/__tests__/git-commit-operations.test.ts +0 -153
- package/packages/server/src/__tests__/git-operations.test.ts +0 -312
- package/packages/server/src/__tests__/git-pr-operations.test.ts +0 -299
- package/packages/server/src/__tests__/git-worktree-compose.test.ts +0 -57
- package/packages/server/src/__tests__/git-worktree-lifecycle-ops.test.ts +0 -620
- package/packages/server/src/__tests__/git-worktree-lifecycle-routes.test.ts +0 -609
- package/packages/server/src/__tests__/git-worktree-lifecycle.test.ts +0 -201
- package/packages/server/src/__tests__/git-worktree-ops.test.ts +0 -263
- package/packages/server/src/__tests__/git-worktree-routes.test.ts +0 -342
- package/packages/server/src/__tests__/git-worktree.test.ts +0 -481
- package/packages/server/src/__tests__/goal-budget-guard.test.ts +0 -32
- package/packages/server/src/__tests__/goal-routes.test.ts +0 -302
- package/packages/server/src/__tests__/goal-session-primer.test.ts +0 -53
- package/packages/server/src/__tests__/goal-status-projector.test.ts +0 -133
- package/packages/server/src/__tests__/goal-store.test.ts +0 -364
- package/packages/server/src/__tests__/goal-supervisor.test.ts +0 -321
- package/packages/server/src/__tests__/goal-verdict-accumulator.test.ts +0 -90
- package/packages/server/src/__tests__/grep.test.ts +0 -95
- package/packages/server/src/__tests__/has-openspec-dir.test.ts +0 -64
- package/packages/server/src/__tests__/headless-pid-registry-goal-id.test.ts +0 -71
- package/packages/server/src/__tests__/headless-pid-registry-kill-by-token.test.ts +0 -107
- package/packages/server/src/__tests__/headless-pid-registry-kill-escalation.test.ts +0 -163
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +0 -765
- package/packages/server/src/__tests__/headless-shutdown-fallback.test.ts +0 -112
- package/packages/server/src/__tests__/health-compatibility.test.ts +0 -81
- package/packages/server/src/__tests__/health-endpoint.test.ts +0 -127
- package/packages/server/src/__tests__/health-shape.test.ts +0 -221
- package/packages/server/src/__tests__/heartbeat-ack.test.ts +0 -63
- package/packages/server/src/__tests__/helpers/draining-ws.ts +0 -170
- package/packages/server/src/__tests__/helpers/load-fixtures.ts +0 -296
- package/packages/server/src/__tests__/hide-unhide-placement.test.ts +0 -88
- package/packages/server/src/__tests__/home-lock-escape-hatch.test.ts +0 -61
- package/packages/server/src/__tests__/home-lock-release.test.ts +0 -85
- package/packages/server/src/__tests__/home-lock.test.ts +0 -682
- package/packages/server/src/__tests__/home-rendezvous.test.ts +0 -150
- package/packages/server/src/__tests__/hydration-metrics.test.ts +0 -62
- package/packages/server/src/__tests__/identity.test.ts +0 -129
- package/packages/server/src/__tests__/idle-timer-respects-terminals.test.ts +0 -114
- package/packages/server/src/__tests__/inline-terminal-handler.test.ts +0 -165
- package/packages/server/src/__tests__/installed-package-enricher.test.ts +0 -225
- package/packages/server/src/__tests__/internal-registry.test.ts +0 -76
- package/packages/server/src/__tests__/is-activity-event.test.ts +0 -75
- package/packages/server/src/__tests__/is-pi-process.test.ts +0 -36
- package/packages/server/src/__tests__/is-unread-trigger.test.ts +0 -222
- package/packages/server/src/__tests__/json-store.test.ts +0 -70
- package/packages/server/src/__tests__/keeper-manager.test.ts +0 -431
- package/packages/server/src/__tests__/known-servers-routes.test.ts +0 -129
- package/packages/server/src/__tests__/last-activity-broadcast.test.ts +0 -188
- package/packages/server/src/__tests__/launch-source-effective.test.ts +0 -39
- package/packages/server/src/__tests__/live-server-endpoint.test.ts +0 -134
- package/packages/server/src/__tests__/liveness-stamp-wiring.test.ts +0 -154
- package/packages/server/src/__tests__/local-token.test.ts +0 -44
- package/packages/server/src/__tests__/localhost-guard.test.ts +0 -227
- package/packages/server/src/__tests__/memory-event-store.test.ts +0 -1776
- package/packages/server/src/__tests__/memory-session-manager.test.ts +0 -199
- package/packages/server/src/__tests__/meta-persistence.test.ts +0 -244
- package/packages/server/src/__tests__/migrate-persistence.test.ts +0 -180
- package/packages/server/src/__tests__/model-proxy-api-key-routes.test.ts +0 -277
- package/packages/server/src/__tests__/model-proxy-auth-gate.test.ts +0 -263
- package/packages/server/src/__tests__/model-proxy-diagnostics-routes.test.ts +0 -64
- package/packages/server/src/__tests__/model-proxy-multi-user.test.ts +0 -169
- package/packages/server/src/__tests__/model-proxy-routes.test.ts +0 -448
- package/packages/server/src/__tests__/model-proxy-second-port.test.ts +0 -116
- package/packages/server/src/__tests__/models-introspection-routes.test.ts +0 -107
- package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +0 -67
- package/packages/server/src/__tests__/move-folder-handler.test.ts +0 -151
- package/packages/server/src/__tests__/node-cap-message-matches-engines.test.ts +0 -55
- package/packages/server/src/__tests__/node-guard.test.ts +0 -187
- package/packages/server/src/__tests__/notify-log-persistence.test.ts +0 -98
- package/packages/server/src/__tests__/npm-search-proxy.test.ts +0 -181
- package/packages/server/src/__tests__/oauth-callback-server.test.ts +0 -181
- package/packages/server/src/__tests__/office-preview.test.ts +0 -198
- package/packages/server/src/__tests__/openspec-archive.test.ts +0 -87
- package/packages/server/src/__tests__/openspec-change-order-store.test.ts +0 -62
- package/packages/server/src/__tests__/openspec-change-watcher-debounce.test.ts +0 -112
- package/packages/server/src/__tests__/openspec-change-watcher-filter.test.ts +0 -45
- package/packages/server/src/__tests__/openspec-change-watcher-fs.test.ts +0 -142
- package/packages/server/src/__tests__/openspec-connect-snapshot.test.ts +0 -148
- package/packages/server/src/__tests__/openspec-group-broadcast.test.ts +0 -97
- package/packages/server/src/__tests__/openspec-group-join.test.ts +0 -80
- package/packages/server/src/__tests__/openspec-group-routes.test.ts +0 -370
- package/packages/server/src/__tests__/openspec-group-store.test.ts +0 -496
- package/packages/server/src/__tests__/openspec-locality.test.ts +0 -170
- package/packages/server/src/__tests__/openspec-poll-worker.test.ts +0 -272
- package/packages/server/src/__tests__/openspec-profile-routes.test.ts +0 -415
- package/packages/server/src/__tests__/openspec-tasks-parser.test.ts +0 -292
- package/packages/server/src/__tests__/openspec-tasks-routes.test.ts +0 -180
- package/packages/server/src/__tests__/package-manager-wrapper-move.test.ts +0 -414
- package/packages/server/src/__tests__/package-manager-wrapper-reset.test.ts +0 -194
- package/packages/server/src/__tests__/package-manager-wrapper-resolve.test.ts +0 -136
- package/packages/server/src/__tests__/package-manager-wrapper.test.ts +0 -198
- package/packages/server/src/__tests__/package-routes.test.ts +0 -404
- package/packages/server/src/__tests__/package-source-helpers.test.ts +0 -101
- package/packages/server/src/__tests__/paired-devices.test.ts +0 -59
- package/packages/server/src/__tests__/pairing.test.ts +0 -215
- package/packages/server/src/__tests__/pending-attach-registry.test.ts +0 -138
- package/packages/server/src/__tests__/pending-automation-run-registry.test.ts +0 -54
- package/packages/server/src/__tests__/pending-client-correlations.test.ts +0 -77
- package/packages/server/src/__tests__/pending-fork-registry.test.ts +0 -119
- package/packages/server/src/__tests__/pending-initial-prompt-registry.test.ts +0 -52
- package/packages/server/src/__tests__/pending-load-manager.test.ts +0 -144
- package/packages/server/src/__tests__/pending-prompt-acks.test.ts +0 -105
- package/packages/server/src/__tests__/pending-resume-intent-registry.test.ts +0 -153
- package/packages/server/src/__tests__/pending-resume-registry.test.ts +0 -130
- package/packages/server/src/__tests__/pending-worktree-base-registry.test.ts +0 -97
- package/packages/server/src/__tests__/pi-agent-settings.test.ts +0 -193
- package/packages/server/src/__tests__/pi-ai-shape.test.ts +0 -147
- package/packages/server/src/__tests__/pi-changelog-integration.test.ts +0 -165
- package/packages/server/src/__tests__/pi-changelog-routes.test.ts +0 -425
- package/packages/server/src/__tests__/pi-core-checker.test.ts +0 -380
- package/packages/server/src/__tests__/pi-core-routes.test.ts +0 -184
- package/packages/server/src/__tests__/pi-core-updater-managed-path.test.ts +0 -236
- package/packages/server/src/__tests__/pi-core-updater.test.ts +0 -214
- package/packages/server/src/__tests__/pi-dashboard-bin-wrapper.test.ts +0 -84
- package/packages/server/src/__tests__/pi-dev-version-check.test.ts +0 -184
- package/packages/server/src/__tests__/pi-gateway-bind-host.test.ts +0 -154
- package/packages/server/src/__tests__/pi-gateway-consume-pending-attach.test.ts +0 -115
- package/packages/server/src/__tests__/pi-gateway-duplicate-register.test.ts +0 -819
- package/packages/server/src/__tests__/pi-gateway-socket-transport.test.ts +0 -372
- package/packages/server/src/__tests__/pi-gateway-teardown.test.ts +0 -45
- package/packages/server/src/__tests__/pi-resource-activation-timeout.test.ts +0 -85
- package/packages/server/src/__tests__/pi-resource-scanner.test.ts +0 -640
- package/packages/server/src/__tests__/pi-runtime-divergence.test.ts +0 -251
- package/packages/server/src/__tests__/pi-runtime-routes.test.ts +0 -273
- package/packages/server/src/__tests__/pi-version-skew-recommended-0-84.test.ts +0 -48
- package/packages/server/src/__tests__/pi-version-skew.test.ts +0 -362
- package/packages/server/src/__tests__/pi-version-update-handling.test.ts +0 -51
- package/packages/server/src/__tests__/plugin-activation-routes.test.ts +0 -267
- package/packages/server/src/__tests__/plugin-intent-cache.test.ts +0 -75
- package/packages/server/src/__tests__/plugin-pi-message-attribution.test.ts +0 -150
- package/packages/server/src/__tests__/preferences-store-move-folder.test.ts +0 -141
- package/packages/server/src/__tests__/preferences-store.test.ts +0 -769
- package/packages/server/src/__tests__/process-classifier.test.ts +0 -104
- package/packages/server/src/__tests__/process-manager-codes.test.ts +0 -83
- package/packages/server/src/__tests__/process-manager-keeper-spawn.test.ts +0 -260
- package/packages/server/src/__tests__/process-manager-managed-path.test.ts +0 -73
- package/packages/server/src/__tests__/process-manager.test.ts +0 -501
- package/packages/server/src/__tests__/prompt-derived-tool-state.integration.test.ts +0 -796
- package/packages/server/src/__tests__/proposal-attach-naming.test.ts +0 -79
- package/packages/server/src/__tests__/provider-auth-handlers.test.ts +0 -77
- package/packages/server/src/__tests__/provider-auth-routes.test.ts +0 -168
- package/packages/server/src/__tests__/provider-auth-storage.test.ts +0 -150
- package/packages/server/src/__tests__/provider-catalogue-cache.test.ts +0 -44
- package/packages/server/src/__tests__/provider-health-cache-route.test.ts +0 -229
- package/packages/server/src/__tests__/provider-probe.test.ts +0 -287
- package/packages/server/src/__tests__/provider-routes-masked-key.test.ts +0 -110
- package/packages/server/src/__tests__/provider-routes-recursion-guard.test.ts +0 -131
- package/packages/server/src/__tests__/provider-test-route.test.ts +0 -149
- package/packages/server/src/__tests__/provisional-register-routing.test.ts +0 -598
- package/packages/server/src/__tests__/reattach-placement.test.ts +0 -255
- package/packages/server/src/__tests__/recommended-routes.test.ts +0 -648
- package/packages/server/src/__tests__/reconcile-session-order.test.ts +0 -71
- package/packages/server/src/__tests__/recovery-dedupe-and-lock.test.ts +0 -40
- package/packages/server/src/__tests__/recovery-e2e.test.ts +0 -198
- package/packages/server/src/__tests__/recovery-exit-intent.test.ts +0 -252
- package/packages/server/src/__tests__/recovery-offer.test.ts +0 -239
- package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +0 -192
- package/packages/server/src/__tests__/recovery-reinstall-reject.test.ts +0 -89
- package/packages/server/src/__tests__/recovery-server.test.ts +0 -254
- package/packages/server/src/__tests__/replace-proposal-race.test.ts +0 -236
- package/packages/server/src/__tests__/replay-compaction-equivalence.test.ts +0 -89
- package/packages/server/src/__tests__/replay-compaction.test.ts +0 -208
- package/packages/server/src/__tests__/replay-streams-fixtures.test.ts +0 -67
- package/packages/server/src/__tests__/replay-truncate.test.ts +0 -61
- package/packages/server/src/__tests__/resolve-mention-endpoint.test.ts +0 -153
- package/packages/server/src/__tests__/resolve-order-key.test.ts +0 -31
- package/packages/server/src/__tests__/resolve-path.test.ts +0 -38
- package/packages/server/src/__tests__/resolve-published-variant.test.ts +0 -133
- package/packages/server/src/__tests__/resource-activation-routes.test.ts +0 -547
- package/packages/server/src/__tests__/resource-activation-toggle.test.ts +0 -906
- package/packages/server/src/__tests__/restart-helper.test.ts +0 -274
- package/packages/server/src/__tests__/resume-remote-origin-bus.test.ts +0 -160
- package/packages/server/src/__tests__/retire-view-message-surface.test.ts +0 -35
- package/packages/server/src/__tests__/ring-buffer.test.ts +0 -45
- package/packages/server/src/__tests__/routes-git-worktree-init.test.ts +0 -552
- package/packages/server/src/__tests__/server-pid.test.ts +0 -89
- package/packages/server/src/__tests__/session-action-handler-followup-queue.test.ts +0 -170
- package/packages/server/src/__tests__/session-action-handler-headless-reload.test.ts +0 -761
- package/packages/server/src/__tests__/session-action-handler-reload-predicate.test.ts +0 -162
- package/packages/server/src/__tests__/session-action-handler-spawn-error.test.ts +0 -89
- package/packages/server/src/__tests__/session-action-handler-spawn-with-attach.test.ts +0 -108
- package/packages/server/src/__tests__/session-action-handler-spawn-with-initial-prompt.test.ts +0 -80
- package/packages/server/src/__tests__/session-action-handler-spawn.test.ts +0 -150
- package/packages/server/src/__tests__/session-api.test.ts +0 -283
- package/packages/server/src/__tests__/session-card-ordering-gates.test.ts +0 -298
- package/packages/server/src/__tests__/session-diff.test.ts +0 -852
- package/packages/server/src/__tests__/session-discovery-skill-firstmessage.test.ts +0 -95
- package/packages/server/src/__tests__/session-file-dedup.test.ts +0 -102
- package/packages/server/src/__tests__/session-file-reader.test.ts +0 -170
- package/packages/server/src/__tests__/session-kill-e2e.test.ts +0 -245
- package/packages/server/src/__tests__/session-lifecycle-logging.test.ts +0 -144
- package/packages/server/src/__tests__/session-load-worker.test.ts +0 -220
- package/packages/server/src/__tests__/session-name-provenance-persistence.test.ts +0 -122
- package/packages/server/src/__tests__/session-order-manager.test.ts +0 -268
- package/packages/server/src/__tests__/session-order-reboot.test.ts +0 -384
- package/packages/server/src/__tests__/session-ordering-integration.test.ts +0 -126
- package/packages/server/src/__tests__/session-routes-tool-result.test.ts +0 -134
- package/packages/server/src/__tests__/session-scanner-resolve-dir.integration.test.ts +0 -96
- package/packages/server/src/__tests__/session-scanner.test.ts +0 -366
- package/packages/server/src/__tests__/session-skill-registry.test.ts +0 -295
- package/packages/server/src/__tests__/session-tags-persistence.test.ts +0 -114
- package/packages/server/src/__tests__/shutdown-endpoint.test.ts +0 -43
- package/packages/server/src/__tests__/shutdown-orphan-signal.test.ts +0 -108
- package/packages/server/src/__tests__/shutdown-terminates-any-strategy.test.ts +0 -294
- package/packages/server/src/__tests__/skip-wipe.test.ts +0 -123
- package/packages/server/src/__tests__/sleep-aware-heartbeat.test.ts +0 -128
- package/packages/server/src/__tests__/smoke-integration.test.ts +0 -175
- package/packages/server/src/__tests__/spa-fallback.test.ts +0 -70
- package/packages/server/src/__tests__/spawn-correlation-performance.test.ts +0 -125
- package/packages/server/src/__tests__/spawn-correlation-token-integration.test.ts +0 -91
- package/packages/server/src/__tests__/spawn-correlation-ttl-derivation.test.ts +0 -182
- package/packages/server/src/__tests__/spawn-env-electron-parity.test.ts +0 -47
- package/packages/server/src/__tests__/spawn-failure-log.test.ts +0 -118
- package/packages/server/src/__tests__/spawn-preflight.test.ts +0 -91
- package/packages/server/src/__tests__/spawn-register-watchdog.test.ts +0 -735
- package/packages/server/src/__tests__/spawn-token.test.ts +0 -152
- package/packages/server/src/__tests__/spawned-turn-log.test.ts +0 -88
- package/packages/server/src/__tests__/start-teardown-wiring.test.ts +0 -64
- package/packages/server/src/__tests__/subscription-handler-backfill.test.ts +0 -693
- package/packages/server/src/__tests__/subscription-handler-compaction.test.ts +0 -227
- package/packages/server/src/__tests__/subscription-handler-window.test.ts +0 -473
- package/packages/server/src/__tests__/subscription-handler.test.ts +0 -625
- package/packages/server/src/__tests__/system-open-endpoints.test.ts +0 -150
- package/packages/server/src/__tests__/system-routes-restart.test.ts +0 -182
- package/packages/server/src/__tests__/system-routes-spawn-failures.test.ts +0 -84
- package/packages/server/src/__tests__/terminal-gateway.test.ts +0 -65
- package/packages/server/src/__tests__/terminal-manager.test.ts +0 -658
- package/packages/server/src/__tests__/test-server-canary.test.ts +0 -98
- package/packages/server/src/__tests__/thin-subagent-tick-downstream.test.ts +0 -81
- package/packages/server/src/__tests__/tool-routes.test.ts +0 -365
- package/packages/server/src/__tests__/translate-path-source.test.ts +0 -77
- package/packages/server/src/__tests__/trusted-networks-config.test.ts +0 -208
- package/packages/server/src/__tests__/trusted-networks-no-oauth-roundtrip.test.ts +0 -126
- package/packages/server/src/__tests__/tunnel-block-events.test.ts +0 -74
- package/packages/server/src/__tests__/tunnel-cleanup.test.ts +0 -90
- package/packages/server/src/__tests__/tunnel-concurrency-wiring.test.ts +0 -215
- package/packages/server/src/__tests__/tunnel-config-redaction.test.ts +0 -68
- package/packages/server/src/__tests__/tunnel-core-executor.test.ts +0 -88
- package/packages/server/src/__tests__/tunnel-enroll.test.ts +0 -105
- package/packages/server/src/__tests__/tunnel-kind-gate.test.ts +0 -48
- package/packages/server/src/__tests__/tunnel-ngrok.test.ts +0 -101
- package/packages/server/src/__tests__/tunnel-readiness.test.ts +0 -328
- package/packages/server/src/__tests__/tunnel-reserved-name-route.test.ts +0 -317
- package/packages/server/src/__tests__/tunnel-tailscale.test.ts +0 -99
- package/packages/server/src/__tests__/tunnel-watchdog.test.ts +0 -139
- package/packages/server/src/__tests__/tunnel-zerotier.test.ts +0 -91
- package/packages/server/src/__tests__/tunnel-zrok-v2.test.ts +0 -319
- package/packages/server/src/__tests__/tunnel.test.ts +0 -369
- package/packages/server/src/__tests__/ui-decorators-replay.test.ts +0 -210
- package/packages/server/src/__tests__/ui-modules-replay.test.ts +0 -236
- package/packages/server/src/__tests__/unread-persistence.test.ts +0 -55
- package/packages/server/src/__tests__/unread-trigger-wiring.test.ts +0 -208
- package/packages/server/src/__tests__/viewed-session-tracker.test.ts +0 -93
- package/packages/server/src/__tests__/worktree-base-spawn-flow.test.ts +0 -157
- package/packages/server/src/__tests__/worktree-init-errors.test.ts +0 -72
- package/packages/server/src/__tests__/worktree-init-registry.test.ts +0 -178
- package/packages/server/src/__tests__/worktree-init-trust.test.ts +0 -105
- package/packages/server/src/__tests__/worktree-init.test.ts +0 -214
- package/packages/server/src/__tests__/worktree-pi-settings-rewrite.test.ts +0 -207
- package/packages/server/src/__tests__/ws-ping-pong.test.ts +0 -120
- package/packages/server/src/__tests__/ws-ticket.test.ts +0 -123
- package/packages/server/src/__tests__/ws-upgrade-routing.test.ts +0 -160
- package/packages/server/src/__tests__/wsl-tmux-probe-cache.test.ts +0 -44
- package/packages/server/src/__tests__/zrok-reserved-name.test.ts +0 -326
- package/packages/server/src/attachments/AGENTS.md +0 -15
- package/packages/server/src/attachments/__tests__/attachment-ingest.test.ts +0 -236
- package/packages/server/src/attachments/__tests__/attachment-resolver.test.ts +0 -339
- package/packages/server/src/attachments/__tests__/display-fit-perf.test.ts +0 -247
- package/packages/server/src/attachments/__tests__/display-fit.test.ts +0 -397
- package/packages/server/src/attachments/__tests__/fit-worker-pool-fallback.test.ts +0 -158
- package/packages/server/src/attachments/__tests__/fit-worker-pool.test.ts +0 -105
- package/packages/server/src/attachments/__tests__/fit-worker-total.test.ts +0 -27
- package/packages/server/src/attachments/__tests__/original-store.test.ts +0 -185
- package/packages/server/src/auth/AGENTS.md +0 -24
- package/packages/server/src/auth/auth-plugin.ts.AGENTS.md +0 -5
- package/packages/server/src/auth/auth.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/bearer-auth.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/cors-origin.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/csp.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/identity.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/local-token.ts.AGENTS.md +0 -5
- package/packages/server/src/auth/localhost-guard.ts.AGENTS.md +0 -5
- package/packages/server/src/auth/node-guard.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/oauth-callback-server.ts +0 -177
- package/packages/server/src/auth/oauth-callback-server.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/provider-auth-handlers.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/provider-auth-storage.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/spawn-token.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/test-env-guard.ts.AGENTS.md +0 -3
- package/packages/server/src/auth/ws-ticket.ts.AGENTS.md +0 -5
- package/packages/server/src/browse.ts.AGENTS.md +0 -3
- package/packages/server/src/browser-handlers/AGENTS.md +0 -13
- package/packages/server/src/browser-handlers/__tests__/directory-handler.test.ts +0 -96
- package/packages/server/src/browser-handlers/__tests__/session-action-handler.test.ts +0 -238
- package/packages/server/src/browser-handlers/__tests__/session-action-liveness-clear.test.ts +0 -75
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +0 -456
- package/packages/server/src/canvas/AGENTS.md +0 -8
- package/packages/server/src/changelog/AGENTS.md +0 -9
- package/packages/server/src/changelog/changelog-fs.ts.AGENTS.md +0 -3
- package/packages/server/src/changelog/changelog-parser.ts.AGENTS.md +0 -3
- package/packages/server/src/changelog/changelog-remote.ts.AGENTS.md +0 -3
- package/packages/server/src/cli.ts.AGENTS.md +0 -3
- package/packages/server/src/commit-draft-relay.ts.AGENTS.md +0 -3
- package/packages/server/src/config-api.ts.AGENTS.md +0 -5
- package/packages/server/src/directory-service.ts.AGENTS.md +0 -3
- package/packages/server/src/embed-lifecycle/AGENTS.md +0 -17
- package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +0 -129
- package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +0 -194
- package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +0 -73
- package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +0 -173
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +0 -26
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +0 -32
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +0 -106
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +0 -39
- package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +0 -77
- package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +0 -175
- package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +0 -77
- package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +0 -38
- package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +0 -145
- package/packages/server/src/event-wiring.ts.AGENTS.md +0 -7
- package/packages/server/src/fix-pty-permissions.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/AGENTS.md +0 -16
- package/packages/server/src/git-worktree/folder-head-poll.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/folder-head-watcher.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/git-operations.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/git-worktree-compose.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/git-worktree.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/worktree-init-errors.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/worktree-init-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/worktree-init-trust.ts.AGENTS.md +0 -3
- package/packages/server/src/git-worktree/worktree-init.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/AGENTS.md +0 -13
- package/packages/server/src/goal/decorate-goals-spend.ts +0 -47
- package/packages/server/src/goal/goal-budget-guard.ts +0 -42
- package/packages/server/src/goal/goal-budget-guard.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/goal-session-primer.ts +0 -99
- package/packages/server/src/goal/goal-session-primer.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/goal-status-projector.ts +0 -121
- package/packages/server/src/goal/goal-status-projector.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/goal-store.ts +0 -530
- package/packages/server/src/goal/goal-store.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/goal-supervisor.ts +0 -447
- package/packages/server/src/goal/goal-supervisor.ts.AGENTS.md +0 -3
- package/packages/server/src/goal/goal-verdict-accumulator.ts +0 -101
- package/packages/server/src/goal/goal-verdict-accumulator.ts.AGENTS.md +0 -3
- package/packages/server/src/lib/AGENTS.md +0 -16
- package/packages/server/src/lib/__tests__/md-candidates.test.ts +0 -81
- package/packages/server/src/lib/__tests__/path-containment.test.ts +0 -119
- package/packages/server/src/lib/__tests__/resolve-file-mention.test.ts +0 -87
- package/packages/server/src/lib/__tests__/writable-md-target.test.ts +0 -112
- package/packages/server/src/lifecycle/AGENTS.md +0 -15
- package/packages/server/src/lifecycle/boot-parent-liveness.ts.AGENTS.md +0 -3
- package/packages/server/src/lifecycle/dashboard-source-decision.ts.AGENTS.md +0 -3
- package/packages/server/src/lifecycle/home-lock-release.ts.AGENTS.md +0 -3
- package/packages/server/src/lifecycle/home-lock.ts.AGENTS.md +0 -3
- package/packages/server/src/lifecycle/launch-source-effective.ts.AGENTS.md +0 -3
- package/packages/server/src/lifecycle/recovery-server.ts.AGENTS.md +0 -3
- package/packages/server/src/live-server/AGENTS.md +0 -8
- package/packages/server/src/live-server/live-server-manager.ts.AGENTS.md +0 -3
- package/packages/server/src/live-server/live-server-proxy.ts.AGENTS.md +0 -3
- package/packages/server/src/metrics/AGENTS.md +0 -9
- package/packages/server/src/metrics/eventloop-sampler.ts.AGENTS.md +0 -3
- package/packages/server/src/metrics/eventloop-spike-metrics.ts.AGENTS.md +0 -3
- package/packages/server/src/metrics/hydration-metrics.ts.AGENTS.md +0 -3
- package/packages/server/src/model-proxy/AGENTS.md +0 -18
- package/packages/server/src/model-proxy/__tests__/api-key-store.test.ts +0 -142
- package/packages/server/src/model-proxy/__tests__/auth-json-contention.test.ts +0 -98
- package/packages/server/src/model-proxy/__tests__/concurrency.test.ts +0 -107
- package/packages/server/src/model-proxy/__tests__/failed-auth-backoff.test.ts +0 -46
- package/packages/server/src/model-proxy/__tests__/internal-auth-storage-refresh.test.ts +0 -148
- package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +0 -279
- package/packages/server/src/model-proxy/__tests__/internal-registry.test.ts +0 -268
- package/packages/server/src/model-proxy/__tests__/oauth-compat.test.ts +0 -31
- package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +0 -132
- package/packages/server/src/model-proxy/__tests__/recursion-guard.test.ts +0 -61
- package/packages/server/src/model-proxy/__tests__/streamer.test.ts +0 -139
- package/packages/server/src/model-proxy/convert/AGENTS.md +0 -13
- package/packages/server/src/model-proxy/convert/__tests__/anthropic-in.test.ts +0 -137
- package/packages/server/src/model-proxy/convert/__tests__/anthropic-out.test.ts +0 -183
- package/packages/server/src/model-proxy/convert/__tests__/openai-in.test.ts +0 -134
- package/packages/server/src/model-proxy/convert/__tests__/openai-out.test.ts +0 -166
- package/packages/server/src/openspec/AGENTS.md +0 -14
- package/packages/server/src/openspec/openspec-archive.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-change-watcher.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-group-store.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-poll-worker.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/openspec-tasks.ts.AGENTS.md +0 -3
- package/packages/server/src/openspec/proposal-attach-naming.ts.AGENTS.md +0 -3
- package/packages/server/src/package/AGENTS.md +0 -12
- package/packages/server/src/package/__tests__/provider-probe-metadata.test.ts +0 -313
- package/packages/server/src/package/installed-package-enricher.ts.AGENTS.md +0 -8
- package/packages/server/src/package/npm-search-proxy.ts.AGENTS.md +0 -8
- package/packages/server/src/package/package-manager-wrapper.ts.AGENTS.md +0 -8
- package/packages/server/src/package/package-source-helpers.ts.AGENTS.md +0 -3
- package/packages/server/src/package/provider-catalogue-cache.ts.AGENTS.md +0 -3
- package/packages/server/src/package/provider-probe.ts.AGENTS.md +0 -3
- package/packages/server/src/pairing/AGENTS.md +0 -11
- package/packages/server/src/pairing/__tests__/subagent-resync-routing.test.ts +0 -93
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +0 -4
- package/packages/server/src/pairing/paired-devices.ts.AGENTS.md +0 -3
- package/packages/server/src/pairing/pairing.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/AGENTS.md +0 -17
- package/packages/server/src/pending/pending-attach-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-automation-run-registry.ts +0 -116
- package/packages/server/src/pending/pending-automation-run-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-client-correlations.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-fork-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-goal-link-registry.ts +0 -107
- package/packages/server/src/pending/pending-goal-link-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-initial-prompt-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-load-manager.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-prompt-acks.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-resume-intent-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-resume-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/pending/pending-worktree-base-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/persistence/AGENTS.md +0 -12
- package/packages/server/src/persistence/json-store.ts.AGENTS.md +0 -3
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +0 -5
- package/packages/server/src/persistence/meta-persistence.ts.AGENTS.md +0 -3
- package/packages/server/src/persistence/migrate-persistence.ts.AGENTS.md +0 -3
- package/packages/server/src/persistence/preferences-store.ts.AGENTS.md +0 -4
- package/packages/server/src/pi/AGENTS.md +0 -24
- package/packages/server/src/pi/__tests__/provisional-registration.test.ts +0 -176
- package/packages/server/src/pi/bridge-contention.ts.AGENTS.md +0 -9
- package/packages/server/src/pi/gateway-socket-bind.ts.AGENTS.md +0 -15
- package/packages/server/src/pi/pi-core-checker.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/pi-core-updater.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/pi-dev-version-check.ts +0 -145
- package/packages/server/src/pi/pi-dev-version-check.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/pi-gateway.ts.AGENTS.md +0 -6
- package/packages/server/src/pi/pi-resource-activation.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/pi-resource-scanner.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/pi-version-skew.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/resource-activation-toggle.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/resource-entry-ownership.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/resource-origin.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/resource-toggle-trust.ts.AGENTS.md +0 -3
- package/packages/server/src/pi/session-skill-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/plugin-intent-cache.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/AGENTS.md +0 -43
- package/packages/server/src/routes/__tests__/attachment-routes.test.ts +0 -161
- package/packages/server/src/routes/__tests__/grep-routes.test.ts +0 -84
- package/packages/server/src/routes/__tests__/manifest-route.test.ts +0 -138
- package/packages/server/src/routes/__tests__/pi-retry-routes.test.ts +0 -84
- package/packages/server/src/routes/attachment-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/doctor-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/file-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/git-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/goal-routes.ts +0 -406
- package/packages/server/src/routes/goal-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/known-servers-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/live-server-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/manifest-route.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/model-proxy-api-key-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/model-proxy-diagnostics-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/model-proxy-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/models-introspection-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/network-interfaces.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/openspec-group-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/openspec-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/package-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/pairing-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/pi-changelog-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/pi-core-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/pi-retry-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/plugin-activation-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/plugin-config-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/preferences-auto-name-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/preferences-display-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/preferences-worktree-init-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/provider-auth-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/provider-health-cache.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/provider-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/recommended-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/resource-activation-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/route-deps.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/session-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/system-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/routes/tool-routes.ts.AGENTS.md +0 -3
- package/packages/server/src/rpc-keeper/AGENTS.md +0 -9
- package/packages/server/src/rpc-keeper/__tests__/fixtures/mock-pi-shim.sh +0 -9
- package/packages/server/src/rpc-keeper/__tests__/fixtures/mock-pi.cjs +0 -89
- package/packages/server/src/rpc-keeper/__tests__/keeper-electron-run-as-node.test.ts +0 -67
- package/packages/server/src/rpc-keeper/__tests__/keeper-env.test.ts +0 -47
- package/packages/server/src/rpc-keeper/__tests__/keeper-shutdown-kills-pi.test.ts +0 -134
- package/packages/server/src/rpc-keeper/__tests__/keeper.test.ts +0 -624
- package/packages/server/src/rpc-keeper/dispatch-router.ts +0 -85
- package/packages/server/src/server.ts.AGENTS.md +0 -9
- package/packages/server/src/session/AGENTS.md +0 -31
- package/packages/server/src/session/__tests__/remote-transcript-store.test.ts +0 -176
- package/packages/server/src/session/__tests__/session-diff-cache.test.ts +0 -62
- package/packages/server/src/session/__tests__/session-diff-eventloop.test.ts +0 -79
- package/packages/server/src/session/__tests__/session-origin.test.ts +0 -153
- package/packages/server/src/session/active-sessions-in-cwd.ts.AGENTS.md +0 -3
- package/packages/server/src/session/event-status-extraction.ts.AGENTS.md +0 -3
- package/packages/server/src/session/memory-session-manager.ts.AGENTS.md +0 -5
- package/packages/server/src/session/reattach-placement.ts.AGENTS.md +0 -3
- package/packages/server/src/session/reconcile-session-order.ts.AGENTS.md +0 -3
- package/packages/server/src/session/replay-compaction.ts.AGENTS.md +0 -5
- package/packages/server/src/session/replay-truncate.ts.AGENTS.md +0 -3
- package/packages/server/src/session/resolve-order-key.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-api.ts.AGENTS.md +0 -7
- package/packages/server/src/session/session-bootstrap.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-diff.ts.AGENTS.md +0 -9
- package/packages/server/src/session/session-discovery.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-file-reader.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-load-worker-pool.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-load-worker.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-order-manager.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-scanner.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-stats-reader.ts.AGENTS.md +0 -3
- package/packages/server/src/session/session-to-meta.ts.AGENTS.md +0 -3
- package/packages/server/src/session/viewed-session-tracker.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/AGENTS.md +0 -17
- package/packages/server/src/spawn-process/headless-pid-registry.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/idle-timer.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/process-classifier.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/process-manager.ts.AGENTS.md +0 -5
- package/packages/server/src/spawn-process/restart-helper.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/server-pid.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/spawn-failure-log.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/spawn-preflight.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/spawn-recovery-window.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts.AGENTS.md +0 -3
- package/packages/server/src/spawn-process/spawned-turn-log.ts.AGENTS.md +0 -3
- package/packages/server/src/terminal/AGENTS.md +0 -8
- package/packages/server/src/terminal/terminal-gateway.ts.AGENTS.md +0 -3
- package/packages/server/src/terminal/terminal-manager.ts.AGENTS.md +0 -11
- package/packages/server/src/test-support/AGENTS.md +0 -9
- package/packages/server/src/test-support/__tests__/event-loop-lag.test.ts +0 -48
- package/packages/server/src/test-support/event-loop-lag.ts +0 -63
- package/packages/server/src/test-support/test-server.ts +0 -66
- package/packages/server/src/tunnel/AGENTS.md +0 -13
- package/packages/server/src/tunnel/tunnel-block-events.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel/tunnel-core.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel/tunnel-endpoints.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel/tunnel-enroll.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel/tunnel-watchdog.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel/tunnel.ts.AGENTS.md +0 -3
- package/packages/server/src/tunnel-providers/AGENTS.md +0 -14
- package/packages/shared/src/AGENTS.md +0 -68
- package/packages/shared/src/__tests__/binary-lookup-resolveJiti.test.ts +0 -256
- package/packages/shared/src/__tests__/binary-lookup-spawn-env.test.ts +0 -61
- package/packages/shared/src/__tests__/binary-lookup.test.ts +0 -211
- package/packages/shared/src/__tests__/bridge-register.test.ts +0 -252
- package/packages/shared/src/__tests__/browser-protocol-types.test.ts +0 -289
- package/packages/shared/src/__tests__/bundled-node-meets-pi-floor.test.ts +0 -109
- package/packages/shared/src/__tests__/bundled-plugins-complete.test.ts +0 -90
- package/packages/shared/src/__tests__/bundled-server-materialization.test.ts +0 -93
- package/packages/shared/src/__tests__/canvas-declare.test.ts +0 -103
- package/packages/shared/src/__tests__/canvas-detect.test.ts +0 -83
- package/packages/shared/src/__tests__/canvas-types.test.ts +0 -46
- package/packages/shared/src/__tests__/changelog-types.test.ts +0 -78
- package/packages/shared/src/__tests__/ci-electron-no-side-effects.test.ts +0 -129
- package/packages/shared/src/__tests__/client-build-deps-runtime.test.ts +0 -79
- package/packages/shared/src/__tests__/client-build-deps-runtime.test.ts.AGENTS.md +0 -3
- package/packages/shared/src/__tests__/config-keeper-log.test.ts +0 -77
- package/packages/shared/src/__tests__/config-openspec.test.ts +0 -180
- package/packages/shared/src/__tests__/config-plugins.test.ts +0 -68
- package/packages/shared/src/__tests__/config.test.ts +0 -989
- package/packages/shared/src/__tests__/content-view-claims-predicated.test.ts +0 -105
- package/packages/shared/src/__tests__/credential-detect.test.ts +0 -145
- package/packages/shared/src/__tests__/cwd-missing-protocol.test.ts +0 -47
- package/packages/shared/src/__tests__/dashboard-paths.test.ts +0 -201
- package/packages/shared/src/__tests__/dashboard-starter.test.ts +0 -40
- package/packages/shared/src/__tests__/deriveChangeState.test.ts +0 -95
- package/packages/shared/src/__tests__/detached-spawn.test.ts +0 -267
- package/packages/shared/src/__tests__/display-prefs.test.ts +0 -404
- package/packages/shared/src/__tests__/doctor-core-legacy-advisory.test.ts +0 -88
- package/packages/shared/src/__tests__/doctor-core.test.ts +0 -234
- package/packages/shared/src/__tests__/doctor-fault-tolerance.test.ts +0 -218
- package/packages/shared/src/__tests__/doctor-format.test.ts +0 -124
- package/packages/shared/src/__tests__/doctor-tunnel-checks.test.ts +0 -422
- package/packages/shared/src/__tests__/ensure-bundled-git.test.ts +0 -111
- package/packages/shared/src/__tests__/ensure-windows-path.test.ts +0 -112
- package/packages/shared/src/__tests__/extension-ui-module-shape.test.ts +0 -265
- package/packages/shared/src/__tests__/file-kind.test.ts +0 -199
- package/packages/shared/src/__tests__/image-block.test.ts +0 -96
- package/packages/shared/src/__tests__/instance-directory.test.ts +0 -131
- package/packages/shared/src/__tests__/intent-types.test.ts +0 -120
- package/packages/shared/src/__tests__/jiti-packages-parity.test.ts +0 -85
- package/packages/shared/src/__tests__/knip-workflow-contract.test.ts +0 -89
- package/packages/shared/src/__tests__/legacy-managed-dir.test.ts +0 -59
- package/packages/shared/src/__tests__/live-server.test.ts +0 -75
- package/packages/shared/src/__tests__/managed-node-path.test.ts +0 -122
- package/packages/shared/src/__tests__/managed-paths.test.ts +0 -60
- package/packages/shared/src/__tests__/managed-runtime-strategy.test.ts +0 -74
- package/packages/shared/src/__tests__/mdns-discovery.test.ts +0 -127
- package/packages/shared/src/__tests__/model-catalogue.test.ts +0 -115
- package/packages/shared/src/__tests__/model-id.test.ts +0 -31
- package/packages/shared/src/__tests__/model-proxy-config.test.ts +0 -183
- package/packages/shared/src/__tests__/models-json-reader.test.ts +0 -135
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +0 -125
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts.AGENTS.md +0 -3
- package/packages/shared/src/__tests__/no-bash-on-windows.test.ts +0 -308
- package/packages/shared/src/__tests__/no-direct-child-process.test.ts +0 -124
- package/packages/shared/src/__tests__/no-direct-platform-branch.test.ts +0 -182
- package/packages/shared/src/__tests__/no-direct-process-kill.test.ts +0 -105
- package/packages/shared/src/__tests__/no-electron-execpath-spawn.test.ts +0 -149
- package/packages/shared/src/__tests__/no-flow-command-route-claims.test.ts +0 -79
- package/packages/shared/src/__tests__/no-flow-references-in-shell.test.ts +0 -221
- package/packages/shared/src/__tests__/no-hardcoded-bundled-git-paths.test.ts +0 -95
- package/packages/shared/src/__tests__/no-hardcoded-node-modules-paths.test.ts +0 -176
- package/packages/shared/src/__tests__/no-managed-dir-reference.test.ts +0 -137
- package/packages/shared/src/__tests__/no-pi-dashboard-version-jiti-gate.test.ts +0 -41
- package/packages/shared/src/__tests__/no-primitive-direct-import.test.ts +0 -236
- package/packages/shared/src/__tests__/no-raw-node-import.test.ts +0 -148
- package/packages/shared/src/__tests__/no-raw-openspec-status-in-skills.test.ts +0 -86
- package/packages/shared/src/__tests__/no-remote-debugging-address.test.ts +0 -72
- package/packages/shared/src/__tests__/no-server-imports-in-resolver.test.ts +0 -53
- package/packages/shared/src/__tests__/node-cap-single-source.test.ts +0 -123
- package/packages/shared/src/__tests__/node-cap-single-source.test.ts.AGENTS.md +0 -3
- package/packages/shared/src/__tests__/node-spawn-jiti-contract.test.ts +0 -96
- package/packages/shared/src/__tests__/node-spawn.test.ts +0 -277
- package/packages/shared/src/__tests__/node-version.test.ts +0 -82
- package/packages/shared/src/__tests__/openspec-design-evidence.test.ts +0 -288
- package/packages/shared/src/__tests__/openspec-effective-status-script.test.ts +0 -174
- package/packages/shared/src/__tests__/openspec-groups-types.test.ts +0 -135
- package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +0 -112
- package/packages/shared/src/__tests__/openspec-poller-derive.test.ts +0 -128
- package/packages/shared/src/__tests__/openspec-poller-design-override.test.ts +0 -225
- package/packages/shared/src/__tests__/openspec-poller-parity.test.ts +0 -77
- package/packages/shared/src/__tests__/openspec-poller-specs-override.test.ts +0 -284
- package/packages/shared/src/__tests__/openspec-poller.test.ts +0 -44
- package/packages/shared/src/__tests__/openspec-specs-evidence.test.ts +0 -144
- package/packages/shared/src/__tests__/overlay-claims-declare-depth.test.ts +0 -139
- package/packages/shared/src/__tests__/pi-package-resolver.test.ts +0 -300
- package/packages/shared/src/__tests__/pi-version-update-protocol.test.ts +0 -30
- package/packages/shared/src/__tests__/platform/is-appimage-self-hit.test.ts +0 -164
- package/packages/shared/src/__tests__/platform-commands.test.ts +0 -136
- package/packages/shared/src/__tests__/platform-exec.test.ts +0 -103
- package/packages/shared/src/__tests__/platform-git.test.ts +0 -300
- package/packages/shared/src/__tests__/platform-npm.test.ts +0 -137
- package/packages/shared/src/__tests__/platform-openspec.test.ts +0 -95
- package/packages/shared/src/__tests__/platform-paths.test.ts +0 -284
- package/packages/shared/src/__tests__/platform-process-scan.test.ts +0 -55
- package/packages/shared/src/__tests__/platform-process.test.ts +0 -160
- package/packages/shared/src/__tests__/platform-runner.test.ts +0 -173
- package/packages/shared/src/__tests__/platform-shell.test.ts +0 -74
- package/packages/shared/src/__tests__/plugin-activation-contracts.test.ts +0 -74
- package/packages/shared/src/__tests__/plugin-bridge-classify-source.test.ts +0 -73
- package/packages/shared/src/__tests__/plugin-bridge-register-extended.test.ts +0 -84
- package/packages/shared/src/__tests__/plugin-bridge-register-packages.test.ts +0 -233
- package/packages/shared/src/__tests__/plugin-bridge-register.test.ts +0 -123
- package/packages/shared/src/__tests__/plugin-config-update-protocol.test.ts +0 -41
- package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +0 -187
- package/packages/shared/src/__tests__/process-identify.test.ts +0 -205
- package/packages/shared/src/__tests__/protocol.test.ts +0 -276
- package/packages/shared/src/__tests__/publish-allowlist-complete.test.ts +0 -146
- package/packages/shared/src/__tests__/publish-tarball-hygiene.test.ts +0 -100
- package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +0 -600
- package/packages/shared/src/__tests__/recommended-extensions.test.ts +0 -245
- package/packages/shared/src/__tests__/recovery-candidate.test.ts +0 -51
- package/packages/shared/src/__tests__/recovery-timing.test.ts +0 -28
- package/packages/shared/src/__tests__/rendezvous.test.ts +0 -146
- package/packages/shared/src/__tests__/resolve-tool-cli.test.ts +0 -105
- package/packages/shared/src/__tests__/resolver-parity-with-scanner.test.ts +0 -77
- package/packages/shared/src/__tests__/role-name-validation.test.ts +0 -46
- package/packages/shared/src/__tests__/select-git-source.test.ts +0 -65
- package/packages/shared/src/__tests__/semaphore.test.ts +0 -119
- package/packages/shared/src/__tests__/server-identity.test.ts +0 -200
- package/packages/shared/src/__tests__/server-launcher.test.ts +0 -371
- package/packages/shared/src/__tests__/server-pinning.test.ts +0 -182
- package/packages/shared/src/__tests__/session-meta-worktree.test.ts +0 -61
- package/packages/shared/src/__tests__/session-meta.test.ts +0 -140
- package/packages/shared/src/__tests__/skill-block-parser.test.ts +0 -153
- package/packages/shared/src/__tests__/smoke-node-matrix.test.ts +0 -107
- package/packages/shared/src/__tests__/smoke-node-matrix.test.ts.AGENTS.md +0 -3
- package/packages/shared/src/__tests__/source-matching.test.ts +0 -211
- package/packages/shared/src/__tests__/spawn-mechanism.test.ts +0 -142
- package/packages/shared/src/__tests__/spawn-session-attach-proposal.test.ts +0 -47
- package/packages/shared/src/__tests__/state-replay-entry-id.test.ts +0 -69
- package/packages/shared/src/__tests__/state-replay-flow-events.test.ts +0 -100
- package/packages/shared/src/__tests__/sync-versions-spec.test.ts +0 -76
- package/packages/shared/src/__tests__/tags.test.ts +0 -65
- package/packages/shared/src/__tests__/tool-registry-definitions.test.ts +0 -453
- package/packages/shared/src/__tests__/tool-registry-overrides.test.ts +0 -137
- package/packages/shared/src/__tests__/tool-registry-registry.test.ts +0 -343
- package/packages/shared/src/__tests__/tool-registry-strategies-appimage.test.ts +0 -118
- package/packages/shared/src/__tests__/tunnel-concurrency.test.ts +0 -161
- package/packages/shared/src/__tests__/tunnel-config-migration.test.ts +0 -159
- package/packages/shared/src/__tests__/tunnel-provider.test.ts +0 -54
- package/packages/shared/src/__tests__/verify-lockfile-versions.test.ts +0 -130
- package/packages/shared/src/__tests__/virtualizer-drain-scope.test.ts +0 -81
- package/packages/shared/src/boot-state.ts.AGENTS.md +0 -3
- package/packages/shared/src/browser-protocol.ts.AGENTS.md +0 -7
- package/packages/shared/src/config.ts.AGENTS.md +0 -5
- package/packages/shared/src/credential-detect.ts.AGENTS.md +0 -3
- package/packages/shared/src/dashboard-paths.ts.AGENTS.md +0 -3
- package/packages/shared/src/dashboard-plugin/AGENTS.md +0 -14
- package/packages/shared/src/dashboard-starter.ts.AGENTS.md +0 -3
- package/packages/shared/src/diff-types.ts.AGENTS.md +0 -3
- package/packages/shared/src/display-prefs.ts.AGENTS.md +0 -3
- package/packages/shared/src/doctor-core.ts.AGENTS.md +0 -3
- package/packages/shared/src/file-kind.ts.AGENTS.md +0 -3
- package/packages/shared/src/git-worktree-helpers.ts.AGENTS.md +0 -3
- package/packages/shared/src/index.ts.AGENTS.md +0 -3
- package/packages/shared/src/legacy-managed-dir.ts.AGENTS.md +0 -3
- package/packages/shared/src/live-server.ts.AGENTS.md +0 -3
- package/packages/shared/src/managed-paths.ts.AGENTS.md +0 -3
- package/packages/shared/src/mdns-discovery.ts.AGENTS.md +0 -3
- package/packages/shared/src/model-id.ts.AGENTS.md +0 -3
- package/packages/shared/src/models-json-reader.ts.AGENTS.md +0 -3
- package/packages/shared/src/node-version.ts.AGENTS.md +0 -3
- package/packages/shared/src/notify.ts.AGENTS.md +0 -3
- package/packages/shared/src/openspec-activity-detector.ts.AGENTS.md +0 -5
- package/packages/shared/src/openspec-design-evidence.ts.AGENTS.md +0 -3
- package/packages/shared/src/openspec-poller.ts.AGENTS.md +0 -3
- package/packages/shared/src/openspec-specs-evidence.ts.AGENTS.md +0 -3
- package/packages/shared/src/pi-installs/AGENTS.md +0 -13
- package/packages/shared/src/pi-installs/__tests__/candidates.test.ts +0 -351
- package/packages/shared/src/pi-installs/__tests__/installs.test.ts +0 -113
- package/packages/shared/src/pi-package-resolver.ts.AGENTS.md +0 -3
- package/packages/shared/src/platform/AGENTS.md +0 -28
- package/packages/shared/src/platform/__tests__/openspec-profile-config.test.ts +0 -109
- package/packages/shared/src/platform/__tests__/openspec-runner-stripped-path.integration.test.ts +0 -127
- package/packages/shared/src/platform/__tests__/runner-spawn-env.test.ts +0 -59
- package/packages/shared/src/platform/__tests__/spawn-mechanism.test.ts +0 -57
- package/packages/shared/src/platform/git.ts.AGENTS.md +0 -19
- package/packages/shared/src/plugin-bridge-register.ts.AGENTS.md +0 -3
- package/packages/shared/src/protocol.ts.AGENTS.md +0 -6
- package/packages/shared/src/recommended-extensions.ts.AGENTS.md +0 -3
- package/packages/shared/src/recovery-timing.ts.AGENTS.md +0 -3
- package/packages/shared/src/rendezvous.ts.AGENTS.md +0 -13
- package/packages/shared/src/rest-api.ts.AGENTS.md +0 -3
- package/packages/shared/src/role-name-validation.ts.AGENTS.md +0 -3
- package/packages/shared/src/semaphore.ts.AGENTS.md +0 -3
- package/packages/shared/src/server-identity.ts.AGENTS.md +0 -3
- package/packages/shared/src/session-group-path.ts.AGENTS.md +0 -3
- package/packages/shared/src/session-meta.ts.AGENTS.md +0 -3
- package/packages/shared/src/skill-block-parser.ts.AGENTS.md +0 -3
- package/packages/shared/src/source-matching.ts.AGENTS.md +0 -3
- package/packages/shared/src/state-replay.ts.AGENTS.md +0 -3
- package/packages/shared/src/stats-extractor.ts.AGENTS.md +0 -3
- package/packages/shared/src/test-support/AGENTS.md +0 -8
- package/packages/shared/src/test-support/setup-home-perfile.ts +0 -50
- package/packages/shared/src/test-support/setup-home.ts +0 -74
- package/packages/shared/src/tool-registry/AGENTS.md +0 -12
- package/packages/shared/src/tool-registry/__tests__/bare-import-exports-map.test.ts +0 -77
- package/packages/shared/src/tool-registry/__tests__/bundled-git-bash-strategy.test.ts +0 -74
- package/packages/shared/src/tool-registry/__tests__/bundled-node-strategy.test.ts +0 -125
- package/packages/shared/src/tool-registry/__tests__/fixtures/strategies.pre-change.ts.txt +0 -480
- package/packages/shared/src/tool-registry/__tests__/install-hints.test.ts +0 -126
- package/packages/shared/src/tool-registry/__tests__/managed-runtime-strategy.test.ts +0 -166
- package/packages/shared/src/tool-registry/__tests__/node-electron-resolution.test.ts +0 -242
- package/packages/shared/src/tool-registry/__tests__/node-script-argv-matrix.test.ts +0 -157
- package/packages/shared/src/tool-registry/__tests__/node-script-toargv-fallback.test.ts +0 -84
- package/packages/shared/src/tool-registry/__tests__/openspec-unix-node-wrap.test.ts +0 -62
- package/packages/shared/src/tool-registry/__tests__/pi-ai-registration.test.ts +0 -130
- package/packages/shared/src/tool-registry/__tests__/resolver-order-preservation.test.ts +0 -305
- package/packages/shared/src/tunnel-provider.ts.AGENTS.md +0 -3
- package/packages/shared/src/types.ts.AGENTS.md +0 -5
- package/packages/shared/src/zrok-env.ts.AGENTS.md +0 -3
package/docs/architecture.md
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
# PI Dashboard Architecture
|
|
2
2
|
|
|
3
|
-
> **Adjacent artifact:**
|
|
4
|
-
> product-adjacent, not part of the dashboard runtime. It has its own Astro
|
|
5
|
-
> build, its own Playwright screenshot pipeline, and its own GitHub Pages
|
|
6
|
-
> deploy workflow (`.github/workflows/deploy-site.yml`). See
|
|
7
|
-
> `/site/README.md` for details.
|
|
3
|
+
> **Adjacent artifact:** public marketing site lives at `/site`. Product-adjacent, not part of dashboard runtime. No framework — one hand-written static page: `site/index.html`, `site/404.html`, `site/field.js` (three.js background), `site/vendor/`, `site/media/`. Zero dependencies. `npm run build -w site` = `node site/build.mjs`: copies explicit allowlist into `site/dist`, verifies every local ref in `index.html` resolves. Artifact path unchanged — `.github/workflows/deploy-site.yml` still uploads `site/dist`, copies `packages/shell` into `site/dist/app`. Release data (download URLs + byte sizes) inline in `index.html`; `site/design-scratch/scripts/sync-release.mjs` rewrites it from GitHub API on `release: published` (`.github/workflows/sync-release-version.yml`), commits to develop. `site/design-scratch/` = design source, not deployed (excluded from build allowlist + deploy push-path filter). Theme: System/Light/Dark modes, storage key `pi-theme`, inline `<head>` script resolves before first paint; dark = absence of `data-theme="light"`. See `/site/README.md` for details.
|
|
8
4
|
|
|
9
5
|
|
|
10
6
|
## Overview
|
|
@@ -45,7 +41,7 @@ Global pi extension running in every pi session. It:
|
|
|
45
41
|
Node.js HTTP + WebSocket server that:
|
|
46
42
|
- Accepts connections from bridge extensions (Pi Gateway, port 9999)
|
|
47
43
|
- Accepts connections from web browsers (Browser Gateway, port 8000)
|
|
48
|
-
- Stores events in an in-memory buffer with LRU eviction (
|
|
44
|
+
- Stores events in an in-memory buffer with LRU eviction (default 32 sessions via `memoryLimits.maxCachedSessions`; bounded by count and serialized byte budgets)
|
|
49
45
|
- Truncates large event payloads (tool results, file content, thinking blocks) to bound memory
|
|
50
46
|
- Applies WebSocket backpressure on browser connections (drops messages when send buffer > 4MB)
|
|
51
47
|
- Manages sessions in a pure in-memory registry (populated from bridge connections and direct disk discovery)
|
|
@@ -150,7 +146,7 @@ TypeScript type definitions shared across all components:
|
|
|
150
146
|
- **"Currently viewing" registry**: `viewed-session-tracker.ts` exposes `Map<sessionId, Set<WebSocket>>`. Browsers populate it via two new browser→server messages, `session_view` and `session_unview`, sent by the client hook `useViewDispatcher` (mounted in `App.tsx`). The hook watches the `/session/:id` route and the WebSocket connection status; on every transition INTO `connected` it re-sends `session_view` for the current id so server-side state re-syncs after reconnect. On WS `close`, the gateway calls `tracker.unviewAll(ws)` so disconnected browsers cannot hold sessions in the viewed state. Read state is GLOBAL across browsers (mirrors mail/Slack: opening on phone clears unread on laptop).
|
|
151
147
|
- **State transitions** in `event-wiring.ts`: right after the `extractSessionUpdates` block, the wiring snapshots `{status, currentTool}` before/after the update and calls `isUnreadTrigger`. If true AND `viewedSessionTracker.isViewedByAnyone(sessionId) === false` AND `!replayingSessions.has(sessionId)`, the wiring stamps `session.unread = true` and broadcasts `session_updated`. The browser-gateway's `session_view` arm clears the bit (`unread: false`) and broadcasts. The clear-on-already-read path is a no-op (no spurious broadcast).
|
|
152
148
|
- **Persistence**: the bit lives in `.meta.json` (`SessionMeta.unread`). `server.ts onChange` writes it on every session update; `session-scanner.ts::sessionFromMeta` restores it on cold start. The cold-start "force `status = ended`" override at `server.ts:273-279` is intentionally non-destructive on `unread` — a session that was unread when the server stopped is still unread when it starts back up, even before its bridge reattaches.
|
|
153
|
-
- **Render precedence** (`SessionCard.tsx::getCardPulseClass`): `ask_user` (purple) > `streaming || resuming` (yellow) > `unread` (cyan) > none. Streaming with `unread: true` shows yellow stripes; when streaming ends with the session still unviewed, the trigger fires, the card flips to cyan. The `card-unread-pulse` CSS class reuses the `card-working-stripes-scroll` and `card-working-opacity-pulse` keyframes verbatim — only the stripe and tint colors change to cool cyan (`rgba(34, 211, 238, 0.18)` and `rgba(34, 211, 238, 0.07)`). Cyan was selected to occupy its own corner of the dashboard palette (distant from yellow, purple, green, red). Reduced-motion users see a static cyan-tinted background, matching the working-pulse arm.
|
|
149
|
+
- **Render precedence** (`SessionCard.tsx::getCardPulseClass`): `ask_user` (purple) > `streaming || resuming` (yellow) > `unread` (cyan) > none. Streaming with `unread: true` shows yellow stripes; when streaming ends with the session still unviewed, the trigger fires, the card flips to cyan. The `card-unread-pulse` CSS class reuses the `card-working-stripes-scroll` and `card-working-opacity-pulse` keyframes verbatim — only the stripe and tint colors change to cool cyan (`rgba(34, 211, 238, 0.18)` and `rgba(34, 211, 238, 0.07)`). Cyan was selected to occupy its own corner of the dashboard palette (distant from yellow, purple, green, red). Reduced-motion users see a static cyan-tinted background, matching the working-pulse arm. Cyan now theme token `--status-unread` (dark `#22d3ee`, light `#0891b2`) in `index.css`; `.card-stripes-unread` uses `color-mix` of it (change: session-list-group-by).
|
|
154
150
|
|
|
155
151
|
**Attention routing & status semantics** (change: improve-dashboard-attention-routing):
|
|
156
152
|
- **Semantic status tokens.** `--status-needs-you` / `--status-working` / `--status-idle` / `--status-error` derive per-theme from accents (`var(--accent-purple/yellow/green/red)`). `themes.ts::statusVars` + `withStatus` merge into every theme dark+light; `index.css` `:root` defines base fallback. Session visuals reference tokens only — no raw palette literals.
|
|
@@ -158,7 +154,131 @@ TypeScript type definitions shared across all components:
|
|
|
158
154
|
- **Non-hue shape channel.** `deriveStatusShape` + `statusShapeIcon` map status to filled/half/ring/cross marker. `SessionCard.tsx::StatusShapeBadge` overlays marker on session-status-icon (`data-status-shape`). Color-blind-safe redundant encoding.
|
|
159
155
|
- **Label split.** `ActivityIndicator`: ask_user → "Needs you" (`--status-needs-you`); idle/active → "Idle" (muted). "Waiting for input" retired.
|
|
160
156
|
- **Folder status capsule** (change: unify-folder-status-capsule). `FolderStatusCapsule` = folder header's ONLY liveness surface. Renders in BOTH collapse states. Replaces `FolderNeedsYouPill` + collapsed-only `FolderStatusRollup` + raw `(N)` count — all DELETED, incl. `countStatusRollup`. Segments by `countStatusCapsule(sessions, flags)` (`packages/client/src/lib/session/session-status-visuals.ts`). Fixed severity order `CAPSULE_SEGMENT_ORDER` = needs-you > error > working > idle; magnitude never reorders. Zero-count segments absent; no countable sessions → no capsule at all (all-ended folder shows none; its `N ended` disclosure row still reports size). Excludes `ended` + `hidden` before shape derivation. `flags.widgetBar` tri-state `(id) => boolean | undefined`; `true` or `undefined` excludes that ask_user session from EVERY bucket. Still per-session `WidgetBarProbe` + `useHasWidgetBarPrompt`, now capsule-owned. needs-you uses explicit predicate, not `deriveStatusShape`; re-adds `!hasError` guard — errored ask_user counts once, as error. `notice` shape folds into `idle` bucket; retrying counts as `working`. Counts cap at `999+`. Non-idle segments = `<button>`s → first session of that state via `firstIds[bucket]`; idle = inert `<span>` + aria-label. Activation `stopPropagation()` → SessionList reveal path (`onSeekToCard` / `revealRequest`): inherits guarded expand, layout-settled scroll, hidden/filtered degrade toasts. Colors from `--status-*` family only, never `--severity-*`; no new CSS custom property. Capsule `flex-none` + `whitespace-nowrap`; sheds nothing; folder name absorbs width pressure. Test ids: `folder-status-capsule-<cwd>`, `folder-capsule-seg-{needs-you,error,working,idle}-<cwd>`.
|
|
161
|
-
- **
|
|
157
|
+
- **Urgency sort RETIRED** (change: session-list-group-by). `useFolderUrgencySort` + `floatAskUserFirst` deleted. Folder menu item `urgency-sort` removed. Superseded by Group by ▸ Status "Needs you" lane. One-shot client migration `runUrgencyMigration` (`packages/client/src/lib/session/group-by-migration.ts`) runs after first `group_by_prefs_updated`: each legacy `dashboard:folder-urgency-sort` folder without explicit mode → `set_folder_group_by {mode:"status"}`; explicit modes kept; localStorage key then removed.
|
|
158
|
+
|
|
159
|
+
**Session list Group by** (change: session-list-group-by):
|
|
160
|
+
- **Modes.** `GroupByMode` = `none` | `status` | `location` (`packages/shared/src/session-group-by.ts`). Per-folder override > `defaultGroupBy` > `none` (`resolveEffectiveGroupBy`, `pathKey` lookup).
|
|
161
|
+
- **Persistence.** `preferences.json` optional `defaultGroupBy`, `folderGroupBy: Record<pathKey, mode>`, `collapsedLanes: string[]` (`<pathKey>::<laneId>`). `preferences-store.ts`: `getGroupByPrefs`, `setFolderGroupBy(path, mode|null)`, `setDefaultGroupBy`, `setLaneCollapsed`. Validate enums. `pathKey`-canonicalize like `collapsedFolders`. Never realpath. Never prune. Return true only on real change.
|
|
162
|
+
- **Protocol.** Browser→server `set_folder_group_by {path, mode|null}` (null = use default), `set_default_group_by {mode}`, `set_lane_collapsed {path, lane, collapsed}`. Server→browser aggregate `group_by_prefs_updated {defaultGroupBy, folderGroupBy, collapsedLanes}`. Handlers `browser-handlers/directory-handler.ts` broadcast only on change. Connect burst: right after `collapsed_folders_updated`, before `pinned_dirs_updated` / `workspaces_updated` / `sessions_snapshot` → lanes on first paint. `frameClassOf` = `state`.
|
|
163
|
+
- **Lanes = client-only view** over unchanged `sessionOrder`. `partitionIntoLanes` stable partition via `sortSessionsByOrder` (`packages/client/src/lib/session/session-lanes.ts`). Status lane order `needs-you, error, working, review, idle`. `classifyStatusLane` wraps `deriveStatusShape`; compacting → working; unread idle / notice → review; ended → ended bucket. Location lanes `main` / `worktrees` (`gitWorktree` set).
|
|
164
|
+
- **Render rules.** `SessionList.tsx` `lanesForGroup` → null (plain list, unchanged DOM) when mode none, search/tag filter active, or ≤1 non-empty lane. One `SortableContext` per lane. `LaneHeader` (`components/session/LaneHeader.tsx`): glyph on rail; label never status-colored; collapsed location lane shows inert status rollup. Ended bucket stays plain below lanes. Per-folder layout cache keyed on mode + order + `laneFingerprint` → token/cost ticks never re-partition.
|
|
165
|
+
- **Drag.** `resolveLaneDrop`: same lane → slot-preserving `mergeLaneOrder` → `onReorderSessions`. Cross-lane → rejected + toast. Ended involved → legacy drag-to-resume path.
|
|
166
|
+
- **Stability.** `useLaneHysteresis` (`hooks/useLaneHysteresis.ts`) holds working→review/idle demotion 3000 ms (`LANE_HOLD_MS`). needs-you / error immediate. Held card shows `.lane-hold-bar` in destination lane color. `useFlipOnLaneChange` FLIP 220 ms; skipped under `prefers-reduced-motion` and during drag. Selected card lane change → polite `lane-live-region` announcement + `scrollIntoView`. Reveal expands collapsed target lane.
|
|
167
|
+
- **UI entry points.** Folder menu `radioGroup` (`FolderActionsMenu`, `role=menuitemradio`: Use default (<Mode>) / None / Status / Location). Header `GroupByChip` on secondary row (`<Mode>` / `<Mode> · default`). Settings ▸ Sessions ▸ Session list `DefaultGroupingField` (instant-apply WS, outside Save-bar draft).
|
|
168
|
+
- **Rollback.** Extra `preferences.json` keys ignored by old loader; dropped on next write.
|
|
169
|
+
|
|
170
|
+
### Bridge Streaming Coalescing (change: coalesce-bridge-message-update-snapshots)
|
|
171
|
+
|
|
172
|
+
**Problem.**
|
|
173
|
+
- pi `message_update` carries FULL accumulated text snapshot, not delta.
|
|
174
|
+
- Bridge forwarded every update synchronously on pi single-threaded loop.
|
|
175
|
+
- Paid `JSON.stringify` + `ws.send` per source token.
|
|
176
|
+
- Strings grow O(N) over N tokens → O(N²) bytes per turn; stalled host event loop.
|
|
177
|
+
|
|
178
|
+
**Mechanism & state machine.**
|
|
179
|
+
- File: `packages/extension/src/message-update-coalescer.ts`.
|
|
180
|
+
- Transport-agnostic single-slot state machine (`MessageUpdateCoalescer`).
|
|
181
|
+
- Bridge injects callbacks: `send`, `setTimer`, `clearTimer`, `isActive`.
|
|
182
|
+
- `COALESCE_WINDOW_MS = 50`.
|
|
183
|
+
- FIXED window anchored at FIRST pending update arrival.
|
|
184
|
+
- NOT debounce: continuous stream never gaps; debounce starves stream until `message_end`.
|
|
185
|
+
- Fixed window caps added latency at ≤ 50 ms non-cumulative.
|
|
186
|
+
- Last-wins single slot; stores live event reference; client takes cumulative latest snapshot.
|
|
187
|
+
|
|
188
|
+
**Family split (sub-event routing).**
|
|
189
|
+
- Text-carrying sub-events park: `text_start`, `text_delta`, `text_end`.
|
|
190
|
+
- Non-text sub-events bypass park: `thinking_start`, `thinking_delta`, `thinking_end`, `toolcall_start`, `toolcall_delta`, `toolcall_end`, `start`, and unknown types.
|
|
191
|
+
- Non-text handler flushes parked text snapshot first, then forwards immediately and unmodified.
|
|
192
|
+
- Preserves thinking deltas: thinking deltas ADDITIVE, not snapshots; coalescing drops tokens.
|
|
193
|
+
- Unknown sub-events fail-safe: pass through immediately to prevent swallowing additive extensions.
|
|
194
|
+
|
|
195
|
+
**Identity barrier.**
|
|
196
|
+
- Per-message generation counter `assistantMessageGen` in `bridge.ts`.
|
|
197
|
+
- Increments on EVERY `message_start` (user + assistant) across turns and retries.
|
|
198
|
+
- Key format: `${gen}:${role}:${timestamp}` via `messageKeyOf`.
|
|
199
|
+
- `message.id` unusable: pi assigns id post-handler during session persistence.
|
|
200
|
+
- `timestamp` required on `AssistantMessage`/`UserMessage`; fallback uses WeakMap object counter.
|
|
201
|
+
|
|
202
|
+
**Drop rule & fail-open lifecycle.**
|
|
203
|
+
- ONLY updates whose identity closed via `messageEnd` drop.
|
|
204
|
+
- Updates with unknown identity or no open message open new slot instead (fail-open).
|
|
205
|
+
- Guard: `npm run reload` re-initializes bridge mid-turn; dropping unknown identity silences active turn.
|
|
206
|
+
- Bounded FIFO (`CLOSED_KEY_MEMORY = 64`) retains closed keys.
|
|
207
|
+
|
|
208
|
+
**Flush choke points.**
|
|
209
|
+
- Entry choke point: enriched + pass-through loops call `if (flushesParkedText(eventType)) coalescer.flush()` at handler entry.
|
|
210
|
+
- Runs before ANY early return; prevents latent ordering bugs from new branches.
|
|
211
|
+
- Out-of-loop chat sinks flush explicitly: `wrapCustomPersistenceForCtx` (`appendCustomMessageEntry`, `appendCustomEntry`) and `sendSyntheticRetryEvent`.
|
|
212
|
+
- `message_end` flushes text before scheduling deferred id-stamping `setTimeout(0)`.
|
|
213
|
+
|
|
214
|
+
**Lifecycle & transport boundaries.**
|
|
215
|
+
- `onReconnect`: flushes pending text BEFORE `sendStateSync()` + replay. Reconnect = transport boundary; preserves in-flight turn tail, forbids post-replay delivery.
|
|
216
|
+
- Session change / `session_shutdown`: call `coalescer.clear()`. Session transition = state invalidation; discards parked snapshot, cancels window.
|
|
217
|
+
- Window timer registered in bridge registry (`prev.timers`); released on fire/clear to prevent leak across reload.
|
|
218
|
+
- Timer callback re-checks `isActive()` at fire time; prevents writing to closed socket after bridge teardown.
|
|
219
|
+
- Image inliner: `maybeInlineAssistantImages` runs inside `coalescer.send` callback; executes once per flushed window instead of once per token. Authoritative `message_end` inliner retained.
|
|
220
|
+
|
|
221
|
+
**Architectural boundary (scope).**
|
|
222
|
+
- Cuts BRIDGE forwarding cost only (`JSON.stringify` + wire transmission).
|
|
223
|
+
- Does NOT replace server fold (`live-event-frame-coalescing-fold`) or client batching (`chat-event-render-batching`).
|
|
224
|
+
- Downstream layers cut RENDER cost; bridge coalescer cuts WIRE/SERIALIZATION cost.
|
|
225
|
+
- Wire protocol format unchanged (`event_forward` message carrying `message_update`).
|
|
226
|
+
|
|
227
|
+
**Measured baseline & scaling.**
|
|
228
|
+
- Baseline (harness uncoalesced): 169 `message_update` frames, 616,534 bytes over 13.4 s stream = 12.6 deltas/s, 1:1 forward.
|
|
229
|
+
- Reduction factor: `max(1, sourceDeltasPerSecond ÷ 20)`.
|
|
230
|
+
- Win activates when provider emits > 20 deltas/s (< 50 ms delta interval). Real providers stream 1–4-token deltas at 20–150 tok/s (2.5×–7.5× reduction).
|
|
231
|
+
- `FAUX_TPS=50` chunks 3–5 tokens (~12.5 deltas/s); harness measures ~1× by design.
|
|
232
|
+
|
|
233
|
+
**References.**
|
|
234
|
+
- Spec: `openspec/specs/bridge-message-update-coalescing/spec.md`.
|
|
235
|
+
- Design decisions: `openspec/changes/archive/2026-09-19-coalesce-bridge-message-update-snapshots/design.md` (D1–D9).
|
|
236
|
+
- Unit tests: `packages/extension/src/__tests__/message-update-coalescer.test.ts`, `packages/extension/src/__tests__/bridge-coalesced-chat-order.test.ts`.
|
|
237
|
+
- E2E test: `tests/e2e/coalesced-streaming.spec.ts`.
|
|
238
|
+
|
|
239
|
+
### Bridge Event Forwarding Exclusions (change: filter-system-role-message-forwarding)
|
|
240
|
+
|
|
241
|
+
**Why.**
|
|
242
|
+
- pi `>= 0.86.0` makes system prompt + tool loadout transcript-backed.
|
|
243
|
+
- First request of a session persists a `role:"system"` message carrying every prompt `section` + full `toolsAdded` declaration list.
|
|
244
|
+
- Later prompt/tool changes persist further system messages.
|
|
245
|
+
- `pi-agent-core` `agent-loop.js` emits that message as a BACK-TO-BACK `message_start` + `message_end` pair (same object); bridge forwarded both.
|
|
246
|
+
- Measured ~150 KB per system message on a live 0.86.1 session.
|
|
247
|
+
- `session_compact.compactionEntry` carries the SAME prompt-sections + tool-declaration blob in `compactionEntry.systemMessage`, plus the compaction `summary`.
|
|
248
|
+
- `session_compact` had no dedicated bridge arm; it fell through to the shared forward tail and was serialized whole.
|
|
249
|
+
|
|
250
|
+
**What changed.**
|
|
251
|
+
- File: `packages/extension/src/bridge.ts`. Three sites.
|
|
252
|
+
- `message_start` arm: early-return when `event.message?.role === "system"`, placed immediately AFTER the existing `role === "custom"` return.
|
|
253
|
+
- `message_end` arm: same early-return, same placement.
|
|
254
|
+
- New exported helper `redactCompactionEntry(event)` in `packages/extension/src/event-forwarder.ts`: returns a shallow COPY of the event with `compactionEntry` deleted.
|
|
255
|
+
- Bridge applies it on the shared tail only for `session_compact`: `const forwardEvent = eventType === "session_compact" ? redactCompactionEntry(event as Record<string, unknown>) : event;` before `mapEventToProtocol`.
|
|
256
|
+
- No version gate: pi `< 0.86` never emits the role; field omission is safe wherever the field is absent.
|
|
257
|
+
- `assistantMessageGen` comment in `bridge.ts` widened from "(user and assistant)" to include the barrier-only `system` start.
|
|
258
|
+
|
|
259
|
+
**Placement (why after the barrier).**
|
|
260
|
+
- Both returns sit AFTER the coalescing barrier (`assistantMessageGen += 1;` + `coalescer.messageStart(...)` / `coalescer.messageEnd(...)`).
|
|
261
|
+
- Barrier contract unchanged.
|
|
262
|
+
- Entry-level flush choke point (`if (flushesParkedText(eventType)) coalescer.flush()` at handler entry) still runs first.
|
|
263
|
+
- Placement is a consistency choice, not behavioural; the parked-snapshot ordering guarantee belongs to the entry choke point.
|
|
264
|
+
|
|
265
|
+
**Redaction on a copy.**
|
|
266
|
+
- Copy, never mutate: pi hands the SAME event object to every subscribed extension.
|
|
267
|
+
- Generic `mapEventToProtocol` stays generic.
|
|
268
|
+
|
|
269
|
+
**Why safe (no consumer).**
|
|
270
|
+
- Client `session_compact` arm (`packages/client/src/lib/chat/event-reducer.ts`) reads only `reason`, `willRetry`, `estimatedPostCompactionTokens`; renders the compaction divider from the event's presence.
|
|
271
|
+
- Server uses the event only to clear the `compacting` latch (`packages/server/src/session/event-status-extraction.ts`).
|
|
272
|
+
- Replay path already synthesizes a metadata-free `session_compact` (`packages/shared/src/state-replay.ts`).
|
|
273
|
+
- Live-vs-replay parity is defined on event type/position/timestamp only; this change does not alter that contract.
|
|
274
|
+
|
|
275
|
+
**Accepted trade-offs.**
|
|
276
|
+
- Sessions that already persisted system events are not evicted (forward-only); they replay until normal rotation removes them.
|
|
277
|
+
|
|
278
|
+
**References.**
|
|
279
|
+
- Design: `openspec/changes/filter-system-role-message-forwarding/` (D2/D6/D7).
|
|
280
|
+
- Spec delta: `openspec/changes/filter-system-role-message-forwarding/specs/catch-all-event-forwarding/spec.md`.
|
|
281
|
+
- Tests: `packages/extension/src/__tests__/bridge-coalesced-chat-order.test.ts`, `packages/extension/src/__tests__/event-forwarder.test.ts`.
|
|
162
282
|
|
|
163
283
|
### EventBus Forwarding Mechanism (subscription-based, change: fix-automation-run-lifecycle)
|
|
164
284
|
|
|
@@ -315,6 +435,70 @@ TypeScript type definitions shared across all components:
|
|
|
315
435
|
- Evicted or post-reset agents answer `resyncNoop`.
|
|
316
436
|
- Client keeps its last rendered state.
|
|
317
437
|
|
|
438
|
+
### Subagent Fan-out Admission (change: bound-subagent-fanout-under-host-pressure)
|
|
439
|
+
|
|
440
|
+
**Problem.**
|
|
441
|
+
|
|
442
|
+
- Wide `Agent` fan-out on loaded host stalls parent event loop.
|
|
443
|
+
- 13/14 census sessions died with unanswered fan-out as final transcript entry.
|
|
444
|
+
- Stall triggers `hostPressure` unresponsive verdict; host reaps parent process.
|
|
445
|
+
|
|
446
|
+
**Registration and ordering.**
|
|
447
|
+
|
|
448
|
+
- Bridge registers admission gate on `tool_call` (`packages/extension/src/subagent-fanout-admission.ts`).
|
|
449
|
+
- Registered AFTER pass-through forwarder in `bridge.ts`.
|
|
450
|
+
- `runner.emitToolCall` stops at first `{block: true}` handler.
|
|
451
|
+
- Earlier registration starves forwarder; dashboard misses `tool_call` while seeing `tool_execution_end`. Order load-bearing.
|
|
452
|
+
|
|
453
|
+
**Concurrency bound.**
|
|
454
|
+
|
|
455
|
+
- Bound measures in-flight concurrency per session, not batch width.
|
|
456
|
+
- Platform drops assistant message before extension sees `tool_call`; batch size and batch identity unknowable.
|
|
457
|
+
- In-flight counter increments at admission, not execution.
|
|
458
|
+
- Siblings preflight sequentially before any executes; execution-time counter reads zero across whole batch.
|
|
459
|
+
- Synchronous reject-only decision. Gate never awaits child; awaiting deadlocks preflight sequence.
|
|
460
|
+
|
|
461
|
+
**Configuration.**
|
|
462
|
+
|
|
463
|
+
- Default cap: `DEFAULT_MAX_CONCURRENT_SUBAGENTS = 2` (`packages/shared/src/config.ts`).
|
|
464
|
+
- Config key: `maxConcurrentSubagents`.
|
|
465
|
+
- Value `0` disables gate (rollback).
|
|
466
|
+
- Absent value resolves to active default (2).
|
|
467
|
+
- Malformed non-integer or negative value resolves to `Infinity` (fail-open).
|
|
468
|
+
|
|
469
|
+
**Resource saturation.**
|
|
470
|
+
|
|
471
|
+
- Saturation narrows effective cap to 1 (never 0); saturated session still makes progress.
|
|
472
|
+
- Private sampler: `subagent-saturation.ts`.
|
|
473
|
+
- Dedicated `monitorEventLoopDelay` over fixed 5 s window plus own CPU baseline.
|
|
474
|
+
- Never reads `collectMetrics()`: destructive read resets 15 s heartbeat histogram, corrupting crash telemetry.
|
|
475
|
+
- Separates process domain (`process.cpuUsage()`, event loop delay) from machine domain (`os.loadavg()`).
|
|
476
|
+
- Hysteresis: enter at threshold, exit only when all metrics fall below 80 % of threshold (`SATURATION_EXIT_RATIO = 0.8`).
|
|
477
|
+
|
|
478
|
+
**Permit release.**
|
|
479
|
+
|
|
480
|
+
- Releases permit on `tool_execution_end`.
|
|
481
|
+
- Fires on normal, blocked, and aborted execution paths.
|
|
482
|
+
- Never releases on `tool_result`: aborted call (Esc) skips result hook, leaking permits and starving session.
|
|
483
|
+
|
|
484
|
+
**Refusal semantics.**
|
|
485
|
+
|
|
486
|
+
- Refusal returns `{block: true, reason}`.
|
|
487
|
+
- Produces real errored tool result; renders terminal card with actionable retry reason.
|
|
488
|
+
- Never sets `terminate`: refusal means re-issue later, not session abort.
|
|
489
|
+
|
|
490
|
+
**Observability and durability.**
|
|
491
|
+
|
|
492
|
+
- Refusal writes durable session entry `subagent-admission-refused` via `pi.appendEntry`. Survives process reap.
|
|
493
|
+
- Admissions skip disk writes to protect hot path.
|
|
494
|
+
- Live counters on `ProcessMetrics`: `fanoutAdmitted`, `fanoutRefused`, `fanoutSaturationRefused`.
|
|
495
|
+
|
|
496
|
+
**Scope boundary.**
|
|
497
|
+
|
|
498
|
+
- Gate runs per gated session, not per host process.
|
|
499
|
+
- Subagent sessions skip bridge initialization via re-entry guard.
|
|
500
|
+
- Grandchildren and `flow_agents` run ungated.
|
|
501
|
+
|
|
318
502
|
### Retry Lifecycle (change: retry-forever-with-stop-control)
|
|
319
503
|
|
|
320
504
|
Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts fire sequentially; each produces ONE complete `agent_start` … `agent_end` event cycle. Final attempt produces ONE `agent_settled` event terminal marker.
|
|
@@ -337,6 +521,7 @@ Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts f
|
|
|
337
521
|
- `agent_settled` carries NO `messages` (verified pi 0.81.1/0.83), so tracker remembers terminal disposition via `lastEndWasError` at `agent_end`.
|
|
338
522
|
- `-1` sentinels REMOVED. `maxAttempts` / `delayMs` sourced read-only from pi settings via `packages/extension/src/pi-retry-settings.ts` (defaults 3 / 2000; unreadable → `delayMs: 0` → surface renders elapsed-only).
|
|
339
523
|
- pi 0.83 exposes retry lifecycle events to RPC/SDK consumers ONLY. ExtensionAPI has no `auto_retry_*` and nothing on EventBus. `willRetry` in 0.83 is compaction-only (`session_before_compact`/`session_compact`). Bridge is extension → must observe-synthesize.
|
|
524
|
+
- Native `agent_settled` guaranteed at the 1.0.0 lockstep floor (`piCompatibility.minimum == recommended == 1.0.0`). Bridge consumes the native settle unconditionally — no version gate, no floor-pi synthesis. Floor-pi synthesis module `packages/extension/src/agent-settled.ts` DELETED. `agent_settled` remains the SOLE terminal retry signal. See change: update-pi-core-0-85-adopt-apis.
|
|
340
525
|
|
|
341
526
|
**3. Settings write + reload-on-save** (`packages/server/src/pi-agent-settings.ts`).
|
|
342
527
|
|
|
@@ -408,6 +593,109 @@ Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts f
|
|
|
408
593
|
- **Page refresh**: Server replays pending `prompt_request` messages when a browser subscribes. Client deduplicates by `requestId` or pending title match.
|
|
409
594
|
- **Bridge reconnect**: Bridge replays pending PromptBus requests on WebSocket reconnect so dashboard dialogs survive server restarts.
|
|
410
595
|
|
|
596
|
+
### Pending-Prompt Recovery (change: fix-pending-prompt-lost-on-replay)
|
|
597
|
+
|
|
598
|
+
A live `ask_user` prompt could go permanently invisible: the server held it, the browser never rendered it, and neither Refresh nor reload recovered it. Two independent defects — a frame shed on a saturated socket, and client state wiped by a replay rebuild.
|
|
599
|
+
|
|
600
|
+
**Critical-frame delivery (server).** `replayPendingUiRequests` runs in the replay-completion callback, so the tiny `prompt_request` frame lands on a socket the just-finished full replay saturated; `sendTo` silently drops any frame while `ws.bufferedAmount > MAX_WS_BUFFER` (4 MB default). The pending-*prompt* leg now sends under a `critical` frame class, exempt from that shed, bounded twice (`packages/server/src/pairing/browser-gateway.ts`):
|
|
601
|
+
- per-delivery cap: **4 frames** (`CRITICAL_FRAMES_PER_DELIVERY`)
|
|
602
|
+
- absolute ceiling: **`MAX_WS_BUFFER` + 1 MB**
|
|
603
|
+
|
|
604
|
+
Past either bound the frame is dropped and counted as a **blocking** drop; the dead `extension_ui_request` leg and `replayNotifyLog` stay fully guarded. `getDroppedFrameStats()` reports transcript drops under `total`/`bySession` (back-compat) and blocking drops under `blocking: { total, bySession }` → `/api/health#droppedFrames.serverToBrowser`.
|
|
605
|
+
|
|
606
|
+
**Resync round trip.** `prompt_resync_request` asks the bridge to re-emit every prompt its PromptBus still holds — the bridge's pending set, never the server's derived registry.
|
|
607
|
+
|
|
608
|
+
```mermaid
|
|
609
|
+
sequenceDiagram
|
|
610
|
+
participant B as Browser
|
|
611
|
+
participant S as Server
|
|
612
|
+
participant X as Bridge (PromptBus)
|
|
613
|
+
B->>S: prompt_resync_request {sessionId, requestId}
|
|
614
|
+
S->>S: record requester (ResyncRequesterRegistry, TTL 30s)
|
|
615
|
+
S->>X: prompt_resync_request {sessionId, requestId}
|
|
616
|
+
X->>S: prompt_request ×N, each with __resyncRequestId
|
|
617
|
+
S->>S: keep all prompt side effects (track, currentTool, unread, order)
|
|
618
|
+
S->>B: critical prompt_request to the recorded socket (non-consuming peek)
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
- Requester lookup is **non-consuming** (`peek`) so every prompt of a multi-prompt reply routes to the same socket, not just the first.
|
|
622
|
+
- `deliverPromptResyncReply` unicasts to the requester as a critical frame; unknown/expired token, requester gone, or no bridge → ordinary fan-out (or drop). Mid-replay requesters are NOT suppressed.
|
|
623
|
+
- Bridge: `emitPendingPrompts` (`packages/extension/src/pending-prompt-emitter.ts`) is the ONE emitter shared by `onReconnect` and the resync handler.
|
|
624
|
+
|
|
625
|
+
**Client state carry.** `carryInteractiveRequests` (`packages/client/src/lib/chat/event-reducer.ts`) preserves `pending` interactive requests **and** their paired `ui-<requestId>` rows across all FIVE reset sites: `useMessageHandler` `event_replay` + `session_state_reset`; `useSessionState` `applyReplay` + `session_state_reset`; the refresh reset in `App.tsx`. `retailPendingInteractiveRows` re-appends those rows at the tail after EVERY replay batch — a multi-batch full replay otherwise folds later transcript rows after the carried dialog, burying it mid-transcript (virtualized off-screen) while its entry keeps the desync detector suppressed.
|
|
626
|
+
|
|
627
|
+
**Refresh + desync affordance.** `refreshChat` fires `prompt_resync_request` unconditionally, failure-isolated from the transcript refresh. When the session reports `currentTool === "ask_user"` but the client holds no pending request — not ended, no replay in flight, held ≥ `PROMPT_DESYNC_GRACE_MS` (5 s) — the `prompt-desync-resync` pill (`packages/client/src/lib/session/prompt-desync.ts`, rendered in `ChatView`) surfaces and fires the same resync.
|
|
628
|
+
|
|
629
|
+
See change: `fix-pending-prompt-lost-on-replay`.
|
|
630
|
+
|
|
631
|
+
### Frame delivery policy (changes: fix-connect-snapshot-frame-loss, close-registry-frame-shed-gaps)
|
|
632
|
+
|
|
633
|
+
Every server→browser frame carries exactly one delivery class. `frameClassOf(msg) -> { cls, key }` (`packages/server/src/pairing/browser-gateway.ts`) — static `switch` on `msg.type`, never on socket condition. No `cls` field on the wire (server concern; old bundles untouched).
|
|
634
|
+
|
|
635
|
+
- **`transcript`** — per-session event stream + session-registry broadcasts (`session_updated`, `session_added`, `session_removed`). Recoverable via history backfill / replay.
|
|
636
|
+
- **`blocking`** — pending-prompt frames only (`ctx.critical === true`). Exempt from shed under pending-prompt-recovery bounds (4 frames/delivery, `MAX_WS_BUFFER + 1 MB` ceiling). Unchanged.
|
|
637
|
+
- **`state`** — idempotent snapshots keyed by `(type, entityKey)`: `sessions_snapshot`, `pinned_dirs_updated`, `workspaces_updated`, `card_sections_updated`, `favorite_models_updated`, `display_prefs_updated`, `reachability_updated`, `openspec_update` / `openspec_get_result` / `git_head_update` / `sessions_page_result` / `sessions_reordered` (key `cwd`, `sessions_reordered:<cwd>`), `terminal_added` / `terminal_updated` / `terminal_removed` (one shared key `terminal:<id>` per terminal, later lifecycle frame supersedes earlier). `sessions_reordered` is already a window-projected FULL per-cwd ordering snapshot at the `broadcast()` choke point, so per-cwd latest-wins is exact; deferred under back-pressure, never shed.
|
|
638
|
+
|
|
639
|
+
**Shed rule per class.** Socket over threshold (`ws.bufferedAmount > MAX_WS_BUFFER`, 4 MB default): `transcript` frame dropped + counted (pre-change counters `total`/`bySession`); `state` frame NEVER shed — deferred; `blocking` exempt within bounds. Transcript sends first flush the socket's pending map — a flushable state frame is never overtaken by a later transcript frame.
|
|
640
|
+
|
|
641
|
+
**State deferral.** Per-socket side-table `pendingState: Map<WebSocket, { map: Map<key, serialized>, bytes, timer }>` (distinct from `subscriptions`). `sendState(ws, key, serialized)` sends inline when socket under threshold + map empty, else defers. Latest-wins per type-qualified key — newer frame replaces older, superseded entry counted `coalescedState`. Map total bytes over `MAX_WS_BUFFER` → `ws.terminate()`, counted `stalledSocketsTerminated` (browser reconnect path re-bootstraps; retained bytes released). Flush in key-insertion order (FIFO; superseded key keeps its slot — state never overtakes earlier pending state), triggered BOTH by send-callback re-flush AND `setInterval(flush, STATE_FLUSH_INTERVAL_MS = 250 ms)` while map non-empty (drain without further sends still flushes). `close`/`error` clears map + timer. Every state-class send routes through `sendState` — `fanout`/`broadcast`, connect bootstrap, handler unicasts; `sendTo` dispatches on `frameClassOf`, so a handler cannot route a state frame onto the shedding path.
|
|
642
|
+
|
|
643
|
+
**Connect bootstrap order.** `sessions_snapshot` last — after `terminal_added` loop and `gateway.onConnect(ws)`. Every other bootstrap frame (`pinned_dirs_updated`, `workspaces_updated`, `card_sections_updated` (always, incl. `{}`), `favorite_models_updated`, `display_prefs_updated`, `reachability_updated`, per-cwd `openspec_update`, per-cwd `git_head_update`, `terminal_added`) precedes it. No session-registry send before `sessions_snapshot`.
|
|
644
|
+
|
|
645
|
+
**Health.** `/api/health#droppedFrames` gains `coalescedState` (superseded pending entries) + `stalledSocketsTerminated` beside transcript/blocking counters. No dropped-state counter — no code path drops one. Coalesce ≠ drop: `total` does not increment. Accepted counter shift: shed reorders move from `droppedFrames.total` to `coalescedState`.
|
|
646
|
+
|
|
647
|
+
### Status reconcile — shed session-registry frame is a debt (changes: fix-backpressure-status-and-subagent-frames, close-registry-frame-shed-gaps)
|
|
648
|
+
|
|
649
|
+
`session_updated`, `session_added`, and `session_removed` stay transcript-class. Carry no seq. No backfill answers them. No successor frame guaranteed. Long tool call emits status once, or session spawns/ends during saturation — shed registry frame leaves browser state unbounded-stale until reconnect/reload. Server treats shed session-registry frame as **debt owed to that socket**. `sessions_reordered` is `state`-class, never shed, needs no debt.
|
|
650
|
+
|
|
651
|
+
**Debt shape.** Per-socket `statusDebt: Map<WebSocket, { entries: Map<string, { kind: "updated" | "added" | "removed", spawnRequestId?: string, sawAdd: boolean }>, timer }>`. Identifiers + kind tag + boolean + at most one short correlation id. Still zero payload bytes; cannot reach pending-state byte ceiling; cannot move `stalledSocketsTerminated`.
|
|
652
|
+
|
|
653
|
+
**Debt capture.** `broadcast()` derives delivery info (`id`, `kind`, `spawnRequestId`) via `deliveryInfoOf(msg)`. `session_added` carries id at `msg.session.id` (NOT top-level `msg.sessionId`), so shared `deliveryInfoOf` derivation must not read `msg.sessionId` blindly. Shed site records entry in `statusDebt.entries`.
|
|
654
|
+
|
|
655
|
+
**Kind precedence.** Last-write-wins across lifecycle kinds `added` / `removed`; newly recorded `updated` overwrites existing `updated`, never downgrades pending `added` or `removed`. `sawAdd` set when `added` recorded; survives supersede by `removed` (preserves memory that browser never received creation); shed `session_added`'s `spawnRequestId` also survives supersede by `removed` (`sawAdd`-branch reconcile clears matching spawn placeholder instead of waiting for timeout).
|
|
656
|
+
|
|
657
|
+
**Own timer.** `STATUS_RECONCILE_INTERVAL_MS = 250`, started when entries map becomes non-empty, stopped when it empties. Deliberately NOT pending-state interval: that one exists only when *state* frame defers, and socket saturated purely by transcript traffic never creates it.
|
|
658
|
+
|
|
659
|
+
**Flush dispatch order.** `flushStatusDebt(ws)` rebuilds from CURRENT server state while socket is under threshold:
|
|
660
|
+
1. Owed `removed`, record `s = sessionManager.get(id)` absent → send `session_removed {sessionId}`.
|
|
661
|
+
2. Owed `removed`, `s.status !== "ended"` → re-registered after removal, removal superseded → send `session_added {session: s, reconciled: true}`.
|
|
662
|
+
3. Owed `removed`, `s.status === "ended"`, `sawAdd: true` → creation and ending both shed, browser holds no row → send `session_added {session: s, reconciled: true, spawnRequestId?}` carrying ended record (creation and ending both shed; renders in ended tier).
|
|
663
|
+
4. Owed `removed`, `s.status === "ended"`, `!sawAdd` → browser holds row, removal stands → send `session_removed {sessionId}`.
|
|
664
|
+
5. Otherwise record `!s` → send `session_removed {sessionId}`.
|
|
665
|
+
6. Otherwise owed `added` → send `session_added {session: s, spawnRequestId?, reconciled: true}`.
|
|
666
|
+
7. Otherwise owed `updated` → send `session_updated {status, currentTool, hostPressure}`. Both optional fields use `null`, never `undefined`, as clearing value (`?? null` preserves fix from `fix-false-unresponsive-badge`).
|
|
667
|
+
Status-based dispatch rests on invariant: `register()` is only path to non-ended record.
|
|
668
|
+
|
|
669
|
+
**Lifecycle clear and self-healing.** Delivered lifecycle frame (`session_added`, `session_removed`) clears socket's debt for that id (delivered frame is socket's current truth). Delivered `session_updated` is partial; does NOT clear. Reconcile sends via `sendTo`; `sendTo` shed site re-records SAME kind (all three kinds, `sendTo` shed site widened) — self-healing, eventually-delivered. Reconcile carries CURRENT value; intermediate transitions within single flood window not recovered.
|
|
670
|
+
|
|
671
|
+
**Client handling (`reconciled: true`).** Additive flag on `session_added`. Reconciled payload carries server's authoritative full current record: client replaces server-owned fields; absent `currentTool`/`hostPressure` clears on re-registered row (plain merge retains previous incarnation's stale value). Client carries over only client-local fields server record does not own: `resuming`, `closing`, `assets`. Add flipping held ended row to non-ended status (owed removal superseded by re-registration) removes group `endedTotals` contribution (prevents stale count; expander never offers page that cannot fill). On `reconciled: true`, client clears spawn placeholder and consumes pending spawn ONLY on exact `spawnRequestId` match (no match → touches no spawn state; prevents clearing unrelated concurrent user spawn in same cwd). Client navigates on NO tier (`reconciled: true` suppresses exact-match, cwd fallback, worktree fallback).
|
|
672
|
+
|
|
673
|
+
**Teardown.** Map + timer released on socket `close`, on socket `error`, and on `sendState` stalled-socket `ws.terminate()` path.
|
|
674
|
+
|
|
675
|
+
**Scope.** `session_updated`, `session_added`, `session_removed`. `sessions_reordered` is `state`-class, never shed, needs no debt.
|
|
676
|
+
|
|
677
|
+
**Health.** `/api/health#droppedFrames` counters `statusReconcileQueued` (entries recorded owed) + `statusReconcileSent` (reconcile frames re-sent) count every registry kind. No new `/api/health` field. Accepted health-counter shift: shed reorders move from `droppedFrames.total` to `coalescedState`. `/api/health#socketBufferOccupancy` = `{ max, p95, msAboveThreshold }` over browser-socket `bufferedAmount`; typed-zero fallback `EMPTY_SOCKET_BUFFER_OCCUPANCY`. Sampled at the send-decision sites, which already read `bufferedAmount` for the shed predicate — **not** on a timer. A periodic sampler was implemented first and rejected: it breaks the "zero timers on an unsaturated socket" invariant (`browser-gateway-critical-frames` P3/E9). Time-above-threshold uses a per-socket entry/exit span (`occupancyAboveSince`); the hot exit branch is gated on `size > 0`.
|
|
678
|
+
|
|
679
|
+
**`msAboveThreshold` is OBSERVATION-based, not continuous wall-clock.** Sampling happens at send decisions, so a crossing that starts and ends between two decisions is never observed, and a reported duration is bounded by the samples that delimit it. `getSocketBufferOccupancy()` adds spans still open at read time (else an in-progress stall reports 0), and SETTLES a span whose socket has since drained or closed — without that, an event-driven sampler leaves such a span open forever and it grows on every health read (unbounded over-report). Settling deletes the entry, so a later exit cannot accrue it twice.
|
|
680
|
+
|
|
681
|
+
**Test-only injector.** `POST /api/test/force-shed { enabled }` forces transcript-class frames to shed while leaving `bufferedAmount` untouched. Registered ONLY under `PI_E2E_FORCE_SHED=1` (set in `docker/compose.test.yml`, never a real image); still `networkGuard`-gated. Returns the effective state, so an unflagged server reports refusal instead of a silent no-op. Exists because real saturation is a browser failing to drain its own socket, which Playwright cannot induce. Drives `tests/e2e/status-reconcile.spec.ts`.
|
|
682
|
+
|
|
683
|
+
### Sessions snapshot window + paging (changes: fix-connect-snapshot-frame-loss, close-registry-frame-shed-gaps)
|
|
684
|
+
|
|
685
|
+
On browser connect, gateway emits ONE `sessions_snapshot { sessions, orders, endedTotals }` — replaces per-session `session_added` / per-cwd `sessions_reordered` bootstrap loops; sent LAST (see Frame delivery policy). Live updates after snapshot keep incremental `session_added` / `session_updated` / `session_removed` / `sessions_reordered`.
|
|
686
|
+
|
|
687
|
+
- **Window.** `snapshotVisibleIds(pinned)` (`packages/server/src/session/memory-session-manager.ts`) = all non-ended sessions ∪ `SNAPSHOT_ENDED_GLOBAL = 120` newest ended overall (by `endedAt ?? lastActivityAt ?? startedAt` desc, id tiebreak) ∪ first `SNAPSHOT_ENDED_PER_GROUP = 3` of `endedSequence(g)` for each group with a non-ended session or pinned.
|
|
688
|
+
- **Group key.** `resolveOrderKey(session)` (`packages/server/src/session/resolve-order-key.ts`): pin > `gitWorktree.mainPath` > `cwd`. Same key sidebar groups/orders by (`resolveSessionGroupPath`, `session-grouping.ts`). `orders` keys, `endedTotals` keys, `sessions_page.cwd` carry this key — worktree session counts within parent group.
|
|
689
|
+
- **Ended sequence.** `endedSequence(groupKey)` = persisted order restricted to ended ids, then ended ids without persisted position by `startedAt` desc — matches client `sortSessionsByOrder` render order.
|
|
690
|
+
- **`endedTotals`.** Ended count per group key regardless of window, every group with ≥1 ended session.
|
|
691
|
+
- **Row slimming.** Snapshot + page rows stripped via `stripNotifyLog` — `notifyLog` replayed on subscribe (`replayNotifyLog`).
|
|
692
|
+
- **Live reorder projection.** `sessions_reordered` broadcast rewritten through the window at the `broadcast()` choke point (`projectOrderThroughWindow` → `snapshotVisibleIds`); all broadcast sites covered, none touched individually.
|
|
693
|
+
- **Bound.** Snapshot ≤ 400 KB at 25 live + 4,000 ended / 400 groups / 20 pinned — L1 bound test pins it; row-shape growth fails loudly.
|
|
694
|
+
- **Paging.** `sessions_page { cwd: groupKey, offset }` served from in-memory registry (`packages/server/src/browser-handlers/session-meta-handler.ts`, `SESSIONS_PAGE_SIZE = 50`); `pageable(g)` = `endedSequence(g)` minus window ids; reply `sessions_page_result { cwd, sessions, order, hasMore }` unicast (state class, key `sessions_page_result:<g>`), rows `stripNotifyLog`, `order` = page ids in sequence order.
|
|
695
|
+
- **Client merge semantics.** Snapshot REPLACES `sessions` + `sessionOrderMap` atomically (paged rows discarded on reconnect — documented trade-off); `sessions_page_result` merges — sessions overwrite by id, order appends after current with held ids deduped. Stub group renders for any group key with `endedTotals > 0` and no held session (header + ended expander only); expander / "more" click pages while `heldEnded < endedTotal`; one in-flight `sessions_page` per cwd: in-flight mark released on ANY `sessions_page_result` for cwd via per-group reply generation `pageReplyGen` (incl. empty reply), plus 15 s timeout and socket-open reset. `hasMore: false` reply marks group `pageExhausted` — hides "more" affordance and suppresses `sessions_page` until `endedTotals` for that group changes by ANY path (ended transition, removal, archive, `session_added` of not-previously-held ended session, snapshot); snapshot clears it unconditionally (snapshot also resets offset). Both marks keyed in same group-key space as `endedTotals`.
|
|
696
|
+
|
|
697
|
+
See change: `fix-connect-snapshot-frame-loss`.
|
|
698
|
+
|
|
411
699
|
### Notify Flow (`ctx.ui.notify` → browser, split from prompt_request)
|
|
412
700
|
|
|
413
701
|
Change: `split-notify-from-prompt-request`. `ctx.ui.notify` used to ship over `prompt_request`. Every consumer treated it as an unanswered ask → `trackPromptRequest` → `currentTool="ask_user"` re-armed on every quiescent moment → permanent "Needs you", false unread, `questionFirst` reorder, and a session the embed-lifecycle reaper could never reclaim. Now a dedicated `notify` message type end to end.
|
|
@@ -431,8 +719,86 @@ Change: `split-notify-from-prompt-request`. `ctx.ui.notify` used to ship over `p
|
|
|
431
719
|
|
|
432
720
|
**Accepted skew:** old client + new server resolves on reload (client ships with the server). Old server + new bridge drops the notification for the skew window — no catch-all forward, no version handshake; accepted, bounded.
|
|
433
721
|
|
|
722
|
+
**Emit time, ordering, collapse** (change: `collapse-and-order-notify-rows`):
|
|
723
|
+
|
|
724
|
+
- Bridge `createNotifyProxy` (`packages/extension/src/notify-proxy.ts`) stamps `ts: Date.now()` — bridge clock = transcript-event clock.
|
|
725
|
+
- Server `handleNotify` (`packages/server/src/event-wiring.ts`) keeps bridge `ts` only when finite number > 0 (`isValidNotifyTs`); else stamps receipt `Date.now()`. Covers live `notify`, legacy `fromLegacyPromptRequest`, server-created notices. Every logged `NotifyLogEntry` + browser `notify` carries `ts`.
|
|
726
|
+
- `ts` persists in `.meta.json` notify log; `replayNotifyLog` forwards it; pre-change entries replay without `ts`.
|
|
727
|
+
- Client `addNotify(state, notifyId, message, level?, ts?)`: `ts` → row `timestamp = ts`, placed by pure `insertByTs` — scan `messages` from end in array order, skip `historyGap`, insert after first row with `timestamp <= ts`; none → before first non-gap row; no non-gap row → append. No `ts` → tail append, client `Date.now()`. Dedup by `notifyId` unchanged.
|
|
728
|
+
- History-backfill splice (`useMessageHandler.ts`) → `reseatTimedNotifies` re-places ts-placed notify rows, ascending `ts`.
|
|
729
|
+
- `collapseRepeatedNotifies` (`packages/client/src/lib/chat/collapse-repeated-notifies.ts`) runs last inside ChatView `displayRows` memo, after `notifyMinLevel` gate. ≥2 adjacent notify rows, same normalized level + same non-empty rendered text → one row, first member `id` kept, `args.params.repeat = {count, firstTs, lastTs}`. State untouched.
|
|
730
|
+
- `NotifyRenderer` renders `repeat.count > 1` as `×N` badge + first–last range (`Intl.DateTimeFormat`, UI language, short date across days) + aria-label; keys `common.notifyRepeat.badge` / `.label`. Timestamp outside JS `Date` range (`isDateTs`) → omit first–last range, label key `common.notifyRepeat.labelNoRange` — `Intl` would throw.
|
|
731
|
+
- Trade-off: live mid-turn notify re-tailed by `reorderToolCardsForAssistantMessage`; replay places by `ts` → may shift within own assistant turn, never across turns.
|
|
732
|
+
|
|
434
733
|
See change: `split-notify-from-prompt-request`.
|
|
435
734
|
|
|
735
|
+
### Push Notifications (change: add-server-push-notifications)
|
|
736
|
+
|
|
737
|
+
Opt-in cross-device notifications. `push.enabled` defaults to `false` — while disabled no dispatcher, no VAPID keys, no outbound calls (`packages/shared/src/config.ts` `parsePushConfig`; `packages/server/src/push/push-service.ts`).
|
|
738
|
+
|
|
739
|
+
```mermaid
|
|
740
|
+
flowchart LR
|
|
741
|
+
E["live event edge (isUnreadTrigger, no viewer)"] --> S["stampUnreadIfTriggered"]
|
|
742
|
+
S -->|"unreadEdge"| D["device tokens: web-push, fcm"]
|
|
743
|
+
S -->|"every trigger"| W["webhook tokens, coalesced"]
|
|
744
|
+
D --> T["setImmediate + Promise.allSettled"]
|
|
745
|
+
W --> T
|
|
746
|
+
T --> O{outcome}
|
|
747
|
+
O -->|gone| P[prune token]
|
|
748
|
+
O -->|ok| U[touch]
|
|
749
|
+
O -->|failure| F[recordFailure]
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
**Trigger — single hook** (`packages/server/src/event-wiring.ts` `stampUnreadIfTriggered`):
|
|
753
|
+
- Called after the unread block, only for a known session: `pushDispatcher?.fanout(sessionId, {eventType, after, payload, unreadEdge})`.
|
|
754
|
+
- Replay never reaches it (`event_forward` checks `replayingSessions`; the `prompt_request` branch is live-only). Viewed session → suppressed.
|
|
755
|
+
- One `ask_user` edge has two callers (`event_forward` / `prompt_request`); only the first reaches fanout — the second sees `currentTool` already `"ask_user"`, so `isUnreadTrigger` is false.
|
|
756
|
+
- Fire-and-forget: `fanout` returns `void`, memory-only sync work, never throws/rejects.
|
|
757
|
+
|
|
758
|
+
**Hybrid cadence** (`packages/server/src/push/push-dispatcher.ts`):
|
|
759
|
+
- Device tokens (`web-push`, `fcm`) only when `unreadEdge` — one buzz per unread period, next after a view.
|
|
760
|
+
- Webhook tokens every qualifying trigger, coalesced per `(sessionId, tokenId)` within `push.coalesceWindowMs`.
|
|
761
|
+
- Coalesce entries expire lazily at 2× window; dropped on token remove.
|
|
762
|
+
- One structured log line per delivery: `{tokenId, transport, target (redacted), outcome, ms, status|errorCode}`.
|
|
763
|
+
|
|
764
|
+
**Payload** (`packages/server/src/push/build-push-payload.ts`): `{type: "session_attention", trigger: turn_end|input|crash|test, sessionId, title, body, url: "/session/<id>"}`.
|
|
765
|
+
- `title` = `<name>: turn finished|waiting for input|crashed`; `<name>` falls back to cwd basename.
|
|
766
|
+
- Crash `body` = error cut to 200 chars + `…`; otherwise the session model id.
|
|
767
|
+
|
|
768
|
+
**Token registry** (`packages/server/src/push/push-token-registry.ts`):
|
|
769
|
+
- `~/.pi/dashboard/push-tokens.json` + `push-vapid.json`, mode `0600` via `writeJsonFile(path, data, {mode})` — `chmod` on the `.tmp` unconditionally before rename.
|
|
770
|
+
- Max 50 tokens; 51st distinct `deviceToken` → `409`. Idempotent by `deviceToken` (same id, new `lastUsedAt`).
|
|
771
|
+
- `touch` persisted ≤ 1 per 60 s. `consecutiveFailures` in memory, reset on success.
|
|
772
|
+
- Corrupt file → renamed `push-tokens.json.corrupt-<epoch ms>`, registry starts empty, `push.errors` entry.
|
|
773
|
+
|
|
774
|
+
**Transports** (`packages/server/src/push/push-transports/`):
|
|
775
|
+
- web-push: `web-push` lib, VAPID (`push-vapid.json`, generated once); 404/410 → gone.
|
|
776
|
+
- fcm: HTTP v1 API, RS256 service-account JWT via `crypto.createSign`, access token cached, refresh at 3500 s, one re-sign + retry on 401; `NOT_FOUND`/`UNREGISTERED` → gone; missing/unreadable service-account file → FCM disabled + `push.errors` entry.
|
|
777
|
+
- webhook: `undici.request`, no redirects (3xx = failure), 5 s timeout, `body.dump()`; 2xx → ok, 410 → gone, anything else incl 404 → failure, token kept, no retry.
|
|
778
|
+
- gone → token pruned (`registry.remove`).
|
|
779
|
+
|
|
780
|
+
**Webhook SSRF** (`push-transports/webhook-url.ts`):
|
|
781
|
+
- http/https only, absolute, no userinfo.
|
|
782
|
+
- Blocked: `169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`, IPv4-mapped forms; dashboard's own listen port on a loopback/local-interface address. Loopback + LAN allowed.
|
|
783
|
+
- Any resolved record blocked → refused. Same check at registration and every delivery.
|
|
784
|
+
- Per-delivery undici `Agent` with `connect.lookup` pinned to the vetted addresses — closes DNS rebinding.
|
|
785
|
+
|
|
786
|
+
**Redaction**: webhook renders `label (origin)`; web-push `<endpoint host> browser`; fcm `fcm device`. Raw errors never logged. `POST /api/push/test` returns only `{tokenId, ok, gone?}`.
|
|
787
|
+
|
|
788
|
+
**REST** (`packages/server/src/routes/push-routes.ts`): `GET /api/push/vapid-public-key` (`observe`); `GET/POST /api/push/register`, `DELETE /api/push/register/:tokenId`, `POST /api/push/test` (`operate`). Routes always registered; handlers answer 404 while push disabled. Auth chain runs first — unauthenticated remote → 401, not 404. `/api/push/` prefix denylisted from MCP.
|
|
789
|
+
|
|
790
|
+
**Health**: `/api/health` carries `push.errors` only when `canDiscloseAccessPosture(request)` and push enabled. Missing `push.webPush.contactEmail` → web-push disabled + `push.errors` entry (FCM + webhook keep working).
|
|
791
|
+
|
|
792
|
+
**Client** (`public/sw.js`, `packages/client/src/hooks/usePushSubscription.ts`, `packages/client/src/components/settings/PushNotificationsSection.tsx`):
|
|
793
|
+
- `sw.js` `push` → `showNotification(title, {body, data: {url, sessionId}})`; `notificationclick` focuses + navigates an existing window, else `openWindow(url)`.
|
|
794
|
+
- Settings ▸ Sessions ▸ Push notifications: device toggle (secure context only, else https notice), iOS install-to-home-screen hint, token list (display, Send test, Remove), Add webhook URL form (works without Web Push).
|
|
795
|
+
|
|
796
|
+
**FCM setup**: `push.fcm.serviceAccountPath` → Google service-account JSON with `project_id`, `client_email`, `private_key`; never inline in `config.json`.
|
|
797
|
+
|
|
798
|
+
**nanoMuse recipe**: create a `hook` trigger, copy its URL (`POST /api/hooks/{id}?key=…`), paste into Settings ▸ Sessions ▸ Push notifications ▸ Add webhook URL. nanoMuse answers 429 within 10 s of a previous call — logged, not retried.
|
|
799
|
+
|
|
800
|
+
See change: `add-server-push-notifications`.
|
|
801
|
+
|
|
436
802
|
### Command Flow (browser → pi)
|
|
437
803
|
1. User types prompt or command in browser
|
|
438
804
|
2. Browser sends `send_prompt` via WebSocket
|
|
@@ -600,6 +966,9 @@ First-party slots (React, possibly also descriptor):
|
|
|
600
966
|
- `content-view` — full-screen content area (replaces every conditional branch in `App.tsx` for `ArchiveBrowserView`, `SpecsBrowserView`, `OpenSpecPreview`, `FlowAgentDetail`, `FlowArchitectDetail`, `MarkdownPreviewView`, `FileDiffView`, `FlowYamlPreview`). Descriptor variant reuses `management-modal`.
|
|
601
967
|
- `content-header-sticky` — sticky element above content-view (replaces sticky `FlowArchitect`/`FlowDashboard`). Descriptor variant reuses `breadcrumb`.
|
|
602
968
|
- `content-inline-footer` — inline element below content-view (replaces `FlowSummary`). React-only.
|
|
969
|
+
- `composer-context-group` — labelled read-only context groups inside the chat composer's session-action strip (`ComposerSessionActions`), after the Git group, before the Status group. Multiplicity `many`, tier `react-only`, claim `{ component }`, context props `{ session, pluginContext }`. Outside the Status group's streaming `<fieldset disabled>` — stays visible mid-run. Runtime exports `ComposerContextGroupSlot` + primitive `ComposerContextGroup` (keeps signature, delegates to `ToolbarGroup` variant `info`). First claimant: quota plugin's `QuotaWidget`. See change: move-quota-to-context-strip; redesign-composer-session-strip.
|
|
970
|
+
|
|
971
|
+
**Composer session-action strip (`ComposerSessionActions`):** host groups (OpenSpec, Git, Status) + plugin `composer-context-group` contributions render through one primitive `ToolbarGroup({ label, variant: "actions"|"info", testId?, labelTestId?, contentAs?: "div"|"fieldset", contentProps?, className? })` (`packages/dashboard-plugin-runtime/src/slot-consumers.tsx`). Renders `<div data-group role="group" aria-labelledby>` + label `<span id>` (`useId`) + content element carrying `data-group-content`. `actions` variant: solid outline, `--bg-tertiary` fill, label segment on `--bg-surface`, hairlines between direct children, children ≥24 px targets. `info` variant: dashed outline, no fill (read-only readouts). Label test id = `labelTestId ?? (testId ? `${testId}-label` : undefined)` — never `undefined-label`. a11y contract change: every claimant becomes a named `role="group"` region; contributions drop own chip borders (quota plugin did). Host containers `composer-{openspec,git,status}-container`; legacy ids `composer-{openspec,git,status}-group-label`, `composer-git-group`, `composer-status-group` kept (Status content is `<fieldset disabled={working}>`). `packages/client/src/index.css`: `[data-group]:has(> [data-group-content]:empty) { display:none }` hides empty group (e.g. all badge claims render null). See change: redesign-composer-session-strip.
|
|
603
972
|
- `anchored-popover` — popover anchored to a triggering UI element (replaces `TasksPopover`).
|
|
604
973
|
- `command-route` — maps a slash command or URL route to a `content-view` (replaces today's hand-wired routing in `App.tsx`).
|
|
605
974
|
- `settings-section` — a section in the Settings page (replaces today's hardcoded `Background polling (OpenSpec)` section). React for first-party plugins; descriptor (RJSF/UiField) for third-party extensions.
|
|
@@ -631,7 +1000,7 @@ Descriptor-only slots (existing in `extension-ui-system`): `management-modal`, `
|
|
|
631
1000
|
**Plugin settings persistence:**
|
|
632
1001
|
- All plugin settings live under `plugins.<id>.*` in `~/.pi/dashboard/config.json`. The dashboard core never reads or writes another plugin's namespace.
|
|
633
1002
|
- Each manifest may declare a `configSchema` (JSON Schema 7); the loader validates on read (with defaults applied) and on write (rejects invalid).
|
|
634
|
-
- `POST /api/config/plugins/:id` accepts a partial config for a single plugin and broadcasts `plugin_config_update { id, config }` to all subscribed browsers.
|
|
1003
|
+
- `POST /api/config/plugins/:id` accepts a partial config for a single plugin and broadcasts `plugin_config_update { id, config }` to all subscribed browsers. Omitted keys keep stored values: validation runs on a clone so Ajv `useDefaults` cannot inject defaults into the merge; defaults fill only never-stored keys (`fix-plugin-config-partial-write`).
|
|
635
1004
|
- The client-side `pluginContext.usePluginConfig<T>()` hook is reactive — consumers re-render within one frame of a write.
|
|
636
1005
|
- Legacy top-level keys (e.g. `openspec.*`) auto-migrate to `plugins.<id>.*` on the plugin's first server boot.
|
|
637
1006
|
|
|
@@ -642,12 +1011,14 @@ Descriptor-only slots (existing in `extension-ui-system`): `management-modal`, `
|
|
|
642
1011
|
|
|
643
1012
|
#### Health endpoint observability
|
|
644
1013
|
|
|
645
|
-
`/api/health` exposes
|
|
1014
|
+
`/api/health` exposes additive measurement fields (no behavior change). Existing clients ignore unknown fields. See change: instrument-session-hydration-timing.
|
|
1015
|
+
- `server.heapSizeLimit` — `v8.getHeapStatistics().heap_size_limit`. Process heap ceiling. Sits with process memory gauges (`rss`, `heapUsed`) for computing memory headroom. See change: `bound-event-store-by-bytes`.
|
|
1016
|
+
- `storeRetention: { residentBytes, effective: { maxBytesPerSession, maxTotalEventBytes, maxCachedSessions }, globalBudgetExceeded }` — from `eventStore.getRetention()`. `residentBytes` = gauge of resident event bytes. `effective.*` = enforced budgets after store floor clamp. `globalBudgetExceeded` = boolean latch set when all-pinned fallback cannot reach budget. Grouped separately from `storeTrim` counters. See change: `bound-event-store-by-bytes`.
|
|
646
1017
|
- `eventLoopDelay: { meanMs, p99Ms, maxMs }` — `perf_hooks.monitorEventLoopDelay` histogram, ns→ms. Resets window each read.
|
|
647
1018
|
- `hydration: HydrationSample[]` — ring buffer, ≤20 newest-first samples. Process-local, no persistence. Sample `{ sessionId, wallMs, fileBytes, entryCount, eventCount, at }` recorded by `loadSessionEvents`.
|
|
648
1019
|
- `eventLoopSpikes: { at, ms, turn }[]` — ring buffer, ≤50 newest-first, process-local, additive. Retains worst-case event-loop stalls. Two feeds: dedicated `monitorEventLoopDelay` sampler (own instance, never the boot histogram `/api/health` resets → no reset race; records `turn: null` for stalls no poll turn owns) + per-turn self-records from the openspec poll path (`turn: "tickOpen" \| "dirPollPre" \| "dirPollPost"`). Sub-threshold ~700 ms stall retained even when nobody polls `/api/health`. See change: attribute-openspec-poll-eventloop-stalls.
|
|
649
1020
|
- `notifyLog: { evictedEntries, bySession }` — from `browserGateway.getNotifyLogStats()` (`packages/server/src/pairing/notify-log.ts` `getStats()`). `evictedEntries` = total cap-50 evictions; `bySession` = per-session counts. Cap-50 eviction = silent transcript loss → counted beside `droppedFrames` / `storeTrim`. See change: split-notify-from-prompt-request.
|
|
650
|
-
- `storeTrim: { trimmedEvents: { total, toolExecutionEnd, bySession }, evictedSessions, collapsedUpdates }` — from `eventStore.getTrimStats()` (`packages/server/src/persistence/memory-event-store.ts`). `trimmedEvents` + `evictedSessions` pre-existing: per-session cap trims, whole-session LRU evictions. See change:
|
|
1021
|
+
- `storeTrim: { trimmedEvents: { total, toolExecutionEnd, bySession }, evictedSessions, collapsedUpdates, trimmedBytes, evictedBytes }` — from `eventStore.getTrimStats()` (`packages/server/src/persistence/memory-event-store.ts`). `trimmedEvents` + `evictedSessions` pre-existing: per-session cap trims, whole-session LRU evictions. `trimmedBytes`: cumulative bytes released by byte-triggered trims. `evictedBytes`: cumulative bytes released by whole-buffer LRU evictions. See change: `bound-event-store-by-bytes`. NEW `collapsedUpdates`: cumulative count of superseded `tool_execution_update` events dropped at retention. Collapse retains per `toolCallId`: pinned creating tick (first-wins `type`/`description`) + newest tail + any non-subsumed intermediate updates — commonly ≤2, not hard bound. Retention-only — never suppresses live broadcast; browser still receives every tick. Predecessor dropped only when successor subsumes it (superset gate on `partialResult.details`). Counters cumulative for process lifetime, never reset on read. No event store wired → `EMPTY_TRIM_STATS` (all-zero), exported from store. Harness A/B (4 sessions × 4 sustained subagent rounds): retained `tool_execution_update` per buffer 36 → 2; buffer share 18.4% → 1.2%. See change: collapse-superseded-tool-execution-updates. NEW `collapseOnEnd` — `tool_execution_end` drops retained tail `tool_execution_update` for a `toolCallId` when end subsumes it; same superset gate (key survival, entries survival, rendered-result implication) resolved END-side on top-level `data.details` (plain object) + `data.result`, updates still resolve `data.partialResult.details`. Additive fail-closed: presence — truthy tail `partialResult.details` + end without `data.details` ⇒ retain (tail replaces `toolDetails` wholesale; detail-less end merges prior); identity — tail `details.agentId` string ⇒ end `toolName === "Agent"` + equal `agentId` + equal `agentSessionId` when present. Agent-shaped tail drops only with resident pinned creating tick (absent ⇒ retain); non-Agent (no `agentId`) tail drops freely; `activity` cleared on end ⇒ tail retained (spec scenario 2 — subagent's last inner event commonly a tool end). Drops fold into `collapsedUpdates` (no new key); fail-open — retain, no throw — on missing `toolCallId` (incl. `{__truncated}`), absent index entry, trimmed tail; `tool_execution_end` itself never a drop candidate; `collapseOnEnd` runs in `insertEvent` immediately after `collapseSuperseded`, after truncation, before trim/evict. Cross-version verification (`openspec/changes/archive/2026-09-13-drop-final-update-on-tool-execution-end/verification.md`): producer `@blackbelt-technology/pi-dashboard-subagents` 0.2.0–0.2.4 — gate sound; only absent-on-end key = `activity`. See change: drop-final-update-on-tool-execution-end.
|
|
651
1022
|
|
|
652
1023
|
**Bundled-by-default plugins:** The plugin loader treats all plugins identically (same manifest, same discovery, same `enabled` flag, same failure isolation). What distinguishes "bundled-by-default" plugins (initial set: `git-plugin`) is purely operational — the build pipeline always includes them in `packages/`. Their absence is a deliberate user opt-out, not a normal state. OpenSpec, Flows, and Subagents plugins are bundled in standard builds but their absence is a normal use case (e.g. a workspace without OpenSpec).
|
|
653
1024
|
|
|
@@ -691,15 +1062,100 @@ Escape hatch: env `PI_DASHBOARD_DISABLE_PLUGIN_BRIDGE_PACKAGES_WRITE=1` skips `p
|
|
|
691
1062
|
|
|
692
1063
|
Classification helper `classifyBridgeSource(settings, id)` returns `"packages[]"` / `"dashboardPluginBridges"` / `"both"` / `"none"`. `/api/health.plugins[].bridgeLoadedFrom` surfaces it. `"both"` = healthy post-0.5.4. `"dashboardPluginBridges"` only = stale install pre-reconcile.
|
|
693
1064
|
|
|
694
|
-
#### Plugin Staleness Detection
|
|
1065
|
+
#### Plugin Staleness Detection and Served-Build Coherence
|
|
1066
|
+
|
|
1067
|
+
Detects when client bundle predates installed plugin set, or served static directory diverges from runtime plugin set.
|
|
1068
|
+
|
|
1069
|
+
**Root cause of historical divergence:** build-time and runtime hashes previously computed over structurally different plugin sets. Build dropped client-less plugins (`Boolean(p.clientEntryPath)`); runtime counted every discovered plugin. Client-less plugins (e.g. `mcp-server`) made runtime `bundleHash` and build `PLUGIN_REGISTRY_HASH` permanently disagree, locking `PluginStalenessBanner` in refresh loops. Runtime discovery also inspected runtime-only roots (`~/.pi/dashboard/plugins`), while builds only bundle repository packages (`<repoRoot>/packages`).
|
|
1070
|
+
|
|
1071
|
+
**Single plugin-set selector (`selectClientRegistryPlugins`):**
|
|
1072
|
+
Single selector in `packages/dashboard-plugin-runtime/src/server/client-registry-set.ts::selectClientRegistryPlugins(discovered, { isProd, bundleRoots })` feeds every producer:
|
|
1073
|
+
- Requires `p.clientEntryPath` (drops client-less plugins from both hashes).
|
|
1074
|
+
- Drops `p.manifest.fixture === true` when `isProd` is true (`demo-plugin` excluded from production build and production runtime hash).
|
|
1075
|
+
- Restricts discovery to bundle-eligible roots (`bundleRootsFor(repoRoot)`). Plugins in runtime-only roots (`~/.pi/dashboard/plugins`) excluded from both hashes (cannot enter client bundle; user-installed plugins contribute no client UI).
|
|
1076
|
+
|
|
1077
|
+
All producers select through this selector:
|
|
1078
|
+
- Build time: Vite plugin (`packages/dashboard-plugin-runtime/src/vite-plugin/index.ts`)
|
|
1079
|
+
- Dev time: Vite `configureServer` HMR regeneration
|
|
1080
|
+
- Script: `scripts/generate-plugin-registry.mjs`
|
|
1081
|
+
- Server runtime: `packages/server/src/routes/system-routes.ts` (`/api/health.bundleHash`)
|
|
1082
|
+
|
|
1083
|
+
All producers hash deterministic manifest serialization via `pluginRegistryHash(...)`.
|
|
1084
|
+
|
|
1085
|
+
**Served-artifact build declaration (`pi-dashboard-build.json`):**
|
|
1086
|
+
Production Vite build writes `packages/client/dist/pi-dashboard-build.json`:
|
|
1087
|
+
- Schema: `{ schemaVersion: 1, pluginRegistryHash: "<sha256>", fixturePolicy: "excluded" | "included" }`.
|
|
1088
|
+
- Byte-reproducible: no timestamps, no host paths. Dev/HMR emits nothing.
|
|
1089
|
+
- SDK: `build-declaration-sdk.ts` + `build-metadata.ts` in `dashboard-plugin-runtime`.
|
|
1090
|
+
|
|
1091
|
+
**Static client resolution and `/api/health.clientBuild`:**
|
|
1092
|
+
Server resolves static root once at startup (`packages/server/src/lib/client-dist.ts::resolveStaticClientDir`):
|
|
1093
|
+
- Package-first: installed `@blackbelt-technology/pi-dashboard-web/dist` wins if resolvable and contains `index.html`.
|
|
1094
|
+
- Resolvable package missing `dist/index.html` → API-only mode (`null`, NO workspace fallback).
|
|
1095
|
+
- Workspace fallback: `packages/client/dist` used only when `require.resolve` throws.
|
|
1096
|
+
|
|
1097
|
+
Server captures startup coherence snapshot (`clientBuildSnapshotFor`):
|
|
1098
|
+
- Compares artifact's declared `pluginRegistryHash` against runtime plugin set evaluated under artifact's declared `fixturePolicy` (avoids false mismatch between dev server and production artifact).
|
|
1099
|
+
- `/api/health` exposes additive field:
|
|
1100
|
+
`clientBuild: { pluginRegistryHash: string | null, status: "matched" | "mismatched" | "metadata-missing" | "not-served" }`.
|
|
1101
|
+
- Path-free startup diagnostic logged (`[dashboard] Served client build: <status>`).
|
|
1102
|
+
- Existing `bundleHash` field and `PluginStalenessBanner` contract unchanged.
|
|
1103
|
+
|
|
1104
|
+
**Rebuild sync gate (`scripts/sync-served-client.mjs`):**
|
|
1105
|
+
Wired into `scripts/rebuild-restart.sh` and `scripts/rebuild-and-restart.sh` between build and restart:
|
|
1106
|
+
- Resolves served destination using server's `resolveStaticClientDir`.
|
|
1107
|
+
- No-op when destination equals `packages/client/dist`.
|
|
1108
|
+
- Mirrors workspace `dist` to destination if different; prunes superseded hashed assets after copy.
|
|
1109
|
+
- Verifies matching declarations before exit; adopts declaration-less destinations.
|
|
1110
|
+
- Refuses (exit 1) on missing source declaration, non-client destination, EACCES, or post-copy mismatch, aborting before server restart or bridge reload.
|
|
1111
|
+
|
|
1112
|
+
```mermaid
|
|
1113
|
+
flowchart TD
|
|
1114
|
+
subgraph Discovery ["Plugin Discovery"]
|
|
1115
|
+
DP["discoverPlugins()"]
|
|
1116
|
+
end
|
|
1117
|
+
|
|
1118
|
+
subgraph Selection ["Single Source of Truth"]
|
|
1119
|
+
SCRP["selectClientRegistryPlugins(discovered, {isProd, bundleRoots})<br/>1. requires clientEntryPath<br/>2. drops fixture if isProd<br/>3. restricts to bundleRoots"]
|
|
1120
|
+
end
|
|
1121
|
+
|
|
1122
|
+
subgraph Build ["Build Pipeline (Vite)"]
|
|
1123
|
+
VITE["Vite Build / generate-plugin-registry"]
|
|
1124
|
+
REG["plugin-registry.tsx<br/>export const PLUGIN_REGISTRY_HASH"]
|
|
1125
|
+
DECL["dist/pi-dashboard-build.json<br/>{schemaVersion, pluginRegistryHash, fixturePolicy}"]
|
|
1126
|
+
end
|
|
1127
|
+
|
|
1128
|
+
subgraph Runtime ["Server Runtime (:8000)"]
|
|
1129
|
+
RESOLVE["resolveStaticClientDir()<br/>1. Installed package dist<br/>2. Workspace fallback (if unresolvable)"]
|
|
1130
|
+
SNAP["readClientBuildSnapshot()<br/>Compare declared vs runtime hash"]
|
|
1131
|
+
HEALTH["/api/health<br/>- bundleHash<br/>- clientBuild: {pluginRegistryHash, status}"]
|
|
1132
|
+
end
|
|
1133
|
+
|
|
1134
|
+
subgraph Client ["Browser UI"]
|
|
1135
|
+
BANNER["PluginStalenessBanner<br/>Compare /api/health.bundleHash vs PLUGIN_REGISTRY_HASH"]
|
|
1136
|
+
end
|
|
695
1137
|
|
|
696
|
-
|
|
1138
|
+
subgraph Rebuild ["Rebuild Gate"]
|
|
1139
|
+
SYNC["scripts/sync-served-client.mjs<br/>Mirror workspace -> served dir<br/>Abort before restart if mismatch"]
|
|
1140
|
+
end
|
|
697
1141
|
|
|
698
|
-
|
|
1142
|
+
DP --> SCRP
|
|
1143
|
+
SCRP --> VITE
|
|
1144
|
+
VITE --> REG
|
|
1145
|
+
VITE --> DECL
|
|
1146
|
+
SCRP --> HEALTH
|
|
1147
|
+
DECL -.-> SYNC
|
|
1148
|
+
SYNC -.-> RESOLVE
|
|
1149
|
+
DECL -.-> RESOLVE
|
|
1150
|
+
RESOLVE --> SNAP
|
|
1151
|
+
SNAP --> HEALTH
|
|
1152
|
+
HEALTH --> BANNER
|
|
1153
|
+
REG --> BANNER
|
|
1154
|
+
```
|
|
699
1155
|
|
|
700
|
-
|
|
1156
|
+
Client banner flow: `PluginStalenessBanner` fetches `/api/health` on mount. Compares `bundleHash` against imported `PLUGIN_REGISTRY_HASH`. Mismatch ⇒ render banner with Refresh + Dismiss buttons. Refresh calls `location.reload()`. Dismiss persists in `sessionStorage` key `pi-plugin-staleness-dismissed` (tab-scoped, clears on browser close). Dismissed banner stays hidden until next session.
|
|
701
1157
|
|
|
702
|
-
|
|
1158
|
+
See change: `add-served-build-coherence-and-hash-parity`.
|
|
703
1159
|
|
|
704
1160
|
#### Plugin Activation UI
|
|
705
1161
|
|
|
@@ -711,7 +1167,7 @@ Settings ▸ Plugins tab lists every discovered plugin (enabled or not) with dis
|
|
|
711
1167
|
|
|
712
1168
|
- `probePiExtension(id)` cross-refs installed pi-extension set (deps.listInstalled).
|
|
713
1169
|
- `probeBinary(name)` resolves via tool registry.
|
|
714
|
-
- `probeService(name)` dispatches to service
|
|
1170
|
+
- `probeService(name)` dispatches to closed service registry. Sole entry `model-proxy` → `service-probes/model-proxy.ts::probeModelProxy`. Satisfied by boot-time `isModelProxyEnabled` dep. No HTTP — routes sit behind proxy auth gate.
|
|
715
1171
|
- `probePath(rawPath, deps)` — existence check on absolute path. Never executes, never shells.
|
|
716
1172
|
|
|
717
1173
|
Results populate `PluginStatus.requirements` + flat `missingRequirements: string[]`; surfaced via `GET /api/plugins`. 30s in-process cache keyed by category+name. `server.ts` invokes `refreshRequirementProbesFor(pluginIds)` on every successful `package_operation_complete` + broadcasts `plugin_config_update` for any plugin whose missing-set changed — install/uninstall of a pi-extension lights up dependent plugin without restart.
|
|
@@ -775,11 +1231,17 @@ Generic channel. Any plugin routes pi events bridge→server→browser + request
|
|
|
775
1231
|
- `plugin_event` (ServerToBrowser). Plugin server `broadcastToSubscribers`. Shell `useMessageHandler` routes `event` → `publishSessionEvent` → plugin `useSessionEvents`.
|
|
776
1232
|
- New `ServerPluginContext` capabilities. `onEvent(handler)` subscribes all forwarded events. `sendToSession(sessionId, text)` sends prompt/command; `/`-prefixed text routes to extension-command dispatch (Path C keeper headless).
|
|
777
1233
|
|
|
1234
|
+
##### Private request/reply lane
|
|
1235
|
+
|
|
1236
|
+
Bridge→server request, separate from the fire-and-forget channel above. Bridge entry `requestPluginServer(pluginId,type,payload)` from `@blackbelt-technology/dashboard-plugin-runtime/bridge`; core bridge installs fn at `Symbol.for("pi-dashboard.pluginRequest")`. Server `ctx.registerPiRequestHandler(type,handler)` — single owner per `(pluginId,type)`, duplicate throws. Wire `plugin_request` → host-internal `plugin_reply` on the SAME socket. Never `pi.events`; never the priority-gated `sendExtensionMessage`. Caps 256 KiB each way; timeout 15 s. Codes `no_handler`/`timeout`/`disconnected`/`request_too_large`/`reply_too_large`/`reply_not_serializable`/`unavailable`. `sessionId` from socket key, never payload. Trust: private = unobservable + unforgeable, NOT authenticated; handlers authorize on payload. Same change adds `ctx.credentials` store + `ctx.oauth.startFlow` + `createLoopbackCallback` — see [`plugin-seams.md`](plugin-seams.md). See change: expose-plugin-credential-and-oauth-seams.
|
|
1237
|
+
|
|
778
1238
|
#### Goal Session Supervisor (`add-goal-session-supervisor`)
|
|
779
1239
|
|
|
780
1240
|
Goal feature = session supervisor over host's existing session-lifecycle mechanism. Clean split: host owns mechanism (spawn + spawn-token correlation via `linkByToken` + death signal via `dispatchPluginSessionEnded`/`sessionManager.onUnregister` + kill via `abortSpawnedRun` + resume via `spawnPiSession` continue-mode). Goal plugin/server adds pursuit policy only.
|
|
781
1241
|
|
|
782
|
-
|
|
1242
|
+
**Relocated.** Goal product (store, supervisor, routes, goal_status peers, primer, link handover) now lives in `packages/goal-plugin/src/server/` — `index.ts` is the composition root. Core is goal-agnostic: no `goal/` dir, no goal wiring in `server.ts`/`event-wiring.ts`. Plugin reaches host services via `ServerPluginContext` capabilities (`spawnSession`/`mintSpawnToken`/`renameSession`/`assignSessionRef`/`networkGuard`/`onShutdown`/`onSessionEnded`/`onSessionResolved`/`consume("host.knownFolderCwds")`). REST paths `/api/folders/goals*`, wire types, and data dir `~/.pi/dashboard/goals` unchanged. Manifest id `goal` = owner id for spawn-token refs. Reaches parity with automation-plugin self-containment. See change: relocate-goal-product-to-plugin.
|
|
1243
|
+
|
|
1244
|
+
Supervisor lives in goal-plugin: `packages/goal-plugin/src/server/goal-supervisor.ts`. Rides plugin death fanout (`onSessionEnded`).
|
|
783
1245
|
|
|
784
1246
|
- Policy: progress-gated auto-respawn. Progress = strict cumulative `totalTurnsUsed` increase past per-driver baseline.
|
|
785
1247
|
- Died-after-progress → resume conversation (continue-mode).
|
|
@@ -808,6 +1270,54 @@ Automation plugin = `packages/automation-plugin/`. Schedule-triggered background
|
|
|
808
1270
|
- UI via shell slots: sidebar-folder-section, command-route `/automation`, shell-overlay-route, session-card-badge, settings-section general.
|
|
809
1271
|
- See change: add-automation-plugin.
|
|
810
1272
|
|
|
1273
|
+
### Plugin Spawn Capability Scope (`add-plugin-spawn-scope`)
|
|
1274
|
+
|
|
1275
|
+
- `ServerPluginContext.spawnSession(opts: PluginSpawnOptions)` gains optional `scope` block.
|
|
1276
|
+
- `scope` constrains spawned session tool/skill/extension surface.
|
|
1277
|
+
- First-party trusted plugins only (priority <= 100).
|
|
1278
|
+
- `scope.tools` (string[]) → `--tools a,b,c` (comma-joined single arg).
|
|
1279
|
+
- `scope.excludeTools` (string[]) → `--exclude-tools a,b,c` (comma-joined single arg).
|
|
1280
|
+
- `scope.noBuiltinTools`, `scope.noTools`, `scope.noSkills` (bool) → bare flags.
|
|
1281
|
+
- `scope.skills` (string[]) → repeatable `--skill <path>`.
|
|
1282
|
+
- `scope.extensions` (string[]) → repeatable `-e <path>`.
|
|
1283
|
+
- NO `noExtensions` toggle. Bridge (control channel) must survive. Disabling extension discovery stops dashboard bridge loading → session uncontrollable. (design D2/D6)
|
|
1284
|
+
- `scope.extensions` ADDITIVE allowlist. Discovery still runs, bridge loads.
|
|
1285
|
+
- `extensionConfig[name][key]` projects to namespaced env `PI_EXT_<NAME>_<KEY>=value` (NOT argv).
|
|
1286
|
+
- Name+key uppercased, non-`[A-Z0-9_]` → `_`.
|
|
1287
|
+
- Headless mechanism only (plugin spawns headless-only).
|
|
1288
|
+
- `extensionConfig` values now `string | string[]`. Scalar env verbatim. Array → `JSON.stringify`. (D8)
|
|
1289
|
+
- env NAME normalization splits camelCase first. `allowedRoots` → `ALLOWED_ROOTS`. Then uppercase. Then non-`[A-Z0-9_]` → `_`.
|
|
1290
|
+
- Mapper `pluginSpawnToSessionOptions(opts): MappedSpawnOptions` in `packages/dashboard-plugin-runtime/src/server/server-context.ts`.
|
|
1291
|
+
- Total + pure. NEVER throws (plugin input untrusted JS).
|
|
1292
|
+
- Flattens `scope` → flat `SessionFlags` argv fields + `extensionConfig`.
|
|
1293
|
+
- Malformed containers treated absent.
|
|
1294
|
+
- Non-string/empty/NUL argv entries dropped.
|
|
1295
|
+
- NUL env values dropped.
|
|
1296
|
+
- Conflicting `noTools` + `tools` both forwarded. Pi arbitrates precedence. (D3)
|
|
1297
|
+
- Empty array ⇒ no flag emitted.
|
|
1298
|
+
- `scope` absent ⇒ argv + env byte-identical to pre-change.
|
|
1299
|
+
- Host hook (`packages/server/src/server.ts`) calls mapper BEFORE `pendingAutomationRunRegistry.enqueue`.
|
|
1300
|
+
- Rejected input cannot strand stale `cwd`-keyed stamp. (D7)
|
|
1301
|
+
- Consumers (automation-plugin, flows, REST spawn) do NOT populate `scope` yet. Future opt-in. Plumbing only.
|
|
1302
|
+
- Part B: host-cwd-policy registry. `CwdPolicyRegistry` + pure `mergeCwdPolicy` in `packages/server/src/spawn-process/cwd-policy.ts`.
|
|
1303
|
+
- cwd-keyed. Tighten-only. Composed across ancestors. Merged into every `spawnPiSession`.
|
|
1304
|
+
- `registerCwdPolicy`/`unregisterCwdPolicy` on plugin ctx. Trust-gated.
|
|
1305
|
+
- Registration requires CANONICAL containment (no lexical fallback — symlink-escape guard).
|
|
1306
|
+
- `resolve()` matches canonical-OR-lexical (fail-toward-applying).
|
|
1307
|
+
- See change: add-plugin-spawn-scope.
|
|
1308
|
+
|
|
1309
|
+
### Plugin Session Lifecycle Declarations (`hide-chat-gateway-sessions`)
|
|
1310
|
+
|
|
1311
|
+
`ServerPluginContext.spawnSession` accepts `PluginSpawnOptions.lifecycle: PluginSessionLifecycle` (`packages/dashboard-plugin-runtime/src/server/server-context.ts`). Owning plugin declares per-session lifecycle decisions; core reads the flags, never the plugin name.
|
|
1312
|
+
|
|
1313
|
+
- `recover?: boolean` — `false` opts owned session out of cold-start recovery (default recoverable). Persisted to `.meta.json` only when `false` (additive opt-out byte).
|
|
1314
|
+
- `finalizeOnSocketClose?: boolean` — `true` finalizes owned session on socket close, no reconnect grace. In-memory only; read at pi-gateway socket-close finalize branch.
|
|
1315
|
+
- `hidden?: boolean` — `true` hides owned session from board on FIRST register. Same `hidden` flag as headless auto-hide (`packages/server/src/session/memory-session-manager.ts`); revealed by "show hidden" toggle. Persisted to `.meta.json`, broadcast via `broadcastSessionUpdated`. Applied on fresh spawn-token resolution only (`packages/server/src/event-wiring.ts`); reattach never re-applies, so a later operator unhide survives. Persists the INTENT as `pluginHidden: true` on the session + `.meta.json` (`session-to-meta.ts`, restored by `sessionFromMeta` in `session-scanner.ts`) so a post-restart respawn re-register (`registerReason: "spawn"`, no token) keeps hidden. `register` order: reattach → `existing.hidden`; `visibilityIntent`; `existing.pluginHidden === true` → hidden; else headless heuristic. Explicit `visibilityIntent: "visible"` still wins. Pre-fix hidden sessions carry no `pluginHidden` → not migrated. See change: fix-plugin-hidden-across-restart.
|
|
1316
|
+
- `pending-plugin-ref-registry.ts` (`packages/server/src/pending/`) files a lifecycle record when ANY of `recover`/`finalizeOnSocketClose`/`hidden` set.
|
|
1317
|
+
- Sibling hook `ServerPluginContext.shutdownSession(sessionId): Promise<boolean>` ends a session like the dashboard **Shutdown**. Trusted plugins only (manifest `priority <= 100`); untrusted or unknown session → `false`. Reuses `browserGateway.shutdownSession` — same body as `POST /api/session/:id/shutdown`, never a parallel `{type:"shutdown"}` path (#449/#452). First consumer: chat-gateway `!close`. See change: chat-gateway-close-command.
|
|
1318
|
+
- First consumer: chat-gateway spawn/resume (`sessionVisibility: "hidden"` default). See [`chat-gateway.md`](chat-gateway.md).
|
|
1319
|
+
- See change: hide-chat-gateway-sessions, fix-plugin-hidden-across-restart.
|
|
1320
|
+
|
|
811
1321
|
### Hermes Memory Settings Plugin (`add-hermes-memory-settings-plugin`)
|
|
812
1322
|
|
|
813
1323
|
New package `packages/hermes-memory-plugin` (client + server + shared). Settings-section plugin for the external `pi-hermes-memory` pi extension.
|
|
@@ -822,17 +1332,67 @@ New package `packages/hermes-memory-plugin` (client + server + shared). Settings
|
|
|
822
1332
|
- Runtime caveat: hermes reads config once at extension load → edits apply to newly started sessions only ("applies to new sessions" notice in the UI), not running ones.
|
|
823
1333
|
- Structured logging: path + field count on read/write success, failure reason on error, NEVER field values (config may hold model/provider hints).
|
|
824
1334
|
|
|
825
|
-
### MCP
|
|
1335
|
+
### MCP Client Plugin (`extract-mcp-client-plugin`, `migrate-mcp-to-pi-builtin`)
|
|
1336
|
+
|
|
1337
|
+
New plugin `packages/mcp-client-plugin/`, id `mcp-client`. Sole owner of the two Pi MCP config layers on the dashboard side. NO `pi-mcp-adapter` dependency — rebuilt on pi 1.0.0's BUILT-IN MCP. `apple-tools` and `mcp-server-plugin` consume it. See change: migrate-mcp-to-pi-builtin.
|
|
1338
|
+
|
|
1339
|
+
**Claims.** `settings-section` → `/settings/plugins/mcp-client`. Folder pill = ONE component on two slots: `sidebar-folder-section` + `worktree-card-section`. `shell-overlay-route` `/folder/:encodedCwd/mcp`, `depth: 2`, `parentPath` `/folder/:encodedCwd`.
|
|
1340
|
+
|
|
1341
|
+
**Exports.** `./client`, `./server`, `./core`. `./core` imports NO React and NO host runtime — the hostless `pi-apple-tools-install` CLI builds the same service from it.
|
|
1342
|
+
|
|
1343
|
+
**Two layers.** Pi global `$PI_CODING_AGENT_DIR/mcp.json` (else `~/.pi/agent/mcp.json`) + trusted `<cwd>/.pi/mcp.json`. A project entry REPLACES the global entry of the same name — whole entry, not a field merge, matching pi's own rule. Both layers parse as STRICT `JSON.parse`; a file with comments or trailing commas is an unparseable layer that pi skips WHOLE — shown as such, never written over. `src/core/layers.ts` (`LayerPaths`, `piAgentDir`, `defaultLayerPaths`, `nullProto`, `readLayer`). DELETED: adapter worker/port, adapter version floor, global-settings form, `adapterLoadTimeoutMs`, `configSchema.json`, and every shared/import layer (`.mcp.json`, `~/.config/mcp`, host imports). `pi-mcp-adapter` + `strip-json-comments` deps removed; `ajv` stays.
|
|
1344
|
+
|
|
1345
|
+
**pi rules.** `src/core/pi-rules.ts` mirrors pi 1.0.0's unexported `validateMcpServerConfig`. `isValidServerName` (`[A-Za-z0-9_-]+`, ≤128, not `__proto__`/`constructor`/`prototype`); `transportOf` (HTTP when `url`, unless `type: "stdio"`); `MCP_EXPOSURES` + `MCP_EXPOSURE_ALIASES` (`codemode-deferred` → `codemode`); `ADAPTER_ONLY_KEYS` / `adapterLeftovers` / `ignoredKeys` (pi ignores unknown keys — adapter keys survive in the file, pi never acts on them); `authModeOf` (provider | header (case-insensitive `Authorization`) | oauth).
|
|
1346
|
+
|
|
1347
|
+
**Service.** `ctx.provide("mcp-client.config", …)` before any route registers. Factory `createMcpClientConfigService({ configIO, knownCwds, isProjectTrusted?, paths?, runner?, scratchCwd?, liveTimeoutMs?, liveCacheTtlMs? })` → `McpClientRuntime` = service + `getLiveState(scope, {fresh})`. Write-only paths never run `pi mcp list`.
|
|
1348
|
+
|
|
1349
|
+
**Trust.** `isProjectTrusted(cwd)` INJECTED. Dashboard server supplies `host.isProjectTrusted` (see Bootstrap). Untrusted folder → its project layer never loads, its rows inactive (`project-not-trusted`). Hostless caller (apple-tools CLI) treats every project as untrusted → global writes only.
|
|
1350
|
+
|
|
1351
|
+
**Live state.** `src/core/live-state.ts` `createLiveStateReader({runner,timeoutMs,cacheTtlMs,now})` runs `pi mcp list --json` through the shared safe-spawn. `LIVE_STATE_TIMEOUT_MS` 30000, `LIVE_STATE_CACHE_TTL_MS` 30000. stdout parsed whatever the exit code — pi exits `1` whenever a server is disconnected or an entry invalid. Timeout aborts the signal → `{ok:false,reason:"timeout"}`; failures never cached. Global view spawns in an empty `mkdtemp` scratch dir so only the global layer loads.
|
|
1352
|
+
|
|
1353
|
+
**Effective view.** `createEffectiveViewReader`. Global view = Pi-global layer only. Project view = global then folder. Rows carry provenance `pi-global`/`pi-folder`, `overridesGlobal`, `transport`, `enabled`, `exposure`, `active`, `inactiveReason` (`disabled` | `project-not-trusted` | `invalid-entry` | `name-collision` | `global-only-auth`), `piError`, `ignoredKeys`, `adapterLeftovers`, `authMode`. Server-side redaction (`redactEntry`, `isSecretKey`): GLOBAL entries shown in a project view lose `headers`/`env` → `{redacted,keys}` and `oauth.clientSecret` → `{redacted}`.
|
|
1354
|
+
|
|
1355
|
+
**Writer.** `createConfigWriter({configIO,paths,knownCwds,isProjectTrusted?})`: `targetPath`, `readServerEntry`, `ensureServerEntry` (merge fields), `saveServer` (whole entry, `previousName` rename), `removeServer`, `setEnabled`, `convertAdapterLeftovers`, `previewEnsure`, `readParseStatus`. Validation order: transport-conflict → pi rules (`invalid-entry`, pi's own message) → project `auth` on HTTP refused (global-only) → `-`/`_` `name-collision`. Collision scope: project = global + project names; global = global + every known TRUSTED folder's project names; entry being replaced excluded. `setEnabled`: write `enabled:false` or remove the key. Folder-disable of a global-only server writes a `folderCopyOf` copy WITHOUT `headers`/`env`/`oauth.clientSecret`/`auth` and returns `omitted`; re-enabling such a copy returns `action:"needs-choice"`. `ConfigRefusalCode` is CLOSED: `unparseable | entry-not-object | invalid-name | name-collision | transport-conflict | invalid-entry | write-failed`. Exports `NotAllowedCwdError`, `FOLDER_COPY_OMITTED`, `folderCopyOf`.
|
|
1356
|
+
|
|
1357
|
+
**Schema.** Published `schema/mcp-config.schema.json` is the pi 1.0.0 entry shape: `description`, `oauth.clientName` / `oauth.authServerMetadataUrl`, global-only `auth.provider`, `exposure` (alias included), `toolExposure`, `timeout` > 0, `enabled`. `ajv` validates every write BEFORE IO. Markers `x-secret` (redaction + masking), `x-transport`, `x-global-only` drive the editor.
|
|
1358
|
+
|
|
1359
|
+
**REST.** `GET /api/mcp-client/effective?cwd=`, `GET /api/mcp-client/live?cwd=&fresh=1`, `GET /api/mcp-client/schema`, `PUT /api/mcp-client/servers/:name` `{scope,cwd?,entry,previousName?}`, `DELETE /api/mcp-client/servers/:name?scope=&cwd=` → `{ok,removed}`, `PUT /api/mcp-client/servers/:name/enabled` `{scope,cwd?,enabled}`, `POST /api/mcp-client/servers/:name/convert` `{scope,cwd?}`. Removed: `/adapter`, `/settings`, `/disabled`. EVERY route — GET included — sits behind `networkGuard`: mutating bodies become executable config for pi and the effective view returns own-layer credentials. Path name decoded + validated and project cwd admitted (403 `not-allowed` + `reason`/`hint`) BEFORE any IO.
|
|
1360
|
+
|
|
1361
|
+
**Runner.** `src/server/pi-runner.ts` `createPiMcpListRunner()`: `ToolResolver.resolvePi()` + shared `spawn` (no shell) + `buildSpawnEnvForArgv` (`ELECTRON_RUN_AS_NODE`) + SIGKILL on abort + 4 MiB stdout cap. Plugin `index.ts` consumes `host.knownFolderCwds` + `host.isProjectTrusted`; absent `isProjectTrusted` → one warning, every project untrusted.
|
|
1362
|
+
|
|
1363
|
+
**Consumers.** `apple-tools` declares `dependsOn: ["mcp-client"]` and drops `requires.piExtensions: ["pi-mcp-adapter"]`. `install.ts` writes only `mcpServers.iMCP` via `ensureServerEntry` (command refreshed; `enabled`/`exposure`/`toolExposure` + unknown keys preserved); `ensureAdapterPackage` and every `settings.json` write removed. `set-disabled` + `set-direct-tools` `plugin_action`s removed (hard break); panel links "Manage MCP servers →" to `/settings/plugins/mcp-client`.
|
|
1364
|
+
|
|
1365
|
+
```mermaid
|
|
1366
|
+
flowchart LR
|
|
1367
|
+
PG["Pi global mcp.json<br/>$PI_CODING_AGENT_DIR else ~/.pi/agent"] --> LV
|
|
1368
|
+
PF["trusted folder .pi/mcp.json<br/>project replaces global"] --> LV
|
|
1369
|
+
PI["pi mcp list --json<br/>live-state.ts 30s timeout+cache"] --> LV
|
|
1370
|
+
TR["host.isProjectTrusted"] --> LV
|
|
1371
|
+
subgraph MC ["packages/mcp-client-plugin"]
|
|
1372
|
+
LV["core/layers.ts + effective-view.ts"] --> CORE["createMcpClientConfigService"]
|
|
1373
|
+
CORE --> SVC["ctx.provide('mcp-client.config')"]
|
|
1374
|
+
CORE --> RT["./server routes<br/>networkGuard on every route"]
|
|
1375
|
+
CORE --> CLI2["./client<br/>settings + folder pill + /folder/:cwd/mcp"]
|
|
1376
|
+
end
|
|
1377
|
+
SVC -->|"ctx.consume (dependsOn)"| AT["apple-tools install.ts<br/>ensureServerEntry('iMCP')"]
|
|
1378
|
+
CORE -->|"package dep, hostless"| BIN["pi-apple-tools-install CLI"]
|
|
1379
|
+
```
|
|
1380
|
+
|
|
1381
|
+
### MCP Endpoint (`add-dashboard-mcp-server`, `mcp-legacy-clients-and-token-issuance`, `paginate-mcp-list-sessions`, `migrate-mcp-to-pi-builtin`)
|
|
826
1382
|
|
|
827
1383
|
New plugin `packages/mcp-server-plugin/`. Headless — no client entry, `claims: []`. Mounts `POST /mcp` on `ctx.fastify`, the shared Fastify instance every plugin gets. Seven other plugins register routes the same way.
|
|
828
1384
|
|
|
829
|
-
**Protocol.**
|
|
1385
|
+
**Protocol.** Dual-era contract on single route (`POST /mcp`):
|
|
1386
|
+
- **Legacy era (`2025-03-26`, `2025-06-18`, `2025-11-25`):** Streamable-HTTP compatibility. `initialize` handshake supported; returns static `InitializeResult` with negotiated `protocolVersion` + opaque unrecorded 128-bit hex `Mcp-Session-Id` header (minted once, never recorded, never checked); `notifications/*` returns 202 (body null); `ping` returns `{}`; streaming refused (`subscriptions/listen` returns 404 + `-32601` `MethodRemoved`).
|
|
1387
|
+
- **Modern era (`2026-07-28`):** handshake-free, stateless. No session ids minted, echoed, or checked. `subscriptions/listen` streaming supported. No `Last-Event-ID` resumption.
|
|
830
1388
|
|
|
831
|
-
|
|
832
|
-
-
|
|
833
|
-
-
|
|
834
|
-
-
|
|
835
|
-
-
|
|
1389
|
+
**Version resolution.** Resolved once per request in `routes.ts` before listen interceptor (single resolution site). `dispatchRpc` receives resolved `{ era, version }`. Resolution rules:
|
|
1390
|
+
- Repeated or comma-joined `MCP-Protocol-Version` header → 400 `AmbiguousHeader` (checked first, applies to all methods including `initialize`).
|
|
1391
|
+
- `initialize` handshake → version read from `params.protocolVersion`. Legacy version echoed; unknown version negotiates down to `2025-11-25`; modern `2026-07-28` on `initialize` refused (404 + `-32601`); non-string version → 400 `UnsupportedProtocolVersion`.
|
|
1392
|
+
- Present header → validated against supported versions (`2025-03-26`, `2025-06-18`, `2025-11-25`, `2026-07-28`). When `params._meta` declares `io.modelcontextprotocol/protocolVersion`, header and body must agree (disagreement → 400 `HeaderMismatch`). Modern revision requires `_meta` version (absent → 400 `MissingMeta`).
|
|
1393
|
+
- Absent header + present `_meta` version → 400 `MissingHeader`.
|
|
1394
|
+
- No marker at all (no header, `_meta` absent or version-less) → legacy default `2025-03-26`.
|
|
1395
|
+
- Unsupported version string → 400 `UnsupportedProtocolVersion`.
|
|
836
1396
|
|
|
837
1397
|
**Method / error mapping.**
|
|
838
1398
|
- Unknown method → `404` + JSON-RPC `-32601`. Unknown tool → `404` + `-32601`.
|
|
@@ -852,45 +1412,68 @@ Two credential kinds resolve to one `McpCaller`:
|
|
|
852
1412
|
- session-scoped MCP tokens → `{ kind:"session", sessionId }`, has originating session
|
|
853
1413
|
- paired-device bearers → `{ kind:"device", deviceId }`, no originating session
|
|
854
1414
|
|
|
855
|
-
**
|
|
1415
|
+
**Throttle.** Pre-auth brute-force control keyed `(ip, SHA-256 credential fingerprint)` at 10 failures / 60 s (`MAX_AUTH_FAILURES`, `packages/mcp-server-plugin/src/server/rate-limit.ts`) plus coarser per-ip ceiling 100 / 60 s (`MAX_IP_AUTH_FAILURES`, D7). Every local session shares 127.0.0.1 — ip-only key let one stale token deny all others. Fingerprint never logged (X6). Success clears both buckets.
|
|
1416
|
+
|
|
1417
|
+
**Session tokens.** Opaque 256-bit. `mcp_` prefix. SHA-256 at rest. Plaintext returned once at mint. Constant-time compare. Flat-array scan, no membership-timing leak. No independent expiry — a token's lifetime IS its session's lifetime. IN-MEMORY only: no `mcp-tokens.json`. Registry dies with the plugin. All die on restart. Sessions re-mint when bridge re-registers. Revocation: `onSessionEnded` / bridge disconnect (primary), mint-replaces (D4; re-mint on reconnect invalidates previous token immediately), explicit `mcp/revoke-token`, process exit / plugin unload.
|
|
856
1418
|
|
|
857
|
-
**Minting.** `mcp/mint-token` over
|
|
1419
|
+
**Minting.** Bridge calls `mcp/mint-token` over session's own bridge WebSocket on every (re)registration (`bridge.ts`, D3). Server mints via `McpTokenRegistry.mintForSession` — REPLACES session's row (D4; stale token dead on re-mint). Server attributes it to session CONNECTION registered as (`currentSessionId`), never `msg.sessionId`. `mcp/revoke-token` revokes by session. Reply is `{type:"mcp_token_minted", token, url}`; `url = dashboardMcpUrl(port)` = `http://127.0.0.1:<host.httpPort>/mcp` (live getter at mint time, fallback 8000).
|
|
858
1420
|
|
|
859
1421
|
`plugin_pi_message.sessionId` a REQUIRED protocol field (`protocol.ts:593`), always present. `pi-gateway.ts` previously preferred it over the connection — a bridge could name any session and receive that session's credential. `plugin_pi_message` now excluded from body-sessionId precedence. Other message types keep prior behaviour.
|
|
860
1422
|
|
|
861
1423
|
Guarantee stated exactly: "the session this connection registered as". Not spoofable per-message — what the self-target guard needs. NOT a claim about pi-gateway port authentication. `currentSessionId` itself set from the first `register` message. Pre-existing bridge trust model. Out of scope here.
|
|
862
1424
|
|
|
863
|
-
|
|
1425
|
+
Reply travels ONLY on session-private extension lane: `mcp_token_minted` (`packages/shared/src/protocol.ts`; `McpTokenMintedExtensionMessage` gains an optional `url`), sent via trust-gated `sendExtensionMessage` context capability (`packages/dashboard-plugin-runtime/src/server/server-context.ts`; wired trust-gated in `packages/server/src/server.ts`, gate = manifest priority ≤ 100). NEVER `pi.events` — `plugin_emit_event` measured to reach unrelated subscribers (spike Q4b).
|
|
864
1426
|
|
|
865
|
-
**
|
|
1427
|
+
**Registration (replaces provisioning).** `packages/extension/src/mcp-token-delivery.ts` builds `createMcpDashboardRegistrar({pi, sessionId, reportUnavailable, log})`. On `onMinted(msg)` (requires `token` + `url`) it calls `pi.registerMcpServer("pi-dashboard", { url, headers: { Authorization: "Bearer <token>" }, exposure: "deferred" })`. Re-mint re-registers — a later registration of the same name REPLACES the earlier one. `onSessionShutdown()` calls `pi.unregisterMcpServer("pi-dashboard")`; `onSessionStart()` re-arms (new/fork/resume keep the same extension instance). Wired in `packages/extension/src/bridge.ts` (`mcp_token_minted` → `onMinted`, `session_start` → `onSessionStart`, `session_shutdown` → `onSessionShutdown`). Exports `DASHBOARD_MCP_SERVER_NAME`, `McpRegistrationApi`, `McpTokenMintedPayload`. NO per-session `mcp.json` write, no header script. Exposure `deferred` → pi auto-activates `tool_search`; found tools then called directly. An `mcp.json` entry named `pi-dashboard` TAKES PRECEDENCE over the registration.
|
|
866
1428
|
|
|
867
|
-
**
|
|
1429
|
+
**Guard.** Missing or throwing `registerMcpServer`, or delivery without `url` → NO registration, one warn log naming the session id, one `plugin_pi_message` `mcp-server`/`mcp/registration-unavailable` `{reason: "api-missing" | "register-failed" | "no-url"}` for the doctor. An installed `pi-mcp-adapter` does NOT throw (pi reports an extension error) — the doctor's adapter row covers it. The dashboard registers NO `/mcp` pi command (static scan `no-mcp-command.test.ts` asserts no `pi.registerCommand` name across `packages/*/src` is `mcp`).
|
|
1430
|
+
|
|
1431
|
+
**Protocol era.** pi sessions reach `/mcp` in the LEGACY era: pi 1.0.0's client offers `2024-11-05`…`2025-11-25` and sends `2025-11-25`. Every request/response tool works. `subscriptions/listen` streaming (modern-era only) is NOT available to pi sessions. Requires pi ≥ 1.0.0.
|
|
868
1432
|
|
|
869
|
-
**
|
|
1433
|
+
**Startup migration.** `packages/mcp-server-plugin/src/server/legacy-entry-migration.ts` (D2). On server start `index.ts` runs `migrateProvisionedEntry` + `logMigration` (never throws). Removes the old provisioned Pi-global `mcp.json` key `pi-dashboard` IFF it matches the provisioned signature (`isProvisionedDashboardEntry`: `requestHeadersCommand.command === "node"` + `args[0]` ending `header-command.mjs`). Via `createMcpClientConfigService` — merge-only, atomic, refuses an unparseable file. A non-matching operator entry is KEPT + warned (it would shadow the registration). Idempotent, no marker. Exports `DASHBOARD_MCP_KEY`, `MigrationResult` (`absent | removed | kept-operator-entry | skipped-unparseable | failed`), `migrateProvisionedEntry(configIO,{paths?})`, `logMigration(result, logger)`. New pi handler `mcp/registration-unavailable` logs `mcp.dashboard_registration_unavailable session=<id> reason=<r>`. Removed: provisioning, the adapter diagnostic, and the `onMcpRequest` route hook (`routes.ts` `McpRouteDeps.onMcpRequest` gone).
|
|
870
1434
|
|
|
871
|
-
**
|
|
1435
|
+
**Direct device-token mint.** `POST /api/paired-devices` issues durable bearer credentials for external MCP clients (Claude Code, Cursor). Gated by `operatorGuard`: requires dashboard login session (`authVia === "session"`), valid `X-Pi-Local-Token`, or genuine local loopback (`isGenuinelyLocal`, no proxy headers). Enforces unconditional Host admission (closes DNS-rebinding). Accepts `{ label, tier }` (`tier` optional, `"observe" | "control" | "operate"`, default `"observe"`, 1..64 UTF-8 bytes for label). Plaintext token returned ONCE in response, never stored or retrievable. Paired-device registry (`~/.pi/dashboard/paired-devices.json`, 0600) stores SHA-256 hash with `source: "manual"` (`source: "pairing"` for QR pairing), `tier` field. Rows without `tier` read as `"operate"` (back-compat with existing paired devices). Revocation via `DELETE /api/paired-devices/:id`.
|
|
1436
|
+
|
|
1437
|
+
**Tier model.** Three ordered tiers: `observe < control < operate`. Registry row holds `tier`. Session-kind MCP tokens hard-wired `control`. Missing `tier` resolves to `operate`.
|
|
1438
|
+
|
|
1439
|
+
**REST tier gate.** `packages/shared/src/route-tiers.ts` defines `ROUTE_TIERS` map + `routeTier()`. Route not in map defaults to `operate` (fail closed). Gate `packages/server/src/auth/route-tier-gate.ts` checks off-host paired-device bearer credentials: tier below required route tier → HTTP 403 + `WWW-Authenticate: Bearer error="insufficient_scope", scope="<tier>"`. Genuinely-local or trusted-network bearers exempt (pass unrestricted). Route `/api/ws-ticket` classified `operate` (prevents privilege escalation to full browser WS).
|
|
1440
|
+
|
|
1441
|
+
**`/mcp` surface.** Tools list filtered to caller tier (`tools/list`). Calling tool above caller tier (`tools/call`) → HTTP 403 + JSON-RPC error `-32001` + `scope: "<tier>"`. Path caps: `/mcp/observe`, `/mcp/control` cap caller tier to path suffix. `/mcp/operate` and unknown suffixes return 404 JSON (no operate path cap).
|
|
1442
|
+
|
|
1443
|
+
**Manifest pipeline.** `packages/mcp-server-plugin/src/server/tools.manifest.ts` is hand-reviewed tool source of truth. Codegen `src/codegen/generate-tools.ts` emits `src/server/generated/tools.ts` + README `<!-- tools:start/end -->` block. Freshness test re-runs generator and fails on drift. Completeness test `packages/server/src/__tests__/mcp-manifest-completeness.test.ts` validates every `/api/*` route and browser-WS verb is either bound in manifest or listed on `tools.denylist.ts`.
|
|
1444
|
+
|
|
1445
|
+
**Manifest binding kinds.**
|
|
1446
|
+
- `rest`: invokes internal route via `fastify.inject`; forwards caller identity per design D4.
|
|
1447
|
+
- `session`: dispatches to bridge via `sendToSession`.
|
|
1448
|
+
- `context`: invokes original 4 tools (`list_sessions` in `observe`; `send_prompt`, `spawn_session`, `abort` in `control`).
|
|
1449
|
+
|
|
1450
|
+
**Reachable endpoints & issuance.** Endpoint `/api/pair/reachable-urls` returns merged local interfaces + active tunnel/public base URLs. Client issuance UI includes tier picker (`observe`, `control`, `operate`) and base-URL selector. CLI supports tier and base URL flags: `pi-dashboard token create --label <l> [--tier <t>] [--url <base>]`.
|
|
1451
|
+
|
|
1452
|
+
**Self-target guard.** Refuses a session-targeting tool call (`send_prompt`, `abort`) whose target equals the caller's own resolved session. Target normalised for equality (trim, one quote pair, lowercase) — bypass-proof. Catches DIRECT self-targeting only. Indirect A→B→A loop permitted, documented out of scope. Device callers have no originating session, structurally outside the guard.
|
|
1453
|
+
|
|
1454
|
+
**Tool surface.** Generated from the reviewed manifest, filtered by caller tier. 4 context tools: `list_sessions` (`observe`), `send_prompt` (`control`), `spawn_session` (`control`), `abort` (`control`). REST and session tools route through manifest bindings with tier constraints. `abort` maps to `abortSession` (soft-only, false on a disconnected bridge), NOT `abortSpawnedRun`. `sessionId` an ordinary required argument. `list_sessions` is bounded, filterable, cursor-paged: envelope `{ sessions, total, nextCursor? }`; default limit 25, hard max 200; `hidden` worker sessions excluded; keyset cursor over `endedAt ?? lastActivityAt ?? startedAt` desc, `id` tiebreak; the bound is advertised in `inputSchema` + description, unknown argument rejected (`additionalProperties: false`), wrong type/range/enum → `-32602` before the handler; handler delegates to `listSessions()` in `packages/mcp-server-plugin/src/server/list-sessions.ts`. See change: paginate-mcp-list-sessions.
|
|
1455
|
+
|
|
1456
|
+
**Streaming.** `subscriptions/listen`, a long-lived POST-response stream. `params.sessionIds[]` required; absent/empty/non-array → `-32602`. No subscribe-to-all. Filter applied per subscription before write. Authorisation re-checked per delivery. Revoked mid-stream → terminates it. Slow consumer → subscription TERMINATED at `MAX_BUFFERED_EVENTS` (1000) buffered events. Does NOT silently drop events. Subscription dies with its request.
|
|
872
1457
|
|
|
873
1458
|
**Config reference.** `MCP_BODY_LIMIT_BYTES` 1 MiB body cap. `MAX_BUFFERED_EVENTS` 1000 buffered events.
|
|
874
1459
|
|
|
875
1460
|
```mermaid
|
|
876
1461
|
sequenceDiagram
|
|
877
|
-
participant
|
|
878
|
-
participant S as /mcp
|
|
879
|
-
participant
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
Note over S,R: session token kind
|
|
886
|
-
B->>S: mcp/mint-token (over session's own socket)
|
|
887
|
-
S->>R: mintForSession(sessionId from socket key)
|
|
888
|
-
R-->>B: plaintext token (once)
|
|
1462
|
+
participant B as Bridge
|
|
1463
|
+
participant S as Server (/mcp tokens)
|
|
1464
|
+
participant P as pi built-in MCP
|
|
1465
|
+
B->>S: plugin_pi_message mcp/mint-token
|
|
1466
|
+
S-->>B: mcp_token_minted {token, url}
|
|
1467
|
+
B->>P: registerMcpServer("pi-dashboard", {url, headers:{Authorization:"Bearer "+token}, exposure:"deferred"})
|
|
1468
|
+
Note over B,P: dashboard restart → re-mint → register again (replaces)
|
|
1469
|
+
B->>P: unregisterMcpServer("pi-dashboard") on session_shutdown
|
|
889
1470
|
```
|
|
890
1471
|
|
|
891
1472
|
**Seam change.** `RegisterPiHandlerFn` widened to `(msg, sessionId)`. Gateway passes its socket key through `dispatchPluginPiMessage`. Additive — `(msg)`-only handlers still valid. `sessionId` from the socket key, never the message body — a plugin can attribute a bridge message as a trust decision.
|
|
892
1473
|
|
|
893
|
-
|
|
1474
|
+
**Security notes (accepted exposure).** The bearer lives ONLY in pi's in-memory `pi-dashboard` registration — never `process.env`, never a file, never `pi.events`, never a log line. REMOVED: `PI_DASHBOARD_MCP_TOKEN` and `header-command.mjs`, which put the token in EVERY subprocess's environment. Remaining exposure: an in-process extension can read it via `pi.getMcpServers()`. Accepted — extensions are trusted in-process code that could already read `process.env`; subprocesses, the documented exposure, no longer see it. Plaintext never at rest, never logged (asserted X4/X5).
|
|
1475
|
+
|
|
1476
|
+
See change: add-dashboard-mcp-server, wire-mcp-session-token, mcp-legacy-clients-and-token-issuance, expand-mcp-tiered-surface, migrate-mcp-to-pi-builtin.
|
|
894
1477
|
|
|
895
1478
|
### Bootstrap & First Run (R3, immutable bundle)
|
|
896
1479
|
|
|
@@ -902,7 +1485,15 @@ pi/openspec/tsx are regular npm dependencies of `@blackbelt-technology/pi-dashbo
|
|
|
902
1485
|
|
|
903
1486
|
`launchSource` (returned by `/api/health`) is `"electron" | "standalone" | "bridge"`, derived from `DASHBOARD_STARTER`. Client uses it via `useLaunchSource()` to hide pi-core update UI on Electron (immutable bundle has no writable target).
|
|
904
1487
|
|
|
905
|
-
Compatibility skew helpers in `pi-version-skew.ts` (`readPiCompatibility`, `readCurrentPiVersion`, `computeCompatibility`) survive as pure helpers. The pinned range is `minimum: "0.
|
|
1488
|
+
Compatibility skew helpers in `pi-version-skew.ts` (`readPiCompatibility`, `readCurrentPiVersion`, `computeCompatibility`) survive as pure helpers. The pinned range is `minimum: "1.0.0"`, `recommended: "1.0.0"`, `maximum: null` (lockstep — one supported pi means no conditional code paths on that artifact). `piCompatibility` unchanged: a `@earendil-works/pi-coding-agent` range, a DIFFERENT artifact from the pi-ai pin below.
|
|
1489
|
+
|
|
1490
|
+
**Below-floor session signal.** Replaces per-feature pi version gates. Bridge `sendPiVersionIfChanged` (`packages/extension/src/model-tracker.ts`) reads the running pi argv-anchored via `readRunningPiVersion` and sends `pi_version_update`; server runs `computePiBelowFloor(version, serverPiMinimum())` (`packages/server/src/pi/pi-version-skew.ts`) → sets `DashboardSession.piBelowFloor: { minimum } | null`; client `PiBelowFloorWarning` renders on `SessionCard` + `SessionHeader`. Unknown or unparseable version → no flag. `minimum` sourced from `piCompatibility.minimum`. See change: update-pi-core-1-0-adopt-apis.
|
|
1491
|
+
|
|
1492
|
+
**pi-ai generation window.** Legacy generation REMOVED — the dashboard supports ONE **pi-ai** generation (pi >= 1.0.0). Supported range `>=1.0.0` (root `package.json` + `packages/extension/package.json` peerDependencies). Root devDependency pin `^1.0.0`. The server streams through pi-coding-agent's own **`ModelRuntime`** (ONE server runtime — see `### Single model runtime`), which owns module shape (factory API only), transcript normalization (`normalizeContext` before dispatch, else systemPrompt + tools drop silently) and OAuth relocation (`dist/oauth.js` is a TYPE-ONLY stub, never consulted; real loaders at `dist/auth/oauth/*.js`, a path NOT in the package `exports` map). `packages/extension/src/bridge.ts` streams through pi's own `ctx.modelRegistry.streamSimple`. The `packages/shared/src/piai-compat/` seam (`adaptPiAi`), its `api-table.ts` / `NON_TEXT_LAZY_FILES` helpers and `packages/shared/src/test-support/piai-factory-fixture.ts` are DELETED.
|
|
1493
|
+
|
|
1494
|
+
See change: collapse-model-proxy-onto-modelruntime.
|
|
1495
|
+
|
|
1496
|
+
**Host project-trust service.** `packages/server/src/server.ts` registers `host.isProjectTrusted(cwd)` (awaited at boot) next to `host.knownFolderCwds`. `packages/server/src/pi/host-project-trust.ts` `createHostProjectTrust({recordedDecision, defaultProjectTrust})` / `loadHostProjectTrust(agentDir)` mirrors a session's own rule: the recorded `ProjectTrustStore` decision wins, else `defaultProjectTrust === "always"`. Unresolvable pi → always false. `mcp-client` injects it as `isProjectTrusted` so folder MCP rows load the project layer only in trusted folders. See change: migrate-mcp-to-pi-builtin.
|
|
906
1497
|
|
|
907
1498
|
#### Legacy `~/.pi-dashboard/` advisory
|
|
908
1499
|
|
|
@@ -916,7 +1507,7 @@ Offer sessions for recovery after server restart. Distinguish crashes (sessions
|
|
|
916
1507
|
|
|
917
1508
|
**Boot record.** File `~/.pi/dashboard/boot-state.json`. One O(1) write per exit, not per session (exit paths have ~100 ms and cannot walk sidecars). Shape: `{ bootId, exitIntent, at, ring: BootRecord[] }`. `bootId` = server `liveEpoch`. `ring` = 8 most recent prior boots (`BOOT_RING_SIZE`). Atomic write via `writeJsonFile` (tmp + rename). Owner: `packages/server/src/persistence/boot-state.ts`. Exports `stampBootStart(bootId)`, `recordExitIntent(intent)`, `resolveExitIntent(liveEpoch)`, `readBootState()`, `_resetBootStateForTests()`.
|
|
918
1509
|
|
|
919
|
-
**Exit intent vocabulary.** `packages/shared/src/boot-state.ts`. `ExitIntent = "restart" | "shutdown" | "user-quit" | "idle" | "signal"`. Null = crash (nothing recorded). Function `isRecoveryAllowed(intent)` returns false ONLY for `restart` and `
|
|
1510
|
+
**Exit intent vocabulary.** `packages/shared/src/boot-state.ts`. `ExitIntent = "restart" | "shutdown" | "user-quit" | "idle" | "signal" | "ephemeral"`. Null = crash (nothing recorded). Function `isRecoveryAllowed(intent)` returns false ONLY for `restart`, `shutdown`, and `ephemeral` — those exits leave sessions RUNNING and announce a bridge quiesce longer than the reattach grace window, so sessions reattach after any window that could retract them. `ephemeral` joins the recovery-suppressing set so a parent-death exit is not treated as a crash to recover from (change: fix-autostart-discovery-precedence). Other exits + null allow recovery via the liveness gate: offer session, retract if it re-registers inside the grace window.
|
|
920
1511
|
|
|
921
1512
|
**Recording points.** `POST /api/restart` → `restart`. `POST /api/shutdown` → `shutdown`, or `user-quit` when request body is `{userQuit:true}` (Electron `stopServerIfNeeded` in `packages/electron/src/lib/server-lifecycle.ts` sends it). Idle timer → `server.stop()` → `idle`. New SIGTERM/SIGINT handler in `packages/server/src/cli.ts::runForeground()` → `signal` then `server.flush()` then `process.exit(0)`. Crash/SIGKILL records nothing → stays null. `recordExitIntent` is write-once per boot (first writer wins), so `spawnRestart`'s SIGTERM→SIGKILL ladder cannot overwrite `restart` with `signal`. Write failure logged, never thrown; unwritten intent = dirty boot = over-offer (conservative direction).
|
|
922
1513
|
|
|
@@ -932,6 +1523,16 @@ Offer sessions for recovery after server restart. Distinguish crashes (sessions
|
|
|
932
1523
|
|
|
933
1524
|
**Observability.** Logs: `[recovery] <id>: suppressed-by-intent (boot <epoch> exited via <intent>)`, `[recovery] N candidate(s) after exit-intent gate; awaiting liveness`, `[recovery] grace window closed; offering N candidate(s)`, `[recovery] retracted candidate <id> (<reason>)`, `[recovery] refused reopen of <id>: keeper still alive`, `[boot-state] exit intent recorded: <intent> (boot <id>)`.
|
|
934
1525
|
|
|
1526
|
+
### Ephemeral Server Lifecycle (change: fix-autostart-discovery-precedence)
|
|
1527
|
+
|
|
1528
|
+
A server started with `--ephemeral` exists only to serve the pi agent that booted it. When that boot parent dies, the server exits and reclaims its ports + memory instead of leaking them. Target: isolated-verification instances. Standalone + Electron-hosted servers excluded by construction — nothing passes the flag for them.
|
|
1529
|
+
|
|
1530
|
+
- **Opt-in: flag ONLY.** `--ephemeral` in `packages/server/src/cli.ts` (`parseArgs` → `buildConfig` → `config.ephemeral`). NO env var; never inferred from temp `HOME`, bind address, or port. An inherited `PI_DASHBOARD_EPHEMERAL=1` in a shell would make a real standalone dashboard exit when that shell dies.
|
|
1531
|
+
- **Watch** — `packages/server/src/lifecycle/ephemeral-parent-watch.ts`. Independent, unconditional 5 s interval (fixed `DEFAULT_INTERVAL_MS` 5000, overridable only via the `intervalMs` dep seam); armed only when ephemeral. Idle timer CANNOT host the check — its `start()` early-returns when `config.autoShutdown` is false (the default, the exact isolated-verification config) and it terminates via raw `process.exit(0)` (the undrained-exit path this design forbids). Interval cadence IS the exit-latency bound.
|
|
1532
|
+
- **Kill-decision liveness** — `isBootParentProvablyDead` (`packages/server/src/lifecycle/boot-parent-liveness.ts`). Dead ONLY on ESRCH (Tier-1 signal-0 probe) or Windows Tier-2 signalled-exit (reuse-immune koffi handle, authoritative where it exists). `EPERM` + any other errno = ALIVE (parent alive but owned by another user / hardened). Alive-biased: reads-alive → occasionally fails to exit, never a false exit.
|
|
1533
|
+
- **Exit path** — proven-dead parent → `server.stop({ exitIntent: "ephemeral" })` (`server.ts` wiring), fired exactly once. Graceful drain (`shutdownHeadlessProcesses` reaps spawned pi, `recordExitIntent`, flush, tunnel teardown). Never `process.exit`.
|
|
1534
|
+
- **Health field** — `/api/health` exposes `ephemeral` (boolean, `config.ephemeral === true`) via `packages/server/src/routes/system-routes.ts`.
|
|
1535
|
+
|
|
935
1536
|
### Force Kill Escalation
|
|
936
1537
|
The Stop button supports two-click escalation for stuck sessions:
|
|
937
1538
|
1. **Click 1 (Abort)**: Sends `abort` → bridge → `ctx.abort()`. Button transitions to orange pulsing "Force Stop".
|
|
@@ -1155,21 +1756,22 @@ flowchart TD
|
|
|
1155
1756
|
S --> DONE
|
|
1156
1757
|
```
|
|
1157
1758
|
|
|
1158
|
-
**Triggers** —
|
|
1759
|
+
**Triggers** — seven sources route through `dispatchReload`; pi-core update is the one exception:
|
|
1159
1760
|
1. Reload button / `/reload` in composer → browser `send_prompt` → `packages/server/src/browser-handlers/session-action-handler.ts` `handleSendPrompt`.
|
|
1160
1761
|
2. `scripts/reload-all.sh` → same browser path.
|
|
1161
1762
|
3. pi retry-policy settings save → `server.ts` `reloadConnectedSessions`.
|
|
1162
1763
|
4. Package install/remove → `packageManagerWrapper.setReloadSessions`.
|
|
1163
1764
|
5. pi-core update complete → `piCoreUpdater.onAllComplete` → `respawnForRuntimeSwap` (NOT `dispatchReload`).
|
|
1164
1765
|
6. `POST /api/resources/reload` → `routes/resource-activation-routes.ts`.
|
|
1766
|
+
7. Radius MCP configure write (`POST /api/provider-auth/radius/mcp`) → `countReloads(reloadFanOutTargets(), dispatchReload)` in `server.ts`. See change: add-radius-provider-login (D5, D6).
|
|
1165
1767
|
|
|
1166
1768
|
**Predicate gate** — `isBareReloadCommand` in `browser-handlers/session-action-helpers.ts`. `text === "/reload"` exactly, zero images, says nothing about session shape. Replaced old `shouldInterceptReload`, which also required a headless PID and thereby made kill-and-respawn the default.
|
|
1167
1769
|
|
|
1168
|
-
**Why no in-process path.** Earlier revision wrote `/__dashboard_reload` to the session's RPC keeper, on the claim that pi RPC mode runs the line through `session.prompt()` WITH command handling. Measured in the docker harness with `keeperLog.capturePiOutput = true
|
|
1770
|
+
**Why no in-process path.** Earlier revision wrote `/__dashboard_reload` to the session's RPC keeper, on the claim that pi RPC mode runs the line through `session.prompt()` WITH command handling. Measured in the docker harness with `keeperLog.capturePiOutput = true` on pi < 0.84.2: it does not — pi's RPC `{type:"prompt"}` performed NO slash-command dispatch. Dispatched `/__dashboard_reload` arrived at the model as an ordinary user prompt and produced a full agent turn (`agent_start` → user message → assistant reply → `agent_end`). Control: pi built-in `/help` written to the same socket behaved identically — so not the `__` prefix, not our registration. (Pi >= 0.84.2 RPC `prompt()` defaults `expandPromptTemplates` ON; the original measurement predates that. Decision unaffected — `/__dashboard_reload` is STILL never written to the keeper.) Consequence: kill-and-respawn is the ONLY mechanism that reloads a headless session. Scope: SERVER/keeper path only — server never writes `/__dashboard_reload` to the keeper. Terminal-hosted sessions DO reload in-process, on the BRIDGE side (`terminal-reload.ts` self-dispatch via `sendUserMessage`; see Bridge side below). See change: fix-terminal-session-dashboard-reload. The extension-slash `dispatch_extension_command` route used the same keeper `writeRpc` + `{type:"prompt"}` mechanism; it was retired by change `retire-slash-dispatch-via-expand-prompt-templates` (bridge dispatches in-process via `sendUserMessage({expandPromptTemplates: true})`).
|
|
1169
1771
|
|
|
1170
1772
|
**Ladder step 1 — busy check.** `isReloadBusy` runs FIRST. Refuse if `session.compacting === true`. Refuse if `status === "streaming"` AND `piGateway.isSessionConnected(sessionId)`. Stale `streaming` on a bridge-dead session does NOT refuse — pinned there forever, and exactly what respawn rescues.
|
|
1171
1773
|
|
|
1172
|
-
**Ladder step 2 — kill-and-respawn.** `headlessPidRegistry.getPid(sessionId)` defined → `handleHeadlessReload` (SIGTERM + `spawnPiSession` `mode:"continue"`), streaming guard suppressed. Registered PID wins over a live bridge:
|
|
1774
|
+
**Ladder step 2 — kill-and-respawn.** `headlessPidRegistry.getPid(sessionId)` defined → `handleHeadlessReload` (SIGTERM + `spawnPiSession` `mode:"continue"`), streaming guard suppressed. Registered PID wins over a live bridge: dashboard-spawned session reloads via respawn; in-process bridge reload (`terminal-reload.ts`) applies to terminal-hosted sessions only. See change: fix-terminal-session-dashboard-reload.
|
|
1173
1775
|
|
|
1174
1776
|
**Ladder step 3 — bridge forward.** No PID, `isSessionConnected` true → `piGateway.sendToSession(sid, {type:"send_prompt", text:"/reload"})`. Gated on the RETURN VALUE, not the probe: the socket can close between the two.
|
|
1175
1777
|
|
|
@@ -1177,7 +1779,17 @@ flowchart TD
|
|
|
1177
1779
|
|
|
1178
1780
|
**Feedback contract** — exactly one terminal `command_feedback` per reload, `command` field always `/reload`.
|
|
1179
1781
|
|
|
1180
|
-
**Bridge side** — `packages/extension/src/
|
|
1782
|
+
**Bridge side** — terminal-hosted path only; ladder step 2 wins for dashboard-spawned sessions. `BridgeCommandOptions.reload` = `terminalReload.reload` (`createTerminalReload`, `packages/extension/src/terminal-reload.ts`). `ExtensionContext` has no `reload()`; only a command handler's `ExtensionCommandContext` does. So `reload()` self-dispatches `pi.sendUserMessage("/__dashboard_reload <token>", {expandPromptTemplates: true})` — pi runs `_tryExecuteExtensionCommand`, hands handler FRESH command ctx → `ctx.reload()`. No TUI bootstrap. Nothing callable captured — works every reload (retired captured-fn-on-`globalThis` path was single-use, stale ctx after first reload). No pi version gate (`update-pi-core-1-0-adopt-apis`): `supportsInProcessCommandDispatch` and `NO_RELOAD_PATH_REASON` retired — the check could never fail on a supported pi (1.0.0 floor). `BridgeCommandOptions.reload` returns `ReloadOutcome` (`{ok:true, handedOff:true}` | `{ok:false, reason}`). See change: fix-terminal-session-dashboard-reload.
|
|
1783
|
+
|
|
1784
|
+
**Token handshake** — slot `process.__pi_dashboard_pending_reload__ = {token, sessionId, state, armedAt}`. State `armed → started → delivered | expired`. Transitions compare-and-set — requesting instance `error` and reloaded instance `completed` mutually exclusive. `START_TIMEOUT_MS` = 5000, `FINISH_TIMEOUT_MS` = 60000, both measured from `armedAt`.
|
|
1785
|
+
|
|
1786
|
+
**Completion from RELOADED instance** — reload tears down the requesting instance's connection, so the NEW bridge instance reports. `consumePendingReloadOnSessionStart` runs at top of `session_start{reason:"reload"}`; `command_feedback {command:"/reload", status:"completed"}` sent after `replay_complete`. Requesting instance returns `{ok:true, handedOff:true}` → `command-handler.ts` emits nothing. Requesting instance reports every failure: did not run (start timeout, `RELOAD_DID_NOT_RUN_REASON`), pi did not reload (refused/threw, `PI_DID_NOT_RELOAD_REASON`), timeout (`RELOAD_TIMEOUT_REASON`), sync throw, reload already in progress (`RELOAD_IN_PROGRESS_REASON`).
|
|
1787
|
+
|
|
1788
|
+
**TUI-typed `/__dashboard_reload` (no args)** — reloads, no dashboard feedback. `ctx.ui.notify` warning if dashboard reload in flight.
|
|
1789
|
+
|
|
1790
|
+
**Re-entry guard** — `session_shutdown{reason:"reload"}` → `releaseBridgeOwnerOnShutdown` clears `prev.pi`; reloaded instance (fresh `ExtensionAPI`) passes `isBridgeReentry`. Before: every in-process reload (TUI `/reload` too) left dashboard session `ended`.
|
|
1791
|
+
|
|
1792
|
+
**Server watch** — `packages/server/src/rpc-keeper/dispatch-reload.ts` keeps per-session forwarded-reload watch. Second reload while one in flight → `"refused"` + error `"A reload is already in progress for this session."` — not forwarded. Deadline `FORWARDED_RELOAD_DEADLINE_MS` = 75000 → server emits `/reload` error `"Reload did not report completion within 75 s — check the pi terminal."`; later bridge feedback dropped (mark cleared by next arm). Watch survives the reload's own unregister/re-register. `event-wiring.ts` calls `routeReloadFeedback` BEFORE the replay-skip early return: settles watch; inside replay-skip window persists + broadcasts feedback itself.
|
|
1181
1793
|
|
|
1182
1794
|
**Compaction signal** — `DashboardSession.compacting` (new, `packages/shared/src/types.ts`). Derived in `packages/server/src/session/event-status-extraction.ts` from bridge-forwarded `session_before_compact` (true) and `session_compact` (false). Cleared in `memory-session-manager.unregister`; never carried onto a re-registration.
|
|
1183
1795
|
|
|
@@ -1452,6 +2064,55 @@ Bridge-side. `packages/extension/src/auto-session-namer.ts`. After each terminal
|
|
|
1452
2064
|
|
|
1453
2065
|
See change: fix-auto-naming-reasoning-model.
|
|
1454
2066
|
|
|
2067
|
+
### HTTP Role Read Surface (change: add-roles-read-api)
|
|
2068
|
+
|
|
2069
|
+
**Endpoint.**
|
|
2070
|
+
|
|
2071
|
+
- `GET /api/roles` — read-only role catalogue. Ungated beyond dashboard auth gate. No `pi-proxy-...` Bearer key. No live pi session required. Mirrors `GET /api/models` envelope + auth posture.
|
|
2072
|
+
|
|
2073
|
+
**Route ownership and registration.**
|
|
2074
|
+
|
|
2075
|
+
- Owned by roles-plugin, NOT `packages/server/src/routes/`. Manifest entry `"server": "./src/server/index.ts"` in `packages/roles-plugin/package.json`. Entry point `registerPlugin(ctx)` calls `mountRolesRoutes(ctx.fastify)` in `packages/roles-plugin/src/server/index.ts`. Route impl at `packages/roles-plugin/src/server/roles-routes.ts`. Registered WITHOUT `networkGuard` preHandler. Host owns `fastify.listen`; plugin only registers.
|
|
2076
|
+
|
|
2077
|
+
**Response structure.**
|
|
2078
|
+
|
|
2079
|
+
- Envelope: `{ object: "list", data: RoleGroup[] }`.
|
|
2080
|
+
- Each group: `{ preset, active, roles }`.
|
|
2081
|
+
- Live group first (`preset: null`); then preset groups in stored order. Exactly one group `active: true`.
|
|
2082
|
+
- Row: `{ role, ref, assigned, builtin }` always; `model`, `provider`, `thinkingLevel` added only when derivable.
|
|
2083
|
+
- `ref: null` for unassigned role (expected state, never an error).
|
|
2084
|
+
- `builtin` = role name in `DEFAULT_ROLE_NAMES`.
|
|
2085
|
+
|
|
2086
|
+
**Role axis construction.**
|
|
2087
|
+
|
|
2088
|
+
- Canonical axis = (defaults → user-added → assigned) ∪ preset-only names (first-referencing-preset order) − `removedRoles`.
|
|
2089
|
+
- Same axis + order in every group.
|
|
2090
|
+
- `ref` split: last colon → `model`/`thinkingLevel`; first `/` → `provider`.
|
|
2091
|
+
- Bare legacy id → `provider` omitted, never guessed. Stored value never rewritten.
|
|
2092
|
+
- Model registry NOT consulted.
|
|
2093
|
+
- Dangling `activePreset` (names no stored preset) → live group active.
|
|
2094
|
+
- Duplicate preset names collapse first-wins.
|
|
2095
|
+
|
|
2096
|
+
**Resilience and error handling.**
|
|
2097
|
+
|
|
2098
|
+
- Never 503. Never empty `data`.
|
|
2099
|
+
- Missing / unparseable / EACCES / EISDIR / TOCTOU config all degrade to "no assignments" → overlay still yields built-in names with `ref: null`.
|
|
2100
|
+
- Config file never created or modified by read.
|
|
2101
|
+
- Credential safety: rows built field-by-field from role/preset maps. Parsed config never serialized or spread into response. Credential-bearing sibling key of `providers.json` cannot reach payload.
|
|
2102
|
+
|
|
2103
|
+
**Per-key ownership split of `~/.pi/agent/providers.json`.**
|
|
2104
|
+
|
|
2105
|
+
- `role-manager.ts` (`packages/extension/src/`) = SOLE WRITER of role slice: `roles`, `rolePresets`, `activePreset`, `roleNames`, `removedRoles`. Atomic tmp+rename; preserves sibling keys.
|
|
2106
|
+
- `provider-routes.ts` (`packages/server/src/routes/`) writes `providers` key of same file. Atomic tmp+rename; preserves other fields.
|
|
2107
|
+
- Role slice reading is NON-exclusive. Every reader normalizes through one shared TOTAL normalizer `parseRoleConfig(raw)` in `packages/shared/src/role-schema.ts`. Pure role-schema helpers (`DEFAULT_ROLE_NAMES`, `effectiveRoleNames`, `overlayRoles`, `splitRef`/`joinRef`, types) live there — no `node:fs`, so client bundles it. `role-manager.ts` `loadRoleConfig` keeps file read but delegates normalization to `parseRoleConfig`.
|
|
2108
|
+
|
|
2109
|
+
**Declared read corrections vs old `roles:get-all`.**
|
|
2110
|
+
|
|
2111
|
+
- Structurally invalid preset entry now dropped (was relayed uninspected).
|
|
2112
|
+
- Role with both removal marker AND assignment now omitted (old trailing spread reintroduced it).
|
|
2113
|
+
|
|
2114
|
+
See change: add-roles-read-api.
|
|
2115
|
+
|
|
1455
2116
|
### Context Usage Tracking
|
|
1456
2117
|
1. On each `turn_end`, the bridge calls pi's `ctx.getContextUsage()` API to get real-time context usage (tokens used + actual context window from the provider)
|
|
1457
2118
|
2. Bridge enriches the `turn_end` event with this `contextUsage` data before forwarding to the server
|
|
@@ -1462,13 +2123,45 @@ See change: fix-auto-naming-reasoning-model.
|
|
|
1462
2123
|
7. Client's event reducer stores `contextUsage` from `stats_update` events; `App.tsx` falls back to `session.contextTokens/contextWindow` for sessions without live reducer state
|
|
1463
2124
|
8. When real data is unavailable (e.g., old sessions without persisted context data), `state-replay.ts` and `session-stats-reader.ts` use `inferContextWindow()` to estimate context window from the model name
|
|
1464
2125
|
|
|
2126
|
+
### Process Scan Cadence
|
|
2127
|
+
- One process-table snapshot per scan (`process-scanner.ts`): Unix `ps -A -o pid=,ppid=,pgid=,etime=,args=`; Windows `Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress`. Capture + check + dead-PGID reap all read that one snapshot.
|
|
2128
|
+
- Async `execFile`. Never blocks pi event loop.
|
|
2129
|
+
- Adaptive cadence (`process-scan-scheduler.ts`, self-rescheduling `setTimeout`): fast 5 s (Win 10 s) while agent/tool runs → +15 s after last activity → +30 s after scanned list change; idle 30 s (Win 60 s). Idle→fast re-arms immediately on `agent_start` / `tool_execution_start`.
|
|
2130
|
+
- Extra scan 1 s after a `bash` `tool_execution_end`.
|
|
2131
|
+
- Overlap skipped (`scanInFlight`), never queued.
|
|
2132
|
+
- Trade-off: process dying while idle leaves list ≤30 s later.
|
|
2133
|
+
|
|
2134
|
+
### Poll-cost counters
|
|
2135
|
+
- Heartbeat `metrics` flat optional scalars on `ProcessMetrics`: `pollProcScan*`, `pollGitProbes*`, `pollGitSpawns`, `pollGitMs`, `pollGitWatchersAttached`. Cumulative per bridge.
|
|
2136
|
+
- `/api/health` `pollCost` SUMS them across live sessions.
|
|
2137
|
+
- `pollGitWatchersAttached` = 0/1 per session; summed = sessions with a watch. Counters reset on reload/end; before/after reads each session's own counters over a fixed window.
|
|
2138
|
+
|
|
1465
2139
|
### VCS Polling (Git)
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
2140
|
+
Two git lanes, one probe in flight, async spawns — pi event loop never blocks on git.
|
|
2141
|
+
|
|
2142
|
+
- **Fast lane**: first evaluation, `HEAD` / `packed-refs` / `*_HEAD` watch events, `git_info_refresh`, reconnect. ≥2 s between probe starts.
|
|
2143
|
+
- **Slow lane**: 30 s tick, mutating tool end, `index` / `null` watch events. ≥10 s between probe starts. Tick always requests one → external edits seen ≤30 s; silently-dead watchers (Docker/WSL mounts) cost nothing extra.
|
|
2144
|
+
- 750 ms trailing debounce, 2 s max wait. Request inside a lane's window deferred, never dropped. Fast request upgrades pending slow one. One probe in flight + dirty bit → one follow-up max.
|
|
2145
|
+
- Probe: async `git --no-optional-locks status --porcelain=v2 --branch` via `gitStatusV2Async`. Branch read from `<gitDir>/HEAD`; non-`refs/heads/` value → async CLI fallback (`currentBranchOrAsync` + `headShaOrAsync`), memoised per HEAD content; previous branch kept while pending.
|
|
2146
|
+
- Files: `packages/extension/src/git-tracker.ts` (facts/status), `git-probe-scheduler.ts` (lanes, debounce, in-flight, `dispose()`), `git-dir-watcher.ts` (`fs.watch(gitDir, {persistent:false})` + `fs.watch(commonDir)` when different), `vcs-info.ts`.
|
|
2147
|
+
- Static facts cached per cwd (`StaticGitFacts`: `remoteUrl`, `roots`, `gitDir`, `dotGitStamp`). Async re-probe (`checkoutRootsAsync`, `remoteUrlOrAsync`) on `dotGitStamp` change, `git_info_refresh`, reconnect, every 10th tick (≈5 min). `dotGitStamp` = `fs.stat` of `<thisCheckout>/.git` + `gitDir`; non-repo stamp = existence of `<cwd>/.git`.
|
|
2148
|
+
- Sync first evaluation ONLY at registration, cwd change, session change, reconnect — handshake requires `git_info_update` carrying `gitWorktree` at once. Status omitted; immediate fast-lane probe sends it right after. `handleSessionChange` (`session-sync.ts`) also resets `lastGitStatusJson`.
|
|
2149
|
+
- Probe reads branch before start + at settle; mismatch or cwd change → discard + one more probe. Failed probe sends branch/facts with `gitStatus` omitted (inconclusive).
|
|
2150
|
+
- Send only from probe-result path (`sendGitInfoIfChanged`); tick/watcher never send directly. `pr-status.ts` `onChange` sends from cached state, no spawn.
|
|
2151
|
+
- PR: `prStatus.observe({branch})` on every resolved branch (first eval, tick, every settled probe incl. failed). Branch-change generation start throttled ≤1 per 30 s, latest branch wins; session/cwd change not throttled.
|
|
2152
|
+
- Read-only tool allow-list (`read`, `grep`, `find`, `ls`, `glob`, case-insensitive); unknown/MCP tools count mutating.
|
|
2153
|
+
- Rate bound: ≤6 slow + ≤30 fast probes/min worst case; idle 2/min async, 1 spawn.
|
|
2154
|
+
|
|
2155
|
+
### PR status
|
|
2156
|
+
PR detection moved OFF the 30 s git tick. `packages/extension/src/pr-status.ts` `createPrStatusScheduler` probes `gh pr view --json number,url,state,isDraft,statusCheckRollup` via `runAsync` (`GH_PR_STATUS`, 20 s timeout) in `packages/shared/src/platform/git.ts`; `classifyPrStatus` → parsed / absent (`no pull requests found`) / failure.
|
|
2157
|
+
Cadence: first observe immediate, then ≥120 s, back-off 120→240→480→600 s on failure, one failure log + one recovery log. Generation = sessionId+cwd+branch; branch change → all-null tuple sent at once + probe; session/cwd change → unknown.
|
|
2158
|
+
`sendGitInfoIfChanged` (`packages/extension/src/model-tracker.ts`) = one change-detector; always sends full cached tuple `gitPrNumber|Url|State|Draft|Checks|CheckedAt` (unknown omitted).
|
|
2159
|
+
Server `event-wiring.ts`: new fields guarded `!== undefined`; cleared to `null` when `gitPrNumber == null`. Not persisted.
|
|
2160
|
+
After successful `/api/git/worktree/push` or `/pr` server sends `git_info_refresh { reason }` to active bridges whose realpath'd cwd is inside the worktree (`activeSessionsUnderResolved`); bridge forces probe (≤1 forced start / 30 s, coalesced); `reason:"pr"` retries +5/+15 s while absent. Merge (local) never refreshes.
|
|
2161
|
+
`collapseCheckRollup` lives in `packages/shared/src/platform/check-rollup.ts` (shared by server `listPullRequests` + bridge). Client `packages/client/src/lib/git/merge-primary.ts` `isMergePrimary` decides Merge emphasis once per surface (composer strip, session card). See change: redesign-composer-session-strip.
|
|
1469
2162
|
|
|
1470
2163
|
### Working-tree status + commit from card
|
|
1471
|
-
1. Bridge gathers working-tree status
|
|
2164
|
+
1. Bridge gathers working-tree status via the async git probe scheduler (no `gatherGitStatus`, no sync spawn). `gitStatusV2Async` runs `git --no-optional-locks status --porcelain=v2 --branch`, shared `parseGitStatusV2` parses into `GitStatus { dirtyCount, staged, unstaged, untracked, ahead, behind }`.
|
|
1472
2165
|
2. `sendGitInfoIfChanged` includes `gitStatus` in `git_info_update`; deduped via `lastGitStatusJson`. Inconclusive probe omits `gitStatus`, leaves last value.
|
|
1473
2166
|
3. Server `event-wiring.ts` merges `gitStatus` from `git_info_update` onto session, broadcasts `session_updated`.
|
|
1474
2167
|
4. Hybrid delivery, keyed by cwd (not session): passive broadcast above PLUS on-demand `GET /api/git/status?cwd=` (`getGitStatus`, reuses `parseGitStatusV2`) on card/folder focus + right after commit. Client `git-status-cache.ts` (`useGitStatus(cwd, fallback)`) keys by cwd — folder header + solo card at same path share one entry.
|
|
@@ -1481,13 +2174,13 @@ See change: fix-auto-naming-reasoning-model.
|
|
|
1481
2174
|
See change: add-session-uncommitted-indicator-and-commit.
|
|
1482
2175
|
|
|
1483
2176
|
### Git Polling (legacy entry, see VCS Polling above)
|
|
1484
|
-
|
|
1485
|
-
2. Changes are sent to the server only when values differ from last poll
|
|
1486
|
-
3. Server broadcasts updates to subscribed browsers
|
|
2177
|
+
Superseded by `### VCS Polling (Git)`. No 30 s sync git poll; no `gatherGitStatus`. Lanes, cadence, async spawns documented there.
|
|
1487
2178
|
|
|
1488
2179
|
### Git worktree convention (`.worktrees/`)
|
|
1489
2180
|
Dashboard derives new worktree path as `<repoRoot>/.worktrees/<slugifyBranch(branch)>` when `POST /api/git/worktree` body omits `path`. `addWorktree` calls `ensureWorktreeExcludeLine(cwd)` first — idempotently appends `.worktrees/` to `<repoRoot>/.git/info/exclude` so parent repo ignores nested checkouts (untouched if line already present). Bridge `detectWorktree` populates `GitInfo.gitWorktree.mainPath`; `resolveSessionGroupPath` collapses worktree sessions under parent repo's pinned-directory group. See change: add-worktree-spawn-dialog.
|
|
1490
2181
|
|
|
2182
|
+
Worktree parentage immutable once resolved (cwd unchanged). `git_info_update { gitWorktree: null }` after parentage set means worktree removed underneath a live session — server keeps prior value; `gitWorktreeReported` stays true. `null` with no prior parentage clears as before. Same-cwd re-register carries `gitWorktree` over (server restart / bridge reconnect / resume); different cwd resets to unresolved. Wire shape unchanged — narrows documented meaning of wire `null`. See change: fix-worktree-grouping-lost-on-remove.
|
|
2183
|
+
|
|
1491
2184
|
### Git worktree lifecycle (push / PR / merge / close)
|
|
1492
2185
|
Dashboard exposes 7 endpoints under `/api/git/worktree/*`: `remove`, `remove-batch`, `prune`, `merge`, `push`, `pr`, `diff-stat`. Localhost-gated. Each forwards stable `{code, stderr}` errors (`active_sessions`, `dirty_worktree`, `branch_not_merged`, `dirty_main`, `merge_conflict`, `base_not_found`, `no_remote`, `auth_failed`, `non_fast_forward`, `gh_not_found`, `gh_not_authed`, `pr_exists`, `pushed_but_pr_failed`, `cwd_invalid`, `is_main_worktree`) produced by pure stderr→code mappers in `git-worktree-lifecycle.ts`.
|
|
1493
2186
|
`/remove-batch` body `{ items: Array<{cwd, force?, deleteBranch?}> }`. Cap 50 items enforced before any git runs — `batch_too_large` 400; non-array `items` → `items_invalid` 400. Returns `{ results }` in INPUT ORDER, one per item. Never aborts on first failure. Item result: `{ cwd, ok, code, sessionIds?, branchDeleted?, branchDeleteCode? }`. `code` widens `RemoveCode` with `active_sessions | cwd_invalid | is_main_worktree`. Sits behind `networkGuard` + `validateCwd`.
|
|
@@ -1500,6 +2193,131 @@ See change: add-worktree-lifecycle-actions.
|
|
|
1500
2193
|
Manage-worktrees surface removes worktrees with NO entry in session map. `active_sessions` guard does not fire. Menu gate on folder being a git repository, never on live sessions.
|
|
1501
2194
|
See change: manage-worktrees-filter-cleanup.
|
|
1502
2195
|
|
|
2196
|
+
### Git checkout-root resolution
|
|
2197
|
+
|
|
2198
|
+
Resolver: `packages/shared/src/platform/git.ts`. Exports `GitCheckoutRoots { thisCheckout, isLinkedWorktree, mainCheckout }`, `resolveCheckoutRootsFrom(probes)`, `checkoutRoots({ cwd, timeout? })`, `hasGitPathSegment(p)`. One shared source for "which checkout does this cwd belong to" — the repo previously copied the arithmetic per consumer.
|
|
2199
|
+
|
|
2200
|
+
Superseded derivation: `path.dirname(git rev-parse --git-common-dir)`. Assumed the git dir sits inside its checkout. Wrong for submodule, worktree-of-submodule, `--separate-git-dir`, bare, worktree-of-bare.
|
|
2201
|
+
|
|
2202
|
+
Symptom: folder card headed `…/<super>/.git/modules/<name>`. Path does not exist. "Not a pi project yet" banner. "KNOWLEDGE BASE: not indexed".
|
|
2203
|
+
|
|
2204
|
+
`--separate-git-dir` and bare are the dangerous rows: derived parent EXISTS and is UNRELATED, so nothing looks wrong.
|
|
2205
|
+
See change: add-git-checkout-root-resolver.
|
|
2206
|
+
|
|
2207
|
+
#### Measured git-state table
|
|
2208
|
+
|
|
2209
|
+
Measured on real repos — `git rev-parse` outputs per cwd state (`<r>` = repo root). NEVER re-derived from fixtures; fixtures pin these rows.
|
|
2210
|
+
|
|
2211
|
+
| cwd state | `--git-dir` | `--git-common-dir` | `--show-toplevel` | `isLinkedWorktree` | `mainCheckout` |
|
|
2212
|
+
|---|---|---|---|---|---|
|
|
2213
|
+
| normal checkout | `<r>/normal/.git` | `<r>/normal/.git` | `<r>/normal` | false | `<r>/normal` |
|
|
2214
|
+
| subdir of checkout | `<r>/normal/.git` | `<r>/normal/.git` | `<r>/normal` | false | `<r>/normal` |
|
|
2215
|
+
| linked worktree | `<r>/normal/.git/worktrees/normal-wt` | `<r>/normal/.git` | `<r>/normal-wt` | true | `<r>/normal` |
|
|
2216
|
+
| submodule | `<r>/super/.git/modules/models/sub` | same as `--git-dir` | `<r>/super/models/sub` | false | `<r>/super/models/sub` |
|
|
2217
|
+
| worktree of submodule | `<r>/super/.git/modules/models/sub/worktrees/sub-wt` | `<r>/super/.git/modules/models/sub` | `<r>/sub-wt` | true | `<r>/super/models/sub` (via repo-local `core.worktree`) |
|
|
2218
|
+
| bare repo | `<r>/barehub.git` | `<r>/barehub.git` | (fails) | false | `null` |
|
|
2219
|
+
| worktree of bare hub | `<r>/barehub.git/worktrees/bare-wt` | `<r>/barehub.git` | `<r>/bare-wt` | true | `null` |
|
|
2220
|
+
| `--separate-git-dir` | `<r>/elsewhere.git` | `<r>/elsewhere.git` | `<r>/sepco` | false | `<r>/sepco` |
|
|
2221
|
+
| non-repo | (fails) | (fails) | (fails) | — | no result |
|
|
2222
|
+
See change: add-git-checkout-root-resolver.
|
|
2223
|
+
|
|
2224
|
+
#### Required probes
|
|
2225
|
+
|
|
2226
|
+
Required probes: `--git-dir` + `--git-common-dir`, both `--path-format=absolute`. Absolute form is contract, not preference: `isLinkedWorktree` is an equality test; mixed relative/absolute makes EVERY normal checkout report as a linked worktree.
|
|
2227
|
+
|
|
2228
|
+
Version floor: `--path-format=absolute` needs git >= 2.31.0 — the release that added the flag. Below floor: BOTH probes fail; `resolveCheckoutRootsFrom` returns `null`; every consumer degrades to its no-result branch — folder card omits `gitWorktree`, kb guard rejects. Fail-closed; worktree admission simply unavailable below 2.31.
|
|
2229
|
+
|
|
2230
|
+
`--show-toplevel` NOT required. Fails by design in bare repo. Failure yields `thisCheckout: null` WITH a result. Keeps bare distinguishable from non-repo.
|
|
2231
|
+
|
|
2232
|
+
Worktree signal: `--git-dir` != `--git-common-dir`. Compared via `samePath` (`packages/shared/src/platform/paths.ts`), never raw `!==`.
|
|
2233
|
+
|
|
2234
|
+
Rejected signals: common-dir-outside-toplevel (calls submodule a worktree); `basename(commonDir) === ".git"` (calls worktree-of-submodule and worktree-of-bare non-worktrees). Both measured.
|
|
2235
|
+
See change: add-git-checkout-root-resolver.
|
|
2236
|
+
|
|
2237
|
+
#### mainCheckout derivation
|
|
2238
|
+
|
|
2239
|
+
`mainCheckout` order: not-worktree → `thisCheckout`; else repo-LOCAL `core.worktree` on commonDir; else `dirname(commonDir)` when basename is `.git` AND repo-LOCAL `core.bare` CONFIRMS `not-bare`; else `null`.
|
|
2240
|
+
|
|
2241
|
+
`core.worktree` read is `--local` and argv-form. Merged read returns `~/.gitconfig` value for EVERY linked worktree on the machine, and `mainCheckout` feeds an authorization anchor. Argv form because the git-dir path is runtime, cwd-derived input.
|
|
2242
|
+
|
|
2243
|
+
Rule-2 bareness guard reads recipe `GIT_CONFIG_LOCAL_CORE_BARE` with `--type=bool`. git accepts `yes`, `on`, `1`, `true` as boolean-true; raw text read vs literal `"true"` classified `bare = yes` as NOT bare. `--type=bool` canonicalizes to exactly `true`/`false`. Same `--local` + argv-form constraints as `core.worktree` read; `tolerate: [1]` = key unset — reads `not-bare`, git's own boolean default, a SUCCESSFUL read. Probe THREE-valued, exported `GitBareness = "not-bare" | "bare" | "unknown"`. Spawn failure or timeout → `"unknown"`, NEVER `"not-bare"` — collapsing would re-open the exact fallback the check closes. `dirname(commonDir)` fallback fires ONLY on positive `"not-bare"`; `"unknown"` falls through to `mainCheckout = null`. Bare hub may itself be named `.git` — `git init --bare <dir>/.git`. Parent holds no working tree. Naming it hands authorization consumer an anchor the repo never owned.
|
|
2244
|
+
|
|
2245
|
+
Resolver returns `mainCheckout` VERBATIM. git does not validate `core.worktree`. CONSUMERS validate; each states its own check. Display consumer omits the field; authorization consumer rejects.
|
|
2246
|
+
|
|
2247
|
+
`.git`-segment test is EXACT PATH-COMPONENT equality. `/work/app.git` is NOT rejected.
|
|
2248
|
+
|
|
2249
|
+
```mermaid
|
|
2250
|
+
flowchart TD
|
|
2251
|
+
A[cwd] --> B{git-dir + common-dir probes succeed?}
|
|
2252
|
+
B -- no --> Z[null — no result, non-repo]
|
|
2253
|
+
B -- yes --> C{gitDir == commonDir? samePath}
|
|
2254
|
+
C -- yes, not a worktree --> D[mainCheckout = thisCheckout]
|
|
2255
|
+
C -- no, linked worktree --> E{repo-local core.worktree set?}
|
|
2256
|
+
E -- yes --> F[mainCheckout = resolve commonDir + core.worktree]
|
|
2257
|
+
E -- no --> G{basename commonDir == .git AND core.bare CONFIRMS not-bare?}
|
|
2258
|
+
G -- yes --> H[mainCheckout = dirname commonDir]
|
|
2259
|
+
G -- no --> I[mainCheckout = null — bare hub, or bareness inconclusive]
|
|
2260
|
+
```
|
|
2261
|
+
See change: add-git-checkout-root-resolver.
|
|
2262
|
+
|
|
2263
|
+
#### Converted consumers
|
|
2264
|
+
|
|
2265
|
+
Converted consumers: `packages/extension/src/vcs-info.ts` `detectWorktree` (folder card + grouping); `packages/kb-plugin/src/server/kb-routes.ts` `mainCheckoutPath` → `isAllowedCwd`; `packages/server/src/session/session-scanner.ts` `isPlausibleWorktreeMainPath`.
|
|
2266
|
+
|
|
2267
|
+
`detectWorktree` returns `undefined` when: required probe fails; cwd not a linked worktree (now covers submodule, `--separate-git-dir`, bare alike); no main checkout resolves (worktree of bare hub); resolved main checkout implausible (`.git` segment); `roots.thisCheckout` null despite `isLinkedWorktree` true. Resolver's user-controlled `core.worktree` output judged HERE — display consumer, safe response omits the field.
|
|
2268
|
+
|
|
2269
|
+
Null-`thisCheckout` + linked worktree = `--show-toplevel` probe FAILED, not a nameless worktree. Linked worktree ALWAYS has working tree. Inconclusive = return `undefined`. `cwd` fallback would silently reintroduce subdirectory mislabel for exactly the unverifiable case.
|
|
2270
|
+
|
|
2271
|
+
`name` = `path.basename(roots.thisCheckout)` — the worktree's OWN root, NOT the request `cwd`. No `cwd` fallback. Reason: a session can sit in a SUBDIRECTORY of the worktree; `basename(cwd)` would label the folder card with the subdirectory name. Verdict already carries the worktree root. Null `thisCheckout` never reaches here — `detectWorktree` returns `undefined` first.
|
|
2272
|
+
|
|
2273
|
+
`mainCheckoutPath` (kb guard): `.git`-segment rejection is the consumer's OWN obligation. Authorization consumer — derives no main path at all, so value never matches known-folder set. Submodule resolves to own checkout, does NOT inherit superproject trust; worktree-of-bare resolves to null, rejected unless independently known. Probe budget `timeout: 400` per probe — up to FIVE SYNC probes on a Fastify request path. Holds superseded single-2000ms worst-case event-loop block, never multiplies it. Timeout degrades to no result → reject, never admit.
|
|
2274
|
+
|
|
2275
|
+
Request cwd containing `.git` path SEGMENT rejected BEFORE both admission paths — direct known-folder match included. Stray pinned dir or session cwd of `<repo>/.git` cannot admit itself. No store opened, no disk read.
|
|
2276
|
+
See change: add-git-checkout-root-resolver.
|
|
2277
|
+
|
|
2278
|
+
|
|
2279
|
+
Worktree operations conversion (`apply-checkout-root-to-worktree-ops`):
|
|
2280
|
+
- `resolveMainPath` wraps `checkoutRoots({cwd, timeout: 400})` + `hasGitPathSegment`. Null on non-repo, bare hub, worktree-of-bare, `.git`-segment mainCheckout.
|
|
2281
|
+
- `resolveConfigRoot` calls `checkoutRoots` directly; `isGitRepo` probe removed; bare returns null; no non-git fall-through.
|
|
2282
|
+
- `directory-service.ts` `configRootFor` returns `string | null`; callers skip on null; `?? cwd` coercion removed.
|
|
2283
|
+
- `listWorktrees` determines `isMain` via `samePath` vs resolved main; accepts optional threaded `mainPath` param (D7); `parsePorcelainWorktrees` emits `isMain: false` always.
|
|
2284
|
+
- `addWorktree`/`addWorktreeFromPr` anchors on `resolveMainPath`; `not_a_repo` preserved; exclude write targets common git dir via `resolveCommonDirAbs`, non-fatal on null.
|
|
2285
|
+
- `removeWorktree` accepts threaded `mainPath` param; `classifyWorktreeRemoval` tri-state gates `/remove` + `/remove-batch`; error codes `is_main_worktree` and `main_checkout_unresolved`, both HTTP 400.
|
|
2286
|
+
- `mergeWorktree`/`worktreeDiffStat` maps `MergeCode` + `not_a_worktree` to HTTP 400 (was `git_failed`/500).
|
|
2287
|
+
- `createPullRequest` drops dead `mainPath`; `pushBranch` untouched (no refusal set).
|
|
2288
|
+
- `orphanCleanup` anchors on resolved main; guard order pinned: anchor → logical containment → statSync → realpath BOTH sides + re-containment → existing guards in order; realpath ENOENT yields `not_a_directory`; other realpath errors yield `fs_failed`; deletes realpath-validated path.
|
|
2289
|
+
- `/remove-batch` cap derives from `DashboardConfig.removeBatchCap` via `clampRemoveBatchCap` (default 50, clamp 1-500); git-routes uses `resolveBatchCap` defensive clamp.
|
|
2290
|
+
|
|
2291
|
+
| resolver result | verdict | behaviour |
|
|
2292
|
+
|---|---|---|
|
|
2293
|
+
| null | unresolved | refuse (code per endpoint) |
|
|
2294
|
+
| not linked | main | `is_main_worktree` 400 (remove) / anchor=main (others) |
|
|
2295
|
+
| linked, thisCheckout null | unresolved | `main_checkout_unresolved` 400 |
|
|
2296
|
+
| linked, mainCheckout null | unresolved | `main_checkout_unresolved` 400 |
|
|
2297
|
+
| linked, `.git`-segment mainCheckout | unresolved | `main_checkout_unresolved` 400 |
|
|
2298
|
+
| linked plausible | removable | proceeds |
|
|
2299
|
+
|
|
2300
|
+
See change: apply-checkout-root-to-worktree-ops.
|
|
2301
|
+
|
|
2302
|
+
#### Persisted phantom repair
|
|
2303
|
+
|
|
2304
|
+
Persisted repair: `gitWorktree.mainPath` is written to `.meta.json` and re-seeded at every boot; an ended session never re-probes; phantoms do not expire. Filter runs at LOAD time.
|
|
2305
|
+
|
|
2306
|
+
Plausible = no `.git` path segment AND `statSync(<mainPath>/.git)` succeeds. One stat per record. Zero subprocesses. Dropped on ANY stat failure, not only ENOENT. `.meta.json` never rewritten.
|
|
2307
|
+
|
|
2308
|
+
`.git`-entry condition is load-bearing: `--separate-git-dir`/bare phantoms are real, existing, unrelated dirs.
|
|
2309
|
+
|
|
2310
|
+
KNOWN LIMITATION: phantom landing on a real working tree survives (bare hub `$HOME/bare.git` → phantom `$HOME`, `$HOME` a dotfiles repo). Shape test, not identity test.
|
|
2311
|
+
|
|
2312
|
+
Worktree parentage inference runs when persisted parentage absent (key absent or `null`) or implausible. Requires ABSOLUTE cwd shape `<X>/.worktrees/<name>[/<sub>...]`. Split at FIRST `.worktrees` segment. `<X>` non-empty, absolute. `<X>/.git` must stat; reuse `isPlausibleWorktreeMainPath` for that one stat. Decline with NO stat for relative cwd or leading `.worktrees` — would resolve `.git` against server cwd. Read-time only; `.meta.json` never rewritten. One stat per record, zero subprocesses. Heals records the removed-worktree race cleared. See change: fix-worktree-grouping-lost-on-remove.
|
|
2313
|
+
|
|
2314
|
+
kb guard is STRICTER, not looser, in every state except a submodule admitted on its own cwd. Submodule does not inherit superproject trust.
|
|
2315
|
+
|
|
2316
|
+
Fixtures: `packages/shared/src/test-support/git-fixtures.ts`. Needs `GIT_CONFIG_GLOBAL=/dev/null` + `GIT_CONFIG_SYSTEM=/dev/null` and `-c protocol.file.allow=always`.
|
|
2317
|
+
|
|
2318
|
+
Converted by `apply-checkout-root-to-worktree-ops`: `resolveMainPath` + its consumers (see "Worktree operations conversion" above); `listWorktrees()` resolves `isMain` via `samePath` against the resolved main checkout. `path-containment.ts` converted by `widen-containment-to-resolved-checkout` — see File Read API.
|
|
2319
|
+
See change: add-git-checkout-root-resolver.
|
|
2320
|
+
|
|
1503
2321
|
### Child Process Scanning
|
|
1504
2322
|
1. Bridge scans child processes every 10s via `process-scanner.ts` (two-phase: capture new PGIDs during active bash calls, then check tracked PGIDs)
|
|
1505
2323
|
2. Only processes running ≥30s are reported (filters out short-lived commands)
|
|
@@ -1533,7 +2351,7 @@ See change: redesign-folder-workspace-add-flow.
|
|
|
1533
2351
|
|
|
1534
2352
|
**Panel.** Testid `folder-actions-menu-panel-<cwd>`, `role="menu"`, `data-menu-form="sheet"|"popover"`. Items carry `role="menuitem"`, testid `folder-menu-item-<id>`. Keyboard: ArrowDown/ArrowUp rove focus over `[role=menuitem]`; Escape closes + returns focus to trigger. Outside `mousedown`/`touchstart` closes.
|
|
1535
2353
|
|
|
1536
|
-
**Groups.** Host-owned fixed taxonomy, stable order: `workspace` then `directory` (`FOLDER_MENU_GROUPS`). Group heading testid `folder-menu-group-<group>`. Group renders only when it holds >=1 item. Item ids: `add-to-workspace`, `remove-from-workspace`, `pin`, `
|
|
2354
|
+
**Groups.** Host-owned fixed taxonomy, stable order: `workspace` then `directory` (`FOLDER_MENU_GROUPS`). Group heading testid `folder-menu-group-<group>`. Group renders only when it holds >=1 item. Item ids: `add-to-workspace`, `remove-from-workspace`, `pin`, `directory-settings`. Directory-group order: pin, directory-settings. Group-by radio set (`radioGroup`, `role=menuitemradio`) renders first, above verb groups (change: session-list-group-by).
|
|
1537
2355
|
|
|
1538
2356
|
**Open state.** `SessionList` owns `folderMenuFor`, keyed by SCOPE `folder:<cwd>` — mirrors `addToWsMenuFor`; a cwd key would co-open a folder row and a same-cwd card.
|
|
1539
2357
|
|
|
@@ -1572,6 +2390,7 @@ See change: add-folder-actions-menu.
|
|
|
1572
2390
|
4. Browsers can request immediate refresh via `openspec_refresh { cwd }`. User-initiated refresh **bypasses the mtime gate** (force-mode) but still respects the concurrency cap — see *Refresh paths* below.
|
|
1573
2391
|
5. New directories (pinned or from new sessions) trigger immediate discovery + polling (eager; bypasses jitter + mtime gate).
|
|
1574
2392
|
6. Each `OpenSpecChange` carries optional `isComplete?: boolean`. Periodic/gated path re-derives `isComplete` locally from `deriveArtifactStatus` (true iff every derived artifact done). Force-refresh path takes `isComplete` from `openspec status --change <name> --json`. Indicates artifact-authoring completeness only — orthogonal to task tally — never feeds `deriveChangeState`. Dashboard uses it solely to gate **Archive anyway** escape hatch (see “OpenSpec session card”). See change: optimize-openspec-poll-derive-artifacts-locally.
|
|
2393
|
+
7. Browsers pull cached state on demand: `openspec_get { requestId, cwd }`. `directoryService.getOrPollOpenSpec(cwd)` gate order: `!enabled` → `GLOBAL_OFF`; opted-out → `OPTED_OUT`; untracked (cwd ∉ registry cwds ∪ pinned) → `ABSENT`; no `<cwd>/openspec/` root → `ABSENT` (`hasOpenspecDir: false`). Gated reply = single `final: true` placeholder naming the gate state, no CLI spawn. Cache hit → one `final: true` reply with cached payload, no spawn. Cold miss → immediate `final: false` `PENDING` placeholder + ONE shared per-cwd gated poll (`openspecGetInFlight: Map<cwd, Promise>`, entry deleted on settle — concurrent `openspec_get` for one cold cwd share one poll); poll = `pollAndBroadcastIfChanged(cwd)` — same function the scheduler tick calls (prev-JSON compare → `pollDirectoryGated` → broadcast only on change or emitted pending), mtime-gated, semaphore-serialized, does NOT add cwd to periodic poll set. On resolve, unicast `final: true` outcome; on reject, unicast `final: true` `BROKEN · cli-failed` placeholder — requester always receives its final reply. Reply is `openspec_get_result { requestId, cwd, data, final }` — UNICAST to requesting browser only, never broadcast; final outcome reaches other browsers only when it differs from cache (ordinary tick broadcast discipline). Delivered under `state` frame class. See change: fix-connect-snapshot-frame-loss.
|
|
1575
2394
|
|
|
1576
2395
|
#### OpenSpec polling cost model
|
|
1577
2396
|
|
|
@@ -1582,7 +2401,8 @@ The scheduler in `packages/server/src/directory-service.ts` applies four layers
|
|
|
1582
2401
|
1. **mtime gate** (`changeDetection: "mtime" | "always"`, default `mtime`) — skips `openspec list` and `openspec status --change X` when no tracked artifact changed since last successful poll. Uses **file-aware effective mtime** (max over fixed file set) rather than directory mtime alone, because POSIX directory mtime advances only on entry create/delete/rename + misses in-place file edits. List-step signal unions `<changes>/` with each known `<change>/tasks.md`; per-change signal unions `<change>/` with `tasks.md`, `proposal.md`, `design.md`, **plus entire `specs/**` subtree** (`specs/` itself, every immediate `specs/<cap>/`, every `specs/<cap>/spec.md`). Missing files/dirs (e.g. change with no `design.md` or no `specs/` yet) skipped, not zero — `readdirSync` on `specs/` try/catch-wrapped so absence yields empty fan-out. `stat` ~10 µs vs. ~500 ms per CLI spawn; steady state drops 67 spawns/tick to 0–2. **TOCTOU-safe**: each per-change iteration captures `preCallMtime` before awaiting `runOpenSpecStatus` + stamps THAT value into cache; if post-call effective mtime differs, entry racy + cache left untouched (next gated tick re-polls because post-write mtime no longer matches preserved cached value). Without guard, write landing during CLI call would stamp `{ mtimeMs: post-write, status: pre-write }` + latch stale status indefinitely — trivially triggered by `/opsx:ff` mid-poll. **Defense in depth**: `buildOpenSpecData` also accepts `SpecsProbeFactory` (parallel to existing `DesignProbeFactory`) that promotes `specs: ready → done` whenever any `specs/**/*.md` found locally — promote-only, never demote, never `blocked → done`. So even if future blind spot creeps in, dashboard cannot under-report `specs` as ready when ≥1 spec file exists. See changes: `fix-openspec-specs-mtime-gate-blind-spot`, `fix-openspec-mtime-gate-toctou`, `fix-openspec-mtime-gate-blind-spots`.
|
|
1583
2402
|
2. **Concurrency cap** (`maxConcurrentSpawns`, default 3, range 1–16) — an in-repo semaphore (`packages/shared/src/semaphore.ts`) serializes CLI spawns across all directories. Burst-work spreads uniformly over the interval instead of pinning every core.
|
|
1584
2403
|
3. **Per-cwd jitter** (`jitterSeconds`, default 5) — each known directory is assigned a deterministic phase offset `fnv1a32(cwd) % (jitterSeconds * 1000)` within the interval so polls don't all align on the same scheduling boundary.
|
|
1585
|
-
4. **
|
|
2404
|
+
4. **pi-resources stale-while-revalidate** — no timer. `GET /api/pi-resources` scans on demand. Cold miss awaits; entry stale (watch event or `now - scannedAt ≥ 5 min`) served at once + one deduped background rescan; `refresh=true` awaits. Per-cwd in-flight dedupe.
|
|
2405
|
+
Watcher `packages/server/src/pi/pi-resources-watcher.ts`: per-cwd `<cwd>/.pi` + `skills|prompts|extensions|agents|themes`, plus one shared global `~/.pi/agent` set. Reconcile rides the OpenSpec poll tick before its gates (runs with OpenSpec disabled). Idle >10 min releases watchers, KEEPS data. Caps: 16 watched, 64 data.
|
|
1586
2406
|
|
|
1587
2407
|
Cache shape (per cwd): `{ listMtimeMs, listResult, changes: Map<name, { mtimeMs, change }>, data }`. Cache is updated atomically per directory — a partial failure leaves the previous snapshot intact and the next tick retries.
|
|
1588
2408
|
|
|
@@ -1605,6 +2425,44 @@ Observability: `DEBUG=pi-dashboard:openspec-poll` (or any `DEBUG=...pi-dashboard
|
|
|
1605
2425
|
|
|
1606
2426
|
**Session-load worker.** Session-event hydration (JSONL parse + replay) runs on a `worker_threads` pool, off main event loop. `packages/server/src/session-load-worker.ts` exports `loadAndReplay(req)`: runs `loadSessionEntries` (JSONL parse + tree-walk) and `replayEntriesAsEvents(...).map(m => m.event)` projection IN-WORKER; only final `events` array crosses thread boundary. `parentPort` bootstrap wires `loadAndReplay` onto a thread; tests + fallback import function directly. Worker output `{jobId, success, events, error, entryCount?}`. `packages/server/src/session-load-worker-pool.ts` runs fixed slots = `max(1, min(maxConcurrentSpawns, os.cpus().length))`; FIFO queue when slots busy; per-request timeout default `30000ms`; lazy spawn per slot via `new Worker(url, {execArgv: process.execArgv})` so jiti hook propagates. Main thread owns per-session `loadingSet` dedup, `eventStore.insertEvent`, and `session_updated` + `event_replay` broadcast (in `directory-service.ts::loadSessionEvents` + `browser-handlers/subscription-handler.ts`); worker never touches store or sockets. `cancel(jobId)`: queued job dropped from queue, resolves `"cancelled"`; in-flight job abandoned, its result discarded on arrival, worker NOT terminated for plain cancel (only timeout/crash terminates slot). `directory-service.ts` exposes `cancelLoad(sessionId)` via `inFlightLoadJobs` map; `subscription-handler.ts` unsubscribe case calls `cancelLoad` when `getSubscribers(sessionId).length === 0`; `subscription-handler.ts` treats `result.error === "cancelled"` as no-op (no `dataUnavailable`, no replay). Fallback: spawn fail / worker crash / non-zero exit / per-request timeout → in-process `loadAndReplay` for that request; `pool.load().result` never rejects. Config: `DashboardConfig.sessions.useLoadWorker` (default `true`) in `packages/shared/src/config.ts`; `false` → permanent in-process path, no `worker_threads` spawn. Plumbed `server.ts` `ServerConfig.sessions` → `cli.ts` → `createDirectoryService` `options.useLoadWorker`. `events` bytes identical to in-process projection; parity test enforces (`packages/server/src/__tests__/session-load-worker.test.ts`). Copies `openspec-poll-worker-pool` scaffold, not extracted (rule-of-three deferred to third consumer). See change: offload-session-events-load-to-worker.
|
|
1607
2427
|
|
|
2428
|
+
### OpenSpec Readiness (add-openspec-init-affordances)
|
|
2429
|
+
|
|
2430
|
+
One server-derived per-cwd readiness state gates every OpenSpec affordance — folder-card section, session-card OPENSPEC subcard. Clients render from `OpenSpecData.readiness`; they never re-derive from raw signals. See change: add-openspec-init-affordances.
|
|
2431
|
+
|
|
2432
|
+
**State table.** `deriveOpenSpecReadiness` folds `openspec.enabled`, `openspec.optOutDirectories`, `openspec.offerInitialization`, `hasOpenspecDir`, `initialized`, `pending`, `hasOpenSpecSkills`, recorded-vs-current update signature into `{ state, reason }`. Precedence = table order, first match wins:
|
|
2433
|
+
|
|
2434
|
+
| state | condition | folder card | session card OPENSPEC subcard |
|
|
2435
|
+
|---|---|---|---|
|
|
2436
|
+
| `GLOBAL_OFF` | `openspec.enabled === false` | nothing | hidden |
|
|
2437
|
+
| `OPTED_OUT` | cwd in `openspec.optOutDirectories` | nothing (re-enable via folder `⋯` menu) | hidden |
|
|
2438
|
+
| `PENDING` | poll in flight | grey loading spinner | existing placeholder |
|
|
2439
|
+
| `ABSENT` | no `<cwd>/openspec/` | one-line pill: Initialize + dismiss | hidden (offer made once on folder card, not per session) |
|
|
2440
|
+
| `BROKEN` | `hasOpenspecDir && !initialized` — reason `missing-changes-dir` \| `cli-failed` | Repair (`missing-changes-dir` only) \| error text | rendered disabled + reason |
|
|
2441
|
+
| `STALE` | `missing-skills` \| `profile-stale` | Update | rendered disabled + reason |
|
|
2442
|
+
| `READY` | otherwise | `OpenSpec (N) →` board nav | live controls |
|
|
2443
|
+
|
|
2444
|
+
`BROKEN`·`cli-failed` offers no Repair — re-running init cannot fix a failing CLI, and the invocation carries `--force` that would auto-clean a directory holding real proposals. `missing-skills` wins over `profile-stale` when both hold (it breaks the session-card controls). `ABSENT` renders no section when `offerInitialization === false`; `BROKEN`/`STALE` render no dismiss (user already opted in; silencing a broken state is not a resolution). Disabled subcard renders exactly one focusable control — routes to the folder card's OpenSpec section (`missing-changes-dir`/`cli-failed`/`missing-skills`; scrolls + expands + focuses) or Settings → OpenSpec Workflow Profile (`profile-stale`); reason text is the accessible explanation, not a `title` attribute.
|
|
2445
|
+
|
|
2446
|
+
**Derivation lives server-side.** `deriveOpenSpecReadiness` in `packages/server/src/openspec/readiness.ts`. `finalizeOpenSpecData` (directory-service.ts) attaches `hasOpenSpecSkills` + `readiness` at every `pollOne` exit; broadcast on every `openspec_update` and WS on-connect snapshot. Disabled-transition cleared payload carries `readiness: { state: "GLOBAL_OFF" }` explicitly, never omits it — a current client is never forced into the legacy gate mid-transition. Legacy fallback: `readiness` absent (older server) → previous `hasOpenspecDir || pending` gate, no disabled or stale presentation.
|
|
2447
|
+
|
|
2448
|
+
**Reconfiguration re-broadcast.** `reconfigurePolling` diffs readiness-affecting keys (`enabled`, `optOutDirectories`, `offerInitialization`) against the previous config; poll-tuning writes (interval, concurrency, jitter, worker flag) never trigger a readiness broadcast. `optOutDirectories` membership change re-broadcasts only the affected cwds; `enabled`/`offerInitialization` change re-broadcasts every cached cwd.
|
|
2449
|
+
|
|
2450
|
+
**`hasOpenSpecSkills`.** Stat `<configRoot>/.pi/skills/openspec-explore/`. Config root via `resolveConfigRoot` (git-worktree/git-operations.ts): a worktree answers from its main checkout, because `.pi/skills/openspec-*` is gitignored and never checks out into a worktree. Root resolution memoized per cwd (stat-pass budget, P4); unresolvable → fall back to the cwd.
|
|
2451
|
+
|
|
2452
|
+
**Config keys** (`OpenSpecPollConfig`): `openspec.optOutDirectories: string[]` (default `[]`; pathKey-normalized at parse, trailing-slash spellings collapse to one entry), `openspec.offerInitialization: boolean` (default `true`; `false` suppresses only the ABSENT offer — `BROKEN`/`STALE`/`READY` unaffected; distinct from `openspec.enabled`, which disables the feature). Both writable via `PUT /api/config` partial `{ openspec: {...} }` — deep-merged, every other key preserved.
|
|
2453
|
+
|
|
2454
|
+
**Update-signature provider.** `currentGlobalSignature` option injected into `createDirectoryService` from the routes layer. Signature is machine-global, identical for every cwd → computed at most once per poll tick, memoized per generation. Invalidated by global profile save and successful init/update via `directoryService.invalidateOpenSpecSignatureCache()`. Provider failure → signature check skipped, no cwd ever falsely STALE. A cwd with no recorded signature is never STALE on that basis — only a recorded signature that differs from the current one triggers `profile-stale`.
|
|
2455
|
+
|
|
2456
|
+
**POST /api/openspec/init.** Spawns `openspec init <cwd> --tools pi --force` via the tool-registry resolver (never a bare `openspec` command). Contract:
|
|
2457
|
+
- Body `{ cwd, confirm? }`. `cwd` validated against union(session cwds, pinned dirs) WITHOUT the `hasOpenSpecRoot` filter — the update-status helper filters to initialized projects and excludes exactly the directories init targets.
|
|
2458
|
+
- 400 when `<cwd>/openspec/` exists without `confirm: true` — deliberately coarse presence check; the CLI's internal legacy-artifact definition is unreachable through public exports.
|
|
2459
|
+
- `init --help` support probe cached per process; unsupported CLI refused with diagnostic naming the resolved binary, before any spawn.
|
|
2460
|
+
- Per-cwd lock: second request while an invocation is in flight → `409 Conflict`, no second spawn.
|
|
2461
|
+
- 60 s timeout — runner kills the process, partial stderr returned, lock released.
|
|
2462
|
+
- argv exactly `<resolved-cli> init <cwd> --tools pi --force`, passed as an array, never a shell string. No `--profile` (CLI accepts only `core|custom`; dashboard profile may be alias `expanded`); no `--no-animation`/`--no-copilot-cloud` (pinned CLI 1.6.0 registers only `--tools`/`--force`/`--profile`; commander strict). `--tools pi` writes `.pi/skills/openspec-*` + `.pi/prompts/opsx-*.md` — omitting it reproduces the dead-buttons defect.
|
|
2463
|
+
- `healExpandedProfileConfig` before the spawn (mirrors the update route).
|
|
2464
|
+
- Success: records the cwd's update signature, invalidates the signature cache, forces `refreshOpenSpec` so the new readiness broadcasts without waiting for the poll interval. Failure: `{ success: false, error, stderr? }`.
|
|
2465
|
+
|
|
1608
2466
|
### OpenSpec board
|
|
1609
2467
|
|
|
1610
2468
|
Board route `/folder/:encodedCwd/openspec` (`OpenSpecBoardView`) replaces inline `FolderOpenSpecSection` accordion. `FolderOpenSpecSection` now slim nav entry `OpenSpec (N) →` to board route.
|
|
@@ -1656,7 +2514,13 @@ The attached-change row on every session card has four affordances driven by the
|
|
|
1656
2514
|
- `POST /api/openspec/tasks/toggle` — body `{ cwd, change, id, done, line }`. Reads the file, validates that `line` still contains the requested `id` and the *opposite* state (optimistic-concurrency check), rewrites only that one line's `[ ]`/`[x]` marker, and atomic-writes via `tmp + rename` so other lines are preserved byte-for-byte. Maps typed errors to HTTP: `NotFoundError` → 404, `LineMismatchError` → 409, `NotACheckboxError` → 400. On success, fires a fire-and-forget `directoryService.refreshOpenSpec(cwd)` followed by an `openspec_update` broadcast.
|
|
1657
2515
|
|
|
1658
2516
|
### File Read API
|
|
1659
|
-
The server exposes `GET /api/file?cwd=...&path=...` for reading files or listing directories from session working directories. Guards: localhost-only, cwd must match a known session,
|
|
2517
|
+
The server exposes `GET /api/file?cwd=...&path=...` for reading files or listing directories from session working directories. Guards: localhost-only, cwd must match a known session, path admitted by `isAllowed` (`packages/server/src/lib/path-containment.ts`). Returns `{ type: "file", content }` or `{ type: "directory", entries }`.
|
|
2518
|
+
|
|
2519
|
+
Containment anchors at each anchor's resolved, repository-BOUND checkout roots — `thisCheckout` + `mainCheckout` from the shared resolver (`packages/shared/src/platform/git.ts`), never `dirname(--git-common-dir)`. `commonDir` = repository identity, never an anchor. Layer ① logical: resolved under anchor cwd, string compare, no spawn — hot path. Layer ② checkout roots: spawned only on ① miss, via `checkoutRootsAsync` — remote caller forces ② at will, so a synchronous probe would be an event-loop DoS. Each derived root kept only when `isBoundCheckout(candidate, commonDir)`: no `.git` path segment, not under the common dir, re-resolves to the SAME common dir, candidate IS its own `thisCheckout`. Binding stops a repository-local `core.worktree` naming an unrelated KNOWN folder. Unbound root → dropped (containment) / rejected (kb cwd guard). Widened states: submodule, `--separate-git-dir`, worktree-of-bare sessions read their OWN checkout — none reaches its superproject, the directory holding its git dir, or a bare hub's parent.
|
|
2520
|
+
|
|
2521
|
+
kb cwd guard (`isAllowedCwd`, `packages/kb-plugin/src/server/kb-routes.ts`) shares `isBoundCheckout`. Admission = authority over the cwd's CONFIGURED paths, not the cwd subtree: an admitted cwd's `knowledge_base.json` may name absolute `sources[].ref` and an absolute `dbPath` outside the cwd (`packages/kb/src/config.ts` `loadConfig` resolves absolute refs verbatim). Reach past admission unbounded → guard rejects an unbound main checkout, never tolerates it.
|
|
2522
|
+
|
|
2523
|
+
See change: widen-containment-to-resolved-checkout (was: git-root-file-containment).
|
|
1660
2524
|
|
|
1661
2525
|
### Filesystem Browser (PathPicker)
|
|
1662
2526
|
|
|
@@ -1705,7 +2569,7 @@ Metadata is parsed from SKILL.md YAML frontmatter (`name`, `description`), promp
|
|
|
1705
2569
|
Package operations use pi's `DefaultPackageManager` API on the server, serialized (one at a time, 409 on concurrent). Progress events are forwarded to browsers via `package_progress` WebSocket messages. After any successful operation, the server sends `/reload` to all connected pi sessions.
|
|
1706
2570
|
|
|
1707
2571
|
**Pi Core Version Check (separate from extension management):**
|
|
1708
|
-
- `GET /api/pi-core/versions[?refresh=true]` — returns `PiCoreStatus` with
|
|
2572
|
+
- `GET /api/pi-core/versions[?refresh=true]` — returns `PiCoreStatus` with discovered pi ecosystem CLI packages (set = strict `CORE_PACKAGE_NAMES` whitelist = `@earendil-works/pi-coding-agent` + `@blackbelt-technology/pi-agent-dashboard`; legacy `@mariozechner/pi-coding-agent` never listed; no `pi-*` prefix / scoped-name discovery), their installed version, latest npm-registry version, `updateAvailable` flag, and `installSource` (`"global"` via `npm list -g --depth=0 --json` vs `"managed"` in `~/.pi-dashboard/node_modules/`). Cached 5 min. See change: drop-mariozechner-pi-fork.
|
|
1709
2573
|
- `POST` to the pi-core update endpoint with `{ packages?: string[] }` — updates the listed packages, or all packages with `updateAvailable` when omitted. Runs `npm update -g <pkg>` (global) or `npm update <pkg>` against a managed install when present. Shares the `PackageManagerWrapper.runExclusive()` busy-lock with extension operations — returns 409 on contention. **Standalone + bridge arms only**; Electron hides this UI under R3 because the bundle is read-only (immutable; updates land via electron-updater whole-app replacement).
|
|
1710
2574
|
|
|
1711
2575
|
Why a separate system? Pi's `DefaultPackageManager` only manages packages listed in `settings.json packages[]` (extensions/skills/prompts/themes). The pi CLI binary itself and the dashboard server package are installed directly via `npm -g` (or into `~/.pi-dashboard/` in the Electron case) and are invisible to pi's manager. `PiCoreChecker` + `PiCoreUpdater` (`pi-core-checker.ts` + `pi-core-updater.ts`) fill that gap.
|
|
@@ -1804,128 +2668,434 @@ The dashboard provides a git branch selector at the folder group level. Clicking
|
|
|
1804
2668
|
- `POST /api/git/init` — initializes a git repository
|
|
1805
2669
|
- `POST /api/git/stash-pop` — pops the most recent stash, reports conflicts
|
|
1806
2670
|
|
|
1807
|
-
**Checkout flow**: Clean checkout closes immediately. Dirty working tree → client shows file list + "Stash & Switch" button → stash + checkout → asks "Pop stash on new branch?" with explicit Yes/No. Remote branches auto-create local tracking branches.
|
|
2671
|
+
**Checkout flow**: Clean checkout closes immediately. Dirty working tree → client shows file list + "Stash & Switch" button → stash + checkout → asks "Pop stash on new branch?" with explicit Yes/No. Remote branches auto-create local tracking branches.
|
|
2672
|
+
|
|
2673
|
+
### Session File Diff View
|
|
2674
|
+
|
|
2675
|
+
The dashboard provides a GitHub-style file diff viewer for sessions. It shows what files a session has changed, with per-change drill-down.
|
|
2676
|
+
|
|
2677
|
+
**Data flow**: `GET /api/session-diff?sessionId=xxx` (localhost-only) derives tool-call events from session transcript (`session.sessionFile`) for local sessions. In-memory event store = fallback only when transcript missing or yields zero parsed entries (missing file, header-only, bad header, unreadable); never zero projected events. Remote (gateway) sessions keep store path; origin gate `mayReadLocalSessionFile` blocks local filesystem stat/read. Extraction, ownership gating, git enrichment, and response shape unchanged. Returns `SessionDiffResponse` with files, per-file change events (timestamps + context messages), optional git diffs. See change: fix-session-diff-durable-source.
|
|
2678
|
+
|
|
2679
|
+
**Durable event source (`session-diff-source.ts`)**: `packages/server/src/session/session-diff-source.ts` sources tool-call events without event-store ring-buffer eviction loss. `resolveDiffSource(session, eventStore, { pool, maxStringSize })` checks `mayReadLocalSessionFile(session)`; returns `{ sourceKey, load }`. Worker pool dispatches `load()` off-thread in `mode:"diff-events"` (`packages/server/src/session/session-load-worker.ts`); runs in-process when pool absent or disposed. `loadSessionEntries` leaf→root ancestry walk covers forked sessions. `projectDiffEvents(sessionId, entries, { maxStringSize })` yields diff-only projection: assistant `message_end` (text parts only, before tool starts), `tool_execution_start`, `tool_execution_end`. Open tool calls stay open (preserves running Bash `[start, now]` window). `lastEntryTs` = max timestamp over all transcript entries. Tool `args` pass through store's exported `truncateStrings` under `maxStringFieldSize` cap; `truncated` flags and payload sizes match store path. See change: fix-session-diff-durable-source.
|
|
2680
|
+
|
|
2681
|
+
**UI**: Split-pane content-area view (replaces ChatView when active). Left panel shows a two-level file tree — files with status indicators, expandable to show individual change events with timestamps and assistant message context. Right panel renders diffs via `@git-diff-view/react` with `@git-diff-view/lowlight` syntax highlighting. Supports split/unified diff modes and a file content view toggle.
|
|
2682
|
+
|
|
2683
|
+
**Numstat counts**: session-diff payload carries optional per-file `additions`/`deletions` + top-level `totalAdditions`/`totalDeletions` from `git diff --numstat --relative HEAD`. Absent for non-git or binary files. `DiffFileTree` shows per-file `+adds −dels` + aggregate `summed` header. See change: add-change-summary-table.
|
|
2684
|
+
|
|
2685
|
+
**Event-loop-safe git enrichment**: `/api/session-diff` computes git enrichment without blocking Node event loop — all git spawns async via `runAsync` (no `spawnSync`). Per-file content diffs sourced from ONE batched `git diff --relative HEAD` (`git.diffAllOr`), split per file by `splitBatchedDiff` on `diff --git` boundaries; replaces old O(files) per-file spawn loop. Diff chunk exceeding `TRACKED_DIFF_MAX_BYTES` (5 MB) or binary file → listed with numstat `additions`/`deletions` but no text `gitDiff`. `buildSessionDiff(events, cwd, opts)` async; gained `opts.windowEnd` threaded to `extractBashWindows(events, windowEnd)`. `buildSessionDiffCached(sessionId, load, cwd, cache, { sourceKey, ended })` wraps with per-session short-TTL result cache + single-flight (`SessionDiffCache`, `packages/server/src/session/session-diff-cache.ts`), key `sessionId:HEAD-sha:djb2(porcelain):sourceKey:e|l`. `load()` executes inside cache compute; cache hit skips transcript parse. `sourceKey` = transcript `mtime:size` (`t:<mtime>:<size>`, stat error → `t:0:0`) for local session with `sessionFile`; else store count of write/edit/bash `tool_execution_start` events (`s:<n>`). `ended` flag passes transcript `lastEntryTs` as `windowEnd`, clamping unclosed Bash windows. Live→ended transition changes `windowEnd`; `e|l` component forces recompute. Repeated UI polls coalesce onto one computation; HEAD/dirty/source change busts key. See change: fix-session-diff-eventloop-block, fix-session-diff-durable-source.
|
|
2686
|
+
|
|
2687
|
+
**Per-turn change-summary block**: deterministic (no LLM). `ChangeSummaryBlock` renders in chat stream per turn, client-derived from Edit/Write events via `buildTurnSummaries` (`lib/lineDelta.ts`, jsdiff `structuredPatch`). Default expanded; collapses to `N files · +X −Y`. Gated on `displayPrefs.changeSummaryTable` (simple off; standard/everything on). See change: add-change-summary-table.
|
|
2688
|
+
|
|
2689
|
+
**Changes rail + diff tab**: Changed Files integrate as a Changes section atop the editor-pane rail (`ChangesRailSection`). Per-file diff opens as a `diff` viewer tab (`DiffViewer`, virtual `diff:<relPath>` path). `SessionDiffProvider` shares one fetch across rail, diff-tab, and takeover. See change: add-change-summary-table.
|
|
2690
|
+
|
|
2691
|
+
**Client/server path agreement**: client and server MUST agree on `data.files` key format. Server `session-diff.ts::normalizePath` keys `data.files` by relative-posix: absolute-under-cwd → relative; absolute-outside-cwd → dropped; already-relative → kept. Pre-fix bug: tool calls could record absolute `args.path`; change-summary row + `openDiffTab` then carried absolute path; absolute path never string-equaled relative key → diff blanked ("No changes for this file"). Now: `lib/normalize-path.ts::normalizeUnderCwd(rawPath, cwd)` mirrors server rule — absolute-under-cwd → relative-posix; else unchanged. `ChatView` applies it to both displayed row path + `openDiffTab` argument at source. `DiffViewer` retries with cwd-normalized path on exact-match miss. Non-git contract: git repo → render `gitDiff`; non-git or no `gitDiff` → `DiffPanel` derives all-additions/edit diff from file's own session change payload (last Write/Edit), never blanks. See change: fix-session-diff-open-nongit-and-preview.
|
|
2692
|
+
|
|
2693
|
+
**Entry point**: SessionHeader `ChangedFilesChip` calls `openChanges()` (Changes rail); only visible when Write/Edit tool events exist. `/session/:id/diff` takeover retained as fallback. Works for both active and ended sessions.
|
|
2694
|
+
|
|
2695
|
+
**Tool-created-file detection** (change: detect-tool-created-files):
|
|
2696
|
+
|
|
2697
|
+
`/api/session-diff` built by `buildSessionDiff(events, cwd)` in `packages/server/src/session-diff.ts` (replaces `extractFileChanges` + `enrichWithVcsDiff`).
|
|
2698
|
+
|
|
2699
|
+
git-status DETECTOR: git repo → `git status --porcelain` (cwd = session.cwd). C-unquotes paths. Rename `R old -> new` resolves to new path. Skips deletions. Routes each via same `normalizePath(abs, cwd)` as Write/Edit (one shared key space; out-of-cwd dropped). Unions detected files into changed-file list.
|
|
2700
|
+
|
|
2701
|
+
Bash ATTRIBUTOR: scans `tool_execution_start` bash events for output tokens (`>`, `>>`, `-o`, `--output`, `tee`) → labels detected file with redacted, 120-char-capped producing command (`producedBy`). Inside cwd it only LABELS, never adds a file (kills `grep -o` false positives). Secret shapes stripped.
|
|
2702
|
+
|
|
2703
|
+
Non-git detector: Bash-token scan + in-cwd `existsSync` only (anchored to cwd, no arbitrary-path probe).
|
|
2704
|
+
|
|
2705
|
+
File-level origin: `FileDiffEntry.origin` = write | edit | tool | mixed. `detectedVia` = git-status | bash-artifact. Reserved `previewable`. mixed = Write/Edit event AND on-disk detection; no synthetic ghost change event injected.
|
|
2706
|
+
|
|
2707
|
+
Binary/size safety: before synthetic new-file diff, sniff binary (NUL byte / known ext) + 256 KB size cap → binary/oversized rows listed with no text `gitDiff`.
|
|
2708
|
+
|
|
2709
|
+
Session-ownership gate (git state cwd-scoped, not session-scoped): each git-detected file classified by evidence from THIS session — Write/Edit event, Bash output-token, or mtime inside Bash execution window `[start,end]` (fallback `[start,now]`, ±1s slack). Owned → `data.files` (`sessionOwned:true`); rest → `data.otherChanges[]`. Worktree-isolated sessions → empty `otherChanges`.
|
|
2710
|
+
|
|
2711
|
+
200-entry file-count cap. Write/Edit take precedence when truncating.
|
|
2712
|
+
|
|
2713
|
+
Client: Files panel badges tool/mixed rows (`created by <command>`). `otherChanges` render under muted, collapsed "N other working-tree changes" group with "this session only" toggle.
|
|
2714
|
+
|
|
2715
|
+
Scope (v1): out-of-cwd files + deleted files excluded. No change to `/api/session-file` cwd 403 gate.
|
|
2716
|
+
|
|
2717
|
+
### Internal Monaco editor pane (v1 read-only)
|
|
2718
|
+
|
|
2719
|
+
Route `/session/:id/editor?file=&line=` renders `EditorPane` in content area. Replaces ChatView. Mirrors FileDiffView takeover. Back button → `goBack`.
|
|
2720
|
+
|
|
2721
|
+
Per-session tabs + tree state persist in localStorage key `pi-dashboard:editor-pane:<sessionId>`. No server persistence.
|
|
2722
|
+
|
|
2723
|
+
Shared `fileKind` classifier (`packages/shared/src/file-kind.ts`) = single viewer-discrimination source. Used by server (`/api/file`) + client (`OpenFileButton`, `EditorFileTree`).
|
|
2724
|
+
|
|
2725
|
+
Viewer registry: monaco (lazy), image, pdf, markdown, binary-warn.
|
|
2726
|
+
|
|
2727
|
+
Monaco lazy chunk loads on first text-file open. ts.worker omitted (no LSP). Theme derives from active dashboard theme via `buildMonacoTheme`. Recolors live on theme/mode change.
|
|
2728
|
+
|
|
2729
|
+
`OpenFileButton` plain button. Click → internal Monaco pane.
|
|
2730
|
+
|
|
2731
|
+
File-open surfaces: internal Monaco pane and preview overlay only.
|
|
2732
|
+
|
|
2733
|
+
v2–v4 follow-on (pin-to-split, create-file, edit-with-conflicts) deferred to separate proposals.
|
|
2734
|
+
|
|
2735
|
+
### Split editor workspace
|
|
2736
|
+
|
|
2737
|
+
`SplitWorkspaceProvider` lifts split state + editor-pane state per session.
|
|
2738
|
+
|
|
2739
|
+
`openInSplit` = single file-open helper. Auto-opens split. Callers: chat file-link, tool-result path, tree click, search result, `/session/:id/editor` deep-link.
|
|
2740
|
+
|
|
2741
|
+
Content search: `GET /api/grep` → `rg` preferred, bounded JS fallback. Filename search: bridge `list_files` walk (`.gitignore`-aware, softened budget).
|
|
2742
|
+
|
|
2743
|
+
Changed-on-disk: browser `watch_files` (open files only) → `file-watch-manager` `fs.watch` → `file_changed` broadcast → per-tab banner (Refresh, no auto-reload). Torn down on disconnect.
|
|
2744
|
+
|
|
2745
|
+
Rail = vertical stack: `ChangesRailSection` (Changes) above the project tree. `openChanges()` reveals it (`changesRevealSignal`); `openDiffTab()` opens a `diff:` viewer tab. See change: add-change-summary-table.
|
|
2746
|
+
|
|
2747
|
+
### Directory Settings + scoped markdown editing
|
|
2748
|
+
|
|
2749
|
+
Dashboard's first user-facing WRITE surface. Prior dashboard read-only.
|
|
2750
|
+
|
|
2751
|
+
Entry: FolderActionBar cog → `/folder/:cwd/settings/:page?` (pages instructions/packages/resources). Legacy `/folder/:cwd/pi-resources` redirects → `…/settings/packages`.
|
|
2752
|
+
|
|
2753
|
+
Instructions page edits markdown. Two scopes: directory (cwd) = markdown under cwd + `.pi/` tree; global (no cwd) = `~/.pi/agent/**/*.{md,mdx}` only.
|
|
2754
|
+
|
|
2755
|
+
Single security boundary: `isWritableMdTarget` (realpath-normalized, markdown-only, scope-bounded allowlist). cwd-containment alone insufficient for global dir → explicit allowlist root. Symlink/`..` escape rejected. Fail-closed.
|
|
2756
|
+
|
|
2757
|
+
Three endpoints share the guard: md-read (read), md-candidates (picker list), file/write (write). Picker ⊆ guard. Write uses mtime optimistic-concurrency → 409 on disk change; atomic tmp+rename.
|
|
2758
|
+
|
|
2759
|
+
Editor = Monaco (reuses add-internal-monaco-editor-pane primitives; MarkdownEditor editable buffer, lazy-loaded). Save contract mirrors unify-settings-save-contract (dirty-gated Save Bar + unsaved-changes guard).
|
|
2760
|
+
|
|
2761
|
+
### Markdown Preview View
|
|
2762
|
+
The web client includes a generic `MarkdownPreviewView` component that replaces the chat area. It supports a back button, title, optional tab bar, and loading/error states. For OpenSpec artifacts, the `useOpenSpecReader` hook maps artifact IDs (P/S/D/T) to file paths, fetches content via the file API, and concatenates specs from subdirectories.
|
|
2763
|
+
|
|
2764
|
+
### Archive Browser
|
|
2765
|
+
The `ArchiveBrowserView` provides a searchable, date-grouped listing of archived OpenSpec changes. It uses a dedicated `GET /api/openspec-archive?cwd=<path>` endpoint that scans `openspec/changes/archive/` and returns entry metadata (name, date, artifacts). The view uses two-level navigation: the list is the first level, and clicking an artifact letter (P/D/S/T) opens the reader as the second level. Back from the reader returns to the list (preserving search and scroll), and back from the list returns to the session view. Entry point is the `[Archive]` button in `FolderOpenSpecSection`.
|
|
2766
|
+
|
|
2767
|
+
### Content View Management
|
|
2768
|
+
|
|
2769
|
+
Content area (right panel) shows one view at a time: ChatView, ArchiveBrowserView, SpecsBrowserView, PiResourcesView, MarkdownPreviewView (readme, pi resource file, flow YAML, OpenSpec artifact), FileDiffView, FlowArchitectDetail, FlowAgentDetail.
|
|
2770
|
+
|
|
2771
|
+
Shell overlays dispatch by route match (see Shell overlay routing). Mutual exclusivity intrinsic — only one route active at a time. No `clearAllContentViews` helper, no `onBeforeOpen`. Session switch navigates; route change unmounts previous view.
|
|
2772
|
+
|
|
2773
|
+
Plugin content-view claims (flows-plugin) still predicate-driven via SlotRegistry. See change `overlay-url-routing`.
|
|
2774
|
+
|
|
2775
|
+
### Network Access Control
|
|
2776
|
+
|
|
2777
|
+
One universal network guard plus the auth plugin. Universal guard runs whether or not auth is configured.
|
|
2778
|
+
|
|
2779
|
+
**Layer 1: Network Guard (`createNetworkGuardHook`)** — `packages/server/src/auth/localhost-guard.ts`. Registered ONCE at root in `packages/server/src/server.ts` as the LAST `onRequest` hook, unconditionally. Not anchored on the model-proxy gate above it: that gate does not exist when `modelProxy` is disabled. Fastify binds root hooks to routes at `preReady`, including encapsulated plugin child scopes, so registering after the routes still covers them. Does NOT cover a route registered after `ready()` (plugin activation is restart-effective today; a future hot-load reopens this).
|
|
2780
|
+
|
|
2781
|
+
Replaces the old per-route-only model. `createNetworkGuard` was a `preHandler` on ~20 core route registrars. Three surfaces never got it and were unguarded when auth was off: plugin routes (`/api/plugins/automation/*`, kb, flows) and `/api/provider-auth/*`. Existing per-route `preHandler: networkGuard` calls stay as redundant defense-in-depth.
|
|
2782
|
+
|
|
2783
|
+
**Jurisdiction** — 4 namespaces, trailing-slash anchored: `/api/`, `/v1/`, `/editor/`, `/live/`. `/apiv2` is a near-miss, not `/api`.
|
|
2784
|
+
- INSIDE jurisdiction: deny by default.
|
|
2785
|
+
- OUTSIDE jurisdiction: no-op.
|
|
2786
|
+
|
|
2787
|
+
Outside is deliberate and load-bearing. Static assets, SPA shell (`/`), SPA deep-link fallback (`setNotFoundHandler`), `/manifest.json`, `/auth/*`, favicon, PWA icons, `/sw.js` keep loading. Auth-off tunnel deployment still reaches its own app shell.
|
|
2788
|
+
|
|
2789
|
+
**In-namespace public exceptions** (reachable unauthenticated inside `/api`): `GET`/`HEAD /api/health` (exact pathname; `HEAD` admitted because Fastify auto-exposes HEAD for a GET route); device-pairing bootstrap (`/api/pair/challenge`, `/api/pair/redeem`, `/api/pair/poll`); configured `auth.bypassUrls` prefixes.
|
|
2790
|
+
|
|
2791
|
+
An exception must hold on **both** views of the target (see **Matching**). Note the scope of `auth.bypassUrls`: it is an exception from the **universal hook only**. A route that also carries a retained per-route `preHandler: networkGuard` is still refused by that `preHandler`, so a `bypassUrls` match is public only for routes WITHOUT a per-route guard. This is unchanged from before this guard existed — `auth.bypassUrls` has only ever skipped the auth plugin, never a per-route guard.
|
|
2792
|
+
|
|
2793
|
+
**Pass conditions** (unchanged from the old per-route guard):
|
|
2794
|
+
1. **Genuine-local** — loopback AND no proxy-forwarding header (`x-forwarded-for`, `x-forwarded-host`, `x-forwarded-proto`, `x-real-ip`, `forwarded`). Tunnel presenting as `127.0.0.1` injects a forwarding header and fails here.
|
|
2795
|
+
2. **Local-IPC token** — `X-Pi-Local-Token` allowlist.
|
|
2796
|
+
3. **Trusted network** — source IP matches `resolvedTrustedNetworks` (CIDR, wildcard, exact). Read live via thunk, so a CIDR added at runtime admits without restart.
|
|
2797
|
+
4. **Authenticated** — `request.isAuthenticated === true`.
|
|
2798
|
+
|
|
2799
|
+
Otherwise → 403.
|
|
2800
|
+
|
|
2801
|
+
**Matching** runs on TWO views of the target, and jurisdiction is the UNION of them:
|
|
2802
|
+
- the **raw** view — percent-decoded, query string and fragment stripped, dot-segments UNRESOLVED;
|
|
2803
|
+
- the **resolved** view — the same pathname with `.` / `..` resolved per RFC 3986.
|
|
2804
|
+
|
|
2805
|
+
A request is in jurisdiction when **either** view is in jurisdiction. Unparseable target → fail closed (denied, treated as in-jurisdiction). `::ffff:` IPv4-mapped prefixes stripped before IP match. In-namespace exceptions must hold on **both** views.
|
|
2806
|
+
|
|
2807
|
+
Both views are load-bearing because the router and the guard disagree about dot-segments: Fastify passes `onRequest` the RAW target, and find-my-way does not resolve dot-segments — it matches them into a `:param` / `*` slot as a literal value. Deciding on the resolved view alone would let `/api/provider-auth/..` reach `/api/provider-auth/:provider` with `provider = ".."`; deciding on the raw view alone would miss `/foo/../api/x`; judging an exception on one view would let `/live/<id>/../../api/pair/challenge` through as the pairing exception while `/live/:id/*` runs. A dotted target that is outside jurisdiction under BOTH views (e.g. `/foo/../settings`) stays a no-op.
|
|
2808
|
+
|
|
2809
|
+
**`/v1/*` model proxy.** `createModelProxyAuthGate` (`packages/server/src/model-proxy/auth-gate.ts`) sets `request.isAuthenticated = true` on a valid `pi-proxy-*` key. Universal guard admits it via pass condition 4. Deliberately NO public `/v1` allowlist entry — such an entry would be a hole when the proxy is disabled.
|
|
2810
|
+
|
|
2811
|
+
**`/mcp` deliberately OUT of jurisdiction.** `/mcp` authenticates in-handler from the paired-device bearer token and does not trust `isAuthenticated`; guarding it would 403 every legitimate remote MCP client. Classified as an ENUMERATED independently-authenticated namespace, not silently skipped.
|
|
2812
|
+
|
|
2813
|
+
**Denial contract.** `403` with body `{ success: false, error: "network_not_allowed", reason, hint }` — clients branch on `error`. Recorded in the buffer behind `GET /api/tunnel/block-events`, which powers the "Trust this network?" prompt. Logged as `[network-guard] denied reason=… path=… ip=…` — path + socket-peer IP + reason only; no body, no token.
|
|
2814
|
+
|
|
2815
|
+
**Second port.** Optional model-proxy second-port Fastify instance runs ONLY the proxy gate, no universal guard. Safe solely because it binds `127.0.0.1` (asserted by `packages/server/src/__tests__/model-proxy-second-port.test.ts`). If that bind ever becomes configurable, install the universal guard there too.
|
|
2816
|
+
|
|
2817
|
+
**Namespace-coverage test.** `packages/server/src/__tests__/network-guard-namespace-coverage.test.ts` enumerates the real route table with plugin routes loaded. Fails if any non-static/non-`/auth`/non-public route sits outside the guarded namespaces or the enumerated independently-authenticated set (`/mcp`).
|
|
2818
|
+
|
|
2819
|
+
**Trusted-network config sources.** `resolvedTrustedNetworks` merges two sources:
|
|
2820
|
+
- `auth.bypassHosts` — canonical. Settings UI writes here (Security tab "Trusted Networks" section; also surfaced on Settings ▸ Servers).
|
|
2821
|
+
- legacy top-level `trustedNetworks` — readable for back-compat with hand-edited `config.json`. UI does not modify it.
|
|
2822
|
+
|
|
2823
|
+
Both honor same matching logic. Both work independently of whether `auth.providers` is configured: `auth: { providers: {}, bypassHosts: [...] }` honored as-is; auth plugin no-ops when provider registry empty and the universal guard serves the bypass path directly. See `openspec/changes/archive/` for `fix-trusted-networks-no-oauth` (restored this after a `consolidate-trusted-networks` regression).
|
|
2824
|
+
|
|
2825
|
+
**Layer 2: Auth Plugin (`onRequest` hook)** — Only registered when `auth` is configured. Skips loopback, trusted networks, `/auth/*`, `/api/health`, and `bypassUrls`. Validates JWT cookie for all other requests. Tags valid requests with `request.isAuthenticated = true`.
|
|
2826
|
+
|
|
2827
|
+
**Execution order** (root `onRequest` hooks run in registration order): auth plugin (when configured) → model-proxy auth gate (when proxy enabled) → universal network guard LAST → route `preHandler` (per-route guards, defense-in-depth) → handler. Auth and proxy gates tag the request before the universal guard reads the pass conditions.
|
|
2828
|
+
|
|
2829
|
+
**WebSocket upgrades** follow the same admission logic: loopback/genuine-local → trusted network → local-IPC token → JWT cookie validation.
|
|
2830
|
+
|
|
2831
|
+
**Zrok tunnel** connections appear as `127.0.0.1` (zrok proxies to localhost) but carry proxy-forwarding headers, so they are NOT genuine-local. A zrok peer passes only when in `trustedNetworks` or authenticated.
|
|
2832
|
+
|
|
2833
|
+
**`GET /api/network-interfaces`** returns detected non-internal IPv4 interfaces with computed CIDRs. Used by the Settings UI "Add Local Network" button. This endpoint uses the legacy `localhostGuard` (localhost-only, not network-guard-aware) since it exposes machine network topology.
|
|
2834
|
+
|
|
2835
|
+
### Trust and Credential Boundaries (change: harden-trust-and-credential-boundaries)
|
|
2836
|
+
|
|
2837
|
+
Hardens five residual trust / credential-boundary weaknesses from audit. Each mitigates a confirmed finding; none is a standalone RCE.
|
|
2838
|
+
|
|
2839
|
+
**Strict local proof (`requireLocalProof`).** Top-level config key, default `false`, read live per request — toggling needs no restart. Off = bare loopback (loopback peer, no forwarding header) stays trusted exactly as today. On = the network guard admits a bare-loopback request only on `observe`-tier `/api/*` REST reads (the `isObserveApiRequest` exception in `localhost-guard.ts`). Everything else needs PROOF, one of:
|
|
2840
|
+
- `pi_dash_local` httpOnly `SameSite=Strict` cookie, 30 d, value `HMAC(localToken, "pi-dashboard/local-proof/v1")` — rotating the local token invalidates every proof cookie;
|
|
2841
|
+
- `X-Pi-Local-Token` header;
|
|
2842
|
+
- authenticated principal (`request.isAuthenticated`).
|
|
2843
|
+
|
|
2844
|
+
Gated surfaces: `control` / `operate` REST routes, browser WS (`/ws`, `/ws/terminal/*`, `/live/*`), plugin-registered WS scopes (`isPluginScopePeerLocal`), bridge-ticket mint (`decideBridgeTicketMint`), and the route-tier exemption (`tierRefusalFor`). A `127.0.0.1` entry in `trustedNetworks` / `auth.bypassHosts` no longer re-admits a relay under strict — `isTrustedSource` refuses a loopback-range peer without proof.
|
|
2845
|
+
|
|
2846
|
+
**Why it exists.** A header-injecting tunnel (zrok) presents as loopback but carries `X-Forwarded-*`, so it already fails `isGenuinelyLocal`. A marker-less relay (`ssh -R`, `socat`) terminates on `127.0.0.1` and injects NO forwarding header — indistinguishable from a same-host browser, so it inherits full unauthenticated access to code-exec routes. Enable `requireLocalProof` when such a relay is used; only zrok-class tunnels are safe without it.
|
|
2847
|
+
|
|
2848
|
+
**Denial.** Under strict, a proof-less bare-loopback denial is `403 { success: false, error: "network_not_allowed", reason: "local_proof_required", hint: … }` — same `error` literal as every other network denial, so clients keep branching on `error`; `reason` carries the strict-mode signal and `hint` names `pi-dashboard open`.
|
|
2849
|
+
|
|
2850
|
+
**Bootstrap.** `pi-dashboard open [--print]` mints a one-time code (`POST /api/local-proof`, `X-Pi-Local-Token` only, 60 s TTL, single use via `LocalProofCodeStore`) and opens `/auth/local-proof?code=…`, which redeems it, sets the `pi_dash_local` cookie, and redirects `/`. Electron always loads that URL. Server not running → `open` exits `1` ("server not running"). Bootstrap routes register regardless of the flag, so `open` works before strict is toggled.
|
|
2851
|
+
|
|
2852
|
+
**Trade-offs (stated, not implied).**
|
|
2853
|
+
- `/v1/*` model proxy keeps bare-loopback admission even under strict: local pi processes call it, and a marker-less relay can spend model credentials but cannot execute code.
|
|
2854
|
+
- `/api/health` posture disclosure unchanged.
|
|
2855
|
+
- A raw `curl -X POST` to `control` / `operate` routes from this host needs `X-Pi-Local-Token` (token at `~/.pi/dashboard/local/token`). `npm run reload` and the CLI `restart` already send it.
|
|
2856
|
+
|
|
2857
|
+
**Pairing approval never honors bare loopback (any mode).** `createApprovalGuard` on `POST /api/pair/approve` and `/api/pair/approve-pending` admits only a login session, a valid proof cookie, or `X-Pi-Local-Token`; a device bearer is refused first, and Host admission still applies. Default-off strict does not exempt it. A hand-typed `http://localhost:8000` on an auth-off install must use `pi-dashboard open` or Electron to approve; the dialog shows the hint.
|
|
2858
|
+
|
|
2859
|
+
**Credential + trust hardening in the same change.**
|
|
2860
|
+
- Login OAuth state carried in a signed `pi_dash_oauth_state` cookie, verified before code exchange; `returnUrl` restricted to same-origin relative paths (closes CSRF + open redirect).
|
|
2861
|
+
- Plugin event emission: automation actions declare `emits: string[]`, undeclared types dropped; `emitEventToSession` refuses reserved namespaces `roles:` `role:` `model:` `prompt:` `dashboard:` `ui:` (`RESERVED_EVENT_PREFIXES`); raw `sendExtensionMessage` refuses `plugin_emit_event`.
|
|
2862
|
+
- `config.json` written atomically `0600` by one secure-write helper (all eight writers); existing group/world-readable files chmod'ed `0600` at load (parity with `auth.json`, `paired-devices.json`, `local/token`).
|
|
2863
|
+
- Same-origin browser exchanges the device bearer once for an httpOnly `pi_dash_device` cookie (`POST /api/device-session`, `Path=/api/`, `SameSite=Strict`); `localStorage` keeps only the non-secret `pi-dashboard:device-paired` marker. Legacy stored bearers are exchanged and removed on startup; WS single-use tickets and the Electron keyring bearer unchanged.
|
|
2864
|
+
|
|
2865
|
+
See change: harden-trust-and-credential-boundaries.
|
|
2866
|
+
|
|
2867
|
+
### Access Grants and Denial Remedies (change: add-access-grants-and-review)
|
|
2868
|
+
|
|
2869
|
+
Companion to **Network Access Control** above. That section's universal `onRequest` guard is the network plane; this one is the filesystem plane. Both turn a terminal refusal into a remedy an operator can accept. Network plane: `403 network_not_allowed` → `BlockEventBuffer` → "Trust this network". Filesystem plane: a containment refusal → `denialId` → **grant** → next read admitted, no restart. The guard above is not re-explained here; see it for the network plane.
|
|
2870
|
+
|
|
2871
|
+
**The single gate.** `packages/server/src/access/containment-gate.ts` `evaluateContainment(resolved, anchors, { site, session })` is the one containment decision every file-read site routes through. Before it, ten sites inlined `isAllowed(...)` and hand-rolled their own 403 body — five distinct denial shapes, two sites with no body at all. The gate keeps the decision exactly as it was and adds the remedy additively. `grep-routes.ts` and `resolve-file-mention.ts` are body-less: they call the grant predicate and discard the denial, so they **consume** grants but can never originate one (a grant must trace to a denial the operator saw).
|
|
2872
|
+
|
|
2873
|
+
**Evaluation order** — the pre-existing containment layers run first and stay authoritative; the grant layer is reached only on their miss.
|
|
2874
|
+
|
|
2875
|
+
```mermaid
|
|
2876
|
+
flowchart TD
|
|
2877
|
+
R["resolved path (lexical)"] --> L1{"Layer ① — within any anchor?"}
|
|
2878
|
+
L1 -->|yes| ALLOW["allow (viaGrant false)"]
|
|
2879
|
+
L1 -->|no| L2{"Layer ② — within anchor's bound checkout roots, realpath'd?"}
|
|
2880
|
+
L2 -->|yes| ALLOW
|
|
2881
|
+
L2 -->|no| G{"Grant layer — within a granted subtree?"}
|
|
2882
|
+
G -->|yes| ALLOWG["allow (viaGrant true) → handle-verified read"]
|
|
2883
|
+
G -->|no| DENY["refuse + remedy: reason, hint, subject, denialId, ancestors"]
|
|
2884
|
+
DENY --> REC[("path-denial registry")]
|
|
2885
|
+
REC --> GRANT["POST /api/access/grants — bind to denialId"]
|
|
2886
|
+
GRANT --> STORE[("access-grants.json")]
|
|
2887
|
+
STORE -. next request .-> G
|
|
2888
|
+
```
|
|
2889
|
+
|
|
2890
|
+
The grant layer is third in evaluation order but is deliberately **not numbered "③"**: `file-routes.ts` already comments an image-only artifact-root admission as "Layer ③", and this change avoids colliding with that numbering. It is always the **grant layer**.
|
|
2891
|
+
|
|
2892
|
+
**Why grants are a subtree check, not an extra `isAllowed` anchor** (design D1). `isAllowed` (`packages/server/src/lib/path-containment.ts`) runs `checkoutAnchors(anchor)` over **every** anchor it receives and admits anything under that anchor's **bound checkout roots** (`thisCheckout` + `mainCheckout`). Appending a grant for `…/repo/sub` as an anchor would therefore silently admit all of `…/repo` — the UI would name one directory and the system would admit its whole repository. Grants are therefore evaluated by a dedicated subtree predicate, `isGrantAdmitted(resolved, grantedSubjects())`, applied **after** `isAllowed` returns false. `isAllowed`'s semantics and its existing per-site anchor sets (`homePiAnchor()`, the pinned-directory anchor) are untouched, so the existing `file-read-containment` suite passes unchanged. What the UI names is exactly what is granted.
|
|
2893
|
+
|
|
2894
|
+
**The stored subject is a realpath; the request side is realpath'd, the stored side is not** (design D2). `resolved` at every call site is **lexical** (`path.resolve`, symlink-unresolved). Two rules follow, asymmetric on purpose:
|
|
2895
|
+
|
|
2896
|
+
- The subject is `realpath`'d **at grant time** and that value is persisted and displayed (`normalizeGrantSubject`). A grant binds to the directory the operator actually saw. Storing the lexical path would bind the grant to a symlink (`/wt/current`) and follow it wherever the link was later repointed — a silent widening with no new approval.
|
|
2897
|
+
- At check time the predicate is `within(realpath(resolved), storedSubject)`: `realpath` on the **request side only**. A lexical compare would reintroduce the symlink escape layer ② exists to close, inside granted directories. The stored subject is **not** re-resolved, because a symlink swapped in over the subject (or any ancestor of it) would then silently migrate the grant and reopen the hole D2 closes.
|
|
2898
|
+
|
|
2899
|
+
The rejected alternative, `within(realpath(resolved), realpath(grant))`, was a **double-realpath** that contradicted D2 and was corrected in planning. Strict `fs.realpath` is used, not `safeRealpath`: a granted directory later deleted (or recreated as a symlink) refuses rather than matching its nearest existing ancestor. An empty grant list short-circuits before any syscall.
|
|
2900
|
+
|
|
2901
|
+
**The store.** `packages/server/src/access/access-grants.ts`. Persisted at `~/.pi/dashboard/access-grants.json` (`PI_ACCESS_GRANTS_STORE` overrides; schema `{ version: 1, grants }`). One grant carries `subject` (realpath), `scope` (`"session"` — in-memory until server restart — or `"project"` — persisted), `grantedAt`, `origin` (the session whose denial produced it), and optional `widenedFrom` (the denied subject when the grant came from an offered ancestor). Invariants: absent/malformed store → empty, never throws; **cap 200 per scope**, oldest-`grantedAt` evicted within that scope only (a union cap would let an ephemeral session grant delete a persisted project grant); writes atomic (temp + rename) so a crash mid-write cannot truncate the store into its own malformed→empty rule; a failed write is non-fatal — the subject stays ungranted, the failure is logged **and returned to the caller** so the UI cannot claim a grant that does not exist. Recorded grants are audited (`[access-grant] granted subject=… scope=… site=… denialId=…`).
|
|
2902
|
+
|
|
2903
|
+
`"session"` scope means the **server process**, not the pi session whose denial produced it (design D17): one grant widens the grant layer for every session and every connected client; `origin` is what the Access tab shows.
|
|
2904
|
+
|
|
2905
|
+
**Read-once, cost-bounded on the hot path** (design D16). The store is loaded into memory once and invalidated on write; the containment path never reads the store synchronously. `isAllowed` is async by explicit design (one caller stalling would block every request), so a sync read on that path would regress it. With an empty store the predicate short-circuits with zero syscalls — that is what makes "empty store is byte-identical to today" true of **cost** as well as outcome. When grants exist, evaluation is a linear scan of distinct subjects with one `realpath` on the request side; `grep-routes.ts` awaits the predicate per match, so N matches x 200 grants x a `realpath` is the worst case the cap alone does not bound. `GET /api/access/store-stats` exposes the load count so a test can prove the hot path never re-reads the store. Rollback consequence: deleting the store file changes nothing until the process restarts — the supported rollback is **revoke through the Access tab** (which invalidates the in-memory set), or delete-then-restart.
|
|
2906
|
+
|
|
2907
|
+
**Denial registry.** `packages/server/src/access/access-denials.ts` is what makes "a grant may only name a subject a recorded denial named" testable — the network ledger `BlockEventBuffer` is keyed by IP and carries no path, so it cannot supply the binding. Keyed by grantable **subject** (the refused path's containing directory), each entry carries an opaque `denialId` (UUID), the subject, the refusing `site` (`file-routes:661`), the originating session, a timestamp, and the offered-ancestor ladder. Entries expire at `DENIAL_TTL_MS = 10 * 60 * 1000` and the registry is capped at 200, oldest-evicted. It is written **only by the containment denial path**, never by an inbound request — the same invariant the network ledger holds. An unknown, expired, or evicted `denialId` makes the grant request fail.
|
|
2908
|
+
|
|
2909
|
+
The denial body is additive on an unchanged `error` string: `{ success, error, reason, hint, subject, denialId, ancestors }`. `ancestors` is always present (possibly empty) so the body has a deterministic key set. No containment outcome changes — every allow stays an allow, every refusal stays a refusal with the same status code and the same `error` string. The two body-less sites emit nothing.
|
|
2910
|
+
|
|
2911
|
+
**Offered-ancestor ladder.** `packages/server/src/access/ancestor-ladder.ts` computes the directories above a denied subject that the remedy may also offer (a refused file is usually a level below a boundary the operator cares about). Rules: computed from the subject's **real** path, truncated at a **git checkout root** (inclusive) or, with no repository, stopping **below** `$HOME` (exclusive); the filesystem root is never a rung; every rung passes the forbidden filter, so a ladder can never climb into a secret store. Parent is `$HOME` → empty ladder.
|
|
1808
2912
|
|
|
1809
|
-
|
|
2913
|
+
**Forbidden subjects are compared as real paths** (design D15). `packages/server/src/access/forbidden-subjects.ts`. `realpath("/etc")` is `/private/etc` on macOS and a home directory may itself be a symlink, so a lexical compare is trivially bypassed. Two lists: `whole` — refused **exactly** — `/`, `$HOME`, and the POSIX/Windows system roots (`/etc`, `/usr`, `/var`, `/Library`, `/System`, `/bin`, `/sbin`, `/opt`, `C:\Windows`, …); `sensitive` — refused **exactly and for every descendant** — `~/.ssh`, `~/.pi`. The descendant rule is what stops an offered-ancestor ladder from climbing into a secret store, and `subsumesForbiddenGrantSubject` also rejects a rung that is an **ancestor** of a forbidden subject (`/private` on macOS would admit `/private/etc`; `/Users` would admit a home directory). `isUngrantableSubject` names the exact pair the route and the store both enforce — the route filters the **normalized** subject it will persist, and `recordGrant` re-applies it as a store-level backstop. Filtering the raw input once left a one-click escalation: a denial subject is the lexical `dirname` of the refused path, so `$HOME/.CFUserTextEncoding/x` named the **file** `$HOME/.CFUserTextEncoding`, which passed the filter and then normalized into a grant for the whole of `$HOME`.
|
|
1810
2914
|
|
|
1811
|
-
|
|
2915
|
+
**Grant endpoint — the one place a grant is created.** `packages/server/src/routes/access-routes.ts` `POST /api/access/grants`. The request must carry a `denialId` that names a **live** recorded denial; the subject must be the denial's subject or one of its offered ancestors, compared in **canonical** form (what the store persists); the forbidden filter runs on the normalized subject. A write failure returns `500` with the reason, while the refused read still `403`s exactly as it would have — failure narrows, never widens.
|
|
1812
2916
|
|
|
1813
|
-
|
|
2917
|
+
Two design boundaries are stated rather than overclaimed (design D15):
|
|
1814
2918
|
|
|
1815
|
-
|
|
2919
|
+
- The endpoint requires authentication and is refused **cross-origin** by the dashboard's global `createMutationOriginGate` (the `onRequest` guard over every `/api/*` non-GET), so the refusal cannot drift from the rest of the API.
|
|
2920
|
+
- This is enforced against **remote and cross-origin** callers only. It does **not** establish operator presence: `auth-plugin.ts` returns early for a genuinely local request, so any local process — including an agent's own `bash` tool — can read a `403`, learn the subject it names, and satisfy the binding. Distinguishing the operator from a local process is the eligibility problem carved into `add-access-grant-dialog`; this change does not solve it and must not claim to. Until that lands, the grant endpoint has no human-facing caller other than the remedy surface.
|
|
1816
2921
|
|
|
1817
|
-
**
|
|
2922
|
+
**Handle-verified reads close the check→open window** (design D14). `packages/server/src/access/verified-read.ts`. Containment is a check on a **path**; the byte read is a later syscall on the same path, so a symlink swapped in between passes the check and serves the substituted file. The fix is not to re-check the path (a second check races identically) but to verify the **open handle**: `lstat` first and require a regular file (load-bearing beyond correctness — `open(2)` on a FIFO **blocks**, so a granted directory holding a FIFO would otherwise hold a request open), then `open` with `O_NOFOLLOW`/`O_NONBLOCK`, then `fstat` and compare `dev`+`ino` against the pre-open `lstat`, then serve from the verified handle. `readFileVerified`/`readFileVerifiedUtf8` read in-process; `assertRegularFile` covers the office/EML gates that hand a **path** to an out-of-process renderer (closes the FIFO hazard, not the inode bind). Scope: **grant-admitted byte-serving reads only** (`viaGrant`) — read, raw, render, session-file, office sheet. `tree`, `exists`, mention and grep never open a file and keep path-based checking; the regular-file rule would break their directory admission. Layers ①/② carry an identical pre-existing window this change deliberately does not touch, so the asymmetry is intentional: the grant layer is the one admitting paths outside every derived anchor, so it earns the stronger check.
|
|
1818
2923
|
|
|
1819
|
-
|
|
2924
|
+
The module states its residual limits rather than overclaiming: `O_NOFOLLOW` covers the final path component only, and a hardlink inside a granted tree pointing at a file outside it is admitted (`realpath` does not resolve hardlinks — inherent to a realpath-based predicate).
|
|
1820
2925
|
|
|
1821
|
-
**
|
|
2926
|
+
The audit that produced D14 also found a **descriptor leak**: the grant-verified handle was opened before HTTP range parsing, and the four `416` early returns never closed it, so `Range: bytes=abc` repeated against any grant-admitted file leaked one descriptor per request until EMFILE. Fixed by construction — range parsing now completes **before** the handle is opened, so no `416` path can leak one.
|
|
1822
2927
|
|
|
1823
|
-
**
|
|
2928
|
+
**Settings → Access tab** (design D6/D12). Server `GET /api/access/grants` aggregates every in-scope store; client `packages/client/src/components/settings/AccessSection.tsx` renders it under the Settings nav, reached via `SettingsPanel.tsx`'s `access` page. It **reviews and revokes only — it never creates a grant**: a filesystem grant originates only from the remedy surface attached to an actual denial, so the tab has no add control by construction. Rendering performs zero store writes; the only request on mount is the aggregate GET.
|
|
1824
2929
|
|
|
1825
|
-
**
|
|
2930
|
+
The tab reads **eight** stores in place and revokes each against its **own** write path — never migrating them: `access-grants.json` (path grants), `worktree-init-trust.json`, `kb-source-trust.json`, pi's `ProjectTrustStore`, `config.trustedNetworks`, `auth.bypassHosts`, `cors.allowedOrigins`, and `preferencesStore` pinned directories. Revokes: `DELETE /api/access/grants` (`revokeGrant`), `/worktree-trust` (also clears in-memory session trust), `/bypass-hosts` (writes `auth.bypassHosts`; **never** `trustedNetworks`), `/project-trust` (routed through pi's own store — `decision: null` deletes the entry — not written directly), and `/pinned-directory`. KB source trust is revoked at `DELETE /api/kb/source-trust` by the kb-plugin, which owns kb's trust module; the dashboard reads that store for display only. Legacy `kb-source-trust.json` entries are `sha256 → true` with no displayable subject, so the tab renders their opaque hash rather than breaking. Two grant-bearing stores are deliberately excluded: `paired-devices.json` (its own surface) and `auth.bypassUrls` (grants route access, not resource access).
|
|
1826
2931
|
|
|
1827
|
-
|
|
2932
|
+
Since revocation invalidates the in-memory set, a revoke takes effect on the **next request with no restart**; the tab refetches after each revoke. This is also why revoke-through-the-tab, not deleting the file, is the supported rollback.
|
|
1828
2933
|
|
|
1829
|
-
|
|
2934
|
+
### Agent Path Gate (change: ask-agent-file-access-in-chat)
|
|
1830
2935
|
|
|
1831
|
-
|
|
2936
|
+
Bridge-side companion to **Access-Grant Prompts and YOLO** and **Access Grants and Denial Remedies** below/above: those guard the dashboard's own filesystem plane (`/api/file*`, preview loads). This one guards the **agent's** `read` / `write` / `edit` tool calls — a pi session opens files in-process, so without a gate a call outside the session workspace is never denied and the operator is never asked.
|
|
1832
2937
|
|
|
1833
|
-
|
|
2938
|
+
**Approve, not sandbox.** Gate asks operator when a covered tool leaves its roots. Does **not** confine: `bash`, `grep`, `find`, `ls`, custom and MCP tools are not covered (shell strings are not reliably parseable). UI copy must not call it a sandbox or confinement. Agent runs as the operator's user and can write `access-grants.json` itself; nothing here defends against a hostile local process.
|
|
1834
2939
|
|
|
1835
|
-
|
|
2940
|
+
**Where it lives** (design D1). Pure decision module `packages/extension/src/path-gate/` (`decidePathAccess`, plus `resolve.ts`, `roots.ts`, `grant-cache.ts`, `suppression.ts`, `grant-link.ts`, `handler.ts`, `index.ts`). Registered in `bridge.ts` as its own `tool_call` handler **after** the fan-out admission handler (`fanoutAdmission.onToolCall`), **not** wrapped in the fail-open `safe(...)`. Own `try/catch` maps any internal error — including a throwing `ctx.cwd` getter after session teardown — to `{ block: true, reason }`. In-root calls take no round-trip.
|
|
1836
2941
|
|
|
1837
|
-
|
|
2942
|
+
**Gated tools.** `read`, `write`, `edit` only, matched by name.
|
|
1838
2943
|
|
|
1839
|
-
|
|
2944
|
+
**Canonicalisation matches the tool** (design D2). `resolveToolPath` reproduces pi's rules: `~` expansion, `@`-prefix strip, Unicode-space normalisation, `file://` URL, win32 shell-path mapping, `..`, resolve against `cwd`. pi's helper is not exported, so the gate carries its own implementation plus a **parity test** importing pi's `dist/core/tools/path-utils.js` by file path; a pi upgrade that changes resolution fails the test. `canonicalizeTarget` then real-paths the **nearest existing ancestor** and re-appends the missing tail. `read` decides on the path pi will open — pi `resolveReadPath` filename-variant fallback (AM/PM narrow-space, NFD, curly-quote, NFD+curly; final name only, same directory) replicated in `path-gate/resolve.ts` `resolveReadTarget`, parity-tested vs pi. `write` / `edit` use plain `resolveToCwd` (no fallback). A variant that is an in-root symlink to an outside file → decided on the outside target; the fallback only changes the final segment within the same directory, so it cannot move a target across a root boundary.
|
|
1840
2945
|
|
|
1841
|
-
|
|
2946
|
+
**Roots** (each real-pathed once when computed):
|
|
1842
2947
|
|
|
1843
|
-
|
|
2948
|
+
1. session `cwd` + bound **checkout root**, resolved by the same rules as `file-read-containment` (nearest root, worktree / submodule / separate-git-dir binding checks, bounded async probe `PROBE_BOUND_MS` 3 s, fail closed to `cwd`). Probe starts at `session_start`; a decision needing it awaits up to the bound, else uses `cwd` only.
|
|
2949
|
+
2. read-only built-ins: pi agent dir, each loaded skill's directory, pi package docs dir, pi-loaded context files.
|
|
2950
|
+
3. read+write built-ins: `os.tmpdir()` (+ `/tmp` on POSIX), session dir under `~/.pi/agent/sessions`.
|
|
2951
|
+
4. persisted **project-scope** grants from `access-grants.json` — read directly by the bridge, mtime-gated cache, malformed → empty. Works with no dashboard.
|
|
1844
2952
|
|
|
1845
|
-
|
|
2953
|
+
Built-in roots are evaluated first, so pi's own `~/.pi/agent` reads never prompt.
|
|
1846
2954
|
|
|
1847
|
-
|
|
2955
|
+
**Containment is component-wise** (`isWithin`, `isSubjectWithin`). Never string prefix; case sensitivity probed from the volume. Exact (case-sensitive) match checked first; volume case probe (`volumeCaseInsensitive`, shared) consulted only when exact check fails → case-sensitive macOS volume never folds; hot path probe-free. Grant cache signature = mtime+size+ino+ctime (atomic rename rewrite seen). `canonical-subject.ts` + `forbidden-subjects.ts` moved to `packages/shared/src/` with server re-exports; browser client MUST NOT import them (the Access page's agent-prompt label reads `via` from the API) — a client-side import guard test enforces it.
|
|
1848
2956
|
|
|
1849
|
-
|
|
2957
|
+
**Verdicts** (design D4). First prompt `ctx.ui.select`, metadata `{ kind: "agent-path-gate", path, access, sensitive }`, always chat-placed (never widget-bar):
|
|
1850
2958
|
|
|
1851
|
-
|
|
2959
|
+
- title `Agent wants to <tool> outside its workspace: <canonical path>` plus ` ⚠ sensitive location` when flagged. Title carries path + sensitive flag — TUI shows title + options only; metadata = dashboard-card detail. Body (dashboard card, `metadata.message`): canonical path, tool name, session cwd; byte count / edit count for `write` / `edit`; sensitive line when flagged; note when Always allow withheld.
|
|
2960
|
+
- options `Allow once`, `Deny`, and — when permitted — `Always allow <dir>…`. Nothing preselected.
|
|
1852
2961
|
|
|
1853
|
-
|
|
2962
|
+
Second prompt (Always-allow only) `ctx.ui.confirm`, metadata `{ kind: "agent-path-gate-confirm", path, subject }`, names the **subject** — the target itself when it is a directory, else its containing directory; never an ancestor — states it persists and is revocable in Settings ▸ Access.
|
|
1854
2963
|
|
|
1855
|
-
|
|
2964
|
+
| Answer | Result |
|
|
2965
|
+
|---|---|
|
|
2966
|
+
| `Allow once` | this call runs; next call to same path asks again (single-call, never remembered) |
|
|
2967
|
+
| `Deny` | block |
|
|
2968
|
+
| first prompt dismissed (`undefined`) | block (treated as Deny) |
|
|
2969
|
+
| `Always allow` → confirm `true` | grant request; this call runs |
|
|
2970
|
+
| `Always allow` → confirm `false` / dismissed | block (treated as Deny) |
|
|
1856
2971
|
|
|
1857
|
-
|
|
2972
|
+
**One time budget.** Both prompts draw from one `agentPathGate.timeoutSeconds` (default 120); the confirm gets only the remaining time; the gate cancels any open prompt via PromptBus on expiry. Per-session **mutex** — at most one gate prompt per session open.
|
|
1858
2973
|
|
|
1859
|
-
|
|
2974
|
+
**Always-allow is a bound, single-use grant** (design D3). On confirm the bridge sends `path_grant_request { requestId, sessionId, promptId, path, subject }` — it never writes the store. Server keeps a bounded confirm registry (`access/agent-confirm-registry.ts`): records `{ promptId, sessionId, path, subject, expiresAt }` when it forwards a `prompt_request` whose metadata `kind` is `agent-path-gate-confirm` — **first sight only** (a replayed `prompt_request` neither re-registers nor extends `expiresAt`). `prompt_cancel` / session end removes the entry; `prompt_dismiss` marks it settled, redeemable 5 s only. A request is accepted only if the WS connection is bound to `sessionId`, an unexpired unused entry exists for `promptId`, and both `path` and `subject` match by `isSameSubject` (canonical, not string equality); the entry is consumed single-use. The server then **re-derives** the subject from the confirmed PATH at grant time by the same rule (the target itself when it is a directory, else its containing directory; never an ancestor), refuses unless it equals the confirmed subject (a directory created, renamed or symlink-swapped between prompt and grant is never persisted under an unseen name), applies `isUngrantableSubject`, calls `recordGrant({ subject, scope: "project", origin: sessionId, via: "agent-prompt" })`, and replies `path_grant_result { requestId, ok, subject | error }`.
|
|
1860
2975
|
|
|
1861
|
-
|
|
2976
|
+
**Same-store gate** (`access/grant-store-id.ts`). Server ensures `~/.pi/dashboard/grant-store-id` exists — exclusive-create `O_EXCL`, `0600`, random 128-bit token; an existing file is never overwritten. On every bridge (re)registration it **re-reads** the file and sends `dashboard_identity { grantStoreId }` (never a cached value). The bridge reads its own file and offers Always allow only when the two are equal. Missing frame / missing local file / mismatch → not offered, card note "can't be remembered here". The offer is re-evaluated on every `dashboard_identity`. This proves the connected server writes the very store the gate reads — **not** operator presence.
|
|
1862
2977
|
|
|
1863
|
-
|
|
2978
|
+
**Fail closed** (design D5):
|
|
1864
2979
|
|
|
1865
|
-
|
|
2980
|
+
| Condition | Result |
|
|
2981
|
+
|---|---|
|
|
2982
|
+
| ungrantable containing dir / target in `sensitive` | ask; Allow once / Deny only; sensitive flag |
|
|
2983
|
+
| recently denied directory (same session, < 120 s) | block, no prompt, reason `recently-denied` |
|
|
2984
|
+
| Deny / dismissal / confirm refused | block, reason `denied` |
|
|
2985
|
+
| budget expired | block, prompts cancelled, reason `timeout` |
|
|
2986
|
+
| `ctx.hasUI === false` | block, no prompt, reason `no-ui` |
|
|
2987
|
+
| gate internal error (incl. `ctx.cwd` throws) | block, reason `error` |
|
|
2988
|
+
| grant write fails (`ok === false`) | this call runs once (operator did approve); card note "not saved: <error>" |
|
|
1866
2989
|
|
|
1867
|
-
|
|
2990
|
+
`forbidden-subjects.ts` lists `whole` (refused exactly: `/`, `$HOME`, system roots) and `sensitive` (refused with descendants: `~/.ssh`, `~/.pi`). They govern what may be **granted**; the gate never hard-blocks on them (hard-block would make `write ~/.pi/agent/AGENTS.md` impossible, pushing operators to disable the gate wholesale).
|
|
1868
2991
|
|
|
1869
|
-
|
|
2992
|
+
**Repeat suppression** (`suppression.ts`, `SUPPRESSION_MS` 120 s). Takes precedence over asking, including sensitive targets. Key `D` = **lexical** parent of the canonical target (nearest-existing ancestor + remaining segments, minus the last), so `/w/newproj1/a.txt` keys `/w/newproj1`, never the shared ancestor `/w`. After a Deny, dismissal or timeout for a target whose containing directory is `D`, further gated calls in the **same session** under `D` block **without a prompt** for 120 s. Expiry or an explicit Allow elsewhere does not lift it early. Sessions are independent; exhaustion never degrades to allow.
|
|
1870
2993
|
|
|
1871
|
-
`
|
|
2994
|
+
**Attention + visibility** (design D7). The gate prompt fires while `currentTool` is already `read` / `write` / `edit`, so the `ask_user` fold never marks needs-you; `currentTool` is left untouched (no race with sibling `tool_execution_start` writes). New session field `awaitingFileAccess: boolean`, **derived** from the server's pending-prompt registry: true while any tracked pending prompt of the session has `kind` `agent-path-gate` / `agent-path-gate-confirm`. Tracked on the live fan-out branch, the reconnect **replay** burst, and unicast resync; dropped on answer / dismiss / cancel / session end / **bridge disconnect**, and re-derived at replay exit. The needs-you rollup and urgency predicate become chat-routed `ask_user` state **or** `awaitingFileAccess`. A non-modal toast ("Session ‹name› is waiting for file access → Open") fires when such a prompt is first shown and the operator is not viewing that session; it clears on settlement.
|
|
1872
2995
|
|
|
1873
|
-
`
|
|
2996
|
+
**Observability** (design D8). One log line per non-in-root outcome: `[path-gate] <outcome> tool=<t> access=<r|w> path=<canonical> session=<id> sensitive=<bool>`; outcomes `asked | allowed-once | allowed-always | denied | recently-denied | timeout | no-ui | error`. In-root outcomes are counted, not logged. Counters ride the existing bridge status payload on heartbeat metrics: `pathGateInRoot`, `pathGateAsked`, `pathGateBlocked`. The server logs accepted and refused `path_grant_request`s with the refusal cause.
|
|
1874
2997
|
|
|
1875
|
-
|
|
2998
|
+
**Config** (design D6). `DashboardConfig.agentPathGate = { enabled: true, timeoutSeconds: 120 }` (`packages/shared/src/config.ts`, `AgentPathGateConfig`, `DEFAULT_AGENT_PATH_GATE`). Bridge stats the config file each call (signature mtime+size+ino+ctime) and re-parses only on change → toggle applies from next tool call; env override applied every call. `PI_DASHBOARD_AGENT_PATH_GATE=off|on` overrides per process. Settings ▸ Security toggle (`components/settings/AgentPathGateSection.tsx`) — inert under an env override. Disabled → handler returns immediately.
|
|
1876
2999
|
|
|
1877
|
-
|
|
3000
|
+
**Residuals / non-goals.** `bash` / `grep` / `find` / `ls` / custom+MCP tools not covered (not a sandbox); TOCTOU symlink swap between gate and open accepted; a same-user process can write `access-grants.json` itself; session-scope grants (server memory) are not shared with the gate (the Access page labels them "dashboard only"); the grant binding proves a **raised** confirm, not operator presence (the server cannot observe answers — browser answers are forwarded unrecorded, TUI answers arrive value-less). Rollback: `agentPathGate.enabled=false` or env `off` — applies from the next tool call; grants already written stay valid for the dashboard's file plane.
|
|
1878
3001
|
|
|
1879
|
-
|
|
3002
|
+
```mermaid
|
|
3003
|
+
sequenceDiagram
|
|
3004
|
+
participant A as agent tool_call
|
|
3005
|
+
participant G as path-gate (bridge)
|
|
3006
|
+
participant U as operator (chat/TUI)
|
|
3007
|
+
participant S as server
|
|
3008
|
+
A->>G: read, write or edit(path)
|
|
3009
|
+
G->>G: resolve pi-parity, canonicalizeTarget
|
|
3010
|
+
G->>G: decidePathAccess vs roots
|
|
3011
|
+
alt in-root
|
|
3012
|
+
G-->>A: allow, no round-trip
|
|
3013
|
+
else out-of-root
|
|
3014
|
+
G->>U: select Allow once / Deny / Always allow
|
|
3015
|
+
alt Allow once
|
|
3016
|
+
G-->>A: allow, single call
|
|
3017
|
+
else Deny, dismiss or timeout
|
|
3018
|
+
G-->>A: block
|
|
3019
|
+
else Always allow
|
|
3020
|
+
G->>U: confirm exact dir, persists
|
|
3021
|
+
U-->>G: true or false
|
|
3022
|
+
G->>S: path_grant_request promptId, path, subject
|
|
3023
|
+
S->>S: redeem confirm single-use 5 s, re-derive subject
|
|
3024
|
+
S->>S: recordGrant project, via agent-prompt
|
|
3025
|
+
S-->>G: path_grant_result ok
|
|
3026
|
+
G-->>A: allow this call
|
|
3027
|
+
end
|
|
3028
|
+
end
|
|
3029
|
+
```
|
|
1880
3030
|
|
|
1881
|
-
###
|
|
3031
|
+
### Access-Grant Prompts and YOLO (change: add-access-grant-dialog)
|
|
1882
3032
|
|
|
1883
|
-
|
|
3033
|
+
Companion to **Access Grants and Denial Remedies** above. That section makes a denial *name* its remedy (`denialId`, subject, ancestors); this one makes it **ask** — an active dialog on the operator's screen at the moment of denial, with `Allow once` / `Allow always` / `Deny`. The hard part is not the dialog but the eligibility question: **which requests may raise a dialog on the operator's screen?** A dialog is an action performed *on* the operator, so an unanswerable eligibility rule is a confused-deputy weapon. Four prior rules (caller-is-human; auth credential; CORS-gated header; `Sec-Fetch` shape) were each defeated against source; `design.md` D1/D1a/D1b records the defeats and the surviving rule.
|
|
1884
3034
|
|
|
1885
|
-
|
|
3035
|
+
**Eligibility — a per-connection capability** (D1/D1a). On connect, `BrowserGateway` issues each browser socket a socket-bound **prompt capability** — a `grant_channel` frame carrying a 256-bit nonce (`packages/server/src/access/prompt-channel.ts`, `issuePromptChannel` / `resolvePromptChannel` / `releasePromptChannel`). Memory only, never persisted, rotated per connection, released on socket close. A request becomes **prompt-eligible** by echoing the nonce in the `X-Pi-Grant-Channel` header (`GRANT_CHANNEL_HEADER`); the server resolves it back to the issuing socket. Absent, empty, wrong and non-string all resolve to the same `null`; comparison is `timingSafeEqual` with no early break, so lookup cost does not depend on where a match sits. Eligibility consults the capability and nothing else — not auth, not CORS, not `Sec-Fetch-*`, not an `Origin`/`Host` compare (the four recorded defeats).
|
|
1886
3036
|
|
|
1887
|
-
|
|
3037
|
+
Issuance itself is gated on browser-shaped provenance (`packages/server/src/access/capability-issuance.ts`, `shouldIssuePromptCapability(headers, corsOpts)`): a non-absent admitted `Origin`, plus a site relation **derived** from `Origin` vs `Host` (`siteRelation`), because Chrome sends no `Sec-Fetch-Site` on a WebSocket upgrade (verified Chrome 153, headed and headless). Derived `same-origin` (`isSameOriginByHost`) qualifies; the same hostname on another port/scheme, or loopback to loopback, is `same-site` and refuses (a hostile dev server on `localhost:3000` is CORS-admitted); anything else is `cross-site` and qualifies only through the admission rule (`isOriginAdmitted`), which serves the neutral `pi-dashboard.dev` shell; an unparseable `Host` refuses. A `Sec-Fetch-Site` that IS present must still be `same-origin` or `cross-site` (defence in depth). These are **provenance signals, not an authentication boundary** — a same-machine process can forge them. Accepted residuals **R-A**/**R-C**: on a no-auth loopback install only real credentials, not the host-gate mode, bound who may *answer*.
|
|
1888
3038
|
|
|
1889
|
-
|
|
3039
|
+
Client half: `packages/client/src/lib/access-grants/grant-channel.ts`. `setGrantChannel` on each `grant_channel` frame, `clearGrantChannel` on socket close. One idempotent `window.fetch` wrapper (`installGrantChannelFetch`) echoes the capability on same-origin `/api/*` only, never cross-origin.
|
|
1890
3040
|
|
|
1891
|
-
|
|
3041
|
+
**Prompting requires `hostGate.mode === "enforce"`** (D2). D1 alone does not beat DNS rebinding: a rebound `attacker.com` is same-origin-by-Host and gets a capability anyway. Only Host validation stops it, so prompting — not merely suspension — is gated on the live resolved mode. Shipped default is now `enforce` (`shared/src/config.ts`); on an opt-out `report` install every plane degrades to **record-only** and the Access surface is the whole product. See change: harden-server-request-surfaces (D2b).
|
|
1892
3042
|
|
|
1893
|
-
|
|
3043
|
+
**Two settlement modes, four planes** (D2a). The proof differs because the question differs: a HELD plane asks “may this request be suspended and resumed?”, which only the request can answer, so the request must carry the capability; a DEFERRED plane asks “may the operator be told?”, whose requester is untrusted by definition, so authority comes from the operator's own live channel.
|
|
1894
3044
|
|
|
1895
|
-
|
|
1896
|
-
|
|
3045
|
+
| Mode | Denied request | Verdict applies | Planes (`access/planes.ts`) |
|
|
3046
|
+
|---|---|---|---|
|
|
3047
|
+
| **HELD** | suspended pending the verdict; on `Allow` the original request proceeds | to this request, plus persisted on `Allow always` | filesystem containment (YOLO-eligible), unknown-`cwd` |
|
|
3048
|
+
| **DEFERRED** | denied immediately with today's 403 | requester's next retry, and only via `Allow always` | network / trusted-networks, CORS origin — and any plane whose requester is untrusted or unreachable |
|
|
1897
3049
|
|
|
1898
|
-
|
|
1899
|
-
The `ArchiveBrowserView` provides a searchable, date-grouped listing of archived OpenSpec changes. It uses a dedicated `GET /api/openspec-archive?cwd=<path>` endpoint that scans `openspec/changes/archive/` and returns entry metadata (name, date, artifacts). The view uses two-level navigation: the list is the first level, and clicking an artifact letter (P/D/S/T) opens the reader as the second level. Back from the reader returns to the list (preserving search and scroll), and back from the list returns to the session view. Entry point is the `[Archive]` button in `FolderOpenSpecSection`.
|
|
3050
|
+
**Degrade ladder** (`access/access-plane.ts` `promptPrecondition`), one-way: **HELD → DEFERRED → record-only**. Evaluated in order: kill switch or `promptEnabled` off → `disabled`; `hostGateMode !== "enforce"` → `report-mode` (every plane, D2); then the per-mode proof — HELD requires `requestHoldsCapability` (else `ineligible`), DEFERRED requires `operatorChannels > 0` (else `no-audience`). `holdsRequest(plane, precondition)` is true only for a held plane whose precondition passed, so a deferred denial never suspends. Every rung returns today's denial; no rung produces an allow. `persistVerdict` writes only on `allow-always`, and only this plane's store.
|
|
1900
3051
|
|
|
1901
|
-
|
|
3052
|
+
**Registry + flood controls** (`packages/server/src/access/pending-grant-registry.ts`, D4/D8/D9). `record` / `settle` / `forget` / `expire` / `list`, keyed `(plane, subject)`, take-once, first-response-wins. A HELD entry holds a continuation; a DEFERRED entry holds none. Constants: entry TTL `GRANT_ENTRY_TTL_MS` 120 s (the hold ceiling is the same 120 s, not a second knob), capacity `GRANT_REGISTRY_CAPACITY` 64, settled-subject backoff `GRANT_BACKOFF_MS` 120 s, `GRANT_PLANE_PROMPTS_PER_MINUTE` 5, `GRANT_MAX_CONCURRENT_DIALOGS` 2, per-channel share `GRANT_CHANNEL_MAX_ENTRIES` 12 of 64, one prompt/plane/min per deferred channel, and deferred planes together `GRANT_DEFERRED_MAX_ENTRIES` 16 (refusal `deferred-share`). Overflow **refuses** the new denial and never evicts a live entry; exhausting any layer degrades to record-only, never to auto-allow.
|
|
1902
3053
|
|
|
1903
|
-
|
|
3054
|
+
A remote requester is keyed by its **allocation**, not its address (`access/source-channel.ts`: IPv4 `/24`, IPv6 `/64`, `::ffff:` mapped as IPv4), so rotation inside one allocation hits the 12-entry share. The *subject* stays the exact address.
|
|
1904
3055
|
|
|
1905
|
-
|
|
3056
|
+
Coordinator and transport `packages/server/src/access/grant-coordinator.ts` joins a denial to the registry, the planes and the operator's browsers — broadcasts `grant_request`, settles the first well-formed `grant_response`, sends `grant_dismiss` to the losers, and consults `yolo.decide` at the prompt point before the registry. `access/denial-hold.ts` is the one call a denial site makes (`holdDenial`); no coordinator installed = today's denial. CORS origin denials reach the `cors` plane through an `onRequest` observer (`packages/server/src/access/cors-denial.ts` `deniedCorsOrigin` + `createCorsDenialObserver`), registered in `server.ts` after the host gate and before `@fastify/cors`: never the opaque `null` origin, never a same-origin-by-Host page, response unchanged, never held; channel `sourceChannel(ip)`. `access/hold-request.ts` `awaitHold` captures `socket.timeout`, calls `setTimeout(0)` for the hold, and restores it on `reply.raw` `finish` behind `!socket.destroyed` (D7); client abort is detected on the **response** (`reply.raw` `close` while `!writableFinished`), not `request.raw` `close`. On release, `containment-gate` **re-evaluates** the layers against the filesystem as it is now — an allow authorises re-evaluation, never a skip (`reEvaluate`).
|
|
1906
3057
|
|
|
1907
|
-
|
|
3058
|
+
```mermaid
|
|
3059
|
+
flowchart TD
|
|
3060
|
+
D["guard denial (filesystem / cwd / network / cors onRequest observer)"] --> C["denial site builds facts; reads capability from LIVE request (D6)"]
|
|
3061
|
+
C --> P{"promptPrecondition"}
|
|
3062
|
+
P -->|disabled / report-mode / ineligible / no-audience| RO["record-only: today's denial; still lands in pending list"]
|
|
3063
|
+
P -->|held + capability| HOLD["suspend request (awaitHold, 120 s ceiling)"]
|
|
3064
|
+
P -->|deferred + live operator| DEF["deny now with today's 403"]
|
|
3065
|
+
HOLD --> REG[("pending-grant-registry keyed (plane, subject)")]
|
|
3066
|
+
DEF --> REG
|
|
3067
|
+
REG --> B["broadcast grant_request to operator browsers"]
|
|
3068
|
+
B --> V{"first grant_response wins"}
|
|
3069
|
+
V -->|allow-once| AO["release THIS request"]
|
|
3070
|
+
V -->|allow-always| AA["persistVerdict -> plane's own store"]
|
|
3071
|
+
V -->|deny / expire / abort| NO["denial stands"]
|
|
3072
|
+
AO --> RE["reEvaluate: layers run again against the filesystem NOW"]
|
|
3073
|
+
AA --> RE
|
|
3074
|
+
```
|
|
1908
3075
|
|
|
1909
|
-
|
|
3076
|
+
**Ancestor ladder** (`access/ancestor-ladder.ts`). The rungs a remedy may also offer. Computed from the subject's **real** path, truncated at a git checkout root (inclusive) or, with no repository, stopping **below** `$HOME` (exclusive); the filesystem root is never a rung; every rung passes the forbidden filter, so a ladder can never climb into a secret store. An unresolvable subject yields an empty ladder, never a lexical tail. Checkout-root lookup is cached per real directory (`CHECKOUT_ROOT_CACHE_TTL_MS` 5000, `CHECKOUT_ROOT_CACHE_MAX` 256); forbidden sets derive once per ladder. Measured p95 ~1.3 ms at 12 levels (was ~26 ms — `git` spawned per denial).
|
|
1910
3077
|
|
|
1911
|
-
|
|
3078
|
+
**YOLO — time-boxed auto-answer** (`packages/server/src/access/yolo-session.ts`, D13). The realistic failure of an ask-at-denial design is not a wrong click but *clicking `Allow always` until the prompt stops meaning anything*. YOLO is the pressure valve: at the exact point a dialog would be raised, a prompt-eligible containment or unknown-`cwd` denial is auto-allowed **once** — nothing persisted, under a fixed countdown that activity cannot extend. It is bounded on two axes:
|
|
1912
3079
|
|
|
1913
|
-
**
|
|
1914
|
-
|
|
1915
|
-
2. **Trusted networks** — IPs matching `resolvedTrustedNetworks` (CIDR, wildcard, exact). `resolvedTrustedNetworks` computed at load time by merging two config sources: Settings UI writes new entries to `auth.bypassHosts` (canonical path on Security tab, surfaced as "Trusted Networks" section); legacy top-level `trustedNetworks` field remains readable for back-compat with hand-edited `config.json`. Both honor same matching logic; UI does not modify legacy field. **Both fields work independently of whether `auth.providers` is configured** — config with `auth: { providers: {}, bypassHosts: [...] }` honored as-is; auth plugin no-ops when provider registry empty + network guard serves bypass path directly. See `openspec/changes/archive/` for `fix-trusted-networks-no-oauth` which restored this after regression in `consolidate-trusted-networks`.
|
|
1916
|
-
3. **Authenticated** — `request.isAuthenticated === true` (set by auth `onRequest` hook via `decorateRequest`)
|
|
3080
|
+
- **Plane** — `yoloEligible` is a field on the plane registration; a deferred plane cannot declare it (typed `?: false`, a cast `true` rejected at `register`). Network, CORS and pairing are unreachable *by type*, not by a check someone can invert.
|
|
3081
|
+
- **Place** — a session holds a set of roots (from `offerRoots`: real-path + ladder, forbidden-filtered, no free text). Default scope is the session `cwd`. Roots may be added, but an add never extends expiry and never promotes to unscoped.
|
|
1917
3082
|
|
|
1918
|
-
|
|
3083
|
+
YOLO requires `hostGate.mode === "enforce"` and a HELD-eligible denial; there is **no degraded-plane YOLO** (D13a). On a `report`-mode install nothing activates and an env session does not start. `YOLO_DURATIONS_MS` is **15 / 30 / 60 minutes** only, fixed at activation. Environment activation (`yolo-env.ts`) lasts the process lifetime. Its limit is explicit: YOLO bounds who may *ask*, not who may *answer* — per **R-A**, any browser-gateway socket can settle a prompt on a no-auth loopback install.
|
|
1919
3084
|
|
|
1920
|
-
|
|
3085
|
+
An operator's explicit `deny` on a YOLO-eligible plane is remembered in the **refusal ledger** (`access/refusal-ledger.ts`, `access-refusals.json`, `PI_ACCESS_REFUSALS_STORE` overrides the path) — durable, cleared only by the operator — so a later YOLO session refuses that subject (`refused-by-prior-refusal`) instead of auto-allowing it. Auto-answers are logged `(no human answered)` and kept in a bounded in-memory history. Store conventions mirror `access-grants.json`: atomic temp+rename, missing/malformed = empty, a failed write leaves the cache unchanged.
|
|
1921
3086
|
|
|
1922
|
-
**
|
|
3087
|
+
**Opt-in and env vars** (D10). Prompting ships behind `accessGrants.promptEnabled` (**default `false`**). `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` is the kill switch — it engages only on the exact value `1` (`isGrantPromptKilled`). Both suppress *prompting only*: existing grants stay in force and denials still land in the pending list. The no-audience rule is necessary but not sufficient for automation — Playwright E2E runs with a browser connected, so CI relies on the env var. `PI_DASHBOARD_GRANT_YOLO` (`parseYoloEnv`) takes one plain absolute path, a JSON array of absolute paths for several, or the literal `unscoped`; anything else (`1`, `true`, relative, `[]`, malformed JSON, `UNSCOPED`) is `invalid` and leaves YOLO inactive.
|
|
1923
3088
|
|
|
1924
|
-
**
|
|
3089
|
+
**REST** (`packages/server/src/routes/access-prompt-routes.ts`):
|
|
1925
3090
|
|
|
1926
|
-
|
|
3091
|
+
- `GET /api/access/prompts` — `prompting{enabled, killSwitch, hostGateMode, blockers}` (blockers: `report-mode` / `kill-switch` / `disabled`), pending entries, verdicts, YOLO availability, refusals.
|
|
3092
|
+
- `POST /api/access/prompts/:promptId` — `coordinator.settle` (also answers unprompted entries).
|
|
3093
|
+
- `GET /api/access/yolo/roots?base=`, `POST /api/access/yolo` (activate or add a root), `DELETE /api/access/yolo`.
|
|
3094
|
+
- `DELETE /api/access/refusals?plane=&subject=`.
|
|
1927
3095
|
|
|
1928
|
-
|
|
3096
|
+
Access-page mutations (`POST /api/access/prompts/:promptId`, `POST`/`DELETE /api/access/yolo`, `DELETE /api/access/refusals`) run the global mutation-origin gate plus `networkGuard` only — genuinely local (tunnel-aware), local token, trusted network, or authenticated. Deliberately wider than `POST /api/access/grants` (auth or loopback, D15), because a trusted-network browser can already answer through the dialog WS (user decision C); a loopback caller behind a forwarding header (a tunnel) is not local. `GET /api/health.accessGrants` is additive and failure-isolated, served **only** to an authenticated or genuinely-local caller, because `/api/health` is unguarded and the field names the host-gate mode, YOLO state and whether an operator is online.
|
|
3097
|
+
|
|
3098
|
+
**Coverage.** Browser E2E `tests/e2e/access-grant-dialog.spec.ts`; clean-install VM smoke `qa/tests/36-access-grant-dialog.sh`.
|
|
1929
3099
|
|
|
1930
3100
|
### OAuth Authentication Flow
|
|
1931
3101
|
|
|
@@ -2009,7 +3179,7 @@ Server ensures persistent Ed25519 keypair at `~/.pi/dashboard/identity.key` (060
|
|
|
2009
3179
|
|
|
2010
3180
|
#### QR / copy-string pairing
|
|
2011
3181
|
|
|
2012
|
-
Two QR kinds (D1). **Pairing QR** = secure payload `{v,id,code,urls[]}` = protocol version, fingerprint, one-time ~
|
|
3182
|
+
Two QR kinds (D1). **Pairing QR** = secure payload `{v,id,code,urls[]}` = protocol version, fingerprint, one-time ~300s code, TLS-only reachable URLs. `urls[]` holds https/wss only (D14) — never self-signed LAN; includes MagicDNS with provisioned `tailscale cert`; Gateway provider endpoints plus operator-configured `publicBaseUrls` (legacy `pairing.publicBaseUrls` fallback). Rendered as QR plus copyable deep link (same `https://<endpoint>/pair#pi:pair:v1.<b64>` as the QR). **Link QR** = per no-TLS http mesh/LAN endpoint. Encodes bare URL string only — no pairing payload, no crypto.subtle, no bearer. Link-QR arrival governed by `config.trustedNetworks`. Module `packages/server/src/pairing.ts`.
|
|
2013
3183
|
|
|
2014
3184
|
#### Compare-code approval — D12
|
|
2015
3185
|
|
|
@@ -2029,6 +3199,59 @@ sequenceDiagram
|
|
|
2029
3199
|
|
|
2030
3200
|
Code consumed on approval, not redemption. Premature redemption cannot lock out legit device. Operator types device confirmation code into dashboard — active compare-and-match, not one-click. Approval requires authenticated browser session. Rate-limit plus lockout. At most one pending device per code — bounds memory and prompt flood.
|
|
2031
3201
|
|
|
3202
|
+
#### App-wide approval dialog, deny, pending feed
|
|
3203
|
+
|
|
3204
|
+
Change: `add-pairing-approval-dialog`.
|
|
3205
|
+
|
|
3206
|
+
- `PairingManager.redeem(code, meta)` stores bounded untrusted metadata: `userAgent` ≤256 chars, `viaHost` (Host) ≤253, `remoteAddress` (`request.ip`) ≤64, `forwardedFor` (first `X-Forwarded-For` hop) ≤64, `createdAt`.
|
|
3207
|
+
- Metadata serves display only; never drives decisions; never enters logs.
|
|
3208
|
+
- `wirePendingHint` (`packages/server/src/pairing/pairing.ts`) emits content-free `{type:"pair_pending_changed"}` on pending add / approve / deny / lockout / expire.
|
|
3209
|
+
- `packages/server/src/server.ts` wires hint through `browserGateway.broadcastToAll` → ALL browser sockets.
|
|
3210
|
+
- `frameClassOf` assigns `state`, key `pair_pending`; coalesces, never sheds.
|
|
3211
|
+
|
|
3212
|
+
```mermaid
|
|
3213
|
+
sequenceDiagram
|
|
3214
|
+
participant Dev as Device
|
|
3215
|
+
participant Srv as Server
|
|
3216
|
+
participant Op as Operator
|
|
3217
|
+
Dev->>Srv: redeem(code, meta)
|
|
3218
|
+
Srv-->>Op: WS pair_pending_changed
|
|
3219
|
+
Op->>Srv: GET /api/pair/pending
|
|
3220
|
+
Op->>Srv: POST /api/pair/approve-pending or /api/pair/deny
|
|
3221
|
+
Dev->>Srv: poll
|
|
3222
|
+
Srv-->>Dev: approved / rejected
|
|
3223
|
+
```
|
|
3224
|
+
|
|
3225
|
+
- `packages/server/src/routes/pairing-routes.ts` registers operator-only routes; each uses `preHandler: operatorGuard`, NOT `networkGuard`.
|
|
3226
|
+
- `operatorGuard` refuses paired-device bearer + trusted-network-only callers.
|
|
3227
|
+
- `DELETE /api/paired-devices/:id` + `POST /api/pair/approve` operator-only (`createOperatorGuard`); paired-device bearer (`authVia === "device"`) refused 401 even over loopback; approve `label` bounded 1..64 UTF-8 bytes.
|
|
3228
|
+
- `GET /api/pair/pending` returns `pendingId`, metadata, `expiresAt`, `attemptsLeft`; never pairing code or confirm code.
|
|
3229
|
+
- `POST /api/pair/approve-pending {pendingId, confirmCode, label?}` validates label 1..64 UTF-8 bytes before delegation → 400.
|
|
3230
|
+
- Approve-pending errors: `locked_out` → 429; `no_pending` → 404; other errors → 400; mismatch body includes `attemptsLeft`.
|
|
3231
|
+
- `POST /api/pair/deny {pendingId}` returns 200 or 404 `no_pending`.
|
|
3232
|
+
- `approvePending` delegates to `approve()`; both share ONE `MAX_APPROVE_ATTEMPTS = 5` budget per pending device.
|
|
3233
|
+
- Fifth wrong code → `locked_out`; first mismatch → post-increment `attemptsLeft: 4`.
|
|
3234
|
+
- `/api/pair/approve` keeps status codes; mismatch body gains additive `attemptsLeft`.
|
|
3235
|
+
- Re-redeem creates new pending device + confirm code + fresh budget (D8).
|
|
3236
|
+
- Deny marks pending `rejected`; kills pairing code (`redeem` → `invalid_code`); `poll` returns `{status:"rejected"}` for 30s.
|
|
3237
|
+
- `packages/client/src/components/connectivity/PairLanding.tsx` shows `pair-landing-rejected` — "The dashboard declined this device"; no retry.
|
|
3238
|
+
- Electron shell `PairView` maps rejection via `pollOutcome` (`packages/shell/src/lib/protocol.ts`).
|
|
3239
|
+
- Both device clients treat any unknown poll status as terminal.
|
|
3240
|
+
- Pushed expiry (D4b): per-entry `setTimeout(...).unref()` at `expiresAt + 50ms` → `sweep()` emits hint + logs `expired`.
|
|
3241
|
+
- Approve / deny / lockout / overwrite clear expiry timer; server stop calls `PairingManager.dispose()` to clear all.
|
|
3242
|
+
- Logs (D7): `[pairing] pending|approved|denied|mismatch|locked_out|expired id=<first 8 of pendingId>` only.
|
|
3243
|
+
- Logs exclude codes, token, metadata; header CR/LF could forge log lines.
|
|
3244
|
+
- `PairingApprovalHost` (`packages/client/src/components/pairing-approval/`) mounts beside `GrantPromptHost` in both App returns.
|
|
3245
|
+
- Host refetches `GET /api/pair/pending` on every hint + every (re)connect; skips entirely when `getDeviceBearer()` set.
|
|
3246
|
+
- Host shows one dialog, oldest first, plus "+N more waiting"; waits while grant dialog open, never dismisses for grant.
|
|
3247
|
+
- Close = decide later; `pairingApprovalStore` (`packages/client/src/lib/pairing/pairing-approval-store.ts`) keeps per-tab dismissed set.
|
|
3248
|
+
- Settings ▸ Gateway `WaitingDevices` list (`pairing-waiting-list`) exposes Review → reopens request.
|
|
3249
|
+
- Request vanishes without local answer → close + toast "Pairing request handled in another window."
|
|
3250
|
+
- `PairingApprovalDialog` never shows confirm code; operator types 8 digits.
|
|
3251
|
+
- Submit-only validation shows "Enter all 8 digits"; optional device name prefilled from UA via `describeUserAgent` / `deviceNameFromUserAgent` (`packages/client/src/lib/pairing/describe-user-agent.ts`).
|
|
3252
|
+
- Dialog states: form / locked / expired / success; success auto-closes after 4s.
|
|
3253
|
+
- React renders untrusted metadata as text only; XFF shows "(reported by proxy)".
|
|
3254
|
+
|
|
2032
3255
|
#### Bearer device auth — D5/D7
|
|
2033
3256
|
|
|
2034
3257
|
Approval mints long-lived opaque bearer token. Registry `~/.pi/dashboard/paired-devices.json` (0600). Stores only SHA-256 hash. Revoke = row delete (Settings → Security → Paired Devices). Auth branch: `Authorization: Bearer` (REST) feeds existing `request.isAuthenticated` — one OR branch, registered before OAuth plugin. Modules `paired-devices.ts`, `bearer-auth.ts`.
|
|
@@ -2041,6 +3264,8 @@ Durable bearer never rides WS. Client mints short-lived ~15s single-use ticket v
|
|
|
2041
3264
|
|
|
2042
3265
|
Loopback auth-exemption replaced by `isGenuinelyLocal(ip, headers)` = loopback AND no proxy-forwarding header (`x-forwarded-*`, `x-real-ip`, `forwarded`). Closes zrok-tunnel-as-127.0.0.1 bypass at all 3 sites: auth-plugin `onRequest`, `createNetworkGuard`, WS upgrade. Marker-less `ssh -R` not caught by header heuristic — accepted narrowing. Affirmative local-IPC token `~/.pi/dashboard/local/token` (dir 0700, file 0600), header `X-Pi-Local-Token`, for same-host process callers. Module `local-token.ts`. Same-desktop browser keeps loopback trust (genuine-local, no forwarding header).
|
|
2043
3266
|
|
|
3267
|
+
Windows credential ACLs now OBSERVED, not assumed. `chmod` no-op on Windows — owner-only property of `~/.pi/dashboard/local/token`, `~/.pi/dashboard/identity.key`, `~/.pi/dashboard/paired-devices.json` rests on inherited NTFS profile ACLs, not mode bits. Observed 2026-09-14. Method `qa/tests/28-gateway-windows.ps1` §4: second local user via `New-LocalUser`, asserted NOT in `Administrators` (else test vacuous), real read attempt via `Start-Process -Credential`; all three files minted first through product writers `ensureLocalToken` / `ensureServerIdentity` / `PairedDeviceRegistry`. Result `READ-DENIED` (`UnauthorizedAccessException`) all three. DACL per file: no `Everyone`, no `BUILTIN\Users`, no `Authenticated Users`; owner `BUILTIN\Administrators`. Host GitHub `windows-latest`, `.github/workflows/ci-gateway-platform.yml`, run 34823022229, job 103908680316, PASS 4m45s. Denial from second user, not owner — files owned by `BUILTIN\Administrators`, so owner-principal read would SUCCEED. Earlier `infeasible` verdict was HARNESS bug, not runner limit: probe wrote verdict into session owner `%TEMP%` with second user granted only `(RX)`, standard user cannot traverse another user's profile; fixed by moving probe dir to `C:\ProgramData\qa-acl-<pid>` granted `(M)` to second user, removed in `Cleanup`. Arm has NO pass-without-verdict path — missing read verdict = hard FAIL, worded evidence failure, never leak. `qa/` VM matrix (`make test-windows`) NOT used, NOT required.
|
|
3268
|
+
|
|
2044
3269
|
#### CORS default
|
|
2045
3270
|
|
|
2046
3271
|
`https://pi-dashboard.dev` built-in allowed origin, beside `*.share.zrok.io`. CORS (origin-keyed) distinct from auth (bearer). Config `cors.allowedOrigins` extends.
|
|
@@ -2051,9 +3276,9 @@ Payload plus handshake carry `v`. Server keeps backward-compatible pairing route
|
|
|
2051
3276
|
|
|
2052
3277
|
#### Operator pairing view — client
|
|
2053
3278
|
|
|
2054
|
-
Operator-side pairing view = `packages/client/src/components/
|
|
3279
|
+
Operator-side pairing view = `packages/client/src/components/Gateway/GatewayPairQR.tsx`. Gateway settings page + toolbar Gateway dialog. ONE surface; Settings → Security renders a link (`security-pair-link` testid → `/settings/gateway`, scrolls `#connect-a-device`). `PairingView.tsx` deleted (duplicate; drifted non-compliant). `QrCodeDialog.tsx` deleted (orphan; no importer). `noSecureRoad` flag keys the no-secure-road block on the `no_reachable_endpoint` response; endpoint-count empty rendering remains separate. No server route changed. `/api/pair/payload` + `/api/pair/approve` already shipped by `add-server-keypair-pairing`. Change: `wire-nonzrok-pairing-view`, `collapse-pairing-into-gateway`.
|
|
2055
3280
|
|
|
2056
|
-
On open calls `GET /api/pair/payload` → `{v,id,code,urls[]}`. Renders QR (`qrcode` dep, `QRCode.toCanvas` idiom) plus
|
|
3281
|
+
On open calls `GET /api/pair/payload` → `{v,id,code,urls[]}`. Renders QR (`qrcode` dep, `QRCode.toCanvas` idiom) plus copy box holding the SAME deep link as the QR (`qrText`) — remote browser opens it directly; Electron shell `decodePayloadString` accepts the https form. Device accepts raw JSON or base64url via `decodePayloadString`. Shows fingerprint `id`, one-time code TTL countdown (~300s; server `CODE_TTL_MS`, client mirror `PAIRING_CODE_TTL_MS` in `GatewayPairQR.tsx`), advertised `urls[]`.
|
|
2057
3282
|
|
|
2058
3283
|
Approval: operator types numeric confirm code shown on device → `POST /api/pair/approve` (D12 typed compare-and-match). Client lib `packages/client/src/lib/pairing-api.ts` `approvePairing(code, confirmCode, label?)`. Success → device joins paired list.
|
|
2059
3284
|
|
|
@@ -2582,19 +3807,44 @@ The per-message ⤘ Fork button needs each chat bubble to carry the entry id of
|
|
|
2582
3807
|
|
|
2583
3808
|
`queueMicrotask` was used previously but no longer works: on pi 0.69+ the microtask resolves *inside* the awaited `_emitExtensionEvent`, before persistence. See change `fix-per-message-fork`.
|
|
2584
3809
|
|
|
3810
|
+
### Session Archiving (change: archive-sessions-lazy-load)
|
|
3811
|
+
|
|
3812
|
+
Archive evicts an ended session from the live set. Replaces manual hide. `hidden` stays — separate axis, auto-hide worker visibility only.
|
|
3813
|
+
|
|
3814
|
+
- Sidecar flags `archived`, `archivedAt`, `restoredAt` in `.meta.json`. Optional. Absent reads not-archived.
|
|
3815
|
+
- Boot scan (`session-scanner.ts`) builds in-memory archive index `Map<groupKey, ArchivedSessionSummary[]>`. `groupKey = pathKey(resolveSessionGroupPath(row, pinned, platform))` — same normalised key client folders use. Migrates: legacy hidden-ended sidecar → archived; age past `sessionList.archiveAfterDays` (default 30, min 0 = disabled) → archived. Logs `archive: N indexed, M migrated, K aged-out (ms)`.
|
|
3816
|
+
- `session-archive.ts` owns archive/unarchive/delete/list. Archive: flush pending sidecar write → merge `{archived:true, archivedAt}` → `remove()` from manager → index insert → broadcast `session_archived { sessionId, cwd: groupKey, count }`. Restore is mirror: `archived:false, restoredAt:now, hidden:false` → `restore()` → `session_added` + `archived_count_updated`.
|
|
3817
|
+
- `archive-sweeper.ts` ticks every `sessionList.archiveSweepIntervalMinutes` (default 60, min 1). Predicate: ended + `live !== true` + not viewed + `max(endedAt, restoredAt)` past threshold. Cap 200 oldest per tick. Re-arms on config change. `archiveAfterDays: 0` no-op.
|
|
3818
|
+
- WS verbs `archive_session`/`unarchive_session` replace `hide_session`/`unhide_session`. Idle-alive archive ends the pi process first, then archives on the `ended` transition (one-shot intent registry, 60 s expiry). Frames `session_archived`, `archived_count_updated`. Snapshot carries `archivedCountByCwd`.
|
|
3819
|
+
- REST: `GET /api/sessions/archived` (`cwd` absolute-only, `limit` 1–200 default 50, opaque base64 `cursor`, `q` ≥ 3 chars), `GET /api/sessions/archived/:id`, `DELETE /api/sessions/archived/:id`. `GET /api/sessions` excludes archived.
|
|
3820
|
+
- Client: per-folder `Archive (N)` fold below the ended fold. First expand issues exactly one lazy `GET`. Rows via `ArchivedSessionRow.tsx`. Click → read-only open `/session/<id>?archived=1` — composer hidden, server resolves `sessionFile` from the index, session stays out of the live `sessions` map.
|
|
3821
|
+
|
|
3822
|
+
```mermaid
|
|
3823
|
+
flowchart LR
|
|
3824
|
+
Boot["boot scan"] -->|archived\nsidecar| Index["archive index\nMap<groupKey, rows>"]
|
|
3825
|
+
Sweeper["archive-sweeper\ntick"] --> Arch["archiveSession"]
|
|
3826
|
+
Card["card archive btn\nidle-alive: confirm"] --> WS["archive_session"] --> Arch
|
|
3827
|
+
Arch --> Sidecar[".meta.json\narchived:true"] --> Index
|
|
3828
|
+
Index --> List["GET /api/sessions/archived"]
|
|
3829
|
+
Index --> Open["read-only open\n?archived=1"]
|
|
3830
|
+
List --> Fold["Archive (N) fold"]
|
|
3831
|
+
```
|
|
3832
|
+
|
|
2585
3833
|
## Persistence
|
|
2586
3834
|
|
|
2587
3835
|
| Data | Storage | Details |
|
|
2588
3836
|
|------|---------|---------|
|
|
2589
|
-
| Events | In-memory Map | LRU eviction, max
|
|
2590
|
-
| Sessions | In-memory Map + `.meta.json` | In-memory registry. Each session's state cached in per-session `.meta.json` sidecar next to `.jsonl`. On startup, `session-scanner.ts` scans `~/.pi/agent/sessions/*/` to restore all sessions from cached meta. |
|
|
2591
|
-
| Session meta | `~/.pi/agent/sessions/…/<id>.meta.json` | Per-session sidecar: dashboard-owned state (name, attachedProposal, hidden, source) + cached stats (tokens, cost, model, status). Debounced per-session writes (max 1/sec). Stale cache detected via `cachedAt` vs `.jsonl` mtime. |
|
|
3837
|
+
| Events | In-memory Map | LRU eviction, max resident sessions (`memoryLimits.maxCachedSessions`, default 32). Pinned if active bridge or browser subscribers. Bounded by count and byte budgets. |
|
|
3838
|
+
| Sessions | In-memory Map + `.meta.json` | In-memory registry. Each session's state cached in per-session `.meta.json` sidecar next to `.jsonl`. On startup, `session-scanner.ts` scans `~/.pi/agent/sessions/*/` to restore all sessions from cached meta. Archived sessions evicted to the in-memory archive index (`session-archive.ts`). See Session Archiving. |
|
|
3839
|
+
| Session meta | `~/.pi/agent/sessions/…/<id>.meta.json` | Per-session sidecar: dashboard-owned state (name, attachedProposal, hidden, source) + cached stats (tokens, cost, model, status) + archive flags (`archived`, `archivedAt`, `restoredAt`). Debounced per-session writes (max 1/sec). Stale cache detected via `cachedAt` vs `.jsonl` mtime. |
|
|
2592
3840
|
| Namer stop state | `~/.pi/agent/sessions/…/<id>.meta.json` (`autoNamerState`) | Auto-naming permanent stop + counters (attemptsUsed, starvedCount, waitingCount, stoppedModelRef, stopCause). Survives process restart; restored via `auto_name_state_restore` at register. Cleared on naming re-resolution or blocking-cause resolution. See change: fix-auto-naming-reasoning-model. |
|
|
2593
3841
|
| Notify log | `~/.pi/agent/sessions/…/<id>.meta.json` (`SessionMeta.notifyLog`) | Bounded per-session notify history (cap 50, oldest-first). Not a `DashboardEvent` — `event_replay` cannot restore. Mirrored by `sessionToMeta` (full-overwrite save), restored by `sessionFromMeta` cold start, carried across bridge reattach by `memory-session-manager.register()`. See Notify Flow. |
|
|
2594
3842
|
| Pinned directories | `~/.pi/dashboard/preferences.json` | Ordered array of cwd paths. Pinned dirs always visible in sidebar. |
|
|
2595
3843
|
| Session order | `~/.pi/dashboard/preferences.json` | Per-cwd ordering managed by `session-order-manager.ts`. |
|
|
3844
|
+
| Session-card sections | `~/.pi/dashboard/preferences.json` (`cardSections`) | Sparse `{global?, folders?}` section id → boolean. Resolution: folder override → global → visible. Folder key `cardSectionFolderKey` (`pathKey` fold, never realpath). Worktree sessions key on `gitWorktree.mainPath`. Ids `/^[a-z0-9-]{1,64}$/`. Absolute paths only. Caps 1000 folders / 64 keys per map. Over-cap write rejected. WS `set_card_section_visibility {path?, section, visible: boolean\|null}` (path absent = global, null = inherit) + `reset_folder_card_sections {path}` → `card_sections_updated` full snapshot. Broadcast only on mutation. Sent on connect before `sessions_snapshot` always (incl. `{}`; reconnect drops stale client state). Resolver `packages/shared/src/card-sections.ts`. See change: configurable-session-card-sections. |
|
|
2596
3845
|
| Server PID | `~/.pi/dashboard/server.pid` | Tracks running server process for daemon management. |
|
|
2597
3846
|
| Headless PIDs | `~/.pi/dashboard/headless-pids.json` | Maps spawned headless processes to sessions. Unix: `tail -f /dev/null \| pi --mode rpc` (uses tail instead of sleep to avoid stdin pipeline bug). Windows: `pi.cmd --mode rpc` with `shell: true` and quoted paths for spaces in usernames. |
|
|
3847
|
+
| Custom event groups | `~/.pi/dashboard/custom-event-groups.json` | Group definitions: `customType` regex → named toggleable chat groups. Shipped defaults written on first boot. User-editable; restart-to-apply. See change: add-custom-event-group-filters. |
|
|
2598
3848
|
| Bridge extension | `~/.pi/agent/settings.json` | On bundled installs (Electron DEB/DMG), the server auto-registers the bridge extension path in pi's global settings so all spawned pi sessions discover and load it. No-op in dev mode. |
|
|
2599
3849
|
| Session files | `~/.pi/agent/sessions/` (pi's own) | Source of truth. Bridge loads on demand. |
|
|
2600
3850
|
|
|
@@ -2609,6 +3859,7 @@ Precedence: CLI flags → environment variables → config file (`~/.pi/dashboar
|
|
|
2609
3859
|
| `autoStart` | true | Bridge extension auto-starts server if not running |
|
|
2610
3860
|
| `autoShutdown` | false | Server shuts down after idle period (disabled by default; enable for TUI auto-start scenarios) |
|
|
2611
3861
|
| `shutdownIdleSeconds` | 300 | Idle timeout before auto-shutdown |
|
|
3862
|
+
| `readinessTimeoutMs` | 10000 | Bridge auto-spawn cold-start readiness budget (ms). Expiry surfaces "readiness timeout" warning only; spawned server keeps booting. Raise on slow hosts (large session scan). Positive number clamped to [1000, 600000]; anything else falls back to default. Auto-start lock staleness bound derived from it: `spawnReadinessBudgetMs` = max(3x value, 30000); raising it cannot break the single-flight lock |
|
|
2612
3863
|
| `spawnStrategy` | `"headless"` | How to spawn new sessions: `"headless"` or `"tmux"` |
|
|
2613
3864
|
| `tunnel.enabled` | true | Enable Gateway (internal id `tunnel`) for remote access |
|
|
2614
3865
|
| `tunnel.provider` | — | `"zrok"`\|`"ngrok"`\|`"tailscale"`\|`"zerotier"`. Required when enabled |
|
|
@@ -2622,6 +3873,9 @@ Precedence: CLI flags → environment variables → config file (`~/.pi/dashboar
|
|
|
2622
3873
|
| `publicBaseUrls` | — | Top-level reachable base URLs. Pairing QR + `GET /api/tunnel/endpoints` surfaces. `resolvePublicBaseUrls` reads top-level first, legacy `pairing.publicBaseUrls` fallback, else `[]`. No default; absent = legacy. Not an OAuth tier (D7) |
|
|
2623
3874
|
| `memoryLimits.maxReplayEvents` | 2000 | Max events in full-stream replay window. Default `2000`; explicit `0` = unlimited (rollback lever). Absent/negative/non-numeric → `2000`; explicit `0` → `0`. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
2624
3875
|
| `memoryLimits.replayWindowMode` | `head-tail` | Replay window shape: `"head-tail"` default or `"tail-only"`. Unknown value coerced to default, never throws. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
3876
|
+
| `memoryLimits.maxBytesPerSession` | 33554432 (32 MiB) | Max serialized `data` bytes per session (`0` = unlimited). Drops oldest non-essential first. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
3877
|
+
| `memoryLimits.maxTotalEventBytes` | 805306368 (768 MiB) | Global aggregate across all resident sessions (`0` = unlimited). Binding constraint. LRU buffer eviction. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
3878
|
+
| `memoryLimits.maxCachedSessions` | 32 | Max resident session buffers (was hardcoded 100). LRU eviction of unpinned buffers. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
2625
3879
|
|
|
2626
3880
|
### Memory Limits
|
|
2627
3881
|
|
|
@@ -2651,6 +3905,34 @@ Threading:
|
|
|
2651
3905
|
|
|
2652
3906
|
See change: `lazy-load-session-history`, `fix-lazy-history-backfill-ux`, `add-tail-only-replay-window`.
|
|
2653
3907
|
|
|
3908
|
+
#### Event store byte budgets (`bound-event-store-by-bytes`)
|
|
3909
|
+
|
|
3910
|
+
Resident envelope is product of per-session budget and resident count (`maxBytesPerSession × maxCachedSessions`); global `maxTotalEventBytes` bounds envelope.
|
|
3911
|
+
Budget counts SERIALIZED `data` bytes, NOT RSS/heap bytes; `rss` ran ~1867 MB against `heapUsed` ~818 MB, so 768 MiB budget is roughly 1 GiB heap / ~2 GiB RSS.
|
|
3912
|
+
|
|
3913
|
+
**Keys and defaults:**
|
|
3914
|
+
- `memoryLimits.maxBytesPerSession`: default `33554432` (32 MiB). Bounds per-session aggregate serialized `data` bytes. `0` = unlimited.
|
|
3915
|
+
- `memoryLimits.maxTotalEventBytes`: default `805306368` (768 MiB). Bounds global aggregate across all resident sessions. `0` = unlimited. Binding constraint.
|
|
3916
|
+
- `memoryLimits.maxCachedSessions`: default `32` (was hardcoded 100 in `server.ts`). Bounds resident session-buffer count.
|
|
3917
|
+
|
|
3918
|
+
**`0` semantics:**
|
|
3919
|
+
- `0` means unlimited for both byte budgets (`maxBytesPerSession`, `maxTotalEventBytes`).
|
|
3920
|
+
- `0` never clamped up by floor clamp.
|
|
3921
|
+
|
|
3922
|
+
**In-store floor clamp:**
|
|
3923
|
+
- Store clamps positive `maxBytesPerSession` up to `4 × effective per-event ceiling`.
|
|
3924
|
+
- Effective ceiling = `maxEventDataSize`, or finite 16 MiB `MEASURE_CEILING_FALLBACK` when `maxEventDataSize` is `0`.
|
|
3925
|
+
- Clamp lives in `createMemoryEventStore`, NOT shared loader; `maxEventDataSize` is top-level `DashboardConfig` field invisible to browser-safe `memory-limits.ts`.
|
|
3926
|
+
- Effective budgets published on `/api/health` `storeRetention.effective.*`.
|
|
3927
|
+
|
|
3928
|
+
**Shed order and reclaim policy:**
|
|
3929
|
+
- Per-session byte trim drops oldest non-essential events first (tool/subagent/flow/reasoning/stats/streaming noise).
|
|
3930
|
+
- Drops oldest essential chat events (`message_start`/`message_end`/inline-terminal open/close) ONLY when essentials alone exceed budget. Matches count trim policy.
|
|
3931
|
+
- Per-session reclaim hysteretic: fires above `budget + byteTrimSlack` (5% of budget, max 4 MiB); reclaims down to budget.
|
|
3932
|
+
- Global reclaim evicts whole UNPINNED session buffers LRU-first.
|
|
3933
|
+
- All-pinned fallback: when every resident session pinned, reclaims non-essential events only from LRU pinned buffers.
|
|
3934
|
+
- Latches `globalBudgetExceeded` true when fallback cannot reach budget; clears on buffer removal/unpin/drop below budget.
|
|
3935
|
+
|
|
2654
3936
|
### Tunnel Lifecycle
|
|
2655
3937
|
|
|
2656
3938
|
**Gateway** = user-facing label. Internal identifiers stay `tunnel`: `config.tunnel`, `/api/tunnel-status`, `tunnel.ts`, `createTunnel()`, `TunnelStatus`. UI-only relabel. No config migration, no API alias.
|
|
@@ -2756,7 +4038,66 @@ The Fastify CORS callback in `server.ts` allows:
|
|
|
2756
4038
|
- Any `*.share.zrok.io` host (covers stale tabs, new reservations, and the brief window before `activeTunnelUrl` is populated on startup).
|
|
2757
4039
|
- Explicitly-configured `corsAllowedOrigins` from config.
|
|
2758
4040
|
|
|
2759
|
-
On a mismatch the callback returns `cb(null, false)` — **not** `cb(new Error(…), false)`. The `Error` form causes `@fastify/cors` to surface the error as HTTP 500 on every asset response, which is exactly what caused the long-running “zrok returns 500 on assets” debugging saga: Vite emits `<script type="module" crossorigin>` entry tags, which per HTML spec browsers always fetch in CORS mode (even same-origin), so the tunnel URL appearing in `Origin` is unavoidable. Returning `cb(null, false)` simply omits CORS headers; the browser enforces same-origin policy on its own.
|
|
4041
|
+
On a mismatch the callback returns `cb(null, false)` — **not** `cb(new Error(…), false)`. The `Error` form causes `@fastify/cors` to surface the error as HTTP 500 on every asset response, which is exactly what caused the long-running “zrok returns 500 on assets” debugging saga: Vite emits `<script type="module" crossorigin>` entry tags, which per HTML spec browsers always fetch in CORS mode (even same-origin), so the tunnel URL appearing in `Origin` is unavoidable. Returning `cb(null, false)` simply omits CORS headers; the browser enforces same-origin policy on its own. CORS answers READ-authority only (may this origin see the response); ADMISSION — may this origin open a socket or mutate state — is decided by the next subsection.
|
|
4042
|
+
|
|
4043
|
+
### Cross-Site Request Gate
|
|
4044
|
+
|
|
4045
|
+
Issue #625. CORS hides a response, never blocks the request. Gate blocks the act, not the read.
|
|
4046
|
+
|
|
4047
|
+
**Shared decision** — `packages/server/src/auth/cors-origin.ts`, `isOriginAdmitted(origin, hostHeader, opts)` = `isCorsOriginAllowed` plus 2 deltas.
|
|
4048
|
+
|
|
4049
|
+
- Delta 1, Host match: Origin `host[:port]` equals request `Host` → admit. Both normalized with `new URL()`; origin scheme applied to Host so default ports elide. Covers mDNS `http://mac.local:8000` + plain-LAN pages. `isBypassedHost` matches IP literals only; without this rule hostname-addressed clients 403.
|
|
4050
|
+
- Delta 2, no zrok wildcard: `isCorsOriginAllowed` gains `allowZrokWildcard` — default `true` for CORS, `false` for admission. `*.share.zrok.io` / `*.shares.zrok.io` skipped for admission. Zrok shares are free + self-service, so a stranger share is likely same-site to the victim tunnel. Dashboard-run tunnels are live tunnel origins, still admitted.
|
|
4051
|
+
- Absent `Origin` → admit. Bridge, `pi-dashboard` CLI, `curl`, skill send none. Browsers cannot omit it. Empty `""`, whitespace-padded, malformed → deny.
|
|
4052
|
+
|
|
4053
|
+
**WebSocket gate** — `server.ts`, `fastify.server.on("upgrade")`, `isWsOriginTrusted(origin, host, scope, corsOpts())`.
|
|
4054
|
+
|
|
4055
|
+
- FIRST statement after `scope`, ahead of the `bridge` 400 early-return and the `authConfig.secret` branch.
|
|
4056
|
+
- Untrusted → `HTTP/1.1 403 Forbidden` + `socket.destroy()`. Refused dial never consumes a ws-ticket.
|
|
4057
|
+
- Cannot distinguish routed from unrouted path.
|
|
4058
|
+
- `live` scope admits `Origin: null` — sandboxed live-preview iframe is the only intended client; refusal breaks HMR. `browser`, `terminal`, `bridge`, unrouted scopes stay strict.
|
|
4059
|
+
|
|
4060
|
+
**REST gate** — `packages/server/src/auth/mutation-origin-gate.ts`, `createMutationOriginGate(getOpts)` returns a Fastify `onRequest` hook, registered in `server.ts` after the CORS plugin.
|
|
4061
|
+
|
|
4062
|
+
- Gates `req.routeOptions.url` starting `/api/` or equal `/auth/logout`.
|
|
4063
|
+
- Skips GET/HEAD/OPTIONS; OPTIONS is safe, so preflights still get CORS headers.
|
|
4064
|
+
- Refuses `403 {"error":"untrusted origin"}`.
|
|
4065
|
+
- Matches the post-routing route PATTERN, never raw `req.url`; `//api/x` either fails to route or resolves to the gated pattern.
|
|
4066
|
+
|
|
4067
|
+
**pi-gateway** — `packages/server/src/pi/bridge-upgrade-auth.ts`. TCP upgrade carrying any `headers.origin` refused, cause `browser-origin`. Sits after the `transport === "unix"` allow, before local-token / ticket / grace. No allow-list; bridges never send Origin.
|
|
4068
|
+
|
|
4069
|
+
**One config source** — a single `corsOpts()` closure in `server.ts` feeds the CORS plugin + WS gate + REST gate. Live thunks, built per decision. Tunnel rotation + runtime `cors.allowedOrigins` edits are seen by all three, no restart.
|
|
4070
|
+
|
|
4071
|
+
**Logs** — `[ws-gate] rejected upgrade origin=… scope=… peer=…`; `[csrf-gate] rejected <method> <path> origin=…`; `[pi-gateway] … browser-origin`. Fields are attacker-controlled; `sanitizeHeaderForLog` strips control chars, caps 256.
|
|
4072
|
+
|
|
4073
|
+
**Escape hatch** — a hand-run `zrok share public` (not the dashboard tunnel feature) needs its origin in `cors.allowedOrigins` (`~/.pi/dashboard/config.json`).
|
|
4074
|
+
|
|
4075
|
+
### Host Admission Gate
|
|
4076
|
+
|
|
4077
|
+
Issue #637. Origin gates cannot see a rebinding page. It is same-origin with the dashboard: plain GETs carry no `Origin`, peer is loopback. `Host` is the only signal left.
|
|
4078
|
+
|
|
4079
|
+
**Hook** — `packages/server/src/auth/host-gate.ts` + `host-admission.ts`. `onRequest` hook on the dashboard listener, registered BEFORE `@fastify/cors`; same check first in the `upgrade` handler. Runs on every path, Origin or none.
|
|
4080
|
+
|
|
4081
|
+
**Admissible hostname** (first match wins, all read live):
|
|
4082
|
+
|
|
4083
|
+
- loopback literal — `localhost`, `127.0.0.1`, `::1`.
|
|
4084
|
+
- any IPv4/IPv6 literal (`net.isIP`). Rebinding needs a NAME; `127.1` / `2130706433` fail closed.
|
|
4085
|
+
- the bind address (a name; an IP bind is covered above).
|
|
4086
|
+
- `<label>.local`, label non-empty. Bare `.local` refused. mDNS not public DNS — not rebindable remotely.
|
|
4087
|
+
- `publicBaseUrls` hosts, `cors.allowedOrigins` hosts, live tunnel hosts — derived at read time, never copied into `allowedHosts`.
|
|
4088
|
+
- top-level `allowedHosts` (new, bare hostnames).
|
|
4089
|
+
|
|
4090
|
+
Match hostname only: port stripped, IPv6 brackets stripped, trailing dot stripped, case-folded. Missing/malformed `Host` fails closed.
|
|
4091
|
+
|
|
4092
|
+
**Mode** — `hostGate.mode` (default `enforce`) or `PI_DASHBOARD_HOST_GATE` (env wins when recognised; unrecognised ignored + logged once at boot). Absent config → `enforce`; unrecognised config value → `report` (a typo cannot lock out). `enforce` refuses unlisted hosts; `report` logs `[host-gate] would-refuse` and proceeds. Boot line `[host-gate] mode=<m> source=env|config|default` names resolved mode.
|
|
4093
|
+
|
|
4094
|
+
**Refusal** — `403 {error:"host_not_allowed", reason, hint}`, no CORS headers. `Accept` first media type `text/html` → static HTML page (escaped Host, `localhost:<port>`, the two config keys; no JS, no assets, no admitted-host enumeration). WS upgrade → `HTTP/1.1 403` + destroy, ticket unconsumed.
|
|
4095
|
+
|
|
4096
|
+
**Operator UI** — `GET /api/host-gate` (`mode`, `envOverridden`, derived `admitted`, `recent` ring). Settings ▸ Security ▸ Allowed hostnames: mode control, read-only admitted list (source pills), `allowedHosts` editor, recent refusals + Allow. Auth same as `GET /api/config`.
|
|
4097
|
+
|
|
4098
|
+
**Logs** — `[host-gate] <refused|would-refuse> host=… origin=… <method> <url>` (REST) / `scope=…` (WS). Values via `sanitizeHeaderForLog`. Rate-limited: 1/host/min, 60/min global, one `suppressed <n>` summary; 256-host map.
|
|
4099
|
+
|
|
4100
|
+
See change: add-host-allowlist-admission.
|
|
2760
4101
|
|
|
2761
4102
|
### HTTP Compression
|
|
2762
4103
|
|
|
@@ -2808,6 +4149,34 @@ See change: `harden-external-link-handling`.
|
|
|
2808
4149
|
|
|
2809
4150
|
| `devBuildOnReload` | false | Rebuild Vite client + restart server on `/reload` |
|
|
2810
4151
|
|
|
4152
|
+
### Custom Event Groups
|
|
4153
|
+
|
|
4154
|
+
Custom (non-pi) extension chat rows grouped by `customType`. Definitions live in `~/.pi/dashboard/custom-event-groups.json` — maps `customType` regex patterns to named, toggleable chat groups. Created with shipped defaults on first boot. User-editable. Restart-to-apply like `config.json`; no file watcher, edits ignored until next server start.
|
|
4155
|
+
|
|
4156
|
+
```json
|
|
4157
|
+
{
|
|
4158
|
+
"version": 1,
|
|
4159
|
+
"groups": [
|
|
4160
|
+
{ "id": "memory", "label": "Memory telemetry", "pattern": "^om\\.", "default": false },
|
|
4161
|
+
{ "id": "search", "label": "Web search results", "pattern": "^web-search-results$", "default": true },
|
|
4162
|
+
{ "id": "subagents", "label": "Subagents", "pattern": "^subagents:|^subagent-notification$", "default": true },
|
|
4163
|
+
{ "id": "flows", "label": "Flows help", "pattern": "^pi-flows-help$", "default": true },
|
|
4164
|
+
{ "id": "goals", "label": "Goals", "pattern": "^pi-goal-hermes:", "default": true }
|
|
4165
|
+
],
|
|
4166
|
+
"seenShippedIds": ["memory", "search", "subagents", "flows", "goals"]
|
|
4167
|
+
}
|
|
4168
|
+
```
|
|
4169
|
+
|
|
4170
|
+
- Shipped groups default visible except `memory` (`^om\.`, default hidden).
|
|
4171
|
+
- Reserved catch-all group `other` always exists — label "Other extension entries". Unmatched `customType` lands there. Not removable via file.
|
|
4172
|
+
- `id` = identity, pref key, merge key. `pattern` + `label` freely editable; `id` not.
|
|
4173
|
+
- `seenShippedIds` gates upgrade-merge. Deleted shipped group never resurrected by later default-group upgrades.
|
|
4174
|
+
- Malformed file → shipped defaults used; file left untouched; failure logged. Invalid individual entry (missing `id`, duplicate `id`, uncompilable pattern) → that entry skipped, others retained.
|
|
4175
|
+
- Matching runs server-side in a long-lived `worker_threads` worker, one pattern per message, per-match timeout. Pathological pattern → group quarantined for process lifetime; logged.
|
|
4176
|
+
- Read-only `GET /api/custom-event-groups` → `{ groups: [{ id, label, default }] }`. Patterns never transmitted — server-side concern.
|
|
4177
|
+
|
|
4178
|
+
See change: `add-custom-event-group-filters`.
|
|
4179
|
+
|
|
2811
4180
|
## Shared Config
|
|
2812
4181
|
|
|
2813
4182
|
Both the server CLI and bridge extension read from `~/.pi/dashboard/config.json` via a shared module (`src/shared/config.ts`). On first access, the config file is auto-created with defaults.
|
|
@@ -2828,7 +4197,7 @@ The `POST /api/restart` endpoint and `pi-dashboard restart` command perform faul
|
|
|
2828
4197
|
3. Wait for old server's port to become free (up to 10s)
|
|
2829
4198
|
4. Start new server with the same (or overridden) flags
|
|
2830
4199
|
5. Verify health via `/api/health` (up to 10s)
|
|
2831
|
-
6. `pi-dashboard stop`
|
|
4200
|
+
6. `pi-dashboard stop` sweeps the ports `start` would bind, but kills only listeners this `HOME` proves it owns (`server.lock.meta.json` pid + `httpPort` match, or `/api/health` `instanceId` + pid match); `server.pid` is not a proof. Unattributable holders are reported + left running (exit 0). `--force` kills every listener (dangerous; orphan recovery only). `restart` ignores `--force`.
|
|
2832
4201
|
|
|
2833
4202
|
The restart endpoint accepts `{ dev: boolean }` to switch between dev/production mode.
|
|
2834
4203
|
|
|
@@ -2836,14 +4205,34 @@ The restart endpoint accepts `{ dev: boolean }` to switch between dev/production
|
|
|
2836
4205
|
|
|
2837
4206
|
Dashboard server spawned via `node --import <loader> <cli.ts>` from 4 call sites (`packages/server/src/cli.ts` `cmdStart`, `packages/extension/src/server-launcher.ts` `launchServer`, `packages/electron/src/lib/server-lifecycle.ts` `launchServer`, `packages/server/src/restart-helper.ts` `buildOrchestratorScript`). On Node ≥ 20, Windows's ESM loader parses **both** `--import` loader position AND entry-script position as URLs. Raw Windows path like `B:\Dev\cli.ts` parses with scheme `b:` (not in ESM loader's `file`/`data`/`node` allowlist) + crashes with `ERR_UNSUPPORTED_ESM_URL_SCHEME`. Node has drive-letter heuristic that auto-wraps common Windows paths with `file://` before URL parse in entry-script position, but heuristic has known gaps for less-common drives (`A:`, `B:`, …), so reliance unsafe.
|
|
2838
4207
|
|
|
2839
|
-
|
|
4208
|
+
Loader position wrapped as `file://` universally; entry position wrapped per `shouldUrlWrapEntry(loader, platform)` — raw for tsx, jiti, and the native loader on every OS, `file://` only for other / unknown loaders on win32:
|
|
2840
4209
|
|
|
2841
|
-
- `packages/shared/src/platform/node-spawn.ts` — `toFileUrl(pathOrUrl)` (idempotent path → file:// URL, handles Windows drive letters on POSIX hosts) and `spawnNodeScript(opts)` (wraps
|
|
4210
|
+
- `packages/shared/src/platform/node-spawn.ts` — `toFileUrl(pathOrUrl)` (idempotent path → file:// URL, handles Windows drive letters on POSIX hosts) and `spawnNodeScript(opts)` (wraps loader; applies `shouldUrlWrapEntry` to entry before delegating to `platform/exec.ts::spawn`). Canonical chokepoint.
|
|
2842
4211
|
- `packages/shared/src/resolve-jiti.ts` — `resolveJitiImport()` and `resolveJitiFromAnchor(anchorPath)` return `pathToFileURL(registerPath).href` for the loader position.
|
|
2843
4212
|
- `packages/server/src/cli.ts` — routes through `spawnNodeScript`.
|
|
2844
|
-
- `packages/extension/src/server-launcher.ts`, `packages/electron/src/lib/server-lifecycle.ts`, `packages/server/src/restart-helper.ts` —
|
|
4213
|
+
- `packages/extension/src/server-launcher.ts`, `packages/electron/src/lib/server-lifecycle.ts`, `packages/server/src/spawn-process/restart-helper.ts` — build argv via `buildNodeImportArgvParts`, which wraps loader + applies `shouldUrlWrapEntry` to entry.
|
|
4214
|
+
|
|
4215
|
+
The URL form is cross-platform safe (Linux/macOS accept `file://` URLs identically to raw paths). Entry wrapping is platform-gated via `shouldUrlWrapEntry`. A repo-level lint test (`packages/shared/src/__tests__/no-raw-node-import.test.ts`) refuses any new call site that passes a raw identifier as argv after `--import` / `--loader`, preventing regression. Mirrors the `platform/exec.ts` + `no-direct-child-process.test.ts` pattern. See changes: `fix-windows-server-parity` (loader position), `fix-windows-entry-script-url` (entry-script position).
|
|
4216
|
+
|
|
4217
|
+
#### TypeScript loader (native default, jiti opt-in)
|
|
4218
|
+
|
|
4219
|
+
Every fresh server launch boots the Node-native TS loader by default: `@blackbelt-technology/pi-dashboard-shared/platform/native-ts-register.mjs` (+ `native-ts-hooks.mjs`). Hooks strip types via `module.stripTypeScriptTypes` in `transform` mode. No transpile cache.
|
|
4220
|
+
|
|
4221
|
+
**Why:** jiti cache dir `resources/server/node_modules/.cache/jiti` read-only on FUSE-mounted AppImage → every launch cold-transpiles → >240 s boot on Ubuntu 22.04. Native boots in 3–5 s (spike CI runs 37285545559, 37286703495). See change: `fix-appimage-cold-boot-latency`.
|
|
4222
|
+
|
|
4223
|
+
**Selection:** `selectTsLoader(env)` in `packages/shared/src/platform/ts-loader-select.mjs` (plain `.mjs`, runs pre-loader). `PI_DASHBOARD_TS_LOADER=jiti` → jiti (rollback). Unknown value → warn + native. Reads launching process env; `opts.env` overlay never selects.
|
|
4224
|
+
|
|
4225
|
+
**Launch sites:** `launchDashboardServer` (`packages/shared/src/server-launcher.ts`; log header `…, loader <url>)`), `packages/server/bin/pi-dashboard.mjs`, Electron `spawnFromSource`, bridge auto-start, `start-server.{sh,cmd,ps1}` (fixed bundle path `node_modules/@blackbelt-technology/pi-dashboard-shared/src/platform/native-ts-register.mjs`), `assert-bundled-server-plugin-load.mjs`, Electron Doctor launch test.
|
|
4226
|
+
|
|
4227
|
+
**Workers** keep inherited loader (native or jiti); `fit-worker-pool.workerExecArgv` adds selected loader when none.
|
|
4228
|
+
|
|
4229
|
+
**`/api/restart`** keeps running loader → loader switch needs fresh launch (`pi-dashboard stop && PI_DASHBOARD_TS_LOADER=jiti pi-dashboard start`, or Electron relaunch).
|
|
2845
4230
|
|
|
2846
|
-
|
|
4231
|
+
**Entry wrap:** entry raw for native AND jiti on every OS (`shouldUrlWrapEntry` false for both); loader position always `file://`. Why: under any `--import` loader Node `path.resolve()`s the main entry before building its URL → `file:///D:/…` entry becomes `D:\<cwd>\file:\D:\…` → `ERR_MODULE_NOT_FOUND` (win32 CI run 37347903583).
|
|
4232
|
+
|
|
4233
|
+
**Loader-neutral source:** server-loaded TS must not use bare `require`/`__dirname`/`__filename`/`module.exports`/`exports.` nor value-import `.tsx`; use `createRequire(import.meta.url)`. Gate: `scripts/check-loader-neutral-source.mjs` (AST, wired into `npm test`).
|
|
4234
|
+
|
|
4235
|
+
pi extensions + plugin bridges still load under pi's jiti (separate process).
|
|
2847
4236
|
|
|
2848
4237
|
#### stdout + stderr capture parity
|
|
2849
4238
|
|
|
@@ -2853,19 +4242,40 @@ Both server-launch call sites (`packages/server/src/cli.ts` and `packages/extens
|
|
|
2853
4242
|
|
|
2854
4243
|
Every server-spawn call site injects `--require <preload-fastify.cjs>` BEFORE `--import <jiti-loader>` in the child's argv, as long as the resolver `resolvePreloadFastifyPath()` in `packages/shared/src/platform/preload-fastify.ts` finds the preload file. The order matters: Node processes `--require` before `--import`, so the preload runs through Node's **legacy synchronous CJS loader** (which predates and bypasses the ESM→CJS translator). The preload synchronously `require()`s `@fastify/ajv-compiler/standalone`, `@fastify/ajv-compiler`, and `fastify` — populating `require.cache` with those modules in `kEvaluated` state.
|
|
2855
4244
|
|
|
2856
|
-
When jiti's ESM hook later resolves an `import "fastify"`, Node's translator finds the modules already cached and short-circuits — it never enters the recursive require chain that triggers the `Unexpected module status 3` assertion on Node
|
|
4245
|
+
When jiti's ESM hook later resolves an `import "fastify"`, Node's translator finds the modules already cached and short-circuits — it never enters the recursive require chain that triggers the `Unexpected module status 3` assertion on Node 22.0.0–22.18.x / 24.1.0–24.2.x.
|
|
2857
4246
|
|
|
2858
4247
|
This is a **race-independent fix**: it doesn't try to close the timing window, it removes the racy code path from the execution trace. All four spawn sites (CLI daemon, bridge auto-start, Electron, restart orchestrator) share the resolver and the same injection pattern. See change: `preload-fastify-cjs`.
|
|
2859
4248
|
|
|
2860
4249
|
#### Node-version preflight
|
|
2861
4250
|
|
|
2862
|
-
`packages/shared/src/
|
|
4251
|
+
Single source of truth: `packages/shared/src/node-version.ts`. Exports `MIN_SUPPORTED_NODE` (`"22.19.0"`), `meetsFloor(version, floor)`, `isAffectedNode(version)`, `isOutOfEnginesRange(version)`, `isUsableNodeVersion(version)`, `isAtOrAboveEnginesCap(version)`. Version predicates live solely here — single module, no platform-split checker.
|
|
4252
|
+
|
|
4253
|
+
Floor `22.19.0`. Affected ranges: `22.0.0–22.18.x` + `24.1.0–24.2.x` ([nodejs/node#58515](https://github.com/nodejs/node/issues/58515) — ESM loader assertion when Fastify's `@fastify/ajv-compiler` requires CJS modules). Engines cap `<27` bounds the dashboard's tested range; cap excess accepted, flagged.
|
|
4254
|
+
|
|
4255
|
+
Startup guard refuses bad Node: `packages/server/src/auth/node-guard.ts` `assertNodeVersionSupported()` runs pre-boot; exits(1) when `isAffectedNode` or `isOutOfEnginesRange` — server never starts (since change `bump-pi-compat-to-0-75`).
|
|
4256
|
+
|
|
4257
|
+
Consumers: startup guard; Electron `lib/dependency-detector.ts` `isUsableNodeVersion` filter on detected system Node; spawn-runtime gate `evaluateVersionGate` (pi floor + affected-range check per candidate, cap excess passes with `capExceeded`).
|
|
4258
|
+
|
|
4259
|
+
Root `package.json` declares `"engines": { "node": ">=22.19.0 <27" }`; `packages/server/package.json` `"node": ">=22.19.0"` as npm-level advisories.
|
|
4260
|
+
|
|
4261
|
+
#### Spawn runtime resolution
|
|
4262
|
+
|
|
4263
|
+
Resolves ONE pi spawn runtime — the Node binary every spawned pi session runs on. See change: `unify-pi-runtime-identity`. Ladder in `packages/shared/src/platform/spawn-runtime.ts::resolveSpawnRuntime`.
|
|
2863
4264
|
|
|
2864
|
-
|
|
2865
|
-
- **Bridge auto-start** (`server-launcher.ts`) — `buildReadyTimeoutMessage()` includes an issue-#58515 upgrade hint in the failure notification when `waitForReady` times out on an affected Node.
|
|
2866
|
-
- **Electron doctor** (`doctor.ts`) — "Node runtime compatibility" row shows `warning` with upgrade guidance.
|
|
4265
|
+
Four rungs, first hit wins:
|
|
2867
4266
|
|
|
2868
|
-
|
|
4267
|
+
1. `runtime.override` in `~/.pi/dashboard/config.json`.
|
|
4268
|
+
2. `node` entry in tool-overrides.json — shadowed by override, named skip in trail.
|
|
4269
|
+
3. User Node — login-shell first on Electron arm, PATH first on terminal arms (`npm`/`docker`); then version-manager fs probe (`~/.nvm/alias/default`), no shell.
|
|
4270
|
+
4. Managed `<managedDir>/node`; else bundled; else `process.execPath` — terminal rung, never fails.
|
|
4271
|
+
|
|
4272
|
+
Gate (`evaluateVersionGate`): pass pi engines floor + not nodejs/node#58515-affected; cap excess (`isAtOrAboveEnginesCap`, `<27`) accepted, flagged `capExceeded`. Floor read from spawned pi copy engines; fallback `MIN_SUPPORTED_NODE`.
|
|
4273
|
+
|
|
4274
|
+
Publication: `runtime.resolved` written to `~/.pi/dashboard/config.json` every server start (`packages/server/src/runtime-publication.ts::publishResolvedRuntime`). Diagnostic-only; override never written. `pi-dashboard runtime` CLI subcommand prints resolved runtime.
|
|
4275
|
+
|
|
4276
|
+
Spawn-time re-validation (`packages/server/src/runtime-resolution.ts`): boot-time resolution cached process-lifetime; re-validated per spawn — stat signature (size/mtime/realpath) + probe for shim-shaped paths.
|
|
4277
|
+
|
|
4278
|
+
Doctor rows: resolved runtime (+ rung/via), ABI mismatch, legacy `~/.pi-dashboard/` dir orphan test. Home split: `~/.pi/dashboard/` = user config + published runtime state; `~/.pi-dashboard/` = machine-managed runtime, managed node_modules, logs.
|
|
2869
4279
|
|
|
2870
4280
|
#### AppImage CLI self-recursion guard (Linux power-user mode)
|
|
2871
4281
|
|
|
@@ -2949,9 +4359,9 @@ On Windows, `spawnDetached` uses `detached: true` which (via libuv's `src/win/pr
|
|
|
2949
4359
|
|
|
2950
4360
|
### RPC keeper sidecar
|
|
2951
4361
|
|
|
2952
|
-
Introduced by change `add-rpc-stdin-dispatch-with-keeper-sidecar`. Default and only headless spawn path as of change `enable-rpc-keeper-by-default`.
|
|
4362
|
+
Introduced by change `add-rpc-stdin-dispatch-with-keeper-sidecar`. Default and only headless spawn path as of change `enable-rpc-keeper-by-default`. Durable owner of pi's stdin across dashboard restarts. Extension slash-command dispatch was retired by change `retire-slash-dispatch-via-expand-prompt-templates` — the bridge dispatches in-process now; the keeper's JSON-line forward protocol is intact.
|
|
2953
4363
|
|
|
2954
|
-
Per-session keeper process owns pi's stdin pipe.
|
|
4364
|
+
Per-session keeper process owns pi's stdin pipe. Keeper forwards verbatim to pi's stdin. Server no longer writes extension-slash RPC lines to the keeper (`keeperManager.writeRpc`, `keeperManager.writeRpcToSockPath`, `headlessPidRegistry.writeRpc` removed; `dispatch-router.ts` deleted).
|
|
2955
4365
|
|
|
2956
4366
|
Keeper outlives dashboard server restarts. Replaced Unix `tail -f /dev/null | pi` wrapper and Windows direct-stdin pipe. Uniform durability across Unix and Windows.
|
|
2957
4367
|
|
|
@@ -2964,7 +4374,7 @@ flowchart LR
|
|
|
2964
4374
|
P["pi --mode rpc"]
|
|
2965
4375
|
B["bridge.ts<br/>(loaded inside pi)"]
|
|
2966
4376
|
|
|
2967
|
-
S
|
|
4377
|
+
S -.->|"UDS /<sessionId>.rpc.sock<br/>(no writer — slash dispatch retired)"| K
|
|
2968
4378
|
K -->|"pi.stdin pipe<br/>(forward JSON lines)"| P
|
|
2969
4379
|
P --- B
|
|
2970
4380
|
B -->|"bridge WS<br/>(events, send_prompt non-slash, abort, model, etc.)"| S
|
|
@@ -2972,16 +4382,16 @@ flowchart LR
|
|
|
2972
4382
|
|
|
2973
4383
|
UDS path: `~/.pi/dashboard/sessions/<sessionId>.rpc.sock`. Windows pipe: `\\.\pipe\pi-rpc-<sessionId>`. Keeper PID sidecar: `<sockPath>.pid`. Server scans on startup for orphan-cleanup + reattach.
|
|
2974
4384
|
|
|
2975
|
-
Protocol: line-framed JSON, fire-and-forget.
|
|
4385
|
+
Protocol: line-framed JSON, fire-and-forget. Keeper forwards the raw line to pi's stdin; no parsing, no response. The server-side writer (`{"type":"prompt","message":"/cmd","id":"<requestId>"}\n` via UDS write) had no remaining caller and was removed by change `retire-slash-dispatch-via-expand-prompt-templates`.
|
|
2976
4386
|
|
|
2977
4387
|
Dual-channel boundary explicit:
|
|
2978
4388
|
- **Bridge WS** owns: send_prompt non-slash, abort, model switch, thinking-level, compaction, rename, events, flow control.
|
|
2979
|
-
- **Server → keeper UDS**
|
|
4389
|
+
- **Server → keeper UDS** owned: extension slash dispatch only — RETIRED. No writer remains; keeper still owns pi's stdin.
|
|
2980
4390
|
- **headlessPidRegistry kill** owns: kill-by-pid for shutdown / force-kill / reload. `killBySessionId` escalates pi via shared `killProcess(pid, { timeoutMs: 2000 })` ladder (SIGTERM → 2 s → SIGKILL) — uniform with `handleForceKill`. See change: `fix-keeper-kill-escalation`.
|
|
2981
4391
|
|
|
2982
|
-
|
|
4392
|
+
Former constraint: bridge cannot reach `session.prompt` from inside pi. Pi >= 0.84.2 exposes the dispatch through `sendUserMessage({expandPromptTemplates: true})`; the handler runs inside pi, so the RPC route is no longer needed.
|
|
2983
4393
|
|
|
2984
|
-
Lifecycle: pi exits → keeper exits 0, unlinks socket + pid sidecar. Keeper crashes → pi reads EOF on stdin → exits. Force-kill → server kills pi PID first, schedules 200 ms keeper-fallback SIGTERM. Keeper `shutdown()` SIGKILLs `piChild` before `process.exit` (defence in depth) — closes orphan-pi gap when pi event loop hung (CPU loop / non-cancellable native call) and stdin EOF never observed. See change: `fix-keeper-kill-escalation`. Tmux / Windows-Terminal sessions
|
|
4394
|
+
Lifecycle: pi exits → keeper exits 0, unlinks socket + pid sidecar. Keeper crashes → pi reads EOF on stdin → exits. Force-kill → server kills pi PID first, schedules 200 ms keeper-fallback SIGTERM. Keeper `shutdown()` SIGKILLs `piChild` before `process.exit` (defence in depth) — closes orphan-pi gap when pi event loop hung (CPU loop / non-cancellable native call) and stdin EOF never observed. See change: `fix-keeper-kill-escalation`. Tmux / Windows-Terminal sessions dispatch extension slash commands in-process now (change `retire-slash-dispatch-via-expand-prompt-templates`); the old `command_feedback {error}` stopgap is gone.
|
|
2985
4395
|
|
|
2986
4396
|
### Server Log Hygiene
|
|
2987
4397
|
|
|
@@ -3012,6 +4422,14 @@ flowchart TD
|
|
|
3012
4422
|
|
|
3013
4423
|
The server is spawned detached (`child_process.spawn` with `detached: true`, stdout/stderr redirected to `~/.pi/dashboard/server.log`), so it outlives the pi session. If multiple pi sessions start simultaneously, duplicate spawn attempts fail harmlessly with EADDRINUSE. After a failed launch, the bridge re-probes the port — if another agent started the server concurrently, the warning is suppressed. The auto-start logic is extracted into `server-auto-start.ts` for testability.
|
|
3014
4424
|
|
|
4425
|
+
#### Auto-start precedence: resolved port first (change: fix-autostart-discovery-precedence)
|
|
4426
|
+
|
|
4427
|
+
`autoStartServer` (`packages/extension/src/server-auto-start.ts`) probes the resolved port BEFORE discovery, in BOTH branches (pre-launch and post-launch `spawnAndAttach`). Probe opts `RESOLVED_PORT_PROBE_OPTS`: 8000 ms timeout, 2 retries, 500 ms delay. Bootstrap-aware — retries ONLY on `AbortError` (previous instance mid-jiti-bootstrap, event loop blocked 5–15 s). `ECONNREFUSED` = definitive "nothing listens" → launch immediately, no retry delay (F7).
|
|
4428
|
+
|
|
4429
|
+
- **Pre-launch gate (D1).** Resolved port serves → return it. Discovery NOT consulted. No mismatch record, no banner (D4). Discovery runs ONLY when resolved port silent or foreign.
|
|
4430
|
+
- **Warning only on silent path (D4).** `warning` toast + durable log (both ports named) fires ONLY after: resolved port probed + found silent + verified candidate discovered. Serving resolved port emits nothing.
|
|
4431
|
+
- **Post-launch branch (D-post).** `spawnAndAttach` re-probes resolved port after `launchServer`, same bootstrap-aware opts. Serves → return it; discovery not consulted — a stray advertiser never displaces the just-launched server. Still silent → discovery resolves ONLY our server's non-localhost address; candidates on other ports never considered; adoption health-verified, shared D3 order. Never raises "resolved port silent" warning on this path.
|
|
4432
|
+
|
|
3015
4433
|
## mDNS Server Discovery
|
|
3016
4434
|
|
|
3017
4435
|
The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery:
|
|
@@ -3022,6 +4440,7 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
|
|
|
3022
4440
|
3. **Auto-start** — if no server found and `autoStart` is enabled, spawn detached server
|
|
3023
4441
|
|
|
3024
4442
|
### Server Advertisement
|
|
4443
|
+
- **Advertisement honesty** — `advertiseDashboard(port, piPort, {bindHost})` (`packages/shared/src/mdns-discovery.ts`). Gate: `shouldAdvertise(bindHost)`. Bind loopback (`127.x`/`::1`/`localhost`) → publish NOTHING. Unset/`0.0.0.0`/`::`/LAN → advertise. Server passes `{bindHost: config.host}` at advertise time (`packages/server/src/server.ts`). Reason: loopback-bound server advertising LAN hostname = unreachable poison record.
|
|
3025
4444
|
- On startup, the server publishes a `_pi-dashboard._tcp` mDNS service with TXT record: `{ version, pid, piPort }`
|
|
3026
4445
|
- On shutdown, the service is unpublished
|
|
3027
4446
|
- A continuous mDNS browser discovers peer servers and broadcasts updates to connected browsers via `servers_discovered`/`servers_updated` WebSocket messages
|
|
@@ -3030,6 +4449,11 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
|
|
|
3030
4449
|
- Bridge extensions use the mDNS discovery chain instead of bare TCP port probes
|
|
3031
4450
|
- `isDashboardRunning(port)` replaces `isPortOpen(port)` for identity-verified detection
|
|
3032
4451
|
- After auto-starting, the bridge waits up to 10s for the server's mDNS advertisement
|
|
4452
|
+
- **Resolved port outranks discovery** (change: fix-autostart-discovery-precedence) — resolved-port probe runs first, bootstrap-aware (see Auto-Start Flow above). Serves → returned, discovery not consulted. Discovery consulted only when resolved port silent or foreign.
|
|
4453
|
+
- **Candidates health-gated (D2)** — `firstVerifiedLocal` adopts a candidate only after `GET /api/health` succeeds at its ADVERTISED host + port (`isDashboardRunning(port, host)` — the `AutoStartDeps` seam widened from `(port: number)` to carry host). Rejection durably logged with endpoint + reason (`candidate rejected: <host>:<port> — not a dashboard (port conflict) | health probe did not answer`). Unverifiable candidate never suppresses launch.
|
|
4454
|
+
- **Deterministic selection (D3)** — `selectLocalCandidate`, shared by both branches: resolved-port match → lowest port → host-string tiebreak (plain codepoint compare). Total order; never advertisement arrival order. Scope: over the candidate set `discoverDashboard` returns; multicast collection window unchanged.
|
|
4455
|
+
- **`portConflict` falls through to discovery (D2b)** — foreign service on resolved port does NOT short-circuit; discovery still runs (a real dashboard may have relocated because a foreign service took the default port). "Port occupied" refusal (`notify` warning + log, no launch) applies only after discovery yields no verified candidate.
|
|
4456
|
+
- **Migration guard** (change: fix-bridge-mdns-migration-hijack) — `ConnectionManager.retargetTo(url, {trigger, verify?})` (`packages/extension/src/connection.ts`) replaces `updateUrl`. Gates, in order: cooldown (60s, `MIGRATION_COOLDOWN_MS`) → established+registered protection → candidate health probe `GET /api/health` `{ok:true}` BEFORE dropping incumbent (`verify`, wired to `probeEndpointReachability`, `packages/extension/src/instance-verification.ts`) → localhost preference (remote candidate never displaces established loopback connection; pure/lexical classification: `isLoopbackEndpoint`, `packages/extension/src/endpoint-resolution.ts`). Reversibility: 4 failed opens (`MIGRATION_MAX_FAILED_OPENS`) against migrated endpoint → return to `lastRegisteredUrl`, reset backoff, cooldown rejected endpoint. `noteRegistered()` marks last registered endpoint (bridge calls at initial `session_register` + `sendStateSync`). Every accepted/refused decision emits `onMigrationEvent` → `bridge_diagnostic` events `retarget_accepted` / `retarget_refused` (protocol `BridgeDiagnosticEvent`) — server-visible under default `keeperLog.capturePiOutput=false`.
|
|
3033
4457
|
|
|
3034
4458
|
### Known Servers
|
|
3035
4459
|
- Users can persist remote servers in `config.json` via `knownServers: KnownServer[]`
|
|
@@ -3164,7 +4588,7 @@ Order matters: register with target BEFORE closing origin. Session never orphane
|
|
|
3164
4588
|
|
|
3165
4589
|
Primitives exist, no parallel path:
|
|
3166
4590
|
- `ConnectionManager.updateUrl()` (`connection.ts:334`) — re-target
|
|
3167
|
-
- `pi.registerCommand("__dashboard_reload", …)` (`
|
|
4591
|
+
- `pi.registerCommand("__dashboard_reload", …)` — reload command handler; fresh command ctx per dispatch → `ctx.reload()` (`terminal-reload.ts`)
|
|
3168
4592
|
|
|
3169
4593
|
```mermaid
|
|
3170
4594
|
sequenceDiagram
|
|
@@ -3204,12 +4628,65 @@ The dashboard supports browser-based authentication with pi's LLM providers, ena
|
|
|
3204
4628
|
|
|
3205
4629
|
### Flow
|
|
3206
4630
|
|
|
3207
|
-
1. **Settings UI** shows
|
|
3208
|
-
2. **
|
|
3209
|
-
3. **
|
|
3210
|
-
4.
|
|
3211
|
-
5.
|
|
3212
|
-
|
|
4631
|
+
1. **Settings UI** shows every sign-in-able provider the runtime registry exposes (see the delegated subsection below) plus API key providers
|
|
4632
|
+
2. **OAuth sign-in is delegated to pi-ai**: one adapter drives each provider's own `login()`; the pane renders whichever step the flow emits — an authorization URL, a device code, or an answerable prompt — and posts the answer back. No per-provider flow code
|
|
4633
|
+
3. **API key flow**: user pastes key in Settings → saved directly
|
|
4634
|
+
4. All credentials written to `~/.pi/agent/auth.json` with lockfile + atomic write (`0600` permissions)
|
|
4635
|
+
5. Server broadcasts `credentials_updated` to all connected bridges → bridges call `reloadProviders(pi)` (to hot-register any newly-added custom providers from `~/.pi/agent/providers.json`) then `authStorage.reload()` and `modelRegistry.refresh()` so running pi sessions pick up new tokens and new providers immediately without a session restart
|
|
4636
|
+
|
|
4637
|
+
#### Provider OAuth sign-in (delegated to pi-ai)
|
|
4638
|
+
|
|
4639
|
+
The dashboard supplies an `AuthInteraction` — not a flow. pi-ai's `login()` owns PKCE, the loopback callback listener, device-code polling, and the code-for-token exchange; the dashboard persists the returned credential through its existing locked, backed-up `writeCredential()`. No per-provider flow code remains. See change: delegate-provider-oauth-to-pi-ai.
|
|
4640
|
+
|
|
4641
|
+
**Registry.** Built once, lazily, off the request path (`oauthRegistryReady()`), from the shared injected server runtime (`setOAuthRegistryRuntimeSource(getServerModelRuntime)`, wired by `server.ts`) — ONE `ModelRuntime` (D6), so a failed create degrades this listing AND the model proxy together. `mapProviders()` filters `auth?.oauth` (no id exclusion), yielding one `OAuthRegistryEntry { id, name, flowType, auth }` per sign-in-able provider. On pi-coding-agent `1.0.0` that set is the nine ids `anthropic`, `openai`, `openai-codex`, `github-copilot`, `openrouter`, `kimi-coding`, `meta`, `xai`, `radius`. Built-in `radius` — name `Radius`, `flowType` hint `auth_code`, `subscription:false` → Account badge. `getOAuthRegistry()` applies the `models.json` override on read (below). `FLOW_TYPE_HINT` (`anthropic` / `openai` / `openai-codex` / `openrouter` / `radius` → `auth_code`, else `device_code`) is a UI hint only: it picks the Add-provider dialog's opening pane. The pane follows whatever the flow emits, so a wrong hint is cosmetic — `flowType` is never a gate. Registry entries and OAuth status rows carry `subscription` from pi's `isSubscription` (absent → `false`; `openrouter` is `false`). `login()` receives `{ getDeviceId }` from pi `SettingsManager.getOrCreateDeviceId()`, pre-loaded in `beginFlow` via `loadPiDeviceId` — pi 1.0.0 Sign in with ChatGPT (`openai`) rejects without it. Environment api-key rows carry `authLabel` (pi `getProviderAuthStatus().label`) and count as authenticated only when the row has no `envVar` and is not `ambient`. See change: update-pi-core-1-0-adopt-apis.
|
|
4642
|
+
|
|
4643
|
+
**Registry override** (`packages/server/src/auth/radius-override.ts`).
|
|
4644
|
+
|
|
4645
|
+
`isRadiusOverridden()` true iff Pi-global `models.json` declares a custom-gateway `radius`. Path `join(getAgentDir(), "models.json")` — honours `PI_CODING_AGENT_DIR`. Shape required: `providers.radius` with `oauth:"radius"` and a non-default `baseUrl`. Default gateway `https://radius.pi.dev`; `/v1` suffix, trailing slash, missing scheme normalized before compare. File parsed as pi parses it — BOM + `//` comments + trailing commas stripped, NO schema validation — so a schema-invalid file carrying the override shape still hides Radius (fails toward hiding). Read error / missing file → no override. Result memoized ≤1 s → an edit applies without restart.
|
|
4646
|
+
|
|
4647
|
+
`getOAuthRegistry()` wraps the snapshot in `applyRadiusOverride()`: overridden → drop entry `radius`, leaving eight ids. One reader feeds `/providers`, `/handlers`, `/start`, and `/status`. Out of scope: other custom `oauth:"radius"` ids (registry builds `modelsPath:null`); an extension-registered `radius` id is not detected. See change: add-radius-provider-login (D2).
|
|
4648
|
+
|
|
4649
|
+
**Radius sign-in.** Built-in Radius has no bespoke flow — renders the generic select pane (browser | device-code), same as Codex. Browser method listens on server `127.0.0.1:1456`; remote browser cannot reach that loopback → use device code. `PI_RADIUS_GATEWAY` does not affect login.
|
|
4650
|
+
|
|
4651
|
+
**Radius MCP follow-up.** Logic `packages/server/src/auth/radius-mcp.ts`; routes `packages/server/src/routes/provider-auth-routes.ts`; tier `operate`.
|
|
4652
|
+
|
|
4653
|
+
- `GET /api/provider-auth/radius/mcp` → `{ configured, name, path }`.
|
|
4654
|
+
- `POST /api/provider-auth/radius/mcp` — refusals first, then no-op, then write. Order: runtime unavailable → `503`; no stored `radius` OAuth credential → `409`; `models.json` override → `409`; global `mcp.json` unparseable → `409`; already configured → no-op `200 { configured:true, written:false, name }`; else write.
|
|
4655
|
+
- Codes: `provider_auth.radius_mcp_runtime_unavailable`, `provider_auth.radius_mcp_no_credential`, `provider_auth.radius_mcp_overridden`, `provider_auth.radius_mcp_write_refused`. `_write_refused` carries `vars.reason` = writer refusal code.
|
|
4656
|
+
- Write = ONE global entry via mcp-client-plugin `./core` `saveServer` — server imports plugin core here first. Entry `{ url: "https://radius.pi.dev/mcp", auth: { provider: "radius" } }`; any `oauth` key dropped. Name = URL-matched entry, else `radius`, else `radius-mcp` on collision.
|
|
4657
|
+
- After write: `/reload` fans out via `dispatchReload` over `reloadFanOutTargets()` (reload trigger source 7). Response `{ configured, written, name, reloaded }` — `reloaded` counts only `respawn` | `forwarded` outcomes.
|
|
4658
|
+
|
|
4659
|
+
See change: add-radius-provider-login (D5, D6).
|
|
4660
|
+
|
|
4661
|
+
**Client.** After a completed `radius` flow, `ProviderAuthSection` shows inline `RadiusMcpOffer` (`packages/client/src/components/settings/RadiusMcpOffer.tsx`). Accept → one `POST`; decline → none. See change: add-radius-provider-login (D5).
|
|
4662
|
+
|
|
4663
|
+
**API-key twin.** `RADIUS_API_KEY` environment row pairs with the OAuth row; on collision the api-key row becomes `radius-api` ("Radius (API Key)"), OAuth row keeps `radius` (`provider-auth-storage.ts` `${entry.id}-api`).
|
|
4664
|
+
|
|
4665
|
+
**Non-goal.** Model proxy has no Radius OAuth refresh loader.
|
|
4666
|
+
|
|
4667
|
+
**Dependency pin.** The server imports only `@earendil-works/pi-coding-agent` (`await import(...)`, public index `ModelRuntime`), never `@earendil-works/pi-ai` and never either package's `dist/` (both unreachable — export maps / hoisted `1.0.0`). Binding to the pi-ai copy pi-coding-agent was built against gives version parity by construction. Six governed pins move together: `packages/server/package.json` dep `^1.0.0`, `piCompatibility.minimum`, `piCompatibility.recommended`, the `pnpm-workspace.yaml` override, `docker/Dockerfile`, and `scripts/verify-release-deps.mjs` `minVersion` (`checkPiPinCoherence`). Every `@earendil-works` peer is `>=1.0.0` (optional, no upper bound); every `@earendil-works` devDependency is `^1.0.0`; `pnpm-workspace.yaml` overrides pin `pi-coding-agent`, `pi-ai`, `pi-tui`. See change: update-pi-core-1-0-adopt-apis.
|
|
4668
|
+
|
|
4669
|
+
**Routes** (`packages/server/src/routes/provider-auth-routes.ts`):
|
|
4670
|
+
|
|
4671
|
+
| Route | Behaviour |
|
|
4672
|
+
|---|---|
|
|
4673
|
+
| `POST /api/provider-auth/start { provider, enterpriseDomain? }` | Supersedes any pending flow for the same provider (fixed callback port), starts `login()`, answers 200 `OAuthFlowStatus` on the first user-facing step; 400 unknown provider; 500 on a pre-event rejection; 504 `Provider did not respond` |
|
|
4674
|
+
| `GET /api/provider-auth/flow/:flowId` | `OAuthFlowStatus`; 404 `Invalid or expired flow` |
|
|
4675
|
+
| `POST /api/provider-auth/flow/:flowId/input { value }` | Resolves the pending prompt → 202 `{ ok: true }`; 409 `No input pending for this flow`; 404 as above |
|
|
4676
|
+
| `DELETE /api/provider-auth/flow/:flowId` | `cancelled = true; abort.abort()` → 204; 404 as above |
|
|
4677
|
+
|
|
4678
|
+
`POST /api/provider-auth/authorize`, `POST /api/provider-auth/device-code`, and `GET /api/provider-auth/device-status/:flowId` are removed.
|
|
4679
|
+
|
|
4680
|
+
**Flow record** (`packages/server/src/auth/provider-auth-adapter.ts`). Holds a STICKY `authUrl` plus a tagged `pending` union, never a single slot — an `auth_url` notify and a `manual_code` prompt arrive back-to-back, so the pane renders the link and the paste field together. `pending` kinds: `device_code` (render-only), `manual_code`, `text`, `select`; `secret` is rejected (`unsupported prompt: secret`) — no bundled provider issues it.
|
|
4681
|
+
|
|
4682
|
+
- **Abort rule.** The flow controller REJECTS the pending prompt (`Cancelled`), not merely stops waiting. pi-ai's auth-code flows `await` a `manualPromise` whose `finally` closes the callback server; rejecting settles it, so the listener closes and the port frees. Waiting on the prompt-level signal alone would deadlock and leak the port.
|
|
4683
|
+
- **`preAnswers`.** `enterpriseDomain` pre-answers the flow's FIRST free-text prompt (blank = `github.com`) so it never becomes pending; discarded after the first prompt of any kind.
|
|
4684
|
+
- **Start handshake.** `POST /start` races the first renderable step, `login()` settling, and a 15 s `FLOW_START_TIMEOUT_MS` timer. `progress` / `info` are deliberately not first steps.
|
|
4685
|
+
- **Lifetime.** 10 min default; a numeric device-code `expiresInSeconds` raises `expiresAt` to `max(expiresAt, deadline + 60 s)`. Pruned on every provider-auth request and by a 60 s timer; a pruned pending flow is cancelled first. `expired` is derived from the device-code deadline, never from pi-ai's message text.
|
|
4686
|
+
|
|
4687
|
+
**Input is a secret.** The `value` posted to `/flow/:flowId/input` may be an authorization code or a redirect URL carrying one. It is handed to the flow unchanged and never logged, persisted, or echoed. Flow ids are `crypto.randomUUID()` (UUID v4), so the capability is unguessable.
|
|
4688
|
+
|
|
4689
|
+
**Degradation.** Any registry failure (`import()` throws, empty provider list, unknown shape) absorbs into an EMPTY registry, never a dead route: `/api/provider-auth/handlers` answers `{ ids: [] }`, `/api/health` carries `providerAuth.error` naming the resolved pi-coding-agent version (a skew, not a bare symptom), every other route keeps serving, and a stored OAuth credential stays visible and removable — `oauthIdSet()` unions the registry with any id holding a stored `{ type: "oauth" }` credential.
|
|
3213
4690
|
|
|
3214
4691
|
### Model metadata enrichment for custom providers
|
|
3215
4692
|
|
|
@@ -3245,10 +4722,15 @@ The endpoint resolves `$ENV_VAR` references and the `***` REDACTED sentinel (for
|
|
|
3245
4722
|
|
|
3246
4723
|
| File | Purpose |
|
|
3247
4724
|
|------|--------|
|
|
3248
|
-
| `src/server/
|
|
3249
|
-
| `src/server/provider-auth-
|
|
3250
|
-
| `src/server/
|
|
3251
|
-
| `src/
|
|
4725
|
+
| `src/server/auth/pi-oauth-types.ts` | Local structural types for pi-ai's OAuth surface (server never imports pi-ai) |
|
|
4726
|
+
| `src/server/auth/provider-auth-registry.ts` | Builds the OAuth registry once from `ModelRuntime` providers; empty registry + health error on failure |
|
|
4727
|
+
| `src/server/auth/provider-auth-adapter.ts` | `AuthInteraction` adapter + flow store (`startFlow`, `pruneFlows`, `abortAllFlows`) |
|
|
4728
|
+
| `src/server/auth/provider-auth-storage.ts` | auth.json read/write with file locking |
|
|
4729
|
+
| `src/server/routes/provider-auth-routes.ts` | REST: start / flow status / flow input / cancel, plus API keys |
|
|
4730
|
+
| `src/server/auth/radius-override.ts` | Detects custom-gateway `radius` in Pi-global `models.json`; drops built-in `radius` from the registry |
|
|
4731
|
+
| `src/server/auth/radius-mcp.ts` | Radius MCP `GET`/`POST` logic — global `mcp.json` write + reload fan-out |
|
|
4732
|
+
| `src/client/components/settings/ProviderAuthSection.tsx` | Settings UI component |
|
|
4733
|
+
| `src/client/components/settings/RadiusMcpOffer.tsx` | Inline Radius MCP offer shown after a completed `radius` sign-in |
|
|
3252
4734
|
|
|
3253
4735
|
## Terminal Emulator
|
|
3254
4736
|
|
|
@@ -3514,7 +4996,7 @@ Guarded by the same network guard as `/api/config`.
|
|
|
3514
4996
|
|
|
3515
4997
|
### Settings UI
|
|
3516
4998
|
|
|
3517
|
-
Settings →
|
|
4999
|
+
Settings → Developer → **Tools** renders one row per registered tool: status badge, source, truncated path, expand-to-trail, override input, per-row rescan. The header has **Rescan all**, **Reset overrides**, **Export diagnostics**.
|
|
3518
5000
|
|
|
3519
5001
|
### Migration path
|
|
3520
5002
|
|
|
@@ -3522,6 +5004,99 @@ Settings → General → **Tools** renders one row per registered tool: status b
|
|
|
3522
5004
|
|
|
3523
5005
|
See change: `consolidate-tool-resolution`.
|
|
3524
5006
|
|
|
5007
|
+
### Node runtime family selection
|
|
5008
|
+
|
|
5009
|
+
`node`, `npm`, `npx` treated as ONE Node distribution — a single selected installation drives all three override keys. See change: `add-node-runtime-family-selection`.
|
|
5010
|
+
|
|
5011
|
+
#### Enumeration
|
|
5012
|
+
|
|
5013
|
+
`enumerateNodeCandidates()` in `packages/shared/src/node-installs/candidates.ts` lists every pickable installation. Roots mirror the strategy chains — bundled `<resourcesPath>/node`, managed `<managedDir>/node`, PATH — plus additive version-manager roots (nvm, fnm, volta, asdf) from `vm-roots.ts` (single root definition; consumers import-only, set cannot drift).
|
|
5014
|
+
|
|
5015
|
+
Entries are per-member FILES: `nodeEntry` / `npmEntry` / `npxEntry`. Partial families legal (distro nodejs without npm) — absent entry, never fabricated path.
|
|
5016
|
+
|
|
5017
|
+
Enumeration filesystem-only. Version from dir name (vm roots) or absent. Never spawns `node --version`.
|
|
5018
|
+
|
|
5019
|
+
#### Selection
|
|
5020
|
+
|
|
5021
|
+
`select.ts`: `planSelection` (pure) + `applySelection`. `applySelection` validates every entry (existing file inside the root), then ONE `registry.setOverrides()` write — all-or-nothing. Absent member key CLEARED unless hand-set. Hand-set member reported pre-write, preserved unless explicitly discarded.
|
|
5022
|
+
|
|
5023
|
+
#### Coherence
|
|
5024
|
+
|
|
5025
|
+
`coherence.ts` `assessFamilyCoherence` — ownership by containment. Mismatch names each deviating member + its root. Absent member alone ≠ mismatch.
|
|
5026
|
+
|
|
5027
|
+
#### REST + UI
|
|
5028
|
+
|
|
5029
|
+
`GET /api/node/installs` + `POST /api/node/installs/select` in `packages/server/src/routes/node-runtime-routes.ts`. UI: `packages/client/src/components/settings/NodeRuntimeSection.tsx` — Settings → Developer, next to the pi runtime picker.
|
|
5030
|
+
|
|
5031
|
+
#### Child PATH
|
|
5032
|
+
|
|
5033
|
+
`node-installs/child-path.ts` `prependSelectedNodeToPath` — dashboard-tooling spawns follow the selection. No selection → byte-identical legacy managed prepend. pi-session spawns governed by the spawn-runtime ladder (selection = gated step-1 candidate via `readToolOverrideNode`). Managed-tree mutations (pi-core-updater) keep managed-first.
|
|
5034
|
+
|
|
5035
|
+
#### Win32 npm anchoring
|
|
5036
|
+
|
|
5037
|
+
`npmCliBesideNodeStrategy` anchors on peer-resolved `node` via `StrategyDeps.resolvePeer` — bound at `getDefaultRegistry` via `bindPeerResolution`, in-flight re-entrancy guard at the binding; falls back to `deps.execPath`. Behaviour change: win32 npm now follows node's override.
|
|
5038
|
+
|
|
5039
|
+
#### Cache
|
|
5040
|
+
|
|
5041
|
+
`invalidateNodeCandidatesCache()` wired into `ToolRegistry.rescan()`.
|
|
5042
|
+
|
|
5043
|
+
## Skill tool provisioning
|
|
5044
|
+
|
|
5045
|
+
Skill packages can declare the external tools they need through a `pi.tools` manifest in their package.json. The registry ingests these at server bootstrap, so a skill tool IS a registry tool — same `list()` / `/api/tools` / Settings → Developer → Tools surface, same override + diagnostic trail. Two faces: library `ensureTools` and CLI `pi-dashboard-ensure`. Distinct from the build-time `pi-dashboard-resolve-tool.cjs` wrapper (path-only, untouched).
|
|
5046
|
+
|
|
5047
|
+
See change: `add-skill-tool-provisioning`.
|
|
5048
|
+
|
|
5049
|
+
### `pi.tools` manifest
|
|
5050
|
+
|
|
5051
|
+
- Array in the skill package's package.json under `pi`, sibling to `pi.skills`.
|
|
5052
|
+
- Entry = `{ id, probe, optional? }` only. No shell strings — install recipes stay first-party in the registry's `installHints` for that id.
|
|
5053
|
+
- Id charset `^[A-Za-z0-9_][A-Za-z0-9._-]*$` — the set of legal env-var names.
|
|
5054
|
+
- Parser `parseSkillTools` validates strictly (exact key set, charset, known probe kinds) and names every rejected entry.
|
|
5055
|
+
- Ingestor `ingestSkillTools` (both in `packages/shared/src/tool-registry/pi-tools.ts`) is idempotent: unknown id → synthesized probe-kind def; known id → referenced, never clobbered.
|
|
5056
|
+
- Default `probe` = `resolve`.
|
|
5057
|
+
|
|
5058
|
+
### Probe kinds → strategies (`strategies.ts`)
|
|
5059
|
+
|
|
5060
|
+
| probe | strategy | semantics |
|
|
5061
|
+
|---|---|---|
|
|
5062
|
+
| `env` | `envProbeStrategy` | boolean presence; value never read — logs stay free of secrets |
|
|
5063
|
+
| `docker-image` | `dockerImageProbeStrategy` | `docker image inspect`; never assumes docker exists |
|
|
5064
|
+
| `pw-browser` | `pwBrowserProbeStrategy` | `PLAYWRIGHT_BROWSERS_PATH` or per-OS cache dir under homedir |
|
|
5065
|
+
| `resolve` | `whereStrategy` | existing PATH chain |
|
|
5066
|
+
| `static-npm` (new) | `staticNpmStrategy` | binary path read from package export — bare string (`ffmpeg-static`) or `{ path }` (`@ffprobe-installer/ffprobe`) |
|
|
5067
|
+
|
|
5068
|
+
New `Source` values: `static-npm`, `probe`. `Resolution.path` nullable when `ok` for non-path kinds (`env`).
|
|
5069
|
+
|
|
5070
|
+
### Media tool definitions (`definitions.ts`)
|
|
5071
|
+
|
|
5072
|
+
| Tool | Kind | Chain | Hint |
|
|
5073
|
+
|---|---|---|---|
|
|
5074
|
+
| `ffmpeg` | binary | override → static-npm(`ffmpeg-static`) → where | per-OS package manager |
|
|
5075
|
+
| `ffprobe` | binary | override → static-npm(`@ffprobe-installer/ffprobe`) → where | per-OS package manager |
|
|
5076
|
+
| `imagemagick` | binary | override → where (`convert`) | per-OS package manager |
|
|
5077
|
+
| `chromium` | probe | override → pw-browser | `npx playwright install chromium` (requiresConfirm) |
|
|
5078
|
+
| `agent-browser` | binary | override → where | `pi install npm:pi-agent-browser` |
|
|
5079
|
+
| `pi-doc-engine` | probe | override → docker-image | `npm run build:image` (requiresConfirm) |
|
|
5080
|
+
|
|
5081
|
+
All registered on every platform — the strategies themselves are cross-platform.
|
|
5082
|
+
|
|
5083
|
+
### Consent
|
|
5084
|
+
|
|
5085
|
+
- Default stance: recommend-only. A missing tool never installs anything.
|
|
5086
|
+
- Opt-in auto-run — `ensureTools(..., { autoInstall: true })` or CLI `--install` — executes ONLY resolved first-party `installHints.commands[pkgmgr]` values. A skill manifest can never contribute an executable string.
|
|
5087
|
+
- `PlatformInstallHint.requiresConfirm` gates network+exec hints (playwright download, image build). Confirmation per invocation; no TTY → auto-deny.
|
|
5088
|
+
- Report matrix: `present` / `recommended` / `installed` / `degraded` / `blocked`. `ok: false` ⇔ a required tool not present/installed. Optional tools degrade, never block.
|
|
5089
|
+
|
|
5090
|
+
### Two faces
|
|
5091
|
+
|
|
5092
|
+
- Library: `ensureTools` (`ensure.ts`) — returns an `EnsureReport`; never throws for missing tools.
|
|
5093
|
+
- CLI: `pi-dashboard-ensure` (`packages/shared/bin/pi-dashboard-ensure.mjs` → `ensure-cli.ts`). Reads a package's `pi.tools`, ingests, ensures, prints the report. tsx launcher — the probe strategies are TypeScript registry code. Flags `--install`, `--json`; exit 0 when every required tool present/installed.
|
|
5094
|
+
- Distinct from build-time `pi-dashboard-resolve-tool.cjs` (path-only, no-transpiler, untouched).
|
|
5095
|
+
|
|
5096
|
+
### Surfacing
|
|
5097
|
+
|
|
5098
|
+
`ingestInstalledSkillTools` runs at server bootstrap (`packages/server/src/cli.ts`). Scans `<root>/node_modules/@blackbelt-technology/<pkg>/package.json` + `<root>/packages/<pkg>/package.json` manifests, ingests into the registry, surfaces through the existing `list()` / `GET /api/tools` / Settings → Developer → Tools rows. No new reporting path. Invalid manifests skipped — a doc bug never breaks startup.
|
|
5099
|
+
|
|
3525
5100
|
## Path Handling (`platform/paths.ts`)
|
|
3526
5101
|
|
|
3527
5102
|
Filesystem paths are OS-aware, and the dashboard touches them in three user-visible places: pin-directory storage (server), session-grouping (client), and the path picker UI (client). All three go through a single module — `packages/shared/src/platform/paths.ts` — rather than inventing their own logic.
|
|
@@ -3714,7 +5289,7 @@ Pre-fix, both cases shared the misleading wording "Server failed to start within
|
|
|
3714
5289
|
|
|
3715
5290
|
### The runtime jiti version contract (Defect 2 defense)
|
|
3716
5291
|
|
|
3717
|
-
`shouldUrlWrapEntry()` in `packages/shared/src/platform/node-spawn.ts` decides whether the entry-script position in `node --import <loader> <entry>` argv needs `file://` URL wrapping.
|
|
5292
|
+
`shouldUrlWrapEntry()` in `packages/shared/src/platform/node-spawn.ts` decides whether the entry-script position in `node --import <loader> <entry>` argv needs `file://` URL wrapping. Entry raw for tsx, jiti, and the native loader (`platform/native-ts-register.mjs`) on every OS. Only other / unknown loaders on win32 wrap with `file://` — sidesteps Node's drive-letter URL-scheme parse (`B:`, `A:` otherwise read as URL schemes). Loader position always `file://`. See change: `fix-appimage-cold-boot-latency`.
|
|
3718
5293
|
|
|
3719
5294
|
The contract holds because Defect 1's fix populates `~/.pi-dashboard/` with `pi-coding-agent` at the offline-cacache-pinned version. The runtime `resolveJitiFromPi()` chain is `managed → system`; once managed is populated with the pinned version, system pi (which may be a newer 0.71.x) is never reached.
|
|
3720
5295
|
|
|
@@ -3950,7 +5525,9 @@ Dashboard-resident LLM proxy: `GET /v1/models`, `POST /v1/chat/completions`, `PO
|
|
|
3950
5525
|
sequenceDiagram
|
|
3951
5526
|
participant C as External client<br/>(LangChain, curl)
|
|
3952
5527
|
participant D as Dashboard :8000/v1/*
|
|
3953
|
-
participant R as InternalRegistry
|
|
5528
|
+
participant R as InternalRegistry /<br/>InternalAuthStorage (facades)
|
|
5529
|
+
participant RT as Server ModelRuntime<br/>(pi-coding-agent)
|
|
5530
|
+
participant S as DashboardCredentialStore
|
|
3954
5531
|
participant P as Upstream provider<br/>(Anthropic, OpenAI, Google…)
|
|
3955
5532
|
|
|
3956
5533
|
C->>D: Authorization: Bearer pi-proxy-*
|
|
@@ -3958,12 +5535,77 @@ sequenceDiagram
|
|
|
3958
5535
|
D->>R: getAvailable() / find(provider, model)
|
|
3959
5536
|
R->>R: auth.json + providers.json + models.json
|
|
3960
5537
|
D->>R: getApiKeyAndHeaders(model)
|
|
5538
|
+
R->>RT: getAuth(model) — single-flight, named errors
|
|
5539
|
+
RT->>S: read / modify (refresh)
|
|
5540
|
+
S->>S: auth.json — locked, CAS persist
|
|
3961
5541
|
R->>D: { apiKey, headers }
|
|
3962
|
-
D->>
|
|
5542
|
+
D->>RT: streamSimple(model, context, opts) — apiKey DROPPED
|
|
5543
|
+
RT->>P: provider's own auth path (OAuth or api-key)
|
|
3963
5544
|
P-->>D: SSE stream
|
|
3964
5545
|
D-->>C: SSE stream (OpenAI or Anthropic shape)
|
|
3965
5546
|
```
|
|
3966
5547
|
|
|
5548
|
+
### Single model runtime
|
|
5549
|
+
|
|
5550
|
+
ONE server pi `ModelRuntime` (`packages/server/src/model-proxy/server-model-runtime.ts`). `getServerModelRuntime()` memoizes `ModelRuntime.create({ credentials: new DashboardCredentialStore(), modelsPath: null, refreshOnCreate: false, allowModelNetwork: false })` → `{ runtime, version }`. A failed `create()` is memoized as `ModelRuntimeUnavailableError` — one failure domain (D6): provider-auth listing returns `{ ids: [] }` and the proxy / `/api/models` report the same registry error together. `modelsPath: null` = built-in catalogue only; the dashboard keeps composing `models.json` + `providers.json` itself (D3).
|
|
5551
|
+
|
|
5552
|
+
```mermaid
|
|
5553
|
+
flowchart LR
|
|
5554
|
+
RT["Server ModelRuntime<br/>(pi-coding-agent)"]
|
|
5555
|
+
P["Model proxy /v1/* · /api/models"] --> IR["InternalRegistry (facade)"]
|
|
5556
|
+
P --> IAS["InternalAuthStorage (facade)"]
|
|
5557
|
+
IR --> RT
|
|
5558
|
+
IAS --> RT
|
|
5559
|
+
IR -->|registerProvider / unregisterProvider| RT
|
|
5560
|
+
PA["Provider auth flow listing"] --> RT
|
|
5561
|
+
PGM["Plugin model runtime"] -->|streamSimple| RT
|
|
5562
|
+
RT --> S["DashboardCredentialStore"]
|
|
5563
|
+
S --> A["~/.pi/agent/auth.json"]
|
|
5564
|
+
```
|
|
5565
|
+
|
|
5566
|
+
- `InternalRegistry` stays a facade. Built-ins come from the runtime; custom composition unchanged (`providers.json` discovery ⨝ `models.json`). Non-built-in providers with a resolvable key are projected onto the runtime with `registerProvider` (changed → `unregisterProvider` first; removed → unregister; unresolved key → skipped, secret-free log), re-checked on every `getAvailable()`. Key/header values escaped with `literalConfigValue` (pi config-template syntax: leading `!` = shell, `$VAR` = env). Listing stays auth.json-based + `oauth-compat.ts`.
|
|
5567
|
+
- `InternalAuthStorage` stays a facade. Presence/kind from auth.json (+ custom-provider keys; ambient env never routes). `MissingOAuthCapabilityError` when a stored OAuth credential's runtime provider has no `auth.oauth`, then `runtime.getAuth` single-flighted per provider, bounded 40 s. `unwrapRuntimeAuthError` unwraps `ModelsError("auth").cause` so named store errors surface. Own refresh/coordination code deleted.
|
|
5568
|
+
- `getStreamSimpleFn()` wraps `runtime.streamSimple` and DROPS `options.apiKey`: the facade already resolved (and refreshed) the credential, the runtime re-reads it through the store and applies the provider's own auth path (an OAuth token sent as an api-key override would hit the wrong header). Proxy streams with headers, no api-key override.
|
|
5569
|
+
- `getModelProxyStatus()` → `{ status, reason? }` (fields `piAiGeneration`, `oauthProviders` removed).
|
|
5570
|
+
|
|
5571
|
+
See change: collapse-model-proxy-onto-modelruntime.
|
|
5572
|
+
|
|
5573
|
+
### Completion request pipeline
|
|
5574
|
+
|
|
5575
|
+
Both POST routes (`/v1/chat/completions`, `/v1/messages`) run ONE pipeline `handleCompletion(format, deps, request, reply)` (`packages/server/src/routes/model-proxy-routes.ts`). Format differences live only in a `CompletionFormat` adapter: `OPENAI_FORMAT`, `ANTHROPIC_FORMAT`. Adapter fields: `invalid` (400 message or null), `newMessageId`, `toUpstream` (message/tool conversion → `{system, messages, tools, maxTokens}`), `sseEncoder` (fresh per response; owns its `ToolCallIndexTracker` / `AnthropicBlockTracker`), `toResponse`.
|
|
5576
|
+
|
|
5577
|
+
```mermaid
|
|
5578
|
+
flowchart TD
|
|
5579
|
+
A["POST /v1/chat/completions or /v1/messages"] --> B["validate body → 400 invalid"]
|
|
5580
|
+
B --> C["registry ready? → 503 MODEL_PROXY_RUNTIME_MISSING"]
|
|
5581
|
+
C --> D["resolveRequestedModel → 400 / 404"]
|
|
5582
|
+
D --> E["acquireSlot → 503 SERVER_FULL, 429 KEY_FULL / PROVIDER_FULL + Retry-After"]
|
|
5583
|
+
E --> F["runCompletion → toUpstream → upstream stream"]
|
|
5584
|
+
F --> G{"stream?"}
|
|
5585
|
+
G -->|streamEvents| H["SSE via format sseEncoder"]
|
|
5586
|
+
G -->|collectEvents| I["JSON via format toResponse"]
|
|
5587
|
+
F -.throw.-> J[failCompletion]
|
|
5588
|
+
H -.throw mid-stream.-> J
|
|
5589
|
+
I -.throw.-> J
|
|
5590
|
+
J -->|AbortError| X["return — client gone"]
|
|
5591
|
+
J -->|headers sent| K["format SSE error event + reply.raw.end()"]
|
|
5592
|
+
J -->|headers not sent| M["500 JSON api_error"]
|
|
5593
|
+
H --> L["logOutcome → optional ~/.pi/dashboard/model-proxy.jsonl"]
|
|
5594
|
+
I --> L
|
|
5595
|
+
K --> L
|
|
5596
|
+
M --> L
|
|
5597
|
+
```
|
|
5598
|
+
|
|
5599
|
+
- Stages in order: validate body (400) → registry (`503 MODEL_PROXY_RUNTIME_MISSING`) → `resolveRequestedModel` (400/404) → `acquireSlot` (`503 SERVER_FULL`, `429 KEY_FULL` / `PROVIDER_FULL` + `Retry-After`) → `runCompletion` → `streamEvents` (SSE) or `collectEvents` (JSON) → `failCompletion` on throw. `logOutcome` writes optional request log (`~/.pi/dashboard/model-proxy.jsonl` when `modelProxy.logRequests`).
|
|
5600
|
+
- Types exported: `ProxyModel`, `ProxyStreamEvent`, `ProxyStreamOpts`, `StreamSimpleFn`. Zero `any`.
|
|
5601
|
+
- Stateless per request — no conversation state kept between requests. Concurrent-conversation isolation covered by `packages/server/src/__tests__/model-proxy-parallel-isolation.test.ts` (real listener, start barrier proves overlap, OpenAI + Anthropic, multi-turn, abort, mid-stream failure, per-key caps).
|
|
5602
|
+
- Disconnect detection: `reply.raw` `"close"` while `!reply.raw.writableFinished` → `AbortController.abort()` → upstream `AbortSignal`. NOT `request.raw` `"close"` — on Node 24 it fires once the request body is consumed, before the listener attaches, so abort never fired (bug fixed).
|
|
5603
|
+
- Mid-stream failure: throw after headers sent → format's SSE `error` event (OpenAI: stop chunk + `data: [DONE]`; Anthropic: `event: error`) + `reply.raw.end()`. Never `reply.code(500)` (was `ERR_HTTP_HEADERS_SENT` + hung client).
|
|
5604
|
+
- System prompt: route passes `system`; `callPiAiStreamSimple(fn, opts)` (`packages/server/src/model-proxy/streamer.ts`) maps it to pi-ai `Context.systemPrompt` via private `toPiAiContext`. Both `/v1` wirings in `server.ts` (main listener + optional second port) use it. Former `{ system }` context key was silently dropped by pi-ai (bug fixed).
|
|
5605
|
+
- Concurrency caps: `ConcurrencyTracker`. Server-wide default 16 (`modelProxy.maxConcurrentStreams`), per key default 4 (`perKeyConcurrentStreams`), per provider default 4 (`perProviderCaps[provider]`). Released exactly once on success/error/abort.
|
|
5606
|
+
|
|
5607
|
+
See change: fix-model-proxy-stream-lifecycle.
|
|
5608
|
+
|
|
3967
5609
|
### API-key auth data flow
|
|
3968
5610
|
|
|
3969
5611
|
1. Client sends `Authorization: Bearer pi-proxy-<48-char-base64url>`.
|
|
@@ -3981,13 +5623,13 @@ sequenceDiagram
|
|
|
3981
5623
|
|
|
3982
5624
|
`auth.json` holds one credential per provider key (`api_key` OR `oauth`, never both). No mixed-cred branch.
|
|
3983
5625
|
|
|
3984
|
-
Override table: `packages/server/src/model-proxy/oauth-compat.ts` → `OAUTH_INCOMPATIBLE: Record<provider, ReadonlySet<modelId>>` + `isOauthIncompatible(provider, id)`. Flags legacy Anthropic snapshots (`claude-3-5-haiku-20241022`, `claude-3-5-sonnet-*`, `claude-3-7-sonnet-*`, `claude-3-opus-*`, `claude-3-haiku-*`, `claude-3-sonnet-*`) unreachable over OAuth. `getAllModels()` sets `oauthCompatible = !isOauthIncompatible(provider, id)` on built-in models; custom models propagate `models.json#oauthCompatible` (default `true`). Hand-maintained. Review when provider ships new model. Stale entry falls back to listed-but-unreachable — not a regression.
|
|
5626
|
+
Override table: `packages/server/src/model-proxy/oauth-compat.ts` → `OAUTH_INCOMPATIBLE: Record<provider, ReadonlySet<modelId>>` + `isOauthIncompatible(provider, id)`. Flags legacy Anthropic snapshots (`claude-3-5-haiku-20241022`, `claude-3-5-sonnet-*`, `claude-3-7-sonnet-*`, `claude-3-opus-*`, `claude-3-haiku-*`, `claude-3-sonnet-*`) unreachable over OAuth. `getAllModels()` sets `oauthCompatible = !isOauthIncompatible(provider, id)` on built-in models; custom models propagate `models.json#oauthCompatible` (default `true`). Hand-maintained. Review when provider ships new model. Stale entry falls back to listed-but-unreachable — not a regression. Unchanged by the 0.85.1 bump: `claude-fable-5-1` NOT added. Its HTTP 400 `claude_code_version_too_old` on Claude Pro/Max OAuth = client-version (user-agent) header gate, not catalog gate. 0.85.1 raises pi's Anthropic UA to `claude-cli/2.1.251`, clearing it. Adding the id would wrongly hide a reachable model.
|
|
3985
5627
|
|
|
3986
|
-
|
|
5628
|
+
Codex OAuth stored under `auth.json` key `openai-codex`. pi 0.85.1 catalog publishes `gpt-6-astra` as FOUR first-class entries, one per channel, each carrying its own `provider`: `openai` (api `openai-responses`), `openai-codex` (api `openai-codex-responses`), `github-copilot`, `azure-openai-responses`. Registry matches credential key to `model.provider` by EQUALITY. An `openai-codex` credential lists the `openai-codex` entry and NOT the `openai` / `github-copilot` / `azure-openai-responses` entries of the same model id. NO provider-key remap needed. Do NOT add one: remap makes a Codex subscription credential appear to route every `openai`-provider model, widening credential scope. See change: `update-pi-core-0-85-adopt-apis`.
|
|
3987
5629
|
|
|
3988
|
-
`GET /api/model-proxy/diagnostics` (JWT-gated, main instance only, `routes/model-proxy-diagnostics-routes.ts`): `getAllAnnotated()` → `{id, provider, excludedReason}` per model. `excludedReason` ∈ `null` (included) | `"no-credential"` | `"oauth-incompatible"`. Feeds future Settings UI. 503 when
|
|
5630
|
+
`GET /api/model-proxy/diagnostics` (JWT-gated, main instance only, `routes/model-proxy-diagnostics-routes.ts`): `getAllAnnotated()` → `{id, provider, excludedReason}` per model. `excludedReason` ∈ `null` (included) | `"no-credential"` | `"oauth-incompatible"`. Response also carries `missingOAuth: string[]` — providers holding an OAuth credential whose runtime provider has no `auth.oauth`. Feeds future Settings UI. 503 (`MODEL_PROXY_RUNTIME_MISSING`) when the runtime is unresolved.
|
|
3989
5631
|
|
|
3990
|
-
See change: `filter-oauth-incompatible-models`.
|
|
5632
|
+
See change: `filter-oauth-incompatible-models`, `collapse-model-proxy-onto-modelruntime`.
|
|
3991
5633
|
|
|
3992
5634
|
### Refresh trigger map
|
|
3993
5635
|
|
|
@@ -4003,16 +5645,18 @@ See change: `filter-oauth-incompatible-models`.
|
|
|
4003
5645
|
|
|
4004
5646
|
Two writer processes for `~/.pi/agent/auth.json`:
|
|
4005
5647
|
|
|
4006
|
-
- **Dashboard**: `provider-auth-storage.ts#writeCredential` (mkdir-based lock). Used by OAuth-flow completion routes
|
|
5648
|
+
- **Dashboard**: `provider-auth-storage.ts#writeCredential` (mkdir-based lock). Used by OAuth-flow completion routes. OAuth-refresh-on-expiry now writes through `DashboardCredentialStore.modify` → `writeRefreshedOAuth` CAS — pi's refresh callback runs with the file lock RELEASED, persist is compare-and-swap; NOT `InternalAuthStorage`.
|
|
4007
5649
|
- **Pi sessions**: `pi-coding-agent`'s `AuthStorage` (proper-lockfile). Runs in each connected pi session.
|
|
4008
5650
|
|
|
4009
5651
|
Last-writer-wins on overlapping provider keys; non-overlapping providers preserved by merge. Acceptable — both writers re-read before writing; churn only occurs during concurrent OAuth refreshes (rare in practice).
|
|
4010
5652
|
|
|
4011
|
-
|
|
5653
|
+
Refresh window: pi refreshes at 5 min remaining (`OAUTH_REFRESH_WINDOW_MS`) with a 15 s abort — was dashboard 30 s / 30 s.
|
|
5654
|
+
|
|
5655
|
+
See change: `add-dashboard-model-proxy`, `collapse-model-proxy-onto-modelruntime`.
|
|
4012
5656
|
|
|
4013
5657
|
## Test execution & isolation
|
|
4014
5658
|
|
|
4015
|
-
Vitest 4. Root `vitest.config.ts` lists projects under `test.projects`.
|
|
5659
|
+
Vitest 4. Root `vitest.config.ts` lists projects under `test.projects`. Parallel projects carry `pool: "forks"` + `maxWorkers: PARALLEL_MAX_WORKERS` imported from repo-root `vitest.workers.ts` (`= "50%"` of logical cores; parallel; was `1`). Deliberately serial projects retain `maxWorkers: 1`. See change: `make-test-suite-deterministic`.
|
|
4016
5660
|
|
|
4017
5661
|
Per-file HOME isolation via `setupFiles` → `packages/shared/src/test-support/setup-home-perfile.ts`. Fresh `mkdtemp` HOME per test file. `globalSetup` `setup-home.ts` tripwire kept.
|
|
4018
5662
|
|
|
@@ -4167,6 +5811,28 @@ Result render emits leaf heading, not breadcrumb, plus `(+N more sections)`. Ful
|
|
|
4167
5811
|
|
|
4168
5812
|
Path-only fetch (`getChunk` without `headingPath`) returns first chunk plus `suppressedSections` count. Never a silent 1-of-N slice.
|
|
4169
5813
|
|
|
5814
|
+
#### DOX doctrine injection (`doctrine` config)
|
|
5815
|
+
|
|
5816
|
+
Config group `doctrine: { "inject": "kb" | "off", "write": boolean }`. Layered project `.pi/dashboard/knowledge_base.json` → global `~/.pi/dashboard/knowledge_base.json` → defaults. Deep-merged one level, same as `readDiscipline` / `ranking`. Defaults `{ inject: "kb", write: false }`. Validation: `inject` ∈ {`kb`,`off`}; `write` boolean.
|
|
5817
|
+
|
|
5818
|
+
`ResolvedConfig.doctrineSource` = `"project"` | `"global"` | `"none"` — highest layer that supplied a `doctrine` KEY. Empty object `{}` counts as a recorded choice; a file that exists without the key does NOT. Distinct from `origin` (file-presence).
|
|
5819
|
+
|
|
5820
|
+
Carrier: kb extension (`packages/kb-extension/src/extension.ts`) registers a `before_agent_start` handler. Config resolved PER TURN from session cwd (`systemPromptOptions.cwd`), so a mid-session config write takes effect next turn.
|
|
5821
|
+
|
|
5822
|
+
READ injection: when `inject === "kb"`, canonical READ doctrine (`packages/kb-extension/dox-doctrine.md`, section `dox:read:kb`) inserted into system prompt under delimiter line `── dox doctrine ──`. WRITE section (`dox:write`) appended only when `write === true`. `inject: "off"` injects nothing and makes `write` inert.
|
|
5823
|
+
|
|
5824
|
+
Insertion point: immediately BEFORE pi's `Current working directory: ` anchor (anchor preserved). Why: dashboard bridge `dashboard-context-injector.ts` splice-replaces everything AFTER that anchor, so a plain append is order-dependent. Idempotent by the delimiter — a reload/repeat never stacks a second fragment.
|
|
5825
|
+
|
|
5826
|
+
First-contact flow: when `doctrineSource === "none"`, a ONE-TIME (per session) nudge tells the agent to ask the user (`ask_user`) which mode to enable — `kb read`, `kb read + write`, `off`, `ask later` — and to record the choice in the PROJECT config by read-merge-write (preserve every other key). Non-interactive run → proceed with defaults and write nothing. `ask later` writes nothing and the nudge re-fires next session. Defaults (`kb read`) apply meanwhile.
|
|
5827
|
+
|
|
5828
|
+
Legacy seed guard: if a loaded context file (root `AGENTS.md`) carries a `dox:write` / `dox:read:kb` / `dox:read:manual` section delimiter, injection is skipped for that cwd (no double-load) and a once-per-session MIGRATION nudge offers to replace the legacy block with the pointer block. Detection is on the delimiter alone (half-migrated files still detected). The new marker-only pointer block (`<!-- dox-doctrine -->`, no delimiter) never trips the guard. `inject: "off"` suppresses both nudges.
|
|
5829
|
+
|
|
5830
|
+
Fault behavior: malformed project config → built-in defaults for that turn (READ injected, WRITE off), NO first-contact nudge, one `[kb]`-prefixed `console.warn` per session. Unreadable doctrine file → system prompt unchanged, one `[kb]` warn per session.
|
|
5831
|
+
|
|
5832
|
+
Packaging: `dox-doctrine.md` ships in the npm `files` of `packages/kb-extension`; the `dox-describe` skill ships at `packages/kb-extension/.pi/skills/dox-describe/`.
|
|
5833
|
+
|
|
5834
|
+
See change: inject-dox-doctrine-and-describe.
|
|
5835
|
+
|
|
4170
5836
|
#### Measured outcome (31,121-chunk index, K=10)
|
|
4171
5837
|
|
|
4172
5838
|
| metric | baseline | shipped |
|
|
@@ -4190,6 +5856,23 @@ Lane quota is the cost: its `agents` lane is a second FTS query, and `doc_type`
|
|
|
4190
5856
|
|
|
4191
5857
|
See change: fix-kb-search-retrieval-quality.
|
|
4192
5858
|
|
|
5859
|
+
### Sources, trust & dashboard reindex
|
|
5860
|
+
|
|
5861
|
+
Settings page `packages/kb-plugin/src/client/KbSettingsPanel.tsx`. Add via `KbSourceAdd`. Kind toggle `Folder | Git repo | URL`. `Browse…` uses host primitive `ui:path-picker` (soft hook — hidden on older hosts). Folder inside cwd stored relative (`docs`); outside stored absolute + `outside folder` badge. GitHub/GitLab/`git@`/`git:` refs auto-select Git. Folder mode refuses `scheme://`, `git@`, `git:`, `npm:` refs. One source per `ref`; ref = index root; duplicate refs erase each other's chunks.
|
|
5862
|
+
|
|
5863
|
+
`reindexAll` (`packages/kb-plugin/src/server/kb-routes.ts`) walks `cfg.allSourceSpecs` — all kinds (filesystem/git/https/npm) via engine resolvers. Each source isolated: failure → `error` outcome, job `jobStatus:"error"`, `lastError` `"N source(s) failed: …"` (≤500 chars); untrusted → skipped, job stays idle; failed/skipped source keeps prior chunks. `git`/`https` resolution async (`execFile`, 120 s timeout) — never blocks server event loop. Reindex gate = saved `allSourceSpecs.length > 0`.
|
|
5864
|
+
|
|
5865
|
+
Trust = TOFU, global. Store `~/.pi/dashboard/kb-source-trust.json`, keyed sha256 of `{kind,ref,subdir,pin}`. One grant covers identical spec in every folder. Revoke under Access → `DELETE /api/kb/source-trust`. Grant path: UI trust dialog (`Trust & add` / `Add without trusting` / `Cancel`) → `PUT /api/kb/config` `trustRefs`, or `POST /api/kb/source-trust {ref}`. Server records SAVED spec matched by exact `ref` (404 none, 409 duplicate refs, 400 filesystem, 500 persist failure). `untrustedRefs` in PUT response lists grants that failed. Trust-store write atomic (`tmp`+rename); `recordTrust` returns boolean. Fetch-side SSRF/zip-slip guards from change `harden-untrusted-content-ingestion` (`net-guard.ts`, `archive-guard.ts`).
|
|
5866
|
+
|
|
5867
|
+
### KB source & search routes
|
|
5868
|
+
|
|
5869
|
+
- `GET /api/kb/sources?cwd=` — per-source kind, files, trusted, outside, last outcome.
|
|
5870
|
+
- `GET /api/kb/search?cwd=&q=&limit=&docType=` — read-only test search over SAVED index. Opens existing store only — no init, no migrate, no create. `q` 1–512, `limit` 1–50 (default 10), `docType` `doc|agents|source-md`. No reindex, no verdicts. Stale schema → `needsReindex:true`.
|
|
5871
|
+
|
|
5872
|
+
All cwd-guarded (`isAllowedCwd`).
|
|
5873
|
+
|
|
5874
|
+
See change: improve-kb-settings-sources-and-search.
|
|
5875
|
+
|
|
4193
5876
|
## Pi Gateway Transport & Identity
|
|
4194
5877
|
|
|
4195
5878
|
Bridge↔server gateway transport + identity. Ground truth: `openspec/changes/add-pi-gateway-transport-identity/design.md` (decisions D0–D16), `packages/extension/src/endpoint-resolution.ts`, `packages/server/src/pi/gateway-transport-policy.ts`, `gateway-socket-bind.ts`, `bridge-upgrade-auth.ts`, `provisional-registration.ts`.
|
|
@@ -4291,7 +5974,7 @@ flowchart TD
|
|
|
4291
5974
|
|
|
4292
5975
|
### Remote transcripts + read-only boundary (D12, D13)
|
|
4293
5976
|
|
|
4294
|
-
- Sessions addressed by id ONLY. `decideTranscriptRequest` (`packages/
|
|
5977
|
+
- Sessions addressed by id ONLY. `decideTranscriptRequest` (`packages/shared/src/transcript-request-guard.ts`) refuses any path-bearing field: `path`, `file`, `filePath`, `filepath`, `sessionFile`, `sessionDir`, `dir`, `cwd`. Refusal on field presence, never value validation — validating values is a traversal-parsing contest.
|
|
4295
5978
|
- Shape checked before subject: two refusals cannot be differenced into an existence check. Foreign `sessionId` refused — bridge serves only its own session.
|
|
4296
5979
|
- Backfill: lazy, interruptible, background after registration. Live events forward eagerly. Cursor = offset + length + hash of last consumed line; mismatch → re-read from start, never resume (append-only is measured, not provable over time).
|
|
4297
5980
|
- Retention: `<dashboardConfigDir>/remote-transcripts/<sessionId>.jsonl` (`~/.pi/dashboard/remote-transcripts/`). File `0600`, dir `0700`. `sessionId` validated `^[A-Za-z0-9_-]{1,64}$` — rejected, never sanitised (write-anywhere guard).
|
|
@@ -4299,3 +5982,114 @@ flowchart TD
|
|
|
4299
5982
|
- Origin derived from the authenticated bridge credential, never bridge-claimed (`attributeOrigin`, `packages/server/src/session/session-origin.ts`). unix / loopback → local. Remote + `deviceId` → remote. Unattributable remote → remote, fail closed. Claimed fields (`claimedDeviceId`, `claimedLocal`, …) ignored.
|
|
4300
5983
|
- Remote-origin sessions refuse local file reads (`mayReadLocalSessionFile`: `remote-origin` | `no-session-file`) — same-username path collision would serve an unrelated host's transcript.
|
|
4301
5984
|
- Remote-origin sessions refuse resume (`decideResume`: `remote-origin-ended` | `remote-origin-live`) — local resume would attach a writer to another host's transcript. Read-only after bridge ends (D13).
|
|
5985
|
+
|
|
5986
|
+
**Read half** (change: `serve-retained-remote-transcripts`). Acquisition shipped first; `read()` had no caller and no route, so retained bytes rendered as an empty session.
|
|
5987
|
+
|
|
5988
|
+
- `RemoteTranscriptStore.read()` → `{entries, complete, retained}`. `retained` = transcript FILE exists. `complete:false` alone conflates "transfer truncated" with "never transferred".
|
|
5989
|
+
- Three states: `complete` | `incomplete` | `absent`. Surfaced as `DashboardSession.retainedTranscript` (`packages/shared/src/types.ts`). Absent on local sessions.
|
|
5990
|
+
- `packages/server/src/session/retained-transcript.ts` exports `decideRetainedRead({sessionId, query, origin})`, `readRetainedState(store, sessionId)` and `readRetainedTranscript(store, sessionId, knownContextWindow?)`.
|
|
5991
|
+
- Read is SPLIT by need. Both HTTP callers want entries/completeness and discard events, so they use `readRetainedState` and skip parse + event synthesis entirely; only cold hydration calls the replaying read. Replaying for a route would parse up to the 44.1 MB observed maximum to produce output nobody reads.
|
|
5992
|
+
- Refusal order: path-bearing field FIRST (`path-on-the-wire`), local-origin SECOND (`local-origin`). Shape before subject — reverse order differences two refusals into an origin oracle.
|
|
5993
|
+
- Path refusal delegates to `decideTranscriptRequest`. Guard MOVED `packages/extension/src/` → `packages/shared/src/`. Bridge wire check and dashboard route check are ONE function.
|
|
5994
|
+
- Route `GET /api/sessions/:sessionId/retained-transcript` → `{entries, state}`. `networkGuard`ed like every content-bearing session read (`session-file`, `session-change`, `session-diff`, `tool-result`) — loopback, `x-pi-local-token`, or a trusted network. Browser never calls it; consumers are local + the L3 gate.
|
|
5995
|
+
- Guard wiring pinned at L1 (spy preHandler), NOT at L3: docker publishes through a proxy, so the server sees a host request as loopback and exempts it — identically for `/api/session-file`. An L3 "guard refuses" arm would assert what that harness cannot produce.
|
|
5996
|
+
- Refusal order: 400 path-bearing query field (shape, checked BEFORE the session lookup so an unknown/known id cannot be differenced), 404 unknown session, 403 local-origin session, 503 no store wired.
|
|
5997
|
+
- Route resolves the subject from `sessionManager.get(id) ?? sessionArchive.getById(id)` — an archived remote session is the case where the retained copy is the ONLY copy.
|
|
5998
|
+
- Browser gets retained history via SUBSCRIBE-TIME HYDRATION, not a client fetch. No `packages/client/src` caller of the route; the route is the addressable surface for non-browser clients and the L3 gate.
|
|
5999
|
+
- Cold hydration (`subscription-handler.ts`) picks a source via `chooseHydrationSource({origin, sessionFile, hasRetentionStore})`. Remote origin → retention store, NEVER `sessionFile`; the remote arm has no branch returning `local-file`, so the property holds by construction. Remote + no store → `none` (fail closed), never a `sessionFile` fallback.
|
|
6000
|
+
- Closes the #E15 hydration hole — same username on two hosts yields the same path, so the local file could be an unrelated transcript.
|
|
6001
|
+
- Origin falls back to the ARCHIVE row. `ArchivedSessionSummary.originDeviceId` captured at archive time; archived sessions are non-resident, so origin read only off `sessionManager.get` would treat every archived remote session as local. Absent = local (back-compat).
|
|
6002
|
+
- Origin is DURABLE. `SessionMeta.originDeviceId` persisted; enumerated in `sessionToMeta` (full-overwrite projection — an unenumerated field is wiped on the next save), restored by `sessionFromMeta` + `archivedRowFromMeta` on boot, and carried through `unarchiveSession`. Origin gates filesystem reads, so it must outlive the process that derived it; forgetting it resurrects a remote session as local and reopens #E15 — and re-enables `decideResume`, which D13 forbids.
|
|
6003
|
+
- `parseSessionEntries` bounds the leaf→root walk with a `seen` set. A `parentId` cycle is two well-formed lines, and retained bytes are bridge-controlled: unbounded, the walk hangs the event loop — HTTP, WS, and the hydration heartbeat alike. A detected cycle falls through to the LINEAR fallback; returning the partial branch would serve an arbitrary prefix of a walk that never terminated.
|
|
6004
|
+
- `state-replay` orphan-close indexes `tool_execution_start` by `toolCallId` instead of `messages.find` per orphan. The former O(orphans × messages) measured 175 ms / 785 ms / 2.8 s at 5k / 10k / 20k orphans — the same stall class over the same untrusted input.
|
|
6005
|
+
- `readRetainedTranscript` never throws, PARSE included: a crafted `message.content: [null]` line crashes the replay, and the read degrades to zero events while KEEPING the state (the bytes really were transferred).
|
|
6006
|
+
- Retained lines parse via `parseSessionEntries(lines)` (`session-file-reader.ts`) — same branch-order resolution as the local path, so a remote session renders what the origin machine renders.
|
|
6007
|
+
- `server.ts` hoists ONE `createRemoteTranscriptStore()`. Shared by `wireEvents` (write), the read route, and hydration.
|
|
6008
|
+
- `ChatView` renders the `retained-transcript-incomplete` notice for `incomplete` ONLY. `absent` keeps the ordinary "No messages yet" empty state.
|
|
6009
|
+
- ARCHIVED read-only open gets the state from `GET /api/sessions/archived/:id` (stamped there, not on the listing), carried through `archivedSummaryToSession`. The `session_updated` broadcast cannot serve it: the client drops that message for any session absent from its live map, which an archived one is by construction.
|
|
6010
|
+
- L3 gate `tests/e2e/remote-transcript-read.spec.ts` — task 12.52 of `add-pi-gateway-transport-identity`, deferred there for want of a read path to drive.
|
|
6011
|
+
## Browser relay (plugin-owned WS scopes + screencast tap)
|
|
6012
|
+
|
|
6013
|
+
Drive the user's real logged-in Chrome from a pi session. Plugin-owned (`packages/browser-plugin/`), opt-in (`defaultEnabled:false`). Ground truth: `openspec/changes/add-browser-relay/design.md` (D1–D9), `packages/browser-plugin/src/server/{ws-routes,status,routes,index}.ts`, `relay/{relay-manager,relay-instance,screencast-tap,viewer-input}.ts`, `packages/dashboard-plugin-runtime/src/server/ws-route-registry.ts`.
|
|
6014
|
+
|
|
6015
|
+
See change: add-browser-relay. Research record: [`research/browser-relay-playwright-extension.md`](research/browser-relay-playwright-extension.md).
|
|
6016
|
+
|
|
6017
|
+
### Connect → relay → viewer flow
|
|
6018
|
+
|
|
6019
|
+
```mermaid
|
|
6020
|
+
sequenceDiagram
|
|
6021
|
+
participant Agent as pi session (agent)
|
|
6022
|
+
participant Dash as Dashboard server (core)
|
|
6023
|
+
participant Mgr as RelayManager (plugin)
|
|
6024
|
+
participant Ext as Playwright Chrome Extension
|
|
6025
|
+
participant Chrome as User Chrome
|
|
6026
|
+
participant Viewer as Dashboard /ws viewer
|
|
6027
|
+
Agent->>Dash: POST /api/browser/connect {profileDirectory}
|
|
6028
|
+
Dash->>Mgr: connect(profileDirectory)
|
|
6029
|
+
Mgr->>Mgr: mint 128-bit guid + public instanceId
|
|
6030
|
+
Mgr->>Chrome: open connect.html?mcpRelayUrl=ws://127.0.0.1:<port>/ws/browser-ext/<guid> --profile-directory=<dir>
|
|
6031
|
+
Ext->>Dash: WS upgrade /ws/browser-ext/<guid>
|
|
6032
|
+
Note over Dash: core gates: host -> pinned origin -> genuinely-local; then plugin handleUpgrade
|
|
6033
|
+
Dash->>Mgr: attachExtension(guid, ws)
|
|
6034
|
+
Mgr-->>Agent: {cdpUrl, instanceId}
|
|
6035
|
+
Agent->>Dash: agent-browser connect ws://127.0.0.1:<port>/ws/browser-cdp/<guid>
|
|
6036
|
+
Note over Dash: core gates; handler refuses ANY Origin header
|
|
6037
|
+
Dash->>Mgr: attachCdp(guid, ws)
|
|
6038
|
+
Agent->>Ext: CDP commands (deny-list verbs answered -32000)
|
|
6039
|
+
Viewer->>Dash: /ws browser_relay_subscribe {instanceId, tabId}
|
|
6040
|
+
Dash->>Ext: Page.startScreencast (tap)
|
|
6041
|
+
Ext-->>Viewer: browser_relay_frame PER socket (jpeg)
|
|
6042
|
+
Dash-->>Viewer: browser_relay_status broadcast
|
|
6043
|
+
```
|
|
6044
|
+
|
|
6045
|
+
### Plugin WS-scope admission (all in core, before `handleUpgrade`)
|
|
6046
|
+
|
|
6047
|
+
- Two scopes: `browser-ext` = `/ws/browser-ext/<guid>`; `browser-cdp` = `/ws/browser-cdp/<guid>`. Registered via `ctx.registerWsRoute` during plugin activation.
|
|
6048
|
+
- Gate order: host admission → origin admission → genuinely-local peer. Then the plugin's `handleUpgrade` owns the guid.
|
|
6049
|
+
- `admitOrigins` non-empty = exact-match, REPLACES the dashboard origin policy. `browser-ext` pins `chrome-extension://mmlmfjhmonkocbjadbfplnigmagldckm`; a loopback page origin (`http://localhost:5173`) is refused there.
|
|
6050
|
+
- `admitOrigins` empty = core policy applies. `browser-cdp` uses empty AND its handler refuses any request carrying an `Origin` header — web content always sends one, a CDP client never does.
|
|
6051
|
+
- Genuinely-local = loopback remote address AND loopback `Host` (`127.0.0.1` / `[::1]` / `localhost`, any port) AND none of 8 forwarding headers (`x-forwarded-*`, `x-real-ip`, `forwarded`, `via`). Tunnel reachability never depends on whether the proxy injects markers.
|
|
6052
|
+
- Cookies, local IPC token, single-use tickets, trusted-CIDR bypass NEVER run for a plugin scope. The guid is the only credential. `POST /api/ws-ticket` refuses to mint for a plugin scope.
|
|
6053
|
+
- Registrations are per activation: toggle off tears down (sockets close 1001, prefixes 404); toggle on registers afresh.
|
|
6054
|
+
|
|
6055
|
+
### Address model
|
|
6056
|
+
|
|
6057
|
+
- **guid** = 128 bits of randomness, minted per connect. Socket credential. In the path of both relay endpoints. Never logged, never persisted, never returned to a browser client.
|
|
6058
|
+
- **`instanceId`** = short public handle (`inst-…`) for the UI and audit. Cannot open a socket.
|
|
6059
|
+
- Deliberately NO cdpUrl-lookup endpoint: REST calls carry no pi-session identity, so a profile-keyed lookup could hand one local process another session's tab group. The caller keeps the `cdpUrl` from `connect`.
|
|
6060
|
+
- No secret reaches a client: the pairing token is `writeOnly` in `configSchema.json`, stripped by `redactPluginConfigForClient` (fails CLOSED — unloadable schema → `{}`), and written through `PUT /api/browser/profile` which merges server-side against the unredacted config.
|
|
6061
|
+
|
|
6062
|
+
### Lifecycle (each end is a real leak otherwise)
|
|
6063
|
+
|
|
6064
|
+
- A minted guid never claimed within 60 s expires (the user never allowed, or token mismatch — indistinguishable, one 504).
|
|
6065
|
+
- An instance closes when its extension socket closes, when its CDP client socket closes (the agent's task is over), and 30 s after the handshake with no CDP client (agent crashed, or the pi session is not on the dashboard host and cannot dial `127.0.0.1`).
|
|
6066
|
+
- Kill switch (`PUT /api/browser/enabled {false}`) persists config first, bumps a `disableEpoch` (a connect in flight re-checks it after each await), then closes every instance; the response returns only after all are gone.
|
|
6067
|
+
- Plugin disable rides the WS-socket tracking: the loader's `teardownPlugin` closes tracked sockets 1001 → `RelayInstance` finalizes → the Chrome tab group releases.
|
|
6068
|
+
|
|
6069
|
+
### Screencast tap + viewer plane
|
|
6070
|
+
|
|
6071
|
+
- One `ScreencastTap` per `(instance, tabId)` with ≥1 viewer. It is an in-process listener on the relay's CDP stream — the extension allows one `chrome.debugger` session per tab, so a second session is impossible.
|
|
6072
|
+
- Frames for a tapped session are FILTERED OUT of the CDP-client stream; a client `Page.startScreencast` on a tapped tab is denied. A client screencast already running on a tab wins: the viewer subscribe is refused `client-screencast-active`.
|
|
6073
|
+
- Frames are sent PER viewer socket (the only way `bufferedAmount` backpressure can skip ONE viewer); `browser_relay_status` (instance list, per-tab state, monotonic `auditSeq`) IS broadcast, coalesced ≤1 per 500 ms on audit append.
|
|
6074
|
+
- Viewer input is allowlisted to `Input.dispatchMouseEvent` / `Input.dispatchKeyEvent` / `Input.synthesizeScrollGesture` / `Page.bringToFront`; coordinates are normalized `[0,1]` of the rendered frame, scaled server-side by the last frame's device geometry. No `Runtime.*` path.
|
|
6075
|
+
- Deny-list: cookie reads (`Storage.getCookies`, `Network.getCookies`, `Network.getAllCookies`) + `Browser.setDownloadBehavior` always refused; `Page.navigate` / `Target.createTarget` fenced off `file:` / `javascript:` / `data:` / `blob:` and (when `allowedDomains` is non-empty) off host-less/outside-list URLs. A refusal is a CDP error `-32000` — loud, never a silent skip.
|
|
6076
|
+
- No-frames detector: no frame for 2 s → tab state `no-frames` (a hidden tab AND a visible idle tab both produce zero frames, so the tile wording stays neutral). DevTools take-over → `detached` + `reason:"devtools"`, input stops.
|
|
6077
|
+
|
|
6078
|
+
### Client surfaces (plugin)
|
|
6079
|
+
|
|
6080
|
+
- `settings-section` → `BrowserSettings`: profile rows keyed by `profileDirectory` (label, email, `installed`, `hasToken`, instances/tab count), write-only token input, `Zero-dialog` toggle, `allowedDomains` editor, Connect/Disconnect per `instanceId`, kill switch, Web Store link, capability notice; `AuditList` per profile.
|
|
6081
|
+
- `session-card-badge` → `BrowserRelayBadge`: always-mounted `browser_relay_status` subscriber. The relay is GLOBAL (no pi-session linkage), so this module-store feed is what lets the hook-less `content-view` predicate `isLiveViewActive` see it.
|
|
6082
|
+
- `content-view` → `LiveViewTile`: one tile per `{instanceId, tabId}`; subscribe/unsubscribe lifecycle, JPEG frames, pointer/key/wheel → normalized `browser_relay_input`, no-frames + DevTools overlays.
|
|
6083
|
+
|
|
6084
|
+
## Bundled Package: deck3d
|
|
6085
|
+
|
|
6086
|
+
`packages/deck3d` (`@blackbelt-technology/pi-dashboard-deck3d`) — deterministic Markdown → one self-contained offline 3D `deck.html`. Independent CLI + pi skill; not part of dashboard runtime.
|
|
6087
|
+
|
|
6088
|
+
- Pipeline: markdown → schema-validated Deck IR (`deck.json`) → `deck.html` (three.js runtime + IR + subset Poppins inlined).
|
|
6089
|
+
- Harvest: `flowchart`/`sequenceDiagram` parsed in headless chromium at parse time (`mermaid@11.17.2` exact pin); output carries no diagram engine.
|
|
6090
|
+
- Tune region: `deck.json` `overrides` only; `slides[]` regenerated every parse; `validate` warns on edits outside `overrides`.
|
|
6091
|
+
- Check: `check <deck.html>` measures fit/legibility/overlap/occlusion/contrast headless at dpr 1; each finding carries an `overrides` suggestion.
|
|
6092
|
+
- Effects: `src/fx/` card-per-effect corpus + deterministic per-slide defaults (`fx list`).
|
|
6093
|
+
- Props: `src/props/` vendored CC0 search + Poly Pizza + sha256-pinned fetch into `.deck3d/props/`.
|
|
6094
|
+
- CLI `deck3d`: `parse | validate | render | build | check | snapshot | fx | props`. Skill: `.pi/skills/deck3d/SKILL.md`.
|
|
6095
|
+
- See `packages/deck3d/README.md`; change: add-deck3d-presentation-package.
|