@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,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TokenManagementProcessor = void 0;
4
+ const processor_1 = require("../../processor");
5
+ class TokenManagementProcessor extends processor_1.BaseProcessor {
6
+ constructor(options = {}) {
7
+ super();
8
+ // Token cache for performance
9
+ this.tokenCache = new Map();
10
+ this.maxTokens = options.maxTokens || 128000;
11
+ this.warningThreshold = options.warningThreshold || 0.8;
12
+ this.enableCompression = options.enableCompression !== false;
13
+ this.compressionThreshold = options.compressionThreshold || 0.7;
14
+ this.enableCaching = options.enableCaching !== false;
15
+ this.modelTokenLimits = options.modelTokenLimits || {
16
+ 'gemini-pro': 128000,
17
+ 'gemini-pro-vision': 128000,
18
+ 'gemini-flash': 1000000,
19
+ 'gpt-4': 128000,
20
+ 'gpt-3.5-turbo': 16385,
21
+ 'claude-3': 200000
22
+ };
23
+ }
24
+ async processInput(input) {
25
+ var _a, _b;
26
+ const { message, context } = input;
27
+ try {
28
+ // Calculate current token usage
29
+ const tokenUsage = await this.calculateTokenUsage(message);
30
+ // Get model-specific limit if available
31
+ const modelName = ((_a = context === null || context === void 0 ? void 0 : context.llmconfig) === null || _a === void 0 ? void 0 : _a.model) || ((_b = context === null || context === void 0 ? void 0 : context.llmconfig) === null || _b === void 0 ? void 0 : _b.llmname) || 'gemini-pro';
32
+ const modelLimit = this.modelTokenLimits[modelName] || this.maxTokens;
33
+ const results = [];
34
+ // Add token usage information
35
+ results.push(this.createEvent('TokenUsageCalculated', {
36
+ usage: tokenUsage,
37
+ modelLimit,
38
+ utilizationPercentage: (tokenUsage.total / modelLimit) * 100
39
+ }));
40
+ // Check if we're approaching token limits
41
+ if (tokenUsage.total > modelLimit * this.warningThreshold) {
42
+ results.push(this.createEvent('TokenLimitWarning', {
43
+ usage: tokenUsage,
44
+ limit: modelLimit,
45
+ warningThreshold: this.warningThreshold,
46
+ recommendation: this.enableCompression ? 'compression_suggested' : 'trim_history'
47
+ }));
48
+ }
49
+ // Check if we need compression
50
+ if (this.enableCompression && tokenUsage.total > modelLimit * this.compressionThreshold) {
51
+ results.push(this.createEvent('CompressionTriggered', {
52
+ usage: tokenUsage,
53
+ limit: modelLimit,
54
+ compressionThreshold: this.compressionThreshold
55
+ }));
56
+ }
57
+ // Check if we're over the limit
58
+ if (tokenUsage.total > modelLimit) {
59
+ results.push(this.createEvent('TokenLimitExceeded', {
60
+ usage: tokenUsage,
61
+ limit: modelLimit,
62
+ excessTokens: tokenUsage.total - modelLimit,
63
+ action: 'truncation_required'
64
+ }));
65
+ }
66
+ return results;
67
+ }
68
+ catch (error) {
69
+ console.error('[TokenManagement] Error calculating tokens:', error);
70
+ return [this.createEvent('TokenCalculationError', {
71
+ error: error instanceof Error ? error.message : String(error),
72
+ fallbackEstimate: this.estimateTokens(message)
73
+ })];
74
+ }
75
+ }
76
+ async calculateTokenUsage(message) {
77
+ try {
78
+ // Try to use CodeBolt's LLM service for accurate token counting
79
+ const messagesText = this.extractTextFromMessage(message);
80
+ // Check cache first
81
+ if (this.enableCaching) {
82
+ const cacheKey = this.getCacheKey(messagesText);
83
+ const cachedCount = this.tokenCache.get(cacheKey);
84
+ if (cachedCount !== undefined) {
85
+ return {
86
+ input: cachedCount,
87
+ output: 0,
88
+ cached: cachedCount,
89
+ total: cachedCount
90
+ };
91
+ }
92
+ }
93
+ // For now, use estimation since we don't have direct access to token counting
94
+ // In a real implementation, you would use codebolt.llm.countTokens() or similar
95
+ const estimatedTokens = this.estimateTokens(message);
96
+ // Cache the result
97
+ if (this.enableCaching) {
98
+ const cacheKey = this.getCacheKey(messagesText);
99
+ this.tokenCache.set(cacheKey, estimatedTokens);
100
+ // Limit cache size
101
+ if (this.tokenCache.size > 1000) {
102
+ const firstKey = this.tokenCache.keys().next().value;
103
+ if (firstKey !== undefined) {
104
+ this.tokenCache.delete(firstKey);
105
+ }
106
+ }
107
+ }
108
+ return {
109
+ input: estimatedTokens,
110
+ output: 0,
111
+ cached: 0,
112
+ total: estimatedTokens,
113
+ estimated: true
114
+ };
115
+ }
116
+ catch (error) {
117
+ console.error('[TokenManagement] Token calculation failed:', error);
118
+ const fallbackEstimate = this.estimateTokens(message);
119
+ return {
120
+ input: fallbackEstimate,
121
+ output: 0,
122
+ cached: 0,
123
+ total: fallbackEstimate,
124
+ estimated: true
125
+ };
126
+ }
127
+ }
128
+ extractTextFromMessage(message) {
129
+ if (typeof message === 'string') {
130
+ return message;
131
+ }
132
+ if ((message === null || message === void 0 ? void 0 : message.messages) && Array.isArray(message.messages)) {
133
+ return message.messages
134
+ .map((msg) => {
135
+ if (typeof msg.content === 'string') {
136
+ return msg.content;
137
+ }
138
+ if (Array.isArray(msg.content)) {
139
+ return msg.content
140
+ .filter((part) => part.type === 'text' || typeof part === 'string')
141
+ .map((part) => typeof part === 'string' ? part : part.text)
142
+ .join(' ');
143
+ }
144
+ return JSON.stringify(msg.content);
145
+ })
146
+ .join('\n');
147
+ }
148
+ return JSON.stringify(message);
149
+ }
150
+ estimateTokens(message) {
151
+ const text = this.extractTextFromMessage(message);
152
+ // Rough estimation: ~4 characters per token for English text
153
+ // This is a simplified estimation - real tokenizers are more complex
154
+ const charCount = text.length;
155
+ const wordCount = text.split(/\s+/).length;
156
+ // Use a combination of character and word count for better estimation
157
+ const charBasedEstimate = Math.ceil(charCount / 4);
158
+ const wordBasedEstimate = Math.ceil(wordCount * 1.3); // Account for subword tokens
159
+ // Use the higher estimate to be conservative
160
+ return Math.max(charBasedEstimate, wordBasedEstimate);
161
+ }
162
+ getCacheKey(text) {
163
+ // Create a hash-like key for caching
164
+ return text.length.toString() + '_' + text.slice(0, 100).replace(/\s+/g, '');
165
+ }
166
+ getTokenUsageStats() {
167
+ // In a real implementation, you would track these statistics
168
+ return {
169
+ cacheSize: this.tokenCache.size,
170
+ cacheHitRate: 0, // Would track cache hits vs misses
171
+ averageTokensPerMessage: 0 // Would track running average
172
+ };
173
+ }
174
+ clearCache() {
175
+ this.tokenCache.clear();
176
+ }
177
+ }
178
+ exports.TokenManagementProcessor = TokenManagementProcessor;
@@ -0,0 +1,43 @@
1
+ import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
+ export interface ToolExecutionInfo {
3
+ toolCall: any;
4
+ toolName: string;
5
+ toolbox: string;
6
+ parameters: Record<string, any>;
7
+ needsConfirmation: boolean;
8
+ confirmed?: boolean;
9
+ }
10
+ export interface ToolExecutionResult {
11
+ toolCallId: string;
12
+ result: any;
13
+ error?: string;
14
+ success: boolean;
15
+ executionTime: number;
16
+ }
17
+ export interface ToolExecutionProcessorOptions {
18
+ enableToolConfirmation?: boolean;
19
+ maxRetries?: number;
20
+ retryDelay?: number;
21
+ enableLogging?: boolean;
22
+ }
23
+ export declare class ToolExecutionProcessor extends BaseProcessor {
24
+ private readonly enableToolConfirmation;
25
+ private readonly maxRetries;
26
+ private readonly retryDelay;
27
+ private readonly enableLogging;
28
+ private executedTools;
29
+ constructor(options?: ToolExecutionProcessorOptions);
30
+ processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
31
+ private extractToolCalls;
32
+ private processToolCall;
33
+ private shouldConfirmTool;
34
+ private executeTool;
35
+ private calculateSuccessRate;
36
+ confirmToolExecution(toolCallId: string, confirmed: boolean): Promise<void>;
37
+ getToolExecutionHistory(): ToolExecutionResult[];
38
+ clearToolHistory(): void;
39
+ setMaxRetries(maxRetries: number): void;
40
+ setRetryDelay(delay: number): void;
41
+ enableLoggingForSession(): void;
42
+ disableLoggingForSession(): void;
43
+ }
@@ -0,0 +1,207 @@
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.ToolExecutionProcessor = void 0;
7
+ const processor_1 = require("../../processor");
8
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
+ class ToolExecutionProcessor extends processor_1.BaseProcessor {
10
+ constructor(options = {}) {
11
+ super(options);
12
+ this.executedTools = new Map();
13
+ this.enableToolConfirmation = options.enableToolConfirmation !== false;
14
+ this.maxRetries = options.maxRetries || 3;
15
+ this.retryDelay = options.retryDelay || 1000;
16
+ this.enableLogging = options.enableLogging !== false;
17
+ }
18
+ async processInput(input) {
19
+ try {
20
+ const { message, context } = input;
21
+ // Check if message contains tool calls
22
+ const toolCalls = this.extractToolCalls(message);
23
+ if (toolCalls.length === 0) {
24
+ return [this.createEvent('NoToolCalls', {
25
+ reason: 'No tool calls found in message'
26
+ })];
27
+ }
28
+ const events = [
29
+ this.createEvent('ToolCallsDetected', {
30
+ count: toolCalls.length,
31
+ tools: toolCalls.map(tc => tc.function.name)
32
+ })
33
+ ];
34
+ // Process each tool call
35
+ for (const toolCall of toolCalls) {
36
+ const executionInfo = await this.processToolCall(toolCall, context);
37
+ if (executionInfo.needsConfirmation) {
38
+ events.push(this.createEvent('ToolConfirmationRequired', executionInfo));
39
+ }
40
+ else {
41
+ const result = await this.executeTool(executionInfo);
42
+ events.push(this.createEvent('ToolExecuted', result));
43
+ }
44
+ }
45
+ // Add summary event
46
+ events.push(this.createEvent('ToolExecutionSummary', {
47
+ totalTools: toolCalls.length,
48
+ executedTools: Array.from(this.executedTools.values()),
49
+ successRate: this.calculateSuccessRate()
50
+ }));
51
+ return events;
52
+ }
53
+ catch (error) {
54
+ console.error('Error in ToolExecutionProcessor:', error);
55
+ return [this.createEvent('ToolExecutionError', {
56
+ error: error instanceof Error ? error.message : String(error)
57
+ })];
58
+ }
59
+ }
60
+ extractToolCalls(message) {
61
+ const toolCalls = [];
62
+ message.messages.forEach((msg) => {
63
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
64
+ toolCalls.push(...msg.tool_calls);
65
+ }
66
+ });
67
+ return toolCalls;
68
+ }
69
+ async processToolCall(toolCall, context) {
70
+ const [toolbox, toolName] = toolCall.function.name.split('--');
71
+ if (!toolbox || !toolName) {
72
+ throw new Error(`Invalid tool name format: ${toolCall.function.name}`);
73
+ }
74
+ // Parse tool arguments
75
+ let parameters = {};
76
+ try {
77
+ parameters = typeof toolCall.function.arguments === 'string'
78
+ ? JSON.parse(toolCall.function.arguments)
79
+ : toolCall.function.arguments;
80
+ }
81
+ catch (error) {
82
+ console.warn(`Failed to parse tool arguments for ${toolCall.function.name}:`, error);
83
+ }
84
+ // Check if tool needs confirmation
85
+ const needsConfirmation = this.shouldConfirmTool(toolCall, parameters);
86
+ return {
87
+ toolCall,
88
+ toolName,
89
+ toolbox,
90
+ parameters,
91
+ needsConfirmation
92
+ };
93
+ }
94
+ shouldConfirmTool(toolCall, parameters) {
95
+ // Check for dangerous operations
96
+ const dangerousOperations = [
97
+ 'delete', 'remove', 'drop', 'destroy', 'format', 'wipe',
98
+ 'shutdown', 'restart', 'kill', 'terminate'
99
+ ];
100
+ const toolName = toolCall.function.name.toLowerCase();
101
+ const hasDangerousOperation = dangerousOperations.some(op => toolName.includes(op));
102
+ // Check for file system operations with important paths
103
+ if (parameters.filePath || parameters.path) {
104
+ const path = (parameters.filePath || parameters.path || '').toLowerCase();
105
+ const importantPaths = ['/', 'c:', 'system', 'windows', 'etc', 'usr'];
106
+ const hasImportantPath = importantPaths.some(ip => path.includes(ip));
107
+ if (hasImportantPath) {
108
+ return true;
109
+ }
110
+ }
111
+ // Check for network operations
112
+ if (parameters.url || parameters.host || parameters.port) {
113
+ return true;
114
+ }
115
+ return hasDangerousOperation;
116
+ }
117
+ async executeTool(executionInfo) {
118
+ const startTime = Date.now();
119
+ const { toolCall, toolbox, toolName, parameters } = executionInfo;
120
+ try {
121
+ // Execute tool using CodeBolt's MCP
122
+ const { data } = await codeboltjs_1.default.mcp.executeTool(toolbox, toolName, parameters);
123
+ // Data comes as [failure: boolean, content: string] from CodeBolt MCP
124
+ let resultData;
125
+ let success = true;
126
+ if (Array.isArray(data) && data.length >= 2) {
127
+ const [failure, content] = data;
128
+ if (failure) {
129
+ success = false;
130
+ resultData = content; // Content is error message on failure
131
+ }
132
+ else {
133
+ resultData = content; // Content is result on success
134
+ }
135
+ }
136
+ else {
137
+ // Fallback for unexpected data format
138
+ console.warn(`[Tool] Unexpected data format from ${toolCall.function.name}:`, data);
139
+ resultData = data;
140
+ }
141
+ const executionResult = {
142
+ toolCallId: toolCall.id,
143
+ result: resultData,
144
+ success: success,
145
+ executionTime: Date.now() - startTime,
146
+ error: success ? undefined : String(resultData)
147
+ };
148
+ // Store result
149
+ this.executedTools.set(toolCall.id, executionResult);
150
+ // Log execution if enabled
151
+ if (this.enableLogging) {
152
+ console.log(`[Tool] Successfully executed ${toolbox}--${toolName} in ${executionResult.executionTime}ms`);
153
+ }
154
+ return executionResult;
155
+ }
156
+ catch (error) {
157
+ const executionResult = {
158
+ toolCallId: toolCall.id,
159
+ result: null,
160
+ error: error instanceof Error ? error.message : String(error),
161
+ success: false,
162
+ executionTime: Date.now() - startTime
163
+ };
164
+ // Store result
165
+ this.executedTools.set(toolCall.id, executionResult);
166
+ // Log error if enabled
167
+ if (this.enableLogging) {
168
+ console.error(`[Tool] Failed to execute ${toolbox}--${toolName}:`, error);
169
+ }
170
+ return executionResult;
171
+ }
172
+ }
173
+ calculateSuccessRate() {
174
+ if (this.executedTools.size === 0)
175
+ return 0;
176
+ const successfulTools = Array.from(this.executedTools.values())
177
+ .filter(result => result.success).length;
178
+ return (successfulTools / this.executedTools.size) * 100;
179
+ }
180
+ // Public methods for external control
181
+ async confirmToolExecution(toolCallId, confirmed) {
182
+ // This method can be used to track confirmation status in the future
183
+ // For now, we'll just log the confirmation
184
+ if (this.enableLogging) {
185
+ console.log(`[ToolExecutor] Tool ${toolCallId} confirmation: ${confirmed}`);
186
+ }
187
+ }
188
+ getToolExecutionHistory() {
189
+ return Array.from(this.executedTools.values());
190
+ }
191
+ clearToolHistory() {
192
+ this.executedTools.clear();
193
+ }
194
+ setMaxRetries(maxRetries) {
195
+ this.maxRetries = Math.max(1, maxRetries);
196
+ }
197
+ setRetryDelay(delay) {
198
+ this.retryDelay = Math.max(100, delay);
199
+ }
200
+ enableLoggingForSession() {
201
+ this.enableLogging = true;
202
+ }
203
+ disableLoggingForSession() {
204
+ this.enableLogging = false;
205
+ }
206
+ }
207
+ exports.ToolExecutionProcessor = ToolExecutionProcessor;
@@ -0,0 +1,26 @@
1
+ import { BaseTool } from '../../processor';
2
+ export declare class FileReadTool extends BaseTool {
3
+ constructor();
4
+ execute(params: any, abortSignal?: AbortSignal): Promise<string>;
5
+ protected validateParameters(params: any): boolean;
6
+ }
7
+ export declare class FileWriteTool extends BaseTool {
8
+ constructor();
9
+ execute(params: any, abortSignal?: AbortSignal): Promise<string>;
10
+ protected validateParameters(params: any): boolean;
11
+ }
12
+ export declare class FileDeleteTool extends BaseTool {
13
+ constructor();
14
+ execute(params: any, abortSignal?: AbortSignal): Promise<string>;
15
+ protected validateParameters(params: any): boolean;
16
+ }
17
+ export declare class FileMoveTool extends BaseTool {
18
+ constructor();
19
+ execute(params: any, abortSignal?: AbortSignal): Promise<string>;
20
+ protected validateParameters(params: any): boolean;
21
+ }
22
+ export declare class FileCopyTool extends BaseTool {
23
+ constructor();
24
+ execute(params: any, abortSignal?: AbortSignal): Promise<string>;
25
+ protected validateParameters(params: any): boolean;
26
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FileCopyTool = exports.FileMoveTool = exports.FileDeleteTool = exports.FileWriteTool = exports.FileReadTool = void 0;
37
+ const processor_1 = require("../../processor");
38
+ const fs = __importStar(require("fs/promises"));
39
+ const path = __importStar(require("path"));
40
+ class FileReadTool extends processor_1.BaseTool {
41
+ constructor() {
42
+ super('FileRead', 'Read content from a file', {
43
+ filePath: { type: 'string', required: true, description: 'Path to the file to read' }
44
+ });
45
+ }
46
+ async execute(params, abortSignal) {
47
+ await this.checkAbortSignal(abortSignal);
48
+ if (!this.validateParameters(params)) {
49
+ throw new Error('Invalid parameters: filePath is required');
50
+ }
51
+ const { filePath } = params;
52
+ const content = await fs.readFile(filePath, 'utf-8');
53
+ return content;
54
+ }
55
+ validateParameters(params) {
56
+ return params && typeof params.filePath === 'string' && params.filePath.trim() !== '';
57
+ }
58
+ }
59
+ exports.FileReadTool = FileReadTool;
60
+ class FileWriteTool extends processor_1.BaseTool {
61
+ constructor() {
62
+ super('FileWrite', 'Write content to a file', {
63
+ filePath: { type: 'string', required: true, description: 'Path to the file to write' },
64
+ content: { type: 'string', required: true, description: 'Content to write to the file' }
65
+ });
66
+ }
67
+ async execute(params, abortSignal) {
68
+ await this.checkAbortSignal(abortSignal);
69
+ if (!this.validateParameters(params)) {
70
+ throw new Error('Invalid parameters: filePath and content are required');
71
+ }
72
+ const { filePath, content } = params;
73
+ // Ensure directory exists
74
+ const dir = path.dirname(filePath);
75
+ await fs.mkdir(dir, { recursive: true });
76
+ await fs.writeFile(filePath, content, 'utf-8');
77
+ return `Successfully wrote ${content.length} characters to ${filePath}`;
78
+ }
79
+ validateParameters(params) {
80
+ return params &&
81
+ typeof params.filePath === 'string' &&
82
+ params.filePath.trim() !== '' &&
83
+ typeof params.content === 'string';
84
+ }
85
+ }
86
+ exports.FileWriteTool = FileWriteTool;
87
+ class FileDeleteTool extends processor_1.BaseTool {
88
+ constructor() {
89
+ super('FileDelete', 'Delete a file', {
90
+ filePath: { type: 'string', required: true, description: 'Path to the file to delete' }
91
+ });
92
+ }
93
+ async execute(params, abortSignal) {
94
+ await this.checkAbortSignal(abortSignal);
95
+ if (!this.validateParameters(params)) {
96
+ throw new Error('Invalid parameters: filePath is required');
97
+ }
98
+ const { filePath } = params;
99
+ await fs.unlink(filePath);
100
+ return `Successfully deleted ${filePath}`;
101
+ }
102
+ validateParameters(params) {
103
+ return params && typeof params.filePath === 'string' && params.filePath.trim() !== '';
104
+ }
105
+ }
106
+ exports.FileDeleteTool = FileDeleteTool;
107
+ class FileMoveTool extends processor_1.BaseTool {
108
+ constructor() {
109
+ super('FileMove', 'Move a file from one location to another', {
110
+ sourcePath: { type: 'string', required: true, description: 'Source file path' },
111
+ destinationPath: { type: 'string', required: true, description: 'Destination file path' }
112
+ });
113
+ }
114
+ async execute(params, abortSignal) {
115
+ await this.checkAbortSignal(abortSignal);
116
+ if (!this.validateParameters(params)) {
117
+ throw new Error('Invalid parameters: sourcePath and destinationPath are required');
118
+ }
119
+ const { sourcePath, destinationPath } = params;
120
+ // Ensure destination directory exists
121
+ const dir = path.dirname(destinationPath);
122
+ await fs.mkdir(dir, { recursive: true });
123
+ await fs.rename(sourcePath, destinationPath);
124
+ return `Successfully moved ${sourcePath} to ${destinationPath}`;
125
+ }
126
+ validateParameters(params) {
127
+ return params &&
128
+ typeof params.sourcePath === 'string' &&
129
+ params.sourcePath.trim() !== '' &&
130
+ typeof params.destinationPath === 'string' &&
131
+ params.destinationPath.trim() !== '';
132
+ }
133
+ }
134
+ exports.FileMoveTool = FileMoveTool;
135
+ class FileCopyTool extends processor_1.BaseTool {
136
+ constructor() {
137
+ super('FileCopy', 'Copy a file from one location to another', {
138
+ sourcePath: { type: 'string', required: true, description: 'Source file path' },
139
+ destinationPath: { type: 'string', required: true, description: 'Destination file path' }
140
+ });
141
+ }
142
+ async execute(params, abortSignal) {
143
+ await this.checkAbortSignal(abortSignal);
144
+ if (!this.validateParameters(params)) {
145
+ throw new Error('Invalid parameters: sourcePath and destinationPath are required');
146
+ }
147
+ const { sourcePath, destinationPath } = params;
148
+ // Ensure destination directory exists
149
+ const dir = path.dirname(destinationPath);
150
+ await fs.mkdir(dir, { recursive: true });
151
+ await fs.copyFile(sourcePath, destinationPath);
152
+ return `Successfully copied ${sourcePath} to ${destinationPath}`;
153
+ }
154
+ validateParameters(params) {
155
+ return params &&
156
+ typeof params.sourcePath === 'string' &&
157
+ params.sourcePath.trim() !== '' &&
158
+ typeof params.destinationPath === 'string' &&
159
+ params.destinationPath.trim() !== '';
160
+ }
161
+ }
162
+ exports.FileCopyTool = FileCopyTool;
@@ -0,0 +1,4 @@
1
+ import { ProcessedMessage } from "@codebolt/types/agent";
2
+ export declare const mergeMessages: (existing: ProcessedMessage, additional: ProcessedMessage) => ProcessedMessage;
3
+ export declare const addSystemMessage: (message: ProcessedMessage, systemContent: string) => ProcessedMessage;
4
+ export declare const addUserContext: (message: ProcessedMessage, contextKey: string, contextValue: unknown) => ProcessedMessage;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addUserContext = exports.addSystemMessage = exports.mergeMessages = void 0;
4
+ // Helper method to merge messages
5
+ const mergeMessages = (existing, additional) => {
6
+ return {
7
+ message: {
8
+ ...existing.message,
9
+ ...additional.message,
10
+ messages: [...existing.message.messages, ...additional.message.messages],
11
+ tools: additional.message.tools
12
+ },
13
+ metadata: {
14
+ ...existing.metadata,
15
+ ...additional.metadata,
16
+ merged: true,
17
+ mergedAt: new Date().toISOString()
18
+ }
19
+ };
20
+ };
21
+ exports.mergeMessages = mergeMessages;
22
+ // Helper method to add system message
23
+ const addSystemMessage = (message, systemContent) => {
24
+ const systemMessage = {
25
+ role: 'system',
26
+ content: systemContent
27
+ };
28
+ return {
29
+ message: {
30
+ ...message.message,
31
+ messages: [systemMessage, ...message.message.messages]
32
+ },
33
+ metadata: {
34
+ ...message.metadata,
35
+ systemMessageAdded: true
36
+ }
37
+ };
38
+ };
39
+ exports.addSystemMessage = addSystemMessage;
40
+ // Helper method to add user context
41
+ const addUserContext = (message, contextKey, contextValue) => {
42
+ const contextString = typeof contextValue === 'string' ? contextValue : JSON.stringify(contextValue);
43
+ const contextMessage = {
44
+ role: 'user',
45
+ content: `Context (${contextKey}): ${contextString}`
46
+ };
47
+ return {
48
+ message: {
49
+ ...message.message,
50
+ messages: [...message.message.messages, contextMessage]
51
+ },
52
+ metadata: {
53
+ ...message.metadata,
54
+ contextAdded: contextKey
55
+ }
56
+ };
57
+ };
58
+ exports.addUserContext = addUserContext;