@codebolt/agent 1.1.0 → 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,598 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Main ComposableAgent implementation
4
+ * @description Core agent class that provides a composable API for creating and running agents
5
+ */
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ComposableAgent = void 0;
11
+ exports.createAgent = createAgent;
12
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
13
+ // Use all relevant CodeBolt APIs
14
+ const { chat, llm, mcp, fs } = codeboltjs_1.default;
15
+ const tool_1 = require("./tool");
16
+ // Import codeboltjs for accessing user message
17
+ // The user message is now automatically saved by codeboltjs.onMessage()
18
+ /**
19
+ * Main ComposableAgent class that provides a simple, composable API for creating agents
20
+ */
21
+ class ComposableAgent {
22
+ constructor(config) {
23
+ this.conversation = [];
24
+ this.config = {
25
+ maxTurns: 10,
26
+ ...config
27
+ };
28
+ // Merge user tools with default tools
29
+ this.tools = {
30
+ ...(0, tool_1.createDefaultTools)(),
31
+ ...(config.tools || {})
32
+ };
33
+ this.memory = config.memory;
34
+ // Initialize conversation with system message
35
+ this.conversation = [
36
+ {
37
+ role: 'system',
38
+ content: config.instructions,
39
+ timestamp: new Date().toISOString()
40
+ }
41
+ ];
42
+ }
43
+ /**
44
+ * Run the agent using globally saved user context from codeboltjs
45
+ * This is the main method to use within codebolt.onMessage()
46
+ *
47
+ * @param options - Execution options
48
+ * @returns Promise<ExecutionResult>
49
+ */
50
+ async run(options = {}) {
51
+ var _a;
52
+ // Get user message from codeboltjs (automatically saved by onMessage)
53
+ const userMessage = (_a = codeboltjs_1.default.userMessage) === null || _a === void 0 ? void 0 : _a.getCurrent();
54
+ if (!userMessage) {
55
+ throw new Error('No user message found. Make sure this is called within codebolt.onMessage()');
56
+ }
57
+ // Convert to CodeBoltMessage format
58
+ const codeboltMessage = {
59
+ userMessage: userMessage.userMessage,
60
+ mentionedFiles: [
61
+ ...(userMessage.mentionedFiles || []),
62
+ ...(userMessage.mentionedFullPaths || [])
63
+ ],
64
+ mentionedMCPs: userMessage.mentionedMCPs || [],
65
+ mentionedAgents: userMessage.mentionedAgents || [],
66
+ remixPrompt: userMessage.remixPrompt
67
+ };
68
+ return this.executeMessage(codeboltMessage, options);
69
+ }
70
+ /**
71
+ * Execute a task with the agent using a simple string message
72
+ *
73
+ * @param message - User message to process
74
+ * @param options - Execution options
75
+ * @returns Promise<ExecutionResult>
76
+ */
77
+ async execute(message, options = {}) {
78
+ // Convert string to CodeBoltMessage format
79
+ const codeboltMessage = {
80
+ userMessage: message,
81
+ mentionedFiles: [],
82
+ mentionedMCPs: [],
83
+ mentionedAgents: []
84
+ };
85
+ return this.executeMessage(codeboltMessage, options);
86
+ }
87
+ /**
88
+ * Execute a task with the agent using CodeBolt Message format
89
+ *
90
+ * @param message - CodeBolt message with enhanced features
91
+ * @param options - Execution options
92
+ * @returns Promise<ExecutionResult>
93
+ */
94
+ async executeMessage(message, options = {}) {
95
+ var _a, _b;
96
+ const { stream = false, callback } = options;
97
+ try {
98
+ // Process the CodeBolt message and enhance the agent
99
+ await this.processCodeBoltMessage(message);
100
+ // Create user message for conversation
101
+ let messageContent = message.userMessage;
102
+ // Add file content if processing enabled
103
+ if (((_a = this.config.processing) === null || _a === void 0 ? void 0 : _a.processMentionedFiles) && ((_b = message.mentionedFiles) === null || _b === void 0 ? void 0 : _b.length)) {
104
+ const fileContents = await this.processFiles(message.mentionedFiles);
105
+ if (fileContents.length > 0) {
106
+ messageContent += '\n\nReferenced files:\n' + fileContents.join('\n\n');
107
+ }
108
+ }
109
+ const userMessage = {
110
+ role: 'user',
111
+ content: messageContent,
112
+ timestamp: new Date().toISOString()
113
+ };
114
+ this.addMessage(userMessage);
115
+ let turnCount = 0;
116
+ let completed = false;
117
+ let lastAssistantMessage = '';
118
+ while (!completed && turnCount < (this.config.maxTurns || 10)) {
119
+ turnCount++;
120
+ if (stream && callback) {
121
+ await callback({
122
+ type: 'text',
123
+ content: `\n--- Turn ${turnCount} ---\n`
124
+ });
125
+ }
126
+ // Make LLM request
127
+ const response = await this.makeLLMRequest();
128
+ if (!response || !response.choices || response.choices.length === 0) {
129
+ throw new Error('No response from LLM');
130
+ }
131
+ const choice = response.choices[0];
132
+ const assistantMessage = choice.message;
133
+ if (!assistantMessage) {
134
+ throw new Error('No message in LLM response');
135
+ }
136
+ // Add assistant message to conversation
137
+ this.addMessage(assistantMessage);
138
+ // Store content for return
139
+ if (assistantMessage.content) {
140
+ lastAssistantMessage = Array.isArray(assistantMessage.content)
141
+ ? assistantMessage.content.map((c) => c.text || '').join('')
142
+ : assistantMessage.content;
143
+ }
144
+ // Send message to chat if it has content
145
+ if (lastAssistantMessage && !stream) {
146
+ await chat.sendMessage(lastAssistantMessage, {});
147
+ }
148
+ if (stream && callback && lastAssistantMessage) {
149
+ await callback({
150
+ type: 'text',
151
+ content: lastAssistantMessage
152
+ });
153
+ }
154
+ // Handle tool calls
155
+ if (assistantMessage.tool_calls && assistantMessage.tool_calls.length > 0) {
156
+ const toolResults = [];
157
+ for (const toolCall of assistantMessage.tool_calls) {
158
+ if (stream && callback) {
159
+ await callback({
160
+ type: 'tool_call',
161
+ content: `Calling tool: ${toolCall.function.name}`,
162
+ tool_call: toolCall
163
+ });
164
+ }
165
+ const result = await this.executeToolCall(toolCall);
166
+ toolResults.push(result);
167
+ if (stream && callback) {
168
+ await callback({
169
+ type: 'tool_result',
170
+ content: result.content,
171
+ tool_call: toolCall
172
+ });
173
+ }
174
+ // Check if task was completed
175
+ if (toolCall.function.name === 'attempt_completion') {
176
+ completed = true;
177
+ }
178
+ }
179
+ // Add tool results to conversation
180
+ toolResults.forEach(result => this.addMessage(result));
181
+ }
182
+ else {
183
+ // No tool calls, assume we need to continue or complete
184
+ const continueMessage = {
185
+ role: 'user',
186
+ content: 'If you have completed the task, use the attempt_completion tool. If you need more information, use the ask_followup_question tool. Otherwise, continue with the next step.',
187
+ timestamp: new Date().toISOString()
188
+ };
189
+ this.addMessage(continueMessage);
190
+ }
191
+ }
192
+ // Save conversation to memory if configured
193
+ if (this.memory) {
194
+ await this.saveConversation();
195
+ }
196
+ return {
197
+ success: completed || turnCount >= (this.config.maxTurns || 10),
198
+ message: lastAssistantMessage,
199
+ conversation: [...this.conversation],
200
+ metadata: {
201
+ turnCount,
202
+ completed,
203
+ toolsUsed: this.getUsedTools()
204
+ }
205
+ };
206
+ }
207
+ catch (error) {
208
+ return {
209
+ success: false,
210
+ error: error instanceof Error ? error.message : String(error),
211
+ conversation: [...this.conversation]
212
+ };
213
+ }
214
+ }
215
+ /**
216
+ * Add a message to the conversation
217
+ *
218
+ * @param message - Message to add
219
+ */
220
+ addMessage(message) {
221
+ this.conversation.push({
222
+ ...message,
223
+ timestamp: message.timestamp || new Date().toISOString()
224
+ });
225
+ }
226
+ /**
227
+ * Get conversation history
228
+ *
229
+ * @returns Array of messages
230
+ */
231
+ getConversation() {
232
+ return [...this.conversation];
233
+ }
234
+ /**
235
+ * Clear conversation history (keeps system message)
236
+ */
237
+ clearConversation() {
238
+ const systemMessage = this.conversation.find(msg => msg.role === 'system');
239
+ this.conversation = systemMessage ? [systemMessage] : [];
240
+ }
241
+ /**
242
+ * Save conversation to memory
243
+ */
244
+ async saveConversation() {
245
+ if (!this.memory)
246
+ return;
247
+ await this.memory.saveMessages(this.conversation);
248
+ }
249
+ /**
250
+ * Load conversation from memory
251
+ */
252
+ async loadConversation() {
253
+ if (!this.memory)
254
+ return;
255
+ const messages = await this.memory.loadMessages();
256
+ if (messages.length > 0) {
257
+ this.conversation = messages;
258
+ }
259
+ }
260
+ /**
261
+ * Make a request to the LLM
262
+ *
263
+ * @returns LLM response
264
+ */
265
+ async makeLLMRequest() {
266
+ try {
267
+ // Prepare messages for API
268
+ const apiMessages = this.conversation.map(msg => ({
269
+ role: msg.role,
270
+ content: msg.content,
271
+ tool_calls: msg.tool_calls,
272
+ tool_call_id: msg.tool_call_id
273
+ }));
274
+ // Prepare tools for API
275
+ const openAITools = (0, tool_1.toolsToOpenAIFunctions)(this.tools);
276
+ const createParams = {
277
+ full: true,
278
+ messages: apiMessages,
279
+ tools: openAITools,
280
+ tool_choice: 'auto',
281
+ llmrole: this.config.model // Use model name as llmrole for CodeBolt inference
282
+ };
283
+ // Use CodeBolt's LLM inference API - no custom logic needed
284
+ const { completion } = await llm.inference(createParams);
285
+ return completion;
286
+ }
287
+ catch (error) {
288
+ console.error('LLM request failed:', error);
289
+ throw error;
290
+ }
291
+ }
292
+ /**
293
+ * Execute a tool call
294
+ *
295
+ * @param toolCall - Tool call to execute
296
+ * @returns Tool result message
297
+ */
298
+ async executeToolCall(toolCall) {
299
+ try {
300
+ const toolName = toolCall.function.name;
301
+ // Parse arguments
302
+ let args;
303
+ try {
304
+ args = JSON.parse(toolCall.function.arguments);
305
+ }
306
+ catch (error) {
307
+ return {
308
+ role: 'tool',
309
+ tool_call_id: toolCall.id,
310
+ content: `Error: Invalid tool arguments: ${toolCall.function.arguments}`,
311
+ timestamp: new Date().toISOString()
312
+ };
313
+ }
314
+ // Check if this is a custom tool first
315
+ if (this.tools[toolName]) {
316
+ const result = await (0, tool_1.executeTool)(this.tools[toolName], args, this);
317
+ return {
318
+ role: 'tool',
319
+ tool_call_id: toolCall.id,
320
+ content: result.success
321
+ ? JSON.stringify(result.result)
322
+ : `Error: ${result.error}`,
323
+ timestamp: new Date().toISOString()
324
+ };
325
+ }
326
+ // Try to execute as MCP tool using CodeBolt API
327
+ try {
328
+ // Parse toolbox--toolName format or guess structure
329
+ let toolbox, actualToolName;
330
+ if (toolName.includes('--')) {
331
+ [toolbox, actualToolName] = toolName.split('--');
332
+ }
333
+ else if (toolName.includes('_')) {
334
+ // Handle tool_name format
335
+ const parts = toolName.split('_');
336
+ toolbox = parts[0];
337
+ actualToolName = parts.slice(1).join('_');
338
+ }
339
+ else {
340
+ // Assume single word tools belong to 'codebolt' toolbox
341
+ toolbox = 'codebolt';
342
+ actualToolName = toolName;
343
+ }
344
+ const mcpResult = await mcp.executeTool(toolbox, actualToolName, args);
345
+ return {
346
+ role: 'tool',
347
+ tool_call_id: toolCall.id,
348
+ content: JSON.stringify(mcpResult.data || mcpResult),
349
+ timestamp: new Date().toISOString()
350
+ };
351
+ }
352
+ catch (mcpError) {
353
+ // If MCP execution fails, return error
354
+ return {
355
+ role: 'tool',
356
+ tool_call_id: toolCall.id,
357
+ content: `Error: Tool '${toolName}' not found in custom tools or MCP toolboxes. ${mcpError.message}`,
358
+ timestamp: new Date().toISOString()
359
+ };
360
+ }
361
+ }
362
+ catch (error) {
363
+ return {
364
+ role: 'tool',
365
+ tool_call_id: toolCall.id,
366
+ content: `Error: ${error instanceof Error ? error.message : String(error)}`,
367
+ timestamp: new Date().toISOString()
368
+ };
369
+ }
370
+ }
371
+ /**
372
+ * Get list of tools that were used in the conversation
373
+ *
374
+ * @returns Array of tool names
375
+ */
376
+ getUsedTools() {
377
+ const usedTools = new Set();
378
+ for (const message of this.conversation) {
379
+ if (message.tool_calls) {
380
+ for (const toolCall of message.tool_calls) {
381
+ usedTools.add(toolCall.function.name);
382
+ }
383
+ }
384
+ }
385
+ return Array.from(usedTools);
386
+ }
387
+ /**
388
+ * Get available tools
389
+ *
390
+ * @returns Record of available tools
391
+ */
392
+ getTools() {
393
+ return { ...this.tools };
394
+ }
395
+ /**
396
+ * Add a tool to the agent
397
+ *
398
+ * @param name - Tool name
399
+ * @param tool - Tool instance
400
+ */
401
+ addTool(name, tool) {
402
+ this.tools[name] = tool;
403
+ }
404
+ /**
405
+ * Remove a tool from the agent
406
+ *
407
+ * @param name - Tool name
408
+ */
409
+ removeTool(name) {
410
+ delete this.tools[name];
411
+ }
412
+ /**
413
+ * Get execution context for tools
414
+ *
415
+ * @returns ExecutionContext
416
+ */
417
+ getExecutionContext() {
418
+ return {
419
+ messages: [...this.conversation],
420
+ tools: { ...this.tools },
421
+ config: { ...this.config }
422
+ };
423
+ }
424
+ /**
425
+ * Process CodeBolt message and enhance agent capabilities
426
+ *
427
+ * @param message - CodeBolt message to process
428
+ */
429
+ async processCodeBoltMessage(message) {
430
+ var _a, _b, _c, _d, _e, _f, _g;
431
+ const processing = this.config.processing || {};
432
+ const userConfig = ((_a = codeboltjs_1.default.userMessage) === null || _a === void 0 ? void 0 : _a.getProcessingConfig()) || {};
433
+ // Merge agent config with global user config from codeboltjs
434
+ const shouldProcessMCPs = (_c = (_b = processing.processMentionedMCPs) !== null && _b !== void 0 ? _b : userConfig.processMentionedMCPs) !== null && _c !== void 0 ? _c : false;
435
+ const shouldProcessRemix = (_e = (_d = processing.processRemixPrompt) !== null && _d !== void 0 ? _d : userConfig.processRemixPrompt) !== null && _e !== void 0 ? _e : false;
436
+ const shouldProcessAgents = (_g = (_f = processing.processMentionedAgents) !== null && _f !== void 0 ? _f : userConfig.processMentionedAgents) !== null && _g !== void 0 ? _g : false;
437
+ // Process remix prompt to enhance system instructions
438
+ if (shouldProcessRemix && message.remixPrompt) {
439
+ await this.processRemixPrompt(message.remixPrompt);
440
+ }
441
+ // Process mentioned MCPs and add as tools
442
+ if (shouldProcessMCPs && message.mentionedMCPs.length > 0) {
443
+ await this.processMCPs(message.mentionedMCPs);
444
+ }
445
+ // Process mentioned agents and add as sub-agent tools
446
+ if (shouldProcessAgents && message.mentionedAgents.length > 0) {
447
+ await this.processAgents(message.mentionedAgents);
448
+ }
449
+ }
450
+ /**
451
+ * Process remix prompt and enhance system instructions
452
+ *
453
+ * @param remixPrompt - Additional instructions to add to system prompt
454
+ */
455
+ async processRemixPrompt(remixPrompt) {
456
+ // Find the system message and enhance it
457
+ const systemMessageIndex = this.conversation.findIndex(msg => msg.role === 'system');
458
+ if (systemMessageIndex !== -1) {
459
+ const currentSystemMessage = this.conversation[systemMessageIndex];
460
+ const enhancedContent = `${currentSystemMessage.content}\n\n--- Enhanced Instructions ---\n${remixPrompt}`;
461
+ this.conversation[systemMessageIndex] = {
462
+ ...currentSystemMessage,
463
+ content: enhancedContent,
464
+ timestamp: new Date().toISOString()
465
+ };
466
+ }
467
+ }
468
+ /**
469
+ * Process mentioned MCP tools and add them to available tools
470
+ *
471
+ * @param mentionedMCPs - List of MCP tools to process
472
+ */
473
+ async processMCPs(mentionedMCPs) {
474
+ const processing = this.config.processing || {};
475
+ for (const mcp of mentionedMCPs) {
476
+ try {
477
+ let tool = null;
478
+ // Use custom processor if provided
479
+ if (processing.mcpToolProcessor) {
480
+ tool = await processing.mcpToolProcessor(mcp.toolbox, mcp.toolName);
481
+ }
482
+ else {
483
+ // Default MCP processing - create a generic tool
484
+ tool = this.createMCPTool(mcp.toolbox, mcp.toolName);
485
+ }
486
+ if (tool) {
487
+ this.tools[`${mcp.toolbox}--${mcp.toolName}`] = tool;
488
+ }
489
+ }
490
+ catch (error) {
491
+ console.warn(`Failed to process MCP tool ${mcp.toolbox}--${mcp.toolName}:`, error);
492
+ }
493
+ }
494
+ }
495
+ /**
496
+ * Create a generic MCP tool wrapper
497
+ *
498
+ * @param toolbox - MCP toolbox name
499
+ * @param toolName - MCP tool name
500
+ * @returns Tool instance
501
+ */
502
+ createMCPTool(toolbox, toolName) {
503
+ return {
504
+ id: `${toolbox}--${toolName}`,
505
+ description: `MCP tool ${toolName} from ${toolbox} toolbox`,
506
+ inputSchema: require('zod').record(require('zod').any()),
507
+ outputSchema: require('zod').any(),
508
+ validateInput: (input) => input,
509
+ validateOutput: (output) => output,
510
+ execute: async ({ context }) => {
511
+ // Use CodeBolt's MCP system to execute the tool
512
+ const { mcp } = codeboltjs_1.default;
513
+ const result = await mcp.executeTool(toolbox, toolName, context);
514
+ return result.data || result;
515
+ }
516
+ };
517
+ }
518
+ /**
519
+ * Process mentioned agents and add them as sub-agent tools
520
+ *
521
+ * @param mentionedAgents - List of agents to process
522
+ */
523
+ async processAgents(mentionedAgents) {
524
+ for (const agent of mentionedAgents) {
525
+ try {
526
+ const agentTool = this.createSubAgentTool(agent);
527
+ this.tools[`subagent--${agent.unique_id || agent.id}`] = agentTool;
528
+ }
529
+ catch (error) {
530
+ console.warn(`Failed to process sub-agent ${agent.unique_id || agent.id}:`, error);
531
+ }
532
+ }
533
+ }
534
+ /**
535
+ * Create a sub-agent tool wrapper
536
+ *
537
+ * @param agent - Agent information
538
+ * @returns Tool instance
539
+ */
540
+ createSubAgentTool(agent) {
541
+ return {
542
+ id: `subagent--${agent.unique_id || agent.id}`,
543
+ description: agent.longDescription || agent.description || `Sub-agent: ${agent.name}`,
544
+ inputSchema: require('zod').object({
545
+ task: require('zod').string().describe('The task to be executed by the sub-agent')
546
+ }),
547
+ outputSchema: require('zod').string(),
548
+ validateInput: (input) => input,
549
+ validateOutput: (output) => output,
550
+ execute: async ({ context }) => {
551
+ // Use CodeBolt's agent system to execute the sub-agent
552
+ const { agent: codeboltAgent } = codeboltjs_1.default;
553
+ const result = await codeboltAgent.startAgent(agent.unique_id || agent.id, context.task);
554
+ return result;
555
+ }
556
+ };
557
+ }
558
+ /**
559
+ * Process mentioned files and return their contents
560
+ *
561
+ * @param mentionedFiles - List of file paths
562
+ * @returns Array of file contents with headers
563
+ */
564
+ async processFiles(mentionedFiles) {
565
+ const processing = this.config.processing || {};
566
+ const fileContents = [];
567
+ for (const filePath of mentionedFiles) {
568
+ try {
569
+ let content;
570
+ if (processing.fileContentProcessor) {
571
+ content = await processing.fileContentProcessor(filePath);
572
+ }
573
+ else {
574
+ // Default file processing using CodeBolt's filesystem
575
+ const { fs } = codeboltjs_1.default;
576
+ const result = await fs.readFile(filePath);
577
+ content = result.data || '';
578
+ }
579
+ fileContents.push(`--- File: ${filePath} ---\n${content}`);
580
+ }
581
+ catch (error) {
582
+ console.warn(`Failed to read file ${filePath}:`, error);
583
+ fileContents.push(`--- File: ${filePath} ---\n[Error reading file: ${error}]`);
584
+ }
585
+ }
586
+ return fileContents;
587
+ }
588
+ }
589
+ exports.ComposableAgent = ComposableAgent;
590
+ /**
591
+ * Create a new ComposableAgent instance
592
+ *
593
+ * @param config - Agent configuration
594
+ * @returns ComposableAgent instance
595
+ */
596
+ function createAgent(config) {
597
+ return new ComposableAgent(config);
598
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @fileoverview CodeBolt Backend Storage Provider for Composable Agent Pattern
3
+ * @description Uses CodeBolt's state and memory functions instead of SQLite for storage
4
+ */
5
+ import type { StorageProvider } from './types';
6
+ /**
7
+ * Storage provider that uses CodeBolt's agent state backend
8
+ * Data is persisted in the CodeBolt application's agent state
9
+ */
10
+ export declare class CodeBoltAgentStore implements StorageProvider {
11
+ private prefix;
12
+ constructor(prefix?: string);
13
+ private getFullKey;
14
+ get(key: string): Promise<any>;
15
+ set(key: string, value: any): Promise<void>;
16
+ delete(key: string): Promise<void>;
17
+ keys(): Promise<string[]>;
18
+ clear(): Promise<void>;
19
+ }
20
+ /**
21
+ * Storage provider that uses CodeBolt's in-memory database (dbmemory)
22
+ * Data is persisted in the CodeBolt application's memory database
23
+ */
24
+ export declare class CodeBoltMemoryStore implements StorageProvider {
25
+ private prefix;
26
+ constructor(prefix?: string);
27
+ private getFullKey;
28
+ get(key: string): Promise<any>;
29
+ set(key: string, value: any): Promise<void>;
30
+ delete(key: string): Promise<void>;
31
+ keys(): Promise<string[]>;
32
+ clear(): Promise<void>;
33
+ /**
34
+ * Override set to maintain key index
35
+ */
36
+ setWithIndex(key: string, value: any): Promise<void>;
37
+ }
38
+ /**
39
+ * Storage provider that uses CodeBolt's project state backend
40
+ * Data is persisted in the CodeBolt application's project state
41
+ */
42
+ export declare class CodeBoltProjectStore implements StorageProvider {
43
+ private prefix;
44
+ constructor(prefix?: string);
45
+ private getFullKey;
46
+ get(key: string): Promise<any>;
47
+ set(key: string, value: any): Promise<void>;
48
+ delete(key: string): Promise<void>;
49
+ keys(): Promise<string[]>;
50
+ clear(): Promise<void>;
51
+ }
52
+ /**
53
+ * Configuration for CodeBolt storage providers
54
+ */
55
+ export interface CodeBoltStoreConfig {
56
+ /** Storage type to use */
57
+ type: 'agent' | 'memory' | 'project';
58
+ /** Prefix for storage keys to avoid conflicts */
59
+ prefix?: string;
60
+ }
61
+ /**
62
+ * Factory function to create appropriate CodeBolt storage provider
63
+ *
64
+ * @param config - Storage configuration
65
+ * @returns StorageProvider instance
66
+ */
67
+ export declare function createCodeBoltStore(config: CodeBoltStoreConfig): StorageProvider;