@blackbelt-technology/pi-dashboard-flows-plugin 0.10.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 (72) hide show
  1. package/README.md +5 -1
  2. package/package.json +33 -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 +47 -9
  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 -18
  33. package/src/client/SessionFlowActions.tsx +65 -10
  34. package/src/client/SessionFlowMenuClaim.tsx +48 -248
  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-inputs.ts +56 -1
  63. package/src/server/flow-open.ts +385 -0
  64. package/src/server/index.ts +123 -40
  65. package/src/server/render-actions.ts +3 -2
  66. package/src/server/state-store.ts +11 -5
  67. package/src/types.ts +180 -0
  68. package/src/bridge/flow-question-adapter.ts +0 -93
  69. package/src/client/FlowQuestionCard.tsx +0 -218
  70. package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
  71. package/src/client/FlowsCommandRoutes.tsx +0 -245
  72. package/src/client/flow-yaml-parse.ts +0 -140
@@ -13,6 +13,12 @@
13
13
  */
14
14
  import fs from "node:fs";
15
15
  import path from "node:path";
16
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
17
+ import type { AdmitCwdOptions } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
18
+ import {
19
+ admitRouteCwdParam,
20
+ sendRouteCwdRefusal,
21
+ } from "@blackbelt-technology/pi-dashboard-shared/plugin-route-cwd.js";
16
22
  import { parse as parseYaml } from "yaml";
17
23
 
18
24
  export type FlowInputType = "string" | "number" | "boolean" | "object" | "array";
@@ -24,10 +30,24 @@ export interface FlowInputField {
24
30
  required: boolean;
25
31
  }
26
32
 
33
+ /** A path segment that would climb or stay put (`.` / `..`) — never a flow namespace or name. */
34
+ const isDotSegment = (s: string): boolean => s === "." || s === "..";
35
+
36
+ /**
37
+ * Whether a flow id could escape the flows dir: exactly `.` / `..`, or any path separator.
38
+ * Only EXACT dot segments count — `team.review`, `a..b`, `...`, `.hidden`, `x.` stay valid.
39
+ * For the `<ns>:<name>` form each segment is checked, since `..:x` would climb.
40
+ * See change: harden-git-terminal-plugin-boundaries (S1r).
41
+ */
42
+ function isTraversalFlowId(flowId: string): boolean {
43
+ if (flowId.includes("/") || flowId.includes("\\")) return true;
44
+ return flowId.split(":").some(isDotSegment);
45
+ }
46
+
27
47
  /** Resolve a `<ns>:<name>` flow id to its `flow.yaml` path under `cwd`. */
28
48
  export function flowYamlPath(cwd: string, flowId: string): string | null {
29
49
  const m = /^([\w.-]+):([\w.-]+)$/.exec(flowId);
30
- if (!m) return null;
50
+ if (!m || isDotSegment(m[1]) || isDotSegment(m[2])) return null;
31
51
  return path.join(cwd, ".pi", "flows", "flows", m[1], m[2], "flow.yaml");
32
52
  }
33
53
 
@@ -56,3 +76,38 @@ export function readFlowInputs(cwd: string, flowId: string): FlowInputField[] {
56
76
  }
57
77
  return out;
58
78
  }
79
+
80
+ export interface FlowInputsRouteDeps {
81
+ /** Live admit set (host known folders), read per request. Fail-closed default: nothing known. */
82
+ knownCwds?: () => string[];
83
+ /** `admitCwd` options (the host's throttled `onIndeterminate` logger; test seams). */
84
+ admitOptions?: AdmitCwdOptions;
85
+ }
86
+
87
+ /**
88
+ * `GET /api/plugins/flows/flow-inputs?cwd=&flow=` — read-only. The cwd is REQUIRED and admitted
89
+ * (400 `invalid_cwd` / `cwd_required`, 403, 503) before any flow file is read — there is no
90
+ * `process.cwd()` fallback — and a traversal-shaped flow id is 400 `invalid_flow_id`.
91
+ * See change: wire-flow-inputs-in-automation; harden-git-terminal-plugin-boundaries (S1r).
92
+ */
93
+ export function mountFlowInputsRoute(fastify: ServerPluginContext["fastify"], deps: FlowInputsRouteDeps = {}): void {
94
+ fastify.get("/api/plugins/flows/flow-inputs", async (req, reply) => {
95
+ const q = (req.query ?? {}) as Record<string, unknown>;
96
+ const adm = await admitRouteCwdParam(q.cwd, {
97
+ required: true,
98
+ ...(deps.knownCwds ? { knownCwds: deps.knownCwds } : {}),
99
+ ...(deps.admitOptions ? { admitOptions: deps.admitOptions } : {}),
100
+ });
101
+ if (!adm.ok) return sendRouteCwdRefusal(reply, adm);
102
+ try {
103
+ const flow = typeof q.flow === "string" ? q.flow : "";
104
+ if (flow && isTraversalFlowId(flow)) {
105
+ reply.code(400);
106
+ return { error: "invalid_flow_id", message: "flow id must not contain path separators or dot segments" };
107
+ }
108
+ return { inputs: flow && adm.cwd ? readFlowInputs(adm.cwd, flow) : [] };
109
+ } finally {
110
+ adm.release();
111
+ }
112
+ });
113
+ }
@@ -0,0 +1,385 @@
1
+ /**
2
+ * `flow/open` request lane — the server half of the agent `flow_open` tool.
3
+ *
4
+ * - `flow` → catalog lookup (polled rediscovery, retried while the ask
5
+ * cooldown suppresses it) → runnable catalog attachment.
6
+ * - `path` → admission (D2): resolve against the session cwd, realpath,
7
+ * directory → direct `flow.yaml|flow.yml`, regular file ≤ MAX_FILE_BYTES,
8
+ * confinement to `realpath(cwd)`; only THEN a guarded read + parse. A path
9
+ * equal to a catalog definition collapses to that catalog flow (D4);
10
+ * otherwise the flow's own files are admitted into the shared
11
+ * `FlowFileRegistry` (D3) and the attachment is view-only.
12
+ * - Delivery (D5): `flows_open` broadcast with a server-stamped baseline,
13
+ * `flows_open_ack` counted per socket for a fixed 1.5 s window.
14
+ * - Rate limit 10 / 10 s per session, one log line per call (D8).
15
+ *
16
+ * Never logs file content. See change: add-flow-open-tool.
17
+ */
18
+ import { randomUUID } from "node:crypto";
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { parse as parseYaml } from "yaml";
22
+ import type { FlowCatalogEntry } from "../flow-catalog-contract.js";
23
+ import { isValidFlowName } from "./flow-control.js";
24
+ import { type FlowFileRegistry, handlerPathsFromDoc, isInside, MAX_FILE_BYTES } from "./flow-files.js";
25
+
26
+ const FLOW_OPEN_REQUEST = "flow/open";
27
+ const FLOWS_OPEN_FRAME = "flows_open";
28
+ export const FLOWS_OPEN_ACK = "flows_open_ack";
29
+
30
+ /** Fixed acknowledgement window after the broadcast. */
31
+ const ACK_WINDOW_MS = 1_500;
32
+ /** Catalog poll period while waiting for a rediscovered catalog. */
33
+ const CATALOG_POLL_MS = 100;
34
+ /** Bounded pending-ack map (oldest dropped). */
35
+ const MAX_PENDING_ACKS = 64;
36
+ const RATE_MAX_CALLS = 10;
37
+ const RATE_WINDOW_MS = 10_000;
38
+ /** Candidate walk bounds for a directory without a direct flow file. */
39
+ const MAX_CANDIDATES = 20;
40
+ const MAX_CANDIDATE_DEPTH = 6;
41
+ const MAX_PATH_CHARS = 4096;
42
+ /** Most directories the candidate walk visits (caps the scan, not just the answer). */
43
+ const MAX_VISITED_DIRS = 2_000;
44
+ const FLOW_FILE = /^flow\.ya?ml$/;
45
+ const SKIP_DIRS = new Set(["node_modules", ".git"]);
46
+
47
+ type FlowOpenReason =
48
+ | "invalid-arguments"
49
+ | "unknown-flow"
50
+ | "not-a-flow"
51
+ | "path-not-allowed"
52
+ | "flow-running"
53
+ | "rate-limited"
54
+ | "unavailable";
55
+
56
+ export type FlowOpenResult =
57
+ | { status: "shown"; acks: number; name: string; path: string; viewOnly: boolean }
58
+ | { status: "no-viewer"; name: string; path: string; viewOnly: boolean; message: string }
59
+ | { status: "refused"; reason: FlowOpenReason; candidates?: string[] };
60
+
61
+ type Located = { ok: true; def: string } | { ok: false; reason: FlowOpenReason; candidates?: string[] };
62
+
63
+ function realpathOrNull(p: string): string | null {
64
+ try {
65
+ return fs.realpathSync(p);
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ function statOrNull(p: string): fs.Stats | null {
72
+ try {
73
+ return fs.statSync(p);
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** Non-symlink subdirectories of `d` (sorted), skipping `node_modules` / `.git`. */
80
+ function childDirs(d: string): string[] {
81
+ let names: string[];
82
+ try {
83
+ names = fs.readdirSync(d).sort();
84
+ } catch {
85
+ return [];
86
+ }
87
+ return names
88
+ .filter((name) => !SKIP_DIRS.has(name))
89
+ .map((name) => path.join(d, name))
90
+ .filter((child) => {
91
+ try {
92
+ return fs.lstatSync(child).isDirectory();
93
+ } catch {
94
+ return false;
95
+ }
96
+ });
97
+ }
98
+
99
+ /** Regular (non-symlink) `flow.yaml` / `flow.yml` files directly in `dir`. */
100
+ function flowFilesIn(dir: string): string[] {
101
+ return ["flow.yaml", "flow.yml"]
102
+ .map((f) => path.join(dir, f))
103
+ .filter((file) => {
104
+ try {
105
+ return fs.lstatSync(file).isFile();
106
+ } catch {
107
+ return false;
108
+ }
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Up to {@link MAX_CANDIDATES} `flow.yaml|flow.yml` files beneath `dir`,
114
+ * cwd-relative, breadth-first, `lstat` only (no symlink followed), at most
115
+ * {@link MAX_CANDIDATE_DEPTH} directory levels down, skipping `node_modules`
116
+ * and `.git`.
117
+ */
118
+ function findFlowCandidates(dir: string, cwdReal: string): string[] {
119
+ const out: string[] = [];
120
+ let level: string[] = [dir];
121
+ let visited = 0;
122
+ for (let depth = 1; depth <= MAX_CANDIDATE_DEPTH && level.length > 0; depth++) {
123
+ const next: string[] = [];
124
+ for (const d of level) {
125
+ if (++visited > MAX_VISITED_DIRS) return out;
126
+ next.push(...childDirs(d));
127
+ }
128
+ level = next;
129
+ for (const child of level) {
130
+ out.push(...flowFilesIn(child).map((file) => path.relative(cwdReal, file)));
131
+ if (out.length >= MAX_CANDIDATES) return out.slice(0, MAX_CANDIDATES);
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** A directory's direct flow file, canonical and confined; or the refusal. */
138
+ function directFlowFile(dir: string, cwdReal: string): Located {
139
+ const direct = ["flow.yaml", "flow.yml"].map((f) => path.join(dir, f)).find((f) => statOrNull(f)?.isFile() === true);
140
+ if (!direct) return { ok: false, reason: "not-a-flow", candidates: findFlowCandidates(dir, cwdReal) };
141
+ const real = realpathOrNull(direct);
142
+ if (real === null) return { ok: false, reason: "not-a-flow" };
143
+ if (!isInside(real, cwdReal)) return { ok: false, reason: "path-not-allowed" };
144
+ return { ok: true, def: real };
145
+ }
146
+
147
+ /**
148
+ * Admission without reading content (D2): canonical location, confinement,
149
+ * name, type, size. `cwdReal` is the realpath of the session cwd.
150
+ */
151
+ function locateFlowPath(input: string, cwd: string, cwdReal: string): Located {
152
+ const abs = path.resolve(cwd, input);
153
+ const real = realpathOrNull(abs);
154
+ if (real === null) {
155
+ // Nonexistent: refuse by where it lexically points.
156
+ const inside = isInside(abs, cwdReal) || isInside(abs, path.resolve(cwd));
157
+ return { ok: false, reason: inside ? "not-a-flow" : "path-not-allowed" };
158
+ }
159
+ if (!isInside(real, cwdReal)) return { ok: false, reason: "path-not-allowed" };
160
+ const st = statOrNull(real);
161
+ if (!st) return { ok: false, reason: "not-a-flow" };
162
+ const located = st.isDirectory() ? directFlowFile(real, cwdReal) : ({ ok: true, def: real } as const);
163
+ if (!located.ok) return located;
164
+ if (!FLOW_FILE.test(path.basename(located.def))) return { ok: false, reason: "not-a-flow" };
165
+ const fst = statOrNull(located.def);
166
+ if (!fst?.isFile() || fst.size > MAX_FILE_BYTES) return { ok: false, reason: "not-a-flow" };
167
+ return located;
168
+ }
169
+
170
+ function isValidPathArg(v: unknown): v is string {
171
+ return typeof v === "string" && v.length > 0 && v.length <= MAX_PATH_CHARS && !v.includes("\0");
172
+ }
173
+
174
+ /** Agent names the definition's steps reference (`agent:`). */
175
+ function agentNames(doc: unknown): string[] {
176
+ const steps = (doc as { steps?: unknown } | null)?.steps;
177
+ if (!Array.isArray(steps)) return [];
178
+ const out: string[] = [];
179
+ for (const s of steps) {
180
+ const a = (s as { agent?: unknown } | null)?.agent;
181
+ if (typeof a === "string" && a) out.push(a);
182
+ }
183
+ return out;
184
+ }
185
+
186
+ export interface FlowOpenDeps {
187
+ registerPiRequestHandler?: (
188
+ type: string,
189
+ h: (payload: unknown, meta: { sessionId: string }) => unknown,
190
+ opts?: { hubLocalOnly?: boolean },
191
+ ) => void;
192
+ registerBrowserHandler: (type: string, h: (msg: unknown, ws: unknown) => void) => void;
193
+ broadcastToSubscribers: (msg: unknown) => void;
194
+ sessionManager: { getSession(id: string): unknown };
195
+ onSessionEnded?: (h: (sessionId: string) => void) => () => void;
196
+ store: { getState(id: string): { flows?: FlowCatalogEntry[] } | undefined };
197
+ requestCatalog: (sessionId: string, opts?: { rediscover?: boolean }) => boolean;
198
+ registry: FlowFileRegistry;
199
+ readFileGuarded?: (absPath: string) => Promise<string | null>;
200
+ logger: { info(m: string): void };
201
+ }
202
+
203
+ export interface FlowOpenController {
204
+ handle(payload: unknown, meta: { sessionId: string }): Promise<FlowOpenResult>;
205
+ /** Test seams. */
206
+ pendingSize(): number;
207
+ limiterSize(): number;
208
+ dispose(): void;
209
+ }
210
+
211
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
212
+
213
+ export function registerFlowOpen(deps: FlowOpenDeps): FlowOpenController {
214
+ const pending = new Map<string, { sessionId: string; acks: Set<unknown> }>();
215
+ const calls = new Map<string, number[]>();
216
+
217
+ const offEnded = deps.onSessionEnded?.((sessionId) => calls.delete(sessionId));
218
+
219
+ deps.registerBrowserHandler(FLOWS_OPEN_ACK, (msg, ws) => {
220
+ const m = msg as { sessionId?: unknown; requestId?: unknown } | null;
221
+ if (typeof m?.requestId !== "string") return;
222
+ const p = pending.get(m.requestId);
223
+ if (!p || p.sessionId !== m.sessionId) return;
224
+ p.acks.add(ws);
225
+ });
226
+
227
+ const rateLimited = (sessionId: string): boolean => {
228
+ const now = Date.now();
229
+ const recent = (calls.get(sessionId) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
230
+ if (recent.length >= RATE_MAX_CALLS) {
231
+ calls.set(sessionId, recent);
232
+ return true;
233
+ }
234
+ recent.push(now);
235
+ calls.set(sessionId, recent);
236
+ return false;
237
+ };
238
+
239
+ const catalogEntry = (sessionId: string, name: string) =>
240
+ deps.store.getState(sessionId)?.flows?.find((f) => f.name === name);
241
+
242
+ /** Catalog hit, or rediscover and poll up to the window (retrying a suppressed ask). */
243
+ const findCatalogFlow = async (sessionId: string, name: string): Promise<FlowCatalogEntry | undefined> => {
244
+ let hit = catalogEntry(sessionId, name);
245
+ if (hit) return hit;
246
+ let asked = false;
247
+ const deadline = Date.now() + ACK_WINDOW_MS;
248
+ while (Date.now() < deadline) {
249
+ if (!asked) asked = deps.requestCatalog(sessionId, { rediscover: true });
250
+ await sleep(CATALOG_POLL_MS);
251
+ hit = catalogEntry(sessionId, name);
252
+ if (hit) return hit;
253
+ }
254
+ return undefined;
255
+ };
256
+
257
+ const deliver = async (
258
+ sessionId: string,
259
+ att: { name: string; source: string; viewOnly: boolean },
260
+ relPath: string,
261
+ acceptedAt: number,
262
+ ): Promise<FlowOpenResult> => {
263
+ const requestId = randomUUID();
264
+ const acks = new Set<unknown>();
265
+ // Never evict a pending ack whose window is still open: refuse instead.
266
+ if (pending.size >= MAX_PENDING_ACKS) return refused("rate-limited");
267
+ pending.set(requestId, { sessionId, acks });
268
+ deps.broadcastToSubscribers({
269
+ type: FLOWS_OPEN_FRAME,
270
+ sessionId,
271
+ requestId,
272
+ attachment: { ...att, baselineStartedAt: acceptedAt },
273
+ });
274
+ await sleep(ACK_WINDOW_MS);
275
+ pending.delete(requestId);
276
+ return acks.size > 0
277
+ ? { status: "shown", acks: acks.size, name: att.name, path: relPath, viewOnly: att.viewOnly }
278
+ : {
279
+ status: "no-viewer",
280
+ name: att.name,
281
+ path: relPath,
282
+ viewOnly: att.viewOnly,
283
+ message: "no viewer confirmed the pin (no dashboard browser showed this session)",
284
+ };
285
+ };
286
+
287
+ const refused = (reason: FlowOpenReason, candidates?: string[]): FlowOpenResult =>
288
+ candidates ? { status: "refused", reason, candidates } : { status: "refused", reason };
289
+
290
+ const cwdOf = (sessionId: string): string | undefined => {
291
+ const session = deps.sessionManager.getSession(sessionId) as { cwd?: unknown } | undefined;
292
+ return typeof session?.cwd === "string" && session.cwd ? session.cwd : undefined;
293
+ };
294
+ const relTo = (cwd: string | undefined, source: string) =>
295
+ cwd && source ? path.relative(cwd, path.resolve(cwd, source)) : source;
296
+
297
+ const openCatalogFlow = async (sessionId: string, flow: unknown, acceptedAt: number): Promise<FlowOpenResult> => {
298
+ if (!isValidFlowName(flow)) return refused("invalid-arguments");
299
+ const entry = await findCatalogFlow(sessionId, flow);
300
+ if (!entry) return refused("unknown-flow");
301
+ const cwd = cwdOf(sessionId);
302
+ return deliver(sessionId, { name: entry.name, source: entry.source, viewOnly: false }, relTo(cwd, entry.source), acceptedAt);
303
+ };
304
+
305
+ /** Guarded read + parse of an admitted definition; a refusal on failure. */
306
+ const readFlowDoc = async (def: string, read: (p: string) => Promise<string | null>): Promise<{ doc: object } | FlowOpenResult> => {
307
+ let doc: unknown;
308
+ try {
309
+ const content = await read(def);
310
+ if (content === null) return refused("path-not-allowed");
311
+ doc = parseYaml(content);
312
+ } catch {
313
+ return refused("not-a-flow");
314
+ }
315
+ if (!doc || typeof doc !== "object" || !Array.isArray((doc as { steps?: unknown }).steps)) return refused("not-a-flow");
316
+ return { doc };
317
+ };
318
+
319
+ const openPathFlow = async (sessionId: string, input: unknown, acceptedAt: number): Promise<FlowOpenResult> => {
320
+ if (!isValidPathArg(input)) return refused("invalid-arguments");
321
+ const cwd = cwdOf(sessionId);
322
+ const read = deps.readFileGuarded;
323
+ const cwdReal = cwd ? realpathOrNull(cwd) : null;
324
+ if (!read || !cwd || cwdReal === null) return refused("unavailable");
325
+ const located = locateFlowPath(input, cwd, cwdReal);
326
+ if (!located.ok) return refused(located.reason, located.candidates);
327
+ const def = located.def;
328
+
329
+ // Same file as a catalog definition → the catalog flow (runnable). D4.
330
+ const catalog = deps.store.getState(sessionId)?.flows?.find((f) => f.source && realpathOrNull(path.resolve(cwd, f.source)) === def);
331
+ if (catalog) return deliver(sessionId, { name: catalog.name, source: catalog.source, viewOnly: false }, relTo(cwd, catalog.source), acceptedAt);
332
+
333
+ const parsed = await readFlowDoc(def, read);
334
+ if (!("doc" in parsed)) return parsed;
335
+ const name = path.relative(cwdReal, def);
336
+ admitOpened(sessionId, name, def, parsed.doc, cwd, cwdReal);
337
+ return deliver(sessionId, { name, source: def, viewOnly: true }, name, acceptedAt);
338
+ };
339
+
340
+ /** Register a path-opened flow's own files (D3); agents only those the session's report resolves. */
341
+ const admitOpened = (sessionId: string, name: string, def: string, doc: object, cwd: string, cwdReal: string) => {
342
+ const reported = deps.registry.files(sessionId)?.agents ?? {};
343
+ const agents: Record<string, string> = Object.create(null);
344
+ for (const a of agentNames(doc)) {
345
+ const file = Object.hasOwn(reported, a) ? reported[a] : undefined;
346
+ if (typeof file === "string") agents[a] = file;
347
+ }
348
+ deps.registry.open(sessionId, name, { def, handlers: handlerPathsFromDoc(doc, def, cwd), agents }, cwdReal);
349
+ };
350
+
351
+ const run = async (sessionId: string, payload: unknown): Promise<FlowOpenResult> => {
352
+ const p = (payload ?? {}) as { flow?: unknown; path?: unknown };
353
+ if (rateLimited(sessionId)) return refused("rate-limited");
354
+ if ((p.flow !== undefined) === (p.path !== undefined)) return refused("invalid-arguments");
355
+ // Baseline = call time, before any catalog wait: a flow started after the
356
+ // call consumes the pin. See change: add-flow-open-tool (D6).
357
+ const acceptedAt = Date.now();
358
+ return p.flow !== undefined ? openCatalogFlow(sessionId, p.flow, acceptedAt) : openPathFlow(sessionId, p.path, acceptedAt);
359
+ };
360
+
361
+ const handle = async (payload: unknown, meta: { sessionId: string }): Promise<FlowOpenResult> => {
362
+ const sessionId = meta.sessionId;
363
+ const p = (payload ?? {}) as { flow?: unknown; path?: unknown };
364
+ const kind = p.flow !== undefined ? "flow" : p.path !== undefined ? "path" : "none";
365
+ let result: FlowOpenResult;
366
+ try {
367
+ result = await run(sessionId, payload);
368
+ } catch {
369
+ result = refused("unavailable");
370
+ }
371
+ const reason = result.status === "refused" ? result.reason : "-";
372
+ const acks = result.status === "shown" ? result.acks : 0;
373
+ deps.logger.info(`flow_open session=${sessionId} kind=${kind} outcome=${result.status} reason=${reason} acks=${acks}`);
374
+ return result;
375
+ };
376
+
377
+ deps.registerPiRequestHandler?.(FLOW_OPEN_REQUEST, handle, { hubLocalOnly: true });
378
+
379
+ return {
380
+ handle,
381
+ pendingSize: () => pending.size,
382
+ limiterSize: () => calls.size,
383
+ dispose: () => offEnded?.(),
384
+ };
385
+ }