@codebolt/agent 5.0.7 → 5.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/processor-pieces/base/basePreToolCallProcessor.js +5 -2
  2. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.d.ts +1 -1
  3. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +2 -2
  4. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +24 -34
  5. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.d.ts +1 -1
  6. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +2 -2
  7. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.d.ts +1 -1
  8. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +2 -2
  9. package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +1 -1
  10. package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +8 -3
  11. package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +1 -1
  12. package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +1 -1
  13. package/dist/processor-pieces/messageModifiers/ideContextModifier.js +114 -17
  14. package/dist/processor-pieces/messageModifiers/memoryImportModifier.d.ts +1 -1
  15. package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +13 -5
  16. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.d.ts +5 -0
  17. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +4 -0
  18. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +24 -8
  19. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +202 -5
  20. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +826 -19
  21. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +1 -1
  22. package/dist/processor-pieces/postToolCallProcessors/index.js +2 -1
  23. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +7 -4
  24. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.d.ts +1 -1
  25. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +12 -16
  26. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.d.ts +2 -3
  27. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.js +1 -2
  28. package/dist/processor-pieces/utils/messageModifierHelper.js +5 -2
  29. package/dist/types/InternalTypes.d.ts +8 -6
  30. package/dist/unified/agent/agent.js +1 -2
  31. package/dist/unified/agent/codeboltAgent.d.ts +23 -2
  32. package/dist/unified/agent/codeboltAgent.js +55 -12
  33. package/dist/unified/agent/tools.d.ts +7 -11
  34. package/dist/unified/agent/tools.js +12 -3
  35. package/dist/unified/agent/workflow.js +38 -20
  36. package/dist/unified/agent/workflowSteps.d.ts +1 -1
  37. package/dist/unified/agent/workflowSteps.js +58 -23
  38. package/dist/unified/base/agentStep.js +20 -1
  39. package/dist/unified/base/initialPromptGenerator.js +3 -1
  40. package/dist/unified/base/responseExecutor.d.ts +3 -0
  41. package/dist/unified/base/responseExecutor.js +47 -21
  42. package/dist/unified/index.d.ts +1 -0
  43. package/dist/unified/index.js +4 -1
  44. package/dist/unified/services/LoopDetectionService.d.ts +44 -0
  45. package/dist/unified/services/LoopDetectionService.js +79 -0
  46. package/dist/unified/utils/utils.d.ts +20 -1
  47. package/dist/unified/utils/utils.js +8 -4
  48. package/package.json +5 -5
  49. package/dist/agent.d.ts +0 -86
  50. package/dist/agent.js +0 -324
  51. package/dist/builderpattern/agent.d.ts +0 -86
  52. package/dist/builderpattern/agent.js +0 -324
  53. package/dist/builderpattern/followupquestionbuilder.d.ts +0 -75
  54. package/dist/builderpattern/followupquestionbuilder.js +0 -197
  55. package/dist/builderpattern/index.d.ts +0 -14
  56. package/dist/builderpattern/index.js +0 -23
  57. package/dist/builderpattern/llmoutputhandler.d.ts +0 -102
  58. package/dist/builderpattern/llmoutputhandler.js +0 -452
  59. package/dist/builderpattern/promptbuilder.d.ts +0 -382
  60. package/dist/builderpattern/promptbuilder.js +0 -805
  61. package/dist/builderpattern/systemprompt.d.ts +0 -20
  62. package/dist/builderpattern/systemprompt.js +0 -48
  63. package/dist/builderpattern/taskInstruction.d.ts +0 -37
  64. package/dist/builderpattern/taskInstruction.js +0 -57
  65. package/dist/builderpattern/usermessage.d.ts +0 -70
  66. package/dist/builderpattern/usermessage.js +0 -123
  67. package/dist/composablepattern/agent.d.ts +0 -169
  68. package/dist/composablepattern/agent.js +0 -598
  69. package/dist/composablepattern/codebolt-storage.d.ts +0 -67
  70. package/dist/composablepattern/codebolt-storage.js +0 -320
  71. package/dist/composablepattern/document.d.ts +0 -149
  72. package/dist/composablepattern/document.js +0 -405
  73. package/dist/composablepattern/examples/codebolt-integration-example.d.ts +0 -12
  74. package/dist/composablepattern/examples/codebolt-integration-example.js +0 -218
  75. package/dist/composablepattern/examples/codebolt-storage-example.d.ts +0 -40
  76. package/dist/composablepattern/examples/codebolt-storage-example.js +0 -223
  77. package/dist/composablepattern/examples/custom-steps-example.d.ts +0 -20
  78. package/dist/composablepattern/examples/custom-steps-example.js +0 -455
  79. package/dist/composablepattern/examples/document-agent.d.ts +0 -17
  80. package/dist/composablepattern/examples/document-agent.js +0 -107
  81. package/dist/composablepattern/examples/simple-codebolt-integration.d.ts +0 -8
  82. package/dist/composablepattern/examples/simple-codebolt-integration.js +0 -164
  83. package/dist/composablepattern/examples/weather-agent.d.ts +0 -18
  84. package/dist/composablepattern/examples/weather-agent.js +0 -86
  85. package/dist/composablepattern/examples/workflow-example.d.ts +0 -12
  86. package/dist/composablepattern/examples/workflow-example.js +0 -463
  87. package/dist/composablepattern/index.d.ts +0 -63
  88. package/dist/composablepattern/index.js +0 -115
  89. package/dist/composablepattern/memory.d.ts +0 -89
  90. package/dist/composablepattern/memory.js +0 -141
  91. package/dist/composablepattern/tool.d.ts +0 -84
  92. package/dist/composablepattern/tool.js +0 -260
  93. package/dist/composablepattern/types.d.ts +0 -194
  94. package/dist/composablepattern/types.js +0 -6
  95. package/dist/composablepattern/user-context.d.ts +0 -214
  96. package/dist/composablepattern/user-context.js +0 -275
  97. package/dist/composablepattern/workflow.d.ts +0 -388
  98. package/dist/composablepattern/workflow.js +0 -562
  99. package/dist/followupquestionbuilder.d.ts +0 -75
  100. package/dist/followupquestionbuilder.js +0 -197
  101. package/dist/index.d.ts +0 -14
  102. package/dist/index.js +0 -23
  103. package/dist/llmoutputhandler.d.ts +0 -102
  104. package/dist/llmoutputhandler.js +0 -452
  105. package/dist/processor/agent/agentStep.d.ts +0 -49
  106. package/dist/processor/agent/agentStep.js +0 -241
  107. package/dist/processor/agent/toolExecutor.d.ts +0 -19
  108. package/dist/processor/agent/toolExecutor.js +0 -90
  109. package/dist/processor/index.d.ts +0 -7
  110. package/dist/processor/index.js +0 -36
  111. package/dist/processor/messageModifiers/baseMessageModifier.d.ts +0 -20
  112. package/dist/processor/messageModifiers/baseMessageModifier.js +0 -55
  113. package/dist/processor/processors/baseProcessor.d.ts +0 -14
  114. package/dist/processor/processors/baseProcessor.js +0 -29
  115. package/dist/processor/tools/baseTool.d.ts +0 -10
  116. package/dist/processor/tools/baseTool.js +0 -20
  117. package/dist/processor/tools/toolList.d.ts +0 -9
  118. package/dist/processor/tools/toolList.js +0 -22
  119. package/dist/processor/types/interfaces.d.ts +0 -94
  120. package/dist/processor/types/interfaces.js +0 -2
  121. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +0 -22
  122. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +0 -144
  123. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +0 -15
  124. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +0 -75
  125. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +0 -11
  126. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +0 -46
  127. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +0 -12
  128. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +0 -60
  129. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +0 -18
  130. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +0 -222
  131. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +0 -22
  132. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +0 -194
  133. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.d.ts +0 -41
  134. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.js +0 -197
  135. package/dist/processor-pieces/processors/chatCompressionProcessor.d.ts +0 -26
  136. package/dist/processor-pieces/processors/chatCompressionProcessor.js +0 -90
  137. package/dist/processor-pieces/processors/chatRecordingProcessor.d.ts +0 -81
  138. package/dist/processor-pieces/processors/chatRecordingProcessor.js +0 -329
  139. package/dist/processor-pieces/processors/contextManagementProcessor.d.ts +0 -40
  140. package/dist/processor-pieces/processors/contextManagementProcessor.js +0 -305
  141. package/dist/processor-pieces/processors/loopDetectionProcessor.d.ts +0 -30
  142. package/dist/processor-pieces/processors/loopDetectionProcessor.js +0 -137
  143. package/dist/processor-pieces/processors/responseValidationProcessor.d.ts +0 -30
  144. package/dist/processor-pieces/processors/responseValidationProcessor.js +0 -228
  145. package/dist/processor-pieces/processors/telemetryProcessor.d.ts +0 -99
  146. package/dist/processor-pieces/processors/telemetryProcessor.js +0 -311
  147. package/dist/processor-pieces/processors/tokenManagementProcessor.d.ts +0 -37
  148. package/dist/processor-pieces/processors/tokenManagementProcessor.js +0 -178
  149. package/dist/processor-pieces/processors/toolExecutionProcessor.d.ts +0 -43
  150. package/dist/processor-pieces/processors/toolExecutionProcessor.js +0 -207
  151. package/dist/processor-pieces/tools/fileTools.d.ts +0 -26
  152. package/dist/processor-pieces/tools/fileTools.js +0 -162
  153. package/dist/promptbuilder.d.ts +0 -382
  154. package/dist/promptbuilder.js +0 -805
  155. package/dist/systemprompt.d.ts +0 -20
  156. package/dist/systemprompt.js +0 -48
  157. package/dist/taskInstruction.d.ts +0 -37
  158. package/dist/taskInstruction.js +0 -57
  159. package/dist/usermessage.d.ts +0 -70
  160. package/dist/usermessage.js +0 -123
@@ -1,452 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.LLMOutputHandler = void 0;
7
- const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
8
- const { chat, mcp, agent: codeboltAgent } = codeboltjs_1.default;
9
- /**
10
- * Handles LLM output processing, tool execution, and completion detection.
11
- * This class processes LLM responses and manages the conversation flow.
12
- */
13
- class LLMOutputHandler {
14
- /**
15
- * Creates a new LLMOutputHandler instance.
16
- *
17
- * @param llmResponse - The LLM response object
18
- * @param codebolt - Optional codebolt API instance
19
- */
20
- constructor(llmResponse, codebolt) {
21
- /** Whether the task has been completed */
22
- this.completed = false;
23
- /** Tool results from execution */
24
- this.toolResults = [];
25
- /** Next user message to be added to conversation */
26
- this.nextUserMessage = null;
27
- /** Whether mcp have been executed */
28
- this.mcpExecuted = false;
29
- // Validate llmResponse structure
30
- if (!llmResponse) {
31
- throw new Error("LLM response is null or undefined");
32
- }
33
- if (!llmResponse.completion) {
34
- throw new Error("LLM response completion is missing");
35
- }
36
- if (!llmResponse.completion.choices || !Array.isArray(llmResponse.completion.choices)) {
37
- throw new Error("LLM response choices array is missing or invalid");
38
- }
39
- this.llmResponse = llmResponse;
40
- this.codebolt = codebolt;
41
- // Check if any message has tool_calls, if none do, mark as completed
42
- let hasToolCalls = false;
43
- try {
44
- this.llmResponse.completion.choices.forEach((message) => {
45
- var _a;
46
- if (((_a = message.message) === null || _a === void 0 ? void 0 : _a.tool_calls) && message.message.tool_calls.length > 0) {
47
- hasToolCalls = true;
48
- }
49
- });
50
- }
51
- catch (error) {
52
- console.error("Error checking for tool calls:", error);
53
- hasToolCalls = false;
54
- }
55
- // If no messages have tool_calls, mark as completed
56
- if (!hasToolCalls) {
57
- try {
58
- this.sendMessageToUser();
59
- }
60
- catch (error) {
61
- console.error("Error sending message to user:", error);
62
- }
63
- this.completed = true;
64
- }
65
- }
66
- /**
67
- * Checks if the task has been completed.
68
- *
69
- * @returns True if the task is completed, false otherwise
70
- */
71
- isCompleted() {
72
- return this.completed;
73
- }
74
- /**
75
- * Gets the tool execution results.
76
- *
77
- * @returns Array of tool results
78
- */
79
- getToolResults() {
80
- return [...this.toolResults];
81
- }
82
- /**
83
- * Gets the next user message to be added to conversation.
84
- *
85
- * @returns The next user message or null
86
- */
87
- getNextUserMessage() {
88
- return this.nextUserMessage;
89
- }
90
- /**
91
- * Sends the assistant's message to the user interface.
92
- *
93
- * @returns Promise that resolves when the message is sent
94
- */
95
- async sendMessageToUser() {
96
- var _a, _b;
97
- if (!this.llmResponse) {
98
- throw new Error("LLM response not available");
99
- }
100
- // Handle the response structure - it might have choices or direct content
101
- let messageContent = '';
102
- const completion = this.llmResponse.completion;
103
- if (completion && completion.choices && completion.choices.length > 0) {
104
- // OpenAI-style response with choices
105
- const choice = completion.choices[0];
106
- if (choice.message && choice.message.content) {
107
- messageContent = choice.message.content;
108
- }
109
- }
110
- else if (completion && completion.content) {
111
- // Direct content response
112
- messageContent = completion.content;
113
- }
114
- if (messageContent) {
115
- (_b = (_a = this.codebolt) === null || _a === void 0 ? void 0 : _a.chat) === null || _b === void 0 ? void 0 : _b.sendMessage(messageContent, {});
116
- }
117
- }
118
- /**
119
- * Executes all tool calls found in the LLM response.
120
- *
121
- * @returns Promise that resolves when all mcp are executed
122
- */
123
- async runTools() {
124
- var _a;
125
- try {
126
- // Validate llmResponse structure
127
- if (!this.llmResponse || !this.llmResponse.completion) {
128
- throw new Error("Invalid LLM response structure");
129
- }
130
- if (!this.llmResponse.completion.choices || !Array.isArray(this.llmResponse.completion.choices)) {
131
- throw new Error("LLM response choices array is missing or invalid");
132
- }
133
- if (this.llmResponse.completion.choices.length === 0) {
134
- console.warn("No choices found in LLM response");
135
- return this.toolResults;
136
- }
137
- let toolResults = [];
138
- let taskCompletedBlock;
139
- let userRejectedToolUse = false;
140
- console.log("Calling run tool: ", JSON.stringify(this.llmResponse.completion));
141
- const contentBlock = this.llmResponse.completion.choices[0];
142
- // Validate contentBlock structure
143
- if (!contentBlock || !contentBlock.message) {
144
- console.warn("Invalid content block structure");
145
- return this.toolResults;
146
- }
147
- if ((_a = contentBlock.message) === null || _a === void 0 ? void 0 : _a.tool_calls) {
148
- for (const tool of contentBlock.message.tool_calls) {
149
- try {
150
- const { toolInput, toolName, toolUseId } = this.getToolDetail(tool);
151
- if (!userRejectedToolUse) {
152
- if (toolName.includes("attempt_completion")) {
153
- taskCompletedBlock = tool;
154
- }
155
- else {
156
- let [serverName] = toolName.replace('--', ':').split(':');
157
- if (serverName == 'subagent') {
158
- const agentResponse = await codeboltAgent.startAgent(toolName.replace("subagent--", ''), toolInput.task);
159
- const [didUserReject, result] = [false, "tool result is successful"];
160
- let toolResult = this.getToolResult(toolUseId, result);
161
- this.toolResults.push({
162
- role: "tool",
163
- tool_call_id: toolResult.tool_call_id,
164
- content: toolResult.content,
165
- });
166
- if (toolResult.userMessage) {
167
- this.nextUserMessage = {
168
- role: "user",
169
- content: toolResult.userMessage
170
- };
171
- }
172
- if (didUserReject) {
173
- userRejectedToolUse = true;
174
- }
175
- }
176
- else {
177
- console.log("Executing tool: ", toolName, toolInput);
178
- const [didUserReject, result] = await this.executeTool(toolName, toolInput);
179
- console.log("Tool result: ", result);
180
- // toolResults.push(this.getToolResult(toolUseId, result));
181
- let toolResult = this.getToolResult(toolUseId, result);
182
- console.log("tool result after parsing", toolResult);
183
- this.toolResults.push({
184
- role: "tool",
185
- tool_call_id: toolResult.tool_call_id,
186
- content: toolResult.content,
187
- });
188
- if (toolResult.userMessage) {
189
- this.nextUserMessage = {
190
- role: "user",
191
- content: toolResult.userMessage
192
- };
193
- }
194
- if (didUserReject) {
195
- userRejectedToolUse = true;
196
- }
197
- }
198
- }
199
- }
200
- else {
201
- let toolResult = this.getToolResult(toolUseId, "Skipping tool execution due to previous tool user rejection.");
202
- this.toolResults.push({
203
- role: "tool",
204
- tool_call_id: toolResult.tool_call_id,
205
- content: toolResult.content,
206
- });
207
- if (toolResult.userMessage) {
208
- this.nextUserMessage = {
209
- role: "user",
210
- content: toolResult.userMessage
211
- };
212
- }
213
- }
214
- }
215
- catch (error) {
216
- this.toolResults.push({
217
- role: "tool",
218
- tool_call_id: (tool === null || tool === void 0 ? void 0 : tool.id) || "unknown",
219
- content: String(error),
220
- });
221
- }
222
- }
223
- }
224
- if (taskCompletedBlock) {
225
- let taskArgs = {};
226
- try {
227
- // Validate taskCompletedBlock structure
228
- if (!taskCompletedBlock.function) {
229
- throw new Error("Task completed block function is missing");
230
- }
231
- if (!taskCompletedBlock.function.name) {
232
- throw new Error("Task completed block function name is missing");
233
- }
234
- // Parse arguments safely
235
- const argumentsString = taskCompletedBlock.function.arguments || "{}";
236
- if (typeof argumentsString !== 'string') {
237
- throw new Error("Task completed block arguments must be a string");
238
- }
239
- taskArgs = JSON.parse(argumentsString);
240
- }
241
- catch (parseError) {
242
- const errorMessage = parseError instanceof Error ? parseError.message : 'Unknown parsing error';
243
- console.error("Failed to parse taskCompletedBlock arguments:", errorMessage);
244
- taskArgs = {};
245
- }
246
- let [_, result] = await this.executeTool(taskCompletedBlock.function.name, taskArgs);
247
- if (result === "") {
248
- this.completed = true;
249
- result = "The user is satisfied with the result.";
250
- }
251
- let toolResult = this.getToolResult((taskCompletedBlock === null || taskCompletedBlock === void 0 ? void 0 : taskCompletedBlock.id) || "unknown", result);
252
- this.toolResults.push({
253
- role: "tool",
254
- tool_call_id: toolResult.tool_call_id,
255
- content: toolResult.content,
256
- });
257
- if (toolResult.userMessage) {
258
- this.nextUserMessage = {
259
- role: "user",
260
- content: toolResult.userMessage
261
- };
262
- }
263
- }
264
- // this.apiConversationHistory.push(...toolResults);
265
- // if (this.nextUserMessage) {
266
- // this.apiConversationHistory.push(this.nextUserMessage);
267
- // }
268
- let nextUserMessage = this.toolResults;
269
- if (this.toolResults.length === 0) {
270
- nextUserMessage = [{
271
- role: "user",
272
- content: [{
273
- type: "text",
274
- text: "If you have completed the user's task, use the attempt_completion tool. If you require additional information from the user, use the ask_followup_question tool. Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task. (This is an automated message, so do not respond to it conversationally.)"
275
- }]
276
- }];
277
- }
278
- return this.toolResults;
279
- }
280
- catch (error) {
281
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
282
- console.error(`Error in runTools: ${errorMessage}`, error);
283
- // Add error information to tool results for debugging
284
- this.toolResults.push({
285
- role: "tool",
286
- tool_call_id: "error",
287
- content: `Error executing mcp: ${errorMessage}`
288
- });
289
- return this.toolResults;
290
- }
291
- }
292
- /**
293
- * Extracts tool calls from the LLM response.
294
- *
295
- * @returns Array of tool calls or null if none found
296
- */
297
- getToolCallsFromResponse() {
298
- if (!this.llmResponse)
299
- return null;
300
- // Check OpenAI-style response structure
301
- const completion = this.llmResponse.completion;
302
- if (completion && completion.choices && completion.choices.length > 0) {
303
- const choice = completion.choices[0];
304
- if (choice.message && choice.message.tool_calls) {
305
- return choice.message.tool_calls;
306
- }
307
- }
308
- // Check direct tool_calls property
309
- if (completion && completion.tool_calls) {
310
- return completion.tool_calls;
311
- }
312
- return null;
313
- }
314
- /**
315
- * Extracts tool details from a tool call object.
316
- *
317
- * @param tool - The tool call object from the LLM response
318
- * @returns ToolDetails object with name, input, and ID
319
- */
320
- getToolDetail(tool) {
321
- try {
322
- // Validate tool object
323
- if (!tool) {
324
- throw new Error("Tool object is null or undefined");
325
- }
326
- // Validate tool.function
327
- if (!tool.function) {
328
- throw new Error("Tool function is null or undefined");
329
- }
330
- // Validate tool.function.name
331
- if (!tool.function.name || typeof tool.function.name !== 'string') {
332
- throw new Error("Tool function name is missing or invalid");
333
- }
334
- // Validate tool.id
335
- if (!tool.id || typeof tool.id !== 'string') {
336
- throw new Error("Tool ID is missing or invalid");
337
- }
338
- // Parse tool arguments safely
339
- let toolInput = {};
340
- if (tool.function.arguments) {
341
- try {
342
- toolInput = JSON.parse(tool.function.arguments);
343
- }
344
- catch (parseError) {
345
- throw new Error(`Failed to parse tool arguments: ${parseError instanceof Error ? parseError.message : 'Invalid JSON'}`);
346
- }
347
- }
348
- return {
349
- toolName: tool.function.name,
350
- toolInput: toolInput,
351
- toolUseId: tool.id
352
- };
353
- }
354
- catch (error) {
355
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
356
- throw new Error(`Failed to extract tool details: ${errorMessage}`);
357
- }
358
- }
359
- /**
360
- * Executes a tool with given name and input.
361
- *
362
- * @param toolName - The name of the tool to execute
363
- * @param toolInput - The input parameters for the tool
364
- * @returns Promise with tuple [userRejected, result]
365
- */
366
- async executeTool(toolName, toolInput) {
367
- var _a;
368
- //codeboltmcp--readfile
369
- const [toolboxName, actualToolName] = toolName.split('--');
370
- console.log("Toolbox name: ", toolboxName, "Actual tool name: ", actualToolName);
371
- const data = await ((_a = this.codebolt) === null || _a === void 0 ? void 0 : _a.mcp.executeTool(toolboxName, actualToolName, toolInput));
372
- console.log("Tool result: ", data);
373
- return data;
374
- }
375
- /**
376
- * Creates a tool result object from the tool execution response.
377
- *
378
- * @param tool_call_id - The ID of the tool call
379
- * @param content - The content returned by the tool
380
- * @returns ToolResult object
381
- */
382
- getToolResult(tool_call_id, content) {
383
- let userMessage = undefined;
384
- try {
385
- // Validate content before parsing
386
- if (typeof content !== 'string') {
387
- throw new Error("Content must be a string");
388
- }
389
- // Only attempt to parse if content looks like JSON
390
- if (content.trim().startsWith('{') || content.trim().startsWith('[')) {
391
- const parsed = JSON.parse(content);
392
- console.log("Parsed Content: ", parsed);
393
- if (parsed && typeof parsed === 'object' && parsed.payload && parsed.payload.content) {
394
- content = `The browser action has been executed. The screenshot have been captured for your analysis. The tool response is provided in the next user message`;
395
- userMessage = parsed.payload.content;
396
- }
397
- }
398
- }
399
- catch (error) {
400
- const errorMessage = error instanceof Error ? error.message : 'Unknown JSON parsing error';
401
- console.warn(`Failed to parse tool result content as JSON: ${errorMessage}. Using content as-is.`);
402
- // Content is not valid JSON, use as-is
403
- }
404
- return {
405
- role: "tool",
406
- tool_call_id,
407
- content,
408
- userMessage
409
- };
410
- }
411
- /**
412
- * Checks if the response has tool calls.
413
- *
414
- * @returns True if the response contains tool calls
415
- */
416
- hasToolCalls() {
417
- if (!this.llmResponse)
418
- return false;
419
- const toolCalls = this.getToolCallsFromResponse();
420
- return toolCalls !== null && toolCalls.length > 0;
421
- }
422
- /**
423
- * Gets the assistant's message content from the response.
424
- *
425
- * @returns The assistant's message content or null
426
- */
427
- getAssistantMessage() {
428
- if (!this.llmResponse)
429
- return null;
430
- const completion = this.llmResponse.completion;
431
- if (completion && completion.choices && completion.choices.length > 0) {
432
- const choice = completion.choices[0];
433
- if (choice.message && choice.message.content) {
434
- return choice.message.content;
435
- }
436
- }
437
- else if (completion && completion.content) {
438
- return completion.content;
439
- }
440
- return null;
441
- }
442
- /**
443
- * Resets the handler state for reuse.
444
- */
445
- reset() {
446
- this.completed = false;
447
- this.toolResults = [];
448
- this.nextUserMessage = null;
449
- this.mcpExecuted = false;
450
- }
451
- }
452
- exports.LLMOutputHandler = LLMOutputHandler;
@@ -1,49 +0,0 @@
1
- import { IAgentStep, AgentStepInput, AgentStepOutput, ProcessedMessage, ToolList, ToolExecutor, Processor } from '../types/interfaces';
2
- export interface AgentStepOptions {
3
- inputProcessors?: Processor[];
4
- outputProcessors?: Processor[];
5
- toolList?: ToolList;
6
- toolExecutor?: ToolExecutor;
7
- maxIterations?: number;
8
- }
9
- export declare abstract class AgentStep implements IAgentStep {
10
- protected readonly inputProcessors: Processor[];
11
- protected readonly outputProcessors: Processor[];
12
- protected readonly toolList?: ToolList;
13
- protected readonly toolExecutor?: ToolExecutor;
14
- protected readonly maxIterations: number;
15
- constructor(options?: AgentStepOptions);
16
- /**
17
- * Single step processing with input/output processors
18
- */
19
- step(message: ProcessedMessage, context?: Record<string, any>): Promise<ProcessedMessage>;
20
- generateOneStep(input: AgentStepInput): Promise<AgentStepOutput>;
21
- generateWithToolExecution(input: AgentStepInput): Promise<AgentStepOutput>;
22
- loop(input: AgentStepInput, maxIterations?: number): Promise<AgentStepOutput>;
23
- protected abstract analyzeForToolCalls(message: ProcessedMessage, tools: any[], context?: Record<string, any>): Promise<Array<{
24
- tool: string;
25
- parameters: any;
26
- }> | null>;
27
- protected abstract generateFinalResponse(message: ProcessedMessage, toolResults: any, context?: Record<string, any>): Promise<AgentStepOutput>;
28
- }
29
- export interface LLMConfig {
30
- llmname?: string;
31
- model?: string;
32
- temperature?: number;
33
- maxTokens?: number;
34
- apiKey?: string;
35
- baseUrl?: string;
36
- }
37
- export interface LLMAgentStepOptions extends AgentStepOptions {
38
- llmconfig?: LLMConfig;
39
- }
40
- export declare class LLMAgentStep extends AgentStep {
41
- protected readonly llmConfig: LLMConfig;
42
- constructor(options?: LLMAgentStepOptions);
43
- protected analyzeForToolCalls(message: ProcessedMessage, tools: any[], context?: Record<string, any>): Promise<Array<{
44
- tool: string;
45
- parameters: any;
46
- }> | null>;
47
- protected generateFinalResponse(message: ProcessedMessage, toolResults: any, context?: Record<string, any>): Promise<AgentStepOutput>;
48
- private extractFilePath;
49
- }