@fractal-solutions/qflow 1.0.24 → 1.0.26

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
@@ -150,6 +150,8 @@ The examples in [Basic Usage & Examples](#basic-usage--examples) below will cove
150
150
 
151
151
  These examples are a great resource for understanding how to leverage `qflow` to its full potential.
152
152
 
153
+ For a detailed list of all tools available to the `AgentNode` and their parameters, see the [Available Tools for Agents](#available-tools-for-agents) section.
154
+
153
155
  ## Basic Usage & Examples
154
156
 
155
157
  ### 1. Simple Node
@@ -1321,3 +1323,111 @@ test("Node should handle parameters via setParams", () => {
1321
1323
  We welcome contributions! Please see our GitHub repository for more details on how to contribute.
1322
1324
 
1323
1325
  ---
1326
+
1327
+ ## Available Tools for Agents
1328
+
1329
+ The `AgentNode` can be equipped with a variety of tools to perform a wide range of tasks. Below is a list of the built-in tools and their functionalities.
1330
+
1331
+ ### Core Tools
1332
+
1333
+ * **finish**: Ends the agent's execution and returns a final output.
1334
+ * `output`: A summary of the final result or the reason for stopping.
1335
+ * **user_input**: Prompts the user for input and waits for their response.
1336
+ * `prompt`: The message to display to the user.
1337
+
1338
+ ### File System
1339
+
1340
+ * **read_file**: Reads the content of a specified file.
1341
+ * `filePath`: The absolute path to the file to read.
1342
+ * **write_file**: Writes content to a specified file.
1343
+ * `filePath`: The absolute path to the file to write to.
1344
+ * `content`: The content to write to the file.
1345
+ * **append_file**: Appends content to an existing file.
1346
+ * `filePath`: The absolute path to the file to append to.
1347
+ * `content`: The content to append to the file.
1348
+ * **list_directory**: Lists the files and subdirectories within a specified directory.
1349
+ * `directoryPath`: The absolute path to the directory to list.
1350
+
1351
+ ### Web
1352
+
1353
+ * **duckduckgo_search**: Performs a web search using DuckDuckGo.
1354
+ * `query`: The search query.
1355
+ * **google_search**: Performs a web search using the Google Custom Search API.
1356
+ * `query`: The search query.
1357
+ * `apiKey`: Your Google API Key.
1358
+ * `cseId`: Your Custom Search Engine ID.
1359
+ * **http_request**: Makes a generic HTTP request to any URL.
1360
+ * `url`: The full URL of the API endpoint.
1361
+ * `method`: The HTTP method to use (e.g., 'GET', 'POST').
1362
+ * `headers`: Custom headers for the request.
1363
+ * `body`: The request payload.
1364
+ * `auth`: Authentication configuration.
1365
+ * **web_scraper**: Fetches the HTML content of a given URL.
1366
+ * `url`: The URL to scrape.
1367
+
1368
+ ### Data & Code
1369
+
1370
+ * **data_extractor**: Extracts structured data from HTML, JSON, or plain text.
1371
+ * `input`: The content string from which to extract data.
1372
+ * `type`: The type of content to extract from (html, json, or text).
1373
+ * `selector`: A CSS selector to target elements (for HTML).
1374
+ * `jsonPath`: A dot-notation path to extract data (for JSON).
1375
+ * `regex`: A regular expression to match and extract data (for text).
1376
+ * `group`: The capturing group index to return from the regex match.
1377
+ * **code_interpreter**: Executes Python code snippets.
1378
+ * `code`: The Python code snippet to execute.
1379
+ * `timeout`: Maximum execution time in milliseconds.
1380
+ * `args`: Command-line arguments to pass to the script.
1381
+ * `requireConfirmation`: If true, the user will be prompted for confirmation before executing the code.
1382
+ * **transform_node**: Transforms input data using a provided JavaScript function.
1383
+ * `input`: The data to be transformed.
1384
+ * `transformFunction`: A JavaScript function string that takes 'data' as an argument and returns the transformed result.
1385
+
1386
+ ### Memory & Embeddings
1387
+
1388
+ * **memory_node**: Stores and retrieves text-based memories from the agent's local file system.
1389
+ * `action`: The action to perform: 'store' or 'retrieve'.
1390
+ * `content`: The text content of the memory to store.
1391
+ * `query`: Keywords to search for within stored memories.
1392
+ * `id`: A unique identifier for the memory.
1393
+ * `memoryPath`: The directory path where memories are stored.
1394
+ * **semantic_memory_node**: Stores and retrieves text-based memories using vector embeddings for semantic search.
1395
+ * `action`: The action to perform: 'store' or 'retrieve'.
1396
+ * `content`: The text content of the memory to store.
1397
+ * `query`: The text query for semantic search.
1398
+ * `id`: A unique identifier for the memory.
1399
+ * `metadata`: Key-value pairs to store alongside the memory.
1400
+ * `memoryPath`: The directory path where memories and the index are stored.
1401
+ * `embeddingModel`: The Ollama embedding model name to use.
1402
+ * `embeddingBaseUrl`: The base URL of the Ollama API for embeddings.
1403
+ * `topK`: The number of top similar results to retrieve.
1404
+ * **generate_embedding**: Generates a vector embedding for a given text using a local Ollama embedding model.
1405
+ * `text`: The text string to generate an embedding for.
1406
+ * `model`: The Ollama embedding model name to use.
1407
+ * `baseUrl`: The base URL of the Ollama API.
1408
+
1409
+ ### Flow Control
1410
+
1411
+ * **sub_flow**: Executes a sub-flow.
1412
+ * `flow`: The flow to execute.
1413
+ * `shared`: The shared object to pass to the sub-flow.
1414
+ * **iterator**: Iterates over a list of items and executes a sub-flow for each item.
1415
+ * `items`: The list of items to iterate over.
1416
+ * `flow`: The flow to execute for each item.
1417
+
1418
+ ### LLM Reasoning
1419
+
1420
+ * **huggingface_llm_reasoning**: A powerful language model for general reasoning, problem-solving, and generating text, using Hugging Face's OpenAI-compatible router.
1421
+ * `prompt`: The prompt or question to send to the language model.
1422
+ * `model`: The Hugging Face model ID.
1423
+ * `hfToken`: Your Hugging Face API token.
1424
+ * `temperature`: Controls randomness.
1425
+ * `max_new_tokens`: Maximum number of tokens to generate.
1426
+ * `baseUrl`: The base URL of the Hugging Face router API.
1427
+ * **llm_reasoning**: A powerful language model for general reasoning, problem-solving, and generating text.
1428
+ * `prompt`: The prompt or question to send to the language model.
1429
+ * **ollama_llm_reasoning**: A powerful local language model for general reasoning, problem-solving, and generating text, running via Ollama.
1430
+ * `prompt`: The prompt or question to send to the local Ollama language model.
1431
+ * `model`: The Ollama model name to use.
1432
+ * `baseUrl`: The base URL of the Ollama API.
1433
+
@@ -1,8 +1,9 @@
1
1
  export class AgentNode extends AsyncNode {
2
- constructor(llmNode: any, availableTools: any, summarizeLLM: any);
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {});
3
3
  llmNode: any;
4
4
  availableTools: any;
5
5
  summarizeLLM: any;
6
+ flowRegistry: {};
6
7
  conversationHistory: any[];
7
8
  maxSteps: number;
8
9
  execAsync(): Promise<any>;
@@ -3,7 +3,7 @@ import { getToolDefinitions } from './tools.js';
3
3
  import { SummarizeNode } from '../nodes/summarize.js';
4
4
  import { logger } from './logger.js';
5
5
  export class AgentNode extends AsyncNode {
6
- constructor(llmNode, availableTools, summarizeLLM) {
6
+ constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}) {
7
7
  super();
8
8
  if (!llmNode) {
9
9
  throw new Error("AgentNode requires an LLMNode instance for reasoning.");
@@ -11,6 +11,7 @@ export class AgentNode extends AsyncNode {
11
11
  this.llmNode = llmNode;
12
12
  this.availableTools = availableTools;
13
13
  this.summarizeLLM = summarizeLLM;
14
+ this.flowRegistry = flowRegistry;
14
15
  this.conversationHistory = [];
15
16
  this.maxSteps = 20;
16
17
  }
@@ -65,6 +66,14 @@ export class AgentNode extends AsyncNode {
65
66
  let toolOutput;
66
67
  try {
67
68
  logger.toolCall(toolCall.tool, toolCall.parameters);
69
+ // If the tool is a sub-flow or iterator, look up the flow in the registry
70
+ if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator') {
71
+ const flowName = toolCall.parameters.flow;
72
+ if (!this.flowRegistry[flowName]) {
73
+ throw new Error(`Flow '${flowName}' not found in registry.`);
74
+ }
75
+ toolCall.parameters.flow = this.flowRegistry[flowName];
76
+ }
68
77
  toolInstance.setParams(toolCall.parameters);
69
78
  const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
70
79
  const toolFlow = new ToolFlowClass(toolInstance);
@@ -103,7 +112,8 @@ export class AgentNode extends AsyncNode {
103
112
  const params = JSON.stringify(tool.parameters);
104
113
  return `### Tool: ${tool.name}\nDescription: ${tool.description}\nParameters: ${params}`;
105
114
  }).join('\n\n');
106
- return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
115
+ const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0 ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}` : "";
116
+ return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}${flowRegistryDescription}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nWhen using 'sub_flow' or 'iterator', the 'flow' parameter must be a string matching one of the pre-defined flow names.\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
107
117
  }
108
118
  async getLLMAction() {
109
119
  this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
@@ -59,6 +59,9 @@ export function getToolDefinitions(): ({
59
59
  headers?: undefined;
60
60
  body?: undefined;
61
61
  auth?: undefined;
62
+ flow?: undefined;
63
+ shared?: undefined;
64
+ items?: undefined;
62
65
  output?: undefined;
63
66
  };
64
67
  required: string[];
@@ -134,6 +137,9 @@ export function getToolDefinitions(): ({
134
137
  headers?: undefined;
135
138
  body?: undefined;
136
139
  auth?: undefined;
140
+ flow?: undefined;
141
+ shared?: undefined;
142
+ items?: undefined;
137
143
  output?: undefined;
138
144
  };
139
145
  required: string[];
@@ -190,6 +196,9 @@ export function getToolDefinitions(): ({
190
196
  headers?: undefined;
191
197
  body?: undefined;
192
198
  auth?: undefined;
199
+ flow?: undefined;
200
+ shared?: undefined;
201
+ items?: undefined;
193
202
  output?: undefined;
194
203
  };
195
204
  required: string[];
@@ -243,6 +252,9 @@ export function getToolDefinitions(): ({
243
252
  headers?: undefined;
244
253
  body?: undefined;
245
254
  auth?: undefined;
255
+ flow?: undefined;
256
+ shared?: undefined;
257
+ items?: undefined;
246
258
  output?: undefined;
247
259
  };
248
260
  required: string[];
@@ -306,6 +318,9 @@ export function getToolDefinitions(): ({
306
318
  headers?: undefined;
307
319
  body?: undefined;
308
320
  auth?: undefined;
321
+ flow?: undefined;
322
+ shared?: undefined;
323
+ items?: undefined;
309
324
  output?: undefined;
310
325
  };
311
326
  required: string[];
@@ -356,6 +371,9 @@ export function getToolDefinitions(): ({
356
371
  headers?: undefined;
357
372
  body?: undefined;
358
373
  auth?: undefined;
374
+ flow?: undefined;
375
+ shared?: undefined;
376
+ items?: undefined;
359
377
  output?: undefined;
360
378
  };
361
379
  required: string[];
@@ -412,6 +430,9 @@ export function getToolDefinitions(): ({
412
430
  headers?: undefined;
413
431
  body?: undefined;
414
432
  auth?: undefined;
433
+ flow?: undefined;
434
+ shared?: undefined;
435
+ items?: undefined;
415
436
  output?: undefined;
416
437
  };
417
438
  required: string[];
@@ -478,6 +499,9 @@ export function getToolDefinitions(): ({
478
499
  headers?: undefined;
479
500
  body?: undefined;
480
501
  auth?: undefined;
502
+ flow?: undefined;
503
+ shared?: undefined;
504
+ items?: undefined;
481
505
  output?: undefined;
482
506
  };
483
507
  required: string[];
@@ -540,6 +564,9 @@ export function getToolDefinitions(): ({
540
564
  headers?: undefined;
541
565
  body?: undefined;
542
566
  auth?: undefined;
567
+ flow?: undefined;
568
+ shared?: undefined;
569
+ items?: undefined;
543
570
  output?: undefined;
544
571
  };
545
572
  required: string[];
@@ -590,6 +617,9 @@ export function getToolDefinitions(): ({
590
617
  headers?: undefined;
591
618
  body?: undefined;
592
619
  auth?: undefined;
620
+ flow?: undefined;
621
+ shared?: undefined;
622
+ items?: undefined;
593
623
  output?: undefined;
594
624
  };
595
625
  required: string[];
@@ -646,6 +676,9 @@ export function getToolDefinitions(): ({
646
676
  headers?: undefined;
647
677
  body?: undefined;
648
678
  auth?: undefined;
679
+ flow?: undefined;
680
+ shared?: undefined;
681
+ items?: undefined;
649
682
  output?: undefined;
650
683
  };
651
684
  required: string[];
@@ -696,6 +729,9 @@ export function getToolDefinitions(): ({
696
729
  headers?: undefined;
697
730
  body?: undefined;
698
731
  auth?: undefined;
732
+ flow?: undefined;
733
+ shared?: undefined;
734
+ items?: undefined;
699
735
  output?: undefined;
700
736
  };
701
737
  required: string[];
@@ -746,6 +782,9 @@ export function getToolDefinitions(): ({
746
782
  headers?: undefined;
747
783
  body?: undefined;
748
784
  auth?: undefined;
785
+ flow?: undefined;
786
+ shared?: undefined;
787
+ items?: undefined;
749
788
  output?: undefined;
750
789
  };
751
790
  required: string[];
@@ -799,6 +838,9 @@ export function getToolDefinitions(): ({
799
838
  headers?: undefined;
800
839
  body?: undefined;
801
840
  auth?: undefined;
841
+ flow?: undefined;
842
+ shared?: undefined;
843
+ items?: undefined;
802
844
  output?: undefined;
803
845
  };
804
846
  required: string[];
@@ -849,6 +891,9 @@ export function getToolDefinitions(): ({
849
891
  headers?: undefined;
850
892
  body?: undefined;
851
893
  auth?: undefined;
894
+ flow?: undefined;
895
+ shared?: undefined;
896
+ items?: undefined;
852
897
  output?: undefined;
853
898
  };
854
899
  required: string[];
@@ -932,6 +977,9 @@ export function getToolDefinitions(): ({
932
977
  command?: undefined;
933
978
  filePath?: undefined;
934
979
  directoryPath?: undefined;
980
+ flow?: undefined;
981
+ shared?: undefined;
982
+ items?: undefined;
935
983
  output?: undefined;
936
984
  };
937
985
  required: string[];
@@ -982,6 +1030,121 @@ export function getToolDefinitions(): ({
982
1030
  headers?: undefined;
983
1031
  body?: undefined;
984
1032
  auth?: undefined;
1033
+ flow?: undefined;
1034
+ shared?: undefined;
1035
+ items?: undefined;
1036
+ output?: undefined;
1037
+ };
1038
+ required: string[];
1039
+ };
1040
+ } | {
1041
+ name: string;
1042
+ description: string;
1043
+ parameters: {
1044
+ type: string;
1045
+ properties: {
1046
+ flow: {
1047
+ type: string;
1048
+ description: string;
1049
+ };
1050
+ shared: {
1051
+ type: string;
1052
+ description: string;
1053
+ };
1054
+ prompt?: undefined;
1055
+ model?: undefined;
1056
+ hfToken?: undefined;
1057
+ temperature?: undefined;
1058
+ max_new_tokens?: undefined;
1059
+ baseUrl?: undefined;
1060
+ action?: undefined;
1061
+ content?: undefined;
1062
+ query?: undefined;
1063
+ id?: undefined;
1064
+ metadata?: undefined;
1065
+ memoryPath?: undefined;
1066
+ embeddingModel?: undefined;
1067
+ embeddingBaseUrl?: undefined;
1068
+ topK?: undefined;
1069
+ text?: undefined;
1070
+ input?: undefined;
1071
+ transformFunction?: undefined;
1072
+ type?: undefined;
1073
+ selector?: undefined;
1074
+ jsonPath?: undefined;
1075
+ regex?: undefined;
1076
+ group?: undefined;
1077
+ code?: undefined;
1078
+ timeout?: undefined;
1079
+ args?: undefined;
1080
+ requireConfirmation?: undefined;
1081
+ apiKey?: undefined;
1082
+ cseId?: undefined;
1083
+ command?: undefined;
1084
+ filePath?: undefined;
1085
+ directoryPath?: undefined;
1086
+ url?: undefined;
1087
+ method?: undefined;
1088
+ headers?: undefined;
1089
+ body?: undefined;
1090
+ auth?: undefined;
1091
+ items?: undefined;
1092
+ output?: undefined;
1093
+ };
1094
+ required: string[];
1095
+ };
1096
+ } | {
1097
+ name: string;
1098
+ description: string;
1099
+ parameters: {
1100
+ type: string;
1101
+ properties: {
1102
+ items: {
1103
+ type: string;
1104
+ description: string;
1105
+ };
1106
+ flow: {
1107
+ type: string;
1108
+ description: string;
1109
+ };
1110
+ prompt?: undefined;
1111
+ model?: undefined;
1112
+ hfToken?: undefined;
1113
+ temperature?: undefined;
1114
+ max_new_tokens?: undefined;
1115
+ baseUrl?: undefined;
1116
+ action?: undefined;
1117
+ content?: undefined;
1118
+ query?: undefined;
1119
+ id?: undefined;
1120
+ metadata?: undefined;
1121
+ memoryPath?: undefined;
1122
+ embeddingModel?: undefined;
1123
+ embeddingBaseUrl?: undefined;
1124
+ topK?: undefined;
1125
+ text?: undefined;
1126
+ input?: undefined;
1127
+ transformFunction?: undefined;
1128
+ type?: undefined;
1129
+ selector?: undefined;
1130
+ jsonPath?: undefined;
1131
+ regex?: undefined;
1132
+ group?: undefined;
1133
+ code?: undefined;
1134
+ timeout?: undefined;
1135
+ args?: undefined;
1136
+ requireConfirmation?: undefined;
1137
+ apiKey?: undefined;
1138
+ cseId?: undefined;
1139
+ command?: undefined;
1140
+ filePath?: undefined;
1141
+ directoryPath?: undefined;
1142
+ url?: undefined;
1143
+ method?: undefined;
1144
+ headers?: undefined;
1145
+ body?: undefined;
1146
+ auth?: undefined;
1147
+ shared?: undefined;
985
1148
  output?: undefined;
986
1149
  };
987
1150
  required: string[];
@@ -1033,6 +1196,9 @@ export function getToolDefinitions(): ({
1033
1196
  headers?: undefined;
1034
1197
  body?: undefined;
1035
1198
  auth?: undefined;
1199
+ flow?: undefined;
1200
+ shared?: undefined;
1201
+ items?: undefined;
1036
1202
  };
1037
1203
  required: string[];
1038
1204
  };
@@ -443,6 +443,42 @@ export function getToolDefinitions() {
443
443
  required: ["prompt"]
444
444
  }
445
445
  },
446
+ {
447
+ name: "sub_flow",
448
+ description: "Executes a sub-flow.",
449
+ parameters: {
450
+ type: "object",
451
+ properties: {
452
+ flow: {
453
+ type: "string",
454
+ description: "The name of the flow to execute, as registered in the flow registry."
455
+ },
456
+ shared: {
457
+ type: "object",
458
+ description: "The shared object to pass to the sub-flow."
459
+ }
460
+ },
461
+ required: ["flow"]
462
+ }
463
+ },
464
+ {
465
+ name: "iterator",
466
+ description: "Iterates over a list of items and executes a sub-flow for each item.",
467
+ parameters: {
468
+ type: "object",
469
+ properties: {
470
+ items: {
471
+ type: "array",
472
+ description: "The list of items to iterate over."
473
+ },
474
+ flow: {
475
+ type: "string",
476
+ description: "The name of the flow to execute for each item, as registered in the flow registry."
477
+ }
478
+ },
479
+ required: ["items", "flow"]
480
+ }
481
+ },
446
482
  {
447
483
  name: "finish",
448
484
  description: "Call this tool when you have successfully achieved the goal or if you are unable to proceed further. This will end the agent's execution.",
@@ -3,10 +3,22 @@ import { UserInputNode } from './user.js';
3
3
  import { promises as fs } from 'fs';
4
4
  import path from 'path';
5
5
  import os from 'os';
6
+ import chalk from 'chalk';
6
7
  let nodeChildProcess = null;
7
8
  if (!process.versions.bun) {
8
9
  nodeChildProcess = require('child_process');
9
10
  }
11
+ function syntaxHighlight(code) {
12
+ return code
13
+ .replace(/\b(def|class|import|from|return|if|else|elif|for|while|with|try|except|finally|raise|assert|yield|lambda|pass|continue|break)\b/g, chalk.blue.bold('$1'))
14
+ .replace(/("""[\s\S]*?""")/g, chalk.hex('#6272a4').italic('$1'))
15
+ .replace(/('''[\s\S]*?''')/g, chalk.hex('#6272a4').italic('$1'))
16
+ .replace(/(".*?")/g, chalk.hex('#f1fa8c')('$1'))
17
+ .replace(/('.*?')/g, chalk.hex('#f1fa8c')('$1'))
18
+ .replace(/#.*/g, chalk.hex('#6272a4').italic('$&'))
19
+ .replace(/\b(True|False|None)\b/g, chalk.hex('#bd93f9').bold('$1'))
20
+ .replace(/\b(self|cls)\b/g, chalk.hex('#ffb86c').italic('$1'));
21
+ }
10
22
  export class CodeInterpreterNode extends AsyncNode {
11
23
  async execAsync() {
12
24
  const { code, timeout = 30000, args = [], requireConfirmation = true, interpreterPath } = this.params;
@@ -18,13 +30,12 @@ export class CodeInterpreterNode extends AsyncNode {
18
30
  const tempFilePath = path.join(tempDir, tempFileName);
19
31
  const interpreterCommand = interpreterPath || 'python';
20
32
  console.log(`[CodeInterpreter] Proposed execution: ${interpreterCommand} ${tempFilePath}`);
21
- console.log(`[CodeInterpreter] Code to execute:\n${code}`);
22
- // --- User Confirmation ---
23
- // --- User Confirmation ---
33
+ if (!requireConfirmation)
34
+ console.log(`[CodeInterpreter] Code to execute:\n${syntaxHighlight(code)}`);
24
35
  if (requireConfirmation) {
25
36
  const confirmNode = new UserInputNode();
26
37
  confirmNode.setParams({
27
- prompt: `The agent wants to execute the following Python code:\n${code}\nDo you approve? (yes/no): `
38
+ prompt: `The agent wants to execute the following Python code:\n${syntaxHighlight(code)}\nDo you approve? (yes/no): `
28
39
  });
29
40
  const confirmFlow = new AsyncFlow(confirmNode);
30
41
  const confirmation = await confirmFlow.runAsync({});
@@ -32,13 +43,11 @@ export class CodeInterpreterNode extends AsyncNode {
32
43
  throw new Error('Code execution denied by user.');
33
44
  }
34
45
  }
35
- // --- End User Confirmation ---
36
- // --- End User Confirmation ---
37
46
  try {
38
47
  await fs.writeFile(tempFilePath, code, 'utf-8');
39
48
  let stdout = '';
40
49
  let stderr = '';
41
- let exitCode = 1; // Default to failure
50
+ let exitCode = 1;
42
51
  const abortController = new AbortController();
43
52
  const timeoutId = setTimeout(() => abortController.abort(), timeout);
44
53
  try {
@@ -49,16 +58,15 @@ export class CodeInterpreterNode extends AsyncNode {
49
58
  stderr: 'pipe',
50
59
  signal: abortController.signal,
51
60
  });
52
- // Await stdout and stderr first
53
61
  stdout = await new Response(childProcess.stdout).text();
54
62
  stderr = await new Response(childProcess.stderr).text();
55
63
  const bunExitResult = await childProcess.exited;
56
64
  if (abortController.signal.aborted) {
57
65
  stderr += `\nExecution timed out after ${timeout}ms.`;
58
- exitCode = 1; // Indicate failure due to timeout
66
+ exitCode = 1;
59
67
  }
60
68
  else {
61
- exitCode = Number(bunExitResult !== null ? bunExitResult : 1); // Ensure exitCode is a number
69
+ exitCode = Number(bunExitResult !== null ? bunExitResult : 1);
62
70
  }
63
71
  }
64
72
  else if (nodeChildProcess) {
@@ -76,25 +84,23 @@ export class CodeInterpreterNode extends AsyncNode {
76
84
  });
77
85
  stdout = Buffer.concat(stdoutChunks).toString('utf-8');
78
86
  stderr = Buffer.concat(stderrChunks).toString('utf-8');
79
- exitCode = exitCodeFromClose !== null ? exitCodeFromClose : (signalFromClose ? 1 : 1); // If signal, treat as failure
87
+ exitCode = exitCodeFromClose !== null ? exitCodeFromClose : (signalFromClose ? 1 : 1);
80
88
  }
81
89
  else {
82
90
  throw new Error('Unsupported runtime environment.');
83
91
  }
84
92
  }
85
93
  catch (error) {
86
- if (error.name === "AbortError" || error.code === "ABORT_ERR") { // Handle AbortError for both Bun and Node
87
- stderr += `
88
- Execution timed out after ${timeout}ms.`;
89
- exitCode = 1; // Indicate failure due to timeout
94
+ if (error.name === "AbortError" || error.code === "ABORT_ERR") {
95
+ stderr += `\nExecution timed out after ${timeout}ms.`;
96
+ exitCode = 1;
90
97
  }
91
98
  else if (error.code === 'ENOENT') {
92
99
  stderr += `\nError: Command '${interpreterCommand}' not found. Please ensure it is installed and in your system's PATH.`;
93
100
  exitCode = 1;
94
101
  }
95
102
  else {
96
- stderr += `
97
- Error during execution: ${error.message}`;
103
+ stderr += `\nError during execution: ${error.message}`;
98
104
  exitCode = 1;
99
105
  }
100
106
  }
@@ -104,7 +110,6 @@ Error during execution: ${error.message}`;
104
110
  return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
105
111
  }
106
112
  finally {
107
- // Clean up temporary file
108
113
  await fs.unlink(tempFilePath).catch(e => console.error(`Failed to delete temp file ${tempFilePath}:`, e));
109
114
  }
110
115
  }
@@ -18,3 +18,5 @@ export * from "./embedding.js";
18
18
  export * from "./semantic_memory.js";
19
19
  export * from "./semantic_memory.js";
20
20
  export * from "../agent/agent.js";
21
+ export * from "./subflow.js";
22
+ export * from "./iterator.js";
@@ -18,3 +18,5 @@ export * from './embedding.js';
18
18
  export * from './semantic_memory.js';
19
19
  export * from './semantic_memory.js';
20
20
  export * from '../agent/agent.js';
21
+ export * from './subflow.js';
22
+ export * from './iterator.js';
@@ -0,0 +1,5 @@
1
+ export class IteratorNode extends AsyncNode {
2
+ execAsync(): Promise<any[]>;
3
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
4
+ }
5
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,23 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ export class IteratorNode extends AsyncNode {
3
+ async execAsync() {
4
+ const { items, flow } = this.params;
5
+ if (!items || !Array.isArray(items)) {
6
+ throw new Error('IteratorNode requires an `items` parameter of type Array.');
7
+ }
8
+ if (!flow || !(flow instanceof AsyncFlow)) {
9
+ throw new Error('IteratorNode requires a `flow` parameter of type AsyncFlow.');
10
+ }
11
+ const results = [];
12
+ for (const item of items) {
13
+ const subFlowShared = { item, params: this.params };
14
+ const result = await flow.runAsync(subFlowShared);
15
+ results.push(result);
16
+ }
17
+ return results;
18
+ }
19
+ async postAsync(shared, prepRes, execRes) {
20
+ shared.iteratorResult = execRes;
21
+ return 'default';
22
+ }
23
+ }
@@ -0,0 +1,5 @@
1
+ export class SubFlowNode extends AsyncNode {
2
+ execAsync(): Promise<any>;
3
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
4
+ }
5
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,16 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ export class SubFlowNode extends AsyncNode {
3
+ async execAsync() {
4
+ const { flow, shared } = this.params;
5
+ if (!flow || !(flow instanceof AsyncFlow)) {
6
+ throw new Error('SubFlowNode requires an `flow` parameter of type AsyncFlow.');
7
+ }
8
+ const subFlowShared = shared || {};
9
+ const result = await flow.runAsync(subFlowShared);
10
+ return result;
11
+ }
12
+ async postAsync(shared, prepRes, execRes) {
13
+ shared.subFlowResult = execRes;
14
+ return 'default';
15
+ }
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.24",
3
+ "version": "1.0.26",
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",
@@ -42,6 +42,7 @@
42
42
  },
43
43
  "homepage": "https://github.com/fractal-solutions/qflow#readme",
44
44
  "dependencies": {
45
+ "chalk": "^5.5.0",
45
46
  "cheerio": "^1.0.0-rc.12"
46
47
  },
47
48
  "devDependencies": {