Skip to main content

ai_agent/tools/powershell/
prompt.rs

1// Source: /data/home/swei/claudecode/openclaudecode/src/tools/PowerShellTool/prompt.rs
2//! PowerShell tool prompt
3
4use crate::constants::env::ai;
5use crate::utils::env_utils::is_env_truthy;
6
7/// Get default timeout in milliseconds
8pub fn get_default_timeout_ms() -> u64 {
9    // Match BashTool's default timeout
10    120000 // 2 minutes
11}
12
13/// Get maximum timeout in milliseconds
14pub fn get_max_timeout_ms() -> u64 {
15    // Match BashTool's max timeout
16    600000 // 10 minutes
17}
18
19/// Check if background tasks are disabled
20pub fn is_background_tasks_disabled() -> bool {
21    is_env_truthy(std::env::var(ai::DISABLE_BACKGROUND_TASKS).ok().as_deref())
22}
23
24/// Get background usage note
25fn get_background_usage_note() -> Option<&'static str> {
26    if is_background_tasks_disabled() {
27        return None;
28    }
29    Some("  - You can use the `run_in_background` parameter to run the command in the background. Only use this if you don't need the result immediately and are OK being notified when the command completes later.")
30}
31
32/// Get sleep guidance
33fn get_sleep_guidance() -> Option<&'static str> {
34    if is_background_tasks_disabled() {
35        return None;
36    }
37    Some(r#"  - Avoid unnecessary `Start-Sleep` commands:
38    - Do not sleep between commands that can run immediately — just run them.
39    - If your command is long running and you would like to be notified when it finishes — simply run your command using `run_in_background`. There is no need to sleep in this case.
40    - Do not retry failing commands in a sleep loop — diagnose the root cause or consider an alternative approach.
41    - If waiting for a background task you started with `run_in_background`, you will be notified when it completes — do not poll.
42    - If you must poll an external process, use a check command rather than sleeping first.
43    - If you must sleep, keep the duration short (1-5 seconds) to avoid blocking the user."#)
44}
45
46/// PowerShell edition
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub enum PowerShellEdition {
49    Desktop, // Windows PowerShell 5.1
50    Core,    // PowerShell 7+
51}
52
53/// Get edition-specific section
54fn get_edition_section(edition: Option<PowerShellEdition>) -> String {
55    match edition {
56        Some(PowerShellEdition::Desktop) => {
57            "PowerShell edition: Windows PowerShell 5.1 (powershell.exe)
58   - Pipeline chain operators `&&` and `||` are NOT available — they cause a parser error. To run B only if A succeeds: `A; if ($?) { B }`. To chain unconditionally: `A; B`.
59   - Ternary (`?:`), null-coalescing (`??`), and null-conditional (`?.`) operators are NOT available. Use `if/else` and explicit `$null -eq` checks instead.
60   - Avoid `2>&1` on native executables. In 5.1, redirecting a native command's stderr inside PowerShell wraps each line in an ErrorRecord (NativeCommandError) and sets `$?` to `$false` even when the exe returned exit code 0. stderr is already captured for you — don't redirect it.
61   - Default file encoding is UTF-16 LE (with BOM). When writing files other tools will read, pass `-Encoding utf8` to `Out-File`/`Set-Content`.
62   - `ConvertFrom-Json` returns a PSCustomObject, not a hashtable. `-AsHashtable` is not available.".to_string()
63        }
64        Some(PowerShellEdition::Core) => {
65            "PowerShell edition: PowerShell 7+ (pwsh)
66   - Pipeline chain operators `&&` and `||` ARE available and work like bash. Prefer `cmd1 && cmd2` over `cmd1; cmd2` when cmd2 should only run if cmd1 succeeds.
67   - Ternary (`$cond ? $a : $b`), null-coalescing (`??`), and null-conditional (`?.`) operators are available.
68   - Default file encoding is UTF-8 without BOM.".to_string()
69        }
70        None => {
71            "PowerShell edition: unknown — assume Windows PowerShell 5.1 for compatibility
72   - Do NOT use `&&`, `||`, ternary `?:`, null-coalescing `??`, or null-conditional `?.`. These are PowerShell 7+ only and parser-error on 5.1.
73   - To chain commands conditionally: `A; if ($?) { B }`. Unconditionally: `A; B`.".to_string()
74        }
75    }
76}
77
78/// Get the full tool prompt
79pub async fn get_prompt() -> String {
80    let background_note = get_background_usage_note();
81    let sleep_guidance = get_sleep_guidance();
82
83    // Note: In Rust, we can't easily detect PowerShell edition at startup
84    // We'll return the unknown edition guidance by default
85    let edition_section = get_edition_section(None);
86
87    let mut prompt = format!(
88        r#"Executes a given PowerShell command with optional timeout. Working directory persists between commands; shell state (variables, functions) does not.
89
90IMPORTANT: This tool is for terminal operations via PowerShell: git, npm, docker, and PS cmdlets. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
91
92{}
93
94Before executing the command, please follow these steps:
95
961. Directory Verification:
97   - If the command will create new directories or files, first use `Get-ChildItem` (or `ls`) to verify the parent directory exists and is the correct location
98
992. Command Execution:
100   - Always quote file paths that contain spaces with double quotes
101   - Capture the output of the command.
102
103PowerShell Syntax Notes:
104   - Variables use $ prefix: $myVar = "value"
105   - Escape character is backtick (`), not backslash
106   - Use Verb-Noun cmdlet naming: Get-ChildItem, Set-Location, New-Item, Remove-Item
107   - Common aliases: ls (Get-ChildItem), cd (Set-Location), cat (Get-Content), rm (Remove-Item)
108   - Pipe operator | works similarly to bash but passes objects, not text
109   - Use Select-Object, Where-Object, ForEach-Object for filtering and transformation
110   - String interpolation: "Hello $name" or "Hello $($obj.Property)"
111   - Registry access uses PSDrive prefixes: `HKLM:\SOFTWARE\...`, `HKCU:\...` — NOT raw `HKEY_LOCAL_MACHINE\...`
112   - Environment variables: read with `$env:NAME`, set with `$env:NAME = "value"` (NOT `Set-Variable` or bash `export`)
113   - Call native exe with spaces in path via call operator: `& "C:\Program Files\App\app.exe" arg1 arg2`
114
115Interactive and blocking commands (will hang — this tool runs with -NonInteractive):
116   - NEVER use `Read-Host`, `Get-Credential`, `Out-GridView`, `$Host.UI.PromptForChoice`, or `pause`
117   - Destructive cmdlets (`Remove-Item`, `Stop-Process`, `Clear-Content`, etc.) may prompt for confirmation. Add `-Confirm:$false` when you intend the action to proceed. Use `-Force` for read-only/hidden items.
118   - Never use `git rebase -i`, `git add -i`, or other commands that open an interactive editor
119
120Passing multiline strings (commit messages, file content) to native executables:
121   - Use a single-quoted here-string so PowerShell does not expand `$` or backticks inside. The closing `'@` MUST be at column 0 (no leading whitespace) on its own line — indenting it is a parse error:
122<example>
123git commit -m @'
124Commit message here.
125Second line with $literal dollar signs.
126'@
127</example>
128   - Use `@'...'@` (single-quoted, literal) not `@"..."@` (double-quoted, interpolated) unless you need variable expansion
129   - For arguments containing `-`, `@`, or other characters PowerShell parses as operators, use the stop-parsing token: `git log --% --format=%H`
130
131Usage notes:
132  - The command argument is required.
133  - You can specify an optional timeout in milliseconds (up to {}ms / {} minutes). If not specified, commands will timeout after {}ms ({} minutes).
134  - It is very helpful if you write a clear, concise description of what this command does.
135  - If the output exceeds 30000 characters, output will be truncated before being returned to you.
136"#,
137        edition_section,
138        get_max_timeout_ms(),
139        get_max_timeout_ms() / 60000,
140        get_default_timeout_ms(),
141        get_default_timeout_ms() / 60000
142    );
143
144    if let Some(note) = background_note {
145        prompt.push_str(note);
146        prompt.push('\n');
147    }
148
149    prompt.push_str(
150        r#"  - Avoid using PowerShell to run commands that have dedicated tools, unless explicitly instructed:
151    - File search: Use Glob (NOT Get-ChildItem -Recurse)
152    - Content search: Use Grep (NOT Select-String)
153    - Read files: Use FileRead (NOT Get-Content)
154    - Edit files: Use FileEdit
155    - Write files: Use FileWrite (NOT Set-Content/Out-File)
156    - Communication: Output text directly (NOT Write-Output/Write-Host)
157  - When issuing multiple commands:
158    - If the commands are independent and can run in parallel, make multiple PowerShell tool calls in a single message.
159    - If the commands depend on each other and must run sequentially, chain them in a single PowerShell call (see edition-specific chaining syntax above).
160    - Use `;` only when you need to run commands sequentially but don't care if earlier commands fail.
161    - DO NOT use newlines to separate commands (newlines are ok in quoted strings and here-strings)
162  - Do NOT prefix commands with `cd` or `Set-Location` -- the working directory is already set to the correct project directory automatically.
163"#,
164    );
165
166    if let Some(guidance) = sleep_guidance {
167        prompt.push_str(guidance);
168        prompt.push('\n');
169    }
170
171    prompt.push_str(
172        "  - For git commands:\n\
173         - Prefer to create a new commit rather than amending an existing commit.\n\
174         - Before running destructive operations (e.g., git reset --hard, git push --force, git checkout --), consider whether there is a safer alternative that achieves the same goal. Only use destructive operations when they are truly the best approach.\n\
175         - Never skip hooks (--no-verify) or bypass signing (--no-gpg-sign, -c commit.gpgsign=false) unless the user has explicitly asked for it. If a hook fails, investigate and fix the underlying issue."
176    );
177
178    prompt
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn test_get_default_timeout_ms() {
187        let timeout = get_default_timeout_ms();
188        assert!(timeout > 0);
189        assert!(timeout <= get_max_timeout_ms());
190    }
191
192    #[test]
193    fn test_get_max_timeout_ms() {
194        let max = get_max_timeout_ms();
195        assert!(max > 0);
196    }
197
198    #[test]
199    fn test_default_less_than_max_timeout() {
200        assert!(get_default_timeout_ms() <= get_max_timeout_ms());
201    }
202
203    #[test]
204    fn test_default_timeout_reasonable() {
205        // Default should be between 30s and 5 minutes
206        let default = get_default_timeout_ms();
207        assert!(default >= 30_000);
208        assert!(default <= 300_000);
209    }
210
211    #[test]
212    fn test_max_timeout_reasonable() {
213        // Max should be at least 1 minute
214        let max = get_max_timeout_ms();
215        assert!(max >= 60_000);
216    }
217}