@blackbelt-technology/pi-dashboard-flows-plugin 0.5.4 → 0.6.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 (66) hide show
  1. package/package.json +25 -16
  2. package/src/AGENTS.md +8 -0
  3. package/src/__tests__/FlowGraph.test.ts +151 -5
  4. package/src/__tests__/FlowInputWiring.test.tsx +97 -0
  5. package/src/__tests__/FlowSummary.test.tsx +331 -0
  6. package/src/__tests__/FlowYamlPreview.test.tsx +75 -0
  7. package/src/__tests__/FlowsSessionStateContext.test.tsx +2 -39
  8. package/src/__tests__/authoring-renderers.test.tsx +190 -0
  9. package/src/__tests__/automation-actions.test.ts +117 -0
  10. package/src/__tests__/flow-agent-card-code-source.test.tsx +154 -0
  11. package/src/__tests__/flow-agent-cost.test.tsx +160 -0
  12. package/src/__tests__/flow-agent-error.test.ts +60 -0
  13. package/src/__tests__/flow-collapse-storage.test.ts +90 -0
  14. package/src/__tests__/flow-edges.test.ts +195 -0
  15. package/src/__tests__/flow-inputs.test.ts +69 -0
  16. package/src/__tests__/flow-reducer-bridge-contract.test.ts +108 -0
  17. package/src/__tests__/flow-reducer-seed-on-start.test.ts +61 -0
  18. package/src/__tests__/flow-yaml-parse.test.ts +124 -0
  19. package/src/__tests__/flows-for-cwd.test.ts +51 -0
  20. package/src/__tests__/flowsAvailability.test.ts +51 -64
  21. package/src/__tests__/node-kind-reducer.test.ts +135 -0
  22. package/src/__tests__/plugin-action-handler.test.ts +54 -0
  23. package/src/__tests__/session-flow-actions-edit.test.tsx +98 -0
  24. package/src/bridge/AGENTS.md +8 -0
  25. package/src/client/AGENTS.md +32 -0
  26. package/src/client/FlowActivityBadge.tsx +8 -5
  27. package/src/client/FlowAgentCard.tsx +231 -110
  28. package/src/client/FlowAgentDetail.tsx +20 -12
  29. package/src/client/FlowAgentsToolRenderer.tsx +228 -0
  30. package/src/client/FlowAuthorPromptDialog.tsx +92 -0
  31. package/src/client/FlowDashboard.tsx +88 -23
  32. package/src/client/FlowGraph.tsx +420 -275
  33. package/src/client/FlowInputWiring.tsx +243 -0
  34. package/src/client/FlowLaunchDialog.tsx +48 -54
  35. package/src/client/FlowQuestionCard.tsx +6 -3
  36. package/src/client/FlowSummary.tsx +252 -69
  37. package/src/client/FlowWriteToolRenderer.tsx +127 -0
  38. package/src/client/FlowYamlPopoverButton.tsx +26 -25
  39. package/src/client/FlowYamlPreview.tsx +9 -7
  40. package/src/client/FlowsSessionStateContext.tsx +14 -33
  41. package/src/client/FlowsSettings.tsx +68 -0
  42. package/src/client/SessionFlowActions.tsx +92 -76
  43. package/src/client/flow-collapse-storage.ts +79 -0
  44. package/src/client/flow-edges.ts +173 -0
  45. package/src/client/flow-yaml-parse.ts +140 -0
  46. package/src/client/flowsAvailability.ts +28 -87
  47. package/src/client/index.tsx +27 -32
  48. package/src/client/shouldRender.ts +24 -12
  49. package/src/configSchema.json +14 -0
  50. package/src/flow-reducer.ts +94 -13
  51. package/src/i18n.ts +90 -0
  52. package/src/reducer.ts +5 -5
  53. package/src/server/AGENTS.md +10 -0
  54. package/src/server/automation-actions.ts +162 -0
  55. package/src/server/flow-inputs.ts +58 -0
  56. package/src/server/index.ts +93 -9
  57. package/src/server/state-store.ts +3 -14
  58. package/src/__tests__/ArchitectInputPrompt.test.tsx +0 -81
  59. package/src/__tests__/architect-reducer.test.ts +0 -307
  60. package/src/architect-reducer.ts +0 -386
  61. package/src/client/FlowAgentPopoutClaim.tsx +0 -66
  62. package/src/client/FlowAgentPopoutPage.tsx +0 -177
  63. package/src/client/FlowArchitect.tsx +0 -699
  64. package/src/client/FlowArchitectPopoutClaim.tsx +0 -52
  65. package/src/client/FlowArchitectPopoutPage.tsx +0 -133
  66. package/src/client/popout-url.ts +0 -59
@@ -4,13 +4,34 @@
4
4
  */
5
5
  import type {
6
6
  DashboardEvent,
7
+ FlowAgentCardConfig,
7
8
  FlowAgentState,
8
9
  FlowDetailEntry,
9
10
  FlowRecentTool,
10
11
  FlowState,
11
- FlowAgentCardConfig,
12
+ NodeKind,
12
13
  } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
14
 
15
+ /** Map a flow-config stepType to a NodeKind for provisional pre-listing at
16
+ * flow_started. The authoritative nodeKind arrives on the started event. */
17
+ function stepTypeToNodeKind(stepType: string | undefined): NodeKind | undefined {
18
+ switch (stepType) {
19
+ case "agent":
20
+ case "agent-decision":
21
+ case "code":
22
+ case "code-decision":
23
+ case "fork":
24
+ return stepType;
25
+ default:
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /** Step kinds that render as a card (have no agent but still get a node card). */
31
+ function isCardableNonAgentKind(nodeKind: NodeKind | undefined): boolean {
32
+ return nodeKind === "code" || nodeKind === "code-decision";
33
+ }
34
+
14
35
  /** Extract a short input preview for tool call display */
15
36
  function extractToolInputPreview(toolName: string, input: unknown): string {
16
37
  if (!input || typeof input !== "object") return "";
@@ -82,20 +103,23 @@ export function reduceFlowEvent(
82
103
  stepType: string;
83
104
  agent?: string;
84
105
  blockedBy?: string[];
85
- loopTarget?: string;
86
- exitTarget?: string;
106
+ branches?: Record<string, string>;
107
+ onComplete?: string;
108
+ onError?: string;
87
109
  }> | undefined;
88
110
  const agents = new Map<string, FlowAgentState>();
89
111
  if (steps) {
90
112
  for (const step of steps) {
91
- // Include all steps that have an agent (not just stepType "agent")
92
- // This covers fork (with agent), agent-loop-decision, agent-decision, etc.
93
- if (step.agent) {
94
- // Key by step ID to avoid deduplication when multiple steps share an agent
113
+ const nodeKind = stepTypeToNodeKind(step.stepType);
114
+ // Pre-list a pending card for agent-bearing steps AND for code/
115
+ // code-decision steps (which have no agent but still render a card).
116
+ // Keeps the grid consistent live and on replay (task 2.6).
117
+ if (step.agent || isCardableNonAgentKind(nodeKind)) {
95
118
  agents.set(step.id, {
96
- agentName: step.agent,
119
+ agentName: step.agent || step.id,
97
120
  stepId: step.id,
98
121
  stepType: step.stepType,
122
+ nodeKind,
99
123
  status: "pending",
100
124
  blockedBy: step.blockedBy || [],
101
125
  recentTools: [],
@@ -104,14 +128,20 @@ export function reduceFlowEvent(
104
128
  }
105
129
  }
106
130
  }
107
- // Store all steps for DAG graph (including non-agent types)
131
+ // Store all steps for DAG graph (including non-agent types). `branches`
132
+ // carries decision routing so the live graph can draw branch/loop edges;
133
+ // `onComplete`/`onError` carry forward/error routing so on_complete-wired
134
+ // flows draw `route` edges live (not just in the static Mermaid). Absent
135
+ // fields (older pi-flows) → no route edges, same as before.
136
+ // See change: fix-flow-ui-graph-zoom-summary.
108
137
  const dagSteps = steps?.map(step => ({
109
138
  id: step.id,
110
139
  stepType: step.stepType,
111
140
  agent: step.agent,
112
141
  blockedBy: step.blockedBy || [],
113
- loopTarget: step.loopTarget,
114
- exitTarget: step.exitTarget,
142
+ branches: step.branches,
143
+ onComplete: step.onComplete,
144
+ onError: step.onError,
115
145
  }));
116
146
 
117
147
  return {
@@ -144,6 +174,11 @@ export function reduceFlowEvent(
144
174
  }),
145
175
  ...(isRerun ? { recentTools: [], detailHistory: [] } : {}),
146
176
  status: "running",
177
+ // nodeKind is decided ONCE here at started (surface-node-kind contract).
178
+ // Fall back to the provisional kind from flow_started, else "agent".
179
+ nodeKind: (data.nodeKind as NodeKind | undefined) ?? existing?.nodeKind ?? "agent",
180
+ // Resolved handler target for code / code-decision nodes (started only).
181
+ codeTarget: (data.target as string | undefined) ?? existing?.codeTarget,
147
182
  label: config?.card?.label,
148
183
  model: config?.model,
149
184
  resolvedModel: (data.resolvedModel as string) || undefined,
@@ -164,18 +199,31 @@ export function reduceFlowEvent(
164
199
  summary?: string;
165
200
  files?: string[];
166
201
  tokens?: { input: number; output: number };
202
+ cost?: number;
167
203
  duration?: number;
204
+ outcome?: "success" | "soft" | "hard";
205
+ typedOutputs?: Record<string, string>;
168
206
  } | undefined;
169
207
  const agents = new Map(flowState.agents);
170
208
  const [key, existing] = findAgent(agents, agentName, stepId);
171
209
  if (key && existing) {
210
+ const typedOutputs = result?.typedOutputs;
211
+ // outcome may ride on the result or the event data; default success.
212
+ const outcome =
213
+ result?.outcome ?? (data.outcome as "success" | "soft" | "hard" | undefined) ??
214
+ (result?.success ? "success" : "soft");
172
215
  agents.set(key, {
173
216
  ...existing,
174
217
  status: result?.status === "blocked" ? "blocked" : result?.success ? "complete" : "error",
175
218
  tokens: result?.tokens,
219
+ cost: result?.cost,
176
220
  duration: result?.duration,
177
221
  summary: result?.summary,
178
222
  files: result?.files,
223
+ outcome,
224
+ typedOutputs,
225
+ // code-decision exposes the chosen branch via typedOutputs.branch.
226
+ branch: typedOutputs?.branch ?? (data.branch as string | undefined) ?? existing.branch,
179
227
  });
180
228
  }
181
229
  return { ...flowState, agents };
@@ -264,6 +312,26 @@ export function reduceFlowEvent(
264
312
  return { ...flowState, agents };
265
313
  }
266
314
 
315
+ case "flow_agent_error": {
316
+ if (!flowState) return null;
317
+ const agentName = data.agentName as string;
318
+ const stepId = data.stepId as string | undefined;
319
+ const text = data.text as string;
320
+ if (!text) return flowState;
321
+ const agents = new Map(flowState.agents);
322
+ const [key, existing] = findAgent(agents, agentName, stepId);
323
+ if (key && existing) {
324
+ // Append an error entry to the agent timeline. Status is owned by
325
+ // flow_agent_complete — do not change it here.
326
+ const detailHistory: FlowDetailEntry[] = [
327
+ ...existing.detailHistory,
328
+ { kind: "error", text },
329
+ ];
330
+ agents.set(key, { ...existing, detailHistory });
331
+ }
332
+ return { ...flowState, agents };
333
+ }
334
+
267
335
  case "flow_loop_iteration": {
268
336
  if (!flowState) return null;
269
337
  const loopTarget = data.loopTarget as string;
@@ -288,10 +356,23 @@ export function reduceFlowEvent(
288
356
 
289
357
  case "flow_complete": {
290
358
  if (!flowState) return null;
291
- const status = (data.status as string) || "success";
359
+ const status = ((data.status as string) || "success") as FlowState["status"];
360
+ // When the flow ends non-successfully (error / aborted / interrupted),
361
+ // downgrade any step left running/pending so its card does not spin
362
+ // forever (task 3.6; covers the synthesized interrupted terminal).
363
+ let agents = flowState.agents;
364
+ if (status !== "success") {
365
+ agents = new Map(flowState.agents);
366
+ for (const [k, a] of agents) {
367
+ if (a.status === "running" || a.status === "pending") {
368
+ agents.set(k, { ...a, status: "error", outcome: a.outcome ?? "hard" });
369
+ }
370
+ }
371
+ }
292
372
  return {
293
373
  ...flowState,
294
- status: status as FlowState["status"],
374
+ status,
375
+ agents,
295
376
  flowResult: data as Record<string, unknown>,
296
377
  };
297
378
  }
package/src/i18n.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Flows plugin i18n catalog — UNPREFIXED leaf keys.
3
+ *
4
+ * The generated plugin registry imports the `catalog` named export (declared
5
+ * as `i18nCatalog` in package.json's `pi-dashboard-plugin` manifest) and the
6
+ * shell merges it under `plugin.flows.*`. Component code resolves keys via the
7
+ * scoped `useT()` hook, which auto-prefixes `plugin.flows.`.
8
+ *
9
+ * zh-CN and hu MUST keep parity (identical key sets). {var} placeholders are
10
+ * preserved verbatim so `t(key, vars)` can interpolate.
11
+ *
12
+ * See change: make-all-ui-text-i18n.
13
+ */
14
+ export const catalog = {
15
+ "zh-CN": {
16
+ abort: "中止",
17
+ delete: "删除",
18
+ run: "运行",
19
+ abortRunningFlow: "中止正在运行的流程",
20
+ back: "返回",
21
+ expandGraph: "展开图表",
22
+ flowGraph: "流程图",
23
+ result: "结果",
24
+ inputs: "输入",
25
+ dismiss: "关闭",
26
+ flowsHeading: "流程",
27
+ editModeLabel: "编辑模式",
28
+ runFlowTitle: "运行流程:{flowName}",
29
+ taskPlaceholder: "描述任务(可选)…",
30
+ summary: "摘要",
31
+ waitingToStart: "等待开始…",
32
+ noActivityYet: "暂无活动",
33
+ closeAgentDetail: "关闭 {name} 详情",
34
+ viewAgentDetail: "查看 {name} 详情",
35
+ details: "详情",
36
+ stepsCount: "{done}/{total} 个步骤",
37
+ toggleAutonomousMode: "切换自主模式",
38
+ abortFlow: "中止流程",
39
+ newFlowOption: "+ 新建流程",
40
+ newFlowOptionDesc: "使用 edit-flow 技能创建新流程",
41
+ runFlowButton: "运行流程…",
42
+ newEditButton: "新建 / 编辑…",
43
+ runFlowDialogTitle: "运行流程",
44
+ searchFlows: "搜索流程…",
45
+ noFlowsAvailable: "没有可用的流程",
46
+ newEditFlowTitle: "新建 / 编辑流程",
47
+ pickFlowToEdit: "选择要编辑的流程,或 + 新建流程…",
48
+ noFlowsYet: "还没有流程 — 选择 + 新建流程",
49
+ deleteFlowTitle: "删除流程",
50
+ deleteFlowConfirm: '删除流程 "{name}"?这将移除流程文件及所有关联的代理。',
51
+ },
52
+ hu: {
53
+ abort: "Megszakítás",
54
+ delete: "Törlés",
55
+ run: "Futtatás",
56
+ abortRunningFlow: "Futó folyamat megszakítása",
57
+ back: "Vissza",
58
+ expandGraph: "Gráf kibontása",
59
+ flowGraph: "Folyamatgráf",
60
+ result: "Eredmény",
61
+ inputs: "Bemenetek",
62
+ dismiss: "Bezárás",
63
+ flowsHeading: "Folyamatok",
64
+ editModeLabel: "Szerkesztő mód",
65
+ runFlowTitle: "Folyamat futtatása: {flowName}",
66
+ taskPlaceholder: "Írd le a feladatot (opcionális)…",
67
+ summary: "Összefoglaló",
68
+ waitingToStart: "Indulásra vár…",
69
+ noActivityYet: "Még nincs tevékenység",
70
+ closeAgentDetail: "{name} részleteinek bezárása",
71
+ viewAgentDetail: "{name} részleteinek megtekintése",
72
+ details: "Részletek",
73
+ stepsCount: "{done}/{total} lépés",
74
+ toggleAutonomousMode: "Autonóm mód váltása",
75
+ abortFlow: "Folyamat megszakítása",
76
+ newFlowOption: "+ Új folyamat",
77
+ newFlowOptionDesc: "Új folyamat készítése az edit-flow készséggel",
78
+ runFlowButton: "Folyamat futtatása…",
79
+ newEditButton: "Új / Szerkesztés…",
80
+ runFlowDialogTitle: "Folyamat futtatása",
81
+ searchFlows: "Folyamatok keresése…",
82
+ noFlowsAvailable: "Nincs elérhető folyamat",
83
+ newEditFlowTitle: "Új / Folyamat szerkesztése",
84
+ pickFlowToEdit: "Válassz folyamatot szerkesztésre, vagy + Új folyamat…",
85
+ noFlowsYet: "Még nincs folyamat — válaszd a + Új folyamat lehetőséget",
86
+ deleteFlowTitle: "Folyamat törlése",
87
+ deleteFlowConfirm:
88
+ 'Törlöd a(z) "{name}" folyamatot? Ez eltávolítja a folyamatfájlt és a hozzá tartozó ügynököket.',
89
+ },
90
+ };
package/src/reducer.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Reducer barrel for the flows plugin.
3
3
  *
4
- * Re-exports the flow + architect reducers so that
5
- * `packages/client/src/lib/event-reducer.ts` can import them via
6
- * `@blackbelt-technology/pi-dashboard-flows-plugin/reducer` instead of
7
- * the previous local paths.
4
+ * Re-exports the flow reducer so that
5
+ * `packages/client/src/lib/event-reducer.ts` can import it via
6
+ * `@blackbelt-technology/pi-dashboard-flows-plugin/reducer`.
7
+ * Architect reducer removed (flow-architect deleted upstream).
8
+ * See change: rework-flows-plugin-for-new-pi-flows.
8
9
  */
9
10
  export { isFlowEvent, reduceFlowEvent } from "./flow-reducer.js";
10
- export { isArchitectEvent, reduceArchitectEvent } from "./architect-reducer.js";
@@ -0,0 +1,10 @@
1
+ # DOX — packages/flows-plugin/src/server
2
+
3
+ Files in this directory. One row per source file.
4
+
5
+ | File | Purpose |
6
+ |------|---------|
7
+ | `automation-actions.ts` | Flows→automation action registration. `discoverFlows(cwd)` scans `<cwd>/.pi/flows/flows/<ns>/<name>/flow.yaml` → `<ns>:<name>`. `registerFlowAutomationActions` registers flows.run/resume/cancel, available=hasFlows(cwd), flows.run payload {flow enum, task multiline}, buildPrompt `/<ns>:<name> <task>`. `wireFlowAutomationActions(consume,...)` consumes `automation.action-registry` service, no-op when absent. See change: register-plugin-automation-events. `flows.run` emits `flow:run` event `{flowName,task}` via buildEvent (was slash-command prompt); `flows.resume`+`flows.cancel` removed. See change: automation-emit-configured-event. Rewritten as pure publisher: `flowsActionContributions()` + `provideFlowsActions(provide)` publish under `automation.action.flows`. Drops consume, registry, ACTION_REGISTRY_SERVICE. See change: decouple-automation-action-registry. `flows.run` availability + `flow` enum options now derive from an injected `FlowsForCwd` resolver (live per-session flows list), NOT a `.pi/flows/flows` scan; static `discoverFlows`/`hasFlows` + fs/path imports removed. `flowsActionContributions(flowsForCwd)` + `provideFlowsActions(provide,log,flowsForCwd)`. Reflects package-bundled + event-registered flows; empty (disabled) when no running session for the cwd. See change: fix-automation-flow-detection. |
8
+ | `index.ts` | registerPlugin calls wireFlowAutomationActions(ctx.consume,...). See change: register-plugin-automation-events. registerPlugin calls `provideFlowsActions(ctx.provide,…)` instead of `wireFlowAutomationActions(ctx.consume,…)`. See change: decouple-automation-action-registry. Exports `makeFlowsForCwd(sessionManager, store)` → `(cwd)=>string[]`: maps cwd to running session(s) via `sessionManager.listActive()` (exact cwd match), unions `stateStore.getState(id).flows[].name` (`<ns>:<name>`), sorted-unique; injected into `provideFlowsActions`. See change: fix-automation-flow-detection. `plugin_action` handler is now production (replaced the v1 stub): `flow.run` emits `flow:run` `{flowName,task?,inputs?}` into the target session via `ctx.emitEventToSession` (same event `flow_management run` + the automation `flows.run` action dispatch); `flow.new` launches `/skill:manage-flows` via `sendToSession`; missing sessionId / flow name are guarded no-ops. See change: fix-plugin-action-fanout-and-handlers. |
9
+ | `render-actions.ts` | Pure render fn for `SessionFlowActions` intent. Exports `RenderActionsInput`, `RenderedActionItem`, `renderSessionFlowActions`. Translates (flows, commands) into `ui:action-list` IntentNode; each item carries `dataAction` descriptor (`flow.run`/`flow.new`). Returns null when no flows and no `/flows:new`. |
10
+ | `state-store.ts` | Per-session server-side flow state holder. Exports `FlowsSessionServerState`, `stateStore` singleton. Holds `flows`, `commands`, `flowState`. Methods: `ensure`, `getState`, `applyEvent` (runs `reduceFlowEvent`), `setFlows`, `setCommands`, `clearSession`, `__resetForTests`. |
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Flows → automation action contribution (publish/collect).
3
+ *
4
+ * Flows PUBLISHES an immutable action contribution under
5
+ * `automation.action.flows` via `ctx.provide`. It does NOT consume an
6
+ * automation-owned registry, import the automation package, or depend on load
7
+ * order — the automation plugin collects published contributions lazily. If
8
+ * flows is disabled, it publishes nothing and `flows.run` never appears.
9
+ *
10
+ * The contribution is typed structurally so flows needs no compile dependency
11
+ * on automation. See change: decouple-automation-action-registry.
12
+ *
13
+ * Flow availability + the `flow` enum options come from the LIVE per-session
14
+ * flows list the server already holds (`stateStore`, populated by the
15
+ * bridge-forwarded `flows_list`), resolved by mapping a cwd to its running
16
+ * session(s). NOT a static `.pi/flows/flows/` scan — so package-bundled and
17
+ * event-registered flows (which pi-flows discovers at runtime) are reflected.
18
+ * See change: fix-automation-flow-detection.
19
+ */
20
+
21
+ /** Publish key automation collects under (`automation.action.<source>`). */
22
+ export const ACTION_CONTRIBUTION_KEY = "automation.action.flows";
23
+
24
+ /** Structural mirror of one automation payload-schema field. */
25
+ interface ActionFieldSpecLike {
26
+ key: string;
27
+ label: string;
28
+ type: "string" | "multiline" | "text" | "enum";
29
+ help?: string;
30
+ options?: (cwd: string) => string[];
31
+ }
32
+
33
+ /** Structural mirror of an automation action contribution. */
34
+ export interface ActionContributionLike {
35
+ id: string;
36
+ source: string;
37
+ label: string;
38
+ description?: string;
39
+ available?: (cwd: string) => boolean;
40
+ unavailableReason?: string;
41
+ payloadSchema?: ActionFieldSpecLike[];
42
+ /**
43
+ * Event-dispatch: emit a configured event into the run session. May also
44
+ * declare `completion` — how a run of this action FINISHES — so the
45
+ * automation engine can finalize an event-dispatched run (which emits no
46
+ * `agent_end`) without knowing anything action-specific.
47
+ * See change: finalize-event-dispatched-automation-runs.
48
+ */
49
+ buildEvent?: (args: { payload: Record<string, unknown>; automation: unknown }) =>
50
+ | {
51
+ eventType: string;
52
+ data?: Record<string, unknown>;
53
+ completion?: {
54
+ eventType: string;
55
+ summarize?: (data: Record<string, unknown> | undefined) => string;
56
+ };
57
+ }
58
+ | null;
59
+ }
60
+
61
+ /**
62
+ * Resolve the flows available in a cwd: `<ns>:<name>` ids from the live
63
+ * per-session flows list. Injected by the server entry (see index.ts) so this
64
+ * module stays free of server/session dependencies.
65
+ */
66
+ export type FlowsForCwd = (cwd: string) => string[];
67
+
68
+ /**
69
+ * A flow id is `<ns>:<name>`. It is placed into the
70
+ * `flow:run` event payload, so a malformed value is rejected (emit nothing).
71
+ */
72
+ const FLOW_ID_RE = /^[\w.-]+:[\w.-]+$/;
73
+
74
+ /** A plain-object `payload.inputs` with at least one key, else undefined.
75
+ * Values are forwarded as-is (already per-fire resolved, types preserved). */
76
+ function normalizeInputs(raw: unknown): Record<string, unknown> | undefined {
77
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
78
+ const obj = raw as Record<string, unknown>;
79
+ return Object.keys(obj).length > 0 ? obj : undefined;
80
+ }
81
+
82
+ /**
83
+ * Derive an automation run-result line from a pi-flows `flow_complete` payload
84
+ * (the forwarded `FlowResult`: `status`, `flowName`, `lastResult.result.summary`).
85
+ * An event-dispatched flows.run has no assistant turn to capture, so this line
86
+ * IS the run result. Owns the FlowResult shape so the automation plugin does
87
+ * not. See change: finalize-event-dispatched-automation-runs.
88
+ */
89
+ export function summarizeFlowResult(data: Record<string, unknown> | undefined): string {
90
+ const d = data as
91
+ | { status?: string; flowName?: string; lastResult?: { result?: { summary?: string } } }
92
+ | undefined;
93
+ const summary = d?.lastResult?.result?.summary;
94
+ return `flow ${d?.flowName ?? ""} ${d?.status ?? "finished"}${summary ? `: ${summary}` : ""}`
95
+ .replace(/\s+/g, " ")
96
+ .trim();
97
+ }
98
+
99
+ /**
100
+ * Build the flows action contribution(s): flows.run only. Availability and the
101
+ * `flow` enum options derive from the injected `flowsForCwd` resolver (live
102
+ * per-session flows list). See change: fix-automation-flow-detection.
103
+ */
104
+ export function flowsActionContributions(flowsForCwd: FlowsForCwd): ActionContributionLike[] {
105
+ const hasFlows = (cwd: string) => flowsForCwd(cwd).length > 0;
106
+ return [
107
+ {
108
+ id: "flows.run",
109
+ source: "flows",
110
+ label: "Run a flow",
111
+ description: "Run a flow with a task.",
112
+ available: hasFlows,
113
+ unavailableReason: "no flows in this folder (no running session, or the session reports no flows)",
114
+ payloadSchema: [
115
+ { key: "flow", label: "Flow", type: "enum", options: flowsForCwd, help: "Flows reported by the running session for this folder" },
116
+ { key: "task", label: "Task", type: "multiline", help: "Passed as the flow's initial task." },
117
+ ],
118
+ // Emit flow:run into the run session (the event pi-flows listens for),
119
+ // not a slash-command prompt. A flows.run run produces NO agent turn in
120
+ // the host session (pi-flows consumes flow:run headlessly), so it emits
121
+ // no `agent_end`. Declare `completion` so the automation engine finalizes
122
+ // it on the forwarded `flow_complete` event instead (the extension's
123
+ // FLOW_EVENT_MAP forwards pi-flows' `flow:complete` → `flow_complete`).
124
+ // All flows knowledge — the event name and the FlowResult shape — stays
125
+ // here; the automation plugin stays generic.
126
+ //
127
+ // `payload` is already per-fire interpolated by the engine (the
128
+ // `${{trigger}}` token in `payload.inputs` is resolved to the fired
129
+ // value, type preserved). We forward `payload.inputs` as `data.inputs`,
130
+ // which pi-flows consumes as `flowInput` → `${{flow.input.<name>}}`.
131
+ // `task` stays optional and may coexist with `inputs`.
132
+ // See change: finalize-event-dispatched-automation-runs, wire-flow-inputs-in-automation.
133
+ buildEvent: ({ payload }) => {
134
+ const flow = String(payload.flow ?? "").trim();
135
+ if (!FLOW_ID_RE.test(flow)) return null;
136
+ const task = String(payload.task ?? "").trim();
137
+ const inputs = normalizeInputs(payload.inputs);
138
+ const data: Record<string, unknown> = { flowName: flow };
139
+ if (task) data.task = task;
140
+ if (inputs) data.inputs = inputs;
141
+ return {
142
+ eventType: "flow:run",
143
+ data,
144
+ completion: { eventType: "flow_complete", summarize: summarizeFlowResult },
145
+ };
146
+ },
147
+ },
148
+ ];
149
+ }
150
+
151
+ /**
152
+ * Publish the flows action contribution for automation to collect. Pure
153
+ * publisher: consumes nothing, references no automation code, order-agnostic.
154
+ */
155
+ export function provideFlowsActions(
156
+ provide: (name: string, value: unknown) => void,
157
+ log: (m: string) => void,
158
+ flowsForCwd: FlowsForCwd,
159
+ ): void {
160
+ provide(ACTION_CONTRIBUTION_KEY, flowsActionContributions(flowsForCwd));
161
+ log("[flows] published automation action: flows.run");
162
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Read-only reader for a flow's declared `inputs:` schema.
3
+ *
4
+ * Parses `<cwd>/.pi/flows/flows/<ns>/<name>/flow.yaml` and returns the
5
+ * declared flow-level inputs (name + type + required). This is the source of
6
+ * truth the automation input-wiring UI renders from. It NEVER writes a flow
7
+ * file — the automation side only reads the flow's input contract.
8
+ *
9
+ * Mirrors pi-flows' `FlowInputDecl` shape (`flow-typed-io-and-run-state`)
10
+ * without a compile dependency on the pi-flows package.
11
+ *
12
+ * See change: wire-flow-inputs-in-automation.
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { parse as parseYaml } from "yaml";
17
+
18
+ export type FlowInputType = "string" | "number" | "boolean" | "object" | "array";
19
+ const VALID_TYPES: readonly FlowInputType[] = ["string", "number", "boolean", "object", "array"];
20
+
21
+ export interface FlowInputField {
22
+ name: string;
23
+ type: FlowInputType;
24
+ required: boolean;
25
+ }
26
+
27
+ /** Resolve a `<ns>:<name>` flow id to its `flow.yaml` path under `cwd`. */
28
+ export function flowYamlPath(cwd: string, flowId: string): string | null {
29
+ const m = /^([\w.-]+):([\w.-]+)$/.exec(flowId);
30
+ if (!m) return null;
31
+ return path.join(cwd, ".pi", "flows", "flows", m[1], m[2], "flow.yaml");
32
+ }
33
+
34
+ /**
35
+ * Read a flow's declared inputs (read-only). Returns `[]` for a missing file,
36
+ * unparseable yaml, or a flow with no `inputs:`. Invalid input entries are
37
+ * skipped rather than throwing (isolate bad rows, keep good ones).
38
+ */
39
+ export function readFlowInputs(cwd: string, flowId: string): FlowInputField[] {
40
+ const p = flowYamlPath(cwd, flowId);
41
+ if (!p) return [];
42
+ let doc: unknown;
43
+ try {
44
+ doc = parseYaml(fs.readFileSync(p, "utf-8"));
45
+ } catch {
46
+ return [];
47
+ }
48
+ const raw = (doc as Record<string, unknown> | null)?.inputs;
49
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return [];
50
+ const out: FlowInputField[] = [];
51
+ for (const [name, decl] of Object.entries(raw as Record<string, unknown>)) {
52
+ const d = decl as Record<string, unknown> | null;
53
+ const type = d?.type;
54
+ if (typeof type !== "string" || !(VALID_TYPES as readonly string[]).includes(type)) continue;
55
+ out.push({ name, type: type as FlowInputType, required: d?.required === true });
56
+ }
57
+ return out;
58
+ }
@@ -8,18 +8,65 @@
8
8
  * See change: adopt-server-driven-intent-rendering.
9
9
  */
10
10
  import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
- import { stateStore } from "./state-store.js";
11
+ import { provideFlowsActions } from "./automation-actions.js";
12
+ import { readFlowInputs } from "./flow-inputs.js";
12
13
  import { renderSessionFlowActions } from "./render-actions.js";
14
+ import { stateStore } from "./state-store.js";
13
15
 
14
16
  const PLUGIN_ID = "flows";
15
17
 
18
+ /**
19
+ * Resolve the flows available in a folder from the LIVE per-session flows list
20
+ * (`stateStore`, populated by the bridge-forwarded `flows_list`), by mapping
21
+ * the cwd to its running session(s) and unioning their reported `<ns>:<name>`
22
+ * ids. Reflects package-bundled and event-registered flows that a static
23
+ * `.pi/flows/flows` scan would miss; empty when no running session matches the
24
+ * cwd. See change: fix-automation-flow-detection.
25
+ */
26
+ export function makeFlowsForCwd(
27
+ sessionManager: { listActive(): unknown[] },
28
+ store: { getState(id: string): { flows?: Array<{ name?: unknown }> } | undefined },
29
+ ): (cwd: string) => string[] {
30
+ return (cwd: string): string[] => {
31
+ const sessions = sessionManager.listActive() as Array<{ id?: unknown; cwd?: unknown }>;
32
+ const ids = new Set<string>();
33
+ for (const s of sessions) {
34
+ if (!s || typeof s.id !== "string" || s.cwd !== cwd) continue;
35
+ const flows = store.getState(s.id)?.flows;
36
+ if (!flows) continue;
37
+ for (const f of flows) {
38
+ if (f && typeof f.name === "string") ids.add(f.name);
39
+ }
40
+ }
41
+ return [...ids].sort();
42
+ };
43
+ }
44
+
16
45
  /**
17
46
  * Plugin entrypoint called by the dashboard plugin loader at boot.
18
47
  */
19
48
  export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
20
- const { logger, broadcastToSubscribers, registerBrowserHandler } = ctx;
49
+ const { logger, broadcastToSubscribers, registerBrowserHandler, emitEventToSession, sendToSession } = ctx;
21
50
  logger.info("flows-plugin server entry activated (server-driven intents)");
22
51
 
52
+ // Publish the flows automation action (flows.run) for the automation plugin
53
+ // to collect. Pure publisher: no consume, no automation dependency, no load
54
+ // order requirement. See change: decouple-automation-action-registry.
55
+ // Availability + enum options resolve from the LIVE per-session flows list.
56
+ // See change: fix-automation-flow-detection.
57
+ const flowsForCwd = makeFlowsForCwd(ctx.sessionManager, stateStore);
58
+ provideFlowsActions((name, value) => ctx.provide(name, value), (m) => logger.info(m), flowsForCwd);
59
+
60
+ // Read-only endpoint: a flow's declared `inputs:` schema, for the automation
61
+ // input-wiring UI. Never writes a flow file. See change:
62
+ // wire-flow-inputs-in-automation.
63
+ ctx.fastify.get("/api/plugins/flows/flow-inputs", async (req) => {
64
+ const q = (req.query ?? {}) as Record<string, unknown>;
65
+ const cwd = typeof q.cwd === "string" ? q.cwd : process.cwd();
66
+ const flow = typeof q.flow === "string" ? q.flow : "";
67
+ return { inputs: flow ? readFlowInputs(cwd, flow) : [] };
68
+ });
69
+
23
70
  /**
24
71
  * Broadcast the current intent tree for one session's slot.
25
72
  * Called from action handlers AND in response to event-store changes
@@ -37,7 +84,10 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
37
84
  });
38
85
  }
39
86
 
40
- // Action handler: dispatched from any connected client.
87
+ // Action handler: dispatched from any connected client (or a bus script).
88
+ // The gateway fans out plugin_action by pluginId, so this only fires for
89
+ // pluginId==="flows"; the guard below is defense-in-depth.
90
+ // See change: fix-plugin-action-fanout-and-handlers.
41
91
  registerBrowserHandler("plugin_action", (msg) => {
42
92
  const m = msg as {
43
93
  pluginId?: string;
@@ -46,18 +96,52 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
46
96
  payload?: Record<string, unknown>;
47
97
  };
48
98
  if (m.pluginId !== PLUGIN_ID) return;
49
- if (!m.sessionId) return;
99
+ if (!m.sessionId) {
100
+ logger.warn(`flows ${m.action ?? "(no action)"}: missing sessionId`);
101
+ return;
102
+ }
103
+ const payload = m.payload ?? {};
50
104
 
51
105
  switch (m.action) {
52
106
  case "flow.run": {
53
- logger.info(`flow.run from session=${m.sessionId} payload=${JSON.stringify(m.payload)}`);
54
- // v1: log and stub. Production wiring TBD in tasks 16.3 (likely
55
- // calls into pi via send_prompt with the appropriate /flows
56
- // command). For now, the broadcast is the proof of round-trip.
107
+ // Accept `flow` (intent path) or `flowName`; run in the target session
108
+ // by emitting the `flow:run` event pi-flows consumes headlessly — the
109
+ // same event the `flow_management run` client path and the automation
110
+ // `flows.run` action dispatch.
111
+ const flowName = String(payload.flow ?? payload.flowName ?? "").trim();
112
+ if (!flowName) {
113
+ logger.warn(`flow.run from session=${m.sessionId}: missing flow name`);
114
+ return;
115
+ }
116
+ const task = typeof payload.task === "string" ? payload.task.trim() : "";
117
+ // Reject a non-object / array `inputs` (typeof [] === "object") — pi-flows
118
+ // consumes it as a keyed record, so an array would be malformed.
119
+ if (
120
+ payload.inputs !== undefined &&
121
+ (payload.inputs === null ||
122
+ typeof payload.inputs !== "object" ||
123
+ Array.isArray(payload.inputs))
124
+ ) {
125
+ logger.warn(`flow.run session=${m.sessionId}: invalid inputs (expected object)`);
126
+ return;
127
+ }
128
+ const inputs = payload.inputs as Record<string, unknown> | undefined;
129
+ const data: Record<string, unknown> = { flowName };
130
+ if (task) data.task = task;
131
+ if (inputs) data.inputs = inputs;
132
+ const delivered = emitEventToSession(m.sessionId, "flow:run", data);
133
+ logger.info(`flow.run "${flowName}" session=${m.sessionId} delivered=${delivered}`);
57
134
  break;
58
135
  }
59
136
  case "flow.new": {
60
- logger.info(`flow.new from session=${m.sessionId}`);
137
+ // No dedicated server core — authoring is the manage-flows skill,
138
+ // launched via a slash prompt into the session (mirrors the client's
139
+ // New/Edit path). An optional `instruction` is appended.
140
+ const instruction =
141
+ typeof payload.instruction === "string" ? payload.instruction.trim() : "";
142
+ const command = instruction ? `/skill:manage-flows ${instruction}` : "/skill:manage-flows";
143
+ const delivered = sendToSession(m.sessionId, command);
144
+ logger.info(`flow.new session=${m.sessionId} delivered=${delivered}`);
61
145
  break;
62
146
  }
63
147
  default: