npcsh 0.3.32__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. npcsh/_state.py +942 -0
  2. npcsh/alicanto.py +1074 -0
  3. npcsh/guac.py +785 -0
  4. npcsh/mcp_helpers.py +357 -0
  5. npcsh/mcp_npcsh.py +822 -0
  6. npcsh/mcp_server.py +184 -0
  7. npcsh/npc.py +218 -0
  8. npcsh/npcsh.py +1161 -0
  9. npcsh/plonk.py +387 -269
  10. npcsh/pti.py +234 -0
  11. npcsh/routes.py +958 -0
  12. npcsh/spool.py +315 -0
  13. npcsh/wander.py +550 -0
  14. npcsh/yap.py +573 -0
  15. npcsh-1.0.0.dist-info/METADATA +596 -0
  16. npcsh-1.0.0.dist-info/RECORD +21 -0
  17. {npcsh-0.3.32.dist-info → npcsh-1.0.0.dist-info}/WHEEL +1 -1
  18. npcsh-1.0.0.dist-info/entry_points.txt +9 -0
  19. {npcsh-0.3.32.dist-info → npcsh-1.0.0.dist-info}/licenses/LICENSE +1 -1
  20. npcsh/audio.py +0 -569
  21. npcsh/audio_gen.py +0 -1
  22. npcsh/cli.py +0 -543
  23. npcsh/command_history.py +0 -566
  24. npcsh/conversation.py +0 -54
  25. npcsh/data_models.py +0 -46
  26. npcsh/dataframes.py +0 -171
  27. npcsh/embeddings.py +0 -168
  28. npcsh/helpers.py +0 -646
  29. npcsh/image.py +0 -298
  30. npcsh/image_gen.py +0 -79
  31. npcsh/knowledge_graph.py +0 -1006
  32. npcsh/llm_funcs.py +0 -2195
  33. npcsh/load_data.py +0 -83
  34. npcsh/main.py +0 -5
  35. npcsh/model_runner.py +0 -189
  36. npcsh/npc_compiler.py +0 -2879
  37. npcsh/npc_sysenv.py +0 -388
  38. npcsh/npc_team/assembly_lines/test_pipeline.py +0 -181
  39. npcsh/npc_team/corca.npc +0 -13
  40. npcsh/npc_team/foreman.npc +0 -7
  41. npcsh/npc_team/npcsh.ctx +0 -11
  42. npcsh/npc_team/sibiji.npc +0 -4
  43. npcsh/npc_team/templates/analytics/celona.npc +0 -0
  44. npcsh/npc_team/templates/hr_support/raone.npc +0 -0
  45. npcsh/npc_team/templates/humanities/eriane.npc +0 -4
  46. npcsh/npc_team/templates/it_support/lineru.npc +0 -0
  47. npcsh/npc_team/templates/marketing/slean.npc +0 -4
  48. npcsh/npc_team/templates/philosophy/maurawa.npc +0 -0
  49. npcsh/npc_team/templates/sales/turnic.npc +0 -4
  50. npcsh/npc_team/templates/software/welxor.npc +0 -0
  51. npcsh/npc_team/tools/bash_executer.tool +0 -32
  52. npcsh/npc_team/tools/calculator.tool +0 -8
  53. npcsh/npc_team/tools/code_executor.tool +0 -16
  54. npcsh/npc_team/tools/generic_search.tool +0 -27
  55. npcsh/npc_team/tools/image_generation.tool +0 -25
  56. npcsh/npc_team/tools/local_search.tool +0 -149
  57. npcsh/npc_team/tools/npcsh_executor.tool +0 -9
  58. npcsh/npc_team/tools/screen_cap.tool +0 -27
  59. npcsh/npc_team/tools/sql_executor.tool +0 -26
  60. npcsh/response.py +0 -272
  61. npcsh/search.py +0 -252
  62. npcsh/serve.py +0 -1467
  63. npcsh/shell.py +0 -524
  64. npcsh/shell_helpers.py +0 -3919
  65. npcsh/stream.py +0 -233
  66. npcsh/video.py +0 -52
  67. npcsh/video_gen.py +0 -69
  68. npcsh-0.3.32.data/data/npcsh/npc_team/bash_executer.tool +0 -32
  69. npcsh-0.3.32.data/data/npcsh/npc_team/calculator.tool +0 -8
  70. npcsh-0.3.32.data/data/npcsh/npc_team/celona.npc +0 -0
  71. npcsh-0.3.32.data/data/npcsh/npc_team/code_executor.tool +0 -16
  72. npcsh-0.3.32.data/data/npcsh/npc_team/corca.npc +0 -13
  73. npcsh-0.3.32.data/data/npcsh/npc_team/eriane.npc +0 -4
  74. npcsh-0.3.32.data/data/npcsh/npc_team/foreman.npc +0 -7
  75. npcsh-0.3.32.data/data/npcsh/npc_team/generic_search.tool +0 -27
  76. npcsh-0.3.32.data/data/npcsh/npc_team/image_generation.tool +0 -25
  77. npcsh-0.3.32.data/data/npcsh/npc_team/lineru.npc +0 -0
  78. npcsh-0.3.32.data/data/npcsh/npc_team/local_search.tool +0 -149
  79. npcsh-0.3.32.data/data/npcsh/npc_team/maurawa.npc +0 -0
  80. npcsh-0.3.32.data/data/npcsh/npc_team/npcsh.ctx +0 -11
  81. npcsh-0.3.32.data/data/npcsh/npc_team/npcsh_executor.tool +0 -9
  82. npcsh-0.3.32.data/data/npcsh/npc_team/raone.npc +0 -0
  83. npcsh-0.3.32.data/data/npcsh/npc_team/screen_cap.tool +0 -27
  84. npcsh-0.3.32.data/data/npcsh/npc_team/sibiji.npc +0 -4
  85. npcsh-0.3.32.data/data/npcsh/npc_team/slean.npc +0 -4
  86. npcsh-0.3.32.data/data/npcsh/npc_team/sql_executor.tool +0 -26
  87. npcsh-0.3.32.data/data/npcsh/npc_team/test_pipeline.py +0 -181
  88. npcsh-0.3.32.data/data/npcsh/npc_team/turnic.npc +0 -4
  89. npcsh-0.3.32.data/data/npcsh/npc_team/welxor.npc +0 -0
  90. npcsh-0.3.32.dist-info/METADATA +0 -779
  91. npcsh-0.3.32.dist-info/RECORD +0 -78
  92. npcsh-0.3.32.dist-info/entry_points.txt +0 -3
  93. {npcsh-0.3.32.dist-info → npcsh-1.0.0.dist-info}/top_level.txt +0 -0
npcsh/npcsh.py ADDED
@@ -0,0 +1,1161 @@
1
+ # Standard Library Imports
2
+ import os
3
+ import sys
4
+ import atexit
5
+ import subprocess
6
+ import shlex
7
+ import re
8
+ from datetime import datetime
9
+ import argparse
10
+ import importlib.metadata
11
+ import textwrap
12
+ from typing import Optional, List, Dict, Any, Tuple, Union
13
+ from dataclasses import dataclass, field
14
+ try:
15
+ from inspect import isgenerator
16
+ except:
17
+ pass
18
+ import platform
19
+ try:
20
+ from termcolor import colored
21
+ except:
22
+ pass
23
+
24
+ try:
25
+ import chromadb
26
+ except ImportError:
27
+ chromadb = None
28
+ import shutil
29
+
30
+ import yaml
31
+ # Local Application Imports
32
+ from npcsh._state import (
33
+ setup_npcsh_config,
34
+ is_npcsh_initialized,
35
+ initialize_base_npcs_if_needed,
36
+ orange,
37
+ interactive_commands,
38
+ BASH_COMMANDS,
39
+ log_action
40
+ )
41
+
42
+ from npcpy.npc_sysenv import (
43
+ print_and_process_stream_with_markdown,
44
+ render_markdown,
45
+ get_locally_available_models,
46
+ start_interactive_session,
47
+ get_model_and_provider,
48
+ )
49
+ from npcpy.routes import router
50
+ from npcpy.data.image import capture_screenshot
51
+ from npcpy.memory.command_history import (
52
+ CommandHistory,
53
+ save_conversation_message,
54
+ )
55
+ from npcpy.memory.knowledge_graph import breathe
56
+ from npcpy.memory.sleep import sleep, forget
57
+ from npcpy.npc_compiler import NPC, Team, load_jinxs_from_directory
58
+ from npcpy.llm_funcs import check_llm_command, get_llm_response, execute_llm_command
59
+ from npcpy.gen.embeddings import get_embeddings
60
+ try:
61
+ import readline
62
+ except:
63
+ print('no readline support, some features may not work as desired. ')
64
+ # --- Constants ---
65
+ try:
66
+ VERSION = importlib.metadata.version("npcpy")
67
+ except importlib.metadata.PackageNotFoundError:
68
+ VERSION = "unknown"
69
+
70
+ TERMINAL_EDITORS = ["vim", "emacs", "nano"]
71
+ EMBEDDINGS_DB_PATH = os.path.expanduser("~/npcsh_chroma.db")
72
+ HISTORY_DB_DEFAULT_PATH = os.path.expanduser("~/npcsh_history.db")
73
+ READLINE_HISTORY_FILE = os.path.expanduser("~/.npcsh_readline_history")
74
+ DEFAULT_NPC_TEAM_PATH = os.path.expanduser("~/.npcsh/npc_team/")
75
+ PROJECT_NPC_TEAM_PATH = "./npc_team/"
76
+
77
+ # --- Global Clients ---
78
+ try:
79
+ chroma_client = chromadb.PersistentClient(path=EMBEDDINGS_DB_PATH) if chromadb else None
80
+ except Exception as e:
81
+ print(f"Warning: Failed to initialize ChromaDB client at {EMBEDDINGS_DB_PATH}: {e}")
82
+ chroma_client = None
83
+
84
+ # --- Custom Exceptions ---
85
+ class CommandNotFoundError(Exception):
86
+ pass
87
+
88
+
89
+ from npcpy.modes._state import initial_state, ShellState
90
+
91
+ def readline_safe_prompt(prompt: str) -> str:
92
+ ansi_escape = re.compile(r"(\033\[[0-9;]*[a-zA-Z])")
93
+ return ansi_escape.sub(r"\001\1\002", prompt)
94
+
95
+ def print_jinxs(jinxs):
96
+ output = "Available jinxs:\n"
97
+ for jinx in jinxs:
98
+ output += f" {jinx.jinx_name}\n"
99
+ output += f" Description: {jinx.description}\n"
100
+ output += f" Inputs: {jinx.inputs}\n"
101
+ return output
102
+
103
+ def open_terminal_editor(command: str) -> str:
104
+ try:
105
+ os.system(command)
106
+ return 'Terminal editor closed.'
107
+ except Exception as e:
108
+ return f"Error opening terminal editor: {e}"
109
+
110
+ def get_multiline_input(prompt: str) -> str:
111
+ lines = []
112
+ current_prompt = prompt
113
+ while True:
114
+ try:
115
+ line = input(current_prompt)
116
+ if line.endswith("\\"):
117
+ lines.append(line[:-1])
118
+ current_prompt = readline_safe_prompt("> ")
119
+ else:
120
+ lines.append(line)
121
+ break
122
+ except EOFError:
123
+ print("Goodbye!")
124
+ sys.exit(0)
125
+ return "\n".join(lines)
126
+
127
+ def split_by_pipes(command: str) -> List[str]:
128
+ parts = []
129
+ current = ""
130
+ in_single_quote = False
131
+ in_double_quote = False
132
+ escape = False
133
+
134
+ for char in command:
135
+ if escape:
136
+ current += char
137
+ escape = False
138
+ elif char == '\\':
139
+ escape = True
140
+ current += char
141
+ elif char == "'" and not in_double_quote:
142
+ in_single_quote = not in_single_quote
143
+ current += char
144
+ elif char == '"' and not in_single_quote:
145
+ in_double_quote = not in_single_quote
146
+ current += char
147
+ elif char == '|' and not in_single_quote and not in_double_quote:
148
+ parts.append(current.strip())
149
+ current = ""
150
+ else:
151
+ current += char
152
+
153
+ if current:
154
+ parts.append(current.strip())
155
+ return parts
156
+
157
+ def parse_command_safely(cmd: str) -> List[str]:
158
+ try:
159
+ return shlex.split(cmd)
160
+ except ValueError as e:
161
+ if "No closing quotation" in str(e):
162
+ if cmd.count('"') % 2 == 1:
163
+ cmd += '"'
164
+ elif cmd.count("'") % 2 == 1:
165
+ cmd += "'"
166
+ try:
167
+ return shlex.split(cmd)
168
+ except ValueError:
169
+ return cmd.split()
170
+ else:
171
+ return cmd.split()
172
+
173
+ def get_file_color(filepath: str) -> tuple:
174
+ if not os.path.exists(filepath):
175
+ return "grey", []
176
+ if os.path.isdir(filepath):
177
+ return "blue", ["bold"]
178
+ elif os.access(filepath, os.X_OK) and not os.path.isdir(filepath):
179
+ return "green", ["bold"]
180
+ elif filepath.endswith((".zip", ".tar", ".gz", ".bz2", ".xz", ".7z")):
181
+ return "red", []
182
+ elif filepath.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff")):
183
+ return "magenta", []
184
+ elif filepath.endswith((".py", ".pyw")):
185
+ return "yellow", []
186
+ elif filepath.endswith((".sh", ".bash", ".zsh")):
187
+ return "green", []
188
+ elif filepath.endswith((".c", ".cpp", ".h", ".hpp")):
189
+ return "cyan", []
190
+ elif filepath.endswith((".js", ".ts", ".jsx", ".tsx")):
191
+ return "yellow", []
192
+ elif filepath.endswith((".html", ".css", ".scss", ".sass")):
193
+ return "magenta", []
194
+ elif filepath.endswith((".md", ".txt", ".log")):
195
+ return "white", []
196
+ elif os.path.basename(filepath).startswith("."):
197
+ return "cyan", []
198
+ else:
199
+ return "white", []
200
+
201
+ def format_file_listing(output: str) -> str:
202
+ colored_lines = []
203
+ current_dir = os.getcwd()
204
+ for line in output.strip().split("\n"):
205
+ parts = line.split()
206
+ if not parts:
207
+ colored_lines.append(line)
208
+ continue
209
+
210
+ filepath_guess = parts[-1]
211
+ potential_path = os.path.join(current_dir, filepath_guess)
212
+
213
+ color, attrs = get_file_color(potential_path)
214
+ colored_filepath = colored(filepath_guess, color, attrs=attrs)
215
+
216
+ if len(parts) > 1 :
217
+ # Handle cases like 'ls -l' where filename is last
218
+ colored_line = " ".join(parts[:-1] + [colored_filepath])
219
+ else:
220
+ # Handle cases where line is just the filename
221
+ colored_line = colored_filepath
222
+
223
+ colored_lines.append(colored_line)
224
+
225
+ return "\n".join(colored_lines)
226
+
227
+ def wrap_text(text: str, width: int = 80) -> str:
228
+ lines = []
229
+ for paragraph in text.split("\n"):
230
+ if len(paragraph) > width:
231
+ lines.extend(textwrap.wrap(paragraph, width=width, replace_whitespace=False, drop_whitespace=False))
232
+ else:
233
+ lines.append(paragraph)
234
+ return "\n".join(lines)
235
+
236
+ # --- Readline Setup and Completion ---
237
+
238
+ def setup_readline() -> str:
239
+ try:
240
+ readline.read_history_file(READLINE_HISTORY_FILE)
241
+
242
+ readline.set_history_length(1000)
243
+ readline.parse_and_bind("set enable-bracketed-paste on")
244
+ #readline.parse_and_bind('"\e[A": history-search-backward')
245
+ #readline.parse_and_bind('"\e[B": history-search-forward')
246
+ readline.parse_and_bind(r'"\C-r": reverse-search-history')
247
+ readline.parse_and_bind(r'"\C-e": end-of-line')
248
+ readline.parse_and_bind(r'"\C-a": beginning-of-line')
249
+ #if sys.platform == "darwin":
250
+ # readline.parse_and_bind("bind ^I rl_complete")
251
+ #else:
252
+ # readline.parse_and_bind("tab: complete")
253
+
254
+ return READLINE_HISTORY_FILE
255
+
256
+
257
+ except FileNotFoundError:
258
+ pass
259
+ except OSError as e:
260
+ print(f"Warning: Could not read readline history file {READLINE_HISTORY_FILE}: {e}")
261
+
262
+ def save_readline_history():
263
+ try:
264
+ readline.write_history_file(READLINE_HISTORY_FILE)
265
+ except OSError as e:
266
+ print(f"Warning: Could not write readline history file {READLINE_HISTORY_FILE}: {e}")
267
+
268
+
269
+ # --- Placeholder for actual valid commands ---
270
+ # This should be populated dynamically based on router, builtins, and maybe PATH executables
271
+ valid_commands_list = list(router.routes.keys()) + list(interactive_commands.keys()) + ["cd", "exit", "quit"] + BASH_COMMANDS
272
+
273
+ def complete(text: str, state: int) -> Optional[str]:
274
+ try:
275
+ buffer = readline.get_line_buffer()
276
+ except:
277
+ print('couldnt get readline buffer')
278
+ line_parts = parse_command_safely(buffer) # Use safer parsing
279
+ word_before_cursor = ""
280
+ if len(line_parts) > 0 and not buffer.endswith(' '):
281
+ current_word = line_parts[-1]
282
+ else:
283
+ current_word = "" # Completing after a space
284
+
285
+ try:
286
+ # Command completion (start of line or after pipe/semicolon)
287
+ # This needs refinement to detect context better
288
+ is_command_start = not line_parts or (len(line_parts) == 1 and not buffer.endswith(' ')) # Basic check
289
+ if is_command_start and not text.startswith('-'): # Don't complete options as commands
290
+ cmd_matches = [cmd + ' ' for cmd in valid_commands_list if cmd.startswith(text)]
291
+ # Add executables from PATH? (Can be slow)
292
+ # path_executables = [f + ' ' for f in shutil.get_exec_path() if os.path.basename(f).startswith(text)]
293
+ # cmd_matches.extend(path_executables)
294
+ return cmd_matches[state]
295
+
296
+ # File/Directory completion (basic)
297
+ # Improve context awareness (e.g., after 'cd', 'ls', 'cat', etc.)
298
+ if text and (not text.startswith('/') or os.path.exists(os.path.dirname(text))):
299
+ basedir = os.path.dirname(text)
300
+ prefix = os.path.basename(text)
301
+ search_dir = basedir if basedir else '.'
302
+ try:
303
+ matches = [os.path.join(basedir, f) + ('/' if os.path.isdir(os.path.join(search_dir, f)) else ' ')
304
+ for f in os.listdir(search_dir) if f.startswith(prefix)]
305
+ return matches[state]
306
+ except OSError: # Handle permission denied etc.
307
+ return None
308
+
309
+ except IndexError:
310
+ return None
311
+ except Exception: # Catch broad exceptions during completion
312
+ return None
313
+
314
+ return None
315
+
316
+
317
+ # --- Command Execution Logic ---
318
+
319
+ def store_command_embeddings(command: str, output: Any, state: ShellState):
320
+ if not chroma_client or not state.embedding_model or not state.embedding_provider:
321
+ if not chroma_client: print("Warning: ChromaDB client not available for embeddings.", file=sys.stderr)
322
+ return
323
+ if not command and not output:
324
+ return
325
+
326
+ try:
327
+ output_str = str(output) if output else ""
328
+ if not command and not output_str: return # Avoid empty embeddings
329
+
330
+ texts_to_embed = [command, output_str]
331
+
332
+ embeddings = get_embeddings(
333
+ texts_to_embed,
334
+ state.embedding_model,
335
+ state.embedding_provider,
336
+ )
337
+
338
+ if not embeddings or len(embeddings) != 2:
339
+ print(f"Warning: Failed to generate embeddings for command: {command[:50]}...", file=sys.stderr)
340
+ return
341
+
342
+ timestamp = datetime.now().isoformat()
343
+ npc_name = state.npc.name if isinstance(state.npc, NPC) else state.npc
344
+
345
+ metadata = [
346
+ {
347
+ "type": "command", "timestamp": timestamp, "path": state.current_path,
348
+ "npc": npc_name, "conversation_id": state.conversation_id,
349
+ },
350
+ {
351
+ "type": "response", "timestamp": timestamp, "path": state.current_path,
352
+ "npc": npc_name, "conversation_id": state.conversation_id,
353
+ },
354
+ ]
355
+
356
+ collection_name = f"{state.embedding_provider}_{state.embedding_model}_embeddings"
357
+ try:
358
+ collection = chroma_client.get_or_create_collection(collection_name)
359
+ ids = [f"cmd_{timestamp}_{hash(command)}", f"resp_{timestamp}_{hash(output_str)}"]
360
+
361
+ collection.add(
362
+ embeddings=embeddings,
363
+ documents=texts_to_embed,
364
+ metadatas=metadata,
365
+ ids=ids,
366
+ )
367
+ except Exception as e:
368
+ print(f"Warning: Failed to add embeddings to collection '{collection_name}': {e}", file=sys.stderr)
369
+
370
+ except Exception as e:
371
+ print(f"Warning: Failed to store embeddings: {e}", file=sys.stderr)
372
+
373
+
374
+ def handle_interactive_command(cmd_parts: List[str], state: ShellState) -> Tuple[ShellState, str]:
375
+ command_name = cmd_parts[0]
376
+ print(f"Starting interactive {command_name} session...")
377
+ try:
378
+ return_code = start_interactive_session(
379
+ interactive_commands[command_name], cmd_parts[1:]
380
+ )
381
+ output = f"Interactive {command_name} session ended with return code {return_code}"
382
+ except Exception as e:
383
+ output = f"Error starting interactive session {command_name}: {e}"
384
+ return state, output
385
+
386
+ def handle_cd_command(cmd_parts: List[str], state: ShellState) -> Tuple[ShellState, str]:
387
+ original_path = os.getcwd()
388
+ target_path = cmd_parts[1] if len(cmd_parts) > 1 else os.path.expanduser("~")
389
+ try:
390
+ os.chdir(target_path)
391
+ state.current_path = os.getcwd()
392
+ output = f"Changed directory to {state.current_path}"
393
+ except FileNotFoundError:
394
+ output = colored(f"cd: no such file or directory: {target_path}", "red")
395
+ except Exception as e:
396
+ output = colored(f"cd: error changing directory: {e}", "red")
397
+ os.chdir(original_path) # Revert if error
398
+
399
+ return state, output
400
+
401
+
402
+ def handle_bash_command(
403
+ cmd_parts: List[str],
404
+ cmd_str: str,
405
+ stdin_input: Optional[str],
406
+ state: ShellState,
407
+ ) -> Tuple[ShellState, str]:
408
+
409
+ command_name = cmd_parts[0]
410
+
411
+ if command_name in TERMINAL_EDITORS:
412
+ output = open_terminal_editor(cmd_str)
413
+ return state, output
414
+
415
+ try:
416
+ process = subprocess.Popen(
417
+ cmd_parts,
418
+ stdin=subprocess.PIPE if stdin_input is not None else None,
419
+ stdout=subprocess.PIPE,
420
+ stderr=subprocess.PIPE,
421
+ text=True,
422
+ cwd=state.current_path
423
+ )
424
+
425
+ stdout, stderr = process.communicate(input=stdin_input)
426
+
427
+ if process.returncode != 0:
428
+ err_msg = stderr.strip() if stderr else f"Command '{cmd_str}' failed with return code {process.returncode}."
429
+ # If it failed because command not found, raise specific error for fallback
430
+ if "No such file or directory" in err_msg or "command not found" in err_msg:
431
+ raise CommandNotFoundError(err_msg)
432
+ # Otherwise, return the error output
433
+ full_output = stdout.strip() + ("\n" + colored(f"stderr: {err_msg}", "red") if err_msg else "")
434
+ return state, full_output.strip()
435
+
436
+
437
+ output = stdout.strip() if stdout else ""
438
+ if stderr:
439
+ # Log stderr but don't necessarily include in piped output unless requested
440
+ print(colored(f"stderr: {stderr.strip()}", "yellow"), file=sys.stderr)
441
+
442
+
443
+ if command_name in ["ls", "find", "dir"]:
444
+ output = format_file_listing(output)
445
+ elif not output and process.returncode == 0 and not stderr:
446
+ output = "" # No output is valid, don't print success message if piping
447
+
448
+ return state, output
449
+
450
+ except FileNotFoundError:
451
+ raise CommandNotFoundError(f"Command not found: {command_name}")
452
+ except PermissionError as e:
453
+ return state, colored(f"Error executing '{cmd_str}': Permission denied. {e}", "red")
454
+ except Exception as e:
455
+ return state, colored(f"Error executing command '{cmd_str}': {e}", "red")
456
+
457
+
458
+ def execute_slash_command(command: str, stdin_input: Optional[str], state: ShellState, stream: bool) -> Tuple[ShellState, Any]:
459
+ """Executes slash commands using the router or checking NPC/Team jinxs."""
460
+ command_parts = command.split()
461
+ command_name = command_parts[0].lstrip('/')
462
+ handler = router.get_route(command_name)
463
+ #print(handler)
464
+ if handler:
465
+ # Prepare kwargs for the handler
466
+ handler_kwargs = {
467
+ 'stream': stream,
468
+ 'npc': state.npc,
469
+ 'team': state.team,
470
+ 'messages': state.messages,
471
+ 'model': state.chat_model,
472
+ 'provider': state.chat_provider,
473
+ 'api_url': state.api_url,
474
+ 'api_key': state.api_key,
475
+ }
476
+ #print(handler_kwargs, command)
477
+ if stdin_input is not None:
478
+ handler_kwargs['stdin_input'] = stdin_input
479
+
480
+ try:
481
+ result_dict = handler(command, **handler_kwargs)
482
+
483
+ if isinstance(result_dict, dict):
484
+ #some respond with output, some with response, needs to be fixed upstream
485
+ output = result_dict.get("output") or result_dict.get("response")
486
+ state.messages = result_dict.get("messages", state.messages)
487
+ return state, output
488
+ else:
489
+ return state, result_dict
490
+
491
+ except Exception as e:
492
+ import traceback
493
+ print(f"Error executing slash command '{command_name}':", file=sys.stderr)
494
+ traceback.print_exc()
495
+ return state, colored(f"Error executing slash command '{command_name}': {e}", "red")
496
+
497
+ active_npc = state.npc if isinstance(state.npc, NPC) else None
498
+ jinx_to_execute = None
499
+ executor = None
500
+ if active_npc and command_name in active_npc.jinxs_dict:
501
+ jinx_to_execute = active_npc.jinxs_dict[command_name]
502
+ executor = active_npc
503
+ elif state.team and command_name in state.team.jinxs_dict:
504
+ jinx_to_execute = state.team.jinxs_dict[command_name]
505
+ executor = state.team
506
+
507
+ if jinx_to_execute:
508
+ args = command_parts[1:]
509
+ try:
510
+ jinx_output = jinx_to_execute.run(
511
+ *args,
512
+ state=state,
513
+ stdin_input=stdin_input,
514
+ messages=state.messages # Pass messages explicitly if needed
515
+ )
516
+ return state, jinx_output
517
+ except Exception as e:
518
+ import traceback
519
+ print(f"Error executing jinx '{command_name}':", file=sys.stderr)
520
+ traceback.print_exc()
521
+ return state, colored(f"Error executing jinx '{command_name}': {e}", "red")
522
+
523
+ if state.team and command_name in state.team.npcs:
524
+ new_npc = state.team.npcs[command_name]
525
+ state.npc = new_npc # Update state directly
526
+ return state, f"Switched to NPC: {new_npc.name}"
527
+
528
+ return state, colored(f"Unknown slash command or jinx: {command_name}", "red")
529
+
530
+
531
+ def process_pipeline_command(
532
+ cmd_segment: str,
533
+ stdin_input: Optional[str],
534
+ state: ShellState,
535
+ stream_final: bool
536
+ ) -> Tuple[ShellState, Any]:
537
+
538
+ if not cmd_segment:
539
+ return state, stdin_input
540
+
541
+ available_models_all = get_locally_available_models(state.current_path)
542
+ available_models_all_list = [item for key, item in available_models_all.items()]
543
+ model_override, provider_override, cmd_cleaned = get_model_and_provider(
544
+ cmd_segment, available_models_all_list
545
+ )
546
+ cmd_to_process = cmd_cleaned.strip()
547
+ if not cmd_to_process:
548
+ return state, stdin_input
549
+
550
+ exec_model = model_override or state.chat_model
551
+ exec_provider = provider_override or state.chat_provider
552
+
553
+ if cmd_to_process.startswith("/"):
554
+ #print(cmd_to_process)
555
+ return execute_slash_command(cmd_to_process, stdin_input, state, stream_final)
556
+ else:
557
+ try:
558
+ cmd_parts = parse_command_safely(cmd_to_process)
559
+ if not cmd_parts:
560
+ return state, stdin_input
561
+
562
+ command_name = cmd_parts[0]
563
+
564
+ if command_name in interactive_commands:
565
+ return handle_interactive_command(cmd_parts, state)
566
+ elif command_name == "cd":
567
+ return handle_cd_command(cmd_parts, state)
568
+ else:
569
+ try:
570
+ bash_state, bash_output = handle_bash_command(cmd_parts, cmd_to_process, stdin_input, state)
571
+ return bash_state, bash_output
572
+ except CommandNotFoundError:
573
+ full_llm_cmd = f"{cmd_to_process} {stdin_input}" if stdin_input else cmd_to_process
574
+
575
+ llm_result = check_llm_command(
576
+ command = full_llm_cmd,
577
+ model = exec_model,
578
+ provider = exec_provider,
579
+ api_url = state.api_url,
580
+ api_key = state.api_key,
581
+ npc = state.npc,
582
+ team = state.team,
583
+ messages = state.messages,
584
+ images = state.attachments,
585
+ stream = stream_final,
586
+ context = None ,
587
+ shell = True,
588
+
589
+ )
590
+ if isinstance(llm_result, dict):
591
+ state.messages = llm_result.get("messages", state.messages)
592
+ output = llm_result.get("output")
593
+ return state, output
594
+ else:
595
+ return state, llm_result
596
+
597
+ except Exception as bash_err:
598
+ return state, colored(f"Bash execution failed: {bash_err}", "red")
599
+
600
+ except Exception as e:
601
+ import traceback
602
+ traceback.print_exc()
603
+ return state, colored(f"Error processing command '{cmd_segment[:50]}...': {e}", "red")
604
+ def check_mode_switch(command:str , state: ShellState):
605
+ if command in ['/cmd', '/agent', '/chat', '/ride']:
606
+ state.current_mode = command[1:]
607
+ return True, state
608
+
609
+ return False, state
610
+ def execute_command(
611
+ command: str,
612
+ state: ShellState,
613
+ ) -> Tuple[ShellState, Any]:
614
+
615
+ if not command.strip():
616
+ return state, ""
617
+ mode_change, state = check_mode_switch(command, state)
618
+ if mode_change:
619
+ return state, 'Mode changed.'
620
+
621
+ original_command_for_embedding = command
622
+ commands = split_by_pipes(command)
623
+ stdin_for_next = None
624
+ final_output = None
625
+ current_state = state
626
+ if state.current_mode == 'agent':
627
+ for i, cmd_segment in enumerate(commands):
628
+ is_last_command = (i == len(commands) - 1)
629
+ stream_this_segment = is_last_command and state.stream_output # Use state's stream setting
630
+
631
+ try:
632
+ current_state, output = process_pipeline_command(
633
+ cmd_segment.strip(),
634
+ stdin_for_next,
635
+ current_state,
636
+ stream_final=stream_this_segment
637
+ )
638
+
639
+ if is_last_command:
640
+ final_output = output # Capture the output of the last command
641
+
642
+ if isinstance(output, str):
643
+ stdin_for_next = output
644
+ elif isgenerator(output):
645
+ if not stream_this_segment: # If intermediate output is a stream, consume for piping
646
+ full_stream_output = "".join(map(str, output))
647
+ stdin_for_next = full_stream_output
648
+ if is_last_command: final_output = full_stream_output
649
+ else: # Final output is a stream, don't consume, can't pipe
650
+ stdin_for_next = None
651
+ final_output = output
652
+ elif output is not None: # Try converting other types to string
653
+ try: stdin_for_next = str(output)
654
+ except Exception:
655
+ print(f"Warning: Cannot convert output to string for piping: {type(output)}", file=sys.stderr)
656
+ stdin_for_next = None
657
+ else: # Output was None
658
+ stdin_for_next = None
659
+
660
+
661
+ except Exception as pipeline_error:
662
+ import traceback
663
+ traceback.print_exc()
664
+ error_msg = colored(f"Error in pipeline stage {i+1} ('{cmd_segment[:50]}...'): {pipeline_error}", "red")
665
+ # Return the state as it was when the error occurred, and the error message
666
+ return current_state, error_msg
667
+
668
+ # Store embeddings using the final state
669
+ if final_output is not None and not (isgenerator(final_output) and current_state.stream_output):
670
+ store_command_embeddings(original_command_for_embedding, final_output, current_state)
671
+
672
+ # Return the final state and the final output
673
+ return current_state, final_output
674
+
675
+
676
+ elif state.current_mode == 'chat':
677
+ # Only treat as bash if it looks like a shell command (starts with known command or is a slash command)
678
+ cmd_parts = parse_command_safely(command)
679
+ is_probably_bash = (
680
+ cmd_parts
681
+ and (
682
+ cmd_parts[0] in interactive_commands
683
+ or cmd_parts[0] in BASH_COMMANDS
684
+ or command.strip().startswith("./")
685
+ or command.strip().startswith("/")
686
+ )
687
+ )
688
+ if is_probably_bash:
689
+ try:
690
+ command_name = cmd_parts[0]
691
+ if command_name in interactive_commands:
692
+ return handle_interactive_command(cmd_parts, state)
693
+ elif command_name == "cd":
694
+ return handle_cd_command(cmd_parts, state)
695
+ else:
696
+ try:
697
+ bash_state, bash_output = handle_bash_command(cmd_parts, command, None, state)
698
+ return bash_state, bash_output
699
+ except CommandNotFoundError:
700
+ pass # Fall through to LLM
701
+ except Exception as bash_err:
702
+ return state, colored(f"Bash execution failed: {bash_err}", "red")
703
+ except Exception:
704
+ pass # Fall through to LLM
705
+
706
+ # Otherwise, treat as chat (LLM)
707
+ response = get_llm_response(
708
+ command,
709
+ model=state.chat_model,
710
+ provider=state.chat_provider,
711
+ npc=state.npc,
712
+ stream=state.stream_output,
713
+ messages=state.messages
714
+ )
715
+ state.messages = response['messages']
716
+ return state, response['response']
717
+
718
+ elif state.current_mode == 'cmd':
719
+
720
+ response = execute_llm_command(command,
721
+ model = state.chat_model,
722
+ provider = state.chat_provider,
723
+ npc = state.npc,
724
+ stream = state.stream_output,
725
+ messages = state.messages)
726
+ state.messages = response['messages']
727
+ return state, response['response']
728
+
729
+ elif state.current_mode == 'ride':
730
+ # Allow bash commands in /ride mode
731
+ cmd_parts = parse_command_safely(command)
732
+ is_probably_bash = (
733
+ cmd_parts
734
+ and (
735
+ cmd_parts[0] in interactive_commands
736
+ or cmd_parts[0] in BASH_COMMANDS
737
+ or command.strip().startswith("./")
738
+ or command.strip().startswith("/")
739
+ )
740
+ )
741
+ if is_probably_bash:
742
+ try:
743
+ command_name = cmd_parts[0]
744
+ if command_name in interactive_commands:
745
+ return handle_interactive_command(cmd_parts, state)
746
+ elif command_name == "cd":
747
+ return handle_cd_command(cmd_parts, state)
748
+ else:
749
+ try:
750
+ bash_state, bash_output = handle_bash_command(cmd_parts, command, None, state)
751
+ return bash_state, bash_output
752
+ except CommandNotFoundError:
753
+ return state, colored(f"Command not found: {command_name}", "red")
754
+ except Exception as bash_err:
755
+ return state, colored(f"Bash execution failed: {bash_err}", "red")
756
+ except Exception:
757
+ return state, colored("Failed to parse or execute bash command.", "red")
758
+
759
+ # Otherwise, run the agentic ride loop
760
+ return agentic_ride_loop(command, state)
761
+
762
+
763
+ def agentic_ride_loop(user_goal: str, state: ShellState) -> tuple:
764
+ """
765
+ /ride mode: orchestrate via team, then LLM suggests 3 next steps, user picks or provides alternative input
766
+ repeat until quit.
767
+
768
+ """
769
+ if not hasattr(state, "team") or state.team is None:
770
+ raise ValueError("No team found in shell state for orchestration.")
771
+
772
+ request = user_goal
773
+ all_results = []
774
+
775
+ while True:
776
+ # 1. Orchestrate the current request
777
+ result = state.team.orchestrate(request)
778
+ all_results.append(result)
779
+ render_markdown("# Orchestration Result")
780
+ render_markdown(f"- Request: {request}")
781
+ render_markdown(f"- Final response: {result.get('output')}")
782
+
783
+ render_markdown('- Summary: '+result['debrief']['summary'])
784
+ recommendations = result['debrief']['recommendations']
785
+ render_markdown(f'- Recommendations: {recommendations}')
786
+
787
+
788
+ # 2. Ask LLM for three next possible steps
789
+ suggestion_prompt = f"""
790
+ Given the following user goal and orchestration result, suggest three new
791
+ avenues to go down that are related but distinct from the original goal and from each other.
792
+
793
+ Be concise. Each step should be a single actionable instruction or question.
794
+
795
+ User goal: {user_goal}
796
+ Orchestration result: {result}
797
+
798
+ Return a JSON object with a "steps" key, whose value is a list of three strings, each string being a next step.
799
+ Return only the JSON object.
800
+ """
801
+ suggestions = get_llm_response(
802
+ suggestion_prompt,
803
+ model=state.chat_model,
804
+ provider=state.chat_provider,
805
+ api_url=state.api_url,
806
+ api_key=state.api_key,
807
+ npc=state.npc,
808
+ format="json"
809
+ )
810
+ # No custom parsing: just use the parsed output
811
+ steps = suggestions.get("response", {}).get("steps", [])
812
+ if not steps or len(steps) < 1:
813
+ print("No further steps suggested by LLM. Exiting.")
814
+ break
815
+
816
+ print("\nNext possible steps:")
817
+ for idx, step in enumerate(steps, 1):
818
+ print(f"{idx}. {step}")
819
+
820
+ user_input = input("\nChoose next step (1/2/3) or q to quit: ").strip().lower()
821
+ if user_input in ("q", "quit", "exit"):
822
+ print("Exiting /ride agentic loop.")
823
+ break
824
+ try:
825
+
826
+ choice = int(user_input)
827
+ if 1 <= choice <= len(steps):
828
+ request = f"""
829
+ My initial goal was: {user_goal}
830
+ The orchestration result was: {result.get('output')}
831
+ I have chosen to pursue the next step: {steps[choice - 1]}
832
+ Now work on this next problem.
833
+ """
834
+ else:
835
+ print("Invalid choice, please enter 1, 2, 3, or q.")
836
+ continue
837
+ except Exception:
838
+ # assume it is natural language input from the user on what to do next, not a number,
839
+
840
+ request = user_input
841
+ print("Invalid input, please enter 1, 2, 3, or q.")
842
+ continue
843
+
844
+ return state, all_results
845
+
846
+ # --- Main Application Logic ---
847
+
848
+ def check_deprecation_warnings():
849
+ if os.getenv("NPCSH_MODEL"):
850
+ cprint(
851
+ "Deprecation Warning: NPCSH_MODEL/PROVIDER deprecated. Use NPCSH_CHAT_MODEL/PROVIDER.",
852
+ "yellow",
853
+ )
854
+
855
+ def print_welcome_message():
856
+ print(
857
+ """
858
+ Welcome to \033[1;94mnpc\033[0m\033[1;38;5;202msh\033[0m!
859
+ \033[1;94m \033[0m\033[1;38;5;202m \\\\
860
+ \033[1;94m _ __ _ __ ___ \033[0m\033[1;38;5;202m ___ | |___ \\\\
861
+ \033[1;94m| '_ \ | '_ \ / __|\033[0m\033[1;38;5;202m/ __/ | |_ _| \\\\
862
+ \033[1;94m| | | || |_) |( |__ \033[0m\033[1;38;5;202m\_ \ | | | | //
863
+ \033[1;94m|_| |_|| .__/ \___|\033[0m\033[1;38;5;202m|___/ |_| |_| //
864
+ \033[1;94m| | \033[0m\033[1;38;5;202m //
865
+ \033[1;94m| |
866
+ \033[1;94m|_|
867
+
868
+ Begin by asking a question, issuing a bash command, or typing '/help' for more information.
869
+
870
+ """
871
+ )
872
+
873
+
874
+ def setup_shell() -> Tuple[CommandHistory, Team, Optional[NPC]]:
875
+ check_deprecation_warnings()
876
+ setup_npcsh_config()
877
+
878
+ db_path = os.getenv("NPCSH_DB_PATH", HISTORY_DB_DEFAULT_PATH)
879
+ db_path = os.path.expanduser(db_path)
880
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
881
+ command_history = CommandHistory(db_path)
882
+
883
+ try:
884
+ readline.set_completer(complete)
885
+ history_file = setup_readline()
886
+ atexit.register(save_readline_history)
887
+ atexit.register(command_history.close)
888
+ except:
889
+ pass
890
+
891
+ project_team_path = os.path.abspath(PROJECT_NPC_TEAM_PATH)
892
+ global_team_path = os.path.expanduser(DEFAULT_NPC_TEAM_PATH)
893
+ team_dir = None
894
+ forenpc_obj = None
895
+ team_ctx = {}
896
+
897
+ # --- Always prefer local/project team first ---
898
+ if os.path.exists(project_team_path):
899
+ team_dir = project_team_path
900
+ forenpc_name = "forenpc"
901
+ else:
902
+ resp = input(f"No npc_team found in {os.getcwd()}. Create a new team here? [Y/n]: ").strip().lower()
903
+ if resp in ("", "y", "yes"):
904
+ team_dir = project_team_path
905
+ os.makedirs(team_dir, exist_ok=True)
906
+ forenpc_name = "forenpc"
907
+ forenpc_directive = input(
908
+ f"Enter a primary directive for {forenpc_name} (default: 'You are the forenpc of the team, coordinating activities between NPCs on the team, verifying that results from NPCs are high quality and can help to adequately answer user requests.'): "
909
+ ).strip() or "You are the forenpc of the team, coordinating activities between NPCs on the team, verifying that results from NPCs are high quality and can help to adequately answer user requests."
910
+ forenpc_model = input("Enter a model for your forenpc (default: llama3.2): ").strip() or "llama3.2"
911
+ forenpc_provider = input("Enter a provider for your forenpc (default: ollama): ").strip() or "ollama"
912
+ forenpc_path = os.path.join(team_dir, f"{forenpc_name}.npc")
913
+ if not os.path.exists(forenpc_path):
914
+ with open(forenpc_path, "w") as f:
915
+ yaml.dump({
916
+ "name": forenpc_name,
917
+ "primary_directive": forenpc_directive,
918
+ "model": forenpc_model,
919
+ "provider": forenpc_provider
920
+ }, f)
921
+ ctx_path = os.path.join(team_dir, "team.ctx")
922
+ folder_context = input("Enter a short description or context for this project/team (optional): ").strip()
923
+ team_ctx = {
924
+ "forenpc": forenpc_name,
925
+ "model": forenpc_model,
926
+ "provider": forenpc_provider,
927
+ "api_key": None,
928
+ "api_url": None,
929
+ "context": folder_context if folder_context else None
930
+ }
931
+ use_jinxs = input("Do you want to copy jinxs from the global folder to this project (c), or use them from the global folder (g)? [c/g, default: g]: ").strip().lower()
932
+ global_jinxs_dir = os.path.expanduser("~/.npcsh/npc_team/jinxs")
933
+ project_jinxs_dir = os.path.join(team_dir, "jinxs")
934
+ if use_jinxs == "c":
935
+ if os.path.exists(global_jinxs_dir):
936
+ shutil.copytree(global_jinxs_dir, project_jinxs_dir, dirs_exist_ok=True)
937
+ print(f"Copied jinxs from {global_jinxs_dir} to {project_jinxs_dir}")
938
+ else:
939
+ print(f"No global jinxs found at {global_jinxs_dir}")
940
+ else:
941
+ team_ctx["use_global_jinxs"] = True
942
+
943
+ with open(ctx_path, "w") as f:
944
+ yaml.dump(team_ctx, f)
945
+ elif os.path.exists(global_team_path):
946
+ team_dir = global_team_path
947
+ forenpc_name = "sibiji"
948
+ else:
949
+ print("No global npc_team found. Please run 'npcpy init' or create a team first.")
950
+ sys.exit(1)
951
+
952
+ # --- Load team context if it exists ---
953
+ ctx_path = os.path.join(team_dir, "team.ctx")
954
+ if os.path.exists(ctx_path):
955
+ with open(ctx_path, "r") as f:
956
+ team_ctx = yaml.safe_load(f) or team_ctx
957
+
958
+ # --- Load the forenpc_obj ---
959
+ forenpc_path = os.path.join(team_dir, f"{forenpc_name}.npc")
960
+ if os.path.exists(forenpc_path):
961
+ forenpc_obj = NPC(forenpc_path)
962
+ else:
963
+ forenpc_obj = None
964
+
965
+ # --- Decide which jinxs directory to use ---
966
+ if team_ctx.get("use_global_jinxs", False):
967
+ jinxs_dir = os.path.expanduser("~/.npcsh/npc_team/jinxs")
968
+ else:
969
+ jinxs_dir = os.path.join(team_dir, "jinxs")
970
+ from npcpy.npc_compiler import load_jinxs_from_directory
971
+ jinxs_list = load_jinxs_from_directory(jinxs_dir)
972
+ jinxs_dict = {jinx.jinx_name: jinx for jinx in jinxs_list}
973
+
974
+ team = Team(team_path=team_dir, forenpc=forenpc_obj, jinxs=jinxs_dict)
975
+ return command_history, team, forenpc_obj
976
+
977
+ def process_result(
978
+ user_input: str,
979
+ result_state: ShellState,
980
+ output: Any,
981
+ command_history: CommandHistory):
982
+
983
+ npc_name = result_state.npc.name if isinstance(result_state.npc, NPC) else result_state.npc
984
+ team_name = result_state.team.name if isinstance(result_state.team, Team) else result_state.team
985
+ save_conversation_message(
986
+ command_history,
987
+ result_state.conversation_id,
988
+ "user",
989
+ user_input,
990
+ wd=result_state.current_path,
991
+ model=result_state.chat_model, # Log primary chat model? Or specific used one?
992
+ provider=result_state.chat_provider,
993
+ npc=npc_name,
994
+ team=team_name,
995
+ attachments=result_state.attachments,
996
+ )
997
+
998
+ result_state.attachments = None # Clear attachments after logging user message
999
+
1000
+ final_output_str = None
1001
+ if user_input =='/help':
1002
+ render_markdown(output)
1003
+ elif result_state.stream_output:
1004
+ try:
1005
+ final_output_str = print_and_process_stream_with_markdown(output, result_state.chat_model, result_state.chat_provider)
1006
+ except AttributeError as e:
1007
+ if isinstance(output, str):
1008
+ if len(output) > 0:
1009
+ final_output_str = output
1010
+ render_markdown(final_output_str)
1011
+
1012
+ elif output is not None:
1013
+ final_output_str = str(output)
1014
+ render_markdown(final_output_str)
1015
+ if final_output_str and result_state.messages and result_state.messages[-1].get("role") != "assistant":
1016
+ result_state.messages.append({"role": "assistant", "content": final_output_str})
1017
+
1018
+ #print(result_state.messages)
1019
+
1020
+ print() # Add spacing after output
1021
+
1022
+ if final_output_str:
1023
+ save_conversation_message(
1024
+ command_history,
1025
+ result_state.conversation_id,
1026
+ "assistant",
1027
+ final_output_str,
1028
+ wd=result_state.current_path,
1029
+ model=result_state.chat_model,
1030
+ provider=result_state.chat_provider,
1031
+ npc=npc_name,
1032
+ team=team_name,
1033
+ )
1034
+
1035
+ def run_repl(command_history: CommandHistory, initial_state: ShellState):
1036
+ state = initial_state
1037
+ print_welcome_message()
1038
+ print(f'Using {state.current_mode} mode. Use /agent, /cmd, /chat, or /ride to switch to other modes')
1039
+ print(f'To switch to a different NPC, type /<npc_name>')
1040
+ is_windows = platform.system().lower().startswith("win")
1041
+
1042
+ def exit_shell(state):
1043
+ print("\nGoodbye!")
1044
+ print('beginning knowledge consolidation')
1045
+ try:
1046
+ breathe_result = breathe(state.messages, state.chat_model, state.chat_provider, state.npc)
1047
+ print(breathe_result)
1048
+ except KeyboardInterrupt:
1049
+ print("Knowledge consolidation interrupted. Exiting immediately.")
1050
+ sys.exit(0)
1051
+
1052
+ while True:
1053
+ try:
1054
+ if is_windows:
1055
+ cwd_part = os.path.basename(state.current_path)
1056
+ if isinstance(state.npc, NPC):
1057
+ prompt_end = f":{state.npc.name}> "
1058
+ else:
1059
+ prompt_end = ":npcsh> "
1060
+ prompt = f"{cwd_part}{prompt_end}"
1061
+ else:
1062
+ cwd_colored = colored(os.path.basename(state.current_path), "blue")
1063
+ if isinstance(state.npc, NPC):
1064
+ prompt_end = f":🤖{orange(state.npc.name)}:{state.chat_model}> "
1065
+ else:
1066
+ prompt_end = f":🤖{colored('npc', 'blue', attrs=['bold'])}{colored('sh', 'yellow')}> "
1067
+ prompt = readline_safe_prompt(f"{cwd_colored}{prompt_end}")
1068
+ cwd_colored = colored(os.path.basename(state.current_path), "blue")
1069
+ if isinstance(state.npc, NPC):
1070
+ prompt_end = f":🤖{orange(state.npc.name)}> "
1071
+ else:
1072
+ prompt_end = f":🤖{colored('npc', 'blue', attrs=['bold'])}{colored('sh', 'yellow')}> "
1073
+ prompt = readline_safe_prompt(f"{cwd_colored}{prompt_end}")
1074
+
1075
+ user_input = get_multiline_input(prompt).strip()
1076
+ # Handle Ctrl+Z (ASCII SUB, '\x1a') as exit (Windows and Unix)
1077
+ if user_input == "\x1a":
1078
+ exit_shell(state)
1079
+
1080
+ if not user_input:
1081
+ continue
1082
+
1083
+ if user_input.lower() in ["exit", "quit"]:
1084
+ if isinstance(state.npc, NPC):
1085
+ print(f"Exiting {state.npc.name} mode.")
1086
+ state.npc = None
1087
+ continue
1088
+ else:
1089
+ exit_shell(state)
1090
+
1091
+ state.current_path = os.getcwd()
1092
+ state, output = execute_command(user_input, state)
1093
+ process_result(user_input, state, output, command_history)
1094
+
1095
+ except KeyboardInterrupt:
1096
+ if is_windows:
1097
+ # On Windows, Ctrl+C cancels the current input line, show prompt again
1098
+ print("^C")
1099
+ continue
1100
+ else:
1101
+ # On Unix, Ctrl+C exits the shell as before
1102
+ exit_shell(state)
1103
+ except EOFError:
1104
+ # Ctrl+D: exit shell cleanly
1105
+ exit_shell(state)
1106
+
1107
+ def run_non_interactive(command_history: CommandHistory, initial_state: ShellState):
1108
+ state = initial_state
1109
+ # print("Running in non-interactive mode...", file=sys.stderr) # Optional debug
1110
+
1111
+ for line in sys.stdin:
1112
+ user_input = line.strip()
1113
+ if not user_input:
1114
+ continue
1115
+ if user_input.lower() in ["exit", "quit"]:
1116
+ break
1117
+
1118
+ state.current_path = os.getcwd()
1119
+ state, output = execute_command(user_input, state)
1120
+ # Non-interactive: just print raw output, don't process results complexly
1121
+ if state.stream_output and isgenerator(output):
1122
+ for chunk in output: print(str(chunk), end='')
1123
+ print()
1124
+ elif output is not None:
1125
+ print(output)
1126
+ # Maybe still log history?
1127
+ # process_result(user_input, state, output, command_history)
1128
+
1129
+ def main() -> None:
1130
+ parser = argparse.ArgumentParser(description="npcsh - An NPC-powered shell.")
1131
+ parser.add_argument(
1132
+ "-v", "--version", action="version", version=f"npcsh version {VERSION}"
1133
+ )
1134
+ parser.add_argument(
1135
+ "-c", "--command", type=str, help="Execute a single command and exit."
1136
+ )
1137
+ args = parser.parse_args()
1138
+
1139
+ command_history, team, default_npc = setup_shell()
1140
+
1141
+ initial_state.npc = default_npc
1142
+ initial_state.team = team
1143
+ #import pdb
1144
+ #pdb.set_trace()
1145
+ if args.command:
1146
+ state = initial_state
1147
+ state.current_path = os.getcwd()
1148
+ final_state, output = execute_command(args.command, state)
1149
+ if final_state.stream_output and isgenerator(output):
1150
+ for chunk in output: print(str(chunk), end='')
1151
+ print()
1152
+ elif output is not None:
1153
+ print(output)
1154
+
1155
+ elif not sys.stdin.isatty():
1156
+ run_non_interactive(command_history, initial_state)
1157
+ else:
1158
+ run_repl(command_history, initial_state)
1159
+
1160
+ if __name__ == "__main__":
1161
+ main()