@fractal-solutions/qflow 1.0.57 → 1.0.59

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
@@ -248,6 +248,20 @@ await asyncFlow.runAsync({});
248
248
 
249
249
  See [documentation/examples.md](documentation/examples.md) for a full list of examples.
250
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
+
251
265
  ## Observability (Event System)
252
266
 
253
267
  `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.
@@ -588,6 +602,8 @@ Here's a comprehensive list of integrated nodes available in qflow, along with a
588
602
  * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
589
603
  * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
590
604
  * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
605
+ * **[InteractiveWebviewNode](documentation/nodes/interactive_webview.md)**: Displays an interactive webview window for notifications, dialogs, or user input.
606
+ * **[WebviewNode](documentation/nodes/webview.md)**: Displays a webview window with custom HTML content.
591
607
 
592
608
  ### Flow Control
593
609
 
@@ -0,0 +1,9 @@
1
+ export function setLogLevel(level: any): void;
2
+ export function log(message: any, nodeLoggingConfig: any, defaultOptions?: {}): void;
3
+ export namespace LogLevel {
4
+ let DEBUG: number;
5
+ let INFO: number;
6
+ let WARN: number;
7
+ let ERROR: number;
8
+ let NONE: number;
9
+ }
package/dist/logger.js ADDED
@@ -0,0 +1,107 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ export const LogLevel = {
4
+ DEBUG: 0,
5
+ INFO: 1,
6
+ WARN: 2,
7
+ ERROR: 3,
8
+ NONE: 4,
9
+ };
10
+ let currentLogLevel = LogLevel.INFO;
11
+ export function setLogLevel(level) {
12
+ currentLogLevel = level;
13
+ }
14
+ // --- Handlers ---
15
+ class ConsoleLogHandler {
16
+ handle(message, level, timestamp) {
17
+ const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
18
+ console.log(`[${timestamp.toISOString()}] [${levelString}]`, message);
19
+ }
20
+ }
21
+ const fileHandlers = {};
22
+ class FileLogHandler {
23
+ constructor(filePath) {
24
+ this.filePath = filePath;
25
+ const dir = path.dirname(filePath);
26
+ if (!fs.existsSync(dir)) {
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ }
29
+ }
30
+ handle(message, level, timestamp) {
31
+ const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
32
+ const logMessage = `[${timestamp.toISOString()}] [${levelString}] ${JSON.stringify(message)}\n`;
33
+ fs.appendFileSync(this.filePath, logMessage);
34
+ }
35
+ }
36
+ class EventLogHandler {
37
+ constructor(emitter) {
38
+ this.emitter = emitter;
39
+ }
40
+ handle(message, level, timestamp) {
41
+ if (this.emitter && typeof this.emitter.emit === 'function') {
42
+ this.emitter.emit('log', {
43
+ level: Object.keys(LogLevel).find(key => LogLevel[key] === level),
44
+ message,
45
+ timestamp,
46
+ });
47
+ }
48
+ }
49
+ }
50
+ class RemoteLogHandler {
51
+ constructor(url) {
52
+ this.url = url;
53
+ }
54
+ handle(message, level, timestamp) {
55
+ const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
56
+ const logEntry = {
57
+ timestamp: timestamp.toISOString(),
58
+ level: levelString,
59
+ message: message
60
+ };
61
+ fetch(this.url, {
62
+ method: 'POST',
63
+ headers: { 'Content-Type': 'application/json' },
64
+ body: JSON.stringify(logEntry)
65
+ }).catch(err => console.error(`Failed to send log to ${this.url}`, err));
66
+ }
67
+ }
68
+ export function log(message, nodeLoggingConfig, defaultOptions = {}) {
69
+ const options = { ...defaultOptions, ...nodeLoggingConfig };
70
+ const { type = 'info', method = 'console', params = {} } = options;
71
+ const level = LogLevel[type.toUpperCase()];
72
+ if (level === undefined || level < currentLogLevel) {
73
+ return;
74
+ }
75
+ const timestamp = new Date();
76
+ switch (method) {
77
+ case 'console':
78
+ new ConsoleLogHandler().handle(message, level, timestamp);
79
+ break;
80
+ case 'file':
81
+ if (!params.filePath) {
82
+ console.error('File logging requires a filePath in params.');
83
+ return;
84
+ }
85
+ if (!fileHandlers[params.filePath]) {
86
+ fileHandlers[params.filePath] = new FileLogHandler(params.filePath);
87
+ }
88
+ fileHandlers[params.filePath].handle(message, level, timestamp);
89
+ break;
90
+ case 'event':
91
+ if (!params.emitter) {
92
+ console.error('Event logging requires an emitter in params.');
93
+ return;
94
+ }
95
+ new EventLogHandler(params.emitter).handle(message, level, timestamp);
96
+ break;
97
+ case 'remote':
98
+ if (!params.url) {
99
+ console.error('Remote logging requires a url in params.');
100
+ return;
101
+ }
102
+ new RemoteLogHandler(params.url).handle(message, level, timestamp);
103
+ break;
104
+ default:
105
+ console.error(`Invalid log method: ${method}`);
106
+ }
107
+ }
@@ -1,4 +1,5 @@
1
1
  import { DeepSeekLLMNode, OpenAILLMNode, GeminiLLMNode, OllamaLLMNode, HuggingFaceLLMNode } from './llm.js';
2
+ import { log } from '../logger.js';
2
3
  /**
3
4
  * A specialized DeepSeekLLMNode for use within the AgentNode.
4
5
  * It expects the full prompt (conversation history) to be provided directly via setParams.
@@ -24,7 +25,7 @@ export class AgentDeepSeekLLMNode extends DeepSeekLLMNode {
24
25
  catch (e) {
25
26
  throw new Error(`AgentDeepSeekLLMNode: Invalid prompt format. Expected stringified JSON array of messages. Error: ${e.message}`);
26
27
  }
27
- console.log(`[DeepSeek] Sending prompt for "${keyword || 'agent_reasoning'}"...`);
28
+ log(`[DeepSeek] Sending prompt for "${keyword || 'agent_reasoning'}"...`, this.params.logging);
28
29
  const response = await fetch('https://api.deepseek.com/chat/completions', {
29
30
  method: 'POST',
30
31
  headers: {
@@ -48,7 +49,7 @@ export class AgentDeepSeekLLMNode extends DeepSeekLLMNode {
48
49
  throw new Error('Invalid response structure from DeepSeek API or missing content.');
49
50
  }
50
51
  const llmResponse = data.choices[0].message.content.trim();
51
- console.log(`[DeepSeek] Received response for "${keyword || 'agent_reasoning'}".`);
52
+ log(`[DeepSeek] Received response for "${keyword || 'agent_reasoning'}".`, this.params.logging);
52
53
  return llmResponse; // Return the actual content
53
54
  }
54
55
  async postAsync(shared, prepRes, execRes) {
@@ -87,7 +88,7 @@ export class AgentOpenAILLMNode extends OpenAILLMNode {
87
88
  catch (e) {
88
89
  throw new Error(`AgentOpenAILLMNode: Invalid prompt format. Expected stringified JSON array of messages. Error: ${e.message}`);
89
90
  }
90
- console.log(`[OpenAI] Sending prompt for "${keyword || 'agent_reasoning'}"...`);
91
+ log(`[OpenAI] Sending prompt for "${keyword || 'agent_reasoning'}"...`, this.params.logging);
91
92
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
92
93
  method: 'POST',
93
94
  headers: {
@@ -110,7 +111,7 @@ export class AgentOpenAILLMNode extends OpenAILLMNode {
110
111
  throw new Error('Invalid response structure from OpenAI API or missing content.');
111
112
  }
112
113
  const llmResponse = data.choices[0].message.content.trim();
113
- console.log(`[OpenAI] Received response for "${keyword || 'agent_reasoning'}".`);
114
+ log(`[OpenAI] Received response for "${keyword || 'agent_reasoning'}".`, this.params.logging);
114
115
  return llmResponse; // Return the actual content
115
116
  }
116
117
  async postAsync(shared, prepRes, execRes) {
@@ -128,7 +129,7 @@ export class AgentGeminiLLMNode extends GeminiLLMNode {
128
129
  if (!apiKey) {
129
130
  throw new Error('Google Gemini API Key is required.');
130
131
  }
131
- console.log(`[AgentGemini] Sending prompt to Gemini...`);
132
+ log(`[AgentGemini] Sending prompt to Gemini...`, this.params.logging);
132
133
  try {
133
134
  const contents = messages.map(msg => ({
134
135
  role: msg.role === 'user' ? 'user' : 'model',
@@ -167,11 +168,11 @@ export class AgentGeminiLLMNode extends GeminiLLMNode {
167
168
  }
168
169
  const data = await response.json();
169
170
  const llmResponse = data.candidates[0].content.parts[0].text.trim();
170
- console.log(`[AgentGemini] Received response from Gemini.`);
171
+ log(`[AgentGemini] Received response from Gemini.`, this.params.logging);
171
172
  return llmResponse;
172
173
  }
173
174
  catch (error) {
174
- console.error('AgentGeminiLLMNode: Error during API call:', error);
175
+ log('AgentGeminiLLMNode: Error during API call:', this.params.logging, { type: 'error' });
175
176
  throw error;
176
177
  }
177
178
  }
@@ -194,7 +195,7 @@ export class AgentOllamaLLMNode extends OllamaLLMNode {
194
195
  if (!prompt) {
195
196
  throw new Error('Prompt is required for AgentOllamaLLMNode.');
196
197
  }
197
- console.log(`[AgentOllama] Sending prompt to ${model} at ${baseUrl}...`);
198
+ log(`[AgentOllama] Sending prompt to ${model} at ${baseUrl}...`, this.params.logging);
198
199
  try {
199
200
  const response = await fetch(`${baseUrl}/api/generate`, {
200
201
  method: 'POST',
@@ -213,11 +214,11 @@ export class AgentOllamaLLMNode extends OllamaLLMNode {
213
214
  }
214
215
  const data = await response.json();
215
216
  const llmResponse = data.response.trim();
216
- console.log(`[AgentOllama] Received response from ${model}.`);
217
+ log(`[AgentOllama] Received response from ${model}.`, this.params.logging);
217
218
  return llmResponse;
218
219
  }
219
220
  catch (error) {
220
- console.error('AgentOllamaLLMNode: Error during API call:', error);
221
+ log('AgentOllamaLLMNode: Error during API call:', this.params.logging, { type: 'error' });
221
222
  throw error;
222
223
  }
223
224
  }
@@ -256,7 +257,7 @@ export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
256
257
  temperature: temperature || 0.7,
257
258
  max_tokens: max_new_tokens || 500,
258
259
  });
259
- console.log(`[AgentHuggingFace] Sending prompt to ${model} at ${url}...`);
260
+ log(`[AgentHuggingFace] Sending prompt to ${model} at ${url}...`, this.params.logging);
260
261
  try {
261
262
  const response = await fetch(url, {
262
263
  method: 'POST',
@@ -286,11 +287,11 @@ export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
286
287
  else {
287
288
  throw new Error('Invalid or unexpected response structure from Hugging Face API.');
288
289
  }
289
- console.log(`[AgentHuggingFace] Received response from ${model}.`);
290
+ log(`[AgentHuggingFace] Received response from ${model}.`, this.params.logging);
290
291
  return data; // Return the full data object for AgentNode to parse
291
292
  }
292
293
  catch (error) {
293
- console.error('AgentHuggingFaceLLMNode: Error during API call:', error);
294
+ log('AgentHuggingFaceLLMNode: Error during API call:', this.params.logging, { type: 'error' });
294
295
  throw error;
295
296
  }
296
297
  }
@@ -4,6 +4,7 @@ import { promises as fs } from 'fs';
4
4
  import path from 'path';
5
5
  import os from 'os';
6
6
  import chalk from 'chalk';
7
+ import { log } from '../logger.js';
7
8
  let nodeChildProcess = null;
8
9
  if (!process.versions.bun) {
9
10
  nodeChildProcess = require('child_process');
@@ -29,9 +30,9 @@ export class CodeInterpreterNode extends AsyncNode {
29
30
  const tempFileName = `qflow_python_code_${Date.now()}_${Math.random().toString(36).substring(2, 8)}.py`;
30
31
  const tempFilePath = path.join(tempDir, tempFileName);
31
32
  const interpreterCommand = interpreterPath || 'python';
32
- console.log(`[CodeInterpreter] Proposed execution: ${interpreterCommand} ${tempFilePath}`);
33
+ log(`Executing code with interpreter: ${interpreterCommand}`, this.params.logging);
33
34
  if (!requireConfirmation)
34
- console.log(`[CodeInterpreter] Code to execute:\n${syntaxHighlight(code)}`);
35
+ log(`Code to execute:\n${code}`, this.params.logging);
35
36
  if (requireConfirmation) {
36
37
  const confirmNode = new UserInputNode();
37
38
  confirmNode.setParams({
@@ -110,7 +111,7 @@ export class CodeInterpreterNode extends AsyncNode {
110
111
  return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
111
112
  }
112
113
  finally {
113
- await fs.unlink(tempFilePath).catch(e => console.error(`Failed to delete temp file ${tempFilePath}:`, e));
114
+ await fs.unlink(tempFilePath).catch(e => log(`Failed to delete temp file ${tempFilePath}:`, this.params.logging, { type: 'error' }));
114
115
  }
115
116
  }
116
117
  async postAsync(shared, prepRes, execRes) {
@@ -1,5 +1,6 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
2
  import * as cheerio from 'cheerio';
3
+ import { log } from '../logger.js';
3
4
  export class DataExtractorNode extends AsyncNode {
4
5
  async execAsync() {
5
6
  const { input, type, selector, jsonPath, regex, group } = this.params;
@@ -15,7 +16,7 @@ export class DataExtractorNode extends AsyncNode {
15
16
  if (!selector) {
16
17
  throw new Error('HTML extraction requires a `selector`.');
17
18
  }
18
- console.log(`[DataExtractor] Extracting HTML with selector: ${selector}`);
19
+ log(`[DataExtractor] Extracting HTML with selector: ${selector}`, this.params.logging);
19
20
  const $ = cheerio.load(input);
20
21
  result = $(selector).map((i, el) => $(el).text()).get();
21
22
  break;
@@ -23,7 +24,7 @@ export class DataExtractorNode extends AsyncNode {
23
24
  if (!jsonPath) {
24
25
  throw new Error('JSON extraction requires a `jsonPath`.');
25
26
  }
26
- console.log(`[DataExtractor] Extracting JSON with path: ${jsonPath}`);
27
+ log(`[DataExtractor] Extracting JSON with path: ${jsonPath}`, this.params.logging);
27
28
  try {
28
29
  const data = JSON.parse(input);
29
30
  // Simple JSON path implementation (dot notation and array indexing)
@@ -49,7 +50,7 @@ export class DataExtractorNode extends AsyncNode {
49
50
  if (!regex) {
50
51
  throw new Error('Text extraction requires a `regex`.');
51
52
  }
52
- console.log(`[DataExtractor] Extracting text with regex: ${regex}`);
53
+ log(`[DataExtractor] Extracting text with regex: ${regex}`, this.params.logging);
53
54
  const re = new RegExp(regex, 'g');
54
55
  const matches = [];
55
56
  let match;
@@ -70,7 +71,7 @@ export class DataExtractorNode extends AsyncNode {
70
71
  default:
71
72
  throw new Error('Unsupported extraction type.');
72
73
  }
73
- console.log(`[DataExtractor] Extraction complete. Result: ${JSON.stringify(result).substring(0, 100)}...`);
74
+ log(`[DataExtractor] Extraction complete. Result: ${JSON.stringify(result).substring(0, 100)}...`, this.params.logging);
74
75
  return result;
75
76
  }
76
77
  async postAsync(shared, prepRes, execRes) {
@@ -1,6 +1,7 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
2
  import { exec } from 'child_process';
3
3
  import os from 'os';
4
+ import { log } from '../logger.js';
4
5
  export class DisplayImageNode extends AsyncNode {
5
6
  constructor(maxRetries = 1, wait = 0) {
6
7
  super(maxRetries, wait);
@@ -28,17 +29,17 @@ export class DisplayImageNode extends AsyncNode {
28
29
  default:
29
30
  throw new Error(`Unsupported platform for DisplayImageNode: ${platform}`);
30
31
  }
31
- console.log(`[DisplayImageNode] Executing: ${command}`);
32
+ log(`[DisplayImageNode] Executing: ${command}`, this.params.logging);
32
33
  return new Promise((resolve, reject) => {
33
34
  exec(command, (error, stdout, stderr) => {
34
35
  if (error) {
35
- console.error(`DisplayImageNode error: ${error.message}`);
36
+ log(`DisplayImageNode error: ${error.message}`, this.params.logging, { type: 'error' });
36
37
  return reject(error);
37
38
  }
38
39
  if (stderr) {
39
- console.warn(`DisplayImageNode stderr: ${stderr}`);
40
+ log(`DisplayImageNode stderr: ${stderr}`, this.params.logging, { type: 'warn' });
40
41
  }
41
- console.log(`Image opened: ${imagePath}`);
42
+ log(`Image opened: ${imagePath}`, this.params.logging);
42
43
  resolve({ imagePath, stdout, stderr });
43
44
  });
44
45
  });
@@ -1,4 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
+ import { log } from '../logger.js';
2
3
  export class EmbeddingNode extends AsyncNode {
3
4
  constructor(maxRetries = 3, wait = 2) {
4
5
  super(maxRetries, wait);
@@ -13,7 +14,7 @@ export class EmbeddingNode extends AsyncNode {
13
14
  model: model,
14
15
  prompt: text,
15
16
  };
16
- console.log(`[EmbeddingNode] Generating embedding for text (model: ${model}) at ${baseUrl}...`);
17
+ log(`[EmbeddingNode] Generating embedding for text (model: ${model}) at ${baseUrl}...`, this.params.logging);
17
18
  try {
18
19
  const response = await fetch(url, {
19
20
  method: 'POST',
@@ -30,7 +31,7 @@ export class EmbeddingNode extends AsyncNode {
30
31
  if (!data.embedding) {
31
32
  throw new Error('Ollama embedding API response missing embedding.');
32
33
  }
33
- console.log(`[EmbeddingNode] Embedding generated successfully.`);
34
+ log(`[EmbeddingNode] Embedding generated successfully.`, this.params.logging);
34
35
  return { embedding: data.embedding };
35
36
  }
36
37
  catch (error) {
@@ -1,6 +1,7 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
2
  import { promises as fs } from 'fs';
3
3
  import path from 'path';
4
+ import { log } from '../logger.js';
4
5
  /**
5
6
  * Reads a file from the file system.
6
7
  * @param {object} params - The parameters for the node.
@@ -13,9 +14,9 @@ export class ReadFileNode extends AsyncNode {
13
14
  if (!filePath) {
14
15
  throw new Error('Missing required parameter: filePath');
15
16
  }
16
- console.log(`[FileSystem] Reading file: ${filePath}`);
17
+ log(`[FileSystem] Reading file: ${filePath}`, this.params.logging);
17
18
  const content = await fs.readFile(filePath, 'utf-8');
18
- console.log(`[FileSystem] Successfully read file: ${filePath}`);
19
+ log(`[FileSystem] Successfully read file: ${filePath}`, this.params.logging);
19
20
  return content;
20
21
  }
21
22
  async postAsync(shared, prepRes, execRes) {
@@ -36,10 +37,10 @@ export class WriteFileNode extends AsyncNode {
36
37
  if (!filePath || content === undefined) {
37
38
  throw new Error('Missing required parameters: filePath, content');
38
39
  }
39
- console.log(`[FileSystem] Writing to file: ${filePath}`);
40
+ log(`[FileSystem] Writing to file: ${filePath}`, this.params.logging);
40
41
  await fs.mkdir(path.dirname(filePath), { recursive: true });
41
42
  await fs.writeFile(filePath, content, 'utf-8');
42
- console.log(`[FileSystem] Successfully wrote to file: ${filePath}`);
43
+ log(`[FileSystem] Successfully wrote to file: ${filePath}`, this.params.logging);
43
44
  return 'default';
44
45
  }
45
46
  }
@@ -56,10 +57,10 @@ export class AppendFileNode extends AsyncNode {
56
57
  if (!filePath || content === undefined) {
57
58
  throw new Error('Missing required parameters: filePath, content');
58
59
  }
59
- console.log(`[FileSystem] Appending to file: ${filePath}`);
60
+ log(`[FileSystem] Appending to file: ${filePath}`, this.params.logging);
60
61
  await fs.mkdir(path.dirname(filePath), { recursive: true });
61
62
  await fs.appendFile(filePath, content, 'utf-8');
62
- console.log(`[FileSystem] Successfully appended to file: ${filePath}`);
63
+ log(`[FileSystem] Successfully appended to file: ${filePath}`, this.params.logging);
63
64
  return 'default';
64
65
  }
65
66
  }
@@ -75,9 +76,9 @@ export class ListDirectoryNode extends AsyncNode {
75
76
  if (!directoryPath) {
76
77
  throw new Error('Missing required parameter: directoryPath');
77
78
  }
78
- console.log(`[FileSystem] Listing directory: ${directoryPath}`);
79
+ log(`[FileSystem] Listing directory: ${directoryPath}`, this.params.logging);
79
80
  const files = await fs.readdir(directoryPath);
80
- console.log(`[FileSystem] Successfully listed directory: ${directoryPath}`);
81
+ log(`[FileSystem] Successfully listed directory: ${directoryPath}`, this.params.logging);
81
82
  return files;
82
83
  }
83
84
  async postAsync(shared, prepRes, execRes) {
@@ -1,4 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
+ import { log } from '../logger.js';
2
3
  const API_BASE = 'https://api.github.com';
3
4
  /**
4
5
  * Creates a new issue in a GitHub repository.
@@ -16,7 +17,7 @@ export class CreateIssueNode extends AsyncNode {
16
17
  if (!token || !owner || !repo || !title) {
17
18
  throw new Error('Missing required parameters: token, owner, repo, title');
18
19
  }
19
- console.log(`[GitHub] Creating issue "${title}" in ${owner}/${repo}...`);
20
+ log(`[GitHub] Creating issue "${title}" in ${owner}/${repo}...`, this.params.logging);
20
21
  const response = await fetch(`${API_BASE}/repos/${owner}/${repo}/issues`, {
21
22
  method: 'POST',
22
23
  headers: {
@@ -30,7 +31,7 @@ export class CreateIssueNode extends AsyncNode {
30
31
  throw new Error(`GitHub API error: ${response.status} - ${errorData.message}`);
31
32
  }
32
33
  const issue = await response.json();
33
- console.log(`[GitHub] Successfully created issue #${issue.number}`);
34
+ log(`[GitHub] Successfully created issue #${issue.number}`, this.params.logging);
34
35
  return issue;
35
36
  }
36
37
  async postAsync(shared, prepRes, execRes) {
@@ -57,7 +58,7 @@ export class GetIssueNode extends AsyncNode {
57
58
  if (!token || !owner || !repo || !issue_number) {
58
59
  throw new Error('Missing required parameters: token, owner, repo, issue_number');
59
60
  }
60
- console.log(`[GitHub] Getting issue #${issue_number} from ${owner}/${repo}...`);
61
+ log(`[GitHub] Getting issue #${issue_number} from ${owner}/${repo}...`, this.params.logging);
61
62
  const response = await fetch(`${API_BASE}/repos/${owner}/${repo}/issues/${issue_number}`, {
62
63
  headers: {
63
64
  'Authorization': `token ${token}`
@@ -68,7 +69,7 @@ export class GetIssueNode extends AsyncNode {
68
69
  throw new Error(`GitHub API error: ${response.status} - ${errorData.message}`);
69
70
  }
70
71
  const issue = await response.json();
71
- console.log(`[GitHub] Successfully retrieved issue #${issue.number}`);
72
+ log(`[GitHub] Successfully retrieved issue #${issue.number}`, this.params.logging);
72
73
  return issue;
73
74
  }
74
75
  }
@@ -1,4 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
+ import { log } from '../logger.js';
2
3
  const API_BASE = 'https://hacker-news.firebaseio.com/v0';
3
4
  /**
4
5
  * Fetches the top story IDs from the Hacker News API.
@@ -9,14 +10,14 @@ const API_BASE = 'https://hacker-news.firebaseio.com/v0';
9
10
  export class GetTopStoriesNode extends AsyncNode {
10
11
  async execAsync(prepRes, shared) {
11
12
  const { limit = 10 } = this.params;
12
- console.log(`[HackerNews] Fetching top ${limit} stories...`);
13
+ log(`[HackerNews] Fetching top ${limit} stories...`, this.params.logging);
13
14
  const response = await fetch(`${API_BASE}/topstories.json`);
14
15
  if (!response.ok) {
15
16
  throw new Error(`Hacker News API error: ${response.status}`);
16
17
  }
17
18
  const storyIds = await response.json();
18
19
  const limitedIds = storyIds.slice(0, limit);
19
- console.log(`[HackerNews] Found ${limitedIds.length} stories.`);
20
+ log(`[HackerNews] Found ${limitedIds.length} stories.`, this.params.logging);
20
21
  shared.storyIds = limitedIds;
21
22
  return 'default';
22
23
  }
@@ -33,14 +34,14 @@ export class GetItemNode extends AsyncNode {
33
34
  if (!id) {
34
35
  throw new Error('Item ID is required for GetItemNode.');
35
36
  }
36
- console.log(`[HackerNews] Fetching item ${id}...`);
37
+ log(`[HackerNews] Fetching item ${id}...`, this.params.logging);
37
38
  const response = await fetch(`${API_BASE}/item/${id}.json`);
38
39
  if (!response.ok) {
39
40
  throw new Error(`Hacker News API error: ${response.status}`);
40
41
  }
41
42
  const item = await response.json();
42
- console.log(`[HackerNews] Fetched item title: ${item.title}`);
43
- console.log(`[HackerNews] Fetched item: ${item.url}`);
43
+ log(`[HackerNews] Fetched item title: ${item.title}`, this.params.logging);
44
+ log(`[HackerNews] Fetched item: ${item.url}`, this.params.logging);
44
45
  return item;
45
46
  }
46
47
  }
@@ -2,6 +2,7 @@ import { AsyncNode } from '../qflow.js';
2
2
  // You would need to install the 'serialport' library: npm install serialport
3
3
  import { SerialPort } from 'serialport';
4
4
  import { ReadlineParser } from '@serialport/parser-readline'; // For reading line-by-line
5
+ import { log } from '../logger.js';
5
6
  export class HardwareInteractionNode extends AsyncNode {
6
7
  constructor(maxRetries = 1, wait = 0) {
7
8
  super(maxRetries, wait);
@@ -47,7 +48,7 @@ export class HardwareInteractionNode extends AsyncNode {
47
48
  this.port.on('open', resolve);
48
49
  this.port.on('error', reject);
49
50
  });
50
- console.log(`[HardwareInteractionNode] Serial port ${portPath} opened.`);
51
+ log(`[HardwareInteractionNode] Serial port ${portPath} opened.`, this.params.logging);
51
52
  if (action === 'write') {
52
53
  if (dataToWrite === undefined) {
53
54
  throw new Error('Write action requires `dataToWrite`.');
@@ -85,7 +86,7 @@ export class HardwareInteractionNode extends AsyncNode {
85
86
  finally {
86
87
  if (this.port && this.port.isOpen) {
87
88
  await new Promise(resolve => this.port.close(resolve));
88
- console.log(`[HardwareInteractionNode] Serial port ${portPath} closed.`);
89
+ log(`[HardwareInteractionNode] Serial port ${portPath} closed.`, this.params.logging);
89
90
  }
90
91
  }
91
92
  break;
@@ -1,4 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
+ import { log } from '../logger.js';
2
3
  /**
3
4
  * A flexible node for making generic HTTP requests to any REST API.
4
5
  * @param {object} params - The parameters for the node.
@@ -43,7 +44,7 @@ export class HttpRequestNode extends AsyncNode {
43
44
  fetchOptions.body = body;
44
45
  }
45
46
  }
46
- console.log(`[HTTP] ${method} ${url}`);
47
+ log(`[HTTP] ${method} ${url}`, this.params.logging);
47
48
  const response = await fetch(url, fetchOptions);
48
49
  const responseBody = await this.parseResponseBody(response);
49
50
  return {
@@ -4,6 +4,7 @@ import { URL } from 'url';
4
4
  import path from 'path';
5
5
  import { promises as fsPromises } from 'fs';
6
6
  import fs from 'fs';
7
+ import { log } from '../logger.js';
7
8
  // Basic mime-type lookup to avoid adding new dependencies
8
9
  function getMimeType(filePath) {
9
10
  const ext = path.extname(filePath).toLowerCase();
@@ -91,7 +92,7 @@ export class HttpServerNode extends AsyncNode {
91
92
  async execAsync() {
92
93
  const { port = 3000, routes = {}, staticDir, cors } = this.params;
93
94
  if (this.server && this.server.listening) {
94
- console.warn(`[HttpServerNode] Server already listening on port ${port}.`);
95
+ log(`[HttpServerNode] Server already listening on port ${port}.`, this.params.logging, { type: 'warn' });
95
96
  return { status: 'server_already_running', port };
96
97
  }
97
98
  this.server = http.createServer(async (req, res) => {
@@ -120,7 +121,7 @@ export class HttpServerNode extends AsyncNode {
120
121
  }
121
122
  const { flow, params: pathParams } = routeMatch;
122
123
  if (!(flow instanceof AsyncFlow)) {
123
- console.error(`[HttpServerNode] Handler for ${req.method} ${reqPath} is not an AsyncFlow.`);
124
+ log(`[HttpServerNode] Handler for ${req.method} ${reqPath} is not an AsyncFlow.`, this.params.logging, { type: 'error' });
124
125
  res.writeHead(500, { 'Content-Type': 'application/json' });
125
126
  res.end(JSON.stringify({ error: 'Internal Server Error: Invalid handler' }));
126
127
  return;
@@ -162,7 +163,7 @@ export class HttpServerNode extends AsyncNode {
162
163
  res.end(responseBody);
163
164
  }
164
165
  catch (flowError) {
165
- console.error(`[HttpServerNode] Flow for ${req.method} ${reqPath} failed:`, flowError);
166
+ log(`[HttpServerNode] Flow for ${req.method} ${reqPath} failed:`, this.params.logging, { type: 'error' });
166
167
  if (!res.writableEnded) {
167
168
  res.writeHead(500, { 'Content-Type': 'application/json' });
168
169
  res.end(JSON.stringify({ error: 'Flow execution failed', details: flowError.message }));
@@ -172,11 +173,11 @@ export class HttpServerNode extends AsyncNode {
172
173
  });
173
174
  await new Promise((resolve, reject) => {
174
175
  this.server.on('error', (err) => {
175
- console.error(`[HttpServerNode] Failed to start server on port ${port}:`, err.message);
176
+ log(`[HttpServerNode] Failed to start server on port ${port}:`, this.params.logging, { type: 'error' });
176
177
  reject(err);
177
178
  });
178
179
  this.server.listen(port, () => {
179
- console.log(`[HttpServerNode] Listening on http://localhost:${port}`);
180
+ log(`[HttpServerNode] Listening on http://localhost:${port}`, this.params.logging);
180
181
  resolve();
181
182
  });
182
183
  });
@@ -3,6 +3,7 @@ import { ShellCommandNode } from './index.js'; // Assuming ShellCommandNode is a
3
3
  import path from 'path';
4
4
  import os from 'os';
5
5
  import { promises as fs } from 'fs';
6
+ import { log } from '../logger.js';
6
7
  export class ImageGalleryNode extends AsyncNode {
7
8
  constructor(maxRetries = 1, wait = 0) {
8
9
  super(maxRetries, wait);
@@ -36,7 +37,7 @@ export class ImageGalleryNode extends AsyncNode {
36
37
  imageHtml += `</div>\n`;
37
38
  }
38
39
  catch (e) {
39
- console.warn(`[ImageGalleryNode] Could not copy image ${imagePath}: ${e.message}. Skipping.`);
40
+ log(`[ImageGalleryNode] Could not copy image ${imagePath}: ${e.message}. Skipping.`, this.params.logging, { type: 'warn' });
40
41
  }
41
42
  }
42
43
  const htmlContent = `
@@ -85,7 +86,7 @@ export class ImageGalleryNode extends AsyncNode {
85
86
  </html>
86
87
  `;
87
88
  await fs.writeFile(htmlFilePath, htmlContent);
88
- console.log(`[ImageGalleryNode] Generated HTML gallery at: ${htmlFilePath}`);
89
+ log(`[ImageGalleryNode] Generated HTML gallery at: ${htmlFilePath}`, this.params.logging);
89
90
  // Open the HTML file in the default web browser
90
91
  const openBrowserCommand = os.platform() === 'darwin' ? `open "${htmlFilePath}"` :
91
92
  os.platform() === 'win32' ? `start "" "${htmlFilePath}"` :
@@ -93,7 +94,7 @@ export class ImageGalleryNode extends AsyncNode {
93
94
  const shellNode = new ShellCommandNode();
94
95
  shellNode.setParams({ command: openBrowserCommand });
95
96
  await new AsyncFlow(shellNode).runAsync({});
96
- console.log(`[ImageGalleryNode] Opened gallery in browser.`);
97
+ log(`[ImageGalleryNode] Opened gallery in browser.`, this.params.logging);
97
98
  return { status: 'gallery_displayed', htmlFilePath: htmlFilePath, imageCount: imagePaths.length };
98
99
  }
99
100
  }
@@ -44,3 +44,5 @@ export * from "../agent/raor_agent.js";
44
44
  export * from "../agent/ooda_agent.js";
45
45
  export * from "../agent/lpavrl_agent.js";
46
46
  export * from "../agent/pema_agent.js";
47
+ export * from "./webview.js";
48
+ export * from "./interactive_webview.js";