@particle-academy/fancy-flow 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,9 @@
2
2
 
3
3
  [![Fancified](art/fancified.svg)](https://particle.academy)
4
4
 
5
- A headless workflow **engine**, plus an optional React Flow **editor** — six built-in node kits, tokenized theme, and topological execution with per-node status events. The editor is for *designing* graphs; running them is a separate concern, so `fancy-flow/engine` executes a graph with **zero React** on a server, worker, or CLI. React Flow is bundled — consumers `npm install fancy-flow` and get nothing extra.
5
+ A headless workflow **engine**, plus an optional React Flow **editor** — 27 built-in node kinds and a node marketplace, a themeable `--ff-*` token layer, and topological execution with per-node status events. The editor is for *designing* graphs; running them is a separate concern, so `fancy-flow/engine` executes a graph with **zero React** on a server, worker, or CLI. React Flow is bundled — consumers `npm install fancy-flow` and get nothing extra.
6
+
7
+ On AI it is a **shuttle, not an engine**: core declares a `registerLlmClient` contract and never imports a provider SDK. Opt-in adapters ship on their own subpaths — [`./llm/vercel-ai`](#llm-adapters) (Vercel AI SDK, optional `ai` peer) and [`./llm/prism`](#llm-adapters) (a Prism-backed endpoint you own, no SDK at all). A PHP runtime twin, [`fancy-flow-php`](https://github.com/Particle-Academy/fancy-flow-php), executes the same graphs server-side.
6
8
 
7
9
  ## Install
8
10
 
@@ -290,16 +292,25 @@ function MyEditor() {
290
292
  }
291
293
  ```
292
294
 
293
- ## Node kit (v0.1)
295
+ ## Node kinds
294
296
 
295
- | Kind | Purpose | Default ports |
296
- |---|---|---|
297
- | `trigger` | Entry point | outputs only (`out`) |
298
- | `action` | Work-doing node | `in` → `out` |
299
- | `decision` | Branching | `in` → `true` / `false` (configurable) |
300
- | `output` | Terminal | `in` only |
301
- | `note` | Annotation | none |
302
- | `subgraph` | Collapse a group | facade ports |
297
+ 27 builtins, grouped by category. Ids are namespaced (`@particle-academy/<name>`)
298
+ and every bare name below is a permanent alias, so graphs saved against either
299
+ keep resolving.
300
+
301
+ | Category | Kinds |
302
+ |---|---|
303
+ | `trigger` | `manual_trigger`, `webhook_trigger`, `schedule_trigger` |
304
+ | `logic` | `branch`, `switch_case`, `merge`, `for_each`, `wait`, `transform`, `subflow` |
305
+ | `human` | `user_input`, `rich_user_input`, `human_approval`, `notify` |
306
+ | `ai` | `llm_call`, `llm_router`, `tool_use`, `embed_search` |
307
+ | `data` | `variable`, `memory_store`, `data_store` |
308
+ | `io` | `api_request`, `webhook_out` |
309
+ | `output` | `output`, `log` |
310
+ | `layout` / `annotation` | `lane`, `note` — visual only, never executed |
311
+
312
+ Don't hand-copy this list into generated graphs — it moves. Enumerate at
313
+ runtime with `getNodeKind()` / the registry, or ask the Fancy MCP's `list_nodes`.
303
314
 
304
315
  Custom nodes plug in via xyflow's standard `nodeTypes` prop:
305
316
 
@@ -307,6 +318,40 @@ Custom nodes plug in via xyflow's standard `nodeTypes` prop:
307
318
  <FlowCanvas nodeTypes={{ ...defaultNodeTypes, myNode: MyCustomNode }} ... />
308
319
  ```
309
320
 
321
+ ## LLM adapters
322
+
323
+ `llm_router` (alias `llm_branch`) asks a model to pick one of a node's declared
324
+ ports. Core ships the **routing**, never a provider: it declares a
325
+ `registerLlmClient` contract and imports no SDK, so a flow with no AI node pays
326
+ nothing. Two adapters ship opt-in, on their own subpaths.
327
+
328
+ **Prism** — no SDK to install. POSTs the routing question to a route you own,
329
+ which answers it with Prism, keeping keys and provider config server-side:
330
+
331
+ ```ts
332
+ import { usePrismForLlmBranch } from "@particle-academy/fancy-flow/llm/prism";
333
+
334
+ usePrismForLlmBranch({ endpoint: "/api/flow/llm-route" });
335
+ ```
336
+
337
+ The endpoint receives an `LlmRouteRequest` and answers `{ port, reason? }` — the
338
+ same shape `fancy-flow-php` models, so one route serves both the editor's preview
339
+ runs and server-side execution.
340
+
341
+ **Vercel AI SDK** — for a JS-side model. `ai` is an *optional* peer, required
342
+ only by this subpath:
343
+
344
+ ```ts
345
+ import { anthropic } from "@ai-sdk/anthropic";
346
+ import { useVercelAiForLlmBranch } from "@particle-academy/fancy-flow/llm/vercel-ai";
347
+
348
+ useVercelAiForLlmBranch({ model: anthropic("claude-sonnet-4-5") });
349
+ ```
350
+
351
+ Neither is required — `registerLlmClient()` takes any implementation, including a
352
+ hand-rolled fetch. Both constrain the model to the declared ports rather than
353
+ parsing prose, and a port that was never declared throws instead of routing.
354
+
310
355
  ## Runtime
311
356
 
312
357
  `runFlow(graph, executors, onEvent?, options?)` does a topological walk:
@@ -353,6 +398,44 @@ is the parity-tested runtime twin — same `WorkflowSchema` JSON in, same output
353
398
  out — and adds queued durable runs with resume-from-checkpoint plus human
354
399
  approval / `user_input` pauses.
355
400
 
401
+ ### One trigger, several flows
402
+
403
+ `runFlow` runs one graph. When a single webhook, schedule, or record change fires
404
+ **several** flows, don't loop it — `runCohort` treats them as a group:
405
+
406
+ ```ts
407
+ import { runCohort } from "@particle-academy/fancy-flow/engine";
408
+
409
+ const results = await runCohort([enrich, archive, notify], executors, undefined, {
410
+ initialInputs: { t: { deal } },
411
+ guard: async () => Boolean(await findDeal(deal.id)),
412
+ reason: () => `deal ${deal.id} no longer exists`,
413
+ });
414
+ ```
415
+
416
+ A loop — or worse, a `Promise.all` — has no answer for the case that actually
417
+ bites: `archive` deletes the deal, and `notify` then runs against state that is
418
+ no longer there and resolves `ok: true`, having done nothing. Nothing throws.
419
+
420
+ `runCohort` runs the flows in declared order, one at a time, and re-checks
421
+ `guard` immediately before each — not at dispatch, because the hazard is exactly
422
+ what changed in between. A flow whose guard doesn't pass comes back
423
+ `skipped: true` with the reason rather than running:
424
+
425
+ ```ts
426
+ results[2]; // { ok: false, skipped: true, skippedReason: "deal 41 no longer exists", index: 2 }
427
+ ```
428
+
429
+ Policies: `serial-guarded` (default), `serial` (ordered, unguarded), `parallel`
430
+ (all at once — only when the fan-out shares no state). A guard that throws
431
+ **fails closed** and skips. A flow that *fails* does not cancel the cohort —
432
+ "the flow before me threw" is not an answer to "is my input still there", and
433
+ the guard is asked either way.
434
+
435
+ The Laravel twin is `FancyFlow::dispatchCohort()` in `fancy-flow-php`: the same
436
+ contract across a queue, where each run is durable and hands on to its successor
437
+ when it settles.
438
+
356
439
  ### Pausing for a human
357
440
 
358
441
  A workflow that waits for a person is not a failure, but it travels the same
@@ -403,13 +486,17 @@ resume.
403
486
 
404
487
  ## Status
405
488
 
406
- `v0.1` editor + runner + node kit. Roadmap:
489
+ Shipping. Since this list was last written, all of the following landed:
490
+ auto-layout (`dagre`), edge labels, subflows, swimlanes, undo/redo, canvas
491
+ notes, a built-in User Input modal, a `--ff-*` theme token layer, the node
492
+ marketplace manifest + golden-fixture contract, two LLM adapters, and the agent
493
+ bridge (`registerFlowBridge` in `@particle-academy/agent-integrations`).
494
+
495
+ Still open:
407
496
 
408
- - Subgraph expand/collapse interactions
409
- - Edge labels (config metadata)
410
- - Auto-layout (`dagre` integration)
411
497
  - Persistence helpers (zod schema)
412
- - Agent bridge (in `@particle-academy/agent-integrations` coming next)
498
+ - Marketplace **content** the pipeline is complete end to end and the registry
499
+ is deliberately empty; what belongs in it hasn't been scoped yet
413
500
 
414
501
  ## License
415
502
 
@@ -231,5 +231,5 @@ function useFlowHistory(flow) {
231
231
  }
232
232
 
233
233
  export { applyOutputsToNodes, applyStatusesToNodes, createHistory, useFlowHistory, useFlowRun, useFlowState };
234
- //# sourceMappingURL=chunk-HHFOHHAQ.js.map
235
- //# sourceMappingURL=chunk-HHFOHHAQ.js.map
234
+ //# sourceMappingURL=chunk-EBE3FEAJ.js.map
235
+ //# sourceMappingURL=chunk-EBE3FEAJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/use-flow-run.ts","../src/runtime/use-flow-state.ts","../src/runtime/history.ts","../src/runtime/use-flow-history.ts"],"names":["useState","useCallback","useRef"],"mappings":";;;;;AAkDO,SAAS,WAAW,EAAE,OAAA,GAAU,GAAA,EAAI,GAAuB,EAAC,EAAqB;AACtF,EAAA,MAAM,CAAC,QAAA,E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AAA,EAAQ;AACR,QAAA,IAAA,CAAK,SAAS,CAAC,CAAA;AAAA,MACjB,CAAA;AAAA,MACA,aAAA,EAAe,CAAC,OAAA,KAA0B;AAExC,QAAA,IAAI,CAAC,SAAA,CAAU,OAAA,IAAW,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,QAAQ,CAAA,EAAG,OAAA,EAAQ;AAC5E,QAAA,IAAA,CAAK,cAAc,OAAO,CAAA;AAAA,MAC5B,CAAA;AAAA,MACA,aAAA,EAAe,CAAC,OAAA,KAA0B;AACxC,QAAA,IAAI,CAAC,SAAA,CAAU,OAAA,IAAW,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,QAAQ,CAAA,EAAG,OAAA,EAAQ;AAC5E,QAAA,IAAA,CAAK,cAAc,OAAO,CAAA;AAAA,MAC5B,CAAA;AAAA,MACA,SAAA,EAAW,CAAC,IAAA,KAAS;AACnB,QAAA,OAAA,EAAQ;AACR,QAAA,IAAA,CAAK,UAAU,IAAI,CAAA;AAAA,MACrB;AAAA,KACF,CAAA;AAAA,IACA,CAAC,MAAM,OAAO;AAAA,GAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IACN,IAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA,IACzB,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA,IACzB,OAAA;AAAA,IACA,eAAA,EAAiB;AAAA,GACnB;AACF","file":"chunk-HHFOHHAQ.js","sourcesContent":["import { useCallback, useRef, useState } from \"react\";\nimport { runFlow, type RunOptions, type RunResult } from \"./run-flow\";\nimport { getNodeKind } from \"../registry/registry\";\nimport type {\n ExecutorRegistry,\n FlowGraph,\n NodeRunStatus,\n RunEvent,\n} from \"../types\";\n\nexport type FlowRunFeedEntry = {\n id: string;\n at: number;\n level: \"info\" | \"warn\" | \"error\" | \"status\";\n text: string;\n nodeId?: string;\n detail?: unknown;\n};\n\nexport type UseFlowRunReturn = {\n /** Status keyed by nodeId — drive the UI overlay from this. */\n statuses: Record<string, NodeRunStatus>;\n /** Per-node status text (e.g. error message). */\n statusText: Record<string, string | undefined>;\n /** Latest computed output value per node (for reactive kinds). */\n outputs: Record<string, unknown>;\n /** Live event log (capped to last N). */\n feed: FlowRunFeedEntry[];\n /** Whether a run is currently in progress. */\n running: boolean;\n /** Last run result, or null. */\n lastResult: RunResult | null;\n /** Kick off a run with the provided graph + executors. */\n run: (graph: FlowGraph, executors: ExecutorRegistry, options?: RunOptions) => Promise<RunResult>;\n /** Cancel the current run (if any). */\n cancel: () => void;\n /** Reset all runtime state (statuses, feed, lastResult). */\n reset: () => void;\n};\n\nexport type UseFlowRunOptions = {\n /** Cap the in-memory feed to this many entries. Default 200. */\n maxFeed?: number;\n};\n\n/**\n * useFlowRun — drives `runFlow` + maintains observability state. Pair with\n * `applyStatusesToNodes` (below) before passing nodes to `<FlowCanvas>` so\n * the per-node status badge renders.\n */\nexport function useFlowRun({ maxFeed = 200 }: UseFlowRunOptions = {}): UseFlowRunReturn {\n const [statuses, setStatuses] = useState<Record<string, NodeRunStatus>>({});\n const [statusText, setStatusText] = useState<Record<string, string | undefined>>({});\n const [outputs, setOutputs] = useState<Record<string, unknown>>({});\n const [feed, setFeed] = useState<FlowRunFeedEntry[]>([]);\n const [running, setRunning] = useState(false);\n const [lastResult, setLastResult] = useState<RunResult | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const handleEvent = useCallback(\n (e: RunEvent) => {\n switch (e.type) {\n case \"node-status\":\n setStatuses((s) => ({ ...s, [e.nodeId]: e.status }));\n setStatusText((t) => ({ ...t, [e.nodeId]: e.text }));\n appendFeed({ level: \"status\", text: `${e.nodeId} → ${e.status}${e.text ? ` (${e.text})` : \"\"}`, nodeId: e.nodeId });\n break;\n case \"node-output\":\n setOutputs((o) => ({ ...o, [e.nodeId]: e.value }));\n appendFeed({ level: \"info\", text: `${e.nodeId}.${e.portId} = ${preview(e.value)}`, nodeId: e.nodeId, detail: e.value });\n break;\n case \"log\":\n appendFeed({ level: e.level, text: e.message, nodeId: e.nodeId, detail: e.detail });\n break;\n case \"run-start\":\n appendFeed({ level: \"info\", text: \"▶ run started\" });\n break;\n case \"run-end\":\n appendFeed({ level: e.ok ? \"info\" : \"error\", text: e.ok ? \"✓ run complete\" : \"✗ run failed\" });\n break;\n case \"run-error\":\n appendFeed({ level: \"error\", text: e.error });\n break;\n }\n function appendFeed(partial: Omit<FlowRunFeedEntry, \"id\" | \"at\">) {\n setFeed((f) => {\n const entry: FlowRunFeedEntry = { id: `${Date.now()}_${f.length}`, at: Date.now(), ...partial };\n const next = [...f, entry];\n return next.length > maxFeed ? next.slice(next.length - maxFeed) : next;\n });\n }\n },\n [maxFeed],\n );\n\n const run = useCallback(\n async (graph: FlowGraph, executors: ExecutorRegistry, options: RunOptions = {}) => {\n if (running) {\n return { ok: false, outputs: {}, error: \"another run is already in progress\" } satisfies RunResult;\n }\n const controller = new AbortController();\n abortRef.current = controller;\n // Reset previous statuses for the nodes we're about to run.\n const idleStatuses: Record<string, NodeRunStatus> = {};\n for (const n of graph.nodes) idleStatuses[n.id] = \"idle\";\n setStatuses(idleStatuses);\n setStatusText({});\n setOutputs({});\n setRunning(true);\n try {\n const result = await runFlow(graph, executors, handleEvent, { ...options, signal: controller.signal });\n setLastResult(result);\n return result;\n } finally {\n setRunning(false);\n abortRef.current = null;\n }\n },\n [handleEvent, running],\n );\n\n const cancel = useCallback(() => abortRef.current?.abort(), []);\n\n const reset = useCallback(() => {\n setStatuses({});\n setStatusText({});\n setOutputs({});\n setFeed([]);\n setLastResult(null);\n }, []);\n\n return { statuses, statusText, outputs, feed, running, lastResult, run, cancel, reset };\n}\n\n/**\n * Write each reactive kind's latest run output into its `data.output`, so its\n * card can render the computed value live. Non-reactive kinds are returned\n * untouched. Pair with `applyStatusesToNodes` before rendering.\n */\nexport function applyOutputsToNodes<TNode extends { id: string; type?: string; data: any }>(\n nodes: TNode[],\n outputs: Record<string, unknown>,\n): TNode[] {\n return nodes.map((n) => {\n const kind = getNodeKind((n.data as any)?.kind ?? n.type ?? \"\");\n if (!kind?.reactive || !(n.id in outputs)) return n;\n return { ...n, data: { ...n.data, output: outputs[n.id] } };\n });\n}\n\n/** Merge runtime statuses into nodes for rendering. */\nexport function applyStatusesToNodes<TNode extends { id: string; data: any }>(\n nodes: TNode[],\n statuses: Record<string, NodeRunStatus>,\n statusText: Record<string, string | undefined>,\n): TNode[] {\n return nodes.map((n) => ({\n ...n,\n data: {\n ...n.data,\n status: statuses[n.id] ?? n.data?.status ?? \"idle\",\n statusText: statusText[n.id] ?? n.data?.statusText,\n },\n }));\n}\n\nfunction preview(v: unknown): string {\n try {\n const s = JSON.stringify(v);\n return s && s.length > 60 ? s.slice(0, 57) + \"…\" : (s ?? String(v));\n } catch {\n return String(v);\n }\n}\n","import { useCallback, useState } from \"react\";\nimport {\n addEdge,\n applyEdgeChanges,\n applyNodeChanges,\n type Connection,\n type Edge,\n type EdgeChange,\n type NodeChange,\n} from \"@xyflow/react\";\nimport type { FlowEdge, FlowGraph, FlowNode } from \"../types\";\n\nexport type UseFlowStateReturn = {\n nodes: FlowNode[];\n edges: FlowEdge[];\n setNodes: React.Dispatch<React.SetStateAction<FlowNode[]>>;\n setEdges: React.Dispatch<React.SetStateAction<FlowEdge[]>>;\n /**\n * Replace nodes AND edges atomically in a single commit. Use this for any op\n * that touches both (delete-with-edge-prune, undo/redo restore, setGraph):\n * calling `setNodes` then `setEdges` is NOT atomic in controlled mode (each\n * closes over a stale `value`), so the second write clobbers the first.\n */\n setGraph: (graph: FlowGraph) => void;\n onNodesChange: (changes: NodeChange[]) => void;\n onEdgesChange: (changes: EdgeChange[]) => void;\n onConnect: (connection: Connection) => void;\n /** Snapshot the current graph (suitable for serialization). */\n toGraph: () => FlowGraph;\n};\n\n/**\n * useFlowState — React Flow's standard controlled-state plumbing in one hook.\n * Spread into <FlowCanvas>.\n */\nexport function useFlowState(initial: FlowGraph): UseFlowStateReturn {\n const [nodes, setNodes] = useState<FlowNode[]>(initial.nodes);\n const [edges, setEdges] = useState<FlowEdge[]>(initial.edges);\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodes((ns) => applyNodeChanges(changes, ns) as FlowNode[]);\n }, []);\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdges((es) => applyEdgeChanges(changes, es));\n }, []);\n const onConnect = useCallback((connection: Connection) => {\n setEdges((es) => addEdge(connection, es) as Edge[]);\n }, []);\n\n const setGraph = useCallback((graph: FlowGraph) => {\n // Two useState writes in one event are batched, so this IS atomic here.\n setNodes(graph.nodes);\n setEdges(graph.edges);\n }, []);\n\n const toGraph = useCallback(() => ({ nodes, edges }), [nodes, edges]);\n\n return { nodes, edges, setNodes, setEdges, setGraph, onNodesChange, onEdgesChange, onConnect, toGraph };\n}\n","import type { FlowGraph } from \"../types\";\n\n/**\n * Undo/redo history — a pure, React-free snapshot controller. The editor pushes\n * a graph snapshot BEFORE each committing mutation; `undo`/`redo` swap snapshots\n * between the past/future stacks. Kept free of React so it can be unit-tested\n * and reused by any host (or a headless driver).\n *\n * Coalescing (collapsing a burst of setState calls from one logical op into a\n * single undo step) is the caller's job — see `useFlowHistory`.\n */\nexport type HistoryController = {\n /** Record `graph` as an undo point. Clears the redo stack (new branch). */\n push: (graph: FlowGraph) => void;\n /** Pop the last undo point; `current` is pushed onto the redo stack. */\n undo: (current: FlowGraph) => FlowGraph | null;\n /** Pop the last redo point; `current` is pushed back onto the undo stack. */\n redo: (current: FlowGraph) => FlowGraph | null;\n canUndo: () => boolean;\n canRedo: () => boolean;\n clear: () => void;\n /** Test/inspection helper — sizes of the two stacks. */\n size: () => { past: number; future: number };\n};\n\nexport function createHistory(limit = 100): HistoryController {\n let past: FlowGraph[] = [];\n let future: FlowGraph[] = [];\n\n return {\n push(graph) {\n past.push(graph);\n if (past.length > limit) past.shift();\n future = [];\n },\n undo(current) {\n const prev = past.pop();\n if (prev === undefined) return null;\n future.push(current);\n return prev;\n },\n redo(current) {\n const next = future.pop();\n if (next === undefined) return null;\n past.push(current);\n return next;\n },\n canUndo: () => past.length > 0,\n canRedo: () => future.length > 0,\n clear() {\n past = [];\n future = [];\n },\n size: () => ({ past: past.length, future: future.length }),\n };\n}\n","import { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { EdgeChange, NodeChange } from \"@xyflow/react\";\nimport type { FlowGraph } from \"../types\";\nimport { createHistory } from \"./history\";\nimport type { UseFlowStateReturn } from \"./use-flow-state\";\n\nexport type UseFlowHistoryReturn = {\n /** The flow sink wrapped so committing mutations snapshot for undo first. */\n flow: UseFlowStateReturn;\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n /** Snapshot the current graph as an undo point (before a programmatic edit). */\n capture: () => void;\n /** Wire to `<FlowCanvas onNodeDragStart>` — snapshots the pre-drag graph. */\n onNodeDragStart: () => void;\n};\n\n/**\n * useFlowHistory — the commit/undo pipeline. Wraps a flow sink (the uncontrolled\n * `useFlowState` hook OR the controlled adapter) so every *committing* mutation\n * records a snapshot first, giving undo/redo without the editor threading\n * history through each call site. This is the single interception point the\n * two-sink architecture otherwise lacks.\n *\n * Granularity: a burst of setState calls from one logical op (e.g. a\n * delete = setNodes+setEdges) is coalesced into ONE undo step; transient\n * interactive changes (drag-move, dimension-measure, selection) are NOT captured\n * — a drag is captured once at `onNodeDragStart` instead.\n */\nexport function useFlowHistory(flow: UseFlowStateReturn): UseFlowHistoryReturn {\n const history = useRef(createHistory()).current;\n const restoring = useRef(false);\n const coalesced = useRef(false);\n const [, bump] = useState(0);\n const rerender = useCallback(() => bump((n) => n + 1), []);\n\n // Latest graph via a ref, so capture never reads a stale snapshot.\n const graphRef = useRef<FlowGraph>({ nodes: flow.nodes, edges: flow.edges });\n graphRef.current = { nodes: flow.nodes, edges: flow.edges };\n\n const capture = useCallback(() => {\n if (restoring.current || coalesced.current) return;\n coalesced.current = true;\n queueMicrotask(() => {\n coalesced.current = false;\n });\n history.push(graphRef.current);\n rerender();\n }, [history, rerender]);\n\n const restore = useCallback(\n (g: FlowGraph | null) => {\n if (!g) return;\n restoring.current = true;\n flow.setGraph(g);\n queueMicrotask(() => {\n restoring.current = false;\n });\n rerender();\n },\n [flow, rerender],\n );\n\n const undo = useCallback(() => restore(history.undo(graphRef.current)), [history, restore]);\n const redo = useCallback(() => restore(history.redo(graphRef.current)), [history, restore]);\n\n const wrapped = useMemo<UseFlowStateReturn>(\n () => ({\n ...flow,\n setNodes: (next) => {\n capture();\n flow.setNodes(next);\n },\n setEdges: (next) => {\n capture();\n flow.setEdges(next);\n },\n setGraph: (g) => {\n capture();\n flow.setGraph(g);\n },\n onNodesChange: (changes: NodeChange[]) => {\n // Only structural removes commit; position/dimensions/select are transient.\n if (!restoring.current && changes.some((c) => c.type === \"remove\")) capture();\n flow.onNodesChange(changes);\n },\n onEdgesChange: (changes: EdgeChange[]) => {\n if (!restoring.current && changes.some((c) => c.type === \"remove\")) capture();\n flow.onEdgesChange(changes);\n },\n onConnect: (conn) => {\n capture();\n flow.onConnect(conn);\n },\n }),\n [flow, capture],\n );\n\n return {\n flow: wrapped,\n undo,\n redo,\n canUndo: history.canUndo(),\n canRedo: history.canRedo(),\n capture,\n onNodeDragStart: capture,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/runtime/use-flow-run.ts","../src/runtime/use-flow-state.ts","../src/runtime/history.ts","../src/runtime/use-flow-history.ts"],"names":["useState","useCallback","useRef"],"mappings":";;;;;AAkDO,SAAS,WAAW,EAAE,OAAA,GAAU,GAAA,EAAI,GAAuB,EAAC,EAAqB;AACtF,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAI,QAAA,CAAwC,EAAE,CAAA;AAC1E,EAAA,MAAM,CAAC,UAAA,EAAY,aAAa,CAAA,GAAI,QAAA,CAA6C,EAAE,CAAA;AACnF,EAAA,MAAM,CAAC,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A,IAAW,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,QAAQ,CAAA,EAAG,OAAA,EAAQ;AAC5E,QAAA,IAAA,CAAK,cAAc,OAAO,CAAA;AAAA,MAC5B,CAAA;AAAA,MACA,aAAA,EAAe,CAAC,OAAA,KAA0B;AACxC,QAAA,IAAI,CAAC,SAAA,CAAU,OAAA,IAAW,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,QAAQ,CAAA,EAAG,OAAA,EAAQ;AAC5E,QAAA,IAAA,CAAK,cAAc,OAAO,CAAA;AAAA,MAC5B,CAAA;AAAA,MACA,SAAA,EAAW,CAAC,IAAA,KAAS;AACnB,QAAA,OAAA,EAAQ;AACR,QAAA,IAAA,CAAK,UAAU,IAAI,CAAA;AAAA,MACrB;AAAA,KACF,CAAA;AAAA,IACA,CAAC,MAAM,OAAO;AAAA,GAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IACN,IAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA,IACzB,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA,IACzB,OAAA;AAAA,IACA,eAAA,EAAiB;AAAA,GACnB;AACF","file":"chunk-EBE3FEAJ.js","sourcesContent":["import { useCallback, useRef, useState } from \"react\";\nimport { runFlow, type RunOptions, type RunResult } from \"./run-flow\";\nimport { getNodeKind } from \"../registry/registry\";\nimport type {\n ExecutorRegistry,\n FlowGraph,\n NodeRunStatus,\n RunEvent,\n} from \"../types\";\n\nexport type FlowRunFeedEntry = {\n id: string;\n at: number;\n level: \"info\" | \"warn\" | \"error\" | \"status\";\n text: string;\n nodeId?: string;\n detail?: unknown;\n};\n\nexport type UseFlowRunReturn = {\n /** Status keyed by nodeId — drive the UI overlay from this. */\n statuses: Record<string, NodeRunStatus>;\n /** Per-node status text (e.g. error message). */\n statusText: Record<string, string | undefined>;\n /** Latest computed output value per node (for reactive kinds). */\n outputs: Record<string, unknown>;\n /** Live event log (capped to last N). */\n feed: FlowRunFeedEntry[];\n /** Whether a run is currently in progress. */\n running: boolean;\n /** Last run result, or null. */\n lastResult: RunResult | null;\n /** Kick off a run with the provided graph + executors. */\n run: (graph: FlowGraph, executors: ExecutorRegistry, options?: RunOptions) => Promise<RunResult>;\n /** Cancel the current run (if any). */\n cancel: () => void;\n /** Reset all runtime state (statuses, feed, lastResult). */\n reset: () => void;\n};\n\nexport type UseFlowRunOptions = {\n /** Cap the in-memory feed to this many entries. Default 200. */\n maxFeed?: number;\n};\n\n/**\n * useFlowRun — drives `runFlow` + maintains observability state. Pair with\n * `applyStatusesToNodes` (below) before passing nodes to `<FlowCanvas>` so\n * the per-node status badge renders.\n */\nexport function useFlowRun({ maxFeed = 200 }: UseFlowRunOptions = {}): UseFlowRunReturn {\n const [statuses, setStatuses] = useState<Record<string, NodeRunStatus>>({});\n const [statusText, setStatusText] = useState<Record<string, string | undefined>>({});\n const [outputs, setOutputs] = useState<Record<string, unknown>>({});\n const [feed, setFeed] = useState<FlowRunFeedEntry[]>([]);\n const [running, setRunning] = useState(false);\n const [lastResult, setLastResult] = useState<RunResult | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const handleEvent = useCallback(\n (e: RunEvent) => {\n switch (e.type) {\n case \"node-status\":\n setStatuses((s) => ({ ...s, [e.nodeId]: e.status }));\n setStatusText((t) => ({ ...t, [e.nodeId]: e.text }));\n appendFeed({ level: \"status\", text: `${e.nodeId} → ${e.status}${e.text ? ` (${e.text})` : \"\"}`, nodeId: e.nodeId });\n break;\n case \"node-output\":\n setOutputs((o) => ({ ...o, [e.nodeId]: e.value }));\n appendFeed({ level: \"info\", text: `${e.nodeId}.${e.portId} = ${preview(e.value)}`, nodeId: e.nodeId, detail: e.value });\n break;\n case \"log\":\n appendFeed({ level: e.level, text: e.message, nodeId: e.nodeId, detail: e.detail });\n break;\n case \"run-start\":\n appendFeed({ level: \"info\", text: \"▶ run started\" });\n break;\n case \"run-end\":\n appendFeed({ level: e.ok ? \"info\" : \"error\", text: e.ok ? \"✓ run complete\" : \"✗ run failed\" });\n break;\n case \"run-error\":\n appendFeed({ level: \"error\", text: e.error });\n break;\n }\n function appendFeed(partial: Omit<FlowRunFeedEntry, \"id\" | \"at\">) {\n setFeed((f) => {\n const entry: FlowRunFeedEntry = { id: `${Date.now()}_${f.length}`, at: Date.now(), ...partial };\n const next = [...f, entry];\n return next.length > maxFeed ? next.slice(next.length - maxFeed) : next;\n });\n }\n },\n [maxFeed],\n );\n\n const run = useCallback(\n async (graph: FlowGraph, executors: ExecutorRegistry, options: RunOptions = {}) => {\n if (running) {\n return { ok: false, outputs: {}, error: \"another run is already in progress\" } satisfies RunResult;\n }\n const controller = new AbortController();\n abortRef.current = controller;\n // Reset previous statuses for the nodes we're about to run.\n const idleStatuses: Record<string, NodeRunStatus> = {};\n for (const n of graph.nodes) idleStatuses[n.id] = \"idle\";\n setStatuses(idleStatuses);\n setStatusText({});\n setOutputs({});\n setRunning(true);\n try {\n const result = await runFlow(graph, executors, handleEvent, { ...options, signal: controller.signal });\n setLastResult(result);\n return result;\n } finally {\n setRunning(false);\n abortRef.current = null;\n }\n },\n [handleEvent, running],\n );\n\n const cancel = useCallback(() => abortRef.current?.abort(), []);\n\n const reset = useCallback(() => {\n setStatuses({});\n setStatusText({});\n setOutputs({});\n setFeed([]);\n setLastResult(null);\n }, []);\n\n return { statuses, statusText, outputs, feed, running, lastResult, run, cancel, reset };\n}\n\n/**\n * Write each reactive kind's latest run output into its `data.output`, so its\n * card can render the computed value live. Non-reactive kinds are returned\n * untouched. Pair with `applyStatusesToNodes` before rendering.\n */\nexport function applyOutputsToNodes<TNode extends { id: string; type?: string; data: any }>(\n nodes: TNode[],\n outputs: Record<string, unknown>,\n): TNode[] {\n return nodes.map((n) => {\n const kind = getNodeKind((n.data as any)?.kind ?? n.type ?? \"\");\n if (!kind?.reactive || !(n.id in outputs)) return n;\n return { ...n, data: { ...n.data, output: outputs[n.id] } };\n });\n}\n\n/** Merge runtime statuses into nodes for rendering. */\nexport function applyStatusesToNodes<TNode extends { id: string; data: any }>(\n nodes: TNode[],\n statuses: Record<string, NodeRunStatus>,\n statusText: Record<string, string | undefined>,\n): TNode[] {\n return nodes.map((n) => ({\n ...n,\n data: {\n ...n.data,\n status: statuses[n.id] ?? n.data?.status ?? \"idle\",\n statusText: statusText[n.id] ?? n.data?.statusText,\n },\n }));\n}\n\nfunction preview(v: unknown): string {\n try {\n const s = JSON.stringify(v);\n return s && s.length > 60 ? s.slice(0, 57) + \"…\" : (s ?? String(v));\n } catch {\n return String(v);\n }\n}\n","import { useCallback, useState } from \"react\";\nimport {\n addEdge,\n applyEdgeChanges,\n applyNodeChanges,\n type Connection,\n type Edge,\n type EdgeChange,\n type NodeChange,\n} from \"@xyflow/react\";\nimport type { FlowEdge, FlowGraph, FlowNode } from \"../types\";\n\nexport type UseFlowStateReturn = {\n nodes: FlowNode[];\n edges: FlowEdge[];\n setNodes: React.Dispatch<React.SetStateAction<FlowNode[]>>;\n setEdges: React.Dispatch<React.SetStateAction<FlowEdge[]>>;\n /**\n * Replace nodes AND edges atomically in a single commit. Use this for any op\n * that touches both (delete-with-edge-prune, undo/redo restore, setGraph):\n * calling `setNodes` then `setEdges` is NOT atomic in controlled mode (each\n * closes over a stale `value`), so the second write clobbers the first.\n */\n setGraph: (graph: FlowGraph) => void;\n onNodesChange: (changes: NodeChange[]) => void;\n onEdgesChange: (changes: EdgeChange[]) => void;\n onConnect: (connection: Connection) => void;\n /** Snapshot the current graph (suitable for serialization). */\n toGraph: () => FlowGraph;\n};\n\n/**\n * useFlowState — React Flow's standard controlled-state plumbing in one hook.\n * Spread into <FlowCanvas>.\n */\nexport function useFlowState(initial: FlowGraph): UseFlowStateReturn {\n const [nodes, setNodes] = useState<FlowNode[]>(initial.nodes);\n const [edges, setEdges] = useState<FlowEdge[]>(initial.edges);\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodes((ns) => applyNodeChanges(changes, ns) as FlowNode[]);\n }, []);\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdges((es) => applyEdgeChanges(changes, es));\n }, []);\n const onConnect = useCallback((connection: Connection) => {\n setEdges((es) => addEdge(connection, es) as Edge[]);\n }, []);\n\n const setGraph = useCallback((graph: FlowGraph) => {\n // Two useState writes in one event are batched, so this IS atomic here.\n setNodes(graph.nodes);\n setEdges(graph.edges);\n }, []);\n\n const toGraph = useCallback(() => ({ nodes, edges }), [nodes, edges]);\n\n return { nodes, edges, setNodes, setEdges, setGraph, onNodesChange, onEdgesChange, onConnect, toGraph };\n}\n","import type { FlowGraph } from \"../types\";\n\n/**\n * Undo/redo history — a pure, React-free snapshot controller. The editor pushes\n * a graph snapshot BEFORE each committing mutation; `undo`/`redo` swap snapshots\n * between the past/future stacks. Kept free of React so it can be unit-tested\n * and reused by any host (or a headless driver).\n *\n * Coalescing (collapsing a burst of setState calls from one logical op into a\n * single undo step) is the caller's job — see `useFlowHistory`.\n */\nexport type HistoryController = {\n /** Record `graph` as an undo point. Clears the redo stack (new branch). */\n push: (graph: FlowGraph) => void;\n /** Pop the last undo point; `current` is pushed onto the redo stack. */\n undo: (current: FlowGraph) => FlowGraph | null;\n /** Pop the last redo point; `current` is pushed back onto the undo stack. */\n redo: (current: FlowGraph) => FlowGraph | null;\n canUndo: () => boolean;\n canRedo: () => boolean;\n clear: () => void;\n /** Test/inspection helper — sizes of the two stacks. */\n size: () => { past: number; future: number };\n};\n\nexport function createHistory(limit = 100): HistoryController {\n let past: FlowGraph[] = [];\n let future: FlowGraph[] = [];\n\n return {\n push(graph) {\n past.push(graph);\n if (past.length > limit) past.shift();\n future = [];\n },\n undo(current) {\n const prev = past.pop();\n if (prev === undefined) return null;\n future.push(current);\n return prev;\n },\n redo(current) {\n const next = future.pop();\n if (next === undefined) return null;\n past.push(current);\n return next;\n },\n canUndo: () => past.length > 0,\n canRedo: () => future.length > 0,\n clear() {\n past = [];\n future = [];\n },\n size: () => ({ past: past.length, future: future.length }),\n };\n}\n","import { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { EdgeChange, NodeChange } from \"@xyflow/react\";\nimport type { FlowGraph } from \"../types\";\nimport { createHistory } from \"./history\";\nimport type { UseFlowStateReturn } from \"./use-flow-state\";\n\nexport type UseFlowHistoryReturn = {\n /** The flow sink wrapped so committing mutations snapshot for undo first. */\n flow: UseFlowStateReturn;\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n /** Snapshot the current graph as an undo point (before a programmatic edit). */\n capture: () => void;\n /** Wire to `<FlowCanvas onNodeDragStart>` — snapshots the pre-drag graph. */\n onNodeDragStart: () => void;\n};\n\n/**\n * useFlowHistory — the commit/undo pipeline. Wraps a flow sink (the uncontrolled\n * `useFlowState` hook OR the controlled adapter) so every *committing* mutation\n * records a snapshot first, giving undo/redo without the editor threading\n * history through each call site. This is the single interception point the\n * two-sink architecture otherwise lacks.\n *\n * Granularity: a burst of setState calls from one logical op (e.g. a\n * delete = setNodes+setEdges) is coalesced into ONE undo step; transient\n * interactive changes (drag-move, dimension-measure, selection) are NOT captured\n * — a drag is captured once at `onNodeDragStart` instead.\n */\nexport function useFlowHistory(flow: UseFlowStateReturn): UseFlowHistoryReturn {\n const history = useRef(createHistory()).current;\n const restoring = useRef(false);\n const coalesced = useRef(false);\n const [, bump] = useState(0);\n const rerender = useCallback(() => bump((n) => n + 1), []);\n\n // Latest graph via a ref, so capture never reads a stale snapshot.\n const graphRef = useRef<FlowGraph>({ nodes: flow.nodes, edges: flow.edges });\n graphRef.current = { nodes: flow.nodes, edges: flow.edges };\n\n const capture = useCallback(() => {\n if (restoring.current || coalesced.current) return;\n coalesced.current = true;\n queueMicrotask(() => {\n coalesced.current = false;\n });\n history.push(graphRef.current);\n rerender();\n }, [history, rerender]);\n\n const restore = useCallback(\n (g: FlowGraph | null) => {\n if (!g) return;\n restoring.current = true;\n flow.setGraph(g);\n queueMicrotask(() => {\n restoring.current = false;\n });\n rerender();\n },\n [flow, rerender],\n );\n\n const undo = useCallback(() => restore(history.undo(graphRef.current)), [history, restore]);\n const redo = useCallback(() => restore(history.redo(graphRef.current)), [history, restore]);\n\n const wrapped = useMemo<UseFlowStateReturn>(\n () => ({\n ...flow,\n setNodes: (next) => {\n capture();\n flow.setNodes(next);\n },\n setEdges: (next) => {\n capture();\n flow.setEdges(next);\n },\n setGraph: (g) => {\n capture();\n flow.setGraph(g);\n },\n onNodesChange: (changes: NodeChange[]) => {\n // Only structural removes commit; position/dimensions/select are transient.\n if (!restoring.current && changes.some((c) => c.type === \"remove\")) capture();\n flow.onNodesChange(changes);\n },\n onEdgesChange: (changes: EdgeChange[]) => {\n if (!restoring.current && changes.some((c) => c.type === \"remove\")) capture();\n flow.onEdgesChange(changes);\n },\n onConnect: (conn) => {\n capture();\n flow.onConnect(conn);\n },\n }),\n [flow, capture],\n );\n\n return {\n flow: wrapped,\n undo,\n redo,\n canUndo: history.canUndo(),\n canRedo: history.canRedo(),\n capture,\n onNodeDragStart: capture,\n };\n}\n"]}
@@ -0,0 +1,50 @@
1
+ import { runFlow } from './chunk-RE7T5GKQ.js';
2
+
3
+ // src/runtime/run-cohort.ts
4
+ async function runCohort(flows, executors, onEvent = () => {
5
+ }, options = {}) {
6
+ const { policy = "serial-guarded", guard, reason, ...runOptions } = options;
7
+ if (policy === "parallel") {
8
+ return Promise.all(
9
+ flows.map(async (flow, index) => ({
10
+ ...await runFlow(flow, executors, (e) => onEvent(e, index), runOptions),
11
+ index
12
+ }))
13
+ );
14
+ }
15
+ const results = [];
16
+ for (const [index, flow] of flows.entries()) {
17
+ if (policy === "serial-guarded" && guard) {
18
+ const why = () => reason?.(flow, index) ?? "trigger precondition no longer holds";
19
+ let passes;
20
+ try {
21
+ passes = await guard(flow, index);
22
+ } catch (error) {
23
+ results.push({
24
+ ok: false,
25
+ outputs: {},
26
+ index,
27
+ skipped: true,
28
+ skippedReason: `guard could not be evaluated: ${errorText(error)}`
29
+ });
30
+ continue;
31
+ }
32
+ if (!passes) {
33
+ results.push({ ok: false, outputs: {}, index, skipped: true, skippedReason: why() });
34
+ continue;
35
+ }
36
+ }
37
+ results.push({
38
+ ...await runFlow(flow, executors, (e) => onEvent(e, index), runOptions),
39
+ index
40
+ });
41
+ }
42
+ return results;
43
+ }
44
+ function errorText(error) {
45
+ return error instanceof Error ? error.message : String(error);
46
+ }
47
+
48
+ export { runCohort };
49
+ //# sourceMappingURL=chunk-FKOXQP76.js.map
50
+ //# sourceMappingURL=chunk-FKOXQP76.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/run-cohort.ts"],"names":[],"mappings":";;;AAoFA,eAAsB,SAAA,CACpB,KAAA,EACA,SAAA,EACA,OAAA,GAAoD,MAAM;AAAC,CAAA,EAC3D,OAAA,GAAyB,EAAC,EACD;AACzB,EAAA,MAAM,EAAE,MAAA,GAAS,gBAAA,EAAkB,OAAO,MAAA,EAAQ,GAAG,YAAW,GAAI,OAAA;AAEpE,EAAA,IAAI,WAAW,UAAA,EAAY;AACzB,IAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,MACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,MAAW;AAAA,QAChC,GAAI,MAAM,OAAA,CAAQ,IAAA,EAAM,SAAA,EAAW,CAAC,CAAA,KAAM,OAAA,CAAQ,CAAA,EAAG,KAAK,CAAA,EAAG,UAAU,CAAA;AAAA,QACvE;AAAA,OACF,CAAE;AAAA,KACJ;AAAA,EACF;AAEA,EAAA,MAAM,UAA0B,EAAC;AAEjC,EAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAA,CAAM,SAAQ,EAAG;AAC3C,IAAA,IAAI,MAAA,KAAW,oBAAoB,KAAA,EAAO;AACxC,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,GAAS,IAAA,EAAM,KAAK,CAAA,IAAK,sCAAA;AAC3C,MAAA,IAAI,MAAA;AAEJ,MAAA,IAAI;AACF,QAAA,MAAA,GAAS,MAAM,KAAA,CAAM,IAAA,EAAM,KAAK,CAAA;AAAA,MAClC,SAAS,KAAA,EAAO;AAGd,QAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,UACX,EAAA,EAAI,KAAA;AAAA,UACJ,SAAS,EAAC;AAAA,UACV,KAAA;AAAA,UACA,OAAA,EAAS,IAAA;AAAA,UACT,aAAA,EAAe,CAAA,8BAAA,EAAiC,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,SACjE,CAAA;AACD,QAAA;AAAA,MACF;AAEA,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,EAAA,EAAI,KAAA,EAAO,OAAA,EAAS,EAAC,EAAG,KAAA,EAAO,OAAA,EAAS,IAAA,EAAM,aAAA,EAAe,GAAA,IAAO,CAAA;AACnF,QAAA;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,MACX,GAAI,MAAM,OAAA,CAAQ,IAAA,EAAM,SAAA,EAAW,CAAC,CAAA,KAAM,OAAA,CAAQ,CAAA,EAAG,KAAK,CAAA,EAAG,UAAU,CAAA;AAAA,MACvE;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,UAAU,KAAA,EAAwB;AACzC,EAAA,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAC9D","file":"chunk-FKOXQP76.js","sourcesContent":["import type { ExecutorRegistry, FlowGraph, RunEvent } from \"../types\";\nimport { runFlow, type RunOptions, type RunResult } from \"./run-flow\";\n\n/**\n * How the flows one trigger fired should treat each other.\n *\n * - `serial-guarded` (default) — run in the declared order, one at a time,\n * re-checking `guard` immediately before each. This is the safe default\n * because it is the only one that notices when an earlier flow invalidated\n * the state a later one was fired for.\n * - `serial` — ordered, one at a time, unguarded.\n * - `parallel` — all at once. Ordering is incidental and collisions are yours to\n * handle; correct for fan-outs that share no state, and only those.\n */\nexport type CohortPolicy = \"serial-guarded\" | \"serial\" | \"parallel\";\n\n/**\n * The precondition re-checked just before each flow starts.\n *\n * Return `false` (or throw) to skip that flow. The engine cannot know what\n * \"still valid\" means for your data, so it asks you — right before the run,\n * not at dispatch, because the whole hazard is what changed in between.\n */\nexport type CohortGuard = (\n flow: FlowGraph,\n index: number,\n) => boolean | Promise<boolean>;\n\nexport type CohortOptions = RunOptions & {\n policy?: CohortPolicy;\n guard?: CohortGuard;\n /** Why the guard said no — recorded on the skipped result. */\n reason?: (flow: FlowGraph, index: number) => string;\n};\n\nexport type CohortResult = RunResult & {\n index: number;\n /** True when the flow never ran because its guard did not pass. */\n skipped?: boolean;\n skippedReason?: string;\n};\n\n/**\n * runCohort — run every flow that one trigger event fired, as a group.\n *\n * ## Why this exists\n *\n * `runFlow` runs one graph. A host that fans a single webhook, schedule, or\n * record change out to several flows usually loops it — and a loop, or worse a\n * `Promise.all`, has no answer for the case that actually bites: one of those\n * flows deletes or mutates the record they were ALL fired for. The others then\n * run against state that is no longer there and resolve `ok: true`, having done\n * nothing. Nothing throws. Nothing is logged. That silent success is the failure\n * mode this function exists to remove.\n *\n * ## What it does\n *\n * Runs the flows in the order you declared, one at a time, and calls `guard`\n * immediately before each. A flow whose guard does not pass is returned with\n * `skipped: true` and a reason instead of being run — and the cohort carries on\n * to the next one.\n *\n * ```ts\n * const results = await runCohort([enrich, archive, notify], executors, undefined, {\n * initialInputs: { t: { deal } }, // snapshotted once, shared by all\n * guard: async () => Boolean(await findDeal(deal.id)),\n * reason: () => `deal ${deal.id} no longer exists`,\n * });\n * ```\n *\n * If `archive` deletes the deal, `notify` comes back skipped with that reason\n * rather than notifying about nothing.\n *\n * ## Failure does not cancel the cohort\n *\n * A flow that fails is reported and the next one still runs. \"The flow before me\n * threw\" is not an answer to \"is my input still there\" — the guard is, and it\n * gets asked either way.\n *\n * The Laravel twin (`FancyFlow::dispatchCohort()` in `fancy-flow-php`) is the\n * same contract across a queue, where each run is durable and hands on to its\n * successor when it settles. Same policies, same guard semantics, same\n * fail-closed rule.\n */\nexport async function runCohort(\n flows: FlowGraph[],\n executors: ExecutorRegistry,\n onEvent: (event: RunEvent, index: number) => void = () => {},\n options: CohortOptions = {},\n): Promise<CohortResult[]> {\n const { policy = \"serial-guarded\", guard, reason, ...runOptions } = options;\n\n if (policy === \"parallel\") {\n return Promise.all(\n flows.map(async (flow, index) => ({\n ...(await runFlow(flow, executors, (e) => onEvent(e, index), runOptions)),\n index,\n })),\n );\n }\n\n const results: CohortResult[] = [];\n\n for (const [index, flow] of flows.entries()) {\n if (policy === \"serial-guarded\" && guard) {\n const why = () => reason?.(flow, index) ?? \"trigger precondition no longer holds\";\n let passes: boolean;\n\n try {\n passes = await guard(flow, index);\n } catch (error) {\n // Fail CLOSED. A guard that cannot answer is not permission to proceed:\n // a skip is visible and re-runnable, a run over missing state is neither.\n results.push({\n ok: false,\n outputs: {},\n index,\n skipped: true,\n skippedReason: `guard could not be evaluated: ${errorText(error)}`,\n });\n continue;\n }\n\n if (!passes) {\n results.push({ ok: false, outputs: {}, index, skipped: true, skippedReason: why() });\n continue;\n }\n }\n\n results.push({\n ...(await runFlow(flow, executors, (e) => onEvent(e, index), runOptions)),\n index,\n });\n }\n\n return results;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"]}
package/dist/engine.cjs CHANGED
@@ -191,6 +191,51 @@ function activatedPorts(node, result) {
191
191
  return { ports: declared?.length ? declared : ["out"], value: result };
192
192
  }
193
193
 
194
+ // src/runtime/run-cohort.ts
195
+ async function runCohort(flows, executors, onEvent = () => {
196
+ }, options = {}) {
197
+ const { policy = "serial-guarded", guard, reason, ...runOptions } = options;
198
+ if (policy === "parallel") {
199
+ return Promise.all(
200
+ flows.map(async (flow, index) => ({
201
+ ...await runFlow(flow, executors, (e) => onEvent(e, index), runOptions),
202
+ index
203
+ }))
204
+ );
205
+ }
206
+ const results = [];
207
+ for (const [index, flow] of flows.entries()) {
208
+ if (policy === "serial-guarded" && guard) {
209
+ const why = () => reason?.(flow, index) ?? "trigger precondition no longer holds";
210
+ let passes;
211
+ try {
212
+ passes = await guard(flow, index);
213
+ } catch (error) {
214
+ results.push({
215
+ ok: false,
216
+ outputs: {},
217
+ index,
218
+ skipped: true,
219
+ skippedReason: `guard could not be evaluated: ${errorText(error)}`
220
+ });
221
+ continue;
222
+ }
223
+ if (!passes) {
224
+ results.push({ ok: false, outputs: {}, index, skipped: true, skippedReason: why() });
225
+ continue;
226
+ }
227
+ }
228
+ results.push({
229
+ ...await runFlow(flow, executors, (e) => onEvent(e, index), runOptions),
230
+ index
231
+ });
232
+ }
233
+ return results;
234
+ }
235
+ function errorText(error) {
236
+ return error instanceof Error ? error.message : String(error);
237
+ }
238
+
194
239
  // src/registry/pause.ts
195
240
  var PAUSE_PREFIX = "fancy-flow:pause:";
196
241
  var LEGACY_PAUSE_PREFIXES = [
@@ -710,6 +755,7 @@ exports.decodePause = decodePause;
710
755
  exports.encodePause = encodePause;
711
756
  exports.isPause = isPause;
712
757
  exports.pauseForHuman = pauseForHuman;
758
+ exports.runCohort = runCohort;
713
759
  exports.runFixtures = runFixtures;
714
760
  exports.runFlow = runFlow;
715
761
  exports.satisfiesRange = satisfiesRange;