@codebolt/agent 1.2.1 → 2.2.2

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 (183) hide show
  1. package/README.md +157 -66
  2. package/dist/builderpattern/agent.d.ts +86 -0
  3. package/dist/builderpattern/agent.js +324 -0
  4. package/dist/builderpattern/followupquestionbuilder.d.ts +75 -0
  5. package/dist/builderpattern/followupquestionbuilder.js +197 -0
  6. package/dist/builderpattern/index.d.ts +14 -0
  7. package/dist/builderpattern/index.js +23 -0
  8. package/dist/builderpattern/llmoutputhandler.d.ts +102 -0
  9. package/dist/builderpattern/llmoutputhandler.js +452 -0
  10. package/dist/builderpattern/promptbuilder.d.ts +382 -0
  11. package/dist/builderpattern/promptbuilder.js +805 -0
  12. package/dist/builderpattern/systemprompt.d.ts +20 -0
  13. package/dist/builderpattern/systemprompt.js +48 -0
  14. package/dist/builderpattern/taskInstruction.d.ts +37 -0
  15. package/dist/builderpattern/taskInstruction.js +57 -0
  16. package/dist/builderpattern/usermessage.d.ts +70 -0
  17. package/dist/builderpattern/usermessage.js +123 -0
  18. package/dist/composablepattern/agent.d.ts +169 -0
  19. package/dist/composablepattern/agent.js +598 -0
  20. package/dist/composablepattern/codebolt-storage.d.ts +67 -0
  21. package/dist/composablepattern/codebolt-storage.js +320 -0
  22. package/dist/composablepattern/document.d.ts +149 -0
  23. package/dist/composablepattern/document.js +405 -0
  24. package/dist/composablepattern/examples/codebolt-integration-example.d.ts +12 -0
  25. package/dist/composablepattern/examples/codebolt-integration-example.js +218 -0
  26. package/dist/composablepattern/examples/codebolt-storage-example.d.ts +40 -0
  27. package/dist/composablepattern/examples/codebolt-storage-example.js +223 -0
  28. package/dist/composablepattern/examples/custom-steps-example.d.ts +20 -0
  29. package/dist/composablepattern/examples/custom-steps-example.js +455 -0
  30. package/dist/composablepattern/examples/document-agent.d.ts +17 -0
  31. package/dist/composablepattern/examples/document-agent.js +107 -0
  32. package/dist/composablepattern/examples/simple-codebolt-integration.d.ts +8 -0
  33. package/dist/composablepattern/examples/simple-codebolt-integration.js +164 -0
  34. package/dist/composablepattern/examples/weather-agent.d.ts +18 -0
  35. package/dist/composablepattern/examples/weather-agent.js +86 -0
  36. package/dist/composablepattern/examples/workflow-example.d.ts +12 -0
  37. package/dist/composablepattern/examples/workflow-example.js +463 -0
  38. package/dist/composablepattern/index.d.ts +63 -0
  39. package/dist/composablepattern/index.js +115 -0
  40. package/dist/composablepattern/memory.d.ts +89 -0
  41. package/dist/composablepattern/memory.js +141 -0
  42. package/dist/composablepattern/tool.d.ts +84 -0
  43. package/dist/composablepattern/tool.js +260 -0
  44. package/dist/composablepattern/types.d.ts +194 -0
  45. package/dist/composablepattern/types.js +6 -0
  46. package/dist/composablepattern/user-context.d.ts +214 -0
  47. package/dist/composablepattern/user-context.js +275 -0
  48. package/dist/composablepattern/workflow.d.ts +388 -0
  49. package/dist/composablepattern/workflow.js +562 -0
  50. package/dist/processor/agent/agentStep.d.ts +49 -0
  51. package/dist/processor/agent/agentStep.js +241 -0
  52. package/dist/processor/agent/toolExecutor.d.ts +19 -0
  53. package/dist/processor/agent/toolExecutor.js +90 -0
  54. package/dist/processor/index.d.ts +7 -0
  55. package/dist/processor/index.js +36 -0
  56. package/dist/processor/messageModifiers/baseMessageModifier.d.ts +20 -0
  57. package/dist/processor/messageModifiers/baseMessageModifier.js +55 -0
  58. package/dist/processor/processors/baseProcessor.d.ts +14 -0
  59. package/dist/processor/processors/baseProcessor.js +29 -0
  60. package/dist/processor/tools/baseTool.d.ts +10 -0
  61. package/dist/processor/tools/baseTool.js +20 -0
  62. package/dist/processor/tools/toolList.d.ts +9 -0
  63. package/dist/processor/tools/toolList.js +22 -0
  64. package/dist/processor/types/interfaces.d.ts +94 -0
  65. package/dist/processor/types/interfaces.js +2 -0
  66. package/dist/processor-pieces/base/baseMessageModifier.d.ts +12 -0
  67. package/dist/processor-pieces/base/baseMessageModifier.js +15 -0
  68. package/dist/processor-pieces/base/basePostInferenceProcessor.d.ts +13 -0
  69. package/dist/processor-pieces/base/basePostInferenceProcessor.js +18 -0
  70. package/dist/processor-pieces/base/basePostToolCallProcessor.d.ts +15 -0
  71. package/dist/processor-pieces/base/basePostToolCallProcessor.js +25 -0
  72. package/dist/processor-pieces/base/basePreInferenceProcessor.d.ts +12 -0
  73. package/dist/processor-pieces/base/basePreInferenceProcessor.js +17 -0
  74. package/dist/processor-pieces/base/basePreToolCallProcessor.d.ts +18 -0
  75. package/dist/processor-pieces/base/basePreToolCallProcessor.js +66 -0
  76. package/dist/processor-pieces/base/index.d.ts +9 -0
  77. package/dist/processor-pieces/base/index.js +18 -0
  78. package/dist/processor-pieces/index.d.ts +1 -0
  79. package/dist/processor-pieces/index.js +59 -0
  80. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +22 -0
  81. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +144 -0
  82. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.d.ts +13 -0
  83. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +68 -0
  84. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.d.ts +25 -0
  85. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +453 -0
  86. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +15 -0
  87. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +75 -0
  88. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +11 -0
  89. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +46 -0
  90. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.d.ts +18 -0
  91. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +104 -0
  92. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.d.ts +23 -0
  93. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +173 -0
  94. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.d.ts +14 -0
  95. package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +130 -0
  96. package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +36 -0
  97. package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +418 -0
  98. package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +26 -0
  99. package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +260 -0
  100. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +12 -0
  101. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +60 -0
  102. package/dist/processor-pieces/messageModifiers/ideContextModifier.d.ts +34 -0
  103. package/dist/processor-pieces/messageModifiers/ideContextModifier.js +157 -0
  104. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +18 -0
  105. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +222 -0
  106. package/dist/processor-pieces/messageModifiers/index.d.ts +11 -0
  107. package/dist/processor-pieces/messageModifiers/index.js +26 -0
  108. package/dist/processor-pieces/messageModifiers/memoryImportModifier.d.ts +15 -0
  109. package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +129 -0
  110. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.d.ts +20 -0
  111. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +152 -0
  112. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +22 -0
  113. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +194 -0
  114. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.d.ts +29 -0
  115. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +174 -0
  116. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +1 -0
  117. package/dist/processor-pieces/postToolCallProcessors/index.js +2 -0
  118. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.d.ts +25 -0
  119. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +225 -0
  120. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.d.ts +35 -0
  121. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +255 -0
  122. package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -0
  123. package/dist/processor-pieces/preInferenceProcessors/index.js +2 -0
  124. package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +1 -0
  125. package/dist/processor-pieces/pretoolCallProcessors/index.js +2 -0
  126. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.d.ts +41 -0
  127. package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.js +197 -0
  128. package/dist/processor-pieces/processors/chatCompressionProcessor.d.ts +26 -0
  129. package/dist/processor-pieces/processors/chatCompressionProcessor.js +90 -0
  130. package/dist/processor-pieces/processors/chatRecordingProcessor.d.ts +81 -0
  131. package/dist/processor-pieces/processors/chatRecordingProcessor.js +329 -0
  132. package/dist/processor-pieces/processors/contextManagementProcessor.d.ts +40 -0
  133. package/dist/processor-pieces/processors/contextManagementProcessor.js +305 -0
  134. package/dist/processor-pieces/processors/loopDetectionProcessor.d.ts +30 -0
  135. package/dist/processor-pieces/processors/loopDetectionProcessor.js +137 -0
  136. package/dist/processor-pieces/processors/responseValidationProcessor.d.ts +30 -0
  137. package/dist/processor-pieces/processors/responseValidationProcessor.js +228 -0
  138. package/dist/processor-pieces/processors/telemetryProcessor.d.ts +99 -0
  139. package/dist/processor-pieces/processors/telemetryProcessor.js +311 -0
  140. package/dist/processor-pieces/processors/tokenManagementProcessor.d.ts +37 -0
  141. package/dist/processor-pieces/processors/tokenManagementProcessor.js +178 -0
  142. package/dist/processor-pieces/processors/toolExecutionProcessor.d.ts +43 -0
  143. package/dist/processor-pieces/processors/toolExecutionProcessor.js +207 -0
  144. package/dist/processor-pieces/tools/fileTools.d.ts +26 -0
  145. package/dist/processor-pieces/tools/fileTools.js +162 -0
  146. package/dist/processor-pieces/utils/messageModifierHelper.d.ts +4 -0
  147. package/dist/processor-pieces/utils/messageModifierHelper.js +58 -0
  148. package/dist/types/commonTypes.d.ts +4 -0
  149. package/dist/types/processorTypes.d.ts +67 -0
  150. package/dist/types/processorTypes.js +58 -0
  151. package/dist/unified/agent/agent.d.ts +17 -0
  152. package/dist/unified/agent/agent.js +79 -0
  153. package/dist/unified/agent/team.d.ts +2 -0
  154. package/dist/unified/agent/team.js +6 -0
  155. package/dist/unified/agent/tools.d.ts +44 -0
  156. package/dist/unified/agent/tools.js +487 -0
  157. package/dist/unified/agent/workflow.d.ts +24 -0
  158. package/dist/unified/agent/workflow.js +275 -0
  159. package/dist/unified/agent/workflowControls.d.ts +11 -0
  160. package/dist/unified/agent/workflowControls.js +20 -0
  161. package/dist/unified/agent/workflowSteps.d.ts +63 -0
  162. package/dist/unified/agent/workflowSteps.js +284 -0
  163. package/dist/unified/base/agentStep.d.ts +32 -0
  164. package/dist/unified/base/agentStep.js +96 -0
  165. package/dist/unified/base/create/createInitialPromptGenerators.d.ts +5 -0
  166. package/dist/unified/base/create/createInitialPromptGenerators.js +17 -0
  167. package/dist/unified/base/index.d.ts +5 -0
  168. package/dist/unified/base/index.js +13 -0
  169. package/dist/unified/base/initialPromptGenerator.d.ts +48 -0
  170. package/dist/unified/base/initialPromptGenerator.js +118 -0
  171. package/dist/unified/base/responseExecutor.d.ts +36 -0
  172. package/dist/unified/base/responseExecutor.js +283 -0
  173. package/dist/unified/index.d.ts +18 -0
  174. package/dist/unified/index.js +42 -0
  175. package/dist/unified/team/team.d.ts +1 -0
  176. package/dist/unified/team/team.js +2 -0
  177. package/dist/unified/types/libTypes.d.ts +378 -0
  178. package/dist/unified/types/libTypes.js +6 -0
  179. package/dist/unified/types/types.d.ts +212 -0
  180. package/dist/unified/types/types.js +43 -0
  181. package/dist/unified/utils/utils.d.ts +40 -0
  182. package/dist/unified/utils/utils.js +219 -0
  183. package/package.json +29 -7
@@ -0,0 +1,104 @@
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.ChatHistoryMessageModifier = void 0;
7
+ const base_1 = require("../base");
8
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
+ // Using MessageObject from SDK types for chat history messages
10
+ class ChatHistoryMessageModifier extends base_1.BaseMessageModifier {
11
+ constructor(options = {}) {
12
+ super({ context: options });
13
+ this.enableChatHistory = options.enableChatHistory !== false;
14
+ this.maxHistoryMessages = options.maxHistoryMessages || 20;
15
+ this.includeSystemMessages = options.includeSystemMessages !== false;
16
+ }
17
+ async modify(originalRequest, createdMessage) {
18
+ try {
19
+ if (!this.enableChatHistory) {
20
+ return createdMessage;
21
+ }
22
+ // Get chat history using the thread ID from the original request
23
+ const chatHistory = await this.getChatHistory(originalRequest.threadId);
24
+ if (!chatHistory || chatHistory.length === 0) {
25
+ return createdMessage;
26
+ }
27
+ // Directly use the chat history messages - they're already in MessageObject format
28
+ return {
29
+ message: {
30
+ ...createdMessage.message,
31
+ messages: [...chatHistory, ...createdMessage.message.messages]
32
+ },
33
+ metadata: {
34
+ ...createdMessage.metadata,
35
+ chatHistoryAdded: true,
36
+ chatHistoryCount: chatHistory.length,
37
+ threadId: originalRequest.threadId
38
+ }
39
+ };
40
+ }
41
+ catch (error) {
42
+ console.error('Error in ChatHistoryMessageModifier:', error);
43
+ // Return original message if chat history fails to avoid breaking the flow
44
+ return createdMessage;
45
+ }
46
+ }
47
+ async getChatHistory(threadId) {
48
+ var _a, _b, _c, _d;
49
+ try {
50
+ const response = await codeboltjs_1.default.chat.getChatHistory(threadId);
51
+ // Check if response has messages array
52
+ if (!(response === null || response === void 0 ? void 0 : response.chats) || !((_a = response === null || response === void 0 ? void 0 : response.chats) === null || _a === void 0 ? void 0 : _a.messages) || !Array.isArray((_b = response === null || response === void 0 ? void 0 : response.chats) === null || _b === void 0 ? void 0 : _b.messages) || ((_c = response === null || response === void 0 ? void 0 : response.chats) === null || _c === void 0 ? void 0 : _c.messages.length) === 0) {
53
+ return [];
54
+ }
55
+ let historyMessages = (_d = response === null || response === void 0 ? void 0 : response.chats) === null || _d === void 0 ? void 0 : _d.messages;
56
+ // Thread filtering is now handled by the API directly via threadId parameter
57
+ // Filter out system messages if not included
58
+ if (!this.includeSystemMessages) {
59
+ historyMessages = historyMessages.filter((msg) => msg.role !== 'system');
60
+ }
61
+ // Limit the number of messages
62
+ // will do it later
63
+ if (false) {
64
+ historyMessages = historyMessages.slice(-this.maxHistoryMessages);
65
+ }
66
+ // Check if the last message is an assistant message with tool_calls
67
+ // If so, add tool response messages for each tool_call
68
+ const lastMessage = historyMessages[historyMessages.length - 1];
69
+ if (lastMessage &&
70
+ lastMessage.role === 'assistant' &&
71
+ lastMessage.tool_calls &&
72
+ Array.isArray(lastMessage.tool_calls) &&
73
+ lastMessage.tool_calls.length > 0) {
74
+ // Add tool response messages for each tool_call
75
+ const toolResponseMessages = [];
76
+ for (const toolCall of lastMessage.tool_calls) {
77
+ toolResponseMessages.push({
78
+ role: 'tool',
79
+ content: `Tool call "${toolCall.function.name}" was not executed. This appears to be from a previous incomplete conversation. The tool was called with arguments: ${toolCall.function.arguments}`,
80
+ tool_call_id: toolCall.id
81
+ });
82
+ }
83
+ // Return original messages + tool responses + context message
84
+ return [...historyMessages, ...toolResponseMessages];
85
+ }
86
+ // Add a system message to indicate this is previous conversation
87
+ const contextMessage = {
88
+ role: 'user',
89
+ content: '--- End of previous conversation history ---\n\nThe above messages are from a previous conversation. Any incomplete tool calls have been marked as not executed. You should now respond to the current user message.'
90
+ };
91
+ historyMessages = [...historyMessages, contextMessage];
92
+ // Return messages as-is if no tool_calls in last message
93
+ return historyMessages;
94
+ }
95
+ catch (error) {
96
+ console.error('Error retrieving chat history:', error);
97
+ return [];
98
+ }
99
+ }
100
+ setMaxHistoryMessages(max) {
101
+ this.maxHistoryMessages = max;
102
+ }
103
+ }
104
+ exports.ChatHistoryMessageModifier = ChatHistoryMessageModifier;
@@ -0,0 +1,23 @@
1
+ import { ProcessedMessage } from "@codebolt/types/agent";
2
+ import { BaseMessageModifier } from "../base";
3
+ import { FlatUserMessage } from "@codebolt/types/sdk";
4
+ export interface ChatRecordingOptions {
5
+ enableRecording?: boolean;
6
+ recordingPath?: string;
7
+ maxRecordingSize?: number;
8
+ includeMetadata?: boolean;
9
+ recordingFormat?: 'json' | 'markdown';
10
+ }
11
+ export declare class ChatRecordingModifier extends BaseMessageModifier {
12
+ private readonly options;
13
+ private recordingFile?;
14
+ constructor(options?: ChatRecordingOptions);
15
+ modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
16
+ private initializeRecording;
17
+ private recordMessages;
18
+ private writeRecord;
19
+ startRecording(customPath?: string): void;
20
+ stopRecording(): void;
21
+ getRecordingFile(): string | undefined;
22
+ isRecording(): boolean;
23
+ }
@@ -0,0 +1,173 @@
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.ChatRecordingModifier = void 0;
37
+ const base_1 = require("../base");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ class ChatRecordingModifier extends base_1.BaseMessageModifier {
41
+ constructor(options = {}) {
42
+ super();
43
+ this.options = {
44
+ enableRecording: options.enableRecording || false,
45
+ recordingPath: options.recordingPath || path.join(process.cwd(), '.chat-recordings'),
46
+ maxRecordingSize: options.maxRecordingSize || 10 * 1024 * 1024, // 10MB
47
+ includeMetadata: options.includeMetadata !== false,
48
+ recordingFormat: options.recordingFormat || 'json'
49
+ };
50
+ if (this.options.enableRecording) {
51
+ this.initializeRecording();
52
+ }
53
+ }
54
+ async modify(originalRequest, createdMessage) {
55
+ try {
56
+ if (!this.options.enableRecording || !this.recordingFile) {
57
+ return createdMessage;
58
+ }
59
+ // Record the conversation
60
+ await this.recordMessages(createdMessage, originalRequest);
61
+ return Promise.resolve({
62
+ ...createdMessage,
63
+ metadata: {
64
+ ...createdMessage.metadata,
65
+ chatRecorded: true,
66
+ recordingFile: this.recordingFile
67
+ }
68
+ });
69
+ }
70
+ catch (error) {
71
+ console.error('Error in ChatRecordingModifier:', error);
72
+ return createdMessage;
73
+ }
74
+ }
75
+ initializeRecording() {
76
+ try {
77
+ // Ensure recording directory exists
78
+ if (!fs.existsSync(this.options.recordingPath)) {
79
+ fs.mkdirSync(this.options.recordingPath, { recursive: true });
80
+ }
81
+ // Create recording file with timestamp
82
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
83
+ const extension = this.options.recordingFormat === 'markdown' ? 'md' : 'jsonl';
84
+ this.recordingFile = path.join(this.options.recordingPath, `chat-${timestamp}.${extension}`);
85
+ // Initialize file with header
86
+ if (this.options.recordingFormat === 'markdown') {
87
+ fs.writeFileSync(this.recordingFile, `# Chat Recording\n\nStarted: ${new Date().toISOString()}\n\n---\n\n`);
88
+ }
89
+ }
90
+ catch (error) {
91
+ console.error('Failed to initialize chat recording:', error);
92
+ this.recordingFile = undefined;
93
+ }
94
+ }
95
+ async recordMessages(createdMessage, originalRequest) {
96
+ var _a, _b;
97
+ if (!this.recordingFile)
98
+ return;
99
+ try {
100
+ // Check file size before writing
101
+ if (fs.existsSync(this.recordingFile)) {
102
+ const stats = fs.statSync(this.recordingFile);
103
+ if (stats.size > this.options.maxRecordingSize) {
104
+ console.warn(`Chat recording file ${this.recordingFile} exceeds maximum size. Stopping recording.`);
105
+ return;
106
+ }
107
+ }
108
+ const timestamp = new Date().toISOString();
109
+ // Record each message
110
+ for (const message of createdMessage.message.messages) {
111
+ const record = {
112
+ timestamp,
113
+ messageId: (_a = createdMessage.metadata) === null || _a === void 0 ? void 0 : _a.messageId,
114
+ threadId: (_b = createdMessage.metadata) === null || _b === void 0 ? void 0 : _b.threadId,
115
+ role: message.role,
116
+ content: typeof message.content === 'string' ? message.content : JSON.stringify(message.content)
117
+ };
118
+ if (this.options.includeMetadata) {
119
+ record.metadata = {
120
+ originalRequest: {
121
+ userMessage: originalRequest.userMessage,
122
+ messageId: originalRequest.messageId,
123
+ threadId: originalRequest.threadId
124
+ },
125
+ processedMetadata: createdMessage.metadata
126
+ };
127
+ }
128
+ await this.writeRecord(record);
129
+ }
130
+ }
131
+ catch (error) {
132
+ console.error('Error recording chat messages:', error);
133
+ }
134
+ }
135
+ async writeRecord(record) {
136
+ if (!this.recordingFile)
137
+ return;
138
+ try {
139
+ if (this.options.recordingFormat === 'markdown') {
140
+ const content = `## ${record.role.toUpperCase()} - ${record.timestamp}\n\n${record.content}\n\n---\n\n`;
141
+ fs.appendFileSync(this.recordingFile, content);
142
+ }
143
+ else {
144
+ const jsonLine = JSON.stringify(record) + '\n';
145
+ fs.appendFileSync(this.recordingFile, jsonLine);
146
+ }
147
+ }
148
+ catch (error) {
149
+ console.error('Error writing chat record:', error);
150
+ }
151
+ }
152
+ startRecording(customPath) {
153
+ this.options.enableRecording = true;
154
+ if (customPath) {
155
+ this.options.recordingPath = customPath;
156
+ }
157
+ this.initializeRecording();
158
+ }
159
+ stopRecording() {
160
+ this.options.enableRecording = false;
161
+ if (this.recordingFile && this.options.recordingFormat === 'markdown') {
162
+ fs.appendFileSync(this.recordingFile, `\n---\n\nRecording ended: ${new Date().toISOString()}\n`);
163
+ }
164
+ this.recordingFile = undefined;
165
+ }
166
+ getRecordingFile() {
167
+ return this.recordingFile;
168
+ }
169
+ isRecording() {
170
+ return (this.options.enableRecording || false) && !!this.recordingFile;
171
+ }
172
+ }
173
+ exports.ChatRecordingModifier = ChatRecordingModifier;
@@ -0,0 +1,14 @@
1
+ import { ProcessedMessage } from "@codebolt/types/agent";
2
+ import { BaseMessageModifier } from "../base";
3
+ import { FlatUserMessage } from "@codebolt/types/sdk";
4
+ export interface CoreSystemPromptOptions {
5
+ customSystemPrompt?: string;
6
+ userMemory?: string;
7
+ }
8
+ export declare class CoreSystemPromptModifier extends BaseMessageModifier {
9
+ private readonly options;
10
+ constructor(options?: CoreSystemPromptOptions);
11
+ modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
12
+ private getCoreSystemPrompt;
13
+ private getDefaultSystemPrompt;
14
+ }
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CoreSystemPromptModifier = void 0;
4
+ const base_1 = require("../base");
5
+ class CoreSystemPromptModifier extends base_1.BaseMessageModifier {
6
+ constructor(options = {}) {
7
+ super();
8
+ this.options = options;
9
+ }
10
+ modify(originalRequest, createdMessage) {
11
+ var _a;
12
+ // Get user memory from metadata or options
13
+ const userMemory = ((_a = createdMessage.metadata) === null || _a === void 0 ? void 0 : _a.userMemory) || this.options.userMemory;
14
+ const systemPrompt = this.options.customSystemPrompt || this.getCoreSystemPrompt(userMemory);
15
+ const systemMessage = {
16
+ role: 'system',
17
+ content: systemPrompt
18
+ };
19
+ // Find existing system message or add new one
20
+ const messages = [...createdMessage.message.messages];
21
+ const systemMessageIndex = messages.findIndex(msg => msg.role === 'system');
22
+ if (systemMessageIndex !== -1) {
23
+ // Replace existing system message
24
+ messages[systemMessageIndex] = systemMessage;
25
+ }
26
+ else {
27
+ // Add new system message at the beginning
28
+ messages.unshift(systemMessage);
29
+ }
30
+ return Promise.resolve({
31
+ message: {
32
+ ...createdMessage.message,
33
+ messages
34
+ },
35
+ metadata: {
36
+ ...createdMessage.metadata,
37
+ coreSystemPromptAdded: true,
38
+ systemPromptSource: this.options.customSystemPrompt ? 'custom' : 'default',
39
+ hasUserMemory: !!userMemory
40
+ }
41
+ });
42
+ }
43
+ getCoreSystemPrompt(userMemory) {
44
+ const basePrompt = this.getDefaultSystemPrompt();
45
+ // Add user memory with separator if provided (exactly like gemini-cli)
46
+ const memorySuffix = userMemory && userMemory.trim().length > 0
47
+ ? `\n\n---\n\n${userMemory.trim()}`
48
+ : '';
49
+ return `${basePrompt}${memorySuffix}`;
50
+ }
51
+ getDefaultSystemPrompt() {
52
+ return `
53
+ You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
54
+
55
+ # Core Mandates
56
+
57
+ - **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
58
+ - **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
59
+ - **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
60
+ - **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
61
+ - **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
62
+ - **Proactiveness:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions.
63
+ - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
64
+ - **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
65
+ - **Path Construction:** Before using any file system tool, you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
66
+ - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
67
+
68
+ # Primary Workflows
69
+
70
+ ## Software Engineering Tasks
71
+ When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
72
+ 1. **Understand:** Think about the user's request and the relevant codebase context. Use search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use file reading tools to understand context and validate any assumptions you may have.
73
+ 2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should try to use a self-verification loop by writing unit tests if relevant to the task. Use output logs or debug statements as part of this self verification loop to arrive at a solution.
74
+ 3. **Implement:** Use the available tools to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
75
+ 4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
76
+ 5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
77
+
78
+ ## New Applications
79
+
80
+ **Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application.
81
+
82
+ 1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
83
+ 2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
84
+ - When key technologies aren't specified, prefer the following:
85
+ - **Websites (Frontend):** React (JavaScript/TypeScript) with Bootstrap CSS, incorporating Material Design principles for UI/UX.
86
+ - **Back-End APIs:** Node.js with Express.js (JavaScript/TypeScript) or Python with FastAPI.
87
+ - **Full-stack:** Next.js (React/Node.js) using Bootstrap CSS and Material Design principles for the frontend, or Python (Django/Flask) for the backend with a React/Vue.js frontend styled with Bootstrap CSS and Material Design principles.
88
+ - **CLIs:** Python or Go.
89
+ - **Mobile App:** Compose Multiplatform (Kotlin Multiplatform) or Flutter (Dart) using Material Design libraries and principles, when sharing code between Android and iOS. Jetpack Compose (Kotlin JVM) with Material Design principles or SwiftUI (Swift) for native apps targeted at either Android or iOS, respectively.
90
+ - **3d Games:** HTML/CSS/JavaScript with Three.js.
91
+ - **2d Games:** HTML/CSS/JavaScript.
92
+ 3. **User Approval:** Obtain user approval for the proposed plan.
93
+ 4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using shell commands for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
94
+ 5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
95
+ 6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.
96
+
97
+ # Operational Guidelines
98
+
99
+ ## Tone and Style (CLI Interaction)
100
+ - **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
101
+ - **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
102
+ - **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
103
+ - **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
104
+ - **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
105
+ - **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
106
+ - **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
107
+
108
+ ## Security and Safety Rules
109
+ - **Explain Critical Commands:** Before executing commands that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this).
110
+ - **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
111
+
112
+ ## Tool Usage
113
+ - **File Paths:** Always use absolute paths when referring to files with tools. Relative paths are not supported. You must provide an absolute path.
114
+ - **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
115
+ - **Command Execution:** Use shell tools for running shell commands, remembering the safety rule to explain modifying commands first.
116
+ - **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user.
117
+ - **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. \`git rebase -i\`). Use non-interactive versions of commands (e.g. \`npm init -y\` instead of \`npm init\`) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
118
+ - **Remembering Facts:** Use memory tools to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
119
+ - **Respect User Confirmations:** Most tool calls will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
120
+
121
+ ## Interaction Details
122
+ - **Help Command:** The user can use '/help' to display help information.
123
+ - **Feedback:** To report a bug or provide feedback, please use the /bug command.
124
+
125
+ # Final Reminder
126
+ Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use file reading tools to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
127
+ `.trim();
128
+ }
129
+ }
130
+ exports.CoreSystemPromptModifier = CoreSystemPromptModifier;
@@ -0,0 +1,36 @@
1
+ import { ProcessedMessage } from "@codebolt/types/agent";
2
+ import { BaseMessageModifier } from "../base";
3
+ import { FlatUserMessage } from "@codebolt/types/sdk";
4
+ export interface DirectoryContextOptions {
5
+ workspaceDirectories?: string[];
6
+ }
7
+ export declare class DirectoryContextModifier extends BaseMessageModifier {
8
+ private readonly options;
9
+ private gitignorePatterns;
10
+ private gitignoreRegexes;
11
+ constructor(options?: DirectoryContextOptions);
12
+ modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
13
+ private loadGitignorePatterns;
14
+ private parseGitignoreContent;
15
+ private isGitIgnored;
16
+ private shouldIgnoreFile;
17
+ /**
18
+ * Generates a string representation of a directory's structure,
19
+ * limiting the number of items displayed. Ignored folders are shown
20
+ * followed by '...' instead of their contents.
21
+ *
22
+ * @param directory The absolute or relative path to the directory.
23
+ * @param options Optional configuration settings.
24
+ * @returns A promise resolving to the formatted folder structure string.
25
+ */
26
+ private getFolderStructure;
27
+ private readFullStructure;
28
+ /**
29
+ * Reads the directory structure using BFS, respecting maxItems.
30
+ * @param node The current node in the reduced structure.
31
+ * @param indent The current indentation string.
32
+ * @param isLast Sibling indicator.
33
+ * @param builder Array to build the string lines.
34
+ */
35
+ private formatStructure;
36
+ }