@fractal-solutions/qflow 1.0.84 → 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,171 +1,5 @@
1
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';
2
+ /** Plan → Execute → Monitor → Adjust. */
5
3
  export class PEMAAgent extends BaseAgent {
6
- async execAsync() {
7
- const { goal } = this.params;
8
- if (!goal) {
9
- throw new Error("PEMAAgent 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
- // Plan
21
- this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Define actions needed to reach the goal." });
22
- const planResponse = await this.getLLMAction();
23
- let parsedPlanResponse;
24
- try {
25
- parsedPlanResponse = this.parseLLMResponse(planResponse);
26
- }
27
- catch (e) {
28
- logger.error(`Error parsing LLM response in Plan phase: ${e.message}`);
29
- this.conversationHistory.push({ role: "user", content: `
30
- 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` });
31
- continue; // Re-run the loop to allow the LLM to correct itself
32
- }
33
- const { thought: planThought, toolCalls, parallel } = parsedPlanResponse;
34
- logger.thought(planThought);
35
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: planThought, tool_calls: toolCalls, parallel }) });
36
- // Validate tool parameters for all tool calls
37
- const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
38
- if (validationErrors.length > 0) {
39
- const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
40
- logger.error(errorMessage);
41
- this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
42
- continue; // Re-run the loop to allow the LLM to correct itself
43
- }
44
- // Handle finish tool (check here before acting)
45
- const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
46
- if (finishToolCall) {
47
- finalOutput = finishToolCall.parameters.output;
48
- if (this.requireFinishConfirmation) {
49
- const confirmNode = new UserInputNode();
50
- confirmNode.setParams({
51
- prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
52
- });
53
- const confirmFlow = new AsyncFlow(confirmNode);
54
- const confirmation = await confirmFlow.runAsync({});
55
- if (confirmation.toLowerCase() !== 'yes') {
56
- logger.info("Agent finish denied by user. User input will be the next prompt.");
57
- this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
58
- continue; // Continue the loop
59
- }
60
- }
61
- logger.final(finalOutput);
62
- break; // Exit the main loop as agent is finished
63
- }
64
- // If no tool calls and not trying to finish, prompt LLM to generate tool calls
65
- if (toolCalls.length === 0) {
66
- 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." });
67
- continue; // Re-run the loop to force tool call generation
68
- }
69
- // Execute
70
- const observations = await this.executeToolCalls(toolCalls, parallel);
71
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
72
- // Check for tool errors and add specific instructions for reflection
73
- const toolErrors = observations.filter(obs => obs.success === false);
74
- if (toolErrors.length > 0) {
75
- const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
76
- this.conversationHistory.push({ role: "system", content: `
77
- IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
78
- ${errorMessages}
79
-
80
- 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.
81
- ` });
82
- }
83
- else {
84
- // Monitor
85
- this.conversationHistory.push({ role: "user", content: "Current Phase: MONITOR. Check current status against the plan." });
86
- }
87
- const monitorResponse = await this.getLLMAction();
88
- const { thought: monitorThought } = this.parseLLMResponse(monitorResponse);
89
- logger.thought(monitorThought);
90
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: monitorThought }) });
91
- // Adjust
92
- this.conversationHistory.push({ role: "user", content: "Current Phase: ADJUST. Modify the plan if deviations are detected." });
93
- const adjustResponse = await this.getLLMAction();
94
- const { thought: adjustThought } = this.parseLLMResponse(adjustResponse);
95
- logger.thought(adjustThought);
96
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: adjustThought }) });
97
- if (finishToolCall) {
98
- finalOutput = finishToolCall.parameters.output;
99
- logger.final(finalOutput);
100
- break;
101
- }
102
- }
103
- if (step >= this.maxSteps && finalOutput === null) {
104
- const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
105
- logger.error(message);
106
- finalOutput = message;
107
- }
108
- return finalOutput;
109
- }
110
- async executeToolCalls(toolCalls, parallel) {
111
- const executeTool = async (toolCall) => {
112
- const toolInstance = this.availableTools[toolCall.tool];
113
- if (!toolInstance) {
114
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
115
- }
116
- let toolOutput;
117
- try {
118
- logger.toolCall(toolCall.tool, toolCall.parameters);
119
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
120
- const flowName = toolCall.parameters.flow;
121
- if (!this.flowRegistry[flowName]) {
122
- throw new Error(`Flow '${flowName}' not found in registry.`);
123
- }
124
- toolCall.parameters.flow = this.flowRegistry[flowName];
125
- }
126
- toolInstance.setParams(toolCall.parameters);
127
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
128
- const toolFlow = new ToolFlowClass(toolInstance);
129
- if (toolInstance instanceof AsyncNode) {
130
- toolOutput = await toolFlow.runAsync({});
131
- }
132
- else {
133
- toolOutput = toolFlow.run({});
134
- }
135
- logger.toolResult(toolCall.tool, toolOutput);
136
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
137
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
138
- const summarizeNode = new SummarizeNode();
139
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
140
- const summarizeFlow = new AsyncFlow(summarizeNode);
141
- toolOutput = await summarizeFlow.runAsync({});
142
- logger.info(`Summarized to ${toolOutput.length} chars.`);
143
- }
144
- return { success: true, output: toolOutput };
145
- }
146
- catch (e) {
147
- return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
148
- }
149
- };
150
- let observations = [];
151
- if (parallel) {
152
- const results = await Promise.all(toolCalls.map(executeTool));
153
- observations = results.map((result, index) => ({
154
- tool: toolCalls[index].tool,
155
- parameters: toolCalls[index].parameters,
156
- ...result // Spread success/error and output/error
157
- }));
158
- }
159
- else {
160
- for (const toolCall of toolCalls) {
161
- const result = await executeTool(toolCall);
162
- observations.push({
163
- tool: toolCall.tool,
164
- parameters: toolCall.parameters,
165
- ...result // Spread success/error and output/error
166
- });
167
- }
168
- }
169
- return observations;
170
- }
4
+ static strategyId = 'pema';
171
5
  }
@@ -1,5 +1,4 @@
1
+ /** Reason → Act → Reflect. */
1
2
  export class RAORAgent extends BaseAgent {
2
- execAsync(): Promise<any>;
3
- executeToolCalls(toolCalls: any, parallel: any): Promise<any[]>;
4
3
  }
5
4
  import { BaseAgent } from './base_agent.js';
@@ -1,164 +1,5 @@
1
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';
2
+ /** Reason → Act → Reflect. */
5
3
  export class RAORAgent extends BaseAgent {
6
- async execAsync() {
7
- const { goal } = this.params;
8
- if (!goal) {
9
- throw new Error("RAORAgent 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
- // Reason
21
- this.conversationHistory.push({ role: "user", content: "Current Phase: REASON. Analyze the user's request and formulate a plan." });
22
- const reasonResponse = await this.getLLMAction();
23
- let parsedReasonResponse;
24
- try {
25
- parsedReasonResponse = this.parseLLMResponse(reasonResponse);
26
- }
27
- catch (e) {
28
- logger.error(`Error parsing LLM response in Reason phase: ${e.message}`);
29
- this.conversationHistory.push({ role: "user", content: `
30
- CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.
31
- Error details: ${e.message}
32
- Your invalid response was:
33
- '''${reasonResponse}'''
34
- You 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.
35
- ` });
36
- continue; // Re-run the loop to allow the LLM to correct itself
37
- }
38
- const { thought, toolCalls, parallel } = parsedReasonResponse;
39
- logger.thought(thought);
40
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
41
- // Validate tool parameters for all tool calls
42
- const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
43
- if (validationErrors.length > 0) {
44
- const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
45
- logger.error(errorMessage);
46
- this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
47
- continue; // Re-run the loop to allow the LLM to correct itself
48
- }
49
- // Handle finish tool (check here before acting)
50
- const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
51
- if (finishToolCall) {
52
- finalOutput = finishToolCall.parameters.output;
53
- if (this.requireFinishConfirmation) {
54
- const confirmNode = new UserInputNode();
55
- confirmNode.setParams({
56
- prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
57
- });
58
- const confirmFlow = new AsyncFlow(confirmNode);
59
- const confirmation = await confirmFlow.runAsync({});
60
- if (confirmation.toLowerCase() !== 'yes') {
61
- logger.info("Agent finish denied by user. User input will be the next prompt.");
62
- this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
63
- continue; // Continue the loop
64
- }
65
- }
66
- logger.final(finalOutput);
67
- break; // Exit the main loop as agent is finished
68
- }
69
- // If no tool calls and not trying to finish, prompt LLM to generate tool calls
70
- if (toolCalls.length === 0) {
71
- this.conversationHistory.push({ role: "user", content: "Current Phase: REASON. 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." });
72
- continue; // Re-run the loop to force tool call generation
73
- }
74
- // Act
75
- const observations = await this.executeToolCalls(toolCalls, parallel);
76
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
77
- // Check for tool errors and add specific instructions for reflection
78
- const toolErrors = observations.filter(obs => obs.success === false);
79
- if (toolErrors.length > 0) {
80
- const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
81
- this.conversationHistory.push({ role: "system", content: `
82
- IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
83
- ${errorMessages}
84
-
85
- 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. If you are stuck, consider using the 'user_input' or 'interactive_input' tool to ask the user for clarification.
86
- ` });
87
- }
88
- else {
89
- this.conversationHistory.push({ role: "user", content: "Current Phase: REFLECT. Evaluate if the result moves toward the goal and adjust plan if needed." });
90
- }
91
- const reflectResponse = await this.getLLMAction();
92
- const { thought: reflectThought } = this.parseLLMResponse(reflectResponse);
93
- logger.thought(reflectThought);
94
- this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: reflectThought }) });
95
- }
96
- if (step >= this.maxSteps && finalOutput === null) {
97
- const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
98
- logger.error(message);
99
- finalOutput = message;
100
- }
101
- return finalOutput;
102
- }
103
- async executeToolCalls(toolCalls, parallel) {
104
- const executeTool = async (toolCall) => {
105
- const toolInstance = this.availableTools[toolCall.tool];
106
- if (!toolInstance) {
107
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
108
- }
109
- let toolOutput;
110
- try {
111
- logger.toolCall(toolCall.tool, toolCall.parameters);
112
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
113
- const flowName = toolCall.parameters.flow;
114
- if (!this.flowRegistry[flowName]) {
115
- throw new Error(`Flow '${flowName}' not found in registry.`);
116
- }
117
- toolCall.parameters.flow = this.flowRegistry[flowName];
118
- }
119
- toolInstance.setParams(toolCall.parameters);
120
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
121
- const toolFlow = new ToolFlowClass(toolInstance);
122
- if (toolInstance instanceof AsyncNode) {
123
- toolOutput = await toolFlow.runAsync({});
124
- }
125
- else {
126
- toolOutput = toolFlow.run({});
127
- }
128
- logger.toolResult(toolCall.tool, toolOutput);
129
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
130
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
131
- const summarizeNode = new SummarizeNode();
132
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
133
- const summarizeFlow = new AsyncFlow(summarizeNode);
134
- toolOutput = await summarizeFlow.runAsync({});
135
- logger.info(`Summarized to ${toolOutput.length} chars.`);
136
- }
137
- return { success: true, output: toolOutput };
138
- }
139
- catch (e) {
140
- return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
141
- }
142
- };
143
- let observations = [];
144
- if (parallel) {
145
- const results = await Promise.all(toolCalls.map(executeTool));
146
- observations = results.map((result, index) => ({
147
- tool: toolCalls[index].tool,
148
- parameters: toolCalls[index].parameters,
149
- ...result // Spread success/error and output/error
150
- }));
151
- }
152
- else {
153
- for (const toolCall of toolCalls) {
154
- const result = await executeTool(toolCall);
155
- observations.push({
156
- tool: toolCall.tool,
157
- parameters: toolCall.parameters,
158
- ...result // Spread success/error and output/error
159
- });
160
- }
161
- }
162
- return observations;
163
- }
4
+ static strategyId = 'raor';
164
5
  }
@@ -0,0 +1,126 @@
1
+ export function getStrategy(id?: string): any;
2
+ export function listStrategies(): {
3
+ id: string;
4
+ label: string;
5
+ }[];
6
+ export namespace agentStrategies {
7
+ namespace _default {
8
+ export let id: string;
9
+ export let label: string;
10
+ export let strictParsing: boolean;
11
+ export let initialMessages: {
12
+ role: string;
13
+ content: string;
14
+ }[];
15
+ export let phases: {
16
+ kind: string;
17
+ }[];
18
+ export let postPhases: never[];
19
+ export let afterTools: string;
20
+ export function noToolCallsPrompt(): string;
21
+ export { toolErrorPrompt as onToolError };
22
+ }
23
+ export { _default as default };
24
+ export namespace raor {
25
+ let id_1: string;
26
+ export { id_1 as id };
27
+ let label_1: string;
28
+ export { label_1 as label };
29
+ let strictParsing_1: boolean;
30
+ export { strictParsing_1 as strictParsing };
31
+ let phases_1: {
32
+ name: string;
33
+ prompt: string;
34
+ kind: string;
35
+ }[];
36
+ export { phases_1 as phases };
37
+ let postPhases_1: {
38
+ name: string;
39
+ prompt: string;
40
+ kind: string;
41
+ when: string;
42
+ }[];
43
+ export { postPhases_1 as postPhases };
44
+ export { noToolCallsPrompt };
45
+ export { toolErrorPrompt as onToolError };
46
+ }
47
+ export namespace ooda {
48
+ let id_2: string;
49
+ export { id_2 as id };
50
+ let label_2: string;
51
+ export { label_2 as label };
52
+ let strictParsing_2: boolean;
53
+ export { strictParsing_2 as strictParsing };
54
+ let phases_2: {
55
+ name: string;
56
+ prompt: string;
57
+ kind: string;
58
+ }[];
59
+ export { phases_2 as phases };
60
+ let postPhases_2: never[];
61
+ export { postPhases_2 as postPhases };
62
+ export { noToolCallsPrompt };
63
+ export { toolErrorPrompt as onToolError };
64
+ }
65
+ export namespace lpavrl {
66
+ let id_3: string;
67
+ export { id_3 as id };
68
+ let label_3: string;
69
+ export { label_3 as label };
70
+ let strictParsing_3: boolean;
71
+ export { strictParsing_3 as strictParsing };
72
+ let phases_3: {
73
+ name: string;
74
+ prompt: string;
75
+ kind: string;
76
+ }[];
77
+ export { phases_3 as phases };
78
+ let postPhases_3: ({
79
+ name: string;
80
+ prompt: string;
81
+ kind: string;
82
+ promptOnlyOnSuccess: boolean;
83
+ } | {
84
+ name: string;
85
+ prompt: string;
86
+ kind: string;
87
+ promptOnlyOnSuccess?: undefined;
88
+ })[];
89
+ export { postPhases_3 as postPhases };
90
+ export { noToolCallsPrompt };
91
+ export { toolErrorPrompt as onToolError };
92
+ }
93
+ export namespace pema {
94
+ let id_4: string;
95
+ export { id_4 as id };
96
+ let label_4: string;
97
+ export { label_4 as label };
98
+ let strictParsing_4: boolean;
99
+ export { strictParsing_4 as strictParsing };
100
+ let phases_4: {
101
+ name: string;
102
+ prompt: string;
103
+ kind: string;
104
+ }[];
105
+ export { phases_4 as phases };
106
+ let postPhases_4: {
107
+ name: string;
108
+ prompt: string;
109
+ kind: string;
110
+ when: string;
111
+ }[];
112
+ export { postPhases_4 as postPhases };
113
+ export { noToolCallsPrompt };
114
+ export { toolErrorPrompt as onToolError };
115
+ }
116
+ }
117
+ /**
118
+ * Reasoning strategies for AgentEngine.
119
+ *
120
+ * A strategy is a declarative description of the phases in one agent cycle:
121
+ * - `phases` run before tool execution; exactly one must be `kind: 'action'`
122
+ * - `postPhases` run after tool execution (thought-only reflection phases)
123
+ */
124
+ declare function toolErrorPrompt(errors: any): string;
125
+ declare function noToolCallsPrompt_1(actionPhase: any): string;
126
+ export {};
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Reasoning strategies for AgentEngine.
3
+ *
4
+ * A strategy is a declarative description of the phases in one agent cycle:
5
+ * - `phases` run before tool execution; exactly one must be `kind: 'action'`
6
+ * - `postPhases` run after tool execution (thought-only reflection phases)
7
+ */
8
+ function toolErrorPrompt(errors) {
9
+ return `
10
+ IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
11
+ ${errors}
12
+
13
+ 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. If you are stuck, consider using the 'user_input' or 'interactive_input' tool to ask the user for clarification.
14
+ `;
15
+ }
16
+ function noToolCallsPrompt(actionPhase) {
17
+ const name = actionPhase?.name ?? 'REASON';
18
+ return `Current Phase: ${name}. 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.`;
19
+ }
20
+ export const agentStrategies = {
21
+ default: {
22
+ id: 'default',
23
+ label: 'Direct thought → action',
24
+ strictParsing: true,
25
+ initialMessages: [
26
+ {
27
+ role: 'system',
28
+ content: "You are now at the 'Understand & Explore' phase. Analyze the user's request and the directory/codebase, then formulate a plan.",
29
+ },
30
+ ],
31
+ phases: [{ kind: 'action' }],
32
+ postPhases: [],
33
+ afterTools: '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.',
34
+ noToolCallsPrompt: () => "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.",
35
+ onToolError: toolErrorPrompt,
36
+ },
37
+ raor: {
38
+ id: 'raor',
39
+ label: 'Reason → Act → Reflect',
40
+ strictParsing: false,
41
+ phases: [
42
+ {
43
+ name: 'REASON',
44
+ prompt: "Current Phase: REASON. Analyze the user's request and formulate a plan.",
45
+ kind: 'action',
46
+ },
47
+ ],
48
+ postPhases: [
49
+ {
50
+ name: 'REFLECT',
51
+ prompt: 'Current Phase: REFLECT. Evaluate if the result moves toward the goal and adjust plan if needed.',
52
+ kind: 'thought',
53
+ when: 'success',
54
+ },
55
+ ],
56
+ noToolCallsPrompt,
57
+ onToolError: toolErrorPrompt,
58
+ },
59
+ ooda: {
60
+ id: 'ooda',
61
+ label: 'Observe → Orient → Decide → Act',
62
+ strictParsing: false,
63
+ phases: [
64
+ {
65
+ name: 'OBSERVE',
66
+ prompt: 'Current Phase: OBSERVE. Summarize the latest data from the environment.',
67
+ kind: 'thought',
68
+ },
69
+ {
70
+ name: 'ORIENT',
71
+ prompt: 'Current Phase: ORIENT. Interpret data in context of history and goal.',
72
+ kind: 'thought',
73
+ },
74
+ {
75
+ name: 'DECIDE',
76
+ prompt: 'Current Phase: DECIDE. Select the best action now.',
77
+ kind: 'action',
78
+ },
79
+ ],
80
+ postPhases: [],
81
+ noToolCallsPrompt,
82
+ onToolError: toolErrorPrompt,
83
+ },
84
+ lpavrl: {
85
+ id: 'lpavrl',
86
+ label: 'Listen → Plan → Act → Visualize → Reflect → Learn',
87
+ strictParsing: false,
88
+ phases: [
89
+ {
90
+ name: 'LISTEN',
91
+ prompt: 'Current Phase: LISTEN. Understand the user’s current request and context.',
92
+ kind: 'thought',
93
+ },
94
+ {
95
+ name: 'PLAN',
96
+ prompt: 'Current Phase: PLAN. Break it into steps with rationale.',
97
+ kind: 'action',
98
+ },
99
+ ],
100
+ postPhases: [
101
+ {
102
+ name: 'VISUALIZE',
103
+ prompt: 'Current Phase: VISUALIZE. Present progress or results in an understandable form.',
104
+ kind: 'thought',
105
+ promptOnlyOnSuccess: true,
106
+ },
107
+ {
108
+ name: 'REFLECT',
109
+ prompt: 'Current Phase: REFLECT. Judge results and align with the original intent.',
110
+ kind: 'thought',
111
+ },
112
+ {
113
+ name: 'LEARN',
114
+ prompt: 'Current Phase: LEARN. Update knowledge or strategy for future tasks.',
115
+ kind: 'thought',
116
+ },
117
+ ],
118
+ noToolCallsPrompt,
119
+ onToolError: toolErrorPrompt,
120
+ },
121
+ pema: {
122
+ id: 'pema',
123
+ label: 'Plan → Execute → Monitor → Adjust',
124
+ strictParsing: false,
125
+ phases: [
126
+ {
127
+ name: 'PLAN',
128
+ prompt: 'Current Phase: PLAN. Define actions needed to reach the goal.',
129
+ kind: 'action',
130
+ },
131
+ ],
132
+ postPhases: [
133
+ {
134
+ name: 'MONITOR',
135
+ prompt: 'Current Phase: MONITOR. Check current status against the plan.',
136
+ kind: 'thought',
137
+ when: 'success',
138
+ },
139
+ {
140
+ name: 'ADJUST',
141
+ prompt: 'Current Phase: ADJUST. Modify the plan if deviations are detected.',
142
+ kind: 'thought',
143
+ when: 'success',
144
+ },
145
+ ],
146
+ noToolCallsPrompt,
147
+ onToolError: toolErrorPrompt,
148
+ },
149
+ };
150
+ export function getStrategy(id = 'default') {
151
+ const strategy = agentStrategies[id];
152
+ if (!strategy) {
153
+ throw new Error(`Unknown agent strategy '${id}'. Available: ${Object.keys(agentStrategies).join(', ')}`);
154
+ }
155
+ return strategy;
156
+ }
157
+ export function listStrategies() {
158
+ return Object.values(agentStrategies).map(({ id, label }) => ({ id, label }));
159
+ }
@@ -1 +1,2 @@
1
+ export function getToolClasses(): any[];
1
2
  export function getToolDefinitions(): any[];