@blackbelt-technology/pi-dashboard-flows-plugin 0.11.0 → 0.12.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 (71) hide show
  1. package/README.md +5 -1
  2. package/package.json +23 -4
  3. package/src/bridge/flow-catalog-publisher.ts +138 -0
  4. package/src/bridge/flow-event-forward.ts +132 -0
  5. package/src/bridge/flow-files-reporter.ts +16 -14
  6. package/src/bridge/flow-open-tool.ts +124 -0
  7. package/src/bridge/flow-probe.ts +20 -0
  8. package/src/bridge/flow-tool-registry.ts +298 -0
  9. package/src/bridge/flow-tools-guideline.ts +52 -0
  10. package/src/bridge/index.ts +67 -10
  11. package/src/bridge/run-snapshot-reporter.ts +146 -0
  12. package/src/catalog-timings.ts +70 -0
  13. package/src/client/AskSession.tsx +82 -0
  14. package/src/client/FlowActionDialogs.tsx +143 -0
  15. package/src/client/FlowActivityBadge.tsx +42 -4
  16. package/src/client/FlowAgentCard.tsx +63 -8
  17. package/src/client/FlowAgentDetail.tsx +3 -5
  18. package/src/client/FlowDashboard.tsx +381 -273
  19. package/src/client/FlowEditMenu.tsx +69 -0
  20. package/src/client/FlowEditPopover.tsx +130 -0
  21. package/src/client/FlowGraph.tsx +127 -44
  22. package/src/client/FlowHeaderActions.tsx +83 -0
  23. package/src/client/FlowInputWiring.tsx +1 -1
  24. package/src/client/FlowOpenListener.tsx +82 -0
  25. package/src/client/FlowQuestionBlock.tsx +226 -0
  26. package/src/client/FlowStepCards.tsx +189 -0
  27. package/src/client/FlowSummary.tsx +72 -240
  28. package/src/client/FlowWriteToolRenderer.tsx +46 -17
  29. package/src/client/FlowYamlPopoverButton.tsx +2 -2
  30. package/src/client/FlowsContextGroup.tsx +156 -0
  31. package/src/client/FlowsSessionStateContext.tsx +202 -54
  32. package/src/client/FlowsSettings.tsx +145 -17
  33. package/src/client/SessionFlowActions.tsx +65 -10
  34. package/src/client/SessionFlowMenuClaim.tsx +48 -241
  35. package/src/client/ask-session-store.ts +243 -0
  36. package/src/client/flow-attach-store.ts +2 -0
  37. package/src/client/flow-card-grid.ts +2 -2
  38. package/src/client/flow-collapse-storage.ts +36 -6
  39. package/src/client/flow-edges.ts +91 -35
  40. package/src/client/flow-files.ts +16 -4
  41. package/src/client/flow-idle-state.ts +93 -37
  42. package/src/client/flowsActionsGate.ts +1 -1
  43. package/src/client/flowsAvailability.ts +8 -2
  44. package/src/client/index.tsx +13 -11
  45. package/src/client/shouldRender.ts +1 -1
  46. package/src/client/useEditModeState.ts +78 -0
  47. package/src/client/useFlowActions.tsx +191 -0
  48. package/src/client/useFlowCatalog.ts +69 -0
  49. package/src/client/useMinuteClock.ts +21 -0
  50. package/src/client/useRunReattach.ts +50 -0
  51. package/src/configSchema.json +37 -2
  52. package/src/flow-catalog-contract.ts +65 -0
  53. package/src/flow-questions.ts +138 -0
  54. package/src/flow-reducer.ts +434 -13
  55. package/src/flow-state-serialize.ts +132 -0
  56. package/src/i18n.ts +144 -6
  57. package/src/server/automation-actions.ts +4 -3
  58. package/src/server/edit-mode.ts +307 -0
  59. package/src/server/flow-catalog.ts +127 -0
  60. package/src/server/flow-control.ts +263 -0
  61. package/src/server/flow-files.ts +140 -14
  62. package/src/server/flow-open.ts +385 -0
  63. package/src/server/index.ts +112 -34
  64. package/src/server/render-actions.ts +3 -2
  65. package/src/server/state-store.ts +11 -5
  66. package/src/types.ts +180 -0
  67. package/src/bridge/flow-question-adapter.ts +0 -93
  68. package/src/client/FlowQuestionCard.tsx +0 -218
  69. package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
  70. package/src/client/FlowsCommandRoutes.tsx +0 -245
  71. package/src/client/flow-yaml-parse.ts +0 -140
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Plugin-server side of the flow catalog (see `../flow-catalog-contract.ts`).
3
+ *
4
+ * - Feeds `stateStore` from forwarded `flow_catalog` events (`ctx.onEvent`)
5
+ * and clears it on session end, so `makeFlowsForCwd` (automation) sees
6
+ * the same catalog the browser does.
7
+ * - `requestCatalog(sessionId, {rediscover})`: asks the session's bridge to
8
+ * (re)publish via `dashboard-flows:report-files`, at most once per session
9
+ * per configured ask limit (own map, independent of the files ask).
10
+ * - Sibling follow: a catalog that DIFFERS from the session's previous known
11
+ * catalog makes every other live session in the same folder rediscover and
12
+ * report. Equal catalogs ask nothing (no loop).
13
+ * - Server start: asks every live session to report, then re-asks the ones
14
+ * that have not reported at the configured interval for the configured
15
+ * window (bridges reconnecting after a restart).
16
+ *
17
+ * Timings are read from the plugin config at each use (a save applies at once).
18
+ * See change: flows-dock-chip-and-panel-actions (D3, D4, D11).
19
+ */
20
+ import { FLOW_CATALOG_EVENT, type FlowCatalogEntry, parseCatalogPayload, sameCatalog } from "../flow-catalog-contract.js";
21
+ import { FLOW_FILES_REQUEST_EVENT } from "../flow-files-contract.js";
22
+ import { type CatalogTimings, readCatalogTimings } from "../catalog-timings.js";
23
+
24
+ interface CatalogStore {
25
+ getState(id: string): { flows?: FlowCatalogEntry[]; catalogKnown?: boolean } | undefined;
26
+ setFlows(id: string, flows: FlowCatalogEntry[]): void;
27
+ clearSession(id: string): void;
28
+ }
29
+
30
+ export interface FlowCatalogDeps {
31
+ onEvent: (handler: (sessionId: string, event: unknown) => void) => () => void;
32
+ onSessionEnded?: (handler: (sessionId: string) => void) => () => void;
33
+ sessionManager: { listActive(): unknown[] };
34
+ emitEventToSession: (sessionId: string, eventType: string, data: Record<string, unknown>) => boolean;
35
+ getPluginConfig: () => Record<string, unknown>;
36
+ store: CatalogStore;
37
+ logger?: { info(m: string): void; warn(m: string): void };
38
+ }
39
+
40
+ export interface FlowCatalogController {
41
+ /** Ask a session to report (rate-limited). Returns true when an ask was sent and delivered. */
42
+ requestCatalog(sessionId: string, opts?: { rediscover?: boolean }): boolean;
43
+ /** Start the server-start ask loop. Returns a stop fn. */
44
+ startServerStartAsks(): () => void;
45
+ dispose(): void;
46
+ }
47
+
48
+ function liveSessions(sm: FlowCatalogDeps["sessionManager"]): Array<{ id: string; cwd?: string }> {
49
+ const out: Array<{ id: string; cwd?: string }> = [];
50
+ for (const s of sm.listActive()) {
51
+ const r = s as { id?: unknown; cwd?: unknown; status?: unknown } | null;
52
+ if (!r || typeof r.id !== "string" || r.status === "ended") continue;
53
+ out.push({ id: r.id, cwd: typeof r.cwd === "string" ? r.cwd : undefined });
54
+ }
55
+ return out;
56
+ }
57
+
58
+ export function registerFlowCatalog(deps: FlowCatalogDeps): FlowCatalogController {
59
+ const lastAsk = new Map<string, number>();
60
+ const reported = new Set<string>();
61
+ const timings = (): CatalogTimings => readCatalogTimings(deps.getPluginConfig());
62
+
63
+ const requestCatalog = (sessionId: string, opts?: { rediscover?: boolean }): boolean => {
64
+ const now = Date.now();
65
+ const prev = lastAsk.get(sessionId);
66
+ if (prev !== undefined && now - prev < timings().askLimitMs) return false;
67
+ lastAsk.set(sessionId, now);
68
+ try {
69
+ return deps.emitEventToSession(sessionId, FLOW_FILES_REQUEST_EVENT, opts?.rediscover ? { rediscover: true } : {});
70
+ } catch {
71
+ return false;
72
+ }
73
+ };
74
+
75
+ const offEvent = deps.onEvent((sessionId, raw) => {
76
+ const ev = raw as { eventType?: unknown; data?: unknown } | null;
77
+ if (ev?.eventType !== FLOW_CATALOG_EVENT) return;
78
+ const flows = parseCatalogPayload(ev.data);
79
+ if (!flows) return;
80
+ const prev = deps.store.getState(sessionId);
81
+ const changed = prev?.catalogKnown === true && !sameCatalog(prev.flows, flows);
82
+ deps.store.setFlows(sessionId, flows);
83
+ reported.add(sessionId);
84
+ if (!changed) return;
85
+ const live = liveSessions(deps.sessionManager);
86
+ const cwd = live.find((s) => s.id === sessionId)?.cwd;
87
+ if (!cwd) return;
88
+ for (const s of live) {
89
+ if (s.id !== sessionId && s.cwd === cwd) requestCatalog(s.id, { rediscover: true });
90
+ }
91
+ });
92
+
93
+ const offEnded = deps.onSessionEnded?.((sessionId) => {
94
+ deps.store.clearSession(sessionId);
95
+ lastAsk.delete(sessionId);
96
+ reported.delete(sessionId);
97
+ });
98
+
99
+ const startServerStartAsks = (): (() => void) => {
100
+ const startedAt = Date.now();
101
+ let timer: ReturnType<typeof setTimeout> | undefined;
102
+ const tick = () => {
103
+ timer = undefined;
104
+ for (const s of liveSessions(deps.sessionManager)) {
105
+ if (!reported.has(s.id)) requestCatalog(s.id);
106
+ }
107
+ const { serverStartIntervalMs, serverStartWindowMs } = timings();
108
+ const next = Date.now() + serverStartIntervalMs;
109
+ if (next - startedAt > serverStartWindowMs) return;
110
+ timer = setTimeout(tick, serverStartIntervalMs);
111
+ (timer as { unref?: () => void }).unref?.();
112
+ };
113
+ tick();
114
+ return () => {
115
+ if (timer) clearTimeout(timer);
116
+ };
117
+ };
118
+
119
+ return {
120
+ requestCatalog,
121
+ startServerStartAsks,
122
+ dispose: () => {
123
+ offEvent();
124
+ offEnded?.();
125
+ },
126
+ };
127
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Flow commands owned by the flows plugin (replaces core `flow_control` /
3
+ * `flow_management`). One validator + relay, two entry points:
4
+ *
5
+ * - `plugin_action { pluginId: "flows", action, sessionId, payload }` (WS);
6
+ * - `POST /api/plugins/flows/control { sessionId, action, flowName?, task?, enabled?, questionId?, requestId? }`
7
+ * (operate authority + network guard; the REST replacement of
8
+ * `/api/session/:id/flow-control`).
9
+ *
10
+ * Each action relays FIXED pi event names through `emitEventToSession` (the
11
+ * manifest `emits` gate admits exactly these). An ACP session is refused with
12
+ * `unsupported_for_acp` before any relay. A rejected command emits nothing,
13
+ * logs a warning and bumps the host's rejected-plugin-action counter.
14
+ * See change: update-flows-plugin (D2; security-hardening).
15
+ */
16
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
17
+ import rateLimit from "@fastify/rate-limit";
18
+ import { handleSetEditMode, type SetEditModeDeps } from "./edit-mode.js";
19
+
20
+ /** The six flow-control actions (both entry points). The AUTO toggle is gone
21
+ * (pi-flows 0.12); `flow.ask-session` hands an open parent question to the
22
+ * session's model. See change: adopt-flow-parent-mailbox (D5, D8). */
23
+ export const FLOW_CONTROL_ACTIONS = [
24
+ "flow.abort",
25
+ "flow.ask-session",
26
+ "flow.dismiss-summary",
27
+ "flow.run",
28
+ "flow.delete",
29
+ "flow.set-edit-mode",
30
+ ] as const;
31
+ type FlowControlAction = (typeof FLOW_CONTROL_ACTIONS)[number];
32
+
33
+ function isFlowControlAction(a: unknown): a is FlowControlAction {
34
+ return typeof a === "string" && (FLOW_CONTROL_ACTIONS as readonly string[]).includes(a);
35
+ }
36
+
37
+ /** Same code the core ACP guard answers (`acp-guard.ts`). */
38
+ const UNSUPPORTED_FOR_ACP = "unsupported_for_acp";
39
+
40
+ const MAX_FLOW_NAME = 200;
41
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point
42
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
43
+
44
+ /**
45
+ * A valid flow id: a non-empty trimmed string (≤ 200 chars) with no `/`, `\`,
46
+ * `..` or control character. `research` and `batch:apply` are valid (G1).
47
+ */
48
+ export function isValidFlowName(v: unknown): v is string {
49
+ if (typeof v !== "string") return false;
50
+ const s = v.trim();
51
+ if (s === "" || s !== v || s.length > MAX_FLOW_NAME) return false;
52
+ return !s.includes("/") && !s.includes("\\") && !s.includes("..") && !CONTROL_CHARS.test(s);
53
+ }
54
+
55
+ /** Ask-session ids: 1–64 chars of `[A-Za-z0-9_-]`. */
56
+ const ASK_ID = /^[A-Za-z0-9_-]{1,64}$/;
57
+ const isAskId = (v: unknown): v is string => typeof v === "string" && ASK_ID.test(v);
58
+
59
+ /** Ask-session throttle: one relay per `(sessionId, questionId)` per 30 s. A
60
+ * per-process map (≤ 1000 entries, 30 s expiry, oldest dropped) bounds model
61
+ * turns on the WS path, which has no route rate limit. See change:
62
+ * adopt-flow-parent-mailbox (D5; security-hardening). */
63
+ const ASK_THROTTLE_MS = 30_000;
64
+ const ASK_THROTTLE_MAX = 1000;
65
+ const askThrottle = new Map<string, number>();
66
+
67
+ /** Current throttle-map size (tests / diagnostics). */
68
+ export function askThrottleSize(): number {
69
+ return askThrottle.size;
70
+ }
71
+
72
+ /** Clear the throttle map (tests). */
73
+ export function resetAskThrottle(): void {
74
+ askThrottle.clear();
75
+ }
76
+
77
+ /** True when `key` may relay now (and records it); false while throttled. */
78
+ function admitAsk(key: string, now: number): boolean {
79
+ for (const [k, at] of askThrottle) {
80
+ if (now - at < ASK_THROTTLE_MS) break; // insertion order = age order
81
+ askThrottle.delete(k);
82
+ }
83
+ const at = askThrottle.get(key);
84
+ if (at !== undefined && now - at < ASK_THROTTLE_MS) return false;
85
+ askThrottle.delete(key);
86
+ askThrottle.set(key, now);
87
+ while (askThrottle.size > ASK_THROTTLE_MAX) {
88
+ const oldest = askThrottle.keys().next().value as string;
89
+ askThrottle.delete(oldest);
90
+ }
91
+ return true;
92
+ }
93
+
94
+ /** pi-side notice after a delete (pi TUI text, not dashboard UI). */
95
+ function deletedNotice(flowName: string): string {
96
+ return ["Flow", JSON.stringify(flowName), "deleted."].join(" ");
97
+ }
98
+
99
+ export type FlowControlResult =
100
+ | { ok: true }
101
+ | { ok: false; status: 400 | 404 | 409 | 429; code: string; error: string };
102
+
103
+ export interface FlowControlDeps extends Omit<SetEditModeDeps, "logger"> {
104
+ sessionManager: SetEditModeDeps["sessionManager"] & { getSession?(id: string): unknown };
105
+ logger: { info(m: string): void; warn(m: string): void };
106
+ recordRejectedAction?: () => void;
107
+ }
108
+
109
+ function sessionDriver(deps: FlowControlDeps, sessionId: string): { found: boolean; driver?: unknown } {
110
+ let s: unknown;
111
+ try {
112
+ s = deps.sessionManager.getSession?.(sessionId);
113
+ } catch {
114
+ s = undefined;
115
+ }
116
+ if (!s || typeof s !== "object") return { found: false };
117
+ return { found: true, driver: (s as { driver?: unknown }).driver };
118
+ }
119
+
120
+ function reject(
121
+ deps: FlowControlDeps,
122
+ status: 400 | 404 | 409,
123
+ code: string,
124
+ error: string,
125
+ sessionId: string,
126
+ action: string,
127
+ ): FlowControlResult {
128
+ deps.logger.warn(`flows control rejected action=${action.slice(0, 64)} session=${sessionId} code=${code}: ${error}`);
129
+ deps.recordRejectedAction?.();
130
+ return { ok: false, status, code, error };
131
+ }
132
+
133
+ /**
134
+ * Validate and relay one flow-control command. `requireSession`: the REST
135
+ * path answers 404 for an unknown session; the WS path relays anyway (the
136
+ * bridge drops it, as before). Never throws.
137
+ */
138
+ export function runFlowControl(
139
+ deps: FlowControlDeps,
140
+ sessionId: string,
141
+ action: string,
142
+ payload: Record<string, unknown>,
143
+ opts: { requireSession?: boolean } = {},
144
+ ): FlowControlResult {
145
+ if (!isFlowControlAction(action)) {
146
+ return reject(deps, 400, "unknown_action", `unknown flows action: ${action.slice(0, 64)}`, sessionId, action);
147
+ }
148
+ const { found, driver } = sessionDriver(deps, sessionId);
149
+ if (opts.requireSession && !found) return reject(deps, 404, "session_not_found", "session not found", sessionId, action);
150
+ if (driver === "acp") {
151
+ return reject(deps, 409, UNSUPPORTED_FOR_ACP, `${action} is not supported for ACP sessions (${UNSUPPORTED_FOR_ACP})`, sessionId, action);
152
+ }
153
+ const emit = (event: string, data: Record<string, unknown>) => {
154
+ const delivered = deps.emitEventToSession(sessionId, event, data);
155
+ deps.logger.info(`${action} → ${event} session=${sessionId} delivered=${delivered}`);
156
+ };
157
+
158
+ switch (action) {
159
+ case "flow.abort":
160
+ // Also abort the architect (mutually exclusive with a run; the
161
+ // irrelevant emit is a no-op on the pi-flows side).
162
+ emit("flow:abort", {});
163
+ emit("flow:architect-abort", {});
164
+ return { ok: true };
165
+ case "flow.ask-session": {
166
+ const { questionId, requestId } = payload;
167
+ if (!isAskId(questionId)) return reject(deps, 400, "invalid_payload", "invalid questionId", sessionId, action);
168
+ if (requestId !== undefined && !isAskId(requestId)) {
169
+ return reject(deps, 400, "invalid_payload", "invalid requestId", sessionId, action);
170
+ }
171
+ // A repeat within 30 s is dropped quietly: info log, not a rejected action.
172
+ if (!admitAsk(`${sessionId}\u0000${questionId}`, Date.now())) {
173
+ deps.logger.info(`${action} throttled session=${sessionId} question=${questionId}`);
174
+ return { ok: false, status: 429, code: "throttled", error: "ask-session throttled" };
175
+ }
176
+ emit("flow:ask-session", { question_id: questionId, ...(requestId !== undefined ? { requestId } : {}) });
177
+ return { ok: true };
178
+ }
179
+ case "flow.dismiss-summary": {
180
+ // Optional runId names the run so the bridge persists the dismissal; an
181
+ // invalid one degrades to the legacy clear-all. See change:
182
+ // persist-flow-run-close (D4).
183
+ const runId = payload.runId;
184
+ const valid = typeof runId === "string" && runId.length >= 1 && runId.length <= 128;
185
+ emit("flow:summary-dismissed", valid ? { runId } : {});
186
+ return { ok: true };
187
+ }
188
+ case "flow.delete": {
189
+ const flowName = payload.flowName;
190
+ if (!isValidFlowName(flowName)) return reject(deps, 400, "invalid_flow_name", "invalid flowName", sessionId, action);
191
+ emit("flow:delete-request", { flowName });
192
+ // pi-flows TUI notice text (sent into pi, not rendered by the dashboard);
193
+ // the same text the retired core handler sent.
194
+ emit("flow:notify", { message: deletedNotice(flowName), level: "info" });
195
+ return { ok: true };
196
+ }
197
+ case "flow.run": {
198
+ // `flow` (intent path) or `flowName`.
199
+ const flowName = payload.flowName ?? payload.flow;
200
+ if (!isValidFlowName(flowName)) return reject(deps, 400, "invalid_flow_name", "invalid flowName", sessionId, action);
201
+ if (payload.task !== undefined && typeof payload.task !== "string") {
202
+ return reject(deps, 400, "invalid_payload", "task must be a string", sessionId, action);
203
+ }
204
+ const inputs = payload.inputs;
205
+ if (inputs !== undefined && (inputs === null || typeof inputs !== "object" || Array.isArray(inputs))) {
206
+ return reject(deps, 400, "invalid_payload", "inputs must be an object", sessionId, action);
207
+ }
208
+ const task = typeof payload.task === "string" ? payload.task.trim() : "";
209
+ // Dashboard-started runs are attached: their steps can ask the parent and
210
+ // `parent: required` flows start. Automations keep their own detached
211
+ // `flow:run`. See change: adopt-flow-parent-mailbox (D7).
212
+ const data: Record<string, unknown> = { flowName };
213
+ if (task) data.task = task;
214
+ if (inputs) data.inputs = inputs;
215
+ data.notifyParent = true;
216
+ emit("flow:run", data);
217
+ return { ok: true };
218
+ }
219
+ case "flow.set-edit-mode": {
220
+ if (typeof payload.enabled !== "boolean") {
221
+ return reject(deps, 400, "invalid_payload", "enabled must be a boolean", sessionId, action);
222
+ }
223
+ // Emits only when the desired value differs from the effective one
224
+ // (flows-edit-mode-settings; G16). The emit itself is synchronous.
225
+ void handleSetEditMode(deps, sessionId, { enabled: payload.enabled }).catch((err) =>
226
+ deps.logger.warn(`flow.set-edit-mode failed: ${err instanceof Error ? err.message : String(err)}`),
227
+ );
228
+ return { ok: true };
229
+ }
230
+ }
231
+ }
232
+
233
+ export interface FlowControlRouteDeps extends FlowControlDeps {
234
+ fastify: ServerPluginContext["fastify"];
235
+ networkGuard: ServerPluginContext["networkGuard"];
236
+ /** `ctx.identity?.hasOperateAuthority`; absent ⇒ refuse. */
237
+ hasOperateAuthority?: (request: unknown) => boolean;
238
+ }
239
+
240
+ /** `POST /api/plugins/flows/control` — operate authority + network guard. */
241
+ export async function registerFlowControlRoute(deps: FlowControlRouteDeps): Promise<void> {
242
+ await deps.fastify.register(async (scope) => {
243
+ await scope.register(rateLimit, { global: true, max: 120, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] });
244
+ scope.post("/api/plugins/flows/control", { preHandler: deps.networkGuard }, async (req, reply) => {
245
+ if (deps.hasOperateAuthority?.(req) !== true) {
246
+ return reply.code(403).send({ success: false, error: "operate_required" });
247
+ }
248
+ const body = (req.body && typeof req.body === "object" ? req.body : {}) as Record<string, unknown>;
249
+ const sessionId = body.sessionId;
250
+ if (typeof sessionId !== "string" || sessionId === "" || sessionId.length > 256) {
251
+ return reply.code(400).send({ success: false, error: "sessionId is required" });
252
+ }
253
+ const action = typeof body.action === "string" ? body.action : "";
254
+ const payload: Record<string, unknown> = {};
255
+ for (const k of ["flowName", "task", "enabled", "inputs", "runId", "questionId", "requestId"]) {
256
+ if (Object.prototype.hasOwnProperty.call(body, k)) payload[k] = body[k];
257
+ }
258
+ const r = runFlowControl(deps, sessionId, action, payload, { requireSession: true });
259
+ if (!r.ok) return reply.code(r.status).send({ success: false, error: r.error, code: r.code });
260
+ return { success: true };
261
+ });
262
+ });
263
+ }
@@ -16,10 +16,11 @@
16
16
  * No sibling, parent dir, or helper file becomes readable.
17
17
  * See change: attach-flow-before-run.
18
18
  */
19
- import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
20
- import rateLimit from "@fastify/rate-limit";
19
+
21
20
  import fs from "node:fs";
22
21
  import path from "node:path";
22
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
23
+ import rateLimit from "@fastify/rate-limit";
23
24
  import { parse as parseYaml } from "yaml";
24
25
  import { FLOW_FILES_REPORT, FLOW_FILES_REQUEST_EVENT, type FlowFilesReport, type ReportedFile } from "../flow-files-contract.js";
25
26
 
@@ -35,7 +36,9 @@ const YAML = /\.ya?ml$/i;
35
36
  const MARKDOWN = /\.md$/i;
36
37
  const HANDLER = /\.[cm]?[jt]s$/i;
37
38
  /** Largest file served / parsed (flow files are small text). */
38
- const MAX_FILE_BYTES = 1024 * 1024;
39
+ export const MAX_FILE_BYTES = 1024 * 1024;
40
+ /** Most path-opened flows kept per session (oldest dropped). See change: add-flow-open-tool. */
41
+ const MAX_OPENED_PER_SESSION = 32;
39
42
  /** Largest number of flows / agents accepted per report. */
40
43
  const MAX_REPORT_ITEMS = 2000;
41
44
  /** Minimum gap between asks to one session's bridge to (re)report. */
@@ -74,14 +77,23 @@ function sanitize(list: unknown, ext: RegExp): ReportedFile[] {
74
77
 
75
78
  /** Handler files pi-flows would run for one flow.yaml (read from disk). */
76
79
  export function codeHandlerPaths(flowSource: string, cwd: string | undefined): Record<string, string> {
77
- const out: Record<string, string> = Object.create(null);
78
- if (!isSmallFile(flowSource)) return out;
80
+ if (!isSmallFile(flowSource)) return Object.create(null);
79
81
  let doc: unknown;
80
82
  try {
81
83
  doc = parseYaml(fs.readFileSync(flowSource, "utf8"));
82
84
  } catch {
83
- return out;
85
+ return Object.create(null);
84
86
  }
87
+ return handlerPathsFromDoc(doc, flowSource, cwd);
88
+ }
89
+
90
+ /**
91
+ * Handler files pi-flows would run for an already-parsed flow document: the
92
+ * {@link codeHandlerPaths} rules without the disk read (the `flow_open`
93
+ * admission reads through the host guard). See change: add-flow-open-tool.
94
+ */
95
+ export function handlerPathsFromDoc(doc: unknown, flowSource: string, cwd: string | undefined): Record<string, string> {
96
+ const out: Record<string, string> = Object.create(null);
85
97
  const steps = (doc as { steps?: unknown } | null)?.steps;
86
98
  if (!Array.isArray(steps)) return out;
87
99
  for (const raw of steps) {
@@ -99,8 +111,71 @@ export function codeHandlerPaths(flowSource: string, cwd: string | undefined): R
99
111
  return out;
100
112
  }
101
113
 
114
+ /** True when canonical `p` is `root` or lies beneath it (`root` `/` included). */
115
+ export function isInside(p: string, root: string): boolean {
116
+ if (p === root) return true;
117
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
118
+ return p.startsWith(prefix);
119
+ }
120
+
121
+ /** One path-opened flow's readable files (canonical, confined to `cwd`). See change: add-flow-open-tool. */
122
+ export interface OpenedFlowFiles {
123
+ /** Canonical definition file. */
124
+ def: string;
125
+ /** step id → handler file. */
126
+ handlers: Record<string, string>;
127
+ /** agent name → agent file. */
128
+ agents: Record<string, string>;
129
+ }
130
+
131
+ interface OpenedEntry extends OpenedFlowFiles {
132
+ /** lookup key → canonical file. */
133
+ allowed: Map<string, string>;
134
+ /** realpath of the session cwd at admission. */
135
+ cwd: string;
136
+ }
137
+
102
138
  export class FlowFileRegistry {
103
139
  private readonly bySession = new Map<string, SessionFiles>();
140
+ /** Path-opened flows per session, by display name; independent of `report()`. */
141
+ private readonly opened = new Map<string, Map<string, OpenedEntry>>();
142
+
143
+ /**
144
+ * Admit one path-opened flow's files for one session. Every file must be
145
+ * canonically inside `cwdReal`; others are dropped. Survives `report()`.
146
+ * See change: add-flow-open-tool (D3).
147
+ */
148
+ open(sessionId: string, name: string, files: OpenedFlowFiles, cwdReal: string): void {
149
+ const allowed = new Map<string, string>();
150
+ const keep = (file: string): boolean => {
151
+ const real = canonical(file);
152
+ if (!isInside(real, cwdReal)) return false;
153
+ allowed.set(path.resolve(file), real);
154
+ allowed.set(real, real);
155
+ return true;
156
+ };
157
+ if (!keep(files.def)) return;
158
+ const pick = (m: Record<string, string>) => {
159
+ const out: Record<string, string> = Object.create(null);
160
+ // Publish the canonical file admitted now, so `/files` and `/file` agree. (CodeRabbit)
161
+ for (const [k, f] of Object.entries(m)) if (keep(f)) out[k] = canonical(f);
162
+ return out;
163
+ };
164
+ const handlers = pick(files.handlers);
165
+ const agents = pick(files.agents);
166
+ let perSession = this.opened.get(sessionId);
167
+ if (!perSession) {
168
+ perSession = new Map();
169
+ this.opened.set(sessionId, perSession);
170
+ }
171
+ perSession.delete(name);
172
+ perSession.set(name, { def: canonical(files.def), handlers, agents, allowed, cwd: cwdReal });
173
+ while (perSession.size > MAX_OPENED_PER_SESSION) {
174
+ const oldest = perSession.keys().next().value;
175
+ if (oldest === undefined) break;
176
+ perSession.delete(oldest);
177
+ }
178
+ }
104
179
 
105
180
  /** Replace a session's report. `cwd` resolves explicit code `target:`s. */
106
181
  report(sessionId: string, report: FlowFilesReport | null | undefined, cwd?: string): void {
@@ -129,11 +204,17 @@ export class FlowFileRegistry {
129
204
  }
130
205
 
131
206
  has(sessionId: string): boolean {
207
+ return this.bySession.has(sessionId) || this.opened.has(sessionId);
208
+ }
209
+
210
+ /** True once the session's bridge has reported (path-opened entries alone do not count). */
211
+ hasReport(sessionId: string): boolean {
132
212
  return this.bySession.has(sessionId);
133
213
  }
134
214
 
135
215
  remove(sessionId: string): void {
136
216
  this.bySession.delete(sessionId);
217
+ this.opened.delete(sessionId);
137
218
  }
138
219
 
139
220
  /**
@@ -143,7 +224,24 @@ export class FlowFileRegistry {
143
224
  */
144
225
  resolveAllowed(sessionId: string, filePath: string): string | null {
145
226
  if (!path.isAbsolute(filePath)) return null;
146
- return this.bySession.get(sessionId)?.allowed.get(path.resolve(filePath)) ?? null;
227
+ const key = path.resolve(filePath);
228
+ const reported = this.bySession.get(sessionId)?.allowed.get(key);
229
+ if (reported) return reported;
230
+ // Path-opened files: re-check on every read that the stored canonical file
231
+ // is unchanged (no symlink swapped in) and still inside the cwd.
232
+ // See change: add-flow-open-tool (D3).
233
+ for (const entry of this.opened.get(sessionId)?.values() ?? []) {
234
+ const stored = entry.allowed.get(key);
235
+ if (!stored) continue;
236
+ let now: string;
237
+ try {
238
+ now = fs.realpathSync(stored);
239
+ } catch {
240
+ return null;
241
+ }
242
+ return now === stored && isInside(now, entry.cwd) ? stored : null;
243
+ }
244
+ return null;
147
245
  }
148
246
 
149
247
  /** True when `filePath` is exactly one of the session's reported files. */
@@ -154,22 +252,42 @@ export class FlowFileRegistry {
154
252
  /** Agent sources + per-flow code handler paths for one session. */
155
253
  files(sessionId: string): { agents: Record<string, string>; handlers: Record<string, Record<string, string>> } | null {
156
254
  const s = this.bySession.get(sessionId);
157
- return s ? { agents: { ...s.agents }, handlers: { ...s.handlers } } : null;
255
+ const opened = this.opened.get(sessionId);
256
+ if (!s && !opened) return null;
257
+ const agents: Record<string, string> = { ...s?.agents };
258
+ const handlers: Record<string, Record<string, string>> = { ...s?.handlers };
259
+ for (const [name, e] of opened ?? []) {
260
+ handlers[name] = { ...e.handlers };
261
+ for (const [a, f] of Object.entries(e.agents)) agents[a] ??= f;
262
+ }
263
+ return { agents, handlers };
158
264
  }
159
265
 
160
266
  /** Drop sessions no longer live. */
161
267
  retainOnly(liveIds: ReadonlySet<string>): void {
162
268
  for (const id of this.bySession.keys()) if (!liveIds.has(id)) this.bySession.delete(id);
269
+ for (const id of this.opened.keys()) if (!liveIds.has(id)) this.opened.delete(id);
163
270
  }
164
271
  }
165
272
 
166
273
 
167
- const flowFileRegistry = new FlowFileRegistry();
274
+ /** The one registry the routes and the `flow/open` lane share (D3). */
275
+ export const flowFileRegistry = new FlowFileRegistry();
168
276
 
169
277
  interface RouteDeps {
170
278
  fastify: ServerPluginContext["fastify"];
171
279
  networkGuard: ServerPluginContext["networkGuard"];
172
- registerPiRequestHandler?: (type: string, h: (payload: unknown, meta: { sessionId: string }) => unknown) => void;
280
+ /**
281
+ * Host guard for reading file CONTENT (state / pi-agent-credential refusal on the real path + post-open
282
+ * recheck). `null` or an absent seam (older host) refuses — never a plain `fs` fallback.
283
+ * See change: close-security-map-high-findings (D1, H1).
284
+ */
285
+ readFileGuarded?: ServerPluginContext["readFileGuarded"];
286
+ registerPiRequestHandler?: (
287
+ type: string,
288
+ h: (payload: unknown, meta: { sessionId: string }) => unknown,
289
+ opts?: { hubLocalOnly?: boolean },
290
+ ) => void;
173
291
  sessionManager: { listActive(): unknown[]; getSession(id: string): unknown };
174
292
  emitEventToSession: (sessionId: string, eventType: string, data: Record<string, unknown>) => boolean;
175
293
  registry?: FlowFileRegistry;
@@ -218,7 +336,10 @@ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
218
336
  const cwd = typeof session?.cwd === "string" ? session.cwd : undefined;
219
337
  registry.report(meta.sessionId, payload as FlowFilesReport, cwd);
220
338
  return { ok: true };
221
- });
339
+ // The report stores absolute paths the bridge CLAIMS, which the hub later reads from its own disk:
340
+ // a remote session's paths name its own disk. Hub-local sessions only.
341
+ // See change: harden-bridge-session-claim (D3).
342
+ }, { hubLocalOnly: true });
222
343
 
223
344
  // Routes live in an encapsulated scope carrying a request rate limit
224
345
  // (recognized by CodeQL js/missing-rate-limiting; same pattern as
@@ -230,8 +351,10 @@ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
230
351
  const sessionId = liveSession(req.query);
231
352
  if (!sessionId) return reply.code(404).send({ success: false, error: "session not found" });
232
353
  const files = registry.files(sessionId);
354
+ // A path-opened flow alone answers `reported: true`, but still asks for the
355
+ // catalog report. See change: add-flow-open-tool.
356
+ if (!registry.hasReport(sessionId)) requestReport(sessionId);
233
357
  if (!files) {
234
- requestReport(sessionId);
235
358
  return { success: true, data: { reported: false, agents: {}, handlers: {} } };
236
359
  }
237
360
  return { success: true, data: { reported: true, ...files } };
@@ -244,8 +367,8 @@ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
244
367
  if (typeof filePath !== "string" || !filePath) {
245
368
  return reply.code(400).send({ success: false, error: "path parameter required" });
246
369
  }
370
+ if (!registry.hasReport(sessionId)) requestReport(sessionId);
247
371
  if (!registry.has(sessionId)) {
248
- requestReport(sessionId);
249
372
  return reply.code(409).send({ success: false, error: "not reported yet", retry: true });
250
373
  }
251
374
  const target = registry.resolveAllowed(sessionId, filePath);
@@ -254,7 +377,10 @@ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
254
377
  }
255
378
  if (!isSmallFile(target)) return reply.code(404).send({ success: false, error: "not found" });
256
379
  try {
257
- const content = await fs.promises.readFile(target, "utf8");
380
+ const content = deps.readFileGuarded ? await deps.readFileGuarded(target) : null;
381
+ if (content === null) {
382
+ return reply.code(403).send({ success: false, error: "not a flow file of this session" });
383
+ }
258
384
  return { success: true, data: { type: "file", content } };
259
385
  } catch {
260
386
  return reply.code(404).send({ success: false, error: "not found" });