@codebolt/agent 1.2.1 → 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.
- package/README.md +157 -66
- package/dist/{agent.js → builderpattern/agent.js} +2 -2
- package/dist/{followupquestionbuilder.d.ts → builderpattern/followupquestionbuilder.d.ts} +1 -1
- package/dist/{followupquestionbuilder.js → builderpattern/followupquestionbuilder.js} +1 -1
- package/dist/{index.d.ts → builderpattern/index.d.ts} +3 -3
- package/dist/{llmoutputhandler.d.ts → builderpattern/llmoutputhandler.d.ts} +1 -1
- package/dist/{llmoutputhandler.js → builderpattern/llmoutputhandler.js} +7 -7
- package/dist/{promptbuilder.d.ts → builderpattern/promptbuilder.d.ts} +3 -3
- package/dist/{taskInstruction.d.ts → builderpattern/taskInstruction.d.ts} +2 -2
- package/dist/{usermessage.d.ts → builderpattern/usermessage.d.ts} +9 -4
- package/dist/composablepattern/agent.d.ts +169 -0
- package/dist/composablepattern/agent.js +598 -0
- package/dist/composablepattern/codebolt-storage.d.ts +67 -0
- package/dist/composablepattern/codebolt-storage.js +320 -0
- package/dist/composablepattern/document.d.ts +149 -0
- package/dist/composablepattern/document.js +372 -0
- package/dist/composablepattern/examples/codebolt-integration-example.d.ts +12 -0
- package/dist/composablepattern/examples/codebolt-integration-example.js +218 -0
- package/dist/composablepattern/examples/codebolt-storage-example.d.ts +40 -0
- package/dist/composablepattern/examples/codebolt-storage-example.js +223 -0
- package/dist/composablepattern/examples/custom-steps-example.d.ts +20 -0
- package/dist/composablepattern/examples/custom-steps-example.js +455 -0
- package/dist/composablepattern/examples/document-agent.d.ts +17 -0
- package/dist/composablepattern/examples/document-agent.js +107 -0
- package/dist/composablepattern/examples/simple-codebolt-integration.d.ts +8 -0
- package/dist/composablepattern/examples/simple-codebolt-integration.js +164 -0
- package/dist/composablepattern/examples/weather-agent.d.ts +18 -0
- package/dist/composablepattern/examples/weather-agent.js +86 -0
- package/dist/composablepattern/examples/workflow-example.d.ts +12 -0
- package/dist/composablepattern/examples/workflow-example.js +463 -0
- package/dist/composablepattern/index.d.ts +63 -0
- package/dist/composablepattern/index.js +115 -0
- package/dist/composablepattern/memory.d.ts +89 -0
- package/dist/composablepattern/memory.js +141 -0
- package/dist/composablepattern/tool.d.ts +84 -0
- package/dist/composablepattern/tool.js +260 -0
- package/dist/composablepattern/types.d.ts +194 -0
- package/dist/composablepattern/types.js +6 -0
- package/dist/composablepattern/user-context.d.ts +214 -0
- package/dist/composablepattern/user-context.js +275 -0
- package/dist/composablepattern/workflow.d.ts +388 -0
- package/dist/composablepattern/workflow.js +562 -0
- package/dist/local-tools/fileTools.d.ts +26 -0
- package/dist/local-tools/fileTools.js +162 -0
- package/dist/processor/agent/agentStep.d.ts +49 -0
- package/dist/processor/agent/agentStep.js +241 -0
- package/dist/processor/agent/toolExecutor.d.ts +19 -0
- package/dist/processor/agent/toolExecutor.js +90 -0
- package/dist/processor/index.d.ts +7 -0
- package/dist/processor/index.js +36 -0
- package/dist/processor/messageModifiers/baseMessageModifier.d.ts +20 -0
- package/dist/processor/messageModifiers/baseMessageModifier.js +55 -0
- package/dist/processor/processors/baseProcessor.d.ts +14 -0
- package/dist/processor/processors/baseProcessor.js +29 -0
- package/dist/processor/tools/baseTool.d.ts +10 -0
- package/dist/processor/tools/baseTool.js +20 -0
- package/dist/processor/tools/toolList.d.ts +9 -0
- package/dist/processor/tools/toolList.js +22 -0
- package/dist/processor/types/interfaces.d.ts +117 -0
- package/dist/processor/types/interfaces.js +2 -0
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +13 -0
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +68 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +212 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +23 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +173 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +14 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +93 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +30 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +330 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +26 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +269 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +38 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +217 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +34 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +147 -0
- package/dist/processor-pieces/additionalModifiers/index.d.ts +12 -0
- package/dist/processor-pieces/additionalModifiers/index.js +28 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +29 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +155 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +129 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +25 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +169 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +20 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +152 -0
- package/dist/processor-pieces/base/baseMessageModifier.d.ts +12 -0
- package/dist/processor-pieces/base/baseMessageModifier.js +15 -0
- package/dist/processor-pieces/base/basePostInferenceProcessor.d.ts +13 -0
- package/dist/processor-pieces/base/basePostInferenceProcessor.js +18 -0
- package/dist/processor-pieces/base/basePostToolCallProcessor.d.ts +15 -0
- package/dist/processor-pieces/base/basePostToolCallProcessor.js +25 -0
- package/dist/processor-pieces/base/basePreInferenceProcessor.d.ts +12 -0
- package/dist/processor-pieces/base/basePreInferenceProcessor.js +17 -0
- package/dist/processor-pieces/base/basePreToolCallProcessor.d.ts +18 -0
- package/dist/processor-pieces/base/basePreToolCallProcessor.js +66 -0
- package/dist/processor-pieces/base/index.d.ts +9 -0
- package/dist/processor-pieces/base/index.js +18 -0
- package/dist/processor-pieces/index.d.ts +1 -0
- package/dist/processor-pieces/index.js +59 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +93 -0
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +31 -0
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +145 -0
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +9 -0
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +77 -0
- package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.d.ts +13 -0
- package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +68 -0
- package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.d.ts +25 -0
- package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +453 -0
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +67 -0
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +9 -0
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +90 -0
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.d.ts +18 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +20 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +124 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +104 -0
- package/dist/processor-pieces/messageModifiers/chatRecordingModifier.d.ts +23 -0
- package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +173 -0
- package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.d.ts +14 -0
- package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +130 -0
- package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +36 -0
- package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +418 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +41 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.js +355 -0
- package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +26 -0
- package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +260 -0
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +13 -0
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +59 -0
- package/dist/processor-pieces/messageModifiers/ideContextModifier.d.ts +34 -0
- package/dist/processor-pieces/messageModifiers/ideContextModifier.js +157 -0
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +19 -0
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +221 -0
- package/dist/processor-pieces/messageModifiers/index.d.ts +11 -0
- package/dist/processor-pieces/messageModifiers/index.js +26 -0
- package/dist/processor-pieces/messageModifiers/memoryImportModifier.d.ts +15 -0
- package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +129 -0
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +23 -0
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +207 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +26 -0
- package/dist/processor-pieces/messageModifiers/toolInjectionModifier.d.ts +20 -0
- package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +152 -0
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +38 -0
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +392 -0
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +1 -0
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +2 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +7 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +24 -0
- package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.d.ts +29 -0
- package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +174 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +41 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +197 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +26 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +90 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +81 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +329 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +40 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +272 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +291 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +47 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +249 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +137 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +228 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +99 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.js +278 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +37 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +178 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +43 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +207 -0
- package/dist/processor-pieces/postToolCallProcessors/index.d.ts +1 -0
- package/dist/processor-pieces/postToolCallProcessors/index.js +2 -0
- package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.d.ts +25 -0
- package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +225 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +52 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +264 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.d.ts +35 -0
- package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +255 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +7 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +31 -0
- package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -0
- package/dist/processor-pieces/preInferenceProcessors/index.js +2 -0
- package/dist/processor-pieces/preToolCall/index.d.ts +9 -0
- package/dist/processor-pieces/preToolCall/index.js +18 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +444 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +44 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +367 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +391 -0
- package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +1 -0
- package/dist/processor-pieces/pretoolCallProcessors/index.js +2 -0
- package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.d.ts +41 -0
- package/dist/processor-pieces/processors/advancedLoopDetectionProcessor.js +197 -0
- package/dist/processor-pieces/processors/chatCompressionProcessor.d.ts +26 -0
- package/dist/processor-pieces/processors/chatCompressionProcessor.js +90 -0
- package/dist/processor-pieces/processors/chatRecordingProcessor.d.ts +81 -0
- package/dist/processor-pieces/processors/chatRecordingProcessor.js +329 -0
- package/dist/processor-pieces/processors/contextManagementProcessor.d.ts +40 -0
- package/dist/processor-pieces/processors/contextManagementProcessor.js +305 -0
- package/dist/processor-pieces/processors/loopDetectionProcessor.d.ts +30 -0
- package/dist/processor-pieces/processors/loopDetectionProcessor.js +137 -0
- package/dist/processor-pieces/processors/responseValidationProcessor.d.ts +30 -0
- package/dist/processor-pieces/processors/responseValidationProcessor.js +228 -0
- package/dist/processor-pieces/processors/telemetryProcessor.d.ts +99 -0
- package/dist/processor-pieces/processors/telemetryProcessor.js +311 -0
- package/dist/processor-pieces/processors/tokenManagementProcessor.d.ts +37 -0
- package/dist/processor-pieces/processors/tokenManagementProcessor.js +178 -0
- package/dist/processor-pieces/processors/toolExecutionProcessor.d.ts +43 -0
- package/dist/processor-pieces/processors/toolExecutionProcessor.js +207 -0
- package/dist/processor-pieces/tools/fileTools.d.ts +26 -0
- package/dist/processor-pieces/tools/fileTools.js +162 -0
- package/dist/processor-pieces/utils/messageModifierHelper.d.ts +4 -0
- package/dist/processor-pieces/utils/messageModifierHelper.js +58 -0
- package/dist/types/commonTypes.d.ts +4 -0
- package/dist/types/processorTypes.d.ts +67 -0
- package/dist/types/processorTypes.js +58 -0
- package/dist/unified/agent/agent.d.ts +17 -0
- package/dist/unified/agent/agent.js +79 -0
- package/dist/unified/agent/team.d.ts +2 -0
- package/dist/unified/agent/team.js +6 -0
- package/dist/unified/agent/tool.d.ts +99 -0
- package/dist/unified/agent/tool.js +440 -0
- package/dist/unified/agent/tools.d.ts +44 -0
- package/dist/unified/agent/tools.js +487 -0
- package/dist/unified/agent/workflow.d.ts +24 -0
- package/dist/unified/agent/workflow.js +275 -0
- package/dist/unified/agent/workflowControls.d.ts +11 -0
- package/dist/unified/agent/workflowControls.js +20 -0
- package/dist/unified/agent/workflowSteps.d.ts +63 -0
- package/dist/unified/agent/workflowSteps.js +284 -0
- package/dist/unified/base/agentStep.d.ts +32 -0
- package/dist/unified/base/agentStep.js +96 -0
- package/dist/unified/base/create/createInitialPromptGenerators.d.ts +5 -0
- package/dist/unified/base/create/createInitialPromptGenerators.js +17 -0
- package/dist/unified/base/index.d.ts +5 -0
- package/dist/unified/base/index.js +13 -0
- package/dist/unified/base/initialPromptGenerator.d.ts +48 -0
- package/dist/unified/base/initialPromptGenerator.js +118 -0
- package/dist/unified/base/responseExecutor.d.ts +36 -0
- package/dist/unified/base/responseExecutor.js +283 -0
- package/dist/unified/examples/agentExample.d.ts +46 -0
- package/dist/unified/examples/agentExample.js +464 -0
- package/dist/unified/examples/documentationPatternExample.d.ts +10 -0
- package/dist/unified/examples/documentationPatternExample.js +385 -0
- package/dist/unified/examples/followUpProcessorsExample.d.ts +45 -0
- package/dist/unified/examples/followUpProcessorsExample.js +311 -0
- package/dist/unified/examples/orchestratorExample.d.ts +16 -0
- package/dist/unified/examples/orchestratorExample.js +415 -0
- package/dist/unified/examples/preToolCallProcessorsExample.d.ts +36 -0
- package/dist/unified/examples/preToolCallProcessorsExample.js +458 -0
- package/dist/unified/examples/workflowExample.d.ts +12 -0
- package/dist/unified/examples/workflowExample.js +497 -0
- package/dist/unified/index.d.ts +18 -0
- package/dist/unified/index.js +42 -0
- package/dist/unified/orchestrator/orchestrator.d.ts +260 -0
- package/dist/unified/orchestrator/orchestrator.js +519 -0
- package/dist/unified/team/team.d.ts +1 -0
- package/dist/unified/team/team.js +2 -0
- package/dist/unified/types/libTypes.d.ts +378 -0
- package/dist/unified/types/libTypes.js +6 -0
- package/dist/unified/types/types.d.ts +212 -0
- package/dist/unified/types/types.js +43 -0
- package/dist/unified/utils/utils.d.ts +40 -0
- package/dist/unified/utils/utils.js +219 -0
- package/package.json +35 -13
- /package/dist/{agent.d.ts → builderpattern/agent.d.ts} +0 -0
- /package/dist/{index.js → builderpattern/index.js} +0 -0
- /package/dist/{promptbuilder.js → builderpattern/promptbuilder.js} +0 -0
- /package/dist/{systemprompt.d.ts → builderpattern/systemprompt.d.ts} +0 -0
- /package/dist/{systemprompt.js → builderpattern/systemprompt.js} +0 -0
- /package/dist/{taskInstruction.js → builderpattern/taskInstruction.js} +0 -0
- /package/dist/{usermessage.js → builderpattern/usermessage.js} +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,418 @@
|
|
|
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
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.DirectoryContextModifier = void 0;
|
|
40
|
+
const base_1 = require("../base");
|
|
41
|
+
const fs = __importStar(require("node:fs/promises"));
|
|
42
|
+
const path = __importStar(require("node:path"));
|
|
43
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
44
|
+
const MAX_ITEMS = 200;
|
|
45
|
+
const TRUNCATION_INDICATOR = '...';
|
|
46
|
+
const DEFAULT_IGNORED_FOLDERS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.cache', '.tmp', 'tmp']);
|
|
47
|
+
// Error handling utility (simplified version of gemini-cli's getErrorMessage)
|
|
48
|
+
function getErrorMessage(error) {
|
|
49
|
+
if (error instanceof Error) {
|
|
50
|
+
return error.message;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
return String(error);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return 'Failed to get error details';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// Node error type guard
|
|
60
|
+
function isNodeError(error) {
|
|
61
|
+
return error instanceof Error && 'code' in error;
|
|
62
|
+
}
|
|
63
|
+
class DirectoryContextModifier extends base_1.BaseMessageModifier {
|
|
64
|
+
constructor(options = {}) {
|
|
65
|
+
super();
|
|
66
|
+
this.gitignorePatterns = new Set();
|
|
67
|
+
this.gitignoreRegexes = [];
|
|
68
|
+
this.options = {
|
|
69
|
+
workspaceDirectories: options.workspaceDirectories || []
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
async modify(originalRequest, createdMessage) {
|
|
73
|
+
try {
|
|
74
|
+
// Get workspace directories from codebolt or use provided options
|
|
75
|
+
let workspaceDirectories = this.options.workspaceDirectories;
|
|
76
|
+
if (!workspaceDirectories || workspaceDirectories.length === 0) {
|
|
77
|
+
const { projectPath } = await codeboltjs_1.default.project.getProjectPath();
|
|
78
|
+
workspaceDirectories = projectPath ? [projectPath] : [];
|
|
79
|
+
}
|
|
80
|
+
if (workspaceDirectories.length === 0) {
|
|
81
|
+
return createdMessage;
|
|
82
|
+
}
|
|
83
|
+
// Load gitignore patterns from all workspace directories
|
|
84
|
+
await this.loadGitignorePatterns(workspaceDirectories);
|
|
85
|
+
const folderStructures = await Promise.all(workspaceDirectories.map((dir) => this.getFolderStructure(dir)));
|
|
86
|
+
const folderStructure = folderStructures.join('\n');
|
|
87
|
+
let workingDirPreamble;
|
|
88
|
+
if (workspaceDirectories.length === 1) {
|
|
89
|
+
workingDirPreamble = `I'm currently working in the directory: ${workspaceDirectories[0]}`;
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
const dirList = workspaceDirectories.map((dir) => ` - ${dir}`).join('\n');
|
|
93
|
+
workingDirPreamble = `I'm currently working in the following directories:\n${dirList}`;
|
|
94
|
+
}
|
|
95
|
+
const directoryContext = `${workingDirPreamble}
|
|
96
|
+
Here is the folder structure of the current working directories:
|
|
97
|
+
|
|
98
|
+
${folderStructure}`;
|
|
99
|
+
const contextMessage = {
|
|
100
|
+
role: 'user', // Note: gemini-cli adds this as user message, not system
|
|
101
|
+
content: directoryContext
|
|
102
|
+
};
|
|
103
|
+
// Add as user message (like gemini-cli does)
|
|
104
|
+
const messages = [...createdMessage.message.messages, contextMessage];
|
|
105
|
+
return Promise.resolve({
|
|
106
|
+
message: {
|
|
107
|
+
...createdMessage.message,
|
|
108
|
+
messages
|
|
109
|
+
},
|
|
110
|
+
metadata: {
|
|
111
|
+
...createdMessage.metadata,
|
|
112
|
+
directoryContextAdded: true,
|
|
113
|
+
workspaceDirectories
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
console.error('Error in DirectoryContextModifier:', error);
|
|
119
|
+
return createdMessage;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async loadGitignorePatterns(workspaceDirectories) {
|
|
123
|
+
this.gitignorePatterns.clear();
|
|
124
|
+
this.gitignoreRegexes = [];
|
|
125
|
+
for (const dir of workspaceDirectories) {
|
|
126
|
+
try {
|
|
127
|
+
const gitignorePath = path.join(dir, '.gitignore');
|
|
128
|
+
const content = await fs.readFile(gitignorePath, 'utf-8');
|
|
129
|
+
this.parseGitignoreContent(content);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
// .gitignore file doesn't exist or can't be read, continue
|
|
133
|
+
console.debug(`No .gitignore found in ${dir}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
parseGitignoreContent(content) {
|
|
138
|
+
const lines = content.split('\n')
|
|
139
|
+
.map(line => line.trim())
|
|
140
|
+
.filter(line => line && !line.startsWith('#')); // Remove empty lines and comments
|
|
141
|
+
for (const line of lines) {
|
|
142
|
+
this.gitignorePatterns.add(line);
|
|
143
|
+
// Convert gitignore pattern to regex
|
|
144
|
+
let regexPattern = line
|
|
145
|
+
.replace(/\./g, '\\.') // Escape dots
|
|
146
|
+
.replace(/\*/g, '.*') // Convert * to .*
|
|
147
|
+
.replace(/\?/g, '.') // Convert ? to .
|
|
148
|
+
.replace(/\//g, '\\/'); // Escape slashes
|
|
149
|
+
// Handle directory patterns (ending with /)
|
|
150
|
+
if (line.endsWith('/')) {
|
|
151
|
+
regexPattern = regexPattern.slice(0, -2) + '$'; // Remove \/ and add end anchor
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
this.gitignoreRegexes.push(new RegExp(regexPattern));
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
console.warn(`Invalid gitignore pattern: ${line}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
isGitIgnored(filePath, fileName) {
|
|
162
|
+
// Check against gitignore patterns
|
|
163
|
+
for (const regex of this.gitignoreRegexes) {
|
|
164
|
+
if (regex.test(fileName) || regex.test(filePath)) {
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// Check exact matches
|
|
169
|
+
return this.gitignorePatterns.has(fileName) ||
|
|
170
|
+
this.gitignorePatterns.has(filePath) ||
|
|
171
|
+
this.gitignorePatterns.has(fileName + '/'); // Directory pattern
|
|
172
|
+
}
|
|
173
|
+
shouldIgnoreFile(fileName, filePath) {
|
|
174
|
+
// Check gitignore first
|
|
175
|
+
if (filePath && this.isGitIgnored(filePath, fileName)) {
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
// Ignore hidden files (except .gitignore itself)
|
|
179
|
+
if (fileName.startsWith('.') && fileName !== '.gitignore') {
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
// Ignore temporary files and caches
|
|
183
|
+
const ignoredPatterns = [
|
|
184
|
+
/^───.*\.tar\.zst$/, // Weird temporary files like ───0069a971db0f139f.tar.zst
|
|
185
|
+
/\.tmp$/,
|
|
186
|
+
/\.temp$/,
|
|
187
|
+
/\.cache$/,
|
|
188
|
+
/\.log$/,
|
|
189
|
+
/\.swp$/,
|
|
190
|
+
/\.bak$/,
|
|
191
|
+
/~$/,
|
|
192
|
+
/^#.*#$/,
|
|
193
|
+
/\.DS_Store$/,
|
|
194
|
+
/Thumbs\.db$/,
|
|
195
|
+
/desktop\.ini$/,
|
|
196
|
+
];
|
|
197
|
+
return ignoredPatterns.some(pattern => pattern.test(fileName));
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Generates a string representation of a directory's structure,
|
|
201
|
+
* limiting the number of items displayed. Ignored folders are shown
|
|
202
|
+
* followed by '...' instead of their contents.
|
|
203
|
+
*
|
|
204
|
+
* @param directory The absolute or relative path to the directory.
|
|
205
|
+
* @param options Optional configuration settings.
|
|
206
|
+
* @returns A promise resolving to the formatted folder structure string.
|
|
207
|
+
*/
|
|
208
|
+
async getFolderStructure(directory, options) {
|
|
209
|
+
var _a, _b;
|
|
210
|
+
const resolvedPath = path.resolve(directory);
|
|
211
|
+
const mergedOptions = {
|
|
212
|
+
maxItems: (_a = options === null || options === void 0 ? void 0 : options.maxItems) !== null && _a !== void 0 ? _a : MAX_ITEMS,
|
|
213
|
+
ignoredFolders: (_b = options === null || options === void 0 ? void 0 : options.ignoredFolders) !== null && _b !== void 0 ? _b : DEFAULT_IGNORED_FOLDERS,
|
|
214
|
+
fileIncludePattern: options === null || options === void 0 ? void 0 : options.fileIncludePattern,
|
|
215
|
+
};
|
|
216
|
+
try {
|
|
217
|
+
// 1. Read the structure using BFS, respecting maxItems
|
|
218
|
+
const structureRoot = await this.readFullStructure(resolvedPath, mergedOptions);
|
|
219
|
+
if (!structureRoot) {
|
|
220
|
+
return `Error: Could not read directory "${resolvedPath}". Check path and permissions.`;
|
|
221
|
+
}
|
|
222
|
+
// 2. Format the structure into a string
|
|
223
|
+
const structureLines = [];
|
|
224
|
+
// Pass true for isRoot for the initial call
|
|
225
|
+
this.formatStructure(structureRoot, '', true, true, structureLines);
|
|
226
|
+
// 3. Build the final output string
|
|
227
|
+
function isTruncated(node) {
|
|
228
|
+
if (node.hasMoreFiles || node.hasMoreSubfolders || node.isIgnored) {
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
for (const sub of node.subFolders) {
|
|
232
|
+
if (isTruncated(sub)) {
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
let summary = `Showing up to ${mergedOptions.maxItems} items (files + folders).`;
|
|
239
|
+
if (isTruncated(structureRoot)) {
|
|
240
|
+
summary += ` Folders or files indicated with ${TRUNCATION_INDICATOR} contain more items not shown, were ignored, or the display limit (${mergedOptions.maxItems} items) was reached.`;
|
|
241
|
+
}
|
|
242
|
+
return `${summary}\n\n${resolvedPath}${path.sep}\n${structureLines.join('\n')}`;
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
console.error(`Error getting folder structure for ${resolvedPath}:`, error);
|
|
246
|
+
return `Error processing directory "${resolvedPath}": ${getErrorMessage(error)}`;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async readFullStructure(rootPath, options) {
|
|
250
|
+
const rootName = path.basename(rootPath);
|
|
251
|
+
const rootNode = {
|
|
252
|
+
name: rootName,
|
|
253
|
+
path: rootPath,
|
|
254
|
+
files: [],
|
|
255
|
+
subFolders: [],
|
|
256
|
+
totalChildren: 0,
|
|
257
|
+
totalFiles: 0,
|
|
258
|
+
};
|
|
259
|
+
const queue = [
|
|
260
|
+
{ folderInfo: rootNode, currentPath: rootPath },
|
|
261
|
+
];
|
|
262
|
+
let currentItemCount = 0;
|
|
263
|
+
// Count the root node itself as one item if we are not just listing its content
|
|
264
|
+
const processedPaths = new Set(); // To avoid processing same path if symlinks create loops
|
|
265
|
+
while (queue.length > 0) {
|
|
266
|
+
const { folderInfo, currentPath } = queue.shift();
|
|
267
|
+
if (processedPaths.has(currentPath)) {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
processedPaths.add(currentPath);
|
|
271
|
+
if (currentItemCount >= options.maxItems) {
|
|
272
|
+
// If the root itself caused us to exceed, we can't really show anything.
|
|
273
|
+
// Otherwise, this folder won't be processed further.
|
|
274
|
+
// The parent that queued this would have set its own hasMoreSubfolders flag.
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
let entries;
|
|
278
|
+
try {
|
|
279
|
+
const rawEntries = await fs.readdir(currentPath, { withFileTypes: true });
|
|
280
|
+
// Sort entries alphabetically by name for consistent processing order
|
|
281
|
+
entries = rawEntries.sort((a, b) => a.name.localeCompare(b.name));
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (isNodeError(error) &&
|
|
285
|
+
(error.code === 'EACCES' || error.code === 'ENOENT')) {
|
|
286
|
+
console.warn(`Warning: Could not read directory ${currentPath}: ${error.message}`);
|
|
287
|
+
if (currentPath === rootPath && error.code === 'ENOENT') {
|
|
288
|
+
return null; // Root directory itself not found
|
|
289
|
+
}
|
|
290
|
+
// For other EACCES/ENOENT on subdirectories, just skip them.
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
const filesInCurrentDir = [];
|
|
296
|
+
const subFoldersInCurrentDir = [];
|
|
297
|
+
// Process files first in the current directory
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
if (entry.isFile()) {
|
|
300
|
+
if (currentItemCount >= options.maxItems) {
|
|
301
|
+
folderInfo.hasMoreFiles = true;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
const fileName = entry.name;
|
|
305
|
+
// Skip hidden files, temporary files, and other unwanted files
|
|
306
|
+
const filePath = path.join(currentPath, fileName);
|
|
307
|
+
if (this.shouldIgnoreFile(fileName, filePath)) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (!options.fileIncludePattern ||
|
|
311
|
+
options.fileIncludePattern.test(fileName)) {
|
|
312
|
+
filesInCurrentDir.push(fileName);
|
|
313
|
+
currentItemCount++;
|
|
314
|
+
folderInfo.totalFiles++;
|
|
315
|
+
folderInfo.totalChildren++;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
folderInfo.files = filesInCurrentDir;
|
|
320
|
+
// Then process directories and queue them
|
|
321
|
+
for (const entry of entries) {
|
|
322
|
+
if (entry.isDirectory()) {
|
|
323
|
+
// Check if adding this directory ITSELF would meet or exceed maxItems
|
|
324
|
+
// (currentItemCount refers to items *already* added before this one)
|
|
325
|
+
if (currentItemCount >= options.maxItems) {
|
|
326
|
+
folderInfo.hasMoreSubfolders = true;
|
|
327
|
+
break; // Already at limit, cannot add this folder or any more
|
|
328
|
+
}
|
|
329
|
+
// If adding THIS folder makes us hit the limit exactly, and it might have children,
|
|
330
|
+
// it's better to show '...' for the parent, unless this is the very last item slot.
|
|
331
|
+
// This logic is tricky. Let's try a simpler: if we can't add this item, mark and break.
|
|
332
|
+
const subFolderName = entry.name;
|
|
333
|
+
const subFolderPath = path.join(currentPath, subFolderName);
|
|
334
|
+
// Check if folder should be ignored (built-in ignore list or gitignore)
|
|
335
|
+
if (options.ignoredFolders.has(subFolderName) ||
|
|
336
|
+
this.shouldIgnoreFile(subFolderName, subFolderPath)) {
|
|
337
|
+
const ignoredSubFolder = {
|
|
338
|
+
name: subFolderName,
|
|
339
|
+
path: subFolderPath,
|
|
340
|
+
files: [],
|
|
341
|
+
subFolders: [],
|
|
342
|
+
totalChildren: 0,
|
|
343
|
+
totalFiles: 0,
|
|
344
|
+
isIgnored: true,
|
|
345
|
+
};
|
|
346
|
+
subFoldersInCurrentDir.push(ignoredSubFolder);
|
|
347
|
+
currentItemCount++; // Count the ignored folder itself
|
|
348
|
+
folderInfo.totalChildren++; // Also counts towards parent's children
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const subFolderNode = {
|
|
352
|
+
name: subFolderName,
|
|
353
|
+
path: subFolderPath,
|
|
354
|
+
files: [],
|
|
355
|
+
subFolders: [],
|
|
356
|
+
totalChildren: 0,
|
|
357
|
+
totalFiles: 0,
|
|
358
|
+
};
|
|
359
|
+
subFoldersInCurrentDir.push(subFolderNode);
|
|
360
|
+
currentItemCount++;
|
|
361
|
+
folderInfo.totalChildren++; // Counts towards parent's children
|
|
362
|
+
// Add to queue for processing its children later
|
|
363
|
+
queue.push({ folderInfo: subFolderNode, currentPath: subFolderPath });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
folderInfo.subFolders = subFoldersInCurrentDir;
|
|
367
|
+
}
|
|
368
|
+
return rootNode;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Reads the directory structure using BFS, respecting maxItems.
|
|
372
|
+
* @param node The current node in the reduced structure.
|
|
373
|
+
* @param indent The current indentation string.
|
|
374
|
+
* @param isLast Sibling indicator.
|
|
375
|
+
* @param builder Array to build the string lines.
|
|
376
|
+
*/
|
|
377
|
+
formatStructure(node, currentIndent, isLastChildOfParent, isProcessingRootNode, builder) {
|
|
378
|
+
const connector = isLastChildOfParent ? '└───' : '├───';
|
|
379
|
+
// The root node of the structure (the one passed initially to getFolderStructure)
|
|
380
|
+
// is not printed with a connector line itself, only its name as a header.
|
|
381
|
+
// Its children are printed relative to that conceptual root.
|
|
382
|
+
// Ignored root nodes ARE printed with a connector.
|
|
383
|
+
if (!isProcessingRootNode || node.isIgnored) {
|
|
384
|
+
builder.push(`${currentIndent}${connector}${node.name}${path.sep}${node.isIgnored ? TRUNCATION_INDICATOR : ''}`);
|
|
385
|
+
}
|
|
386
|
+
// Determine the indent for the children of *this* node.
|
|
387
|
+
// If *this* node was the root of the whole structure, its children start with no indent before their connectors.
|
|
388
|
+
// Otherwise, children's indent extends from the current node's indent.
|
|
389
|
+
const indentForChildren = isProcessingRootNode
|
|
390
|
+
? ''
|
|
391
|
+
: currentIndent + (isLastChildOfParent ? ' ' : '│ ');
|
|
392
|
+
// Render files of the current node
|
|
393
|
+
const fileCount = node.files.length;
|
|
394
|
+
for (let i = 0; i < fileCount; i++) {
|
|
395
|
+
const isLastFileAmongSiblings = i === fileCount - 1 &&
|
|
396
|
+
node.subFolders.length === 0 &&
|
|
397
|
+
!node.hasMoreSubfolders;
|
|
398
|
+
const fileConnector = isLastFileAmongSiblings ? '└───' : '├───';
|
|
399
|
+
builder.push(`${indentForChildren}${fileConnector}${node.files[i]}`);
|
|
400
|
+
}
|
|
401
|
+
if (node.hasMoreFiles) {
|
|
402
|
+
const isLastIndicatorAmongSiblings = node.subFolders.length === 0 && !node.hasMoreSubfolders;
|
|
403
|
+
const fileConnector = isLastIndicatorAmongSiblings ? '└───' : '├───';
|
|
404
|
+
builder.push(`${indentForChildren}${fileConnector}${TRUNCATION_INDICATOR}`);
|
|
405
|
+
}
|
|
406
|
+
// Render subfolders of the current node
|
|
407
|
+
const subFolderCount = node.subFolders.length;
|
|
408
|
+
for (let i = 0; i < subFolderCount; i++) {
|
|
409
|
+
const isLastSubfolderAmongSiblings = i === subFolderCount - 1 && !node.hasMoreSubfolders;
|
|
410
|
+
// Children are never the root node being processed initially.
|
|
411
|
+
this.formatStructure(node.subFolders[i], indentForChildren, isLastSubfolderAmongSiblings, false, builder);
|
|
412
|
+
}
|
|
413
|
+
if (node.hasMoreSubfolders) {
|
|
414
|
+
builder.push(`${indentForChildren}└───${TRUNCATION_INDICATOR}`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
exports.DirectoryContextModifier = DirectoryContextModifier;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2025 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
export interface Part {
|
|
7
|
+
text: string;
|
|
8
|
+
}
|
|
9
|
+
export interface EnvironmentContextOptions {
|
|
10
|
+
workspaceDirectories: string[];
|
|
11
|
+
includeFullContext?: boolean;
|
|
12
|
+
maxItems?: number;
|
|
13
|
+
ignoredFolders?: Set<string>;
|
|
14
|
+
fileIncludePattern?: RegExp;
|
|
15
|
+
respectGitIgnore?: boolean;
|
|
16
|
+
respectGeminiIgnore?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface FolderStructureOptions {
|
|
19
|
+
maxItems?: number;
|
|
20
|
+
ignoredFolders?: Set<string>;
|
|
21
|
+
fileIncludePattern?: RegExp;
|
|
22
|
+
respectGitIgnore?: boolean;
|
|
23
|
+
respectGeminiIgnore?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Standalone version of getFolderStructure
|
|
27
|
+
*/
|
|
28
|
+
export declare function getFolderStructure(targetPath: string, options?: FolderStructureOptions): Promise<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Standalone version of getDirectoryContextString
|
|
31
|
+
*/
|
|
32
|
+
export declare function getDirectoryContextString(workspaceDirectories: string[], options?: FolderStructureOptions): Promise<string>;
|
|
33
|
+
/**
|
|
34
|
+
* Standalone version of getEnvironmentContext
|
|
35
|
+
*/
|
|
36
|
+
export declare function getEnvironmentContext(options: EnvironmentContextOptions): Promise<Part[]>;
|
|
37
|
+
/**
|
|
38
|
+
* Utility function to read multiple files (basic implementation for full context)
|
|
39
|
+
* This is a simplified version - extend as needed for your use case
|
|
40
|
+
*/
|
|
41
|
+
export declare function readMultipleFiles(basePath: string, patterns?: string[], options?: FolderStructureOptions): Promise<string>;
|