@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.
- package/README.md +5 -1
- package/package.json +23 -4
- package/src/bridge/flow-catalog-publisher.ts +138 -0
- package/src/bridge/flow-event-forward.ts +132 -0
- package/src/bridge/flow-files-reporter.ts +16 -14
- package/src/bridge/flow-open-tool.ts +124 -0
- package/src/bridge/flow-probe.ts +20 -0
- package/src/bridge/flow-tool-registry.ts +298 -0
- package/src/bridge/flow-tools-guideline.ts +52 -0
- package/src/bridge/index.ts +67 -10
- package/src/bridge/run-snapshot-reporter.ts +146 -0
- package/src/catalog-timings.ts +70 -0
- package/src/client/AskSession.tsx +82 -0
- package/src/client/FlowActionDialogs.tsx +143 -0
- package/src/client/FlowActivityBadge.tsx +42 -4
- package/src/client/FlowAgentCard.tsx +63 -8
- package/src/client/FlowAgentDetail.tsx +3 -5
- package/src/client/FlowDashboard.tsx +381 -273
- package/src/client/FlowEditMenu.tsx +69 -0
- package/src/client/FlowEditPopover.tsx +130 -0
- package/src/client/FlowGraph.tsx +127 -44
- package/src/client/FlowHeaderActions.tsx +83 -0
- package/src/client/FlowInputWiring.tsx +1 -1
- package/src/client/FlowOpenListener.tsx +82 -0
- package/src/client/FlowQuestionBlock.tsx +226 -0
- package/src/client/FlowStepCards.tsx +189 -0
- package/src/client/FlowSummary.tsx +72 -240
- package/src/client/FlowWriteToolRenderer.tsx +46 -17
- package/src/client/FlowYamlPopoverButton.tsx +2 -2
- package/src/client/FlowsContextGroup.tsx +156 -0
- package/src/client/FlowsSessionStateContext.tsx +202 -54
- package/src/client/FlowsSettings.tsx +145 -17
- package/src/client/SessionFlowActions.tsx +65 -10
- package/src/client/SessionFlowMenuClaim.tsx +48 -241
- package/src/client/ask-session-store.ts +243 -0
- package/src/client/flow-attach-store.ts +2 -0
- package/src/client/flow-card-grid.ts +2 -2
- package/src/client/flow-collapse-storage.ts +36 -6
- package/src/client/flow-edges.ts +91 -35
- package/src/client/flow-files.ts +16 -4
- package/src/client/flow-idle-state.ts +93 -37
- package/src/client/flowsActionsGate.ts +1 -1
- package/src/client/flowsAvailability.ts +8 -2
- package/src/client/index.tsx +13 -11
- package/src/client/shouldRender.ts +1 -1
- package/src/client/useEditModeState.ts +78 -0
- package/src/client/useFlowActions.tsx +191 -0
- package/src/client/useFlowCatalog.ts +69 -0
- package/src/client/useMinuteClock.ts +21 -0
- package/src/client/useRunReattach.ts +50 -0
- package/src/configSchema.json +37 -2
- package/src/flow-catalog-contract.ts +65 -0
- package/src/flow-questions.ts +138 -0
- package/src/flow-reducer.ts +434 -13
- package/src/flow-state-serialize.ts +132 -0
- package/src/i18n.ts +144 -6
- package/src/server/automation-actions.ts +4 -3
- package/src/server/edit-mode.ts +307 -0
- package/src/server/flow-catalog.ts +127 -0
- package/src/server/flow-control.ts +263 -0
- package/src/server/flow-files.ts +140 -14
- package/src/server/flow-open.ts +385 -0
- package/src/server/index.ts +112 -34
- package/src/server/render-actions.ts +3 -2
- package/src/server/state-store.ts +11 -5
- package/src/types.ts +180 -0
- package/src/bridge/flow-question-adapter.ts +0 -93
- package/src/client/FlowQuestionCard.tsx +0 -218
- package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
- package/src/client/FlowsCommandRoutes.tsx +0 -245
- package/src/client/flow-yaml-parse.ts +0 -140
|
@@ -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
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -7,19 +7,25 @@
|
|
|
7
7
|
*
|
|
8
8
|
* See change: adopt-server-driven-intent-rendering.
|
|
9
9
|
*/
|
|
10
|
-
import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
10
|
+
import type { PluginStorePolicy, ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
11
11
|
import type { AdmitCwdOptions } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
|
|
12
12
|
import { provideFlowsActions } from "./automation-actions.js";
|
|
13
|
-
import {
|
|
13
|
+
import { broadcastEditModeState, handleSetEditMode, migrateLegacyEditFlow, registerEditModeRoutes } from "./edit-mode.js";
|
|
14
|
+
import { FLOW_REQUEST_CATALOG_ACTION } from "../flow-catalog-contract.js";
|
|
15
|
+
import { FLOW_RUN_SNAPSHOT_EVENT } from "../flow-state-serialize.js";
|
|
16
|
+
import { registerFlowCatalog } from "./flow-catalog.js";
|
|
17
|
+
import { flowFileRegistry, registerFlowFileRoutes } from "./flow-files.js";
|
|
18
|
+
import { registerFlowOpen } from "./flow-open.js";
|
|
14
19
|
import { mountFlowInputsRoute } from "./flow-inputs.js";
|
|
20
|
+
import { FLOW_CONTROL_ACTIONS, type FlowControlDeps, registerFlowControlRoute, runFlowControl } from "./flow-control.js";
|
|
15
21
|
import { renderSessionFlowActions } from "./render-actions.js";
|
|
16
22
|
import { stateStore } from "./state-store.js";
|
|
17
23
|
|
|
18
24
|
const PLUGIN_ID = "flows";
|
|
19
25
|
|
|
20
26
|
/**
|
|
21
|
-
* Resolve the flows available in a folder from the LIVE per-session
|
|
22
|
-
* (`stateStore`,
|
|
27
|
+
* Resolve the flows available in a folder from the LIVE per-session flow catalog
|
|
28
|
+
* (`stateStore`, fed by forwarded `flow_catalog` events), by mapping
|
|
23
29
|
* the cwd to its running session(s) and unioning their reported `<ns>:<name>`
|
|
24
30
|
* ids. Reflects package-bundled and event-registered flows that a static
|
|
25
31
|
* `.pi/flows/flows` scan would miss; empty when no running session matches the
|
|
@@ -44,12 +50,34 @@ export function makeFlowsForCwd(
|
|
|
44
50
|
};
|
|
45
51
|
}
|
|
46
52
|
|
|
53
|
+
const snapshotRunId = (data: unknown): unknown => (data as { runId?: unknown } | null | undefined)?.runId;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Store policy: a `flow_run_snapshot` is stored intact (the bridge budget keeps
|
|
57
|
+
* it under the ceiling; the generic caps would collapse its agents and history)
|
|
58
|
+
* and supersedes older snapshots of the same run. Every other flow event keeps
|
|
59
|
+
* the generic path. See change: fix-flow-reattach-per-run-state (D4).
|
|
60
|
+
*/
|
|
61
|
+
export const FLOWS_STORE_POLICY: PluginStorePolicy = {
|
|
62
|
+
bound: (event) => (event.eventType === FLOW_RUN_SNAPSHOT_EVENT ? event : undefined),
|
|
63
|
+
onStored: (event, view) => {
|
|
64
|
+
const runId = snapshotRunId(event.data);
|
|
65
|
+
if (event.eventType !== FLOW_RUN_SNAPSHOT_EVENT || typeof runId !== "string" || !runId) return undefined;
|
|
66
|
+
const older: number[] = [];
|
|
67
|
+
for (const r of view.resident()) {
|
|
68
|
+
if (r.event.eventType === FLOW_RUN_SNAPSHOT_EVENT && snapshotRunId(r.event.data) === runId) older.push(r.seq);
|
|
69
|
+
}
|
|
70
|
+
return older;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
47
74
|
/**
|
|
48
75
|
* Plugin entrypoint called by the dashboard plugin loader at boot.
|
|
49
76
|
*/
|
|
50
77
|
export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
51
78
|
const { logger, broadcastToSubscribers, registerBrowserHandler, emitEventToSession, sendToSession } = ctx;
|
|
52
79
|
logger.info("flows-plugin server entry activated (server-driven intents)");
|
|
80
|
+
ctx.registerStorePolicy?.(FLOWS_STORE_POLICY);
|
|
53
81
|
|
|
54
82
|
// Publish the flows automation action (flows.run) for the automation plugin
|
|
55
83
|
// to collect. Pure publisher: no consume, no automation dependency, no load
|
|
@@ -82,11 +110,58 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
82
110
|
await registerFlowFileRoutes({
|
|
83
111
|
fastify: ctx.fastify,
|
|
84
112
|
networkGuard: ctx.networkGuard,
|
|
113
|
+
readFileGuarded: ctx.readFileGuarded,
|
|
85
114
|
registerPiRequestHandler: ctx.registerPiRequestHandler,
|
|
86
115
|
sessionManager: ctx.sessionManager,
|
|
87
116
|
emitEventToSession,
|
|
117
|
+
registry: flowFileRegistry,
|
|
88
118
|
});
|
|
89
119
|
|
|
120
|
+
// Flow catalog: feed stateStore from forwarded `flow_catalog` events, ask
|
|
121
|
+
// sessions to report (client ask, sibling follow, server start).
|
|
122
|
+
// See change: flows-dock-chip-and-panel-actions (D3, D4).
|
|
123
|
+
const catalog = registerFlowCatalog({
|
|
124
|
+
onEvent: ctx.onEvent,
|
|
125
|
+
onSessionEnded: ctx.onSessionEnded,
|
|
126
|
+
sessionManager: ctx.sessionManager,
|
|
127
|
+
emitEventToSession,
|
|
128
|
+
getPluginConfig: () => ctx.getPluginConfig<Record<string, unknown>>() ?? {},
|
|
129
|
+
store: stateStore,
|
|
130
|
+
logger,
|
|
131
|
+
});
|
|
132
|
+
catalog.startServerStartAsks();
|
|
133
|
+
|
|
134
|
+
// Agent `flow_open` tool (bridge) → `flow/open` lane: catalog or path flow,
|
|
135
|
+
// admitted path files join the SAME file registry the routes serve from.
|
|
136
|
+
// See change: add-flow-open-tool.
|
|
137
|
+
registerFlowOpen({
|
|
138
|
+
registerPiRequestHandler: ctx.registerPiRequestHandler,
|
|
139
|
+
registerBrowserHandler,
|
|
140
|
+
broadcastToSubscribers,
|
|
141
|
+
sessionManager: ctx.sessionManager,
|
|
142
|
+
onSessionEnded: ctx.onSessionEnded,
|
|
143
|
+
store: stateStore,
|
|
144
|
+
requestCatalog: catalog.requestCatalog,
|
|
145
|
+
registry: flowFileRegistry,
|
|
146
|
+
readFileGuarded: ctx.readFileGuarded,
|
|
147
|
+
logger,
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// Edit mode: global default (`~/.pi/agent/settings.json#flows.editFlow`) +
|
|
151
|
+
// per-session effective state, read-only except the guarded global PUT.
|
|
152
|
+
// The dashboard never writes a repo's `.pi/settings.json` on its own.
|
|
153
|
+
// See change: stop-flows-edit-mode-project-writes (D2, D4).
|
|
154
|
+
const editModeDeps = { sessionManager: ctx.sessionManager, broadcastToSubscribers };
|
|
155
|
+
await registerEditModeRoutes({ ...editModeDeps, fastify: ctx.fastify, networkGuard: ctx.networkGuard });
|
|
156
|
+
|
|
157
|
+
// One-time legacy plugin-config `editFlow` → global file (D6). A failure
|
|
158
|
+
// keeps the key so the next start retries.
|
|
159
|
+
try {
|
|
160
|
+
if ((await migrateLegacyEditFlow(ctx, { logger })) === "migrated") broadcastEditModeState(editModeDeps);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
logger.warn(`flows: legacy editFlow migration failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
163
|
+
}
|
|
164
|
+
|
|
90
165
|
/**
|
|
91
166
|
* Broadcast the current intent tree for one session's slot.
|
|
92
167
|
* Called from action handlers AND in response to event-store changes
|
|
@@ -104,6 +179,24 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
104
179
|
});
|
|
105
180
|
}
|
|
106
181
|
|
|
182
|
+
// Flow commands (Abort / Auto / Dismiss / Run / Delete / Edit mode): shared
|
|
183
|
+
// by plugin_action and the REST route. See change: update-flows-plugin (D2).
|
|
184
|
+
const controlDeps: FlowControlDeps = {
|
|
185
|
+
...editModeDeps,
|
|
186
|
+
sessionManager: ctx.sessionManager,
|
|
187
|
+
emitEventToSession,
|
|
188
|
+
logger,
|
|
189
|
+
recordRejectedAction: ctx.recordRejectedAction,
|
|
190
|
+
};
|
|
191
|
+
await registerFlowControlRoute({
|
|
192
|
+
...controlDeps,
|
|
193
|
+
fastify: ctx.fastify,
|
|
194
|
+
networkGuard: ctx.networkGuard,
|
|
195
|
+
hasOperateAuthority: ctx.identity?.hasOperateAuthority
|
|
196
|
+
? (req) => ctx.identity?.hasOperateAuthority?.(req) === true
|
|
197
|
+
: undefined,
|
|
198
|
+
});
|
|
199
|
+
|
|
107
200
|
// Action handler: dispatched from any connected client (or a bus script).
|
|
108
201
|
// The gateway fans out plugin_action by pluginId, so this only fires for
|
|
109
202
|
// pluginId==="flows"; the guard below is defense-in-depth.
|
|
@@ -122,37 +215,14 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
122
215
|
}
|
|
123
216
|
const payload = m.payload ?? {};
|
|
124
217
|
|
|
218
|
+
// The six flow-control actions share validation + relay with the REST
|
|
219
|
+
// route (flow-control.ts). See change: update-flows-plugin (D2).
|
|
220
|
+
if ((FLOW_CONTROL_ACTIONS as readonly string[]).includes(m.action ?? "")) {
|
|
221
|
+
runFlowControl(controlDeps, m.sessionId, m.action as string, payload);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
125
225
|
switch (m.action) {
|
|
126
|
-
case "flow.run": {
|
|
127
|
-
// Accept `flow` (intent path) or `flowName`; run in the target session
|
|
128
|
-
// by emitting the `flow:run` event pi-flows consumes headlessly — the
|
|
129
|
-
// same event the `flow_management run` client path and the automation
|
|
130
|
-
// `flows.run` action dispatch.
|
|
131
|
-
const flowName = String(payload.flow ?? payload.flowName ?? "").trim();
|
|
132
|
-
if (!flowName) {
|
|
133
|
-
logger.warn(`flow.run from session=${m.sessionId}: missing flow name`);
|
|
134
|
-
return;
|
|
135
|
-
}
|
|
136
|
-
const task = typeof payload.task === "string" ? payload.task.trim() : "";
|
|
137
|
-
// Reject a non-object / array `inputs` (typeof [] === "object") — pi-flows
|
|
138
|
-
// consumes it as a keyed record, so an array would be malformed.
|
|
139
|
-
if (
|
|
140
|
-
payload.inputs !== undefined &&
|
|
141
|
-
(payload.inputs === null ||
|
|
142
|
-
typeof payload.inputs !== "object" ||
|
|
143
|
-
Array.isArray(payload.inputs))
|
|
144
|
-
) {
|
|
145
|
-
logger.warn(`flow.run session=${m.sessionId}: invalid inputs (expected object)`);
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
const inputs = payload.inputs as Record<string, unknown> | undefined;
|
|
149
|
-
const data: Record<string, unknown> = { flowName };
|
|
150
|
-
if (task) data.task = task;
|
|
151
|
-
if (inputs) data.inputs = inputs;
|
|
152
|
-
const delivered = emitEventToSession(m.sessionId, "flow:run", data);
|
|
153
|
-
logger.info(`flow.run "${flowName}" session=${m.sessionId} delivered=${delivered}`);
|
|
154
|
-
break;
|
|
155
|
-
}
|
|
156
226
|
case "flow.new": {
|
|
157
227
|
// No dedicated server core — authoring is the manage-flows skill,
|
|
158
228
|
// launched via a slash prompt into the session (mirrors the client's
|
|
@@ -164,8 +234,16 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
164
234
|
logger.info(`flow.new session=${m.sessionId} delivered=${delivered}`);
|
|
165
235
|
break;
|
|
166
236
|
}
|
|
237
|
+
case FLOW_REQUEST_CATALOG_ACTION: {
|
|
238
|
+
// Browser ask while a session's catalog is unknown, or on chip / menu
|
|
239
|
+
// / picker open (`rediscover` re-reads flows from disk first).
|
|
240
|
+
// Rate-limited per session. See change: flows-dock-chip-and-panel-actions (D3).
|
|
241
|
+
catalog.requestCatalog(m.sessionId, { rediscover: payload.rediscover === true });
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
167
244
|
default:
|
|
168
245
|
logger.warn(`unknown flows action: ${m.action}`);
|
|
246
|
+
ctx.recordRejectedAction?.();
|
|
169
247
|
}
|
|
170
248
|
});
|
|
171
249
|
|
|
@@ -19,10 +19,11 @@
|
|
|
19
19
|
* See change: adopt-server-driven-intent-rendering.
|
|
20
20
|
*/
|
|
21
21
|
import type { IntentNode } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/intent-types.js";
|
|
22
|
-
import type {
|
|
22
|
+
import type { CommandInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
23
|
+
import type { FlowCatalogEntry } from "../flow-catalog-contract.js";
|
|
23
24
|
|
|
24
25
|
export interface RenderActionsInput {
|
|
25
|
-
flows:
|
|
26
|
+
flows: FlowCatalogEntry[];
|
|
26
27
|
commands: CommandInfo[];
|
|
27
28
|
}
|
|
28
29
|
|
|
@@ -6,12 +6,17 @@
|
|
|
6
6
|
*
|
|
7
7
|
* See change: adopt-server-driven-intent-rendering.
|
|
8
8
|
*/
|
|
9
|
-
import type {
|
|
9
|
+
import type { CommandInfo, DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
10
|
+
import type { FlowState } from "../types.js";
|
|
11
|
+
import type { FlowCatalogEntry } from "../flow-catalog-contract.js";
|
|
10
12
|
import { isFlowEvent, reduceFlowEvent } from "../flow-reducer.js";
|
|
11
13
|
|
|
12
14
|
export interface FlowsSessionServerState {
|
|
13
|
-
/** Available flows for this session (
|
|
14
|
-
flows:
|
|
15
|
+
/** Available flows for this session (the plugin flow catalog). */
|
|
16
|
+
flows: FlowCatalogEntry[];
|
|
17
|
+
/** True once a `flow_catalog` arrived for this session. See change:
|
|
18
|
+
* flows-dock-chip-and-panel-actions (D4). */
|
|
19
|
+
catalogKnown?: boolean;
|
|
15
20
|
/** Available commands for this session. */
|
|
16
21
|
commands: CommandInfo[];
|
|
17
22
|
/** Current flow state derived from event stream. Null when no flow active. */
|
|
@@ -49,10 +54,11 @@ class StateStore {
|
|
|
49
54
|
return changed;
|
|
50
55
|
}
|
|
51
56
|
|
|
52
|
-
/** Update
|
|
53
|
-
setFlows(sessionId: string, flows:
|
|
57
|
+
/** Update the session's flow catalog (from a forwarded `flow_catalog` event). */
|
|
58
|
+
setFlows(sessionId: string, flows: FlowCatalogEntry[]): void {
|
|
54
59
|
const s = this.ensure(sessionId);
|
|
55
60
|
s.flows = flows;
|
|
61
|
+
s.catalogKnown = true;
|
|
56
62
|
}
|
|
57
63
|
|
|
58
64
|
/** Update available commands list. */
|