@blackbelt-technology/pi-dashboard-flows-plugin 0.8.0 → 0.10.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.
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Per-session registry of the flow files a live session's pi-flows engine
3
+ * actually uses, reported by this plugin's own bridge (`flow:list-flows` +
4
+ * `flow:get-agents`) over the private plugin request lane. Lets the flows UI
5
+ * open a flow's YAML, its agent `.md` files and its code-node handlers even
6
+ * when they live in runtime-registered dirs (`flow:register-flows-dir` /
7
+ * `flow:register-agents-dir`, e.g. InvoiceBot / RackInspect) outside the host's
8
+ * `/api/pi-resource-file` allow-list — without any host-core change.
9
+ *
10
+ * Allowed = EXACT files only (realpath-canonicalized):
11
+ * - each reported flow `source` (`.yaml`/`.yml`)
12
+ * - each reported agent `source` (`.md`)
13
+ * - each code / code-decision handler the engine would run for a reported
14
+ * flow: `target:` → `resolve(sessionCwd, target)`, else
15
+ * `<dirname(flow.source)>/<step id>.ts` (pi-flows 0.5.0 execute-code-step)
16
+ * No sibling, parent dir, or helper file becomes readable.
17
+ * See change: attach-flow-before-run.
18
+ */
19
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
20
+ import rateLimit from "@fastify/rate-limit";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { parse as parseYaml } from "yaml";
24
+ import { FLOW_FILES_REPORT, FLOW_FILES_REQUEST_EVENT, type FlowFilesReport, type ReportedFile } from "../flow-files-contract.js";
25
+
26
+ interface SessionFiles {
27
+ allowed: Map<string, string>;
28
+ /** agent name → absolute agent file. */
29
+ agents: Record<string, string>;
30
+ /** flow name → step id → absolute handler file. */
31
+ handlers: Record<string, Record<string, string>>;
32
+ }
33
+
34
+ const YAML = /\.ya?ml$/i;
35
+ const MARKDOWN = /\.md$/i;
36
+ const HANDLER = /\.[cm]?[jt]s$/i;
37
+ /** Largest file served / parsed (flow files are small text). */
38
+ const MAX_FILE_BYTES = 1024 * 1024;
39
+ /** Largest number of flows / agents accepted per report. */
40
+ const MAX_REPORT_ITEMS = 2000;
41
+ /** Minimum gap between asks to one session's bridge to (re)report. */
42
+ const REPORT_REQUEST_COOLDOWN_MS = 2_000;
43
+
44
+ /** A regular file no larger than {@link MAX_FILE_BYTES}. */
45
+ function isSmallFile(p: string): boolean {
46
+ try {
47
+ const st = fs.statSync(p);
48
+ return st.isFile() && st.size <= MAX_FILE_BYTES;
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function canonical(p: string): string {
55
+ try {
56
+ return fs.realpathSync(p);
57
+ } catch {
58
+ return path.resolve(p);
59
+ }
60
+ }
61
+
62
+ function sanitize(list: unknown, ext: RegExp): ReportedFile[] {
63
+ if (!Array.isArray(list)) return [];
64
+ const out: ReportedFile[] = [];
65
+ for (const item of list.slice(0, MAX_REPORT_ITEMS)) {
66
+ const name = (item as ReportedFile | null)?.name;
67
+ const source = (item as ReportedFile | null)?.source;
68
+ if (typeof name !== "string" || typeof source !== "string") continue;
69
+ if (!path.isAbsolute(source) || !ext.test(source)) continue;
70
+ out.push({ name, source });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** Handler files pi-flows would run for one flow.yaml (read from disk). */
76
+ 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;
79
+ let doc: unknown;
80
+ try {
81
+ doc = parseYaml(fs.readFileSync(flowSource, "utf8"));
82
+ } catch {
83
+ return out;
84
+ }
85
+ const steps = (doc as { steps?: unknown } | null)?.steps;
86
+ if (!Array.isArray(steps)) return out;
87
+ for (const raw of steps) {
88
+ const s = raw as { id?: unknown; type?: unknown; target?: unknown } | null;
89
+ if (!s || typeof s.id !== "string" || s.id === "__proto__") continue;
90
+ if (s.type !== "code" && s.type !== "code-decision") continue;
91
+ let file: string | undefined;
92
+ if (s.target !== undefined && s.target !== null && s.target !== "") {
93
+ if (cwd) file = path.resolve(cwd, String(s.target));
94
+ } else {
95
+ file = path.join(path.dirname(flowSource), `${s.id}.ts`);
96
+ }
97
+ if (file && HANDLER.test(file)) out[s.id] = file;
98
+ }
99
+ return out;
100
+ }
101
+
102
+ export class FlowFileRegistry {
103
+ private readonly bySession = new Map<string, SessionFiles>();
104
+
105
+ /** Replace a session's report. `cwd` resolves explicit code `target:`s. */
106
+ report(sessionId: string, report: FlowFilesReport | null | undefined, cwd?: string): void {
107
+ const flows = sanitize(report?.flows, YAML);
108
+ const agents = sanitize(report?.agents, MARKDOWN);
109
+ // lookup key (as reported / resolved, and its realpath) → canonical file.
110
+ const allowed = new Map<string, string>();
111
+ const allow = (file: string) => {
112
+ const real = canonical(file);
113
+ allowed.set(path.resolve(file), real);
114
+ allowed.set(real, real);
115
+ };
116
+ const agentMap: Record<string, string> = Object.create(null);
117
+ const handlers: Record<string, Record<string, string>> = Object.create(null);
118
+ for (const f of flows) {
119
+ allow(f.source);
120
+ const h = codeHandlerPaths(f.source, cwd);
121
+ handlers[f.name] = h;
122
+ for (const file of Object.values(h)) allow(file);
123
+ }
124
+ for (const a of agents) {
125
+ agentMap[a.name] = a.source;
126
+ allow(a.source);
127
+ }
128
+ this.bySession.set(sessionId, { allowed, agents: agentMap, handlers });
129
+ }
130
+
131
+ has(sessionId: string): boolean {
132
+ return this.bySession.has(sessionId);
133
+ }
134
+
135
+ remove(sessionId: string): void {
136
+ this.bySession.delete(sessionId);
137
+ }
138
+
139
+ /**
140
+ * The stored canonical path when `filePath` is exactly one of the session's
141
+ * reported files, else null. Pure string lookup — the request path never
142
+ * touches the filesystem; callers read only the returned stored path.
143
+ */
144
+ resolveAllowed(sessionId: string, filePath: string): string | null {
145
+ if (!path.isAbsolute(filePath)) return null;
146
+ return this.bySession.get(sessionId)?.allowed.get(path.resolve(filePath)) ?? null;
147
+ }
148
+
149
+ /** True when `filePath` is exactly one of the session's reported files. */
150
+ isAllowed(sessionId: string, filePath: string): boolean {
151
+ return this.resolveAllowed(sessionId, filePath) !== null;
152
+ }
153
+
154
+ /** Agent sources + per-flow code handler paths for one session. */
155
+ files(sessionId: string): { agents: Record<string, string>; handlers: Record<string, Record<string, string>> } | null {
156
+ const s = this.bySession.get(sessionId);
157
+ return s ? { agents: { ...s.agents }, handlers: { ...s.handlers } } : null;
158
+ }
159
+
160
+ /** Drop sessions no longer live. */
161
+ retainOnly(liveIds: ReadonlySet<string>): void {
162
+ for (const id of this.bySession.keys()) if (!liveIds.has(id)) this.bySession.delete(id);
163
+ }
164
+ }
165
+
166
+
167
+ const flowFileRegistry = new FlowFileRegistry();
168
+
169
+ interface RouteDeps {
170
+ fastify: ServerPluginContext["fastify"];
171
+ networkGuard: ServerPluginContext["networkGuard"];
172
+ registerPiRequestHandler?: (type: string, h: (payload: unknown, meta: { sessionId: string }) => unknown) => void;
173
+ sessionManager: { listActive(): unknown[]; getSession(id: string): unknown };
174
+ emitEventToSession: (sessionId: string, eventType: string, data: Record<string, unknown>) => boolean;
175
+ registry?: FlowFileRegistry;
176
+ }
177
+
178
+ function liveIds(sm: RouteDeps["sessionManager"]): Set<string> {
179
+ const ids = new Set<string>();
180
+ for (const s of sm.listActive()) {
181
+ const r = s as { id?: unknown; status?: unknown } | null;
182
+ if (r && typeof r.id === "string" && r.status !== "ended") ids.add(r.id);
183
+ }
184
+ return ids;
185
+ }
186
+
187
+ /**
188
+ * Wire the report lane + `GET /api/plugins/flows/files?sessionId` (agent
189
+ * sources + code handler paths) and `GET /api/plugins/flows/file?sessionId&path`
190
+ * (content of an exact reported file). Both behind the host `networkGuard`.
191
+ * A lookup for a live session with no report yet asks its bridge to report
192
+ * and answers `reported: false` (the client retries).
193
+ */
194
+ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
195
+ const registry = deps.registry ?? flowFileRegistry;
196
+ const lastAsk = new Map<string, number>();
197
+ const requestReport = (sessionId: string) => {
198
+ const now = Date.now();
199
+ if (now - (lastAsk.get(sessionId) ?? 0) < REPORT_REQUEST_COOLDOWN_MS) return;
200
+ lastAsk.set(sessionId, now);
201
+ try {
202
+ deps.emitEventToSession(sessionId, FLOW_FILES_REQUEST_EVENT, {});
203
+ } catch {
204
+ /* best-effort */
205
+ }
206
+ };
207
+ const liveSession = (q: unknown): string | null => {
208
+ const id = (q as { sessionId?: unknown } | null)?.sessionId;
209
+ if (typeof id !== "string" || !id) return null;
210
+ const live = liveIds(deps.sessionManager);
211
+ registry.retainOnly(live);
212
+ for (const sid of lastAsk.keys()) if (!live.has(sid)) lastAsk.delete(sid);
213
+ return live.has(id) ? id : null;
214
+ };
215
+
216
+ deps.registerPiRequestHandler?.(FLOW_FILES_REPORT, (payload, meta) => {
217
+ const session = deps.sessionManager.getSession(meta.sessionId) as { cwd?: unknown } | undefined;
218
+ const cwd = typeof session?.cwd === "string" ? session.cwd : undefined;
219
+ registry.report(meta.sessionId, payload as FlowFilesReport, cwd);
220
+ return { ok: true };
221
+ });
222
+
223
+ // Routes live in an encapsulated scope carrying a request rate limit
224
+ // (recognized by CodeQL js/missing-rate-limiting; same pattern as
225
+ // system-one / gmail). Loopback is allow-listed.
226
+ await deps.fastify.register(async (scope) => {
227
+ await scope.register(rateLimit, { global: true, max: 600, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] });
228
+
229
+ scope.get("/api/plugins/flows/files", { preHandler: deps.networkGuard }, async (req, reply) => {
230
+ const sessionId = liveSession(req.query);
231
+ if (!sessionId) return reply.code(404).send({ success: false, error: "session not found" });
232
+ const files = registry.files(sessionId);
233
+ if (!files) {
234
+ requestReport(sessionId);
235
+ return { success: true, data: { reported: false, agents: {}, handlers: {} } };
236
+ }
237
+ return { success: true, data: { reported: true, ...files } };
238
+ });
239
+
240
+ scope.get("/api/plugins/flows/file", { preHandler: deps.networkGuard }, async (req, reply) => {
241
+ const sessionId = liveSession(req.query);
242
+ const filePath = (req.query as { path?: unknown } | null)?.path;
243
+ if (!sessionId) return reply.code(404).send({ success: false, error: "session not found" });
244
+ if (typeof filePath !== "string" || !filePath) {
245
+ return reply.code(400).send({ success: false, error: "path parameter required" });
246
+ }
247
+ if (!registry.has(sessionId)) {
248
+ requestReport(sessionId);
249
+ return reply.code(409).send({ success: false, error: "not reported yet", retry: true });
250
+ }
251
+ const target = registry.resolveAllowed(sessionId, filePath);
252
+ if (!target) {
253
+ return reply.code(403).send({ success: false, error: "not a flow file of this session" });
254
+ }
255
+ if (!isSmallFile(target)) return reply.code(404).send({ success: false, error: "not found" });
256
+ try {
257
+ const content = await fs.promises.readFile(target, "utf8");
258
+ return { success: true, data: { type: "file", content } };
259
+ } catch {
260
+ return reply.code(404).send({ success: false, error: "not found" });
261
+ }
262
+ });
263
+ });
264
+ }
@@ -10,6 +10,7 @@
10
10
  import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
11
  import { provideFlowsActions } from "./automation-actions.js";
12
12
  import { readFlowInputs } from "./flow-inputs.js";
13
+ import { registerFlowFileRoutes } from "./flow-files.js";
13
14
  import { renderSessionFlowActions } from "./render-actions.js";
14
15
  import { stateStore } from "./state-store.js";
15
16
 
@@ -67,6 +68,20 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
67
68
  return { inputs: flow ? readFlowInputs(cwd, flow) : [] };
68
69
  });
69
70
 
71
+ // Flow YAML / agent / code-handler files reported by this plugin's bridge,
72
+ // so the UI can open files in runtime-registered flow dirs. Plugin-owned
73
+ // (no host allow-list change). Mounted in an encapsulated scope carrying a
74
+ // request rate limit (recognized by CodeQL js/missing-rate-limiting; same
75
+ // pattern as system-one / gmail). Loopback is allow-listed.
76
+ // See change: attach-flow-before-run.
77
+ await registerFlowFileRoutes({
78
+ fastify: ctx.fastify,
79
+ networkGuard: ctx.networkGuard,
80
+ registerPiRequestHandler: ctx.registerPiRequestHandler,
81
+ sessionManager: ctx.sessionManager,
82
+ emitEventToSession,
83
+ });
84
+
70
85
  /**
71
86
  * Broadcast the current intent tree for one session's slot.
72
87
  * Called from action handlers AND in response to event-store changes