@fractal-solutions/qflow 1.0.50 → 1.0.53

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
@@ -14,18 +14,20 @@
14
14
 
15
15
  ## Installation
16
16
 
17
- You can install `qflow` via npm or Bun:
17
+ To get started quickly with a new project, you can use the `create-qflow` tool (Recommended):
18
18
 
19
19
  ```bash
20
- npm install @fractal-solutions/qflow
21
- # or
22
- bun add @fractal-solutions/qflow
20
+ bunx create-qflow@latest <project-name>
23
21
  ```
24
22
 
25
- To get started quickly with a new project, you can use the `create-qflow` tool:
23
+ or
24
+
25
+ You can install `qflow` via npm or Bun:
26
26
 
27
27
  ```bash
28
- bunx create-qflow@latest <project-name>
28
+ npm install @fractal-solutions/qflow
29
+ # or
30
+ bun add @fractal-solutions/qflow
29
31
  ```
30
32
 
31
33
  ## Module Imports
@@ -251,7 +253,74 @@ For a detailed explanation of the agents, see the [Agents documentation](documen
251
253
 
252
254
  ## Integrated Nodes and their Examples
253
255
 
254
- For a detailed explanation of the integrated nodes and their examples, see the [Integrated Nodes documentation](documentation/nodes/index.md).
256
+ Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
257
+
258
+ ### Data
259
+
260
+ * **[CodeInterpreterNode](documentation/nodes/code_interpreter.md)**: Executes Python code snippets.
261
+ * **[DataExtractorNode](documentation/nodes/data_extractor.md)**: Extracts structured data from HTML, JSON, or plain text.
262
+ * **[DatabaseNode](documentation/nodes/database.md)**: Provides a powerful and flexible way to interact with SQL databases.
263
+ * **[EmbeddingNode](documentation/nodes/embedding.md)**: Generates vector embeddings for text (requires Ollama).
264
+ * **[MemoryNode](documentation/nodes/memory.md)**: Stores and retrieves text memories (keyword-based).
265
+ * **[SemanticMemoryNode](documentation/nodes/semantic_memory.md)**: Stores and retrieves text memories via semantic search (requires Ollama).
266
+ * **[TransformNode](documentation/nodes/transform.md)**: Transforms input data using a provided JavaScript function.
267
+ * **[PDFProcessorNode](documentation/nodes/pdf_processor.md)**: Extracts text or images from PDF documents.
268
+ * **[SpreadsheetNode](documentation/nodes/spreadsheet.md)**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
269
+ * **[DataValidationNode](documentation/nodes/data_validation.md)**: Validates structured data against a JSON Schema.
270
+
271
+ ### System
272
+
273
+ * **[ShellCommandNode](documentation/nodes/shell_command.md)**: Executes shell commands.
274
+ * **[ReadFileNode](documentation/nodes/read_file.md)**: Reads the content of a specified file.
275
+ * **[WriteFileNode](documentation/nodes/write_file.md)**: Writes content to a specified file.
276
+ * **[AppendFileNode](documentation/nodes/append_file.md)**: Appends content to an existing file.
277
+ * **[ListDirectoryNode](documentation/nodes/list_directory.md)**: Lists the files and subdirectories within a specified directory.
278
+ * **[SystemNotificationNode](documentation/nodes/system_notification.md)**: Displays a system-level notification across OSs.
279
+ * **[DisplayImageNode](documentation/nodes/display_image.md)**: Displays an image file using the system's default image viewer.
280
+ * **[HardwareInteractionNode](documentation/nodes/hardware_interaction.md)**: Communicates with local hardware via serial port (UART).
281
+ * **[ImageGalleryNode](documentation/nodes/image_gallery.md)**: Generates an HTML gallery from multiple image files and opens it in a web browser.
282
+ * **[SpeechSynthesisNode](documentation/nodes/speech_synthesis.md)**: Converts text to spoken audio using OS capabilities or cloud APIs.
283
+ * **[MultimediaProcessingNode](documentation/nodes/multimedia_processing.md)**: Performs various multimedia operations on audio and video files using ffmpeg.
284
+ * **[RemoteExecutionNode](documentation/nodes/remote_execution.md)**: Executes commands on remote machines via SSH.
285
+
286
+ ### Web
287
+
288
+ * **[HttpRequestNode](documentation/nodes/http_request.md)**: Makes a generic HTTP request to any URL.
289
+ * **[WebScraperNode](documentation/nodes/web_scraper.md)**: Fetches the HTML content of a given URL.
290
+ * **[DuckDuckGoSearchNode](documentation/nodes/duckduckgo_search.md)**: Performs a web search using DuckDuckGo.
291
+ * **[GoogleSearchNode](documentation/nodes/google_search.md)**: Performs a web search using the Google Custom Search API.
292
+ * **[BrowserControlNode](documentation/nodes/browser_control.md)**: Controls a web browser to navigate pages, interact with elements, and take screenshots.
293
+ * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
294
+ * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
295
+ * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
296
+
297
+ ### Flow Control
298
+
299
+ * **[SubFlowNode](documentation/nodes/sub_flow.md)**: Executes a sub-flow.
300
+ * **[IteratorNode](documentation/nodes/iterator.md)**: Iterates items, executes sub-flow for each.
301
+ * **[SchedulerNode](documentation/nodes/scheduler.md)**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
302
+
303
+ ### Other
304
+
305
+ * **[GitNode](documentation/nodes/git.md)**: Performs Git operations like clone, add, commit, and push.
306
+ * **[GISNode](documentation/nodes/gis.md)**: Performs Geographic Information System operations like geocoding and reverse geocoding.
307
+ * **[GitHubNode](documentation/nodes/github.md)**: Performs GitHub operations like creating and managing issues.
308
+ * **[HackerNewsNode](documentation/nodes/hackernews.md)**: Fetches top stories and item details from Hacker News.
309
+ * **[StripeNode](documentation/nodes/stripe.md)**: Performs Stripe operations like creating charges and retrieving account balances.
310
+
311
+ ### LLMs
312
+
313
+ * **[DeepSeekLLMNode](documentation/nodes/deepseek_llm.md)**: Interacts with the DeepSeek API.
314
+ * **[OpenAILLMNode](documentation/nodes/openai_llm.md)**: Interacts with the OpenAI API.
315
+ * **[GeminiLLMNode](documentation/nodes/gemini_llm.md)**: Interacts with the Google Gemini API.
316
+ * **[OllamaLLMNode](documentation/nodes/ollama_llm.md)**: Interacts with a local Ollama instance.
317
+ * **[HuggingFaceLLMNode](documentation/nodes/huggingface_llm.md)**: Interacts with the Hugging Face API.
318
+ * **[OpenRouterLLMNode](documentation/nodes/openrouter_llm.md)**: Interacts with the OpenRouter API.
319
+
320
+ ### Agent
321
+
322
+ * **[AgentNode](documentation/nodes/agent.md)**: The core of agentic behavior in qflow. It orchestrates tools and LLM reasoning to achieve complex goals.
323
+
255
324
 
256
325
 
257
326
  ## Error Handling
@@ -0,0 +1,17 @@
1
+ export class HttpServerNode extends AsyncNode {
2
+ constructor();
3
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | null;
4
+ findMatchingRoute(routes: any, method: any, path: any): {
5
+ flow: any;
6
+ params: {};
7
+ } | null;
8
+ handleStatic(staticDir: any, reqPath: any, res: any): Promise<boolean>;
9
+ applyCorsHeaders(res: any, corsConfig: any): void;
10
+ execAsync(): Promise<{
11
+ status: string;
12
+ port: any;
13
+ }>;
14
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
15
+ }
16
+ import { AsyncNode } from '../qflow.js';
17
+ import http from 'http';
@@ -0,0 +1,189 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ import http from 'http';
3
+ import { URL } from 'url';
4
+ import path from 'path';
5
+ import { promises as fsPromises } from 'fs';
6
+ import fs from 'fs';
7
+ // Basic mime-type lookup to avoid adding new dependencies
8
+ function getMimeType(filePath) {
9
+ const ext = path.extname(filePath).toLowerCase();
10
+ const types = {
11
+ '.html': 'text/html',
12
+ '.css': 'text/css',
13
+ '.js': 'application/javascript',
14
+ '.json': 'application/json',
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.gif': 'image/gif',
19
+ '.svg': 'image/svg+xml',
20
+ '.txt': 'text/plain',
21
+ };
22
+ return types[ext] || 'application/octet-stream';
23
+ }
24
+ export class HttpServerNode extends AsyncNode {
25
+ constructor() {
26
+ super();
27
+ this.server = null;
28
+ }
29
+ // Helper to find a matching route and extract params
30
+ findMatchingRoute(routes, method, path) {
31
+ for (const routePath in routes) {
32
+ const routeHandlers = routes[routePath];
33
+ const paramNames = [];
34
+ // Convert route path to regex, e.g., /users/:id -> /users/([^/]+)
35
+ const regexPath = routePath.replace(/:(\w+)/g, (_, paramName) => {
36
+ paramNames.push(paramName);
37
+ return '([^/]+)';
38
+ });
39
+ const regex = new RegExp(`^${regexPath}$`);
40
+ const match = path.match(regex);
41
+ if (match) {
42
+ const handler = routeHandlers[method.toUpperCase()];
43
+ if (handler) {
44
+ const params = {};
45
+ paramNames.forEach((name, index) => {
46
+ params[name] = match[index + 1];
47
+ });
48
+ return { flow: handler, params };
49
+ }
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ // Helper to serve static files
55
+ async handleStatic(staticDir, reqPath, res) {
56
+ if (!staticDir)
57
+ return false;
58
+ // Prevent directory traversal attacks
59
+ const safePath = path.normalize(reqPath).replace(/^(\.\.[\/\\])+/, '');
60
+ const filePath = path.join(staticDir, safePath);
61
+ try {
62
+ const stats = await fsPromises.stat(filePath);
63
+ if (stats.isFile()) {
64
+ const mimeType = getMimeType(filePath);
65
+ res.writeHead(200, { 'Content-Type': mimeType });
66
+ // Create a read stream and pipe it to the response
67
+ const fileStream = fs.createReadStream(filePath);
68
+ fileStream.pipe(res);
69
+ return true;
70
+ }
71
+ }
72
+ catch (e) {
73
+ // File doesn't exist, fall through to dynamic routing
74
+ }
75
+ return false;
76
+ }
77
+ // Helper to apply CORS headers
78
+ applyCorsHeaders(res, corsConfig) {
79
+ if (!corsConfig)
80
+ return;
81
+ if (corsConfig.origin) {
82
+ res.setHeader('Access-Control-Allow-Origin', corsConfig.origin);
83
+ }
84
+ if (corsConfig.methods) {
85
+ res.setHeader('Access-Control-Allow-Methods', corsConfig.methods);
86
+ }
87
+ if (corsConfig.headers) {
88
+ res.setHeader('Access-Control-Allow-Headers', corsConfig.headers);
89
+ }
90
+ }
91
+ async execAsync() {
92
+ const { port = 3000, routes = {}, staticDir, cors } = this.params;
93
+ if (this.server && this.server.listening) {
94
+ console.warn(`[HttpServerNode] Server already listening on port ${port}.`);
95
+ return { status: 'server_already_running', port };
96
+ }
97
+ this.server = http.createServer(async (req, res) => {
98
+ // Apply CORS headers to all responses
99
+ this.applyCorsHeaders(res, cors);
100
+ // Handle CORS pre-flight OPTIONS request
101
+ if (cors && req.method === 'OPTIONS') {
102
+ res.writeHead(204); // No Content
103
+ res.end();
104
+ return;
105
+ }
106
+ const requestUrl = new URL(req.url, `http://${req.headers.host}`);
107
+ const reqPath = requestUrl.pathname;
108
+ // 1. Try to serve static file
109
+ if (staticDir) {
110
+ const served = await this.handleStatic(staticDir, reqPath, res);
111
+ if (served)
112
+ return;
113
+ }
114
+ // 2. Find a matching dynamic route
115
+ const routeMatch = this.findMatchingRoute(routes, req.method, reqPath);
116
+ if (!routeMatch) {
117
+ res.writeHead(404, { 'Content-Type': 'application/json' });
118
+ res.end(JSON.stringify({ error: 'Not Found' }));
119
+ return;
120
+ }
121
+ const { flow, params: pathParams } = routeMatch;
122
+ if (!(flow instanceof AsyncFlow)) {
123
+ console.error(`[HttpServerNode] Handler for ${req.method} ${reqPath} is not an AsyncFlow.`);
124
+ res.writeHead(500, { 'Content-Type': 'application/json' });
125
+ res.end(JSON.stringify({ error: 'Internal Server Error: Invalid handler' }));
126
+ return;
127
+ }
128
+ // 3. Process request body and trigger flow
129
+ let body = '';
130
+ req.on('data', chunk => { body += chunk.toString(); });
131
+ req.on('end', async () => {
132
+ let payload;
133
+ if (body) {
134
+ try {
135
+ payload = JSON.parse(body);
136
+ }
137
+ catch (e) {
138
+ payload = body; // Not JSON, treat as raw string
139
+ }
140
+ }
141
+ const requestContext = {
142
+ headers: req.headers,
143
+ body: payload,
144
+ method: req.method,
145
+ path: reqPath,
146
+ query: Object.fromEntries(requestUrl.searchParams),
147
+ params: pathParams
148
+ };
149
+ try {
150
+ const flowResult = await flow.runAsync({ request: requestContext });
151
+ const response = flowResult || { statusCode: 204, body: '' };
152
+ const statusCode = response.statusCode || 200;
153
+ const headers = response.headers || {};
154
+ let responseBody = response.body;
155
+ if (typeof responseBody === 'object' && !(responseBody instanceof Buffer)) {
156
+ responseBody = JSON.stringify(responseBody);
157
+ if (!headers['Content-Type']) {
158
+ headers['Content-Type'] = 'application/json';
159
+ }
160
+ }
161
+ res.writeHead(statusCode, headers);
162
+ res.end(responseBody);
163
+ }
164
+ catch (flowError) {
165
+ console.error(`[HttpServerNode] Flow for ${req.method} ${reqPath} failed:`, flowError);
166
+ if (!res.writableEnded) {
167
+ res.writeHead(500, { 'Content-Type': 'application/json' });
168
+ res.end(JSON.stringify({ error: 'Flow execution failed', details: flowError.message }));
169
+ }
170
+ }
171
+ });
172
+ });
173
+ await new Promise((resolve, reject) => {
174
+ this.server.on('error', (err) => {
175
+ console.error(`[HttpServerNode] Failed to start server on port ${port}:`, err.message);
176
+ reject(err);
177
+ });
178
+ this.server.listen(port, () => {
179
+ console.log(`[HttpServerNode] Listening on http://localhost:${port}`);
180
+ resolve();
181
+ });
182
+ });
183
+ return { status: 'listening', port };
184
+ }
185
+ async postAsync(shared, prepRes, execRes) {
186
+ shared.httpServer = this.server;
187
+ return 'default';
188
+ }
189
+ }
@@ -25,6 +25,7 @@ export * from "./shell.js";
25
25
  export * from "./filesystem.js";
26
26
  export * from "./user.js";
27
27
  export * from "./http.js";
28
+ export * from "./http_server.js";
28
29
  export * from "./search.js";
29
30
  export * from "./summarize.js";
30
31
  export * from "./memory.js";
@@ -25,6 +25,7 @@ export * from './shell.js';
25
25
  export * from './filesystem.js';
26
26
  export * from './user.js';
27
27
  export * from './http.js';
28
+ export * from './http_server.js';
28
29
  export * from './search.js';
29
30
  export * from './summarize.js';
30
31
  export * from './memory.js';
@@ -16,7 +16,8 @@ export class WebHookNode extends AsyncNode {
16
16
  flow, // The qflow AsyncFlow instance to trigger
17
17
  sharedSecret, // Optional: for HMAC verification
18
18
  responseStatus = 200, // HTTP status to send back
19
- responseBody = { status: 'received' } // HTTP body to send back
19
+ responseBody = { status: 'received' }, // HTTP body to send back
20
+ waitForFlow = false // Whether to wait for the flow to complete
20
21
  } = this.params;
21
22
  if (!flow || !(flow instanceof AsyncFlow)) {
22
23
  throw new Error('WebHookNode requires a `flow` parameter of type AsyncFlow to trigger.');
@@ -68,19 +69,32 @@ export class WebHookNode extends AsyncNode {
68
69
  console.log('[WebHookNode] Webhook signature verified.');
69
70
  }
70
71
  console.log(`[WebHookNode] Webhook received on ${this.webhookPath}. Triggering flow...`);
71
- // Trigger the flow in the background
72
- // Create a new shared object for the triggered flow, including the webhook payload
73
72
  const triggeredFlowShared = { webhook: { headers: req.headers, payload: payload, method: req.method, path: requestUrl.pathname } };
74
- this.flowToTrigger.runAsync(triggeredFlowShared)
75
- .then(flowResult => {
76
- console.log('[WebHookNode] Triggered flow completed successfully:', flowResult);
77
- })
78
- .catch(flowError => {
79
- console.error('[WebHookNode] Triggered flow failed:', flowError);
80
- });
81
- // Send response back to webhook sender
82
- res.writeHead(responseStatus, { 'Content-Type': 'application/json' });
83
- res.end(JSON.stringify(responseBody));
73
+ if (this.params.waitForFlow) {
74
+ try {
75
+ const flowResult = await this.flowToTrigger.runAsync(triggeredFlowShared);
76
+ console.log('[WebHookNode] Triggered flow completed successfully:', flowResult);
77
+ res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
78
+ res.end(JSON.stringify(flowResult));
79
+ }
80
+ catch (flowError) {
81
+ console.error('[WebHookNode] Triggered flow failed:', flowError);
82
+ res.writeHead(500, { 'Content-Type': 'application/json' });
83
+ res.end(JSON.stringify({ error: 'Flow execution failed' }));
84
+ }
85
+ }
86
+ else {
87
+ this.flowToTrigger.runAsync(triggeredFlowShared)
88
+ .then(flowResult => {
89
+ console.log('[WebHookNode] Triggered flow completed successfully:', flowResult);
90
+ })
91
+ .catch(flowError => {
92
+ console.error('[WebHookNode] Triggered flow failed:', flowError);
93
+ });
94
+ // Send response back to webhook sender
95
+ res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
96
+ res.end(JSON.stringify(this.params.responseBody || { status: 'received' }));
97
+ }
84
98
  });
85
99
  }
86
100
  else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.50",
3
+ "version": "1.0.53",
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",