@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.md +47 -6
- package/docs/architecture.md +1369 -63
- package/package.json +14 -9
- package/packages/extension/package.json +5 -3
- package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
- package/packages/extension/src/bridge-handlers/instance.ts +10 -1
- package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +41 -28
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +80 -6
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +30 -7
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +77 -6
- package/packages/extension/src/model-refresh.ts +69 -0
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +159 -20
- package/packages/extension/src/provider-register.ts +59 -18
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +1 -1
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-sync.ts +42 -12
- package/packages/extension/src/vault-delivery.ts +11 -1
- package/packages/server/package.json +8 -8
- package/packages/server/src/access/access-grants.ts +61 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- package/packages/server/src/access/containment-gate.ts +55 -17
- package/packages/server/src/access/cwd-verdict.ts +3 -3
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
- package/packages/server/src/access/planes.ts +106 -1
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/yolo-session.ts +54 -2
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/auth/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +44 -25
- package/packages/server/src/auth/auth.ts +24 -4
- package/packages/server/src/auth/bearer-auth.ts +52 -12
- package/packages/server/src/auth/cors-origin.ts +76 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +105 -9
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +69 -18
- package/packages/server/src/auth/localhost-guard.ts +48 -10
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
- package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-storage.ts +6 -1
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +111 -11
- package/packages/server/src/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +210 -39
- package/packages/server/src/config-api.ts +23 -1
- package/packages/server/src/config-snapshot.ts +48 -1
- package/packages/server/src/directory-service.ts +160 -54
- package/packages/server/src/event-wiring.ts +143 -108
- package/packages/server/src/git-worktree/git-operations.ts +44 -10
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
- package/packages/server/src/identity/http-road-classification.ts +13 -1
- package/packages/server/src/identity/ws-message-scope.ts +1 -0
- package/packages/server/src/identity/ws-road-classification.ts +1 -0
- package/packages/server/src/known-server-moves.ts +36 -15
- package/packages/server/src/lib/browse-roots.ts +118 -17
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-md-target.ts +4 -0
- package/packages/server/src/lifecycle/recovery-server.ts +65 -18
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +224 -17
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +162 -17
- package/packages/server/src/live-server/live-static.ts +228 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
- package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +141 -267
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/provider-probe.ts +8 -2
- package/packages/server/src/pairing/browser-gateway.ts +188 -12
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +34 -4
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/persistence/preferences-store.ts +9 -0
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/host-project-trust.ts +14 -6
- package/packages/server/src/pi/pi-gateway.ts +191 -21
- package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/routes/access-routes.ts +159 -9
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +329 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
- package/packages/server/src/routes/folder-project-routes.ts +18 -12
- package/packages/server/src/routes/git-routes.ts +319 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +189 -91
- package/packages/server/src/routes/live-server-routes.ts +378 -15
- package/packages/server/src/routes/local-proof-routes.ts +14 -0
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +379 -28
- package/packages/server/src/routes/package-routes.ts +58 -10
- package/packages/server/src/routes/pairing-routes.ts +146 -10
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +15 -2
- package/packages/server/src/routes/resource-activation-routes.ts +18 -4
- package/packages/server/src/routes/session-routes.ts +51 -4
- package/packages/server/src/routes/system-routes.ts +84 -15
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/server.ts +648 -137
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/memory-session-manager.ts +7 -0
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/session-load-worker.ts +11 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
- package/packages/server/src/terminal/terminal-manager.ts +54 -46
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +2 -0
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/browser-protocol.ts +148 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/config.ts +372 -53
- package/packages/shared/src/containment-guard.ts +35 -0
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +2 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
- package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +94 -27
- package/packages/shared/src/live-server.ts +141 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/mdns-discovery.ts +25 -6
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-poller.ts +3 -2
- package/packages/shared/src/pairing-knock-client.ts +44 -4
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
- package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
- package/packages/shared/src/pi-trust-mirror.ts +29 -3
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +14 -8
- package/packages/shared/src/platform/process.ts +48 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/protocol.ts +40 -1
- package/packages/shared/src/recommended-extensions.ts +18 -0
- package/packages/shared/src/recovery-timing.ts +27 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +55 -8
- package/packages/shared/src/route-tiers.ts +55 -1
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-launcher.ts +9 -1
- package/packages/shared/src/server-pinning.ts +55 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tool-registry/definitions.ts +5 -5
- package/packages/shared/src/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/types.ts +66 -0
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +15 -0
- package/packages/shared/src/ws-message-tiers.ts +1 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-only bookkeeping that ties cold disk hydration to the bridge register:
|
|
3
|
+
* - a fingerprint of the hydrated branch, so a later register can skip the
|
|
4
|
+
* wipe when it is provably the same branch (and the store is untouched);
|
|
5
|
+
* - the leaf id the last bridge register reported (the bridge-learned skip);
|
|
6
|
+
* - a per-session register generation, so a hydration that was started (or
|
|
7
|
+
* resolved) before a register never inserts its stale result.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately NOT on `DashboardSession`, which is broadcast to every browser.
|
|
10
|
+
*
|
|
11
|
+
* See change: fix-large-session-resume-replay (D5, D6).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
createReplayExitController,
|
|
16
|
+
type ReplayExitController,
|
|
17
|
+
type ReplayExitControllerOptions,
|
|
18
|
+
} from "./replay-exit-controller.js";
|
|
19
|
+
|
|
20
|
+
/** Bridge-supplied `leafEntryId` is an untrusted string: bound it. */
|
|
21
|
+
const LEAF_ENTRY_ID_MAX = 128;
|
|
22
|
+
|
|
23
|
+
interface HydrationFingerprint {
|
|
24
|
+
entryCount: number;
|
|
25
|
+
leafEntryId: string;
|
|
26
|
+
/** Highest store seq right after the hydration insert. */
|
|
27
|
+
storeMaxSeq: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SkipWipeInput {
|
|
31
|
+
eventCount: number | undefined;
|
|
32
|
+
/** Already validated with `validLeafEntryId`. */
|
|
33
|
+
leafEntryId: string | undefined;
|
|
34
|
+
liveTailOpen: boolean | undefined;
|
|
35
|
+
hasEvents: boolean;
|
|
36
|
+
storeMaxSeq: number;
|
|
37
|
+
/** `lastEntryCount` + leaf the previous BRIDGE register reported. */
|
|
38
|
+
bridgeLearned: { entryCount: number | undefined; leafEntryId: string | undefined };
|
|
39
|
+
fingerprint: HydrationFingerprint | undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type SkipWipeReason =
|
|
43
|
+
| "bridge-learned"
|
|
44
|
+
| "hydration-learned"
|
|
45
|
+
| "no-event-count"
|
|
46
|
+
| "no-leaf"
|
|
47
|
+
| "no-events"
|
|
48
|
+
| "no-match";
|
|
49
|
+
|
|
50
|
+
export function validLeafEntryId(v: unknown): string | undefined {
|
|
51
|
+
return typeof v === "string" && v.length >= 1 && v.length <= LEAF_ENTRY_ID_MAX ? v : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Pure skip-wipe decision. A skip needs a register carrying a valid `leafEntryId`. */
|
|
55
|
+
export function decideSkipWipe(i: SkipWipeInput): { skip: boolean; reason: SkipWipeReason } {
|
|
56
|
+
if (i.eventCount === undefined) return { skip: false, reason: "no-event-count" };
|
|
57
|
+
if (i.leafEntryId === undefined) return { skip: false, reason: "no-leaf" };
|
|
58
|
+
if (!i.hasEvents) return { skip: false, reason: "no-events" };
|
|
59
|
+
// Bridge-learned: the store was built by that bridge's own replay, so no
|
|
60
|
+
// `liveTailOpen` / `storeMaxSeq` check applies (unlike the hydration arm below,
|
|
61
|
+
// whose store holds fabricated closed-tail ends and can be touched afterwards).
|
|
62
|
+
if (i.bridgeLearned.entryCount === i.eventCount && i.bridgeLearned.leafEntryId === i.leafEntryId) {
|
|
63
|
+
return { skip: true, reason: "bridge-learned" };
|
|
64
|
+
}
|
|
65
|
+
const fp = i.fingerprint;
|
|
66
|
+
if (
|
|
67
|
+
fp &&
|
|
68
|
+
fp.entryCount === i.eventCount &&
|
|
69
|
+
fp.leafEntryId === i.leafEntryId &&
|
|
70
|
+
i.liveTailOpen === false &&
|
|
71
|
+
fp.storeMaxSeq === i.storeMaxSeq
|
|
72
|
+
) {
|
|
73
|
+
return { skip: true, reason: "hydration-learned" };
|
|
74
|
+
}
|
|
75
|
+
return { skip: false, reason: "no-match" };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Replay-mode controller + hydration bookkeeping, built once in `createServer`
|
|
79
|
+
* and shared by `wireEvents`, the browser gateway and the subscribe handler. */
|
|
80
|
+
export interface ReplayState {
|
|
81
|
+
controller: ReplayExitController;
|
|
82
|
+
hydration: HydrationState;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createReplayState(controllerOpts?: ReplayExitControllerOptions): ReplayState {
|
|
86
|
+
return { controller: createReplayExitController(controllerOpts), hydration: createHydrationState() };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
interface HydrationState {
|
|
90
|
+
/**
|
|
91
|
+
* A cold hydration just rebuilt the store: drop the bridge-learned pair (the
|
|
92
|
+
* rebuilt store has fabricated closed-tail ends, so the bridge-learned arm
|
|
93
|
+
* must not skip over it) and record the fingerprint when the leaf is known.
|
|
94
|
+
*/
|
|
95
|
+
markHydrated(sessionId: string, fp: HydrationFingerprint | undefined): void;
|
|
96
|
+
getFingerprint(sessionId: string): HydrationFingerprint | undefined;
|
|
97
|
+
clearFingerprint(sessionId: string): void;
|
|
98
|
+
/**
|
|
99
|
+
* Count + leaf the last bridge register reported (the bridge-learned skip).
|
|
100
|
+
* Kept here, not on the session record: `register()` rebuilds that record on
|
|
101
|
+
* every re-register, so a field on it never survives to the next comparison.
|
|
102
|
+
*/
|
|
103
|
+
setBridgeLearned(sessionId: string, learned: { entryCount: number; leafEntryId: string | undefined }): void;
|
|
104
|
+
getBridgeLearned(sessionId: string): { entryCount: number | undefined; leafEntryId: string | undefined };
|
|
105
|
+
/** Current register generation (0 = never registered / released). */
|
|
106
|
+
generation(sessionId: string): number;
|
|
107
|
+
/** A register happened: every hydration started before it is now stale. */
|
|
108
|
+
bumpRegister(sessionId: string): number;
|
|
109
|
+
/** Unregister: drop the fingerprint + generation (the bridge-learned count + leaf stay so a reconnect can still match them). */
|
|
110
|
+
release(sessionId: string): void;
|
|
111
|
+
/** Session removed: drop everything held for it. */
|
|
112
|
+
forget(sessionId: string): void;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function createHydrationState(): HydrationState {
|
|
116
|
+
const fingerprints = new Map<string, HydrationFingerprint>();
|
|
117
|
+
const bridgeLearned = new Map<string, { entryCount: number; leafEntryId: string | undefined }>();
|
|
118
|
+
const generations = new Map<string, number>();
|
|
119
|
+
// Globally unique values: a released-then-re-registered session can never
|
|
120
|
+
// reuse a generation a still-running hydration captured.
|
|
121
|
+
let counter = 0;
|
|
122
|
+
return {
|
|
123
|
+
markHydrated: (id, fp) => {
|
|
124
|
+
bridgeLearned.delete(id);
|
|
125
|
+
if (fp) fingerprints.set(id, fp);
|
|
126
|
+
else fingerprints.delete(id);
|
|
127
|
+
},
|
|
128
|
+
getFingerprint: (id) => fingerprints.get(id),
|
|
129
|
+
clearFingerprint: (id) => { fingerprints.delete(id); },
|
|
130
|
+
setBridgeLearned: (id, learned) => { bridgeLearned.set(id, learned); },
|
|
131
|
+
getBridgeLearned: (id) => bridgeLearned.get(id) ?? { entryCount: undefined, leafEntryId: undefined },
|
|
132
|
+
generation: (id) => generations.get(id) ?? 0,
|
|
133
|
+
bumpRegister: (id) => {
|
|
134
|
+
const next = ++counter;
|
|
135
|
+
generations.set(id, next);
|
|
136
|
+
return next;
|
|
137
|
+
},
|
|
138
|
+
release: (id) => {
|
|
139
|
+
fingerprints.delete(id);
|
|
140
|
+
generations.delete(id);
|
|
141
|
+
},
|
|
142
|
+
forget: (id) => {
|
|
143
|
+
fingerprints.delete(id);
|
|
144
|
+
bridgeLearned.delete(id);
|
|
145
|
+
generations.delete(id);
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
@@ -378,6 +378,13 @@ export function createMemorySessionManager(
|
|
|
378
378
|
statsExtractorVersion: existing.statsExtractorVersion,
|
|
379
379
|
// Preserve user-set openspec assignment (not polled, set via dashboard UI)
|
|
380
380
|
attachedProposal: existing.attachedProposal,
|
|
381
|
+
// A live replace-suggestion (and the names the user already dismissed)
|
|
382
|
+
// must survive a bridge reconnect: they are in-memory only, so
|
|
383
|
+
// dropping them here would lose the pending dialog on every
|
|
384
|
+
// reconnect. The replay itself neither raises nor clears them.
|
|
385
|
+
// See change: fix-large-session-resume-replay (D3).
|
|
386
|
+
pendingReplaceProposal: existing.pendingReplaceProposal,
|
|
387
|
+
rejectedReplaceProposals: existing.rejectedReplaceProposals,
|
|
381
388
|
// Preserve user-owned tags across a bridge reattach (not polled, set via
|
|
382
389
|
// dashboard UI). Without this the reattach onChange save wipes them from
|
|
383
390
|
// disk. See change: fix-tags-lost-on-bridge-reattach.
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session bridge replay mode: membership, fallback exit timers, and the
|
|
3
|
+
* bookkeeping a windowed, abortable exit flush needs.
|
|
4
|
+
*
|
|
5
|
+
* A bridge replay normally ends on `replay_complete`. For bridges that mark
|
|
6
|
+
* replayed events (`event_forward.replay`) the timers here only bound WHEN the
|
|
7
|
+
* exit work runs if `replay_complete` is lost; classification of a marked event
|
|
8
|
+
* does not depend on them. For old, unmarked bridges they are the fallback:
|
|
9
|
+
* - idle: no processed bridge message for `idleMs` (one `setImmediate`
|
|
10
|
+
* re-check, so input already read from the socket is handled first);
|
|
11
|
+
* - cap: `capMs` after the register, whatever keeps arriving.
|
|
12
|
+
* One record per session; a new `begin` cancels the previous register's timers,
|
|
13
|
+
* so a stale timer can never end a newer replay.
|
|
14
|
+
*
|
|
15
|
+
* The record outlives the exit (skip flag + flush bookkeeping live on it) until
|
|
16
|
+
* `release` (unregister / remove).
|
|
17
|
+
*
|
|
18
|
+
* See change: fix-large-session-resume-replay (D2).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export type ReplayExitCause = "complete" | "idle" | "cap" | "unregister";
|
|
22
|
+
|
|
23
|
+
export const REPLAY_IDLE_MS = 5_000;
|
|
24
|
+
export const REPLAY_CAP_MS = 60_000;
|
|
25
|
+
/** Keepalive cadence for subscribers waiting on a bridge replay (= cold-load heartbeat). */
|
|
26
|
+
const REPLAY_KEEPALIVE_MS = 10_000;
|
|
27
|
+
|
|
28
|
+
type Timer = ReturnType<typeof setTimeout>;
|
|
29
|
+
|
|
30
|
+
interface ReplayRecord {
|
|
31
|
+
active: boolean;
|
|
32
|
+
idleTimer: Timer | null;
|
|
33
|
+
capTimer: Timer | null;
|
|
34
|
+
lastTouchAt: number;
|
|
35
|
+
/** Register skipped the wipe: marked events are never inserted until the next `begin`. */
|
|
36
|
+
skipped: boolean;
|
|
37
|
+
flushEpoch: number;
|
|
38
|
+
/** A wipe happened (or events were stored) and no flush has completed since. */
|
|
39
|
+
flushPending: boolean;
|
|
40
|
+
/** Subscribers waiting for the replay; each stops its keepalive. */
|
|
41
|
+
waiters: Set<() => void>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ReplayExitControllerOptions {
|
|
45
|
+
idleMs?: number;
|
|
46
|
+
capMs?: number;
|
|
47
|
+
keepaliveMs?: number;
|
|
48
|
+
now?: () => number;
|
|
49
|
+
setTimeout?: (fn: () => void, ms: number) => Timer;
|
|
50
|
+
clearTimeout?: (t: Timer) => void;
|
|
51
|
+
setImmediate?: (fn: () => void) => void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ReplayExitController {
|
|
55
|
+
/** Sessions in bridge replay mode. Membership is owned by this controller. */
|
|
56
|
+
readonly replayingSessions: Set<string>;
|
|
57
|
+
readonly keepaliveMs: number;
|
|
58
|
+
/** Set by the owner of the exit work (`exitReplay`). Called once per exit. */
|
|
59
|
+
setOnExit(fn: (sessionId: string, cause: ReplayExitCause) => void): void;
|
|
60
|
+
begin(sessionId: string, opts: { skipped: boolean }): void;
|
|
61
|
+
touch(sessionId: string): void;
|
|
62
|
+
/** A marked event arrived after an exit: re-enter replay mode. Returns whether it did. */
|
|
63
|
+
reopen(sessionId: string): boolean;
|
|
64
|
+
/** `replay_complete`. No-op when the replay already exited. */
|
|
65
|
+
complete(sessionId: string): void;
|
|
66
|
+
/** Unregister / remove: exit with cause `unregister` (if active), drop the record. */
|
|
67
|
+
release(sessionId: string): void;
|
|
68
|
+
isSkipped(sessionId: string): boolean;
|
|
69
|
+
isFlushPending(sessionId: string): boolean;
|
|
70
|
+
/** Start a flush: stales any older flush, returns its staleness probe + completion. */
|
|
71
|
+
startFlush(sessionId: string): { isStale: () => boolean; finish: () => void };
|
|
72
|
+
/** Register a waiting subscriber. Returns an idempotent remover (does not call `stop`). */
|
|
73
|
+
addWaiter(sessionId: string, stop: () => void): () => void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function createReplayExitController(opts: ReplayExitControllerOptions = {}): ReplayExitController {
|
|
77
|
+
const idleMs = opts.idleMs ?? REPLAY_IDLE_MS;
|
|
78
|
+
const capMs = opts.capMs ?? REPLAY_CAP_MS;
|
|
79
|
+
const keepaliveMs = opts.keepaliveMs ?? REPLAY_KEEPALIVE_MS;
|
|
80
|
+
const now = opts.now ?? (() => Date.now());
|
|
81
|
+
const setT = opts.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
82
|
+
const clearT = opts.clearTimeout ?? ((t) => clearTimeout(t));
|
|
83
|
+
const setImm = opts.setImmediate ?? ((fn) => { setImmediate(fn); });
|
|
84
|
+
const replayingSessions = new Set<string>();
|
|
85
|
+
const records = new Map<string, ReplayRecord>();
|
|
86
|
+
let onExit: (sessionId: string, cause: ReplayExitCause) => void = () => {};
|
|
87
|
+
|
|
88
|
+
function clearTimers(rec: ReplayRecord): void {
|
|
89
|
+
if (rec.idleTimer) clearT(rec.idleTimer);
|
|
90
|
+
if (rec.capTimer) clearT(rec.capTimer);
|
|
91
|
+
rec.idleTimer = null;
|
|
92
|
+
rec.capTimer = null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function stopWaiters(rec: ReplayRecord): void {
|
|
96
|
+
const waiters = [...rec.waiters];
|
|
97
|
+
rec.waiters.clear();
|
|
98
|
+
for (const stop of waiters) {
|
|
99
|
+
try { stop(); } catch { /* a waiter must never break the exit */ }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** First exit wins: later ones find `active` false and no-op. */
|
|
104
|
+
function exit(sessionId: string, rec: ReplayRecord, cause: ReplayExitCause): void {
|
|
105
|
+
if (!rec.active) return;
|
|
106
|
+
rec.active = false;
|
|
107
|
+
clearTimers(rec);
|
|
108
|
+
replayingSessions.delete(sessionId);
|
|
109
|
+
// A subscriber was waiting on this replay: it must get the flush's terminal
|
|
110
|
+
// batch even if nothing else marked a flush pending.
|
|
111
|
+
if (rec.waiters.size > 0) rec.flushPending = true;
|
|
112
|
+
stopWaiters(rec);
|
|
113
|
+
onExit(sessionId, cause);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function armIdle(sessionId: string, rec: ReplayRecord, delay: number): void {
|
|
117
|
+
if (rec.idleTimer) clearT(rec.idleTimer);
|
|
118
|
+
rec.idleTimer = setT(() => {
|
|
119
|
+
rec.idleTimer = null;
|
|
120
|
+
if (!rec.active || records.get(sessionId) !== rec) return;
|
|
121
|
+
// Let input already read from the socket be handled once, then re-check.
|
|
122
|
+
setImm(() => {
|
|
123
|
+
if (!rec.active || records.get(sessionId) !== rec) return;
|
|
124
|
+
const quiet = now() - rec.lastTouchAt;
|
|
125
|
+
if (quiet >= idleMs) exit(sessionId, rec, "idle");
|
|
126
|
+
else armIdle(sessionId, rec, idleMs - quiet);
|
|
127
|
+
});
|
|
128
|
+
}, delay);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
replayingSessions,
|
|
133
|
+
keepaliveMs,
|
|
134
|
+
setOnExit(fn) { onExit = fn; },
|
|
135
|
+
|
|
136
|
+
begin(sessionId, { skipped }) {
|
|
137
|
+
let rec = records.get(sessionId);
|
|
138
|
+
if (!rec) {
|
|
139
|
+
rec = { active: false, idleTimer: null, capTimer: null, lastTouchAt: 0, skipped: false, flushEpoch: 0, flushPending: false, waiters: new Set() };
|
|
140
|
+
records.set(sessionId, rec);
|
|
141
|
+
}
|
|
142
|
+
clearTimers(rec);
|
|
143
|
+
rec.active = true;
|
|
144
|
+
rec.skipped = skipped;
|
|
145
|
+
rec.flushEpoch++;
|
|
146
|
+
if (!skipped) rec.flushPending = true;
|
|
147
|
+
rec.lastTouchAt = now();
|
|
148
|
+
replayingSessions.add(sessionId);
|
|
149
|
+
armIdle(sessionId, rec, idleMs);
|
|
150
|
+
const r = rec;
|
|
151
|
+
rec.capTimer = setT(() => {
|
|
152
|
+
r.capTimer = null;
|
|
153
|
+
if (records.get(sessionId) === r) exit(sessionId, r, "cap");
|
|
154
|
+
}, capMs);
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
touch(sessionId) {
|
|
158
|
+
const rec = records.get(sessionId);
|
|
159
|
+
if (rec?.active) rec.lastTouchAt = now();
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
reopen(sessionId) {
|
|
163
|
+
const rec = records.get(sessionId);
|
|
164
|
+
if (!rec || rec.active || rec.skipped) return false;
|
|
165
|
+
rec.active = true;
|
|
166
|
+
rec.flushPending = true;
|
|
167
|
+
// A flush still draining from the earlier exit no longer covers the events
|
|
168
|
+
// this reopened replay will store: stale it, so its completion cannot clear
|
|
169
|
+
// the pending flag the next exit must honour.
|
|
170
|
+
rec.flushEpoch++;
|
|
171
|
+
rec.lastTouchAt = now();
|
|
172
|
+
replayingSessions.add(sessionId);
|
|
173
|
+
armIdle(sessionId, rec, idleMs);
|
|
174
|
+
return true;
|
|
175
|
+
},
|
|
176
|
+
|
|
177
|
+
complete(sessionId) {
|
|
178
|
+
const rec = records.get(sessionId);
|
|
179
|
+
if (rec) exit(sessionId, rec, "complete");
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
release(sessionId) {
|
|
183
|
+
const rec = records.get(sessionId);
|
|
184
|
+
if (!rec) return;
|
|
185
|
+
rec.flushEpoch++;
|
|
186
|
+
if (rec.active) exit(sessionId, rec, "unregister");
|
|
187
|
+
else stopWaiters(rec);
|
|
188
|
+
clearTimers(rec);
|
|
189
|
+
records.delete(sessionId);
|
|
190
|
+
replayingSessions.delete(sessionId);
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
isSkipped(sessionId) {
|
|
194
|
+
return records.get(sessionId)?.skipped === true;
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
isFlushPending(sessionId) {
|
|
198
|
+
return records.get(sessionId)?.flushPending === true;
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
startFlush(sessionId) {
|
|
202
|
+
const rec = records.get(sessionId);
|
|
203
|
+
if (!rec) return { isStale: () => false, finish: () => {} };
|
|
204
|
+
const epoch = ++rec.flushEpoch;
|
|
205
|
+
return {
|
|
206
|
+
isStale: () => records.get(sessionId) !== rec || rec.flushEpoch !== epoch,
|
|
207
|
+
finish: () => {
|
|
208
|
+
if (records.get(sessionId) === rec && rec.flushEpoch === epoch) rec.flushPending = false;
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
addWaiter(sessionId, stop) {
|
|
214
|
+
const rec = records.get(sessionId);
|
|
215
|
+
if (!rec) return () => {};
|
|
216
|
+
const r = rec;
|
|
217
|
+
r.waiters.add(stop);
|
|
218
|
+
return () => { r.waiters.delete(stop); };
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -107,7 +107,14 @@ type RetainedTranscriptEvents = Array<{
|
|
|
107
107
|
*/
|
|
108
108
|
export type RetainedTranscriptHydration =
|
|
109
109
|
| { cancelled: true }
|
|
110
|
-
| {
|
|
110
|
+
| {
|
|
111
|
+
cancelled: false;
|
|
112
|
+
events: RetainedTranscriptEvents;
|
|
113
|
+
state: RetainedTranscriptState;
|
|
114
|
+
/** Skip-wipe fingerprint source (see `LoadResult`). */
|
|
115
|
+
entryCount?: number;
|
|
116
|
+
leafEntryId?: string;
|
|
117
|
+
};
|
|
111
118
|
|
|
112
119
|
/**
|
|
113
120
|
* The one `DirectoryService` method the hydration read needs. Narrowed to a
|
|
@@ -247,5 +254,5 @@ export async function readRetainedTranscript(
|
|
|
247
254
|
);
|
|
248
255
|
return { cancelled: false, events: [], state };
|
|
249
256
|
}
|
|
250
|
-
return { cancelled: false, events: out.events, state };
|
|
257
|
+
return { cancelled: false, events: out.events, state, entryCount: out.entryCount, leafEntryId: out.leafEntryId };
|
|
251
258
|
}
|
|
@@ -73,11 +73,20 @@ export interface SessionLoadResult {
|
|
|
73
73
|
/** Parsed entry count — telemetry for the hydration sample. Omitted on the
|
|
74
74
|
* failure path. Additive; not part of the event-parity contract. */
|
|
75
75
|
entryCount?: number;
|
|
76
|
+
/** Id of the last branch entry (server reader rule) — the skip-wipe
|
|
77
|
+
* fingerprint's leaf. Omitted when that entry has no string id.
|
|
78
|
+
* See change: fix-large-session-resume-replay (D5). */
|
|
79
|
+
leafEntryId?: string;
|
|
76
80
|
/** Max timestamp over ALL transcript entries. Only set in `"diff-events"`
|
|
77
81
|
* mode; used to clamp an ended session's open Bash window. */
|
|
78
82
|
lastEntryTs?: number;
|
|
79
83
|
}
|
|
80
84
|
|
|
85
|
+
function leafIdOf(entries: ReadonlyArray<{ id?: unknown }>): string | undefined {
|
|
86
|
+
const id = entries.length > 0 ? entries[entries.length - 1].id : undefined;
|
|
87
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
81
90
|
/**
|
|
82
91
|
* Pure parse + replay + projection. Safe on the main thread (fallback) or
|
|
83
92
|
* inside a `worker_threads` Worker (normal path). Mirrors the prior in-process
|
|
@@ -100,10 +109,10 @@ export function loadAndReplay(req: SessionLoadRequest): SessionLoadResult {
|
|
|
100
109
|
: loadSessionEntries(sessionFile as string);
|
|
101
110
|
if (mode === "diff-events") {
|
|
102
111
|
const { events, lastEntryTs } = projectDiffEvents(sessionId, entries, { maxStringSize });
|
|
103
|
-
return { jobId, success: true, events, entryCount: entries.length, lastEntryTs };
|
|
112
|
+
return { jobId, success: true, events, entryCount: entries.length, leafEntryId: leafIdOf(entries), lastEntryTs };
|
|
104
113
|
}
|
|
105
114
|
const events = replayEntriesAsEvents(sessionId, entries, knownContextWindow).map((m) => m.event);
|
|
106
|
-
return { jobId, success: true, events, entryCount: entries.length };
|
|
115
|
+
return { jobId, success: true, events, entryCount: entries.length, leafEntryId: leafIdOf(entries) };
|
|
107
116
|
} catch (err: any) {
|
|
108
117
|
const error = err?.code === "ENOENT" ? "file_not_found" : (err?.message ?? "parse_error");
|
|
109
118
|
return { jobId, success: false, events: [], error };
|
|
@@ -8,7 +8,12 @@ import { EventEmitter } from "node:events";
|
|
|
8
8
|
import os from "node:os";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import type { ChildProcess } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
isProcessAlive,
|
|
13
|
+
killPidWithGroup,
|
|
14
|
+
killProcess,
|
|
15
|
+
killProcessGroup,
|
|
16
|
+
} from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
|
|
12
17
|
import { isUnsafeTestHomeScan } from "../auth/test-env-guard.js";
|
|
13
18
|
import { readJsonFile, writeJsonFile } from "../persistence/json-store.js";
|
|
14
19
|
|
|
@@ -315,15 +320,15 @@ export function createHeadlessPidRegistry(options?: HeadlessPidRegistryOptions):
|
|
|
315
320
|
killedSomething = true;
|
|
316
321
|
} catch { /* pi may already be dead */ }
|
|
317
322
|
}
|
|
318
|
-
// Fallback
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
//
|
|
323
|
+
// Fallback after a 200 ms grace: terminate the keeper's whole process
|
|
324
|
+
// GROUP (keeper + pi + pi's children — pi is spawned non-detached by the
|
|
325
|
+
// keeper, so it shares the keeper's group). Gated on the GROUP still
|
|
326
|
+
// existing, not on keeper liveness: the keeper auto-exits with pi, but
|
|
327
|
+
// pi's orphaned children (long bash calls, MCP servers) stay in the
|
|
328
|
+
// group. killProcessGroup is a no-op once the group is gone and
|
|
329
|
+
// escalates SIGTERM → SIGKILL. See issue #912.
|
|
323
330
|
setTimeout(() => {
|
|
324
|
-
|
|
325
|
-
try { killPidWithGroup(keeperPid, "SIGTERM"); } catch { /* ignore */ }
|
|
326
|
-
}
|
|
331
|
+
void killProcessGroup(keeperPid, { timeoutMs: 2000 }).catch(() => undefined);
|
|
327
332
|
}, 200).unref?.();
|
|
328
333
|
// If pi was unknown (bridge never connected), fall through to
|
|
329
334
|
// killing the keeper directly with SIGKILL escalation so the
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { DEFAULT_TERMINALS_CONFIG } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
6
7
|
import { stripDashboardHeapFlag } from "@blackbelt-technology/pi-dashboard-shared/heap-flags.js";
|
|
7
8
|
import type { TerminalControlMessage, TerminalSession } from "@blackbelt-technology/pi-dashboard-shared/terminal-types.js";
|
|
8
9
|
import type { IPty } from "node-pty";
|
|
@@ -76,28 +77,27 @@ const TOMBSTONE_CAP = 64;
|
|
|
76
77
|
const RELEASED_TTL_MS = 60_000;
|
|
77
78
|
|
|
78
79
|
/**
|
|
79
|
-
* PTY bounds (B7). Each live terminal costs a ring buffer plus a real OS
|
|
80
|
-
* process, so an authenticated client looping `create_terminal`
|
|
81
|
-
* memory/PIDs. Defaults
|
|
80
|
+
* PTY bounds (B7, D3). Each live terminal costs a ring buffer plus a real OS
|
|
81
|
+
* shell process, so an authenticated client looping `create_terminal` /
|
|
82
|
+
* `open_inline_terminal` could exhaust memory/PIDs. Defaults come from
|
|
83
|
+
* `DEFAULT_TERMINALS_CONFIG` in shared `config.ts` (the `terminals.*` block).
|
|
82
84
|
* See change: harden-server-capability-bounds.
|
|
83
85
|
*/
|
|
84
|
-
|
|
85
|
-
export const DEFAULT_MAX_TERMINALS_PER_CWD = 16;
|
|
86
|
-
/** A terminal with no client attached and no PTY output for this long is reaped. */
|
|
87
|
-
export const DEFAULT_IDLE_REAP_MS = 6 * 60 * 60 * 1000;
|
|
88
|
-
const DEFAULT_REAP_INTERVAL_MS = 60_000;
|
|
86
|
+
const DEFAULT_REAP_INTERVAL_MS = 30_000;
|
|
89
87
|
|
|
90
|
-
/** Thrown by `spawn
|
|
88
|
+
/** Thrown by `spawn`, BEFORE any shell starts, when a concurrent-terminal cap would be exceeded. */
|
|
91
89
|
export class TerminalLimitError extends Error {
|
|
92
|
-
readonly scope: "global" | "
|
|
93
|
-
|
|
90
|
+
readonly scope: "global" | "owner";
|
|
91
|
+
readonly limit: number;
|
|
92
|
+
constructor(scope: "global" | "owner", limit: number) {
|
|
94
93
|
super(
|
|
95
94
|
scope === "global"
|
|
96
95
|
? `terminal limit reached (${limit} concurrent terminals)`
|
|
97
|
-
: `terminal limit reached for this
|
|
96
|
+
: `terminal limit reached for this user (${limit} concurrent terminals)`,
|
|
98
97
|
);
|
|
99
98
|
this.name = "TerminalLimitError";
|
|
100
99
|
this.scope = scope;
|
|
100
|
+
this.limit = limit;
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
103
|
|
|
@@ -196,8 +196,11 @@ interface TerminalEntry {
|
|
|
196
196
|
clients: Set<WebSocket>;
|
|
197
197
|
/** True once the user has sent any input keystroke to this PTY. */
|
|
198
198
|
sawInput: boolean;
|
|
199
|
-
/**
|
|
200
|
-
|
|
199
|
+
/**
|
|
200
|
+
* Orphan clock for ephemeral (inline) PTYs: ms epoch of spawn or of the last
|
|
201
|
+
* client detach. Meaningful only while no client is attached.
|
|
202
|
+
*/
|
|
203
|
+
orphanSince: number;
|
|
201
204
|
/** Set once the reaper has issued a kill, so a slow exit is not re-killed every sweep. */
|
|
202
205
|
reaping?: boolean;
|
|
203
206
|
}
|
|
@@ -213,12 +216,12 @@ export interface TerminalManagerOptions {
|
|
|
213
216
|
bufferSize?: number;
|
|
214
217
|
/** Byte budget for captured transcripts. See change: preserve-inline-terminal-transcript. */
|
|
215
218
|
transcriptCapBytes?: number;
|
|
216
|
-
/** Global
|
|
217
|
-
|
|
218
|
-
/** Per-
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
|
|
219
|
+
/** Global cap on live PTYs. See change: harden-server-capability-bounds. */
|
|
220
|
+
maxConcurrent?: number;
|
|
221
|
+
/** Per-owner cap (`{iss,sub}` equality); ownerless PTYs count toward the global cap only. */
|
|
222
|
+
maxPerOwner?: number;
|
|
223
|
+
/** Orphaned inline PTY reap threshold in ms. Tab terminals are never reaped. */
|
|
224
|
+
inlineOrphanTtlMs?: number;
|
|
222
225
|
/** Reaper sweep period in ms. */
|
|
223
226
|
reapIntervalMs?: number;
|
|
224
227
|
}
|
|
@@ -264,9 +267,9 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
264
267
|
const entries = new Map<string, TerminalEntry>();
|
|
265
268
|
const bufferSize = options?.bufferSize ?? DEFAULT_BUFFER_SIZE;
|
|
266
269
|
const transcriptCapBytes = options?.transcriptCapBytes ?? DEFAULT_TRANSCRIPT_CAP_BYTES;
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
const
|
|
270
|
+
const maxConcurrent = options?.maxConcurrent ?? DEFAULT_TERMINALS_CONFIG.maxConcurrent;
|
|
271
|
+
const maxPerOwner = options?.maxPerOwner ?? DEFAULT_TERMINALS_CONFIG.maxPerOwner;
|
|
272
|
+
const inlineOrphanTtlMs = options?.inlineOrphanTtlMs ?? DEFAULT_TERMINALS_CONFIG.inlineOrphanTtlMs;
|
|
270
273
|
// Retained transcripts of dead ephemeral terminals (insertion-ordered).
|
|
271
274
|
const transcripts = new Map<string, TranscriptTombstone>();
|
|
272
275
|
// Sticky close-release suppression flags: id -> timestamp (ms). Bounded by
|
|
@@ -298,11 +301,17 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
298
301
|
}
|
|
299
302
|
|
|
300
303
|
function spawn(cwd: string, opts?: { ephemeral?: boolean; owner?: { iss: string; sub: string } }): TerminalSession {
|
|
301
|
-
// Bound BEFORE any shell is spawned (B7).
|
|
302
|
-
if (entries.size >=
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
304
|
+
// Bound BEFORE any shell is spawned (B7). Global first, then per-owner.
|
|
305
|
+
if (entries.size >= maxConcurrent) throw new TerminalLimitError("global", maxConcurrent);
|
|
306
|
+
const owner = opts?.owner;
|
|
307
|
+
if (owner) {
|
|
308
|
+
let owned = 0;
|
|
309
|
+
for (const e of entries.values()) {
|
|
310
|
+
const o = e.session.principalOwner;
|
|
311
|
+
if (o && o.iss === owner.iss && o.sub === owner.sub) owned++;
|
|
312
|
+
}
|
|
313
|
+
if (owned >= maxPerOwner) throw new TerminalLimitError("owner", maxPerOwner);
|
|
314
|
+
}
|
|
306
315
|
|
|
307
316
|
const shell = detectShell();
|
|
308
317
|
const id = generateId();
|
|
@@ -346,12 +355,11 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
346
355
|
const buffer = new RingBuffer(bufferSize);
|
|
347
356
|
const clients = new Set<WebSocket>();
|
|
348
357
|
|
|
349
|
-
const entry: TerminalEntry = { session, pty: p, buffer, clients, sawInput: false,
|
|
358
|
+
const entry: TerminalEntry = { session, pty: p, buffer, clients, sawInput: false, orphanSince: Date.now() };
|
|
350
359
|
entries.set(id, entry);
|
|
351
360
|
|
|
352
361
|
p.onData((data: string) => {
|
|
353
362
|
const buf = Buffer.from(data);
|
|
354
|
-
entry.lastActivity = Date.now();
|
|
355
363
|
buffer.write(buf);
|
|
356
364
|
for (const ws of clients) {
|
|
357
365
|
if (ws.readyState === ws.OPEN) {
|
|
@@ -386,7 +394,6 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
386
394
|
}
|
|
387
395
|
|
|
388
396
|
entry.clients.add(ws);
|
|
389
|
-
entry.lastActivity = Date.now();
|
|
390
397
|
|
|
391
398
|
ws.on("message", (data: Buffer, isBinary: boolean) => {
|
|
392
399
|
if (isBinary) {
|
|
@@ -428,7 +435,7 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
428
435
|
|
|
429
436
|
ws.on("close", () => {
|
|
430
437
|
entry.clients.delete(ws);
|
|
431
|
-
entry.
|
|
438
|
+
if (entry.clients.size === 0) entry.orphanSince = Date.now(); // orphan clock restarts at last detach
|
|
432
439
|
});
|
|
433
440
|
}
|
|
434
441
|
|
|
@@ -436,7 +443,7 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
436
443
|
const entry = entries.get(id);
|
|
437
444
|
if (entry) {
|
|
438
445
|
entry.clients.delete(ws);
|
|
439
|
-
entry.
|
|
446
|
+
if (entry.clients.size === 0) entry.orphanSince = Date.now();
|
|
440
447
|
}
|
|
441
448
|
}
|
|
442
449
|
|
|
@@ -540,20 +547,21 @@ export function createTerminalManager(options?: TerminalManagerOptions): Termina
|
|
|
540
547
|
}
|
|
541
548
|
}
|
|
542
549
|
|
|
543
|
-
//
|
|
544
|
-
//
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
550
|
+
// Orphaned-inline reaper (B7, D3): inline PTYs are hidden from the tab bar, so
|
|
551
|
+
// without this a client looping `open_inline_terminal` could hold the cap with
|
|
552
|
+
// shells no UI can close. Tab (non-ephemeral) terminals are NEVER reaped:
|
|
553
|
+
// detached long-running shells (dev servers, watchers) are a supported use.
|
|
554
|
+
const reapTimer = setInterval(() => {
|
|
555
|
+
const cutoff = Date.now() - inlineOrphanTtlMs;
|
|
556
|
+
for (const [id, entry] of [...entries]) {
|
|
557
|
+
if (!entry.session.ephemeral || entry.reaping) continue;
|
|
558
|
+
if (entry.clients.size === 0 && entry.orphanSince <= cutoff) {
|
|
559
|
+
entry.reaping = true;
|
|
560
|
+
try { kill(id); } catch { /* exited in the same tick */ }
|
|
553
561
|
}
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
|
|
562
|
+
}
|
|
563
|
+
}, options?.reapIntervalMs ?? DEFAULT_REAP_INTERVAL_MS);
|
|
564
|
+
reapTimer.unref?.();
|
|
557
565
|
|
|
558
566
|
return { spawn, attach, detach, kill, get, list, updateTitle, getTranscript, getTerminalRecord, releaseTranscript, isReleased };
|
|
559
567
|
}
|