@fractal-solutions/qflow 1.0.62 → 1.0.64

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.
Files changed (199) hide show
  1. package/dist/agent/tools.d.ts +1 -5378
  2. package/dist/agent/tools.js +145 -1171
  3. package/dist/nodes/browser_control.d.ts +31 -0
  4. package/dist/nodes/browser_control.js +33 -0
  5. package/dist/nodes/code_interpreter.d.ts +29 -0
  6. package/dist/nodes/code_interpreter.js +29 -0
  7. package/dist/nodes/data_extractor.d.ts +35 -0
  8. package/dist/nodes/data_extractor.js +37 -0
  9. package/dist/nodes/data_validation.d.ts +27 -0
  10. package/dist/nodes/data_validation.js +29 -0
  11. package/dist/nodes/database.d.ts +44 -0
  12. package/dist/nodes/database.js +46 -0
  13. package/dist/nodes/display_image.d.ts +14 -0
  14. package/dist/nodes/display_image.js +16 -0
  15. package/dist/nodes/embedding.d.ts +22 -0
  16. package/dist/nodes/embedding.js +24 -0
  17. package/dist/nodes/filesystem.d.ts +64 -0
  18. package/dist/nodes/filesystem.js +72 -0
  19. package/dist/nodes/gis.d.ts +25 -0
  20. package/dist/nodes/gis.js +27 -0
  21. package/dist/nodes/git.d.ts +42 -0
  22. package/dist/nodes/git.js +44 -0
  23. package/dist/nodes/github.d.ts +56 -0
  24. package/dist/nodes/github.js +60 -0
  25. package/dist/nodes/hackernews.d.ts +28 -0
  26. package/dist/nodes/hackernews.js +32 -0
  27. package/dist/nodes/hardware_interaction.d.ts +31 -0
  28. package/dist/nodes/hardware_interaction.js +33 -0
  29. package/dist/nodes/http.d.ts +51 -0
  30. package/dist/nodes/http.js +53 -0
  31. package/dist/nodes/http_server.d.ts +37 -0
  32. package/dist/nodes/http_server.js +33 -0
  33. package/dist/nodes/image_gallery.d.ts +29 -0
  34. package/dist/nodes/image_gallery.js +29 -0
  35. package/dist/nodes/interactive_input.d.ts +22 -0
  36. package/dist/nodes/interactive_input.js +24 -0
  37. package/dist/nodes/interactive_webview.d.ts +59 -0
  38. package/dist/nodes/interactive_webview.js +59 -0
  39. package/dist/nodes/iterator.d.ts +18 -0
  40. package/dist/nodes/iterator.js +20 -0
  41. package/dist/nodes/llm.d.ts +142 -0
  42. package/dist/nodes/llm.js +152 -0
  43. package/dist/nodes/memory.d.ts +31 -0
  44. package/dist/nodes/memory.js +80 -38
  45. package/dist/nodes/multimedia_processing.d.ts +47 -0
  46. package/dist/nodes/multimedia_processing.js +49 -0
  47. package/dist/nodes/openrouter_llm.d.ts +30 -0
  48. package/dist/nodes/openrouter_llm.js +32 -0
  49. package/dist/nodes/pdf_processor.d.ts +39 -0
  50. package/dist/nodes/pdf_processor.js +37 -0
  51. package/dist/nodes/remote_execution.d.ts +47 -0
  52. package/dist/nodes/remote_execution.js +49 -0
  53. package/dist/nodes/s3.d.ts +67 -0
  54. package/dist/nodes/s3.js +69 -0
  55. package/dist/nodes/scheduler.d.ts +31 -0
  56. package/dist/nodes/scheduler.js +33 -0
  57. package/dist/nodes/search.d.ts +36 -0
  58. package/dist/nodes/search.js +40 -0
  59. package/dist/nodes/semantic_memory.d.ts +47 -0
  60. package/dist/nodes/semantic_memory.js +49 -0
  61. package/dist/nodes/shell.d.ts +14 -0
  62. package/dist/nodes/shell.js +16 -0
  63. package/dist/nodes/speech_synthesis.d.ts +27 -0
  64. package/dist/nodes/speech_synthesis.js +29 -0
  65. package/dist/nodes/spreadsheet.d.ts +51 -0
  66. package/dist/nodes/spreadsheet.js +53 -0
  67. package/dist/nodes/stripe.d.ts +44 -0
  68. package/dist/nodes/stripe.js +48 -0
  69. package/dist/nodes/subflow.d.ts +18 -0
  70. package/dist/nodes/subflow.js +20 -0
  71. package/dist/nodes/summarize.d.ts +14 -0
  72. package/dist/nodes/summarize.js +20 -0
  73. package/dist/nodes/system_notification.d.ts +22 -0
  74. package/dist/nodes/system_notification.js +24 -0
  75. package/dist/nodes/transform.d.ts +18 -0
  76. package/dist/nodes/transform.js +20 -0
  77. package/dist/nodes/user.d.ts +14 -0
  78. package/dist/nodes/user.js +16 -0
  79. package/dist/nodes/webhook.d.ts +34 -0
  80. package/dist/nodes/webhook.js +36 -0
  81. package/dist/nodes/webscraper.d.ts +14 -0
  82. package/dist/nodes/webscraper.js +16 -0
  83. package/dist/nodes/websockets.d.ts +23 -0
  84. package/dist/nodes/websockets.js +25 -0
  85. package/dist/nodes/webview.d.ts +26 -0
  86. package/dist/nodes/webview.js +28 -0
  87. package/package.json +3 -2
  88. package/dist/qflow.config.d.ts +0 -5
  89. package/dist/qflow.config.js +0 -16
  90. package/dist/src/agent/agent.d.ts +0 -23
  91. package/dist/src/agent/agent.js +0 -365
  92. package/dist/src/agent/base_agent.d.ts +0 -21
  93. package/dist/src/agent/base_agent.js +0 -206
  94. package/dist/src/agent/logger.d.ts +0 -9
  95. package/dist/src/agent/logger.js +0 -45
  96. package/dist/src/agent/lpavrl_agent.d.ts +0 -5
  97. package/dist/src/agent/lpavrl_agent.js +0 -178
  98. package/dist/src/agent/ooda_agent.d.ts +0 -5
  99. package/dist/src/agent/ooda_agent.js +0 -167
  100. package/dist/src/agent/pema_agent.d.ts +0 -5
  101. package/dist/src/agent/pema_agent.js +0 -171
  102. package/dist/src/agent/raor_agent.d.ts +0 -5
  103. package/dist/src/agent/raor_agent.js +0 -164
  104. package/dist/src/agent/tools.d.ts +0 -1
  105. package/dist/src/agent/tools.js +0 -148
  106. package/dist/src/logger.d.ts +0 -9
  107. package/dist/src/logger.js +0 -107
  108. package/dist/src/nodes/agent_llm.d.ts +0 -31
  109. package/dist/src/nodes/agent_llm.js +0 -302
  110. package/dist/src/nodes/browser_control.d.ts +0 -35
  111. package/dist/src/nodes/browser_control.js +0 -106
  112. package/dist/src/nodes/code_interpreter.d.ts +0 -38
  113. package/dist/src/nodes/code_interpreter.js +0 -150
  114. package/dist/src/nodes/data_extractor.d.ts +0 -40
  115. package/dist/src/nodes/data_extractor.js +0 -118
  116. package/dist/src/nodes/data_validation.d.ts +0 -36
  117. package/dist/src/nodes/data_validation.js +0 -77
  118. package/dist/src/nodes/database.d.ts +0 -50
  119. package/dist/src/nodes/database.js +0 -135
  120. package/dist/src/nodes/display_image.d.ts +0 -18
  121. package/dist/src/nodes/display_image.js +0 -63
  122. package/dist/src/nodes/embedding.d.ts +0 -29
  123. package/dist/src/nodes/embedding.js +0 -69
  124. package/dist/src/nodes/filesystem.d.ts +0 -105
  125. package/dist/src/nodes/filesystem.js +0 -160
  126. package/dist/src/nodes/gis.d.ts +0 -62
  127. package/dist/src/nodes/gis.js +0 -133
  128. package/dist/src/nodes/git.d.ts +0 -46
  129. package/dist/src/nodes/git.js +0 -99
  130. package/dist/src/nodes/github.d.ts +0 -83
  131. package/dist/src/nodes/github.js +0 -135
  132. package/dist/src/nodes/hackernews.d.ts +0 -47
  133. package/dist/src/nodes/hackernews.js +0 -79
  134. package/dist/src/nodes/hardware_interaction.d.ts +0 -39
  135. package/dist/src/nodes/hardware_interaction.js +0 -131
  136. package/dist/src/nodes/http.d.ts +0 -77
  137. package/dist/src/nodes/http.js +0 -120
  138. package/dist/src/nodes/http_server.d.ts +0 -54
  139. package/dist/src/nodes/http_server.js +0 -223
  140. package/dist/src/nodes/image_gallery.d.ts +0 -37
  141. package/dist/src/nodes/image_gallery.js +0 -129
  142. package/dist/src/nodes/index.d.ts +0 -48
  143. package/dist/src/nodes/index.js +0 -48
  144. package/dist/src/nodes/interactive_input.d.ts +0 -26
  145. package/dist/src/nodes/interactive_input.js +0 -95
  146. package/dist/src/nodes/interactive_webview.d.ts +0 -78
  147. package/dist/src/nodes/interactive_webview.js +0 -369
  148. package/dist/src/nodes/iterator.d.ts +0 -23
  149. package/dist/src/nodes/iterator.js +0 -43
  150. package/dist/src/nodes/llm.d.ts +0 -160
  151. package/dist/src/nodes/llm.js +0 -367
  152. package/dist/src/nodes/memory.d.ts +0 -43
  153. package/dist/src/nodes/memory.js +0 -90
  154. package/dist/src/nodes/multimedia_processing.d.ts +0 -57
  155. package/dist/src/nodes/multimedia_processing.js +0 -129
  156. package/dist/src/nodes/openrouter_llm.d.ts +0 -38
  157. package/dist/src/nodes/openrouter_llm.js +0 -156
  158. package/dist/src/nodes/pdf_processor.d.ts +0 -43
  159. package/dist/src/nodes/pdf_processor.js +0 -112
  160. package/dist/src/nodes/remote_execution.d.ts +0 -51
  161. package/dist/src/nodes/remote_execution.js +0 -132
  162. package/dist/src/nodes/s3.d.ts +0 -73
  163. package/dist/src/nodes/s3.js +0 -107
  164. package/dist/src/nodes/scheduler.d.ts +0 -51
  165. package/dist/src/nodes/scheduler.js +0 -131
  166. package/dist/src/nodes/search.d.ts +0 -61
  167. package/dist/src/nodes/search.js +0 -118
  168. package/dist/src/nodes/semantic_memory.d.ts +0 -64
  169. package/dist/src/nodes/semantic_memory.js +0 -160
  170. package/dist/src/nodes/shell.d.ts +0 -25
  171. package/dist/src/nodes/shell.js +0 -45
  172. package/dist/src/nodes/speech_synthesis.d.ts +0 -72
  173. package/dist/src/nodes/speech_synthesis.js +0 -171
  174. package/dist/src/nodes/spreadsheet.d.ts +0 -61
  175. package/dist/src/nodes/spreadsheet.js +0 -294
  176. package/dist/src/nodes/stripe.d.ts +0 -67
  177. package/dist/src/nodes/stripe.js +0 -117
  178. package/dist/src/nodes/subflow.d.ts +0 -23
  179. package/dist/src/nodes/subflow.js +0 -36
  180. package/dist/src/nodes/summarize.d.ts +0 -26
  181. package/dist/src/nodes/summarize.js +0 -51
  182. package/dist/src/nodes/system_notification.d.ts +0 -26
  183. package/dist/src/nodes/system_notification.js +0 -74
  184. package/dist/src/nodes/transform.d.ts +0 -23
  185. package/dist/src/nodes/transform.js +0 -52
  186. package/dist/src/nodes/user.d.ts +0 -25
  187. package/dist/src/nodes/user.js +0 -48
  188. package/dist/src/nodes/webhook.d.ts +0 -49
  189. package/dist/src/nodes/webhook.js +0 -161
  190. package/dist/src/nodes/webscraper.d.ts +0 -25
  191. package/dist/src/nodes/webscraper.js +0 -49
  192. package/dist/src/nodes/websockets.d.ts +0 -27
  193. package/dist/src/nodes/websockets.js +0 -98
  194. package/dist/src/nodes/webview.d.ts +0 -38
  195. package/dist/src/nodes/webview.js +0 -55
  196. package/dist/src/qflow.d.ts +0 -69
  197. package/dist/src/qflow.js +0 -320
  198. /package/dist/{src/types.d.ts → types.d.ts} +0 -0
  199. /package/dist/{src/types.js → types.js} +0 -0
@@ -1,206 +0,0 @@
1
- import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
2
- import { UserInputNode } from '../nodes';
3
- import { getToolDefinitions } from './tools.js';
4
- import { SummarizeNode } from '../nodes/summarize.js';
5
- import { logger } from './logger.js';
6
- export class BaseAgent extends AsyncNode {
7
- constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true, maxConversationHistoryTokens = 100000) {
8
- super();
9
- if (!llmNode) {
10
- throw new Error("AgentNode requires an LLMNode instance for reasoning.");
11
- }
12
- this.llmNode = llmNode;
13
- this.availableTools = availableTools;
14
- this.summarizeLLM = summarizeLLM;
15
- this.flowRegistry = flowRegistry;
16
- this.conversationHistory = [];
17
- this.maxSteps = 70;
18
- this.requireFinishConfirmation = requireFinishConfirmation;
19
- this.maxConversationHistoryTokens = maxConversationHistoryTokens;
20
- }
21
- getSystemPrompt() {
22
- const toolDefinitions = getToolDefinitions();
23
- const toolDescriptions = toolDefinitions.map(tool => {
24
- const params = JSON.stringify(tool.parameters);
25
- return `### ${tool.name}: ${tool.description}
26
- Parameters: ${params}`;
27
- }).join('\n');
28
- 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- ')}` : "";
29
- return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
30
- After expounding effectively out your initial plan, make a roadmap, save it in your memory through a memory node using either memory_node or semantic_memory_node (semantic preferred) tools and confirm to the user.
31
- Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!
32
- If you have a plan, you MUST include at least one tool call. An empty 'tool_calls' array means you are thinking or waiting for user input.
33
- Remember to always seek user feedback often(interactive input or user input ifinteractive is missing), and notify the user of your progress(system notificaitons)
34
- If the user asks about your capabilities or what tools you have, answer by summarizing the 'Available Tools' section of this prompt. Do not attempt to use a tool to answer such questions.
35
-
36
-
37
- Available Tools:
38
- ${toolDescriptions}${flowRegistryDescription}
39
-
40
-
41
- CRITICAL: Your response MUST be a single JSON object. Any deviation will be considered an error. DO NOT generate code, prose, or any other text outside of the JSON structure.
42
- Your response must be a single JSON object with 'thought' and 'tool_calls'.
43
-
44
- 'thought': Your reasoning and plan.
45
-
46
- 'tool_calls': An array of tool calls. Each tool call has 'tool' (name) and 'parameters' (object). Set 'parallel': true in the top-level JSON for parallel execution.
47
-
48
-
49
- Example response:
50
- {
51
- "thought": "I need to search for information.",
52
- "tool_calls": [
53
- {
54
- "tool": "duckduckgo_search",
55
- "parameters": {
56
- "query": "latest AI research"
57
- }
58
- }
59
- ]
60
- }
61
-
62
-
63
- When the user explicitly indicates they are done, use the 'finish' tool. Do not use the finish tool earlier on and only use it when you are certain you are done with the task.
64
- If no tools are needed, return an empty 'tool_calls' array and reflect.
65
-
66
- **IMPORTANT:** If you have a plan that requires action, you MUST include at least one tool call. An empty 'tool_calls' array means no action.
67
- If new instructions are given after a finish proposal, treat them as your updated goal and update your memory.
68
- Tell user how far you've gone using system notifications and KEEP THE USER INVOLVED using interactive input (or user input if interactive input not available) and OFTEN CHECK YOUR MEMORY to ensure alignmemt.
69
-
70
- Begin!`;
71
- }
72
- async getLLMAction() {
73
- await this.manageConversationHistory();
74
- this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
75
- const llmResult = await this.llmNode.runAsync({});
76
- return llmResult;
77
- }
78
- async manageConversationHistory() {
79
- if (!this.summarizeLLM) {
80
- logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
81
- return;
82
- }
83
- let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
84
- // Keep at least the system prompt and the initial goal
85
- const minHistoryLength = 2;
86
- while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
87
- logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
88
- // Summarize the oldest observation entry
89
- const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
90
- if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
91
- const observationContent = oldestEntry.content.substring("Observation:".length).trim();
92
- logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
93
- try {
94
- const summarizeNode = new SummarizeNode();
95
- summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
96
- const summarizeFlow = new AsyncFlow(summarizeNode);
97
- const summarizedContent = await summarizeFlow.runAsync({});
98
- // Replace the original observation with the summarized version
99
- this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
100
- logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
101
- }
102
- catch (e) {
103
- logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
104
- // If summarization fails, remove the oldest entry to prevent context overflow
105
- this.conversationHistory.splice(minHistoryLength, 1);
106
- }
107
- }
108
- else {
109
- logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
110
- // If it's not an observation or we can't summarize, just remove the oldest entry
111
- this.conversationHistory.splice(minHistoryLength, 1);
112
- }
113
- // Recalculate token count after modification
114
- currentTokenCount = JSON.stringify(this.conversationHistory).length;
115
- }
116
- }
117
- parseLLMResponse(llmResponse) {
118
- if (typeof llmResponse === 'string') {
119
- let jsonString = llmResponse;
120
- // Find the first '{' and the last '}' to isolate the JSON object
121
- const firstBrace = jsonString.indexOf('{');
122
- const lastBrace = jsonString.lastIndexOf('}');
123
- if (firstBrace !== -1 && lastBrace > firstBrace) {
124
- jsonString = jsonString.substring(firstBrace, lastBrace + 1);
125
- }
126
- try {
127
- const parsed = JSON.parse(jsonString);
128
- if (parsed.thought && Array.isArray(parsed.tool_calls)) {
129
- return {
130
- thought: parsed.thought,
131
- toolCalls: parsed.tool_calls,
132
- parallel: parsed.parallel || false,
133
- };
134
- }
135
- }
136
- catch (e) {
137
- // Parsing failed, fall through to treat the original string as a thought.
138
- }
139
- // Fallback for plain text responses or malformed JSON.
140
- return { thought: llmResponse, toolCalls: [], parallel: false };
141
- }
142
- // This part of the function handles the case where llmResponse is an OBJECT,
143
- // typically from OpenAI's function calling API.
144
- const rawData = llmResponse;
145
- if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
146
- const message = rawData.choices[0].message;
147
- if (message.tool_calls && message.tool_calls.length > 0) {
148
- const toolCalls = message.tool_calls.map(tc => ({
149
- tool: tc.function.name,
150
- parameters: JSON.parse(tc.function.arguments)
151
- }));
152
- const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
153
- return { thought, toolCalls, parallel: false };
154
- }
155
- else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
156
- try {
157
- const parsed = JSON.parse(message.content);
158
- if (parsed.thought && Array.isArray(parsed.tool_calls)) {
159
- return {
160
- thought: parsed.thought,
161
- toolCalls: parsed.tool_calls,
162
- parallel: parsed.parallel || false,
163
- };
164
- }
165
- }
166
- catch (e) {
167
- throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
168
- }
169
- }
170
- else if (typeof message.content === 'string') {
171
- return { thought: message.content, toolCalls: [], parallel: false };
172
- }
173
- }
174
- throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
175
- }
176
- validateToolParameters(toolCall) {
177
- const toolDefinitions = getToolDefinitions();
178
- const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
179
- if (!toolSchema) {
180
- return `Tool '${toolCall.tool}' is not a recognized tool.`;
181
- }
182
- // If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
183
- if (toolCall.tool === "finish") {
184
- if (toolCall.parameters.output === undefined) {
185
- return "Missing required parameter: 'output' for tool 'finish'.";
186
- }
187
- return null;
188
- }
189
- else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
190
- if (toolCall.parameters.flow === undefined) {
191
- return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
192
- }
193
- if (!this.flowRegistry[toolCall.parameters.flow]) {
194
- return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
195
- }
196
- return null;
197
- }
198
- const requiredParams = toolSchema.parameters.required || [];
199
- for (const param of requiredParams) {
200
- if (toolCall.parameters[param] === undefined) {
201
- return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
202
- }
203
- }
204
- return null; // No validation errors
205
- }
206
- }
@@ -1,9 +0,0 @@
1
- export namespace logger {
2
- function info(message: any): void;
3
- function warn(message: any): void;
4
- function thought(message: any): void;
5
- function toolCall(tool: any, params: any): void;
6
- function toolResult(tool: any, result: any): void;
7
- function error(message: any): void;
8
- function final(message: any): void;
9
- }
@@ -1,45 +0,0 @@
1
- const colors = {
2
- reset: "\x1b[0m",
3
- cyan: "\x1b[36m",
4
- yellow: "\x1b[33m",
5
- green: "\x1b[32m",
6
- magenta: "\x1b[35m",
7
- red: "\x1b[31m",
8
- grey: "\x1b[90m"
9
- };
10
- function colorize(text, color) {
11
- return `${color}${text}${colors.reset}`;
12
- }
13
- export const logger = {
14
- info: (message) => console.log(colorize(`[INFO] ${message}`, colors.cyan)),
15
- warn: (message) => console.log(colorize(`[WARN] ${message}`, colors.yellow)),
16
- thought: (message) => {
17
- console.log("---------------------");
18
- console.log(colorize("🤔 Thought", colors.yellow));
19
- console.log(colorize(message, colors.grey));
20
- console.log("---------------------");
21
- },
22
- toolCall: (tool, params) => {
23
- console.log(colorize("\n🛠️ Tool Call", colors.green));
24
- console.log(colorize(`Tool: ${tool}`, colors.magenta));
25
- console.log(colorize(`Params: ${JSON.stringify(params, null, 2)}`, colors.magenta));
26
- console.log("---------------------");
27
- },
28
- toolResult: (tool, result) => {
29
- console.log(colorize("\n✅ Tool Result", colors.green));
30
- console.log(colorize(`Tool: ${tool}`, colors.magenta));
31
- console.log(colorize(`Result: ${JSON.stringify(result, null, 2)}`, colors.grey));
32
- console.log("---------------------");
33
- },
34
- error: (message) => {
35
- console.log(colorize("\n❌ Error", colors.red));
36
- console.log(colorize(message, colors.red));
37
- console.log("---------------------");
38
- },
39
- final: (message) => {
40
- console.log("\n---------------------");
41
- console.log(colorize("🎉 Final Output", colors.yellow));
42
- console.log(colorize(message, colors.cyan));
43
- console.log("---------------------");
44
- }
45
- };
@@ -1,5 +0,0 @@
1
- export class LPAVRLAgent extends BaseAgent {
2
- execAsync(): Promise<any>;
3
- executeToolCalls(toolCalls: any, parallel: any): Promise<any[]>;
4
- }
5
- import { BaseAgent } from './base_agent.js';
@@ -1,178 +0,0 @@
1
- import { BaseAgent } from './base_agent.js';
2
- import { logger } from './logger.js';
3
- import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
4
- import { UserInputNode } from '../nodes/index.js';
5
- export class LPAVRLAgent extends BaseAgent {
6
- async execAsync() {
7
- const { goal } = this.params;
8
- if (!goal) {
9
- throw new Error("LPAVRLAgent requires a 'goal' parameter.");
10
- }
11
- this.conversationHistory = [
12
- { role: "system", content: this.getSystemPrompt() },
13
- { role: "user", content: `Goal: ${goal}` },
14
- ];
15
- let step = 0;
16
- let finalOutput = null;
17
- while (step < this.maxSteps) {
18
- step++;
19
- logger.info(`Agent Step ${step}`);
20
- // Listen
21
- this.conversationHistory.push({ role: "user", content: "Current Phase: LISTEN. Understand the user’s current request and context." });
22
- const listenResponse = await this.getLLMAction();
23
- const { thought: listenThought } = this.parseLLMResponse(listenResponse);
24
- logger.thought(listenThought);
25
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: listenThought }) });
26
- // Plan
27
- this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Break it into steps with rationale." });
28
- const planResponse = await this.getLLMAction();
29
- let parsedPlanResponse;
30
- try {
31
- parsedPlanResponse = this.parseLLMResponse(planResponse);
32
- }
33
- catch (e) {
34
- logger.error(`Error parsing LLM response in Plan phase: ${e.message}`);
35
- this.conversationHistory.push({ role: "user", content: `
36
- CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.\nError details: ${e.message}\nYour invalid response was: \n\`\`\`\n${planResponse}\n\`\`\`\nYou MUST respond with a single JSON object containing 'thought' and 'tool_calls'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.\n` });
37
- continue; // Re-run the loop to allow the LLM to correct itself
38
- }
39
- const { thought: planThought, toolCalls, parallel } = parsedPlanResponse;
40
- logger.thought(planThought);
41
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: planThought, tool_calls: toolCalls, parallel }) });
42
- // Validate tool parameters for all tool calls
43
- const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
44
- if (validationErrors.length > 0) {
45
- const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
46
- logger.error(errorMessage);
47
- this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
48
- continue; // Re-run the loop to allow the LLM to correct itself
49
- }
50
- // Handle finish tool (check here before acting)
51
- const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
52
- if (finishToolCall) {
53
- finalOutput = finishToolCall.parameters.output;
54
- if (this.requireFinishConfirmation) {
55
- const confirmNode = new UserInputNode();
56
- confirmNode.setParams({
57
- prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
58
- });
59
- const confirmFlow = new AsyncFlow(confirmNode);
60
- const confirmation = await confirmFlow.runAsync({});
61
- if (confirmation.toLowerCase() !== 'yes') {
62
- logger.info("Agent finish denied by user. User input will be the next prompt.");
63
- this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
64
- continue; // Continue the loop
65
- }
66
- }
67
- logger.final(finalOutput);
68
- break; // Exit the main loop as agent is finished
69
- }
70
- // If no tool calls and not trying to finish, prompt LLM to generate tool calls
71
- if (toolCalls.length === 0) {
72
- this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
73
- continue; // Re-run the loop to force tool call generation
74
- }
75
- // Act
76
- const observations = await this.executeToolCalls(toolCalls, parallel);
77
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
78
- // Check for tool errors and add specific instructions for reflection
79
- const toolErrors = observations.filter(obs => obs.success === false);
80
- if (toolErrors.length > 0) {
81
- const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
82
- this.conversationHistory.push({ role: "system", content: `
83
- IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
84
- ${errorMessages}
85
-
86
- Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal.
87
- ` });
88
- }
89
- else {
90
- // Visualize
91
- this.conversationHistory.push({ role: "user", content: "Current Phase: VISUALIZE. Present progress or results in an understandable form." });
92
- }
93
- const visualizeResponse = await this.getLLMAction();
94
- const { thought: visualizeThought } = this.parseLLMResponse(visualizeResponse);
95
- logger.thought(visualizeThought);
96
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: visualizeThought }) });
97
- // Reflect
98
- this.conversationHistory.push({ role: "user", content: "Current Phase: REFLECT. Judge results and align with the original intent." });
99
- const reflectResponse = await this.getLLMAction();
100
- const { thought: reflectThought } = this.parseLLMResponse(reflectResponse);
101
- logger.thought(reflectThought);
102
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: reflectThought }) });
103
- // Learn
104
- this.conversationHistory.push({ role: "user", content: "Current Phase: LEARN. Update knowledge or strategy for future tasks." });
105
- const learnResponse = await this.getLLMAction();
106
- const { thought: learnThought } = this.parseLLMResponse(learnResponse);
107
- logger.thought(learnThought);
108
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: learnThought }) });
109
- }
110
- if (step >= this.maxSteps && finalOutput === null) {
111
- const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
112
- logger.error(message);
113
- finalOutput = message;
114
- }
115
- return finalOutput;
116
- }
117
- async executeToolCalls(toolCalls, parallel) {
118
- const executeTool = async (toolCall) => {
119
- const toolInstance = this.availableTools[toolCall.tool];
120
- if (!toolInstance) {
121
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
122
- }
123
- let toolOutput;
124
- try {
125
- logger.toolCall(toolCall.tool, toolCall.parameters);
126
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
127
- const flowName = toolCall.parameters.flow;
128
- if (!this.flowRegistry[flowName]) {
129
- throw new Error(`Flow '${flowName}' not found in registry.`);
130
- }
131
- toolCall.parameters.flow = this.flowRegistry[flowName];
132
- }
133
- toolInstance.setParams(toolCall.parameters);
134
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
135
- const toolFlow = new ToolFlowClass(toolInstance);
136
- if (toolInstance instanceof AsyncNode) {
137
- toolOutput = await toolFlow.runAsync({});
138
- }
139
- else {
140
- toolOutput = toolFlow.run({});
141
- }
142
- logger.toolResult(toolCall.tool, toolOutput);
143
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
144
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
145
- const summarizeNode = new SummarizeNode();
146
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
147
- const summarizeFlow = new AsyncFlow(summarizeNode);
148
- toolOutput = await summarizeFlow.runAsync({});
149
- logger.info(`Summarized to ${toolOutput.length} chars.`);
150
- }
151
- return { success: true, output: toolOutput };
152
- }
153
- catch (e) {
154
- return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
155
- }
156
- };
157
- let observations = [];
158
- if (parallel) {
159
- const results = await Promise.all(toolCalls.map(executeTool));
160
- observations = results.map((result, index) => ({
161
- tool: toolCalls[index].tool,
162
- parameters: toolCalls[index].parameters,
163
- ...result // Spread success/error and output/error
164
- }));
165
- }
166
- else {
167
- for (const toolCall of toolCalls) {
168
- const result = await executeTool(toolCall);
169
- observations.push({
170
- tool: toolCall.tool,
171
- parameters: toolCall.parameters,
172
- ...result // Spread success/error and output/error
173
- });
174
- }
175
- }
176
- return observations;
177
- }
178
- }
@@ -1,5 +0,0 @@
1
- export class OODAAgent extends BaseAgent {
2
- execAsync(): Promise<any>;
3
- executeToolCalls(toolCalls: any, parallel: any): Promise<any[]>;
4
- }
5
- import { BaseAgent } from './base_agent.js';
@@ -1,167 +0,0 @@
1
- import { BaseAgent } from './base_agent.js';
2
- import { logger } from './logger.js';
3
- import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
4
- import { UserInputNode } from '../nodes/index.js';
5
- export class OODAAgent extends BaseAgent {
6
- async execAsync() {
7
- const { goal } = this.params;
8
- if (!goal) {
9
- throw new Error("OODAAgent requires a 'goal' parameter.");
10
- }
11
- this.conversationHistory = [
12
- { role: "system", content: this.getSystemPrompt() },
13
- { role: "user", content: `Goal: ${goal}` },
14
- ];
15
- let step = 0;
16
- let finalOutput = null;
17
- while (step < this.maxSteps) {
18
- step++;
19
- logger.info(`Agent Step ${step}`);
20
- // Observe
21
- this.conversationHistory.push({ role: "user", content: "Current Phase: OBSERVE. Summarize the latest data from the environment." });
22
- const observeResponse = await this.getLLMAction();
23
- const { thought: observeThought } = this.parseLLMResponse(observeResponse);
24
- logger.thought(observeThought);
25
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: observeThought }) });
26
- // Orient
27
- this.conversationHistory.push({ role: "user", content: "Current Phase: ORIENT. Interpret data in context of history and goal." });
28
- const orientResponse = await this.getLLMAction();
29
- const { thought: orientThought } = this.parseLLMResponse(orientResponse);
30
- logger.thought(orientThought);
31
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: orientThought }) });
32
- // Decide
33
- this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. Select the best action now." });
34
- const decideResponse = await this.getLLMAction();
35
- let parsedDecideResponse;
36
- try {
37
- parsedDecideResponse = this.parseLLMResponse(decideResponse);
38
- }
39
- catch (e) {
40
- logger.error(`Error parsing LLM response in Decide phase: ${e.message}`);
41
- this.conversationHistory.push({ role: "user", content: `
42
- CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.\nError details: ${e.message}\nYour invalid response was: \n\`\`\`\n${decideResponse}\n\`\`\`\nYou MUST respond with a single JSON object containing \'thought\' and \'tool_calls\'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.\n` });
43
- continue; // Re-run the loop to allow the LLM to correct itself
44
- }
45
- const { thought: decideThought, toolCalls, parallel } = parsedDecideResponse;
46
- logger.thought(decideThought);
47
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: decideThought, tool_calls: toolCalls, parallel }) });
48
- // Validate tool parameters for all tool calls
49
- const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
50
- if (validationErrors.length > 0) {
51
- const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
52
- logger.error(errorMessage);
53
- this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
54
- continue; // Re-run the loop to allow the LLM to correct itself
55
- }
56
- // Handle finish tool (check here before acting)
57
- const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
58
- if (finishToolCall) {
59
- finalOutput = finishToolCall.parameters.output;
60
- if (this.requireFinishConfirmation) {
61
- const confirmNode = new UserInputNode();
62
- confirmNode.setParams({
63
- prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
64
- });
65
- const confirmFlow = new AsyncFlow(confirmNode);
66
- const confirmation = await confirmFlow.runAsync({});
67
- if (confirmation.toLowerCase() !== 'yes') {
68
- logger.info("Agent finish denied by user. User input will be the next prompt.");
69
- this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
70
- continue; // Continue the loop
71
- }
72
- }
73
- logger.final(finalOutput);
74
- break; // Exit the main loop as agent is finished
75
- }
76
- // If no tool calls and not trying to finish, prompt LLM to generate tool calls
77
- if (toolCalls.length === 0) {
78
- this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
79
- continue; // Re-run the loop to force tool call generation
80
- }
81
- // Act
82
- const observations = await this.executeToolCalls(toolCalls, parallel);
83
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
84
- // Check for tool errors and add specific instructions for reflection
85
- const toolErrors = observations.filter(obs => obs.success === false);
86
- if (toolErrors.length > 0) {
87
- const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
88
- this.conversationHistory.push({ role: "system", content: `
89
- IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
90
- ${errorMessages}
91
-
92
- Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal.
93
- ` });
94
- }
95
- else {
96
- // No specific reflect phase for OODA after act, it loops back to observe
97
- }
98
- }
99
- if (step >= this.maxSteps && finalOutput === null) {
100
- const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
101
- logger.error(message);
102
- finalOutput = message;
103
- }
104
- return finalOutput;
105
- }
106
- async executeToolCalls(toolCalls, parallel) {
107
- const executeTool = async (toolCall) => {
108
- const toolInstance = this.availableTools[toolCall.tool];
109
- if (!toolInstance) {
110
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
111
- }
112
- let toolOutput;
113
- try {
114
- logger.toolCall(toolCall.tool, toolCall.parameters);
115
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
116
- const flowName = toolCall.parameters.flow;
117
- if (!this.flowRegistry[flowName]) {
118
- throw new Error(`Flow '${flowName}' not found in registry.`);
119
- }
120
- toolCall.parameters.flow = this.flowRegistry[flowName];
121
- }
122
- toolInstance.setParams(toolCall.parameters);
123
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
124
- const toolFlow = new ToolFlowClass(toolInstance);
125
- if (toolInstance instanceof AsyncNode) {
126
- toolOutput = await toolFlow.runAsync({});
127
- }
128
- else {
129
- toolOutput = toolFlow.run({});
130
- }
131
- logger.toolResult(toolCall.tool, toolOutput);
132
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
133
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
134
- const summarizeNode = new SummarizeNode();
135
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
136
- const summarizeFlow = new AsyncFlow(summarizeNode);
137
- toolOutput = await summarizeFlow.runAsync({});
138
- logger.info(`Summarized to ${toolOutput.length} chars.`);
139
- }
140
- return { success: true, output: toolOutput };
141
- }
142
- catch (e) {
143
- return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
144
- }
145
- };
146
- let observations = [];
147
- if (parallel) {
148
- const results = await Promise.all(toolCalls.map(executeTool));
149
- observations = results.map((result, index) => ({
150
- tool: toolCalls[index].tool,
151
- parameters: toolCalls[index].parameters,
152
- ...result // Spread success/error and output/error
153
- }));
154
- }
155
- else {
156
- for (const toolCall of toolCalls) {
157
- const result = await executeTool(toolCall);
158
- observations.push({
159
- tool: toolCall.tool,
160
- parameters: toolCall.parameters,
161
- ...result // Spread success/error and output/error
162
- });
163
- }
164
- }
165
- return observations;
166
- }
167
- }
@@ -1,5 +0,0 @@
1
- export class PEMAAgent extends BaseAgent {
2
- execAsync(): Promise<any>;
3
- executeToolCalls(toolCalls: any, parallel: any): Promise<any[]>;
4
- }
5
- import { BaseAgent } from './base_agent.js';