@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.
Files changed (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -1,24 +1,136 @@
1
1
  /**
2
2
  * Trusted-plugin → session emit seams (`emitEventToSession`, `sendExtensionMessage`).
3
3
  * Refuses reserved host namespaces and the raw `plugin_emit_event` lane so a plugin
4
- * cannot fire privileged `pi.events` listeners (roles:, model:, dashboard:, …).
5
- * See change: harden-trust-and-credential-boundaries (D3).
4
+ * cannot fire privileged `pi.events` listeners (roles:, model:, dashboard:, …), and
5
+ * refuses any event type absent from the calling plugin's manifest `emits`
6
+ * allowlist (computed live from loaded manifests; automation additionally gets the
7
+ * manifest `emits` of the providers of its accepted `automation.action.*`
8
+ * registrations). The bridge stays a relay: this server seam is the trust point.
9
+ * See change: harden-trust-and-credential-boundaries (D3);
10
+ * harden-git-terminal-plugin-boundaries (D16).
6
11
  */
7
- import { isReservedEventType } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
12
+ import { isReservedEventType, RESERVED_EVENT_PREFIXES } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
8
13
 
9
14
  type Send = (sessionId: string, msg: any) => boolean;
10
15
 
16
+ /** Plugin whose allowlist is widened by its collected action providers. */
17
+ const AUTOMATION_PLUGIN_ID = "automation";
18
+ const AUTOMATION_ACTION_PREFIX = "automation.action.";
19
+
20
+ /** Max distinct (plugin, eventType) pairs warned about per process; then one summary. */
21
+ const MAX_WARNED_PAIRS = 1000;
22
+ /** Event types are truncated to this length in the dedupe key and log lines. */
23
+ const MAX_LOGGED_TYPE_CHARS = 128;
24
+
25
+ export interface EmitAllowlistDeps {
26
+ /** Live manifest `emits` of a LOADED plugin; `undefined` when not loaded / unknown. */
27
+ manifestEmits(pluginId: string): readonly string[] | undefined;
28
+ /** Live `automation.action.*` service entries with the host-recorded provider. */
29
+ actionEntries(): ReadonlyArray<{ key: string; value: unknown; provider: string }>;
30
+ }
31
+
32
+ /** `<source>` of an `automation.action.<source>[.…]` key ("" when empty/not in namespace). */
33
+ function actionSource(key: string): string {
34
+ if (!key.startsWith(AUTOMATION_ACTION_PREFIX)) return "";
35
+ const rest = key.slice(AUTOMATION_ACTION_PREFIX.length);
36
+ const dot = rest.indexOf(".");
37
+ return dot === -1 ? rest : rest.slice(0, dot);
38
+ }
39
+
40
+ /**
41
+ * Event types `pluginId` may emit right now: its own manifest `emits`; for the
42
+ * automation plugin, additionally the WHOLE manifest `emits` of every loaded
43
+ * plugin that is the recorded provider of an accepted `automation.action.<provider>`
44
+ * registration. A registration is accepted when at least one of its event
45
+ * actions declares a non-empty `emits` that is a subset of that provider's
46
+ * manifest `emits` (mirrors the registry's registration check; host-set and
47
+ * mismatched-provider entries never count). No runtime channel widens it.
48
+ */
49
+ export function computeEmitAllowlist(pluginId: string, deps: EmitAllowlistDeps): Set<string> {
50
+ const allowed = new Set<string>(deps.manifestEmits(pluginId) ?? []);
51
+ if (pluginId !== AUTOMATION_PLUGIN_ID) return allowed;
52
+ for (const { key, value, provider } of deps.actionEntries()) {
53
+ if (actionSource(key) !== provider) continue;
54
+ const manifest = deps.manifestEmits(provider);
55
+ if (!manifest) continue; // provider unloaded → its types leave the allowlist
56
+ const declared = new Set(manifest);
57
+ const contribs = Array.isArray(value) ? value : [value];
58
+ const accepted = contribs.some((c) => {
59
+ if (!c || typeof c !== "object") return false;
60
+ const a = c as { buildEvent?: unknown; emits?: unknown };
61
+ return (
62
+ typeof a.buildEvent === "function" &&
63
+ Array.isArray(a.emits) &&
64
+ a.emits.length > 0 &&
65
+ a.emits.every((t) => typeof t === "string" && declared.has(t))
66
+ );
67
+ });
68
+ if (accepted) for (const t of manifest) allowed.add(t);
69
+ }
70
+ return allowed;
71
+ }
72
+
73
+ /** (plugin, eventType) pairs already warned about, capped at MAX_WARNED_PAIRS. */
74
+ const warnedPairs = new Set<string>();
75
+ let capSummaryLogged = false;
76
+
77
+ /** Test seam: forget the per-process warning de-duplication state. */
78
+ export function resetEmitWarnings(): void {
79
+ warnedPairs.clear();
80
+ capSummaryLogged = false;
81
+ }
82
+
83
+ /** Log `message` at most once per (plugin, eventType) per process, bounded. */
84
+ function warnOnce(pluginId: string, eventType: string, message: string): void {
85
+ const key = `${pluginId}\u0000${eventType.slice(0, MAX_LOGGED_TYPE_CHARS)}`;
86
+ if (warnedPairs.has(key)) return;
87
+ if (warnedPairs.size >= MAX_WARNED_PAIRS) {
88
+ if (!capSummaryLogged) {
89
+ capSummaryLogged = true;
90
+ console.warn(
91
+ `[plugin] emitEventToSession refusals: warning cap of ${MAX_WARNED_PAIRS} (plugin, event type) pairs reached ` +
92
+ `(last plugin "${pluginId}"); further refusals are silent`,
93
+ );
94
+ }
95
+ return;
96
+ }
97
+ warnedPairs.add(key);
98
+ console.warn(message);
99
+ }
100
+
101
+ export interface EmitPolicy {
102
+ /** Calling plugin's manifest id (attribution for allowlist + warnings). */
103
+ pluginId: string;
104
+ /** Live allowlist getter (evaluated per call; never cached). */
105
+ allowed: () => ReadonlySet<string>;
106
+ }
107
+
11
108
  export function emitEventToSession(
12
109
  trusted: boolean,
13
110
  send: Send,
14
111
  sessionId: string,
15
112
  eventType: string,
16
113
  data: Record<string, unknown> | undefined,
114
+ policy: EmitPolicy,
17
115
  ): boolean {
18
116
  if (!trusted) return false;
19
117
  if (typeof eventType !== "string" || eventType.length === 0) return false;
118
+ const shown = eventType.slice(0, MAX_LOGGED_TYPE_CHARS);
20
119
  if (isReservedEventType(eventType)) {
21
- console.warn(`[plugin] refused emitEventToSession: reserved event namespace "${eventType}"`);
120
+ const prefix = RESERVED_EVENT_PREFIXES.find((p) => eventType.startsWith(p));
121
+ warnOnce(
122
+ policy.pluginId,
123
+ eventType,
124
+ `[plugin] refused emitEventToSession from "${policy.pluginId}": event type "${shown}" is in the reserved namespace "${prefix}"`,
125
+ );
126
+ return false;
127
+ }
128
+ if (!policy.allowed().has(eventType)) {
129
+ warnOnce(
130
+ policy.pluginId,
131
+ eventType,
132
+ `[plugin] refused emitEventToSession from "${policy.pluginId}": event type "${shown}" is not declared in the plugin manifest field "emits"`,
133
+ );
22
134
  return false;
23
135
  }
24
136
  return send(sessionId, { type: "plugin_emit_event", sessionId, eventType, data: data ?? {} });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Server wiring of the runtime-client registry (`dashboard-plugin-runtime/server`): production deps
3
+ * (discovery winners, the served declaration's ids, persisted enabled state, live `auth.trustedPlugins`,
4
+ * the status store) and the process-wide singleton the routes call.
5
+ *
6
+ * `installRuntimeClientRegistry()` also installs the registry as the status store's `client` resolver, so
7
+ * EVERY status read (`GET /api/plugins`, `/api/health.plugins[]` — which strips `sha256` — and each
8
+ * `plugins_changed` broadcast) shows the live admission verdict and the live content hash.
9
+ *
10
+ * Route surface (6.10–6.12, `routes/plugin-runtime-client-routes.ts` + `registerPluginAssetsRoute`):
11
+ * `getRuntimeClientRegistry()` → `getAdmittedRuntimePlugins()`, `getAdmittedAssetRoot(id, sha)`,
12
+ * `currentContentHash(id)`, `clearContentHashCache()`. `logRuntimeAdmissions` is the 6.20 admission log.
13
+ *
14
+ * See change: decouple-plugins-from-core (task 6.7).
15
+ */
16
+ import {
17
+ createRuntimeClientRegistry,
18
+ discoverPlugins,
19
+ getDeclaredBundledPluginIds,
20
+ getPluginStatusStore,
21
+ type RuntimeClientRegistry,
22
+ resolvePluginEnabled,
23
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
24
+ import { getPluginConfig, loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
25
+ import { readTrustedPlugins } from "./auth/plugin-trust-store.js";
26
+
27
+ /** 12-hex prefix of a content hash: the only form that ever reaches a log line. */
28
+ export const hashPrefix = (sha256: string | undefined): string => (sha256 ? sha256.slice(0, 12) : "-");
29
+
30
+ export interface AdmissionLog {
31
+ info(message: string): void;
32
+ }
33
+
34
+ /**
35
+ * One structured line per runtime-eligible plugin (client `runtime` or `refused`): id, source, delivery,
36
+ * reason and the 12-hex hash prefix; never the full hash, a bearer or a request body. Called after each
37
+ * discovery refresh and each trust change (`trigger`). See change: decouple-plugins-from-core (task 6.20).
38
+ */
39
+ export function logRuntimeAdmissions(log: AdmissionLog, trigger: "refresh" | "trust"): void {
40
+ for (const status of getPluginStatusStore().listAll()) {
41
+ const client = status.client;
42
+ if (client?.delivery !== "runtime" && client?.delivery !== "refused") continue;
43
+ log.info(
44
+ `[plugin-runtime] admission trigger=${trigger} id=${status.id} source=${status.source ?? "-"} delivery=${client.delivery} reason=${client.refusedReason ?? "-"} sha=${hashPrefix(client.sha256)}`,
45
+ );
46
+ }
47
+ }
48
+
49
+ export interface RuntimeClientsOptions {
50
+ /** Explicit discovery root (tests); production passes none. */
51
+ repoRoot?: string;
52
+ /** Override the served declaration's ids (tests); default: the loader's process-wide declared ids. */
53
+ declaredIds?: () => readonly string[] | undefined;
54
+ }
55
+
56
+ /** Build a registry over the production deps (no singleton, no store hook). */
57
+ function createServerRuntimeClients(opts: RuntimeClientsOptions = {}): RuntimeClientRegistry {
58
+ const discover = () => discoverPlugins(opts.repoRoot);
59
+ return createRuntimeClientRegistry({
60
+ discover,
61
+ declaredIds: opts.declaredIds ?? getDeclaredBundledPluginIds,
62
+ isEnabled: (id) => {
63
+ const manifest = discover().find((p) => p.manifest.id === id)?.manifest;
64
+ return resolvePluginEnabled(getPluginConfig(loadConfig(), id) as Record<string, unknown>, manifest?.defaultEnabled);
65
+ },
66
+ readTrust: readTrustedPlugins,
67
+ getStoredStatus: (id) => getPluginStatusStore().getStoredStatus(id),
68
+ });
69
+ }
70
+
71
+ let _registry: RuntimeClientRegistry | undefined;
72
+
73
+ /** Create the singleton and install it as the status store's client resolver. */
74
+ export function installRuntimeClientRegistry(opts: RuntimeClientsOptions = {}): RuntimeClientRegistry {
75
+ _registry = createServerRuntimeClients(opts);
76
+ getPluginStatusStore().setClientResolver((status) => _registry?.resolveClient(status));
77
+ return _registry;
78
+ }
79
+
80
+ /** The installed registry, or `undefined` before boot wiring (routes treat that as "nothing admitted"). */
81
+ export function getRuntimeClientRegistry(): RuntimeClientRegistry | undefined {
82
+ return _registry;
83
+ }
84
+
85
+ /** Remove the singleton and the resolver (tests). */
86
+ export function resetRuntimeClientRegistry(): void {
87
+ _registry = undefined;
88
+ getPluginStatusStore().setClientResolver(null);
89
+ }
@@ -35,7 +35,7 @@ import { MIRROR_SOURCE_LABELS } from "@blackbelt-technology/pi-dashboard-shared/
35
35
  import { readPiTrustFileLockless } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-snapshot.js";
36
36
  import { MIRROR_REASON_LABELS, type MirrorSourceKind } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-types.js";
37
37
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
38
- import type { FastifyInstance } from "fastify";
38
+ import type { FastifyInstance, FastifyReply } from "fastify";
39
39
  import { getPathDenial } from "../access/access-denials.js";
40
40
  import {
41
41
  __accessGrantsLoadCount,
@@ -45,6 +45,9 @@ import {
45
45
  } from "../access/access-grants.js";
46
46
  import { grantNamedPathSubject } from "../access/named-grant.js";
47
47
  import { getPiTrustMirror } from "../access/pi-trust-mirror-service.js";
48
+ import { listPreviewEgressRows, revokePreviewEgressGrant } from "../access/preview-egress-store.js";
49
+ import { isPromptEligible } from "../access/prompt-channel.js";
50
+ import type { ProvisionFailure, ProvisioningRegistry, ProvisionRequestView, SettleInput } from "../access/provisioning.js";
48
51
  import { readRawConfig } from "../config-api.js";
49
52
  import { revokeTrust as revokeWorktreeTrust } from "../git-worktree/worktree-init-trust.js";
50
53
  import type { PreferencesStore } from "../persistence/preferences-store.js";
@@ -137,6 +140,12 @@ export function registerAccessRoutes(
137
140
  preferencesStore: PreferencesStore;
138
141
  /** Config write path (the tab revokes trusted networks / CORS origins here). */
139
142
  writeConfigPartial: (partial: Record<string, unknown>) => { success: boolean; error?: string };
143
+ /**
144
+ * Access provisioning (change: add-access-provisioning). Absent = the four
145
+ * `/api/access/provision*` routes are not registered. `announce` delivers a
146
+ * freshly created request to the operator sockets (the route itself never does).
147
+ */
148
+ provisioning?: { registry: ProvisioningRegistry; announce(request: ProvisionRequestView): void };
140
149
  },
141
150
  ): void {
142
151
  const { networkGuard, preferencesStore, writeConfigPartial } = deps;
@@ -169,6 +178,8 @@ export function registerAccessRoutes(
169
178
  bypassHosts: config.auth?.bypassHosts ?? [],
170
179
  corsOrigins: config.cors?.allowedOrigins ?? [],
171
180
  pinnedDirectories: preferencesStore.getPinnedDirectories(),
181
+ // Project egress grants for restricted previews: one row per (project, origin). Read-only here.
182
+ previewEgress: listPreviewEgressRows().map((r) => ({ store: "preview-egress" as const, ...r })),
172
183
  },
173
184
  } satisfies ApiResponse;
174
185
  });
@@ -307,6 +318,31 @@ export function registerAccessRoutes(
307
318
  },
308
319
  );
309
320
 
321
+ // ── REVOKE: a project's preview-egress origin (own locked store, not config.json) ──
322
+ // Takes effect on the next CSP build: the proxy reads the store on every capability response.
323
+ fastify.delete<{ Body: { project?: string; origin?: string } }>(
324
+ "/api/access/preview-egress",
325
+ { preHandler: networkGuard },
326
+ async (request, reply) => {
327
+ const { project, origin } = request.body ?? {};
328
+ if (!project || typeof project !== "string" || !origin || typeof origin !== "string") {
329
+ reply.code(400);
330
+ return { success: false, error: "project and origin are required" } satisfies ApiResponse;
331
+ }
332
+ try {
333
+ const { changed } = await revokePreviewEgressGrant(project, origin);
334
+ if (!changed) {
335
+ reply.code(404);
336
+ return { success: false, error: "no such grant" } satisfies ApiResponse;
337
+ }
338
+ } catch (err) {
339
+ reply.code(500);
340
+ return { success: false, error: `failed to revoke: ${(err as Error)?.message ?? String(err)}` } satisfies ApiResponse;
341
+ }
342
+ return { success: true } satisfies ApiResponse;
343
+ },
344
+ );
345
+
310
346
  // ── REVOKE: project trust, routed through pi's own API (design D13) ──
311
347
  // `decision: null` DELETES the entry in pi's store (`setMany` does
312
348
  // `delete data[key]`); it never records a standing refusal. The dashboard
@@ -431,6 +467,13 @@ export function registerAccessRoutes(
431
467
  }
432
468
  const result = outcome;
433
469
  const widened = outcome.widened;
470
+ // A session grant's choice lives in memory with the grant and dies with it.
471
+ // See change: mirror-dashboard-trust-live-remote.
472
+ if (typeof piTrust === "boolean" && result.grant.scope === "session") {
473
+ const mirror = getPiTrustMirror();
474
+ mirror?.live?.setChoice("accessGrants", result.grant.subject, piTrust);
475
+ mirror?.noteLiveChanged();
476
+ }
434
477
  // "Also trust this folder in pi" — stored with the (persisted) grant it belongs to.
435
478
  if (typeof piTrust === "boolean" && result.grant.scope === "project") {
436
479
  try {
@@ -482,6 +525,24 @@ export function registerAccessRoutes(
482
525
  ...(reason ? { reason, reasonLabel: MIRROR_REASON_LABELS[reason] } : {}),
483
526
  };
484
527
  });
528
+ // Live (server-lifetime) entries: session worktree trust, session grants, YOLO roots.
529
+ // Listed with their lifetime; they end with their source. See change: mirror-dashboard-trust-live-remote.
530
+ const liveEnum = mirror.live?.enumerate();
531
+ const liveReason = new Map((liveEnum?.ignored ?? []).map((i) => [`${i.entry.sourceKind}\u0000${i.entry.key}`, i.reason]));
532
+ const liveEntries = (liveEnum?.candidates ?? []).map((c) => {
533
+ const reason = liveReason.get(`${c.candidate.sourceKind}\u0000${c.candidate.key}`);
534
+ return {
535
+ live: true as const,
536
+ sourceKind: c.candidate.sourceKind,
537
+ sourceLabel: MIRROR_SOURCE_LABELS[c.candidate.sourceKind],
538
+ folder: c.candidate.key,
539
+ choice: c.candidate.choice ?? null,
540
+ byDefault: c.candidate.choice === undefined,
541
+ confers: c.confers,
542
+ lifetime: c.lifetime,
543
+ ...(reason ? { reason, reasonLabel: MIRROR_REASON_LABELS[reason] } : {}),
544
+ };
545
+ });
485
546
  return {
486
547
  success: true,
487
548
  data: {
@@ -489,14 +550,26 @@ export function registerAccessRoutes(
489
550
  config,
490
551
  agentDir,
491
552
  piEntries,
492
- effective: ev.counted.map((c) => ({
493
- folder: c.candidate.key,
494
- sourceKind: c.candidate.sourceKind,
495
- sourceLabel: MIRROR_SOURCE_LABELS[c.candidate.sourceKind],
496
- coversSubfolders: true,
497
- })),
498
- ignored: entries.filter((e) => !e.confers),
499
- entries,
553
+ effective: [
554
+ ...ev.counted.map((c) => ({
555
+ folder: c.candidate.key,
556
+ sourceKind: c.candidate.sourceKind,
557
+ sourceLabel: MIRROR_SOURCE_LABELS[c.candidate.sourceKind],
558
+ coversSubfolders: true,
559
+ })),
560
+ ...liveEntries
561
+ .filter((e) => e.confers)
562
+ .map((e) => ({
563
+ folder: e.folder,
564
+ sourceKind: e.sourceKind,
565
+ sourceLabel: e.sourceLabel,
566
+ coversSubfolders: true,
567
+ live: true as const,
568
+ lifetime: e.lifetime,
569
+ })),
570
+ ],
571
+ ignored: [...entries, ...liveEntries].filter((e) => !e.confers),
572
+ entries: [...entries, ...liveEntries],
500
573
  sourcesNotInstalled: ev.sourcesNotInstalled,
501
574
  choicesReadable: ev.choicesReadable,
502
575
  },
@@ -530,12 +603,89 @@ export function registerAccessRoutes(
530
603
  },
531
604
  );
532
605
 
606
+ if (deps.provisioning) registerProvisionRoutes(fastify, networkGuard, deps.provisioning);
607
+
533
608
  // Diagnostics: confirms the containment hot path never re-reads the store.
534
609
  fastify.get("/api/access/store-stats", { preHandler: networkGuard }, async () => {
535
610
  return { success: true, data: { loads: __accessGrantsLoadCount() } } satisfies ApiResponse;
536
611
  });
537
612
  }
538
613
 
614
+ /** Map a registry refusal onto the HTTP reply (`retry-after` in whole seconds when it carries a delay). */
615
+ function provisionFailure(reply: FastifyReply, f: ProvisionFailure): ApiResponse & Record<string, unknown> {
616
+ reply.code(f.status);
617
+ if (f.retryAfterMs !== undefined) reply.header("retry-after", String(Math.max(1, Math.ceil(f.retryAfterMs / 1000))));
618
+ return {
619
+ success: false,
620
+ error: f.error,
621
+ ...(f.reason ? { reason: f.reason } : {}),
622
+ ...(f.requestId ? { requestId: f.requestId } : {}),
623
+ ...(f.retryAfterMs !== undefined ? { retryAfterMs: f.retryAfterMs } : {}),
624
+ };
625
+ }
626
+
627
+ /**
628
+ * Access provisioning routes (change: add-access-provisioning, design D2/D3).
629
+ *
630
+ * `POST` proposes: validate, classify, record pending, announce to operator
631
+ * sockets; it writes no grant and no config. The two reads sit at observe tier.
632
+ * `settle` is the HTTP twin of the `provision_response` WS message and is
633
+ * accepted only when the request presents a LIVE prompt capability
634
+ * (`isPromptEligible`): a plain operate-tier caller (the agent) cannot approve
635
+ * what it asked for. Honest-path guard, not proof of operator presence (D11).
636
+ */
637
+ function registerProvisionRoutes(
638
+ fastify: FastifyInstance,
639
+ networkGuard: NetworkGuard,
640
+ { registry, announce }: NonNullable<Parameters<typeof registerAccessRoutes>[1]["provisioning"]>,
641
+ ): void {
642
+ fastify.post<{ Body: { projectRoot?: unknown; lines?: unknown; remote?: unknown } }>(
643
+ "/api/access/provision",
644
+ { preHandler: networkGuard },
645
+ async (request, reply) => {
646
+ const { projectRoot, lines, remote } = request.body ?? {};
647
+ const out = registry.create({ projectRoot, lines, remote });
648
+ if (!out.ok) return provisionFailure(reply, out);
649
+ announce(out.request);
650
+ return { success: true, data: out.request } satisfies ApiResponse;
651
+ },
652
+ );
653
+
654
+ fastify.get("/api/access/provision", { preHandler: networkGuard }, async () => {
655
+ return { success: true, data: { requests: registry.list() } } satisfies ApiResponse;
656
+ });
657
+
658
+ fastify.get<{ Params: { id: string } }>("/api/access/provision/:id", { preHandler: networkGuard }, async (request, reply) => {
659
+ const found = registry.get(request.params.id);
660
+ if (!found) return provisionFailure(reply, { ok: false, status: 404, error: "not-found" });
661
+ return { success: true, data: found } satisfies ApiResponse;
662
+ });
663
+
664
+ // Static segment: find-my-way ranks it above the parametric `/api/access/provision/:id`
665
+ // (GET) and the POST `/:id/settle` shape cannot match it, so registration order is moot.
666
+ fastify.post("/api/access/provision/dismiss-all", { preHandler: networkGuard }, async (request, reply) => {
667
+ if (!isPromptEligible(request)) {
668
+ reply.code(403);
669
+ return { success: false, error: "no-capability" } satisfies ApiResponse;
670
+ }
671
+ return { success: true, data: { dismissed: registry.dismissAll() } } satisfies ApiResponse;
672
+ });
673
+
674
+ fastify.post<{ Params: { id: string }; Body: Partial<SettleInput> }>(
675
+ "/api/access/provision/:id/settle",
676
+ { preHandler: networkGuard },
677
+ async (request, reply) => {
678
+ if (!isPromptEligible(request)) {
679
+ reply.code(403);
680
+ return { success: false, error: "no-capability" } satisfies ApiResponse;
681
+ }
682
+ const out = await registry.settle(request.params.id, { lines: request.body?.lines as SettleInput["lines"] });
683
+ if (!out.ok) return provisionFailure(reply, out);
684
+ return { success: true, data: out.request } satisfies ApiResponse;
685
+ },
686
+ );
687
+ }
688
+
539
689
  /**
540
690
  * A genuinely-local request. Mirrors `auth-plugin`'s own early return, which is
541
691
  * exactly why the grant endpoint's auth requirement cannot establish operator
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `GET /api/events/stream` — Server-Sent Events feed of agent transitions
3
+ * (observe tier), for an external controller that must react to pi sessions
4
+ * instead of polling them (the Claude Code plugin's `pi-dashboard-watch`).
5
+ *
6
+ * Query: `session=<id>[,<id>…]` (full ids) and `types=<type>[,<type>…]`
7
+ * (see `AGENT_EVENT_TYPES`; unknown type → 400). Frames:
8
+ * event: ready data: {sessions?, types?} (first, once)
9
+ * id: N / event: <type> data: AgentEvent (open questions first, then live)
10
+ * : ping (heartbeat)
11
+ * Visibility = the session-list predicate (`canAccessSession`), evaluated per
12
+ * event with the requester's principal. The reply is hijacked (no compression,
13
+ * no buffering); a client that stops reading past `MAX_BUFFERED_BYTES` is
14
+ * dropped. Streams end on disconnect and on server close.
15
+ * See change: add-agent-event-stream.
16
+ */
17
+ import type { ServerResponse } from "node:http";
18
+ import type { FastifyInstance } from "fastify";
19
+ import { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventHub, type AgentEventType } from "../agent-events/agent-event-hub.js";
20
+ import { canAccessSession, sessionPrincipalOf } from "../identity/session-access.js";
21
+ import type { NetworkGuard } from "./route-deps.js";
22
+
23
+ export const EVENT_STREAM_HEARTBEAT_MS = 20_000;
24
+ const MAX_BUFFERED_BYTES = 1024 * 1024;
25
+
26
+ export interface AgentEventStreamRouteDeps {
27
+ networkGuard: NetworkGuard;
28
+ hub: Pick<AgentEventHub, "subscribe" | "openQuestions" | "ownerOf">;
29
+ /** Ownership resolver active? (inert → every session is visible). */
30
+ isResolverActive: () => boolean;
31
+ heartbeatMs?: number;
32
+ }
33
+
34
+ type ListParam = string | string[] | undefined;
35
+
36
+ /** Comma list; a repeated parameter (`?types=a&types=b`, parsed as an array) joins the same way. */
37
+ const listOf = (raw: ListParam): string[] | undefined => {
38
+ const items = (Array.isArray(raw) ? raw.join(",") : raw)
39
+ ?.split(",")
40
+ .map((s) => s.trim())
41
+ .filter(Boolean);
42
+ return items && items.length > 0 ? items : undefined;
43
+ };
44
+
45
+ type Owner = { iss: string; sub: string };
46
+ type Filter = { sessions?: string[]; types?: string[] };
47
+
48
+ /** Parsed `session` / `types` query, or the 400 message for an unknown type. */
49
+ function parseFilter(query: { session?: ListParam; types?: ListParam }): Filter | { error: string } {
50
+ const sessions = listOf(query.session);
51
+ const types = listOf(query.types);
52
+ const unknown = types?.filter((t) => !AGENT_EVENT_TYPES.includes(t as AgentEventType)) ?? [];
53
+ if (unknown.length > 0) return { error: `unknown event type(s): ${unknown.join(",")}` };
54
+ return { ...(sessions ? { sessions } : {}), ...(types ? { types } : {}) };
55
+ }
56
+
57
+ /** Per-request predicate: query filter + session-list visibility for this principal. */
58
+ function wantedBy(filter: Filter, principal: Owner | null, isResolverActive: () => boolean) {
59
+ const sessionSet = filter.sessions ? new Set(filter.sessions) : undefined;
60
+ const typeSet = filter.types ? new Set<string>(filter.types) : undefined;
61
+ return (event: AgentEvent, owner: Owner | undefined) =>
62
+ (!sessionSet || sessionSet.has(event.sessionId)) &&
63
+ (!typeSet || typeSet.has(event.type)) &&
64
+ canAccessSession({ active: isResolverActive(), principal, owner });
65
+ }
66
+
67
+ /** Write the SSE head + ready frame, replay open questions, then follow the hub. Returns the closer. */
68
+ function startStream(
69
+ res: ServerResponse,
70
+ filter: Filter,
71
+ wanted: (event: AgentEvent, owner: Owner | undefined) => boolean,
72
+ deps: AgentEventStreamRouteDeps,
73
+ onClosed: () => void,
74
+ ): () => void {
75
+ let closed = false;
76
+ let seq = 0;
77
+ const write = (chunk: string) => {
78
+ if (closed) return;
79
+ res.write(chunk);
80
+ if (res.writableLength > MAX_BUFFERED_BYTES) close();
81
+ };
82
+ const send = (event: AgentEvent) => write(`id: ${++seq}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
83
+
84
+ write(`retry: 3000\nevent: ready\ndata: ${JSON.stringify(filter)}\n\n`);
85
+ for (const event of deps.hub.openQuestions()) if (wanted(event, deps.hub.ownerOf(event.sessionId))) send(event);
86
+ const unsubscribe = deps.hub.subscribe((event, owner) => {
87
+ if (wanted(event, owner)) send(event);
88
+ });
89
+ const heartbeat = setInterval(() => write(": ping\n\n"), deps.heartbeatMs ?? EVENT_STREAM_HEARTBEAT_MS);
90
+ heartbeat.unref();
91
+
92
+ function close(): void {
93
+ if (closed) return;
94
+ closed = true;
95
+ unsubscribe();
96
+ clearInterval(heartbeat);
97
+ res.end();
98
+ onClosed();
99
+ }
100
+ // The RESPONSE's close (client gone); the request's fires once its body is read.
101
+ res.on("close", close);
102
+ return close;
103
+ }
104
+
105
+ export function registerAgentEventStreamRoutes(fastify: FastifyInstance, deps: AgentEventStreamRouteDeps): void {
106
+ const open = new Set<() => void>();
107
+ // preClose: `server.close()` waits for these never-ending responses, so end them first.
108
+ fastify.addHook("preClose", async () => {
109
+ for (const close of [...open]) close();
110
+ });
111
+
112
+ fastify.get<{ Querystring: { session?: ListParam; types?: ListParam } }>(
113
+ "/api/events/stream",
114
+ { preHandler: deps.networkGuard },
115
+ async (request, reply) => {
116
+ const filter = parseFilter(request.query);
117
+ if ("error" in filter) {
118
+ reply.code(400);
119
+ return { success: false, error: filter.error };
120
+ }
121
+ const wanted = wantedBy(filter, sessionPrincipalOf(request), deps.isResolverActive);
122
+
123
+ reply.hijack();
124
+ if (typeof request.raw.setTimeout === "function") request.raw.setTimeout(0);
125
+ // Keep headers other hooks already set (CORS); hijack skips onSend.
126
+ reply.raw.writeHead(200, {
127
+ ...(reply.getHeaders() as Record<string, string | number | string[]>),
128
+ "Content-Type": "text/event-stream",
129
+ "Cache-Control": "no-cache, no-transform",
130
+ Connection: "keep-alive",
131
+ "X-Accel-Buffering": "no",
132
+ });
133
+ const close = startStream(reply.raw, filter, wanted, deps, () => open.delete(close));
134
+ open.add(close);
135
+ },
136
+ );
137
+ }
@@ -17,6 +17,8 @@ import {
17
17
  readCanvasTypesScopes,
18
18
  writeCanvasTypesScope,
19
19
  } from "../canvas/canvas-settings.js";
20
+ import { admitOptionalCwd, sendCwdFailure } from "../lib/file-cwd-admission.js";
21
+ import type { RouteAdmissionDeps } from "../lib/route-admission.js";
20
22
  import type { NetworkGuard } from "./route-deps.js";
21
23
 
22
24
  interface PatchBody {
@@ -39,16 +41,26 @@ function validatePatch(body: PatchBody | undefined): string | null {
39
41
 
40
42
  export function registerCanvasTypesRoutes(
41
43
  fastify: FastifyInstance,
42
- deps: { networkGuard: NetworkGuard },
44
+ deps: {
45
+ networkGuard: NetworkGuard;
46
+ /**
47
+ * Shared cwd admission (change: core-file-cwd-admission): a supplied `cwd` must be admitted;
48
+ * no `cwd` keeps the global scope. Absent → fail-closed (nothing is known).
49
+ */
50
+ routeAdmission?: RouteAdmissionDeps;
51
+ },
43
52
  ): void {
44
53
  const { networkGuard } = deps;
54
+ const routeAdmission: RouteAdmissionDeps = deps.routeAdmission ?? {};
45
55
 
46
56
  fastify.get<{ Querystring: { cwd?: string } }>(
47
57
  "/api/canvas-types",
48
58
  { preHandler: networkGuard },
49
- async (request) => {
50
- const cwd = typeof request.query.cwd === "string" ? request.query.cwd : "";
51
- return readCanvasTypesScopes(cwd);
59
+ async (request, reply) => {
60
+ // The no-cwd branch hands the sink a constant `""`, never the request value.
61
+ const admitted = await admitOptionalCwd(request.query.cwd, routeAdmission, reply);
62
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
63
+ return readCanvasTypesScopes(admitted.cwd ?? "");
52
64
  },
53
65
  );
54
66
 
@@ -60,9 +72,11 @@ export function registerCanvasTypesRoutes(
60
72
  const err = validatePatch(body);
61
73
  if (err) return reply.code(400).send({ error: err });
62
74
  // Non-null after validatePatch passed.
63
- const { scope, cwd = "", canvasTypes } = body as Required<Pick<PatchBody, "scope" | "canvasTypes">> & PatchBody;
75
+ const { scope, canvasTypes } = body as Required<Pick<PatchBody, "scope" | "canvasTypes">> & PatchBody;
76
+ const admitted = await admitOptionalCwd((body as PatchBody).cwd, routeAdmission, reply);
77
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
64
78
  try {
65
- return writeCanvasTypesScope(scope, cwd, canvasTypes);
79
+ return writeCanvasTypesScope(scope, admitted.cwd ?? "", canvasTypes);
66
80
  } catch (e) {
67
81
  return reply
68
82
  .code(400)