@codebolt/agent 5.0.1 → 5.0.6

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 (160) hide show
  1. package/dist/agent.d.ts +86 -0
  2. package/dist/agent.js +324 -0
  3. package/dist/builderpattern/agent.js +2 -2
  4. package/dist/builderpattern/followupquestionbuilder.js +1 -1
  5. package/dist/builderpattern/llmoutputhandler.js +7 -7
  6. package/dist/builderpattern/usermessage.d.ts +1 -6
  7. package/dist/composablepattern/document.js +35 -2
  8. package/dist/followupquestionbuilder.d.ts +75 -0
  9. package/dist/followupquestionbuilder.js +197 -0
  10. package/dist/index.d.ts +14 -0
  11. package/dist/index.js +23 -0
  12. package/dist/llmoutputhandler.d.ts +102 -0
  13. package/dist/llmoutputhandler.js +452 -0
  14. package/dist/processor/types/interfaces.d.ts +21 -44
  15. package/dist/processor-pieces/index.d.ts +3 -0
  16. package/dist/processor-pieces/index.js +3 -0
  17. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +5 -14
  18. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +40 -41
  19. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +13 -5
  20. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +58 -50
  21. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +8 -6
  22. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +22 -66
  23. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +2 -3
  24. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +2 -1
  25. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +2 -3
  26. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +2 -1
  27. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +4 -1
  28. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +2 -18
  29. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +93 -291
  30. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +18 -0
  31. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +41 -0
  32. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +2 -1
  33. package/dist/processor-pieces/postToolCallProcessors/index.js +5 -0
  34. package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -1
  35. package/dist/processor-pieces/preInferenceProcessors/index.js +3 -0
  36. package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +2 -1
  37. package/dist/processor-pieces/pretoolCallProcessors/index.js +5 -0
  38. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.d.ts +21 -0
  39. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.js +32 -0
  40. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.d.ts +16 -0
  41. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.js +37 -0
  42. package/dist/promptbuilder.d.ts +382 -0
  43. package/dist/promptbuilder.js +805 -0
  44. package/dist/systemprompt.d.ts +20 -0
  45. package/dist/systemprompt.js +48 -0
  46. package/dist/taskInstruction.d.ts +37 -0
  47. package/dist/taskInstruction.js +57 -0
  48. package/dist/unified/agent/agent.js +2 -2
  49. package/dist/unified/agent/codeboltAgent.d.ts +122 -0
  50. package/dist/unified/agent/codeboltAgent.js +210 -0
  51. package/dist/unified/base/initialPromptGenerator.js +18 -4
  52. package/dist/unified/base/responseExecutor.d.ts +3 -2
  53. package/dist/unified/base/responseExecutor.js +100 -56
  54. package/dist/unified/index.d.ts +4 -0
  55. package/dist/unified/index.js +12 -1
  56. package/dist/usermessage.d.ts +70 -0
  57. package/dist/usermessage.js +123 -0
  58. package/package.json +5 -5
  59. package/dist/local-tools/fileTools.d.ts +0 -26
  60. package/dist/local-tools/fileTools.js +0 -162
  61. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +0 -13
  62. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +0 -68
  63. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +0 -15
  64. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +0 -212
  65. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +0 -19
  66. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +0 -110
  67. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +0 -23
  68. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +0 -173
  69. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +0 -14
  70. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +0 -93
  71. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +0 -30
  72. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +0 -330
  73. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +0 -26
  74. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +0 -269
  75. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +0 -38
  76. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +0 -217
  77. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +0 -34
  78. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +0 -147
  79. package/dist/processor-pieces/additionalModifiers/index.d.ts +0 -12
  80. package/dist/processor-pieces/additionalModifiers/index.js +0 -28
  81. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +0 -29
  82. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +0 -155
  83. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +0 -15
  84. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +0 -129
  85. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +0 -25
  86. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +0 -169
  87. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +0 -20
  88. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +0 -152
  89. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +0 -7
  90. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +0 -93
  91. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +0 -9
  92. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +0 -77
  93. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +0 -19
  94. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +0 -110
  95. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +0 -20
  96. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +0 -124
  97. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +0 -41
  98. package/dist/processor-pieces/messageModifiers/environmentContext.js +0 -355
  99. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +0 -23
  100. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +0 -207
  101. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +0 -7
  102. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +0 -26
  103. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +0 -1
  104. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +0 -2
  105. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +0 -7
  106. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +0 -24
  107. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +0 -41
  108. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +0 -197
  109. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +0 -26
  110. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +0 -90
  111. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +0 -81
  112. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +0 -329
  113. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +0 -40
  114. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +0 -272
  115. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +0 -49
  116. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +0 -291
  117. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +0 -49
  118. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +0 -293
  119. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +0 -47
  120. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +0 -249
  121. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +0 -30
  122. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +0 -137
  123. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +0 -30
  124. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +0 -228
  125. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +0 -99
  126. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +0 -278
  127. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +0 -37
  128. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +0 -178
  129. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +0 -43
  130. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +0 -207
  131. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +0 -52
  132. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +0 -264
  133. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +0 -49
  134. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +0 -293
  135. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +0 -7
  136. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +0 -31
  137. package/dist/processor-pieces/preToolCall/index.d.ts +0 -9
  138. package/dist/processor-pieces/preToolCall/index.js +0 -18
  139. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +0 -58
  140. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +0 -444
  141. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +0 -44
  142. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +0 -367
  143. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +0 -58
  144. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +0 -391
  145. package/dist/unified/agent/tool.d.ts +0 -99
  146. package/dist/unified/agent/tool.js +0 -440
  147. package/dist/unified/examples/agentExample.d.ts +0 -46
  148. package/dist/unified/examples/agentExample.js +0 -464
  149. package/dist/unified/examples/documentationPatternExample.d.ts +0 -10
  150. package/dist/unified/examples/documentationPatternExample.js +0 -385
  151. package/dist/unified/examples/followUpProcessorsExample.d.ts +0 -45
  152. package/dist/unified/examples/followUpProcessorsExample.js +0 -311
  153. package/dist/unified/examples/orchestratorExample.d.ts +0 -16
  154. package/dist/unified/examples/orchestratorExample.js +0 -415
  155. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +0 -36
  156. package/dist/unified/examples/preToolCallProcessorsExample.js +0 -458
  157. package/dist/unified/examples/workflowExample.d.ts +0 -12
  158. package/dist/unified/examples/workflowExample.js +0 -497
  159. package/dist/unified/orchestrator/orchestrator.d.ts +0 -260
  160. package/dist/unified/orchestrator/orchestrator.js +0 -519
@@ -1,137 +0,0 @@
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.LoopDetectionProcessor = void 0;
7
- const processor_1 = require("../../processor");
8
- const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
- class LoopDetectionProcessor extends processor_1.BaseProcessor {
10
- constructor(options = {}) {
11
- super(options);
12
- this.lastPromptId = null;
13
- this.loopCount = 0;
14
- this.maxLoops = options.maxLoops || 3;
15
- this.messageThreshold = options.messageThreshold || 6;
16
- this.enableLoopDetection = options.enableLoopDetection !== false;
17
- }
18
- async processInput(input) {
19
- try {
20
- const { message, context } = input;
21
- if (!this.enableLoopDetection) {
22
- return [this.createEvent('LoopDetectionDisabled', {
23
- reason: 'Loop detection is disabled for this session'
24
- })];
25
- }
26
- // Get prompt ID from context or generate one
27
- const promptId = (context === null || context === void 0 ? void 0 : context.promptId) || this.generatePromptId();
28
- // Reset loop detector if new prompt
29
- if (this.lastPromptId !== promptId) {
30
- await this.resetLoopDetector(promptId);
31
- this.lastPromptId = promptId;
32
- }
33
- else {
34
- this.loopCount++;
35
- }
36
- // Check for conversation loops using CodeBolt state
37
- const loopDetected = await this.checkLoopDetection();
38
- if (loopDetected) {
39
- // Send notification about loop detection
40
- await codeboltjs_1.default.chat.sendNotificationEvent('Loop detected in conversation', 'debug');
41
- return [this.createEvent('LoopDetected', {
42
- promptId,
43
- loopCount: this.loopCount,
44
- maxLoops: this.maxLoops
45
- })];
46
- }
47
- // Check if max loops reached
48
- if (this.loopCount > this.maxLoops) {
49
- return [this.createEvent('MaxLoopsReached', {
50
- promptId,
51
- loopCount: this.loopCount,
52
- maxLoops: this.maxLoops
53
- })];
54
- }
55
- // Continue processing
56
- return [this.createEvent('LoopDetectionPassed', {
57
- promptId,
58
- loopCount: this.loopCount,
59
- maxLoops: this.maxLoops
60
- })];
61
- }
62
- catch (error) {
63
- console.error('Error in LoopDetectionProcessor:', error);
64
- return [this.createEvent('LoopDetectionError', {
65
- error: error instanceof Error ? error.message : String(error)
66
- })];
67
- }
68
- }
69
- generatePromptId() {
70
- return `prompt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
71
- }
72
- async resetLoopDetector(promptId) {
73
- this.loopCount = 0;
74
- this.setContext('currentPromptId', promptId);
75
- this.setContext('loopDetectorReset', Date.now().toString());
76
- // Update CodeBolt agent state
77
- try {
78
- await codeboltjs_1.default.cbstate.addToAgentState('lastPromptId', promptId);
79
- await codeboltjs_1.default.cbstate.addToAgentState('loopDetectorReset', Date.now().toString());
80
- }
81
- catch (error) {
82
- console.warn('Failed to update CodeBolt agent state:', error);
83
- }
84
- }
85
- async checkLoopDetection() {
86
- var _a;
87
- try {
88
- // Get recent messages from CodeBolt state
89
- const agentState = await codeboltjs_1.default.cbstate.getAgentState();
90
- const recentMessages = ((_a = agentState.data) === null || _a === void 0 ? void 0 : _a.recentMessages) || [];
91
- // Simple loop detection: check for repeated patterns
92
- if (recentMessages.length >= this.messageThreshold) {
93
- const lastThree = recentMessages.slice(-3);
94
- const previousThree = recentMessages.slice(-6, -3);
95
- if (lastThree.length === 3 && previousThree.length === 3) {
96
- const isLoop = JSON.stringify(lastThree) === JSON.stringify(previousThree);
97
- if (isLoop) {
98
- console.log('[Loop Detection] Loop detected in conversation');
99
- return true;
100
- }
101
- }
102
- }
103
- return false;
104
- }
105
- catch (error) {
106
- console.warn('Failed to check loop detection:', error);
107
- return false;
108
- }
109
- }
110
- // Public methods for external control
111
- resetSession() {
112
- this.loopCount = 0;
113
- this.lastPromptId = null;
114
- this.clearContext();
115
- // Clear CodeBolt agent state
116
- try {
117
- codeboltjs_1.default.cbstate.addToAgentState('sessionTurnCount', '0');
118
- codeboltjs_1.default.cbstate.addToAgentState('lastPromptId', '');
119
- }
120
- catch (error) {
121
- console.warn('Failed to clear CodeBolt agent state:', error);
122
- }
123
- }
124
- getCurrentLoopCount() {
125
- return this.loopCount;
126
- }
127
- setMaxLoops(maxLoops) {
128
- this.maxLoops = Math.max(1, maxLoops);
129
- }
130
- enableLoopDetectionForSession() {
131
- this.enableLoopDetection = true;
132
- }
133
- disableLoopDetectionForSession() {
134
- this.enableLoopDetection = false;
135
- }
136
- }
137
- exports.LoopDetectionProcessor = LoopDetectionProcessor;
@@ -1,30 +0,0 @@
1
- import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
- export interface ResponseValidationProcessorOptions {
3
- validateToolCalls?: boolean;
4
- validateContent?: boolean;
5
- validateStructure?: boolean;
6
- allowEmptyContent?: boolean;
7
- maxContentLength?: number;
8
- requiredFields?: string[];
9
- }
10
- export interface ValidationResult {
11
- isValid: boolean;
12
- errors: string[];
13
- warnings: string[];
14
- fixes: string[];
15
- }
16
- export declare class ResponseValidationProcessor extends BaseProcessor {
17
- private readonly enableToolCallValidation;
18
- private readonly validateContent;
19
- private readonly validateStructure;
20
- private readonly allowEmptyContent;
21
- private readonly maxContentLength;
22
- private readonly requiredFields;
23
- constructor(options?: ResponseValidationProcessorOptions);
24
- processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
25
- private validateMessage;
26
- private validateMessageStructure;
27
- private validateMessageContent;
28
- private validateToolCallsInMessage;
29
- getValidationSummary(validationResult: ValidationResult): string;
30
- }
@@ -1,228 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ResponseValidationProcessor = void 0;
4
- const processor_1 = require("../../processor");
5
- class ResponseValidationProcessor extends processor_1.BaseProcessor {
6
- constructor(options = {}) {
7
- super();
8
- this.enableToolCallValidation = options.validateToolCalls !== false;
9
- this.validateContent = options.validateContent !== false;
10
- this.validateStructure = options.validateStructure !== false;
11
- this.allowEmptyContent = options.allowEmptyContent || false;
12
- this.maxContentLength = options.maxContentLength || 100000;
13
- this.requiredFields = options.requiredFields || ['role'];
14
- }
15
- async processInput(input) {
16
- var _a;
17
- const { message } = input;
18
- const validationResult = this.validateMessage(message);
19
- const results = [
20
- this.createEvent('ValidationCompleted', {
21
- result: validationResult,
22
- messageId: ((_a = message.metadata) === null || _a === void 0 ? void 0 : _a.id) || 'unknown'
23
- })
24
- ];
25
- if (!validationResult.isValid) {
26
- results.push(this.createEvent('ValidationFailed', {
27
- errors: validationResult.errors,
28
- warnings: validationResult.warnings,
29
- fixes: validationResult.fixes
30
- }));
31
- }
32
- if (validationResult.warnings.length > 0) {
33
- results.push(this.createEvent('ValidationWarnings', {
34
- warnings: validationResult.warnings
35
- }));
36
- }
37
- return results;
38
- }
39
- validateMessage(message) {
40
- const errors = [];
41
- const warnings = [];
42
- const fixes = [];
43
- // Structure validation
44
- if (this.validateStructure) {
45
- const structureValidation = this.validateMessageStructure(message);
46
- errors.push(...structureValidation.errors);
47
- warnings.push(...structureValidation.warnings);
48
- fixes.push(...structureValidation.fixes);
49
- }
50
- // Content validation
51
- if (this.validateContent && message.messages) {
52
- for (let i = 0; i < message.messages.length; i++) {
53
- const msg = message.messages[i];
54
- const contentValidation = this.validateMessageContent(msg, i);
55
- errors.push(...contentValidation.errors);
56
- warnings.push(...contentValidation.warnings);
57
- fixes.push(...contentValidation.fixes);
58
- }
59
- }
60
- // Tool calls validation
61
- if (this.enableToolCallValidation && message.messages) {
62
- for (let i = 0; i < message.messages.length; i++) {
63
- const msg = message.messages[i];
64
- if (msg.tool_calls) {
65
- const toolValidation = this.validateToolCallsInMessage(msg.tool_calls, i);
66
- errors.push(...toolValidation.errors);
67
- warnings.push(...toolValidation.warnings);
68
- fixes.push(...toolValidation.fixes);
69
- }
70
- }
71
- }
72
- return {
73
- isValid: errors.length === 0,
74
- errors,
75
- warnings,
76
- fixes
77
- };
78
- }
79
- validateMessageStructure(message) {
80
- const errors = [];
81
- const warnings = [];
82
- const fixes = [];
83
- // Check if message exists
84
- if (!message) {
85
- errors.push('Message is null or undefined');
86
- fixes.push('Provide a valid message object');
87
- return { isValid: false, errors, warnings, fixes };
88
- }
89
- // Check if messages array exists
90
- if (!message.messages) {
91
- errors.push('Message object missing required "messages" array');
92
- fixes.push('Add a "messages" array to the message object');
93
- }
94
- else if (!Array.isArray(message.messages)) {
95
- errors.push('Messages field must be an array');
96
- fixes.push('Convert messages field to an array');
97
- }
98
- else if (message.messages.length === 0) {
99
- warnings.push('Messages array is empty');
100
- }
101
- // Check metadata structure
102
- if (message.metadata && typeof message.metadata !== 'object') {
103
- warnings.push('Metadata should be an object');
104
- fixes.push('Convert metadata to an object or remove it');
105
- }
106
- return { isValid: errors.length === 0, errors, warnings, fixes };
107
- }
108
- validateMessageContent(msg, index) {
109
- const errors = [];
110
- const warnings = [];
111
- const fixes = [];
112
- // Check required fields
113
- for (const field of this.requiredFields) {
114
- if (!(field in msg)) {
115
- errors.push(`Message at index ${index} missing required field: ${field}`);
116
- fixes.push(`Add ${field} field to message at index ${index}`);
117
- }
118
- }
119
- // Validate role
120
- if (msg.role) {
121
- const validRoles = ['user', 'assistant', 'system', 'tool'];
122
- if (!validRoles.includes(msg.role)) {
123
- errors.push(`Invalid role "${msg.role}" at index ${index}. Must be one of: ${validRoles.join(', ')}`);
124
- fixes.push(`Change role to one of: ${validRoles.join(', ')}`);
125
- }
126
- }
127
- // Validate content
128
- if (msg.content !== undefined) {
129
- if (typeof msg.content === 'string') {
130
- // String content validation
131
- if (!this.allowEmptyContent && msg.content.trim() === '') {
132
- warnings.push(`Empty content in message at index ${index}`);
133
- fixes.push('Provide meaningful content or remove the message');
134
- }
135
- if (msg.content.length > this.maxContentLength) {
136
- warnings.push(`Content too long at index ${index}: ${msg.content.length} chars (max: ${this.maxContentLength})`);
137
- fixes.push('Truncate or compress the content');
138
- }
139
- }
140
- else if (Array.isArray(msg.content)) {
141
- // Array content validation (for multimodal messages)
142
- for (let partIndex = 0; partIndex < msg.content.length; partIndex++) {
143
- const part = msg.content[partIndex];
144
- if (!part || (typeof part !== 'object' && typeof part !== 'string')) {
145
- errors.push(`Invalid content part at message ${index}, part ${partIndex}`);
146
- fixes.push('Ensure all content parts are valid objects or strings');
147
- }
148
- }
149
- }
150
- else if (typeof msg.content !== 'object') {
151
- warnings.push(`Unexpected content type at index ${index}: ${typeof msg.content}`);
152
- }
153
- }
154
- // Validate name field
155
- if (msg.name && typeof msg.name !== 'string') {
156
- warnings.push(`Name field should be a string at index ${index}`);
157
- fixes.push('Convert name field to string');
158
- }
159
- return { isValid: errors.length === 0, errors, warnings, fixes };
160
- }
161
- validateToolCallsInMessage(toolCalls, messageIndex) {
162
- const errors = [];
163
- const warnings = [];
164
- const fixes = [];
165
- if (!Array.isArray(toolCalls)) {
166
- errors.push(`Tool calls must be an array at message index ${messageIndex}`);
167
- fixes.push('Convert tool_calls to an array');
168
- return { isValid: false, errors, warnings, fixes };
169
- }
170
- for (let i = 0; i < toolCalls.length; i++) {
171
- const toolCall = toolCalls[i];
172
- // Check required tool call fields
173
- if (!toolCall.id) {
174
- errors.push(`Tool call at message ${messageIndex}, call ${i} missing required "id" field`);
175
- fixes.push('Add unique id to tool call');
176
- }
177
- if (!toolCall.function) {
178
- errors.push(`Tool call at message ${messageIndex}, call ${i} missing required "function" field`);
179
- fixes.push('Add function object to tool call');
180
- }
181
- else {
182
- // Validate function object
183
- if (!toolCall.function.name) {
184
- errors.push(`Tool call function at message ${messageIndex}, call ${i} missing "name" field`);
185
- fixes.push('Add function name to tool call');
186
- }
187
- if (toolCall.function.arguments === undefined) {
188
- warnings.push(`Tool call function at message ${messageIndex}, call ${i} missing "arguments" field`);
189
- fixes.push('Add arguments field (can be empty object)');
190
- }
191
- else {
192
- // Validate arguments
193
- if (typeof toolCall.function.arguments === 'string') {
194
- try {
195
- JSON.parse(toolCall.function.arguments);
196
- }
197
- catch (e) {
198
- errors.push(`Invalid JSON in tool call arguments at message ${messageIndex}, call ${i}`);
199
- fixes.push('Ensure arguments are valid JSON string or object');
200
- }
201
- }
202
- else if (typeof toolCall.function.arguments !== 'object') {
203
- warnings.push(`Tool call arguments should be object or JSON string at message ${messageIndex}, call ${i}`);
204
- }
205
- }
206
- }
207
- }
208
- return { isValid: errors.length === 0, errors, warnings, fixes };
209
- }
210
- // Utility method to get validation summary
211
- getValidationSummary(validationResult) {
212
- const summary = [];
213
- if (validationResult.isValid) {
214
- summary.push('✅ Validation passed');
215
- }
216
- else {
217
- summary.push('❌ Validation failed');
218
- }
219
- if (validationResult.errors.length > 0) {
220
- summary.push(`${validationResult.errors.length} error(s)`);
221
- }
222
- if (validationResult.warnings.length > 0) {
223
- summary.push(`${validationResult.warnings.length} warning(s)`);
224
- }
225
- return summary.join(' - ');
226
- }
227
- }
228
- exports.ResponseValidationProcessor = ResponseValidationProcessor;
@@ -1,99 +0,0 @@
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
- }