@fractal-solutions/qflow 1.0.58 → 1.0.60

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
@@ -557,9 +557,85 @@ anotherNode.setParams({
557
557
 
558
558
  ## Agents
559
559
 
560
-
561
560
  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).
562
561
 
562
+ ### Extending Agents with Custom Tools
563
+
564
+ `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.
565
+
566
+ #### 1. Creating a Custom Tool Node
567
+
568
+ To create a custom node that can be used as a tool by an agent, your node class must:
569
+ * Extend `AsyncNode`.
570
+ * Implement a `static getToolDefinition()` method that returns a JSON Schema object describing the tool's name, description, and parameters.
571
+
572
+ Here's an example of a simple custom node that an agent could use as a tool:
573
+
574
+ ```javascript
575
+ // my_nodes/MyCustomToolNode.js
576
+ import { AsyncNode } from '@fractal-solutions/qflow';
577
+
578
+ export class MyCustomToolNode extends AsyncNode {
579
+ static getToolDefinition() {
580
+ return {
581
+ name: "my_custom_tool",
582
+ description: "A custom tool that greets the user with a personalized message.",
583
+ parameters: {
584
+ type: "object",
585
+ properties: {
586
+ name: {
587
+ type: "string",
588
+ description: "The name of the person to greet."
589
+ },
590
+ greeting: {
591
+ type: "string",
592
+ description: "Optional. The greeting message. Defaults to 'Hello'."
593
+ }
594
+ },
595
+ required: ["name"]
596
+ }
597
+ };
598
+ }
599
+
600
+ async execAsync() {
601
+ const { name, greeting = 'Hello' } = this.params;
602
+ const message = `${greeting}, ${name}! Welcome to your custom tool.`;
603
+ console.log(message);
604
+ return { message: message };
605
+ }
606
+
607
+ async postAsync(shared, prepRes, execRes) {
608
+ shared.customToolOutput = execRes.message;
609
+ return 'default';
610
+ }
611
+ }
612
+ ```
613
+
614
+ #### 2. Making Custom Tools Discoverable
615
+
616
+ 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.
617
+
618
+ First, create a `qflow.config.js` file if you don't have one:
619
+
620
+ ```javascript
621
+ // qflow.config.js
622
+ /**
623
+ * @type {import('./src/types').QFlowConfig}
624
+ */
625
+ const qflowConfig = {
626
+ customNodePaths: [
627
+ './my_nodes/MyCustomToolNode.js', // Path to your custom node file
628
+ // Add more paths for other custom nodes
629
+ ],
630
+ };
631
+
632
+ export default qflowConfig;
633
+ ```
634
+
635
+ 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.
636
+
637
+ 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.
638
+
563
639
  ## Integrated Nodes and their Examples
564
640
 
565
641
  Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
@@ -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 {