@fractal-solutions/qflow 1.0.44 → 1.0.46

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.
@@ -23,6 +23,8 @@ export class AgentNode extends AsyncNode {
23
23
  if (!goal) {
24
24
  throw new Error("AgentNode requires a 'goal' parameter.");
25
25
  }
26
+ // Set the goal on the internal agent instance (RAORAgent in this case)
27
+ this.llmNode.setParams({ goal });
26
28
  this.conversationHistory = [
27
29
  { role: "system", content: this.getSystemPrompt() },
28
30
  { role: "user", content: `Goal: ${goal}` },
@@ -311,12 +313,13 @@ Begin!`;
311
313
  parallel: parsed.parallel || false,
312
314
  };
313
315
  }
316
+ else {
317
+ throw new Error("JSON is missing 'thought' or 'tool_calls' array.");
318
+ }
314
319
  }
315
320
  catch (e) {
316
- // Parsing failed, fall through to treat the original string as a thought.
321
+ throw new Error(`Invalid JSON format: ${e.message}. Content: ${jsonString}`);
317
322
  }
318
- // Fallback for plain text responses or malformed JSON.
319
- return { thought: llmResponse, toolCalls: [], parallel: false };
320
323
  }
321
324
  // This part of the function handles the case where llmResponse is an OBJECT,
322
325
  // typically from OpenAI's function calling API.
@@ -341,13 +344,16 @@ Begin!`;
341
344
  parallel: parsed.parallel || false,
342
345
  };
343
346
  }
347
+ else {
348
+ throw new Error("JSON in message.content is missing 'thought' or 'tool_calls' array.");
349
+ }
344
350
  }
345
351
  catch (e) {
346
- throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
352
+ throw new Error(`Invalid JSON in message.content: ${e.message}. Content: ${message.content}`);
347
353
  }
348
354
  }
349
355
  else if (typeof message.content === 'string') {
350
- return { thought: message.content, toolCalls: [], parallel: false };
356
+ throw new Error(`Expected JSON with 'thought' and 'tool_calls', but received plain string content: ${message.content}`);
351
357
  }
352
358
  }
353
359
  throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
@@ -0,0 +1,21 @@
1
+ export class BaseAgent extends AsyncNode {
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
3
+ llmNode: any;
4
+ availableTools: any;
5
+ summarizeLLM: any;
6
+ flowRegistry: {};
7
+ conversationHistory: any[];
8
+ maxSteps: number;
9
+ requireFinishConfirmation: boolean;
10
+ maxConversationHistoryTokens: number;
11
+ getSystemPrompt(): string;
12
+ getLLMAction(): Promise<any>;
13
+ manageConversationHistory(): Promise<void>;
14
+ parseLLMResponse(llmResponse: any): {
15
+ thought: any;
16
+ toolCalls: any;
17
+ parallel: any;
18
+ };
19
+ validateToolParameters(toolCall: any): string | null;
20
+ }
21
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,206 @@
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
+ }
@@ -0,0 +1,5 @@
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';
@@ -0,0 +1,178 @@
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
+ }
@@ -0,0 +1,5 @@
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';
@@ -0,0 +1,167 @@
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
+ }
@@ -0,0 +1,5 @@
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';