| 1 | import { execSync } from "child_process"; |
| 2 | import * as fs from "fs"; |
| 3 | import * as path from "path"; |
| 4 | |
| 5 | import pkg from "ignore-walk"; |
| 6 | import { Minimatch } from "minimatch"; |
| 7 | |
| 8 | import { processPromptOrRule } from "./args.js"; |
| 9 | import { PermissionMode } from "./permissions/types.js"; |
| 10 | import { modeService } from "./services/ModeService.js"; |
| 11 | import { serviceContainer } from "./services/ServiceContainer.js"; |
| 12 | import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; |
| 13 | const { WalkerSync } = pkg; |
| 14 | |
| 15 | /** |
| 16 | * Check if current directory is a git repository |
| 17 | */ |
| 18 | function isGitRepo(): boolean { |
| 19 | try { |
| 20 | execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" }); |
| 21 | return true; |
| 22 | } catch { |
| 23 | return false; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Get basic directory structure |
| 29 | */ |
| 30 | function getDirectoryStructure(): string { |
| 31 | try { |
| 32 | const walker = new WalkerSync({ |
| 33 | path: process.cwd(), |
| 34 | includeEmpty: false, |
| 35 | follow: false, |
| 36 | ignoreFiles: [".gitignore", ".continueignore", ".customignore"], |
| 37 | }); |
| 38 | |
| 39 | (walker.ignoreRules as any)[".customignore"] = [ |
| 40 | new Minimatch(".git/*", { |
| 41 | matchBase: true, |
| 42 | dot: true, |
| 43 | flipNegate: true, |
| 44 | nocase: true, |
| 45 | }), |
| 46 | ]; |
| 47 | |
| 48 | const files = walker.start().result as string[]; |
| 49 | |
| 50 | const filteredFiles = files |
| 51 | .slice(0, 500) |
| 52 | .map((file: string) => `./${file}`); |
| 53 | |
| 54 | return filteredFiles.join("\n") || "No structure available"; |
| 55 | } catch { |
| 56 | return "Directory structure not available"; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Get git status |
| 62 | */ |
| 63 | function getGitStatus(): string { |
| 64 | try { |
| 65 | if (!isGitRepo()) { |
| 66 | return "Not a git repository"; |
| 67 | } |
| 68 | const result = execSync("git status --porcelain", { |
| 69 | encoding: "utf-8", |
| 70 | cwd: process.cwd(), |
| 71 | }); |
| 72 | return result.trim() || "Working tree clean"; |
| 73 | } catch { |
| 74 | return "Git status not available"; |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | const 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. |
| 79 | |
| 80 | Notes: |
| 81 | 1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. |
| 82 | 2. When relevant, share file names and code snippets relevant to the query |
| 83 | Here is useful information about the environment you are running in: |
| 84 | <env> |
| 85 | Working directory: ${process.cwd()} |
| 86 | Is directory a git repo: ${isGitRepo()} |
| 87 | Platform: ${process.platform} |
| 88 | Today's date: ${new Date().toISOString().split("T")[0]} |
| 89 | </env> |
| 90 | |
| 91 | As you answer the user's questions, you can use the following context: |
| 92 | |
| 93 | <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. |
| 94 | |
| 95 | ${getDirectoryStructure()} |
| 96 | </context> |
| 97 | <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. |
| 98 | |
| 99 | ${getGitStatus()} |
| 100 | </context>`; |
| 101 | |
| 102 | async function getConfigYamlRules(): Promise<string[]> { |
| 103 | const configState = await serviceContainer.get<ConfigServiceState>( |
| 104 | SERVICE_NAMES.CONFIG, |
| 105 | ); |
| 106 | if (configState.config?.rules) { |
| 107 | // Extract systemMessage from the config if it exists |
| 108 | const rules = configState.config.rules; |
| 109 | return rules |
| 110 | .map((rule) => { |
| 111 | return typeof rule === "string" ? rule : rule?.rule; |
| 112 | }) |
| 113 | .filter((rule): rule is string => !!rule); |
| 114 | } |
| 115 | |
| 116 | return []; |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * Load and construct a comprehensive system message with base message and rules section |
| 121 | * @param additionalRules - Additional rules from --rule flags |
| 122 | * @param format - Output format for headless mode |
| 123 | * @param headless - Whether running in headless mode |
| 124 | * @param mode - Current permission mode |
| 125 | * @returns The comprehensive system message with base message and rules section |
| 126 | */ |
| 127 | export async function constructSystemMessage( |
| 128 | additionalRules?: string[], |
| 129 | format?: "json", |
| 130 | headless?: boolean, |
| 131 | mode?: PermissionMode, |
| 132 | ): Promise<string> { |
| 133 | const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; |
| 134 | |
| 135 | let agentContent = ""; |
| 136 | |
| 137 | try { |
| 138 | for (const fileName of agentFiles) { |
| 139 | const filePath = path.join(process.cwd(), fileName); |
| 140 | |
| 141 | if (fs.existsSync(filePath)) { |
| 142 | agentContent = fs.readFileSync(filePath, "utf-8"); |
| 143 | break; // Use the first found agent file |
| 144 | } |
| 145 | } |
| 146 | } catch (error) { |
| 147 | // If there's any error reading the file, continue without agent content |
| 148 | console.warn("Warning: Could not read agent configuration file:", error); |
| 149 | } |
| 150 | |
| 151 | // Process additional rules from --rule flags |
| 152 | const processedRules: string[] = []; |
| 153 | if (additionalRules && additionalRules.length > 0) { |
| 154 | for (const ruleSpec of additionalRules) { |
| 155 | try { |
| 156 | const processedRule = await processPromptOrRule(ruleSpec); |
| 157 | processedRules.push(processedRule); |
| 158 | } catch (error: any) { |
| 159 | console.warn( |
| 160 | `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, |
| 161 | ); |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | const configYamlRules = await getConfigYamlRules(); |
| 167 | processedRules.push(...configYamlRules); |
| 168 | |
| 169 | // Get current mode if not provided |
| 170 | const currentMode = mode ?? modeService.getCurrentMode(); |
| 171 | |
| 172 | // Construct the comprehensive system message |
| 173 | let systemMessage = baseSystemMessage; |
| 174 | |
| 175 | // Add plan mode specific instructions if in plan mode |
| 176 | if (currentMode === "plan") { |
| 177 | systemMessage += |
| 178 | '\n<context name="planMode">You are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.</context>\n'; |
| 179 | } else { |
| 180 | // TODO - make including this coauthor commit configurable |
| 181 | systemMessage += `\n<context name="commitSignature">When creating commits using any CLI or tool, include the following in the commit message: |
| 182 | Generated with [Continue](https://continue.dev) |
| 183 | |
| 184 | Co-Authored-By: Continue <noreply@continue.dev> |
| 185 | </context>\n`; |
| 186 | } |
| 187 | |
| 188 | // In headless mode, add instructions to be concise and only provide final answers |
| 189 | if (headless) { |
| 190 | systemMessage += ` |
| 191 | |
| 192 | IMPORTANT: 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.`; |
| 193 | } |
| 194 | |
| 195 | // Add JSON formatting instructions if format is json |
| 196 | if (format === "json") { |
| 197 | systemMessage += ` |
| 198 | |
| 199 | IMPORTANT: 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. |
| 200 | |
| 201 | Example response format: |
| 202 | { |
| 203 | "property": "value" |
| 204 | }`; |
| 205 | } |
| 206 | |
| 207 | // Add rules section if we have any rules or agent content |
| 208 | if (agentContent || processedRules.length > 0) { |
| 209 | systemMessage += '\n\n<context name="userRules">'; |
| 210 | |
| 211 | if (agentContent) { |
| 212 | systemMessage += `\n${agentContent}`; |
| 213 | } |
| 214 | |
| 215 | // Add processed rules from --rule flags |
| 216 | if (processedRules.length > 0) { |
| 217 | const separator = agentContent ? "\n\n" : "\n"; |
| 218 | systemMessage += `${separator}${processedRules.join("\n\n")}`; |
| 219 | } |
| 220 | |
| 221 | systemMessage += "\n</context>"; |
| 222 | } |
| 223 | |
| 224 | return systemMessage; |
| 225 | } |