@fractal-solutions/qflow 1.0.84 → 2.0.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 (114) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/LICENSE +21 -504
  3. package/MIGRATION.md +1130 -0
  4. package/README.md +1432 -823
  5. package/dist/agent/agent.d.ts +4 -22
  6. package/dist/agent/agent.js +4 -364
  7. package/dist/agent/base_agent.d.ts +8 -20
  8. package/dist/agent/base_agent.js +8 -205
  9. package/dist/agent/control_nodes.d.ts +61 -0
  10. package/dist/agent/control_nodes.js +164 -0
  11. package/dist/agent/engine.d.ts +45 -0
  12. package/dist/agent/engine.js +415 -0
  13. package/dist/agent/flow.d.ts +77 -0
  14. package/dist/agent/flow.js +148 -0
  15. package/dist/agent/index.d.ts +12 -0
  16. package/dist/agent/index.js +12 -0
  17. package/dist/agent/lpavrl_agent.d.ts +1 -2
  18. package/dist/agent/lpavrl_agent.js +2 -175
  19. package/dist/agent/ooda_agent.d.ts +1 -2
  20. package/dist/agent/ooda_agent.js +2 -164
  21. package/dist/agent/pema_agent.d.ts +1 -2
  22. package/dist/agent/pema_agent.js +2 -168
  23. package/dist/agent/raor_agent.d.ts +1 -2
  24. package/dist/agent/raor_agent.js +2 -161
  25. package/dist/agent/strategies.d.ts +126 -0
  26. package/dist/agent/strategies.js +159 -0
  27. package/dist/agent/tools.d.ts +1 -0
  28. package/dist/agent/tools.js +42 -24
  29. package/dist/approval.d.ts +42 -0
  30. package/dist/approval.js +86 -0
  31. package/dist/budget.d.ts +103 -0
  32. package/dist/budget.js +133 -0
  33. package/dist/bun_nodes.d.ts +119 -0
  34. package/dist/bun_nodes.js +331 -0
  35. package/dist/contracts.d.ts +30 -0
  36. package/dist/contracts.js +103 -0
  37. package/dist/durable.d.ts +278 -0
  38. package/dist/durable.js +730 -0
  39. package/dist/eval.d.ts +165 -0
  40. package/dist/eval.js +263 -0
  41. package/dist/graph.d.ts +157 -0
  42. package/dist/graph.js +330 -0
  43. package/dist/llm/index.d.ts +359 -0
  44. package/dist/llm/index.js +924 -0
  45. package/dist/logger.js +7 -3
  46. package/dist/mcp/client.d.ts +55 -0
  47. package/dist/mcp/client.js +145 -0
  48. package/dist/mcp/index.d.ts +2 -0
  49. package/dist/mcp/index.js +2 -0
  50. package/dist/mcp/server.d.ts +106 -0
  51. package/dist/mcp/server.js +154 -0
  52. package/dist/mcp/stdio.d.ts +2 -0
  53. package/dist/mcp/stdio.js +3 -0
  54. package/dist/memory.d.ts +101 -0
  55. package/dist/memory.js +217 -0
  56. package/dist/nodes/browser_control.js +5 -4
  57. package/dist/nodes/data_extractor.js +2 -1
  58. package/dist/nodes/data_validation.d.ts +3 -3
  59. package/dist/nodes/data_validation.js +19 -5
  60. package/dist/nodes/database.d.ts +2 -1
  61. package/dist/nodes/database.js +71 -58
  62. package/dist/nodes/gis.js +1 -1
  63. package/dist/nodes/git.d.ts +1 -1
  64. package/dist/nodes/git.js +65 -51
  65. package/dist/nodes/github.d.ts +1 -0
  66. package/dist/nodes/hardware_interaction.d.ts +2 -4
  67. package/dist/nodes/hardware_interaction.js +4 -3
  68. package/dist/nodes/http.d.ts +1 -7
  69. package/dist/nodes/http.js +46 -33
  70. package/dist/nodes/image_gallery.js +45 -45
  71. package/dist/nodes/index.d.ts +8 -0
  72. package/dist/nodes/index.js +8 -0
  73. package/dist/nodes/interactive_webview.d.ts +1 -2
  74. package/dist/nodes/interactive_webview.js +217 -216
  75. package/dist/nodes/multimedia_processing.js +1 -1
  76. package/dist/nodes/navigator.d.ts +7 -0
  77. package/dist/nodes/navigator.js +48 -8
  78. package/dist/nodes/pdf_processor.js +2 -1
  79. package/dist/nodes/remote_execution.js +2 -2
  80. package/dist/nodes/s3.d.ts +1 -0
  81. package/dist/nodes/scheduler.js +2 -2
  82. package/dist/nodes/search.d.ts +1 -1
  83. package/dist/nodes/search.js +3 -2
  84. package/dist/nodes/speech_synthesis.js +2 -1
  85. package/dist/nodes/spreadsheet.d.ts +1 -7
  86. package/dist/nodes/spreadsheet.js +2 -1
  87. package/dist/nodes/streaming_llm.d.ts +51 -0
  88. package/dist/nodes/streaming_llm.js +120 -0
  89. package/dist/nodes/webhook.d.ts +1 -5
  90. package/dist/nodes/webhook.js +106 -93
  91. package/dist/nodes/websockets.js +5 -3
  92. package/dist/nodes/webview.js +3 -2
  93. package/dist/optional.d.ts +32 -0
  94. package/dist/optional.js +61 -0
  95. package/dist/qflow.d.ts +25 -14
  96. package/dist/qflow.js +140 -49
  97. package/dist/schedule.d.ts +41 -0
  98. package/dist/schedule.js +149 -0
  99. package/dist/side_effects.d.ts +50 -0
  100. package/dist/side_effects.js +94 -0
  101. package/dist/streaming.d.ts +35 -0
  102. package/dist/streaming.js +199 -0
  103. package/dist/testing.d.ts +47 -0
  104. package/dist/testing.js +130 -0
  105. package/dist/tool_spec.d.ts +76 -0
  106. package/dist/tool_spec.js +321 -0
  107. package/dist/trace.d.ts +28 -0
  108. package/dist/trace.js +190 -0
  109. package/dist/util.d.ts +57 -0
  110. package/dist/util.js +122 -0
  111. package/package.json +153 -67
  112. package/qflow.config.js +18 -18
  113. package/scripts/postinstall.js +50 -0
  114. package/scripts/verify-package.js +114 -0
package/README.md CHANGED
@@ -1,823 +1,1432 @@
1
- # qflow: A Lightweight and Flexible JavaScript Workflow and Agent Library
2
-
3
- `qflow` is a lightweight and flexible JavaScript library designed for creating and managing complex workflows and autonomous agents. It provides a minimalist yet expressive API to define sequences of operations, manage data flow, and orchestrate execution, supporting both synchronous and asynchronous patterns.
4
-
5
- ## Features
6
-
7
- * **Modular & Extensible:** Easily define custom nodes and compose them into complex, reusable flows.
8
- * **Synchronous & Asynchronous Flows:** Supports both blocking and non-blocking execution models.
9
- * **Observability:** Monitor workflows with a built-in event system that emits detailed lifecycle events for flows and nodes.
10
- * **Shared State Management:** Pass and manipulate data across nodes using a central, mutable `shared` object.
11
- * **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows, including parallel execution.
12
- * **Agents:** Built upon the `qflow` core functionality are plug and play agents with extensive tool integrations available.
13
- * **Built-in Integrations:** Comes with pre-built nodes for multiple tasks like LLM interactions, browser use, pdf tools, webhooks, spreadsheet manipulation, code interpretation, media manipulation, web scraping, and popular API integrations (GitHub, Git, Open Router, HackerNews, Stripe, Maps).
14
- * **Custom Agent Tools:** Build your own Agent tools using the flow registry pattern.
15
-
16
- ## Installation
17
-
18
- To get started quickly with a new project, you can use the `create-qflow` tool (Recommended):
19
-
20
- ```bash
21
- bunx create-qflow@latest <project-name>
22
- ```
23
-
24
- or
25
-
26
- You can install `qflow` via npm or Bun:
27
-
28
- ```bash
29
- npm install @fractal-solutions/qflow
30
- # or
31
- bun add @fractal-solutions/qflow
32
- ```
33
-
34
- ## Module Imports
35
-
36
- `qflow` provides different entry points for its core functionalities and built-in nodes to keep your imports clean and specific.
37
-
38
- * **Core Classes (`Node`, `Flow`, `AsyncNode`, `AsyncFlow`, etc.):**
39
- These are imported directly from the main package:
40
- ```javascript
41
- import { Node, Flow, AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
42
- ```
43
-
44
- * **Built-in Integration Nodes (`LLMNode`, `DeepSeekLLMNode`, `GitHubNode`, `WebScraperNode`, etc.):**
45
- These are imported from the `/nodes` subpath:
46
- ```javascript
47
- import { DeepSeekLLMNode, GitHubNode, WebScraperNode } from '@fractal-solutions/qflow/nodes';
48
- ```
49
-
50
- ## Core Abstractions
51
-
52
- `qflow` is built around a few core abstractions that enable powerful and flexible workflow definitions.
53
-
54
- ### Shared State (`shared` object)
55
-
56
- A central, mutable JavaScript object that is passed through the entire flow. Nodes can read from and write to this `shared` object, making it the primary mechanism for passing data and context between different nodes in a workflow. This is particularly useful for accumulating results or maintaining state across multiple steps.
57
-
58
- ### Node
59
-
60
- The fundamental building block of any `qflow` workflow. A `Node` represents a single, atomic operation or step in your flow.
61
-
62
- * `prep(shared)`: Prepares data for execution. Receives the `shared` object.
63
- * `exec(prepRes)`: Executes the node's primary logic.
64
- * `post(shared, prepRes, execRes)`: Processes the result of `exec`. Receives the `shared` object.
65
- * `setParams(params)`: Configures the node with specific parameters. Parameters are accessible via `this.params`.
66
- * `next(node, action = "default")`: Chains this node to another, defining the next step in the flow.
67
-
68
- **Asynchronous Nodes (`AsyncNode`, `AsyncBatchNode`, `AsyncParallelBatchNode`)**
69
- For operations that involve I/O or are inherently asynchronous, `qflow` provides `AsyncNode` and its variants. These nodes leverage `async`/`await` for non-blocking execution. When working within `AsyncFlow`s, it's crucial to implement the `async` versions of the lifecycle methods:
70
- * `prepAsync(shared)`
71
- * `execAsync(prepRes, shared)`
72
- * `postAsync(shared, prepRes, execRes)`
73
- * `preparePrompt(shared)` (specifically for LLM nodes, allowing prompt construction based on `shared` state)
74
-
75
- These `async` methods ensure proper awaiting and data propagation within asynchronous workflows.
76
-
77
- ### Flow
78
-
79
- A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
80
-
81
- * `start(startNode)`: Sets the initial node for the flow. (Note: In practice, you often pass the start node directly to the `Flow` constructor for conciseness).
82
- * `_orch(shared, params)` / `_orchAsync(shared, params)`: Internal methods used to run the flow, especially when passing initial parameters to the starting node. For most use cases, `flow.run(sharedState)` or `await flow.runAsync(sharedState)` is sufficient.
83
-
84
- **Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
85
- These specialized flows are designed to process collections of items. They run a sub-flow for each item in the batch. `AsyncParallelBatchFlow` is particularly useful for concurrently processing batch items, significantly speeding up operations.
86
-
87
-
88
- ## Basic Usage & Examples
89
-
90
- ### 1. Simple Node
91
-
92
- A basic example of defining and running a single node.
93
-
94
- ```javascript
95
- import { Node } from '@fractal-solutions/qflow';
96
-
97
- class MySimpleNode extends Node {
98
- prep(shared) {
99
- console.log('Preparing data...');
100
- return shared.inputData * 2;
101
- }
102
-
103
- exec(prepRes) {
104
- console.log('Executing with prepared data:', prepRes);
105
- return prepRes + 10;
106
- }
107
-
108
- post(shared, prepRes, execRes) {
109
- console.log('Post-processing result:', execRes);
110
- return { finalResult: execRes, originalInput: shared.inputData };
111
- }
112
- }
113
-
114
- const node = new MySimpleNode();
115
- const result = node.run({ inputData: 5 });
116
- console.log('Node run result:', result);
117
- // Expected output:
118
- // Preparing data...
119
- // Executing with prepared data: 10
120
- // Post-processing result: 20
121
- // Node run result: { finalResult: 20, originalInput: 5 }
122
- ```
123
-
124
- ### 2. Simple Flow
125
-
126
- Chaining multiple nodes together to form a basic workflow.
127
-
128
- ```javascript
129
- import { Node, Flow } from '@fractal-solutions/qflow';
130
-
131
- let count = 0;
132
-
133
- class MessageNode extends Node {
134
- exec() {
135
- count++;
136
- console.log(`New Message ${count}`);
137
- return `default`;
138
- }
139
- }
140
-
141
- class TimeNode extends Node {
142
- exec() {
143
- console.log(`Time ${Date.now()}`);
144
- return `default`;
145
- }
146
- }
147
-
148
- const m1 = new MessageNode();
149
- const t1 = new TimeNode();
150
- const m2 = new MessageNode();
151
-
152
- m1.next(t1);
153
- t1.next(m2);
154
-
155
- const flow = new Flow(m1);
156
- flow.run({});
157
- // Expected output (approximate):
158
- // New Message 1
159
- // Time <timestamp>
160
- // New Message 2
161
- ```
162
-
163
- ### 3. Conditional Flow
164
-
165
- Using `transition()` for dynamic branching based on an action. This example demonstrates configuring a node using `setParams` for a cleaner API.
166
-
167
- ```javascript
168
- import { Node, Flow } from '@fractal-solutions/qflow';
169
-
170
- class ConditionalNode extends Node {
171
- exec() {
172
- // Access shouldGoLeft from this.params, which is set via setParams
173
- if (this.params.shouldGoLeft) {
174
- console.log('ConditionalNode: Going left');
175
- return 'left';
176
- } else {
177
- console.log('ConditionalNode: Going right');
178
- return 'right';
179
- }
180
- }
181
- }
182
-
183
- // Helper node for conditional transition test
184
- function MessageNode(message) {
185
- return new (class extends Node {
186
- exec() {
187
- console.log(message);
188
- return 'default';
189
- }
190
- })();
191
- }
192
-
193
- const conditionalNode = new ConditionalNode();
194
- conditionalNode.setParams({ shouldGoLeft: true }); // Configure via setParams
195
-
196
- const leftNode = MessageNode('Went Left');
197
- const rightNode = MessageNode('Went Right');
198
-
199
- conditionalNode.next(leftNode, 'left');
200
- conditionalNode.next(rightNode, 'right');
201
-
202
- const conditionalFlow = new Flow(conditionalNode);
203
- conditionalFlow.run({});
204
- // Expected output:
205
- // ConditionalNode: Going left
206
- // Went Left
207
-
208
- const conditionalNode2 = new ConditionalNode();
209
- conditionalNode2.setParams({ shouldGoLeft: false }); // Configure via setParams
210
-
211
- conditionalNode2.next(leftNode, 'left');
212
- conditionalNode2.next(rightNode, 'right');
213
- const conditionalFlow2 = new Flow(conditionalNode2);
214
- conditionalFlow2.run({});
215
- // Expected output:
216
- // ConditionalNode: Going right
217
- // Went Right
218
- ```
219
-
220
- ### 4. Asynchronous Flow
221
-
222
- Handling asynchronous operations within a flow.
223
-
224
- ```javascript
225
- import { AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
226
-
227
- class MyAsyncNode extends AsyncNode {
228
- async execAsync() {
229
- console.log('AsyncNode: Starting...');
230
- await new Promise(resolve => setTimeout(resolve, 100));
231
- console.log('AsyncNode: Finished!');
232
- return 'default';
233
- }
234
- }
235
-
236
- const asyncNode1 = new MyAsyncNode();
237
- const asyncNode2 = new MyAsyncNode();
238
- asyncNode1.next(asyncNode2);
239
-
240
- const asyncFlow = new AsyncFlow(asyncNode1);
241
- await asyncFlow.runAsync({});
242
- // Expected output:
243
- // AsyncNode: Starting...
244
- // AsyncNode: Finished!
245
- // AsyncNode: Starting...
246
- // AsyncNode: Finished!
247
- ```
248
-
249
- See [documentation/examples.md](documentation/examples.md) for a full list of examples.
250
-
251
- ## Advanced Examples
252
-
253
- ### Interactive Webview Form with Validation
254
-
255
- This example demonstrates how to create a persistent interactive webview for a multi-field form, perform data validation using `DataValidationNode`, and provide dynamic feedback to the user within the webview.
256
-
257
- See [examples/advanced_interactive_webview_form.js](examples/advanced_interactive_webview_form.js) for the full example.
258
-
259
- ### Webview Data Visualization
260
-
261
- This example demonstrates how to generate data within a qflow, create dynamic HTML content with embedded JavaScript (using Chart.js) for data visualization, and display this visualization in a `WebviewNode`.
262
-
263
- See [examples/webview_data_visualization.js](examples/webview_data_visualization.js) for the full example.
264
-
265
-
266
-
267
- ## Integrated Nodes and their Examples
268
-
269
- Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
270
-
271
- ### Data
272
-
273
- * **[CodeInterpreterNode](documentation/nodes/code_interpreter.md)**: Executes Python code snippets.
274
- * **[DataExtractorNode](documentation/nodes/data_extractor.md)**: Extracts structured data from HTML, JSON, or plain text.
275
- * **[DatabaseNode](documentation/nodes/database.md)**: Provides a powerful and flexible way to interact with SQL databases.
276
- * **[EmbeddingNode](documentation/nodes/embedding.md)**: Generates vector embeddings for text (requires Ollama).
277
- * **[MemoryNode](documentation/nodes/memory.md)**: Stores and retrieves text memories (keyword-based).
278
- * **[SemanticMemoryNode](documentation/nodes/semantic_memory.md)**: Stores and retrieves text memories via semantic search (requires Ollama).
279
- * **[TransformNode](documentation/nodes/transform.md)**: Transforms input data using a provided JavaScript function.
280
- * **[PDFProcessorNode](documentation/nodes/pdf_processor.md)**: Extracts text or images from PDF documents.
281
- * **[SpreadsheetNode](documentation/nodes/spreadsheet.md)**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
282
- * **[DataValidationNode](documentation/nodes/data_validation.md)**: Validates structured data against a JSON Schema.
283
-
284
- ### System
285
-
286
- * **[ShellCommandNode](documentation/nodes/shell_command.md)**: Executes shell commands.
287
- * **[ReadFileNode](documentation/nodes/read_file.md)**: Reads the content of a specified file.
288
- * **[WriteFileNode](documentation/nodes/write_file.md)**: Writes content to a specified file.
289
- * **[AppendFileNode](documentation/nodes/append_file.md)**: Appends content to an existing file.
290
- * **[ListDirectoryNode](documentation/nodes/list_directory.md)**: Lists the files and subdirectories within a specified directory.
291
- * **[SystemNotificationNode](documentation/nodes/system_notification.md)**: Displays a system-level notification across OSs.
292
- * **[DisplayImageNode](documentation/nodes/display_image.md)**: Displays an image file using the system's default image viewer.
293
- * **[HardwareInteractionNode](documentation/nodes/hardware_interaction.md)**: Communicates with local hardware via serial port (UART).
294
- * **[ImageGalleryNode](documentation/nodes/image_gallery.md)**: Generates an HTML gallery from multiple image files and opens it in a web browser.
295
- * **[SpeechSynthesisNode](documentation/nodes/speech_synthesis.md)**: Converts text to spoken audio using OS capabilities or cloud APIs.
296
- * **[MultimediaProcessingNode](documentation/nodes/multimedia_processing.md)**: Performs various multimedia operations on audio and video files using ffmpeg.
297
- * **[RemoteExecutionNode](documentation/nodes/remote_execution.md)**: Executes commands on remote machines via SSH.
298
-
299
- ### Web
300
-
301
- * **[HttpRequestNode](documentation/nodes/http_request.md)**: Makes a generic HTTP request to any URL.
302
- * **[WebScraperNode](documentation/nodes/web_scraper.md)**: Fetches the HTML content of a given URL.
303
- * **[DuckDuckGoSearchNode](documentation/nodes/duckduckgo_search.md)**: Performs a web search using DuckDuckGo.
304
- * **[GoogleSearchNode](documentation/nodes/google_search.md)**: Performs a web search using the Google Custom Search API.
305
- * **[BrowserControlNode](documentation/nodes/browser_control.md)**: Controls a Playwright browser to navigate pages, interact with elements, evaluate scripts, and take screenshots.
306
- * **[NavigatorNode](documentation/nodes/navigator.md)**: Controls PinchTab instances/tabs for advanced browser navigation, snapshots, actions, text extraction, media export, and tab safety features.
307
- * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
308
- * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
309
- * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
310
- * **[InteractiveWebviewNode](documentation/nodes/interactive_webview.md)**: Displays an interactive webview window for notifications, dialogs, or user input.
311
- * **[WebviewNode](documentation/nodes/webview.md)**: Displays a webview window with custom HTML content.
312
-
313
- ### Flow Control
314
-
315
- * **[SubFlowNode](documentation/nodes/sub_flow.md)**: Executes a sub-flow.
316
- * **[IteratorNode](documentation/nodes/iterator.md)**: Iterates items, executes sub-flow for each.
317
- * **[SchedulerNode](documentation/nodes/scheduler.md)**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
318
-
319
- ### Other
320
-
321
- * **[GitNode](documentation/nodes/git.md)**: Performs Git operations like clone, add, commit, and push.
322
- * **[GISNode](documentation/nodes/gis.md)**: Performs Geographic Information System operations like geocoding and reverse geocoding.
323
- * **[GitHubNode](documentation/nodes/github.md)**: Performs GitHub operations like creating and managing issues.
324
- * **[HackerNewsNode](documentation/nodes/hackernews.md)**: Fetches top stories and item details from Hacker News.
325
- * **[StripeNode](documentation/nodes/stripe.md)**: Performs Stripe operations like creating charges and retrieving account balances.
326
-
327
- ### LLMs
328
-
329
- * **[DeepSeekLLMNode](documentation/nodes/deepseek_llm.md)**: Interacts with the DeepSeek API.
330
- * **[OpenAILLMNode](documentation/nodes/openai_llm.md)**: Interacts with the OpenAI API.
331
- * **[GeminiLLMNode](documentation/nodes/gemini_llm.md)**: Interacts with the Google Gemini API.
332
- * **[OllamaLLMNode](documentation/nodes/ollama_llm.md)**: Interacts with a local Ollama instance.
333
- * **[HuggingFaceLLMNode](documentation/nodes/huggingface_llm.md)**: Interacts with the Hugging Face API.
334
- * **[OpenRouterLLMNode](documentation/nodes/openrouter_llm.md)**: Interacts with the OpenRouter API.
335
-
336
- ### Agent
337
-
338
- * **[AgentNode](documentation/nodes/agent.md)**: The core of agentic behavior in qflow. It orchestrates tools and LLM reasoning to achieve complex goals.
339
-
340
-
341
- ## Observability (Event System)
342
-
343
- `qflow` includes a built-in event system for `AsyncFlow` that provides detailed insights into the execution of your workflows. This allows for powerful, real-time monitoring, logging, and debugging.
344
-
345
- You can attach listeners to an `AsyncFlow` instance to subscribe to key lifecycle events.
346
-
347
- ### Available Events
348
-
349
- * `flow:start`: Emitted when the flow begins.
350
- * **Payload:** `{ flowId, startTime }`
351
- * `flow:end`: Emitted when the flow finishes, either successfully or with an error.
352
- * **Payload:** `{ flowId, endTime, duration, status, error }`
353
- * `node:start`: Emitted just before a node executes.
354
- * **Payload:** `{ flowId, nodeClass, startTime, params }`
355
- * `node:end`: Emitted right after a node finishes.
356
- * **Payload:** `{ flowId, nodeClass, endTime, duration, status, result, error }`
357
-
358
-
359
- This example demonstrates how to use the built-in event system to monitor the execution of a flow.
360
-
361
- ```javascript
362
- import { AsyncFlow, AsyncNode } from '@fractal-solutions/qflow';
363
-
364
- const colors = {
365
- reset: "\x1b[0m",
366
- cyan: "\x1b[36m",
367
- green: "\x1b[32m",
368
- red: "\x1b[31m",
369
- grey: "\x1b[90m"
370
- };
371
- function colorize(text, color) {
372
- return `${color}${text}${colors.reset}`;
373
- }
374
-
375
- // A simple node that simulates some work
376
- class WorkNode extends AsyncNode {
377
- async execAsync() {
378
- const workTime = Math.random() * 100 + 50; // 50-150ms
379
- await new Promise(resolve => setTimeout(resolve, workTime));
380
- return { status: 'work_done' };
381
- }
382
- }
383
-
384
- // A node that is designed to fail once before succeeding
385
- let failCount = 0;
386
- class SometimesFailsNode extends AsyncNode {
387
- constructor() {
388
- // Configure this node to allow 1 retry (for a total of 2 attempts)
389
- super(2, 0.1);
390
- }
391
- async execAsync() {
392
- if (failCount < 1) {
393
- failCount++;
394
- throw new Error('Simulating a transient error');
395
- }
396
- return { status: 'succeeded_after_failure' };
397
- }
398
- }
399
-
400
- // 1. Define the workflow
401
- const startNode = new WorkNode();
402
- const middleNode = new SometimesFailsNode();
403
- const endNode = new WorkNode();
404
-
405
- startNode.next(middleNode);
406
- middleNode.next(endNode);
407
-
408
- // 2. Create the flow
409
- const myFlow = new AsyncFlow(startNode);
410
-
411
- // 3. Attach listeners for observability
412
- myFlow.on('flow:start', (payload) => {
413
- const time = new Date(payload.startTime).toLocaleTimeString();
414
- console.log(`\n${colorize(`[FLOW:START]`, colors.cyan)} ${payload.flowId} at ${time}`);
415
- });
416
-
417
- myFlow.on('node:start', (payload) => {
418
- console.log(colorize(` [NODE:START] ${payload.nodeClass}`, colors.grey));
419
- });
420
-
421
- myFlow.on('node:end', (payload) => {
422
- const status = payload.status.toUpperCase();
423
- const color = payload.status === 'success' ? colors.green : colors.red;
424
- const statusStr = colorize(status.padEnd(7), color); // Pad for alignment
425
- const duration = `${payload.duration.toFixed(2)}ms`.padStart(10);
426
- console.log(` [NODE:END] ${payload.nodeClass.padEnd(18)} | Status: ${statusStr} | Duration: ${duration}`);
427
- if (payload.error) {
428
- console.log(colorize(` └─ ERROR: ${payload.error.message}`, colors.red));
429
- }
430
- });
431
-
432
- myFlow.on('flow:end', (payload) => {
433
- const status = payload.status.toUpperCase();
434
- const color = payload.status === 'success' ? colors.green : colors.red;
435
- const statusStr = colorize(status.padEnd(7), color);
436
- const duration = `${payload.duration.toFixed(2)}ms`;
437
- console.log(`\n${colorize(`[FLOW:END]`, colors.cyan)} ${payload.flowId} | Status: ${statusStr} | Duration: ${duration}`);
438
- if (payload.error) {
439
- console.log(colorize(` └─ FLOW ERROR: ${payload.error.message}`, colors.red));
440
- }
441
- });
442
-
443
- // 4. Run the flow
444
- await myFlow.runAsync({});
445
-
446
- // Expected output:
447
- //
448
- // [FLOW:START] <flow-id> at <time>
449
- // [NODE:START] WorkNode
450
- // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
451
- // [NODE:START] SometimesFailsNode
452
- // [NODE:END] SometimesFailsNode | Status: ERROR | Duration: X.XXms
453
- // └─ ERROR: Simulating a transient error
454
- // [NODE:START] SometimesFailsNode
455
- // [NODE:END] SometimesFailsNode | Status: SUCCESS | Duration: X.XXms
456
- // [NODE:START] WorkNode
457
- // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
458
- //
459
- // [FLOW:END] <flow-id> | Status: SUCCESS | Duration: XXX.XXms
460
- ```
461
-
462
-
463
-
464
-
465
-
466
- ## Logging
467
-
468
- `qflow` provides a simple yet powerful logging mechanism that gives you per-node control over how and where log messages are sent.
469
-
470
- ### Basic Usage
471
-
472
- By default, all built-in nodes will log to the console. You don't need to configure anything for this to work.
473
-
474
- ### Per-Node Logging Configuration
475
-
476
- To customize the logging for a specific node, you can pass a `logging` object in its parameters. This gives you fine-grained control over the logging behavior of each node in your flow.
477
-
478
- ```javascript
479
- import { HttpRequestNode } from '@fractal-solutions/qflow/nodes';
480
-
481
- const httpNode = new HttpRequestNode();
482
-
483
- // This node will log to the console by default
484
- httpNode.setParams({
485
- url: 'https://api.example.com/data'
486
- });
487
-
488
- // This node will log to a file
489
- const anotherHttpNode = new HttpRequestNode();
490
- anotherHttpNode.setParams({
491
- url: 'https://api.example.com/other-data',
492
- logging: {
493
- method: 'file',
494
- params: { filePath: './logs/http.log' }
495
- }
496
- });
497
- ```
498
-
499
- ### Logging Methods
500
-
501
- The following logging methods are available out of the box:
502
-
503
- * **`console` (default):** Logs messages to the console.
504
- * **`file`:** Appends log messages to a file.
505
- * **params:** `{ filePath: string }`
506
- * **`event`:** Emits log messages through an event emitter.
507
- * **params:** `{ emitter: EventEmitter }`
508
- * **`remote`:** Sends log messages to a remote server via a POST request.
509
- * **params:** `{ url: string }`
510
-
511
- ### Examples
512
-
513
- #### Logging to a File
514
-
515
- ```javascript
516
- import { CodeInterpreterNode } from '@fractal-solutions/qflow/nodes';
517
-
518
- const codeNode = new CodeInterpreterNode();
519
- codeNode.setParams({
520
- code: 'print("Hello from Python!")',
521
- logging: {
522
- method: 'file',
523
- params: { filePath: './logs/code-interpreter.log' }
524
- }
525
- });
526
- ```
527
-
528
- #### Logging to an Event Emitter
529
-
530
- This is useful for integrating `qflow`'s logging with your application's event system.
531
-
532
- ```javascript
533
- import { EventEmitter } from 'events';
534
- import { MemoryNode } from '@fractal-solutions/qflow/nodes';
535
-
536
- const myEmitter = new EventEmitter();
537
- myEmitter.on('log', (logEntry) => {
538
- console.log('Received log event:', logEntry);
539
- });
540
-
541
- const memoryNode = new MemoryNode();
542
- memoryNode.setParams({
543
- action: 'store',
544
- content: 'This is a test memory.',
545
- logging: {
546
- method: 'event',
547
- params: { emitter: myEmitter }
548
- }
549
- });
550
- ```
551
-
552
- #### Disabling Logging for a Node
553
-
554
- You can disable logging for a specific node by setting the `type` to `none`.
555
-
556
- ```javascript
557
- const silentHttpNode = new HttpRequestNode();
558
- silentHttpNode.setParams({
559
- url: 'https://api.example.com/silent',
560
- logging: {
561
- type: 'none'
562
- }
563
- });
564
- ```
565
-
566
- ### Global Log Level
567
-
568
- You can set a global log level to control the verbosity of all logs in your application. Only messages with a severity level equal to or higher than the current log level will be processed.
569
-
570
- ```javascript
571
- import { setLogLevel, LogLevel } from '@fractal-solutions/qflow/logger';
572
-
573
- // Set the global log level to INFO.
574
- // This will show INFO, WARN, and ERROR messages, but hide DEBUG messages.
575
- setLogLevel(LogLevel.INFO);
576
- ```
577
-
578
- The available log levels are, in order of severity:
579
-
580
- * `LogLevel.DEBUG`: Detailed information, useful for debugging.
581
- * `LogLevel.INFO`: General information about the application's state.
582
- * `LogLevel.WARN`: Indicates a potential problem that does not prevent the application from running.
583
- * `LogLevel.ERROR`: Indicates a serious error that prevented a specific operation from completing.
584
- * `LogLevel.NONE`: Disables all logging.
585
-
586
- ### Making Your Custom Nodes Loggable
587
-
588
- You can make your own custom nodes loggable by following the same pattern as the built-in nodes.
589
-
590
- 1. **Import the `log` function:**
591
- ```javascript
592
- import { log } from '@fractal-solutions/qflow/logger';
593
- ```
594
-
595
- 2. **Call the `log` function:** In your node's methods, call the `log` function and pass `this.params.logging` as the second argument. This will allow users of your node to configure its logging behavior.
596
-
597
- Here is an example of a custom node that implements loggable behavior:
598
-
599
- ```javascript
600
- import { AsyncNode } from '@fractal-solutions/qflow';
601
- import { log } from '@fractal-solutions/qflow/logger';
602
-
603
- class MyCustomNode extends AsyncNode {
604
- async execAsync() {
605
- log('Starting execution of MyCustomNode', this.params.logging);
606
- // ... your node's logic ...
607
-
608
- log('Finished execution of MyCustomNode', this.params.logging);
609
-
610
- return 'default';
611
- }
612
- }
613
-
614
- // --- User of your node can now configure logging ---
615
-
616
- const myNode = new MyCustomNode();
617
-
618
- // This will log to the console (default)
619
- myNode.setParams({ /* ... */ });
620
-
621
- // This will log to a file
622
- const anotherNode = new MyCustomNode();
623
- anotherNode.setParams({
624
- /* ... */,
625
- logging: {
626
- method: 'file',
627
- params: { filePath: './my-custom-node.log' }
628
- }
629
- });
630
- ```
631
-
632
-
633
- ## Agents
634
-
635
- For a detailed explanation of the agents, see the [Agents documentation](documentation/agents.md). The tools available to agents are documented in the [Tools documentation](documentation/integrated_nodes.md).
636
-
637
- ### Extending Agents with Custom Tools
638
-
639
- `qflow` agents can be extended with custom tools by defining your own Node classes and making them discoverable. This allows agents to leverage any custom logic or external integrations you build.
640
-
641
- #### 1. Creating a Custom Tool Node
642
-
643
- To create a custom node that can be used as a tool by an agent, your node class must:
644
- * Extend `AsyncNode`.
645
- * Implement a `static getToolDefinition()` method that returns a JSON Schema object describing the tool's name, description, and parameters.
646
-
647
- Here's an example of a simple custom node that an agent could use as a tool:
648
-
649
- ```javascript
650
- // my_nodes/MyCustomToolNode.js
651
- import { AsyncNode } from '@fractal-solutions/qflow';
652
-
653
- export class MyCustomToolNode extends AsyncNode {
654
- static getToolDefinition() {
655
- return {
656
- name: "my_custom_tool",
657
- description: "A custom tool that greets the user with a personalized message.",
658
- parameters: {
659
- type: "object",
660
- properties: {
661
- name: {
662
- type: "string",
663
- description: "The name of the person to greet."
664
- },
665
- greeting: {
666
- type: "string",
667
- description: "Optional. The greeting message. Defaults to 'Hello'."
668
- }
669
- },
670
- required: ["name"]
671
- }
672
- };
673
- }
674
-
675
- async execAsync() {
676
- const { name, greeting = 'Hello' } = this.params;
677
- const message = `${greeting}, ${name}! Welcome to your custom tool.`;
678
- console.log(message);
679
- return { message: message };
680
- }
681
-
682
- async postAsync(shared, prepRes, execRes) {
683
- shared.customToolOutput = execRes.message;
684
- return 'default';
685
- }
686
- }
687
- ```
688
-
689
- #### 2. Making Custom Tools Discoverable
690
-
691
- To make your custom tool nodes available to `qflow` agents, you need to specify their paths in a `qflow.config.js` file in your project's root directory.
692
-
693
- First, create a `qflow.config.js` file if you don't have one:
694
-
695
- ```javascript
696
- // qflow.config.js
697
- /**
698
- * @type {import('./src/types').QFlowConfig}
699
- */
700
- const qflowConfig = {
701
- customNodePaths: [
702
- './my_nodes/MyCustomToolNode.js', // Path to your custom node file
703
- // Add more paths for other custom nodes
704
- ],
705
- };
706
-
707
- export default qflowConfig;
708
- ```
709
-
710
- The `customNodePaths` array should contain paths to your custom node files, relative to your project's root directory. `qflow` will automatically load these files, discover any `AsyncNode` classes with a `static getToolDefinition()` method, and register them as available tools for your agents.
711
-
712
- Once configured, your agents will be able to "see" and utilize `my_custom_tool` just like any built-in tool, allowing for powerful and flexible agentic workflows tailored to your specific needs.
713
-
714
-
715
- ## Error Handling
716
-
717
-
718
- `qflow` provides mechanisms to handle errors gracefully within your workflows.
719
-
720
- * **Node-level Error Handling:**
721
- * Synchronous `Node`s: If an error occurs in `prep` or `exec`, it will be caught by the flow and propagate up. You can implement `execFallback(prepRes, error)` in your `Node` subclass to provide a fallback mechanism when `exec` fails after all retries.
722
- * Asynchronous `AsyncNode`s: Similarly, `prepAsync` or `execAsync` can throw errors. Implement `execFallbackAsync(prepRes, error)` for asynchronous fallbacks.
723
- * **Flow-level Error Handling:**
724
- * When you run a flow using `flow.run(sharedState)` or `await flow.runAsync(sharedState)`, any unhandled errors from within the nodes will propagate up and can be caught using standard JavaScript `try...catch` blocks around the `run` or `runAsync` call. This allows you to manage errors at the workflow level.
725
-
726
- ```javascript
727
- import { Node, Flow } from '@fractal-solutions/qflow';
728
-
729
- class FailingNode extends Node {
730
- exec() {
731
- throw new Error("Something went wrong in FailingNode!");
732
- }
733
- execFallback(prepRes, error) {
734
- console.error("FailingNode fallback triggered:", error.message);
735
- return "Fallback successful!";
736
- }
737
- }
738
-
739
- const failingNode = new FailingNode();
740
- const errorFlow = new Flow(failingNode);
741
-
742
- try {
743
- const result = errorFlow.run({});
744
- console.log("Flow completed with result:", result);
745
- } catch (error) {
746
- console.error("Flow failed with unhandled error:", error.message);
747
- }
748
- // Expected output:
749
- // FailingNode fallback triggered: Something went wrong in FailingNode!
750
- // Flow completed with result: Fallback successful!
751
- ```
752
-
753
- ## Debugging
754
-
755
- Debugging `qflow` workflows can be done using standard JavaScript debugging tools and techniques.
756
-
757
- * **`console.log`:** The simplest way to inspect data and execution flow. Strategically place `console.log` statements within `prep`, `exec`, `post`, and their `Async` counterparts to trace the `shared` object, `prepRes`, and `execRes` values.
758
- * **Debugger:** Use your IDE's built-in debugger (e.g., VS Code's debugger) or Node.js/Bun's inspector (`node --inspect` or `bun --inspect`). Set breakpoints within your node's lifecycle methods to step through the execution and examine the state.
759
- * **Error Messages:** Pay close attention to the error messages and stack traces. `qflow` aims to provide clear error messages that point to the source of the problem within your nodes.
760
-
761
- ## Testing
762
-
763
- Testing `qflow` workflows involves unit testing individual nodes and integration testing entire flows.
764
-
765
- * **Unit Testing Nodes:**
766
- * Test each `Node` or `AsyncNode` subclass in isolation.
767
- * Mock external dependencies (e.g., API calls for `LLMNode`, `GitHubNode`) to ensure tests are fast and reliable.
768
- * Verify the behavior of `prep`, `exec`, `post`, and their `Async` counterparts, as well as `setParams` and `execFallback`.
769
- * **Integration Testing Flows:**
770
- * Test entire `Flow`s or `AsyncFlow`s to ensure nodes are chained correctly and data flows as expected.
771
- * Provide controlled `shared` state inputs and assert on the final `shared` state or the flow's return value.
772
- * Use your preferred testing framework (e.g., Jest, Mocha, Bun's built-in test runner).
773
-
774
- ```javascript
775
- // Example (using Bun's test runner syntax)
776
- import { test, expect } from "bun:test";
777
- import { Node, Flow } from '@fractal-solutions/qflow';
778
-
779
- class TestNodeA extends Node {
780
- exec(input) { return input + 1; }
781
- }
782
-
783
- class TestNodeB extends Node {
784
- exec(input) { return input * 2; }
785
- }
786
-
787
- test("Simple Flow should process data correctly", () => {
788
- const nodeA = new TestNodeA();
789
- const nodeB = new TestNodeB();
790
- nodeA.next(nodeB);
791
-
792
- const flow = new Flow(nodeA);
793
- const sharedState = { initialValue: 5 };
794
- const result = flow.run(sharedState); // Assuming run returns the final execRes of the last node
795
-
796
- expect(result).toBe(12); // (5 + 1) * 2 = 12
797
- });
798
-
799
- test("Node should handle parameters via setParams", () => {
800
- class ParamNode extends Node {
801
- exec() { return this.params.value; }
802
- }
803
- const node = new ParamNode();
804
- node.setParams({ value: "hello" });
805
- const result = node.run({});
806
- expect(result).toBe("hello");
807
- });
808
- ```
809
-
810
- ## Integration
811
-
812
- `qflow` is designed to be highly flexible and can be integrated into various application architectures:
813
-
814
- * **CLI Tools:** Build powerful command-line tools that automate complex tasks.
815
- * **Web Servers (e.g., Express.js, Koa):** Implement API endpoints that trigger workflows for data processing, background jobs, or agent-driven responses.
816
- * **Background Services:** Run long-running processes or scheduled tasks.
817
- * **Browser Applications:** Create interactive, client-side workflows (ensure appropriate polyfills for `SharedArrayBuffer` if using synchronous `wait` in `Node`).
818
-
819
- ## Contributing
820
-
821
- We welcome contributions! Please see our GitHub repository for more details on how to contribute.
822
-
823
-
1
+ # qflow: A Lightweight and Flexible JavaScript Workflow and Agent Library
2
+
3
+ `qflow` is a lightweight and flexible JavaScript library designed for creating and managing complex workflows and autonomous agents. It provides a minimalist yet expressive API to define sequences of operations, manage data flow, and orchestrate execution, supporting both synchronous and asynchronous patterns.
4
+
5
+ ## Features
6
+
7
+ * **Modular & Extensible:** Easily define custom nodes and compose them into complex, reusable flows.
8
+ * **Synchronous & Asynchronous Flows:** Supports both blocking and non-blocking execution models.
9
+ * **Observability:** Monitor workflows with a built-in event system that emits detailed lifecycle events for flows and nodes, including custom and streaming events.
10
+ * **Shared State Management:** Pass and manipulate data across nodes using a central, mutable `shared` object.
11
+ * **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows, including parallel execution.
12
+ * **Agents:** Built upon the `qflow` core functionality are plug and play agents with extensive tool integrations available.
13
+ * **Built-in Integrations:** Comes with pre-built nodes for multiple tasks like LLM interactions, browser use, pdf tools, webhooks, spreadsheet manipulation, code interpretation, media manipulation, web scraping, and popular API integrations (GitHub, Git, Open Router, HackerNews, Stripe, Maps).
14
+ * **Custom Agent Tools:** Build your own Agent tools using the flow registry pattern.
15
+ * **MCP Bridge:** Expose qflow nodes as MCP tools over stdio, or call external MCP servers from an agent.
16
+ * **Streaming LLM Output:** Surface token deltas as flow events with OpenAI-compatible providers.
17
+ * **Durable Execution:** Checkpoint flow state to `bun:sqlite` and resume runs after a crash.
18
+ * **Graph Guards:** Fan-out/fan-in nodes, error edges, loop limits and flow-level timeouts.
19
+ * **Trace Viewer:** Export flow/durable-run traces as JSON and inspect them at `#trace` on the docs site.
20
+ * **Opt-in Integrations:** Heavy packages load only when the node action that needs them runs.
21
+ * **Provider-Neutral LLM:** One `LLMNode` with adapters for OpenAI-compatible APIs, Anthropic, Ollama and Gemini, plus capability negotiation, retries, fallbacks and usage/cost events.
22
+ * **Portable Tool Specs:** `ToolSpec` / `ToolRegistry` power agents, MCP export and docs from one definition, with permissions, namespaces, dry-run, timeouts and idempotency.
23
+ * **Replay-Safe Side Effects:** Durable operations reserve an ID before running, replay completed results, and refuse to re-run uncertain effects.
24
+ * **Agent-Native Nodes:** Plan, critique, reflect, finish and human approval as composable, checkpointable graph nodes; `AgentEngine.asFlow()` exposes strategies as inspectable flows.
25
+ * **Dataflow & Contracts:** Map/reduce/join/branch/cycle nodes with typed shared-state schemas and explicit iteration budgets.
26
+ * **Eval & Replay:** Assert, score, compare and replay nodes turn saved traces into regression suites.
27
+ * **Bun-Native Nodes:** Process spawning, SQLite queries, file watching and Web Stream transforms without optional native packages.
28
+ * **Durable Human Approval:** Suspend a run on a decision stored in SQLite, review it in any UI, and resume days later without losing context.
29
+ * **Durable Scheduling:** Suspend until a date, delay or cron slot; a worker resumes due runs without holding an in-process timer.
30
+ * **Deterministic LLM Replay:** Cache normalized completions across workers and restarts, with readable keys and a visible `llm:cache_hit` event.
31
+ * **Budget Guardrails:** Track cost, tokens, duration and steps, then route to a fallback or throw a coded error when a limit is crossed.
32
+ * **Flow Versioning & Worker Leases:** Resume old runs with an explicit migration policy; stop two workers from executing the same side effect.
33
+ * **Unified Memory:** One `MemoryStore` interface with in-memory and SQLite implementations, wrapped by a single `MemoryStoreNode`.
34
+
35
+ ## What qflow 2.0 is good for
36
+
37
+ | Application | Why the 2.0 node set fits | Start here |
38
+ | --- | --- | --- |
39
+ | **Tool-using research and copilot agents** | One `LLMNode` switches providers without rewriting flows; `ToolSpec` gives tools permissions, timeouts and idempotency; strategies become inspectable flows with `asFlow()`. | [Unified tool contract example](examples/v2/unified-tool-contract.js) · [Agent flows tutorial](documentation/tutorials/agent-flows.md) |
40
+ | **Durable transactional workflows** (checkout, refunds, onboarding) | `DurableFlow` checkpoints every node; replay-safe side effects reserve an operation ID and replay completed results instead of charging twice. | [Replay-safe checkout](examples/v2/replay-safe-checkout.js) · [Side effects tutorial](documentation/tutorials/durable-side-effects.md) |
41
+ | **MCP tool servers and agent interoperability** | `ToolRegistry` exposes the same definitions to agents, MCP `tools/list`, LLM tool schemas and generated docs; `MCPClientNode` calls external servers from a flow. | [MCP tutorial](documentation/tutorials/mcp.md) |
42
+ | **Data and LLM pipelines** (ETL, enrichment, batch scoring) | `MapNode` / `ReduceNode` / `JoinNode` / `BranchNode` / `CycleNode` add explicit routing and budgets; `StateContract` validates state at node boundaries; Bun stream nodes compose without optional packages. | [Dataflow regression example](examples/v2/dataflow-eval-regression.js) · [Bun ingest example](examples/v2/bun-stream-ingest.js) |
43
+ | **Eval-driven LLM products** | Normalized traces are the contract between runtime and tests: replay a saved trace against a new flow, diff spans and payloads, then gate releases with assert/score nodes. | [Trace replay tutorial](documentation/tutorials/trace-driven-eval.md) |
44
+ | **Local automation and scripting** | `BunSpawnNode`, `FileWatchNode`, `SQLiteQueryNode` and Web Stream transforms handle process, file and data work with Bun primitives only. | [Bun ingest example](examples/v2/bun-stream-ingest.js) |
45
+ | **Visual workflow authoring** | `describeGraph()` and `strategyGraph()` emit JSON nodes/edges, while contracts declare what each boundary expects. | [Dataflow regression example](examples/v2/dataflow-eval-regression.js) |
46
+ | **Human-in-the-loop operations** (refunds, overrides, deploys) | `WaitForApprovalNode` suspends a durable run with `status: 'suspended'`; decisions live in SQLite and can be recorded from any UI. | [Approval tutorial](documentation/tutorials/durable-approval.md) |
47
+ | **Time-based workflows** (reminders, retries, nightly jobs) | `ScheduleNode` persists a due time, so a worker can resume due runs after any restart. Cron parsing needs no optional package. | [Scheduling tutorial](documentation/tutorials/durable-scheduling.md) |
48
+ | **Cost-controlled agents** | `BudgetTracker` accumulates real usage; `BudgetNode` routes to `continue` / `exceeded` and `LLMNode` can hard-stop with `QFLOW_BUDGET_EXCEEDED`. | [Budget tutorial](documentation/tutorials/budget-guardrails.md) |
49
+ | **Multi-tenant assistants** | A `MemoryStore` per tenant plus `MemoryStoreNode` keeps recall isolated while flow code stays identical. | [Memory tutorial](documentation/tutorials/multi-tenant-memory.md) |
50
+
51
+ The earlier production gaps — long-lived approvals, deterministic LLM replay,
52
+ distributed side effects and multi-tenant memory/scheduling — are closed in
53
+ `2.0.0`. See [Production gaps closed](#production-gaps-closed-200)
54
+ for the 1-2-3 paths, or [MIGRATION.md § 9-15](MIGRATION.md) for every option and
55
+ error code.
56
+
57
+ ### 2.0 in three steps
58
+
59
+ Every durable feature follows the same rhythm. Learn it once and the rest of
60
+ the API is predictable:
61
+
62
+ 1. **Create the state owner.** A `SQLiteCheckpointer('./runs.db')` owns runs,
63
+ checkpoints, approvals, schedules, leases and the LLM cache. One file per
64
+ application; share it across workers.
65
+ 2. **Run with a caller-owned `runId` and read `status`.**
66
+ `await flow.runDurable({ runId, shared })` returns `completed`, `suspended`
67
+ (approval), `scheduled` (time) or throws a coded error. Never assume a call
68
+ finishes just because the process stayed up.
69
+ 3. **Act on the state, then resume the same run.**
70
+ Record a decision, wait for a due time, or release a stale lease, then call
71
+ `runDurable({ runId, resume: true })`. The waiting node re-enters and reads
72
+ what you recorded.
73
+
74
+ ```javascript
75
+ import { DurableFlow, SQLiteCheckpointer } from '@fractal-solutions/qflow/durable';
76
+
77
+ const checkpointer = new SQLiteCheckpointer('./runs.db', {
78
+ workerId: 'worker-1', // unique per worker: protects side effects with a lease
79
+ leaseMs: 60_000,
80
+ });
81
+ const flow = new DurableFlow(startNode, { checkpointer, name: 'checkout', version: '1.0.0' });
82
+
83
+ const outcome = await flow.runDurable({ runId: 'order-1', shared: { orderId: 'ord-1' } });
84
+ if (outcome.status === 'suspended' || outcome.status === 'scheduled') {
85
+ // Decide or wait, using checkpointer.listApprovals() / listScheduledRuns().
86
+ }
87
+ await flow.runDurable({ runId: 'order-1', resume: true });
88
+ ```
89
+
90
+ **Why a `runId` you control?** Because the id is the join key between your
91
+ system (order, request, invoice) and every checkpoint, decision, reservation and
92
+ trace. A generated id is fine for one-off runs; a business id is what makes
93
+ recovery possible.
94
+
95
+ ## Installation
96
+
97
+ To get started quickly with a new project, you can use the `create-qflow` tool (Recommended):
98
+
99
+ ```bash
100
+ bunx create-qflow@latest <project-name>
101
+ ```
102
+
103
+ or install the package with Bun:
104
+
105
+ ```bash
106
+ bun add @fractal-solutions/qflow
107
+ ```
108
+
109
+ qflow 2.0 is **Bun-only**. Node.js is not a supported runtime.
110
+
111
+ ### Install 2.0
112
+
113
+ `2.0.0` is now the `latest` release, so the normal install command gets it:
114
+
115
+ ```bash
116
+ bun add @fractal-solutions/qflow
117
+ # or pin the exact release
118
+ bun add @fractal-solutions/qflow@2.0.0
119
+ ```
120
+
121
+ The `canary` dist-tag still points to `2.0.0-canary.4` for prerelease trackers.
122
+ Read [MIGRATION.md](MIGRATION.md) before upgrading — 2.0 is a breaking release.
123
+
124
+ ## Module Imports
125
+
126
+ `qflow` provides different entry points for its core functionalities and built-in nodes to keep your imports clean and specific.
127
+
128
+ * **Core Classes (`Node`, `Flow`, `AsyncNode`, `AsyncFlow`, etc.):**
129
+ These are imported directly from the main package:
130
+ ```javascript
131
+ import { Node, Flow, AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
132
+ ```
133
+
134
+ * **Built-in Integration Nodes (`LLMNode`, `DeepSeekLLMNode`, `GitHubNode`, `WebScraperNode`, etc.):**
135
+ These are imported from the `/nodes` subpath:
136
+ ```javascript
137
+ import { DeepSeekLLMNode, GitHubNode, WebScraperNode } from '@fractal-solutions/qflow/nodes';
138
+ ```
139
+
140
+ * **Agents:** Agent classes and strategies are imported from `/agent`:
141
+ ```javascript
142
+ import { AgentNode, RAORAgent, listStrategies } from '@fractal-solutions/qflow/agent';
143
+ ```
144
+
145
+ * **MCP, streaming, durability, testing and tooling:**
146
+ ```javascript
147
+ import { QFlowMCPServer, MCPClientNode } from '@fractal-solutions/qflow/mcp';
148
+ import { streamChatCompletions } from '@fractal-solutions/qflow/streaming';
149
+ import { DurableFlow, SQLiteCheckpointer, createRunTrace } from '@fractal-solutions/qflow/durable';
150
+ import { MockNode, recordFlow } from '@fractal-solutions/qflow/testing';
151
+ import { FanOutNode, FanInNode } from '@fractal-solutions/qflow/graph';
152
+ import { normalizeTrace, writeTraceFile } from '@fractal-solutions/qflow/trace';
153
+ import { OPTIONAL_DEPENDENCIES, loadOptional } from '@fractal-solutions/qflow/optional';
154
+ import { setLogLevel, LogLevel } from '@fractal-solutions/qflow/logger';
155
+
156
+ // 2.0 node families
157
+ import { LLMNode, registerLLMAdapter, listLLMAdapters } from '@fractal-solutions/qflow/llm';
158
+ import { ToolSpec, ToolRegistry, generateToolDocs } from '@fractal-solutions/qflow/tool-spec';
159
+ import { StateContract, defineState } from '@fractal-solutions/qflow/contracts';
160
+ import { ReplaySafeNode, SideEffectUncertainError } from '@fractal-solutions/qflow/side-effects';
161
+ import { AssertNode, ScoreNode, CompareNode, ReplayNode } from '@fractal-solutions/qflow/eval';
162
+ import { BunSpawnNode, SQLiteQueryNode, FileWatchNode } from '@fractal-solutions/qflow/bun';
163
+
164
+ // Production-gap closures (canary.4), also re-exported from /nodes
165
+ import { WaitForApprovalNode } from '@fractal-solutions/qflow/approval';
166
+ import { ScheduleNode, nextCronTime } from '@fractal-solutions/qflow/schedule';
167
+ import { BudgetNode, BudgetTracker, BudgetExceededError } from '@fractal-solutions/qflow/budget';
168
+ import { MemoryStoreNode, InMemoryMemoryStore, SQLiteMemoryStore } from '@fractal-solutions/qflow/memory';
169
+
170
+ // /durable is the single entry point for long-lived run control
171
+ import {
172
+ DurableFlow, WaitForApprovalNode, ScheduleNode, BudgetNode,
173
+ FlowVersionMismatchError, SideEffectClaimedError,
174
+ } from '@fractal-solutions/qflow/durable';
175
+ ```
176
+
177
+ See [MIGRATION.md](./MIGRATION.md) when upgrading from 1.x, and [CHANGELOG.md](./CHANGELOG.md) for release notes.
178
+
179
+ ## Core Abstractions
180
+
181
+ `qflow` is built around a few core abstractions that enable powerful and flexible workflow definitions.
182
+
183
+ ### Shared State (`shared` object)
184
+
185
+ A central, mutable JavaScript object that is passed through the entire flow. Nodes can read from and write to this `shared` object, making it the primary mechanism for passing data and context between different nodes in a workflow. This is particularly useful for accumulating results or maintaining state across multiple steps.
186
+
187
+ ### Node
188
+
189
+ The fundamental building block of any `qflow` workflow. A `Node` represents a single, atomic operation or step in your flow.
190
+
191
+ * `prep(shared)`: Prepares data for execution. Receives the `shared` object.
192
+ * `exec(prepRes)`: Executes the node's primary logic.
193
+ * `post(shared, prepRes, execRes)`: Processes the result of `exec`. Receives the `shared` object.
194
+ * `setParams(params)`: Configures the node with specific parameters. Parameters are accessible via `this.params`.
195
+ * `next(node, action = "default")`: Chains this node to another, defining the next step in the flow.
196
+
197
+ **Asynchronous Nodes (`AsyncNode`, `AsyncBatchNode`, `AsyncParallelBatchNode`)**
198
+ For operations that involve I/O or are inherently asynchronous, `qflow` provides `AsyncNode` and its variants. These nodes leverage `async`/`await` for non-blocking execution. When working within `AsyncFlow`s, it's crucial to implement the `async` versions of the lifecycle methods:
199
+ * `prepAsync(shared, observer)`
200
+ * `execAsync(prepRes, shared, observer)`
201
+ * `postAsync(shared, prepRes, execRes, observer)`
202
+
203
+ The `observer` is optional and can be used to emit custom flow events with `observer.emit(name, payload)`.
204
+ * `preparePrompt(shared)` (specifically for LLM nodes, allowing prompt construction based on `shared` state)
205
+
206
+ These `async` methods ensure proper awaiting and data propagation within asynchronous workflows.
207
+
208
+ ### Flow
209
+
210
+ A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
211
+
212
+ * `start(startNode)`: Sets the initial node for the flow. (Note: In practice, you often pass the start node directly to the `Flow` constructor for conciseness).
213
+ * `_orch(shared, params)` / `_orchAsync(shared, params)`: Internal methods used to run the flow, especially when passing initial parameters to the starting node. For most use cases, `flow.run(sharedState)` or `await flow.runAsync(sharedState)` is sufficient.
214
+
215
+ **Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
216
+ These specialized flows are designed to process collections of items. They run a sub-flow for each item in the batch. `AsyncParallelBatchFlow` is particularly useful for concurrently processing batch items, significantly speeding up operations.
217
+
218
+
219
+ ## Basic Usage & Examples
220
+
221
+ ### 1. Simple Node
222
+
223
+ A basic example of defining and running a single node.
224
+
225
+ ```javascript
226
+ import { Node } from '@fractal-solutions/qflow';
227
+
228
+ class MySimpleNode extends Node {
229
+ prep(shared) {
230
+ console.log('Preparing data...');
231
+ return shared.inputData * 2;
232
+ }
233
+
234
+ exec(prepRes) {
235
+ console.log('Executing with prepared data:', prepRes);
236
+ return prepRes + 10;
237
+ }
238
+
239
+ post(shared, prepRes, execRes) {
240
+ console.log('Post-processing result:', execRes);
241
+ return { finalResult: execRes, originalInput: shared.inputData };
242
+ }
243
+ }
244
+
245
+ const node = new MySimpleNode();
246
+ const result = node.run({ inputData: 5 });
247
+ console.log('Node run result:', result);
248
+ // Expected output:
249
+ // Preparing data...
250
+ // Executing with prepared data: 10
251
+ // Post-processing result: 20
252
+ // Node run result: { finalResult: 20, originalInput: 5 }
253
+ ```
254
+
255
+ ### 2. Simple Flow
256
+
257
+ Chaining multiple nodes together to form a basic workflow.
258
+
259
+ ```javascript
260
+ import { Node, Flow } from '@fractal-solutions/qflow';
261
+
262
+ let count = 0;
263
+
264
+ class MessageNode extends Node {
265
+ exec() {
266
+ count++;
267
+ console.log(`New Message ${count}`);
268
+ return `default`;
269
+ }
270
+ }
271
+
272
+ class TimeNode extends Node {
273
+ exec() {
274
+ console.log(`Time ${Date.now()}`);
275
+ return `default`;
276
+ }
277
+ }
278
+
279
+ const m1 = new MessageNode();
280
+ const t1 = new TimeNode();
281
+ const m2 = new MessageNode();
282
+
283
+ m1.next(t1);
284
+ t1.next(m2);
285
+
286
+ const flow = new Flow(m1);
287
+ flow.run({});
288
+ // Expected output (approximate):
289
+ // New Message 1
290
+ // Time <timestamp>
291
+ // New Message 2
292
+ ```
293
+
294
+ ### 3. Conditional Flow
295
+
296
+ Using `transition()` for dynamic branching based on an action. This example demonstrates configuring a node using `setParams` for a cleaner API.
297
+
298
+ ```javascript
299
+ import { Node, Flow } from '@fractal-solutions/qflow';
300
+
301
+ class ConditionalNode extends Node {
302
+ exec() {
303
+ // Access shouldGoLeft from this.params, which is set via setParams
304
+ if (this.params.shouldGoLeft) {
305
+ console.log('ConditionalNode: Going left');
306
+ return 'left';
307
+ } else {
308
+ console.log('ConditionalNode: Going right');
309
+ return 'right';
310
+ }
311
+ }
312
+ }
313
+
314
+ // Helper node for conditional transition test
315
+ function MessageNode(message) {
316
+ return new (class extends Node {
317
+ exec() {
318
+ console.log(message);
319
+ return 'default';
320
+ }
321
+ })();
322
+ }
323
+
324
+ const conditionalNode = new ConditionalNode();
325
+ conditionalNode.setParams({ shouldGoLeft: true }); // Configure via setParams
326
+
327
+ const leftNode = MessageNode('Went Left');
328
+ const rightNode = MessageNode('Went Right');
329
+
330
+ conditionalNode.next(leftNode, 'left');
331
+ conditionalNode.next(rightNode, 'right');
332
+
333
+ const conditionalFlow = new Flow(conditionalNode);
334
+ conditionalFlow.run({});
335
+ // Expected output:
336
+ // ConditionalNode: Going left
337
+ // Went Left
338
+
339
+ const conditionalNode2 = new ConditionalNode();
340
+ conditionalNode2.setParams({ shouldGoLeft: false }); // Configure via setParams
341
+
342
+ conditionalNode2.next(leftNode, 'left');
343
+ conditionalNode2.next(rightNode, 'right');
344
+ const conditionalFlow2 = new Flow(conditionalNode2);
345
+ conditionalFlow2.run({});
346
+ // Expected output:
347
+ // ConditionalNode: Going right
348
+ // Went Right
349
+ ```
350
+
351
+ ### 4. Asynchronous Flow
352
+
353
+ Handling asynchronous operations within a flow.
354
+
355
+ ```javascript
356
+ import { AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
357
+
358
+ class MyAsyncNode extends AsyncNode {
359
+ async execAsync() {
360
+ console.log('AsyncNode: Starting...');
361
+ await new Promise(resolve => setTimeout(resolve, 100));
362
+ console.log('AsyncNode: Finished!');
363
+ return 'default';
364
+ }
365
+ }
366
+
367
+ const asyncNode1 = new MyAsyncNode();
368
+ const asyncNode2 = new MyAsyncNode();
369
+ asyncNode1.next(asyncNode2);
370
+
371
+ const asyncFlow = new AsyncFlow(asyncNode1);
372
+ await asyncFlow.runAsync({});
373
+ // Expected output:
374
+ // AsyncNode: Starting...
375
+ // AsyncNode: Finished!
376
+ // AsyncNode: Starting...
377
+ // AsyncNode: Finished!
378
+ ```
379
+
380
+ See [documentation/examples.md](documentation/examples.md) for a full list of examples.
381
+
382
+ ## Advanced Examples
383
+
384
+ ### Interactive Webview Form with Validation
385
+
386
+ This example demonstrates how to create a persistent interactive webview for a multi-field form, perform data validation using `DataValidationNode`, and provide dynamic feedback to the user within the webview. It requires the optional `webview-bun`, `ajv`, and `ajv-formats` packages.
387
+
388
+ See [examples/advanced_interactive_webview_form.js](examples/advanced_interactive_webview_form.js) for the full example.
389
+
390
+ ### Webview Data Visualization
391
+
392
+ This example demonstrates how to generate data within a qflow, create dynamic HTML content with embedded JavaScript (using Chart.js) for data visualization, and display this visualization in a `WebviewNode`.
393
+
394
+ See [examples/webview_data_visualization.js](examples/webview_data_visualization.js) for the full example.
395
+
396
+
397
+
398
+ ## 2.0 Node Families
399
+
400
+ These families shipped in `2.0.0-canary.3`; the production-gap closures below
401
+ arrived in `2.0.0-canary.4`. All of them are additive: the older
402
+ vendor-specific nodes and agent classes keep working.
403
+
404
+ ### Provider-neutral LLM
405
+
406
+ `LLMNode` replaces a separate class per vendor. Adapters cover `openai` (plus DeepSeek, OpenRouter, Hugging Face, Groq, Together and any OpenAI-compatible endpoint), `anthropic`, `ollama` and `gemini`. Register your own with `registerLLMAdapter()`.
407
+
408
+ ```javascript
409
+ import { AsyncFlow } from '@fractal-solutions/qflow';
410
+ import { LLMNode } from '@fractal-solutions/qflow/llm';
411
+
412
+ const flow = new AsyncFlow(new LLMNode({
413
+ provider: 'openai',
414
+ model: 'gpt-4o-mini',
415
+ apiKey: Bun.env.OPENAI_API_KEY,
416
+ pricing: { inputPerMillion: 0.15, outputPerMillion: 0.6 },
417
+ }));
418
+ flow.on('llm:delta', ({ delta }) => process.stdout.write(delta));
419
+
420
+ const result = await flow.runAsync({ prompt: 'Summarize this release.' });
421
+ // result: { text, reasoning, toolCalls, usage: { prompt, completion, total, cost }, ... }
422
+ ```
423
+
424
+ Capabilities are negotiated before a call: requesting `toolCalls` from an adapter that does not support it emits `llm:capability` and fails without hitting the API. Failures emit `llm:retry`, then `llm:fallback` when `fallbackProviders` is set. Events: `llm:delta`, `llm:reasoning`, `llm:done`, `llm:retry`, `llm:fallback`, `llm:negotiated`, `llm:capability`, `llm:usage`, `llm:tool_call`.
425
+
426
+ ### Tool specs and registries
427
+
428
+ `ToolSpec` turns `getToolDefinition()` into a portable definition for agents, MCP clients and generated docs. `ToolRegistry` adds namespaces, capability/permission grants, dry-run, timeouts and idempotency caching.
429
+
430
+ ```javascript
431
+ import { ToolSpec, ToolRegistry, generateToolDocs } from '@fractal-solutions/qflow/tool-spec';
432
+ import { QFlowMCPServer } from '@fractal-solutions/qflow/mcp';
433
+
434
+ const spec = new ToolSpec({
435
+ name: 'echo',
436
+ description: 'Echo a value.',
437
+ parameters: { type: 'object', properties: { value: { type: 'string' } }, required: ['value'] },
438
+ capabilities: ['read'],
439
+ permissions: ['public'],
440
+ idempotencyKey: '{{value}}',
441
+ execute: async ({ value }) => value,
442
+ });
443
+ const registry = new ToolRegistry({ tools: [spec], grantedCapabilities: ['read'] });
444
+ await registry.execute('echo', { value: 'hello' }); // { tool, result, args }
445
+ registry.llmTools(); // OpenAI tool definitions
446
+ new QFlowMCPServer({ toolRegistry: registry }); // tools/list + tools/call
447
+ generateToolDocs(registry); // Markdown
448
+ ```
449
+
450
+ `toolSpecFromNode(NodeClass)` derives the same spec from an existing node. Agents accept a registry with `new AgentNode({ llmNode, toolRegistry, grantedCapabilities, grantedPermissions })`.
451
+
452
+ ### Replay-safe side effects
453
+
454
+ Pass an `operationId` to make an external effect safe across durable replay. The checkpointer reserves the operation before execution; completed effects return their recorded result, while a reserved-but-unfinished effect raises `SideEffectUncertainError` (`QFLOW_SIDE_EFFECT_UNCERTAIN`) instead of running twice.
455
+
456
+ ```javascript
457
+ import { DurableFlow, SQLiteCheckpointer } from '@fractal-solutions/qflow/durable';
458
+ import { ReplaySafeNode } from '@fractal-solutions/qflow/side-effects';
459
+
460
+ const charge = new ReplaySafeNode({
461
+ operationId: '{{orderId}}',
462
+ kind: 'charge',
463
+ execute: async ({ input }) => paymentApi.charge(input),
464
+ });
465
+ const checkpointer = new SQLiteCheckpointer('./runs.db');
466
+ const flow = new DurableFlow(charge, { checkpointer });
467
+ const runId = 'order-charge-1';
468
+
469
+ await flow.runDurable({ runId, shared: { orderId: 'ord-1', input: { amount: 42 } } });
470
+ await flow.runDurable({ runId, resume: true }); // no second charge
471
+ ```
472
+
473
+ `HttpRequestNode`, `GitNode`, `WebHookNode` and `DatabaseNode` also accept `operationId` (with `{{template}}` placeholders). Events: `side_effect:replay`, `side_effect:committed`.
474
+
475
+ ### Dataflow and shared-state contracts
476
+
477
+ `MapNode`, `ReduceNode`, `JoinNode`, `BranchNode` and `CycleNode` add explicit dataflow routing. `StateContract` validates `shared` at node boundaries, and `describeGraph(flow.startNode)` returns JSON nodes/edges for visual authoring.
478
+
479
+ ```javascript
480
+ import { AsyncFlow } from '@fractal-solutions/qflow';
481
+ import { defineState } from '@fractal-solutions/qflow/contracts';
482
+ import { MapNode, ReduceNode } from '@fractal-solutions/qflow/graph';
483
+
484
+ const contract = defineState({
485
+ fields: { items: { type: 'array', required: true } },
486
+ strict: true,
487
+ });
488
+ const map = new MapNode({ mapper: value => value * 2, inputContract: contract });
489
+ const reduce = new ReduceNode({ reducer: (sum, value) => sum + value, initialValue: 0 });
490
+ map.next(reduce);
491
+ await new AsyncFlow(map).runAsync({ items: [1, 2, 3] }); // shared.reduceResult === 12
492
+ ```
493
+
494
+ `CycleNode` enforces `maxIterations` / `maxItems` budgets; events include `cycle:iteration`, `map:item_error` and `reduce:step`.
495
+
496
+ ### Agent-native control nodes
497
+
498
+ `PlanNode`, `CriticNode`, `ReflectNode`, `FinishNode` and `HumanApprovalNode` are first-class nodes from `/agent`. `AgentEngine.asFlow()` turns any declarative strategy into a runnable, inspectable `AsyncFlow`; each phase becomes its own checkpointable node.
499
+
500
+ ```javascript
501
+ import { AgentNode, PlanNode, CriticNode } from '@fractal-solutions/qflow/agent';
502
+
503
+ const plan = new PlanNode({ llmNode });
504
+ const critic = new CriticNode({ llmNode });
505
+ plan.next(critic, 'default');
506
+ // critic.next(approvedNode, 'approve').next(reviseNode, 'reject')
507
+
508
+ const flow = new AgentNode({ llmNode, availableTools, strategy: 'raor' }).asFlow();
509
+ flow.graph; // { nodes, edges } suitable for a visual editor
510
+ ```
511
+
512
+ ### Evaluation and trace replay
513
+
514
+ `AssertNode`, `ScoreNode`, `CompareNode` and `ReplayNode` turn saved traces into regression suites. Volatile fields (IDs, timings, stack traces) are ignored when diffing.
515
+
516
+ ```javascript
517
+ import { AssertNode, ScoreNode, createEvalSuite } from '@fractal-solutions/qflow/eval';
518
+
519
+ const suite = createEvalSuite(flow, [{ name: 'happy path', shared: { input: 'hello' } }]);
520
+ const results = await suite.run();
521
+ ```
522
+
523
+ `ReplayNode` accepts a trace (or `tracePath`), reruns a `flowFactory`, and diffs events/spans/status; events include `eval:assert`, `eval:score`, `eval:compare` and `eval:replay`.
524
+
525
+ ### Bun-native nodes
526
+
527
+ Small, composable nodes built on Bun primitives with no optional native dependencies: `BunSpawnNode`, `SQLiteQueryNode`, `FileWatchNode`, `StreamTransformNode`, `StreamMapNode`, `StreamFilterNode` and `StreamReduceNode`.
528
+
529
+ ```javascript
530
+ import { AsyncFlow } from '@fractal-solutions/qflow';
531
+ import { BunSpawnNode, SQLiteQueryNode, StreamMapNode } from '@fractal-solutions/qflow/bun';
532
+
533
+ const spawn = new BunSpawnNode();
534
+ spawn.setParams({ command: 'bun', args: ['--version'] });
535
+ await new AsyncFlow(spawn).runAsync({}); // shared.spawnStdout
536
+
537
+ const query = new SQLiteQueryNode();
538
+ query.setParams({ database: ':memory:', sql: 'SELECT 1 AS ok', mode: 'all' });
539
+ await new AsyncFlow(query).runAsync({}); // shared.sqliteResult
540
+
541
+ const stream = new StreamMapNode({ transform: value => value * 2 });
542
+ await new AsyncFlow(stream).runAsync({ streamInput: [1, 2, 3] }); // shared.streamResult
543
+ ```
544
+
545
+ Events include `spawn:exit`, `file:change` and `stream:item`.
546
+
547
+ ## Production gaps closed (2.0.0)
548
+
549
+ The canary.3 families gave qflow breadth. Stable 2.0 closes the six gaps that
550
+ prevented those features from running unattended in production. Each subsection
551
+ answers three questions: **why it exists**, **the 1-2-3 steps**, and **which
552
+ options matter**. Full tables and failure modes live in
553
+ [MIGRATION.md](MIGRATION.md) and the linked tutorials.
554
+
555
+ | Gap | What closes it | Why it matters | Deep dive |
556
+ | --- | --- | --- | --- |
557
+ | Long-lived human decisions | `WaitForApprovalNode`, `approve()` / `reject()` | A review can take days and outlive the worker | [Approval tutorial](documentation/tutorials/durable-approval.md) |
558
+ | Time-based suspension | `ScheduleNode`, `listScheduledRuns()` | Reminders must survive restarts | [Scheduling tutorial](documentation/tutorials/durable-scheduling.md) |
559
+ | Non-deterministic model calls | `LLMNode` cache + `llm:cache_hit` | Replay should not re-pay or re-roll a prompt | [LLM replay tutorial](documentation/tutorials/llm-deterministic-cache.md) |
560
+ | Unbounded agent spend | `BudgetTracker`, `BudgetNode` | Limits must be enforceable, not documented | [Budget tutorial](documentation/tutorials/budget-guardrails.md) |
561
+ | Competing workers / stale graphs | side-effect leases, flow versioning | Exactly-once effects and safe resume after a deploy | [MIGRATION § 9](MIGRATION.md#9-side-effects-replay-and-worker-leases) · [§ 10](MIGRATION.md#10-flow-versioning) |
562
+ | Tenant-isolated recall | `MemoryStoreNode`, two store implementations | One flow, separate data per customer | [Memory tutorial](documentation/tutorials/multi-tenant-memory.md) |
563
+
564
+ ### 1. Suspend on a human decision
565
+
566
+ **Why:** a callback held in process memory cannot wait three days. The approval
567
+ is a row in SQLite; the flow returns `status: 'suspended'` and resumes from the
568
+ saved decision.
569
+
570
+ 1. Add the gate with a stable id: `new WaitForApprovalNode({ approvalId: '{{requestId}}', prompt: 'Approve?' })` and register `approve` / `reject` successors.
571
+ 2. Run durably and show `checkpointer.listApprovals(runId, { status: 'pending' })` to a reviewer.
572
+ 3. Call `checkpointer.approve(runId, decision, approvalId)` (or `reject`), then `runDurable({ runId, resume: true })`.
573
+
574
+ | Option | Type | Default | Meaning |
575
+ | --- | --- | --- | --- |
576
+ | `approvalId` | template string / function / `true` | `true` | Stable decision key; templates use `{{sharedKey}}` and get an `approval:` prefix |
577
+ | `prompt` | string | `null` | Reviewer question; also read from `shared.approvalPrompt` |
578
+ | `resultKey` / `approvalsKey` | string | `'approval'` / `'approvals'` | Where the decision and the id→decision map are written in `shared` |
579
+ | `metadata` | JSON object | `null` | Extra reviewer context (amount, links, UI hints) |
580
+
581
+ ```javascript
582
+ import { DurableFlow, SQLiteCheckpointer, WaitForApprovalNode } from '@fractal-solutions/qflow/durable';
583
+
584
+ const gate = new WaitForApprovalNode({ approvalId: '{{requestId}}', prompt: 'Approve refund?' });
585
+ gate.next(approvedNode, 'approve');
586
+ gate.next(rejectedNode, 'reject');
587
+
588
+ const checkpointer = new SQLiteCheckpointer('./runs.db');
589
+ const flow = new DurableFlow(gate, { checkpointer, version: '1.0.0' });
590
+ const pending = await flow.runDurable({ runId: 'refund-req-1', shared: { requestId: 'req-1' } });
591
+ // pending.status === 'suspended', pending.approvalId === 'approval:req-1'
592
+
593
+ checkpointer.approve('refund-req-1', { by: 'alice' }, 'approval:req-1');
594
+ const finished = await flow.runDurable({ runId: 'refund-req-1', resume: true });
595
+ // finished.shared.approval = { approved: true, by: 'alice', ... }
596
+ ```
597
+
598
+ ### 2. Suspend until a time
599
+
600
+ **Why:** a timer that lives in a process disappears on restart. The due time is
601
+ stored with the run; any worker can pick it up when it is due.
602
+
603
+ 1. Add `ScheduleNode` with `at` (absolute), `delayMs` (relative) or `cron` (five fields) and register the `due` successor.
604
+ 2. Read `status === 'scheduled'` and `dueAt`; poll `checkpointer.listScheduledRuns({ before: Date.now() })` in a worker.
605
+ 3. Resume each due `runId` with `{ resume: true }`; the node re-checks the same stored time.
606
+
607
+ | Option | Type | Default | Meaning |
608
+ | --- | --- | --- | --- |
609
+ | `at` | `Date` / ISO string / epoch ms | `null` | Absolute due time (highest priority) |
610
+ | `delayMs` | number | `null` | Relative delay, resolved once |
611
+ | `cron` | string | `null` | Five fields: `minute hour day month weekday`, no optional package |
612
+ | `dueAtKey` / `scheduleIdKey` | string | `'scheduledAt'` / `'scheduleId'` | Shared keys holding the persisted schedule |
613
+
614
+ ```javascript
615
+ import { DurableFlow, SQLiteCheckpointer, ScheduleNode } from '@fractal-solutions/qflow/durable';
616
+
617
+ const wait = new ScheduleNode({ delayMs: 60_000 });
618
+ wait.next(sendReminder, 'due');
619
+ const checkpointer = new SQLiteCheckpointer('./runs.db');
620
+ const flow = new DurableFlow(wait, { checkpointer });
621
+
622
+ const paused = await flow.runDurable({ runId: 'reminder-1', shared: {} });
623
+ // paused.status === 'scheduled'
624
+ for (const run of checkpointer.listScheduledRuns({ before: Date.now() })) {
625
+ await flow.runDurable({ runId: run.runId, resume: true });
626
+ }
627
+ ```
628
+
629
+ ### 3. Replay LLM calls instead of re-paying for them
630
+
631
+ **Why:** a checkpoint knows a node ran, but the model call itself is external.
632
+ A cache makes replay deterministic and emits `llm:cache_hit` so traces show it.
633
+
634
+ 1. Add `cache: true` to `LLMNode` inside a `DurableFlow` (the checkpointer becomes the store), or pass `{ get, set }`.
635
+ 2. Keep the default request hash, or set `cacheKey: '{{tenant}}:{{prompt}}'` for readable keys.
636
+ 3. Use `cacheTtlMs` for changing data and listen for `llm:cache_hit` in tests.
637
+
638
+ | Option | Type | Default | Meaning |
639
+ | --- | --- | --- | --- |
640
+ | `cache` | `true` / `{ get, set }` / `null` | `null` | Cache store; `true` uses the checkpointer's `llm` namespace |
641
+ | `cacheKey` | template / function `({request, shared})` / `null` | request hash | Must include every input that changes the answer |
642
+ | `cacheTtlMs` | number / `null` | `null` | Entry lifetime; `null` never expires |
643
+
644
+ ```javascript
645
+ import { LLMNode, LLM_CACHE_HIT_EVENT } from '@fractal-solutions/qflow/llm';
646
+
647
+ const llm = new LLMNode({
648
+ provider: 'openai', model: 'gpt-4o-mini',
649
+ cache: true, cacheKey: '{{tenant}}:{{prompt}}',
650
+ cacheTtlMs: 24 * 60 * 60 * 1000,
651
+ });
652
+ flow.on(LLM_CACHE_HIT_EVENT, ({ key }) => console.log('replayed', key));
653
+ ```
654
+
655
+ ### 4. Enforce a spend limit
656
+
657
+ **Why:** "keep costs reasonable" is not a control; a limit with a coded error
658
+ and a fallback edge is.
659
+
660
+ 1. Create `new BudgetTracker({ maxCost, maxTokens, maxDurationMs, maxSteps })`.
661
+ 2. Pass it to `LLMNode` via `budget`, and add `BudgetNode` where the run can branch.
662
+ 3. Wire `exceeded` to a fallback node, or set `throwOnExceed: true` for `QFLOW_BUDGET_EXCEEDED`.
663
+
664
+ | Option | Type | Default | Meaning |
665
+ | --- | --- | --- | --- |
666
+ | `maxCost` / `maxTokens` | number | `Infinity` | Spend and token ceilings |
667
+ | `maxDurationMs` / `maxSteps` | number | `Infinity` | Wall-clock and step ceilings |
668
+ | `tracker` | `BudgetTracker` | `null` | Usage source for `BudgetNode`; without it, reads `shared.llmCost` / `llmUsage` |
669
+ | `throwOnExceed` | boolean | `false` | Throw instead of routing to `exceeded` |
670
+
671
+ ```javascript
672
+ import { BudgetTracker, BudgetNode } from '@fractal-solutions/qflow/budget';
673
+
674
+ const budget = new BudgetTracker({ maxCost: 0.50, maxTokens: 20_000 });
675
+ const guard = new BudgetNode({ tracker: budget, maxCost: 0.50 });
676
+ guard.next(llm, 'continue'); // within limits
677
+ guard.next(fallbackNode, 'exceeded'); // over a limit
678
+ flow.on('budget:check', result => console.log(result.cost, result.tokens));
679
+ ```
680
+
681
+ ### 5. Keep workers honest and resumes safe
682
+
683
+ **Why:** replay protection must also stop two workers starting the same
684
+ operation, and a resumed run must not follow a graph that no longer exists.
685
+
686
+ 1. Give each worker a distinct `workerId` and a `leaseMs` longer than the effect.
687
+ 2. Use stable `operationId` templates (`'{{orderId}}'`) on replay-safe nodes.
688
+ 3. Set `version` and `onVersionMismatch` (`abort` / `migrate` / `ignore`) on every durable flow that can be resumed.
689
+
690
+ ```javascript
691
+ const checkpointer = new SQLiteCheckpointer('./runs.db', {
692
+ workerId: `worker-${process.pid}`, leaseMs: 60_000,
693
+ });
694
+ const flow = new DurableFlow(charge, {
695
+ checkpointer,
696
+ version: '2.0.0',
697
+ onVersionMismatch: 'migrate',
698
+ migrate: ({ shared }) => ({ ...shared, customerTier: shared.plan ?? 'free' }),
699
+ });
700
+ // A second live worker gets QFLOW_SIDE_EFFECT_CLAIMED instead of executing.
701
+ // A stale resume gets QFLOW_FLOW_VERSION_MISMATCH unless you migrate or ignore.
702
+ ```
703
+
704
+ ### 6. Isolate tenant memory
705
+
706
+ **Why:** recall is only useful if it belongs to the right customer. A store per
707
+ tenant makes that a construction detail rather than a query filter.
708
+
709
+ 1. Construct `new SQLiteMemoryStore('./tenant-acme.db')` (or `InMemoryMemoryStore()` for tests).
710
+ 2. Put it in `shared.memoryStore`, then use `MemoryStoreNode` with `operation: 'add'` / `'search'`.
711
+ 3. Close SQLite stores when a tenant is removed.
712
+
713
+ | Operation | Reads | Result |
714
+ | --- | --- | --- |
715
+ | `add` | `text`, `id?`, `tags?`, `metadata?` | stored record |
716
+ | `search` | `query` / `text`, `tags?`, `limit?` | scored records |
717
+ | `get` / `delete` | `id` | record / boolean |
718
+ | `list` / `clear` | — | records / count removed |
719
+
720
+ ```javascript
721
+ import { SQLiteMemoryStore, MemoryStoreNode } from '@fractal-solutions/qflow/memory';
722
+
723
+ const store = new SQLiteMemoryStore('./tenant-acme.db');
724
+ const add = new MemoryStoreNode({ operation: 'add', store });
725
+ const search = new MemoryStoreNode({ operation: 'search', store, limit: 3 });
726
+ await new AsyncFlow(add).runAsync({ memoryInput: { text: 'Net-30 terms', tags: ['policy'] } });
727
+ const hits = await new AsyncFlow(search).runAsync({ memoryInput: { query: 'payment terms' } });
728
+ ```
729
+
730
+ ### Where to go next
731
+
732
+ - [Tutorial index](documentation/tutorials/README.md) — ten guided paths with option tables.
733
+ - [MIGRATION.md](MIGRATION.md) — old→new mapping, every parameter, error codes and troubleshooting.
734
+ - [`examples/v2/`](examples/v2/README.md) — four offline, end-to-end stories (`bun run examples:v2`).
735
+ - [CHANGELOG.md](CHANGELOG.md) — exact release contents.
736
+
737
+ ## 2.0 End-to-End Examples
738
+
739
+ The snippets above show individual APIs. For the *why*, see [`examples/v2/`](examples/v2/README.md): four offline stories that compose the new families around real failure modes. Run them all with `bun run examples:v2`.
740
+
741
+ | Example | Problem it solves | What you'll see |
742
+ | --- | --- | --- |
743
+ | [`replay-safe-checkout.js`](examples/v2/replay-safe-checkout.js) | A retry after a payment must not charge twice. | A simulated post-commit crash, replay of the recorded charge, and `SideEffectUncertainError` when a reservation has no result. |
744
+ | [`unified-tool-contract.js`](examples/v2/unified-tool-contract.js) | Tools get re-described in the agent, MCP server, LLM schema and docs. | One `ToolSpec` feeding all four, plus capability grants, idempotency and `AgentEngine.asFlow()`. |
745
+ | [`dataflow-eval-regression.js`](examples/v2/dataflow-eval-regression.js) | A graph changes behavior and nobody notices. | Contract rejection, explicit routing, saved trace replay with zero diffs, and an assert/score suite. |
746
+ | [`bun-stream-ingest.js`](examples/v2/bun-stream-ingest.js) | Local ingest shouldn't need optional native packages. | Child-process output through Web Streams into SQLite, plus a real file-watch event. |
747
+
748
+ ## Tutorials
749
+
750
+ Step-by-step guides for the 2.0 families. Start with the
751
+ [full tutorial index](documentation/tutorials/README.md) for two guided learning
752
+ paths; the short list below is the quick route.
753
+
754
+ 1. [MCP tool servers and clients](documentation/tutorials/mcp.md)
755
+ 2. [Provider-neutral LLM nodes](documentation/tutorials/provider-neutral-llm.md)
756
+ 3. [Durable side effects and safe replay](documentation/tutorials/durable-side-effects.md)
757
+ 4. [Durable human approval](documentation/tutorials/durable-approval.md)
758
+ 5. [Durable scheduling](documentation/tutorials/durable-scheduling.md)
759
+ 6. [Deterministic LLM replay and caching](documentation/tutorials/llm-deterministic-cache.md)
760
+ 7. [Budget guardrails](documentation/tutorials/budget-guardrails.md)
761
+ 8. [Multi-tenant memory](documentation/tutorials/multi-tenant-memory.md)
762
+ 9. [Agent strategies as flows](documentation/tutorials/agent-flows.md)
763
+ 10. [Trace-driven evaluation](documentation/tutorials/trace-driven-eval.md)
764
+
765
+ ## Integrated Nodes and their Examples
766
+
767
+ Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
768
+
769
+ ### Data
770
+
771
+ * **[CodeInterpreterNode](documentation/nodes/code_interpreter.md)**: Executes Python code snippets.
772
+ * **[DataExtractorNode](documentation/nodes/data_extractor.md)**: Extracts structured data from HTML, JSON, or plain text.
773
+ * **[DatabaseNode](documentation/nodes/database.md)**: Provides a powerful and flexible way to interact with SQL databases.
774
+ * **[EmbeddingNode](documentation/nodes/embedding.md)**: Generates vector embeddings for text (requires Ollama).
775
+ * **[MemoryNode](documentation/nodes/memory.md)**: Stores and retrieves text memories (keyword-based).
776
+ * **[SemanticMemoryNode](documentation/nodes/semantic_memory.md)**: Stores and retrieves text memories via semantic search (requires Ollama).
777
+ * **[TransformNode](documentation/nodes/transform.md)**: Transforms input data using a provided JavaScript function.
778
+ * **[PDFProcessorNode](documentation/nodes/pdf_processor.md)**: Extracts text or images from PDF documents.
779
+ * **[SpreadsheetNode](documentation/nodes/spreadsheet.md)**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
780
+ * **[DataValidationNode](documentation/nodes/data_validation.md)**: Validates structured data against a JSON Schema.
781
+
782
+ ### System
783
+
784
+ * **[ShellCommandNode](documentation/nodes/shell_command.md)**: Executes shell commands.
785
+ * **[ReadFileNode](documentation/nodes/read_file.md)**: Reads the content of a specified file.
786
+ * **[WriteFileNode](documentation/nodes/write_file.md)**: Writes content to a specified file.
787
+ * **[AppendFileNode](documentation/nodes/append_file.md)**: Appends content to an existing file.
788
+ * **[ListDirectoryNode](documentation/nodes/list_directory.md)**: Lists the files and subdirectories within a specified directory.
789
+ * **[SystemNotificationNode](documentation/nodes/system_notification.md)**: Displays a system-level notification across OSs.
790
+ * **[DisplayImageNode](documentation/nodes/display_image.md)**: Displays an image file using the system's default image viewer.
791
+ * **[HardwareInteractionNode](documentation/nodes/hardware_interaction.md)**: Communicates with local hardware via serial port (UART).
792
+ * **[ImageGalleryNode](documentation/nodes/image_gallery.md)**: Generates an HTML gallery from multiple image files and opens it in a web browser.
793
+ * **[SpeechSynthesisNode](documentation/nodes/speech_synthesis.md)**: Converts text to spoken audio using OS capabilities or cloud APIs.
794
+ * **[MultimediaProcessingNode](documentation/nodes/multimedia_processing.md)**: Performs various multimedia operations on audio and video files using ffmpeg.
795
+ * **[RemoteExecutionNode](documentation/nodes/remote_execution.md)**: Executes commands on remote machines via SSH.
796
+
797
+ ### Web
798
+
799
+ * **[HttpRequestNode](documentation/nodes/http_request.md)**: Makes a generic HTTP request to any URL.
800
+ * **[WebScraperNode](documentation/nodes/web_scraper.md)**: Fetches the HTML content of a given URL.
801
+ * **[DuckDuckGoSearchNode](documentation/nodes/duckduckgo_search.md)**: Performs a web search using DuckDuckGo.
802
+ * **[GoogleSearchNode](documentation/nodes/google_search.md)**: Performs a web search using the Google Custom Search API.
803
+ * **[BrowserControlNode](documentation/nodes/browser_control.md)**: Controls a Playwright browser to navigate pages, interact with elements, evaluate scripts, and take screenshots.
804
+ * **[NavigatorNode](documentation/nodes/navigator.md)**: Controls PinchTab instances/tabs for advanced browser navigation, snapshots, actions, text extraction, media export, and tab safety features.
805
+ * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
806
+ * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
807
+ * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
808
+ * **[InteractiveWebviewNode](documentation/nodes/interactive_webview.md)**: Displays an interactive webview window for notifications, dialogs, or user input.
809
+ * **[WebviewNode](documentation/nodes/webview.md)**: Displays a webview window with custom HTML content.
810
+
811
+ ### Flow Control
812
+
813
+ * **[SubFlowNode](documentation/nodes/sub_flow.md)**: Executes a sub-flow.
814
+ * **[IteratorNode](documentation/nodes/iterator.md)**: Iterates items, executes sub-flow for each.
815
+ * **[SchedulerNode](documentation/nodes/scheduler.md)**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
816
+
817
+ ### Other
818
+
819
+ * **[GitNode](documentation/nodes/git.md)**: Performs Git operations like clone, add, commit, and push.
820
+ * **[GISNode](documentation/nodes/gis.md)**: Performs Geographic Information System operations like geocoding and reverse geocoding.
821
+ * **[GitHubNode](documentation/nodes/github.md)**: Performs GitHub operations like creating and managing issues.
822
+ * **[HackerNewsNode](documentation/nodes/hackernews.md)**: Fetches top stories and item details from Hacker News.
823
+ * **[StripeNode](documentation/nodes/stripe.md)**: Performs Stripe operations like creating charges and retrieving account balances.
824
+
825
+ ### LLMs
826
+
827
+ * **[DeepSeekLLMNode](documentation/nodes/deepseek_llm.md)**: Interacts with the DeepSeek API.
828
+ * **[OpenAILLMNode](documentation/nodes/openai_llm.md)**: Interacts with the OpenAI API.
829
+ * **[GeminiLLMNode](documentation/nodes/gemini_llm.md)**: Interacts with the Google Gemini API.
830
+ * **[OllamaLLMNode](documentation/nodes/ollama_llm.md)**: Interacts with a local Ollama instance.
831
+ * **[HuggingFaceLLMNode](documentation/nodes/huggingface_llm.md)**: Interacts with the Hugging Face API.
832
+ * **[OpenRouterLLMNode](documentation/nodes/openrouter_llm.md)**: Interacts with the OpenRouter API.
833
+
834
+ ### Agent
835
+
836
+ * **[AgentNode](documentation/nodes/agent.md)**: The core of agentic behavior in qflow. It orchestrates tools and LLM reasoning to achieve complex goals.
837
+
838
+
839
+ ## Observability (Event System)
840
+
841
+ `qflow` includes a built-in event system for `AsyncFlow` that provides detailed insights into the execution of your workflows. This allows for powerful, real-time monitoring, logging, and debugging.
842
+
843
+ You can attach listeners with `on(name, handler)`, subscribe to everything with `onAny(handler)` / `on('*', handler)`, or emit custom events from a node with `observer.emit(name, payload)`.
844
+
845
+ ### Built-in Events
846
+
847
+ * `flow:start`: `{ flowId, startTime }`
848
+ * `flow:end`: `{ flowId, endTime, duration, status, error }`
849
+ * `node:start`: `{ flowId, nodeClass, startTime, params }`
850
+ * `node:retry`: `{ flowId, nodeClass, attempt, maxRetries, error }`
851
+ * `node:end`: `{ flowId, nodeClass, endTime, duration, status, result, error }`
852
+ * `llm:delta` / `llm:reasoning` / `llm:done`: streaming payloads from `StreamingLLMNode` and `LLMNode`
853
+ * `llm:retry` / `llm:fallback` / `llm:negotiated` / `llm:capability` / `llm:usage` / `llm:tool_call` / `llm:cache_hit`: provider-neutral LLM lifecycle and deterministic replay
854
+ * `side_effect:replay` / `side_effect:committed`: replay-safe side-effect outcomes
855
+ * `approval:requested` / `approval:resolved` / `approval:pending`: durable human decisions
856
+ * `schedule:waiting` / `schedule:pending`: durable time-based suspension
857
+ * `budget:check` / `budget:exceeded`: spend, token, duration and step guardrails
858
+ * `memory:add` / `memory:search`: unified memory operations
859
+ * `flow:version_migrated` / `flow:version_mismatch` / `flow:node_remapped`: safe resume after a graph change
860
+ * `eval:assert` / `eval:score` / `eval:compare` / `eval:replay`: evaluation results
861
+ * `cycle:iteration` / `map:item_error` / `reduce:step`: dataflow progress
862
+ * `spawn:exit` / `file:change` / `stream:item`: Bun-native node progress
863
+ * `agent:approval`: in-process agent approval decisions
864
+ * `run:start` / `run:end` / `run:resumed` / `checkpoint:saved`: durable-run events
865
+
866
+ Nested flow events are forwarded to the parent with `nested: true` and `parentFlowId`.
867
+
868
+ ### Coded errors you should handle
869
+
870
+ Every production-gap failure has a stable `code`, so you can branch on the code
871
+ without importing the class:
872
+
873
+ | Code | Meaning | Usual response |
874
+ | --- | --- | --- |
875
+ | `QFLOW_APPROVAL_PENDING` | A decision is required | Record it, resume the run |
876
+ | `QFLOW_SCHEDULE_PENDING` | The due time has not arrived | Wait, then resume |
877
+ | `QFLOW_SIDE_EFFECT_UNCERTAIN` | Effect may have committed; no result recorded | Reconcile with the provider, never retry blindly |
878
+ | `QFLOW_SIDE_EFFECT_CLAIMED` | Another worker owns the operation | Wait or let that worker finish |
879
+ | `QFLOW_FLOW_VERSION_MISMATCH` | Resume targets a different graph version | Migrate, ignore deliberately, or redeploy the old version |
880
+ | `QFLOW_BUDGET_EXCEEDED` | A limit was crossed | Route to a fallback or stop |
881
+ | `QFLOW_OPTIONAL_DEPENDENCY_MISSING` | A heavy integration is not installed | Run the printed `bun add --optional ...` command |
882
+
883
+ Full descriptions are in [MIGRATION.md § 20](MIGRATION.md#20-error-code-reference).
884
+
885
+ This example demonstrates how to use the built-in event system to monitor the execution of a flow.
886
+
887
+ ```javascript
888
+ import { AsyncFlow, AsyncNode } from '@fractal-solutions/qflow';
889
+
890
+ const colors = {
891
+ reset: "\x1b[0m",
892
+ cyan: "\x1b[36m",
893
+ green: "\x1b[32m",
894
+ red: "\x1b[31m",
895
+ grey: "\x1b[90m"
896
+ };
897
+ function colorize(text, color) {
898
+ return `${color}${text}${colors.reset}`;
899
+ }
900
+
901
+ // A simple node that simulates some work
902
+ class WorkNode extends AsyncNode {
903
+ async execAsync() {
904
+ const workTime = Math.random() * 100 + 50; // 50-150ms
905
+ await new Promise(resolve => setTimeout(resolve, workTime));
906
+ return { status: 'work_done' };
907
+ }
908
+ }
909
+
910
+ // A node that is designed to fail once before succeeding
911
+ let failCount = 0;
912
+ class SometimesFailsNode extends AsyncNode {
913
+ constructor() {
914
+ // Configure this node to allow 1 retry (for a total of 2 attempts)
915
+ super(2, 0.1);
916
+ }
917
+ async execAsync() {
918
+ if (failCount < 1) {
919
+ failCount++;
920
+ throw new Error('Simulating a transient error');
921
+ }
922
+ return { status: 'succeeded_after_failure' };
923
+ }
924
+ }
925
+
926
+ // 1. Define the workflow
927
+ const startNode = new WorkNode();
928
+ const middleNode = new SometimesFailsNode();
929
+ const endNode = new WorkNode();
930
+
931
+ startNode.next(middleNode);
932
+ middleNode.next(endNode);
933
+
934
+ // 2. Create the flow
935
+ const myFlow = new AsyncFlow(startNode);
936
+
937
+ // 3. Attach listeners for observability
938
+ myFlow.on('flow:start', (payload) => {
939
+ const time = new Date(payload.startTime).toLocaleTimeString();
940
+ console.log(`\n${colorize(`[FLOW:START]`, colors.cyan)} ${payload.flowId} at ${time}`);
941
+ });
942
+
943
+ myFlow.on('node:start', (payload) => {
944
+ console.log(colorize(` [NODE:START] ${payload.nodeClass}`, colors.grey));
945
+ });
946
+
947
+ myFlow.on('node:end', (payload) => {
948
+ const status = payload.status.toUpperCase();
949
+ const color = payload.status === 'success' ? colors.green : colors.red;
950
+ const statusStr = colorize(status.padEnd(7), color); // Pad for alignment
951
+ const duration = `${payload.duration.toFixed(2)}ms`.padStart(10);
952
+ console.log(` [NODE:END] ${payload.nodeClass.padEnd(18)} | Status: ${statusStr} | Duration: ${duration}`);
953
+ if (payload.error) {
954
+ console.log(colorize(` └─ ERROR: ${payload.error.message}`, colors.red));
955
+ }
956
+ });
957
+
958
+ myFlow.on('flow:end', (payload) => {
959
+ const status = payload.status.toUpperCase();
960
+ const color = payload.status === 'success' ? colors.green : colors.red;
961
+ const statusStr = colorize(status.padEnd(7), color);
962
+ const duration = `${payload.duration.toFixed(2)}ms`;
963
+ console.log(`\n${colorize(`[FLOW:END]`, colors.cyan)} ${payload.flowId} | Status: ${statusStr} | Duration: ${duration}`);
964
+ if (payload.error) {
965
+ console.log(colorize(` └─ FLOW ERROR: ${payload.error.message}`, colors.red));
966
+ }
967
+ });
968
+
969
+ // 4. Run the flow
970
+ await myFlow.runAsync({});
971
+
972
+ // Expected output:
973
+ //
974
+ // [FLOW:START] <flow-id> at <time>
975
+ // [NODE:START] WorkNode
976
+ // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
977
+ // [NODE:START] SometimesFailsNode
978
+ // [NODE:END] SometimesFailsNode | Status: ERROR | Duration: X.XXms
979
+ // └─ ERROR: Simulating a transient error
980
+ // [NODE:START] SometimesFailsNode
981
+ // [NODE:END] SometimesFailsNode | Status: SUCCESS | Duration: X.XXms
982
+ // [NODE:START] WorkNode
983
+ // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
984
+ //
985
+ // [FLOW:END] <flow-id> | Status: SUCCESS | Duration: XXX.XXms
986
+ ```
987
+
988
+
989
+
990
+
991
+
992
+ ## Trace Viewer and Snapshots
993
+
994
+ Capture events with `recordFlow()`, write a JSON trace, and open `site/index.html#trace` (or the deployed docs site with `#trace`) to inspect the timeline, spans, token deltas, checkpoints, and payloads.
995
+
996
+ ```javascript
997
+ import { recordFlow } from '@fractal-solutions/qflow/testing';
998
+ import { writeTraceFile } from '@fractal-solutions/qflow/trace';
999
+
1000
+ const recorder = recordFlow(flow);
1001
+ await flow.runAsync({ prompt: 'Hello' });
1002
+
1003
+ await writeTraceFile(recorder.events, './trace.json');
1004
+ ```
1005
+
1006
+ For durable runs, merge persisted checkpoints with captured events:
1007
+
1008
+ ```javascript
1009
+ import { recordFlow } from '@fractal-solutions/qflow/testing';
1010
+ import { createRunTrace } from '@fractal-solutions/qflow/durable';
1011
+ import { writeTraceFile } from '@fractal-solutions/qflow/trace';
1012
+
1013
+ const recorder = recordFlow(flow);
1014
+ const { runId } = await flow.runDurable({ shared: {} });
1015
+
1016
+ const trace = createRunTrace(checkpointer, runId, {
1017
+ events: recorder.events,
1018
+ includeState: true,
1019
+ });
1020
+ await writeTraceFile(trace, `./runs/${runId}.json`);
1021
+ ```
1022
+
1023
+ `createTraceSnapshot(recorder.events)` remains available for deterministic Bun snapshots; `normalizeTrace()` converts either raw events or snapshots into the viewer's JSON shape.
1024
+
1025
+ ## Optional Integrations
1026
+
1027
+ Core imports stay lightweight. Browser automation, webviews, spreadsheets, serial ports, SSH, Git, cron scheduling, HTML parsing, and schema validation are `optionalDependencies`. They are loaded with a guarded dynamic import only when a matching node action runs.
1028
+
1029
+ | Node(s) | Package | Install |
1030
+ | --- | --- | --- |
1031
+ | `BrowserControlNode` | `playwright` | `bun add --optional playwright` |
1032
+ | `WebviewNode`, `InteractiveWebviewNode` | `webview-bun` | `bun add --optional webview-bun` |
1033
+ | `SpreadsheetNode` | `xlsx` | `bun add --optional xlsx` |
1034
+ | `HardwareInteractionNode` | `serialport`, `@serialport/parser-readline` | `bun add --optional serialport @serialport/parser-readline` |
1035
+ | `RemoteExecutionNode` | `ssh2` | `bun add --optional ssh2` |
1036
+ | `GitNode` | `simple-git` | `bun add --optional simple-git` |
1037
+ | `WebSocketsNode` | `ws` | `bun add --optional ws` |
1038
+ | `DuckDuckGoSearchNode`, `DataExtractorNode` (HTML) | `cheerio` | `bun add --optional cheerio` |
1039
+ | `DataValidationNode` | `ajv`, `ajv-formats` | `bun add --optional ajv ajv-formats` |
1040
+ | `SchedulerNode` (cron strings) | `node-cron` | `bun add --optional node-cron` |
1041
+
1042
+ If a package is missing, the error includes the exact command to install it. You can also inspect the map programmatically:
1043
+
1044
+ ```javascript
1045
+ import { OPTIONAL_DEPENDENCIES, optionalInstallCommand } from '@fractal-solutions/qflow/optional';
1046
+
1047
+ console.log(OPTIONAL_DEPENDENCIES.playwright); // 'playwright'
1048
+ console.log(optionalInstallCommand('playwright')); // 'bun add --optional playwright'
1049
+ ```
1050
+
1051
+ ## Logging
1052
+
1053
+ `qflow` provides a simple yet powerful logging mechanism that gives you per-node control over how and where log messages are sent.
1054
+
1055
+ ### Basic Usage
1056
+
1057
+ By default, all built-in nodes will log to the console. You don't need to configure anything for this to work.
1058
+
1059
+ ### Per-Node Logging Configuration
1060
+
1061
+ To customize the logging for a specific node, pass a `logging` object in its parameters. `type` selects the severity (`info`, `warn`, `error`, `debug`, `none`) and `method` selects the destination (`console`, `file`, `event`, `remote`).
1062
+
1063
+ ```javascript
1064
+ import { HttpRequestNode } from '@fractal-solutions/qflow/nodes';
1065
+
1066
+ const httpNode = new HttpRequestNode();
1067
+
1068
+ // This node will log to the console by default
1069
+ httpNode.setParams({
1070
+ url: 'https://api.example.com/data'
1071
+ });
1072
+
1073
+ // This node will log to a file
1074
+ const anotherHttpNode = new HttpRequestNode();
1075
+ anotherHttpNode.setParams({
1076
+ url: 'https://api.example.com/other-data',
1077
+ logging: {
1078
+ method: 'file',
1079
+ params: { filePath: './logs/http.log' }
1080
+ }
1081
+ });
1082
+ ```
1083
+
1084
+ ### Logging Methods
1085
+
1086
+ The following logging methods are available out of the box:
1087
+
1088
+ * **`console` (default):** Logs messages to the console.
1089
+ * **`file`:** Appends log messages to a file.
1090
+ * **params:** `{ filePath: string }`
1091
+ * **`event`:** Emits log messages through an event emitter.
1092
+ * **params:** `{ emitter: EventEmitter }`
1093
+ * **`remote`:** Sends log messages to a remote server via a POST request.
1094
+ * **params:** `{ url: string }`
1095
+
1096
+ ### Examples
1097
+
1098
+ #### Logging to a File
1099
+
1100
+ ```javascript
1101
+ import { CodeInterpreterNode } from '@fractal-solutions/qflow/nodes';
1102
+
1103
+ const codeNode = new CodeInterpreterNode();
1104
+ codeNode.setParams({
1105
+ code: 'print("Hello from Python!")',
1106
+ logging: {
1107
+ method: 'file',
1108
+ params: { filePath: './logs/code-interpreter.log' }
1109
+ }
1110
+ });
1111
+ ```
1112
+
1113
+ #### Logging to an Event Emitter
1114
+
1115
+ This is useful for integrating `qflow`'s logging with your application's event system.
1116
+
1117
+ ```javascript
1118
+ import { EventEmitter } from 'events';
1119
+ import { MemoryNode } from '@fractal-solutions/qflow/nodes';
1120
+
1121
+ const myEmitter = new EventEmitter();
1122
+ myEmitter.on('log', (logEntry) => {
1123
+ console.log('Received log event:', logEntry);
1124
+ });
1125
+
1126
+ const memoryNode = new MemoryNode();
1127
+ memoryNode.setParams({
1128
+ action: 'store',
1129
+ content: 'This is a test memory.',
1130
+ logging: {
1131
+ method: 'event',
1132
+ params: { emitter: myEmitter }
1133
+ }
1134
+ });
1135
+ ```
1136
+
1137
+ #### Disabling Logging for a Node
1138
+
1139
+ You can disable logging for a specific node by setting the `type` to `none`.
1140
+
1141
+ ```javascript
1142
+ const silentHttpNode = new HttpRequestNode();
1143
+ silentHttpNode.setParams({
1144
+ url: 'https://api.example.com/silent',
1145
+ logging: {
1146
+ type: 'none'
1147
+ }
1148
+ });
1149
+ ```
1150
+
1151
+ ### Global Log Level
1152
+
1153
+ You can set a global log level to control the verbosity of all logs in your application. Only messages with a severity level equal to or higher than the current log level will be processed.
1154
+
1155
+ ```javascript
1156
+ import { setLogLevel, LogLevel } from '@fractal-solutions/qflow/logger';
1157
+
1158
+ // Set the global log level to INFO.
1159
+ // This will show INFO, WARN, and ERROR messages, but hide DEBUG messages.
1160
+ setLogLevel(LogLevel.INFO);
1161
+ ```
1162
+
1163
+ The available log levels are, in order of severity:
1164
+
1165
+ * `LogLevel.DEBUG`: Detailed information, useful for debugging.
1166
+ * `LogLevel.INFO`: General information about the application's state.
1167
+ * `LogLevel.WARN`: Indicates a potential problem that does not prevent the application from running.
1168
+ * `LogLevel.ERROR`: Indicates a serious error that prevented a specific operation from completing.
1169
+ * `LogLevel.NONE`: Disables all logging.
1170
+
1171
+ ### Making Your Custom Nodes Loggable
1172
+
1173
+ You can make your own custom nodes loggable by following the same pattern as the built-in nodes.
1174
+
1175
+ 1. **Import the `log` function:**
1176
+ ```javascript
1177
+ import { log } from '@fractal-solutions/qflow/logger';
1178
+ ```
1179
+
1180
+ 2. **Call the `log` function:** In your node's methods, call the `log` function and pass `this.params.logging` as the second argument. This will allow users of your node to configure its logging behavior.
1181
+
1182
+ Here is an example of a custom node that implements loggable behavior:
1183
+
1184
+ ```javascript
1185
+ import { AsyncNode } from '@fractal-solutions/qflow';
1186
+ import { log } from '@fractal-solutions/qflow/logger';
1187
+
1188
+ class MyCustomNode extends AsyncNode {
1189
+ async execAsync() {
1190
+ log('Starting execution of MyCustomNode', this.params.logging);
1191
+ // ... your node's logic ...
1192
+
1193
+ log('Finished execution of MyCustomNode', this.params.logging);
1194
+
1195
+ return 'default';
1196
+ }
1197
+ }
1198
+
1199
+ // --- User of your node can now configure logging ---
1200
+
1201
+ const myNode = new MyCustomNode();
1202
+
1203
+ // This will log to the console (default)
1204
+ myNode.setParams({ /* ... */ });
1205
+
1206
+ // This will log to a file
1207
+ const anotherNode = new MyCustomNode();
1208
+ anotherNode.setParams({
1209
+ /* ... */,
1210
+ logging: {
1211
+ method: 'file',
1212
+ params: { filePath: './my-custom-node.log' }
1213
+ }
1214
+ });
1215
+ ```
1216
+
1217
+
1218
+ ## Agents
1219
+
1220
+ For a detailed explanation of the agents, see the [Agents documentation](documentation/agents.md). The tools available to agents are documented in the [Tools documentation](documentation/integrated_nodes.md).
1221
+
1222
+ ### Extending Agents with Custom Tools
1223
+
1224
+ `qflow` agents can be extended with custom tools by defining your own Node classes and making them discoverable. This allows agents to leverage any custom logic or external integrations you build.
1225
+
1226
+ #### 1. Creating a Custom Tool Node
1227
+
1228
+ To create a custom node that can be used as a tool by an agent, your node class must:
1229
+ * Extend `AsyncNode`.
1230
+ * Implement a `static getToolDefinition()` method that returns a JSON Schema object describing the tool's name, description, and parameters.
1231
+
1232
+ Here's an example of a simple custom node that an agent could use as a tool:
1233
+
1234
+ ```javascript
1235
+ // my_nodes/MyCustomToolNode.js
1236
+ import { AsyncNode } from '@fractal-solutions/qflow';
1237
+
1238
+ export class MyCustomToolNode extends AsyncNode {
1239
+ static getToolDefinition() {
1240
+ return {
1241
+ name: "my_custom_tool",
1242
+ description: "A custom tool that greets the user with a personalized message.",
1243
+ parameters: {
1244
+ type: "object",
1245
+ properties: {
1246
+ name: {
1247
+ type: "string",
1248
+ description: "The name of the person to greet."
1249
+ },
1250
+ greeting: {
1251
+ type: "string",
1252
+ description: "Optional. The greeting message. Defaults to 'Hello'."
1253
+ }
1254
+ },
1255
+ required: ["name"]
1256
+ }
1257
+ };
1258
+ }
1259
+
1260
+ async execAsync() {
1261
+ const { name, greeting = 'Hello' } = this.params;
1262
+ const message = `${greeting}, ${name}! Welcome to your custom tool.`;
1263
+ console.log(message);
1264
+ return { message: message };
1265
+ }
1266
+
1267
+ async postAsync(shared, prepRes, execRes) {
1268
+ shared.customToolOutput = execRes.message;
1269
+ return 'default';
1270
+ }
1271
+ }
1272
+ ```
1273
+
1274
+ #### 2. Making Custom Tools Discoverable
1275
+
1276
+ To make your custom tool nodes available to `qflow` agents, you need to specify their paths in a `qflow.config.js` file in your project's root directory.
1277
+
1278
+ First, create a `qflow.config.js` file if you don't have one:
1279
+
1280
+ ```javascript
1281
+ // qflow.config.js
1282
+ /**
1283
+ * @type {import('./src/types').QFlowConfig}
1284
+ */
1285
+ const qflowConfig = {
1286
+ customNodePaths: [
1287
+ './my_nodes/MyCustomToolNode.js', // Path to your custom node file
1288
+ // Add more paths for other custom nodes
1289
+ ],
1290
+ };
1291
+
1292
+ export default qflowConfig;
1293
+ ```
1294
+
1295
+ The `customNodePaths` array should contain paths to your custom node files, relative to your project's root directory. `qflow` will automatically load these files, discover any `AsyncNode` classes with a `static getToolDefinition()` method, and register them as available tools for your agents.
1296
+
1297
+ Once configured, your agents will be able to "see" and utilize `my_custom_tool` just like any built-in tool, allowing for powerful and flexible agentic workflows tailored to your specific needs.
1298
+
1299
+
1300
+ ## Error Handling
1301
+
1302
+
1303
+ `qflow` provides mechanisms to handle errors gracefully within your workflows.
1304
+
1305
+ * **Node-level Error Handling:**
1306
+ * Synchronous `Node`s: If an error occurs in `prep` or `exec`, it will be caught by the flow and propagate up. You can implement `execFallback(prepRes, error)` in your `Node` subclass to provide a fallback mechanism when `exec` fails after all retries.
1307
+ * Asynchronous `AsyncNode`s: Similarly, `prepAsync` or `execAsync` can throw errors. Implement `execFallbackAsync(prepRes, error)` for asynchronous fallbacks.
1308
+ * **Flow-level Error Handling:**
1309
+ * When you run a flow using `flow.run(sharedState)` or `await flow.runAsync(sharedState)`, any unhandled errors from within the nodes will propagate up and can be caught using standard JavaScript `try...catch` blocks around the `run` or `runAsync` call. This allows you to manage errors at the workflow level.
1310
+
1311
+ ```javascript
1312
+ import { Node, Flow } from '@fractal-solutions/qflow';
1313
+
1314
+ class FailingNode extends Node {
1315
+ exec() {
1316
+ throw new Error("Something went wrong in FailingNode!");
1317
+ }
1318
+ execFallback(prepRes, error) {
1319
+ console.error("FailingNode fallback triggered:", error.message);
1320
+ return "Fallback successful!";
1321
+ }
1322
+ }
1323
+
1324
+ const failingNode = new FailingNode();
1325
+ const errorFlow = new Flow(failingNode);
1326
+
1327
+ try {
1328
+ const result = errorFlow.run({});
1329
+ console.log("Flow completed with result:", result);
1330
+ } catch (error) {
1331
+ console.error("Flow failed with unhandled error:", error.message);
1332
+ }
1333
+ // Expected output:
1334
+ // FailingNode fallback triggered: Something went wrong in FailingNode!
1335
+ // Flow completed with result: Fallback successful!
1336
+ ```
1337
+
1338
+ ## Debugging
1339
+
1340
+ Debugging `qflow` workflows can be done using standard JavaScript debugging tools and techniques.
1341
+
1342
+ * **`console.log`:** The simplest way to inspect data and execution flow. Strategically place `console.log` statements within `prep`, `exec`, `post`, and their `Async` counterparts to trace the `shared` object, `prepRes`, and `execRes` values.
1343
+ * **Debugger:** Use your IDE's built-in debugger or Bun's inspector (`bun --inspect`). Set breakpoints within your node's lifecycle methods to step through the execution and examine the state.
1344
+ * **Error Messages:** Pay close attention to the error messages and stack traces. `qflow` aims to provide clear error messages that point to the source of the problem within your nodes.
1345
+
1346
+ ## Testing
1347
+
1348
+ Testing `qflow` workflows involves unit testing individual nodes and integration testing entire flows.
1349
+
1350
+ * **Unit Testing Nodes:**
1351
+ * Test each `Node` or `AsyncNode` subclass in isolation.
1352
+ * Mock external dependencies (e.g., API calls for `LLMNode`, `GitHubNode`) to ensure tests are fast and reliable.
1353
+ * Verify the behavior of `prep`, `exec`, `post`, and their `Async` counterparts, as well as `setParams` and `execFallback`.
1354
+ * **Integration Testing Flows:**
1355
+ * Test entire `Flow`s or `AsyncFlow`s to ensure nodes are chained correctly and data flows as expected.
1356
+ * Provide controlled `shared` state inputs and assert on the final `shared` state or the flow's return value.
1357
+ * Use Bun's built-in test runner (`bun test`).
1358
+
1359
+ ```javascript
1360
+ // Example (using Bun's test runner syntax)
1361
+ import { test, expect } from "bun:test";
1362
+ import { Node, Flow } from '@fractal-solutions/qflow';
1363
+
1364
+ class TestNodeA extends Node {
1365
+ prep(shared) { return shared.initialValue + 1; }
1366
+ exec(prepRes) { return prepRes; }
1367
+ post(shared, prepRes, execRes) { shared.value = execRes; return 'default'; }
1368
+ }
1369
+
1370
+ class TestNodeB extends Node {
1371
+ prep(shared) { return shared.value; }
1372
+ exec(prepRes) { return prepRes * 2; }
1373
+ post(shared, prepRes, execRes) { shared.value = execRes; return 'default'; }
1374
+ }
1375
+
1376
+ test("Simple Flow should process data correctly", () => {
1377
+ const nodeA = new TestNodeA();
1378
+ const nodeB = new TestNodeB();
1379
+ nodeA.next(nodeB);
1380
+
1381
+ const flow = new Flow(nodeA);
1382
+ const sharedState = { initialValue: 5 };
1383
+ flow.run(sharedState);
1384
+
1385
+ // Flow.run() returns the last action, so assert on shared state.
1386
+ expect(sharedState.value).toBe(12);
1387
+ });
1388
+
1389
+ test("Node should handle parameters via setParams", () => {
1390
+ class ParamNode extends Node {
1391
+ exec() { return this.params.value; }
1392
+ }
1393
+ const node = new ParamNode();
1394
+ node.setParams({ value: "hello" });
1395
+ const result = node.run({});
1396
+ expect(result).toBe("hello");
1397
+ });
1398
+ ```
1399
+
1400
+ 2.0 also ships deterministic trace helpers:
1401
+
1402
+ ```javascript
1403
+ import { test, expect } from 'bun:test';
1404
+ import { AsyncFlow } from '@fractal-solutions/qflow';
1405
+ import { MockLLMNode, recordFlow, createTraceSnapshot } from '@fractal-solutions/qflow/testing';
1406
+
1407
+ test('agent prompts the LLM', async () => {
1408
+ const llm = new MockLLMNode({ responses: ['done'] });
1409
+ const flow = new AsyncFlow(llm);
1410
+ const recorder = recordFlow(flow);
1411
+
1412
+ await flow.runAsync({ prompt: 'Hello' });
1413
+
1414
+ expect(llm.calls).toHaveLength(1);
1415
+ expect(createTraceSnapshot(recorder.events)).toMatchSnapshot();
1416
+ });
1417
+ ```
1418
+
1419
+ ## Integration
1420
+
1421
+ `qflow` is designed to be highly flexible and can be integrated into various application architectures:
1422
+
1423
+ * **CLI Tools:** Build powerful command-line tools that automate complex tasks.
1424
+ * **Web Servers (e.g., Express.js, Koa):** Implement API endpoints that trigger workflows for data processing, background jobs, or agent-driven responses.
1425
+ * **Background Services:** Run long-running processes or scheduled tasks.
1426
+ * **Bun Services and Scripts:** Use `Bun.spawn`, `bun:sqlite`, and streaming `fetch` alongside workflows. Reach for the optional integration packages only when a node needs them.
1427
+
1428
+ ## Contributing
1429
+
1430
+ We welcome contributions! Please see our GitHub repository for more details on how to contribute.
1431
+
1432
+