@codebolt/agent 2.2.2 → 2.2.3
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.
- package/dist/builderpattern/agent.js +2 -2
- package/dist/builderpattern/followupquestionbuilder.js +1 -1
- package/dist/builderpattern/llmoutputhandler.js +7 -7
- package/dist/builderpattern/usermessage.d.ts +6 -1
- package/dist/composablepattern/document.js +2 -35
- package/dist/local-tools/fileTools.d.ts +26 -0
- package/dist/local-tools/fileTools.js +162 -0
- package/dist/processor/types/interfaces.d.ts +44 -21
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +13 -0
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +68 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +212 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +23 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +173 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +14 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +93 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +30 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +330 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +26 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +269 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +38 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +217 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +34 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +147 -0
- package/dist/processor-pieces/additionalModifiers/index.d.ts +12 -0
- package/dist/processor-pieces/additionalModifiers/index.js +28 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +29 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +155 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +129 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +25 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +169 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +20 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +152 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +93 -0
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +14 -5
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +41 -40
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +9 -0
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +77 -0
- package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +5 -5
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +5 -13
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +50 -58
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +6 -8
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +66 -22
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +20 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +124 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +41 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.js +355 -0
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +3 -2
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +1 -2
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +3 -2
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +1 -2
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +23 -0
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +207 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +26 -0
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +18 -2
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +291 -93
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +1 -0
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +2 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +7 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +24 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +41 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +197 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +26 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +90 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +81 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +329 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +40 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +272 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +291 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +47 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +249 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +137 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +228 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +99 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.js +278 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +37 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +178 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +43 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +207 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +52 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +264 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +7 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +31 -0
- package/dist/processor-pieces/preToolCall/index.d.ts +9 -0
- package/dist/processor-pieces/preToolCall/index.js +18 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +444 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +44 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +367 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +391 -0
- package/dist/unified/agent/agent.js +2 -2
- package/dist/unified/agent/tool.d.ts +99 -0
- package/dist/unified/agent/tool.js +440 -0
- package/dist/unified/base/initialPromptGenerator.js +5 -5
- package/dist/unified/base/responseExecutor.js +6 -6
- package/dist/unified/examples/agentExample.d.ts +46 -0
- package/dist/unified/examples/agentExample.js +464 -0
- package/dist/unified/examples/documentationPatternExample.d.ts +10 -0
- package/dist/unified/examples/documentationPatternExample.js +385 -0
- package/dist/unified/examples/followUpProcessorsExample.d.ts +45 -0
- package/dist/unified/examples/followUpProcessorsExample.js +311 -0
- package/dist/unified/examples/orchestratorExample.d.ts +16 -0
- package/dist/unified/examples/orchestratorExample.js +415 -0
- package/dist/unified/examples/preToolCallProcessorsExample.d.ts +36 -0
- package/dist/unified/examples/preToolCallProcessorsExample.js +458 -0
- package/dist/unified/examples/workflowExample.d.ts +12 -0
- package/dist/unified/examples/workflowExample.js +497 -0
- package/dist/unified/orchestrator/orchestrator.d.ts +260 -0
- package/dist/unified/orchestrator/orchestrator.js +519 -0
- package/package.json +15 -15
- package/dist/agent.d.ts +0 -86
- package/dist/agent.js +0 -324
- package/dist/followupquestionbuilder.d.ts +0 -75
- package/dist/followupquestionbuilder.js +0 -197
- package/dist/index.d.ts +0 -14
- package/dist/index.js +0 -23
- package/dist/llmoutputhandler.d.ts +0 -102
- package/dist/llmoutputhandler.js +0 -452
- package/dist/promptbuilder.d.ts +0 -382
- package/dist/promptbuilder.js +0 -805
- package/dist/systemprompt.d.ts +0 -20
- package/dist/systemprompt.js +0 -48
- package/dist/taskInstruction.d.ts +0 -37
- package/dist/taskInstruction.js +0 -57
- package/dist/usermessage.d.ts +0 -70
- package/dist/usermessage.js +0 -123
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
|
|
2
|
+
export interface TelemetryProcessorOptions {
|
|
3
|
+
enablePerformanceTracking?: boolean;
|
|
4
|
+
enableErrorTracking?: boolean;
|
|
5
|
+
enableUsageTracking?: boolean;
|
|
6
|
+
enableTokenTracking?: boolean;
|
|
7
|
+
sampleRate?: number;
|
|
8
|
+
batchSize?: number;
|
|
9
|
+
flushInterval?: number;
|
|
10
|
+
enableLocalStorage?: boolean;
|
|
11
|
+
exportPath?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PerformanceMetric {
|
|
14
|
+
operation: string;
|
|
15
|
+
startTime: number;
|
|
16
|
+
endTime: number;
|
|
17
|
+
duration: number;
|
|
18
|
+
success: boolean;
|
|
19
|
+
metadata?: Record<string, any>;
|
|
20
|
+
}
|
|
21
|
+
export interface ErrorMetric {
|
|
22
|
+
type: string;
|
|
23
|
+
message: string;
|
|
24
|
+
stack?: string;
|
|
25
|
+
timestamp: number;
|
|
26
|
+
context?: Record<string, any>;
|
|
27
|
+
}
|
|
28
|
+
export interface UsageMetric {
|
|
29
|
+
feature: string;
|
|
30
|
+
count: number;
|
|
31
|
+
timestamp: number;
|
|
32
|
+
userId?: string;
|
|
33
|
+
sessionId?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface TokenMetric {
|
|
36
|
+
model: string;
|
|
37
|
+
inputTokens: number;
|
|
38
|
+
outputTokens: number;
|
|
39
|
+
cachedTokens: number;
|
|
40
|
+
totalTokens: number;
|
|
41
|
+
timestamp: number;
|
|
42
|
+
cost?: number;
|
|
43
|
+
}
|
|
44
|
+
export interface TelemetryData {
|
|
45
|
+
sessionId: string;
|
|
46
|
+
timestamp: number;
|
|
47
|
+
performance: PerformanceMetric[];
|
|
48
|
+
errors: ErrorMetric[];
|
|
49
|
+
usage: UsageMetric[];
|
|
50
|
+
tokens: TokenMetric[];
|
|
51
|
+
metadata: Record<string, any>;
|
|
52
|
+
}
|
|
53
|
+
export declare class TelemetryProcessor extends BaseProcessor {
|
|
54
|
+
private readonly enablePerformanceTracking;
|
|
55
|
+
private readonly enableErrorTracking;
|
|
56
|
+
private readonly enableUsageTracking;
|
|
57
|
+
private readonly enableTokenTracking;
|
|
58
|
+
private readonly sampleRate;
|
|
59
|
+
private readonly batchSize;
|
|
60
|
+
private readonly flushInterval;
|
|
61
|
+
private readonly enableLocalStorage;
|
|
62
|
+
private readonly exportPath;
|
|
63
|
+
private performanceMetrics;
|
|
64
|
+
private errorMetrics;
|
|
65
|
+
private usageMetrics;
|
|
66
|
+
private tokenMetrics;
|
|
67
|
+
private sessionId;
|
|
68
|
+
private startTime;
|
|
69
|
+
private operationTimers;
|
|
70
|
+
private flushTimer?;
|
|
71
|
+
constructor(options?: TelemetryProcessorOptions);
|
|
72
|
+
processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
|
|
73
|
+
startOperation(operation: string): void;
|
|
74
|
+
endOperation(operation: string, success: boolean, metadata?: Record<string, any>): void;
|
|
75
|
+
trackError(type: string, message: string, stack?: string, context?: Record<string, any>): void;
|
|
76
|
+
trackUsage(feature: string, userId?: string, sessionId?: string): void;
|
|
77
|
+
trackTokens(model: string, inputTokens: number, outputTokens: number, cachedTokens?: number, cost?: number): void;
|
|
78
|
+
flushMetrics(): Promise<void>;
|
|
79
|
+
private saveToFile;
|
|
80
|
+
private clearMetrics;
|
|
81
|
+
private getTotalMetricsCount;
|
|
82
|
+
private generateSessionId;
|
|
83
|
+
getMetricsSummary(): {
|
|
84
|
+
sessionId: string;
|
|
85
|
+
sessionDuration: number;
|
|
86
|
+
performance: number;
|
|
87
|
+
errors: number;
|
|
88
|
+
usage: number;
|
|
89
|
+
tokens: number;
|
|
90
|
+
total: number;
|
|
91
|
+
};
|
|
92
|
+
getPerformanceStats(): {
|
|
93
|
+
averageDuration: number;
|
|
94
|
+
successRate: number;
|
|
95
|
+
slowestOperation: PerformanceMetric | null;
|
|
96
|
+
fastestOperation: PerformanceMetric | null;
|
|
97
|
+
};
|
|
98
|
+
destroy(): Promise<void>;
|
|
99
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TelemetryProcessor = void 0;
|
|
4
|
+
const processor_1 = require("../../processor");
|
|
5
|
+
class TelemetryProcessor extends processor_1.BaseProcessor {
|
|
6
|
+
constructor(options = {}) {
|
|
7
|
+
super();
|
|
8
|
+
// Metrics storage
|
|
9
|
+
this.performanceMetrics = [];
|
|
10
|
+
this.errorMetrics = [];
|
|
11
|
+
this.usageMetrics = [];
|
|
12
|
+
this.tokenMetrics = [];
|
|
13
|
+
this.operationTimers = new Map();
|
|
14
|
+
this.enablePerformanceTracking = options.enablePerformanceTracking !== false;
|
|
15
|
+
this.enableErrorTracking = options.enableErrorTracking !== false;
|
|
16
|
+
this.enableUsageTracking = options.enableUsageTracking !== false;
|
|
17
|
+
this.enableTokenTracking = options.enableTokenTracking !== false;
|
|
18
|
+
this.sampleRate = options.sampleRate || 1.0;
|
|
19
|
+
this.batchSize = options.batchSize || 100;
|
|
20
|
+
this.flushInterval = options.flushInterval || 60000; // 1 minute
|
|
21
|
+
this.enableLocalStorage = options.enableLocalStorage !== false;
|
|
22
|
+
this.exportPath = options.exportPath || './telemetry';
|
|
23
|
+
this.sessionId = this.generateSessionId();
|
|
24
|
+
this.startTime = Date.now();
|
|
25
|
+
// Setup periodic flush
|
|
26
|
+
if (this.flushInterval > 0) {
|
|
27
|
+
this.flushTimer = setInterval(() => {
|
|
28
|
+
this.flushMetrics().catch(console.error);
|
|
29
|
+
}, this.flushInterval);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async processInput(input) {
|
|
33
|
+
var _a;
|
|
34
|
+
const { message, context } = input;
|
|
35
|
+
// Sample based on rate
|
|
36
|
+
if (Math.random() > this.sampleRate) {
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
const results = [];
|
|
40
|
+
try {
|
|
41
|
+
// Track processing performance
|
|
42
|
+
if (this.enablePerformanceTracking) {
|
|
43
|
+
this.startOperation('message_processing');
|
|
44
|
+
}
|
|
45
|
+
// Track usage
|
|
46
|
+
if (this.enableUsageTracking) {
|
|
47
|
+
this.trackUsage('message_processed', context === null || context === void 0 ? void 0 : context.userId, this.sessionId);
|
|
48
|
+
}
|
|
49
|
+
// Track token usage if available
|
|
50
|
+
if (this.enableTokenTracking && (context === null || context === void 0 ? void 0 : context.tokenUsage)) {
|
|
51
|
+
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);
|
|
52
|
+
}
|
|
53
|
+
// Track tool usage
|
|
54
|
+
if (this.enableUsageTracking && message.messages) {
|
|
55
|
+
for (const msg of message.messages) {
|
|
56
|
+
if (msg.tool_calls && msg.tool_calls.length > 0) {
|
|
57
|
+
for (const toolCall of msg.tool_calls) {
|
|
58
|
+
this.trackUsage(`tool_${toolCall.function.name}`, context === null || context === void 0 ? void 0 : context.userId, this.sessionId);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
results.push(this.createEvent('TelemetryRecorded', {
|
|
64
|
+
sessionId: this.sessionId,
|
|
65
|
+
metricsCount: this.getTotalMetricsCount()
|
|
66
|
+
}));
|
|
67
|
+
// Check if we need to flush
|
|
68
|
+
if (this.getTotalMetricsCount() >= this.batchSize) {
|
|
69
|
+
await this.flushMetrics();
|
|
70
|
+
results.push(this.createEvent('TelemetryFlushed', {
|
|
71
|
+
sessionId: this.sessionId,
|
|
72
|
+
reason: 'batch_size_reached'
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (this.enableErrorTracking) {
|
|
78
|
+
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) : [] });
|
|
79
|
+
}
|
|
80
|
+
results.push(this.createEvent('TelemetryError', {
|
|
81
|
+
error: error instanceof Error ? error.message : String(error)
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
if (this.enablePerformanceTracking) {
|
|
86
|
+
this.endOperation('message_processing', true);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return results;
|
|
90
|
+
}
|
|
91
|
+
// Performance tracking methods
|
|
92
|
+
startOperation(operation) {
|
|
93
|
+
if (!this.enablePerformanceTracking)
|
|
94
|
+
return;
|
|
95
|
+
this.operationTimers.set(operation, Date.now());
|
|
96
|
+
}
|
|
97
|
+
endOperation(operation, success, metadata) {
|
|
98
|
+
if (!this.enablePerformanceTracking)
|
|
99
|
+
return;
|
|
100
|
+
const startTime = this.operationTimers.get(operation);
|
|
101
|
+
if (startTime === undefined)
|
|
102
|
+
return;
|
|
103
|
+
const endTime = Date.now();
|
|
104
|
+
const duration = endTime - startTime;
|
|
105
|
+
this.performanceMetrics.push({
|
|
106
|
+
operation,
|
|
107
|
+
startTime,
|
|
108
|
+
endTime,
|
|
109
|
+
duration,
|
|
110
|
+
success,
|
|
111
|
+
metadata
|
|
112
|
+
});
|
|
113
|
+
this.operationTimers.delete(operation);
|
|
114
|
+
}
|
|
115
|
+
// Error tracking methods
|
|
116
|
+
trackError(type, message, stack, context) {
|
|
117
|
+
if (!this.enableErrorTracking)
|
|
118
|
+
return;
|
|
119
|
+
this.errorMetrics.push({
|
|
120
|
+
type,
|
|
121
|
+
message,
|
|
122
|
+
stack,
|
|
123
|
+
timestamp: Date.now(),
|
|
124
|
+
context
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
// Usage tracking methods
|
|
128
|
+
trackUsage(feature, userId, sessionId) {
|
|
129
|
+
if (!this.enableUsageTracking)
|
|
130
|
+
return;
|
|
131
|
+
// Check if we already have a metric for this feature in the current batch
|
|
132
|
+
const existingMetric = this.usageMetrics.find(m => m.feature === feature &&
|
|
133
|
+
m.userId === userId &&
|
|
134
|
+
m.sessionId === sessionId &&
|
|
135
|
+
Date.now() - m.timestamp < 60000 // Within last minute
|
|
136
|
+
);
|
|
137
|
+
if (existingMetric) {
|
|
138
|
+
existingMetric.count++;
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
this.usageMetrics.push({
|
|
142
|
+
feature,
|
|
143
|
+
count: 1,
|
|
144
|
+
timestamp: Date.now(),
|
|
145
|
+
userId,
|
|
146
|
+
sessionId: sessionId || this.sessionId
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// Token tracking methods
|
|
151
|
+
trackTokens(model, inputTokens, outputTokens, cachedTokens = 0, cost) {
|
|
152
|
+
if (!this.enableTokenTracking)
|
|
153
|
+
return;
|
|
154
|
+
this.tokenMetrics.push({
|
|
155
|
+
model,
|
|
156
|
+
inputTokens,
|
|
157
|
+
outputTokens,
|
|
158
|
+
cachedTokens,
|
|
159
|
+
totalTokens: inputTokens + outputTokens + cachedTokens,
|
|
160
|
+
timestamp: Date.now(),
|
|
161
|
+
cost
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
// Flush methods
|
|
165
|
+
async flushMetrics() {
|
|
166
|
+
if (!this.enableLocalStorage)
|
|
167
|
+
return;
|
|
168
|
+
const telemetryData = {
|
|
169
|
+
sessionId: this.sessionId,
|
|
170
|
+
timestamp: Date.now(),
|
|
171
|
+
performance: [...this.performanceMetrics],
|
|
172
|
+
errors: [...this.errorMetrics],
|
|
173
|
+
usage: [...this.usageMetrics],
|
|
174
|
+
tokens: [...this.tokenMetrics],
|
|
175
|
+
metadata: {
|
|
176
|
+
sessionStartTime: this.startTime,
|
|
177
|
+
flushTime: Date.now(),
|
|
178
|
+
totalOperationsTracked: this.performanceMetrics.length,
|
|
179
|
+
totalErrorsTracked: this.errorMetrics.length,
|
|
180
|
+
totalUsageEvents: this.usageMetrics.length,
|
|
181
|
+
totalTokenEvents: this.tokenMetrics.length
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
try {
|
|
185
|
+
// In a real implementation, you would send this to a telemetry service
|
|
186
|
+
// For now, we'll just log it and optionally save to file
|
|
187
|
+
console.log('[Telemetry] Flushing metrics:', {
|
|
188
|
+
sessionId: this.sessionId,
|
|
189
|
+
metricsCount: this.getTotalMetricsCount()
|
|
190
|
+
});
|
|
191
|
+
if (this.enableLocalStorage) {
|
|
192
|
+
await this.saveToFile(telemetryData);
|
|
193
|
+
}
|
|
194
|
+
// Clear metrics after successful flush
|
|
195
|
+
this.clearMetrics();
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
console.error('[Telemetry] Error flushing metrics:', error);
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async saveToFile(data) {
|
|
203
|
+
try {
|
|
204
|
+
const fs = await import('fs/promises');
|
|
205
|
+
const path = await import('path');
|
|
206
|
+
// Ensure directory exists
|
|
207
|
+
try {
|
|
208
|
+
await fs.access(this.exportPath);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
await fs.mkdir(this.exportPath, { recursive: true });
|
|
212
|
+
}
|
|
213
|
+
const filename = `telemetry-${this.sessionId}-${Date.now()}.json`;
|
|
214
|
+
const filepath = path.join(this.exportPath, filename);
|
|
215
|
+
await fs.writeFile(filepath, JSON.stringify(data, null, 2), 'utf-8');
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
console.error('[Telemetry] Error saving to file:', error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
clearMetrics() {
|
|
222
|
+
this.performanceMetrics = [];
|
|
223
|
+
this.errorMetrics = [];
|
|
224
|
+
this.usageMetrics = [];
|
|
225
|
+
this.tokenMetrics = [];
|
|
226
|
+
}
|
|
227
|
+
getTotalMetricsCount() {
|
|
228
|
+
return this.performanceMetrics.length +
|
|
229
|
+
this.errorMetrics.length +
|
|
230
|
+
this.usageMetrics.length +
|
|
231
|
+
this.tokenMetrics.length;
|
|
232
|
+
}
|
|
233
|
+
generateSessionId() {
|
|
234
|
+
return `telemetry-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
235
|
+
}
|
|
236
|
+
// Public methods for getting metrics
|
|
237
|
+
getMetricsSummary() {
|
|
238
|
+
return {
|
|
239
|
+
sessionId: this.sessionId,
|
|
240
|
+
sessionDuration: Date.now() - this.startTime,
|
|
241
|
+
performance: this.performanceMetrics.length,
|
|
242
|
+
errors: this.errorMetrics.length,
|
|
243
|
+
usage: this.usageMetrics.length,
|
|
244
|
+
tokens: this.tokenMetrics.length,
|
|
245
|
+
total: this.getTotalMetricsCount()
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
getPerformanceStats() {
|
|
249
|
+
if (this.performanceMetrics.length === 0) {
|
|
250
|
+
return {
|
|
251
|
+
averageDuration: 0,
|
|
252
|
+
successRate: 0,
|
|
253
|
+
slowestOperation: null,
|
|
254
|
+
fastestOperation: null
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
const totalDuration = this.performanceMetrics.reduce((sum, m) => sum + m.duration, 0);
|
|
258
|
+
const successCount = this.performanceMetrics.filter(m => m.success).length;
|
|
259
|
+
const sortedByDuration = [...this.performanceMetrics].sort((a, b) => a.duration - b.duration);
|
|
260
|
+
return {
|
|
261
|
+
averageDuration: totalDuration / this.performanceMetrics.length,
|
|
262
|
+
successRate: successCount / this.performanceMetrics.length,
|
|
263
|
+
slowestOperation: sortedByDuration[sortedByDuration.length - 1] || null,
|
|
264
|
+
fastestOperation: sortedByDuration[0] || null
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
// Cleanup
|
|
268
|
+
async destroy() {
|
|
269
|
+
if (this.flushTimer) {
|
|
270
|
+
clearInterval(this.flushTimer);
|
|
271
|
+
}
|
|
272
|
+
// Final flush
|
|
273
|
+
if (this.getTotalMetricsCount() > 0) {
|
|
274
|
+
await this.flushMetrics();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
exports.TelemetryProcessor = TelemetryProcessor;
|
|
@@ -0,0 +1,37 @@
|
|
|
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
|
+
}
|
|
@@ -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
|
+
}
|