npcsh 1.0.16__py3-none-any.whl → 1.0.18__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.
- npcsh/_state.py +1541 -78
- npcsh/corca.py +709 -0
- npcsh/guac.py +1433 -596
- npcsh/mcp_server.py +64 -60
- npcsh/npc.py +5 -4
- npcsh/npcsh.py +27 -1334
- npcsh/pti.py +195 -215
- npcsh/routes.py +99 -26
- npcsh/spool.py +138 -144
- npcsh-1.0.18.dist-info/METADATA +483 -0
- npcsh-1.0.18.dist-info/RECORD +21 -0
- {npcsh-1.0.16.dist-info → npcsh-1.0.18.dist-info}/entry_points.txt +1 -1
- npcsh/mcp_npcsh.py +0 -822
- npcsh-1.0.16.dist-info/METADATA +0 -825
- npcsh-1.0.16.dist-info/RECORD +0 -21
- {npcsh-1.0.16.dist-info → npcsh-1.0.18.dist-info}/WHEEL +0 -0
- {npcsh-1.0.16.dist-info → npcsh-1.0.18.dist-info}/licenses/LICENSE +0 -0
- {npcsh-1.0.16.dist-info → npcsh-1.0.18.dist-info}/top_level.txt +0 -0
npcsh/npcsh.py
CHANGED
|
@@ -1,1075 +1,55 @@
|
|
|
1
1
|
import os
|
|
2
2
|
import sys
|
|
3
|
-
import atexit
|
|
4
|
-
import subprocess
|
|
5
|
-
import shlex
|
|
6
|
-
import re
|
|
7
|
-
from datetime import datetime
|
|
8
3
|
import argparse
|
|
9
4
|
import importlib.metadata
|
|
10
|
-
|
|
11
|
-
from typing import Optional, List, Dict, Any, Tuple, Union
|
|
12
|
-
from dataclasses import dataclass, field
|
|
5
|
+
|
|
13
6
|
import platform
|
|
14
7
|
try:
|
|
15
8
|
from termcolor import colored
|
|
16
9
|
except:
|
|
17
10
|
pass
|
|
18
|
-
|
|
19
|
-
try:
|
|
20
|
-
import chromadb
|
|
21
|
-
except ImportError:
|
|
22
|
-
chromadb = None
|
|
23
|
-
import shutil
|
|
24
|
-
import json
|
|
25
|
-
import sqlite3
|
|
26
|
-
import copy
|
|
27
|
-
import yaml
|
|
28
|
-
|
|
29
|
-
from npcsh._state import (
|
|
30
|
-
setup_npcsh_config,
|
|
31
|
-
initial_state,
|
|
32
|
-
is_npcsh_initialized,
|
|
33
|
-
initialize_base_npcs_if_needed,
|
|
34
|
-
orange,
|
|
35
|
-
ShellState,
|
|
36
|
-
interactive_commands,
|
|
37
|
-
BASH_COMMANDS,
|
|
38
|
-
|
|
39
|
-
start_interactive_session,
|
|
40
|
-
validate_bash_command,
|
|
41
|
-
normalize_and_expand_flags,
|
|
42
|
-
|
|
43
|
-
)
|
|
44
|
-
|
|
45
11
|
from npcpy.npc_sysenv import (
|
|
46
|
-
print_and_process_stream_with_markdown,
|
|
47
12
|
render_markdown,
|
|
48
|
-
get_locally_available_models,
|
|
49
|
-
get_model_and_provider,
|
|
50
|
-
lookup_provider
|
|
51
13
|
)
|
|
52
|
-
from npcsh.routes import router
|
|
53
|
-
from npcpy.data.image import capture_screenshot
|
|
54
14
|
from npcpy.memory.command_history import (
|
|
55
15
|
CommandHistory,
|
|
56
|
-
save_conversation_message,
|
|
57
16
|
load_kg_from_db,
|
|
58
17
|
save_kg_to_db,
|
|
59
18
|
)
|
|
60
|
-
from npcpy.npc_compiler import NPC
|
|
61
|
-
from npcpy.llm_funcs import (
|
|
62
|
-
check_llm_command,
|
|
63
|
-
get_llm_response,
|
|
64
|
-
execute_llm_command,
|
|
65
|
-
breathe
|
|
66
|
-
)
|
|
19
|
+
from npcpy.npc_compiler import NPC
|
|
67
20
|
from npcpy.memory.knowledge_graph import (
|
|
68
|
-
kg_initial,
|
|
69
21
|
kg_evolve_incremental
|
|
70
22
|
)
|
|
71
|
-
from npcpy.gen.embeddings import get_embeddings
|
|
72
23
|
|
|
24
|
+
from npcsh.routes import router
|
|
73
25
|
try:
|
|
74
26
|
import readline
|
|
75
27
|
except:
|
|
76
28
|
print('no readline support, some features may not work as desired. ')
|
|
77
|
-
|
|
29
|
+
|
|
78
30
|
try:
|
|
79
|
-
VERSION = importlib.metadata.version("
|
|
31
|
+
VERSION = importlib.metadata.version("npcsh")
|
|
80
32
|
except importlib.metadata.PackageNotFoundError:
|
|
81
33
|
VERSION = "unknown"
|
|
82
34
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
except Exception as e:
|
|
94
|
-
print(f"Warning: Failed to initialize ChromaDB client at {EMBEDDINGS_DB_PATH}: {e}")
|
|
95
|
-
chroma_client = None
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def get_path_executables() -> List[str]:
|
|
101
|
-
"""Get executables from PATH (cached for performance)"""
|
|
102
|
-
if not hasattr(get_path_executables, '_cache'):
|
|
103
|
-
executables = set()
|
|
104
|
-
path_dirs = os.environ.get('PATH', '').split(os.pathsep)
|
|
105
|
-
for path_dir in path_dirs:
|
|
106
|
-
if os.path.isdir(path_dir):
|
|
107
|
-
try:
|
|
108
|
-
for item in os.listdir(path_dir):
|
|
109
|
-
item_path = os.path.join(path_dir, item)
|
|
110
|
-
if os.path.isfile(item_path) and os.access(item_path, os.X_OK):
|
|
111
|
-
executables.add(item)
|
|
112
|
-
except (PermissionError, OSError):
|
|
113
|
-
continue
|
|
114
|
-
get_path_executables._cache = sorted(list(executables))
|
|
115
|
-
return get_path_executables._cache
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
import logging
|
|
119
|
-
|
|
120
|
-
# Set up completion logger
|
|
121
|
-
completion_logger = logging.getLogger('npcsh.completion')
|
|
122
|
-
completion_logger.setLevel(logging.WARNING) # Default to WARNING (quiet)
|
|
123
|
-
|
|
124
|
-
# Add handler if not already present
|
|
125
|
-
if not completion_logger.handlers:
|
|
126
|
-
handler = logging.StreamHandler(sys.stderr)
|
|
127
|
-
formatter = logging.Formatter('[%(name)s] %(message)s')
|
|
128
|
-
handler.setFormatter(formatter)
|
|
129
|
-
completion_logger.addHandler(handler)
|
|
130
|
-
|
|
131
|
-
def make_completer(shell_state: ShellState):
|
|
132
|
-
def complete(text: str, state_index: int) -> Optional[str]:
|
|
133
|
-
"""Main completion function"""
|
|
134
|
-
try:
|
|
135
|
-
buffer = readline.get_line_buffer()
|
|
136
|
-
begidx = readline.get_begidx()
|
|
137
|
-
endidx = readline.get_endidx()
|
|
138
|
-
|
|
139
|
-
completion_logger.debug(f"text='{text}', buffer='{buffer}', begidx={begidx}, endidx={endidx}, state_index={state_index}")
|
|
140
|
-
|
|
141
|
-
matches = []
|
|
142
|
-
|
|
143
|
-
# Check if we're completing a slash command
|
|
144
|
-
if begidx > 0 and buffer[begidx-1] == '/':
|
|
145
|
-
completion_logger.debug(f"Slash command completion - text='{text}'")
|
|
146
|
-
slash_commands = get_slash_commands(shell_state)
|
|
147
|
-
completion_logger.debug(f"Available slash commands: {slash_commands}")
|
|
148
|
-
|
|
149
|
-
if text == '':
|
|
150
|
-
matches = [cmd[1:] for cmd in slash_commands]
|
|
151
|
-
else:
|
|
152
|
-
full_text = '/' + text
|
|
153
|
-
matching_commands = [cmd for cmd in slash_commands if cmd.startswith(full_text)]
|
|
154
|
-
matches = [cmd[1:] for cmd in matching_commands]
|
|
155
|
-
|
|
156
|
-
completion_logger.debug(f"Slash command matches: {matches}")
|
|
157
|
-
|
|
158
|
-
elif is_command_position(buffer, begidx):
|
|
159
|
-
completion_logger.debug("Command position detected")
|
|
160
|
-
bash_matches = [cmd for cmd in BASH_COMMANDS if cmd.startswith(text)]
|
|
161
|
-
matches.extend(bash_matches)
|
|
162
|
-
|
|
163
|
-
interactive_matches = [cmd for cmd in interactive_commands.keys() if cmd.startswith(text)]
|
|
164
|
-
matches.extend(interactive_matches)
|
|
165
|
-
|
|
166
|
-
if len(text) >= 1:
|
|
167
|
-
path_executables = get_path_executables()
|
|
168
|
-
exec_matches = [cmd for cmd in path_executables if cmd.startswith(text)]
|
|
169
|
-
matches.extend(exec_matches[:20])
|
|
170
|
-
else:
|
|
171
|
-
completion_logger.debug("File completion")
|
|
172
|
-
matches = get_file_completions(text)
|
|
173
|
-
|
|
174
|
-
matches = sorted(list(set(matches)))
|
|
175
|
-
completion_logger.debug(f"Final matches: {matches}")
|
|
176
|
-
|
|
177
|
-
if state_index < len(matches):
|
|
178
|
-
result = matches[state_index]
|
|
179
|
-
completion_logger.debug(f"Returning: '{result}'")
|
|
180
|
-
return result
|
|
181
|
-
else:
|
|
182
|
-
completion_logger.debug(f"No match for state_index {state_index}")
|
|
183
|
-
|
|
184
|
-
except Exception as e:
|
|
185
|
-
completion_logger.error(f"Exception in completion: {e}")
|
|
186
|
-
completion_logger.debug("Exception details:", exc_info=True)
|
|
187
|
-
|
|
188
|
-
return None
|
|
189
|
-
|
|
190
|
-
return complete
|
|
191
|
-
|
|
192
|
-
def get_slash_commands(state: ShellState) -> List[str]:
|
|
193
|
-
"""Get available slash commands from router and team"""
|
|
194
|
-
commands = []
|
|
195
|
-
|
|
196
|
-
completion_logger.debug("Getting slash commands...")
|
|
197
|
-
|
|
198
|
-
# Router commands
|
|
199
|
-
if router and hasattr(router, 'routes'):
|
|
200
|
-
router_cmds = [f"/{cmd}" for cmd in router.routes.keys()]
|
|
201
|
-
commands.extend(router_cmds)
|
|
202
|
-
completion_logger.debug(f"Router commands: {router_cmds}")
|
|
203
|
-
|
|
204
|
-
# Team jinxs
|
|
205
|
-
if state.team and hasattr(state.team, 'jinxs_dict'):
|
|
206
|
-
jinx_cmds = [f"/{jinx}" for jinx in state.team.jinxs_dict.keys()]
|
|
207
|
-
commands.extend(jinx_cmds)
|
|
208
|
-
completion_logger.debug(f"Jinx commands: {jinx_cmds}")
|
|
209
|
-
|
|
210
|
-
# NPC names for switching
|
|
211
|
-
if state.team and hasattr(state.team, 'npcs'):
|
|
212
|
-
npc_cmds = [f"/{npc}" for npc in state.team.npcs.keys()]
|
|
213
|
-
commands.extend(npc_cmds)
|
|
214
|
-
completion_logger.debug(f"NPC commands: {npc_cmds}")
|
|
215
|
-
|
|
216
|
-
# Mode switching commands
|
|
217
|
-
mode_cmds = ['/cmd', '/agent', '/chat']
|
|
218
|
-
commands.extend(mode_cmds)
|
|
219
|
-
completion_logger.debug(f"Mode commands: {mode_cmds}")
|
|
220
|
-
|
|
221
|
-
result = sorted(commands)
|
|
222
|
-
completion_logger.debug(f"Final slash commands: {result}")
|
|
223
|
-
return result
|
|
224
|
-
def get_file_completions(text: str) -> List[str]:
|
|
225
|
-
"""Get file/directory completions"""
|
|
226
|
-
try:
|
|
227
|
-
if text.startswith('/'):
|
|
228
|
-
basedir = os.path.dirname(text) or '/'
|
|
229
|
-
prefix = os.path.basename(text)
|
|
230
|
-
elif text.startswith('./') or text.startswith('../'):
|
|
231
|
-
basedir = os.path.dirname(text) or '.'
|
|
232
|
-
prefix = os.path.basename(text)
|
|
233
|
-
else:
|
|
234
|
-
basedir = '.'
|
|
235
|
-
prefix = text
|
|
236
|
-
|
|
237
|
-
if not os.path.exists(basedir):
|
|
238
|
-
return []
|
|
239
|
-
|
|
240
|
-
matches = []
|
|
241
|
-
try:
|
|
242
|
-
for item in os.listdir(basedir):
|
|
243
|
-
if item.startswith(prefix):
|
|
244
|
-
full_path = os.path.join(basedir, item)
|
|
245
|
-
if basedir == '.':
|
|
246
|
-
completion = item
|
|
247
|
-
else:
|
|
248
|
-
completion = os.path.join(basedir, item)
|
|
249
|
-
|
|
250
|
-
# Just return the name, let readline handle spacing/slashes
|
|
251
|
-
matches.append(completion)
|
|
252
|
-
except (PermissionError, OSError):
|
|
253
|
-
pass
|
|
254
|
-
|
|
255
|
-
return sorted(matches)
|
|
256
|
-
except Exception:
|
|
257
|
-
return []
|
|
258
|
-
def is_command_position(buffer: str, begidx: int) -> bool:
|
|
259
|
-
"""Determine if cursor is at a command position"""
|
|
260
|
-
# Get the part of buffer before the current word
|
|
261
|
-
before_word = buffer[:begidx]
|
|
262
|
-
|
|
263
|
-
# Split by command separators
|
|
264
|
-
parts = re.split(r'[|;&]', before_word)
|
|
265
|
-
current_command_part = parts[-1].strip()
|
|
266
|
-
|
|
267
|
-
# If there's nothing before the current word in this command part,
|
|
268
|
-
# or only whitespace, we're at command position
|
|
269
|
-
return len(current_command_part) == 0
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
def readline_safe_prompt(prompt: str) -> str:
|
|
273
|
-
ansi_escape = re.compile(r"(\033\[[0-9;]*[a-zA-Z])")
|
|
274
|
-
return ansi_escape.sub(r"\001\1\002", prompt)
|
|
275
|
-
|
|
276
|
-
def print_jinxs(jinxs):
|
|
277
|
-
output = "Available jinxs:\n"
|
|
278
|
-
for jinx in jinxs:
|
|
279
|
-
output += f" {jinx.jinx_name}\n"
|
|
280
|
-
output += f" Description: {jinx.description}\n"
|
|
281
|
-
output += f" Inputs: {jinx.inputs}\n"
|
|
282
|
-
return output
|
|
283
|
-
|
|
284
|
-
def open_terminal_editor(command: str) -> str:
|
|
285
|
-
try:
|
|
286
|
-
os.system(command)
|
|
287
|
-
return 'Terminal editor closed.'
|
|
288
|
-
except Exception as e:
|
|
289
|
-
return f"Error opening terminal editor: {e}"
|
|
290
|
-
|
|
291
|
-
def get_multiline_input(prompt: str) -> str:
|
|
292
|
-
lines = []
|
|
293
|
-
current_prompt = prompt
|
|
294
|
-
while True:
|
|
295
|
-
try:
|
|
296
|
-
line = input(current_prompt)
|
|
297
|
-
if line.endswith("\\"):
|
|
298
|
-
lines.append(line[:-1])
|
|
299
|
-
current_prompt = readline_safe_prompt("> ")
|
|
300
|
-
else:
|
|
301
|
-
lines.append(line)
|
|
302
|
-
break
|
|
303
|
-
except EOFError:
|
|
304
|
-
print("Goodbye!")
|
|
305
|
-
sys.exit(0)
|
|
306
|
-
return "\n".join(lines)
|
|
307
|
-
|
|
308
|
-
def split_by_pipes(command: str) -> List[str]:
|
|
309
|
-
parts = []
|
|
310
|
-
current = ""
|
|
311
|
-
in_single_quote = False
|
|
312
|
-
in_double_quote = False
|
|
313
|
-
escape = False
|
|
314
|
-
|
|
315
|
-
for char in command:
|
|
316
|
-
if escape:
|
|
317
|
-
current += char
|
|
318
|
-
escape = False
|
|
319
|
-
elif char == '\\':
|
|
320
|
-
escape = True
|
|
321
|
-
current += char
|
|
322
|
-
elif char == "'" and not in_double_quote:
|
|
323
|
-
in_single_quote = not in_single_quote
|
|
324
|
-
current += char
|
|
325
|
-
elif char == '"' and not in_single_quote:
|
|
326
|
-
in_double_quote = not in_single_quote
|
|
327
|
-
current += char
|
|
328
|
-
elif char == '|' and not in_single_quote and not in_double_quote:
|
|
329
|
-
parts.append(current.strip())
|
|
330
|
-
current = ""
|
|
331
|
-
else:
|
|
332
|
-
current += char
|
|
333
|
-
|
|
334
|
-
if current:
|
|
335
|
-
parts.append(current.strip())
|
|
336
|
-
return parts
|
|
337
|
-
|
|
338
|
-
def parse_command_safely(cmd: str) -> List[str]:
|
|
339
|
-
try:
|
|
340
|
-
return shlex.split(cmd)
|
|
341
|
-
except ValueError as e:
|
|
342
|
-
if "No closing quotation" in str(e):
|
|
343
|
-
if cmd.count('"') % 2 == 1:
|
|
344
|
-
cmd += '"'
|
|
345
|
-
elif cmd.count("'") % 2 == 1:
|
|
346
|
-
cmd += "'"
|
|
347
|
-
try:
|
|
348
|
-
return shlex.split(cmd)
|
|
349
|
-
except ValueError:
|
|
350
|
-
return cmd.split()
|
|
351
|
-
else:
|
|
352
|
-
return cmd.split()
|
|
353
|
-
|
|
354
|
-
def get_file_color(filepath: str) -> tuple:
|
|
355
|
-
if not os.path.exists(filepath):
|
|
356
|
-
return "grey", []
|
|
357
|
-
if os.path.isdir(filepath):
|
|
358
|
-
return "blue", ["bold"]
|
|
359
|
-
elif os.access(filepath, os.X_OK) and not os.path.isdir(filepath):
|
|
360
|
-
return "green", ["bold"]
|
|
361
|
-
elif filepath.endswith((".zip", ".tar", ".gz", ".bz2", ".xz", ".7z")):
|
|
362
|
-
return "red", []
|
|
363
|
-
elif filepath.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff")):
|
|
364
|
-
return "magenta", []
|
|
365
|
-
elif filepath.endswith((".py", ".pyw")):
|
|
366
|
-
return "yellow", []
|
|
367
|
-
elif filepath.endswith((".sh", ".bash", ".zsh")):
|
|
368
|
-
return "green", []
|
|
369
|
-
elif filepath.endswith((".c", ".cpp", ".h", ".hpp")):
|
|
370
|
-
return "cyan", []
|
|
371
|
-
elif filepath.endswith((".js", ".ts", ".jsx", ".tsx")):
|
|
372
|
-
return "yellow", []
|
|
373
|
-
elif filepath.endswith((".html", ".css", ".scss", ".sass")):
|
|
374
|
-
return "magenta", []
|
|
375
|
-
elif filepath.endswith((".md", ".txt", ".log")):
|
|
376
|
-
return "white", []
|
|
377
|
-
elif os.path.basename(filepath).startswith("."):
|
|
378
|
-
return "cyan", []
|
|
379
|
-
else:
|
|
380
|
-
return "white", []
|
|
381
|
-
|
|
382
|
-
def format_file_listing(output: str) -> str:
|
|
383
|
-
colored_lines = []
|
|
384
|
-
current_dir = os.getcwd()
|
|
385
|
-
for line in output.strip().split("\n"):
|
|
386
|
-
parts = line.split()
|
|
387
|
-
if not parts:
|
|
388
|
-
colored_lines.append(line)
|
|
389
|
-
continue
|
|
390
|
-
|
|
391
|
-
filepath_guess = parts[-1]
|
|
392
|
-
potential_path = os.path.join(current_dir, filepath_guess)
|
|
393
|
-
|
|
394
|
-
color, attrs = get_file_color(potential_path)
|
|
395
|
-
colored_filepath = colored(filepath_guess, color, attrs=attrs)
|
|
396
|
-
|
|
397
|
-
if len(parts) > 1 :
|
|
398
|
-
# Handle cases like 'ls -l' where filename is last
|
|
399
|
-
colored_line = " ".join(parts[:-1] + [colored_filepath])
|
|
400
|
-
else:
|
|
401
|
-
# Handle cases where line is just the filename
|
|
402
|
-
colored_line = colored_filepath
|
|
403
|
-
|
|
404
|
-
colored_lines.append(colored_line)
|
|
405
|
-
|
|
406
|
-
return "\n".join(colored_lines)
|
|
407
|
-
|
|
408
|
-
def wrap_text(text: str, width: int = 80) -> str:
|
|
409
|
-
lines = []
|
|
410
|
-
for paragraph in text.split("\n"):
|
|
411
|
-
if len(paragraph) > width:
|
|
412
|
-
lines.extend(textwrap.wrap(paragraph, width=width, replace_whitespace=False, drop_whitespace=False))
|
|
413
|
-
else:
|
|
414
|
-
lines.append(paragraph)
|
|
415
|
-
return "\n".join(lines)
|
|
416
|
-
|
|
417
|
-
# --- Readline Setup and Completion ---
|
|
418
|
-
|
|
419
|
-
def setup_readline() -> str:
|
|
420
|
-
"""Setup readline with history and completion"""
|
|
421
|
-
try:
|
|
422
|
-
readline.read_history_file(READLINE_HISTORY_FILE)
|
|
423
|
-
readline.set_history_length(1000)
|
|
424
|
-
|
|
425
|
-
# Don't set completer here - it will be set in run_repl with state
|
|
426
|
-
readline.parse_and_bind("tab: complete")
|
|
427
|
-
|
|
428
|
-
readline.parse_and_bind("set enable-bracketed-paste on")
|
|
429
|
-
readline.parse_and_bind(r'"\C-r": reverse-search-history')
|
|
430
|
-
readline.parse_and_bind(r'"\C-e": end-of-line')
|
|
431
|
-
readline.parse_and_bind(r'"\C-a": beginning-of-line')
|
|
432
|
-
|
|
433
|
-
return READLINE_HISTORY_FILE
|
|
434
|
-
|
|
435
|
-
except FileNotFoundError:
|
|
436
|
-
pass
|
|
437
|
-
except OSError as e:
|
|
438
|
-
print(f"Warning: Could not read readline history file {READLINE_HISTORY_FILE}: {e}")
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
def save_readline_history():
|
|
442
|
-
try:
|
|
443
|
-
readline.write_history_file(READLINE_HISTORY_FILE)
|
|
444
|
-
except OSError as e:
|
|
445
|
-
print(f"Warning: Could not write readline history file {READLINE_HISTORY_FILE}: {e}")
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
valid_commands_list = list(router.routes.keys()) + list(interactive_commands.keys()) + ["cd", "exit", "quit"] + BASH_COMMANDS
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
# --- Command Execution Logic ---
|
|
456
|
-
|
|
457
|
-
def store_command_embeddings(command: str, output: Any, state: ShellState):
|
|
458
|
-
if not chroma_client or not state.embedding_model or not state.embedding_provider:
|
|
459
|
-
if not chroma_client: print("Warning: ChromaDB client not available for embeddings.", file=sys.stderr)
|
|
460
|
-
return
|
|
461
|
-
if not command and not output:
|
|
462
|
-
return
|
|
463
|
-
|
|
464
|
-
try:
|
|
465
|
-
output_str = str(output) if output else ""
|
|
466
|
-
if not command and not output_str: return # Avoid empty embeddings
|
|
467
|
-
|
|
468
|
-
texts_to_embed = [command, output_str]
|
|
469
|
-
|
|
470
|
-
embeddings = get_embeddings(
|
|
471
|
-
texts_to_embed,
|
|
472
|
-
state.embedding_model,
|
|
473
|
-
state.embedding_provider,
|
|
474
|
-
)
|
|
475
|
-
|
|
476
|
-
if not embeddings or len(embeddings) != 2:
|
|
477
|
-
print(f"Warning: Failed to generate embeddings for command: {command[:50]}...", file=sys.stderr)
|
|
478
|
-
return
|
|
479
|
-
|
|
480
|
-
timestamp = datetime.now().isoformat()
|
|
481
|
-
npc_name = state.npc.name if isinstance(state.npc, NPC) else state.npc
|
|
482
|
-
|
|
483
|
-
metadata = [
|
|
484
|
-
{
|
|
485
|
-
"type": "command", "timestamp": timestamp, "path": state.current_path,
|
|
486
|
-
"npc": npc_name, "conversation_id": state.conversation_id,
|
|
487
|
-
},
|
|
488
|
-
{
|
|
489
|
-
"type": "response", "timestamp": timestamp, "path": state.current_path,
|
|
490
|
-
"npc": npc_name, "conversation_id": state.conversation_id,
|
|
491
|
-
},
|
|
492
|
-
]
|
|
493
|
-
|
|
494
|
-
collection_name = f"{state.embedding_provider}_{state.embedding_model}_embeddings"
|
|
495
|
-
try:
|
|
496
|
-
collection = chroma_client.get_or_create_collection(collection_name)
|
|
497
|
-
ids = [f"cmd_{timestamp}_{hash(command)}", f"resp_{timestamp}_{hash(output_str)}"]
|
|
498
|
-
|
|
499
|
-
collection.add(
|
|
500
|
-
embeddings=embeddings,
|
|
501
|
-
documents=texts_to_embed,
|
|
502
|
-
metadatas=metadata,
|
|
503
|
-
ids=ids,
|
|
504
|
-
)
|
|
505
|
-
except Exception as e:
|
|
506
|
-
print(f"Warning: Failed to add embeddings to collection '{collection_name}': {e}", file=sys.stderr)
|
|
507
|
-
|
|
508
|
-
except Exception as e:
|
|
509
|
-
print(f"Warning: Failed to store embeddings: {e}", file=sys.stderr)
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
def handle_interactive_command(cmd_parts: List[str], state: ShellState) -> Tuple[ShellState, str]:
|
|
513
|
-
command_name = cmd_parts[0]
|
|
514
|
-
print(f"Starting interactive {command_name} session...")
|
|
515
|
-
try:
|
|
516
|
-
return_code = start_interactive_session(
|
|
517
|
-
interactive_commands[command_name], cmd_parts[1:]
|
|
518
|
-
)
|
|
519
|
-
output = f"Interactive {command_name} session ended with return code {return_code}"
|
|
520
|
-
except Exception as e:
|
|
521
|
-
output = f"Error starting interactive session {command_name}: {e}"
|
|
522
|
-
return state, output
|
|
523
|
-
|
|
524
|
-
def handle_cd_command(cmd_parts: List[str], state: ShellState) -> Tuple[ShellState, str]:
|
|
525
|
-
original_path = os.getcwd()
|
|
526
|
-
target_path = cmd_parts[1] if len(cmd_parts) > 1 else os.path.expanduser("~")
|
|
527
|
-
try:
|
|
528
|
-
os.chdir(target_path)
|
|
529
|
-
state.current_path = os.getcwd()
|
|
530
|
-
output = f"Changed directory to {state.current_path}"
|
|
531
|
-
except FileNotFoundError:
|
|
532
|
-
output = colored(f"cd: no such file or directory: {target_path}", "red")
|
|
533
|
-
except Exception as e:
|
|
534
|
-
output = colored(f"cd: error changing directory: {e}", "red")
|
|
535
|
-
os.chdir(original_path) # Revert if error
|
|
536
|
-
|
|
537
|
-
return state, output
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
def handle_bash_command(
|
|
541
|
-
cmd_parts: List[str],
|
|
542
|
-
cmd_str: str,
|
|
543
|
-
stdin_input: Optional[str],
|
|
544
|
-
state: ShellState,
|
|
545
|
-
) -> Tuple[bool, str]:
|
|
546
|
-
try:
|
|
547
|
-
process = subprocess.Popen(
|
|
548
|
-
cmd_parts,
|
|
549
|
-
stdin=subprocess.PIPE if stdin_input is not None else None,
|
|
550
|
-
stdout=subprocess.PIPE,
|
|
551
|
-
stderr=subprocess.PIPE,
|
|
552
|
-
text=True,
|
|
553
|
-
cwd=state.current_path
|
|
554
|
-
)
|
|
555
|
-
stdout, stderr = process.communicate(input=stdin_input)
|
|
556
|
-
|
|
557
|
-
if process.returncode != 0:
|
|
558
|
-
return False, stderr.strip() if stderr else f"Command '{cmd_str}' failed with return code {process.returncode}."
|
|
559
|
-
|
|
560
|
-
if stderr.strip():
|
|
561
|
-
print(colored(f"stderr: {stderr.strip()}", "yellow"), file=sys.stderr)
|
|
562
|
-
|
|
563
|
-
if cmd_parts[0] in ["ls", "find", "dir"]:
|
|
564
|
-
return True, format_file_listing(stdout.strip())
|
|
565
|
-
|
|
566
|
-
return True, stdout.strip()
|
|
567
|
-
|
|
568
|
-
except FileNotFoundError:
|
|
569
|
-
return False, f"Command not found: {cmd_parts[0]}"
|
|
570
|
-
except PermissionError:
|
|
571
|
-
return False, f"Permission denied: {cmd_str}"
|
|
572
|
-
|
|
573
|
-
def _try_convert_type(value: str) -> Union[str, int, float, bool]:
|
|
574
|
-
"""Helper to convert string values to appropriate types."""
|
|
575
|
-
if value.lower() in ['true', 'yes']:
|
|
576
|
-
return True
|
|
577
|
-
if value.lower() in ['false', 'no']:
|
|
578
|
-
return False
|
|
579
|
-
try:
|
|
580
|
-
return int(value)
|
|
581
|
-
except (ValueError, TypeError):
|
|
582
|
-
pass
|
|
583
|
-
try:
|
|
584
|
-
return float(value)
|
|
585
|
-
except (ValueError, TypeError):
|
|
586
|
-
pass
|
|
587
|
-
return value
|
|
588
|
-
|
|
589
|
-
def parse_generic_command_flags(parts: List[str]) -> Tuple[Dict[str, Any], List[str]]:
|
|
590
|
-
"""
|
|
591
|
-
Parses a list of command parts into a dictionary of keyword arguments and a list of positional arguments.
|
|
592
|
-
Handles: -f val, --flag val, --flag=val, flag=val, --boolean-flag
|
|
593
|
-
"""
|
|
594
|
-
parsed_kwargs = {}
|
|
595
|
-
positional_args = []
|
|
596
|
-
i = 0
|
|
597
|
-
while i < len(parts):
|
|
598
|
-
part = parts[i]
|
|
599
|
-
|
|
600
|
-
if part.startswith('--'):
|
|
601
|
-
key_part = part[2:]
|
|
602
|
-
if '=' in key_part:
|
|
603
|
-
key, value = key_part.split('=', 1)
|
|
604
|
-
parsed_kwargs[key] = _try_convert_type(value)
|
|
605
|
-
else:
|
|
606
|
-
# Look ahead for a value
|
|
607
|
-
if i + 1 < len(parts) and not parts[i + 1].startswith('-'):
|
|
608
|
-
parsed_kwargs[key_part] = _try_convert_type(parts[i + 1])
|
|
609
|
-
i += 1 # Consume the value
|
|
610
|
-
else:
|
|
611
|
-
parsed_kwargs[key_part] = True # Boolean flag
|
|
612
|
-
|
|
613
|
-
elif part.startswith('-'):
|
|
614
|
-
key = part[1:]
|
|
615
|
-
# Look ahead for a value
|
|
616
|
-
if i + 1 < len(parts) and not parts[i + 1].startswith('-'):
|
|
617
|
-
parsed_kwargs[key] = _try_convert_type(parts[i + 1])
|
|
618
|
-
i += 1 # Consume the value
|
|
619
|
-
else:
|
|
620
|
-
parsed_kwargs[key] = True # Boolean flag
|
|
621
|
-
|
|
622
|
-
elif '=' in part and not part.startswith('-'):
|
|
623
|
-
key, value = part.split('=', 1)
|
|
624
|
-
parsed_kwargs[key] = _try_convert_type(value)
|
|
625
|
-
|
|
626
|
-
else:
|
|
627
|
-
positional_args.append(part)
|
|
628
|
-
|
|
629
|
-
i += 1
|
|
630
|
-
|
|
631
|
-
return parsed_kwargs, positional_args
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
def should_skip_kg_processing(user_input: str, assistant_output: str) -> bool:
|
|
635
|
-
"""Determine if this interaction is too trivial for KG processing"""
|
|
636
|
-
|
|
637
|
-
# Skip if user input is too short or trivial
|
|
638
|
-
trivial_inputs = {
|
|
639
|
-
'/sq', '/exit', '/quit', 'exit', 'quit', 'hey', 'hi', 'hello',
|
|
640
|
-
'fwah!', 'test', 'ping', 'ok', 'thanks', 'ty'
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
if user_input.lower().strip() in trivial_inputs:
|
|
644
|
-
return True
|
|
645
|
-
|
|
646
|
-
# Skip if user input is very short (less than 10 chars)
|
|
647
|
-
if len(user_input.strip()) < 10:
|
|
648
|
-
return True
|
|
649
|
-
|
|
650
|
-
# Skip simple bash commands
|
|
651
|
-
simple_bash = {'ls', 'pwd', 'cd', 'mkdir', 'touch', 'rm', 'mv', 'cp'}
|
|
652
|
-
first_word = user_input.strip().split()[0] if user_input.strip() else ""
|
|
653
|
-
if first_word in simple_bash:
|
|
654
|
-
return True
|
|
655
|
-
|
|
656
|
-
# Skip if assistant output is very short (less than 20 chars)
|
|
657
|
-
if len(assistant_output.strip()) < 20:
|
|
658
|
-
return True
|
|
659
|
-
|
|
660
|
-
# Skip if it's just a mode exit message
|
|
661
|
-
if "exiting" in assistant_output.lower() or "exited" in assistant_output.lower():
|
|
662
|
-
return True
|
|
663
|
-
|
|
664
|
-
return False
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
def execute_slash_command(command: str, stdin_input: Optional[str], state: ShellState, stream: bool) -> Tuple[ShellState, Any]:
|
|
668
|
-
"""Executes slash commands using the router or checking NPC/Team jinxs."""
|
|
669
|
-
all_command_parts = shlex.split(command)
|
|
670
|
-
command_name = all_command_parts[0].lstrip('/')
|
|
671
|
-
|
|
672
|
-
# Handle NPC switching commands
|
|
673
|
-
if command_name in ['n', 'npc']:
|
|
674
|
-
npc_to_switch_to = all_command_parts[1] if len(all_command_parts) > 1 else None
|
|
675
|
-
if npc_to_switch_to and state.team and npc_to_switch_to in state.team.npcs:
|
|
676
|
-
state.npc = state.team.npcs[npc_to_switch_to]
|
|
677
|
-
return state, f"Switched to NPC: {npc_to_switch_to}"
|
|
678
|
-
else:
|
|
679
|
-
available_npcs = list(state.team.npcs.keys()) if state.team else []
|
|
680
|
-
return state, colored(f"NPC '{npc_to_switch_to}' not found. Available NPCs: {', '.join(available_npcs)}", "red")
|
|
681
|
-
|
|
682
|
-
# Check router commands first
|
|
683
|
-
handler = router.get_route(command_name)
|
|
684
|
-
if handler:
|
|
685
|
-
parsed_flags, positional_args = parse_generic_command_flags(all_command_parts[1:])
|
|
686
|
-
normalized_flags = normalize_and_expand_flags(parsed_flags)
|
|
687
|
-
|
|
688
|
-
handler_kwargs = {
|
|
689
|
-
'stream': stream,
|
|
690
|
-
'team': state.team,
|
|
691
|
-
'messages': state.messages,
|
|
692
|
-
'api_url': state.api_url,
|
|
693
|
-
'api_key': state.api_key,
|
|
694
|
-
'stdin_input': stdin_input,
|
|
695
|
-
'positional_args': positional_args,
|
|
696
|
-
'plonk_context': state.team.shared_context.get('PLONK_CONTEXT') if state.team and hasattr(state.team, 'shared_context') else None,
|
|
697
|
-
|
|
698
|
-
# Default chat model/provider
|
|
699
|
-
'model': state.npc.model if isinstance(state.npc, NPC) and state.npc.model else state.chat_model,
|
|
700
|
-
'provider': state.npc.provider if isinstance(state.npc, NPC) and state.npc.provider else state.chat_provider,
|
|
701
|
-
'npc': state.npc,
|
|
702
|
-
|
|
703
|
-
# All other specific defaults
|
|
704
|
-
'sprovider': state.search_provider,
|
|
705
|
-
'emodel': state.embedding_model,
|
|
706
|
-
'eprovider': state.embedding_provider,
|
|
707
|
-
'igmodel': state.image_gen_model,
|
|
708
|
-
'igprovider': state.image_gen_provider,
|
|
709
|
-
'vgmodel': state.video_gen_model,
|
|
710
|
-
'vgprovider': state.video_gen_provider,
|
|
711
|
-
'vmodel': state.vision_model,
|
|
712
|
-
'vprovider': state.vision_provider,
|
|
713
|
-
'rmodel': state.reasoning_model,
|
|
714
|
-
'rprovider': state.reasoning_provider,
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
if len(normalized_flags) > 0:
|
|
718
|
-
kwarg_part = 'with kwargs: \n -' + '\n -'.join(f'{key}={item}' for key, item in normalized_flags.items())
|
|
719
|
-
else:
|
|
720
|
-
kwarg_part = ''
|
|
721
|
-
|
|
722
|
-
render_markdown(f'- Calling {command_name} handler {kwarg_part} ')
|
|
723
|
-
|
|
724
|
-
# Handle model/provider inference
|
|
725
|
-
if 'model' in normalized_flags and 'provider' not in normalized_flags:
|
|
726
|
-
inferred_provider = lookup_provider(normalized_flags['model'])
|
|
727
|
-
if inferred_provider:
|
|
728
|
-
handler_kwargs['provider'] = inferred_provider
|
|
729
|
-
print(colored(f"Info: Inferred provider '{inferred_provider}' for model '{normalized_flags['model']}'.", "cyan"))
|
|
730
|
-
|
|
731
|
-
if 'provider' in normalized_flags and 'model' not in normalized_flags:
|
|
732
|
-
current_provider = lookup_provider(handler_kwargs['model'])
|
|
733
|
-
if current_provider != normalized_flags['provider']:
|
|
734
|
-
prov = normalized_flags['provider']
|
|
735
|
-
print(f'Please specify a model for the provider: {prov}')
|
|
736
|
-
|
|
737
|
-
handler_kwargs.update(normalized_flags)
|
|
738
|
-
|
|
739
|
-
try:
|
|
740
|
-
result_dict = handler(command=command, **handler_kwargs)
|
|
741
|
-
if isinstance(result_dict, dict):
|
|
742
|
-
state.messages = result_dict.get("messages", state.messages)
|
|
743
|
-
return state, result_dict
|
|
744
|
-
else:
|
|
745
|
-
return state, result_dict
|
|
746
|
-
except Exception as e:
|
|
747
|
-
import traceback
|
|
748
|
-
print(f"Error executing slash command '{command_name}':", file=sys.stderr)
|
|
749
|
-
traceback.print_exc()
|
|
750
|
-
return state, colored(f"Error executing slash command '{command_name}': {e}", "red")
|
|
751
|
-
|
|
752
|
-
# Check for jinxs in active NPC
|
|
753
|
-
active_npc = state.npc if isinstance(state.npc, NPC) else None
|
|
754
|
-
jinx_to_execute = None
|
|
755
|
-
executor = None
|
|
756
|
-
|
|
757
|
-
if active_npc and hasattr(active_npc, 'jinxs_dict') and command_name in active_npc.jinxs_dict:
|
|
758
|
-
jinx_to_execute = active_npc.jinxs_dict[command_name]
|
|
759
|
-
executor = active_npc
|
|
760
|
-
elif state.team and hasattr(state.team, 'jinxs_dict') and command_name in state.team.jinxs_dict:
|
|
761
|
-
jinx_to_execute = state.team.jinxs_dict[command_name]
|
|
762
|
-
executor = state.team
|
|
763
|
-
if jinx_to_execute:
|
|
764
|
-
args = all_command_parts[1:] # Fix: use all_command_parts instead of command_parts
|
|
765
|
-
try:
|
|
766
|
-
# Create input dictionary from args based on jinx inputs
|
|
767
|
-
input_values = {}
|
|
768
|
-
if hasattr(jinx_to_execute, 'inputs') and jinx_to_execute.inputs:
|
|
769
|
-
for i, input_name in enumerate(jinx_to_execute.inputs):
|
|
770
|
-
if i < len(args):
|
|
771
|
-
input_values[input_name] = args[i]
|
|
772
|
-
|
|
773
|
-
# Execute the jinx with proper parameters
|
|
774
|
-
if isinstance(executor, NPC):
|
|
775
|
-
jinx_output = jinx_to_execute.execute(
|
|
776
|
-
input_values=input_values,
|
|
777
|
-
jinxs_dict=executor.jinxs_dict if hasattr(executor, 'jinxs_dict') else {},
|
|
778
|
-
npc=executor,
|
|
779
|
-
messages=state.messages
|
|
780
|
-
)
|
|
781
|
-
else: # Team executor
|
|
782
|
-
jinx_output = jinx_to_execute.execute(
|
|
783
|
-
input_values=input_values,
|
|
784
|
-
jinxs_dict=executor.jinxs_dict if hasattr(executor, 'jinxs_dict') else {},
|
|
785
|
-
npc=active_npc or state.npc,
|
|
786
|
-
messages=state.messages
|
|
787
|
-
)
|
|
788
|
-
if isinstance(jinx_output, dict) and 'messages' in jinx_output:
|
|
789
|
-
state.messages = jinx_output['messages']
|
|
790
|
-
return state, str(jinx_output.get('output', jinx_output))
|
|
791
|
-
elif isinstance(jinx_output, dict):
|
|
792
|
-
return state, str(jinx_output.get('output', jinx_output))
|
|
793
|
-
else:
|
|
794
|
-
return state, jinx_output
|
|
795
|
-
|
|
796
|
-
except Exception as e:
|
|
797
|
-
import traceback
|
|
798
|
-
print(f"Error executing jinx '{command_name}':", file=sys.stderr)
|
|
799
|
-
traceback.print_exc()
|
|
800
|
-
return state, colored(f"Error executing jinx '{command_name}': {e}", "red")
|
|
801
|
-
|
|
802
|
-
# Check if it's an NPC name for switching
|
|
803
|
-
if state.team and command_name in state.team.npcs:
|
|
804
|
-
new_npc = state.team.npcs[command_name]
|
|
805
|
-
state.npc = new_npc
|
|
806
|
-
return state, f"Switched to NPC: {new_npc.name}"
|
|
807
|
-
|
|
808
|
-
return state, colored(f"Unknown slash command, jinx, or NPC: {command_name}", "red")
|
|
809
|
-
|
|
810
|
-
def process_pipeline_command(
|
|
811
|
-
cmd_segment: str,
|
|
812
|
-
stdin_input: Optional[str],
|
|
813
|
-
state: ShellState,
|
|
814
|
-
stream_final: bool
|
|
815
|
-
) -> Tuple[ShellState, Any]:
|
|
816
|
-
|
|
817
|
-
if not cmd_segment:
|
|
818
|
-
return state, stdin_input
|
|
819
|
-
|
|
820
|
-
available_models_all = get_locally_available_models(state.current_path)
|
|
821
|
-
available_models_all_list = [item for key, item in available_models_all.items()]
|
|
822
|
-
|
|
823
|
-
model_override, provider_override, cmd_cleaned = get_model_and_provider(
|
|
824
|
-
cmd_segment, available_models_all_list
|
|
35
|
+
from npcsh._state import (
|
|
36
|
+
initial_state,
|
|
37
|
+
orange,
|
|
38
|
+
ShellState,
|
|
39
|
+
execute_command,
|
|
40
|
+
make_completer,
|
|
41
|
+
process_result,
|
|
42
|
+
readline_safe_prompt,
|
|
43
|
+
setup_shell,
|
|
44
|
+
get_multiline_input,
|
|
825
45
|
)
|
|
826
|
-
cmd_to_process = cmd_cleaned.strip()
|
|
827
|
-
if not cmd_to_process:
|
|
828
|
-
return state, stdin_input
|
|
829
|
-
|
|
830
|
-
npc_model = state.npc.model if isinstance(state.npc, NPC) and state.npc.model else None
|
|
831
|
-
npc_provider = state.npc.provider if isinstance(state.npc, NPC) and state.npc.provider else None
|
|
832
|
-
|
|
833
|
-
exec_model = model_override or npc_model or state.chat_model
|
|
834
|
-
exec_provider = provider_override or npc_provider or state.chat_provider
|
|
835
|
-
|
|
836
|
-
if cmd_to_process.startswith("/"):
|
|
837
|
-
return execute_slash_command(cmd_to_process, stdin_input, state, stream_final)
|
|
838
|
-
|
|
839
|
-
cmd_parts = parse_command_safely(cmd_to_process)
|
|
840
|
-
if not cmd_parts:
|
|
841
|
-
return state, stdin_input
|
|
842
|
-
|
|
843
|
-
command_name = cmd_parts[0]
|
|
844
|
-
|
|
845
|
-
if command_name == "cd":
|
|
846
|
-
return handle_cd_command(cmd_parts, state)
|
|
847
|
-
|
|
848
|
-
if command_name in interactive_commands:
|
|
849
|
-
return handle_interactive_command(cmd_parts, state)
|
|
850
|
-
|
|
851
|
-
if validate_bash_command(cmd_parts):
|
|
852
|
-
success, result = handle_bash_command(cmd_parts, cmd_to_process, stdin_input, state)
|
|
853
|
-
if success:
|
|
854
|
-
return state, result
|
|
855
|
-
else:
|
|
856
|
-
print(colored(f"Bash command failed: {result}. Asking LLM for a fix...", "yellow"), file=sys.stderr)
|
|
857
|
-
fixer_prompt = f"The command '{cmd_to_process}' failed with the error: '{result}'. Provide the correct command."
|
|
858
|
-
response = execute_llm_command(
|
|
859
|
-
fixer_prompt,
|
|
860
|
-
model=exec_model,
|
|
861
|
-
provider=exec_provider,
|
|
862
|
-
npc=state.npc,
|
|
863
|
-
stream=stream_final,
|
|
864
|
-
messages=state.messages
|
|
865
|
-
)
|
|
866
|
-
state.messages = response['messages']
|
|
867
|
-
return state, response['response']
|
|
868
|
-
else:
|
|
869
|
-
full_llm_cmd = f"{cmd_to_process} {stdin_input}" if stdin_input else cmd_to_process
|
|
870
|
-
path_cmd = 'The current working directory is: ' + state.current_path
|
|
871
|
-
ls_files = 'Files in the current directory (full paths):\n' + "\n".join([os.path.join(state.current_path, f) for f in os.listdir(state.current_path)]) if os.path.exists(state.current_path) else 'No files found in the current directory.'
|
|
872
|
-
platform_info = f"Platform: {platform.system()} {platform.release()} ({platform.machine()})"
|
|
873
|
-
info = path_cmd + '\n' + ls_files + '\n' + platform_info + '\n'
|
|
874
|
-
|
|
875
|
-
llm_result = check_llm_command(
|
|
876
|
-
full_llm_cmd,
|
|
877
|
-
model=exec_model,
|
|
878
|
-
provider=exec_provider,
|
|
879
|
-
api_url=state.api_url,
|
|
880
|
-
api_key=state.api_key,
|
|
881
|
-
npc=state.npc,
|
|
882
|
-
team=state.team,
|
|
883
|
-
messages=state.messages,
|
|
884
|
-
images=state.attachments,
|
|
885
|
-
stream=stream_final,
|
|
886
|
-
context=info,
|
|
887
|
-
)
|
|
888
|
-
if isinstance(llm_result, dict):
|
|
889
|
-
state.messages = llm_result.get("messages", state.messages)
|
|
890
|
-
output = llm_result.get("output")
|
|
891
|
-
return state, output
|
|
892
|
-
else:
|
|
893
|
-
return state, llm_result
|
|
894
|
-
def check_mode_switch(command:str , state: ShellState):
|
|
895
|
-
if command in ['/cmd', '/agent', '/chat',]:
|
|
896
|
-
state.current_mode = command[1:]
|
|
897
|
-
return True, state
|
|
898
46
|
|
|
899
|
-
return False, state
|
|
900
|
-
def execute_command(
|
|
901
|
-
command: str,
|
|
902
|
-
state: ShellState,
|
|
903
|
-
) -> Tuple[ShellState, Any]:
|
|
904
|
-
|
|
905
|
-
if not command.strip():
|
|
906
|
-
return state, ""
|
|
907
|
-
mode_change, state = check_mode_switch(command, state)
|
|
908
|
-
if mode_change:
|
|
909
|
-
return state, 'Mode changed.'
|
|
910
|
-
|
|
911
|
-
original_command_for_embedding = command
|
|
912
|
-
commands = split_by_pipes(command)
|
|
913
|
-
stdin_for_next = None
|
|
914
|
-
final_output = None
|
|
915
|
-
current_state = state
|
|
916
|
-
npc_model = state.npc.model if isinstance(state.npc, NPC) and state.npc.model else None
|
|
917
|
-
npc_provider = state.npc.provider if isinstance(state.npc, NPC) and state.npc.provider else None
|
|
918
|
-
active_model = npc_model or state.chat_model
|
|
919
|
-
active_provider = npc_provider or state.chat_provider
|
|
920
|
-
|
|
921
|
-
if state.current_mode == 'agent':
|
|
922
|
-
print('# of parsed commands: ', len(commands))
|
|
923
|
-
print('Commands:' '\n'.join(commands))
|
|
924
|
-
for i, cmd_segment in enumerate(commands):
|
|
925
|
-
|
|
926
|
-
render_markdown(f'- executing command {i+1}/{len(commands)}')
|
|
927
|
-
is_last_command = (i == len(commands) - 1)
|
|
928
|
-
|
|
929
|
-
stream_this_segment = state.stream_output and not is_last_command
|
|
930
|
-
|
|
931
|
-
try:
|
|
932
|
-
current_state, output = process_pipeline_command(
|
|
933
|
-
cmd_segment.strip(),
|
|
934
|
-
stdin_for_next,
|
|
935
|
-
current_state,
|
|
936
|
-
stream_final=stream_this_segment
|
|
937
|
-
)
|
|
938
|
-
|
|
939
|
-
if is_last_command:
|
|
940
|
-
return current_state, output
|
|
941
|
-
if isinstance(output, str):
|
|
942
|
-
stdin_for_next = output
|
|
943
|
-
elif not isinstance(output, str):
|
|
944
|
-
try:
|
|
945
|
-
if stream_this_segment:
|
|
946
|
-
full_stream_output = print_and_process_stream_with_markdown(output,
|
|
947
|
-
state.npc.model,
|
|
948
|
-
state.npc.provider)
|
|
949
|
-
stdin_for_next = full_stream_output
|
|
950
|
-
if is_last_command:
|
|
951
|
-
final_output = full_stream_output
|
|
952
|
-
except:
|
|
953
|
-
if output is not None: # Try converting other types to string
|
|
954
|
-
try:
|
|
955
|
-
stdin_for_next = str(output)
|
|
956
|
-
except Exception:
|
|
957
|
-
print(f"Warning: Cannot convert output to string for piping: {type(output)}", file=sys.stderr)
|
|
958
|
-
stdin_for_next = None
|
|
959
|
-
else: # Output was None
|
|
960
|
-
stdin_for_next = None
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
except Exception as pipeline_error:
|
|
964
|
-
import traceback
|
|
965
|
-
traceback.print_exc()
|
|
966
|
-
error_msg = colored(f"Error in pipeline stage {i+1} ('{cmd_segment[:50]}...'): {pipeline_error}", "red")
|
|
967
|
-
# Return the state as it was when the error occurred, and the error message
|
|
968
|
-
return current_state, error_msg
|
|
969
|
-
|
|
970
|
-
# Store embeddings using the final state
|
|
971
|
-
if final_output is not None and isinstance(final_output,str):
|
|
972
|
-
store_command_embeddings(original_command_for_embedding, final_output, current_state)
|
|
973
|
-
|
|
974
|
-
# Return the final state and the final output
|
|
975
|
-
return current_state, final_output
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
elif state.current_mode == 'chat':
|
|
979
|
-
# Only treat as bash if it looks like a shell command (starts with known command or is a slash command)
|
|
980
|
-
cmd_parts = parse_command_safely(command)
|
|
981
|
-
is_probably_bash = (
|
|
982
|
-
cmd_parts
|
|
983
|
-
and (
|
|
984
|
-
cmd_parts[0] in interactive_commands
|
|
985
|
-
or cmd_parts[0] in BASH_COMMANDS
|
|
986
|
-
or command.strip().startswith("./")
|
|
987
|
-
or command.strip().startswith("/")
|
|
988
|
-
)
|
|
989
|
-
)
|
|
990
|
-
if is_probably_bash:
|
|
991
|
-
try:
|
|
992
|
-
command_name = cmd_parts[0]
|
|
993
|
-
if command_name in interactive_commands:
|
|
994
|
-
return handle_interactive_command(cmd_parts, state)
|
|
995
|
-
elif command_name == "cd":
|
|
996
|
-
return handle_cd_command(cmd_parts, state)
|
|
997
|
-
else:
|
|
998
|
-
try:
|
|
999
|
-
bash_state, bash_output = handle_bash_command(cmd_parts, command, None, state)
|
|
1000
|
-
return state, bash_output
|
|
1001
|
-
except Exception as bash_err:
|
|
1002
|
-
return state, colored(f"Bash execution failed: {bash_err}", "red")
|
|
1003
|
-
except Exception:
|
|
1004
|
-
pass # Fall through to LLM
|
|
1005
|
-
|
|
1006
|
-
# Otherwise, treat as chat (LLM)
|
|
1007
|
-
response = get_llm_response(
|
|
1008
|
-
command,
|
|
1009
|
-
model=active_model,
|
|
1010
|
-
provider=active_provider,
|
|
1011
|
-
npc=state.npc,
|
|
1012
|
-
stream=state.stream_output,
|
|
1013
|
-
messages=state.messages
|
|
1014
|
-
)
|
|
1015
|
-
state.messages = response['messages']
|
|
1016
|
-
return state, response['response']
|
|
1017
|
-
|
|
1018
|
-
elif state.current_mode == 'cmd':
|
|
1019
|
-
|
|
1020
|
-
response = execute_llm_command(command,
|
|
1021
|
-
model=active_model,
|
|
1022
|
-
provider=active_provider,
|
|
1023
|
-
npc = state.npc,
|
|
1024
|
-
stream = state.stream_output,
|
|
1025
|
-
messages = state.messages)
|
|
1026
|
-
state.messages = response['messages']
|
|
1027
|
-
return state, response['response']
|
|
1028
|
-
|
|
1029
|
-
"""
|
|
1030
|
-
# to be replaced with a standalone corca mode
|
|
1031
|
-
|
|
1032
|
-
elif state.current_mode == 'ride':
|
|
1033
|
-
# Allow bash commands in /ride mode
|
|
1034
|
-
cmd_parts = parse_command_safely(command)
|
|
1035
|
-
is_probably_bash = (
|
|
1036
|
-
cmd_parts
|
|
1037
|
-
and (
|
|
1038
|
-
cmd_parts[0] in interactive_commands
|
|
1039
|
-
or cmd_parts[0] in BASH_COMMANDS
|
|
1040
|
-
or command.strip().startswith("./")
|
|
1041
|
-
or command.strip().startswith("/")
|
|
1042
|
-
)
|
|
1043
|
-
)
|
|
1044
|
-
if is_probably_bash:
|
|
1045
|
-
try:
|
|
1046
|
-
command_name = cmd_parts[0]
|
|
1047
|
-
if command_name in interactive_commands:
|
|
1048
|
-
return handle_interactive_command(cmd_parts, state)
|
|
1049
|
-
elif command_name == "cd":
|
|
1050
|
-
return handle_cd_command(cmd_parts, state)
|
|
1051
|
-
else:
|
|
1052
|
-
try:
|
|
1053
|
-
bash_state, bash_output = handle_bash_command(cmd_parts, command, None, state)
|
|
1054
|
-
return bash_state, bash_output
|
|
1055
|
-
except Exception as bash_err:
|
|
1056
|
-
return state, colored(f"Bash execution failed: {bash_err}", "red")
|
|
1057
|
-
except Exception:
|
|
1058
|
-
return state, colored("Failed to parse or execute bash command.", "red")
|
|
1059
|
-
|
|
1060
|
-
# Otherwise, run the agentic ride loop
|
|
1061
|
-
return agentic_ride_loop(command, state)
|
|
1062
|
-
"""
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
def check_deprecation_warnings():
|
|
1066
|
-
if os.getenv("NPCSH_MODEL"):
|
|
1067
|
-
cprint(
|
|
1068
|
-
"Deprecation Warning: NPCSH_MODEL/PROVIDER deprecated. Use NPCSH_CHAT_MODEL/PROVIDER.",
|
|
1069
|
-
"yellow",
|
|
1070
|
-
)
|
|
1071
47
|
|
|
1072
48
|
def print_welcome_message():
|
|
49
|
+
'''
|
|
50
|
+
function for printing npcsh graphic
|
|
51
|
+
'''
|
|
52
|
+
|
|
1073
53
|
print(
|
|
1074
54
|
"""
|
|
1075
55
|
Welcome to \033[1;94mnpc\033[0m\033[1;38;5;202msh\033[0m!
|
|
@@ -1087,294 +67,11 @@ Begin by asking a question, issuing a bash command, or typing '/help' for more i
|
|
|
1087
67
|
"""
|
|
1088
68
|
)
|
|
1089
69
|
|
|
1090
|
-
def setup_shell() -> Tuple[CommandHistory, Team, Optional[NPC]]:
|
|
1091
|
-
check_deprecation_warnings()
|
|
1092
|
-
setup_npcsh_config()
|
|
1093
|
-
|
|
1094
|
-
db_path = os.getenv("NPCSH_DB_PATH", HISTORY_DB_DEFAULT_PATH)
|
|
1095
|
-
db_path = os.path.expanduser(db_path)
|
|
1096
|
-
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
|
1097
|
-
command_history = CommandHistory(db_path)
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
if not is_npcsh_initialized():
|
|
1101
|
-
print("Initializing NPCSH...")
|
|
1102
|
-
initialize_base_npcs_if_needed(db_path)
|
|
1103
|
-
print("NPCSH initialization complete. Restart or source ~/.npcshrc.")
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
try:
|
|
1108
|
-
history_file = setup_readline()
|
|
1109
|
-
atexit.register(save_readline_history)
|
|
1110
|
-
atexit.register(command_history.close)
|
|
1111
|
-
except:
|
|
1112
|
-
pass
|
|
1113
|
-
|
|
1114
|
-
project_team_path = os.path.abspath(PROJECT_NPC_TEAM_PATH)
|
|
1115
|
-
global_team_path = os.path.expanduser(DEFAULT_NPC_TEAM_PATH)
|
|
1116
|
-
team_dir = None
|
|
1117
|
-
default_forenpc_name = None
|
|
1118
|
-
|
|
1119
|
-
if os.path.exists(project_team_path):
|
|
1120
|
-
team_dir = project_team_path
|
|
1121
|
-
default_forenpc_name = "forenpc"
|
|
1122
|
-
else:
|
|
1123
|
-
if not os.path.exists('.npcsh_global'):
|
|
1124
|
-
resp = input(f"No npc_team found in {os.getcwd()}. Create a new team here? [Y/n]: ").strip().lower()
|
|
1125
|
-
if resp in ("", "y", "yes"):
|
|
1126
|
-
team_dir = project_team_path
|
|
1127
|
-
os.makedirs(team_dir, exist_ok=True)
|
|
1128
|
-
default_forenpc_name = "forenpc"
|
|
1129
|
-
forenpc_directive = input(
|
|
1130
|
-
f"Enter a primary directive for {default_forenpc_name} (default: 'You are the forenpc of the team...'): "
|
|
1131
|
-
).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."
|
|
1132
|
-
forenpc_model = input("Enter a model for your forenpc (default: llama3.2): ").strip() or "llama3.2"
|
|
1133
|
-
forenpc_provider = input("Enter a provider for your forenpc (default: ollama): ").strip() or "ollama"
|
|
1134
|
-
|
|
1135
|
-
with open(os.path.join(team_dir, f"{default_forenpc_name}.npc"), "w") as f:
|
|
1136
|
-
yaml.dump({
|
|
1137
|
-
"name": default_forenpc_name, "primary_directive": forenpc_directive,
|
|
1138
|
-
"model": forenpc_model, "provider": forenpc_provider
|
|
1139
|
-
}, f)
|
|
1140
|
-
|
|
1141
|
-
ctx_path = os.path.join(team_dir, "team.ctx")
|
|
1142
|
-
folder_context = input("Enter a short description for this project/team (optional): ").strip()
|
|
1143
|
-
team_ctx_data = {
|
|
1144
|
-
"forenpc": default_forenpc_name, "model": forenpc_model,
|
|
1145
|
-
"provider": forenpc_provider, "api_key": None, "api_url": None,
|
|
1146
|
-
"context": folder_context if folder_context else None
|
|
1147
|
-
}
|
|
1148
|
-
use_jinxs = input("Use global jinxs folder (g) or copy to this project (c)? [g/c, default: g]: ").strip().lower()
|
|
1149
|
-
if use_jinxs == "c":
|
|
1150
|
-
global_jinxs_dir = os.path.expanduser("~/.npcsh/npc_team/jinxs")
|
|
1151
|
-
if os.path.exists(global_jinxs_dir):
|
|
1152
|
-
shutil.copytree(global_jinxs_dir, team_dir, dirs_exist_ok=True)
|
|
1153
|
-
else:
|
|
1154
|
-
team_ctx_data["use_global_jinxs"] = True
|
|
1155
|
-
|
|
1156
|
-
with open(ctx_path, "w") as f:
|
|
1157
|
-
yaml.dump(team_ctx_data, f)
|
|
1158
|
-
else:
|
|
1159
|
-
render_markdown('From now on, npcsh will assume you will use the global team when activating from this folder. \n If you change your mind and want to initialize a team, use /init from within npcsh, `npc init` or `rm .npcsh_global` from the current working directory.')
|
|
1160
|
-
with open(".npcsh_global", "w") as f:
|
|
1161
|
-
pass
|
|
1162
|
-
team_dir = global_team_path
|
|
1163
|
-
default_forenpc_name = "sibiji"
|
|
1164
|
-
elif os.path.exists(global_team_path):
|
|
1165
|
-
team_dir = global_team_path
|
|
1166
|
-
default_forenpc_name = "sibiji"
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
team_ctx = {}
|
|
1170
|
-
for filename in os.listdir(team_dir):
|
|
1171
|
-
if filename.endswith(".ctx"):
|
|
1172
|
-
try:
|
|
1173
|
-
with open(os.path.join(team_dir, filename), "r") as f:
|
|
1174
|
-
team_ctx = yaml.safe_load(f) or {}
|
|
1175
|
-
break
|
|
1176
|
-
except Exception as e:
|
|
1177
|
-
print(f"Warning: Could not load context file {filename}: {e}")
|
|
1178
|
-
|
|
1179
|
-
forenpc_name = team_ctx.get("forenpc", default_forenpc_name)
|
|
1180
|
-
#render_markdown(f"- Using forenpc: {forenpc_name}")
|
|
1181
|
-
|
|
1182
|
-
if team_ctx.get("use_global_jinxs", False):
|
|
1183
|
-
jinxs_dir = os.path.expanduser("~/.npcsh/npc_team/jinxs")
|
|
1184
|
-
else:
|
|
1185
|
-
jinxs_dir = os.path.join(team_dir, "jinxs")
|
|
1186
|
-
|
|
1187
|
-
jinxs_list = load_jinxs_from_directory(jinxs_dir)
|
|
1188
|
-
jinxs_dict = {jinx.jinx_name: jinx for jinx in jinxs_list}
|
|
1189
|
-
|
|
1190
|
-
forenpc_obj = None
|
|
1191
|
-
forenpc_path = os.path.join(team_dir, f"{forenpc_name}.npc")
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
#render_markdown('- Loaded team context'+ json.dumps(team_ctx, indent=2))
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
if os.path.exists(forenpc_path):
|
|
1199
|
-
forenpc_obj = NPC(file = forenpc_path,
|
|
1200
|
-
jinxs=jinxs_list,
|
|
1201
|
-
db_conn=command_history.engine)
|
|
1202
|
-
if forenpc_obj.model is None:
|
|
1203
|
-
forenpc_obj.model= team_ctx.get("model", initial_state.chat_model)
|
|
1204
|
-
if forenpc_obj.provider is None:
|
|
1205
|
-
forenpc_obj.provider=team_ctx.get('provider', initial_state.chat_provider)
|
|
1206
|
-
|
|
1207
|
-
else:
|
|
1208
|
-
print(f"Warning: Forenpc file '{forenpc_name}.npc' not found in {team_dir}.")
|
|
1209
|
-
|
|
1210
|
-
team = Team(team_path=team_dir,
|
|
1211
|
-
forenpc=forenpc_obj,
|
|
1212
|
-
jinxs=jinxs_dict)
|
|
1213
|
-
|
|
1214
|
-
for npc_name, npc_obj in team.npcs.items():
|
|
1215
|
-
if not npc_obj.model:
|
|
1216
|
-
npc_obj.model = initial_state.chat_model
|
|
1217
|
-
if not npc_obj.provider:
|
|
1218
|
-
npc_obj.provider = initial_state.chat_provider
|
|
1219
|
-
|
|
1220
|
-
# Also apply to the forenpc specifically
|
|
1221
|
-
if team.forenpc and isinstance(team.forenpc, NPC):
|
|
1222
|
-
if not team.forenpc.model:
|
|
1223
|
-
team.forenpc.model = initial_state.chat_model
|
|
1224
|
-
if not team.forenpc.provider:
|
|
1225
|
-
team.forenpc.provider = initial_state.chat_provider
|
|
1226
|
-
team_name_from_ctx = team_ctx.get("name")
|
|
1227
|
-
if team_name_from_ctx:
|
|
1228
|
-
team.name = team_name_from_ctx
|
|
1229
|
-
elif team_dir and os.path.basename(team_dir) != 'npc_team':
|
|
1230
|
-
team.name = os.path.basename(team_dir)
|
|
1231
|
-
else:
|
|
1232
|
-
team.name = "global_team" # fallback for ~/.npcsh/npc_team
|
|
1233
|
-
|
|
1234
|
-
return command_history, team, forenpc_obj
|
|
1235
|
-
|
|
1236
|
-
# In your main npcsh.py file
|
|
1237
|
-
|
|
1238
|
-
def process_result(
|
|
1239
|
-
user_input: str,
|
|
1240
|
-
result_state: ShellState,
|
|
1241
|
-
output: Any,
|
|
1242
|
-
command_history: CommandHistory
|
|
1243
|
-
):
|
|
1244
|
-
|
|
1245
|
-
team_name = result_state.team.name if result_state.team else "__none__"
|
|
1246
|
-
npc_name = result_state.npc.name if isinstance(result_state.npc, NPC) else "__none__"
|
|
1247
|
-
|
|
1248
|
-
# Determine the actual NPC object to use for this turn's operations
|
|
1249
|
-
active_npc = result_state.npc if isinstance(result_state.npc, NPC) else NPC(
|
|
1250
|
-
name="default",
|
|
1251
|
-
model=result_state.chat_model,
|
|
1252
|
-
provider=result_state.chat_provider,
|
|
1253
|
-
db_conn=command_history.engine)
|
|
1254
|
-
save_conversation_message(
|
|
1255
|
-
command_history,
|
|
1256
|
-
result_state.conversation_id,
|
|
1257
|
-
"user",
|
|
1258
|
-
user_input,
|
|
1259
|
-
wd=result_state.current_path,
|
|
1260
|
-
model=active_npc.model,
|
|
1261
|
-
provider=active_npc.provider,
|
|
1262
|
-
npc=npc_name,
|
|
1263
|
-
team=team_name,
|
|
1264
|
-
attachments=result_state.attachments,
|
|
1265
|
-
)
|
|
1266
|
-
result_state.attachments = None
|
|
1267
|
-
|
|
1268
|
-
final_output_str = None
|
|
1269
|
-
output_content = output.get('output') if isinstance(output, dict) else output
|
|
1270
|
-
model_for_stream = output.get('model', active_npc.model) if isinstance(output, dict) else active_npc.model
|
|
1271
|
-
provider_for_stream = output.get('provider', active_npc.provider) if isinstance(output, dict) else active_npc.provider
|
|
1272
|
-
|
|
1273
|
-
print('\n')
|
|
1274
|
-
if user_input =='/help':
|
|
1275
|
-
render_markdown(output.get('output'))
|
|
1276
|
-
elif result_state.stream_output:
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
final_output_str = print_and_process_stream_with_markdown(output_content, model_for_stream, provider_for_stream)
|
|
1280
|
-
elif output_content is not None:
|
|
1281
|
-
final_output_str = str(output_content)
|
|
1282
|
-
render_markdown(final_output_str)
|
|
1283
|
-
|
|
1284
|
-
if final_output_str:
|
|
1285
|
-
|
|
1286
|
-
if result_state.messages and (not result_state.messages or result_state.messages[-1].get("role") != "assistant"):
|
|
1287
|
-
result_state.messages.append({"role": "assistant", "content": final_output_str})
|
|
1288
|
-
save_conversation_message(
|
|
1289
|
-
command_history,
|
|
1290
|
-
result_state.conversation_id,
|
|
1291
|
-
"assistant",
|
|
1292
|
-
final_output_str,
|
|
1293
|
-
wd=result_state.current_path,
|
|
1294
|
-
model=active_npc.model,
|
|
1295
|
-
provider=active_npc.provider,
|
|
1296
|
-
npc=npc_name,
|
|
1297
|
-
team=team_name,
|
|
1298
|
-
)
|
|
1299
|
-
|
|
1300
|
-
conversation_turn_text = f"User: {user_input}\nAssistant: {final_output_str}"
|
|
1301
|
-
engine = command_history.engine
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
if result_state.build_kg:
|
|
1305
|
-
try:
|
|
1306
|
-
if not should_skip_kg_processing(user_input, final_output_str):
|
|
1307
|
-
|
|
1308
|
-
npc_kg = load_kg_from_db(engine, team_name, npc_name, result_state.current_path)
|
|
1309
|
-
evolved_npc_kg, _ = kg_evolve_incremental(
|
|
1310
|
-
existing_kg=npc_kg,
|
|
1311
|
-
new_content_text=conversation_turn_text,
|
|
1312
|
-
model=active_npc.model,
|
|
1313
|
-
provider=active_npc.provider,
|
|
1314
|
-
get_concepts=True,
|
|
1315
|
-
link_concepts_facts = False,
|
|
1316
|
-
link_concepts_concepts = False,
|
|
1317
|
-
link_facts_facts = False,
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
)
|
|
1321
|
-
save_kg_to_db(engine,
|
|
1322
|
-
evolved_npc_kg,
|
|
1323
|
-
team_name,
|
|
1324
|
-
npc_name,
|
|
1325
|
-
result_state.current_path)
|
|
1326
|
-
except Exception as e:
|
|
1327
|
-
print(colored(f"Error during real-time KG evolution: {e}", "red"))
|
|
1328
|
-
|
|
1329
|
-
# --- Part 3: Periodic Team Context Suggestions ---
|
|
1330
|
-
result_state.turn_count += 1
|
|
1331
|
-
|
|
1332
|
-
if result_state.turn_count > 0 and result_state.turn_count % 10 == 0:
|
|
1333
|
-
print(colored("\nChecking for potential team improvements...", "cyan"))
|
|
1334
|
-
try:
|
|
1335
|
-
summary = breathe(messages=result_state.messages[-20:],
|
|
1336
|
-
npc=active_npc)
|
|
1337
|
-
characterization = summary.get('output')
|
|
1338
|
-
|
|
1339
|
-
if characterization and result_state.team:
|
|
1340
|
-
team_ctx_path = os.path.join(result_state.team.team_path, "team.ctx")
|
|
1341
|
-
ctx_data = {}
|
|
1342
|
-
if os.path.exists(team_ctx_path):
|
|
1343
|
-
with open(team_ctx_path, 'r') as f:
|
|
1344
|
-
ctx_data = yaml.safe_load(f) or {}
|
|
1345
|
-
current_context = ctx_data.get('context', '')
|
|
1346
|
-
|
|
1347
|
-
prompt = f"""Based on this characterization: {characterization},
|
|
1348
|
-
|
|
1349
|
-
suggest changes (additions, deletions, edits) to the team's context.
|
|
1350
|
-
Additions need not be fully formed sentences and can simply be equations, relationships, or other plain clear items.
|
|
1351
|
-
|
|
1352
|
-
Current Context: "{current_context}".
|
|
1353
|
-
|
|
1354
|
-
Respond with JSON: {{"suggestion": "Your sentence."
|
|
1355
|
-
}}"""
|
|
1356
|
-
response = get_llm_response(prompt, npc=active_npc, format="json")
|
|
1357
|
-
suggestion = response.get("response", {}).get("suggestion")
|
|
1358
|
-
|
|
1359
|
-
if suggestion:
|
|
1360
|
-
new_context = (current_context + " " + suggestion).strip()
|
|
1361
|
-
print(colored(f"{result_state.npc.name} suggests updating team context:", "yellow"))
|
|
1362
|
-
print(f" - OLD: {current_context}\n + NEW: {new_context}")
|
|
1363
|
-
if input("Apply? [y/N]: ").strip().lower() == 'y':
|
|
1364
|
-
ctx_data['context'] = new_context
|
|
1365
|
-
with open(team_ctx_path, 'w') as f:
|
|
1366
|
-
yaml.dump(ctx_data, f)
|
|
1367
|
-
print(colored("Team context updated.", "green"))
|
|
1368
|
-
else:
|
|
1369
|
-
print("Suggestion declined.")
|
|
1370
|
-
except Exception as e:
|
|
1371
|
-
import traceback
|
|
1372
|
-
print(colored(f"Could not generate team suggestions: {e}", "yellow"))
|
|
1373
|
-
traceback.print_exc()
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
70
|
|
|
1377
71
|
def run_repl(command_history: CommandHistory, initial_state: ShellState):
|
|
72
|
+
'''
|
|
73
|
+
Func for running the npcsh repl
|
|
74
|
+
'''
|
|
1378
75
|
state = initial_state
|
|
1379
76
|
print_welcome_message()
|
|
1380
77
|
|
|
@@ -1502,7 +199,10 @@ def run_repl(command_history: CommandHistory, initial_state: ShellState):
|
|
|
1502
199
|
npc_name = state.npc.name if isinstance(state.npc, NPC) else "__none__"
|
|
1503
200
|
session_scopes.add((team_name, npc_name, state.current_path))
|
|
1504
201
|
|
|
1505
|
-
state, output = execute_command(user_input,
|
|
202
|
+
state, output = execute_command(user_input,
|
|
203
|
+
state,
|
|
204
|
+
review = True,
|
|
205
|
+
router=router)
|
|
1506
206
|
process_result(user_input,
|
|
1507
207
|
state,
|
|
1508
208
|
output,
|
|
@@ -1510,14 +210,11 @@ def run_repl(command_history: CommandHistory, initial_state: ShellState):
|
|
|
1510
210
|
|
|
1511
211
|
except KeyboardInterrupt:
|
|
1512
212
|
if is_windows:
|
|
1513
|
-
# On Windows, Ctrl+C cancels the current input line, show prompt again
|
|
1514
213
|
print("^C")
|
|
1515
214
|
continue
|
|
1516
215
|
else:
|
|
1517
|
-
# On Unix, Ctrl+C exits the shell as before
|
|
1518
216
|
exit_shell(state)
|
|
1519
217
|
except EOFError:
|
|
1520
|
-
# Ctrl+D: exit shell cleanly
|
|
1521
218
|
exit_shell(state)
|
|
1522
219
|
def main() -> None:
|
|
1523
220
|
parser = argparse.ArgumentParser(description="npcsh - An NPC-powered shell.")
|
|
@@ -1532,11 +229,7 @@ def main() -> None:
|
|
|
1532
229
|
command_history, team, default_npc = setup_shell()
|
|
1533
230
|
|
|
1534
231
|
initial_state.npc = default_npc
|
|
1535
|
-
initial_state.team = team
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
# add a -g global command to indicate if to use the global or project, otherwise go thru normal flow
|
|
1539
|
-
|
|
232
|
+
initial_state.team = team
|
|
1540
233
|
if args.command:
|
|
1541
234
|
state = initial_state
|
|
1542
235
|
state.current_path = os.getcwd()
|