@codebolt/agent 1.2.1 → 2.2.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.
Files changed (183) hide show
  1. package/README.md +157 -66
  2. package/dist/builderpattern/agent.d.ts +86 -0
  3. package/dist/builderpattern/agent.js +324 -0
  4. package/dist/builderpattern/followupquestionbuilder.d.ts +75 -0
  5. package/dist/builderpattern/followupquestionbuilder.js +197 -0
  6. package/dist/builderpattern/index.d.ts +14 -0
  7. package/dist/builderpattern/index.js +23 -0
  8. package/dist/builderpattern/llmoutputhandler.d.ts +102 -0
  9. package/dist/builderpattern/llmoutputhandler.js +452 -0
  10. package/dist/builderpattern/promptbuilder.d.ts +382 -0
  11. package/dist/builderpattern/promptbuilder.js +805 -0
  12. package/dist/builderpattern/systemprompt.d.ts +20 -0
  13. package/dist/builderpattern/systemprompt.js +48 -0
  14. package/dist/builderpattern/taskInstruction.d.ts +37 -0
  15. package/dist/builderpattern/taskInstruction.js +57 -0
  16. package/dist/builderpattern/usermessage.d.ts +70 -0
  17. package/dist/builderpattern/usermessage.js +123 -0
  18. package/dist/composablepattern/agent.d.ts +169 -0
  19. package/dist/composablepattern/agent.js +598 -0
  20. package/dist/composablepattern/codebolt-storage.d.ts +67 -0
  21. package/dist/composablepattern/codebolt-storage.js +320 -0
  22. package/dist/composablepattern/document.d.ts +149 -0
  23. package/dist/composablepattern/document.js +405 -0
  24. package/dist/composablepattern/examples/codebolt-integration-example.d.ts +12 -0
  25. package/dist/composablepattern/examples/codebolt-integration-example.js +218 -0
  26. package/dist/composablepattern/examples/codebolt-storage-example.d.ts +40 -0
  27. package/dist/composablepattern/examples/codebolt-storage-example.js +223 -0
  28. package/dist/composablepattern/examples/custom-steps-example.d.ts +20 -0
  29. package/dist/composablepattern/examples/custom-steps-example.js +455 -0
  30. package/dist/composablepattern/examples/document-agent.d.ts +17 -0
  31. package/dist/composablepattern/examples/document-agent.js +107 -0
  32. package/dist/composablepattern/examples/simple-codebolt-integration.d.ts +8 -0
  33. package/dist/composablepattern/examples/simple-codebolt-integration.js +164 -0
  34. package/dist/composablepattern/examples/weather-agent.d.ts +18 -0
  35. package/dist/composablepattern/examples/weather-agent.js +86 -0
  36. package/dist/composablepattern/examples/workflow-example.d.ts +12 -0
  37. package/dist/composablepattern/examples/workflow-example.js +463 -0
  38. package/dist/composablepattern/index.d.ts +63 -0
  39. package/dist/composablepattern/index.js +115 -0
  40. package/dist/composablepattern/memory.d.ts +89 -0
  41. package/dist/composablepattern/memory.js +141 -0
  42. package/dist/composablepattern/tool.d.ts +84 -0
  43. package/dist/composablepattern/tool.js +260 -0
  44. package/dist/composablepattern/types.d.ts +194 -0
  45. package/dist/composablepattern/types.js +6 -0
  46. package/dist/composablepattern/user-context.d.ts +214 -0
  47. package/dist/composablepattern/user-context.js +275 -0
  48. package/dist/composablepattern/workflow.d.ts +388 -0
  49. package/dist/composablepattern/workflow.js +562 -0
  50. package/dist/processor/agent/agentStep.d.ts +49 -0
  51. package/dist/processor/agent/agentStep.js +241 -0
  52. package/dist/processor/agent/toolExecutor.d.ts +19 -0
  53. package/dist/processor/agent/toolExecutor.js +90 -0
  54. package/dist/processor/index.d.ts +7 -0
  55. package/dist/processor/index.js +36 -0
  56. package/dist/processor/messageModifiers/baseMessageModifier.d.ts +20 -0
  57. package/dist/processor/messageModifiers/baseMessageModifier.js +55 -0
  58. package/dist/processor/processors/baseProcessor.d.ts +14 -0
  59. package/dist/processor/processors/baseProcessor.js +29 -0
  60. package/dist/processor/tools/baseTool.d.ts +10 -0
  61. package/dist/processor/tools/baseTool.js +20 -0
  62. package/dist/processor/tools/toolList.d.ts +9 -0
  63. package/dist/processor/tools/toolList.js +22 -0
  64. package/dist/processor/types/interfaces.d.ts +94 -0
  65. package/dist/processor/types/interfaces.js +2 -0
  66. package/dist/processor-pieces/base/baseMessageModifier.d.ts +12 -0
  67. package/dist/processor-pieces/base/baseMessageModifier.js +15 -0
  68. package/dist/processor-pieces/base/basePostInferenceProcessor.d.ts +13 -0
  69. package/dist/processor-pieces/base/basePostInferenceProcessor.js +18 -0
  70. package/dist/processor-pieces/base/basePostToolCallProcessor.d.ts +15 -0
  71. package/dist/processor-pieces/base/basePostToolCallProcessor.js +25 -0
  72. package/dist/processor-pieces/base/basePreInferenceProcessor.d.ts +12 -0
  73. package/dist/processor-pieces/base/basePreInferenceProcessor.js +17 -0
  74. package/dist/processor-pieces/base/basePreToolCallProcessor.d.ts +18 -0
  75. package/dist/processor-pieces/base/basePreToolCallProcessor.js +66 -0
  76. package/dist/processor-pieces/base/index.d.ts +9 -0
  77. package/dist/processor-pieces/base/index.js +18 -0
  78. package/dist/processor-pieces/index.d.ts +1 -0
  79. package/dist/processor-pieces/index.js +59 -0
  80. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +22 -0
  81. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +144 -0
  82. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.d.ts +13 -0
  83. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +68 -0
  84. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.d.ts +25 -0
  85. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +453 -0
  86. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +15 -0
  87. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +75 -0
  88. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +11 -0
  89. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +46 -0
  90. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.d.ts +18 -0
  91. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +104 -0
  92. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.d.ts +23 -0
  93. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +173 -0
  94. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.d.ts +14 -0
  95. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +130 -0
  96. package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +36 -0
  97. package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +418 -0
  98. package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +26 -0
  99. package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +260 -0
  100. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +12 -0
  101. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +60 -0
  102. package/dist/processor-pieces/messageModifiers/ideContextModifier.d.ts +34 -0
  103. package/dist/processor-pieces/messageModifiers/ideContextModifier.js +157 -0
  104. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +18 -0
  105. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +222 -0
  106. package/dist/processor-pieces/messageModifiers/index.d.ts +11 -0
  107. package/dist/processor-pieces/messageModifiers/index.js +26 -0
  108. package/dist/processor-pieces/messageModifiers/memoryImportModifier.d.ts +15 -0
  109. package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +129 -0
  110. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.d.ts +20 -0
  111. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +152 -0
  112. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +22 -0
  113. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +194 -0
  114. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.d.ts +29 -0
  115. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +174 -0
  116. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +1 -0
  117. package/dist/processor-pieces/postToolCallProcessors/index.js +2 -0
  118. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.d.ts +25 -0
  119. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +225 -0
  120. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.d.ts +35 -0
  121. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +255 -0
  122. package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -0
  123. package/dist/processor-pieces/preInferenceProcessors/index.js +2 -0
  124. package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +1 -0
  125. package/dist/processor-pieces/pretoolCallProcessors/index.js +2 -0
  126. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.d.ts +41 -0
  127. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.js +197 -0
  128. package/dist/processor-pieces/processors/chatCompressionProcessor.d.ts +26 -0
  129. package/dist/processor-pieces/processors/chatCompressionProcessor.js +90 -0
  130. package/dist/processor-pieces/processors/chatRecordingProcessor.d.ts +81 -0
  131. package/dist/processor-pieces/processors/chatRecordingProcessor.js +329 -0
  132. package/dist/processor-pieces/processors/contextManagementProcessor.d.ts +40 -0
  133. package/dist/processor-pieces/processors/contextManagementProcessor.js +305 -0
  134. package/dist/processor-pieces/processors/loopDetectionProcessor.d.ts +30 -0
  135. package/dist/processor-pieces/processors/loopDetectionProcessor.js +137 -0
  136. package/dist/processor-pieces/processors/responseValidationProcessor.d.ts +30 -0
  137. package/dist/processor-pieces/processors/responseValidationProcessor.js +228 -0
  138. package/dist/processor-pieces/processors/telemetryProcessor.d.ts +99 -0
  139. package/dist/processor-pieces/processors/telemetryProcessor.js +311 -0
  140. package/dist/processor-pieces/processors/tokenManagementProcessor.d.ts +37 -0
  141. package/dist/processor-pieces/processors/tokenManagementProcessor.js +178 -0
  142. package/dist/processor-pieces/processors/toolExecutionProcessor.d.ts +43 -0
  143. package/dist/processor-pieces/processors/toolExecutionProcessor.js +207 -0
  144. package/dist/processor-pieces/tools/fileTools.d.ts +26 -0
  145. package/dist/processor-pieces/tools/fileTools.js +162 -0
  146. package/dist/processor-pieces/utils/messageModifierHelper.d.ts +4 -0
  147. package/dist/processor-pieces/utils/messageModifierHelper.js +58 -0
  148. package/dist/types/commonTypes.d.ts +4 -0
  149. package/dist/types/processorTypes.d.ts +67 -0
  150. package/dist/types/processorTypes.js +58 -0
  151. package/dist/unified/agent/agent.d.ts +17 -0
  152. package/dist/unified/agent/agent.js +79 -0
  153. package/dist/unified/agent/team.d.ts +2 -0
  154. package/dist/unified/agent/team.js +6 -0
  155. package/dist/unified/agent/tools.d.ts +44 -0
  156. package/dist/unified/agent/tools.js +487 -0
  157. package/dist/unified/agent/workflow.d.ts +24 -0
  158. package/dist/unified/agent/workflow.js +275 -0
  159. package/dist/unified/agent/workflowControls.d.ts +11 -0
  160. package/dist/unified/agent/workflowControls.js +20 -0
  161. package/dist/unified/agent/workflowSteps.d.ts +63 -0
  162. package/dist/unified/agent/workflowSteps.js +284 -0
  163. package/dist/unified/base/agentStep.d.ts +32 -0
  164. package/dist/unified/base/agentStep.js +96 -0
  165. package/dist/unified/base/create/createInitialPromptGenerators.d.ts +5 -0
  166. package/dist/unified/base/create/createInitialPromptGenerators.js +17 -0
  167. package/dist/unified/base/index.d.ts +5 -0
  168. package/dist/unified/base/index.js +13 -0
  169. package/dist/unified/base/initialPromptGenerator.d.ts +48 -0
  170. package/dist/unified/base/initialPromptGenerator.js +118 -0
  171. package/dist/unified/base/responseExecutor.d.ts +36 -0
  172. package/dist/unified/base/responseExecutor.js +283 -0
  173. package/dist/unified/index.d.ts +18 -0
  174. package/dist/unified/index.js +42 -0
  175. package/dist/unified/team/team.d.ts +1 -0
  176. package/dist/unified/team/team.js +2 -0
  177. package/dist/unified/types/libTypes.d.ts +378 -0
  178. package/dist/unified/types/libTypes.js +6 -0
  179. package/dist/unified/types/types.d.ts +212 -0
  180. package/dist/unified/types/types.js +43 -0
  181. package/dist/unified/utils/utils.d.ts +40 -0
  182. package/dist/unified/utils/utils.js +219 -0
  183. package/package.json +29 -7
@@ -0,0 +1,324 @@
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.Agent = void 0;
7
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
8
+ const { chat, mcp, llm, agent: codeboltAgent } = codeboltjs_1.default;
9
+ // All interfaces moved to libFunctionTypes.ts
10
+ /**
11
+ * Agent class that manages conversations with LLMs and tool executions.
12
+ * Handles the conversation flow, tool calls, and task completions.
13
+ */
14
+ class Agent {
15
+ /**
16
+ * Creates a new Agent instance.
17
+ *
18
+ * @param tools - The tools available to the agent
19
+ * @param systemPrompt - The system prompt providing instructions to the LLM
20
+ * @param maxRun - Maximum number of conversation turns (0 means unlimited)
21
+ */
22
+ constructor(tools = [], systemPrompt, maxRun = 0) {
23
+ this.tools = tools;
24
+ this.userMessage = [];
25
+ this.apiConversationHistory = [];
26
+ this.maxRun = maxRun;
27
+ this.systemPrompt = systemPrompt;
28
+ }
29
+ /**
30
+ * Runs the agent on a specific task until completion or max runs reached.
31
+ *
32
+ * @param task - The task instruction to be executed
33
+ * @param successCondition - Optional function to determine if the task is successful
34
+ * @returns Promise with success status, error (if any), and the last assistant message
35
+ */
36
+ async run(task, successCondition = () => true) {
37
+ var _a, _b;
38
+ let mentaionedMCPSTool = await task.userMessage.getMentionedMcpsTools();
39
+ this.tools = [
40
+ ...this.tools,
41
+ ...mentaionedMCPSTool || [],
42
+ ];
43
+ let mentionedAgents = await task.userMessage.getMentionedAgents();
44
+ // Transform agents into tool format
45
+ const agentTools = mentionedAgents.map(agent => {
46
+ return {
47
+ type: "function",
48
+ function: {
49
+ name: `subagent--${agent.unique_id}`,
50
+ description: agent.longDescription || agent.description,
51
+ parameters: {
52
+ type: "object",
53
+ properties: {
54
+ task: {
55
+ type: "string",
56
+ description: "The task to be executed by the tool."
57
+ }
58
+ },
59
+ required: ["task"]
60
+ }
61
+ }
62
+ };
63
+ });
64
+ this.tools = this.tools.concat(agentTools);
65
+ let completed = false;
66
+ let userMessages = await task.toPrompt();
67
+ this.apiConversationHistory.push({ role: "user", content: userMessages });
68
+ let runcomplete = 0;
69
+ while (!completed && (runcomplete <= this.maxRun || this.maxRun === 0)) {
70
+ try {
71
+ runcomplete++;
72
+ const response = await this.attemptLlmRequest(this.apiConversationHistory, this.tools);
73
+ let isMessagePresentinReply = false;
74
+ for (const contentBlock of response.choices) {
75
+ if (contentBlock.message) {
76
+ isMessagePresentinReply = true;
77
+ this.apiConversationHistory.push(contentBlock.message);
78
+ if (contentBlock.message.content != null) {
79
+ await chat.sendMessage(contentBlock.message.content, {});
80
+ }
81
+ }
82
+ }
83
+ if (!isMessagePresentinReply) {
84
+ this.apiConversationHistory.push({
85
+ role: "assistant",
86
+ content: [{ type: "text", text: "Failure: I did not provide a response." }],
87
+ });
88
+ }
89
+ try {
90
+ let toolResults = [];
91
+ let taskCompletedBlock;
92
+ let userRejectedToolUse = false;
93
+ const contentBlock = response.choices[0];
94
+ if ((_a = contentBlock.message) === null || _a === void 0 ? void 0 : _a.tool_calls) {
95
+ for (const tool of contentBlock.message.tool_calls) {
96
+ try {
97
+ const { toolInput, toolName, toolUseId } = this.getToolDetail(tool);
98
+ if (!userRejectedToolUse) {
99
+ if (toolName.includes("attempt_completion")) {
100
+ taskCompletedBlock = tool;
101
+ }
102
+ else {
103
+ let [serverName] = toolName.replace('--', ':').split(':');
104
+ if (serverName == 'subagent') {
105
+ const agentResponse = await codeboltAgent.startAgent(toolName.replace("subagent--", ''), toolInput.task);
106
+ const [didUserReject, result] = [false, "tool result is successful"];
107
+ let toolResult = this.getToolResult(toolUseId, result);
108
+ toolResults.push({
109
+ role: "tool",
110
+ tool_call_id: toolResult.tool_call_id,
111
+ content: toolResult.content,
112
+ });
113
+ if (toolResult.userMessage) {
114
+ this.nextUserMessage = {
115
+ role: "user",
116
+ content: toolResult.userMessage
117
+ };
118
+ }
119
+ if (didUserReject) {
120
+ userRejectedToolUse = true;
121
+ }
122
+ }
123
+ else {
124
+ const [didUserReject, result] = await this.executeTool(toolName, toolInput);
125
+ // toolResults.push(this.getToolResult(toolUseId, result));
126
+ let toolResult = this.getToolResult(toolUseId, result);
127
+ toolResults.push({
128
+ role: "tool",
129
+ tool_call_id: toolResult.tool_call_id,
130
+ content: toolResult.content,
131
+ });
132
+ if (toolResult.userMessage) {
133
+ this.nextUserMessage = {
134
+ role: "user",
135
+ content: toolResult.userMessage
136
+ };
137
+ }
138
+ if (didUserReject) {
139
+ userRejectedToolUse = true;
140
+ }
141
+ }
142
+ }
143
+ }
144
+ else {
145
+ let toolResult = this.getToolResult(toolUseId, "Skipping tool execution due to previous tool user rejection.");
146
+ toolResults.push({
147
+ role: "tool",
148
+ tool_call_id: toolResult.tool_call_id,
149
+ content: toolResult.content,
150
+ });
151
+ if (toolResult.userMessage) {
152
+ this.nextUserMessage = {
153
+ role: "user",
154
+ content: toolResult.userMessage
155
+ };
156
+ }
157
+ }
158
+ }
159
+ catch (error) {
160
+ toolResults.push({
161
+ role: "tool",
162
+ tool_call_id: tool.id,
163
+ content: `please provide valid json string for tool.function.arguments String(error)`,
164
+ });
165
+ }
166
+ }
167
+ }
168
+ if (taskCompletedBlock) {
169
+ let [_, result] = await this.executeTool(taskCompletedBlock.function.name, JSON.parse(taskCompletedBlock.function.arguments || "{}"));
170
+ if (result === "") {
171
+ completed = true;
172
+ result = "The user is satisfied with the result.";
173
+ }
174
+ let toolResult = this.getToolResult(taskCompletedBlock.id, result);
175
+ toolResults.push({
176
+ role: "tool",
177
+ tool_call_id: toolResult.tool_call_id,
178
+ content: toolResult.content,
179
+ });
180
+ if (toolResult.userMessage) {
181
+ this.nextUserMessage = {
182
+ role: "user",
183
+ content: toolResult.userMessage
184
+ };
185
+ }
186
+ }
187
+ this.apiConversationHistory.push(...toolResults);
188
+ if (this.nextUserMessage) {
189
+ this.apiConversationHistory.push(this.nextUserMessage);
190
+ }
191
+ let nextUserMessage = toolResults;
192
+ if (toolResults.length === 0) {
193
+ nextUserMessage = [{
194
+ role: "user",
195
+ content: [{
196
+ type: "text",
197
+ 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.)"
198
+ }]
199
+ }];
200
+ if (nextUserMessage) {
201
+ this.apiConversationHistory.push(nextUserMessage[0]);
202
+ }
203
+ }
204
+ }
205
+ catch (error) {
206
+ console.error("Error in agent tool call:", error);
207
+ return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
208
+ }
209
+ }
210
+ catch (error) {
211
+ console.error("Error in agent tool call:", error);
212
+ return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
213
+ }
214
+ }
215
+ return {
216
+ success: completed,
217
+ error: null,
218
+ message: ((_b = this.apiConversationHistory
219
+ .filter(msg => msg.role === 'assistant')
220
+ .pop()) === null || _b === void 0 ? void 0 : _b.content) || ''
221
+ };
222
+ }
223
+ /**
224
+ * Attempts to make a request to the LLM with conversation history and tools.
225
+ *
226
+ * @param apiConversationHistory - The current conversation history
227
+ * @param tools - The tools available to the LLM
228
+ * @returns Promise with the LLM response
229
+ */
230
+ async attemptLlmRequest(apiConversationHistory, tools) {
231
+ try {
232
+ let systemPrompt = await this.systemPrompt.toPromptText();
233
+ const aiMessages = [
234
+ { role: "system", content: systemPrompt },
235
+ ...apiConversationHistory,
236
+ ];
237
+ const createParams = {
238
+ full: true,
239
+ messages: aiMessages,
240
+ tools: tools,
241
+ tool_choice: "auto",
242
+ };
243
+ //@ts-ignore
244
+ const { completion } = await llm.inference(createParams);
245
+ return completion;
246
+ }
247
+ catch (error) {
248
+ return this.attemptApiRequest();
249
+ }
250
+ }
251
+ /**
252
+ * Executes a tool with given name and input.
253
+ *
254
+ * @param toolName - The name of the tool to execute
255
+ * @param toolInput - The input parameters for the tool
256
+ * @returns Promise with tuple [userRejected, result]
257
+ */
258
+ async executeTool(toolName, toolInput) {
259
+ //codebolttools--readfile
260
+ const [toolboxName, actualToolName] = toolName.split('--');
261
+ console.log("Toolbox name: ", toolboxName, "Actual tool name: ", actualToolName);
262
+ const { data } = await mcp.executeTool(toolboxName, actualToolName, toolInput);
263
+ console.log("Tool result: ", data);
264
+ return data;
265
+ }
266
+ /**
267
+ * Starts a sub-agent to handle a specific task.
268
+ *
269
+ * @param agentName - The name of the sub-agent to start
270
+ * @param params - Parameters for the sub-agent
271
+ * @returns Promise with tuple [userRejected, result]
272
+ */
273
+ async startSubAgent(agentName, params) {
274
+ return [false, await codeboltAgent.startAgent(agentName, params.task)];
275
+ }
276
+ /**
277
+ * Extracts tool details from a tool call object.
278
+ *
279
+ * @param tool - The tool call object from the LLM response
280
+ * @returns ToolDetails object with name, input, and ID
281
+ */
282
+ getToolDetail(tool) {
283
+ return {
284
+ toolName: tool.function.name,
285
+ toolInput: JSON.parse(tool.function.arguments || "{}"),
286
+ toolUseId: tool.id
287
+ };
288
+ }
289
+ /**
290
+ * Creates a tool result object from the tool execution response.
291
+ *
292
+ * @param tool_call_id - The ID of the tool call
293
+ * @param content - The content returned by the tool
294
+ * @returns ToolResult object
295
+ */
296
+ getToolResult(tool_call_id, content) {
297
+ let userMessage = undefined;
298
+ try {
299
+ let parsed = JSON.parse(content);
300
+ if (parsed.payload && parsed.payload.content) {
301
+ 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`;
302
+ // this.apiConversationHistory.push()
303
+ userMessage = parsed.payload.content;
304
+ }
305
+ }
306
+ catch (error) {
307
+ }
308
+ return {
309
+ role: "tool",
310
+ tool_call_id,
311
+ content,
312
+ userMessage
313
+ };
314
+ }
315
+ /**
316
+ * Fallback method for API requests in case of failures.
317
+ *
318
+ * @throws Error API request fallback not implemented
319
+ */
320
+ attemptApiRequest() {
321
+ throw new Error("API request fallback not implemented");
322
+ }
323
+ }
324
+ exports.Agent = Agent;
@@ -0,0 +1,75 @@
1
+ import type { OpenAIMessage, OpenAITool, ToolResult, CodeboltAPI } from "../types/libFunctionTypes";
2
+ /**
3
+ * Builds follow-up prompts for continuing conversations with tool results.
4
+ * Manages conversation history and summarization when conversations get too long.
5
+ */
6
+ declare class FollowUpPromptBuilder {
7
+ /** Previous conversation messages */
8
+ private previousConversation;
9
+ /** Tool results to add to the conversation */
10
+ private toolResults;
11
+ /** Available tools for the conversation */
12
+ private tools;
13
+ /** The last LLM response, if available */
14
+ private llmResponse?;
15
+ /** Maximum conversation length before summarization */
16
+ private maxConversationLength;
17
+ /** Whether to force summarization */
18
+ private forceSummarization;
19
+ /** Codebolt API instance */
20
+ private codebolt?;
21
+ /**
22
+ * Creates a new FollowUpQuestionBuilder instance.
23
+ *
24
+ * @param codebolt - Optional codebolt API instance
25
+ */
26
+ constructor(codebolt?: CodeboltAPI);
27
+ /**
28
+ * Adds the previous conversation to the builder.
29
+ *
30
+ * @param previousPrompt - The previous prompt object containing messages and tools
31
+ * @returns The FollowUpQuestionBuilder instance for chaining
32
+ */
33
+ addPreviousConversation(previousPrompt: {
34
+ messages: OpenAIMessage[];
35
+ tools: OpenAITool[];
36
+ tool_choice?: string;
37
+ }, llmResponse: {
38
+ completion: any;
39
+ }): this;
40
+ addLLMResponseToConverstaion(llmResponse: {
41
+ completion: any;
42
+ }): this;
43
+ /**
44
+ * Adds tool execution results to the conversation.
45
+ *
46
+ * @param toolResults - Array of tool execution results
47
+ * @returns The FollowUpQuestionBuilder instance for chaining
48
+ */
49
+ addToolResult(toolResults: ToolResult[]): this;
50
+ /**
51
+ * Checks if the conversation is too long and sets up summarization with custom max length.
52
+ *
53
+ * @param maxLength - Maximum number of messages before summarization
54
+ * @returns The FollowUpQuestionBuilder instance for chaining
55
+ */
56
+ checkAndSummarizeConversationIfLong(maxLength: number): this;
57
+ /**
58
+ * Performs conversation summarization if needed.
59
+ *
60
+ * @returns Promise that resolves to the summarized messages
61
+ */
62
+ private performSummarization;
63
+ /**
64
+ * Builds the follow-up conversation prompt with tool results.
65
+ *
66
+ * @returns Promise that resolves to the conversation prompt object
67
+ */
68
+ build(): Promise<{
69
+ messages: OpenAIMessage[];
70
+ tools: OpenAITool[];
71
+ tool_choice: "auto";
72
+ full: boolean;
73
+ }>;
74
+ }
75
+ export { FollowUpPromptBuilder };
@@ -0,0 +1,197 @@
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.FollowUpPromptBuilder = void 0;
7
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
8
+ const { chatSummary } = codeboltjs_1.default;
9
+ /**
10
+ * Builds follow-up prompts for continuing conversations with tool results.
11
+ * Manages conversation history and summarization when conversations get too long.
12
+ */
13
+ class FollowUpPromptBuilder {
14
+ /**
15
+ * Creates a new FollowUpQuestionBuilder instance.
16
+ *
17
+ * @param codebolt - Optional codebolt API instance
18
+ */
19
+ constructor(codebolt) {
20
+ /** Previous conversation messages */
21
+ this.previousConversation = [];
22
+ /** Tool results to add to the conversation */
23
+ this.toolResults = [];
24
+ /** Available tools for the conversation */
25
+ this.tools = [];
26
+ /** Maximum conversation length before summarization */
27
+ this.maxConversationLength = 50;
28
+ /** Whether to force summarization */
29
+ this.forceSummarization = false;
30
+ this.codebolt = codebolt;
31
+ }
32
+ /**
33
+ * Adds the previous conversation to the builder.
34
+ *
35
+ * @param previousPrompt - The previous prompt object containing messages and tools
36
+ * @returns The FollowUpQuestionBuilder instance for chaining
37
+ */
38
+ addPreviousConversation(previousPrompt, llmResponse) {
39
+ this.previousConversation = [...previousPrompt.messages];
40
+ this.tools = [...previousPrompt.tools];
41
+ try {
42
+ // Resolve the response if it's a promise
43
+ const resolvedResponse = llmResponse;
44
+ if (!resolvedResponse || !resolvedResponse.completion) {
45
+ console.warn("Invalid LLM response provided");
46
+ return this;
47
+ }
48
+ const completion = resolvedResponse.completion;
49
+ let assistantMessage = null;
50
+ // Handle different response formats
51
+ if (completion.choices && completion.choices.length > 0) {
52
+ // OpenAI-style response with choices
53
+ const choice = completion.choices[0];
54
+ if (choice.message) {
55
+ assistantMessage = {
56
+ role: "assistant",
57
+ content: choice.message.content || "",
58
+ tool_calls: choice.message.tool_calls || undefined
59
+ };
60
+ }
61
+ }
62
+ else if (completion.content) {
63
+ // Direct content response
64
+ assistantMessage = {
65
+ role: "assistant",
66
+ content: completion.content
67
+ };
68
+ }
69
+ else if (completion.message) {
70
+ // Message format response
71
+ assistantMessage = {
72
+ role: "assistant",
73
+ content: completion.message.content || "",
74
+ tool_calls: completion.message.tool_calls || undefined
75
+ };
76
+ }
77
+ // Add the assistant message to conversation history
78
+ if (assistantMessage) {
79
+ this.previousConversation.push(assistantMessage);
80
+ }
81
+ else {
82
+ // Fallback for cases where no valid message is found
83
+ this.previousConversation.push({
84
+ role: "assistant",
85
+ content: "I apologize, but I was unable to provide a proper response."
86
+ });
87
+ }
88
+ }
89
+ catch (error) {
90
+ console.error("Error adding LLM response to conversation:", error);
91
+ // Add error message to conversation history
92
+ this.previousConversation.push({
93
+ role: "assistant",
94
+ content: "An error occurred while processing my response."
95
+ });
96
+ }
97
+ return this;
98
+ }
99
+ addLLMResponseToConverstaion(llmResponse) {
100
+ return this;
101
+ }
102
+ /**
103
+ * Adds tool execution results to the conversation.
104
+ *
105
+ * @param toolResults - Array of tool execution results
106
+ * @returns The FollowUpQuestionBuilder instance for chaining
107
+ */
108
+ addToolResult(toolResults) {
109
+ toolResults.forEach(toolResult => {
110
+ this.previousConversation.push(toolResult);
111
+ });
112
+ if (!toolResults.length) {
113
+ this.previousConversation.push({
114
+ role: "user",
115
+ content: [{
116
+ type: "text",
117
+ 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.)"
118
+ }]
119
+ });
120
+ }
121
+ return this;
122
+ }
123
+ /**
124
+ * Checks if the conversation is too long and sets up summarization with custom max length.
125
+ *
126
+ * @param maxLength - Maximum number of messages before summarization
127
+ * @returns The FollowUpQuestionBuilder instance for chaining
128
+ */
129
+ checkAndSummarizeConversationIfLong(maxLength) {
130
+ this.maxConversationLength = maxLength;
131
+ this.forceSummarization = this.previousConversation.length > maxLength;
132
+ return this;
133
+ }
134
+ /**
135
+ * Performs conversation summarization if needed.
136
+ *
137
+ * @returns Promise that resolves to the summarized messages
138
+ */
139
+ async performSummarization() {
140
+ const shouldSummarize = this.forceSummarization ||
141
+ this.previousConversation.length > this.maxConversationLength;
142
+ if (!shouldSummarize) {
143
+ return this.previousConversation;
144
+ }
145
+ try {
146
+ console.log("Summarizing conversation due to length:", this.previousConversation.length);
147
+ // Convert OpenAI messages to the format expected by chatSummary
148
+ const messagesToSummarize = this.previousConversation.map(msg => ({
149
+ role: msg.role,
150
+ content: typeof msg.content === 'string' ? msg.content :
151
+ Array.isArray(msg.content) ? msg.content.map(c => c.text).join(' ') :
152
+ String(msg.content)
153
+ }));
154
+ // Use the chat summary service to summarize the conversation
155
+ const summaryResponse = await chatSummary.summarize(messagesToSummarize, Math.floor(this.maxConversationLength / 2));
156
+ if (summaryResponse.payload || summaryResponse.summary) {
157
+ const summaryText = summaryResponse.payload || summaryResponse.summary || '';
158
+ // Keep the system message if it exists, and replace the rest with summary
159
+ const systemMessage = this.previousConversation.find(msg => msg.role === 'system');
160
+ const summarizedMessages = [];
161
+ if (systemMessage) {
162
+ summarizedMessages.push(systemMessage);
163
+ }
164
+ // Add the summary as a system message
165
+ summarizedMessages.push({
166
+ role: 'system',
167
+ content: `Previous conversation summary: ${summaryText}`
168
+ });
169
+ // Keep the last few messages for context
170
+ const recentMessages = this.previousConversation.slice(-5);
171
+ summarizedMessages.push(...recentMessages);
172
+ return summarizedMessages;
173
+ }
174
+ }
175
+ catch (error) {
176
+ console.error("Error summarizing conversation:", error);
177
+ }
178
+ // If summarization fails, just return the original conversation
179
+ return this.previousConversation;
180
+ }
181
+ /**
182
+ * Builds the follow-up conversation prompt with tool results.
183
+ *
184
+ * @returns Promise that resolves to the conversation prompt object
185
+ */
186
+ async build() {
187
+ // Perform summarization if needed
188
+ let messages = this.previousConversation;
189
+ return {
190
+ messages,
191
+ tools: this.tools,
192
+ full: true,
193
+ tool_choice: "auto"
194
+ };
195
+ }
196
+ }
197
+ exports.FollowUpPromptBuilder = FollowUpPromptBuilder;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @fileoverview Main entry point for CodeBolt Agent Utils
3
+ * @description Exports all agent utilities including Agent class, message builders, and prompt utilities
4
+ */
5
+ export { Agent } from './agent';
6
+ export { UserMessage } from './usermessage';
7
+ export { SystemPrompt } from './systemprompt';
8
+ export { TaskInstruction } from './taskInstruction';
9
+ export { InitialPromptBuilder } from './promptbuilder';
10
+ export { FollowUpPromptBuilder } from './followupquestionbuilder';
11
+ export { LLMOutputHandler } from './llmoutputhandler';
12
+ export type { Message, ToolResult, ToolDetails, OpenAIMessage, OpenAITool, ConversationEntry, UserMessageContent, CodeboltAPI, ToolCall } from '../types/libFunctionTypes';
13
+ export type { MCPTool, Agent as AgentType, InitialUserMessage } from '../types/commonTypes';
14
+ export type { UserMessage as CLIUserMessage } from '../types/socketMessageTypes';
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Main entry point for CodeBolt Agent Utils
4
+ * @description Exports all agent utilities including Agent class, message builders, and prompt utilities
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.LLMOutputHandler = exports.FollowUpPromptBuilder = exports.InitialPromptBuilder = exports.TaskInstruction = exports.SystemPrompt = exports.UserMessage = exports.Agent = void 0;
8
+ // Core Agent functionality
9
+ var agent_1 = require("./agent");
10
+ Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_1.Agent; } });
11
+ // Message and prompt builders
12
+ var usermessage_1 = require("./usermessage");
13
+ Object.defineProperty(exports, "UserMessage", { enumerable: true, get: function () { return usermessage_1.UserMessage; } });
14
+ var systemprompt_1 = require("./systemprompt");
15
+ Object.defineProperty(exports, "SystemPrompt", { enumerable: true, get: function () { return systemprompt_1.SystemPrompt; } });
16
+ var taskInstruction_1 = require("./taskInstruction");
17
+ Object.defineProperty(exports, "TaskInstruction", { enumerable: true, get: function () { return taskInstruction_1.TaskInstruction; } });
18
+ var promptbuilder_1 = require("./promptbuilder");
19
+ Object.defineProperty(exports, "InitialPromptBuilder", { enumerable: true, get: function () { return promptbuilder_1.InitialPromptBuilder; } });
20
+ var followupquestionbuilder_1 = require("./followupquestionbuilder");
21
+ Object.defineProperty(exports, "FollowUpPromptBuilder", { enumerable: true, get: function () { return followupquestionbuilder_1.FollowUpPromptBuilder; } });
22
+ var llmoutputhandler_1 = require("./llmoutputhandler");
23
+ Object.defineProperty(exports, "LLMOutputHandler", { enumerable: true, get: function () { return llmoutputhandler_1.LLMOutputHandler; } });