@codebolt/agent 5.0.8 → 5.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/unified/base/responseExecutor.js +10 -6
  2. package/package.json +5 -5
  3. package/dist/agent.d.ts +0 -86
  4. package/dist/agent.js +0 -324
  5. package/dist/builderpattern/agent.d.ts +0 -86
  6. package/dist/builderpattern/agent.js +0 -324
  7. package/dist/builderpattern/followupquestionbuilder.d.ts +0 -75
  8. package/dist/builderpattern/followupquestionbuilder.js +0 -197
  9. package/dist/builderpattern/index.d.ts +0 -14
  10. package/dist/builderpattern/index.js +0 -23
  11. package/dist/builderpattern/llmoutputhandler.d.ts +0 -102
  12. package/dist/builderpattern/llmoutputhandler.js +0 -452
  13. package/dist/builderpattern/promptbuilder.d.ts +0 -382
  14. package/dist/builderpattern/promptbuilder.js +0 -805
  15. package/dist/builderpattern/systemprompt.d.ts +0 -20
  16. package/dist/builderpattern/systemprompt.js +0 -48
  17. package/dist/builderpattern/taskInstruction.d.ts +0 -37
  18. package/dist/builderpattern/taskInstruction.js +0 -57
  19. package/dist/builderpattern/usermessage.d.ts +0 -70
  20. package/dist/builderpattern/usermessage.js +0 -123
  21. package/dist/composablepattern/agent.d.ts +0 -169
  22. package/dist/composablepattern/agent.js +0 -598
  23. package/dist/composablepattern/codebolt-storage.d.ts +0 -67
  24. package/dist/composablepattern/codebolt-storage.js +0 -320
  25. package/dist/composablepattern/document.d.ts +0 -149
  26. package/dist/composablepattern/document.js +0 -405
  27. package/dist/composablepattern/examples/codebolt-integration-example.d.ts +0 -12
  28. package/dist/composablepattern/examples/codebolt-integration-example.js +0 -218
  29. package/dist/composablepattern/examples/codebolt-storage-example.d.ts +0 -40
  30. package/dist/composablepattern/examples/codebolt-storage-example.js +0 -223
  31. package/dist/composablepattern/examples/custom-steps-example.d.ts +0 -20
  32. package/dist/composablepattern/examples/custom-steps-example.js +0 -455
  33. package/dist/composablepattern/examples/document-agent.d.ts +0 -17
  34. package/dist/composablepattern/examples/document-agent.js +0 -107
  35. package/dist/composablepattern/examples/simple-codebolt-integration.d.ts +0 -8
  36. package/dist/composablepattern/examples/simple-codebolt-integration.js +0 -164
  37. package/dist/composablepattern/examples/weather-agent.d.ts +0 -18
  38. package/dist/composablepattern/examples/weather-agent.js +0 -86
  39. package/dist/composablepattern/examples/workflow-example.d.ts +0 -12
  40. package/dist/composablepattern/examples/workflow-example.js +0 -463
  41. package/dist/composablepattern/index.d.ts +0 -63
  42. package/dist/composablepattern/index.js +0 -115
  43. package/dist/composablepattern/memory.d.ts +0 -89
  44. package/dist/composablepattern/memory.js +0 -141
  45. package/dist/composablepattern/tool.d.ts +0 -84
  46. package/dist/composablepattern/tool.js +0 -260
  47. package/dist/composablepattern/types.d.ts +0 -194
  48. package/dist/composablepattern/types.js +0 -6
  49. package/dist/composablepattern/user-context.d.ts +0 -214
  50. package/dist/composablepattern/user-context.js +0 -275
  51. package/dist/composablepattern/workflow.d.ts +0 -388
  52. package/dist/composablepattern/workflow.js +0 -562
  53. package/dist/followupquestionbuilder.d.ts +0 -75
  54. package/dist/followupquestionbuilder.js +0 -197
  55. package/dist/index.d.ts +0 -14
  56. package/dist/index.js +0 -23
  57. package/dist/llmoutputhandler.d.ts +0 -102
  58. package/dist/llmoutputhandler.js +0 -452
  59. package/dist/processor/agent/agentStep.d.ts +0 -49
  60. package/dist/processor/agent/agentStep.js +0 -241
  61. package/dist/processor/agent/toolExecutor.d.ts +0 -19
  62. package/dist/processor/agent/toolExecutor.js +0 -90
  63. package/dist/processor/index.d.ts +0 -7
  64. package/dist/processor/index.js +0 -36
  65. package/dist/processor/messageModifiers/baseMessageModifier.d.ts +0 -20
  66. package/dist/processor/messageModifiers/baseMessageModifier.js +0 -55
  67. package/dist/processor/processors/baseProcessor.d.ts +0 -14
  68. package/dist/processor/processors/baseProcessor.js +0 -29
  69. package/dist/processor/tools/baseTool.d.ts +0 -10
  70. package/dist/processor/tools/baseTool.js +0 -20
  71. package/dist/processor/tools/toolList.d.ts +0 -9
  72. package/dist/processor/tools/toolList.js +0 -22
  73. package/dist/processor/types/interfaces.d.ts +0 -94
  74. package/dist/processor/types/interfaces.js +0 -2
  75. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +0 -22
  76. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +0 -144
  77. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +0 -15
  78. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +0 -75
  79. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +0 -11
  80. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +0 -46
  81. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +0 -12
  82. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +0 -60
  83. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +0 -18
  84. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +0 -222
  85. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +0 -22
  86. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +0 -194
  87. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.d.ts +0 -41
  88. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.js +0 -197
  89. package/dist/processor-pieces/processors/chatCompressionProcessor.d.ts +0 -26
  90. package/dist/processor-pieces/processors/chatCompressionProcessor.js +0 -90
  91. package/dist/processor-pieces/processors/chatRecordingProcessor.d.ts +0 -81
  92. package/dist/processor-pieces/processors/chatRecordingProcessor.js +0 -329
  93. package/dist/processor-pieces/processors/contextManagementProcessor.d.ts +0 -40
  94. package/dist/processor-pieces/processors/contextManagementProcessor.js +0 -305
  95. package/dist/processor-pieces/processors/loopDetectionProcessor.d.ts +0 -30
  96. package/dist/processor-pieces/processors/loopDetectionProcessor.js +0 -137
  97. package/dist/processor-pieces/processors/responseValidationProcessor.d.ts +0 -30
  98. package/dist/processor-pieces/processors/responseValidationProcessor.js +0 -228
  99. package/dist/processor-pieces/processors/telemetryProcessor.d.ts +0 -99
  100. package/dist/processor-pieces/processors/telemetryProcessor.js +0 -311
  101. package/dist/processor-pieces/processors/tokenManagementProcessor.d.ts +0 -37
  102. package/dist/processor-pieces/processors/tokenManagementProcessor.js +0 -178
  103. package/dist/processor-pieces/processors/toolExecutionProcessor.d.ts +0 -43
  104. package/dist/processor-pieces/processors/toolExecutionProcessor.js +0 -207
  105. package/dist/processor-pieces/tools/fileTools.d.ts +0 -26
  106. package/dist/processor-pieces/tools/fileTools.js +0 -162
  107. package/dist/promptbuilder.d.ts +0 -382
  108. package/dist/promptbuilder.js +0 -805
  109. package/dist/systemprompt.d.ts +0 -20
  110. package/dist/systemprompt.js +0 -48
  111. package/dist/taskInstruction.d.ts +0 -37
  112. package/dist/taskInstruction.js +0 -57
  113. package/dist/usermessage.d.ts +0 -70
  114. package/dist/usermessage.js +0 -123
@@ -1,311 +0,0 @@
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.TelemetryProcessor = void 0;
37
- const processor_1 = require("../../processor");
38
- class TelemetryProcessor extends processor_1.BaseProcessor {
39
- constructor(options = {}) {
40
- super();
41
- // Metrics storage
42
- this.performanceMetrics = [];
43
- this.errorMetrics = [];
44
- this.usageMetrics = [];
45
- this.tokenMetrics = [];
46
- this.operationTimers = new Map();
47
- this.enablePerformanceTracking = options.enablePerformanceTracking !== false;
48
- this.enableErrorTracking = options.enableErrorTracking !== false;
49
- this.enableUsageTracking = options.enableUsageTracking !== false;
50
- this.enableTokenTracking = options.enableTokenTracking !== false;
51
- this.sampleRate = options.sampleRate || 1.0;
52
- this.batchSize = options.batchSize || 100;
53
- this.flushInterval = options.flushInterval || 60000; // 1 minute
54
- this.enableLocalStorage = options.enableLocalStorage !== false;
55
- this.exportPath = options.exportPath || './telemetry';
56
- this.sessionId = this.generateSessionId();
57
- this.startTime = Date.now();
58
- // Setup periodic flush
59
- if (this.flushInterval > 0) {
60
- this.flushTimer = setInterval(() => {
61
- this.flushMetrics().catch(console.error);
62
- }, this.flushInterval);
63
- }
64
- }
65
- async processInput(input) {
66
- var _a;
67
- const { message, context } = input;
68
- // Sample based on rate
69
- if (Math.random() > this.sampleRate) {
70
- return [];
71
- }
72
- const results = [];
73
- try {
74
- // Track processing performance
75
- if (this.enablePerformanceTracking) {
76
- this.startOperation('message_processing');
77
- }
78
- // Track usage
79
- if (this.enableUsageTracking) {
80
- this.trackUsage('message_processed', context === null || context === void 0 ? void 0 : context.userId, this.sessionId);
81
- }
82
- // Track token usage if available
83
- if (this.enableTokenTracking && (context === null || context === void 0 ? void 0 : context.tokenUsage)) {
84
- this.trackTokens(((_a = context.llmconfig) === null || _a === void 0 ? void 0 : _a.model) || 'unknown', context.tokenUsage.input || 0, context.tokenUsage.output || 0, context.tokenUsage.cached || 0, context.tokenUsage.cost);
85
- }
86
- // Track tool usage
87
- if (this.enableUsageTracking && message.messages) {
88
- for (const msg of message.messages) {
89
- if (msg.tool_calls && msg.tool_calls.length > 0) {
90
- for (const toolCall of msg.tool_calls) {
91
- this.trackUsage(`tool_${toolCall.function.name}`, context === null || context === void 0 ? void 0 : context.userId, this.sessionId);
92
- }
93
- }
94
- }
95
- }
96
- results.push(this.createEvent('TelemetryRecorded', {
97
- sessionId: this.sessionId,
98
- metricsCount: this.getTotalMetricsCount()
99
- }));
100
- // Check if we need to flush
101
- if (this.getTotalMetricsCount() >= this.batchSize) {
102
- await this.flushMetrics();
103
- results.push(this.createEvent('TelemetryFlushed', {
104
- sessionId: this.sessionId,
105
- reason: 'batch_size_reached'
106
- }));
107
- }
108
- }
109
- catch (error) {
110
- if (this.enableErrorTracking) {
111
- this.trackError('telemetry_processing_error', error instanceof Error ? error.message : String(error), error instanceof Error ? error.stack : undefined, { messageType: typeof message, contextKeys: context ? Object.keys(context) : [] });
112
- }
113
- results.push(this.createEvent('TelemetryError', {
114
- error: error instanceof Error ? error.message : String(error)
115
- }));
116
- }
117
- finally {
118
- if (this.enablePerformanceTracking) {
119
- this.endOperation('message_processing', true);
120
- }
121
- }
122
- return results;
123
- }
124
- // Performance tracking methods
125
- startOperation(operation) {
126
- if (!this.enablePerformanceTracking)
127
- return;
128
- this.operationTimers.set(operation, Date.now());
129
- }
130
- endOperation(operation, success, metadata) {
131
- if (!this.enablePerformanceTracking)
132
- return;
133
- const startTime = this.operationTimers.get(operation);
134
- if (startTime === undefined)
135
- return;
136
- const endTime = Date.now();
137
- const duration = endTime - startTime;
138
- this.performanceMetrics.push({
139
- operation,
140
- startTime,
141
- endTime,
142
- duration,
143
- success,
144
- metadata
145
- });
146
- this.operationTimers.delete(operation);
147
- }
148
- // Error tracking methods
149
- trackError(type, message, stack, context) {
150
- if (!this.enableErrorTracking)
151
- return;
152
- this.errorMetrics.push({
153
- type,
154
- message,
155
- stack,
156
- timestamp: Date.now(),
157
- context
158
- });
159
- }
160
- // Usage tracking methods
161
- trackUsage(feature, userId, sessionId) {
162
- if (!this.enableUsageTracking)
163
- return;
164
- // Check if we already have a metric for this feature in the current batch
165
- const existingMetric = this.usageMetrics.find(m => m.feature === feature &&
166
- m.userId === userId &&
167
- m.sessionId === sessionId &&
168
- Date.now() - m.timestamp < 60000 // Within last minute
169
- );
170
- if (existingMetric) {
171
- existingMetric.count++;
172
- }
173
- else {
174
- this.usageMetrics.push({
175
- feature,
176
- count: 1,
177
- timestamp: Date.now(),
178
- userId,
179
- sessionId: sessionId || this.sessionId
180
- });
181
- }
182
- }
183
- // Token tracking methods
184
- trackTokens(model, inputTokens, outputTokens, cachedTokens = 0, cost) {
185
- if (!this.enableTokenTracking)
186
- return;
187
- this.tokenMetrics.push({
188
- model,
189
- inputTokens,
190
- outputTokens,
191
- cachedTokens,
192
- totalTokens: inputTokens + outputTokens + cachedTokens,
193
- timestamp: Date.now(),
194
- cost
195
- });
196
- }
197
- // Flush methods
198
- async flushMetrics() {
199
- if (!this.enableLocalStorage)
200
- return;
201
- const telemetryData = {
202
- sessionId: this.sessionId,
203
- timestamp: Date.now(),
204
- performance: [...this.performanceMetrics],
205
- errors: [...this.errorMetrics],
206
- usage: [...this.usageMetrics],
207
- tokens: [...this.tokenMetrics],
208
- metadata: {
209
- sessionStartTime: this.startTime,
210
- flushTime: Date.now(),
211
- totalOperationsTracked: this.performanceMetrics.length,
212
- totalErrorsTracked: this.errorMetrics.length,
213
- totalUsageEvents: this.usageMetrics.length,
214
- totalTokenEvents: this.tokenMetrics.length
215
- }
216
- };
217
- try {
218
- // In a real implementation, you would send this to a telemetry service
219
- // For now, we'll just log it and optionally save to file
220
- console.log('[Telemetry] Flushing metrics:', {
221
- sessionId: this.sessionId,
222
- metricsCount: this.getTotalMetricsCount()
223
- });
224
- if (this.enableLocalStorage) {
225
- await this.saveToFile(telemetryData);
226
- }
227
- // Clear metrics after successful flush
228
- this.clearMetrics();
229
- }
230
- catch (error) {
231
- console.error('[Telemetry] Error flushing metrics:', error);
232
- throw error;
233
- }
234
- }
235
- async saveToFile(data) {
236
- try {
237
- const fs = await Promise.resolve().then(() => __importStar(require('fs/promises')));
238
- const path = await Promise.resolve().then(() => __importStar(require('path')));
239
- // Ensure directory exists
240
- try {
241
- await fs.access(this.exportPath);
242
- }
243
- catch {
244
- await fs.mkdir(this.exportPath, { recursive: true });
245
- }
246
- const filename = `telemetry-${this.sessionId}-${Date.now()}.json`;
247
- const filepath = path.join(this.exportPath, filename);
248
- await fs.writeFile(filepath, JSON.stringify(data, null, 2), 'utf-8');
249
- }
250
- catch (error) {
251
- console.error('[Telemetry] Error saving to file:', error);
252
- }
253
- }
254
- clearMetrics() {
255
- this.performanceMetrics = [];
256
- this.errorMetrics = [];
257
- this.usageMetrics = [];
258
- this.tokenMetrics = [];
259
- }
260
- getTotalMetricsCount() {
261
- return this.performanceMetrics.length +
262
- this.errorMetrics.length +
263
- this.usageMetrics.length +
264
- this.tokenMetrics.length;
265
- }
266
- generateSessionId() {
267
- return `telemetry-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
268
- }
269
- // Public methods for getting metrics
270
- getMetricsSummary() {
271
- return {
272
- sessionId: this.sessionId,
273
- sessionDuration: Date.now() - this.startTime,
274
- performance: this.performanceMetrics.length,
275
- errors: this.errorMetrics.length,
276
- usage: this.usageMetrics.length,
277
- tokens: this.tokenMetrics.length,
278
- total: this.getTotalMetricsCount()
279
- };
280
- }
281
- getPerformanceStats() {
282
- if (this.performanceMetrics.length === 0) {
283
- return {
284
- averageDuration: 0,
285
- successRate: 0,
286
- slowestOperation: null,
287
- fastestOperation: null
288
- };
289
- }
290
- const totalDuration = this.performanceMetrics.reduce((sum, m) => sum + m.duration, 0);
291
- const successCount = this.performanceMetrics.filter(m => m.success).length;
292
- const sortedByDuration = [...this.performanceMetrics].sort((a, b) => a.duration - b.duration);
293
- return {
294
- averageDuration: totalDuration / this.performanceMetrics.length,
295
- successRate: successCount / this.performanceMetrics.length,
296
- slowestOperation: sortedByDuration[sortedByDuration.length - 1] || null,
297
- fastestOperation: sortedByDuration[0] || null
298
- };
299
- }
300
- // Cleanup
301
- async destroy() {
302
- if (this.flushTimer) {
303
- clearInterval(this.flushTimer);
304
- }
305
- // Final flush
306
- if (this.getTotalMetricsCount() > 0) {
307
- await this.flushMetrics();
308
- }
309
- }
310
- }
311
- exports.TelemetryProcessor = TelemetryProcessor;
@@ -1,37 +0,0 @@
1
- import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
- export interface TokenManagementProcessorOptions {
3
- maxTokens?: number;
4
- warningThreshold?: number;
5
- enableCompression?: boolean;
6
- compressionThreshold?: number;
7
- enableCaching?: boolean;
8
- modelTokenLimits?: Record<string, number>;
9
- }
10
- export interface TokenUsage {
11
- input: number;
12
- output: number;
13
- cached: number;
14
- total: number;
15
- estimated?: boolean;
16
- }
17
- export declare class TokenManagementProcessor extends BaseProcessor {
18
- private readonly maxTokens;
19
- private readonly warningThreshold;
20
- private readonly enableCompression;
21
- private readonly compressionThreshold;
22
- private readonly enableCaching;
23
- private readonly modelTokenLimits;
24
- private tokenCache;
25
- constructor(options?: TokenManagementProcessorOptions);
26
- processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
27
- private calculateTokenUsage;
28
- private extractTextFromMessage;
29
- private estimateTokens;
30
- private getCacheKey;
31
- getTokenUsageStats(): {
32
- cacheSize: number;
33
- cacheHitRate: number;
34
- averageTokensPerMessage: number;
35
- };
36
- clearCache(): void;
37
- }
@@ -1,178 +0,0 @@
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;
@@ -1,43 +0,0 @@
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
- }