@codebolt/agent 5.0.2 → 5.0.7

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 (164) hide show
  1. package/dist/agent.d.ts +86 -0
  2. package/dist/agent.js +324 -0
  3. package/dist/builderpattern/agent.js +2 -2
  4. package/dist/builderpattern/followupquestionbuilder.js +1 -1
  5. package/dist/builderpattern/llmoutputhandler.js +7 -7
  6. package/dist/builderpattern/usermessage.d.ts +1 -6
  7. package/dist/composablepattern/document.js +35 -2
  8. package/dist/followupquestionbuilder.d.ts +75 -0
  9. package/dist/followupquestionbuilder.js +197 -0
  10. package/dist/index.d.ts +14 -0
  11. package/dist/index.js +23 -0
  12. package/dist/llmoutputhandler.d.ts +102 -0
  13. package/dist/llmoutputhandler.js +452 -0
  14. package/dist/processor/types/interfaces.d.ts +21 -44
  15. package/dist/processor-pieces/index.d.ts +3 -0
  16. package/dist/processor-pieces/index.js +3 -0
  17. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +5 -14
  18. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +40 -41
  19. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +13 -5
  20. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +58 -50
  21. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +8 -6
  22. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +22 -66
  23. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +2 -3
  24. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +2 -1
  25. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +2 -3
  26. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +2 -1
  27. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +4 -1
  28. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +2 -18
  29. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +93 -291
  30. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +18 -0
  31. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +41 -0
  32. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +2 -1
  33. package/dist/processor-pieces/postToolCallProcessors/index.js +5 -0
  34. package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -1
  35. package/dist/processor-pieces/preInferenceProcessors/index.js +3 -0
  36. package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +2 -1
  37. package/dist/processor-pieces/pretoolCallProcessors/index.js +5 -0
  38. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.d.ts +21 -0
  39. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.js +32 -0
  40. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.d.ts +16 -0
  41. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.js +37 -0
  42. package/dist/promptbuilder.d.ts +382 -0
  43. package/dist/promptbuilder.js +805 -0
  44. package/dist/systemprompt.d.ts +20 -0
  45. package/dist/systemprompt.js +48 -0
  46. package/dist/taskInstruction.d.ts +37 -0
  47. package/dist/taskInstruction.js +57 -0
  48. package/dist/types/libFunctionTypes.d.ts +13 -19
  49. package/dist/types/libFunctionTypes.js +3 -0
  50. package/dist/types/processorTypes.d.ts +8 -8
  51. package/dist/types/processorTypes.js +6 -23
  52. package/dist/unified/agent/agent.js +2 -2
  53. package/dist/unified/agent/codeboltAgent.d.ts +122 -0
  54. package/dist/unified/agent/codeboltAgent.js +210 -0
  55. package/dist/unified/base/initialPromptGenerator.js +18 -4
  56. package/dist/unified/base/responseExecutor.d.ts +3 -2
  57. package/dist/unified/base/responseExecutor.js +109 -56
  58. package/dist/unified/index.d.ts +4 -0
  59. package/dist/unified/index.js +12 -1
  60. package/dist/usermessage.d.ts +70 -0
  61. package/dist/usermessage.js +123 -0
  62. package/package.json +11 -6
  63. package/dist/local-tools/fileTools.d.ts +0 -26
  64. package/dist/local-tools/fileTools.js +0 -162
  65. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +0 -13
  66. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +0 -68
  67. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +0 -15
  68. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +0 -212
  69. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +0 -19
  70. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +0 -110
  71. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +0 -23
  72. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +0 -173
  73. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +0 -14
  74. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +0 -93
  75. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +0 -30
  76. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +0 -330
  77. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +0 -26
  78. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +0 -269
  79. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +0 -38
  80. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +0 -217
  81. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +0 -34
  82. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +0 -147
  83. package/dist/processor-pieces/additionalModifiers/index.d.ts +0 -12
  84. package/dist/processor-pieces/additionalModifiers/index.js +0 -28
  85. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +0 -29
  86. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +0 -155
  87. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +0 -15
  88. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +0 -129
  89. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +0 -25
  90. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +0 -169
  91. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +0 -20
  92. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +0 -152
  93. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +0 -7
  94. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +0 -93
  95. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +0 -9
  96. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +0 -77
  97. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +0 -19
  98. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +0 -110
  99. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +0 -20
  100. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +0 -124
  101. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +0 -41
  102. package/dist/processor-pieces/messageModifiers/environmentContext.js +0 -355
  103. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +0 -23
  104. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +0 -207
  105. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +0 -7
  106. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +0 -26
  107. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +0 -1
  108. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +0 -2
  109. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +0 -7
  110. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +0 -24
  111. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +0 -41
  112. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +0 -197
  113. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +0 -26
  114. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +0 -90
  115. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +0 -81
  116. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +0 -329
  117. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +0 -40
  118. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +0 -272
  119. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +0 -49
  120. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +0 -291
  121. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +0 -49
  122. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +0 -293
  123. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +0 -47
  124. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +0 -249
  125. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +0 -30
  126. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +0 -137
  127. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +0 -30
  128. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +0 -228
  129. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +0 -99
  130. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +0 -278
  131. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +0 -37
  132. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +0 -178
  133. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +0 -43
  134. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +0 -207
  135. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +0 -52
  136. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +0 -264
  137. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +0 -49
  138. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +0 -293
  139. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +0 -7
  140. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +0 -31
  141. package/dist/processor-pieces/preToolCall/index.d.ts +0 -9
  142. package/dist/processor-pieces/preToolCall/index.js +0 -18
  143. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +0 -58
  144. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +0 -444
  145. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +0 -44
  146. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +0 -367
  147. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +0 -58
  148. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +0 -391
  149. package/dist/unified/agent/tool.d.ts +0 -99
  150. package/dist/unified/agent/tool.js +0 -440
  151. package/dist/unified/examples/agentExample.d.ts +0 -46
  152. package/dist/unified/examples/agentExample.js +0 -464
  153. package/dist/unified/examples/documentationPatternExample.d.ts +0 -10
  154. package/dist/unified/examples/documentationPatternExample.js +0 -385
  155. package/dist/unified/examples/followUpProcessorsExample.d.ts +0 -45
  156. package/dist/unified/examples/followUpProcessorsExample.js +0 -311
  157. package/dist/unified/examples/orchestratorExample.d.ts +0 -16
  158. package/dist/unified/examples/orchestratorExample.js +0 -415
  159. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +0 -36
  160. package/dist/unified/examples/preToolCallProcessorsExample.js +0 -458
  161. package/dist/unified/examples/workflowExample.d.ts +0 -12
  162. package/dist/unified/examples/workflowExample.js +0 -497
  163. package/dist/unified/orchestrator/orchestrator.d.ts +0 -260
  164. package/dist/unified/orchestrator/orchestrator.js +0 -519
@@ -0,0 +1,452 @@
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,75 +1,52 @@
1
- import type { FlatUserMessage } from '@codebolt/types';
2
1
  export interface ToolCall {
3
- /** Unique identifier for this tool call */
4
2
  id: string;
5
- /** The type of tool call */
6
- type: 'function';
7
- /** Function call details */
8
3
  function: {
9
- /** Name of the function to call */
10
4
  name: string;
11
- /** Arguments for the function call as JSON string */
12
- arguments: string;
5
+ arguments: string | Record<string, any>;
13
6
  };
14
7
  }
15
8
  export interface Message {
16
- /** Role of the message sender */
17
- role: 'system' | 'user' | 'assistant' | 'tool';
18
- /** Content of the message */
19
- content: string | Array<{
20
- type: string;
21
- text: string;
22
- }>;
23
- /** Optional name for the message sender */
9
+ role: 'user' | 'assistant' | 'tool' | 'system';
10
+ content: string | any[];
24
11
  name?: string;
25
- /** Tool call ID for tool messages */
12
+ tool_calls?: ToolCall[];
26
13
  tool_call_id?: string;
27
- /** Tool calls for assistant messages */
28
- tool_calls?: Array<{
29
- id: string;
30
- type: 'function';
31
- function: {
32
- name: string;
33
- arguments: string;
34
- };
35
- }>;
14
+ [key: string]: any;
36
15
  }
37
16
  export interface ProcessedMessage {
38
- /** Array of messages in OpenAI format */
39
17
  messages: Message[];
40
- /** Optional metadata about the processing */
41
- metadata?: Record<string, unknown>;
18
+ metadata?: Record<string, any>;
42
19
  }
43
20
  export interface ProcessorInput {
44
21
  message: ProcessedMessage;
45
- context?: Record<string, unknown>;
22
+ context?: Record<string, any>;
46
23
  }
47
24
  export interface ProcessorOutput {
48
25
  type: string;
49
- value?: unknown;
26
+ value?: any;
50
27
  }
51
28
  export interface Processor {
52
29
  processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
53
- setContext(key: string, value: unknown): void;
54
- getContext(key: string): unknown;
30
+ setContext(key: string, value: any): void;
31
+ getContext(key: string): any;
55
32
  clearContext(): void;
56
33
  }
57
34
  export interface MessageModifierInput {
58
- originalRequest: FlatUserMessage;
35
+ originalRequest: any;
59
36
  createdMessage: ProcessedMessage;
60
- context?: Record<string, unknown>;
37
+ context?: Record<string, any>;
61
38
  }
62
39
  export interface MessageModifier {
63
40
  modify(input: MessageModifierInput): Promise<ProcessedMessage>;
64
- setContext(key: string, value: unknown): void;
65
- getContext(key: string): unknown;
41
+ setContext(key: string, value: any): void;
42
+ getContext(key: string): any;
66
43
  clearContext(): void;
67
44
  }
68
45
  export interface Tool {
69
46
  name: string;
70
47
  description: string;
71
- parameters: Record<string, unknown>;
72
- execute(params: unknown, abortSignal?: AbortSignal): Promise<unknown>;
48
+ parameters: Record<string, any>;
49
+ execute(params: any, abortSignal?: AbortSignal): Promise<any>;
73
50
  }
74
51
  export interface ToolList {
75
52
  getTool(name: string): Tool | undefined;
@@ -80,13 +57,13 @@ export interface ToolList {
80
57
  export interface AgentStepInput {
81
58
  message: ProcessedMessage;
82
59
  tools: Tool[];
83
- context?: Record<string, unknown>;
60
+ context?: Record<string, any>;
84
61
  }
85
62
  export interface AgentStepOutput {
86
63
  response: ProcessedMessage;
87
64
  toolCalls?: Array<{
88
65
  tool: string;
89
- parameters: unknown;
66
+ parameters: any;
90
67
  }>;
91
68
  finished: boolean;
92
69
  }
@@ -98,15 +75,15 @@ export interface IAgentStep {
98
75
  export interface ToolExecutionInput {
99
76
  toolCalls: Array<{
100
77
  tool: string;
101
- parameters: unknown;
78
+ parameters: any;
102
79
  }>;
103
80
  tools: ToolList;
104
- context?: Record<string, unknown>;
81
+ context?: Record<string, any>;
105
82
  }
106
83
  export interface ToolExecutionOutput {
107
84
  results: Array<{
108
85
  tool: string;
109
- result: unknown;
86
+ result: any;
110
87
  error?: string;
111
88
  }>;
112
89
  success: boolean;
@@ -1 +1,4 @@
1
1
  export * from './messageModifiers';
2
+ export * from './pretoolCallProcessors';
3
+ export * from './postToolCallProcessors';
4
+ export * from './preInferenceProcessors';
@@ -57,3 +57,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
57
57
  // FileCopyTool
58
58
  // } from './tools/fileTools';
59
59
  __exportStar(require("./messageModifiers"), exports);
60
+ __exportStar(require("./pretoolCallProcessors"), exports);
61
+ __exportStar(require("./postToolCallProcessors"), exports);
62
+ __exportStar(require("./preInferenceProcessors"), exports);
@@ -1,28 +1,19 @@
1
- import { ProcessedMessage } from "@codebolt/types/agent";
2
- import { BaseMessageModifier } from "../base";
3
- import { FlatUserMessage, Tool } from "@codebolt/types/sdk";
4
- export interface ToolList {
5
- getAllTools(): Tool[];
6
- addTool?(tool: Tool): void;
7
- removeTool?(toolName: string): void;
8
- getTool?(toolName: string): Tool | undefined;
9
- getToolNames?(): string[];
10
- }
1
+ import { BaseMessageModifier, MessageModifierInput, ProcessedMessage, ToolList } from '../../processor';
11
2
  export interface AddToolsListMessageModifierOptions {
12
- toolsList?: ToolList;
3
+ toolsList: ToolList;
13
4
  addToolsLocation?: 'InsidePrompt' | 'Tool' | 'SystemMessage';
14
5
  giveToolExamples?: boolean;
15
6
  maxToolExamples?: number;
16
7
  includeToolDescriptions?: boolean;
17
8
  }
18
9
  export declare class AddToolsListMessageModifier extends BaseMessageModifier {
19
- private readonly toolsList?;
10
+ private readonly toolsList;
20
11
  private readonly addToolsLocation;
21
12
  private readonly giveToolExamples;
22
13
  private readonly maxToolExamples;
23
14
  private readonly includeToolDescriptions;
24
- constructor(options?: AddToolsListMessageModifierOptions);
25
- modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
15
+ constructor(options: AddToolsListMessageModifierOptions);
16
+ modify(input: MessageModifierInput): Promise<ProcessedMessage>;
26
17
  private addToolsInsidePrompt;
27
18
  private addToolsAsSystemMessage;
28
19
  private addToolsAsToolCalls;