vtcode_core/prompts/
system.rs

1//! System instructions and prompt management
2
3use crate::gemini::Content;
4use std::fs;
5use std::path::Path;
6
7/// System instruction configuration
8#[derive(Debug, Clone)]
9pub struct SystemPromptConfig {
10    pub include_examples: bool,
11    pub include_debugging_guides: bool,
12    pub include_error_handling: bool,
13    pub max_response_length: Option<usize>,
14    pub enable_thorough_reasoning: bool,
15}
16
17impl Default for SystemPromptConfig {
18    fn default() -> Self {
19        Self {
20            include_examples: true,
21            include_debugging_guides: true,
22            include_error_handling: true,
23            max_response_length: None,
24            enable_thorough_reasoning: true,
25        }
26    }
27}
28
29/// Read system prompt from markdown file
30pub fn read_system_prompt_from_md() -> Result<String, std::io::Error> {
31    // Try to read from prompts/system.md relative to project root
32    let prompt_paths = [
33        "prompts/system.md",
34        "../prompts/system.md",
35        "../../prompts/system.md",
36    ];
37
38    for path in &prompt_paths {
39        if let Ok(content) = fs::read_to_string(path) {
40            // Extract the main system prompt content (skip the markdown header)
41            if let Some(start) = content.find("## Core System Prompt") {
42                // Find the end of the prompt (look for the next major section)
43                let after_start = &content[start..];
44                if let Some(end) = after_start.find("## Specialized System Prompts") {
45                    let prompt_content = &after_start[..end].trim();
46                    // Remove the header and return the content
47                    if let Some(content_start) = prompt_content.find("```rust\nr#\"") {
48                        if let Some(content_end) = prompt_content[content_start..].find("\"#\n```")
49                        {
50                            let prompt_start = content_start + 9; // Skip ```rust\nr#"
51                            let prompt_end = content_start + content_end;
52                            return Ok(prompt_content[prompt_start..prompt_end].to_string());
53                        }
54                    }
55                    // If no code block found, return the section content
56                    return Ok(prompt_content.to_string());
57                }
58            }
59            // If no specific section found, return the entire content
60            return Ok(content);
61        }
62    }
63
64    // Fallback to a minimal prompt if file not found
65    Ok(r#"You are a coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. VTCode is an open source project that provides a reliable, context-aware coding experience. You are expected to be precise, safe, helpful, and smart.
66
67## WORKSPACE CONTEXT
68- The `WORKSPACE_DIR` environment variable points to the active project; treat it as your default operating surface.
69- You may read, create, and modify files within this workspace and run shell commands or scripts scoped to it.
70- Perform light workspace reconnaissance (directory listings, targeted searches) before major changes so your decisions reflect the live codebase.
71- For new feature work, inspect existing modules under `WORKSPACE_DIR` that align with the request before implementing changes.
72- When debugging, consult workspace tests, logs, or recent diffs to ground your hypotheses in current project state.
73- Ask before touching paths outside `WORKSPACE_DIR` or downloading untrusted artifacts.
74
75## AVAILABLE TOOLS
76- **File Operations**: list_files, read_file, write_file, edit_file
77- **Search & Analysis**: rp_search, grep_search, ast_grep_search
78- **Terminal Access**: run_terminal_cmd (default: pty) for shell operations
79- **PTY Access**: Enhanced terminal emulation for interactive commands
80
81Your capabilities:
82- Receive user prompts and other context provided by the harness, such as files in the workspace.
83- Communicate with the user by streaming thinking & responses, and by making & updating plans.
84- Output is rendered with ANSI styles; return plain text and let the interface style the response.
85- Emit function calls to run terminal commands and apply patches.
86
87Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string())
88}
89
90/// Generate system instruction by loading from system.md
91pub fn generate_system_instruction(_config: &SystemPromptConfig) -> Content {
92    match read_system_prompt_from_md() {
93        Ok(prompt_content) => Content::system_text(prompt_content),
94        Err(_) => Content::system_text(r#"You are a coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. You are expected to be precise, safe, helpful, and smart.
95
96## WORKSPACE CONTEXT
97- The `WORKSPACE_DIR` environment variable points to the active project; treat it as your default operating surface.
98- You may read, create, and modify files within this workspace and run shell commands or scripts scoped to it.
99- Perform light workspace reconnaissance (directory listings, targeted searches) before major changes so your decisions reflect the live codebase.
100- For new feature work, inspect existing modules under `WORKSPACE_DIR` that align with the request before implementing changes.
101- When debugging, consult workspace tests, logs, or recent diffs to ground your hypotheses in current project state.
102- Ask before touching paths outside `WORKSPACE_DIR` or downloading untrusted artifacts.
103
104## AVAILABLE TOOLS
105- **File Operations**: list_files, read_file, write_file, edit_file
106- **Search & Analysis**: rp_search, grep_search, ast_grep_search
107- **Terminal Access**: run_terminal_cmd (default: pty) for shell operations
108- **PTY Access**: Enhanced terminal emulation for interactive commands
109
110Your capabilities:
111- Receive user prompts and other context provided by the harness, such as files in the workspace.
112- Communicate with the user by streaming thinking & responses, and by making & updating plans.
113- Output is rendered with ANSI styles; return plain text and let the interface style the response.
114- Emit function calls to run terminal commands and apply patches.
115
116Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string()),
117    }
118}
119
120/// Read AGENTS.md file if present and extract agent guidelines
121pub fn read_agent_guidelines(project_root: &Path) -> Option<String> {
122    let agents_md_path = project_root.join("AGENTS.md");
123    if agents_md_path.exists() {
124        fs::read_to_string(&agents_md_path).ok()
125    } else {
126        None
127    }
128}
129
130/// Generate system instruction with configuration and AGENTS.md guidelines incorporated
131pub fn generate_system_instruction_with_config(
132    _config: &SystemPromptConfig,
133    project_root: &Path,
134    vtcode_config: Option<&crate::config::VTCodeConfig>,
135) -> Content {
136    let mut instruction = match read_system_prompt_from_md() {
137        Ok(content) => content,
138        Err(_) => r#"You are a coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. You are expected to be precise, safe, helpful, and smart.
139
140## WORKSPACE CONTEXT
141- The `WORKSPACE_DIR` environment variable points to the active project; treat it as your default operating surface.
142- You may read, create, and modify files within this workspace and run shell commands or scripts scoped to it.
143- Perform light workspace reconnaissance (directory listings, targeted searches) before major changes so your decisions reflect the live codebase.
144- For new feature work, inspect existing modules under `WORKSPACE_DIR` that align with the request before implementing changes.
145- When debugging, consult workspace tests, logs, or recent diffs to ground your hypotheses in current project state.
146- Ask before touching paths outside `WORKSPACE_DIR` or downloading untrusted artifacts.
147
148## AVAILABLE TOOLS
149- **File Operations**: list_files, read_file, write_file, edit_file
150- **Search & Analysis**: rp_search, grep_search, ast_grep_search
151- **Terminal Access**: run_terminal_cmd for shell operations
152- **PTY Access**: Enhanced terminal emulation for interactive commands
153
154Your capabilities:
155- Receive user prompts and other context provided by the harness, such as files in the workspace.
156- Communicate with the user by streaming thinking & responses, and by making & updating plans.
157- Output is rendered with ANSI styles; return plain text and let the interface style the response.
158- Emit function calls to run terminal commands and apply patches.
159
160Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string(),
161    };
162
163    // Add configuration awareness
164    if let Some(cfg) = vtcode_config {
165        instruction.push_str("\n\n## CONFIGURATION AWARENESS\n");
166        instruction
167            .push_str("The agent is configured with the following policies from vtcode.toml:\n\n");
168
169        // Add security settings info
170        if cfg.security.human_in_the_loop {
171            instruction.push_str("- **Human-in-the-loop**: Required for critical actions\n");
172        }
173
174        // Add command policy info
175        if !cfg.commands.allow_list.is_empty() {
176            instruction.push_str(&format!(
177                "- **Allowed commands**: {} commands in allow list\n",
178                cfg.commands.allow_list.len()
179            ));
180        }
181        if !cfg.commands.deny_list.is_empty() {
182            instruction.push_str(&format!(
183                "- **Denied commands**: {} commands in deny list\n",
184                cfg.commands.deny_list.len()
185            ));
186        }
187
188        // Add PTY configuration info
189        if cfg.pty.enabled {
190            instruction.push_str("- **PTY functionality**: Enabled\n");
191            let (rows, cols) = (cfg.pty.default_rows, cfg.pty.default_cols);
192            instruction.push_str(&format!(
193                "- **Default terminal size**: {} rows × {} columns\n",
194                rows, cols
195            ));
196            instruction.push_str(&format!(
197                "- **PTY command timeout**: {} seconds\n",
198                cfg.pty.command_timeout_seconds
199            ));
200        } else {
201            instruction.push_str("- **PTY functionality**: Disabled\n");
202        }
203
204        instruction.push_str("\n**IMPORTANT**: Respect these configuration policies. Commands not in the allow list will require user confirmation. Always inform users when actions require confirmation due to security policies.\n");
205    }
206
207    // Read and incorporate AGENTS.md guidelines if available
208    if let Some(guidelines) = read_agent_guidelines(project_root) {
209        instruction.push_str("\n\n## AGENTS.MD GUIDELINES\n");
210        instruction.push_str("Please follow these project-specific guidelines from AGENTS.md:\n\n");
211        instruction.push_str(&guidelines);
212        instruction.push_str("\n\nThese guidelines take precedence over general instructions.");
213    }
214
215    Content::system_text(instruction)
216}
217
218/// Generate system instruction with AGENTS.md guidelines incorporated
219pub fn generate_system_instruction_with_guidelines(
220    _config: &SystemPromptConfig,
221    project_root: &Path,
222) -> Content {
223    let mut instruction = match read_system_prompt_from_md() {
224        Ok(content) => content,
225        Err(_) => r#"You are a coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. You are expected to be precise, safe, helpful, and smart.
226
227## AVAILABLE TOOLS
228- **File Operations**: list_files, read_file, write_file, edit_file
229- **Search & Analysis**: rp_search, grep_search, ast_grep_search
230- **Terminal Access**: run_terminal_cmd for shell operations
231- **PTY Access**: Enhanced terminal emulation for interactive commands
232
233Your capabilities:
234- Receive user prompts and other context provided by the harness, such as files in the workspace.
235- Communicate with the user by streaming thinking & responses, and by making & updating plans.
236- Output is rendered with ANSI styles; return plain text and let the interface style the response.
237- Emit function calls to run terminal commands and apply patches.
238
239Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string(),
240    };
241
242    // Read and incorporate AGENTS.md guidelines if available
243    if let Some(guidelines) = read_agent_guidelines(project_root) {
244        instruction.push_str("\n\n## AGENTS.MD GUIDELINES\n");
245        instruction.push_str("Please follow these project-specific guidelines from AGENTS.md:\n\n");
246        instruction.push_str(&guidelines);
247        instruction.push_str("\n\nThese guidelines take precedence over general instructions.");
248    }
249
250    Content::system_text(instruction)
251}
252
253/// Generate a lightweight system instruction for simple operations
254pub fn generate_lightweight_instruction() -> Content {
255    Content::system_text(r#"You are a coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. You are expected to be precise, safe, helpful, and smart.
256
257## AVAILABLE TOOLS
258- **File Operations**: list_files, read_file, write_file, edit_file
259- **Search & Analysis**: rp_search, grep_search, ast_grep_search
260- **Terminal Access**: run_terminal_cmd for shell operations
261
262Your capabilities:
263- Receive user prompts and other context provided by the harness, such as files in the workspace.
264- Communicate with the user by streaming thinking & responses, and by making & updating plans.
265- Output is rendered with ANSI styles; return plain text and let the interface style the response.
266- Emit function calls to run terminal commands and apply patches.
267
268Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string())
269}
270
271/// Generate a specialized system instruction for advanced operations
272pub fn generate_specialized_instruction() -> Content {
273    Content::system_text(r#"You are a specialized coding agent running in VTCode, a terminal-based coding assistant created by vinhnx. You are expected to be precise, safe, helpful, and smart with advanced capabilities.
274
275## AVAILABLE TOOLS
276- **File Operations**: list_files, read_file, write_file, edit_file
277- **Search & Analysis**: rp_search, grep_search, ast_grep_search
278- **Terminal Access**: run_terminal_cmd for shell operations
279- **PTY Access**: Enhanced terminal emulation for interactive commands
280- **Advanced Analysis**: Tree-sitter parsing, performance profiling, prompt caching
281
282Your capabilities:
283- Receive user prompts and other context provided by the harness, such as files in the workspace.
284- Communicate with the user by streaming thinking & responses, and by making & updating plans.
285- Output is rendered with ANSI styles; return plain text and let the interface style the response.
286- Emit function calls to run terminal commands and apply patches.
287- Perform advanced code analysis and optimization
288- Handle complex multi-step operations with proper error handling
289
290Within this context, VTCode refers to the open-source agentic coding interface created by vinhnx, not any other coding tools or models."#.to_string())
291}