60255
Zn
Zoea-Nova / files
Zoea-Nova / documentation / guides / SHELL_COMMANDS_AND_COMPLETIONS.md
7.6 KB
1# Shell Commands and Completions in Go 2 3This document covers how to execute shell commands and implement shell completions in pure Go without requiring CGO. 4 5## Executing Shell Commands 6 7Go's standard library provides `os/exec` for running external commands. This is pure Go and requires no CGO. 8 9### Basic Command Execution 10 11```go 12import "os/exec" 13 14// Simple command with arguments 15cmd := exec.Command("ls", "-la", "/tmp") 16output, err := cmd.Output() 17if err != nil { 18 log.Fatal(err) 19} 20fmt.Println(string(output)) 21``` 22 23### Shell Pipelines 24 25```go 26// Run command through shell for pipelines 27cmd := exec.Command("bash", "-c", "echo hello | grep h") 28output, err := cmd.CombinedOutput() 29``` 30 31### Interactive Commands 32 33```go 34// Connect stdin/stdout/stderr 35cmd := exec.Command("/bin/bash") 36cmd.Stdin = os.Stdin 37cmd.Stdout = os.Stdout 38cmd.Stderr = os.Stderr 39err := cmd.Run() 40``` 41 42### With Timeout 43 44```go 45import "context" 46 47ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 48defer cancel() 49 50cmd := exec.CommandContext(ctx, "long-running-command") 51output, err := cmd.Output() 52if ctx.Err() == context.DeadlineExceeded { 53 log.Println("Command timed out") 54} 55``` 56 57### Capturing Output Separately 58 59```go 60var stdout, stderr bytes.Buffer 61cmd := exec.Command("some-command") 62cmd.Stdout = &stdout 63cmd.Stderr = &stderr 64 65err := cmd.Run() 66fmt.Println("stdout:", stdout.String()) 67fmt.Println("stderr:", stderr.String()) 68``` 69 70## MCP Tool Example 71 72If Zoea Nova needed a shell execution tool for Myses: 73 74```go 75// internal/mcp/tools.go 76 77func (r *Registry) registerShellTool() { 78 r.AddTool(Tool{ 79 Name: "run_command", 80 Description: "Execute a shell command", 81 InputSchema: map[string]interface{}{ 82 "type": "object", 83 "properties": map[string]interface{}{ 84 "command": map[string]interface{}{ 85 "type": "string", 86 "description": "Shell command to execute", 87 }, 88 "timeout": map[string]interface{}{ 89 "type": "number", 90 "description": "Timeout in seconds (default 30)", 91 }, 92 }, 93 "required": []string{"command"}, 94 }, 95 Handler: r.executeCommand, 96 }) 97} 98 99func (r *Registry) executeCommand(args map[string]interface{}) (interface{}, error) { 100 command := args["command"].(string) 101 timeout := 30 102 if t, ok := args["timeout"].(float64); ok { 103 timeout = int(t) 104 } 105 106 // Security: validate/sanitize command 107 // Consider allowlist of safe commands or restricted shell 108 109 ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second) 110 defer cancel() 111 112 cmd := exec.CommandContext(ctx, "bash", "-c", command) 113 output, err := cmd.CombinedOutput() 114 115 result := map[string]interface{}{ 116 "output": string(output), 117 "exitCode": 0, 118 } 119 120 if err != nil { 121 if exitErr, ok := err.(*exec.ExitError); ok { 122 result["exitCode"] = exitErr.ExitCode() 123 } else { 124 return nil, err 125 } 126 } 127 128 return result, nil 129} 130``` 131 132**Security Note**: Shell execution tools should be carefully designed with security in mind. Consider: 133- Command allowlists 134- Restricted shell environments 135- Input sanitization 136- Resource limits (timeout, memory, CPU) 137 138## Shell Completions 139 140Shell completions help users by auto-completing commands, flags, and arguments. All approaches below are pure Go. 141 142### Option 1: Cobra Framework (Recommended) 143 144[Cobra](https://github.com/spf13/cobra) is the standard for Go CLI applications and includes built-in completion generation. 145 146```go 147import "github.com/spf13/cobra" 148 149var rootCmd = &cobra.Command{ 150 Use: "zoea", 151 Short: "Zoea Nova - AI swarm controller", 152} 153 154func init() { 155 // Add flags 156 rootCmd.PersistentFlags().BoolP("debug", "d", false, "Enable debug logging") 157 rootCmd.PersistentFlags().StringP("config", "c", "", "Config file path") 158 159 // Add completion command 160 rootCmd.AddCommand(&cobra.Command{ 161 Use: "completion [bash|zsh|fish|powershell]", 162 Short: "Generate completion script", 163 Long: `Generate shell completion script. 164 165Example usage: 166 # Bash 167 zoea completion bash > /etc/bash_completion.d/zoea 168 169 # Zsh 170 zoea completion zsh > "${fpath[1]}/_zoea" 171 172 # Fish 173 zoea completion fish > ~/.config/fish/completions/zoea.fish 174`, 175 Args: cobra.ExactArgs(1), 176 Run: func(cmd *cobra.Command, args []string) { 177 switch args[0] { 178 case "bash": 179 rootCmd.GenBashCompletion(os.Stdout) 180 case "zsh": 181 rootCmd.GenZshCompletion(os.Stdout) 182 case "fish": 183 rootCmd.GenFishCompletion(os.Stdout, true) 184 case "powershell": 185 rootCmd.GenPowerShellCompletion(os.Stdout) 186 default: 187 fmt.Fprintf(os.Stderr, "Unsupported shell: %s\n", args[0]) 188 os.Exit(1) 189 } 190 }, 191 }) 192} 193``` 194 195**Installation:** 196```bash 197# Bash 198zoea completion bash | sudo tee /etc/bash_completion.d/zoea 199 200# Zsh 201zoea completion zsh > "${fpath[1]}/_zoea" 202 203# Fish 204zoea completion fish > ~/.config/fish/completions/zoea.fish 205``` 206 207### Option 2: posener/complete (Lightweight) 208 209[posener/complete](https://github.com/posener/complete) is a lightweight pure Go completion library. 210 211```go 212import "github.com/posener/complete" 213 214func main() { 215 zoea := complete.Command{ 216 Flags: complete.Flags{ 217 "-debug": complete.PredictNothing, 218 "-config": complete.PredictFiles("*.toml"), 219 }, 220 Sub: complete.Commands{ 221 "start": complete.Command{}, 222 "stop": complete.Command{}, 223 "list": complete.Command{}, 224 }, 225 } 226 227 cmp := complete.New("zoea", zoea) 228 cmp.Run() 229} 230``` 231 232### Option 3: Manual Generation 233 234For full control, generate completion scripts manually: 235 236```go 237const bashCompletion = ` 238_zoea_completion() { 239 local cur prev opts 240 COMPREPLY=() 241 cur="${COMP_WORDS[COMP_CWORD]}" 242 prev="${COMP_WORDS[COMP_CWORD-1]}" 243 opts="-debug -config -help" 244 245 case "${prev}" in 246 -config) 247 COMPREPLY=( $(compgen -f -X '!*.toml' -- ${cur}) ) 248 return 0 249 ;; 250 *) 251 ;; 252 esac 253 254 COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) 255} 256complete -F _zoea_completion zoea 257` 258 259func generateCompletion(shell string) { 260 switch shell { 261 case "bash": 262 fmt.Println(bashCompletion) 263 case "zsh": 264 fmt.Println(zshCompletion) 265 case "fish": 266 fmt.Println(fishCompletion) 267 default: 268 fmt.Fprintf(os.Stderr, "Unsupported shell: %s\n", shell) 269 os.Exit(1) 270 } 271} 272``` 273 274## Zoea Nova Context 275 276Zoea Nova is currently a TUI application, not a CLI with subcommands. Shell completions would be most useful if: 277 2781. **CLI commands are added** - e.g., `zoea list`, `zoea create`, `zoea delete` 2792. **Flag completion** - Complete `-debug`, `-config`, etc. 2803. **Config file paths** - Complete `*.toml` files for `-config` flag 281 282**Recommendation**: If CLI commands are added in the future, use **Cobra** for automatic completion generation. For now, basic flag completion can wait until needed. 283 284## Testing Completions 285 286```bash 287# Test bash completion manually 288source <(zoea completion bash) 289zoea <TAB><TAB> 290 291# Test with specific shell 292bash -c "source <(zoea completion bash) && complete -p zoea" 293``` 294 295## References 296 297- [os/exec Package](https://pkg.go.dev/os/exec) 298- [Cobra CLI Framework](https://github.com/spf13/cobra) 299- [posener/complete](https://github.com/posener/complete) 300- [Bash Completion Guide](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html)