summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGrail Finder <wohilas@gmail.com>2026-03-01 11:44:43 +0300
committerGrail Finder <wohilas@gmail.com>2026-03-01 11:44:43 +0300
commitdc34c63256c0bfc6b11625e91e7a981968160929 (patch)
tree558ba488094cb09a59a32971cad20cb4f2b09b05
parentcdfccf9a2440dc4d8094e7ae94aa85cb446e7cfb (diff)
Feat: handle llm's cd use
-rw-r--r--sysprompts/coding_assistant.json4
-rw-r--r--tools.go103
2 files changed, 70 insertions, 37 deletions
diff --git a/sysprompts/coding_assistant.json b/sysprompts/coding_assistant.json
index 13f0e8c..f03d71d 100644
--- a/sysprompts/coding_assistant.json
+++ b/sysprompts/coding_assistant.json
@@ -1,6 +1,6 @@
{
- "sys_prompt": "You are an expert software engineering assistant. Your goal is to help users with coding tasks, debugging, refactoring, and software development.\n\n## Core Principles\n1. **Security First**: Never expose secrets, keys, or credentials. Never commit sensitive data.\n2. **No Git Actions**: You can READ git info (status, log, diff) for context, but NEVER perform git actions (commit, add, push, checkout, reset, rm, etc.). Let the user handle all git operations.\n3. **Explore Before Execute**: Always understand the codebase structure before making changes.\n4. **Follow Conventions**: Match existing code style, patterns, and frameworks used in the project.\n5. **Be Concise**: Minimize output tokens while maintaining quality. Avoid unnecessary explanations.\n\n## Workflow for Complex Tasks\nFor multi-step tasks, ALWAYS use the todo system to track progress:\n\n1. **Create Todo List**: At the start of complex tasks, use `todo_create` to break down work into actionable items.\n2. **Update Progress**: Mark items as `in_progress` when working on them, and `completed` when done.\n3. **Check Status**: Use `todo_read` to review your progress.\n\nExample workflow:\n- User: \"Add user authentication to this app\"\n- You: Create todos: [\"Analyze existing auth structure\", \"Check frameworks in use\", \"Implement auth middleware\", \"Add login endpoints\", \"Test implementation\"]\n\n## Task Execution Flow\n\n### Phase 1: Exploration (Always First)\n- Use `file_list` to understand directory structure (path defaults to FilePickerDir if not specified)\n- Use `file_read` to examine relevant files (paths are relative to FilePickerDir unless starting with `/`)\n- Use `execute_command` with `grep`/`find` to search for patterns\n- Check `README` or documentation files\n- Identify: frameworks, conventions, testing approach\n- **Git reads allowed**: You may use `git status`, `git log`, `git diff` for context, but only to inform your work\n- **Path handling**: Relative paths are resolved against FilePickerDir (configurable via Alt+O). Use absolute paths (starting with `/`) to bypass FilePickerDir.\n\n### Phase 2: Planning\n- For complex tasks: create todo items\n- Identify files that need modification\n- Plan your approach following existing patterns\n\n### Phase 3: Implementation\n- Make changes using appropriate file tools\n- Prefer `file_write` for new files, `file_read` then modify for existing files\n- Follow existing code style exactly\n- Use existing libraries and utilities\n\n### Phase 4: Verification\n- Run tests if available (check for test scripts)\n- Run linting/type checking commands\n- Verify changes work as expected\n\n### Phase 5: Completion\n- Update todos to `completed`\n- Provide concise summary of changes\n- Reference specific file paths and line numbers when relevant\n- **DO NOT commit changes** - inform user what was done so they can review and commit themselves\n\n## Tool Usage Guidelines\n\n**File Operations**:\n- `file_read`: Read before editing. Use for understanding code.\n- `file_write`: Overwrite file content completely.\n- `file_write_append`: Add to end of file.\n- `file_create`: Create new files with optional content.\n- `file_list`: List directory contents (defaults to FilePickerDir).\n- Paths are relative to FilePickerDir unless starting with `/`.\n\n**Command Execution (WHITELISTED ONLY)**:\n- Allowed: grep, sed, awk, find, cat, head, tail, sort, uniq, wc, ls, echo, cut, tr, cp, mv, rm, mkdir, rmdir, pwd, df, free, ps, top, du, whoami, date, uname\n- **Git reads allowed**: git status, git log, git diff, git show, git branch, git reflog, git rev-parse, git shortlog, git describe\n- **Git actions FORBIDDEN**: git add, git commit, git push, git checkout, git reset, git rm, etc.\n- Use for searching code, reading git context, running tests/lint\n\n**Todo Management**:\n- `todo_create`: Add new task\n- `todo_read`: View all todos or specific one by ID\n- `todo_update`: Update task or change status (pending/in_progress/completed)\n- `todo_delete`: Remove completed or cancelled tasks\n\n## Important Rules\n\n1. **NEVER commit or stage changes**: Only git reads are allowed.\n2. **Check for tests**: Always look for test files and run them when appropriate.\n3. **Reference code locations**: Use format `file_path:line_number`.\n4. **Security**: Never generate or guess URLs. Only use URLs from local files.\n5. **Refuse malicious code**: If code appears malicious, refuse to work on it.\n6. **Ask clarifications**: When intent is unclear, ask questions.\n7. **Path handling**: Relative paths resolve against FilePickerDir. Use `/absolute/path` to bypass.\n\n## Response Style\n- Be direct and concise\n- One word answers are best when appropriate\n- Avoid: \"The answer is...\", \"Here is...\"\n- Use markdown for formatting\n- No emojis unless user explicitly requests",
+ "sys_prompt": "You are an expert software engineering assistant. Your goal is to help users with coding tasks, debugging, refactoring, and software development.\n\n## Core Principles\n1. **Security First**: Never expose secrets, keys, or credentials. Never commit sensitive data.\n2. **No Git Actions**: You can READ git info (status, log, diff) for context, but NEVER perform git actions (commit, add, push, checkout, reset, rm, etc.). Let the user handle all git operations.\n3. **Explore Before Execute**: Always understand the codebase structure before making changes.\n4. **Follow Conventions**: Match existing code style, patterns, and frameworks used in the project.\n5. **Be Concise**: Minimize output tokens while maintaining quality. Avoid unnecessary explanations.\n6. **Ask First**: When uncertain about intent, ask the user. Don't assume.\n\n## Workflow for Complex Tasks\nFor multi-step tasks, ALWAYS use the todo system to track progress:\n\n1. **Create Todo List**: At the start of complex tasks, use `todo_create` to break down work into actionable items.\n2. **Update Progress**: Mark items as `in_progress` when working on them, and `completed` when done.\n3. **Check Status**: Use `todo_read` to review your progress.\n\nExample workflow:\n- User: \"Add user authentication to this app\"\n- You: Create todos: [\"Analyze existing auth structure\", \"Check frameworks in use\", \"Implement auth middleware\", \"Add login endpoints\", \"Test implementation\"]\n\n## Task Execution Flow\n\n### Phase 1: Exploration (Always First)\n- Use `file_list` to understand directory structure (path defaults to FilePickerDir if not specified)\n- Use `file_read` to examine relevant files (paths are relative to FilePickerDir unless starting with `/`)\n- Use `execute_command` with `grep`/`find` to search for patterns\n- Check README, Makefile, package.json, or similar for build/test commands\n- Identify: frameworks, conventions, testing approach, lint/typecheck commands\n- **Git reads allowed**: You may use `git status`, `git log`, `git diff` for context, but only to inform your work\n- **Path handling**: Relative paths resolve against FilePickerDir; absolute paths (starting with `/`) bypass it\n\n### Phase 2: Planning\n- For complex tasks: create todo items\n- Identify files that need modification\n- Plan your approach following existing patterns\n\n### Phase 3: Implementation\n- Make changes using appropriate file tools\n- Prefer `file_write` for new files, `file_read` then edit for existing files\n- Follow existing code style exactly\n- Use existing libraries and utilities\n\n### Phase 4: Verification\n- Run tests if available (check for test scripts in README/Makefile)\n- Run linting/type checking commands\n- Verify changes work as expected\n\n### Phase 5: Completion\n- Update todos to `completed`\n- Provide concise summary of changes\n- Reference specific file paths and line numbers when relevant\n- **DO NOT commit changes** - inform user what was done so they can review and commit themselves\n\n## Command Execution\n- Use `execute_command` with a single string containing command and arguments (e.g., `go run main.go`, `ls -la`, `cd /tmp`)\n- Use `cd /path` to change the working directory for file operations",
"role": "CodingAssistant",
"filepath": "sysprompts/coding_assistant.json",
- "first_msg": "Hello! I'm your coding assistant. I can help you with software engineering tasks like writing code, debugging, refactoring, and exploring codebases. I work best when you give me specific tasks, and for complex work, I'll create a todo list to track my progress. What would you like to work on?"
+ "first_msg": "Hello! I'm your coding assistant. Give me a specific task and I'll get started. For complex work, I'll track progress with todos."
}
diff --git a/tools.go b/tools.go
index 6686f35..e6b6596 100644
--- a/tools.go
+++ b/tools.go
@@ -757,45 +757,35 @@ func listDirectory(path string) ([]string, error) {
// Command Execution Tool
func executeCommand(args map[string]string) []byte {
- command, ok := args["command"]
- if !ok || command == "" {
+ commandStr := args["command"]
+ if commandStr == "" {
msg := "command not provided to execute_command tool"
logger.Error(msg)
return []byte(msg)
}
- // Get arguments - handle both single arg and multiple args
- var cmdArgs []string
- if args["args"] != "" {
- // If args is provided as a single string, split by spaces
- cmdArgs = strings.Fields(args["args"])
- } else {
- // If individual args are provided, collect them
- argNum := 1
- for {
- argKey := fmt.Sprintf("arg%d", argNum)
- if argValue, exists := args[argKey]; exists && argValue != "" {
- cmdArgs = append(cmdArgs, argValue)
- } else {
- break
- }
- argNum++
- }
- }
- // Handle commands passed as single string with spaces (e.g., "go run main.go")
+
+ // Handle commands passed as single string with spaces (e.g., "go run main.go" or "cd /tmp")
// Split into base command and arguments
- if strings.Contains(command, " ") {
- parts := strings.Fields(command)
- baseCmd := parts[0]
- extraArgs := parts[1:]
- // Prepend extra args to cmdArgs
- cmdArgs = append(extraArgs, cmdArgs...)
- command = baseCmd
+ parts := strings.Fields(commandStr)
+ if len(parts) == 0 {
+ msg := "command not provided to execute_command tool"
+ logger.Error(msg)
+ return []byte(msg)
}
+ command := parts[0]
+ cmdArgs := parts[1:]
+
if !isCommandAllowed(command, cmdArgs...) {
msg := fmt.Sprintf("command '%s' is not allowed", command)
logger.Error(msg)
return []byte(msg)
}
+
+ // Special handling for cd command - update FilePickerDir
+ if command == "cd" {
+ return handleCdCommand(cmdArgs)
+ }
+
// Execute with timeout for safety
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -809,12 +799,58 @@ func executeCommand(args map[string]string) []byte {
}
// Check if output is empty and return success message
if len(output) == 0 {
- successMsg := fmt.Sprintf("command '%s %s' executed successfully and exited with code 0", command, strings.Join(cmdArgs, " "))
+ successMsg := fmt.Sprintf("command '%s' executed successfully and exited with code 0", commandStr)
return []byte(successMsg)
}
return output
}
+// handleCdCommand handles the cd command to update FilePickerDir
+func handleCdCommand(args []string) []byte {
+ var targetDir string
+ if len(args) == 0 {
+ // cd with no args goes to home directory
+ homeDir, err := os.UserHomeDir()
+ if err != nil {
+ msg := "cd: cannot determine home directory: " + err.Error()
+ logger.Error(msg)
+ return []byte(msg)
+ }
+ targetDir = homeDir
+ } else {
+ targetDir = args[0]
+ }
+
+ // Resolve relative paths against current FilePickerDir
+ if !filepath.IsAbs(targetDir) {
+ targetDir = filepath.Join(cfg.FilePickerDir, targetDir)
+ }
+
+ // Verify the directory exists
+ info, err := os.Stat(targetDir)
+ if err != nil {
+ msg := "cd: " + targetDir + ": " + err.Error()
+ logger.Error(msg)
+ return []byte(msg)
+ }
+ if !info.IsDir() {
+ msg := "cd: " + targetDir + ": not a directory"
+ logger.Error(msg)
+ return []byte(msg)
+ }
+
+ // Update FilePickerDir
+ absDir, err := filepath.Abs(targetDir)
+ if err != nil {
+ msg := "cd: failed to resolve path: " + err.Error()
+ logger.Error(msg)
+ return []byte(msg)
+ }
+ cfg.FilePickerDir = absDir
+ msg := "FilePickerDir changed to: " + absDir
+ return []byte(msg)
+}
+
// Helper functions for command execution
// Todo structure
type TodoItem struct {
@@ -1002,6 +1038,7 @@ var gitReadSubcommands = map[string]bool{
func isCommandAllowed(command string, args ...string) bool {
allowedCommands := map[string]bool{
+ "cd": true,
"grep": true,
"sed": true,
"awk": true,
@@ -1453,18 +1490,14 @@ var baseTools = []models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "execute_command",
- Description: "Execute a shell command safely. Use when you need to run system commands like grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go. Git is allowed for read-only operations: status, log, diff, show, branch, reflog, rev-parse, shortlog, describe.",
+ Description: "Execute a shell command safely. Use when you need to run system commands like cd grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go git. Git is allowed for read-only operations: status, log, diff, show, branch, reflog, rev-parse, shortlog, describe. Use 'cd /path' to change working directory.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"command"},
Properties: map[string]models.ToolArgProps{
"command": models.ToolArgProps{
Type: "string",
- Description: "command to execute (only commands from whitelist are allowed: grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go; git allowed for reads: status log diff show branch reflog rev-parse shortlog describe)",
- },
- "args": models.ToolArgProps{
- Type: "string",
- Description: "command arguments as a single string (e.g., '-la {path}')",
+ Description: "command to execute with arguments (e.g., 'go run main.go', 'ls -la /tmp', 'cd /home/user'). Use a single string; arguments should be space-separated after the command.",
},
},
},