@blackbelt-technology/pi-agent-dashboard 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -38
- package/docs/architecture.md +148 -2
- package/package.json +6 -4
- package/packages/extension/package.json +4 -3
- package/packages/extension/src/AGENTS.md +1 -0
- package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
- package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
- package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
- package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
- package/packages/extension/src/bridge-context.ts +21 -0
- package/packages/extension/src/bridge.ts +41 -6
- package/packages/extension/src/openspec-cli-shim.ts +173 -0
- package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
- package/packages/extension/src/provider-register.ts +180 -17
- package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
- package/packages/extension/src/session-sync.ts +9 -4
- package/packages/server/package.json +8 -8
- package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
- package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
- package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
- package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
- package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
- package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
- package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
- package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
- package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
- package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
- package/packages/server/src/browser-handlers/AGENTS.md +1 -1
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
- package/packages/server/src/browser-handlers/handler-context.ts +24 -13
- package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
- package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
- package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
- package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
- package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
- package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
- package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
- package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
- package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
- package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
- package/packages/server/src/embed-lifecycle/caps.ts +88 -0
- package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
- package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
- package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
- package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
- package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
- package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
- package/packages/server/src/event-wiring.ts +20 -0
- package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
- package/packages/server/src/goal/AGENTS.md +1 -0
- package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
- package/packages/server/src/goal/goal-supervisor.ts +5 -3
- package/packages/server/src/model-proxy/AGENTS.md +2 -2
- package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
- package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
- package/packages/server/src/model-proxy/internal-registry.ts +49 -23
- package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
- package/packages/server/src/pairing/browser-gateway.ts +40 -11
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
- package/packages/server/src/persistence/memory-event-store.ts +369 -23
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
- package/packages/server/src/routes/AGENTS.md +2 -2
- package/packages/server/src/routes/goal-routes.ts +14 -9
- package/packages/server/src/routes/models-introspection-routes.ts +10 -0
- package/packages/server/src/routes/system-routes.ts +16 -1
- package/packages/server/src/server.ts +216 -65
- package/packages/server/src/server.ts.AGENTS.md +1 -1
- package/packages/server/src/session/memory-session-manager.ts +4 -0
- package/packages/server/src/session/session-scanner.ts +9 -0
- package/packages/server/src/session/session-to-meta.ts +6 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/AGENTS.md +5 -3
- package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
- package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
- package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
- package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
- package/packages/shared/src/browser-protocol.ts +22 -0
- package/packages/shared/src/config.ts +70 -0
- package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
- package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
- package/packages/shared/src/models-json-reader.ts +98 -0
- package/packages/shared/src/platform/AGENTS.md +1 -1
- package/packages/shared/src/platform/paths.ts +12 -0
- package/packages/shared/src/session-meta.ts +9 -0
- package/packages/shared/src/types.ts +52 -1
- package/docs/AGENTS.md +0 -47
- package/packages/extension/AGENTS.md +0 -7
- package/packages/server/AGENTS.md +0 -7
- package/packages/shared/AGENTS.md +0 -7
- package/scripts/AGENTS.md +0 -38
|
@@ -27,39 +27,37 @@ import fastifyStatic from "@fastify/static";
|
|
|
27
27
|
import Fastify from "fastify";
|
|
28
28
|
import { registerAuthPlugin, validateWsUpgrade } from "./auth/auth-plugin.js";
|
|
29
29
|
import { registerBearerAuth } from "./auth/bearer-auth.js";
|
|
30
|
-
import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
|
|
31
|
-
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
32
|
-
import { writeConfigPartial } from "./config-api.js";
|
|
33
30
|
import { isCorsOriginAllowed } from "./auth/cors-origin.js";
|
|
34
31
|
import { registerCsp, resolveCspMode } from "./auth/csp.js";
|
|
32
|
+
import { ensureServerIdentity } from "./auth/identity.js";
|
|
33
|
+
import { ensureLocalToken, verifyLocalToken } from "./auth/local-token.js";
|
|
34
|
+
import { createNetworkGuard, isBypassedHost, isGenuinelyLocal } from "./auth/localhost-guard.js";
|
|
35
|
+
import { mintSpawnToken } from "./auth/spawn-token.js";
|
|
36
|
+
import { extractTicket, routeScopeForUrl, type WsRouteScope, WsTicketStore } from "./auth/ws-ticket.js";
|
|
37
|
+
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
38
|
+
import { writeConfigPartial } from "./config-api.js";
|
|
35
39
|
// pending-load-manager removed — server loads sessions directly via DirectoryService
|
|
36
40
|
import { createDirectoryService, type DirectoryService } from "./directory-service.js";
|
|
37
41
|
import { wireEvents } from "./event-wiring.js";
|
|
38
|
-
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
39
|
-
import { createEventLoopSpikeMetrics } from "./metrics/eventloop-spike-metrics.js";
|
|
40
42
|
import { createFileWatchManager } from "./file-watch-manager.js";
|
|
43
|
+
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
44
|
+
import { decorateGoalsWithSpend } from "./goal/decorate-goals-spend.js";
|
|
41
45
|
import { decideBudgetHalt } from "./goal/goal-budget-guard.js";
|
|
42
46
|
import { buildGoalReprime, primeGoalSession } from "./goal/goal-session-primer.js";
|
|
43
47
|
import { createGoalStatusProjector } from "./goal/goal-status-projector.js";
|
|
44
48
|
import { createGoalStore } from "./goal/goal-store.js";
|
|
45
49
|
import { createGoalSupervisor, type GoalDriverSpawnRequest, type GoalSupervisor } from "./goal/goal-supervisor.js";
|
|
46
50
|
import { createGoalVerdictAccumulator } from "./goal/goal-verdict-accumulator.js";
|
|
47
|
-
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
48
|
-
import { createHydrationMetrics } from "./metrics/hydration-metrics.js";
|
|
49
|
-
import { ensureServerIdentity } from "./auth/identity.js";
|
|
50
|
-
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
51
51
|
import { createLiveServerManager } from "./live-server/live-server-manager.js";
|
|
52
52
|
import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
53
|
-
import {
|
|
54
|
-
import {
|
|
55
|
-
import {
|
|
56
|
-
import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
|
|
57
|
-
import { createMetaPersistence, type MetaPersistence } from "./persistence/meta-persistence.js";
|
|
58
|
-
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
53
|
+
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
54
|
+
import { createEventLoopSpikeMetrics } from "./metrics/eventloop-spike-metrics.js";
|
|
55
|
+
import { createHydrationMetrics } from "./metrics/hydration-metrics.js";
|
|
59
56
|
import { createModelProxyAuthGate } from "./model-proxy/auth-gate.js";
|
|
60
57
|
import { getModelRegistry, getStreamSimpleFn } from "./model-proxy/registry-singleton.js";
|
|
61
58
|
import { createOpenSpecGroupStore, joinGroupIdsToOpenSpecData } from "./openspec/openspec-group-store.js";
|
|
62
59
|
import { PackageManagerWrapper } from "./package/package-manager-wrapper.js";
|
|
60
|
+
import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
|
|
63
61
|
import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
|
|
64
62
|
import { PairingManager } from "./pairing/pairing.js";
|
|
65
63
|
import { createPendingAttachRegistry } from "./pending/pending-attach-registry.js";
|
|
@@ -70,15 +68,14 @@ import { createPendingGoalLinkRegistry } from "./pending/pending-goal-link-regis
|
|
|
70
68
|
import { createPendingInitialPromptRegistry } from "./pending/pending-initial-prompt-registry.js";
|
|
71
69
|
import { createPendingResumeIntentRegistry } from "./pending/pending-resume-intent-registry.js";
|
|
72
70
|
import { createPendingWorktreeBaseRegistry } from "./pending/pending-worktree-base-registry.js";
|
|
71
|
+
import { createMemoryEventStore, type EventStore } from "./persistence/memory-event-store.js";
|
|
72
|
+
import { createMetaPersistence, type MetaPersistence } from "./persistence/meta-persistence.js";
|
|
73
|
+
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
74
|
+
import { createPreferencesStore, type PreferencesStore } from "./persistence/preferences-store.js";
|
|
73
75
|
import { PiCoreChecker } from "./pi/pi-core-checker.js";
|
|
74
76
|
import { PiCoreUpdater } from "./pi/pi-core-updater.js";
|
|
75
77
|
import { createPiGateway, type PiGateway } from "./pi/pi-gateway.js";
|
|
76
78
|
import { pluginIntentCache } from "./plugin-intent-cache.js";
|
|
77
|
-
import { createPreferencesStore, type PreferencesStore } from "./persistence/preferences-store.js";
|
|
78
|
-
import { spawnPiSession } from "./spawn-process/process-manager.js";
|
|
79
|
-
import { applyReattachPolicy } from "./session/reattach-placement.js";
|
|
80
|
-
import { reconcileSessionOrder } from "./session/reconcile-session-order.js";
|
|
81
|
-
import { resolveOrderKey } from "./session/resolve-order-key.js";
|
|
82
79
|
import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
|
|
83
80
|
import { registerDoctorRoutes } from "./routes/doctor-routes.js";
|
|
84
81
|
import { registerFileRoutes } from "./routes/file-routes.js";
|
|
@@ -109,21 +106,26 @@ import { registerProviderRoutes } from "./routes/provider-routes.js";
|
|
|
109
106
|
import { invalidateRecommendedCache, registerRecommendedRoutes } from "./routes/recommended-routes.js";
|
|
110
107
|
import { registerResourceActivationRoutes } from "./routes/resource-activation-routes.js";
|
|
111
108
|
import { registerSessionRoutes } from "./routes/session-routes.js";
|
|
109
|
+
import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycle-controller.js";
|
|
112
110
|
import { registerSystemRoutes } from "./routes/system-routes.js";
|
|
113
111
|
import { registerToolRoutes } from "./routes/tool-routes.js";
|
|
114
|
-
import {
|
|
112
|
+
import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
|
|
113
|
+
import { applyReattachPolicy } from "./session/reattach-placement.js";
|
|
114
|
+
import { reconcileSessionOrder } from "./session/reconcile-session-order.js";
|
|
115
|
+
import { resolveOrderKey } from "./session/resolve-order-key.js";
|
|
115
116
|
import { registerSessionApi } from "./session/session-api.js";
|
|
116
117
|
import { discoverAndBroadcastSessions } from "./session/session-bootstrap.js";
|
|
117
118
|
import { createSessionOrderManager, type SessionOrderManager } from "./session/session-order-manager.js";
|
|
118
119
|
import { scanAllSessions } from "./session/session-scanner.js";
|
|
119
120
|
import { sessionToMeta } from "./session/session-to-meta.js";
|
|
120
|
-
import {
|
|
121
|
+
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
122
|
+
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
123
|
+
import { spawnPiSession } from "./spawn-process/process-manager.js";
|
|
124
|
+
import { removePid, writePid } from "./spawn-process/server-pid.js";
|
|
121
125
|
import { createTerminalGateway, type TerminalGateway } from "./terminal/terminal-gateway.js";
|
|
122
126
|
import { createTerminalManager, type TerminalManager } from "./terminal/terminal-manager.js";
|
|
123
127
|
import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
|
|
124
128
|
import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
|
|
125
|
-
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
126
|
-
import { extractTicket, routeScopeForUrl, type WsRouteScope, WsTicketStore } from "./auth/ws-ticket.js";
|
|
127
129
|
|
|
128
130
|
export interface ServerConfig {
|
|
129
131
|
port: number;
|
|
@@ -210,6 +212,19 @@ export interface DashboardServer {
|
|
|
210
212
|
sessionOrderManager: SessionOrderManager;
|
|
211
213
|
}
|
|
212
214
|
|
|
215
|
+
/**
|
|
216
|
+
* Recovery reattach grace window (ms). After cold start, a recovery candidate
|
|
217
|
+
* whose bridge re-registers (comes alive) within this window is a survivor of a
|
|
218
|
+
* plain restart — not a genuine loss — so it is retracted from the offer and its
|
|
219
|
+
* on-disk liveness marker consumed. Keeper-carried sessions are gated
|
|
220
|
+
* synchronously at broadcast time; this window covers non-keeper (tmux / TUI /
|
|
221
|
+
* mDNS-discovery) bridges whose liveness is only revealed on async reattach.
|
|
222
|
+
* Sized above typical mDNS-discovery + WS-reconnect latency. In `auto` mode the
|
|
223
|
+
* resume itself is deferred by this window so a reattaching session is never
|
|
224
|
+
* double-spawned. See change: fix-recovery-offer-bridge-liveness-gate.
|
|
225
|
+
*/
|
|
226
|
+
const RECOVERY_REATTACH_GRACE_MS = 2500;
|
|
227
|
+
|
|
213
228
|
export async function createServer(config: ServerConfig): Promise<DashboardServer> {
|
|
214
229
|
// Ensure bridge extension is registered in pi's global settings
|
|
215
230
|
// (needed for bundled installs where pi can't discover it from package.json)
|
|
@@ -327,12 +342,36 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
327
342
|
console.log(`[dashboard] Session scan: ${scanResult.sessions.length} sessions, ${scanResult.cacheUpdates} cache updates`);
|
|
328
343
|
}
|
|
329
344
|
|
|
345
|
+
// Liveness-gated recovery (change: fix-recovery-offer-bridge-liveness-gate).
|
|
346
|
+
// Candidates still eligible to be OFFERED (`ask`) or RESUMED (`auto`), keyed
|
|
347
|
+
// by sessionId. Disk-only classification (`recoveryCandidates`) cannot tell a
|
|
348
|
+
// plain restart (process survived) from a crash (process gone). A candidate is
|
|
349
|
+
// removed from this map — and its on-disk marker consumed — the moment a
|
|
350
|
+
// process-carrier proves it alive: synchronously by the keeper reclaim
|
|
351
|
+
// (Class 1, in `start()`) or asynchronously when its bridge comes alive within
|
|
352
|
+
// `RECOVERY_REATTACH_GRACE_MS` (Class 2, via the `onChange` retract check
|
|
353
|
+
// below). After the grace window the map is finalized (cleared).
|
|
354
|
+
const liveRecoveryCandidates = new Map<string, DashboardSession>(
|
|
355
|
+
recoveryCandidates.map((c) => [c.id, c]),
|
|
356
|
+
);
|
|
357
|
+
let recoveryOfferBroadcast = false;
|
|
358
|
+
let recoveryGraceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
359
|
+
|
|
330
360
|
// Save per-session .meta.json on any change. The meta payload is an EXPLICIT
|
|
331
361
|
// field enumeration (`sessionToMeta`) written as a FULL overwrite — omitting a
|
|
332
362
|
// field there wipes it on the next unrelated save. See change: add-session-tags.
|
|
333
363
|
sessionManager.onChange = (sessionId: string, ctx) => {
|
|
334
364
|
const session = sessionManager.get(sessionId);
|
|
335
365
|
if (!session?.sessionFile) return;
|
|
366
|
+
// Class 2 liveness gate (change: fix-recovery-offer-bridge-liveness-gate).
|
|
367
|
+
// A pending recovery candidate that comes alive (its bridge reattached /
|
|
368
|
+
// process re-registered) is a plain-restart survivor, not a loss. Retract
|
|
369
|
+
// it: drop from the eligible set, consume its marker, and rebuild an
|
|
370
|
+
// already-broadcast offer. Keyed on the ended→alive fact, not
|
|
371
|
+
// `registerReason` — tmux/TUI/mDNS bridges re-register without one.
|
|
372
|
+
if (session.status !== "ended" && liveRecoveryCandidates.has(sessionId)) {
|
|
373
|
+
retractRecoveryCandidate(sessionId, "bridge-reattach");
|
|
374
|
+
}
|
|
336
375
|
metaPersistence.save(session.sessionFile, sessionToMeta(session));
|
|
337
376
|
// Order-map key for this session: the RESOLVED group path (parent repo
|
|
338
377
|
// for worktree sessions), the same key the client reads.
|
|
@@ -709,6 +748,62 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
709
748
|
browserGateway.onRecoveryResolve = () => {
|
|
710
749
|
pendingRecoveryOffer = null;
|
|
711
750
|
};
|
|
751
|
+
// The resume handler refuses a `continue` reopen while a candidate's liveness
|
|
752
|
+
// is still unresolved (grace window open), closing the Class-2 double-spawn
|
|
753
|
+
// race even for non-UI clients. Membership in `liveRecoveryCandidates` IS the
|
|
754
|
+
// pending signal: dead candidates leave when the window finalizes (map clear),
|
|
755
|
+
// reattached ones leave on retract. See change: fix-recovery-offer-bridge-liveness-gate.
|
|
756
|
+
browserGateway.isRecoveryLivenessPending = (sessionId: string) =>
|
|
757
|
+
liveRecoveryCandidates.has(sessionId);
|
|
758
|
+
|
|
759
|
+
// Epoch-ms deadline the ask-mode offer carries so the client can render a
|
|
760
|
+
// non-actionable "verifying…" state until Class-2 liveness is finalized.
|
|
761
|
+
// Set once at broadcast; reused when an offer is rebuilt on retract.
|
|
762
|
+
let recoveryGraceUntil: number | undefined;
|
|
763
|
+
|
|
764
|
+
// Build a recovery_offer wire message from the eligible candidate set.
|
|
765
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
766
|
+
function buildRecoveryOffer(
|
|
767
|
+
candidates: DashboardSession[],
|
|
768
|
+
): import("@blackbelt-technology/pi-dashboard-shared/browser-protocol.js").RecoveryOfferMessage {
|
|
769
|
+
return {
|
|
770
|
+
type: "recovery_offer",
|
|
771
|
+
candidates: candidates.map((s) => ({
|
|
772
|
+
sessionId: s.id,
|
|
773
|
+
name: s.name,
|
|
774
|
+
cwd: s.cwd,
|
|
775
|
+
model: s.model,
|
|
776
|
+
liveEpoch: s.liveEpoch,
|
|
777
|
+
})),
|
|
778
|
+
graceUntil: recoveryGraceUntil,
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Retract a still-pending recovery candidate proven alive (keeper reclaim or
|
|
783
|
+
// bridge reattach). Idempotent: no-op once the candidate has left the eligible
|
|
784
|
+
// set (already retracted, or the grace window finalized the map). Consumes the
|
|
785
|
+
// on-disk liveness marker exactly like dismiss / clean stop, so a later cold
|
|
786
|
+
// boot with no NEW unclean shutdown does not re-offer it. When an offer was
|
|
787
|
+
// already broadcast, the held/replayed offer is rebuilt so a client connecting
|
|
788
|
+
// afterward never sees the retracted candidate.
|
|
789
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
790
|
+
function retractRecoveryCandidate(sessionId: string, reason: string): void {
|
|
791
|
+
const cand = liveRecoveryCandidates.get(sessionId);
|
|
792
|
+
if (!cand) return;
|
|
793
|
+
liveRecoveryCandidates.delete(sessionId);
|
|
794
|
+
if (cand.sessionFile) metaPersistence.setLiveness(cand.sessionFile, { live: false });
|
|
795
|
+
console.info(
|
|
796
|
+
`[recovery] retracted candidate ${sessionId} (${reason}); ${liveRecoveryCandidates.size} still pending`,
|
|
797
|
+
);
|
|
798
|
+
if (!recoveryOfferBroadcast) return;
|
|
799
|
+
if (liveRecoveryCandidates.size === 0) {
|
|
800
|
+
pendingRecoveryOffer = null;
|
|
801
|
+
browserGateway.broadcastToAll(buildRecoveryOffer([]));
|
|
802
|
+
} else {
|
|
803
|
+
pendingRecoveryOffer = buildRecoveryOffer([...liveRecoveryCandidates.values()]);
|
|
804
|
+
browserGateway.broadcastToAll(pendingRecoveryOffer);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
712
807
|
|
|
713
808
|
// Plugin pi-message dispatch registry + raw-event subscribers.
|
|
714
809
|
// Populated by ServerPluginContext.registerPiHandler / onEvent (see the
|
|
@@ -1063,7 +1158,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1063
1158
|
// Folder-scoped goals: broadcast on mutation + REST surface.
|
|
1064
1159
|
// See change: add-goals-folder-page.
|
|
1065
1160
|
goalStore.subscribe((cwd, payload) => {
|
|
1066
|
-
|
|
1161
|
+
// Decorate with read-time spend so the WS path is not a raw second delivery
|
|
1162
|
+
// path. See change: fix-goal-detail-turns-and-spend.
|
|
1163
|
+
browserGateway.broadcastToAll({ type: "goals_update", cwd, goals: decorateGoalsWithSpend(payload.goals, sessionManager) });
|
|
1067
1164
|
});
|
|
1068
1165
|
// Stamp/clear goalId on a session: in-memory + .meta.json + broadcast.
|
|
1069
1166
|
const applyGoalIdToSession = (sessionId: string, goalId: string | null): void => {
|
|
@@ -1192,7 +1289,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1192
1289
|
}, GOAL_BOOT_RECONCILE_DELAY_MS);
|
|
1193
1290
|
bootReconcileTimer.unref?.();
|
|
1194
1291
|
|
|
1195
|
-
|
|
1292
|
+
// Embed-session-lifecycle: construct the reaper + observability metrics wired
|
|
1293
|
+
// to the live server components. Dormant unless config.embedLifecycle.enabled
|
|
1294
|
+
// (off by default) — construction/start is behavior-preserving on upgrade.
|
|
1295
|
+
// Reclaims the automation-produced ephemeral sessions #383 is about; the
|
|
1296
|
+
// acquire registry + caps are shared-layer modules the embed front constructs.
|
|
1297
|
+
// See change: add-embed-session-lifecycle.
|
|
1298
|
+
const embedLifecycle = createEmbedLifecycleController({
|
|
1299
|
+
config: () => loadConfig().embedLifecycle,
|
|
1300
|
+
listSessions: () => sessionManager.listAll(),
|
|
1301
|
+
getSubscriberCount: (id) => browserGateway.getSubscriberCount(id),
|
|
1302
|
+
listTerminalCwds: () => terminalManager.list().map((t) => t.cwd),
|
|
1303
|
+
hasPendingUiRequest: (id) => browserGateway.hasPendingUiRequest(id),
|
|
1304
|
+
killBySessionId: (id) => browserGateway.headlessPidRegistry.killBySessionId(id),
|
|
1305
|
+
sendStopAfterTurn: (id) =>
|
|
1306
|
+
piGateway.sendToSession(id, { type: "stop_after_turn", sessionId: id }),
|
|
1307
|
+
});
|
|
1308
|
+
|
|
1309
|
+
registerSystemRoutes(fastify, { sessionManager, preferencesStore, metaPersistence, config, networkGuard, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, embedLifecycle });
|
|
1196
1310
|
// GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
|
|
1197
1311
|
registerDoctorRoutes(fastify);
|
|
1198
1312
|
registerToolRoutes(fastify, { registry: getDefaultRegistry(), networkGuard });
|
|
@@ -1593,7 +1707,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1593
1707
|
try {
|
|
1594
1708
|
const { getKeeperManager } = await import("./spawn-process/process-manager.js");
|
|
1595
1709
|
browserGateway.headlessPidRegistry.setKeeperWriter(getKeeperManager());
|
|
1596
|
-
await browserGateway.headlessPidRegistry.cleanupKeeperOrphans();
|
|
1710
|
+
const keeperAliveIds = await browserGateway.headlessPidRegistry.cleanupKeeperOrphans();
|
|
1711
|
+
// Class 1 synchronous liveness gate: a candidate whose keeper+pi the
|
|
1712
|
+
// reclaim found alive was never lost — drop it before the offer is
|
|
1713
|
+
// built and consume its marker. Runs before the broadcast below.
|
|
1714
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
1715
|
+
for (const id of keeperAliveIds) {
|
|
1716
|
+
if (liveRecoveryCandidates.has(id)) {
|
|
1717
|
+
retractRecoveryCandidate(id, "keeper-alive");
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1597
1720
|
} catch (err) {
|
|
1598
1721
|
console.warn("[dashboard] keeper-manager wire-up failed (RPC dispatch disabled):", err);
|
|
1599
1722
|
}
|
|
@@ -2038,28 +2161,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2038
2161
|
}
|
|
2039
2162
|
|
|
2040
2163
|
idleTimer.start();
|
|
2164
|
+
// Start the embed-lifecycle reaper sweep (dormant unless the feature is
|
|
2165
|
+
// enabled). See change: add-embed-session-lifecycle.
|
|
2166
|
+
embedLifecycle.start();
|
|
2041
2167
|
|
|
2042
2168
|
// Cold-start recovery offer. Gated by `reopenSessionsAfterShutdown`:
|
|
2043
2169
|
// off → handled at classify time (candidates normalized to `ended`,
|
|
2044
|
-
// so `
|
|
2170
|
+
// so `liveRecoveryCandidates` is empty here — this block is skipped)
|
|
2045
2171
|
// ask → broadcast one recovery offer to all connected clients
|
|
2046
2172
|
// auto → resume every candidate via the existing resume flow
|
|
2047
2173
|
// Concurrent acceptances are deduped by `pendingResumeIntents`
|
|
2048
2174
|
// (last-write-wins) so a session spawns at most once.
|
|
2175
|
+
//
|
|
2176
|
+
// Liveness gate (change: fix-recovery-offer-bridge-liveness-gate): the
|
|
2177
|
+
// Class 1 keeper-alive candidates were already removed from
|
|
2178
|
+
// `liveRecoveryCandidates` above; the remaining set is offered/resumed.
|
|
2179
|
+
// A late bridge reattach within `RECOVERY_REATTACH_GRACE_MS` retracts a
|
|
2180
|
+
// candidate (Class 2, via the onChange check); after the window the map
|
|
2181
|
+
// is finalized so a legitimate offer for a genuine loss is never revoked.
|
|
2049
2182
|
// See change: reopen-sessions-after-shutdown.
|
|
2050
|
-
if (
|
|
2183
|
+
if (liveRecoveryCandidates.size > 0) {
|
|
2051
2184
|
const mode = recoveryMode;
|
|
2052
2185
|
if (mode === "ask") {
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
cwd: s.cwd,
|
|
2059
|
-
model: s.model,
|
|
2060
|
-
liveEpoch: s.liveEpoch,
|
|
2061
|
-
})),
|
|
2062
|
-
};
|
|
2186
|
+
// Deadline until which Class-2 liveness is unresolved; the client keeps
|
|
2187
|
+
// Reopen non-actionable until then. See change: fix-recovery-offer-bridge-liveness-gate.
|
|
2188
|
+
recoveryGraceUntil = Date.now() + RECOVERY_REATTACH_GRACE_MS;
|
|
2189
|
+
pendingRecoveryOffer = buildRecoveryOffer([...liveRecoveryCandidates.values()]);
|
|
2190
|
+
recoveryOfferBroadcast = true;
|
|
2063
2191
|
// Reaches any already-connected clients; onConnect replays to the rest.
|
|
2064
2192
|
browserGateway.broadcastToAll(pendingRecoveryOffer);
|
|
2065
2193
|
// Consume each offered candidate's on-disk liveness sentinel so the
|
|
@@ -2074,35 +2202,51 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2074
2202
|
// resumed session's next activity (event-wiring). Mirrors the
|
|
2075
2203
|
// marker clears in `recovery_dismiss` and clean `stop()`.
|
|
2076
2204
|
// See change: fix-recovery-offer-dismiss-and-phantom-reopen.
|
|
2077
|
-
for (const cand of
|
|
2205
|
+
for (const cand of liveRecoveryCandidates.values()) {
|
|
2078
2206
|
if (cand.sessionFile) metaPersistence.setLiveness(cand.sessionFile, { live: false });
|
|
2079
2207
|
}
|
|
2208
|
+
// Stop retracting once the grace window closes: a reattach after this
|
|
2209
|
+
// must NOT revoke a legitimate offer for a genuine loss.
|
|
2210
|
+
recoveryGraceTimer = setTimeout(() => { liveRecoveryCandidates.clear(); }, RECOVERY_REATTACH_GRACE_MS);
|
|
2211
|
+
recoveryGraceTimer.unref?.();
|
|
2080
2212
|
} else if (mode === "auto") {
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
cand.
|
|
2097
|
-
result.
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2213
|
+
// Defer the resume by the grace window so a session whose bridge
|
|
2214
|
+
// reattaches (Class 2) is retracted before we spawn — a second
|
|
2215
|
+
// `continue` for an already-alive sessionId double-registers it and
|
|
2216
|
+
// breaks message routing. Keeper-alive candidates (Class 1) were
|
|
2217
|
+
// already excluded above.
|
|
2218
|
+
recoveryGraceTimer = setTimeout(() => {
|
|
2219
|
+
void (async () => {
|
|
2220
|
+
const resumeConfig = loadConfig();
|
|
2221
|
+
const survivors = [...liveRecoveryCandidates.values()];
|
|
2222
|
+
liveRecoveryCandidates.clear();
|
|
2223
|
+
for (const cand of survivors) {
|
|
2224
|
+
if (!cand.sessionFile) continue;
|
|
2225
|
+
// Tag the resume intent so the ended→alive reattach branch keeps
|
|
2226
|
+
// the slot; dedupes concurrent acceptances. Mirrors the core of
|
|
2227
|
+
// handleResumeSession (no ws at cold start).
|
|
2228
|
+
pendingResumeIntents.record(cand.id, "keep");
|
|
2229
|
+
const result = await spawnPiSession(cand.cwd, {
|
|
2230
|
+
sessionFile: cand.sessionFile,
|
|
2231
|
+
mode: "continue",
|
|
2232
|
+
strategy: resumeConfig.spawnStrategy,
|
|
2233
|
+
});
|
|
2234
|
+
if (result.process && result.pid) {
|
|
2235
|
+
browserGateway.headlessPidRegistry.register(
|
|
2236
|
+
result.pid,
|
|
2237
|
+
cand.cwd,
|
|
2238
|
+
result.process,
|
|
2239
|
+
result.spawnToken,
|
|
2240
|
+
keeperOptsFromSpawnResult(result),
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
if (result.dashboardSpawned && result.success) {
|
|
2244
|
+
pendingDashboardSpawns.set(cand.cwd, (pendingDashboardSpawns.get(cand.cwd) ?? 0) + 1);
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
})();
|
|
2248
|
+
}, RECOVERY_REATTACH_GRACE_MS);
|
|
2249
|
+
recoveryGraceTimer.unref?.();
|
|
2106
2250
|
}
|
|
2107
2251
|
// mode === "off": no-op.
|
|
2108
2252
|
}
|
|
@@ -2115,6 +2259,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2115
2259
|
// Stop the dedicated ELD safety-net sampler + its histogram.
|
|
2116
2260
|
// See change: attribute-openspec-poll-eventloop-stalls.
|
|
2117
2261
|
try { eventLoopSampler.stop(); } catch { /* ignore */ }
|
|
2262
|
+
// Stop the embed-lifecycle reaper sweep.
|
|
2263
|
+
// See change: add-embed-session-lifecycle.
|
|
2264
|
+
try { embedLifecycle.stop(); } catch { /* ignore */ }
|
|
2118
2265
|
// Stop mDNS before closing
|
|
2119
2266
|
try {
|
|
2120
2267
|
if (mdnsBrowser) { mdnsBrowser.stop(); mdnsBrowser = null; }
|
|
@@ -2138,6 +2285,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2138
2285
|
// timers) so a create/stop cycle in one process leaves no stale timer.
|
|
2139
2286
|
// See change: add-goal-session-supervisor.
|
|
2140
2287
|
clearTimeout(bootReconcileTimer);
|
|
2288
|
+
// Cancel the recovery grace timer (ask: finalize-clear; auto: deferred
|
|
2289
|
+
// resume) so a create/stop cycle leaves no stale timer / late spawn.
|
|
2290
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
2291
|
+
if (recoveryGraceTimer) clearTimeout(recoveryGraceTimer);
|
|
2141
2292
|
goalSupervisor?.dispose();
|
|
2142
2293
|
pendingForkRegistry.dispose();
|
|
2143
2294
|
preferencesStore.flush();
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
# server.ts — index
|
|
2
2
|
|
|
3
|
-
Dashboard HTTP + WebSocket server. Exports `ServerConfig`, `DashboardServer`, `createServer(config)`. Wires Fastify + CORS (origin callback delegates to `isCorsOriginAllowed` in `cors-origin.ts`; trusted-network origins allowed for LAN-to-LAN switching — change: fix-remote-connect-cors-gates) + compress + auth, registers all route modules, session/terminal/editor managers, pi/browser gateways, event forwarding, mDNS discovery, zrok tunnel, plugin runtime, OpenSpec polling. ~2190 lines. host provides cross-plugin service `host.knownFolderCwds` (live getter: session cwds ∪ pinned dirs) via pluginServiceRegistry; kb-plugin consumes for cwd validation. Trusted plugin ctx gains `abortSpawnedRun({sessionId?,spawnToken?,graceful?})` (RENAMED from `abortAutomationRun` — generic spawned-run kill, goal is a 2nd caller; gate priority<=100): graceful sends `{type:"shutdown"}` hint THEN `killBySessionId` (mirrors handleShutdown — hint dropped when WS not OPEN); hard kills by sessionId else falls back to `killByToken`. See change: add-kb-folder-slot, fix-automation-stop-zombie-runs, add-goal-session-supervisor. `pluginSessionEndSubs` + `dispatchPluginSessionEnded` fan `sessionManager.onUnregister` to `ctx.onSessionEnded` subscribers AND the main-server `goalSupervisor.onDriverDeath` (C2a). Builds `goalSupervisor` (createGoalSupervisor): `spawnGoalDriver` (headless-forced, token+goalId register, continue-mode resume / fresh reprime), boot reconcile deferred 30s. goal-routes `abortGoalSupervision` + budget guard on cumulative `totalTurnsUsed`. See change: finalize-automation-run-on-session-death, add-goal-session-supervisor. `worktree_init_subscribe`/`_unsubscribe` handlers accept `cwd` (registry.subscribeCwd/unsubscribeCwd) in addition to `requestId`. See change: friendlier-worktree-init. `sessionManager.onChange` debounced `.meta.json` save delegates to `sessionToMeta(session)` (full-overwrite enumeration; extracted for testability). See change: add-session-tags. Plugin ctx `registerBrowserHandler` wrapper routes `type==="plugin_action"` to `browserGateway.registerPluginActionHandler(plugin.manifest.id, ...)` (manifest-authoritative pluginId, not self-declared) so plugins fan out; other custom types stay single-owner via `registerHandler`. See change: fix-plugin-action-fanout-and-handlers.
|
|
3
|
+
Dashboard HTTP + WebSocket server. Exports `ServerConfig`, `DashboardServer`, `createServer(config)`. Wires Fastify + CORS (origin callback delegates to `isCorsOriginAllowed` in `cors-origin.ts`; trusted-network origins allowed for LAN-to-LAN switching — change: fix-remote-connect-cors-gates) + compress + auth, registers all route modules, session/terminal/editor managers, pi/browser gateways, event forwarding, mDNS discovery, zrok tunnel, plugin runtime, OpenSpec polling. ~2190 lines. host provides cross-plugin service `host.knownFolderCwds` (live getter: session cwds ∪ pinned dirs) via pluginServiceRegistry; kb-plugin consumes for cwd validation. Trusted plugin ctx gains `abortSpawnedRun({sessionId?,spawnToken?,graceful?})` (RENAMED from `abortAutomationRun` — generic spawned-run kill, goal is a 2nd caller; gate priority<=100): graceful sends `{type:"shutdown"}` hint THEN `killBySessionId` (mirrors handleShutdown — hint dropped when WS not OPEN); hard kills by sessionId else falls back to `killByToken`. See change: add-kb-folder-slot, fix-automation-stop-zombie-runs, add-goal-session-supervisor. `pluginSessionEndSubs` + `dispatchPluginSessionEnded` fan `sessionManager.onUnregister` to `ctx.onSessionEnded` subscribers AND the main-server `goalSupervisor.onDriverDeath` (C2a). Builds `goalSupervisor` (createGoalSupervisor): `spawnGoalDriver` (headless-forced, token+goalId register, continue-mode resume / fresh reprime), boot reconcile deferred 30s. goal-routes `abortGoalSupervision` + budget guard on cumulative `totalTurnsUsed`. See change: finalize-automation-run-on-session-death, add-goal-session-supervisor. `worktree_init_subscribe`/`_unsubscribe` handlers accept `cwd` (registry.subscribeCwd/unsubscribeCwd) in addition to `requestId`. See change: friendlier-worktree-init. `sessionManager.onChange` debounced `.meta.json` save delegates to `sessionToMeta(session)` (full-overwrite enumeration; extracted for testability). See change: add-session-tags. Plugin ctx `registerBrowserHandler` wrapper routes `type==="plugin_action"` to `browserGateway.registerPluginActionHandler(plugin.manifest.id, ...)` (manifest-authoritative pluginId, not self-declared) so plugins fan out; other custom types stay single-owner via `registerHandler`. See change: fix-plugin-action-fanout-and-handlers. The `goalStore.subscribe` → `goals_update` broadcast now wraps `payload.goals` in `decorateGoalsWithSpend(...,sessionManager)` so the WS delivery path carries `totalSpendUsd` like the REST paths. See change: fix-goal-detail-turns-and-spend.
|
|
@@ -97,6 +97,10 @@ export function createMemorySessionManager(): SessionManager {
|
|
|
97
97
|
cost: existing.cost,
|
|
98
98
|
// Preserve user-set openspec assignment (not polled, set via dashboard UI)
|
|
99
99
|
attachedProposal: existing.attachedProposal,
|
|
100
|
+
// Preserve user-owned tags across a bridge reattach (not polled, set via
|
|
101
|
+
// dashboard UI). Without this the reattach onChange save wipes them from
|
|
102
|
+
// disk. See change: fix-tags-lost-on-bridge-reattach.
|
|
103
|
+
tags: existing.tags,
|
|
100
104
|
// Preserve context usage until bridge sends fresh data
|
|
101
105
|
contextTokens: existing.contextTokens,
|
|
102
106
|
contextWindow: existing.contextWindow,
|
|
@@ -69,6 +69,10 @@ function sessionFromMeta(
|
|
|
69
69
|
// See change: add-auto-session-naming.
|
|
70
70
|
nameSource: meta.nameSource,
|
|
71
71
|
source: (meta.source as SessionSource) ?? "tui",
|
|
72
|
+
// Restore the disposability marker so a restart never reclassifies an
|
|
73
|
+
// ephemeral session as durable (absent ⇒ durable) and lets it escape
|
|
74
|
+
// reaping forever. See change: add-embed-session-lifecycle.
|
|
75
|
+
lifecyclePolicy: meta.lifecyclePolicy,
|
|
72
76
|
status: (meta.status as DashboardSession["status"]) ?? "ended",
|
|
73
77
|
model: meta.model,
|
|
74
78
|
thinkingLevel: meta.thinkingLevel,
|
|
@@ -77,6 +81,11 @@ function sessionFromMeta(
|
|
|
77
81
|
// Seed last-activity from events.jsonl mtime so the session-card relative-time
|
|
78
82
|
// badge survives server restarts. See change: session-card-last-activity-badge.
|
|
79
83
|
lastActivityAt: readJsonlMtime(sessionFile),
|
|
84
|
+
// Seed the lifecycle at-rest mark from the same mtime so a rehydrated
|
|
85
|
+
// quiescent ephemeral session is immediately evaluable by the reaper's
|
|
86
|
+
// quiescence gate without waiting for a fresh run to settle (E14).
|
|
87
|
+
// See change: add-embed-session-lifecycle.
|
|
88
|
+
lastSettledAt: readJsonlMtime(sessionFile),
|
|
80
89
|
tokensIn: meta.tokensIn ?? 0,
|
|
81
90
|
tokensOut: meta.tokensOut ?? 0,
|
|
82
91
|
cacheRead: meta.cacheRead,
|
|
@@ -62,6 +62,12 @@ export function sessionToMeta(session: DashboardSession): SessionMeta {
|
|
|
62
62
|
// full .meta.json overwrite (not a merge) — omitting it wipes tags on the
|
|
63
63
|
// next unrelated save. See change: add-session-tags.
|
|
64
64
|
tags: session.tags,
|
|
65
|
+
// Persist the disposability marker. MUST be listed here because this save
|
|
66
|
+
// does a full .meta.json overwrite (not a merge) — omitting it wipes the
|
|
67
|
+
// marker, so a restart would reclassify an ephemeral session as durable
|
|
68
|
+
// (absent ⇒ durable) and it would escape reaping forever.
|
|
69
|
+
// See change: add-embed-session-lifecycle.
|
|
70
|
+
lifecyclePolicy: session.lifecyclePolicy,
|
|
65
71
|
cachedAt: Date.now(),
|
|
66
72
|
};
|
|
67
73
|
}
|
|
@@ -217,8 +217,14 @@ export interface HeadlessPidRegistry {
|
|
|
217
217
|
* registry entry doesn't yet exist are skipped (the bridge will
|
|
218
218
|
* register them on connect). No-op when no `keeperManager` was injected.
|
|
219
219
|
* See change: add-rpc-stdin-dispatch-with-keeper-sidecar (Phase 6).
|
|
220
|
+
*
|
|
221
|
+
* Returns the sessionIds of the keepers found alive (keeper PID + pi PID
|
|
222
|
+
* both live) so the caller can gate cold-start recovery: a session with a
|
|
223
|
+
* live reclaimed keeper was never lost and must NOT be offered for reopen.
|
|
224
|
+
* Empty when the scan was skipped (no keeper writer / unsafe test HOME) or
|
|
225
|
+
* no live keepers exist. See change: fix-recovery-offer-bridge-liveness-gate.
|
|
220
226
|
*/
|
|
221
|
-
cleanupKeeperOrphans(): Promise<
|
|
227
|
+
cleanupKeeperOrphans(): Promise<string[]>;
|
|
222
228
|
/**
|
|
223
229
|
* Inject the keeper writer / discoverer after construction. Necessary
|
|
224
230
|
* because `browser-gateway.ts` constructs the registry before the
|
|
@@ -500,12 +506,12 @@ export function createHeadlessPidRegistry(options?: HeadlessPidRegistryOptions):
|
|
|
500
506
|
return keeperWriter.writeRpcToSockPath(entry.keeperSockPath, line);
|
|
501
507
|
},
|
|
502
508
|
|
|
503
|
-
async cleanupKeeperOrphans(): Promise<
|
|
509
|
+
async cleanupKeeperOrphans(): Promise<string[]> {
|
|
504
510
|
if (isUnsafeTestHomeScan()) {
|
|
505
511
|
console.warn("[headless-pid-registry] cleanupKeeperOrphans() blocked: running under vitest with real HOME");
|
|
506
|
-
return;
|
|
512
|
+
return [];
|
|
507
513
|
}
|
|
508
|
-
if (!keeperWriter) return;
|
|
514
|
+
if (!keeperWriter) return [];
|
|
509
515
|
// KeeperManager.discoverExistingKeepers does the heavy lifting:
|
|
510
516
|
// unlinks stale sockets, SIGTERMs orphans whose pi child is dead.
|
|
511
517
|
// The registry only needs to know about live pairs so it can
|
|
@@ -525,8 +531,12 @@ export function createHeadlessPidRegistry(options?: HeadlessPidRegistryOptions):
|
|
|
525
531
|
persist();
|
|
526
532
|
}
|
|
527
533
|
}
|
|
534
|
+
// Report the live keeper sessionIds so cold-start recovery can gate on
|
|
535
|
+
// them. See change: fix-recovery-offer-bridge-liveness-gate.
|
|
536
|
+
return live.map((k) => k.sessionId);
|
|
528
537
|
} catch (err) {
|
|
529
538
|
console.warn("[headless-pid-registry] cleanupKeeperOrphans failed", err);
|
|
539
|
+
return [];
|
|
530
540
|
}
|
|
531
541
|
},
|
|
532
542
|
|
|
@@ -4,11 +4,12 @@ Files in this directory. One row per source file.
|
|
|
4
4
|
|
|
5
5
|
| File | Purpose |
|
|
6
6
|
|------|---------|
|
|
7
|
+
| `__tests__/nightly-workflow-contract.test.ts` | Repo-lint safety contract for the nightly (change: add-nightly-verdaccio-build). Asserts `nightly.yml`: every `npm publish` is `--dry-run` or carries `--registry http://localhost` (no public write), no `softprops/action-gh-release`, no tag `git push`, no version-bump `git commit`, and the electron job passes a loopback `registry_url`. Also asserts `_electron-build.yml` keeps its pure-artifact-producer invariant (no `npm publish`/Release/tag push) despite the `registry_url` addition. |
|
|
7
8
|
| `archive-types.ts` | `ArchiveEntry` interface — OpenSpec archive dir row (name, date, done artifacts). Shared server↔client. |
|
|
8
9
|
| `bridge-register.ts` | Shared bridge registration: `findBundledExtension(baseDir)` + `registerBridgeExtension(path)`; non-destructive cleanup, AppImage guard. Used by server startup and Electron wizard. |
|
|
9
|
-
| `browser-protocol.ts` | Server↔Browser WebSocket message contracts. Exports `ServerToBrowserMessage` + `BrowserToServerMessage` unions, `BootstrapStateSnapshot`, `Workspace`, `SpawnFailureCode`, follow-up-queue bridge-buffer messages, re-exports batch `ask_user` types from `protocol.ts`. `RoleRemoveBrowserMessage` (`role_remove`) added to `BrowserToServerMessage` — server gateway forwards it to the session bridge (change: add-custom-roles-ui). `SpawnSessionBrowserMessage.initialPrompt` = optional first prompt dispatched on session_register (no-hook Initialize pre-injects `/skill:project-init`). See change: project-init-skill-and-profiles. `SubagentResyncRequestBrowserMessage` (`subagent_resync_request` `{sessionId,agentId}`) added to `BrowserToServerMessage`; server forwards to owning bridge. See change: fix-subagent-live-detail-reliability (D2). `WorktreeInitSubscribe`/`Unsubscribe` messages carry optional `cwd` (stable per-checkout key) alongside optional `requestId`; new `ActiveWorktreeInit` type ({cwd,phase,startedAt,lastLine?,code?}) for `GET /active-inits`. `SetSessionTagsBrowserMessage` (`set_session_tags` `{sessionId,tags}`) added to `BrowserToServerMessage`. `PackageOperationCompleteMessage.action` union widened with `"reset"` (reset-to-npm composite op reuses `moveId` + `partialSuccess`). See changes: friendlier-worktree-init, add-session-tags, reset-override-to-npm. `PluginActionErrorMessage` (`plugin_action_error` `{pluginId,action?,error}`) added to `ServerToBrowserMessage` — gateway sends it to the sender when a `plugin_action` targets a pluginId with no registered handler. See change: fix-plugin-action-fanout-and-handlers. |
|
|
10
|
+
| `browser-protocol.ts` | Server↔Browser WebSocket message contracts. Exports `ServerToBrowserMessage` + `BrowserToServerMessage` unions, `BootstrapStateSnapshot`, `Workspace`, `SpawnFailureCode`, follow-up-queue bridge-buffer messages, re-exports batch `ask_user` types from `protocol.ts`. `RoleRemoveBrowserMessage` (`role_remove`) added to `BrowserToServerMessage` — server gateway forwards it to the session bridge (change: add-custom-roles-ui). `SpawnSessionBrowserMessage.initialPrompt` = optional first prompt dispatched on session_register (no-hook Initialize pre-injects `/skill:project-init`). See change: project-init-skill-and-profiles. `SubagentResyncRequestBrowserMessage` (`subagent_resync_request` `{sessionId,agentId}`) added to `BrowserToServerMessage`; server forwards to owning bridge. See change: fix-subagent-live-detail-reliability (D2). `WorktreeInitSubscribe`/`Unsubscribe` messages carry optional `cwd` (stable per-checkout key) alongside optional `requestId`; new `ActiveWorktreeInit` type ({cwd,phase,startedAt,lastLine?,code?}) for `GET /active-inits`. `SetSessionTagsBrowserMessage` (`set_session_tags` `{sessionId,tags}`) added to `BrowserToServerMessage`. `RemoveTagGloballyBrowserMessage` (`remove_tag_globally` `{tag}`) added to `BrowserToServerMessage` — server fans the strip out to every carrying session (see change: sidebar-tag-collapse-and-delete). `PackageOperationCompleteMessage.action` union widened with `"reset"` (reset-to-npm composite op reuses `moveId` + `partialSuccess`). See changes: friendlier-worktree-init, add-session-tags, reset-override-to-npm. `PluginActionErrorMessage` (`plugin_action_error` `{pluginId,action?,error}`) added to `ServerToBrowserMessage` — gateway sends it to the sender when a `plugin_action` targets a pluginId with no registered handler. See change: fix-plugin-action-fanout-and-handlers. |
|
|
10
11
|
| `changelog-types.ts` | `ChangelogBullet` / `Release` / `Response` types for parsed CHANGELOG.md responses. See change: pi-update-whats-new-panel. |
|
|
11
|
-
| `config.ts` | Dashboard config loader. `loadConfig()` reads `~/.pi/dashboard/config.json` via `CONFIG_FILE`; `ensureConfig()` seeds defaults. Exports `DashboardConfig`, `AuthConfig`, `OpenSpecPollConfig`, `ModelProxyConfig`, `SpawnStrategy`, `ReattachPlacement`, `parseReattachPlacement`, `parseModelProxyConfig`, `getPluginConfig`, `clampSpawnRegisterTimeoutMs`. v2 (support-zrok-v2): `tunnel.zrok` gains `reservedName?`/`persistent?` (default false, in DEFAULTS + `normalizeTunnelConfig`); legacy `reservedToken` preserved on read but NOT promoted to `reservedName`. External-editor `EditorConfig`/`parseEditorConfigForTest` removed (change: remove-external-editor-integration). `ModelProxyConfig` + `parseModelProxyConfig` gain optional `preferredModels?: string[]` (ordered, drop non-string/empty, omit empty) + `modelAliases?: Record<string,string>` (drop non-string/empty key or value, omit empty). See change: fix-and-prefer-model-proxy-resolution. |
|
|
12
|
+
| `config.ts` | Dashboard config loader. `loadConfig()` reads `~/.pi/dashboard/config.json` via `CONFIG_FILE`; `ensureConfig()` seeds defaults. Exports `DashboardConfig`, `AuthConfig`, `OpenSpecPollConfig`, `ModelProxyConfig`, `SpawnStrategy`, `ReattachPlacement`, `parseReattachPlacement`, `parseModelProxyConfig`, `getPluginConfig`, `clampSpawnRegisterTimeoutMs`. v2 (support-zrok-v2): `tunnel.zrok` gains `reservedName?`/`persistent?` (default false, in DEFAULTS + `normalizeTunnelConfig`); legacy `reservedToken` preserved on read but NOT promoted to `reservedName`. External-editor `EditorConfig`/`parseEditorConfigForTest` removed (change: remove-external-editor-integration). `ModelProxyConfig` + `parseModelProxyConfig` gain optional `preferredModels?: string[]` (ordered, drop non-string/empty, omit empty) + `modelAliases?: Record<string,string>` (drop non-string/empty key or value, omit empty). See change: fix-and-prefer-model-proxy-resolution. Adds `EmbedLifecycleConfig` + `DEFAULT_EMBED_LIFECYCLE` (`config.embedLifecycle`, default-inert `enabled:false` + idle/hardCeiling/grace/sweep/register seconds + per-visitor & global caps), parsed clamped via `parseEmbedLifecycleConfig`. See change: add-embed-session-lifecycle. |
|
|
12
13
|
| `credential-detect.ts` | Detects configured LLM-provider credential. `hasAnyProviderCredential(homeDir?)` OR-merges `~/.pi/agent/settings.json` + `~/.pi/agent/auth.json`; never logs/returns secret values. `inspectedCredentialFiles(homeDir?)` returns the two probed paths. |
|
|
13
14
|
| `dashboard-paths.ts` | Single-source path helpers for dashboard runtime dirs. `getDashboardConfigDir` → `~/.pi/dashboard/`. `getDashboardServerLogPath` → `~/.pi/dashboard/server.log` (live server log). `getManagedDir` re-export → `~/.pi-dashboard/`. `getInstallerLogPath` → `~/.pi-dashboard/server.log` (legacy installer log, distinct from server log). All accept `DashboardPathsEnv = { homedir? }` override for test isolation. See change: harvest-bootstrap-survivor-fixes. Adds `resolvePiSessionsDir(env?)`: resolves pi sessions root dashboard scans. Precedence: `config.json#piSessionsDir` → `PI_CODING_AGENT_SESSION_DIR` → `PI_CODING_AGENT_DIR`+`/sessions` → literal `~/.pi/agent/sessions`. Trims each layer; blank falls through; leading `~/` expands against `homedir`. `DashboardPathsEnv` gains `piSessionsDir?`, `sessionDirEnv?`, `agentDirEnv?` (latter two test seams). Reads `PI_CODING_AGENT_DIR` directly, not pi-core import (pi-core `.d.ts` barrel unresolvable under `moduleResolution: bundler`). See change: configurable-pi-sessions-dir. |
|
|
14
15
|
| `dashboard-starter.ts` | Identifies dashboard launcher. `DashboardStarter` = `Bridge` | `Standalone` | `Electron`. `parseDashboardStarter(env)` reads `DASHBOARD_STARTER` (default `Standalone`). `LaunchSource` lowercase alias; `parseLaunchSource(env)` maps to `electron` | `bridge` | `standalone` for `/api/health` arm-gating. |
|
|
@@ -24,6 +25,7 @@ Files in this directory. One row per source file.
|
|
|
24
25
|
| `managed-paths.ts` | Single source of truth for managed install dir `~/.pi-dashboard/`. Constants `MANAGED_DIR`, `MANAGED_BIN`, `PI_SETTINGS_PATH` reflect live env at load. Getters `getManagedDir(env?)`, `getManagedBin(env?)`, `getPiSettingsPath(env?)` accept optional `{ homedir }` override for tests. |
|
|
25
26
|
| `model-id.ts` | First-slash model-id parser. `parseModelId(label)` → `{provider, modelId}`: provider = before first `/`, modelId = whole remainder (may contain `/`); no leading provider (`""`, `"gpt-4"`, `"/x"`) → `provider === ""`. Mirrors goal-plugin `parseModelLabel`; converges model-proxy routes off truncating `split("/", 2)`. See change: fix-and-prefer-model-proxy-resolution. |
|
|
26
27
|
| `mdns-discovery.ts` | mDNS `_pi-dashboard._tcp` advertise + discover. `advertiseDashboard(port, piPort)`, `stopAdvertising()`, `discoverDashboard(timeout?)`, `discoverFallback(port)`, `discoverDashboardWithFallback(configPort)`, `createBrowser()` (EventEmitter `server-up`/`server-down`), `pickBestHost(service)` (DNS-safe fallback), `isLocalService(service)`. Exports `DiscoveredServer`, `DashboardBrowser`. |
|
|
28
|
+
| `models-json-reader.ts` | ONE shared pure reader for user-authored `~/.pi/agent/models.json`, consumed by BOTH registry paths (extension `provider-register.ts` + server `registry-singleton.readModels`) so flatten/precedence cannot diverge. `flattenModelsJson(parsed)` → stamped `NativeModelEntry[]`: native nested `providers.<name>.models[]` (parent key wins over in-entry `provider`) + legacy top-level array + `{models:[]}`; deduped by `provider/id`, nested wins on collision. Per-provider defensive (non-array `models` → skip block, no throw); pure (callers own file I/O + parse `console.warn`). Exports `NativeModelEntry` (carries `thinkingLevelMap?`/`compat?`). See change: honor-native-models-json-metadata. |
|
|
27
29
|
| `node-version.ts` | Single source of truth for Node-version predicates. `isAffectedNode(version)` flags nodejs/node#58515 Fastify-affected ranges (v22.0–v22.18, v24.1–v24.2). `isOutOfEnginesRange(version)` true when `<22.19.0` OR `>=26`, mirrors package.json#engines.node. `isUsableNodeVersion(version)` = `!isOutOfEnginesRange && !isAffectedNode`, rejects unparseable strings. Accept: 22.19+, 24.0, 24.3+, 25.x. Reject: 21.x, 22.0–22.18, 24.1–24.2, 26+. Consumed by server `node-guard.ts` (re-export) + electron `dependency-detector.ts` (`isUsableNodeVersion`). See change: unify-node-version-gate. |
|
|
28
30
|
| `openspec-activity-detector.ts` | Detects OpenSpec activity from tool-execution events. `detectOpenSpecActivity(toolName, args)` returns `{ phase?, changeName?, isActive? }` via skill-path / change-path / CLI-flag regexes. Exports `isValidOpenSpecChangeSlug(name)` (lowercase kebab, ≤64 chars, `[a-z]`-first). |
|
|
29
31
|
| `openspec-design-evidence.ts` | Local-evidence override for OpenSpec `design` artifact. `evaluateLocalDesignSatisfaction(changeDir, probe)` runs R1 design*.md → R2 `design/`+*.md → R3 `tasks.md` checkbox, short-circuit. `createFsDesignEvidenceProbe()` returns fs-backed `DesignEvidenceProbe`. Promote-only; design-only. |
|
|
@@ -46,5 +48,5 @@ Files in this directory. One row per source file.
|
|
|
46
48
|
| `stats-extractor.ts` | Extracts `StatsData` (tokensIn/out, cost, turnUsage, optional contextUsage) from a `turn_end` event's `message.usage`. Exports `StatsData`, `extractTurnStats(event, contextUsage?)`. Returns null when no usage present. |
|
|
47
49
|
| `tunnel-provider.ts` | Tunnel ("Gateway") provider abstraction types. Exports `TunnelProvider` interface (`id`, `kind` child\|daemon, `supportsMode`, `detectBinary`, `isEnrolled`, `connect`, `disconnect`, `status`), `TunnelProviderId`/`TunnelKind`/`TunnelMode`/`EndpointKind`, `TunnelEndpoint`/`ProviderEndpoints`/`ProviderStatus`/`TunnelConnectOpts` (v2: `reservedName?`/`persistent?`), `PROVIDER_MODES`/`PROVIDER_KIND` matrices, `providerSupportsMode()`. zrok/ngrok public-only child; zerotier private-only daemon; tailscale both daemon. See change: add-tunnel-providers, support-zrok-v2. |
|
|
48
50
|
| `terminal-types.ts` | Terminal emulator shared types. Exports `TerminalSession` (id, cwd, shell, status, title, `ephemeral` flag for inline cards) and `TerminalControlMessage` (resize | title) control frame union. |
|
|
49
|
-
| `types.ts` | Core dashboard shared type surface. Exports `DashboardSession`, `DashboardEvent`, `FlowInfo`, `CommandInfo`, `ModelInfo`, `ProviderInfo`, `OpenSpecChange`/`OpenSpecConfig`, `FlowState`/`FlowAgentState` (`cost?` = per-agent USD from `flow_agent_complete.result.cost`, sibling of `tokens`; see change surface-flow-agent-cost)/`NodeKind`, `ArchitectState`, `GoalRecord`/`GoalsFile`, `ApiResponse`, `ViewTarget`, extension UI module + decorator unions (`ExtensionUiModule`, `DecoratorDescriptor`), and `deriveChangeState`. Plus workflow + schema-version constants (`CORE_WORKFLOWS`, `EXPANDED_WORKFLOWS`, `OPENSPEC_GROUPS_SCHEMA_VERSION`, `GOALS_SCHEMA_VERSION`, `GOAL_VERDICTS_CAP`, `GOAL_RESPAWNS_CAP`). `GoalRecordStatus` gains `respawning`+`failed` (visible non-terminal / terminal breaker verdict). `GoalRecord` gains supervisor fields: `autoRespawn?`, `respawns?:GoalRespawn[]`, `generation?`, `statusReason?`, `inFlightSpawn?:GoalInFlightSpawn`, `currentDriverBaselineTurns?` (progress baseline). New types `GoalRespawn` (`{at,sessionId,reason:"resume"\|"fresh",madeProgress}`), `GoalInFlightSpawn` (`{spawnToken,generation,startedAt}`). See change: add-goal-session-supervisor. |
|
|
51
|
+
| `types.ts` | Core dashboard shared type surface. Exports `DashboardSession`, `DashboardEvent`, `FlowInfo`, `CommandInfo`, `ModelInfo`, `ProviderInfo`, `OpenSpecChange`/`OpenSpecConfig`, `FlowState`/`FlowAgentState` (`cost?` = per-agent USD from `flow_agent_complete.result.cost`, sibling of `tokens`; see change surface-flow-agent-cost)/`NodeKind`, `ArchitectState`, `GoalRecord`/`GoalsFile`, `ApiResponse`, `ViewTarget`, extension UI module + decorator unions (`ExtensionUiModule`, `DecoratorDescriptor`), and `deriveChangeState`. Plus workflow + schema-version constants (`CORE_WORKFLOWS`, `EXPANDED_WORKFLOWS`, `OPENSPEC_GROUPS_SCHEMA_VERSION`, `GOALS_SCHEMA_VERSION`, `GOAL_VERDICTS_CAP`, `GOAL_RESPAWNS_CAP`). `GoalRecordStatus` gains `respawning`+`failed` (visible non-terminal / terminal breaker verdict). `GoalRecord` gains supervisor fields: `autoRespawn?`, `respawns?:GoalRespawn[]`, `generation?`, `statusReason?`, `inFlightSpawn?:GoalInFlightSpawn`, `currentDriverBaselineTurns?` (progress baseline). New types `GoalRespawn` (`{at,sessionId,reason:"resume"\|"fresh",madeProgress}`), `GoalInFlightSpawn` (`{spawnToken,generation,startedAt}`). See change: add-goal-session-supervisor. `GoalRecord` gains `totalSpendUsd?:number` — server-derived at read time (Σ linked `DashboardSession.cost`), never persisted / never bridge-sent (same convention as `groupId`). See change: fix-goal-detail-turns-and-spend. `SessionSource`+`"embed"`; new `LifecyclePolicy`(`"ephemeral"`/`"durable"`); `DashboardSession`+`lifecyclePolicy?`(absent⇒durable, persisted)+non-persisted `lastSettledAt?`/`lastRunStartedAt?`(reaper at-rest, mtime-seeded). See change: add-embed-session-lifecycle. |
|
|
50
52
|
| `zrok-env.ts` | Pure `readZrokEnvironment({homedir,fs})` returning `{found, kind: v2\|v1\|null, path, env, reason}`. Prefers `~/.zrok2/environment.json` over `~/.zrok/environment.json`. Never throws. Consumed by `tunnel.ts#loadZrokEnv` and `doctor-core.ts` zrok-environment check so runtime and diagnostic agree. See change: add-tunnel-diagnostic-checks. |
|