kagent-ts 0.1.0
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/LICENSE +21 -0
- package/README.md +395 -0
- package/dist/compression/interface.d.ts +26 -0
- package/dist/compression/interface.d.ts.map +1 -0
- package/dist/compression/interface.js +3 -0
- package/dist/compression/interface.js.map +1 -0
- package/dist/compression/sliding-window.d.ts +21 -0
- package/dist/compression/sliding-window.d.ts.map +1 -0
- package/dist/compression/sliding-window.js +55 -0
- package/dist/compression/sliding-window.js.map +1 -0
- package/dist/compression/types.d.ts +12 -0
- package/dist/compression/types.d.ts.map +1 -0
- package/dist/compression/types.js +3 -0
- package/dist/compression/types.js.map +1 -0
- package/dist/context/context-manager.d.ts +76 -0
- package/dist/context/context-manager.d.ts.map +1 -0
- package/dist/context/context-manager.js +132 -0
- package/dist/context/context-manager.js.map +1 -0
- package/dist/context/types.d.ts +35 -0
- package/dist/context/types.d.ts.map +1 -0
- package/dist/context/types.js +3 -0
- package/dist/context/types.js.map +1 -0
- package/dist/core/agent.d.ts +288 -0
- package/dist/core/agent.d.ts.map +1 -0
- package/dist/core/agent.js +398 -0
- package/dist/core/agent.js.map +1 -0
- package/dist/core/hooks.d.ts +34 -0
- package/dist/core/hooks.d.ts.map +1 -0
- package/dist/core/hooks.js +3 -0
- package/dist/core/hooks.js.map +1 -0
- package/dist/core/plan-solve-agent.d.ts +114 -0
- package/dist/core/plan-solve-agent.d.ts.map +1 -0
- package/dist/core/plan-solve-agent.js +450 -0
- package/dist/core/plan-solve-agent.js.map +1 -0
- package/dist/core/react-agent.d.ts +52 -0
- package/dist/core/react-agent.d.ts.map +1 -0
- package/dist/core/react-agent.js +266 -0
- package/dist/core/react-agent.js.map +1 -0
- package/dist/core/response-schema.d.ts +91 -0
- package/dist/core/response-schema.d.ts.map +1 -0
- package/dist/core/response-schema.js +292 -0
- package/dist/core/response-schema.js.map +1 -0
- package/dist/core/types.d.ts +6 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +3 -0
- package/dist/core/types.js.map +1 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +67 -0
- package/dist/index.js.map +1 -0
- package/dist/llm/interface.d.ts +87 -0
- package/dist/llm/interface.d.ts.map +1 -0
- package/dist/llm/interface.js +3 -0
- package/dist/llm/interface.js.map +1 -0
- package/dist/llm/openai-provider.d.ts +92 -0
- package/dist/llm/openai-provider.d.ts.map +1 -0
- package/dist/llm/openai-provider.js +262 -0
- package/dist/llm/openai-provider.js.map +1 -0
- package/dist/messages/message.d.ts +50 -0
- package/dist/messages/message.d.ts.map +1 -0
- package/dist/messages/message.js +87 -0
- package/dist/messages/message.js.map +1 -0
- package/dist/messages/types.d.ts +31 -0
- package/dist/messages/types.d.ts.map +1 -0
- package/dist/messages/types.js +14 -0
- package/dist/messages/types.js.map +1 -0
- package/dist/preferences/preference-manager.d.ts +88 -0
- package/dist/preferences/preference-manager.d.ts.map +1 -0
- package/dist/preferences/preference-manager.js +196 -0
- package/dist/preferences/preference-manager.js.map +1 -0
- package/dist/preferences/types.d.ts +27 -0
- package/dist/preferences/types.d.ts.map +1 -0
- package/dist/preferences/types.js +3 -0
- package/dist/preferences/types.js.map +1 -0
- package/dist/session/session-manager.d.ts +56 -0
- package/dist/session/session-manager.d.ts.map +1 -0
- package/dist/session/session-manager.js +156 -0
- package/dist/session/session-manager.js.map +1 -0
- package/dist/session/session-types.d.ts +51 -0
- package/dist/session/session-types.d.ts.map +1 -0
- package/dist/session/session-types.js +3 -0
- package/dist/session/session-types.js.map +1 -0
- package/dist/skills/file-skill-loader.d.ts +88 -0
- package/dist/skills/file-skill-loader.d.ts.map +1 -0
- package/dist/skills/file-skill-loader.js +365 -0
- package/dist/skills/file-skill-loader.js.map +1 -0
- package/dist/skills/index.d.ts +4 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +10 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/skills/skill-manager.d.ts +133 -0
- package/dist/skills/skill-manager.d.ts.map +1 -0
- package/dist/skills/skill-manager.js +310 -0
- package/dist/skills/skill-manager.js.map +1 -0
- package/dist/skills/types.d.ts +42 -0
- package/dist/skills/types.d.ts.map +1 -0
- package/dist/skills/types.js +3 -0
- package/dist/skills/types.js.map +1 -0
- package/dist/tools/builtin/edit-file.d.ts +12 -0
- package/dist/tools/builtin/edit-file.d.ts.map +1 -0
- package/dist/tools/builtin/edit-file.js +123 -0
- package/dist/tools/builtin/edit-file.js.map +1 -0
- package/dist/tools/builtin/glob-search.d.ts +11 -0
- package/dist/tools/builtin/glob-search.d.ts.map +1 -0
- package/dist/tools/builtin/glob-search.js +264 -0
- package/dist/tools/builtin/glob-search.js.map +1 -0
- package/dist/tools/builtin/grep-search.d.ts +14 -0
- package/dist/tools/builtin/grep-search.d.ts.map +1 -0
- package/dist/tools/builtin/grep-search.js +264 -0
- package/dist/tools/builtin/grep-search.js.map +1 -0
- package/dist/tools/builtin/index.d.ts +21 -0
- package/dist/tools/builtin/index.d.ts.map +1 -0
- package/dist/tools/builtin/index.js +53 -0
- package/dist/tools/builtin/index.js.map +1 -0
- package/dist/tools/builtin/read-file.d.ts +11 -0
- package/dist/tools/builtin/read-file.d.ts.map +1 -0
- package/dist/tools/builtin/read-file.js +122 -0
- package/dist/tools/builtin/read-file.js.map +1 -0
- package/dist/tools/builtin/write-file.d.ts +10 -0
- package/dist/tools/builtin/write-file.d.ts.map +1 -0
- package/dist/tools/builtin/write-file.js +89 -0
- package/dist/tools/builtin/write-file.js.map +1 -0
- package/dist/tools/circuit-breaker.d.ts +77 -0
- package/dist/tools/circuit-breaker.d.ts.map +1 -0
- package/dist/tools/circuit-breaker.js +102 -0
- package/dist/tools/circuit-breaker.js.map +1 -0
- package/dist/tools/error-tracker.d.ts +116 -0
- package/dist/tools/error-tracker.d.ts.map +1 -0
- package/dist/tools/error-tracker.js +484 -0
- package/dist/tools/error-tracker.js.map +1 -0
- package/dist/tools/tool-registry.d.ts +87 -0
- package/dist/tools/tool-registry.d.ts.map +1 -0
- package/dist/tools/tool-registry.js +188 -0
- package/dist/tools/tool-registry.js.map +1 -0
- package/dist/tools/types.d.ts +95 -0
- package/dist/tools/types.d.ts.map +1 -0
- package/dist/tools/types.js +14 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/utils/token-counter.d.ts +31 -0
- package/dist/utils/token-counter.d.ts.map +1 -0
- package/dist/utils/token-counter.js +105 -0
- package/dist/utils/token-counter.js.map +1 -0
- package/package.json +56 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PlanSolveAgent = void 0;
|
|
4
|
+
const agent_1 = require("./agent");
|
|
5
|
+
const message_1 = require("../messages/message");
|
|
6
|
+
const response_schema_1 = require("./response-schema");
|
|
7
|
+
const openai_provider_1 = require("../llm/openai-provider");
|
|
8
|
+
const preference_manager_1 = require("../preferences/preference-manager");
|
|
9
|
+
/**
|
|
10
|
+
* Default system prompt for the Plan-and-Solve paradigm.
|
|
11
|
+
*
|
|
12
|
+
* The LLM is instructed to separate planning from execution:
|
|
13
|
+
* 1. Phase 1 — PLAN: Analyze and create a detailed numbered plan.
|
|
14
|
+
* 2. Phase 2 — RESOLVE: Work through each step, using tools as needed.
|
|
15
|
+
* The plan can be revised mid-execution when new information emerges.
|
|
16
|
+
* 3. FINAL: When all steps are complete, output the full answer.
|
|
17
|
+
*/
|
|
18
|
+
const DEFAULT_PLAN_SOLVE_SYSTEM_PROMPT = `You are a helpful AI assistant powered by the Plan-and-Resolve paradigm.
|
|
19
|
+
You have access to a set of tools you can use to answer the user's question.
|
|
20
|
+
|
|
21
|
+
Process:
|
|
22
|
+
1. First, analyze the user's request and create a detailed plan.
|
|
23
|
+
2. Then, work through each step of the plan using tools as needed.
|
|
24
|
+
3. If you encounter unexpected information or tool failures, revise the remaining steps.
|
|
25
|
+
4. When all steps are complete, provide the final answer.
|
|
26
|
+
|
|
27
|
+
If no tools are needed, respond with the final answer directly.
|
|
28
|
+
|
|
29
|
+
=== Tool Error Recovery ===
|
|
30
|
+
When a tool returns an error:
|
|
31
|
+
1. READ the error message carefully — understand WHY it failed.
|
|
32
|
+
2. ANALYZE whether the parameters were correct. Common issues:
|
|
33
|
+
- Wrong file path (check spelling, use absolute paths)
|
|
34
|
+
- Missing or incorrect arguments
|
|
35
|
+
- The tool may need different input formats
|
|
36
|
+
3. RETRY with corrected parameters if you can fix the issue.
|
|
37
|
+
4. If the same tool fails repeatedly, try a COMPLETELY DIFFERENT approach.
|
|
38
|
+
5. If a tool fails 2+ times in a row, consider whether your PLAN needs revision.
|
|
39
|
+
The approach may be fundamentally wrong — output a "revised_plan".
|
|
40
|
+
6. If a tool is disabled after too many failures, DO NOT try to use it again.
|
|
41
|
+
Find another way to accomplish the task.${response_schema_1.PLAN_SOLVE_INSTRUCTIONS}`;
|
|
42
|
+
/**
|
|
43
|
+
* Plan-and-Solve Agent implementing a structured Plan → Resolve → Final Answer loop.
|
|
44
|
+
*
|
|
45
|
+
* This paradigm separates high-level planning from step-by-step execution:
|
|
46
|
+
* - **Phase 1 (Plan):** The LLM analyzes the request and creates a numbered plan.
|
|
47
|
+
* - **Phase 2 (Resolve):** The LLM executes each step, using tools. The plan is
|
|
48
|
+
* injected into the system prompt to keep the LLM focused. If obstacles arise,
|
|
49
|
+
* the LLM can output a `revised_plan` to adjust remaining steps.
|
|
50
|
+
* - **Final:** When all steps are complete, the LLM provides the final answer.
|
|
51
|
+
*
|
|
52
|
+
* Compared to ReAct, Plan-and-Solve encourages more deliberate decomposition
|
|
53
|
+
* up front, reducing the chance of the agent getting lost mid-task.
|
|
54
|
+
*
|
|
55
|
+
* Session persistence:
|
|
56
|
+
* When `enableCheckpointing` is set, the agent auto-saves checkpoints that
|
|
57
|
+
* include full plan state (current plan, completed steps, replan info) so the
|
|
58
|
+
* session can be resumed after a network interruption.
|
|
59
|
+
*/
|
|
60
|
+
class PlanSolveAgent extends agent_1.Agent {
|
|
61
|
+
maxIterations;
|
|
62
|
+
maxPlanSteps;
|
|
63
|
+
enableSkillAutoDetect;
|
|
64
|
+
/** The current plan steps (empty until the plan is created). */
|
|
65
|
+
currentPlan = [];
|
|
66
|
+
/** Whether a plan has been created in this run. */
|
|
67
|
+
hasPlan = false;
|
|
68
|
+
/**
|
|
69
|
+
* How many consecutive tool failures before a replan hint is injected.
|
|
70
|
+
* 0 = disabled (no auto-replanning hints).
|
|
71
|
+
*/
|
|
72
|
+
replanThreshold;
|
|
73
|
+
/** Consecutive tool failures in the current run (resets on success). */
|
|
74
|
+
consecutiveFailures = 0;
|
|
75
|
+
/** How many plan steps have been completed (used for plan display). */
|
|
76
|
+
completedSteps = 0;
|
|
77
|
+
/** Internal flag: when true, run() skips plan state reset (used by resume()). */
|
|
78
|
+
_skipPlanReset = false;
|
|
79
|
+
constructor(config) {
|
|
80
|
+
// Set default Plan-Solve system prompt if none provided
|
|
81
|
+
const mergedConfig = {
|
|
82
|
+
...config,
|
|
83
|
+
systemPrompt: config.systemPrompt ?? DEFAULT_PLAN_SOLVE_SYSTEM_PROMPT,
|
|
84
|
+
};
|
|
85
|
+
super(mergedConfig);
|
|
86
|
+
this.maxIterations = config.maxIterations ?? 15;
|
|
87
|
+
this.maxPlanSteps = config.maxPlanSteps ?? 12;
|
|
88
|
+
this.enableSkillAutoDetect = config.enableSkillAutoDetect ?? true;
|
|
89
|
+
this.replanThreshold = config.replanThreshold ?? 2;
|
|
90
|
+
// If skills are registered, rebuild the system prompt so the
|
|
91
|
+
// available-skills hint is included in the initial prompt.
|
|
92
|
+
if (this.skillManager.activeCount > 0) {
|
|
93
|
+
this.rebuildSystemPrompt();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async run(input) {
|
|
97
|
+
// ── Phase 0: Progressive disclosure ──────────────────────────────
|
|
98
|
+
if (this.enableSkillAutoDetect && this.skillManager.activeCount >= 0) {
|
|
99
|
+
const activated = this.skillManager.detectAndActivate(input);
|
|
100
|
+
if (activated.length > 0) {
|
|
101
|
+
this.rebuildSystemPrompt();
|
|
102
|
+
console.log(`[Skills] Auto-activated: ${activated.join(", ")}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// ── Create user message ─────────────────────────────────────────
|
|
106
|
+
const userMessage = message_1.Message.user(input);
|
|
107
|
+
this.contextManager.addMessage(userMessage.toDict());
|
|
108
|
+
// Reset plan state for this run (skip when resuming a session)
|
|
109
|
+
if (!this._skipPlanReset) {
|
|
110
|
+
this.currentPlan = [];
|
|
111
|
+
this.hasPlan = false;
|
|
112
|
+
this.consecutiveFailures = 0;
|
|
113
|
+
this.completedSteps = 0;
|
|
114
|
+
}
|
|
115
|
+
this._skipPlanReset = false;
|
|
116
|
+
// Save initial checkpoint (captures user input before any LLM call)
|
|
117
|
+
if (this.checkpointingEnabled) {
|
|
118
|
+
this.saveCheckpoint("active");
|
|
119
|
+
}
|
|
120
|
+
// Track consecutive unproductive iterations (no tool calls, no answer)
|
|
121
|
+
let consecutiveEmptyIterations = 0;
|
|
122
|
+
const EMPTY_ITERATION_LIMIT = 5;
|
|
123
|
+
// ── Main Plan-Solve loop ────────────────────────────────────────
|
|
124
|
+
for (let iteration = 0; iteration < this.maxIterations; iteration++) {
|
|
125
|
+
// Check if user cancelled (SIGINT)
|
|
126
|
+
if (this.isCancelled) {
|
|
127
|
+
this.sessionManager?.deleteSession(this.sessionManager.getSessionId());
|
|
128
|
+
return "Execution cancelled by user. Session discarded.";
|
|
129
|
+
}
|
|
130
|
+
this.checkAndCompress();
|
|
131
|
+
// Rebuild the system prompt to inject current plan progress
|
|
132
|
+
// and any replan hint if consecutive failures are detected
|
|
133
|
+
const replanHint = this.computeReplanHint();
|
|
134
|
+
this.rebuildContextWithPlan(replanHint);
|
|
135
|
+
const contextMessages = this.contextManager.getContextMessages();
|
|
136
|
+
// Call the LLM — with network error handling
|
|
137
|
+
this.hooks.onLLMStart?.();
|
|
138
|
+
let response;
|
|
139
|
+
try {
|
|
140
|
+
response = await this.llm.chat(contextMessages, this.toolRegistry.getTools());
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
if (err instanceof openai_provider_1.LLMNetworkError) {
|
|
144
|
+
this.hooks.onLLMError?.(err);
|
|
145
|
+
return this.handleNetworkError(err, iteration + 1);
|
|
146
|
+
}
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
this.hooks.onLLMEnd?.(response);
|
|
150
|
+
const parsed = (0, response_schema_1.parsePlanSolveResponse)(response.content);
|
|
151
|
+
// Create assistant message from the response
|
|
152
|
+
const assistantMessage = message_1.Message.assistant(response.content, response.tool_calls);
|
|
153
|
+
this.contextManager.addMessage(assistantMessage.toDict());
|
|
154
|
+
// ── Handle tool calls (execution phase) ─────────────────────
|
|
155
|
+
if (response.tool_calls && response.tool_calls.length > 0) {
|
|
156
|
+
consecutiveEmptyIterations = 0;
|
|
157
|
+
if (parsed.thought) {
|
|
158
|
+
console.log(`[Thought] ${parsed.thought}`);
|
|
159
|
+
this.hooks.onThought?.(parsed.thought);
|
|
160
|
+
this.captureAnalysisFromThought(parsed.thought);
|
|
161
|
+
}
|
|
162
|
+
// Track whether ANY tool in this round failed
|
|
163
|
+
let roundHadFailure = false;
|
|
164
|
+
for (const toolCall of response.tool_calls) {
|
|
165
|
+
let args;
|
|
166
|
+
try {
|
|
167
|
+
args = JSON.parse(toolCall.function.arguments);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
args = {};
|
|
171
|
+
}
|
|
172
|
+
this.hooks.onToolStart?.(toolCall.function.name, args);
|
|
173
|
+
let result;
|
|
174
|
+
try {
|
|
175
|
+
result = await this.toolRegistry.execute(toolCall.function.name, args);
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
179
|
+
result = `Error executing tool "${toolCall.function.name}": ${message}`;
|
|
180
|
+
}
|
|
181
|
+
// Track failure/success for replan detection and hooks
|
|
182
|
+
if (result.startsWith("Error")) {
|
|
183
|
+
roundHadFailure = true;
|
|
184
|
+
this.hooks.onToolError?.(toolCall.function.name, result);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
this.hooks.onToolEnd?.(toolCall.function.name, result);
|
|
188
|
+
}
|
|
189
|
+
// Track this result for error analysis if it indicates a failure
|
|
190
|
+
this.trackToolErrorForAnalysis(toolCall.function.name, result);
|
|
191
|
+
const toolMessage = message_1.Message.tool(result, toolCall.id, toolCall.function.name);
|
|
192
|
+
this.contextManager.addMessage(toolMessage.toDict());
|
|
193
|
+
}
|
|
194
|
+
// Update consecutive failure count and step progress
|
|
195
|
+
if (roundHadFailure) {
|
|
196
|
+
this.consecutiveFailures++;
|
|
197
|
+
console.log(`[Replan] Consecutive failures: ${this.consecutiveFailures}` +
|
|
198
|
+
(this.replanThreshold > 0 &&
|
|
199
|
+
this.consecutiveFailures >= this.replanThreshold
|
|
200
|
+
? ` — threshold reached (${this.replanThreshold}), will prompt replan`
|
|
201
|
+
: ""));
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
// Reset failure counter on success
|
|
205
|
+
this.consecutiveFailures = 0;
|
|
206
|
+
// Advance completed steps based on LLM-reported progress
|
|
207
|
+
if (parsed.currentStep && this.hasPlan) {
|
|
208
|
+
this.completedSteps = Math.max(this.completedSteps, Math.min(parsed.currentStep - 1, this.currentPlan.length));
|
|
209
|
+
}
|
|
210
|
+
else if (this.hasPlan) {
|
|
211
|
+
this.completedSteps = Math.min(this.completedSteps + 1, this.currentPlan.length);
|
|
212
|
+
}
|
|
213
|
+
if (this.hasPlan) {
|
|
214
|
+
console.log(`[Progress] Step ${this.completedSteps}/${this.currentPlan.length} completed`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// Save checkpoint after complete tool execution round
|
|
218
|
+
if (this.checkpointingEnabled) {
|
|
219
|
+
this.saveCheckpoint("active");
|
|
220
|
+
}
|
|
221
|
+
// Continue the loop for the next thought
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
// ── Final answer ────────────────────────────────────────────
|
|
225
|
+
if (parsed.answer) {
|
|
226
|
+
if (parsed.thought) {
|
|
227
|
+
console.log(`[Thought] ${parsed.thought}`);
|
|
228
|
+
this.hooks.onThought?.(parsed.thought);
|
|
229
|
+
}
|
|
230
|
+
console.log(`[Plan-Solve] Task complete — returning final answer.`);
|
|
231
|
+
// Save final checkpoint as completed
|
|
232
|
+
if (this.checkpointingEnabled) {
|
|
233
|
+
this.saveCheckpoint("completed");
|
|
234
|
+
}
|
|
235
|
+
this.hooks.onFinish?.(parsed.answer);
|
|
236
|
+
return parsed.answer;
|
|
237
|
+
}
|
|
238
|
+
// ── Initial plan creation ───────────────────────────────────
|
|
239
|
+
if (!this.hasPlan &&
|
|
240
|
+
parsed.plan &&
|
|
241
|
+
Array.isArray(parsed.plan) &&
|
|
242
|
+
parsed.plan.length > 0) {
|
|
243
|
+
consecutiveEmptyIterations = 0;
|
|
244
|
+
this.currentPlan = parsed.plan.slice(0, this.maxPlanSteps);
|
|
245
|
+
this.hasPlan = true;
|
|
246
|
+
console.log(`[Plan] Created ${this.currentPlan.length}-step plan:`);
|
|
247
|
+
for (let i = 0; i < this.currentPlan.length; i++) {
|
|
248
|
+
console.log(` ${i + 1}. ${this.currentPlan[i]}`);
|
|
249
|
+
}
|
|
250
|
+
this.hooks.onPlanCreated?.(this.currentPlan);
|
|
251
|
+
if (parsed.thought) {
|
|
252
|
+
console.log(`[Thought] ${parsed.thought}`);
|
|
253
|
+
this.hooks.onThought?.(parsed.thought);
|
|
254
|
+
}
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
// ── Plan revision ───────────────────────────────────────────
|
|
258
|
+
if (parsed.revised_plan &&
|
|
259
|
+
Array.isArray(parsed.revised_plan) &&
|
|
260
|
+
parsed.revised_plan.length > 0) {
|
|
261
|
+
consecutiveEmptyIterations = 0;
|
|
262
|
+
this.currentPlan = parsed.revised_plan.slice(0, this.maxPlanSteps);
|
|
263
|
+
this.completedSteps = 0; // Remaining steps are now new
|
|
264
|
+
console.log(`[Plan] Revised — ${this.currentPlan.length} steps remaining:`);
|
|
265
|
+
for (let i = 0; i < this.currentPlan.length; i++) {
|
|
266
|
+
console.log(` ${i + 1}. ${this.currentPlan[i]}`);
|
|
267
|
+
}
|
|
268
|
+
this.hooks.onPlanRevised?.(this.currentPlan);
|
|
269
|
+
if (parsed.thought) {
|
|
270
|
+
console.log(`[Thought] ${parsed.thought}`);
|
|
271
|
+
this.hooks.onThought?.(parsed.thought);
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
// ── Default: log thought and continue loop ──────────────────
|
|
276
|
+
if (parsed.thought) {
|
|
277
|
+
consecutiveEmptyIterations++;
|
|
278
|
+
console.log(`[Thought] ${parsed.thought}`);
|
|
279
|
+
this.hooks.onThought?.(parsed.thought);
|
|
280
|
+
this.captureAnalysisFromThought(parsed.thought);
|
|
281
|
+
// If stuck in thought-only loop, bail out
|
|
282
|
+
if (consecutiveEmptyIterations >= EMPTY_ITERATION_LIMIT) {
|
|
283
|
+
const stuckMsg = "I apologize, but I'm having difficulty making progress on your request. " +
|
|
284
|
+
"Please try rephrasing or breaking it down into smaller, more specific steps.";
|
|
285
|
+
const stuckAssistantMessage = message_1.Message.assistant(stuckMsg);
|
|
286
|
+
this.contextManager.addMessage(stuckAssistantMessage.toDict());
|
|
287
|
+
this.hooks.onFinish?.(stuckMsg);
|
|
288
|
+
return stuckMsg;
|
|
289
|
+
}
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
// Empty response (no thought, no answer, no tool calls, no plan)
|
|
293
|
+
consecutiveEmptyIterations++;
|
|
294
|
+
if (consecutiveEmptyIterations >= EMPTY_ITERATION_LIMIT) {
|
|
295
|
+
const stuckMsg = "I apologize, but I'm having difficulty making progress on your request. " +
|
|
296
|
+
"Please try rephrasing or breaking it down into smaller, more specific steps.";
|
|
297
|
+
const stuckAssistantMessage = message_1.Message.assistant(stuckMsg);
|
|
298
|
+
this.contextManager.addMessage(stuckAssistantMessage.toDict());
|
|
299
|
+
this.hooks.onFinish?.(stuckMsg);
|
|
300
|
+
return stuckMsg;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// ── Max iterations reached without final answer ──────────────
|
|
304
|
+
const timeoutMsg = `I apologize, but I was unable to complete the task within ${this.maxIterations} iterations. ` +
|
|
305
|
+
`Please try breaking your request into smaller steps.`;
|
|
306
|
+
const timeoutAssistantMessage = message_1.Message.assistant(timeoutMsg);
|
|
307
|
+
this.contextManager.addMessage(timeoutAssistantMessage.toDict());
|
|
308
|
+
return timeoutMsg;
|
|
309
|
+
}
|
|
310
|
+
// ─── Session Persistence Overrides ───────────────────────────────────
|
|
311
|
+
/**
|
|
312
|
+
* Agent type identifier for session metadata.
|
|
313
|
+
*/
|
|
314
|
+
getAgentType() {
|
|
315
|
+
return "plan-solve";
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Include plan state in session checkpoints.
|
|
319
|
+
*/
|
|
320
|
+
buildBaseSessionState(status) {
|
|
321
|
+
const base = super.buildBaseSessionState(status);
|
|
322
|
+
return {
|
|
323
|
+
...base,
|
|
324
|
+
planState: {
|
|
325
|
+
currentPlan: this.currentPlan,
|
|
326
|
+
hasPlan: this.hasPlan,
|
|
327
|
+
completedSteps: this.completedSteps,
|
|
328
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Restore plan state from a saved session.
|
|
334
|
+
*/
|
|
335
|
+
loadAndRestoreSession(sessionId) {
|
|
336
|
+
const state = super.loadAndRestoreSession(sessionId);
|
|
337
|
+
if (state.planState) {
|
|
338
|
+
this.currentPlan = state.planState.currentPlan;
|
|
339
|
+
this.hasPlan = state.planState.hasPlan;
|
|
340
|
+
this.completedSteps = state.planState.completedSteps;
|
|
341
|
+
this.consecutiveFailures = state.planState.consecutiveFailures;
|
|
342
|
+
}
|
|
343
|
+
return state;
|
|
344
|
+
}
|
|
345
|
+
// ─── Resume ──────────────────────────────────────────────────────────
|
|
346
|
+
/**
|
|
347
|
+
* Resume a previously interrupted session.
|
|
348
|
+
*
|
|
349
|
+
* Restores messages, system prompt, and plan state so the agent can
|
|
350
|
+
* continue from where it left off.
|
|
351
|
+
*
|
|
352
|
+
* @param sessionId The session ID to resume.
|
|
353
|
+
* @param input New user input to continue the conversation.
|
|
354
|
+
*/
|
|
355
|
+
async resume(sessionId, input) {
|
|
356
|
+
this.loadAndRestoreSession(sessionId);
|
|
357
|
+
// Signal run() to preserve the restored plan state
|
|
358
|
+
this._skipPlanReset = true;
|
|
359
|
+
return this.run(input);
|
|
360
|
+
}
|
|
361
|
+
// ─── Private Helpers ─────────────────────────────────────────────────
|
|
362
|
+
/**
|
|
363
|
+
* Handle an LLMNetworkError: save an interrupted checkpoint if
|
|
364
|
+
* checkpointing is enabled, and return a user-facing message with
|
|
365
|
+
* resume instructions.
|
|
366
|
+
*/
|
|
367
|
+
handleNetworkError(err, iteration) {
|
|
368
|
+
if (this.checkpointingEnabled) {
|
|
369
|
+
this.saveCheckpoint("interrupted");
|
|
370
|
+
}
|
|
371
|
+
const sid = this.sessionManager?.getSessionId() ?? "unknown";
|
|
372
|
+
console.error(`\n[Network Error] ${err.cause}: ${err.message}`);
|
|
373
|
+
if (this.checkpointingEnabled && this.sessionManager) {
|
|
374
|
+
return (`[Network Error] ${err.message}\n\n` +
|
|
375
|
+
`Your session "${sid}" has been saved (iteration ${iteration}).\n` +
|
|
376
|
+
`After your network is restored, resume with:\n` +
|
|
377
|
+
` agent.resume("${sid}", "continue with what you were doing")\n\n` +
|
|
378
|
+
`Or start a new session by calling agent.run() again.`);
|
|
379
|
+
}
|
|
380
|
+
return (`[Network Error] ${err.message}\n\n` +
|
|
381
|
+
`Please check your network connection and try again.`);
|
|
382
|
+
}
|
|
383
|
+
// ─── Plan Context Injection ─────────────────────────────────────────────
|
|
384
|
+
/**
|
|
385
|
+
* Rebuild the system prompt to include the current plan context
|
|
386
|
+
* alongside the core prompt and active skill prompts.
|
|
387
|
+
*
|
|
388
|
+
* Called each iteration so the LLM always sees the up-to-date plan.
|
|
389
|
+
*
|
|
390
|
+
* @param replanHint Optional hint injected when consecutive tool
|
|
391
|
+
* failures exceed the threshold, nudging the LLM
|
|
392
|
+
* to consider revising its plan.
|
|
393
|
+
*/
|
|
394
|
+
rebuildContextWithPlan(replanHint) {
|
|
395
|
+
let prompt = this.coreSystemPrompt;
|
|
396
|
+
// User preferences — injected as a system-prompt section
|
|
397
|
+
prompt += preference_manager_1.PreferenceManager.toPrompt(this.preferences);
|
|
398
|
+
// Available skills hint (progressive disclosure — names only)
|
|
399
|
+
prompt += this.skillManager.buildAvailableSkillsHint();
|
|
400
|
+
// Plan context — injected when a plan exists
|
|
401
|
+
if (this.hasPlan && this.currentPlan.length > 0) {
|
|
402
|
+
prompt += `\n\n=== Current Plan (${this.completedSteps}/${this.currentPlan.length} completed) ===\n`;
|
|
403
|
+
for (let i = 0; i < this.currentPlan.length; i++) {
|
|
404
|
+
const marker = i < this.completedSteps
|
|
405
|
+
? "✅"
|
|
406
|
+
: i === this.completedSteps
|
|
407
|
+
? "➡️"
|
|
408
|
+
: " ";
|
|
409
|
+
prompt += ` ${marker} ${i + 1}. ${this.currentPlan[i]}\n`;
|
|
410
|
+
}
|
|
411
|
+
prompt +=
|
|
412
|
+
`\nWork through the plan step by step. ` +
|
|
413
|
+
`When you complete a step, move to the next one. ` +
|
|
414
|
+
`If you need to revise remaining steps, output a "revised_plan".`;
|
|
415
|
+
}
|
|
416
|
+
// Replan hint — injected when consecutive failures are detected
|
|
417
|
+
if (replanHint) {
|
|
418
|
+
prompt += `\n\n${replanHint}`;
|
|
419
|
+
}
|
|
420
|
+
// Active skill instructions
|
|
421
|
+
prompt += this.skillManager.buildSkillsPrompt();
|
|
422
|
+
this.contextManager.setSystemMessage(prompt);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Compute a replan hint based on the current consecutive failure count.
|
|
426
|
+
*
|
|
427
|
+
* When consecutive failures reach the configured threshold, a message is
|
|
428
|
+
* returned that will be appended to the system prompt, nudging the LLM
|
|
429
|
+
* to consider revising its plan rather than continuing with a failing approach.
|
|
430
|
+
*
|
|
431
|
+
* Returns undefined when no hint is needed (failures below threshold
|
|
432
|
+
* or auto-replan is disabled).
|
|
433
|
+
*/
|
|
434
|
+
computeReplanHint() {
|
|
435
|
+
if (this.replanThreshold <= 0)
|
|
436
|
+
return undefined;
|
|
437
|
+
if (!this.hasPlan)
|
|
438
|
+
return undefined;
|
|
439
|
+
if (this.consecutiveFailures >= this.replanThreshold) {
|
|
440
|
+
return (`⚠️ REPLAN SUGGESTED: Multiple consecutive tool failures detected (${this.consecutiveFailures}).\n` +
|
|
441
|
+
`The current approach may be fundamentally wrong.\n` +
|
|
442
|
+
`Please consider whether your plan needs revision. If so, output a "revised_plan" ` +
|
|
443
|
+
`with a new strategy for the remaining steps. Only the REMAINING steps — ` +
|
|
444
|
+
`do NOT re-list already completed steps.`);
|
|
445
|
+
}
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
exports.PlanSolveAgent = PlanSolveAgent;
|
|
450
|
+
//# sourceMappingURL=plan-solve-agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan-solve-agent.js","sourceRoot":"","sources":["../../src/core/plan-solve-agent.ts"],"names":[],"mappings":";;;AAAA,mCAA6C;AAC7C,iDAA8C;AAC9C,uDAG2B;AAC3B,4DAAyD;AAGzD,0EAAsE;AAEtE;;;;;;;;GAQG;AACH,MAAM,gCAAgC,GAAG;;;;;;;;;;;;;;;;;;;;;;;6CAuBI,yCAAuB,EAAE,CAAC;AA2BvE;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,cAAe,SAAQ,aA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IAAI,OAAO,UAAU,EAAE,CAAC;QAChC,CAAC;QAED,4BAA4B;QAC5B,MAAM,IAAI,IAAI,CAAC,YAAY,CAAC,iBAAiB,EAAE,CAAC;QAEhD,IAAI,CAAC,cAAc,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;;;;OASG;IACK,iBAAiB;QACvB,IAAI,IAAI,CAAC,eAAe,IAAI,CAAC;YAAE,OAAO,SAAS,CAAC;QAChD,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO,SAAS,CAAC;QACpC,IAAI,IAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACrD,OAAO,CACL,qEAAqE,IAAI,CAAC,mBAAmB,MAAM;gBACnG,oDAAoD;gBACpD,mFAAmF;gBACnF,0EAA0E;gBAC1E,yCAAyC,CAC1C,CAAC;QACJ,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA3eD,wCA2eC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Agent, AgentConfig } from "./agent";
|
|
2
|
+
/**
|
|
3
|
+
* Configuration specific to the ReAct Agent.
|
|
4
|
+
*/
|
|
5
|
+
export interface ReActAgentConfig extends AgentConfig {
|
|
6
|
+
/** Maximum iterations for the ReAct loop (default: 10). */
|
|
7
|
+
maxIterations?: number;
|
|
8
|
+
/**
|
|
9
|
+
* Enable progressive skill disclosure.
|
|
10
|
+
* When true, skills are auto-detected from user input and loaded
|
|
11
|
+
* into the system prompt on demand (default: true).
|
|
12
|
+
*/
|
|
13
|
+
enableSkillAutoDetect?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* ReAct Agent implementing a structured Thought → Action → Observation → Final Answer loop.
|
|
17
|
+
*
|
|
18
|
+
* The agent uses structured JSON output from the LLM:
|
|
19
|
+
* - Intermediate steps: {"thought": "..."}
|
|
20
|
+
* - Final answer: {"thought": "...", "answer": "..."}
|
|
21
|
+
* - Tool calls via native function calling (OpenAI tool_calls)
|
|
22
|
+
*
|
|
23
|
+
* Session persistence:
|
|
24
|
+
* When `enableCheckpointing` is set, the agent auto-saves checkpoints after
|
|
25
|
+
* each LLM+tools cycle. On network error, an `interrupted` checkpoint is
|
|
26
|
+
* saved so the user can resume later via `agent.resume(sessionId, input)`.
|
|
27
|
+
*/
|
|
28
|
+
export declare class ReActAgent extends Agent {
|
|
29
|
+
private maxIterations;
|
|
30
|
+
private enableSkillAutoDetect;
|
|
31
|
+
constructor(config: ReActAgentConfig);
|
|
32
|
+
run(input: string): Promise<string>;
|
|
33
|
+
/**
|
|
34
|
+
* Resume a previously interrupted session.
|
|
35
|
+
*
|
|
36
|
+
* Loads the saved session state (messages, system prompt) so the agent
|
|
37
|
+
* can continue from where it left off. The `input` is treated as a new
|
|
38
|
+
* user message appended to the restored conversation.
|
|
39
|
+
*
|
|
40
|
+
* @param sessionId The session ID to resume.
|
|
41
|
+
* @param input New user input to continue the conversation.
|
|
42
|
+
* @returns The agent's final response.
|
|
43
|
+
*/
|
|
44
|
+
resume(sessionId: string, input: string): Promise<string>;
|
|
45
|
+
/**
|
|
46
|
+
* Handle an LLMNetworkError: save an interrupted checkpoint if
|
|
47
|
+
* checkpointing is enabled, and return a user-facing message with
|
|
48
|
+
* resume instructions.
|
|
49
|
+
*/
|
|
50
|
+
private handleNetworkError;
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=react-agent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react-agent.d.ts","sourceRoot":"","sources":["../../src/core/react-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAyC7C;;GAEG;AACH,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,UAAW,SAAQ,KAAK;IACnC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,qBAAqB,CAAU;gBAE3B,MAAM,EAAE,gBAAgB;IAkB9B,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA2MzC;;;;;;;;;;OAUG;IACG,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAO/D;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;CA2B3B"}
|