@blackbelt-technology/pi-dashboard-flows-plugin 0.8.0 → 0.9.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,152 @@
1
+ /**
2
+ * Client access to a session's flow files (flow YAML, agent `.md`, code-node
3
+ * handlers) via the flows-plugin server (`/api/plugins/flows/file|files`, fed
4
+ * by this plugin's bridge) — so files in runtime-registered flow dirs open —
5
+ * falling back to the host `/api/pi-resource-file` (project `.pi/**`,
6
+ * `~/.pi/agent/**`, `node_modules/**`). Never touches host core.
7
+ * See change: attach-flow-before-run.
8
+ */
9
+ import type { FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { useCallback, useEffect, useState } from "react";
11
+ import { useLocation } from "wouter";
12
+
13
+ const RETRY_MS = 1_200;
14
+
15
+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
16
+
17
+ async function readJson(r: Response): Promise<Record<string, unknown> | null> {
18
+ try {
19
+ return (await r.json()) as Record<string, unknown>;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function contentOf(json: Record<string, unknown> | null): string | null {
26
+ const data = json?.data as { content?: unknown } | undefined;
27
+ return json?.success && typeof data?.content === "string" ? data.content : null;
28
+ }
29
+
30
+ /** Read a flow-related file's content; throws `Error(message)` on failure. */
31
+ export async function fetchFlowFile(sessionId: string | undefined, filePath: string): Promise<string> {
32
+ if (sessionId) {
33
+ const url = `/api/plugins/flows/file?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(filePath)}`;
34
+ for (let attempt = 0; attempt < 2; attempt++) {
35
+ try {
36
+ const r = await fetch(url);
37
+ const json = await readJson(r);
38
+ const content = contentOf(json);
39
+ if (content !== null) return content;
40
+ if (r.status !== 409 || !json?.retry) break;
41
+ await wait(RETRY_MS);
42
+ } catch {
43
+ break; // network / plugin unavailable → host fallback
44
+ }
45
+ }
46
+ }
47
+ const r = await fetch(`/api/pi-resource-file?path=${encodeURIComponent(filePath)}`);
48
+ const json = await readJson(r);
49
+ const content = contentOf(json);
50
+ if (content !== null) return content;
51
+ throw new Error(typeof json?.error === "string" ? json.error : `HTTP ${r.status}`);
52
+ }
53
+
54
+ export interface FlowNodeFiles {
55
+ /** agent name → absolute agent file. */
56
+ agents: Record<string, string>;
57
+ /** flow name → step id → absolute code handler file. */
58
+ handlers: Record<string, Record<string, string>>;
59
+ }
60
+
61
+ /** The session's reported agent + handler file paths (null until known). */
62
+ export function useFlowNodeFiles(sessionId: string | undefined, enabled = true): FlowNodeFiles | null {
63
+ const [files, setFiles] = useState<FlowNodeFiles | null>(null);
64
+ useEffect(() => {
65
+ setFiles(null);
66
+ if (!sessionId || !enabled) return;
67
+ let cancelled = false;
68
+ void (async () => {
69
+ for (let attempt = 0; attempt < 4 && !cancelled; attempt++) {
70
+ try {
71
+ const r = await fetch(`/api/plugins/flows/files?sessionId=${encodeURIComponent(sessionId)}`);
72
+ const json = await readJson(r);
73
+ const data = json?.data as ({ reported?: unknown } & Partial<FlowNodeFiles>) | undefined;
74
+ if (!json?.success || !data) return;
75
+ if (data.reported === true) {
76
+ if (!cancelled) setFiles({ agents: data.agents ?? {}, handlers: data.handlers ?? {} });
77
+ return;
78
+ }
79
+ } catch {
80
+ return;
81
+ }
82
+ await wait(RETRY_MS);
83
+ }
84
+ })();
85
+ return () => {
86
+ cancelled = true;
87
+ };
88
+ }, [sessionId, enabled]);
89
+ return files;
90
+ }
91
+
92
+ /**
93
+ * Fill `sourcePath` (agent file) and `codeTarget` (handler file) on cards that
94
+ * do not carry them yet — idle cards never do, live cards only after
95
+ * `flow_agent_started`. Existing values are never overridden. Returns the SAME
96
+ * state when nothing changes.
97
+ */
98
+ export function withNodeFiles(state: FlowState, files: FlowNodeFiles | null): FlowState {
99
+ if (!files) return state;
100
+ const handlers = files.handlers[state.flowName] ?? {};
101
+ const steps = new Map((state.dagSteps ?? []).map((d) => [d.id, d]));
102
+ let agents: FlowState["agents"] | undefined;
103
+ for (const [key, a] of state.agents) {
104
+ const stepId = a.stepId || key;
105
+ const agentName = steps.get(stepId)?.agent ?? (a.nodeKind === "code" || a.nodeKind === "code-decision" ? undefined : a.agentName);
106
+ const sourcePath = a.sourcePath ?? (agentName ? files.agents[agentName] : undefined);
107
+ const codeTarget = a.codeTarget ?? handlers[stepId];
108
+ if (sourcePath === a.sourcePath && codeTarget === a.codeTarget) continue;
109
+ agents ??= new Map(state.agents);
110
+ agents.set(key, { ...a, sourcePath, codeTarget });
111
+ }
112
+ return agents ? { ...state, agents } : state;
113
+ }
114
+
115
+ /**
116
+ * Open a file in the host's built-in editor (Monaco, Split view) via its
117
+ * `/session/:id/editor?file=<path>` deep link — the same in-app route the
118
+ * host's own file links use. `null` without a session (no editor to target).
119
+ *
120
+ * Every call stamps a fresh `openNonce` into the history entry's state. The URL
121
+ * is byte-identical for the same file, so after the user closes the editor
122
+ * (pane close control, or just the file's tab) a second click would otherwise
123
+ * be indistinguishable from the re-render that follows the close — the host's
124
+ * apply-once key would not change and the split would never come back. The host
125
+ * folds the nonce into that key, so a deliberate open re-applies while a
126
+ * re-render at the same nonce stays a no-op. The nonce stays out of the URL, so
127
+ * a copied deep link is unchanged. See change: consolidate-flow-agent-cards (D8).
128
+ *
129
+ * The nonce must be unique across page loads: `history.state` survives a
130
+ * reload, but this module's counter restarts, so a bare counter would re-mint a
131
+ * value that already sits in the surviving entry (open file → nonce 1 → reload
132
+ * → close → click = nonce 1 again) and the swallowed open would recur. Hence a
133
+ * timestamp prefix plus the counter, as a string (the host accepts
134
+ * number|string).
135
+ */
136
+ let openNonceSeq = 0;
137
+
138
+ const nextOpenNonce = (): string => `${Date.now().toString(36)}-${(++openNonceSeq).toString(36)}`;
139
+
140
+ export function useOpenFileInEditor(sessionId: string | undefined): ((filePath: string) => void) | null {
141
+ const [, navigate] = useLocation();
142
+ const open = useCallback(
143
+ (filePath: string) => {
144
+ if (sessionId)
145
+ navigate(`/session/${encodeURIComponent(sessionId)}/editor?file=${encodeURIComponent(filePath)}`, {
146
+ state: { openNonce: nextOpenNonce() },
147
+ });
148
+ },
149
+ [navigate, sessionId],
150
+ );
151
+ return sessionId ? open : null;
152
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Idle (not-started) flow state for the attach-before-run panel.
3
+ *
4
+ * `buildIdleFlowState` maps a flow.yaml to the step payload pi-flows 0.5.0
5
+ * `onFlowStarted` would emit (per-kind field subset + parser coercions), wraps it
6
+ * in a fake `flow_started` event and replays it through the REAL reducer, so the
7
+ * idle graph + cards equal what a real start shows. Mirrors every 0.5.0 parser
8
+ * throw so a bad definition yields an error instead of a wrong panel.
9
+ *
10
+ * `resolveFlowSlot` decides what the flow slot renders (running → attached →
11
+ * completed → nothing); `isAttachmentConsumed` is the replay catch-up rule.
12
+ *
13
+ * `flow-yaml-parse.ts` (the shallow `flow_write` snapshot parser) is untouched.
14
+ * See change: attach-flow-before-run (D1, D3, D4).
15
+ */
16
+ import type { DashboardEvent, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
17
+ import { parse as parseYaml } from "yaml";
18
+ import { reduceFlowEvent } from "../reducer.js";
19
+
20
+ /** One step of the pi-flows 0.5.0 `flow:flow-started` payload. */
21
+ interface StartedStep {
22
+ id: string;
23
+ stepType: string;
24
+ agent?: string;
25
+ blockedBy: string[];
26
+ branches?: Record<string, string>;
27
+ onError?: string;
28
+ }
29
+
30
+ type Raw = Record<string, unknown>;
31
+
32
+ function requireField(obj: Raw, key: string, where: string): string {
33
+ const v = obj[key];
34
+ if (v === undefined || v === null) throw new Error(`flow.yaml: ${where} missing required field "${key}"`);
35
+ return String(v);
36
+ }
37
+
38
+ function blockedByOf(raw: Raw): string[] {
39
+ if (!raw.blockedBy) return [];
40
+ return Array.isArray(raw.blockedBy) ? raw.blockedBy.map(String) : [String(raw.blockedBy)];
41
+ }
42
+
43
+ function branchesOf(raw: Raw): Record<string, string> {
44
+ const out: Record<string, string> = {};
45
+ if (raw.branches && typeof raw.branches === "object") {
46
+ for (const [k, v] of Object.entries(raw.branches as Raw)) out[k] = String(v);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /** 0.5.0 `toInt`: an optional integer field must parse. */
52
+ function checkInt(obj: Raw, key: string, where: string): void {
53
+ if (obj[key] === undefined) return;
54
+ if (Number.isNaN(Number.parseInt(String(obj[key]), 10))) {
55
+ throw new Error(`flow.yaml: ${where} "${key}" must be an integer`);
56
+ }
57
+ }
58
+
59
+ const INPUT_TYPES = new Set(["string", "number", "boolean", "object", "array"]);
60
+
61
+ /** 0.5.0 `parseFlowInputs`: optional mapping of name → { type }. */
62
+ function checkInputs(raw: unknown): void {
63
+ if (raw === undefined) return;
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error('flow.yaml: "inputs" must be a mapping');
65
+ for (const [k, v] of Object.entries(raw as Raw)) {
66
+ const type = (v as Raw | null)?.type;
67
+ if (typeof type !== "string" || !INPUT_TYPES.has(type)) {
68
+ throw new Error(`flow.yaml: input "${k}" needs a valid "type"`);
69
+ }
70
+ }
71
+ }
72
+
73
+ function onErrorOf(raw: Raw): string | undefined {
74
+ return raw.on_error ? String(raw.on_error) : undefined;
75
+ }
76
+
77
+ /**
78
+ * Map one YAML step to its started-payload shape using the pi-flows 0.5.0
79
+ * per-kind field table (agent: blockedBy+on_error; code: blockedBy+on_error;
80
+ * code-decision: blockedBy+branches; fork: branches (+optional agent);
81
+ * agent-decision: agent+branches). Throws where the 0.5.0 parser throws.
82
+ */
83
+ function toStartedStep(raw: unknown, index: number): StartedStep {
84
+ if (!raw || typeof raw !== "object") throw new Error(`flow.yaml: step ${index} is not an object`);
85
+ const r = raw as Raw;
86
+ const id = r.id;
87
+ if (!id || typeof id !== "string") throw new Error(`flow.yaml: step ${index} missing "id" field`);
88
+ const type = r.type;
89
+ if (!type || typeof type !== "string") throw new Error(`flow.yaml: step "${id}" missing required "type" field`);
90
+ const where = `step "${id}"`;
91
+ checkInt(r, "timeout", where);
92
+ checkInt(r, "max_iterations", where);
93
+ switch (type) {
94
+ case "agent":
95
+ return { id, stepType: type, agent: requireField(r, "agent", where), blockedBy: blockedByOf(r), onError: onErrorOf(r) };
96
+ case "code":
97
+ return { id, stepType: type, blockedBy: blockedByOf(r), onError: onErrorOf(r) };
98
+ case "code-decision":
99
+ return { id, stepType: type, blockedBy: blockedByOf(r), branches: branchesOf(r) };
100
+ case "fork":
101
+ requireField(r, "question", where);
102
+ requireField(r, "options", where);
103
+ return { id, stepType: type, agent: r.agent ? String(r.agent) : undefined, blockedBy: [], branches: branchesOf(r) };
104
+ case "agent-decision": {
105
+ const agent = requireField(r, "agent", where);
106
+ requireField(r, "task", where);
107
+ return { id, stepType: type, agent, blockedBy: [], branches: branchesOf(r) };
108
+ }
109
+ default:
110
+ throw new Error(`flow.yaml: unknown step type "${type}" for step "${id}"`);
111
+ }
112
+ }
113
+
114
+ /** Parse a flow.yaml into the 0.5.0 started-step payload. Throws on any error. */
115
+ function flowYamlToStartedSteps(content: string): StartedStep[] {
116
+ const doc = parseYaml(content) as unknown;
117
+ if (!doc || typeof doc !== "object") throw new Error("flow.yaml: empty or not a mapping");
118
+ requireField(doc as Raw, "name", "flow");
119
+ requireField(doc as Raw, "description", "flow");
120
+ checkInt(doc as Raw, "max_concurrent", "flow");
121
+ checkInputs((doc as Raw).inputs);
122
+ const steps = (doc as Raw).steps;
123
+ if (!Array.isArray(steps)) throw new Error('flow.yaml: "steps" must be an array');
124
+ return steps.map(toStartedStep);
125
+ }
126
+
127
+ export type IdleBuildResult =
128
+ | { kind: "ready"; flowState: FlowState }
129
+ | { kind: "error"; message: string };
130
+
131
+ /** Build the idle FlowState by replaying a fake 0.5.0 `flow_started`. */
132
+ export function buildIdleFlowState(
133
+ content: string,
134
+ flow: { name: string; source?: string },
135
+ ): IdleBuildResult {
136
+ let steps: StartedStep[];
137
+ try {
138
+ steps = flowYamlToStartedSteps(content);
139
+ } catch (err) {
140
+ return { kind: "error", message: err instanceof Error ? err.message : String(err) };
141
+ }
142
+ const event = {
143
+ seq: 0,
144
+ timestamp: 0,
145
+ eventType: "flow_started",
146
+ data: { flowName: flow.name, task: "", source: flow.source, autonomousMode: true, steps },
147
+ } as unknown as DashboardEvent;
148
+ // flow_started always seeds a state from null.
149
+ return { kind: "ready", flowState: reduceFlowEvent(null, event) as FlowState };
150
+ }
151
+
152
+ /** Coerce an event timestamp (number or ISO string) to epoch ms; non-finite → 0. */
153
+ export function toEventTime(ts: unknown): number {
154
+ const n = typeof ts === "string" ? Date.parse(ts) : Number(ts);
155
+ return Number.isFinite(n) ? n : 0;
156
+ }
157
+
158
+ /** Replay catch-up: a `flow_started` strictly newer than the attach baseline. */
159
+ export function isAttachmentConsumed(baselineStartedAt: number | null, lastFlowStartedAt: unknown): boolean {
160
+ if (baselineStartedAt === null) return false;
161
+ if (lastFlowStartedAt === undefined || lastFlowStartedAt === null) return false;
162
+ return toEventTime(lastFlowStartedAt) > baselineStartedAt;
163
+ }
164
+
165
+ /** Stored per-session attachment (see flow-attach-store.ts). */
166
+ export interface FlowAttachment {
167
+ /** Random per-attach token (conditional delete). */
168
+ id: string;
169
+ name: string;
170
+ source?: string;
171
+ baselineStartedAt: number | null;
172
+ }
173
+
174
+ export type IdleLoad =
175
+ | { kind: "loading" }
176
+ | { kind: "error"; message: string }
177
+ | { kind: "ready"; flowState: FlowState };
178
+
179
+ type FlowSlotError = { kind: "unavailable" } | { kind: "load"; message: string };
180
+
181
+ export interface FlowSlot {
182
+ mode: "live" | "idle" | "loading" | "error" | "none";
183
+ flowState?: FlowState;
184
+ error?: FlowSlotError;
185
+ /** True when an attachment exists and has been consumed (caller deletes it). */
186
+ attachmentConsumed: boolean;
187
+ }
188
+
189
+ function findRunning(
190
+ live: FlowState | null,
191
+ liveStates: ReadonlyMap<string, FlowState>,
192
+ ): FlowState | undefined {
193
+ if (live?.status === "running") return live;
194
+ let running: FlowState | undefined;
195
+ for (const s of liveStates.values()) if (s.status === "running") running = s;
196
+ return running;
197
+ }
198
+
199
+ /**
200
+ * Slot priority: running flow → attached (unconsumed) flow → completed flow →
201
+ * nothing. The idle state is only ever returned in `idle` mode; it never enters
202
+ * the live path.
203
+ */
204
+ export function resolveFlowSlot(input: {
205
+ live: FlowState | null;
206
+ liveStates: ReadonlyMap<string, FlowState>;
207
+ attachment: FlowAttachment | null;
208
+ idle: IdleLoad;
209
+ lastFlowStartedAt?: unknown;
210
+ flowsList: ReadonlyArray<{ name: string }>;
211
+ }): FlowSlot {
212
+ const { live, liveStates, attachment, idle, lastFlowStartedAt, flowsList } = input;
213
+ const running = findRunning(live, liveStates);
214
+ if (running) return { mode: "live", flowState: running, attachmentConsumed: !!attachment };
215
+
216
+ if (attachment && !isAttachmentConsumed(attachment.baselineStartedAt, lastFlowStartedAt)) {
217
+ if (flowsList.length > 0 && !flowsList.some((f) => f.name === attachment.name)) {
218
+ return { mode: "error", error: { kind: "unavailable" }, attachmentConsumed: false };
219
+ }
220
+ if (idle.kind === "loading") return { mode: "loading", attachmentConsumed: false };
221
+ if (idle.kind === "error") {
222
+ return { mode: "error", error: { kind: "load", message: idle.message }, attachmentConsumed: false };
223
+ }
224
+ return { mode: "idle", flowState: idle.flowState, attachmentConsumed: false };
225
+ }
226
+
227
+ const consumed = !!attachment;
228
+ if (live) return { mode: "live", flowState: live, attachmentConsumed: consumed };
229
+ return { mode: "none", attachmentConsumed: consumed };
230
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Contract between the flows-plugin bridge and server for reporting a session's
3
+ * flow files (see `bridge/flow-files-reporter.ts`, `server/flow-files.ts`).
4
+ * Import-free leaf so the bridge never pulls server code.
5
+ * See change: attach-flow-before-run.
6
+ */
7
+
8
+ export interface ReportedFile {
9
+ name: string;
10
+ source: string;
11
+ }
12
+
13
+ export interface FlowFilesReport {
14
+ flows?: ReportedFile[];
15
+ agents?: ReportedFile[];
16
+ }
17
+
18
+ /** Private bridge → server lane message carrying a {@link FlowFilesReport}. */
19
+ export const FLOW_FILES_REPORT = "flow-files/report";
20
+ /** pi event the server emits into a session to ask its bridge to (re)report. */
21
+ export const FLOW_FILES_REQUEST_EVENT = "dashboard-flows:report-files";
@@ -356,6 +356,10 @@ export function reduceFlowEvent(
356
356
 
357
357
  case "flow_complete": {
358
358
  if (!flowState) return null;
359
+ // A rejected start (pi-flows refused to run; no flow_started was emitted)
360
+ // never refers to the run held here — leave it untouched.
361
+ // See change: attach-flow-before-run (D10).
362
+ if (data.status === "rejected") return flowState;
359
363
  const status = ((data.status as string) || "success") as FlowState["status"];
360
364
  // When the flow ends non-successfully (error / aborted / interrupted),
361
365
  // downgrade any step left running/pending so its card does not spin
package/src/i18n.ts CHANGED
@@ -39,6 +39,20 @@ export const catalog = {
39
39
  newFlowOption: "+ 新建流程",
40
40
  newFlowOptionDesc: "使用 edit-flow 技能创建新流程",
41
41
  runFlowButton: "运行流程…",
42
+ openFlowButton: "打开流程…",
43
+ openFlowDialogTitle: "打开流程",
44
+ openFlowDisabledRunning: "有流程正在运行",
45
+ flowNotStarted: "未开始",
46
+ runFlow: "运行",
47
+ closeAttachedFlow: "关闭",
48
+ flowDefinitionLoadError: "流程定义文件不可用",
49
+ flowNoLongerAvailable: "已不可用",
50
+ flowLoading: "加载中…",
51
+ flowRunRejected: "启动被拒绝",
52
+ flowRunSendFailed: "无法启动流程",
53
+ openHandlerInEditor: "在编辑器中打开处理程序",
54
+ openSourceInEditor: "在编辑器中打开 {name} 源文件",
55
+ openFlowYamlInEditor: "在编辑器中打开 {name} YAML",
42
56
  newEditButton: "新建 / 编辑…",
43
57
  runFlowDialogTitle: "运行流程",
44
58
  searchFlows: "搜索流程…",
@@ -76,6 +90,20 @@ export const catalog = {
76
90
  newFlowOption: "+ Új folyamat",
77
91
  newFlowOptionDesc: "Új folyamat készítése az edit-flow készséggel",
78
92
  runFlowButton: "Folyamat futtatása…",
93
+ openFlowButton: "Folyamat megnyitása…",
94
+ openFlowDialogTitle: "Folyamat megnyitása",
95
+ openFlowDisabledRunning: "Egy folyamat fut",
96
+ flowNotStarted: "nincs elindítva",
97
+ runFlow: "Futtatás",
98
+ closeAttachedFlow: "Bezárás",
99
+ flowDefinitionLoadError: "A folyamatdefiníciós fájl nem érhető el",
100
+ flowNoLongerAvailable: "már nem érhető el",
101
+ flowLoading: "betöltés…",
102
+ flowRunRejected: "Az indítás elutasítva",
103
+ flowRunSendFailed: "A folyamat nem indítható el",
104
+ openHandlerInEditor: "Kezelő megnyitása a szerkesztőben",
105
+ openSourceInEditor: "{name} forrásának megnyitása a szerkesztőben",
106
+ openFlowYamlInEditor: "{name} YAML megnyitása a szerkesztőben",
79
107
  newEditButton: "Új / Szerkesztés…",
80
108
  runFlowDialogTitle: "Folyamat futtatása",
81
109
  searchFlows: "Folyamatok keresése…",
@@ -46,6 +46,8 @@ export interface ActionContributionLike {
46
46
  * `agent_end`) without knowing anything action-specific.
47
47
  * See change: finalize-event-dispatched-automation-runs.
48
48
  */
49
+ /** Event types `buildEvent` may emit (required by the automation registry). */
50
+ emits?: string[];
49
51
  buildEvent?: (args: { payload: Record<string, unknown>; automation: unknown }) =>
50
52
  | {
51
53
  eventType: string;
@@ -130,6 +132,7 @@ export function flowsActionContributions(flowsForCwd: FlowsForCwd): ActionContri
130
132
  // which pi-flows consumes as `flowInput` → `${{flow.input.<name>}}`.
131
133
  // `task` stays optional and may coexist with `inputs`.
132
134
  // See change: finalize-event-dispatched-automation-runs, wire-flow-inputs-in-automation.
135
+ emits: ["flow:run"],
133
136
  buildEvent: ({ payload }) => {
134
137
  const flow = String(payload.flow ?? "").trim();
135
138
  if (!FLOW_ID_RE.test(flow)) return null;