@fractal-solutions/qflow 1.0.53 → 1.0.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  * **Modular & Extensible:** Easily define custom nodes and compose them into complex, reusable flows.
8
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.
9
10
  * **Shared State Management:** Pass and manipulate data across nodes using a central, mutable `shared` object.
10
11
  * **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows, including parallel execution.
11
12
  * **Agents:** Built upon the `qflow` core functionality are plug and play agents with extensive tool integrations available.
@@ -83,6 +84,24 @@ A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the ove
83
84
  **Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
84
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.
85
86
 
87
+ ## Observability (Event System)
88
+
89
+ `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.
90
+
91
+ You can attach listeners to an `AsyncFlow` instance to subscribe to key lifecycle events.
92
+
93
+ ### Available Events
94
+
95
+ * `flow:start`: Emitted when the flow begins.
96
+ * **Payload:** `{ flowId, startTime }`
97
+ * `flow:end`: Emitted when the flow finishes, either successfully or with an error.
98
+ * **Payload:** `{ flowId, endTime, duration, status, error }`
99
+ * `node:start`: Emitted just before a node executes.
100
+ * **Payload:** `{ flowId, nodeClass, startTime, params }`
101
+ * `node:end`: Emitted right after a node finishes.
102
+ * **Payload:** `{ flowId, nodeClass, endTime, duration, status, result, error }`
103
+
104
+
86
105
  ## Basic Usage & Examples
87
106
 
88
107
  ### 1. Simple Node
@@ -246,9 +265,115 @@ await asyncFlow.runAsync({});
246
265
 
247
266
  See [documentation/examples.md](documentation/examples.md) for a full list of examples.
248
267
 
268
+ ### 5. Observability
269
+
270
+ This example demonstrates how to use the built-in event system to monitor the execution of a flow.
271
+
272
+ ```javascript
273
+ import { AsyncFlow, AsyncNode } from '@fractal-solutions/qflow';
274
+
275
+ const colors = {
276
+ reset: "\x1b[0m",
277
+ cyan: "\x1b[36m",
278
+ green: "\x1b[32m",
279
+ red: "\x1b[31m",
280
+ grey: "\x1b[90m"
281
+ };
282
+ function colorize(text, color) {
283
+ return `${color}${text}${colors.reset}`;
284
+ }
285
+
286
+ // A simple node that simulates some work
287
+ class WorkNode extends AsyncNode {
288
+ async execAsync() {
289
+ const workTime = Math.random() * 100 + 50; // 50-150ms
290
+ await new Promise(resolve => setTimeout(resolve, workTime));
291
+ return { status: 'work_done' };
292
+ }
293
+ }
294
+
295
+ // A node that is designed to fail once before succeeding
296
+ let failCount = 0;
297
+ class SometimesFailsNode extends AsyncNode {
298
+ constructor() {
299
+ // Configure this node to allow 1 retry (for a total of 2 attempts)
300
+ super(2, 0.1);
301
+ }
302
+ async execAsync() {
303
+ if (failCount < 1) {
304
+ failCount++;
305
+ throw new Error('Simulating a transient error');
306
+ }
307
+ return { status: 'succeeded_after_failure' };
308
+ }
309
+ }
310
+
311
+ // 1. Define the workflow
312
+ const startNode = new WorkNode();
313
+ const middleNode = new SometimesFailsNode();
314
+ const endNode = new WorkNode();
315
+
316
+ startNode.next(middleNode);
317
+ middleNode.next(endNode);
318
+
319
+ // 2. Create the flow
320
+ const myFlow = new AsyncFlow(startNode);
321
+
322
+ // 3. Attach listeners for observability
323
+ myFlow.on('flow:start', (payload) => {
324
+ const time = new Date(payload.startTime).toLocaleTimeString();
325
+ console.log(`\n${colorize(`[FLOW:START]`, colors.cyan)} ${payload.flowId} at ${time}`);
326
+ });
327
+
328
+ myFlow.on('node:start', (payload) => {
329
+ console.log(colorize(` [NODE:START] ${payload.nodeClass}`, colors.grey));
330
+ });
331
+
332
+ myFlow.on('node:end', (payload) => {
333
+ const status = payload.status.toUpperCase();
334
+ const color = payload.status === 'success' ? colors.green : colors.red;
335
+ const statusStr = colorize(status.padEnd(7), color); // Pad for alignment
336
+ const duration = `${payload.duration.toFixed(2)}ms`.padStart(10);
337
+ console.log(` [NODE:END] ${payload.nodeClass.padEnd(18)} | Status: ${statusStr} | Duration: ${duration}`);
338
+ if (payload.error) {
339
+ console.log(colorize(` └─ ERROR: ${payload.error.message}`, colors.red));
340
+ }
341
+ });
342
+
343
+ myFlow.on('flow:end', (payload) => {
344
+ const status = payload.status.toUpperCase();
345
+ const color = payload.status === 'success' ? colors.green : colors.red;
346
+ const statusStr = colorize(status.padEnd(7), color);
347
+ const duration = `${payload.duration.toFixed(2)}ms`;
348
+ console.log(`\n${colorize(`[FLOW:END]`, colors.cyan)} ${payload.flowId} | Status: ${statusStr} | Duration: ${duration}`);
349
+ if (payload.error) {
350
+ console.log(colorize(` └─ FLOW ERROR: ${payload.error.message}`, colors.red));
351
+ }
352
+ });
353
+
354
+ // 4. Run the flow
355
+ await myFlow.runAsync({});
356
+
357
+ // Expected output:
358
+ //
359
+ // [FLOW:START] <flow-id> at <time>
360
+ // [NODE:START] WorkNode
361
+ // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
362
+ // [NODE:START] SometimesFailsNode
363
+ // [NODE:END] SometimesFailsNode | Status: ERROR | Duration: X.XXms
364
+ // └─ ERROR: Simulating a transient error
365
+ // [NODE:START] SometimesFailsNode
366
+ // [NODE:END] SometimesFailsNode | Status: SUCCESS | Duration: X.XXms
367
+ // [NODE:START] WorkNode
368
+ // [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
369
+ //
370
+ // [FLOW:END] <flow-id> | Status: SUCCESS | Duration: XXX.XXms
371
+ ```
372
+
249
373
 
250
374
  ## Agents
251
375
 
376
+
252
377
  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).
253
378
 
254
379
  ## Integrated Nodes and their Examples
package/dist/qflow.d.ts CHANGED
@@ -35,24 +35,27 @@ export class AsyncNode extends Node {
35
35
  execAsync(prepRes: any): Promise<void>;
36
36
  execFallbackAsync(prepRes: any, error: any): Promise<void>;
37
37
  postAsync(shared: any, prepRes: any, execRes: any): Promise<void>;
38
- _exec(prepRes: any, shared: any): Promise<void>;
38
+ _exec(prepRes: any, shared: any, observer?: {}): Promise<void>;
39
39
  runAsync(shared: any): Promise<void>;
40
40
  _runAsync(shared: any): Promise<void>;
41
41
  _run(): void;
42
42
  }
43
43
  export class AsyncBatchNode extends AsyncNode {
44
- _exec(items: any): Promise<void[]>;
44
+ _exec(items: any, shared: any, observer: any): Promise<void[]>;
45
45
  }
46
46
  export class AsyncParallelBatchNode extends AsyncNode {
47
- _exec(items: any): Promise<any[]>;
47
+ _exec(items: any, shared: any, observer: any): Promise<any[]>;
48
48
  }
49
49
  export class AsyncFlow extends Flow {
50
+ listeners: {};
51
+ on(eventName: any, callback: any): void;
52
+ emit(eventName: any, payload: any): void;
50
53
  prepAsync(shared: any): Promise<void>;
51
54
  postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
52
- _orchAsync(shared: any, params?: {}, initialNode?: any): Promise<any>;
55
+ _orchAsync(flowId: any, shared: any, params?: {}, initialNode?: any): Promise<any>;
53
56
  _runAsync(shared: any): Promise<any>;
54
57
  run(): void;
55
- runAsync(shared: any): Promise<any>;
58
+ runAsync(shared?: {}): Promise<any>;
56
59
  }
57
60
  export class AsyncBatchFlow extends AsyncFlow {
58
61
  }
package/dist/qflow.js CHANGED
@@ -127,18 +127,69 @@ class AsyncNode extends Node {
127
127
  throw error;
128
128
  }
129
129
  async postAsync(shared, prepRes, execRes) { }
130
- async _exec(prepRes, shared) {
131
- for (let i = 0; i < this.maxRetries; i++) {
132
- try {
133
- return await this.execAsync(prepRes, shared);
130
+ async _exec(prepRes, shared, observer = {}) {
131
+ const { emit, flowId } = observer;
132
+ const nodeClass = this.constructor.name;
133
+ const nodeStartTime = performance.now();
134
+ if (emit) {
135
+ emit('node:start', {
136
+ flowId,
137
+ nodeClass,
138
+ startTime: Date.now(),
139
+ params: this.params
140
+ });
141
+ }
142
+ let finalResult;
143
+ let finalError = null;
144
+ try {
145
+ for (let i = 0; i < this.maxRetries; i++) {
146
+ try {
147
+ finalResult = await this.execAsync(prepRes, shared);
148
+ finalError = null; // Succeeded, clear any error from previous attempt
149
+ break; // Exit retry loop
150
+ }
151
+ catch (e) {
152
+ finalError = e;
153
+ if (emit) {
154
+ emit('node:retry', {
155
+ flowId,
156
+ nodeClass,
157
+ attempt: i + 1,
158
+ maxRetries: this.maxRetries,
159
+ error: { message: e.message }
160
+ });
161
+ }
162
+ if (i >= this.maxRetries - 1) {
163
+ // On the last attempt, let fallback handle it.
164
+ // The fallback is expected to throw if it cannot recover.
165
+ finalResult = await this.execFallbackAsync(prepRes, e);
166
+ finalError = null; // If fallback doesn't throw, it "succeeded" in recovering
167
+ }
168
+ if (this.wait > 0)
169
+ await new Promise(resolve => setTimeout(resolve, this.wait * 1000));
170
+ }
134
171
  }
135
- catch (e) {
136
- if (i === this.maxRetries - 1)
137
- return await this.execFallbackAsync(prepRes, e);
138
- if (this.wait > 0)
139
- await new Promise(resolve => setTimeout(resolve, this.wait * 1000));
172
+ }
173
+ catch (e) {
174
+ finalError = e;
175
+ // Re-throw to stop the flow execution in _orchAsync
176
+ throw e;
177
+ }
178
+ finally {
179
+ if (emit) {
180
+ const nodeEndTime = performance.now();
181
+ emit('node:end', {
182
+ flowId,
183
+ nodeClass,
184
+ endTime: Date.now(),
185
+ duration: nodeEndTime - nodeStartTime,
186
+ status: finalError ? 'error' : 'success',
187
+ error: finalError ? { message: finalError.message, stack: finalError.stack } : null,
188
+ result: finalResult
189
+ });
140
190
  }
141
191
  }
192
+ return finalResult;
142
193
  }
143
194
  async runAsync(shared) {
144
195
  if (Object.keys(this.successors).length) {
@@ -156,48 +207,92 @@ class AsyncNode extends Node {
156
207
  }
157
208
  }
158
209
  class AsyncBatchNode extends AsyncNode {
159
- async _exec(items) {
210
+ async _exec(items, shared, observer) {
160
211
  const results = [];
161
212
  for (const item of items) {
162
- results.push(await super._exec(item));
213
+ results.push(await super._exec(item, shared, observer));
163
214
  }
164
215
  return results;
165
216
  }
166
217
  }
167
218
  class AsyncParallelBatchNode extends AsyncNode {
168
- async _exec(items) {
169
- return await Promise.all(items.map(item => super._exec(item)));
219
+ async _exec(items, shared, observer) {
220
+ return await Promise.all(items.map(item => super._exec(item, shared, observer)));
170
221
  }
171
222
  }
172
223
  class AsyncFlow extends Flow {
224
+ constructor(start = null) {
225
+ super(start);
226
+ this.listeners = {};
227
+ }
228
+ on(eventName, callback) {
229
+ if (!this.listeners[eventName]) {
230
+ this.listeners[eventName] = [];
231
+ }
232
+ this.listeners[eventName].push(callback);
233
+ }
234
+ emit(eventName, payload) {
235
+ if (this.listeners[eventName]) {
236
+ for (const callback of this.listeners[eventName]) {
237
+ try {
238
+ callback(payload);
239
+ }
240
+ catch (e) {
241
+ console.error(`Error in event listener for '${eventName}':`, e);
242
+ }
243
+ }
244
+ }
245
+ }
173
246
  async prepAsync(shared) { }
174
247
  async postAsync(shared, prepRes, execRes) {
175
248
  return execRes;
176
249
  }
177
- async _orchAsync(shared, params = {}, initialNode = this.startNode) {
250
+ async _orchAsync(flowId, shared, params = {}, initialNode = this.startNode) {
178
251
  let curr = initialNode;
179
252
  let lastAction = null;
180
253
  let lastExecRes = null;
181
254
  let p = { ...this.params, ...params };
182
255
  while (curr) {
183
256
  curr.setParams(p);
257
+ const observerContext = { emit: this.emit.bind(this), flowId };
184
258
  const prepRes = curr instanceof AsyncNode ? await curr.prepAsync(shared) : curr.prep(shared);
185
- const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared) : curr._exec(prepRes, shared);
259
+ const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared, observerContext) : curr._exec(prepRes, shared);
186
260
  lastAction = curr instanceof AsyncNode ? await curr.postAsync(shared, prepRes, execRes) : curr.post(shared, prepRes, execRes);
187
- lastExecRes = execRes; // Store execRes for the next iteration
261
+ lastExecRes = execRes;
188
262
  curr = this.getNextNode(curr, lastAction);
189
263
  }
190
264
  return lastExecRes;
191
265
  }
192
266
  async _runAsync(shared) {
193
- const prepRes = await this.prepAsync(shared);
194
- const result = await this._orchAsync(shared);
195
- return await this.postAsync(shared, prepRes, result);
267
+ const flowId = crypto.randomUUID();
268
+ const flowStartTime = performance.now();
269
+ this.emit('flow:start', { flowId, startTime: Date.now() });
270
+ let result;
271
+ let flowError = null;
272
+ try {
273
+ const prepRes = await this.prepAsync(shared);
274
+ result = await this._orchAsync(flowId, shared);
275
+ return await this.postAsync(shared, prepRes, result);
276
+ }
277
+ catch (e) {
278
+ flowError = e;
279
+ throw e; // Re-throw so the caller knows the flow failed
280
+ }
281
+ finally {
282
+ const flowEndTime = performance.now();
283
+ this.emit('flow:end', {
284
+ flowId,
285
+ endTime: Date.now(),
286
+ duration: flowEndTime - flowStartTime,
287
+ status: flowError ? 'error' : 'success',
288
+ error: flowError ? { message: flowError.message, stack: flowError.stack } : null,
289
+ });
290
+ }
196
291
  }
197
292
  run() {
198
293
  throw new Error("Use runAsync instead.");
199
294
  }
200
- async runAsync(shared) {
295
+ async runAsync(shared = {}) {
201
296
  return await this._runAsync(shared);
202
297
  }
203
298
  }
@@ -206,7 +301,7 @@ class AsyncBatchFlow extends AsyncFlow {
206
301
  const prepResults = await this.prepAsync(shared) || [];
207
302
  const results = [];
208
303
  for (const bp of prepResults) {
209
- results.push(await this._orchAsync(shared, { ...this.params, ...bp }));
304
+ results.push(await this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }));
210
305
  }
211
306
  return await this.postAsync(shared, prepResults, results);
212
307
  }
@@ -215,11 +310,9 @@ class AsyncParallelBatchFlow extends AsyncFlow {
215
310
  async _runAsync(shared) {
216
311
  const prepResults = await this.prepAsync(shared) || [];
217
312
  const results = await Promise.all(prepResults.map(bp => {
218
- // Create a new instance of the startNode for each batch item
219
313
  const newStartNode = new this.startNode.constructor();
220
- // Copy successors from the original startNode to the new instance
221
314
  Object.assign(newStartNode.successors, this.startNode.successors);
222
- return this._orchAsync(shared, { ...this.params, ...bp }, newStartNode);
315
+ return this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }, newStartNode);
223
316
  }));
224
317
  return await this.postAsync(shared, prepResults, results);
225
318
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.53",
3
+ "version": "1.0.54",
4
4
  "description": "A lightweight and flexible JavaScript library for creating and managing workflows and agents.",
5
5
  "main": "dist/qflow.js",
6
6
  "types": "dist/qflow.d.ts",