@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
@@ -7,21 +7,25 @@
7
7
  * - `sequential` — `blockedBy` dependency
8
8
  * - `branch` — decision `branches` (fork / agent-decision / code-decision)
9
9
  * - `route` — `on_complete` / `on_error` cross-segment routing
10
- * - `implicit` — a step after a separator with no `blockedBy` (segment fall-through)
10
+ * - `implicit` — engine fall-through: segment exit → next declared segment's
11
+ * entries (pi-flows `splitIntoSegments` + `segmentIndex++`)
11
12
  *
12
- * The function derives only the classes its input carries: the live caller
13
- * passes `branches` but not `onComplete`/`onError` (pi-flows omits those from
14
- * `flow:flow-started`), so `route` edges appear only in the static caller.
13
+ * The function derives only the classes its input carries. Both callers pass
14
+ * `onError`; only the static (YAML) caller can carry legacy `onComplete`.
15
+ * An `implicit` (or in-segment `sequential`) edge and an `on_error` route on the
16
+ * same pair are BOTH kept — success fall-through and error route are distinct.
15
17
  *
16
- * See change: improve-flow-ui.
18
+ * See change: improve-flow-ui, fix-flow-graph-engine-order.
17
19
  */
18
20
 
19
21
  export type FlowEdgeKind = "sequential" | "branch" | "route" | "implicit";
20
22
 
21
23
  export interface FlowEdgeStep {
22
24
  id: string;
23
- /** Node kind (`agent` | `fork` | `agent-decision` | `code` | `code-decision`). */
24
- type: string;
25
+ /** RAW engine node kind (`agent` | `fork` | `agent-decision` | `code` |
26
+ * `code-decision`) — never a display mapping that merges kinds. Anything
27
+ * outside the separator set (absent, unknown) is a DAG-segment member. */
28
+ type?: string;
25
29
  blockedBy: string[];
26
30
  /** Decision branch label → target step id. */
27
31
  branches?: Record<string, string>;
@@ -44,16 +48,20 @@ export interface FlowEdge {
44
48
  routeTopology?: "returning" | "terminal";
45
49
  }
46
50
 
51
+ /** Engine separator kinds: each is its own segment (pi-flows
52
+ * `splitIntoSegments`). Closed set — anything else joins a DAG segment. */
53
+ const SEPARATOR_KINDS = new Set(["code", "code-decision", "fork", "agent-decision"]);
54
+ /** Decisions fall through at their `max_iterations` loop cap; forks never do. */
55
+ const CAPPED_DECISION_KINDS = new Set(["code-decision", "agent-decision"]);
56
+
57
+ const isErrorRoute = (kind: FlowEdgeKind, label?: string) => kind === "route" && label === "on_error";
58
+ const isPlain = (kind: FlowEdgeKind) => kind === "sequential" || kind === "implicit";
59
+
47
60
  /** Derive the canonical edge set for a flow. Pure; order-sensitive (array index
48
61
  * defines forward/backward). Skips edges whose endpoints are not in `steps`,
49
- * and collapses duplicate `{from,to}` pairs (labeled branch/route wins). */
50
- /** Separator node types that close a DAG segment and open the next. A
51
- * no-blockedBy step falling through from one of these is the only `implicit`
52
- * edge the engine actually serializes. (`flow-ref` is NOT a separator.) The
53
- * set covers both raw stepTypes (static YAML preview) and the live graph's
54
- * mapped types, where `agent-decision` collapses to `fork`. */
55
- const SEPARATOR_TYPES = new Set(["fork", "agent-decision", "code-decision"]);
56
-
62
+ * and collapses duplicate `{from,to}` pairs (labeled branch/route wins) —
63
+ * except a plain (sequential/implicit) edge and an `on_error` route, which
64
+ * coexist. */
57
65
  export function deriveFlowEdges(steps: FlowEdgeStep[]): FlowEdge[] {
58
66
  const order = new Map(steps.map((s, i) => [s.id, i]));
59
67
  const has = (id: string) => order.has(id);
@@ -62,7 +70,10 @@ export function deriveFlowEdges(steps: FlowEdgeStep[]): FlowEdge[] {
62
70
  const add = (from: string, to: string, kind: FlowEdgeKind, label?: string): void => {
63
71
  if (!has(from) || !has(to)) return;
64
72
  const backward = (order.get(to) ?? 0) <= (order.get(from) ?? 0);
65
- const existing = edges.find((e) => e.from === from && e.to === to);
73
+ // A plain edge and an on_error route on the same pair stay distinct.
74
+ const coexists = (e: FlowEdge) =>
75
+ (isErrorRoute(kind, label) && isPlain(e.kind)) || (isPlain(kind) && isErrorRoute(e.kind, e.label));
76
+ const existing = edges.find((e) => e.from === from && e.to === to && !coexists(e));
66
77
  if (existing) {
67
78
  // De-dup: prefer the labeled branch/route classification over a plain
68
79
  // sequential/implicit edge for the same pair.
@@ -97,25 +108,12 @@ export function deriveFlowEdges(steps: FlowEdgeStep[]): FlowEdge[] {
97
108
  if (s.onError) add(s.id, s.onError, "route", "on_error");
98
109
  }
99
110
 
100
- // 4. Implicit-segment edges. The engine wave scheduler runs EVERY step whose
101
- // blockedBy is satisfied at once — a step with no blockedBy is a root that
102
- // fires in wave 1, in parallel with its siblings. Inter-segment ordering is
103
- // enforced only by SEPARATOR steps (fork / agent-decision / code-decision),
104
- // which close one segment and open the next. So a no-blockedBy step with no
105
- // incoming edge falls through ONLY from the most recent separator (placing it
106
- // after that boundary); two such roots after the same separator are parallel
107
- // siblings and both fan out from it (never chained to each other). Roots
108
- // before any separator stay un-parented → same rank → parallel.
109
- const incoming = new Set(edges.map((e) => e.to));
110
- let lastSeparator: string | undefined;
111
- for (const curr of steps) {
112
- const fallsThrough = curr.blockedBy.length === 0 && !incoming.has(curr.id);
113
- if (fallsThrough && lastSeparator && lastSeparator !== curr.id) {
114
- add(lastSeparator, curr.id, "implicit");
115
- incoming.add(curr.id);
116
- }
117
- if (SEPARATOR_TYPES.has(curr.type)) lastSeparator = curr.id;
118
- }
111
+ // 4. Fall-through edges, mirroring the engine's segment program. Steps split
112
+ // into segments in declared order: each separator is its own segment,
113
+ // consecutive other steps form one DAG segment. A segment that finishes
114
+ // without routing runs the next declared segment, so every exit of segment
115
+ // i gets an `implicit` edge to every entry of segment i+1.
116
+ addFallThrough(steps, order, add);
119
117
 
120
118
  // 5. on_error route topology. The engine keeps running everything reachable
121
119
  // from an on_error target. A handler is `returning` when its forward
@@ -126,6 +124,64 @@ export function deriveFlowEdges(steps: FlowEdgeStep[]): FlowEdge[] {
126
124
  return edges;
127
125
  }
128
126
 
127
+ interface Segment {
128
+ /** Steps that may complete without routing (fall-through sources). */
129
+ exits: string[];
130
+ /** Steps the segment starts with (fall-through targets). */
131
+ entries: string[];
132
+ }
133
+
134
+ function addFallThrough(
135
+ steps: FlowEdgeStep[],
136
+ order: Map<string, number>,
137
+ add: (from: string, to: string, kind: FlowEdgeKind, label?: string) => void,
138
+ ): void {
139
+ // Split into segments: separator → own segment; others group into DAGs.
140
+ const groups: { dag: boolean; members: FlowEdgeStep[] }[] = [];
141
+ for (const s of steps) {
142
+ const separator = SEPARATOR_KINDS.has(s.type ?? "");
143
+ const last = groups[groups.length - 1];
144
+ if (!separator && last?.dag) last.members.push(s);
145
+ else groups.push({ dag: !separator, members: [s] });
146
+ }
147
+
148
+ const segments: Segment[] = groups.map(({ dag, members }) => {
149
+ if (!dag) {
150
+ const s = members[0];
151
+ const branchTargets = Object.values(s.branches ?? {});
152
+ const own = order.get(s.id) ?? 0;
153
+ const fallsThrough =
154
+ branchTargets.length === 0 ||
155
+ (CAPPED_DECISION_KINDS.has(s.type ?? "") &&
156
+ branchTargets.some((t) => order.has(t) && (order.get(t) ?? 0) <= own));
157
+ return { exits: fallsThrough ? [s.id] : [], entries: [s.id] };
158
+ }
159
+ // DAG segment: in-segment blockedBy + in-segment on_error source→target.
160
+ const ids = new Set(members.map((m) => m.id));
161
+ const deps = new Map<string, Set<string>>(members.map((m) => [m.id, new Set<string>()]));
162
+ for (const m of members) {
163
+ for (const dep of m.blockedBy) if (ids.has(dep) && dep !== m.id) deps.get(m.id)?.add(dep);
164
+ if (m.onError && ids.has(m.onError) && m.onError !== m.id) {
165
+ deps.get(m.onError)?.add(m.id);
166
+ // The engine runs every DAG step: the target also runs after a success.
167
+ add(m.id, m.onError, "sequential");
168
+ }
169
+ }
170
+ const dependedOn = new Set<string>();
171
+ for (const d of deps.values()) for (const id of d) dependedOn.add(id);
172
+ return {
173
+ entries: members.filter((m) => deps.get(m.id)?.size === 0).map((m) => m.id),
174
+ exits: members.filter((m) => !dependedOn.has(m.id)).map((m) => m.id),
175
+ };
176
+ });
177
+
178
+ for (let i = 0; i + 1 < segments.length; i++) {
179
+ for (const from of segments[i].exits) {
180
+ for (const to of segments[i + 1].entries) add(from, to, "implicit");
181
+ }
182
+ }
183
+ }
184
+
129
185
  /** Tag each `on_error` route edge with `routeTopology`. Pure: reachability over
130
186
  * the flow edges EXCLUDING on_error routes (those are what we classify). A
131
187
  * handler is `returning` when its forward closure reaches the route source or
@@ -6,7 +6,7 @@
6
6
  * `~/.pi/agent/**`, `node_modules/**`). Never touches host core.
7
7
  * See change: attach-flow-before-run.
8
8
  */
9
- import type { FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
9
+ import type { FlowState } from "../types.js";
10
10
  import { useCallback, useEffect, useState } from "react";
11
11
  import { useLocation } from "wouter";
12
12
 
@@ -27,8 +27,17 @@ function contentOf(json: Record<string, unknown> | null): string | null {
27
27
  return json?.success && typeof data?.content === "string" ? data.content : null;
28
28
  }
29
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> {
30
+ /**
31
+ * Read a flow-related file's content; throws `Error(message)` on failure.
32
+ * `noHostFallback`: plugin route only (a path-opened, view-only flow's files are
33
+ * admitted there and nowhere else). See change: add-flow-open-tool (D7).
34
+ */
35
+ export async function fetchFlowFile(
36
+ sessionId: string | undefined,
37
+ filePath: string,
38
+ opts: { noHostFallback?: boolean } = {},
39
+ ): Promise<string> {
40
+ let pluginError: string | undefined;
32
41
  if (sessionId) {
33
42
  const url = `/api/plugins/flows/file?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(filePath)}`;
34
43
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -37,13 +46,16 @@ export async function fetchFlowFile(sessionId: string | undefined, filePath: str
37
46
  const json = await readJson(r);
38
47
  const content = contentOf(json);
39
48
  if (content !== null) return content;
49
+ pluginError = typeof json?.error === "string" ? json.error : `HTTP ${r.status}`;
40
50
  if (r.status !== 409 || !json?.retry) break;
41
51
  await wait(RETRY_MS);
42
- } catch {
52
+ } catch (err) {
53
+ pluginError = err instanceof Error ? err.message : String(err);
43
54
  break; // network / plugin unavailable → host fallback
44
55
  }
45
56
  }
46
57
  }
58
+ if (opts.noHostFallback) throw new Error(pluginError ?? "no session");
47
59
  const r = await fetch(`/api/pi-resource-file?path=${encodeURIComponent(filePath)}`);
48
60
  const json = await readJson(r);
49
61
  const content = contentOf(json);
@@ -10,10 +10,12 @@
10
10
  * `resolveFlowSlot` decides what the flow slot renders (running → attached →
11
11
  * completed → nothing); `isAttachmentConsumed` is the replay catch-up rule.
12
12
  *
13
- * `flow-yaml-parse.ts` (the shallow `flow_write` snapshot parser) is untouched.
14
- * See change: attach-flow-before-run (D1, D3, D4).
13
+ * `{ lenient: true }` (the `flow_write` card) skips the required-field checks,
14
+ * defaults a missing/unknown `type` to `agent` and skips invalid steps.
15
+ * See change: attach-flow-before-run (D1, D3, D4), unify-flow-rendering (D4, D5).
15
16
  */
16
- import type { DashboardEvent, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
17
+ import type { DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import type { FlowState } from "../types.js";
17
19
  import { parse as parseYaml } from "yaml";
18
20
  import { reduceFlowEvent } from "../reducer.js";
19
21
 
@@ -29,9 +31,17 @@ interface StartedStep {
29
31
 
30
32
  type Raw = Record<string, unknown>;
31
33
 
32
- function requireField(obj: Raw, key: string, where: string): string {
34
+ /** Parse mode: strict mirrors every 0.5.0 parser throw; lenient checks nothing optional. */
35
+ interface ParseMode {
36
+ lenient: boolean;
37
+ }
38
+
39
+ function requireField(obj: Raw, key: string, where: string, mode: ParseMode): string | undefined {
33
40
  const v = obj[key];
34
- if (v === undefined || v === null) throw new Error(`flow.yaml: ${where} missing required field "${key}"`);
41
+ if (v === undefined || v === null) {
42
+ if (mode.lenient) return undefined;
43
+ throw new Error(`flow.yaml: ${where} missing required field "${key}"`);
44
+ }
35
45
  return String(v);
36
46
  }
37
47
 
@@ -40,17 +50,30 @@ function blockedByOf(raw: Raw): string[] {
40
50
  return Array.isArray(raw.blockedBy) ? raw.blockedBy.map(String) : [String(raw.blockedBy)];
41
51
  }
42
52
 
53
+ /** Scalar → its string; `{ to: "<non-empty>", ... }` → `to`; anything else skipped. */
54
+ function branchTarget(v: unknown): string | undefined {
55
+ if (v === null || v === undefined || Array.isArray(v)) return undefined;
56
+ if (typeof v === "object") {
57
+ const to = (v as Raw).to;
58
+ return typeof to === "string" && to !== "" ? to : undefined;
59
+ }
60
+ return String(v);
61
+ }
62
+
43
63
  function branchesOf(raw: Raw): Record<string, string> {
44
64
  const out: Record<string, string> = {};
45
65
  if (raw.branches && typeof raw.branches === "object") {
46
- for (const [k, v] of Object.entries(raw.branches as Raw)) out[k] = String(v);
66
+ for (const [k, v] of Object.entries(raw.branches as Raw)) {
67
+ const to = branchTarget(v);
68
+ if (to !== undefined) out[k] = to;
69
+ }
47
70
  }
48
71
  return out;
49
72
  }
50
73
 
51
74
  /** 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;
75
+ function checkInt(obj: Raw, key: string, where: string, mode: ParseMode): void {
76
+ if (mode.lenient || obj[key] === undefined) return;
54
77
  if (Number.isNaN(Number.parseInt(String(obj[key]), 10))) {
55
78
  throw new Error(`flow.yaml: ${where} "${key}" must be an integer`);
56
79
  }
@@ -79,32 +102,36 @@ function onErrorOf(raw: Raw): string | undefined {
79
102
  * per-kind field table (agent: blockedBy+on_error; code: blockedBy+on_error;
80
103
  * code-decision: blockedBy+branches; fork: branches (+optional agent);
81
104
  * agent-decision: agent+branches). Throws where the 0.5.0 parser throws.
105
+ * Lenient: missing/unknown `type` → `agent`, no required-field/integer checks.
82
106
  */
83
- function toStartedStep(raw: unknown, index: number): StartedStep {
107
+ const STEP_TYPES = new Set(["agent", "code", "code-decision", "fork", "agent-decision"]);
108
+
109
+ function toStartedStep(raw: unknown, index: number, mode: ParseMode): StartedStep {
84
110
  if (!raw || typeof raw !== "object") throw new Error(`flow.yaml: step ${index} is not an object`);
85
111
  const r = raw as Raw;
86
112
  const id = r.id;
87
113
  if (!id || typeof id !== "string") throw new Error(`flow.yaml: step ${index} missing "id" field`);
88
- const type = r.type;
114
+ let type = r.type;
115
+ if (mode.lenient && (typeof type !== "string" || !STEP_TYPES.has(type))) type = "agent";
89
116
  if (!type || typeof type !== "string") throw new Error(`flow.yaml: step "${id}" missing required "type" field`);
90
117
  const where = `step "${id}"`;
91
- checkInt(r, "timeout", where);
92
- checkInt(r, "max_iterations", where);
118
+ checkInt(r, "timeout", where, mode);
119
+ checkInt(r, "max_iterations", where, mode);
93
120
  switch (type) {
94
121
  case "agent":
95
- return { id, stepType: type, agent: requireField(r, "agent", where), blockedBy: blockedByOf(r), onError: onErrorOf(r) };
122
+ return { id, stepType: type, agent: requireField(r, "agent", where, mode), blockedBy: blockedByOf(r), onError: onErrorOf(r) };
96
123
  case "code":
97
124
  return { id, stepType: type, blockedBy: blockedByOf(r), onError: onErrorOf(r) };
98
125
  case "code-decision":
99
- return { id, stepType: type, blockedBy: blockedByOf(r), branches: branchesOf(r) };
126
+ return { id, stepType: type, blockedBy: blockedByOf(r), branches: branchesOf(r), onError: onErrorOf(r) };
100
127
  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) };
128
+ requireField(r, "question", where, mode);
129
+ requireField(r, "options", where, mode);
130
+ return { id, stepType: type, agent: r.agent ? String(r.agent) : undefined, blockedBy: [], branches: branchesOf(r), onError: onErrorOf(r) };
104
131
  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) };
132
+ const agent = requireField(r, "agent", where, mode);
133
+ requireField(r, "task", where, mode);
134
+ return { id, stepType: type, agent, blockedBy: [], branches: branchesOf(r), onError: onErrorOf(r) };
108
135
  }
109
136
  default:
110
137
  throw new Error(`flow.yaml: unknown step type "${type}" for step "${id}"`);
@@ -112,16 +139,21 @@ function toStartedStep(raw: unknown, index: number): StartedStep {
112
139
  }
113
140
 
114
141
  /** Parse a flow.yaml into the 0.5.0 started-step payload. Throws on any error. */
115
- function flowYamlToStartedSteps(content: string): StartedStep[] {
142
+ function flowYamlToStartedSteps(content: string, mode: ParseMode): StartedStep[] {
116
143
  const doc = parseYaml(content) as unknown;
117
144
  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);
145
+ if (!mode.lenient) {
146
+ requireField(doc as Raw, "name", "flow", mode);
147
+ requireField(doc as Raw, "description", "flow", mode);
148
+ checkInt(doc as Raw, "max_concurrent", "flow", mode);
149
+ checkInputs((doc as Raw).inputs);
150
+ }
122
151
  const steps = (doc as Raw).steps;
123
152
  if (!Array.isArray(steps)) throw new Error('flow.yaml: "steps" must be an array');
124
- return steps.map(toStartedStep);
153
+ if (!mode.lenient) return steps.map((s, i) => toStartedStep(s, i, mode));
154
+ const valid = steps.filter((s): s is Raw => !!s && typeof s === "object" && typeof (s as Raw).id === "string" && (s as Raw).id !== "");
155
+ if (valid.length === 0) throw new Error("flow.yaml: no valid steps");
156
+ return valid.map((s, i) => toStartedStep(s, i, mode));
125
157
  }
126
158
 
127
159
  export type IdleBuildResult =
@@ -132,10 +164,11 @@ export type IdleBuildResult =
132
164
  export function buildIdleFlowState(
133
165
  content: string,
134
166
  flow: { name: string; source?: string },
167
+ opts: { lenient?: boolean } = {},
135
168
  ): IdleBuildResult {
136
169
  let steps: StartedStep[];
137
170
  try {
138
- steps = flowYamlToStartedSteps(content);
171
+ steps = flowYamlToStartedSteps(content, { lenient: opts.lenient === true });
139
172
  } catch (err) {
140
173
  return { kind: "error", message: err instanceof Error ? err.message : String(err) };
141
174
  }
@@ -143,7 +176,7 @@ export function buildIdleFlowState(
143
176
  seq: 0,
144
177
  timestamp: 0,
145
178
  eventType: "flow_started",
146
- data: { flowName: flow.name, task: "", source: flow.source, autonomousMode: true, steps },
179
+ data: { flowName: flow.name, task: "", source: flow.source, steps },
147
180
  } as unknown as DashboardEvent;
148
181
  // flow_started always seeds a state from null.
149
182
  return { kind: "ready", flowState: reduceFlowEvent(null, event) as FlowState };
@@ -155,11 +188,18 @@ export function toEventTime(ts: unknown): number {
155
188
  return Number.isFinite(n) ? n : 0;
156
189
  }
157
190
 
158
- /** Replay catch-up: a `flow_started` strictly newer than the attach baseline. */
191
+ /** Clock slack between a live `flow_started` (stamped at forward time) and its
192
+ * replayed copy (stamped at entry time). See change:
193
+ * fix-flow-reattach-per-run-state (D2). */
194
+ const ATTACH_CLOCK_SLACK_MS = 5_000;
195
+
196
+ /** Replay catch-up: a `flow_started` more than the clock slack newer than the
197
+ * attach baseline, so a restart's re-stamped copy of the baseline start never
198
+ * consumes the attachment. */
159
199
  export function isAttachmentConsumed(baselineStartedAt: number | null, lastFlowStartedAt: unknown): boolean {
160
200
  if (baselineStartedAt === null) return false;
161
201
  if (lastFlowStartedAt === undefined || lastFlowStartedAt === null) return false;
162
- return toEventTime(lastFlowStartedAt) > baselineStartedAt;
202
+ return toEventTime(lastFlowStartedAt) > baselineStartedAt + ATTACH_CLOCK_SLACK_MS;
163
203
  }
164
204
 
165
205
  /** Stored per-session attachment (see flow-attach-store.ts). */
@@ -169,6 +209,11 @@ export interface FlowAttachment {
169
209
  name: string;
170
210
  source?: string;
171
211
  baselineStartedAt: number | null;
212
+ /**
213
+ * Path-opened by the agent's `flow_open` (not in the catalog): view-only
214
+ * panel, never "unavailable". See change: add-flow-open-tool (D7).
215
+ */
216
+ viewOnly?: true;
172
217
  }
173
218
 
174
219
  export type IdleLoad =
@@ -186,13 +231,23 @@ export interface FlowSlot {
186
231
  attachmentConsumed: boolean;
187
232
  }
188
233
 
189
- function findRunning(
234
+ /**
235
+ * The running run to show: the last running entry in rank order at or after the
236
+ * slot run (`liveStates` iterates in rank order). A running run older than the
237
+ * slot run (a phantom whose pi died before `flow_complete`) is never chosen;
238
+ * no slot run → none. See change: fix-flow-reattach-per-run-state (D2).
239
+ */
240
+ export function findRunning(
190
241
  live: FlowState | null,
191
242
  liveStates: ReadonlyMap<string, FlowState>,
192
243
  ): 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;
244
+ if (!live) return undefined;
245
+ let running: FlowState | undefined = live.status === "running" ? live : undefined;
246
+ let reached = false;
247
+ for (const s of liveStates.values()) {
248
+ if (s === live) reached = true;
249
+ else if (reached && s.status === "running") running = s;
250
+ }
196
251
  return running;
197
252
  }
198
253
 
@@ -207,14 +262,15 @@ export function resolveFlowSlot(input: {
207
262
  attachment: FlowAttachment | null;
208
263
  idle: IdleLoad;
209
264
  lastFlowStartedAt?: unknown;
210
- flowsList: ReadonlyArray<{ name: string }>;
265
+ /** The session's flow catalog (plugin `flow_catalog`). */
266
+ flows: ReadonlyArray<{ name: string }>;
211
267
  }): FlowSlot {
212
- const { live, liveStates, attachment, idle, lastFlowStartedAt, flowsList } = input;
268
+ const { live, liveStates, attachment, idle, lastFlowStartedAt, flows } = input;
213
269
  const running = findRunning(live, liveStates);
214
270
  if (running) return { mode: "live", flowState: running, attachmentConsumed: !!attachment };
215
271
 
216
272
  if (attachment && !isAttachmentConsumed(attachment.baselineStartedAt, lastFlowStartedAt)) {
217
- if (flowsList.length > 0 && !flowsList.some((f) => f.name === attachment.name)) {
273
+ if (!attachment.viewOnly && flows.length > 0 && !flows.some((f) => f.name === attachment.name)) {
218
274
  return { mode: "error", error: { kind: "unavailable" }, attachmentConsumed: false };
219
275
  }
220
276
  if (idle.kind === "loading") return { mode: "loading", attachmentConsumed: false };
@@ -6,7 +6,7 @@
6
6
  * Open iff pi-flows is active in the session's cwd — a command named `flows` or
7
7
  * starting with `flows:` in `commandsList`, the removed `flows:new` alone NOT
8
8
  * counting — OR the session has any flow event (live or replayed). Never gates on
9
- * `flowsList` length, so an active-but-empty cwd still offers New / Edit….
9
+ * flow catalog length, so an active-but-empty cwd still offers New / Edit….
10
10
  * Closed by default: no `commandsList` published yet → closed.
11
11
  *
12
12
  * Synchronous and side-effect-free; reads `getSessionData` directly like
@@ -10,13 +10,14 @@
10
10
  * See change: fix-empty-flows-subcard.
11
11
  */
12
12
  import { getSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
13
+ import { FLOW_CATALOG_EVENT } from "../flow-catalog-contract.js";
13
14
  import { isFlowEvent } from "../reducer.js";
14
15
 
15
16
  // Per-session memo for "has this session seen any flow event?". Keyed on the
16
17
  // session-events array reference (stable until the next publish) so the scan
17
18
  // runs only when the event list grows; once true it stays true (flow events
18
19
  // are append-only). Lets the FLOWS subcard reattach on cold load after replay,
19
- // where the `flowsList`/`commandsList` availability signal is NOT replayed and
20
+ // where the flow-catalog/`commandsList` availability signal is NOT replayed and
20
21
  // is closed-by-default. See change: replay-persisted-flow-runs (task 5.5).
21
22
  const flowEventMemo = new Map<string, { ref: readonly unknown[]; has: boolean }>();
22
23
 
@@ -29,7 +30,12 @@ export function sessionHasFlowEvents(sessionId: string): boolean {
29
30
  const events = getSessionEvents(sessionId);
30
31
  const cached = flowEventMemo.get(sessionId);
31
32
  if (cached && (cached.has || cached.ref === events)) return cached.has;
32
- const has = events.some((e) => isFlowEvent((e as { eventType: string }).eventType));
33
+ // The catalog is session metadata, not flow activity: it never opens the
34
+ // FLOWS subcard. See change: flows-dock-chip-and-panel-actions.
35
+ const has = events.some((e) => {
36
+ const type = (e as { eventType: string }).eventType;
37
+ return type !== FLOW_CATALOG_EVENT && isFlowEvent(type);
38
+ });
33
39
  flowEventMemo.set(sessionId, { ref: events, has });
34
40
  return has;
35
41
  }
@@ -29,7 +29,6 @@ export { computeLayout, FlowGraph, flowStateToGraphSteps } from "./FlowGraph.js"
29
29
  // Input-wiring editor claimed into automation-plugin's `automation-action-editor`
30
30
  // slot for `flows.run`. See change: wire-flow-inputs-in-automation.
31
31
  export { FlowLaunchDialog } from "./FlowLaunchDialog.js";
32
- export { FlowSummary, FlowSummaryClaim } from "./FlowSummary.js";
33
32
  export type { FlowsPluginConfig } from "./FlowsSettings.js";
34
33
 
35
34
  // Settings section (global edit-mode default) — manifest `settings-section` claim.
@@ -44,6 +43,15 @@ export { SessionFlowActions, SessionFlowActionsClaim } from "./SessionFlowAction
44
43
  export { flowsActionsAvailable, hasFlowsCommand } from "./flowsActionsGate.js";
45
44
  export { SessionFlowMenuClaim } from "./SessionFlowMenuClaim.js";
46
45
 
46
+ // `composer-context-group` claim: the FLOWS dock chip. Eager: a hot composer
47
+ // slot must not suspend (lazy-plugin-claims policy). See change:
48
+ // flows-dock-chip-and-panel-actions.
49
+ export { FlowsContextGroup } from "./FlowsContextGroup.js";
50
+
51
+ // `shell-headless` claim: always-mounted receiver of the agent `flow_open` pin
52
+ // (stores + acks on every connected browser). See change: add-flow-open-tool.
53
+ export { FlowOpenListener } from "./FlowOpenListener.js";
54
+
47
55
  // Manifest-level shouldRender predicate for the `session-card-flows` claim
48
56
  // (any flow event). See change: add-flows-subcard, add-session-actions-flyout.
49
57
  export { shouldRenderFlowsSubcard } from "./shouldRender.js";
@@ -53,10 +61,8 @@ export { shouldRenderFlowsSubcard } from "./shouldRender.js";
53
61
  // surface through buttons only (`SessionFlowActions`, `FlowLaunchDialog`,
54
62
  // `FlowDashboard` Abort). pi-flows itself continues to register the slash
55
63
  // commands for TUI users. See change: fix-pi-flows-end-to-end (Group 8).
56
- //
57
- // The FlowsCommandRoutes module is no longer exported from this barrel.
58
- // Restore the exports here if/when the dashboard re-introduces command-route
59
- // claims for flows.
64
+ // The dead FlowsCommandRoutes module was deleted. See change:
65
+ // flows-dock-chip-and-panel-actions.
60
66
 
61
67
  export type { FlowsSessionState } from "./FlowsSessionStateContext.js";
62
68
  // Plugin-internal state hooks. Components consume these in place of
@@ -67,14 +73,10 @@ export {
67
73
  useFlowsSessionState,
68
74
  } from "./FlowsSessionStateContext.js";
69
75
 
70
- import { registerPromptComponent } from "@blackbelt-technology/dashboard-plugin-runtime";
71
76
  import { getFlowsUiStateSnapshot } from "./FlowsUiStateContext.js";
72
77
 
73
- // Register the `flow-question` prompt component type so the shell knows to
74
- // route flow-tagged prompts to the widget-bar placement instead of inline
75
- // chat. Idempotent under HMR — `registerPromptComponent` replaces prior
76
- // entries without throwing. See change: route-flow-asks-to-upper-slot.
77
- registerPromptComponent({ type: "flow-question", placement: "widget-bar" });
78
+ // No prompt component: pi-flows 0.11+ asks through the parent mailbox
79
+ // (`flow_question`), shown on the asking card. See change: adopt-flow-parent-mailbox (D8).
78
80
 
79
81
  export type { FlowsUiActions, FlowsUiState } from "./FlowsUiStateContext.js";
80
82
  export {getFlowsUiStateSnapshot,
@@ -3,7 +3,7 @@
3
3
  * `session-card-flows` claim (`SessionFlowActionsClaim`).
4
4
  *
5
5
  * The FLOWS subcard carries flow STATUS only, so it renders IFF the session has
6
- * any flow event (live or replayed). It no longer depends on `flowsList`, edit
6
+ * any flow event (live or replayed). It no longer depends on the flow catalog, edit
7
7
  * mode or extension presence — those gate the flow ACTIONS, which live in the
8
8
  * `session-card-action-bar` claim (see `flowsActionsGate.ts`).
9
9
  *
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Effective flows edit mode for one session (project `.pi/settings.json`
3
+ * overriding the global `~/.pi/agent/settings.json`), resolved read-only by
4
+ * the plugin server.
5
+ *
6
+ * - GET `/api/plugins/flows/edit-mode-state?sessionId` while `active`
7
+ * becomes true and again each time the session actions menu opens (picks
8
+ * up out-of-band changes: `/flows:edit-mode`, hand edits).
9
+ * - Live `flows_edit_mode_state` frames for THIS session update the value;
10
+ * a frame carrying `error` surfaces it once.
11
+ * - `enabled === undefined` = unknown (not fetched yet, or the request
12
+ * failed); callers hide edit-mode UI then.
13
+ *
14
+ * Never sends anything. See change: stop-flows-edit-mode-project-writes (D4).
15
+ */
16
+ import { usePluginMessage } from "@blackbelt-technology/dashboard-plugin-runtime";
17
+ import { useCallback, useEffect, useRef, useState } from "react";
18
+
19
+ type EditModeError = "not-delivered" | "timeout";
20
+
21
+ interface EditModeFrame {
22
+ sessionId?: unknown;
23
+ enabled?: unknown;
24
+ error?: unknown;
25
+ }
26
+
27
+ export interface EditModeState {
28
+ enabled: boolean | undefined;
29
+ error: EditModeError | null;
30
+ clearError: () => void;
31
+ }
32
+
33
+ export function useEditModeState(sessionId: string, opts: { active: boolean; menuOpen?: boolean }): EditModeState {
34
+ const { active, menuOpen } = opts;
35
+ const [enabled, setEnabled] = useState<boolean | undefined>(undefined);
36
+ const [error, setError] = useState<EditModeError | null>(null);
37
+ const seq = useRef(0);
38
+
39
+ const refresh = useCallback(async () => {
40
+ const mine = ++seq.current;
41
+ let next: boolean | undefined;
42
+ try {
43
+ const r = await fetch(`/api/plugins/flows/edit-mode-state?sessionId=${encodeURIComponent(sessionId)}`);
44
+ const body = r.ok ? ((await r.json()) as { enabled?: unknown }) : null;
45
+ next = typeof body?.enabled === "boolean" ? body.enabled : undefined;
46
+ } catch {
47
+ next = undefined;
48
+ }
49
+ if (mine === seq.current) setEnabled(next);
50
+ }, [sessionId]);
51
+
52
+ // Fetch when the gate opens (and on session change).
53
+ useEffect(() => {
54
+ if (!active) return;
55
+ void refresh();
56
+ return () => {
57
+ seq.current++; // drop an in-flight response for a stale session / unmount
58
+ };
59
+ }, [active, refresh]);
60
+
61
+ // Re-fetch on each menu open transition (closed → open).
62
+ const wasOpen = useRef(menuOpen);
63
+ useEffect(() => {
64
+ if (active && menuOpen && !wasOpen.current) void refresh();
65
+ wasOpen.current = menuOpen;
66
+ }, [active, menuOpen, refresh]);
67
+
68
+ usePluginMessage<EditModeFrame>("flows_edit_mode_state", (msg) => {
69
+ if (msg.sessionId !== sessionId || typeof msg.enabled !== "boolean") return;
70
+ seq.current++; // a pushed value supersedes any in-flight GET
71
+ setEnabled(msg.enabled);
72
+ // A clean frame (the change landed later) clears a surfaced error.
73
+ setError(msg.error === "not-delivered" || msg.error === "timeout" ? msg.error : null);
74
+ });
75
+
76
+ const clearError = useCallback(() => setError(null), []);
77
+ return { enabled, error, clearError };
78
+ }