@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.
Files changed (141) hide show
  1. package/dist/builderpattern/agent.js +2 -2
  2. package/dist/builderpattern/followupquestionbuilder.js +1 -1
  3. package/dist/builderpattern/llmoutputhandler.js +7 -7
  4. package/dist/builderpattern/usermessage.d.ts +6 -1
  5. package/dist/composablepattern/document.js +2 -35
  6. package/dist/local-tools/fileTools.d.ts +26 -0
  7. package/dist/local-tools/fileTools.js +162 -0
  8. package/dist/processor/types/interfaces.d.ts +44 -21
  9. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +13 -0
  10. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +68 -0
  11. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +15 -0
  12. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +212 -0
  13. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +19 -0
  14. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +110 -0
  15. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +23 -0
  16. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +173 -0
  17. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +14 -0
  18. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +93 -0
  19. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +30 -0
  20. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +330 -0
  21. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +26 -0
  22. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +269 -0
  23. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +38 -0
  24. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +217 -0
  25. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +34 -0
  26. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +147 -0
  27. package/dist/processor-pieces/additionalModifiers/index.d.ts +12 -0
  28. package/dist/processor-pieces/additionalModifiers/index.js +28 -0
  29. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +29 -0
  30. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +155 -0
  31. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +15 -0
  32. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +129 -0
  33. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +25 -0
  34. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +169 -0
  35. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +20 -0
  36. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +152 -0
  37. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +7 -0
  38. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +93 -0
  39. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +14 -5
  40. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +41 -40
  41. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +9 -0
  42. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +77 -0
  43. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +5 -5
  44. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +5 -13
  45. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +50 -58
  46. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +6 -8
  47. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +66 -22
  48. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +19 -0
  49. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +110 -0
  50. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +20 -0
  51. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +124 -0
  52. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +41 -0
  53. package/dist/processor-pieces/messageModifiers/environmentContext.js +355 -0
  54. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +3 -2
  55. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +1 -2
  56. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +3 -2
  57. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +1 -2
  58. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +23 -0
  59. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +207 -0
  60. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +7 -0
  61. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +26 -0
  62. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +18 -2
  63. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +291 -93
  64. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +1 -0
  65. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +2 -0
  66. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +7 -0
  67. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +24 -0
  68. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +41 -0
  69. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +197 -0
  70. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +26 -0
  71. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +90 -0
  72. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +81 -0
  73. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +329 -0
  74. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +40 -0
  75. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +272 -0
  76. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +49 -0
  77. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +291 -0
  78. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +49 -0
  79. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +293 -0
  80. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +47 -0
  81. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +249 -0
  82. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +30 -0
  83. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +137 -0
  84. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +30 -0
  85. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +228 -0
  86. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +99 -0
  87. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +278 -0
  88. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +37 -0
  89. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +178 -0
  90. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +43 -0
  91. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +207 -0
  92. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +52 -0
  93. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +264 -0
  94. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +49 -0
  95. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +293 -0
  96. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +7 -0
  97. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +31 -0
  98. package/dist/processor-pieces/preToolCall/index.d.ts +9 -0
  99. package/dist/processor-pieces/preToolCall/index.js +18 -0
  100. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +58 -0
  101. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +444 -0
  102. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +44 -0
  103. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +367 -0
  104. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +58 -0
  105. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +391 -0
  106. package/dist/unified/agent/agent.js +2 -2
  107. package/dist/unified/agent/tool.d.ts +99 -0
  108. package/dist/unified/agent/tool.js +440 -0
  109. package/dist/unified/base/initialPromptGenerator.js +5 -5
  110. package/dist/unified/base/responseExecutor.js +6 -6
  111. package/dist/unified/examples/agentExample.d.ts +46 -0
  112. package/dist/unified/examples/agentExample.js +464 -0
  113. package/dist/unified/examples/documentationPatternExample.d.ts +10 -0
  114. package/dist/unified/examples/documentationPatternExample.js +385 -0
  115. package/dist/unified/examples/followUpProcessorsExample.d.ts +45 -0
  116. package/dist/unified/examples/followUpProcessorsExample.js +311 -0
  117. package/dist/unified/examples/orchestratorExample.d.ts +16 -0
  118. package/dist/unified/examples/orchestratorExample.js +415 -0
  119. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +36 -0
  120. package/dist/unified/examples/preToolCallProcessorsExample.js +458 -0
  121. package/dist/unified/examples/workflowExample.d.ts +12 -0
  122. package/dist/unified/examples/workflowExample.js +497 -0
  123. package/dist/unified/orchestrator/orchestrator.d.ts +260 -0
  124. package/dist/unified/orchestrator/orchestrator.js +519 -0
  125. package/package.json +15 -15
  126. package/dist/agent.d.ts +0 -86
  127. package/dist/agent.js +0 -324
  128. package/dist/followupquestionbuilder.d.ts +0 -75
  129. package/dist/followupquestionbuilder.js +0 -197
  130. package/dist/index.d.ts +0 -14
  131. package/dist/index.js +0 -23
  132. package/dist/llmoutputhandler.d.ts +0 -102
  133. package/dist/llmoutputhandler.js +0 -452
  134. package/dist/promptbuilder.d.ts +0 -382
  135. package/dist/promptbuilder.js +0 -805
  136. package/dist/systemprompt.d.ts +0 -20
  137. package/dist/systemprompt.js +0 -48
  138. package/dist/taskInstruction.d.ts +0 -37
  139. package/dist/taskInstruction.js +0 -57
  140. package/dist/usermessage.d.ts +0 -70
  141. package/dist/usermessage.js +0 -123
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ChatRecordingProcessor = void 0;
37
+ const processor_1 = require("../../processor");
38
+ const fs = __importStar(require("fs/promises"));
39
+ const path = __importStar(require("path"));
40
+ class ChatRecordingProcessor extends processor_1.BaseProcessor {
41
+ constructor(options = {}) {
42
+ super();
43
+ // Session tracking
44
+ this.currentSession = null;
45
+ this.messageCount = 0;
46
+ this.sessions = [];
47
+ this.enableTokenTracking = options.enableTokenTracking !== false;
48
+ this.exportFormat = options.exportFormat || 'json';
49
+ this.outputDirectory = options.outputDirectory || './chat-recordings';
50
+ this.maxFileSize = options.maxFileSize || 10 * 1024 * 1024; // 10MB
51
+ this.enableCompression = options.enableCompression || false;
52
+ this.includeMetadata = options.includeMetadata !== false;
53
+ this.autoExport = options.autoExport || false;
54
+ this.exportInterval = options.exportInterval || 50;
55
+ }
56
+ async processInput(input) {
57
+ const { message, context } = input;
58
+ try {
59
+ // Initialize session if not exists
60
+ if (!this.currentSession) {
61
+ this.initializeSession(context);
62
+ }
63
+ // Record the message
64
+ const messageRecord = this.createMessageRecord(message, context);
65
+ this.currentSession.messages.push(messageRecord);
66
+ this.messageCount++;
67
+ // Update session totals
68
+ this.updateSessionTotals(messageRecord);
69
+ const results = [
70
+ this.createEvent('MessageRecorded', {
71
+ messageId: messageRecord.id,
72
+ sessionId: this.currentSession.sessionId,
73
+ messageCount: this.messageCount
74
+ })
75
+ ];
76
+ // Auto-export if enabled and interval reached
77
+ if (this.autoExport && this.messageCount % this.exportInterval === 0) {
78
+ try {
79
+ const exportPath = await this.exportSession(this.currentSession);
80
+ results.push(this.createEvent('SessionExported', {
81
+ sessionId: this.currentSession.sessionId,
82
+ exportPath,
83
+ messageCount: this.currentSession.messages.length
84
+ }));
85
+ }
86
+ catch (exportError) {
87
+ results.push(this.createEvent('ExportError', {
88
+ error: exportError instanceof Error ? exportError.message : String(exportError),
89
+ sessionId: this.currentSession.sessionId
90
+ }));
91
+ }
92
+ }
93
+ return results;
94
+ }
95
+ catch (error) {
96
+ console.error('[ChatRecording] Error recording message:', error);
97
+ const messageStr = String(message);
98
+ return [this.createEvent('RecordingError', {
99
+ error: error instanceof Error ? error.message : String(error),
100
+ messageContent: messageStr.slice(0, 100)
101
+ })];
102
+ }
103
+ }
104
+ initializeSession(context) {
105
+ const sessionId = this.generateSessionId();
106
+ this.currentSession = {
107
+ sessionId,
108
+ startTime: new Date().toISOString(),
109
+ messages: [],
110
+ totalTokens: {
111
+ input: 0,
112
+ output: 0,
113
+ cached: 0,
114
+ total: 0
115
+ },
116
+ toolCallCount: 0,
117
+ metadata: {
118
+ llmConfig: (context === null || context === void 0 ? void 0 : context.llmconfig) || {},
119
+ userAgent: 'codebolt-agent',
120
+ version: '1.0.0',
121
+ ...context === null || context === void 0 ? void 0 : context.sessionMetadata
122
+ }
123
+ };
124
+ }
125
+ createMessageRecord(message, context) {
126
+ const id = this.generateMessageId();
127
+ const timestamp = new Date().toISOString();
128
+ // Extract basic message info
129
+ let role = 'unknown';
130
+ let content = '';
131
+ let toolCalls = [];
132
+ if (message.messages && Array.isArray(message.messages) && message.messages.length > 0) {
133
+ const lastMessage = message.messages[message.messages.length - 1];
134
+ role = lastMessage.role || 'unknown';
135
+ content = this.extractContent(lastMessage.content);
136
+ if (lastMessage.tool_calls) {
137
+ toolCalls = this.extractToolCalls(lastMessage.tool_calls);
138
+ }
139
+ }
140
+ else if (typeof message === 'string') {
141
+ role = 'user';
142
+ content = message;
143
+ }
144
+ else {
145
+ content = JSON.stringify(message);
146
+ }
147
+ // Calculate tokens if enabled
148
+ let tokens;
149
+ if (this.enableTokenTracking) {
150
+ tokens = this.estimateTokens(content);
151
+ }
152
+ return {
153
+ id,
154
+ timestamp,
155
+ role,
156
+ content: content.slice(0, 10000), // Limit content length for storage
157
+ metadata: this.includeMetadata ? {
158
+ originalMessageLength: content.length,
159
+ hasToolCalls: toolCalls.length > 0,
160
+ contextKeys: context ? Object.keys(context) : [],
161
+ ...message.metadata
162
+ } : undefined,
163
+ tokens,
164
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined
165
+ };
166
+ }
167
+ extractContent(content) {
168
+ if (typeof content === 'string') {
169
+ return content;
170
+ }
171
+ if (Array.isArray(content)) {
172
+ return content
173
+ .map(part => {
174
+ if (typeof part === 'string')
175
+ return part;
176
+ if (part === null || part === void 0 ? void 0 : part.text)
177
+ return part.text;
178
+ if ((part === null || part === void 0 ? void 0 : part.type) === 'text')
179
+ return part.text || '';
180
+ return JSON.stringify(part);
181
+ })
182
+ .join(' ');
183
+ }
184
+ return JSON.stringify(content);
185
+ }
186
+ extractToolCalls(toolCalls) {
187
+ return toolCalls.map(tc => {
188
+ var _a, _b, _c;
189
+ return ({
190
+ id: tc.id || this.generateToolCallId(),
191
+ name: ((_a = tc.function) === null || _a === void 0 ? void 0 : _a.name) || 'unknown',
192
+ args: typeof ((_b = tc.function) === null || _b === void 0 ? void 0 : _b.arguments) === 'string'
193
+ ? JSON.parse(tc.function.arguments)
194
+ : ((_c = tc.function) === null || _c === void 0 ? void 0 : _c.arguments) || {},
195
+ status: 'pending',
196
+ timestamp: new Date().toISOString()
197
+ });
198
+ });
199
+ }
200
+ estimateTokens(content) {
201
+ // Simple token estimation
202
+ const charCount = content.length;
203
+ const estimated = Math.ceil(charCount / 4);
204
+ return {
205
+ input: estimated,
206
+ output: 0,
207
+ cached: 0,
208
+ total: estimated
209
+ };
210
+ }
211
+ updateSessionTotals(messageRecord) {
212
+ if (!this.currentSession || !messageRecord.tokens)
213
+ return;
214
+ this.currentSession.totalTokens.input += messageRecord.tokens.input;
215
+ this.currentSession.totalTokens.output += messageRecord.tokens.output;
216
+ this.currentSession.totalTokens.cached += messageRecord.tokens.cached;
217
+ this.currentSession.totalTokens.total += messageRecord.tokens.total;
218
+ if (messageRecord.toolCalls) {
219
+ this.currentSession.toolCallCount += messageRecord.toolCalls.length;
220
+ }
221
+ }
222
+ generateSessionId() {
223
+ return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
224
+ }
225
+ generateMessageId() {
226
+ return `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
227
+ }
228
+ generateToolCallId() {
229
+ return `tool-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
230
+ }
231
+ async exportSession(session) {
232
+ // Ensure output directory exists
233
+ await this.ensureDirectoryExists();
234
+ const filename = `chat-session-${session.sessionId}-${Date.now()}.${this.exportFormat}`;
235
+ const filepath = path.join(this.outputDirectory, filename);
236
+ // Update end time
237
+ session.endTime = new Date().toISOString();
238
+ let content;
239
+ switch (this.exportFormat) {
240
+ case 'json':
241
+ content = JSON.stringify(session, null, 2);
242
+ break;
243
+ case 'txt':
244
+ content = this.formatAsText(session);
245
+ break;
246
+ case 'csv':
247
+ content = this.formatAsCSV(session);
248
+ break;
249
+ default:
250
+ content = JSON.stringify(session, null, 2);
251
+ }
252
+ await fs.writeFile(filepath, content, 'utf-8');
253
+ return filepath;
254
+ }
255
+ async ensureDirectoryExists() {
256
+ try {
257
+ await fs.access(this.outputDirectory);
258
+ }
259
+ catch {
260
+ await fs.mkdir(this.outputDirectory, { recursive: true });
261
+ }
262
+ }
263
+ formatAsText(session) {
264
+ const lines = [];
265
+ lines.push(`Chat Session: ${session.sessionId}`);
266
+ lines.push(`Start Time: ${session.startTime}`);
267
+ lines.push(`End Time: ${session.endTime || 'Ongoing'}`);
268
+ lines.push(`Total Messages: ${session.messages.length}`);
269
+ lines.push(`Total Tokens: ${session.totalTokens.total}`);
270
+ lines.push(`Tool Calls: ${session.toolCallCount}`);
271
+ lines.push('---');
272
+ for (const message of session.messages) {
273
+ lines.push(`[${message.timestamp}] ${message.role.toUpperCase()}: ${message.content}`);
274
+ if (message.toolCalls) {
275
+ for (const tool of message.toolCalls) {
276
+ lines.push(` 🔧 ${tool.name}(${JSON.stringify(tool.args)})`);
277
+ }
278
+ }
279
+ lines.push('');
280
+ }
281
+ return lines.join('\n');
282
+ }
283
+ formatAsCSV(session) {
284
+ var _a, _b;
285
+ const headers = ['timestamp', 'role', 'content', 'tokens', 'tool_calls'];
286
+ const rows = [headers.join(',')];
287
+ for (const message of session.messages) {
288
+ const row = [
289
+ message.timestamp,
290
+ message.role,
291
+ `"${message.content.replace(/"/g, '""')}"`, // Escape quotes
292
+ ((_a = message.tokens) === null || _a === void 0 ? void 0 : _a.total) || 0,
293
+ ((_b = message.toolCalls) === null || _b === void 0 ? void 0 : _b.length) || 0
294
+ ];
295
+ rows.push(row.join(','));
296
+ }
297
+ return rows.join('\n');
298
+ }
299
+ // Public methods for session management
300
+ async finalizeSession() {
301
+ if (!this.currentSession)
302
+ return null;
303
+ try {
304
+ const exportPath = await this.exportSession(this.currentSession);
305
+ this.sessions.push(this.currentSession);
306
+ this.currentSession = null;
307
+ this.messageCount = 0;
308
+ return exportPath;
309
+ }
310
+ catch (error) {
311
+ console.error('[ChatRecording] Error finalizing session:', error);
312
+ return null;
313
+ }
314
+ }
315
+ getCurrentSession() {
316
+ return this.currentSession;
317
+ }
318
+ getSessionStats() {
319
+ var _a, _b;
320
+ const totalMessages = this.sessions.reduce((sum, session) => sum + session.messages.length, 0) +
321
+ (((_a = this.currentSession) === null || _a === void 0 ? void 0 : _a.messages.length) || 0);
322
+ return {
323
+ currentSessionMessages: ((_b = this.currentSession) === null || _b === void 0 ? void 0 : _b.messages.length) || 0,
324
+ totalSessions: this.sessions.length + (this.currentSession ? 1 : 0),
325
+ totalMessages
326
+ };
327
+ }
328
+ }
329
+ exports.ChatRecordingProcessor = ChatRecordingProcessor;
@@ -0,0 +1,40 @@
1
+ import { BaseProcessor, ProcessorInput, ProcessorOutput } from '../../processor';
2
+ export interface ContextInfo {
3
+ projectContext?: string;
4
+ ideContext?: any;
5
+ directoryContext?: string;
6
+ contextAdded: boolean;
7
+ }
8
+ export interface ContextManagementProcessorOptions {
9
+ enableProjectContext?: boolean;
10
+ enableIdeContext?: boolean;
11
+ enableDirectoryContext?: boolean;
12
+ forceFullContext?: boolean;
13
+ contextThreshold?: number;
14
+ }
15
+ export declare class ContextManagementProcessor extends BaseProcessor {
16
+ private readonly enableProjectContext;
17
+ private readonly enableIdeContext;
18
+ private readonly enableDirectoryContext;
19
+ private readonly forceFullContext;
20
+ private readonly contextThreshold;
21
+ private lastSentIdeContext;
22
+ private contextAddedToHistory;
23
+ constructor(options?: ContextManagementProcessorOptions);
24
+ processInput(input: ProcessorInput): Promise<ProcessorOutput[]>;
25
+ private collectContext;
26
+ private getProjectContext;
27
+ private getIdeContext;
28
+ private getDirectoryContext;
29
+ private detectIdeType;
30
+ private getOpenFiles;
31
+ private getActiveFile;
32
+ private addContextToMessage;
33
+ resetContext(): void;
34
+ forceContextRefresh(): void;
35
+ setContextThreshold(threshold: number): void;
36
+ enableProjectContextForSession(): void;
37
+ disableProjectContextForSession(): void;
38
+ enableIdeContextForSession(): void;
39
+ disableIdeContextForSession(): void;
40
+ }
@@ -0,0 +1,272 @@
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;
@@ -0,0 +1,49 @@
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
+ }