@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.
- package/CHANGELOG.md +107 -0
- package/LICENSE +21 -504
- package/MIGRATION.md +1130 -0
- package/README.md +1432 -823
- package/dist/agent/agent.d.ts +4 -22
- package/dist/agent/agent.js +4 -364
- package/dist/agent/base_agent.d.ts +8 -20
- package/dist/agent/base_agent.js +8 -205
- package/dist/agent/control_nodes.d.ts +61 -0
- package/dist/agent/control_nodes.js +164 -0
- package/dist/agent/engine.d.ts +45 -0
- package/dist/agent/engine.js +415 -0
- package/dist/agent/flow.d.ts +77 -0
- package/dist/agent/flow.js +148 -0
- package/dist/agent/index.d.ts +12 -0
- package/dist/agent/index.js +12 -0
- package/dist/agent/lpavrl_agent.d.ts +1 -2
- package/dist/agent/lpavrl_agent.js +2 -175
- package/dist/agent/ooda_agent.d.ts +1 -2
- package/dist/agent/ooda_agent.js +2 -164
- package/dist/agent/pema_agent.d.ts +1 -2
- package/dist/agent/pema_agent.js +2 -168
- package/dist/agent/raor_agent.d.ts +1 -2
- package/dist/agent/raor_agent.js +2 -161
- package/dist/agent/strategies.d.ts +126 -0
- package/dist/agent/strategies.js +159 -0
- package/dist/agent/tools.d.ts +1 -0
- package/dist/agent/tools.js +42 -24
- package/dist/approval.d.ts +42 -0
- package/dist/approval.js +86 -0
- package/dist/budget.d.ts +103 -0
- package/dist/budget.js +133 -0
- package/dist/bun_nodes.d.ts +119 -0
- package/dist/bun_nodes.js +331 -0
- package/dist/contracts.d.ts +30 -0
- package/dist/contracts.js +103 -0
- package/dist/durable.d.ts +278 -0
- package/dist/durable.js +730 -0
- package/dist/eval.d.ts +165 -0
- package/dist/eval.js +263 -0
- package/dist/graph.d.ts +157 -0
- package/dist/graph.js +330 -0
- package/dist/llm/index.d.ts +359 -0
- package/dist/llm/index.js +924 -0
- package/dist/logger.js +7 -3
- package/dist/mcp/client.d.ts +55 -0
- package/dist/mcp/client.js +145 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +106 -0
- package/dist/mcp/server.js +154 -0
- package/dist/mcp/stdio.d.ts +2 -0
- package/dist/mcp/stdio.js +3 -0
- package/dist/memory.d.ts +101 -0
- package/dist/memory.js +217 -0
- package/dist/nodes/browser_control.js +5 -4
- package/dist/nodes/data_extractor.js +2 -1
- package/dist/nodes/data_validation.d.ts +3 -3
- package/dist/nodes/data_validation.js +19 -5
- package/dist/nodes/database.d.ts +2 -1
- package/dist/nodes/database.js +71 -58
- package/dist/nodes/gis.js +1 -1
- package/dist/nodes/git.d.ts +1 -1
- package/dist/nodes/git.js +65 -51
- package/dist/nodes/github.d.ts +1 -0
- package/dist/nodes/hardware_interaction.d.ts +2 -4
- package/dist/nodes/hardware_interaction.js +4 -3
- package/dist/nodes/http.d.ts +1 -7
- package/dist/nodes/http.js +46 -33
- package/dist/nodes/image_gallery.js +45 -45
- package/dist/nodes/index.d.ts +8 -0
- package/dist/nodes/index.js +8 -0
- package/dist/nodes/interactive_webview.d.ts +1 -2
- package/dist/nodes/interactive_webview.js +217 -216
- package/dist/nodes/multimedia_processing.js +1 -1
- package/dist/nodes/navigator.d.ts +7 -0
- package/dist/nodes/navigator.js +48 -8
- package/dist/nodes/pdf_processor.js +2 -1
- package/dist/nodes/remote_execution.js +2 -2
- package/dist/nodes/s3.d.ts +1 -0
- package/dist/nodes/scheduler.js +2 -2
- package/dist/nodes/search.d.ts +1 -1
- package/dist/nodes/search.js +3 -2
- package/dist/nodes/speech_synthesis.js +2 -1
- package/dist/nodes/spreadsheet.d.ts +1 -7
- package/dist/nodes/spreadsheet.js +2 -1
- package/dist/nodes/streaming_llm.d.ts +51 -0
- package/dist/nodes/streaming_llm.js +120 -0
- package/dist/nodes/webhook.d.ts +1 -5
- package/dist/nodes/webhook.js +106 -93
- package/dist/nodes/websockets.js +5 -3
- package/dist/nodes/webview.js +3 -2
- package/dist/optional.d.ts +32 -0
- package/dist/optional.js +61 -0
- package/dist/qflow.d.ts +25 -14
- package/dist/qflow.js +140 -49
- package/dist/schedule.d.ts +41 -0
- package/dist/schedule.js +149 -0
- package/dist/side_effects.d.ts +50 -0
- package/dist/side_effects.js +94 -0
- package/dist/streaming.d.ts +35 -0
- package/dist/streaming.js +199 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +130 -0
- package/dist/tool_spec.d.ts +76 -0
- package/dist/tool_spec.js +321 -0
- package/dist/trace.d.ts +28 -0
- package/dist/trace.js +190 -0
- package/dist/util.d.ts +57 -0
- package/dist/util.js +122 -0
- package/package.json +153 -67
- package/qflow.config.js +18 -18
- package/scripts/postinstall.js +50 -0
- package/scripts/verify-package.js +114 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn a declarative strategy into a runnable, inspectable AsyncFlow.
|
|
3
|
+
* The engine still owns reasoning/tool semantics; the flow makes each phase a
|
|
4
|
+
* checkpointable, traceable node.
|
|
5
|
+
*/
|
|
6
|
+
export function buildAgentFlow(agent: any, options?: {}): AsyncFlow;
|
|
7
|
+
/** Metadata-only view of a strategy, suitable for docs or visual editors. */
|
|
8
|
+
export function strategyGraph(strategyId?: string): {
|
|
9
|
+
id: any;
|
|
10
|
+
label: any;
|
|
11
|
+
phases: any[];
|
|
12
|
+
edges: {
|
|
13
|
+
from: any;
|
|
14
|
+
to: any;
|
|
15
|
+
action: string;
|
|
16
|
+
}[];
|
|
17
|
+
};
|
|
18
|
+
/** One node per declarative strategy phase; each node delegates to AgentEngine. */
|
|
19
|
+
export class AgentPhaseNode extends AsyncNode {
|
|
20
|
+
constructor({ agent, phase, role }: {
|
|
21
|
+
agent: any;
|
|
22
|
+
phase: any;
|
|
23
|
+
role?: string | undefined;
|
|
24
|
+
});
|
|
25
|
+
agent: any;
|
|
26
|
+
phase: any;
|
|
27
|
+
role: string;
|
|
28
|
+
prepAsync(shared?: {}): Promise<{
|
|
29
|
+
goal: any;
|
|
30
|
+
}>;
|
|
31
|
+
execAsync(_prepRes: any, shared?: {}, observer?: {}): Promise<{
|
|
32
|
+
done: boolean;
|
|
33
|
+
output: string;
|
|
34
|
+
phase: any;
|
|
35
|
+
invalid?: undefined;
|
|
36
|
+
parsed?: undefined;
|
|
37
|
+
observations?: undefined;
|
|
38
|
+
} | {
|
|
39
|
+
done: boolean;
|
|
40
|
+
invalid: boolean;
|
|
41
|
+
phase: any;
|
|
42
|
+
output?: undefined;
|
|
43
|
+
parsed?: undefined;
|
|
44
|
+
observations?: undefined;
|
|
45
|
+
} | {
|
|
46
|
+
done: boolean;
|
|
47
|
+
parsed: any;
|
|
48
|
+
phase: any;
|
|
49
|
+
output?: undefined;
|
|
50
|
+
invalid?: undefined;
|
|
51
|
+
observations?: undefined;
|
|
52
|
+
} | {
|
|
53
|
+
done: boolean;
|
|
54
|
+
output: any;
|
|
55
|
+
phase: string;
|
|
56
|
+
invalid?: undefined;
|
|
57
|
+
parsed?: undefined;
|
|
58
|
+
observations?: undefined;
|
|
59
|
+
} | {
|
|
60
|
+
done: boolean;
|
|
61
|
+
phase: any;
|
|
62
|
+
output?: undefined;
|
|
63
|
+
invalid?: undefined;
|
|
64
|
+
parsed?: undefined;
|
|
65
|
+
observations?: undefined;
|
|
66
|
+
} | {
|
|
67
|
+
done: boolean;
|
|
68
|
+
observations: any;
|
|
69
|
+
phase: any;
|
|
70
|
+
output?: undefined;
|
|
71
|
+
invalid?: undefined;
|
|
72
|
+
parsed?: undefined;
|
|
73
|
+
}>;
|
|
74
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<"continue" | "finish">;
|
|
75
|
+
}
|
|
76
|
+
import { AsyncFlow } from '../qflow.js';
|
|
77
|
+
import { AsyncNode } from '../qflow.js';
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { AsyncFlow, AsyncNode } from '../qflow.js';
|
|
2
|
+
import { getStrategy } from './strategies.js';
|
|
3
|
+
import { describeGraph } from '../graph.js';
|
|
4
|
+
class AgentFlowFinishNode extends AsyncNode {
|
|
5
|
+
constructor() {
|
|
6
|
+
super();
|
|
7
|
+
this.output = null;
|
|
8
|
+
}
|
|
9
|
+
async prepAsync(shared = {}) {
|
|
10
|
+
return shared.finalOutput ?? this.output ?? '';
|
|
11
|
+
}
|
|
12
|
+
async execAsync(prepRes) {
|
|
13
|
+
return prepRes;
|
|
14
|
+
}
|
|
15
|
+
async postAsync(shared, prepRes, execRes) {
|
|
16
|
+
shared.finalOutput = execRes;
|
|
17
|
+
return execRes;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** One node per declarative strategy phase; each node delegates to AgentEngine. */
|
|
21
|
+
export class AgentPhaseNode extends AsyncNode {
|
|
22
|
+
constructor({ agent, phase, role = 'phase' }) {
|
|
23
|
+
super();
|
|
24
|
+
this.agent = agent;
|
|
25
|
+
this.phase = phase;
|
|
26
|
+
this.role = role;
|
|
27
|
+
}
|
|
28
|
+
async prepAsync(shared = {}) {
|
|
29
|
+
const goal = this.params.goal ?? shared.goal ?? this.agent.params?.goal;
|
|
30
|
+
if (!goal)
|
|
31
|
+
throw new Error('Agent flow requires a goal in shared state or node params.');
|
|
32
|
+
if (this.agent.currentGoal !== goal) {
|
|
33
|
+
this.agent.initialize(goal);
|
|
34
|
+
this.agent.currentGoal = goal;
|
|
35
|
+
}
|
|
36
|
+
shared.agentFlowSteps = (shared.agentFlowSteps ?? 0) + 1;
|
|
37
|
+
return { goal };
|
|
38
|
+
}
|
|
39
|
+
async execAsync(_prepRes, shared = {}, observer = {}) {
|
|
40
|
+
if (shared.agentFlowSteps > this.agent.maxSteps) {
|
|
41
|
+
return { done: true, output: 'Agent step budget exhausted.', phase: this.phase.name ?? 'budget' };
|
|
42
|
+
}
|
|
43
|
+
this.agent.currentObserver = observer;
|
|
44
|
+
this.agent.currentShared = shared;
|
|
45
|
+
const parsed = await this.agent.runPhase(this.phase, observer);
|
|
46
|
+
if (parsed.invalid)
|
|
47
|
+
return { done: false, invalid: true, phase: this.phase.name ?? this.phase.kind };
|
|
48
|
+
if (this.phase.kind !== 'action') {
|
|
49
|
+
return { done: false, parsed, phase: this.phase.name ?? this.phase.kind };
|
|
50
|
+
}
|
|
51
|
+
const finishCall = parsed.toolCalls.find(call => call.tool === 'finish');
|
|
52
|
+
if (finishCall) {
|
|
53
|
+
const output = finishCall.parameters?.output ?? '';
|
|
54
|
+
if (this.agent.requireFinishConfirmation && !(await this.agent.confirmFinish(output))) {
|
|
55
|
+
return { done: false, phase: 'finish_denied' };
|
|
56
|
+
}
|
|
57
|
+
return { done: true, output, phase: 'finish' };
|
|
58
|
+
}
|
|
59
|
+
if (!parsed.toolCalls.length) {
|
|
60
|
+
const prompt = this.agent.strategy.noToolCallsPrompt?.(this.phase);
|
|
61
|
+
if (prompt)
|
|
62
|
+
this.agent.conversationHistory.push({ role: 'user', content: prompt });
|
|
63
|
+
return { done: false, phase: this.phase.name ?? this.phase.kind };
|
|
64
|
+
}
|
|
65
|
+
const validationErrors = parsed.toolCalls
|
|
66
|
+
.map(call => this.agent.validateToolParameters(call))
|
|
67
|
+
.filter(Boolean);
|
|
68
|
+
if (validationErrors.length) {
|
|
69
|
+
this.agent.conversationHistory.push({
|
|
70
|
+
role: 'user',
|
|
71
|
+
content: `Tool parameter validation failed: ${validationErrors.join('; ')}. Correct the calls.`,
|
|
72
|
+
});
|
|
73
|
+
return { done: false, phase: this.phase.name ?? this.phase.kind };
|
|
74
|
+
}
|
|
75
|
+
const observations = await this.agent.executeToolCalls(parsed.toolCalls, parsed.parallel, shared);
|
|
76
|
+
this.agent.conversationHistory.push({ role: 'user', content: `Observation: ${JSON.stringify(observations)}` });
|
|
77
|
+
const toolErrors = observations.filter(observation => observation.success === false);
|
|
78
|
+
if (toolErrors.length && this.agent.strategy.onToolError) {
|
|
79
|
+
const errors = toolErrors
|
|
80
|
+
.map(error => `Tool: ${error.tool}, Error: ${error.error}`)
|
|
81
|
+
.join('\n');
|
|
82
|
+
this.agent.conversationHistory.push({ role: 'system', content: this.agent.strategy.onToolError(errors) });
|
|
83
|
+
}
|
|
84
|
+
if (typeof this.agent.strategy.afterTools === 'string') {
|
|
85
|
+
this.agent.conversationHistory.push({ role: 'system', content: this.agent.strategy.afterTools });
|
|
86
|
+
}
|
|
87
|
+
return { done: false, observations, phase: this.phase.name ?? this.phase.kind };
|
|
88
|
+
}
|
|
89
|
+
async postAsync(shared, prepRes, execRes) {
|
|
90
|
+
shared.agentPhase = execRes.phase;
|
|
91
|
+
if (execRes.done)
|
|
92
|
+
shared.finalOutput = execRes.output;
|
|
93
|
+
return execRes.done ? 'finish' : 'continue';
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Turn a declarative strategy into a runnable, inspectable AsyncFlow.
|
|
98
|
+
* The engine still owns reasoning/tool semantics; the flow makes each phase a
|
|
99
|
+
* checkpointable, traceable node.
|
|
100
|
+
*/
|
|
101
|
+
export function buildAgentFlow(agent, options = {}) {
|
|
102
|
+
if (!agent || typeof agent.runPhase !== 'function') {
|
|
103
|
+
throw new Error('buildAgentFlow requires an AgentEngine instance.');
|
|
104
|
+
}
|
|
105
|
+
const strategy = options.strategy
|
|
106
|
+
? (typeof options.strategy === 'string' ? getStrategy(options.strategy) : options.strategy)
|
|
107
|
+
: agent.strategy;
|
|
108
|
+
const phases = [
|
|
109
|
+
...(strategy.phases ?? []).map(phase => ({ phase, role: 'phase' })),
|
|
110
|
+
...(strategy.postPhases ?? []).map(phase => ({ phase, role: 'postPhase' })),
|
|
111
|
+
];
|
|
112
|
+
if (!phases.length)
|
|
113
|
+
throw new Error(`Strategy '${strategy.id ?? strategy.label}' has no phases.`);
|
|
114
|
+
const nodes = phases.map(({ phase, role }) => new AgentPhaseNode({ agent, phase, role }));
|
|
115
|
+
const finish = new AgentFlowFinishNode();
|
|
116
|
+
for (let index = 0; index < nodes.length; index += 1) {
|
|
117
|
+
const next = nodes[index + 1] ?? nodes[0];
|
|
118
|
+
nodes[index].next(next, 'continue');
|
|
119
|
+
nodes[index].next(finish, 'finish');
|
|
120
|
+
}
|
|
121
|
+
const flow = new AsyncFlow(nodes[0], {
|
|
122
|
+
maxSteps: options.maxSteps ?? Math.max(10, (agent.maxSteps ?? 70) * phases.length),
|
|
123
|
+
timeout: options.timeout,
|
|
124
|
+
onError: options.onError,
|
|
125
|
+
});
|
|
126
|
+
flow.agent = agent;
|
|
127
|
+
flow.strategy = strategy;
|
|
128
|
+
flow.graph = describeGraph(nodes[0]);
|
|
129
|
+
return flow;
|
|
130
|
+
}
|
|
131
|
+
/** Metadata-only view of a strategy, suitable for docs or visual editors. */
|
|
132
|
+
export function strategyGraph(strategyId = 'default') {
|
|
133
|
+
const strategy = typeof strategyId === 'string' ? getStrategy(strategyId) : strategyId;
|
|
134
|
+
const phases = [
|
|
135
|
+
...(strategy.phases ?? []).map(phase => ({ ...phase, role: 'phase' })),
|
|
136
|
+
...(strategy.postPhases ?? []).map(phase => ({ ...phase, role: 'postPhase' })),
|
|
137
|
+
];
|
|
138
|
+
return {
|
|
139
|
+
id: strategy.id ?? 'custom',
|
|
140
|
+
label: strategy.label ?? '',
|
|
141
|
+
phases,
|
|
142
|
+
edges: phases.map((phase, index) => ({
|
|
143
|
+
from: phase.name ?? `phase-${index + 1}`,
|
|
144
|
+
to: phase.name ?? `phase-${((index + 1) % phases.length) + 1}`,
|
|
145
|
+
action: 'continue',
|
|
146
|
+
})),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "../tool_spec.js";
|
|
2
|
+
export * from "./engine.js";
|
|
3
|
+
export * from "./strategies.js";
|
|
4
|
+
export * from "./control_nodes.js";
|
|
5
|
+
export * from "./flow.js";
|
|
6
|
+
export * from "./agent.js";
|
|
7
|
+
export * from "./base_agent.js";
|
|
8
|
+
export * from "./raor_agent.js";
|
|
9
|
+
export * from "./ooda_agent.js";
|
|
10
|
+
export * from "./lpavrl_agent.js";
|
|
11
|
+
export * from "./pema_agent.js";
|
|
12
|
+
export { logger } from "./logger.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from '../tool_spec.js';
|
|
2
|
+
export * from './engine.js';
|
|
3
|
+
export * from './strategies.js';
|
|
4
|
+
export * from './control_nodes.js';
|
|
5
|
+
export * from './flow.js';
|
|
6
|
+
export * from './agent.js';
|
|
7
|
+
export * from './base_agent.js';
|
|
8
|
+
export * from './raor_agent.js';
|
|
9
|
+
export * from './ooda_agent.js';
|
|
10
|
+
export * from './lpavrl_agent.js';
|
|
11
|
+
export * from './pema_agent.js';
|
|
12
|
+
export { logger } from './logger.js';
|
|
@@ -1,178 +1,5 @@
|
|
|
1
1
|
import { BaseAgent } from './base_agent.js';
|
|
2
|
-
|
|
3
|
-
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
4
|
-
import { UserInputNode } from '../nodes/index.js';
|
|
2
|
+
/** Listen → Plan → Act → Visualize → Reflect → Learn. */
|
|
5
3
|
export class LPAVRLAgent extends BaseAgent {
|
|
6
|
-
|
|
7
|
-
const { goal } = this.params;
|
|
8
|
-
if (!goal) {
|
|
9
|
-
throw new Error("LPAVRLAgent requires a 'goal' parameter.");
|
|
10
|
-
}
|
|
11
|
-
this.conversationHistory = [
|
|
12
|
-
{ role: "system", content: this.getSystemPrompt() },
|
|
13
|
-
{ role: "user", content: `Goal: ${goal}` },
|
|
14
|
-
];
|
|
15
|
-
let step = 0;
|
|
16
|
-
let finalOutput = null;
|
|
17
|
-
while (step < this.maxSteps) {
|
|
18
|
-
step++;
|
|
19
|
-
logger.info(`Agent Step ${step}`);
|
|
20
|
-
// Listen
|
|
21
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: LISTEN. Understand the user’s current request and context." });
|
|
22
|
-
const listenResponse = await this.getLLMAction();
|
|
23
|
-
const { thought: listenThought } = this.parseLLMResponse(listenResponse);
|
|
24
|
-
logger.thought(listenThought);
|
|
25
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: listenThought }) });
|
|
26
|
-
// Plan
|
|
27
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Break it into steps with rationale." });
|
|
28
|
-
const planResponse = await this.getLLMAction();
|
|
29
|
-
let parsedPlanResponse;
|
|
30
|
-
try {
|
|
31
|
-
parsedPlanResponse = this.parseLLMResponse(planResponse);
|
|
32
|
-
}
|
|
33
|
-
catch (e) {
|
|
34
|
-
logger.error(`Error parsing LLM response in Plan phase: ${e.message}`);
|
|
35
|
-
this.conversationHistory.push({ role: "user", content: `
|
|
36
|
-
CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.\nError details: ${e.message}\nYour invalid response was: \n\`\`\`\n${planResponse}\n\`\`\`\nYou MUST respond with a single JSON object containing 'thought' and 'tool_calls'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.\n` });
|
|
37
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
38
|
-
}
|
|
39
|
-
const { thought: planThought, toolCalls, parallel } = parsedPlanResponse;
|
|
40
|
-
logger.thought(planThought);
|
|
41
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: planThought, tool_calls: toolCalls, parallel }) });
|
|
42
|
-
// Validate tool parameters for all tool calls
|
|
43
|
-
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
44
|
-
if (validationErrors.length > 0) {
|
|
45
|
-
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
46
|
-
logger.error(errorMessage);
|
|
47
|
-
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
48
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
49
|
-
}
|
|
50
|
-
// Handle finish tool (check here before acting)
|
|
51
|
-
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
52
|
-
if (finishToolCall) {
|
|
53
|
-
finalOutput = finishToolCall.parameters.output;
|
|
54
|
-
if (this.requireFinishConfirmation) {
|
|
55
|
-
const confirmNode = new UserInputNode();
|
|
56
|
-
confirmNode.setParams({
|
|
57
|
-
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
58
|
-
});
|
|
59
|
-
const confirmFlow = new AsyncFlow(confirmNode);
|
|
60
|
-
const confirmation = await confirmFlow.runAsync({});
|
|
61
|
-
if (confirmation.toLowerCase() !== 'yes') {
|
|
62
|
-
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
63
|
-
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
64
|
-
continue; // Continue the loop
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
logger.final(finalOutput);
|
|
68
|
-
break; // Exit the main loop as agent is finished
|
|
69
|
-
}
|
|
70
|
-
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
71
|
-
if (toolCalls.length === 0) {
|
|
72
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
|
|
73
|
-
continue; // Re-run the loop to force tool call generation
|
|
74
|
-
}
|
|
75
|
-
// Act
|
|
76
|
-
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
77
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
78
|
-
// Check for tool errors and add specific instructions for reflection
|
|
79
|
-
const toolErrors = observations.filter(obs => obs.success === false);
|
|
80
|
-
if (toolErrors.length > 0) {
|
|
81
|
-
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
82
|
-
this.conversationHistory.push({ role: "system", content: `
|
|
83
|
-
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
84
|
-
${errorMessages}
|
|
85
|
-
|
|
86
|
-
Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal.
|
|
87
|
-
` });
|
|
88
|
-
}
|
|
89
|
-
else {
|
|
90
|
-
// Visualize
|
|
91
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: VISUALIZE. Present progress or results in an understandable form." });
|
|
92
|
-
}
|
|
93
|
-
const visualizeResponse = await this.getLLMAction();
|
|
94
|
-
const { thought: visualizeThought } = this.parseLLMResponse(visualizeResponse);
|
|
95
|
-
logger.thought(visualizeThought);
|
|
96
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: visualizeThought }) });
|
|
97
|
-
// Reflect
|
|
98
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: REFLECT. Judge results and align with the original intent." });
|
|
99
|
-
const reflectResponse = await this.getLLMAction();
|
|
100
|
-
const { thought: reflectThought } = this.parseLLMResponse(reflectResponse);
|
|
101
|
-
logger.thought(reflectThought);
|
|
102
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: reflectThought }) });
|
|
103
|
-
// Learn
|
|
104
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: LEARN. Update knowledge or strategy for future tasks." });
|
|
105
|
-
const learnResponse = await this.getLLMAction();
|
|
106
|
-
const { thought: learnThought } = this.parseLLMResponse(learnResponse);
|
|
107
|
-
logger.thought(learnThought);
|
|
108
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: learnThought }) });
|
|
109
|
-
}
|
|
110
|
-
if (step >= this.maxSteps && finalOutput === null) {
|
|
111
|
-
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
112
|
-
logger.error(message);
|
|
113
|
-
finalOutput = message;
|
|
114
|
-
}
|
|
115
|
-
return finalOutput;
|
|
116
|
-
}
|
|
117
|
-
async executeToolCalls(toolCalls, parallel) {
|
|
118
|
-
const executeTool = async (toolCall) => {
|
|
119
|
-
const toolInstance = this.availableTools[toolCall.tool];
|
|
120
|
-
if (!toolInstance) {
|
|
121
|
-
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
122
|
-
}
|
|
123
|
-
let toolOutput;
|
|
124
|
-
try {
|
|
125
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
126
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
127
|
-
const flowName = toolCall.parameters.flow;
|
|
128
|
-
if (!this.flowRegistry[flowName]) {
|
|
129
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
130
|
-
}
|
|
131
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
132
|
-
}
|
|
133
|
-
toolInstance.setParams(toolCall.parameters);
|
|
134
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
135
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
136
|
-
if (toolInstance instanceof AsyncNode) {
|
|
137
|
-
toolOutput = await toolFlow.runAsync({});
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
toolOutput = toolFlow.run({});
|
|
141
|
-
}
|
|
142
|
-
logger.toolResult(toolCall.tool, toolOutput);
|
|
143
|
-
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
144
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
145
|
-
const summarizeNode = new SummarizeNode();
|
|
146
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
147
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
148
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
149
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
150
|
-
}
|
|
151
|
-
return { success: true, output: toolOutput };
|
|
152
|
-
}
|
|
153
|
-
catch (e) {
|
|
154
|
-
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
155
|
-
}
|
|
156
|
-
};
|
|
157
|
-
let observations = [];
|
|
158
|
-
if (parallel) {
|
|
159
|
-
const results = await Promise.all(toolCalls.map(executeTool));
|
|
160
|
-
observations = results.map((result, index) => ({
|
|
161
|
-
tool: toolCalls[index].tool,
|
|
162
|
-
parameters: toolCalls[index].parameters,
|
|
163
|
-
...result // Spread success/error and output/error
|
|
164
|
-
}));
|
|
165
|
-
}
|
|
166
|
-
else {
|
|
167
|
-
for (const toolCall of toolCalls) {
|
|
168
|
-
const result = await executeTool(toolCall);
|
|
169
|
-
observations.push({
|
|
170
|
-
tool: toolCall.tool,
|
|
171
|
-
parameters: toolCall.parameters,
|
|
172
|
-
...result // Spread success/error and output/error
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
return observations;
|
|
177
|
-
}
|
|
4
|
+
static strategyId = 'lpavrl';
|
|
178
5
|
}
|
package/dist/agent/ooda_agent.js
CHANGED
|
@@ -1,167 +1,5 @@
|
|
|
1
1
|
import { BaseAgent } from './base_agent.js';
|
|
2
|
-
|
|
3
|
-
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
4
|
-
import { UserInputNode } from '../nodes/index.js';
|
|
2
|
+
/** Observe → Orient → Decide → Act. */
|
|
5
3
|
export class OODAAgent extends BaseAgent {
|
|
6
|
-
|
|
7
|
-
const { goal } = this.params;
|
|
8
|
-
if (!goal) {
|
|
9
|
-
throw new Error("OODAAgent requires a 'goal' parameter.");
|
|
10
|
-
}
|
|
11
|
-
this.conversationHistory = [
|
|
12
|
-
{ role: "system", content: this.getSystemPrompt() },
|
|
13
|
-
{ role: "user", content: `Goal: ${goal}` },
|
|
14
|
-
];
|
|
15
|
-
let step = 0;
|
|
16
|
-
let finalOutput = null;
|
|
17
|
-
while (step < this.maxSteps) {
|
|
18
|
-
step++;
|
|
19
|
-
logger.info(`Agent Step ${step}`);
|
|
20
|
-
// Observe
|
|
21
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: OBSERVE. Summarize the latest data from the environment." });
|
|
22
|
-
const observeResponse = await this.getLLMAction();
|
|
23
|
-
const { thought: observeThought } = this.parseLLMResponse(observeResponse);
|
|
24
|
-
logger.thought(observeThought);
|
|
25
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: observeThought }) });
|
|
26
|
-
// Orient
|
|
27
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: ORIENT. Interpret data in context of history and goal." });
|
|
28
|
-
const orientResponse = await this.getLLMAction();
|
|
29
|
-
const { thought: orientThought } = this.parseLLMResponse(orientResponse);
|
|
30
|
-
logger.thought(orientThought);
|
|
31
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: orientThought }) });
|
|
32
|
-
// Decide
|
|
33
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. Select the best action now." });
|
|
34
|
-
const decideResponse = await this.getLLMAction();
|
|
35
|
-
let parsedDecideResponse;
|
|
36
|
-
try {
|
|
37
|
-
parsedDecideResponse = this.parseLLMResponse(decideResponse);
|
|
38
|
-
}
|
|
39
|
-
catch (e) {
|
|
40
|
-
logger.error(`Error parsing LLM response in Decide phase: ${e.message}`);
|
|
41
|
-
this.conversationHistory.push({ role: "user", content: `
|
|
42
|
-
CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.\nError details: ${e.message}\nYour invalid response was: \n\`\`\`\n${decideResponse}\n\`\`\`\nYou MUST respond with a single JSON object containing \'thought\' and \'tool_calls\'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.\n` });
|
|
43
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
44
|
-
}
|
|
45
|
-
const { thought: decideThought, toolCalls, parallel } = parsedDecideResponse;
|
|
46
|
-
logger.thought(decideThought);
|
|
47
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: decideThought, tool_calls: toolCalls, parallel }) });
|
|
48
|
-
// Validate tool parameters for all tool calls
|
|
49
|
-
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
50
|
-
if (validationErrors.length > 0) {
|
|
51
|
-
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
52
|
-
logger.error(errorMessage);
|
|
53
|
-
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
54
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
55
|
-
}
|
|
56
|
-
// Handle finish tool (check here before acting)
|
|
57
|
-
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
58
|
-
if (finishToolCall) {
|
|
59
|
-
finalOutput = finishToolCall.parameters.output;
|
|
60
|
-
if (this.requireFinishConfirmation) {
|
|
61
|
-
const confirmNode = new UserInputNode();
|
|
62
|
-
confirmNode.setParams({
|
|
63
|
-
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
64
|
-
});
|
|
65
|
-
const confirmFlow = new AsyncFlow(confirmNode);
|
|
66
|
-
const confirmation = await confirmFlow.runAsync({});
|
|
67
|
-
if (confirmation.toLowerCase() !== 'yes') {
|
|
68
|
-
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
69
|
-
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
70
|
-
continue; // Continue the loop
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
logger.final(finalOutput);
|
|
74
|
-
break; // Exit the main loop as agent is finished
|
|
75
|
-
}
|
|
76
|
-
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
77
|
-
if (toolCalls.length === 0) {
|
|
78
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
|
|
79
|
-
continue; // Re-run the loop to force tool call generation
|
|
80
|
-
}
|
|
81
|
-
// Act
|
|
82
|
-
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
83
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
84
|
-
// Check for tool errors and add specific instructions for reflection
|
|
85
|
-
const toolErrors = observations.filter(obs => obs.success === false);
|
|
86
|
-
if (toolErrors.length > 0) {
|
|
87
|
-
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
88
|
-
this.conversationHistory.push({ role: "system", content: `
|
|
89
|
-
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
90
|
-
${errorMessages}
|
|
91
|
-
|
|
92
|
-
Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal.
|
|
93
|
-
` });
|
|
94
|
-
}
|
|
95
|
-
else {
|
|
96
|
-
// No specific reflect phase for OODA after act, it loops back to observe
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if (step >= this.maxSteps && finalOutput === null) {
|
|
100
|
-
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
101
|
-
logger.error(message);
|
|
102
|
-
finalOutput = message;
|
|
103
|
-
}
|
|
104
|
-
return finalOutput;
|
|
105
|
-
}
|
|
106
|
-
async executeToolCalls(toolCalls, parallel) {
|
|
107
|
-
const executeTool = async (toolCall) => {
|
|
108
|
-
const toolInstance = this.availableTools[toolCall.tool];
|
|
109
|
-
if (!toolInstance) {
|
|
110
|
-
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
111
|
-
}
|
|
112
|
-
let toolOutput;
|
|
113
|
-
try {
|
|
114
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
115
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
116
|
-
const flowName = toolCall.parameters.flow;
|
|
117
|
-
if (!this.flowRegistry[flowName]) {
|
|
118
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
119
|
-
}
|
|
120
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
121
|
-
}
|
|
122
|
-
toolInstance.setParams(toolCall.parameters);
|
|
123
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
124
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
125
|
-
if (toolInstance instanceof AsyncNode) {
|
|
126
|
-
toolOutput = await toolFlow.runAsync({});
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
toolOutput = toolFlow.run({});
|
|
130
|
-
}
|
|
131
|
-
logger.toolResult(toolCall.tool, toolOutput);
|
|
132
|
-
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
133
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
134
|
-
const summarizeNode = new SummarizeNode();
|
|
135
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
136
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
137
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
138
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
139
|
-
}
|
|
140
|
-
return { success: true, output: toolOutput };
|
|
141
|
-
}
|
|
142
|
-
catch (e) {
|
|
143
|
-
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
let observations = [];
|
|
147
|
-
if (parallel) {
|
|
148
|
-
const results = await Promise.all(toolCalls.map(executeTool));
|
|
149
|
-
observations = results.map((result, index) => ({
|
|
150
|
-
tool: toolCalls[index].tool,
|
|
151
|
-
parameters: toolCalls[index].parameters,
|
|
152
|
-
...result // Spread success/error and output/error
|
|
153
|
-
}));
|
|
154
|
-
}
|
|
155
|
-
else {
|
|
156
|
-
for (const toolCall of toolCalls) {
|
|
157
|
-
const result = await executeTool(toolCall);
|
|
158
|
-
observations.push({
|
|
159
|
-
tool: toolCall.tool,
|
|
160
|
-
parameters: toolCall.parameters,
|
|
161
|
-
...result // Spread success/error and output/error
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
return observations;
|
|
166
|
-
}
|
|
4
|
+
static strategyId = 'ooda';
|
|
167
5
|
}
|