Skip to content

Commit dad7be3

Browse files
committed
forgot to include the check_llm_command for non bash
1 parent feb0668 commit dad7be3

File tree

2 files changed

+93
-70
lines changed

2 files changed

+93
-70
lines changed

npcsh/npcsh.py

Lines changed: 92 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import atexit
66
from datetime import datetime
77
import pandas as pd
8+
89
# Configure logging
910
import sqlite3
1011
from termcolor import colored
@@ -18,59 +19,63 @@
1819
enter_spool_mode,
1920
)
2021
from .helpers import (
21-
log_action,
22+
log_action,
2223
load_npc_from_file,
23-
list_directory,
24-
read_file,
24+
list_directory,
25+
read_file,
2526
ensure_npcshrc_exists,
2627
setup_npcsh_config,
27-
execute_java,
28-
execute_scala,
29-
execute_r,
30-
execute_sql,
31-
execute_python,
32-
BASH_COMMANDS,
33-
TERMINAL_EDITORS,
34-
open_terminal_editor,
35-
get_npc_from_command,
28+
execute_java,
29+
execute_scala,
30+
execute_r,
31+
execute_sql,
32+
execute_python,
33+
BASH_COMMANDS,
34+
TERMINAL_EDITORS,
35+
open_terminal_editor,
36+
get_npc_from_command,
3637
is_valid_npc,
37-
get_npc_path,
38-
initialize_base_npcs_if_needed,
38+
get_npc_path,
39+
initialize_base_npcs_if_needed,
3940
is_npcsh_initialized,
40-
set_npcsh_initialized,
41-
get_valid_npcs
41+
set_npcsh_initialized,
42+
get_valid_npcs,
4243
)
4344

4445
from .npc_compiler import NPCCompiler, NPC
4546
from colorama import Fore, Back, Style
4647

4748
import shlex
4849
import subprocess
50+
51+
4952
def get_file_color(filepath):
5053
if os.path.isdir(filepath):
5154
return "blue", ["bold"]
5255
elif os.access(filepath, os.X_OK):
5356
return "green", []
54-
elif filepath.endswith(('.zip', '.tar', '.gz', '.bz2', '.xz', '.7z')):
57+
elif filepath.endswith((".zip", ".tar", ".gz", ".bz2", ".xz", ".7z")):
5558
return "red", []
56-
elif filepath.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff')):
59+
elif filepath.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff")):
5760
return "magenta", []
58-
elif filepath.endswith(('.py', '.pyw')):
61+
elif filepath.endswith((".py", ".pyw")):
5962
return "yellow", []
60-
elif filepath.endswith(('.sh', '.bash', '.zsh')):
63+
elif filepath.endswith((".sh", ".bash", ".zsh")):
6164
return "green", []
62-
elif filepath.endswith(('.c', '.cpp', '.h', '.hpp')):
65+
elif filepath.endswith((".c", ".cpp", ".h", ".hpp")):
6366
return "cyan", []
64-
elif filepath.endswith(('.js', '.ts', '.jsx', '.tsx')):
67+
elif filepath.endswith((".js", ".ts", ".jsx", ".tsx")):
6568
return "yellow", []
66-
elif filepath.endswith(('.html', '.css', '.scss', '.sass')):
69+
elif filepath.endswith((".html", ".css", ".scss", ".sass")):
6770
return "magenta", []
68-
elif filepath.endswith(('.md', '.txt', '.log')):
71+
elif filepath.endswith((".md", ".txt", ".log")):
6972
return "white", []
70-
elif filepath.startswith('.'):
73+
elif filepath.startswith("."):
7174
return "cyan", []
7275
else:
7376
return "white", []
77+
78+
7479
def execute_command(command, command_history, db_path, npc_compiler, current_npc=None):
7580
subcommands = []
7681
output = ""
@@ -80,15 +85,15 @@ def execute_command(command, command_history, db_path, npc_compiler, current_npc
8085

8186
if current_npc is None:
8287
valid_npcs = get_valid_npcs(db_path)
83-
88+
8489
npc_name = get_npc_from_command(command)
8590
if npc_name is None:
8691
npc_name = "base" # Default NPC
87-
#print(npc_name)
92+
# print(npc_name)
8893
npc_path = get_npc_path(npc_name, db_path)
89-
npc = load_npc_from_file(npc_path, db_conn)
94+
npc = load_npc_from_file(npc_path, db_conn)
9095
else:
91-
npc = current_npc
96+
npc = current_npc
9297
if command.startswith("/"):
9398
command = command[1:]
9499
log_action("Command Executed", command)
@@ -98,10 +103,10 @@ def execute_command(command, command_history, db_path, npc_compiler, current_npc
98103
args = command_parts[1:]
99104
if current_npc is None and command_name in valid_npcs:
100105
npc_path = get_npc_path(command_name, db_path)
101-
npc = load_npc_from_file(npc_path, db_conn)
102-
106+
npc = load_npc_from_file(npc_path, db_conn)
107+
103108
if command_name == "compile" or command_name == "com":
104-
try:
109+
try:
105110
compiled_script = npc_compiler.compile(npc)
106111
output = f"Compiled NPC profile: {compiled_script}"
107112
print(output)
@@ -119,12 +124,12 @@ def execute_command(command, command_history, db_path, npc_compiler, current_npc
119124
# output = enter_observation_mode(command_history, npc=npc)
120125
elif command_name == "cmd" or command_name == "command":
121126
output = execute_llm_command(command, command_history, npc=npc)
122-
elif command_name == "set":
127+
elif command_name == "set":
123128
parts = command.split()
124129
if len(parts) == 3 and parts[1] in ["model", "provider", "db_path"]:
125-
output = execute_set_command(parts[1], parts[2])
130+
output = execute_set_command(parts[1], parts[2])
126131
else:
127-
return "Invalid set command. Usage: /set [model|provider|db_path] 'value_in_quotes' "
132+
return "Invalid set command. Usage: /set [model|provider|db_path] 'value_in_quotes' "
128133
elif command_name == "sample":
129134
output = execute_llm_question(command, command_history, npc=npc)
130135
elif command_name == "spool" or command_name == "sp":
@@ -139,7 +144,7 @@ def execute_command(command, command_history, db_path, npc_compiler, current_npc
139144

140145
output = enter_spool_mode(command_history, inherit_last, npc=npc)
141146
return output
142-
147+
143148
else:
144149
output = f"Unknown command: {command_name}"
145150

@@ -151,73 +156,81 @@ def execute_command(command, command_history, db_path, npc_compiler, current_npc
151156
language = command_parts[0].lower()
152157
code = " ".join(command_parts[1:])
153158

154-
if language == 'python':
159+
if language == "python":
155160
output = execute_python(code)
156-
elif language == 'r':
161+
elif language == "r":
157162
output = execute_r(code)
158-
elif language == 'sql':
163+
elif language == "sql":
159164
output = execute_sql(code)
160-
elif language == 'scala':
165+
elif language == "scala":
161166
output = execute_scala(code)
162-
elif language == 'java':
167+
elif language == "java":
163168
output = execute_java(code)
164169
else:
165170
output = check_llm_command(command, command_history, npc=npc)
166171
else:
167172
# Check if it's a bash command
168-
#print(command)
173+
# print(command)
169174
command_parts = shlex.split(command)
170-
171-
if command_parts[0] == 'cd':
175+
176+
if command_parts[0] == "cd":
172177
try:
173178
if len(command_parts) > 1:
174179
new_dir = os.path.expanduser(command_parts[1])
175180
else:
176-
new_dir = os.path.expanduser('~')
181+
new_dir = os.path.expanduser("~")
177182
os.chdir(new_dir)
178183
return f"Changed directory to {os.getcwd()}"
179184
except FileNotFoundError:
180185
return f"Directory not found: {new_dir}"
181186
except PermissionError:
182187
return f"Permission denied: {new_dir}"
183-
188+
184189
elif command_parts[0] in BASH_COMMANDS:
185190
if command_parts[0] in TERMINAL_EDITORS:
186191
return open_terminal_editor(command)
187192
else:
188193
try:
189-
result = subprocess.run(command_parts, capture_output=True, text=True)
194+
result = subprocess.run(
195+
command_parts, capture_output=True, text=True
196+
)
190197
output = result.stdout
191198
if result.stderr:
192199
output += colored(f"\nError: {result.stderr}", "red")
193-
200+
194201
# Color code the output
195202
colored_output = ""
196-
for line in output.split('\n'):
203+
for line in output.split("\n"):
197204
parts = line.split()
198205
if parts:
199206
filepath = parts[-1]
200207
color, attrs = get_file_color(filepath)
201208
colored_filepath = colored(filepath, color, attrs=attrs)
202-
colored_line = ' '.join(parts[:-1] + [colored_filepath])
209+
colored_line = " ".join(parts[:-1] + [colored_filepath])
203210
colored_output += colored_line + "\n"
204211
else:
205212
colored_output += line + "\n"
206-
213+
207214
output = colored_output.rstrip()
208-
215+
209216
if not output and result.returncode == 0:
210-
output = colored(f"Command '{command}' executed successfully (no output).", "green")
217+
output = colored(
218+
f"Command '{command}' executed successfully (no output).",
219+
"green",
220+
)
211221
except Exception as e:
212222
output = colored(f"Error executing command: {e}", "red")
213223

224+
else:
225+
output = check_llm_command(command, command_history, npc=npc)
226+
214227
# Add command to history
215228
command_history.add(command, subcommands, output, location)
216229

217230
# Print the output
218231
if output:
219232
print(output)
220-
233+
221234
return output
222235

223236

@@ -227,7 +240,7 @@ def setup_readline():
227240
readline.read_history_file(history_file)
228241
except FileNotFoundError:
229242
pass
230-
243+
231244
readline.set_history_length(1000)
232245
readline.parse_and_bind("set editing-mode vi")
233246
readline.parse_and_bind('"\e[A": history-search-backward')
@@ -236,47 +249,52 @@ def setup_readline():
236249

237250
return history_file
238251

252+
239253
def save_readline_history():
240254
readline.write_history_file(os.path.expanduser("~/.npcsh_readline_history"))
241255

256+
242257
def orange(text):
243258
return f"\033[38;2;255;165;0m{text}{Style.RESET_ALL}"
244259

260+
245261
def main():
246262
setup_npcsh_config()
247263
if "NPCSH_DB_PATH" in os.environ:
248264
db_path = os.path.expanduser(os.environ["NPCSH_DB_PATH"])
249265
else:
250-
db_path = os.path.expanduser('~/npcsh_history.db')
251-
266+
db_path = os.path.expanduser("~/npcsh_history.db")
267+
252268
command_history = CommandHistory(db_path)
253-
269+
254270
os.makedirs("./npc_profiles", exist_ok=True)
255271
npc_directory = os.path.expanduser("./npc_profiles")
256272
npc_compiler = NPCCompiler(npc_directory)
257-
273+
258274
if not is_npcsh_initialized():
259275
print("Initializing NPCSH...")
260276
initialize_base_npcs_if_needed(db_path)
261-
print("NPCSH initialization complete. Please restart your terminal or run 'source ~/.npcshrc' for the changes to take effect.")
277+
print(
278+
"NPCSH initialization complete. Please restart your terminal or run 'source ~/.npcshrc' for the changes to take effect."
279+
)
262280
history_file = setup_readline()
263281
atexit.register(readline.write_history_file, history_file)
264282
atexit.register(command_history.close)
265-
283+
266284
print("Welcome to npcsh!")
267-
285+
268286
current_npc = None
269287
while True:
270288
try:
271289
if current_npc:
272290
prompt = f"{colored(os.getcwd(), 'blue')}:{orange(current_npc.name)}> "
273291
else:
274292
prompt = f"{colored(os.getcwd(), 'blue')}:{orange('npcsh')}> "
275-
293+
276294
# After executing the command
277-
#print(f"{colored(os.getcwd(), 'blue')}$")
295+
# print(f"{colored(os.getcwd(), 'blue')}$")
278296
user_input = input(prompt).strip()
279-
297+
280298
if user_input.lower() in ["exit", "quit"]:
281299
if current_npc:
282300
print(f"Exiting {current_npc.name} mode.")
@@ -293,10 +311,14 @@ def main():
293311
npc_path = get_npc_path(command_name, db_path)
294312
db_conn = sqlite3.connect(db_path)
295313
current_npc = load_npc_from_file(npc_path, db_conn)
296-
print(f"Entered {current_npc.name} mode. Type 'exit' to return to main shell.")
314+
print(
315+
f"Entered {current_npc.name} mode. Type 'exit' to return to main shell."
316+
)
297317
continue
298-
299-
execute_command(user_input, command_history, db_path, npc_compiler, current_npc)
318+
319+
execute_command(
320+
user_input, command_history, db_path, npc_compiler, current_npc
321+
)
300322
except (KeyboardInterrupt, EOFError):
301323
if current_npc:
302324
print(f"\nExiting {current_npc.name} mode.")
@@ -305,5 +327,6 @@ def main():
305327
print("\nGoodbye!")
306328
break
307329

330+
308331
if __name__ == "__main__":
309-
main()
332+
main()

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def package_files(directory):
1414

1515
setup(
1616
name="npcsh",
17-
version="0.1.9",
17+
version="0.1.10",
1818
packages=find_packages(exclude=["tests*"]),
1919
install_requires=[
2020
"jinja2",

0 commit comments

Comments
 (0)