Elffuss BraidHub

kikocis/continue public

e0b45db6ff5d · 6.4 KiBRawPermalink
1import { execSync } from "child_process";
2import * as fs from "fs";
3import * as path from "path";
4
5import pkg from "ignore-walk";
6import { Minimatch } from "minimatch";
7
8import { processRule } from "./args.js";
9import { serviceContainer } from "./services/ServiceContainer.js";
10import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js";
11const { WalkerSync } = pkg;
12
13/**
14 * Check if current directory is a git repository
15 */
16function isGitRepo(): boolean {
17 try {
18 execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" });
19 return true;
20 } catch {
21 return false;
22 }
23}
24
25/**
26 * Get basic directory structure
27 */
28function getDirectoryStructure(): string {
29 try {
30 const walker = new WalkerSync({
31 path: process.cwd(),
32 includeEmpty: false,
33 follow: false,
34 ignoreFiles: [".gitignore", ".continueignore", ".customignore"],
35 });
36
37 (walker.ignoreRules as any)[".customignore"] = [
38 new Minimatch(".git/*", {
39 matchBase: true,
40 dot: true,
41 flipNegate: true,
42 nocase: true,
43 }),
44 ];
45
46 const files = walker.start().result as string[];
47
48 const filteredFiles = files
49 .slice(0, 500)
50 .map((file: string) => `./${file}`);
51
52 return filteredFiles.join("\n") || "No structure available";
53 } catch {
54 return "Directory structure not available";
55 }
56}
57
58/**
59 * Get git status
60 */
61function getGitStatus(): string {
62 try {
63 if (!isGitRepo()) {
64 return "Not a git repository";
65 }
66 const result = execSync("git status --porcelain", {
67 encoding: "utf-8",
68 cwd: process.cwd(),
69 });
70 return result.trim() || "Working tree clean";
71 } catch {
72 return "Git status not available";
73 }
74}
75
76const baseSystemMessage = `You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question.
77
78Notes:
791. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface.
802. When relevant, share file names and code snippets relevant to the query
81Here is useful information about the environment you are running in:
82<env>
83Working directory: ${process.cwd()}
84Is directory a git repo: ${isGitRepo()}
85Platform: ${process.platform}
86Today's date: ${new Date().toISOString().split("T")[0]}
87</env>
88
89As you answer the user's questions, you can use the following context:
90
91<context name="directoryStructure">Below is a snapshot of this project's file structure at the start of the conversation. This snapshot will NOT update during the conversation. It skips over .gitignore patterns.
92
93${getDirectoryStructure()}
94</context>
95<context name="gitStatus">This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.
96
97${getGitStatus()}
98</context>`;
99
100async function getConfigYamlRules(): Promise<string[]> {
101 const configState = await serviceContainer.get<ConfigServiceState>(
102 SERVICE_NAMES.CONFIG,
103 );
104 if (configState.config?.rules) {
105 // Extract systemMessage from the config if it exists
106 const rules = configState.config.rules;
107 return rules
108 .map((rule) => {
109 return typeof rule === "string" ? rule : rule?.rule;
110 })
111 .filter((rule): rule is string => !!rule);
112 }
113
114 return [];
115}
116
117/**
118 * Load and construct a comprehensive system message with base message and rules section
119 * @param rulesSystemMessage - The rules system message from the assistant
120 * @param additionalRules - Additional rules from --rule flags
121 * @param format - Output format for headless mode
122 * @param headless - Whether running in headless mode
123 * @returns The comprehensive system message with base message and rules section
124 */
125export async function constructSystemMessage(
126 additionalRules?: string[],
127 format?: "json",
128 headless?: boolean,
129): Promise<string> {
130 const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
131
132 let agentContent = "";
133
134 try {
135 for (const fileName of agentFiles) {
136 const filePath = path.join(process.cwd(), fileName);
137
138 if (fs.existsSync(filePath)) {
139 agentContent = fs.readFileSync(filePath, "utf-8");
140 break; // Use the first found agent file
141 }
142 }
143 } catch (error) {
144 // If there's any error reading the file, continue without agent content
145 console.warn("Warning: Could not read agent configuration file:", error);
146 }
147
148 // Process additional rules from --rule flags
149 const processedRules: string[] = [];
150 if (additionalRules && additionalRules.length > 0) {
151 for (const ruleSpec of additionalRules) {
152 try {
153 const processedRule = await processRule(ruleSpec);
154 processedRules.push(processedRule);
155 } catch (error: any) {
156 console.warn(
157 `Warning: Failed to process rule "${ruleSpec}": ${error.message}`,
158 );
159 }
160 }
161 }
162
163 const configYamlRules = await getConfigYamlRules();
164 processedRules.push(...configYamlRules);
165
166 // Construct the comprehensive system message
167 let systemMessage = baseSystemMessage;
168
169 // In headless mode, add instructions to be concise and only provide final answers
170 if (headless) {
171 systemMessage += `
172
173IMPORTANT: You are running in headless mode. Provide ONLY your final answer to the user's question. Do not include explanations, reasoning, or additional commentary unless specifically requested. Be direct and concise.`;
174 }
175
176 // Add JSON formatting instructions if format is json
177 if (format === "json") {
178 systemMessage += `
179
180IMPORTANT: You are operating in JSON output mode. Your final response MUST be valid JSON that can be parsed by JSON.parse(). The JSON should contain properties relevant to answer the user's question. You don't need to include any general "response" or "answer" field. Do not include any text before or after the JSON - the entire response must be parseable JSON.
181
182Example response format:
183{
184 "property": "value"
185}`;
186 }
187
188 // Add rules section if we have any rules or agent content
189 if (agentContent || processedRules.length > 0) {
190 systemMessage += '\n\n<context name="userRules">';
191
192 if (agentContent) {
193 systemMessage += `\n${agentContent}`;
194 }
195
196 // Add processed rules from --rule flags
197 if (processedRules.length > 0) {
198 const separator = agentContent ? "\n\n" : "\n";
199 systemMessage += `${separator}${processedRules.join("\n\n")}`;
200 }
201
202 systemMessage += "\n</context>";
203 }
204
205 return systemMessage;
206}