@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,18 +7,25 @@
7
7
  *
8
8
  * See change: adopt-server-driven-intent-rendering.
9
9
  */
10
- import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
10
+ import type { PluginStorePolicy, ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
+ import type { AdmitCwdOptions } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
11
12
  import { provideFlowsActions } from "./automation-actions.js";
12
- import { readFlowInputs } from "./flow-inputs.js";
13
- import { registerFlowFileRoutes } from "./flow-files.js";
13
+ import { broadcastEditModeState, handleSetEditMode, migrateLegacyEditFlow, registerEditModeRoutes } from "./edit-mode.js";
14
+ import { FLOW_REQUEST_CATALOG_ACTION } from "../flow-catalog-contract.js";
15
+ import { FLOW_RUN_SNAPSHOT_EVENT } from "../flow-state-serialize.js";
16
+ import { registerFlowCatalog } from "./flow-catalog.js";
17
+ import { flowFileRegistry, registerFlowFileRoutes } from "./flow-files.js";
18
+ import { registerFlowOpen } from "./flow-open.js";
19
+ import { mountFlowInputsRoute } from "./flow-inputs.js";
20
+ import { FLOW_CONTROL_ACTIONS, type FlowControlDeps, registerFlowControlRoute, runFlowControl } from "./flow-control.js";
14
21
  import { renderSessionFlowActions } from "./render-actions.js";
15
22
  import { stateStore } from "./state-store.js";
16
23
 
17
24
  const PLUGIN_ID = "flows";
18
25
 
19
26
  /**
20
- * Resolve the flows available in a folder from the LIVE per-session flows list
21
- * (`stateStore`, populated by the bridge-forwarded `flows_list`), by mapping
27
+ * Resolve the flows available in a folder from the LIVE per-session flow catalog
28
+ * (`stateStore`, fed by forwarded `flow_catalog` events), by mapping
22
29
  * the cwd to its running session(s) and unioning their reported `<ns>:<name>`
23
30
  * ids. Reflects package-bundled and event-registered flows that a static
24
31
  * `.pi/flows/flows` scan would miss; empty when no running session matches the
@@ -43,12 +50,34 @@ export function makeFlowsForCwd(
43
50
  };
44
51
  }
45
52
 
53
+ const snapshotRunId = (data: unknown): unknown => (data as { runId?: unknown } | null | undefined)?.runId;
54
+
55
+ /**
56
+ * Store policy: a `flow_run_snapshot` is stored intact (the bridge budget keeps
57
+ * it under the ceiling; the generic caps would collapse its agents and history)
58
+ * and supersedes older snapshots of the same run. Every other flow event keeps
59
+ * the generic path. See change: fix-flow-reattach-per-run-state (D4).
60
+ */
61
+ export const FLOWS_STORE_POLICY: PluginStorePolicy = {
62
+ bound: (event) => (event.eventType === FLOW_RUN_SNAPSHOT_EVENT ? event : undefined),
63
+ onStored: (event, view) => {
64
+ const runId = snapshotRunId(event.data);
65
+ if (event.eventType !== FLOW_RUN_SNAPSHOT_EVENT || typeof runId !== "string" || !runId) return undefined;
66
+ const older: number[] = [];
67
+ for (const r of view.resident()) {
68
+ if (r.event.eventType === FLOW_RUN_SNAPSHOT_EVENT && snapshotRunId(r.event.data) === runId) older.push(r.seq);
69
+ }
70
+ return older;
71
+ },
72
+ };
73
+
46
74
  /**
47
75
  * Plugin entrypoint called by the dashboard plugin loader at boot.
48
76
  */
49
77
  export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
50
78
  const { logger, broadcastToSubscribers, registerBrowserHandler, emitEventToSession, sendToSession } = ctx;
51
79
  logger.info("flows-plugin server entry activated (server-driven intents)");
80
+ ctx.registerStorePolicy?.(FLOWS_STORE_POLICY);
52
81
 
53
82
  // Publish the flows automation action (flows.run) for the automation plugin
54
83
  // to collect. Pure publisher: no consume, no automation dependency, no load
@@ -61,11 +90,15 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
61
90
  // Read-only endpoint: a flow's declared `inputs:` schema, for the automation
62
91
  // input-wiring UI. Never writes a flow file. See change:
63
92
  // wire-flow-inputs-in-automation.
64
- ctx.fastify.get("/api/plugins/flows/flow-inputs", async (req) => {
65
- const q = (req.query ?? {}) as Record<string, unknown>;
66
- const cwd = typeof q.cwd === "string" ? q.cwd : process.cwd();
67
- const flow = typeof q.flow === "string" ? q.flow : "";
68
- return { inputs: flow ? readFlowInputs(cwd, flow) : [] };
93
+ // The cwd is required + admitted against the host known folders (no `process.cwd()`
94
+ // fallback); a traversal-shaped flow id is refused. See change:
95
+ // harden-git-terminal-plugin-boundaries (S1r).
96
+ const admitOnIndeterminate = ctx.consume<NonNullable<AdmitCwdOptions["onIndeterminate"]>>(
97
+ "host.cwdAdmissionOnIndeterminate",
98
+ );
99
+ mountFlowInputsRoute(ctx.fastify, {
100
+ knownCwds: ctx.consume<() => string[]>("host.knownFolderCwds") ?? (() => []),
101
+ ...(admitOnIndeterminate ? { admitOptions: { onIndeterminate: admitOnIndeterminate } } : {}),
69
102
  });
70
103
 
71
104
  // Flow YAML / agent / code-handler files reported by this plugin's bridge,
@@ -77,11 +110,58 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
77
110
  await registerFlowFileRoutes({
78
111
  fastify: ctx.fastify,
79
112
  networkGuard: ctx.networkGuard,
113
+ readFileGuarded: ctx.readFileGuarded,
80
114
  registerPiRequestHandler: ctx.registerPiRequestHandler,
81
115
  sessionManager: ctx.sessionManager,
82
116
  emitEventToSession,
117
+ registry: flowFileRegistry,
83
118
  });
84
119
 
120
+ // Flow catalog: feed stateStore from forwarded `flow_catalog` events, ask
121
+ // sessions to report (client ask, sibling follow, server start).
122
+ // See change: flows-dock-chip-and-panel-actions (D3, D4).
123
+ const catalog = registerFlowCatalog({
124
+ onEvent: ctx.onEvent,
125
+ onSessionEnded: ctx.onSessionEnded,
126
+ sessionManager: ctx.sessionManager,
127
+ emitEventToSession,
128
+ getPluginConfig: () => ctx.getPluginConfig<Record<string, unknown>>() ?? {},
129
+ store: stateStore,
130
+ logger,
131
+ });
132
+ catalog.startServerStartAsks();
133
+
134
+ // Agent `flow_open` tool (bridge) → `flow/open` lane: catalog or path flow,
135
+ // admitted path files join the SAME file registry the routes serve from.
136
+ // See change: add-flow-open-tool.
137
+ registerFlowOpen({
138
+ registerPiRequestHandler: ctx.registerPiRequestHandler,
139
+ registerBrowserHandler,
140
+ broadcastToSubscribers,
141
+ sessionManager: ctx.sessionManager,
142
+ onSessionEnded: ctx.onSessionEnded,
143
+ store: stateStore,
144
+ requestCatalog: catalog.requestCatalog,
145
+ registry: flowFileRegistry,
146
+ readFileGuarded: ctx.readFileGuarded,
147
+ logger,
148
+ });
149
+
150
+ // Edit mode: global default (`~/.pi/agent/settings.json#flows.editFlow`) +
151
+ // per-session effective state, read-only except the guarded global PUT.
152
+ // The dashboard never writes a repo's `.pi/settings.json` on its own.
153
+ // See change: stop-flows-edit-mode-project-writes (D2, D4).
154
+ const editModeDeps = { sessionManager: ctx.sessionManager, broadcastToSubscribers };
155
+ await registerEditModeRoutes({ ...editModeDeps, fastify: ctx.fastify, networkGuard: ctx.networkGuard });
156
+
157
+ // One-time legacy plugin-config `editFlow` → global file (D6). A failure
158
+ // keeps the key so the next start retries.
159
+ try {
160
+ if ((await migrateLegacyEditFlow(ctx, { logger })) === "migrated") broadcastEditModeState(editModeDeps);
161
+ } catch (err) {
162
+ logger.warn(`flows: legacy editFlow migration failed: ${err instanceof Error ? err.message : String(err)}`);
163
+ }
164
+
85
165
  /**
86
166
  * Broadcast the current intent tree for one session's slot.
87
167
  * Called from action handlers AND in response to event-store changes
@@ -99,6 +179,24 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
99
179
  });
100
180
  }
101
181
 
182
+ // Flow commands (Abort / Auto / Dismiss / Run / Delete / Edit mode): shared
183
+ // by plugin_action and the REST route. See change: update-flows-plugin (D2).
184
+ const controlDeps: FlowControlDeps = {
185
+ ...editModeDeps,
186
+ sessionManager: ctx.sessionManager,
187
+ emitEventToSession,
188
+ logger,
189
+ recordRejectedAction: ctx.recordRejectedAction,
190
+ };
191
+ await registerFlowControlRoute({
192
+ ...controlDeps,
193
+ fastify: ctx.fastify,
194
+ networkGuard: ctx.networkGuard,
195
+ hasOperateAuthority: ctx.identity?.hasOperateAuthority
196
+ ? (req) => ctx.identity?.hasOperateAuthority?.(req) === true
197
+ : undefined,
198
+ });
199
+
102
200
  // Action handler: dispatched from any connected client (or a bus script).
103
201
  // The gateway fans out plugin_action by pluginId, so this only fires for
104
202
  // pluginId==="flows"; the guard below is defense-in-depth.
@@ -117,37 +215,14 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
117
215
  }
118
216
  const payload = m.payload ?? {};
119
217
 
218
+ // The six flow-control actions share validation + relay with the REST
219
+ // route (flow-control.ts). See change: update-flows-plugin (D2).
220
+ if ((FLOW_CONTROL_ACTIONS as readonly string[]).includes(m.action ?? "")) {
221
+ runFlowControl(controlDeps, m.sessionId, m.action as string, payload);
222
+ return;
223
+ }
224
+
120
225
  switch (m.action) {
121
- case "flow.run": {
122
- // Accept `flow` (intent path) or `flowName`; run in the target session
123
- // by emitting the `flow:run` event pi-flows consumes headlessly — the
124
- // same event the `flow_management run` client path and the automation
125
- // `flows.run` action dispatch.
126
- const flowName = String(payload.flow ?? payload.flowName ?? "").trim();
127
- if (!flowName) {
128
- logger.warn(`flow.run from session=${m.sessionId}: missing flow name`);
129
- return;
130
- }
131
- const task = typeof payload.task === "string" ? payload.task.trim() : "";
132
- // Reject a non-object / array `inputs` (typeof [] === "object") — pi-flows
133
- // consumes it as a keyed record, so an array would be malformed.
134
- if (
135
- payload.inputs !== undefined &&
136
- (payload.inputs === null ||
137
- typeof payload.inputs !== "object" ||
138
- Array.isArray(payload.inputs))
139
- ) {
140
- logger.warn(`flow.run session=${m.sessionId}: invalid inputs (expected object)`);
141
- return;
142
- }
143
- const inputs = payload.inputs as Record<string, unknown> | undefined;
144
- const data: Record<string, unknown> = { flowName };
145
- if (task) data.task = task;
146
- if (inputs) data.inputs = inputs;
147
- const delivered = emitEventToSession(m.sessionId, "flow:run", data);
148
- logger.info(`flow.run "${flowName}" session=${m.sessionId} delivered=${delivered}`);
149
- break;
150
- }
151
226
  case "flow.new": {
152
227
  // No dedicated server core — authoring is the manage-flows skill,
153
228
  // launched via a slash prompt into the session (mirrors the client's
@@ -159,8 +234,16 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
159
234
  logger.info(`flow.new session=${m.sessionId} delivered=${delivered}`);
160
235
  break;
161
236
  }
237
+ case FLOW_REQUEST_CATALOG_ACTION: {
238
+ // Browser ask while a session's catalog is unknown, or on chip / menu
239
+ // / picker open (`rediscover` re-reads flows from disk first).
240
+ // Rate-limited per session. See change: flows-dock-chip-and-panel-actions (D3).
241
+ catalog.requestCatalog(m.sessionId, { rediscover: payload.rediscover === true });
242
+ break;
243
+ }
162
244
  default:
163
245
  logger.warn(`unknown flows action: ${m.action}`);
246
+ ctx.recordRejectedAction?.();
164
247
  }
165
248
  });
166
249
 
@@ -19,10 +19,11 @@
19
19
  * See change: adopt-server-driven-intent-rendering.
20
20
  */
21
21
  import type { IntentNode } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/intent-types.js";
22
- import type { FlowInfo, CommandInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
22
+ import type { CommandInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
23
+ import type { FlowCatalogEntry } from "../flow-catalog-contract.js";
23
24
 
24
25
  export interface RenderActionsInput {
25
- flows: FlowInfo[];
26
+ flows: FlowCatalogEntry[];
26
27
  commands: CommandInfo[];
27
28
  }
28
29
 
@@ -6,12 +6,17 @@
6
6
  *
7
7
  * See change: adopt-server-driven-intent-rendering.
8
8
  */
9
- import type { FlowState, FlowInfo, CommandInfo, DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
9
+ import type { CommandInfo, DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import type { FlowState } from "../types.js";
11
+ import type { FlowCatalogEntry } from "../flow-catalog-contract.js";
10
12
  import { isFlowEvent, reduceFlowEvent } from "../flow-reducer.js";
11
13
 
12
14
  export interface FlowsSessionServerState {
13
- /** Available flows for this session (from pi-flows extension). */
14
- flows: FlowInfo[];
15
+ /** Available flows for this session (the plugin flow catalog). */
16
+ flows: FlowCatalogEntry[];
17
+ /** True once a `flow_catalog` arrived for this session. See change:
18
+ * flows-dock-chip-and-panel-actions (D4). */
19
+ catalogKnown?: boolean;
15
20
  /** Available commands for this session. */
16
21
  commands: CommandInfo[];
17
22
  /** Current flow state derived from event stream. Null when no flow active. */
@@ -49,10 +54,11 @@ class StateStore {
49
54
  return changed;
50
55
  }
51
56
 
52
- /** Update available flows list (from pi flows_list message). */
53
- setFlows(sessionId: string, flows: FlowInfo[]): void {
57
+ /** Update the session's flow catalog (from a forwarded `flow_catalog` event). */
58
+ setFlows(sessionId: string, flows: FlowCatalogEntry[]): void {
54
59
  const s = this.ensure(sessionId);
55
60
  s.flows = flows;
61
+ s.catalogKnown = true;
56
62
  }
57
63
 
58
64
  /** Update available commands list. */
package/src/types.ts ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Flow types — owned by the flows plugin (moved out of
3
+ * `packages/shared/src/types.ts`; core holds no flow type). The plugin keeps its
4
+ * per-session slice through its registered session-event reducer and the
5
+ * server `state-store.ts`.
6
+ *
7
+ * pi-flows 0.10 additions (design D6): `skipped` status (untaken / unchosen
8
+ * branch), fan-out item cards keyed `<stepId>[<i>]` grouped under
9
+ * `FlowState.groups`, and a decision's chosen routes on its card.
10
+ * See change: update-flows-plugin (D5, D6).
11
+ */
12
+ import type { FlowDetailEntry, FlowRecentTool } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
+
14
+ // Shared with the core architect state (not flow-run specific); re-exported.
15
+ export type { FlowDetailEntry, FlowRecentTool };
16
+
17
+ /** Status of a flow agent card */
18
+ export type FlowAgentStatus = "pending" | "running" | "complete" | "error" | "blocked" | "skipped";
19
+
20
+ /** Agent card config from pi-flows AgentConfig (minimal subset) */
21
+ export interface FlowAgentCardConfig {
22
+ name: string;
23
+ description?: string;
24
+ model?: string;
25
+ card?: { label?: string; metric?: string; role?: string };
26
+ sourcePath?: string;
27
+ }
28
+
29
+ /** First-class node-kind discriminator emitted by every pi-flows executor.
30
+ * Decided once at the node's started event; carried on the event payload so it
31
+ * persists + replays. Distinct from FlowDetailEntry.kind (text|thinking|tool|error).
32
+ * See change: rework-flows-plugin-for-new-pi-flows (consumes pi-flows surface-node-kind). */
33
+ export type NodeKind =
34
+ | "agent"
35
+ | "agent-decision"
36
+ | "code"
37
+ | "code-decision"
38
+ | "fork";
39
+
40
+ /** Per-agent (per-step) state tracked in flow state */
41
+ export interface FlowAgentState {
42
+ agentName: string;
43
+ stepId: string;
44
+ /** Step type from the flow config (agent, fork, agent-decision, etc.) */
45
+ stepType?: string;
46
+ /** Node-kind from the lifecycle started event; selects the card renderer. */
47
+ nodeKind?: NodeKind;
48
+ /** Failure outcome from the completion event: routed-soft vs flow-halting-hard. */
49
+ outcome?: "success" | "soft" | "hard";
50
+ /** Typed outputs from the completion event (code/agent contract). */
51
+ typedOutputs?: Record<string, string>;
52
+ /** Chosen branch label for code-decision / agent-decision nodes. */
53
+ branch?: string;
54
+ /** Resolved handler target path for code / code-decision nodes (from started). */
55
+ codeTarget?: string;
56
+ status: FlowAgentStatus;
57
+ label?: string;
58
+ model?: string;
59
+ resolvedModel?: string;
60
+ cardRole?: string;
61
+ blockedBy: string[];
62
+ tokens?: { input: number; output: number };
63
+ /** Accumulated per-agent USD cost from `flow_agent_complete` (`result.cost`).
64
+ * Sibling of `tokens`; `undefined` when the session predates cost surfacing. */
65
+ cost?: number;
66
+ duration?: number;
67
+ summary?: string;
68
+ files?: string[];
69
+ recentTools: FlowRecentTool[];
70
+ detailHistory: FlowDetailEntry[];
71
+ loopIteration?: number;
72
+ loopMax?: number;
73
+ sourcePath?: string;
74
+ runCount?: number;
75
+ /** Fan-out item card: 0-based item index and its key `<stepId>[<i>]`. */
76
+ itemIndex?: number;
77
+ itemKey?: string;
78
+ /** Fan-out group parent: item count and ok / failed rollup (derived). */
79
+ itemCount?: number;
80
+ rollup?: { ok: number; failed: number };
81
+ /** Multi-route decision (pi-flows 0.10 `flow_decision`): chosen labels,
82
+ * chosen routes (with fan-out item counts) and a post-routing error. */
83
+ decision?: FlowDecisionInfo;
84
+ }
85
+
86
+ /** What a `flow_decision` stored for one decision step. */
87
+ export interface FlowDecisionInfo {
88
+ labels?: string[];
89
+ routes?: Array<{ branch: string; itemCount?: number }>;
90
+ routeError?: string;
91
+ /** Resolved chosen target step ids (route branch → `branches` target). */
92
+ chosenTargets: string[];
93
+ /** Branch targets of this decision that were not chosen. */
94
+ notTaken: string[];
95
+ }
96
+
97
+ /** How a parent-mailbox question closed (pi-flows `flow:answer.via`). */
98
+ export type FlowQuestionVia = "reply" | "timeout" | "cancel";
99
+
100
+ /** The question's own context block (pi-flows `flow:question.context`). */
101
+ export interface FlowQuestionContext {
102
+ values?: Record<string, unknown>;
103
+ changes?: Array<{ path?: string; added?: number; removed?: number; [k: string]: unknown }>;
104
+ upstream?: Record<string, unknown> | unknown[];
105
+ payload?: unknown;
106
+ text?: string;
107
+ }
108
+
109
+ /** One question a flow step asked its parent session (pi-flows 0.11+ parent
110
+ * mailbox). Folded from `flow_question` / `flow_answer`; holds no receive time,
111
+ * so live and replayed runs fold identically. See change: adopt-flow-parent-mailbox (D1). */
112
+ export interface FlowQuestionState {
113
+ id: string;
114
+ runId?: string;
115
+ stepId?: string;
116
+ agent?: string;
117
+ /** Fan-out item that asked (`item.index` maps onto the item card). */
118
+ item?: { index: number; count?: number };
119
+ kind?: string;
120
+ question: string;
121
+ options?: string[];
122
+ multiSelect?: boolean;
123
+ allowCustom?: boolean;
124
+ canDecide?: boolean;
125
+ /** Effective timeout in seconds (pi-flows 0.14+; `0` disables). */
126
+ timeoutS?: number;
127
+ /** Expiry as epoch ms on the pi host (pi-flows 0.14+). */
128
+ expiresAt?: number;
129
+ default?: string | string[];
130
+ context?: FlowQuestionContext;
131
+ /** Set once by the first `flow_answer` (or `cancel` at run end). */
132
+ closed?: { via: FlowQuestionVia; answer?: string | string[]; notes?: string; decide?: boolean };
133
+ }
134
+
135
+ /** Overall flow execution status. `interrupted` = orphaned run reconciled on resume
136
+ * (pi-flows clear-orphaned synthesized terminal). */
137
+ export type FlowStatus = "running" | "success" | "error" | "aborted" | "interrupted";
138
+
139
+ /** Flow execution state tracked client-side by the event reducer */
140
+ export interface FlowState {
141
+ flowName: string;
142
+ task: string;
143
+ status: FlowStatus;
144
+ /** Parent-mailbox questions keyed by `question_id` (empty at run start).
145
+ * See change: adopt-flow-parent-mailbox (D1). */
146
+ questions?: Record<string, FlowQuestionState>;
147
+ /** Path to the flow YAML file (for YAML viewer) */
148
+ flowSource?: string;
149
+ /** pi-flows run id from `flow_started` (dismiss names the run by it).
150
+ * See change: persist-flow-run-close (D3). */
151
+ runId?: string;
152
+ /** Ordered map — insertion order matches step order from flow config */
153
+ agents: Map<string, FlowAgentState>;
154
+ /** All steps from the flow configuration — used for DAG graph rendering.
155
+ * Includes non-agent steps (fork, agent-decision, code-decision). `branches`
156
+ * carries decision routing (label → target) emitted by `flow:flow-started`. */
157
+ dagSteps?: Array<{ id: string; stepType: string; agent?: string; blockedBy: string[]; branches?: Record<string, string>; onComplete?: string; onError?: string }>;
158
+ /** Set after flow_complete event */
159
+ flowResult?: Record<string, unknown>;
160
+ /** Fan-out groups: step id → item cards in item order (`<stepId>[<i>]`).
161
+ * The pre-listed step card is the group parent. pi-flows ≥ 0.10. */
162
+ groups?: Record<string, FlowAgentState[]>;
163
+ /** Decision step id → its last `flow_decision`. pi-flows ≥ 0.10. */
164
+ decisions?: Record<string, FlowDecisionInfo>;
165
+ /** Steps marked skipped that have no card (non-agent targets). */
166
+ skippedSteps?: string[];
167
+ /** Set when a run snapshot dropped detail history to fit its byte budget.
168
+ * No UI. See change: fix-flow-reattach-per-run-state (D4). */
169
+ historyTrimmed?: boolean;
170
+
171
+ /** Next flow to run (workflow stage resolution) */
172
+ nextStep?: string | null;
173
+ /** Pre-computed summary stats */
174
+ summaryStats?: {
175
+ agentCount: number;
176
+ duration: string;
177
+ fileCount: number;
178
+ perAgent: Array<{ name: string; status: string; fileCount: number }>;
179
+ };
180
+ }
@@ -1,93 +0,0 @@
1
- /**
2
- * FlowQuestionAdapter — PromptBus adapter that claims prompts originating
3
- * inside a running flow step (carrying `metadata.flowId`) so they render
4
- * in the FlowDashboard's upper slot instead of the chat stream.
5
- *
6
- * Lives in the flows-plugin bridge entry. Auto-loaded by pi when the
7
- * dashboard server registers the plugin's bridge path into pi's
8
- * `settings.json#dashboardPluginBridges` + `packages[]` via the standard
9
- * `discoverPlugins → registerAllPluginBridges` pipeline.
10
- *
11
- * Registration: the bridge entry (`./index.ts`) emits
12
- * `pi.events.emit("prompt:register-adapter", new FlowQuestionAdapter())`.
13
- * The main dashboard bridge listens for that event and calls
14
- * `promptBus.registerAdapter(adapter)` (see `packages/extension/src/bridge.ts`
15
- * around the `prompt:register-adapter` handler). PromptBus sorts adapters by
16
- * `priority` (lower first); we use 100 so this adapter beats
17
- * `DashboardDefaultAdapter` (priority 9999).
18
- *
19
- * See change: route-flow-asks-to-upper-slot.
20
- */
21
-
22
- // Structural typing — avoid a hard dep on the main bridge package. The shape
23
- // matches `PromptAdapter` / `PromptRequest` / `PromptClaim` /
24
- // `PromptResponse` in `packages/extension/src/prompt-bus.ts` byte-for-byte.
25
-
26
- interface PromptRequest {
27
- id: string;
28
- pipeline: string;
29
- type: "select" | "input" | "confirm" | "editor" | "multiselect";
30
- question: string;
31
- options?: string[];
32
- defaultValue?: string;
33
- metadata?: Record<string, unknown>;
34
- }
35
-
36
- interface PromptResponse {
37
- id: string;
38
- answer?: string;
39
- cancelled?: boolean;
40
- source: string;
41
- }
42
-
43
- interface PromptComponent {
44
- type: string;
45
- props: Record<string, unknown>;
46
- }
47
-
48
- interface PromptClaim {
49
- component?: PromptComponent;
50
- placement?: "widget-bar" | "inline" | "overlay";
51
- }
52
-
53
- interface PromptAdapter {
54
- name: string;
55
- priority?: number;
56
- onRequest(prompt: PromptRequest): PromptClaim | null | undefined | void;
57
- onResponse(response: PromptResponse): void;
58
- onCancel(id: string): void;
59
- }
60
-
61
- export class FlowQuestionAdapter implements PromptAdapter {
62
- readonly name = "flow-question";
63
- readonly priority = 100;
64
-
65
- onRequest(prompt: PromptRequest): PromptClaim | null {
66
- const flowId = prompt.metadata?.flowId;
67
- if (typeof flowId !== "string" || flowId.length === 0) return null;
68
- const stepId = typeof prompt.metadata?.stepId === "string" ? prompt.metadata.stepId : "";
69
- return {
70
- component: {
71
- type: "flow-question",
72
- props: {
73
- flowId,
74
- stepId,
75
- question: prompt.question,
76
- type: prompt.type,
77
- options: prompt.options,
78
- defaultValue: prompt.defaultValue,
79
- },
80
- },
81
- placement: "widget-bar",
82
- };
83
- }
84
-
85
- onResponse(_response: PromptResponse): void {
86
- // No adapter-owned UI to dismiss — the client tears down the card on
87
- // submit; the bus broadcasts `prompt_dismiss` for all listeners.
88
- }
89
-
90
- onCancel(_id: string): void {
91
- // No adapter-owned UI to dismiss.
92
- }
93
- }