-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.go
More file actions
301 lines (260 loc) · 6.19 KB
/
shell.go
File metadata and controls
301 lines (260 loc) · 6.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"
"github.com/peterh/liner"
"github.com/pterm/pterm"
)
// _---~~(~~-_.
// _{ ) )
// , ) -~~- ( ,-' )_
// ( `-,_..`., )-- '_,)
// ( ` _) ( -~( -_ `, }
// (_- _ ~_-~~~~`, ,' )
// `~ -^( __;-,((()))
// ~~~~ {_ -_(())
// `\ }
// { } Neurocli
type ShellCommand struct {
Name string
Description string
Handler func([]string) error
}
var (
shellCommands []ShellCommand
historyFile string
)
func init() {
home, _ := os.UserHomeDir()
historyFile = filepath.Join(home, ".neurocli_history")
shellCommands = []ShellCommand{
{
Name: "help",
Description: "Show this help message",
Handler: handleHelp,
},
{
Name: "exit",
Description: "Exit the shell",
Handler: handleExit,
},
{
Name: "clear",
Description: "Clear the screen",
Handler: handleClear,
},
{
Name: "cd",
Description: "Change directory",
Handler: handleChangeDir,
},
}
}
// newShell creates a new liner instance with configuration
func newShell() *liner.State {
line := liner.NewLiner()
line.SetTabCompletionStyle(liner.TabCircular)
line.SetCtrlCAborts(true)
// Set up command completion
var commands []string
for _, cmd := range shellCommands {
commands = append(commands, cmd.Name)
}
line.SetCompleter(func(line string) (c []string) {
for _, cmd := range commands {
if strings.HasPrefix(cmd, strings.ToLower(line)) {
c = append(c, cmd)
}
}
return
})
// Load history
if f, err := os.Open(historyFile); err == nil {
line.ReadHistory(f)
f.Close()
}
return line
}
// saveHistory saves the command history to a file
func saveHistory(line *liner.State) {
if f, err := os.Create(historyFile); err == nil {
line.WriteHistory(f)
f.Close()
}
}
// getPrompt returns a simple, reliable prompt string
func getPrompt() string {
return "> "
}
func handleShell() error {
line := newShell()
defer line.Close()
// Save history on exit
defer saveHistory(line)
// Save limited history on exit
defer func() {
if f, err := os.Create(historyFile); err == nil {
defer f.Close()
// WriteHistory will write the current history to the writer
line.WriteHistory(f)
}
}()
fmt.Println("NeuroCLI Shell - Type 'help' for commands, 'exit' to quit")
for {
input, err := line.Prompt(getPrompt())
if err != nil {
if err == liner.ErrPromptAborted {
fmt.Println("^C")
continue
}
return err
}
input = strings.TrimSpace(input)
if input == "" {
continue
}
line.AppendHistory(input)
parts := strings.Fields(input)
if len(parts) == 0 {
continue
}
cmd := strings.ToLower(parts[0])
args := parts[1:]
// Handle built-in commands
if handleBuiltInCommand(cmd, args) {
continue
}
// Handle shell commands (prefixed with '!')
if handleShellCommand(input) {
continue
}
// Handle as AI query
response, err := askAI(input)
if err != nil {
pterm.Error.Println("Error:", err)
continue
}
// If AI response is a command to execute
if strings.HasPrefix(response, "Command: ") {
cmdStr := strings.TrimSpace(strings.TrimPrefix(response, "Command: "))
if !isValidCommand(cmdStr) {
pterm.Error.Println("Invalid or potentially unsafe command.")
continue
}
pterm.Info.Println("Executing command:", cmdStr)
if err := executeCommand(cmdStr); err != nil {
pterm.Error.Println("Command failed:", err)
}
continue
}
// Print AI response with code block formatting if present
if strings.Contains(response, "```") {
parts := strings.Split(response, "```")
for i, part := range parts {
if i%2 == 1 { // Code block
fmt.Println("\n--- CODE ---")
fmt.Println(part)
fmt.Println("------------")
fmt.Println()
} else {
fmt.Print(part)
}
}
} else {
fmt.Println(response)
}
}
}
// handleBuiltInCommand encapsulates handling of built-in shell commands.
func handleBuiltInCommand(cmd string, args []string) bool {
for _, shellCmd := range shellCommands {
if shellCmd.Name == cmd {
if err := shellCmd.Handler(args); err != nil {
pterm.Error.Println(err)
}
return true
}
}
return false
}
// handleShellCommand encapsulates handling of shell commands (prefixed with '!').
func handleShellCommand(input string) bool {
if strings.HasPrefix(input, "!") {
cmdStr := strings.TrimSpace(input[1:])
if !isValidCommand(cmdStr) {
pterm.Error.Println("Invalid or potentially unsafe command.")
return true
}
if err := executeCommand(cmdStr); err != nil {
pterm.Error.Println("Command failed:", err)
}
return true
}
return false
}
// isValidCommand checks if a command is safe to execute
func isValidCommand(cmd string) bool {
// Define a list of allowed commands
allowedCommands := []string{
"ls", "pwd", "echo", "cat", "grep", "find", "ps",
"top", "df", "du", "date", "whoami", "uname",
}
// Split the command into parts
parts := strings.Fields(cmd)
if len(parts) == 0 {
return false
}
// Check if the command is in the allowed list
for _, allowed := range allowedCommands {
if parts[0] == allowed {
return true
}
}
return false
}
// Command handlers
func handleHelp(args []string) error {
t := table.New().
Border(lipgloss.NormalBorder()).
BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("63"))).
Headers("COMMAND", "DESCRIPTION")
for _, cmd := range shellCommands {
t.Row(cmd.Name, cmd.Description)
}
// Add AI commands
t.Row("!command", "Execute a shell command")
t.Row("query", "Ask a question to the AI")
fmt.Println(t.Render())
return nil
}
func handleExit(args []string) error {
pterm.Info.Println("Goodbye!")
os.Exit(0)
return nil
}
func handleClear(args []string) error {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/c", "cls")
} else {
cmd = exec.Command("clear")
}
cmd.Stdout = os.Stdout
return cmd.Run()
}
func handleChangeDir(args []string) error {
if len(args) == 0 {
home, err := os.UserHomeDir()
if err != nil {
return err
}
return os.Chdir(home)
}
return os.Chdir(args[0])
}