@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
@@ -0,0 +1,61 @@
1
+ /** Shared base for LLM-backed control phases used by composable agent flows. */
2
+ export class AgentControlNode extends AsyncNode {
3
+ constructor({ llmNode, prompt, outputKey, action, parse, maxContextChars, }?: {
4
+ llmNode?: null | undefined;
5
+ prompt?: string | undefined;
6
+ outputKey?: string | undefined;
7
+ action?: string | undefined;
8
+ parse?: boolean | undefined;
9
+ maxContextChars?: number | undefined;
10
+ });
11
+ llmNode: any;
12
+ prompt: string;
13
+ outputKey: string;
14
+ action: string;
15
+ parse: boolean;
16
+ maxContextChars: number;
17
+ buildContext(shared?: {}): any;
18
+ buildPrompt(shared?: {}): string;
19
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
20
+ resolveAction(execRes: any): any;
21
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
22
+ }
23
+ export class PlanNode extends AgentControlNode {
24
+ constructor(options?: {});
25
+ execAsync(prepRes: any, shared: any, observer: any): Promise<{
26
+ plan: any;
27
+ }>;
28
+ }
29
+ export class CriticNode extends AgentControlNode {
30
+ constructor(options?: {});
31
+ }
32
+ export class ReflectNode extends AgentControlNode {
33
+ constructor(options?: {});
34
+ }
35
+ /** Terminal node that records the agent's final answer. */
36
+ export class FinishNode extends AsyncNode {
37
+ constructor({ outputKey, action }?: {
38
+ outputKey?: string | undefined;
39
+ action?: string | undefined;
40
+ });
41
+ outputKey: string;
42
+ action: string;
43
+ prepAsync(shared?: {}): Promise<any>;
44
+ execAsync(prepRes: any): Promise<any>;
45
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
46
+ }
47
+ /** Approval gate that routes to `approve` or `reject`. */
48
+ export class HumanApprovalNode extends AsyncNode {
49
+ constructor({ prompt, approvalKey }?: {
50
+ prompt?: string | undefined;
51
+ approvalKey?: string | undefined;
52
+ });
53
+ prompt: string;
54
+ approvalKey: string;
55
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<{
56
+ approved: boolean;
57
+ answer: any;
58
+ }>;
59
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
60
+ }
61
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,164 @@
1
+ import { AsyncFlow, AsyncNode } from '../qflow.js';
2
+ import { UserInputNode } from '../nodes/user.js';
3
+ function parseResponse(response) {
4
+ if (typeof response !== 'string') {
5
+ const message = response?.choices?.[0]?.message ?? response?.message ?? null;
6
+ if (message && typeof message.content === 'string')
7
+ return parseResponse(message.content);
8
+ if (message?.tool_calls?.length) {
9
+ const call = message.tool_calls[0];
10
+ try {
11
+ return JSON.parse(call.function?.arguments ?? '{}');
12
+ }
13
+ catch {
14
+ return { text: call.function?.arguments ?? '' };
15
+ }
16
+ }
17
+ return response ?? {};
18
+ }
19
+ const firstBrace = response.indexOf('{');
20
+ const lastBrace = response.lastIndexOf('}');
21
+ const candidate = firstBrace !== -1 && lastBrace > firstBrace
22
+ ? response.slice(firstBrace, lastBrace + 1)
23
+ : response;
24
+ try {
25
+ return JSON.parse(candidate);
26
+ }
27
+ catch {
28
+ return { text: response };
29
+ }
30
+ }
31
+ /** Shared base for LLM-backed control phases used by composable agent flows. */
32
+ export class AgentControlNode extends AsyncNode {
33
+ constructor({ llmNode = null, prompt = '', outputKey = 'agentControlResult', action = 'default', parse = true, maxContextChars = 20_000, } = {}) {
34
+ super();
35
+ this.llmNode = llmNode;
36
+ this.prompt = prompt;
37
+ this.outputKey = outputKey;
38
+ this.action = action;
39
+ this.parse = parse;
40
+ this.maxContextChars = maxContextChars;
41
+ }
42
+ buildContext(shared = {}) {
43
+ return {
44
+ goal: shared.goal ?? this.params.goal ?? null,
45
+ plan: shared.plan ?? null,
46
+ critique: shared.critique ?? null,
47
+ reflection: shared.reflection ?? null,
48
+ history: (shared.conversationHistory ?? this.params.history ?? []).slice(-10),
49
+ ...(shared.agentContext ?? {}),
50
+ };
51
+ }
52
+ buildPrompt(shared = {}) {
53
+ const context = JSON.stringify(this.buildContext(shared), null, 2).slice(0, this.maxContextChars);
54
+ return `${this.params.prompt ?? this.prompt}\n\nContext:\n${context}`;
55
+ }
56
+ async execAsync(prepRes, shared = {}, observer = {}) {
57
+ if (!this.llmNode)
58
+ throw new Error(`${this.constructor.name} requires an llmNode.`);
59
+ this.llmNode.setParams({ prompt: this.buildPrompt(shared) });
60
+ const response = await new AsyncFlow(this.llmNode).runAsync({}, observer);
61
+ return this.parse ? parseResponse(response) : response;
62
+ }
63
+ resolveAction(execRes) {
64
+ return typeof this.action === 'function' ? this.action(execRes) : this.action;
65
+ }
66
+ async postAsync(shared, prepRes, execRes) {
67
+ shared[this.outputKey] = execRes;
68
+ return this.resolveAction(execRes);
69
+ }
70
+ }
71
+ export class PlanNode extends AgentControlNode {
72
+ constructor(options = {}) {
73
+ super({
74
+ prompt: 'Create a concise, ordered plan for the goal. Return JSON: {"plan": ["step 1", "step 2"]}.',
75
+ outputKey: 'planResult',
76
+ ...options,
77
+ });
78
+ }
79
+ async execAsync(prepRes, shared, observer) {
80
+ const result = await super.execAsync(prepRes, shared, observer);
81
+ if (Array.isArray(result))
82
+ return { plan: result };
83
+ if (typeof result?.plan === 'string')
84
+ return { plan: result.split(/\n+/).map(step => step.trim()).filter(Boolean) };
85
+ return { plan: result.plan ?? result.text ?? String(result) };
86
+ }
87
+ async postAsync(shared, prepRes, execRes) {
88
+ shared.plan = execRes.plan;
89
+ shared.planResult = execRes;
90
+ return Object.keys(this.successors).length ? 'default' : execRes;
91
+ }
92
+ }
93
+ export class CriticNode extends AgentControlNode {
94
+ constructor(options = {}) {
95
+ super({
96
+ prompt: 'Critique the plan and decide whether it is ready. Return JSON: {"approved": true|false, "critique": "..."}.',
97
+ outputKey: 'critiqueResult',
98
+ ...options,
99
+ });
100
+ }
101
+ async postAsync(shared, prepRes, execRes) {
102
+ const approved = execRes.approved === true || execRes.approved === 'true';
103
+ shared.critique = execRes.critique ?? execRes.text ?? '';
104
+ shared.approved = approved;
105
+ shared.critiqueResult = execRes;
106
+ return Object.keys(this.successors).length ? (approved ? 'approve' : 'reject') : execRes;
107
+ }
108
+ }
109
+ export class ReflectNode extends AgentControlNode {
110
+ constructor(options = {}) {
111
+ super({
112
+ prompt: 'Reflect on the latest observations. Return JSON: {"reflection": "...", "nextAction": "..."}.',
113
+ outputKey: 'reflectionResult',
114
+ ...options,
115
+ });
116
+ }
117
+ async postAsync(shared, prepRes, execRes) {
118
+ shared.reflection = execRes.reflection ?? execRes.text ?? String(execRes);
119
+ shared.nextAction = execRes.nextAction ?? null;
120
+ shared.reflectionResult = execRes;
121
+ return Object.keys(this.successors).length ? 'default' : execRes;
122
+ }
123
+ }
124
+ /** Terminal node that records the agent's final answer. */
125
+ export class FinishNode extends AsyncNode {
126
+ constructor({ outputKey = 'finalOutput', action = 'finish' } = {}) {
127
+ super();
128
+ this.outputKey = outputKey;
129
+ this.action = action;
130
+ }
131
+ async prepAsync(shared = {}) {
132
+ return shared[this.outputKey] ?? this.params.output ?? shared.agentOutput ?? null;
133
+ }
134
+ async execAsync(prepRes) {
135
+ return prepRes;
136
+ }
137
+ async postAsync(shared, prepRes, execRes) {
138
+ shared[this.outputKey] = execRes;
139
+ return Object.keys(this.successors).length ? this.action : execRes;
140
+ }
141
+ }
142
+ /** Approval gate that routes to `approve` or `reject`. */
143
+ export class HumanApprovalNode extends AsyncNode {
144
+ constructor({ prompt = 'Approve this action? (yes/no): ', approvalKey = 'approval' } = {}) {
145
+ super();
146
+ this.prompt = prompt;
147
+ this.approvalKey = approvalKey;
148
+ }
149
+ async execAsync(prepRes, shared = {}, observer = {}) {
150
+ const node = new UserInputNode();
151
+ node.setParams({
152
+ prompt: this.params.prompt ?? this.prompt,
153
+ logging: this.params.logging,
154
+ });
155
+ const answer = this.params.answer ?? await new AsyncFlow(node).runAsync({}, observer);
156
+ const approved = /^(yes|y|approve|approved|ok)$/i.test(String(answer).trim());
157
+ observer.emit?.('agent:approval', { approved, answer });
158
+ return { approved, answer };
159
+ }
160
+ async postAsync(shared, prepRes, execRes) {
161
+ shared[this.approvalKey] = execRes;
162
+ return Object.keys(this.successors).length ? (execRes.approved ? 'approve' : 'reject') : execRes;
163
+ }
164
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The single agent execution engine. Reasoning patterns are supplied as
3
+ * declarative strategies (see ./strategies.js) rather than duplicated loops.
4
+ *
5
+ * Supports both the legacy positional constructor and an options object:
6
+ * new AgentNode(llmNode, tools, summarizeLLM, flowRegistry, confirm, maxTokens)
7
+ * new AgentNode({ llmNode, availableTools, strategy: 'raor', ... })
8
+ */
9
+ export class AgentEngine extends AsyncNode {
10
+ constructor(optionsOrLlmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
11
+ llmNode: any;
12
+ availableTools: any;
13
+ summarizeLLM: any;
14
+ flowRegistry: any;
15
+ conversationHistory: any[];
16
+ maxSteps: any;
17
+ requireFinishConfirmation: any;
18
+ maxConversationHistoryTokens: any;
19
+ strategy: any;
20
+ toolRegistry: any;
21
+ grantedCapabilities: Set<any> | null;
22
+ grantedPermissions: Set<any> | null;
23
+ currentGoal: any;
24
+ /** Expose the declarative reasoning loop as a runnable, inspectable flow. */
25
+ asFlow(options?: {}): AsyncFlow;
26
+ /** Initialise conversation state once, shared by the loop and asFlow(). */
27
+ initialize(goal: any): any[];
28
+ getToolDescriptions(): any;
29
+ getSystemPrompt(): string;
30
+ getLLMAction(observer?: {}): Promise<any>;
31
+ manageConversationHistory(): Promise<void>;
32
+ parseLLMResponse(llmResponse: any, { strict }?: {
33
+ strict?: any;
34
+ }): any;
35
+ validateToolParameters(toolCall: any): any;
36
+ executeToolCalls(toolCalls: any, parallel: any, shared?: {}): Promise<any[]>;
37
+ confirmFinish(output: any): Promise<boolean>;
38
+ runPhase(phase: any, observer?: {}): Promise<any>;
39
+ execAsync(prepRes: any, shared: any, observer?: {}): Promise<any>;
40
+ currentObserver: {} | undefined;
41
+ currentShared: any;
42
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
43
+ }
44
+ import { AsyncNode } from '../qflow.js';
45
+ import { AsyncFlow } from '../qflow.js';
@@ -0,0 +1,415 @@
1
+ import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
2
+ import { UserInputNode } from '../nodes/user.js';
3
+ import { SummarizeNode } from '../nodes/summarize.js';
4
+ import { getToolDefinitions } from './tools.js';
5
+ import { logger } from './logger.js';
6
+ import { getStrategy } from './strategies.js';
7
+ import { buildAgentFlow } from './flow.js';
8
+ const FLOW_TOOLS = new Set(['sub_flow', 'iterator', 'scheduler']);
9
+ /**
10
+ * The single agent execution engine. Reasoning patterns are supplied as
11
+ * declarative strategies (see ./strategies.js) rather than duplicated loops.
12
+ *
13
+ * Supports both the legacy positional constructor and an options object:
14
+ * new AgentNode(llmNode, tools, summarizeLLM, flowRegistry, confirm, maxTokens)
15
+ * new AgentNode({ llmNode, availableTools, strategy: 'raor', ... })
16
+ */
17
+ export class AgentEngine extends AsyncNode {
18
+ constructor(optionsOrLlmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true, maxConversationHistoryTokens = 100000) {
19
+ super();
20
+ const options = optionsOrLlmNode && typeof optionsOrLlmNode === 'object' && 'llmNode' in optionsOrLlmNode
21
+ ? optionsOrLlmNode
22
+ : {
23
+ llmNode: optionsOrLlmNode,
24
+ availableTools,
25
+ summarizeLLM,
26
+ flowRegistry,
27
+ requireFinishConfirmation,
28
+ maxConversationHistoryTokens,
29
+ };
30
+ const { llmNode, availableTools: tools = {}, summarizeLLM: summarizer, flowRegistry: registry = {}, requireFinishConfirmation: confirm = true, maxConversationHistoryTokens: maxTokens = 100000, maxSteps = 70, strategy, toolRegistry = null, grantedCapabilities = null, grantedPermissions = null, } = options;
31
+ if (!llmNode) {
32
+ throw new Error(`${this.constructor.name} requires an LLMNode instance for reasoning.`);
33
+ }
34
+ this.llmNode = llmNode;
35
+ this.availableTools = tools;
36
+ this.summarizeLLM = summarizer;
37
+ this.flowRegistry = registry;
38
+ this.conversationHistory = [];
39
+ this.maxSteps = maxSteps;
40
+ this.requireFinishConfirmation = confirm;
41
+ this.maxConversationHistoryTokens = maxTokens;
42
+ this.strategy = getStrategy(strategy ?? new.target.strategyId ?? 'default');
43
+ this.toolRegistry = toolRegistry;
44
+ this.grantedCapabilities = grantedCapabilities ? new Set(grantedCapabilities) : null;
45
+ this.grantedPermissions = grantedPermissions ? new Set(grantedPermissions) : null;
46
+ this.currentGoal = null;
47
+ }
48
+ /** Expose the declarative reasoning loop as a runnable, inspectable flow. */
49
+ asFlow(options = {}) {
50
+ return buildAgentFlow(this, options);
51
+ }
52
+ /** Initialise conversation state once, shared by the loop and asFlow(). */
53
+ initialize(goal) {
54
+ if (!goal)
55
+ throw new Error(`${this.constructor.name} requires a 'goal' parameter.`);
56
+ this.llmNode.setParams({ goal });
57
+ this.conversationHistory = [
58
+ { role: 'system', content: this.getSystemPrompt() },
59
+ { role: 'user', content: `Goal: ${goal}` },
60
+ ...(this.strategy.initialMessages ?? []),
61
+ ];
62
+ return this.conversationHistory;
63
+ }
64
+ getToolDescriptions() {
65
+ if (this.toolRegistry) {
66
+ return this.toolRegistry.definitions({
67
+ grantedCapabilities: this.grantedCapabilities,
68
+ grantedPermissions: this.grantedPermissions,
69
+ });
70
+ }
71
+ return getToolDefinitions();
72
+ }
73
+ getSystemPrompt() {
74
+ const toolDescriptions = this.getToolDescriptions().map(tool => `### ${tool.name}: ${tool.description}\nParameters: ${JSON.stringify(tool.parameters)}`).join('\n');
75
+ const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0
76
+ ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}`
77
+ : '';
78
+ return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
79
+ Always prefer tools over long explanations. If you have a plan, you MUST include at least one tool call.
80
+ If the user asks about your capabilities, summarize the 'Available Tools' section of this prompt instead of calling a tool.
81
+
82
+ Reasoning strategy: ${this.strategy.label}
83
+
84
+ Available Tools:
85
+ ${toolDescriptions}${flowRegistryDescription}
86
+
87
+ CRITICAL: Your response MUST be a single JSON object with 'thought' and 'tool_calls'.
88
+ 'thought' is your reasoning; 'tool_calls' is an array of { tool, parameters } objects.
89
+ Set "parallel": true at the top level to execute tool calls concurrently.
90
+ Use the 'finish' tool only when you are certain the task is complete.
91
+
92
+ Example response:
93
+ {
94
+ "thought": "I need to search for information.",
95
+ "tool_calls": [{ "tool": "duckduckgo_search", "parameters": { "query": "latest AI research" } }]
96
+ }
97
+
98
+ Begin!`;
99
+ }
100
+ async getLLMAction(observer = {}) {
101
+ await this.manageConversationHistory();
102
+ this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
103
+ return await this.llmNode.runAsync({}, observer);
104
+ }
105
+ async manageConversationHistory() {
106
+ if (!this.summarizeLLM)
107
+ return;
108
+ const minHistoryLength = 2;
109
+ let currentSize = JSON.stringify(this.conversationHistory).length;
110
+ while (currentSize > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
111
+ const oldestEntry = this.conversationHistory[minHistoryLength];
112
+ if (oldestEntry?.role === 'user' && oldestEntry.content.startsWith('Observation:')) {
113
+ const observation = oldestEntry.content.slice('Observation:'.length).trim();
114
+ try {
115
+ const summarizeNode = new SummarizeNode();
116
+ summarizeNode.setParams({ text: observation, llmNode: this.summarizeLLM });
117
+ const summarized = await new AsyncFlow(summarizeNode).runAsync({});
118
+ this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarized}`;
119
+ }
120
+ catch (error) {
121
+ logger.error(`Failed to summarize observation: ${error.message}. Removing oldest entry.`);
122
+ this.conversationHistory.splice(minHistoryLength, 1);
123
+ }
124
+ }
125
+ else {
126
+ this.conversationHistory.splice(minHistoryLength, 1);
127
+ }
128
+ currentSize = JSON.stringify(this.conversationHistory).length;
129
+ }
130
+ }
131
+ parseLLMResponse(llmResponse, { strict = this.strategy.strictParsing } = {}) {
132
+ if (typeof llmResponse === 'string') {
133
+ const firstBrace = llmResponse.indexOf('{');
134
+ const lastBrace = llmResponse.lastIndexOf('}');
135
+ const jsonString = firstBrace !== -1 && lastBrace > firstBrace
136
+ ? llmResponse.slice(firstBrace, lastBrace + 1)
137
+ : llmResponse;
138
+ try {
139
+ const parsed = JSON.parse(jsonString);
140
+ if (parsed.thought && Array.isArray(parsed.tool_calls)) {
141
+ return {
142
+ thought: parsed.thought,
143
+ toolCalls: parsed.tool_calls,
144
+ parallel: parsed.parallel || false,
145
+ };
146
+ }
147
+ if (strict)
148
+ throw new Error("JSON is missing 'thought' or 'tool_calls' array.");
149
+ return { thought: parsed.thought ?? llmResponse, toolCalls: [], parallel: false };
150
+ }
151
+ catch (error) {
152
+ if (strict)
153
+ throw new Error(`Invalid JSON format: ${error.message}. Content: ${jsonString}`);
154
+ return { thought: llmResponse, toolCalls: [], parallel: false };
155
+ }
156
+ }
157
+ const message = llmResponse?.choices?.[0]?.message;
158
+ if (message) {
159
+ if (message.tool_calls?.length) {
160
+ return {
161
+ thought: message.reasoning_content || `Calling tool(s): ${message.tool_calls.map(tc => tc.function.name).join(', ')}`,
162
+ toolCalls: message.tool_calls.map(tc => ({
163
+ tool: tc.function.name,
164
+ parameters: JSON.parse(tc.function.arguments),
165
+ })),
166
+ parallel: false,
167
+ };
168
+ }
169
+ if (typeof message.content === 'string') {
170
+ return this.parseLLMResponse(message.content, { strict });
171
+ }
172
+ }
173
+ if (strict)
174
+ throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(llmResponse)}`);
175
+ return { thought: String(llmResponse), toolCalls: [], parallel: false };
176
+ }
177
+ validateToolParameters(toolCall) {
178
+ if (toolCall.tool === 'finish') {
179
+ return toolCall.parameters?.output === undefined ? "Missing required parameter: 'output' for tool 'finish'." : null;
180
+ }
181
+ if (FLOW_TOOLS.has(toolCall.tool)) {
182
+ if (toolCall.parameters?.flow === undefined) {
183
+ return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
184
+ }
185
+ return this.flowRegistry[toolCall.parameters.flow] ? null : `Flow '${toolCall.parameters.flow}' not found in registry.`;
186
+ }
187
+ if (this.toolRegistry) {
188
+ const spec = this.toolRegistry.get(toolCall.tool);
189
+ if (!spec)
190
+ return `Tool '${toolCall.tool}' is not a recognized tool.`;
191
+ if (!this.toolRegistry.allowed(spec, {
192
+ grantedCapabilities: this.grantedCapabilities,
193
+ grantedPermissions: this.grantedPermissions,
194
+ })) {
195
+ return `Tool '${toolCall.tool}' is not allowed by the current capability grant.`;
196
+ }
197
+ const errors = spec.validate(toolCall.parameters ?? {});
198
+ return errors.length ? errors.join(' ') : null;
199
+ }
200
+ const toolSchema = getToolDefinitions().find(def => def.name === toolCall.tool) ??
201
+ (this.availableTools[toolCall.tool] ? { parameters: { required: [] } } : null);
202
+ if (!toolSchema)
203
+ return `Tool '${toolCall.tool}' is not a recognized tool.`;
204
+ const required = toolSchema.parameters?.required ?? [];
205
+ for (const param of required) {
206
+ if (toolCall.parameters?.[param] === undefined) {
207
+ return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
208
+ }
209
+ }
210
+ return null;
211
+ }
212
+ async executeToolCalls(toolCalls, parallel, shared = {}) {
213
+ const executeTool = async (toolCall) => {
214
+ if (this.toolRegistry && this.toolRegistry.get(toolCall.tool)) {
215
+ try {
216
+ logger.toolCall(toolCall.tool, toolCall.parameters);
217
+ const outcome = await this.toolRegistry.execute(toolCall.tool, toolCall.parameters ?? {}, {
218
+ shared,
219
+ observer: this.currentObserver,
220
+ grantedCapabilities: this.grantedCapabilities,
221
+ grantedPermissions: this.grantedPermissions,
222
+ });
223
+ const output = outcome.result;
224
+ logger.toolResult(toolCall.tool, output);
225
+ return { success: true, output };
226
+ }
227
+ catch (error) {
228
+ return { success: false, error: `Error executing tool '${toolCall.tool}': ${error.message}` };
229
+ }
230
+ }
231
+ const toolInstance = this.availableTools[toolCall.tool];
232
+ if (!toolInstance) {
233
+ return { success: false, error: `Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.` };
234
+ }
235
+ try {
236
+ logger.toolCall(toolCall.tool, toolCall.parameters);
237
+ if (FLOW_TOOLS.has(toolCall.tool)) {
238
+ const flowName = toolCall.parameters.flow;
239
+ if (!this.flowRegistry[flowName])
240
+ throw new Error(`Flow '${flowName}' not found in registry.`);
241
+ toolCall.parameters.flow = this.flowRegistry[flowName];
242
+ }
243
+ toolInstance.setParams(toolCall.parameters ?? {});
244
+ const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
245
+ const toolFlow = new ToolFlowClass(toolInstance);
246
+ let output = toolInstance instanceof AsyncNode
247
+ ? await toolFlow.runAsync({})
248
+ : toolFlow.run({});
249
+ logger.toolResult(toolCall.tool, output);
250
+ if (this.summarizeLLM && typeof output === 'string' && output.length > 1000) {
251
+ const summarizeNode = new SummarizeNode();
252
+ summarizeNode.setParams({ text: output, llmNode: this.summarizeLLM });
253
+ output = await new AsyncFlow(summarizeNode).runAsync({});
254
+ }
255
+ return { success: true, output };
256
+ }
257
+ catch (error) {
258
+ return { success: false, error: `Error executing tool '${toolCall.tool}': ${error.message}` };
259
+ }
260
+ };
261
+ const results = [];
262
+ if (parallel) {
263
+ results.push(...await Promise.all(toolCalls.map(executeTool)));
264
+ }
265
+ else {
266
+ for (const toolCall of toolCalls)
267
+ results.push(await executeTool(toolCall));
268
+ }
269
+ return results.map((result, index) => ({
270
+ tool: toolCalls[index].tool,
271
+ parameters: toolCalls[index].parameters,
272
+ ...result,
273
+ }));
274
+ }
275
+ async confirmFinish(output) {
276
+ const confirmNode = new UserInputNode();
277
+ confirmNode.setParams({ prompt: `Agent proposes to finish with output: "${output}". Do you approve? (yes/no): ` });
278
+ const confirmation = await new AsyncFlow(confirmNode).runAsync({});
279
+ if (String(confirmation).toLowerCase() !== 'yes') {
280
+ logger.info('Agent finish denied by user. User input will be the next prompt.');
281
+ this.conversationHistory.push({
282
+ role: 'user',
283
+ content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.`,
284
+ });
285
+ return false;
286
+ }
287
+ return true;
288
+ }
289
+ async runPhase(phase, observer = {}) {
290
+ if (phase.prompt) {
291
+ this.conversationHistory.push({ role: 'user', content: phase.prompt });
292
+ }
293
+ const response = await this.getLLMAction(observer);
294
+ let parsed;
295
+ try {
296
+ parsed = this.parseLLMResponse(response);
297
+ }
298
+ catch (error) {
299
+ const raw = typeof response === 'string' ? response : JSON.stringify(response);
300
+ logger.error(`Error parsing LLM response in ${phase.name ?? 'action'} phase: ${error.message}`);
301
+ this.conversationHistory.push({
302
+ role: 'user',
303
+ content: `CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.
304
+ Error details: ${error.message}
305
+ Your invalid response was:
306
+ \`\`\`
307
+ ${raw}
308
+ \`\`\`
309
+ 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.`,
310
+ });
311
+ return { invalid: true };
312
+ }
313
+ logger.thought(parsed.thought);
314
+ this.conversationHistory.push({
315
+ role: 'assistant',
316
+ content: JSON.stringify(parsed.toolCalls?.length
317
+ ? { thought: parsed.thought, tool_calls: parsed.toolCalls, parallel: parsed.parallel }
318
+ : { thought: parsed.thought }),
319
+ });
320
+ return parsed;
321
+ }
322
+ async execAsync(prepRes, shared, observer = {}) {
323
+ const { goal } = this.params;
324
+ this.currentObserver = observer;
325
+ this.currentShared = shared;
326
+ this.initialize(goal);
327
+ const actionPhase = this.strategy.phases.find(phase => phase.kind === 'action');
328
+ let step = 0;
329
+ let finalOutput = null;
330
+ while (step < this.maxSteps) {
331
+ step++;
332
+ logger.info(`Agent Step ${step}`);
333
+ let action = null;
334
+ let invalid = false;
335
+ for (const phase of this.strategy.phases) {
336
+ let parsed;
337
+ try {
338
+ parsed = await this.runPhase(phase, observer);
339
+ }
340
+ catch (error) {
341
+ logger.error(`Failed to get LLM response: ${error.message}`);
342
+ this.conversationHistory.push({ role: 'user', content: `Error: Failed to get LLM response: ${error.message}` });
343
+ invalid = true;
344
+ break;
345
+ }
346
+ if (parsed.invalid) {
347
+ invalid = true;
348
+ break;
349
+ }
350
+ if (phase.kind === 'action')
351
+ action = parsed;
352
+ }
353
+ if (invalid)
354
+ continue;
355
+ const validationErrors = action.toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
356
+ if (validationErrors.length) {
357
+ const message = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
358
+ logger.error(message);
359
+ this.conversationHistory.push({ role: 'user', content: `Error: ${message}` });
360
+ continue;
361
+ }
362
+ const finishToolCall = action.toolCalls.find(tc => tc.tool === 'finish');
363
+ if (finishToolCall) {
364
+ finalOutput = finishToolCall.parameters.output;
365
+ if (this.requireFinishConfirmation && !(await this.confirmFinish(finalOutput)))
366
+ continue;
367
+ logger.final(finalOutput);
368
+ break;
369
+ }
370
+ if (action.toolCalls.length === 0) {
371
+ const prompt = this.strategy.noToolCallsPrompt(actionPhase);
372
+ if (prompt)
373
+ this.conversationHistory.push({ role: 'user', content: prompt });
374
+ continue;
375
+ }
376
+ const observations = await this.executeToolCalls(action.toolCalls, action.parallel, shared);
377
+ this.conversationHistory.push({ role: 'user', content: `Observation: ${JSON.stringify(observations)}` });
378
+ const toolErrors = observations.filter(obs => obs.success === false);
379
+ if (this.strategy.afterTools) {
380
+ this.conversationHistory.push({ role: 'system', content: this.strategy.afterTools });
381
+ }
382
+ if (toolErrors.length) {
383
+ const errors = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
384
+ this.conversationHistory.push({ role: 'system', content: this.strategy.onToolError(errors) });
385
+ }
386
+ for (const phase of this.strategy.postPhases) {
387
+ if (phase.when === 'success' && toolErrors.length)
388
+ continue;
389
+ if (phase.prompt && !(phase.promptOnlyOnSuccess && toolErrors.length)) {
390
+ this.conversationHistory.push({ role: 'user', content: phase.prompt });
391
+ }
392
+ let parsed;
393
+ try {
394
+ parsed = await this.runPhase({ ...phase, prompt: null }, observer);
395
+ }
396
+ catch (error) {
397
+ logger.error(`Failed to get LLM response in ${phase.name} phase: ${error.message}`);
398
+ break;
399
+ }
400
+ if (parsed.invalid)
401
+ break;
402
+ }
403
+ }
404
+ if (step >= this.maxSteps && finalOutput === null) {
405
+ finalOutput = 'Agent reached max steps without finishing. Last observation: ' +
406
+ JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
407
+ logger.error(finalOutput);
408
+ }
409
+ return finalOutput;
410
+ }
411
+ async postAsync(shared, prepRes, execRes) {
412
+ shared.agentOutput = execRes;
413
+ return 'default';
414
+ }
415
+ }