@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,169 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ShellProcessorModifier = void 0;
4
- const base_1 = require("../base");
5
- const child_process_1 = require("child_process");
6
- const util_1 = require("util");
7
- class ShellProcessorModifier extends base_1.BaseMessageModifier {
8
- constructor(options = {}) {
9
- super();
10
- this.execAsync = (0, util_1.promisify)(child_process_1.exec);
11
- this.SHELL_TRIGGER = '!{';
12
- this.SHELL_CLOSE = '}';
13
- this.ARGS_PLACEHOLDER = '{{args}}';
14
- this.options = {
15
- enableShellExecution: options.enableShellExecution || false, // Disabled by default for security
16
- maxExecutionTime: options.maxExecutionTime || 10000, // 10 seconds
17
- allowedCommands: options.allowedCommands || ['ls', 'pwd', 'echo', 'cat', 'head', 'tail', 'grep', 'find', 'wc'],
18
- blockedCommands: options.blockedCommands || ['rm', 'del', 'format', 'sudo', 'su', 'chmod', 'chown', 'kill', 'killall'],
19
- workingDirectory: options.workingDirectory || process.cwd()
20
- };
21
- }
22
- async modify(originalRequest, createdMessage) {
23
- var _a;
24
- try {
25
- // Get the user message content to process
26
- const userMessage = createdMessage.message.messages.find(msg => msg.role === 'user');
27
- if (!userMessage || typeof userMessage.content !== 'string') {
28
- return createdMessage;
29
- }
30
- const content = userMessage.content;
31
- const args = ((_a = createdMessage.metadata) === null || _a === void 0 ? void 0 : _a.args) || '';
32
- // First, replace {{args}} placeholders
33
- let processedContent = content.replace(new RegExp(this.escapeRegex(this.ARGS_PLACEHOLDER), 'g'), args);
34
- // Then process shell injections if enabled
35
- if (this.options.enableShellExecution && processedContent.includes(this.SHELL_TRIGGER)) {
36
- processedContent = await this.processShellInjections(processedContent, args);
37
- }
38
- // If content was modified, update the message
39
- if (processedContent !== content) {
40
- const updatedMessages = createdMessage.message.messages.map(msg => {
41
- if (msg.role === 'user' && typeof msg.content === 'string' && msg.content === content) {
42
- return {
43
- ...msg,
44
- content: processedContent
45
- };
46
- }
47
- return msg;
48
- });
49
- return Promise.resolve({
50
- message: {
51
- ...createdMessage.message,
52
- messages: updatedMessages
53
- },
54
- metadata: {
55
- ...createdMessage.metadata,
56
- shellProcessed: true,
57
- argsReplaced: content.includes(this.ARGS_PLACEHOLDER)
58
- }
59
- });
60
- }
61
- return createdMessage;
62
- }
63
- catch (error) {
64
- console.error('Error in ShellProcessorModifier:', error);
65
- return createdMessage;
66
- }
67
- }
68
- async processShellInjections(content, args) {
69
- let processedContent = content;
70
- const injections = this.extractShellInjections(content);
71
- // Process injections in reverse order to maintain correct indices
72
- for (let i = injections.length - 1; i >= 0; i--) {
73
- const injection = injections[i];
74
- try {
75
- // Replace {{args}} in the command with shell-escaped args
76
- const command = injection.command.replace(new RegExp(this.escapeRegex(this.ARGS_PLACEHOLDER), 'g'), this.escapeShellArg(args));
77
- // Validate and execute command
78
- this.validateCommand(command);
79
- const result = await this.executeCommand(command);
80
- const replacement = result;
81
- processedContent = processedContent.substring(0, injection.startIndex) +
82
- replacement +
83
- processedContent.substring(injection.endIndex);
84
- }
85
- catch (error) {
86
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
87
- const replacement = `[Shell command error: ${errorMessage}]`;
88
- processedContent = processedContent.substring(0, injection.startIndex) +
89
- replacement +
90
- processedContent.substring(injection.endIndex);
91
- }
92
- }
93
- return processedContent;
94
- }
95
- extractShellInjections(content) {
96
- const injections = [];
97
- let searchIndex = 0;
98
- while (true) {
99
- const startIndex = content.indexOf(this.SHELL_TRIGGER, searchIndex);
100
- if (startIndex === -1)
101
- break;
102
- const contentStart = startIndex + this.SHELL_TRIGGER.length;
103
- const endIndex = content.indexOf(this.SHELL_CLOSE, contentStart);
104
- if (endIndex === -1) {
105
- // No closing brace found, skip this occurrence
106
- searchIndex = contentStart;
107
- continue;
108
- }
109
- const command = content.substring(contentStart, endIndex).trim();
110
- if (command.length > 0) {
111
- injections.push({
112
- startIndex,
113
- endIndex: endIndex + this.SHELL_CLOSE.length,
114
- command
115
- });
116
- }
117
- searchIndex = endIndex + this.SHELL_CLOSE.length;
118
- }
119
- return injections;
120
- }
121
- validateCommand(command) {
122
- if (!this.options.enableShellExecution) {
123
- throw new Error('Shell execution is disabled');
124
- }
125
- // Extract the base command (first word)
126
- const baseCommand = command.trim().split(/\s+/)[0];
127
- // Check blocked commands
128
- if (this.options.blockedCommands.some(blocked => baseCommand.includes(blocked))) {
129
- throw new Error(`Command '${baseCommand}' is blocked for security reasons`);
130
- }
131
- // Check allowed commands (if allowlist is defined)
132
- if (this.options.allowedCommands.length > 0 &&
133
- !this.options.allowedCommands.some(allowed => baseCommand.includes(allowed))) {
134
- throw new Error(`Command '${baseCommand}' is not in the allowed commands list`);
135
- }
136
- // Additional security checks
137
- if (command.includes('&&') || command.includes('||') || command.includes(';') || command.includes('|')) {
138
- throw new Error('Command chaining and piping are not allowed');
139
- }
140
- }
141
- async executeCommand(command) {
142
- try {
143
- const { stdout, stderr } = await this.execAsync(command, {
144
- cwd: this.options.workingDirectory,
145
- timeout: this.options.maxExecutionTime,
146
- maxBuffer: 1024 * 1024 // 1MB buffer
147
- });
148
- let result = stdout;
149
- if (stderr) {
150
- result += `\n[stderr]: ${stderr}`;
151
- }
152
- return result || '[Command executed successfully with no output]';
153
- }
154
- catch (error) {
155
- if (error.killed && error.signal === 'SIGTERM') {
156
- throw new Error(`Command timed out after ${this.options.maxExecutionTime}ms`);
157
- }
158
- throw new Error(`Command failed: ${error.message}`);
159
- }
160
- }
161
- escapeShellArg(arg) {
162
- // Basic shell escaping - in production, use a proper shell escaping library
163
- return `"${arg.replace(/"/g, '\\"')}"`;
164
- }
165
- escapeRegex(str) {
166
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
167
- }
168
- }
169
- exports.ShellProcessorModifier = ShellProcessorModifier;
@@ -1,20 +0,0 @@
1
- import { ProcessedMessage } from "@codebolt/types/agent";
2
- import { BaseMessageModifier } from "../base";
3
- import { FlatUserMessage } from "@codebolt/types/sdk";
4
- export interface ToolInjectionOptions {
5
- toolsLocation?: 'Tool' | 'SystemMessage' | 'InsidePrompt';
6
- includeToolDescriptions?: boolean;
7
- maxToolsInMessage?: number;
8
- giveToolExamples?: boolean;
9
- maxToolExamples?: number;
10
- }
11
- export declare class ToolInjectionModifier extends BaseMessageModifier {
12
- private readonly options;
13
- constructor(options?: ToolInjectionOptions);
14
- modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
15
- private addToolsInsidePrompt;
16
- private addToolsAsSystemMessage;
17
- private addToolsAsToolCalls;
18
- private generateToolsInfo;
19
- private generateToolExample;
20
- }
@@ -1,152 +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.ToolInjectionModifier = void 0;
7
- const base_1 = require("../base");
8
- const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
- class ToolInjectionModifier extends base_1.BaseMessageModifier {
10
- constructor(options = {}) {
11
- super();
12
- this.options = {
13
- toolsLocation: options.toolsLocation || 'Tool',
14
- includeToolDescriptions: options.includeToolDescriptions !== false,
15
- maxToolsInMessage: options.maxToolsInMessage || 20,
16
- giveToolExamples: options.giveToolExamples || false,
17
- maxToolExamples: options.maxToolExamples || 2
18
- };
19
- }
20
- async modify(originalRequest, createdMessage) {
21
- try {
22
- const toolsResponse = await codeboltjs_1.default.mcp.listMcpFromServers(['codebolt']);
23
- const tools = (toolsResponse === null || toolsResponse === void 0 ? void 0 : toolsResponse.data) || [];
24
- if (tools.length === 0) {
25
- return createdMessage;
26
- }
27
- switch (this.options.toolsLocation) {
28
- case 'InsidePrompt':
29
- //@ts-ignore
30
- return this.addToolsInsidePrompt(createdMessage, tools);
31
- //@ts-ignore
32
- case 'SystemMessage':
33
- //@ts-ignore
34
- return this.addToolsAsSystemMessage(createdMessage, tools);
35
- case 'Tool':
36
- //@ts-ignore
37
- return this.addToolsAsToolCalls(createdMessage, tools);
38
- default:
39
- //@ts-ignore
40
- return this.addToolsAsToolCalls(createdMessage, tools);
41
- }
42
- }
43
- catch (error) {
44
- console.error('Error in ToolInjectionModifier:', error);
45
- return createdMessage;
46
- }
47
- }
48
- addToolsInsidePrompt(createdMessage, tools) {
49
- const toolsInfo = this.generateToolsInfo(tools);
50
- // Modify the last user message to include tools information
51
- const modifiedMessages = createdMessage.message.messages.map((message, index) => {
52
- if (message.role === 'user' && index === createdMessage.message.messages.length - 1) {
53
- return {
54
- ...message,
55
- content: `${message.content}\n\n--- Available Tools ---\n${toolsInfo}`
56
- };
57
- }
58
- return message;
59
- });
60
- return {
61
- message: {
62
- ...createdMessage.message,
63
- messages: modifiedMessages
64
- },
65
- metadata: {
66
- ...createdMessage.metadata,
67
- toolsInjected: true,
68
- toolsLocation: 'InsidePrompt',
69
- toolsCount: tools.length
70
- }
71
- };
72
- }
73
- addToolsAsSystemMessage(createdMessage, tools) {
74
- const toolsInfo = this.generateToolsInfo(tools);
75
- const toolsMessage = {
76
- role: 'system',
77
- content: `Available Tools:\n${toolsInfo}`
78
- };
79
- return {
80
- message: {
81
- ...createdMessage.message,
82
- messages: [toolsMessage, ...createdMessage.message.messages]
83
- },
84
- metadata: {
85
- ...createdMessage.metadata,
86
- toolsInjected: true,
87
- toolsLocation: 'SystemMessage',
88
- toolsCount: tools.length
89
- }
90
- };
91
- }
92
- addToolsAsToolCalls(createdMessage, tools) {
93
- return {
94
- message: {
95
- ...createdMessage.message,
96
- tools,
97
- tool_choice: 'auto'
98
- },
99
- metadata: {
100
- ...createdMessage.metadata,
101
- toolsInjected: true,
102
- toolsLocation: 'Tool',
103
- toolsCount: tools.length
104
- }
105
- };
106
- }
107
- generateToolsInfo(tools) {
108
- const toolsInfo = [];
109
- tools.slice(0, this.options.maxToolsInMessage).forEach((tool, index) => {
110
- let toolInfo = `${index + 1}. **${tool.function.name}**`;
111
- if (this.options.includeToolDescriptions && tool.function.description) {
112
- toolInfo += `\n Description: ${tool.function.description}`;
113
- }
114
- if (tool.function.parameters) {
115
- const params = typeof tool.function.parameters === 'object'
116
- ? Object.keys(tool.function.parameters).join(', ')
117
- : String(tool.function.parameters);
118
- toolInfo += `\n Parameters: ${params}`;
119
- }
120
- if (this.options.giveToolExamples && index < this.options.maxToolExamples) {
121
- const example = this.generateToolExample(tool);
122
- if (example) {
123
- toolInfo += `\n Example: ${example}`;
124
- }
125
- }
126
- toolsInfo.push(toolInfo);
127
- });
128
- return toolsInfo.join('\n\n');
129
- }
130
- generateToolExample(tool) {
131
- // Generate simple examples based on tool name
132
- const toolName = tool.function.name.toLowerCase();
133
- if (toolName.includes('read') && toolName.includes('file')) {
134
- return `${tool.function.name}({ filePath: "example.txt" })`;
135
- }
136
- if (toolName.includes('write') && toolName.includes('file')) {
137
- return `${tool.function.name}({ filePath: "output.txt", content: "Hello World" })`;
138
- }
139
- if (toolName.includes('delete') && toolName.includes('file')) {
140
- return `${tool.function.name}({ filePath: "temp.txt" })`;
141
- }
142
- if (toolName.includes('move') && toolName.includes('file')) {
143
- return `${tool.function.name}({ sourcePath: "old.txt", destinationPath: "new.txt" })`;
144
- }
145
- if (toolName.includes('copy') && toolName.includes('file')) {
146
- return `${tool.function.name}({ sourcePath: "source.txt", destinationPath: "copy.txt" })`;
147
- }
148
- // Generic example
149
- return `${tool.function.name}({ /* parameters */ })`;
150
- }
151
- }
152
- exports.ToolInjectionModifier = ToolInjectionModifier;
@@ -1,7 +0,0 @@
1
- import { ProcessedMessage } from "@codebolt/types/agent";
2
- import { BaseMessageModifier } from "../base";
3
- import { FlatUserMessage } from "@codebolt/types/sdk";
4
- export declare class AddCurrentDirectoryRootFilesModifier extends BaseMessageModifier {
5
- constructor();
6
- modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage, context?: Record<string, unknown>): Promise<ProcessedMessage>;
7
- }
@@ -1,93 +0,0 @@
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.AddCurrentDirectoryRootFilesModifier = void 0;
37
- const base_1 = require("../base");
38
- const fs = __importStar(require("fs"));
39
- class AddCurrentDirectoryRootFilesModifier extends base_1.BaseMessageModifier {
40
- constructor() {
41
- super();
42
- }
43
- async modify(originalRequest, createdMessage, context) {
44
- try {
45
- // Use current working directory
46
- const currentPath = process.cwd();
47
- // Read directory contents
48
- const files = await fs.promises.readdir(currentPath, { withFileTypes: true });
49
- // Format files list with type indicators
50
- const filesList = files
51
- .map(file => {
52
- return ` ${file.name}`;
53
- })
54
- .join('\n');
55
- const filesContent = filesList || 'No files found';
56
- // Find system message and append files list to it
57
- const messages = [...createdMessage.message.messages];
58
- const systemMessageIndex = messages.findIndex(message => message.role === 'system');
59
- if (systemMessageIndex !== -1) {
60
- // Update existing system message
61
- messages[systemMessageIndex] = {
62
- ...messages[systemMessageIndex],
63
- content: `${messages[systemMessageIndex].content}\n\nCurrent directory root files:\n\n${filesContent}`
64
- };
65
- }
66
- else {
67
- // Add new system message if none exists
68
- messages.unshift({
69
- role: 'system',
70
- content: `Current directory root files:\n\n${filesContent}`
71
- });
72
- }
73
- // Return updated message
74
- return {
75
- message: {
76
- ...createdMessage.message,
77
- messages
78
- },
79
- metadata: {
80
- ...createdMessage.metadata,
81
- currentDirectoryFilesAdded: true,
82
- currentDirectoryPath: currentPath
83
- }
84
- };
85
- }
86
- catch (error) {
87
- console.error('Error in AddCurrentDirectoryRootFilesModifier:', error);
88
- // Return original message if there's an error
89
- return createdMessage;
90
- }
91
- }
92
- }
93
- exports.AddCurrentDirectoryRootFilesModifier = AddCurrentDirectoryRootFilesModifier;
@@ -1,9 +0,0 @@
1
- import { ProcessedMessage } from "@codebolt/types/agent";
2
- import { BaseMessageModifier } from "../base";
3
- import { FlatUserMessage } from "@codebolt/types/sdk";
4
- export declare class AdvancedSystemInstructionMessageModifier extends BaseMessageModifier {
5
- private readonly systemInstruction;
6
- constructor(systemInstruction?: string);
7
- modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
8
- private getAdvancedSystemPrompt;
9
- }
@@ -1,77 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AdvancedSystemInstructionMessageModifier = void 0;
4
- const base_1 = require("../base");
5
- class AdvancedSystemInstructionMessageModifier extends base_1.BaseMessageModifier {
6
- constructor(systemInstruction) {
7
- super();
8
- this.systemInstruction = systemInstruction || this.getAdvancedSystemPrompt();
9
- }
10
- async modify(originalRequest, createdMessage) {
11
- try {
12
- const systemMessage = {
13
- role: 'system',
14
- content: this.systemInstruction
15
- };
16
- const messages = [...(createdMessage.message.messages || [])];
17
- const existingSystemIndex = messages.findIndex(msg => msg.role === 'system');
18
- if (existingSystemIndex !== -1) {
19
- messages[existingSystemIndex] = systemMessage;
20
- }
21
- else {
22
- messages.unshift(systemMessage);
23
- }
24
- return {
25
- message: {
26
- ...createdMessage.message,
27
- messages
28
- },
29
- metadata: {
30
- ...createdMessage.metadata
31
- }
32
- };
33
- }
34
- catch (error) {
35
- console.error('Error in AdvancedSystemInstructionMessageModifier:', error);
36
- throw error;
37
- }
38
- }
39
- getAdvancedSystemPrompt() {
40
- const advancedPrompt = `
41
- You are an advanced AI software engineering assistant with expertise in multiple programming languages, frameworks, and best practices. Your primary goal is to assist users efficiently and safely while adhering to the following guidelines:
42
-
43
- 1. Code Quality and Best Practices:
44
- - Write clean, efficient, and maintainable code
45
- - Follow SOLID principles and design patterns when appropriate
46
- - Implement proper error handling and logging
47
- - Write unit tests for new functionality
48
- - Ensure code is secure and follows cybersecurity best practices
49
-
50
- 2. Project-Specific Considerations:
51
- - Analyze and adhere to existing project structure, naming conventions, and coding style
52
- - Use established libraries and frameworks within the project
53
- - Consider scalability and performance implications of changes
54
- - Maintain backward compatibility unless explicitly instructed otherwise
55
-
56
- 3. Communication and Collaboration:
57
- - Provide clear, concise explanations for your decisions and implementations
58
- - Ask clarifying questions when requirements are ambiguous
59
- - Suggest improvements or alternatives when appropriate
60
- - Break down complex tasks into manageable steps
61
-
62
- 4. Continuous Learning and Adaptation:
63
- - Stay updated on latest industry trends and best practices
64
- - Adapt your approach based on user feedback and project requirements
65
- - Recommend modern tools and techniques when beneficial to the project
66
-
67
- 5. Ethical Considerations:
68
- - Respect intellectual property rights and licensing
69
- - Avoid implementing features that could be used maliciously
70
- - Promote inclusive and accessible code practices
71
-
72
- Remember to use the provided tools effectively, always prioritize user safety and project integrity, and strive for excellence in every task you undertake.
73
- `.trim();
74
- return advancedPrompt;
75
- }
76
- }
77
- exports.AdvancedSystemInstructionMessageModifier = AdvancedSystemInstructionMessageModifier;
@@ -1,19 +0,0 @@
1
- import { ProcessedMessage } from "@codebolt/types/agent";
2
- import { BaseMessageModifier } from "../base";
3
- import { FlatUserMessage } from "@codebolt/types/sdk";
4
- export interface ChatCompressionOptions {
5
- tokenThreshold?: number;
6
- compressionRatio?: number;
7
- preserveRecentMessages?: number;
8
- enableCompression?: boolean;
9
- }
10
- export declare class ChatCompressionModifier extends BaseMessageModifier {
11
- private readonly options;
12
- private hasFailedCompressionAttempt;
13
- constructor(options?: ChatCompressionOptions);
14
- modify(originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
15
- private shouldCompressChat;
16
- private compressMessages;
17
- private createConversationSummary;
18
- resetCompressionState(): void;
19
- }
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ChatCompressionModifier = void 0;
4
- const base_1 = require("../base");
5
- class ChatCompressionModifier extends base_1.BaseMessageModifier {
6
- constructor(options = {}) {
7
- super();
8
- this.hasFailedCompressionAttempt = false;
9
- this.options = {
10
- tokenThreshold: options.tokenThreshold || 8000, // Approximate token threshold
11
- compressionRatio: options.compressionRatio || 0.5, // Compress to 50% of original
12
- preserveRecentMessages: options.preserveRecentMessages || 5,
13
- enableCompression: options.enableCompression !== false
14
- };
15
- }
16
- async modify(originalRequest, createdMessage) {
17
- try {
18
- if (!this.options.enableCompression || this.hasFailedCompressionAttempt) {
19
- return createdMessage;
20
- }
21
- const messages = createdMessage.message.messages;
22
- // Skip compression if we don't have enough messages
23
- if (messages.length <= this.options.preserveRecentMessages) {
24
- return createdMessage;
25
- }
26
- const shouldCompress = await this.shouldCompressChat(messages);
27
- if (!shouldCompress) {
28
- return createdMessage;
29
- }
30
- const compressedMessages = await this.compressMessages(messages);
31
- return Promise.resolve({
32
- message: {
33
- ...createdMessage.message,
34
- messages: compressedMessages
35
- },
36
- metadata: {
37
- ...createdMessage.metadata,
38
- chatCompressed: true,
39
- originalMessageCount: messages.length,
40
- compressedMessageCount: compressedMessages.length
41
- }
42
- });
43
- }
44
- catch (error) {
45
- console.error('Error in ChatCompressionModifier:', error);
46
- this.hasFailedCompressionAttempt = true;
47
- return createdMessage;
48
- }
49
- }
50
- async shouldCompressChat(messages) {
51
- // Estimate token count (rough approximation: 4 characters per token)
52
- const totalCharacters = messages.reduce((sum, msg) => {
53
- return sum + (typeof msg.content === 'string' ? msg.content.length : JSON.stringify(msg.content).length);
54
- }, 0);
55
- const estimatedTokens = totalCharacters / 4;
56
- return estimatedTokens > this.options.tokenThreshold;
57
- }
58
- async compressMessages(messages) {
59
- const preserveCount = this.options.preserveRecentMessages;
60
- const recentMessages = messages.slice(-preserveCount);
61
- const messagesToCompress = messages.slice(0, -preserveCount);
62
- if (messagesToCompress.length === 0) {
63
- return messages;
64
- }
65
- // Create a summary of the messages to compress
66
- const conversationSummary = this.createConversationSummary(messagesToCompress);
67
- const compressionMessage = {
68
- role: 'system',
69
- content: `[Conversation Summary - Previous ${messagesToCompress.length} messages compressed]
70
-
71
- ${conversationSummary}
72
-
73
- [End of Summary - Continuing with recent conversation...]`
74
- };
75
- return [compressionMessage, ...recentMessages];
76
- }
77
- createConversationSummary(messages) {
78
- const summaryParts = [];
79
- let currentTopic = '';
80
- let userQuestions = [];
81
- let assistantResponses = [];
82
- for (const message of messages) {
83
- const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
84
- if (message.role === 'user') {
85
- // Extract key questions or requests
86
- if (content.length > 20) { // Only include substantial messages
87
- userQuestions.push(content.substring(0, 100) + (content.length > 100 ? '...' : ''));
88
- }
89
- }
90
- else if (message.role === 'assistant') {
91
- // Extract key responses or actions
92
- if (content.length > 20) {
93
- assistantResponses.push(content.substring(0, 100) + (content.length > 100 ? '...' : ''));
94
- }
95
- }
96
- }
97
- if (userQuestions.length > 0) {
98
- summaryParts.push(`Key user requests: ${userQuestions.slice(0, 3).join('; ')}`);
99
- }
100
- if (assistantResponses.length > 0) {
101
- summaryParts.push(`Key assistant actions: ${assistantResponses.slice(0, 3).join('; ')}`);
102
- }
103
- summaryParts.push(`Total messages compressed: ${messages.length}`);
104
- return summaryParts.join('\n');
105
- }
106
- resetCompressionState() {
107
- this.hasFailedCompressionAttempt = false;
108
- }
109
- }
110
- exports.ChatCompressionModifier = ChatCompressionModifier;