@codebolt/agent 5.0.2 → 5.0.7

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 (164) 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/types/libFunctionTypes.d.ts +13 -19
  49. package/dist/types/libFunctionTypes.js +3 -0
  50. package/dist/types/processorTypes.d.ts +8 -8
  51. package/dist/types/processorTypes.js +6 -23
  52. package/dist/unified/agent/agent.js +2 -2
  53. package/dist/unified/agent/codeboltAgent.d.ts +122 -0
  54. package/dist/unified/agent/codeboltAgent.js +210 -0
  55. package/dist/unified/base/initialPromptGenerator.js +18 -4
  56. package/dist/unified/base/responseExecutor.d.ts +3 -2
  57. package/dist/unified/base/responseExecutor.js +109 -56
  58. package/dist/unified/index.d.ts +4 -0
  59. package/dist/unified/index.js +12 -1
  60. package/dist/usermessage.d.ts +70 -0
  61. package/dist/usermessage.js +123 -0
  62. package/package.json +11 -6
  63. package/dist/local-tools/fileTools.d.ts +0 -26
  64. package/dist/local-tools/fileTools.js +0 -162
  65. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +0 -13
  66. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +0 -68
  67. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +0 -15
  68. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +0 -212
  69. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +0 -19
  70. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +0 -110
  71. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +0 -23
  72. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +0 -173
  73. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +0 -14
  74. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +0 -93
  75. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +0 -30
  76. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +0 -330
  77. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +0 -26
  78. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +0 -269
  79. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +0 -38
  80. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +0 -217
  81. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +0 -34
  82. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +0 -147
  83. package/dist/processor-pieces/additionalModifiers/index.d.ts +0 -12
  84. package/dist/processor-pieces/additionalModifiers/index.js +0 -28
  85. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +0 -29
  86. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +0 -155
  87. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +0 -15
  88. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +0 -129
  89. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +0 -25
  90. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +0 -169
  91. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +0 -20
  92. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +0 -152
  93. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +0 -7
  94. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +0 -93
  95. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +0 -9
  96. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +0 -77
  97. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +0 -19
  98. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +0 -110
  99. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +0 -20
  100. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +0 -124
  101. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +0 -41
  102. package/dist/processor-pieces/messageModifiers/environmentContext.js +0 -355
  103. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +0 -23
  104. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +0 -207
  105. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +0 -7
  106. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +0 -26
  107. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +0 -1
  108. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +0 -2
  109. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +0 -7
  110. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +0 -24
  111. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +0 -41
  112. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +0 -197
  113. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +0 -26
  114. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +0 -90
  115. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +0 -81
  116. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +0 -329
  117. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +0 -40
  118. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +0 -272
  119. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +0 -49
  120. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +0 -291
  121. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +0 -49
  122. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +0 -293
  123. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +0 -47
  124. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +0 -249
  125. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +0 -30
  126. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +0 -137
  127. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +0 -30
  128. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +0 -228
  129. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +0 -99
  130. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +0 -278
  131. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +0 -37
  132. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +0 -178
  133. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +0 -43
  134. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +0 -207
  135. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +0 -52
  136. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +0 -264
  137. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +0 -49
  138. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +0 -293
  139. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +0 -7
  140. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +0 -31
  141. package/dist/processor-pieces/preToolCall/index.d.ts +0 -9
  142. package/dist/processor-pieces/preToolCall/index.js +0 -18
  143. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +0 -58
  144. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +0 -444
  145. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +0 -44
  146. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +0 -367
  147. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +0 -58
  148. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +0 -391
  149. package/dist/unified/agent/tool.d.ts +0 -99
  150. package/dist/unified/agent/tool.js +0 -440
  151. package/dist/unified/examples/agentExample.d.ts +0 -46
  152. package/dist/unified/examples/agentExample.js +0 -464
  153. package/dist/unified/examples/documentationPatternExample.d.ts +0 -10
  154. package/dist/unified/examples/documentationPatternExample.js +0 -385
  155. package/dist/unified/examples/followUpProcessorsExample.d.ts +0 -45
  156. package/dist/unified/examples/followUpProcessorsExample.js +0 -311
  157. package/dist/unified/examples/orchestratorExample.d.ts +0 -16
  158. package/dist/unified/examples/orchestratorExample.js +0 -415
  159. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +0 -36
  160. package/dist/unified/examples/preToolCallProcessorsExample.js +0 -458
  161. package/dist/unified/examples/workflowExample.d.ts +0 -12
  162. package/dist/unified/examples/workflowExample.js +0 -497
  163. package/dist/unified/orchestrator/orchestrator.d.ts +0 -260
  164. package/dist/unified/orchestrator/orchestrator.js +0 -519
@@ -1,272 +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.ContextManagementProcessor = void 0;
7
- const processor_1 = require("../../processor");
8
- const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
- class ContextManagementProcessor extends processor_1.BaseProcessor {
10
- constructor(options = {}) {
11
- super(options);
12
- this.lastSentIdeContext = undefined;
13
- this.contextAddedToHistory = false;
14
- this.enableProjectContext = options.enableProjectContext !== false;
15
- this.enableIdeContext = options.enableIdeContext !== false;
16
- this.enableDirectoryContext = options.enableDirectoryContext !== false;
17
- this.forceFullContext = options.forceFullContext || false;
18
- this.contextThreshold = options.contextThreshold || 100;
19
- }
20
- async processInput(input) {
21
- try {
22
- const { message, context } = input;
23
- // Check if context should be added
24
- if (this.contextAddedToHistory && !this.forceFullContext) {
25
- return [this.createEvent('ContextAlreadyAdded', {
26
- reason: 'Context has already been added to this session'
27
- })];
28
- }
29
- // Collect context information using CodeBolt
30
- const contextInfo = await this.collectContext();
31
- if (!contextInfo.contextAdded) {
32
- return [this.createEvent('NoContextAvailable', {
33
- reason: 'No relevant context found for this session'
34
- })];
35
- }
36
- // Add context to the message
37
- const messageWithContext = await this.addContextToMessage(message, contextInfo);
38
- // Mark context as added
39
- this.contextAddedToHistory = true;
40
- return [
41
- this.createEvent('ContextAdded', contextInfo),
42
- this.createEvent('MessageWithContext', messageWithContext)
43
- ];
44
- }
45
- catch (error) {
46
- console.error('Error in ContextManagementProcessor:', error);
47
- return [this.createEvent('ContextError', {
48
- error: error instanceof Error ? error.message : String(error)
49
- })];
50
- }
51
- }
52
- async collectContext() {
53
- const contextInfo = {
54
- contextAdded: false
55
- };
56
- try {
57
- // Collect project context if enabled
58
- if (this.enableProjectContext) {
59
- contextInfo.projectContext = await this.getProjectContext();
60
- }
61
- // Collect IDE context if enabled
62
- if (this.enableIdeContext) {
63
- contextInfo.ideContext = await this.getIdeContext();
64
- }
65
- // Collect directory context if enabled
66
- if (this.enableDirectoryContext) {
67
- contextInfo.directoryContext = await this.getDirectoryContext();
68
- }
69
- // Check if we have any meaningful context
70
- contextInfo.contextAdded = !!(contextInfo.projectContext || contextInfo.ideContext || contextInfo.directoryContext);
71
- }
72
- catch (error) {
73
- console.warn('Failed to collect context:', error);
74
- }
75
- return contextInfo;
76
- }
77
- async getProjectContext() {
78
- try {
79
- // Get current working directory and project info
80
- const cwd = process.cwd();
81
- const projectName = cwd.split(/[\\/]/).pop() || 'unknown-project';
82
- // Try to get additional project info from CodeBolt if available
83
- let additionalInfo = '';
84
- try {
85
- const projectPath = await codeboltjs_1.default.project.getProjectPath();
86
- if (projectPath.success && projectPath.data) {
87
- additionalInfo = `\nProject Path: ${projectPath.data}`;
88
- }
89
- }
90
- catch (error) {
91
- // Project info is optional
92
- }
93
- return `Project: ${projectName}\nWorking Directory: ${cwd}${additionalInfo}`;
94
- }
95
- catch (error) {
96
- console.warn('Failed to get project context:', error);
97
- return undefined;
98
- }
99
- }
100
- async getIdeContext() {
101
- try {
102
- // This would normally integrate with CodeBolt's IDE context detection
103
- // For now, simulate basic IDE context
104
- const ideContext = {
105
- ideType: this.detectIdeType(),
106
- openFiles: await this.getOpenFiles(),
107
- activeFile: await this.getActiveFile()
108
- };
109
- // Update last sent IDE context
110
- this.lastSentIdeContext = ideContext;
111
- return ideContext;
112
- }
113
- catch (error) {
114
- console.warn('Failed to get IDE context:', error);
115
- return undefined;
116
- }
117
- }
118
- async getDirectoryContext() {
119
- try {
120
- // Get directory structure using CodeBolt's file system capabilities
121
- const cwd = process.cwd();
122
- // Try to get directory listing from CodeBolt
123
- let directoryContents = '';
124
- try {
125
- const listResult = await codeboltjs_1.default.fs.listFile(cwd);
126
- if (listResult.success && listResult.data) {
127
- const items = listResult.data.filter((item) => !item.name.startsWith('.'));
128
- directoryContents = items.slice(0, 10).map((item) => item.name).join(', ');
129
- if (items.length > 10) {
130
- directoryContents += '...';
131
- }
132
- }
133
- }
134
- catch (error) {
135
- // Fallback to basic directory listing
136
- const fs = await import('fs/promises');
137
- const items = await fs.readdir(cwd);
138
- const files = items.filter(item => !item.startsWith('.'));
139
- directoryContents = files.slice(0, 10).join(', ') + (files.length > 10 ? '...' : '');
140
- }
141
- return `Directory: ${cwd}\nContents: ${directoryContents}`;
142
- }
143
- catch (error) {
144
- console.warn('Failed to get directory context:', error);
145
- return undefined;
146
- }
147
- }
148
- detectIdeType() {
149
- // Detect IDE type from environment variables
150
- if (process.env.VSCODE_PID || process.env.VSCODE_IPC_HOOK) {
151
- return 'vscode';
152
- }
153
- if (process.env.CURSOR_PID || process.env.CURSOR_SESSION_ID) {
154
- return 'cursor';
155
- }
156
- return 'unknown';
157
- }
158
- async getOpenFiles() {
159
- try {
160
- // This would normally get actual open files from IDE
161
- // For now, simulate with recent files in current directory
162
- const cwd = process.cwd();
163
- // Try to get recent files from CodeBolt
164
- let files = [];
165
- try {
166
- // CodeBolt doesn't have findRecentFiles, so we'll use listFile as fallback
167
- const listResult = await codeboltjs_1.default.fs.listFile(cwd);
168
- if (listResult.success && listResult.data) {
169
- const fileItems = listResult.data.filter((item) => !item.name.startsWith('.') && item.includes('.'));
170
- files = fileItems.slice(0, 5).map((file, index) => ({
171
- path: file.name,
172
- isActive: index === 0,
173
- timestamp: Date.now()
174
- }));
175
- }
176
- }
177
- catch (error) {
178
- // Fallback to basic file listing
179
- const fs = await import('fs/promises');
180
- const items = await fs.readdir(cwd);
181
- const fileItems = items.filter(item => !item.startsWith('.') && item.includes('.'));
182
- files = fileItems.slice(0, 5).map((file, index) => ({
183
- path: file,
184
- isActive: index === 0,
185
- timestamp: Date.now()
186
- }));
187
- }
188
- return files;
189
- }
190
- catch (error) {
191
- return [];
192
- }
193
- }
194
- async getActiveFile() {
195
- try {
196
- const openFiles = await this.getOpenFiles();
197
- return openFiles.find(f => f.isActive);
198
- }
199
- catch (error) {
200
- return undefined;
201
- }
202
- }
203
- async addContextToMessage(message, contextInfo) {
204
- const contextMessages = [];
205
- // Add project context
206
- if (contextInfo.projectContext) {
207
- contextMessages.push({
208
- role: 'system',
209
- content: `Project Context:\n${contextInfo.projectContext}`,
210
- name: 'project-context'
211
- });
212
- }
213
- // Add IDE context
214
- if (contextInfo.ideContext) {
215
- contextMessages.push({
216
- role: 'system',
217
- content: `IDE Context:\n\`\`\`json\n${JSON.stringify(contextInfo.ideContext, null, 2)}\n\`\`\``,
218
- name: 'ide-context'
219
- });
220
- }
221
- // Add directory context
222
- if (contextInfo.directoryContext) {
223
- contextMessages.push({
224
- role: 'system',
225
- content: `Directory Context:\n${contextInfo.directoryContext}`,
226
- name: 'directory-context'
227
- });
228
- }
229
- // Add acknowledgment message
230
- if (contextMessages.length > 0) {
231
- contextMessages.push({
232
- role: 'assistant',
233
- content: 'Got it. Thanks for the context!',
234
- name: 'context-acknowledgment'
235
- });
236
- }
237
- return {
238
- messages: [...contextMessages, ...message.messages],
239
- metadata: {
240
- ...message.metadata,
241
- contextAdded: true,
242
- contextInfo
243
- }
244
- };
245
- }
246
- // Public methods for external control
247
- resetContext() {
248
- this.contextAddedToHistory = false;
249
- this.lastSentIdeContext = undefined;
250
- this.clearContext();
251
- }
252
- forceContextRefresh() {
253
- this.forceFullContext = true;
254
- this.contextAddedToHistory = false;
255
- }
256
- setContextThreshold(threshold) {
257
- this.contextThreshold = Math.max(1, threshold);
258
- }
259
- enableProjectContextForSession() {
260
- this.enableProjectContext = true;
261
- }
262
- disableProjectContextForSession() {
263
- this.enableProjectContext = false;
264
- }
265
- enableIdeContextForSession() {
266
- this.enableIdeContext = true;
267
- }
268
- disableIdeContextForSession() {
269
- this.enableIdeContext = false;
270
- }
271
- }
272
- exports.ContextManagementProcessor = ContextManagementProcessor;
@@ -1,49 +0,0 @@
1
- import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
- export interface ConversationCompactorInfo {
3
- originalMessageCount: number;
4
- compactedMessageCount: number;
5
- compressionRatio: number;
6
- compactionMethod: 'summarization' | 'truncation' | 'smart_removal';
7
- preservedMessages: number;
8
- removedMessages: number;
9
- }
10
- export interface ConversationCompactorProcessorOptions {
11
- maxConversationLength?: number;
12
- compactionThreshold?: number;
13
- preserveRecentMessages?: number;
14
- preserveSystemMessages?: boolean;
15
- preserveToolMessages?: boolean;
16
- enableSummarization?: boolean;
17
- enableSmartRemoval?: boolean;
18
- compressionRatio?: number;
19
- }
20
- /**
21
- * Processor that compacts long conversations to keep them within manageable limits
22
- * while preserving important context and recent interactions.
23
- */
24
- export declare class ConversationCompactorProcessor extends BaseProcessor {
25
- private readonly maxConversationLength;
26
- private readonly compactionThreshold;
27
- private readonly preserveRecentMessages;
28
- private readonly preserveSystemMessages;
29
- private readonly preserveToolMessages;
30
- private readonly enableSummarization;
31
- private readonly enableSmartRemoval;
32
- private readonly compressionRatio;
33
- constructor(options?: ConversationCompactorProcessorOptions);
34
- processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
35
- private compactConversation;
36
- private performSmartRemoval;
37
- private selectImportantMessages;
38
- private calculateMessageImportance;
39
- private performSummarization;
40
- private performTruncation;
41
- private calculateCompactionInfo;
42
- setMaxConversationLength(length: number): void;
43
- setCompressionRatio(ratio: number): void;
44
- setPreserveRecentMessages(count: number): void;
45
- enableSummarizationForSession(): void;
46
- disableSummarizationForSession(): void;
47
- enableSmartRemovalForSession(): void;
48
- disableSmartRemovalForSession(): void;
49
- }
@@ -1,291 +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.ConversationCompactorProcessor = void 0;
7
- const processor_1 = require("../../processor");
8
- const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
- const { chatSummary } = codeboltjs_1.default;
10
- /**
11
- * Processor that compacts long conversations to keep them within manageable limits
12
- * while preserving important context and recent interactions.
13
- */
14
- class ConversationCompactorProcessor extends processor_1.BaseProcessor {
15
- constructor(options = {}) {
16
- super(options);
17
- this.maxConversationLength = options.maxConversationLength || 50;
18
- this.compactionThreshold = options.compactionThreshold || 0.8; // Compact when 80% of max length
19
- this.preserveRecentMessages = options.preserveRecentMessages || 10;
20
- this.preserveSystemMessages = options.preserveSystemMessages !== false;
21
- this.preserveToolMessages = options.preserveToolMessages !== false;
22
- this.enableSummarization = options.enableSummarization !== false;
23
- this.enableSmartRemoval = options.enableSmartRemoval !== false;
24
- this.compressionRatio = options.compressionRatio || 0.6; // Target 60% of original size
25
- }
26
- async processInput(input) {
27
- try {
28
- const { message, context } = input;
29
- const conversationLength = message.messages.length;
30
- const threshold = Math.floor(this.maxConversationLength * this.compactionThreshold);
31
- // Check if compaction is needed
32
- if (conversationLength <= threshold) {
33
- return [this.createEvent('ConversationCompactionSkipped', {
34
- conversationLength,
35
- threshold,
36
- reason: 'Below compaction threshold'
37
- })];
38
- }
39
- // Perform compaction
40
- const compactedMessage = await this.compactConversation(message, context);
41
- const compactionInfo = this.calculateCompactionInfo(message, compactedMessage);
42
- return [
43
- this.createEvent('ConversationCompacted', compactionInfo),
44
- this.createEvent('ConversationProcessed', compactedMessage)
45
- ];
46
- }
47
- catch (error) {
48
- console.error('Error in ConversationCompactorProcessor:', error);
49
- return [this.createEvent('ConversationCompactionError', {
50
- error: error instanceof Error ? error.message : String(error),
51
- originalLength: input.message.messages.length
52
- })];
53
- }
54
- }
55
- async compactConversation(message, context) {
56
- const messages = [...message.messages];
57
- let compactionMethod = 'truncation';
58
- // Try smart removal first if enabled
59
- if (this.enableSmartRemoval) {
60
- const smartCompacted = await this.performSmartRemoval(messages);
61
- if (smartCompacted.length <= this.maxConversationLength) {
62
- compactionMethod = 'smart_removal';
63
- return {
64
- ...message,
65
- messages: smartCompacted,
66
- metadata: {
67
- ...message.metadata,
68
- compacted: true,
69
- compactionMethod,
70
- originalLength: messages.length,
71
- compactedLength: smartCompacted.length
72
- }
73
- };
74
- }
75
- }
76
- // Try summarization if enabled and we have chat summary service
77
- if (this.enableSummarization) {
78
- try {
79
- const summarized = await this.performSummarization(messages);
80
- if (summarized.length <= this.maxConversationLength) {
81
- compactionMethod = 'summarization';
82
- return {
83
- ...message,
84
- messages: summarized,
85
- metadata: {
86
- ...message.metadata,
87
- compacted: true,
88
- compactionMethod,
89
- originalLength: messages.length,
90
- compactedLength: summarized.length
91
- }
92
- };
93
- }
94
- }
95
- catch (error) {
96
- console.warn('Summarization failed, falling back to truncation:', error);
97
- }
98
- }
99
- // Fall back to truncation
100
- const truncated = this.performTruncation(messages);
101
- return {
102
- ...message,
103
- messages: truncated,
104
- metadata: {
105
- ...message.metadata,
106
- compacted: true,
107
- compactionMethod,
108
- originalLength: messages.length,
109
- compactedLength: truncated.length
110
- }
111
- };
112
- }
113
- async performSmartRemoval(messages) {
114
- const result = [];
115
- const messagesToAnalyze = [...messages];
116
- // Always preserve system messages if enabled
117
- if (this.preserveSystemMessages) {
118
- const systemMessages = messagesToAnalyze.filter(m => m.role === 'system');
119
- result.push(...systemMessages);
120
- messagesToAnalyze.splice(0, messagesToAnalyze.length, ...messagesToAnalyze.filter(m => m.role !== 'system'));
121
- }
122
- // Always preserve recent messages
123
- const recentMessages = messagesToAnalyze.slice(-this.preserveRecentMessages);
124
- const olderMessages = messagesToAnalyze.slice(0, -this.preserveRecentMessages);
125
- // Analyze older messages for importance
126
- const importantOlderMessages = this.selectImportantMessages(olderMessages);
127
- // Preserve tool messages if enabled
128
- let toolMessages = [];
129
- if (this.preserveToolMessages) {
130
- toolMessages = olderMessages.filter(m => m.role === 'tool');
131
- }
132
- // Combine all preserved messages
133
- const preservedMessages = [
134
- ...importantOlderMessages,
135
- ...toolMessages,
136
- ...recentMessages
137
- ];
138
- // Remove duplicates while preserving order
139
- const seen = new Set();
140
- const uniqueMessages = preservedMessages.filter(msg => {
141
- const key = `${msg.role}-${JSON.stringify(msg.content)}-${msg.tool_call_id || ''}`;
142
- if (seen.has(key))
143
- return false;
144
- seen.add(key);
145
- return true;
146
- });
147
- result.push(...uniqueMessages);
148
- return result;
149
- }
150
- selectImportantMessages(messages) {
151
- // Score messages based on importance criteria
152
- const scoredMessages = messages.map(msg => ({
153
- message: msg,
154
- score: this.calculateMessageImportance(msg)
155
- }));
156
- // Sort by score (highest first)
157
- scoredMessages.sort((a, b) => b.score - a.score);
158
- // Select top messages up to compression ratio
159
- const targetCount = Math.floor(messages.length * this.compressionRatio);
160
- return scoredMessages.slice(0, targetCount).map(sm => sm.message);
161
- }
162
- calculateMessageImportance(message) {
163
- let score = 0;
164
- // Base score by role
165
- switch (message.role) {
166
- case 'system':
167
- score += 10;
168
- break;
169
- case 'tool':
170
- score += 8;
171
- break;
172
- case 'assistant':
173
- score += 5;
174
- break;
175
- case 'user':
176
- score += 3;
177
- break;
178
- }
179
- // Content-based scoring
180
- const content = typeof message.content === 'string'
181
- ? message.content
182
- : JSON.stringify(message.content);
183
- // Longer messages might be more important
184
- score += Math.min(content.length / 100, 5);
185
- // Messages with tool calls are important
186
- if (message.tool_calls && message.tool_calls.length > 0) {
187
- score += 7;
188
- }
189
- // Messages with specific keywords are important
190
- const importantKeywords = [
191
- 'error', 'warning', 'critical', 'important', 'required',
192
- 'configuration', 'setup', 'install', 'deploy', 'build'
193
- ];
194
- const lowerContent = content.toLowerCase();
195
- importantKeywords.forEach(keyword => {
196
- if (lowerContent.includes(keyword)) {
197
- score += 2;
198
- }
199
- });
200
- return score;
201
- }
202
- async performSummarization(messages) {
203
- try {
204
- // Preserve system messages and recent messages
205
- const systemMessages = this.preserveSystemMessages
206
- ? messages.filter(m => m.role === 'system')
207
- : [];
208
- const recentMessages = messages.slice(-this.preserveRecentMessages);
209
- const messagesToSummarize = messages.slice(0, -this.preserveRecentMessages)
210
- .filter(m => !this.preserveSystemMessages || m.role !== 'system');
211
- if (messagesToSummarize.length === 0) {
212
- return [...systemMessages, ...recentMessages];
213
- }
214
- // Convert to format expected by chatSummary
215
- const formattedMessages = messagesToSummarize.map(msg => ({
216
- role: msg.role,
217
- content: typeof msg.content === 'string' ? msg.content :
218
- Array.isArray(msg.content) ? msg.content.map(c => c.text).join(' ') :
219
- JSON.stringify(msg.content)
220
- }));
221
- // Use chat summary service
222
- const targetLength = Math.floor(this.maxConversationLength * this.compressionRatio);
223
- const summaryResponse = await chatSummary.summarize(formattedMessages, targetLength);
224
- if (summaryResponse && (summaryResponse.payload || summaryResponse.summary)) {
225
- const summaryText = summaryResponse.payload || summaryResponse.summary;
226
- const summaryMessage = {
227
- role: 'system',
228
- content: `Previous conversation summary: ${summaryText}`,
229
- name: 'conversation-summary'
230
- };
231
- return [
232
- ...systemMessages,
233
- summaryMessage,
234
- ...recentMessages
235
- ];
236
- }
237
- // If summarization fails, fall back to truncation
238
- return this.performTruncation(messages);
239
- }
240
- catch (error) {
241
- console.warn('Summarization failed:', error);
242
- return this.performTruncation(messages);
243
- }
244
- }
245
- performTruncation(messages) {
246
- // Simple truncation: keep system messages + recent messages
247
- const systemMessages = this.preserveSystemMessages
248
- ? messages.filter(m => m.role === 'system')
249
- : [];
250
- const nonSystemMessages = messages.filter(m => !this.preserveSystemMessages || m.role !== 'system');
251
- const availableSlots = this.maxConversationLength - systemMessages.length;
252
- const recentMessages = nonSystemMessages.slice(-Math.max(availableSlots, this.preserveRecentMessages));
253
- return [...systemMessages, ...recentMessages];
254
- }
255
- calculateCompactionInfo(original, compacted) {
256
- var _a;
257
- const originalCount = original.messages.length;
258
- const compactedCount = compacted.messages.length;
259
- return {
260
- originalMessageCount: originalCount,
261
- compactedMessageCount: compactedCount,
262
- compressionRatio: compactedCount / originalCount,
263
- compactionMethod: ((_a = compacted.metadata) === null || _a === void 0 ? void 0 : _a.compactionMethod) || 'truncation',
264
- preservedMessages: compactedCount,
265
- removedMessages: originalCount - compactedCount
266
- };
267
- }
268
- // Public methods for configuration
269
- setMaxConversationLength(length) {
270
- this.maxConversationLength = Math.max(10, length);
271
- }
272
- setCompressionRatio(ratio) {
273
- this.compressionRatio = Math.max(0.1, Math.min(0.9, ratio));
274
- }
275
- setPreserveRecentMessages(count) {
276
- this.preserveRecentMessages = Math.max(1, count);
277
- }
278
- enableSummarizationForSession() {
279
- this.enableSummarization = true;
280
- }
281
- disableSummarizationForSession() {
282
- this.enableSummarization = false;
283
- }
284
- enableSmartRemovalForSession() {
285
- this.enableSmartRemoval = true;
286
- }
287
- disableSmartRemovalForSession() {
288
- this.enableSmartRemoval = false;
289
- }
290
- }
291
- exports.ConversationCompactorProcessor = ConversationCompactorProcessor;
@@ -1,49 +0,0 @@
1
- import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
- export interface ConversationContinuityInfo {
3
- contextLinksAdded: number;
4
- referenceResolutionsAdded: number;
5
- continuityEnhanced: boolean;
6
- missingContextDetected: boolean;
7
- conversationGapsFound: number;
8
- }
9
- export interface ConversationContinuityProcessorOptions {
10
- enableContextLinking?: boolean;
11
- enableReferenceResolution?: boolean;
12
- enableGapDetection?: boolean;
13
- maxContextLinks?: number;
14
- contextLookbackWindow?: number;
15
- enableProactiveContext?: boolean;
16
- }
17
- /**
18
- * Processor that maintains conversation continuity by linking related messages,
19
- * resolving references, and detecting context gaps in follow-up conversations.
20
- */
21
- export declare class ConversationContinuityProcessor extends BaseProcessor {
22
- private readonly enableContextLinking;
23
- private readonly enableReferenceResolution;
24
- private readonly enableGapDetection;
25
- private readonly maxContextLinks;
26
- private readonly contextLookbackWindow;
27
- private readonly enableProactiveContext;
28
- constructor(options?: ConversationContinuityProcessorOptions);
29
- processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
30
- private enhanceConversationContinuity;
31
- private addContextLinks;
32
- private findReferencingMessages;
33
- private generateContextLinkMessage;
34
- private resolveReferences;
35
- private resolveMessageReferences;
36
- private detectAndFillGaps;
37
- private detectConversationGaps;
38
- private generateGapFillerMessage;
39
- private addProactiveContext;
40
- private calculateContinuityInfo;
41
- setContextLookbackWindow(window: number): void;
42
- setMaxContextLinks(max: number): void;
43
- enableContextLinkingForSession(): void;
44
- disableContextLinkingForSession(): void;
45
- enableReferenceResolutionForSession(): void;
46
- disableReferenceResolutionForSession(): void;
47
- enableGapDetectionForSession(): void;
48
- disableGapDetectionForSession(): void;
49
- }