@codebolt/agent 6.0.0 → 6.1.2
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/README.md +118 -153
- package/dist/index.d.ts +2 -0
- package/dist/index.js +41 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +2 -4
- package/dist/processor-pieces/messageModifiers/contextAssemblyModifier.d.ts +81 -0
- package/dist/processor-pieces/messageModifiers/contextAssemblyModifier.js +316 -0
- package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +2 -19
- package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +2 -6
- package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +2 -7
- package/dist/processor-pieces/messageModifiers/ideContextModifier.js +2 -21
- package/dist/processor-pieces/messageModifiers/index.d.ts +3 -0
- package/dist/processor-pieces/messageModifiers/index.js +7 -1
- package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +2 -1
- package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +34 -5
- package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +374 -89
- package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.d.ts +3 -0
- package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +50 -27
- package/dist/unified/agent/agent.d.ts +10 -0
- package/dist/unified/agent/agent.js +198 -10
- package/dist/unified/agent/codeboltAgent.d.ts +19 -100
- package/dist/unified/agent/codeboltAgent.js +209 -109
- package/dist/unified/base/agentStep.js +17 -17
- package/dist/unified/base/initialPromptGenerator.js +13 -31
- package/dist/unified/base/promptContext.d.ts +13 -0
- package/dist/unified/base/promptContext.js +213 -0
- package/dist/unified/base/responseExecutor.d.ts +7 -19
- package/dist/unified/base/responseExecutor.js +280 -259
- package/dist/unified/index.d.ts +9 -0
- package/dist/unified/index.js +20 -13
- package/dist/unified/services/CompressionCoordinator.d.ts +67 -0
- package/dist/unified/services/CompressionCoordinator.js +214 -0
- package/dist/unified/services/compaction/autoCompact.d.ts +52 -0
- package/dist/unified/services/compaction/autoCompact.js +294 -0
- package/dist/unified/services/compaction/compactionOrchestrator.d.ts +78 -0
- package/dist/unified/services/compaction/compactionOrchestrator.js +230 -0
- package/dist/unified/services/compaction/contextCollapse.d.ts +63 -0
- package/dist/unified/services/compaction/contextCollapse.js +291 -0
- package/dist/unified/services/compaction/microCompact.d.ts +34 -0
- package/dist/unified/services/compaction/microCompact.js +195 -0
- package/dist/unified/services/compaction/postCompactCleanup.d.ts +15 -0
- package/dist/unified/services/compaction/postCompactCleanup.js +37 -0
- package/dist/unified/services/compaction/reactiveCompact.d.ts +65 -0
- package/dist/unified/services/compaction/reactiveCompact.js +301 -0
- package/dist/unified/services/compaction/snipCompact.d.ts +31 -0
- package/dist/unified/services/compaction/snipCompact.js +124 -0
- package/dist/unified/services/compaction/types.d.ts +66 -0
- package/dist/unified/services/compaction/types.js +39 -0
- package/package.json +25 -29
|
@@ -1,70 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
exports.CodeboltAgent = void 0;
|
|
4
7
|
exports.createCodeboltAgent = createCodeboltAgent;
|
|
8
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
5
9
|
const base_1 = require("../base");
|
|
6
|
-
const responseExecutor_1 = require("../base/responseExecutor");
|
|
7
10
|
const agentStep_1 = require("../base/agentStep");
|
|
11
|
+
const responseExecutor_1 = require("../base/responseExecutor");
|
|
12
|
+
const promptContext_1 = require("../base/promptContext");
|
|
13
|
+
const compactionOrchestrator_1 = require("../services/compaction/compactionOrchestrator");
|
|
8
14
|
const processor_pieces_1 = require("../../processor-pieces");
|
|
9
|
-
/**
|
|
10
|
-
* CodeboltAgent is a high-level agent class that:
|
|
11
|
-
* - Uses InitialPromptGenerator with configurable processors/modifiers
|
|
12
|
-
* - Runs an agent loop with AgentStep and ResponseExecutor
|
|
13
|
-
* - Handles tool execution and conversation flow automatically
|
|
14
|
-
* - Is triggered via processMessage (not via onMessage listener)
|
|
15
|
-
*
|
|
16
|
-
* @example
|
|
17
|
-
* ```typescript
|
|
18
|
-
* import { CodeboltAgent } from '@codebolt/agent/unified';
|
|
19
|
-
* import {
|
|
20
|
-
* EnvironmentContextModifier,
|
|
21
|
-
* CoreSystemPromptModifier,
|
|
22
|
-
* DirectoryContextModifier,
|
|
23
|
-
* IdeContextModifier,
|
|
24
|
-
* AtFileProcessorModifier,
|
|
25
|
-
* ToolInjectionModifier,
|
|
26
|
-
* ChatHistoryMessageModifier
|
|
27
|
-
* } from '@codebolt/agent/processor-pieces';
|
|
28
|
-
*
|
|
29
|
-
* const systemPrompt = `You are an AI coding assistant...`;
|
|
30
|
-
*
|
|
31
|
-
* const agent = new CodeboltAgent({
|
|
32
|
-
* instructions: systemPrompt,
|
|
33
|
-
* processors: {
|
|
34
|
-
* messageModifiers: [
|
|
35
|
-
* new ChatHistoryMessageModifier({ enableChatHistory: true }),
|
|
36
|
-
* new EnvironmentContextModifier({ enableFullContext: true }),
|
|
37
|
-
* new DirectoryContextModifier(),
|
|
38
|
-
* new IdeContextModifier({
|
|
39
|
-
* includeActiveFile: true,
|
|
40
|
-
* includeOpenFiles: true,
|
|
41
|
-
* includeCursorPosition: true,
|
|
42
|
-
* includeSelectedText: true
|
|
43
|
-
* }),
|
|
44
|
-
* new CoreSystemPromptModifier({ customSystemPrompt: systemPrompt }),
|
|
45
|
-
* new ToolInjectionModifier({ includeToolDescriptions: true }),
|
|
46
|
-
* new AtFileProcessorModifier({ enableRecursiveSearch: true })
|
|
47
|
-
* ],
|
|
48
|
-
* preInferenceProcessors: [],
|
|
49
|
-
* postInferenceProcessors: [],
|
|
50
|
-
* preToolCallProcessors: [],
|
|
51
|
-
* postToolCallProcessors: []
|
|
52
|
-
* }
|
|
53
|
-
* });
|
|
54
|
-
*
|
|
55
|
-
* // Process a message (triggered from graph node)
|
|
56
|
-
* const result = await agent.processMessage(userMessage);
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
15
|
class CodeboltAgent {
|
|
60
16
|
constructor(config) {
|
|
61
|
-
var _a, _b, _c, _d, _e, _f;
|
|
17
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
62
18
|
this.config = { ...config };
|
|
63
19
|
this.enableLogging = config.enableLogging !== false;
|
|
64
20
|
this.baseSystemPrompt = config.instructions || 'Based on User Message send reply';
|
|
65
21
|
this.context = config.context;
|
|
66
22
|
this.allowedTools = config.allowedTools;
|
|
67
|
-
// Use provided modifiers or default ones
|
|
68
23
|
this.messageModifiers = ((_b = (_a = config.processors) === null || _a === void 0 ? void 0 : _a.messageModifiers) === null || _b === void 0 ? void 0 : _b.length)
|
|
69
24
|
? config.processors.messageModifiers
|
|
70
25
|
: this.createDefaultMessageModifiers(this.baseSystemPrompt, this.allowedTools);
|
|
@@ -72,39 +27,29 @@ class CodeboltAgent {
|
|
|
72
27
|
this.postInferenceProcessors = ((_d = config.processors) === null || _d === void 0 ? void 0 : _d.postInferenceProcessors) || [];
|
|
73
28
|
this.preToolCallProcessors = ((_e = config.processors) === null || _e === void 0 ? void 0 : _e.preToolCallProcessors) || [];
|
|
74
29
|
this.postToolCallProcessors = ((_f = config.processors) === null || _f === void 0 ? void 0 : _f.postToolCallProcessors) || [];
|
|
30
|
+
this.compactionOrchestrator = new compactionOrchestrator_1.CompactionOrchestrator(config.compaction);
|
|
31
|
+
this.loopDetectionService = config.loopDetectionService;
|
|
32
|
+
this.maxTurns = (_g = config.maxTurns) !== null && _g !== void 0 ? _g : 25;
|
|
75
33
|
}
|
|
76
|
-
/**
|
|
77
|
-
* Creates default message modifiers when none are provided
|
|
78
|
-
*/
|
|
79
34
|
createDefaultMessageModifiers(systemPrompt, allowedTools) {
|
|
80
35
|
return [
|
|
81
|
-
// 1. Chat History
|
|
82
36
|
new processor_pieces_1.ChatHistoryMessageModifier({ enableChatHistory: true }),
|
|
83
|
-
// 2. Environment Context (date, OS)
|
|
84
37
|
new processor_pieces_1.EnvironmentContextModifier({ enableFullContext: true }),
|
|
85
|
-
// 3. Directory Context (folder structure)
|
|
86
38
|
new processor_pieces_1.DirectoryContextModifier(),
|
|
87
|
-
// 4. IDE Context (active file, opened files)
|
|
88
39
|
new processor_pieces_1.IdeContextModifier({
|
|
89
40
|
includeActiveFile: true,
|
|
90
41
|
includeOpenFiles: true,
|
|
91
42
|
includeCursorPosition: true,
|
|
92
43
|
includeSelectedText: true
|
|
93
44
|
}),
|
|
94
|
-
// 5. Core System Prompt (instructions)
|
|
95
45
|
new processor_pieces_1.CoreSystemPromptModifier({ customSystemPrompt: systemPrompt }),
|
|
96
|
-
// 6. Tools (function declarations)
|
|
97
46
|
new processor_pieces_1.ToolInjectionModifier({
|
|
98
47
|
includeToolDescriptions: true,
|
|
99
48
|
...(allowedTools && { allowedTools })
|
|
100
49
|
}),
|
|
101
|
-
// 7. At-file processing (@file mentions)
|
|
102
50
|
new processor_pieces_1.AtFileProcessorModifier({ enableRecursiveSearch: true })
|
|
103
51
|
];
|
|
104
52
|
}
|
|
105
|
-
/**
|
|
106
|
-
* Creates a default FlatUserMessage from a string
|
|
107
|
-
*/
|
|
108
53
|
createDefaultUserMessage(message) {
|
|
109
54
|
return {
|
|
110
55
|
userMessage: message,
|
|
@@ -122,27 +67,14 @@ class CodeboltAgent {
|
|
|
122
67
|
threadId: `thread-${Date.now()}`
|
|
123
68
|
};
|
|
124
69
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Process a message through the agent pipeline.
|
|
127
|
-
* This is the main entry point - triggered from graph nodes.
|
|
128
|
-
* @param message - Either a string message or a FlatUserMessage object
|
|
129
|
-
* @param context - Optional context from a previous agent to continue from
|
|
130
|
-
*/
|
|
131
70
|
async processMessage(message, context) {
|
|
132
71
|
try {
|
|
133
|
-
if (this.enableLogging) {
|
|
134
|
-
console.log('[CodeboltAgent] Processing message');
|
|
135
|
-
}
|
|
136
72
|
const reqMessage = typeof message === 'string'
|
|
137
73
|
? this.createDefaultUserMessage(message)
|
|
138
74
|
: message;
|
|
139
|
-
// Use provided context, config context, or generate new one
|
|
140
|
-
const contextToUse = context || this.context;
|
|
141
75
|
let prompt;
|
|
76
|
+
const contextToUse = context || this.context;
|
|
142
77
|
if (contextToUse) {
|
|
143
|
-
if (this.enableLogging) {
|
|
144
|
-
console.log('[CodeboltAgent] Continuing from previous context');
|
|
145
|
-
}
|
|
146
78
|
prompt = contextToUse;
|
|
147
79
|
}
|
|
148
80
|
else {
|
|
@@ -154,16 +86,52 @@ class CodeboltAgent {
|
|
|
154
86
|
prompt = await promptGenerator.processMessage(reqMessage);
|
|
155
87
|
}
|
|
156
88
|
let completed = false;
|
|
89
|
+
let turnNumber = 0;
|
|
90
|
+
let finalMessage;
|
|
157
91
|
while (!completed) {
|
|
92
|
+
turnNumber += 1;
|
|
93
|
+
if (turnNumber > this.maxTurns) {
|
|
94
|
+
throw new Error(`Agent exceeded the maximum turn limit of ${this.maxTurns}.`);
|
|
95
|
+
}
|
|
96
|
+
this.compactionOrchestrator.resetForTurn();
|
|
97
|
+
prompt = await this.applyCompaction(prompt);
|
|
98
|
+
prompt = await this.refreshAvailableTools(reqMessage, prompt);
|
|
158
99
|
const agentStep = new agentStep_1.AgentStep({
|
|
159
100
|
preInferenceProcessors: this.preInferenceProcessors,
|
|
160
101
|
postInferenceProcessors: this.postInferenceProcessors
|
|
161
102
|
});
|
|
162
|
-
|
|
163
|
-
|
|
103
|
+
let stepResult;
|
|
104
|
+
while (!stepResult) {
|
|
105
|
+
try {
|
|
106
|
+
const nextStepResult = await agentStep.executeStep(reqMessage, prompt);
|
|
107
|
+
const recoverableResponseError = this.getRecoverableResponseError(nextStepResult.rawLLMResponse);
|
|
108
|
+
if (!recoverableResponseError) {
|
|
109
|
+
stepResult = nextStepResult;
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
const recoveredPrompt = await this.tryRecoverPrompt(prompt, new Error(recoverableResponseError));
|
|
113
|
+
if (!recoveredPrompt) {
|
|
114
|
+
throw new Error(recoverableResponseError);
|
|
115
|
+
}
|
|
116
|
+
prompt = recoveredPrompt;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
const recoveredPrompt = await this.tryRecoverPrompt(prompt, error);
|
|
120
|
+
if (!recoveredPrompt) {
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
prompt = recoveredPrompt;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (!stepResult) {
|
|
127
|
+
throw new Error('Agent step did not produce a response.');
|
|
128
|
+
}
|
|
164
129
|
const responseExecutor = new responseExecutor_1.ResponseExecutor({
|
|
165
130
|
preToolCallProcessors: this.preToolCallProcessors,
|
|
166
|
-
postToolCallProcessors: this.postToolCallProcessors
|
|
131
|
+
postToolCallProcessors: this.postToolCallProcessors,
|
|
132
|
+
...(this.loopDetectionService
|
|
133
|
+
? { loopDetectionService: this.loopDetectionService }
|
|
134
|
+
: {}),
|
|
167
135
|
});
|
|
168
136
|
const executionResult = await responseExecutor.executeResponse({
|
|
169
137
|
initialUserMessage: reqMessage,
|
|
@@ -173,14 +141,13 @@ class CodeboltAgent {
|
|
|
173
141
|
});
|
|
174
142
|
completed = executionResult.completed;
|
|
175
143
|
prompt = executionResult.nextMessage;
|
|
176
|
-
|
|
177
|
-
if (this.enableLogging) {
|
|
178
|
-
console.log('[CodeboltAgent] Message processing completed');
|
|
144
|
+
finalMessage = executionResult.finalMessage;
|
|
179
145
|
}
|
|
180
146
|
return {
|
|
181
147
|
success: true,
|
|
182
148
|
result: prompt,
|
|
183
|
-
context: prompt
|
|
149
|
+
context: prompt,
|
|
150
|
+
...(finalMessage !== undefined ? { finalMessage } : {}),
|
|
184
151
|
};
|
|
185
152
|
}
|
|
186
153
|
catch (error) {
|
|
@@ -196,47 +163,177 @@ class CodeboltAgent {
|
|
|
196
163
|
};
|
|
197
164
|
}
|
|
198
165
|
}
|
|
199
|
-
/**
|
|
200
|
-
* Get the current configuration
|
|
201
|
-
*/
|
|
202
166
|
getConfig() {
|
|
203
167
|
return { ...this.config };
|
|
204
168
|
}
|
|
205
|
-
/**
|
|
206
|
-
* Get all message modifiers
|
|
207
|
-
*/
|
|
208
169
|
getMessageModifiers() {
|
|
209
170
|
return [...this.messageModifiers];
|
|
210
171
|
}
|
|
211
|
-
/**
|
|
212
|
-
* Get all pre-inference processors
|
|
213
|
-
*/
|
|
214
172
|
getPreInferenceProcessors() {
|
|
215
173
|
return [...this.preInferenceProcessors];
|
|
216
174
|
}
|
|
217
|
-
/**
|
|
218
|
-
* Get all post-inference processors
|
|
219
|
-
*/
|
|
220
175
|
getPostInferenceProcessors() {
|
|
221
176
|
return [...this.postInferenceProcessors];
|
|
222
177
|
}
|
|
223
|
-
/**
|
|
224
|
-
* Get all pre-tool-call processors
|
|
225
|
-
*/
|
|
226
178
|
getPreToolCallProcessors() {
|
|
227
179
|
return [...this.preToolCallProcessors];
|
|
228
180
|
}
|
|
229
|
-
/**
|
|
230
|
-
* Get all post-tool-call processors
|
|
231
|
-
*/
|
|
232
181
|
getPostToolCallProcessors() {
|
|
233
182
|
return [...this.postToolCallProcessors];
|
|
234
183
|
}
|
|
184
|
+
async applyCompaction(prompt) {
|
|
185
|
+
const result = await this.compactionOrchestrator.compact((0, promptContext_1.getTranscriptMessages)(prompt));
|
|
186
|
+
if (!result.wasCompacted) {
|
|
187
|
+
return prompt;
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
...(0, promptContext_1.replaceTranscriptMessages)(prompt, result.messages),
|
|
191
|
+
metadata: {
|
|
192
|
+
...prompt.metadata,
|
|
193
|
+
compaction: {
|
|
194
|
+
totalTokensFreed: result.totalTokensFreed,
|
|
195
|
+
layersApplied: result.layersApplied,
|
|
196
|
+
boundaries: result.boundaries,
|
|
197
|
+
timestamp: new Date().toISOString(),
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
async tryRecoverPrompt(prompt, error) {
|
|
203
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
204
|
+
if (!this.compactionOrchestrator.getReactiveLayer().isRecoverableError(errorMessage)) {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
const recovery = await this.compactionOrchestrator.recoverFromError((0, promptContext_1.getTranscriptMessages)(prompt), error);
|
|
208
|
+
if (!recovery.wasCompacted) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
...(0, promptContext_1.replaceTranscriptMessages)(prompt, recovery.messages),
|
|
213
|
+
metadata: {
|
|
214
|
+
...prompt.metadata,
|
|
215
|
+
reactiveCompaction: {
|
|
216
|
+
totalTokensFreed: recovery.totalTokensFreed,
|
|
217
|
+
layersApplied: recovery.layersApplied,
|
|
218
|
+
boundaries: recovery.boundaries,
|
|
219
|
+
timestamp: new Date().toISOString(),
|
|
220
|
+
error: errorMessage,
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
async refreshAvailableTools(originalRequest, prompt) {
|
|
226
|
+
var _a, _b, _c, _d;
|
|
227
|
+
if (((_a = prompt.metadata) === null || _a === void 0 ? void 0 : _a['toolsInjected']) !== true ||
|
|
228
|
+
((_b = prompt.metadata) === null || _b === void 0 ? void 0 : _b['toolsLocation']) !== 'Tool') {
|
|
229
|
+
return prompt;
|
|
230
|
+
}
|
|
231
|
+
const existingTools = Array.isArray(prompt.message.tools)
|
|
232
|
+
? prompt.message.tools
|
|
233
|
+
: [];
|
|
234
|
+
try {
|
|
235
|
+
const toolsResponse = await codeboltjs_1.default.mcp.listMcpFromServers(['codebolt']);
|
|
236
|
+
let refreshedTools = ((_c = toolsResponse === null || toolsResponse === void 0 ? void 0 : toolsResponse.data) === null || _c === void 0 ? void 0 : _c.tools) || (toolsResponse === null || toolsResponse === void 0 ? void 0 : toolsResponse.data) || [];
|
|
237
|
+
const mentionedMCPs = Array.isArray(originalRequest.mentionedMCPs)
|
|
238
|
+
? originalRequest.mentionedMCPs
|
|
239
|
+
: [];
|
|
240
|
+
if (mentionedMCPs.length > 0) {
|
|
241
|
+
const { data: mentionedTools } = await codeboltjs_1.default.mcp.getTools(mentionedMCPs);
|
|
242
|
+
refreshedTools = [...refreshedTools, ...(mentionedTools || [])];
|
|
243
|
+
}
|
|
244
|
+
const allowedToolNames = this.getAllowedToolNames(prompt);
|
|
245
|
+
if (allowedToolNames && allowedToolNames.length > 0) {
|
|
246
|
+
const allowed = new Set(allowedToolNames);
|
|
247
|
+
refreshedTools = refreshedTools.filter((tool) => { var _a; return !!((_a = tool.function) === null || _a === void 0 ? void 0 : _a.name) && allowed.has(tool.function.name); });
|
|
248
|
+
}
|
|
249
|
+
const mergedTools = this.mergeTools(existingTools, refreshedTools);
|
|
250
|
+
return {
|
|
251
|
+
...prompt,
|
|
252
|
+
message: {
|
|
253
|
+
...prompt.message,
|
|
254
|
+
tools: mergedTools,
|
|
255
|
+
...(mergedTools.length > 0
|
|
256
|
+
? { tool_choice: (_d = prompt.message.tool_choice) !== null && _d !== void 0 ? _d : 'auto' }
|
|
257
|
+
: {}),
|
|
258
|
+
},
|
|
259
|
+
metadata: {
|
|
260
|
+
...prompt.metadata,
|
|
261
|
+
toolsCount: mergedTools.length,
|
|
262
|
+
toolsRefreshedAt: new Date().toISOString(),
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (this.enableLogging) {
|
|
268
|
+
console.error('[CodeboltAgent] Failed to refresh tools:', error);
|
|
269
|
+
}
|
|
270
|
+
return prompt;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
mergeTools(existingTools, refreshedTools) {
|
|
274
|
+
var _a, _b;
|
|
275
|
+
const mergedTools = new Map();
|
|
276
|
+
for (const tool of refreshedTools) {
|
|
277
|
+
const toolName = (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name;
|
|
278
|
+
if (toolName) {
|
|
279
|
+
mergedTools.set(toolName, tool);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for (const tool of existingTools) {
|
|
283
|
+
const toolName = (_b = tool.function) === null || _b === void 0 ? void 0 : _b.name;
|
|
284
|
+
if (toolName && !mergedTools.has(toolName)) {
|
|
285
|
+
mergedTools.set(toolName, tool);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return Array.from(mergedTools.values());
|
|
289
|
+
}
|
|
290
|
+
getAllowedToolNames(prompt) {
|
|
291
|
+
var _a;
|
|
292
|
+
const metadataAllowedTools = (_a = prompt.metadata) === null || _a === void 0 ? void 0 : _a['allowedTools'];
|
|
293
|
+
if (Array.isArray(metadataAllowedTools)) {
|
|
294
|
+
const allowedToolNames = metadataAllowedTools.filter((toolName) => typeof toolName === 'string' && toolName.length > 0);
|
|
295
|
+
if (allowedToolNames.length > 0) {
|
|
296
|
+
return allowedToolNames;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return this.allowedTools;
|
|
300
|
+
}
|
|
301
|
+
getRecoverableResponseError(response) {
|
|
302
|
+
var _a, _b, _c, _d;
|
|
303
|
+
const reactiveLayer = this.compactionOrchestrator.getReactiveLayer();
|
|
304
|
+
const candidateMessages = this.collectResponseMessages(response);
|
|
305
|
+
const recoverableMessage = candidateMessages.find((message) => reactiveLayer.isRecoverableError(message));
|
|
306
|
+
if (recoverableMessage) {
|
|
307
|
+
return recoverableMessage;
|
|
308
|
+
}
|
|
309
|
+
const finishReasons = [
|
|
310
|
+
response.finish_reason,
|
|
311
|
+
...((_a = response.choices) !== null && _a !== void 0 ? _a : []).map((choice) => choice.finish_reason),
|
|
312
|
+
].filter((reason) => typeof reason === 'string');
|
|
313
|
+
const hasLengthFinishReason = finishReasons.some((reason) => reason.toLowerCase() === 'length');
|
|
314
|
+
const hasToolCalls = ((_c = (_b = response.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0 ||
|
|
315
|
+
((_d = response.choices) !== null && _d !== void 0 ? _d : []).some((choice) => { var _a, _b, _c; return ((_c = (_b = (_a = choice.message) === null || _a === void 0 ? void 0 : _a.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0; });
|
|
316
|
+
if (hasLengthFinishReason && candidateMessages.length === 0 && !hasToolCalls) {
|
|
317
|
+
return 'Too many tokens or token limit reached before producing usable output.';
|
|
318
|
+
}
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
collectResponseMessages(response) {
|
|
322
|
+
var _a, _b;
|
|
323
|
+
const messages = [];
|
|
324
|
+
if (typeof response.content === 'string' && response.content.trim().length > 0) {
|
|
325
|
+
messages.push(response.content.trim());
|
|
326
|
+
}
|
|
327
|
+
for (const choice of (_a = response.choices) !== null && _a !== void 0 ? _a : []) {
|
|
328
|
+
if (typeof ((_b = choice.message) === null || _b === void 0 ? void 0 : _b.content) === 'string' &&
|
|
329
|
+
choice.message.content.trim().length > 0) {
|
|
330
|
+
messages.push(choice.message.content.trim());
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return messages;
|
|
334
|
+
}
|
|
235
335
|
}
|
|
236
336
|
exports.CodeboltAgent = CodeboltAgent;
|
|
237
|
-
/**
|
|
238
|
-
* Factory function to create a CodeboltAgent with common defaults
|
|
239
|
-
*/
|
|
240
337
|
function createCodeboltAgent(options) {
|
|
241
338
|
var _a;
|
|
242
339
|
return new CodeboltAgent({
|
|
@@ -248,6 +345,9 @@ function createCodeboltAgent(options) {
|
|
|
248
345
|
preToolCallProcessors: options.preToolCallProcessors || [],
|
|
249
346
|
postToolCallProcessors: options.postToolCallProcessors || []
|
|
250
347
|
},
|
|
251
|
-
enableLogging: (_a = options.enableLogging) !== null && _a !== void 0 ? _a : true
|
|
348
|
+
enableLogging: (_a = options.enableLogging) !== null && _a !== void 0 ? _a : true,
|
|
349
|
+
...(options.compaction ? { compaction: options.compaction } : {}),
|
|
350
|
+
...(options.loopDetectionService ? { loopDetectionService: options.loopDetectionService } : {}),
|
|
351
|
+
...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns } : {}),
|
|
252
352
|
});
|
|
253
353
|
}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.AgentStep = void 0;
|
|
7
7
|
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
8
|
+
const promptContext_1 = require("./promptContext");
|
|
8
9
|
/**
|
|
9
10
|
* Unified agent step that handles LLM interaction and tool call analysis
|
|
10
11
|
*/
|
|
@@ -20,40 +21,39 @@ class AgentStep {
|
|
|
20
21
|
async executeStep(originalRequest, createdMessage) {
|
|
21
22
|
var _a;
|
|
22
23
|
try {
|
|
24
|
+
let preparedMessage = (0, promptContext_1.syncProcessedMessageWithRuntimeContext)(createdMessage);
|
|
23
25
|
for (const preInferenceProcessor of this.preInferenceProcessors) {
|
|
24
26
|
try {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
preparedMessage = await preInferenceProcessor.modify(originalRequest, preparedMessage);
|
|
28
|
+
preparedMessage = (0, promptContext_1.reconcileRuntimePromptContext)(preparedMessage);
|
|
27
29
|
}
|
|
28
30
|
catch (error) {
|
|
29
31
|
console.error(`[InitialPromptGenerator] Error in message modifier:`, error);
|
|
30
|
-
// Continue with other modifiers
|
|
31
32
|
}
|
|
32
33
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
34
|
+
const actualMessageSentToLLM = {
|
|
35
|
+
...preparedMessage,
|
|
36
|
+
message: (0, promptContext_1.buildInferenceParams)(preparedMessage),
|
|
37
|
+
};
|
|
38
|
+
const rawLLMResponse = await this.generateResponse(actualMessageSentToLLM.message);
|
|
39
|
+
const assistantMessages = ((_a = rawLLMResponse.choices) !== null && _a !== void 0 ? _a : []).map((contentBlock) => ({
|
|
40
|
+
...contentBlock.message,
|
|
41
|
+
role: contentBlock.message.role
|
|
42
|
+
}));
|
|
43
|
+
let modifiedMessage = (0, promptContext_1.appendTranscriptMessages)(preparedMessage, assistantMessages);
|
|
43
44
|
for (const postInferenceProcessor of this.postInferenceProcessors) {
|
|
44
45
|
try {
|
|
45
|
-
|
|
46
|
-
modifiedMessage =
|
|
46
|
+
modifiedMessage = await postInferenceProcessor.modify(actualMessageSentToLLM, rawLLMResponse, modifiedMessage);
|
|
47
|
+
modifiedMessage = (0, promptContext_1.reconcileRuntimePromptContext)(modifiedMessage);
|
|
47
48
|
}
|
|
48
49
|
catch (error) {
|
|
49
50
|
console.error(`[InitialPromptGenerator] Error in message modifier:`, error);
|
|
50
|
-
// Continue with other modifiers
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
const output = {
|
|
54
54
|
rawLLMResponse: rawLLMResponse,
|
|
55
55
|
nextMessage: modifiedMessage,
|
|
56
|
-
actualMessageSentToLLM
|
|
56
|
+
actualMessageSentToLLM
|
|
57
57
|
};
|
|
58
58
|
return output;
|
|
59
59
|
}
|
|
@@ -7,6 +7,7 @@ exports.InitialPromptGenerator = void 0;
|
|
|
7
7
|
exports.createUnifiedMessageProcessor = createUnifiedMessageProcessor;
|
|
8
8
|
const types_1 = require("../types/types");
|
|
9
9
|
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
10
|
+
const promptContext_1 = require("./promptContext");
|
|
10
11
|
/**
|
|
11
12
|
* Initial prompt generator that combines message modifiers with unified processing
|
|
12
13
|
*/
|
|
@@ -29,13 +30,9 @@ class InitialPromptGenerator {
|
|
|
29
30
|
if (this.enableLogging) {
|
|
30
31
|
// console.log('[InitialPromptGenerator] Processing message:', input);
|
|
31
32
|
}
|
|
32
|
-
// Create initial ProcessedMessage from FlatUserMessage
|
|
33
|
-
const content = input.userMessage;
|
|
34
|
-
// Create messages array, starting with system message if baseSystemPrompt is defined
|
|
35
|
-
const messages = [];
|
|
36
33
|
let createdMessage = {
|
|
37
34
|
message: {
|
|
38
|
-
messages:
|
|
35
|
+
messages: [],
|
|
39
36
|
tools: []
|
|
40
37
|
},
|
|
41
38
|
metadata: {
|
|
@@ -44,52 +41,37 @@ class InitialPromptGenerator {
|
|
|
44
41
|
threadId: input.threadId
|
|
45
42
|
}
|
|
46
43
|
};
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
createdMessage = (0, promptContext_1.syncProcessedMessageWithRuntimeContext)(createdMessage);
|
|
45
|
+
if (this.baseSystemPrompt !== undefined) {
|
|
46
|
+
createdMessage = (0, promptContext_1.setSystemPrompt)(createdMessage, this.baseSystemPrompt);
|
|
47
|
+
}
|
|
48
|
+
createdMessage = (0, promptContext_1.appendTranscriptMessage)(createdMessage, {
|
|
49
|
+
role: 'user',
|
|
50
|
+
content: input.userMessage.trim(),
|
|
51
|
+
});
|
|
49
52
|
for (const messageModifier of this.processors) {
|
|
50
53
|
try {
|
|
51
|
-
// Each modifier returns a new ProcessedMessage
|
|
52
54
|
createdMessage = await messageModifier.modify(input, createdMessage);
|
|
55
|
+
createdMessage = (0, promptContext_1.reconcileRuntimePromptContext)(createdMessage);
|
|
53
56
|
}
|
|
54
57
|
catch (error) {
|
|
55
58
|
console.error(`[InitialPromptGenerator] Error in message modifier:`, error);
|
|
56
|
-
// Continue with other modifiers
|
|
57
59
|
}
|
|
58
60
|
}
|
|
59
|
-
const lastMessage = createdMessage.message.messages[createdMessage.message.messages.length - 1];
|
|
60
|
-
if (!lastMessage || lastMessage.role !== 'system') {
|
|
61
|
-
createdMessage.message.messages.push({
|
|
62
|
-
role: 'assistant',
|
|
63
|
-
content: "Got it. Thanks for the context!"
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
61
|
let { todos } = await codeboltjs_1.default.todo.getAllIncompleteTodos();
|
|
67
62
|
if (todos && todos.length == 0) {
|
|
68
|
-
createdMessage.
|
|
63
|
+
createdMessage = (0, promptContext_1.appendUserContextMessage)(createdMessage, {
|
|
69
64
|
role: 'user',
|
|
70
65
|
content: "<system-reminder>\nThis is a reminder that your todo list is currently empty. DO NOT mention this to the user explicitly because they are already aware. If you are working on tasks that would benefit from a todo list please use the TodoWrite tool to create one. If not, please feel free to ignore. Again do not mention this message to the user.\n</system-reminder>"
|
|
71
66
|
});
|
|
72
67
|
}
|
|
73
|
-
createdMessage.message.messages.push({
|
|
74
|
-
role: 'user',
|
|
75
|
-
content: content.trim()
|
|
76
|
-
});
|
|
77
68
|
if (this.enableLogging) {
|
|
78
69
|
// console.log('[InitialPromptGenerator] Processing completed:', {
|
|
79
70
|
// messageCount: createdMessage.message.messages.length,
|
|
80
71
|
// metadata: createdMessage.metadata
|
|
81
72
|
// });
|
|
82
73
|
}
|
|
83
|
-
|
|
84
|
-
const hasSystem = createdMessage.message.messages.some(msg => msg.role === 'system');
|
|
85
|
-
if (!hasSystem) {
|
|
86
|
-
createdMessage.message.messages.unshift({
|
|
87
|
-
role: 'system',
|
|
88
|
-
content: this.baseSystemPrompt
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return createdMessage;
|
|
74
|
+
return (0, promptContext_1.syncProcessedMessageWithRuntimeContext)(createdMessage);
|
|
93
75
|
}
|
|
94
76
|
catch (error) {
|
|
95
77
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ProcessedMessage } from '@codebolt/types/agent';
|
|
2
|
+
import type { LLMInferenceParams, MessageObject } from '@codebolt/types/sdk';
|
|
3
|
+
export declare function syncProcessedMessageWithRuntimeContext(prompt: ProcessedMessage): ProcessedMessage;
|
|
4
|
+
export declare function reconcileRuntimePromptContext(prompt: ProcessedMessage): ProcessedMessage;
|
|
5
|
+
export declare function setSystemPrompt(prompt: ProcessedMessage, systemPrompt: string): ProcessedMessage;
|
|
6
|
+
export declare function appendSystemContextMessage(prompt: ProcessedMessage, message: MessageObject): ProcessedMessage;
|
|
7
|
+
export declare function appendUserContextMessage(prompt: ProcessedMessage, message: MessageObject): ProcessedMessage;
|
|
8
|
+
export declare function appendTranscriptMessage(prompt: ProcessedMessage, message: MessageObject): ProcessedMessage;
|
|
9
|
+
export declare function appendTranscriptMessages(prompt: ProcessedMessage, messages: MessageObject[]): ProcessedMessage;
|
|
10
|
+
export declare function prependTranscriptMessages(prompt: ProcessedMessage, messages: MessageObject[]): ProcessedMessage;
|
|
11
|
+
export declare function replaceTranscriptMessages(prompt: ProcessedMessage, messages: MessageObject[]): ProcessedMessage;
|
|
12
|
+
export declare function getTranscriptMessages(prompt: ProcessedMessage): MessageObject[];
|
|
13
|
+
export declare function buildInferenceParams(prompt: ProcessedMessage): LLMInferenceParams;
|