@fractal-solutions/qflow 1.0.83 → 2.0.0-canary.4

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 (114) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +21 -504
  3. package/MIGRATION.md +1130 -0
  4. package/README.md +1432 -823
  5. package/dist/agent/agent.d.ts +4 -22
  6. package/dist/agent/agent.js +4 -364
  7. package/dist/agent/base_agent.d.ts +8 -20
  8. package/dist/agent/base_agent.js +8 -205
  9. package/dist/agent/control_nodes.d.ts +61 -0
  10. package/dist/agent/control_nodes.js +164 -0
  11. package/dist/agent/engine.d.ts +45 -0
  12. package/dist/agent/engine.js +415 -0
  13. package/dist/agent/flow.d.ts +77 -0
  14. package/dist/agent/flow.js +148 -0
  15. package/dist/agent/index.d.ts +12 -0
  16. package/dist/agent/index.js +12 -0
  17. package/dist/agent/lpavrl_agent.d.ts +1 -2
  18. package/dist/agent/lpavrl_agent.js +2 -175
  19. package/dist/agent/ooda_agent.d.ts +1 -2
  20. package/dist/agent/ooda_agent.js +2 -164
  21. package/dist/agent/pema_agent.d.ts +1 -2
  22. package/dist/agent/pema_agent.js +2 -168
  23. package/dist/agent/raor_agent.d.ts +1 -2
  24. package/dist/agent/raor_agent.js +2 -161
  25. package/dist/agent/strategies.d.ts +126 -0
  26. package/dist/agent/strategies.js +159 -0
  27. package/dist/agent/tools.d.ts +1 -0
  28. package/dist/agent/tools.js +42 -24
  29. package/dist/approval.d.ts +42 -0
  30. package/dist/approval.js +86 -0
  31. package/dist/budget.d.ts +103 -0
  32. package/dist/budget.js +133 -0
  33. package/dist/bun_nodes.d.ts +119 -0
  34. package/dist/bun_nodes.js +331 -0
  35. package/dist/contracts.d.ts +30 -0
  36. package/dist/contracts.js +103 -0
  37. package/dist/durable.d.ts +278 -0
  38. package/dist/durable.js +730 -0
  39. package/dist/eval.d.ts +165 -0
  40. package/dist/eval.js +263 -0
  41. package/dist/graph.d.ts +157 -0
  42. package/dist/graph.js +330 -0
  43. package/dist/llm/index.d.ts +359 -0
  44. package/dist/llm/index.js +924 -0
  45. package/dist/logger.js +7 -3
  46. package/dist/mcp/client.d.ts +55 -0
  47. package/dist/mcp/client.js +145 -0
  48. package/dist/mcp/index.d.ts +2 -0
  49. package/dist/mcp/index.js +2 -0
  50. package/dist/mcp/server.d.ts +106 -0
  51. package/dist/mcp/server.js +154 -0
  52. package/dist/mcp/stdio.d.ts +2 -0
  53. package/dist/mcp/stdio.js +3 -0
  54. package/dist/memory.d.ts +101 -0
  55. package/dist/memory.js +217 -0
  56. package/dist/nodes/browser_control.js +5 -4
  57. package/dist/nodes/data_extractor.js +2 -1
  58. package/dist/nodes/data_validation.d.ts +3 -3
  59. package/dist/nodes/data_validation.js +19 -5
  60. package/dist/nodes/database.d.ts +2 -1
  61. package/dist/nodes/database.js +71 -58
  62. package/dist/nodes/gis.js +1 -1
  63. package/dist/nodes/git.d.ts +1 -1
  64. package/dist/nodes/git.js +65 -51
  65. package/dist/nodes/github.d.ts +1 -0
  66. package/dist/nodes/hardware_interaction.d.ts +2 -4
  67. package/dist/nodes/hardware_interaction.js +4 -3
  68. package/dist/nodes/http.d.ts +1 -7
  69. package/dist/nodes/http.js +46 -33
  70. package/dist/nodes/image_gallery.js +45 -45
  71. package/dist/nodes/index.d.ts +8 -0
  72. package/dist/nodes/index.js +8 -0
  73. package/dist/nodes/interactive_webview.d.ts +1 -2
  74. package/dist/nodes/interactive_webview.js +217 -216
  75. package/dist/nodes/multimedia_processing.js +1 -1
  76. package/dist/nodes/navigator.d.ts +7 -0
  77. package/dist/nodes/navigator.js +48 -8
  78. package/dist/nodes/pdf_processor.js +2 -1
  79. package/dist/nodes/remote_execution.js +2 -2
  80. package/dist/nodes/s3.d.ts +1 -0
  81. package/dist/nodes/scheduler.js +2 -2
  82. package/dist/nodes/search.d.ts +1 -1
  83. package/dist/nodes/search.js +3 -2
  84. package/dist/nodes/speech_synthesis.js +2 -1
  85. package/dist/nodes/spreadsheet.d.ts +1 -7
  86. package/dist/nodes/spreadsheet.js +2 -1
  87. package/dist/nodes/streaming_llm.d.ts +51 -0
  88. package/dist/nodes/streaming_llm.js +120 -0
  89. package/dist/nodes/webhook.d.ts +1 -5
  90. package/dist/nodes/webhook.js +106 -93
  91. package/dist/nodes/websockets.js +5 -3
  92. package/dist/nodes/webview.js +3 -2
  93. package/dist/optional.d.ts +32 -0
  94. package/dist/optional.js +61 -0
  95. package/dist/qflow.d.ts +25 -14
  96. package/dist/qflow.js +140 -49
  97. package/dist/schedule.d.ts +41 -0
  98. package/dist/schedule.js +149 -0
  99. package/dist/side_effects.d.ts +50 -0
  100. package/dist/side_effects.js +94 -0
  101. package/dist/streaming.d.ts +35 -0
  102. package/dist/streaming.js +199 -0
  103. package/dist/testing.d.ts +47 -0
  104. package/dist/testing.js +130 -0
  105. package/dist/tool_spec.d.ts +76 -0
  106. package/dist/tool_spec.js +321 -0
  107. package/dist/trace.d.ts +28 -0
  108. package/dist/trace.js +190 -0
  109. package/dist/util.d.ts +57 -0
  110. package/dist/util.js +122 -0
  111. package/package.json +153 -67
  112. package/qflow.config.js +18 -18
  113. package/scripts/postinstall.js +50 -0
  114. package/scripts/verify-package.js +114 -0
@@ -1,23 +1,5 @@
1
- export class AgentNode 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
- execAsync(): Promise<any>;
12
- validateToolParameters(toolCall: any): string | null;
13
- getSystemPrompt(): string;
14
- getLLMAction(): Promise<any>;
15
- manageConversationHistory(): Promise<void>;
16
- parseLLMResponse(llmResponse: any): {
17
- thought: any;
18
- toolCalls: any;
19
- parallel: any;
20
- };
21
- postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
1
+ /** The direct thought → action agent. */
2
+ export class AgentNode extends AgentEngine {
3
+ static strategyId: string;
22
4
  }
23
- import { AsyncNode } from '../qflow.js';
5
+ import { AgentEngine } from './engine.js';
@@ -1,365 +1,5 @@
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 AgentNode 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
- async execAsync() {
22
- const { goal } = this.params;
23
- if (!goal) {
24
- throw new Error("AgentNode requires a 'goal' parameter.");
25
- }
26
- // Set the goal on the internal agent instance (RAORAgent in this case)
27
- this.llmNode.setParams({ goal });
28
- this.conversationHistory = [
29
- { role: "system", content: this.getSystemPrompt() },
30
- { role: "user", content: `Goal: ${goal}` },
31
- { role: "system", content: "You are now at the 'Understand & Explore' phase. Analyze the user's request and the directory/codebase, then formulate a plan." }
32
- ];
33
- let step = 0;
34
- let finalOutput = null;
35
- while (step < this.maxSteps) {
36
- step++;
37
- logger.info(`Agent Step ${step}`);
38
- let llmResponse;
39
- try {
40
- llmResponse = await this.getLLMAction();
41
- }
42
- catch (e) {
43
- logger.error(`Error getting LLM action: ${e.message}`);
44
- this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
45
- continue;
46
- }
47
- let thought, toolCalls, parallel;
48
- try {
49
- const parsedResponse = this.parseLLMResponse(llmResponse);
50
- thought = parsedResponse.thought;
51
- toolCalls = parsedResponse.toolCalls;
52
- parallel = parsedResponse.parallel;
53
- logger.thought(thought);
54
- }
55
- catch (e) {
56
- logger.error(`Error parsing LLM response: ${e.message}`);
57
- this.conversationHistory.push({ role: "user", content: `Error: Your response was not valid JSON or did not follow the expected format. Please respond with a 'thought' and 'tool_calls' array. Error: ${e.message}. Your last response was: ${llmResponse}` });
58
- continue;
59
- }
60
- // Validate tool parameters for all tool calls
61
- const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
62
- if (validationErrors.length > 0) {
63
- const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
64
- logger.error(errorMessage);
65
- this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
66
- continue;
67
- }
68
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
69
- // If no tool calls, continue the loop to allow the LLM to re-evaluate
70
- if (toolCalls.length === 0) {
71
- this.conversationHistory.push({ role: "system", content: "Your last step resulted in no action. Re-evaluate your plan. If you are stuck, consider using a different tool or asking the user for clarification with the 'interactive_input'tool." });
72
- continue;
73
- }
74
- // Handle finish tool
75
- const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
76
- if (finishToolCall) {
77
- finalOutput = finishToolCall.parameters.output;
78
- if (this.requireFinishConfirmation) {
79
- const confirmNode = new UserInputNode();
80
- confirmNode.setParams({
81
- prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
82
- });
83
- const confirmFlow = new AsyncFlow(confirmNode);
84
- const confirmation = await confirmFlow.runAsync({});
85
- if (confirmation.toLowerCase() !== 'yes') {
86
- logger.info("Agent finish denied by user. User input will be the next prompt.");
87
- // Treat the user's new input as a new instruction/goal
88
- this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan (save to memory if available) and continue working.` });
89
- // Optionally, you might want to clear some of the previous conversation history
90
- // to give more weight to the new instruction, but be careful not to lose context.
91
- // For now, we'll just add the new instruction.
92
- continue; // Continue the loop
93
- }
94
- }
95
- logger.final(finalOutput);
96
- break;
97
- }
98
- try {
99
- const executeTool = async (toolCall) => {
100
- const toolInstance = this.availableTools[toolCall.tool];
101
- if (!toolInstance) {
102
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
103
- }
104
- let toolOutput;
105
- try {
106
- logger.toolCall(toolCall.tool, toolCall.parameters);
107
- // If the tool is a sub-flow, iterator or scheduler, look up the flow in the registry
108
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
109
- const flowName = toolCall.parameters.flow;
110
- if (!this.flowRegistry[flowName]) {
111
- throw new Error(`Flow '${flowName}' not found in registry.`);
112
- }
113
- toolCall.parameters.flow = this.flowRegistry[flowName];
114
- }
115
- toolInstance.setParams(toolCall.parameters);
116
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
117
- const toolFlow = new ToolFlowClass(toolInstance);
118
- if (toolInstance instanceof AsyncNode) {
119
- toolOutput = await toolFlow.runAsync({});
120
- }
121
- else {
122
- toolOutput = toolFlow.run({});
123
- }
124
- logger.toolResult(toolCall.tool, toolOutput);
125
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
126
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
127
- const summarizeNode = new SummarizeNode();
128
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
129
- const summarizeFlow = new AsyncFlow(summarizeNode);
130
- toolOutput = await summarizeFlow.runAsync({});
131
- logger.info(`Summarized to ${toolOutput.length} chars.`);
132
- }
133
- return toolOutput;
134
- }
135
- catch (e) {
136
- return `Error executing tool '${toolCall.tool}': ${e.message}`;
137
- }
138
- };
139
- let observations = [];
140
- if (parallel) {
141
- const results = await Promise.all(toolCalls.map(executeTool));
142
- observations = results.map((result, index) => ({
143
- tool: toolCalls[index].tool,
144
- parameters: toolCalls[index].parameters,
145
- output: result
146
- }));
147
- }
148
- else {
149
- for (const toolCall of toolCalls) {
150
- const result = await executeTool(toolCall);
151
- observations.push({
152
- tool: toolCall.tool,
153
- parameters: toolCall.parameters,
154
- output: result
155
- });
156
- }
157
- }
158
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
159
- }
160
- catch (e) {
161
- logger.error(`Error during tool execution: ${e.message}`);
162
- this.conversationHistory.push({ role: "user", content: `Error: Tool execution failed with message: ${e.message}. You should try a different approach.` });
163
- }
164
- this.conversationHistory.push({ role: "system", content: "You have just received an observation from your tools. Analyze the result and proceed to the next step in your plan. If the observation was an error, you must adjust your plan to fix the error." });
165
- }
166
- if (step >= this.maxSteps && finalOutput === null) {
167
- const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
168
- logger.error(message);
169
- finalOutput = message;
170
- }
171
- return finalOutput;
172
- }
173
- validateToolParameters(toolCall) {
174
- const toolDefinitions = getToolDefinitions();
175
- const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
176
- if (!toolSchema) {
177
- return `Tool '${toolCall.tool}' is not a recognized tool.`;
178
- }
179
- // If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
180
- if (toolCall.tool === "finish") {
181
- if (toolCall.parameters.output === undefined) {
182
- return "Missing required parameter: 'output' for tool 'finish'.";
183
- }
184
- return null;
185
- }
186
- else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
187
- if (toolCall.parameters.flow === undefined) {
188
- return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
189
- }
190
- if (!this.flowRegistry[toolCall.parameters.flow]) {
191
- return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
192
- }
193
- return null;
194
- }
195
- const requiredParams = toolSchema.parameters.required || [];
196
- for (const param of requiredParams) {
197
- if (toolCall.parameters[param] === undefined) {
198
- return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
199
- }
200
- }
201
- return null; // No validation errors
202
- }
203
- getSystemPrompt() {
204
- const toolDefinitions = getToolDefinitions();
205
- const toolDescriptions = toolDefinitions.map(tool => {
206
- const params = JSON.stringify(tool.parameters);
207
- return `### ${tool.name}: ${tool.description}
208
- Parameters: ${params}`;
209
- }).join('\n');
210
- 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- ')}` : "";
211
- return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
212
- 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.
213
- Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!
214
- 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.
215
- Remember to always seek user feedback often(interactive input or user input ifinteractive is missing), and notify the user of your progress(system notificaitons)
216
- 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.
217
-
218
-
219
- Available Tools:
220
- ${toolDescriptions}${flowRegistryDescription}
221
-
222
-
223
- Your response must be a single JSON object with 'thought' and 'tool_calls'.
224
-
225
- 'thought': Your reasoning and plan.
226
-
227
- '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.
228
-
229
-
230
- Example response:
231
- {
232
- "thought": "I need to search for information.",
233
- "tool_calls": [
234
- {
235
- "tool": "duckduckgo_search",
236
- "parameters": {
237
- "query": "latest AI research"
238
- }
239
- }
240
- ]
241
- }
242
-
243
-
244
- 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.
245
- If no tools are needed, return an empty 'tool_calls' array and reflect.
246
-
247
- **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.
248
- If new instructions are given after a finish proposal, treat them as your updated goal and update your memory.
249
- 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.
250
-
251
- Begin!`;
252
- }
253
- async getLLMAction() {
254
- await this.manageConversationHistory();
255
- this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
256
- const llmResult = await this.llmNode.runAsync({});
257
- return llmResult;
258
- }
259
- async manageConversationHistory() {
260
- if (!this.summarizeLLM) {
261
- logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
262
- return;
263
- }
264
- let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
265
- // Keep at least the system prompt and the initial goal
266
- const minHistoryLength = 2;
267
- while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
268
- logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
269
- // Summarize the oldest observation entry
270
- const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
271
- if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
272
- const observationContent = oldestEntry.content.substring("Observation:".length).trim();
273
- logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
274
- try {
275
- const summarizeNode = new SummarizeNode();
276
- summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
277
- const summarizeFlow = new AsyncFlow(summarizeNode);
278
- const summarizedContent = await summarizeFlow.runAsync({});
279
- // Replace the original observation with the summarized version
280
- this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
281
- logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
282
- }
283
- catch (e) {
284
- logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
285
- // If summarization fails, remove the oldest entry to prevent context overflow
286
- this.conversationHistory.splice(minHistoryLength, 1);
287
- }
288
- }
289
- else {
290
- logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
291
- // If it's not an observation or we can't summarize, just remove the oldest entry
292
- this.conversationHistory.splice(minHistoryLength, 1);
293
- }
294
- // Recalculate token count after modification
295
- currentTokenCount = JSON.stringify(this.conversationHistory).length;
296
- }
297
- }
298
- parseLLMResponse(llmResponse) {
299
- if (typeof llmResponse === 'string') {
300
- let jsonString = llmResponse;
301
- // Find the first '{' and the last '}' to isolate the JSON object
302
- const firstBrace = jsonString.indexOf('{');
303
- const lastBrace = jsonString.lastIndexOf('}');
304
- if (firstBrace !== -1 && lastBrace > firstBrace) {
305
- jsonString = jsonString.substring(firstBrace, lastBrace + 1);
306
- }
307
- try {
308
- const parsed = JSON.parse(jsonString);
309
- if (parsed.thought && Array.isArray(parsed.tool_calls)) {
310
- return {
311
- thought: parsed.thought,
312
- toolCalls: parsed.tool_calls,
313
- parallel: parsed.parallel || false,
314
- };
315
- }
316
- else {
317
- throw new Error("JSON is missing 'thought' or 'tool_calls' array.");
318
- }
319
- }
320
- catch (e) {
321
- throw new Error(`Invalid JSON format: ${e.message}. Content: ${jsonString}`);
322
- }
323
- }
324
- // This part of the function handles the case where llmResponse is an OBJECT,
325
- // typically from OpenAI's function calling API.
326
- const rawData = llmResponse;
327
- if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
328
- const message = rawData.choices[0].message;
329
- if (message.tool_calls && message.tool_calls.length > 0) {
330
- const toolCalls = message.tool_calls.map(tc => ({
331
- tool: tc.function.name,
332
- parameters: JSON.parse(tc.function.arguments)
333
- }));
334
- const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
335
- return { thought, toolCalls, parallel: false };
336
- }
337
- else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
338
- try {
339
- const parsed = JSON.parse(message.content);
340
- if (parsed.thought && Array.isArray(parsed.tool_calls)) {
341
- return {
342
- thought: parsed.thought,
343
- toolCalls: parsed.tool_calls,
344
- parallel: parsed.parallel || false,
345
- };
346
- }
347
- else {
348
- throw new Error("JSON in message.content is missing 'thought' or 'tool_calls' array.");
349
- }
350
- }
351
- catch (e) {
352
- throw new Error(`Invalid JSON in message.content: ${e.message}. Content: ${message.content}`);
353
- }
354
- }
355
- else if (typeof message.content === 'string') {
356
- throw new Error(`Expected JSON with 'thought' and 'tool_calls', but received plain string content: ${message.content}`);
357
- }
358
- }
359
- throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
360
- }
361
- async postAsync(shared, prepRes, execRes) {
362
- shared.agentOutput = execRes;
363
- return 'default';
364
- }
1
+ import { AgentEngine } from './engine.js';
2
+ /** The direct thought → action agent. */
3
+ export class AgentNode extends AgentEngine {
4
+ static strategyId = 'default';
365
5
  }
@@ -1,21 +1,9 @@
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;
1
+ /**
2
+ * Shared base for the named reasoning agents. New patterns should subclass
3
+ * this and set `strategyId` (or pass `strategy` in the options constructor).
4
+ */
5
+ export class BaseAgent extends AgentEngine {
6
+ static strategyId: string;
20
7
  }
21
- import { AsyncNode } from '../qflow.js';
8
+ export { AgentEngine };
9
+ import { AgentEngine } from './engine.js';
@@ -1,206 +1,9 @@
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
- }
1
+ import { AgentEngine } from './engine.js';
2
+ /**
3
+ * Shared base for the named reasoning agents. New patterns should subclass
4
+ * this and set `strategyId` (or pass `strategy` in the options constructor).
5
+ */
6
+ export class BaseAgent extends AgentEngine {
7
+ static strategyId = 'default';
206
8
  }
9
+ export { AgentEngine };