-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_machine.py
More file actions
814 lines (671 loc) · 30.9 KB
/
Copy pathvirtual_machine.py
File metadata and controls
814 lines (671 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
# hybrid_shell_replicator.py
from __future__ import annotations
from pathlib import Path
from typing import Dict, List
from pathlib import Path
import shlex
from file_system import SimpleFileSystem
from langchain_openai import ChatOpenAI
import random
from utils import remove_fence
import logging
import csv
import uuid
import re
import glob
logger = logging.getLogger(__name__)
class VM():
INJECT_ERROR_CMD_PROB = 0.1
MAX_HISTORY_COMMANDS = 10
NEXT_PID = 1000 # Starting PID for simulated processes
def __init__(self,
llm: ChatOpenAI,
context: Dict[str,str],
initial_files: Dict[str, str] = {},
known_hosts: Dict[str,VM] = dict(),
madness:float = 0.0):
self.context = context
self.llm = llm
self.user, self.ip = self.context['user'], self.context['primary_ip']
self.fs = SimpleFileSystem(cwd=f"/home/{self.user}",
initial_files=initial_files)
self.madness = madness
self.packages = {
"apt": {"bash", "coreutils", "python3", "python"},
"pip": {"wheel","setuptools"}
}
self.gpu_info = {
"name": "NVIDIA GeForce RTX 3090",
"driver_version": "470.57.02",
"cuda_version": "11.4",
"memory_total": "24GB",
}
self.process_table: List[Dict] = []
self.interaction_history = []
self.known_hosts: Dict[str,VM] = known_hosts
self.remote_context = None # if set, a VM instance we're logged into remotely
def build_system_prompt(self):
"""Build system prompt with indexed prior commands + summaries."""
prompt_parts = [
"You are an expert Ubuntu bash shell running on a system with NVIDIA GPU.\n",
]
if self.interaction_history:
prompt_parts.append("Prior interaction history:\n")
# Include last N (=MAX_HISTORY_COMMANDS) interactions numbered
for idx, (cmd_idx, cmd, summary) in enumerate(
reversed(self.interaction_history[-self.MAX_HISTORY_COMMANDS:])
):
prompt_parts.append(
f"[{cmd_idx}]$ {cmd}\nOutput summary:\n{summary}\n"
)
prompt_parts.append("\n")
# Add current system snapshot
prompt_parts.append(self.build_system_snapshot_text())
prompt_parts.append(
"""
Instructions:
- Respond ONLY with the shell output, do NOT mention you are an AI or simulation. Never respond with something like the bash prompt like "(venv) agent@ubuntu2204:~$ ".
- Respond with "xxx: command not found" if the input command can never be a bash command.
- Use full knowledge of files, installed packages, and GPU.
- Simulate realistic behavior: successes, warnings, errors, anomalies.
- File system modifications already applied; respond with outputs only.
- Handle commands like ls, cat, pwd, nvidia-smi, apt list --installed, pip list, python3, echo, etc.
- Respond as realistically as possible as a Linux bash shell.
- If a command is invalid, respond with typical bash errors.
- When simulating command outputs, indicate possible files that may be <UPDATE_FILE>updated</UPDATE_FILE>, <CREATE_FILE>created</CREATE_FILE>, or <REMOVE_FILE>removed</REMOVE_FILE> when executing the command, enclosed in the respective tags.
- If a new process needs to be created (e.g., running a script or a command in the background), provide information about the new process in <UPDATE_PROCESS> tags, including the process ID and command being run.
"""
)
# Add the realistic errors/failures sentence with ~10% probability
if random.random() < self.madness:
prompt_parts.append(
"- Commands should randomly simulate realistic errors or failures (e.g., permission denied, I/O errors, network issues)."
)
return "\n".join(prompt_parts)
def _ps(self) -> str:
lines = ["PID CMD STATUS"]
for proc in self.process_table:
lines.append(f"{proc['pid']} {proc['cmd']:20} {proc['status']}")
return "\n".join(lines)
def _grep(self, pattern: str, input_data: str) -> str:
lines = input_data.split("\n")
matched = [line for line in lines if pattern in line]
return "\n".join(matched)
def build_system_snapshot_text(self):
files_summary = self.fs.tree()
package_str = ""
for k in self.packages:
package_str += ", ".join(sorted(self.packages[k])) or f"no third-party {k} packages installed"
gpu = self.gpu_info
gpu_desc = (
f"GPU: {gpu['name']}\n"
f"Driver Version: {gpu['driver_version']}\n"
f"CUDA Version: {gpu['cuda_version']}\n"
f"Memory Total: {gpu['memory_total']}"
)
snapshot = f"""
System Info:
{self.context['distro']}
System snapshot:
{gpu_desc}
Installed packages:
{package_str}
Files/folders in the current working directory:
{files_summary}
"""
# Add process count info in snapshot
proc_running = len(self.process_table)
snapshot += f"\n\nCurrently running background processes: {proc_running}"
return snapshot.strip()
def _apt(self, args: List[str]) -> str:
"""Simulate apt package manager."""
if not args:
return "apt: missing operation"
operation = args[0]
# apt install operation
if operation == "install":
if len(args) < 2:
return "apt: you must specify a package to install"
packages_to_install = [p for p in args[1:] if not p.startswith('-')]
for pkg in packages_to_install:
self.packages["apt"].add(pkg)
return f"Successfully installed: {' '.join(packages_to_install)}"
# Other apt operations
else:
return "Simulated apt OK"
def _pip(self, args: List[str]) -> str:
"""Simulate pip package manager."""
if not args:
return "pip: missing operation"
operation = args[0]
# pip install operation
if operation == "install":
if len(args) < 2:
return "pip: you must specify a package to install"
packages_to_install = []
for arg in args[1:]:
if arg.startswith('-'):
continue
# Handle package versions like package==1.0.0
pkg_name = arg.split('==')[0].split('>=')[0].split('<=')[0].split('>')[0].split('<')[0]
packages_to_install.append(pkg_name)
for pkg in packages_to_install:
self.packages["pip"].add(pkg)
return f"Successfully installed: {' '.join(packages_to_install)}"
# Other pip operations
else:
return "Simulated pip OK"
def _execute_local_command(self, cmd: str) -> str:
cmd = cmd.strip()
if not cmd:
return ""
background = cmd.endswith("&")
if background:
cmd = cmd[:-1].strip()
# Split by pipe first
pipe_segments = cmd.split("|")
last_output = ""
for segment in pipe_segments:
segment = segment.strip()
# Handle commands connected with `&&`
and_segments = segment.split("&&")
for index, subcommand in enumerate(and_segments):
subcommand = subcommand.strip()
subcommand, redir_out_path, redir_out_mode, combine_err = self._parse_redirection(subcommand)
current_output = self._run_simple_command(subcommand, input_data=last_output)
# Check if the previous command was successful (zero exit status)
if index > 0 and not self._last_command_success:
# If the previous command failed, we break out of further commands.
return ""
# Store the status of the last command
self._last_command_success = (current_output != "")
if redir_out_path:
existing = ""
if redir_out_mode == "append" and self.fs.exists(redir_out_path):
existing = self.fs.read(redir_out_path)
self.fs.write(redir_out_path, existing + current_output)
current_output = ""
last_output = current_output # For the next command in the sequence
if background:
pid = str(uuid.uuid4())[:8]
self.process_table.append({
"pid": pid,
"cmd": cmd,
"status": "Running",
})
return f"[{pid}] {cmd} &"
return last_output
def _parse_redirection(self, segment: str):
redir_out_path = None
redir_out_mode = "truncate"
combine_err = False
tokens = shlex.split(segment)
final_tokens = []
skip_next = False
for i, token in enumerate(tokens):
if skip_next:
skip_next = False
continue
if token == "2>&1":
combine_err = True
elif token in (">", ">>"):
redir_out_mode = "append" if token == ">>" else "truncate"
if i + 1 < len(tokens):
redir_out_path = tokens[i + 1]
skip_next = True
else:
final_tokens.append(token)
segment_without_redir = " ".join(final_tokens)
return segment_without_redir, redir_out_path, redir_out_mode, combine_err
def _python(self, args: List[str]) -> str:
"""Simulate running a Python script, update the process table, and return simulated output."""
if not args:
return "python: missing script operand"
script_path = args[0]
norm_path = self.fs._norm(script_path)
# Check if the script exists
if norm_path not in self.fs.files:
return f"python: can't open file '{script_path}': [Errno 2] No such file or directory"
# Simulate running the script (you can expand this as needed)
simulated_output = f"Simulated output of {script_path}...\n"
# Add to the process table as a running script
process_entry = {
"pid": str(uuid.uuid4())[:8], # Use a UUID for process ID simulation
"cmd": f"python {script_path}",
"status": "Running"
}
self.process_table.append(process_entry)
# Simulated success message
return f"{simulated_output}Process '{process_entry['pid']}' is now running.\n(Process table updated)"
def run_command(self, cmd: str) -> str:
# Check for remote context
cmd = cmd.replace('sudo ','')
logger.debug(f"BEGIN System {self.user}@{self.ip} Execution: {cmd}")
if self.remote_context:
if cmd.strip() == "exit":
# Exit remote context
remote_user_ip = f"{self.remote_context.user}@{self.remote_context.ip}"
self.remote_context = None
res= f"Exit remote session ({remote_user_ip})"
else:
return self.remote_context.run_command(cmd)
parts = shlex.split(cmd.strip())
if not parts:
return ""
# Handle ssh command simulation
if parts[0] == "ssh":
res = self._handle_ssh(parts[1:])
elif parts[0] == "sftp":
res = self._handle_sftp(parts[1:])
elif parts[0] == "rsync":
res = self._handle_rsync(parts[1:])
elif parts[0] == 'scp':
res = self._handle_scp(parts[1:])
else:
res = self._execute_local_command(cmd)
summary = self.summarize_output(res.strip())
next_index = 1 + (self.interaction_history[-1][0] if self.interaction_history else 0)
self.interaction_history.append((next_index, cmd, res.strip()))
logger.info(f"END System {self.user}@{self.ip} Execution: {cmd}")
logger.info(f"Output: {res}")
return res
def save_interaction_history_to_csv(self, path):
filename = f"{path}.traj.csv"
with open(filename, mode='w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Optionally write header:
writer.writerow(['next_index', 'cmd', 'res'])
for record in self.interaction_history:
writer.writerow(record)
print(f'Saving traj to {filename}...')
def _handle_ssh(self, args: list) -> str:
"""
Parse ssh command with options.
Example command lines this simulates:
ssh ubuntu@10.235.128.35
ssh -o ConnectTimeout=10 ubuntu@10.235.128.35 pwd
ssh -i id_rsa ubuntu@10.235.128.35 'ls -la'
"""
if not args:
return "ssh: usage: ssh [options] user@host [command]"
# Parse options before user@ip
i = 0
while i < len(args) and args[i].startswith('-'):
# Handle options that have argument, e.g. -o ConnectTimeout=10, -i identityfile
opt = args[i]
# '-o' and '-i' options take one additional argument
if opt in ('-o', '-i'):
i += 2
else:
# Other options (like -v, -q) without args
i += 1
if i >= len(args):
return "ssh: user@host not specified"
# The current arg should be user@ip
remote = args[i]
i += 1
# Check if remote VM exists
remote_vm = self.known_hosts.get(remote)
if remote_vm is None:
return f"ssh: Could not resolve hostname {remote}: Name or service not known"
# The rest args are remote command, if any
if i == len(args):
# No remote command, interactive session
self.remote_context = remote_vm
return f"Connected to {remote}. All future commands run on remote VM."
# Compose remote command string from remaining args
remote_cmd = " ".join(args[i:])
# Strip quotes if present
if (remote_cmd.startswith('"') and remote_cmd.endswith('"')) or (remote_cmd.startswith("'") and remote_cmd.endswith("'")):
remote_cmd = remote_cmd[1:-1]
# Execute on remote VM
return remote_vm.run_command(remote_cmd)
def _handle_sftp(self, args: list) -> str:
"""
Simulate sftp connection to remote VM
Usage: sftp user@ip
"""
if not args:
return "sftp: missing host operand"
remote = args[0]
remote_vm = self.known_hosts.get(remote)
if remote_vm is None:
return f"sftp: Could not resolve hostname {remote}: Name or service not known"
# For simulation, just return a basic interaction message
return f"Connected to {remote} via sftp. (Simulation)"
def _handle_rsync(self, args: list) -> str:
"""
Improved rsync simulation with support for options like '-avz' and '-e ssh'.
"""
print(args)
if len(args) < 2:
return "rsync: missing source or destination"
# Parse args to separate options and positional args
positional_args = []
options = []
i = 0
exclude_patterns = []
while i < len(args):
arg = args[i]
if arg.startswith('-'):
options.append(arg)
# Handle --exclude=pattern
if arg.startswith('--exclude='):
pattern = arg[len('--exclude='):]
exclude_patterns.append(pattern.strip('"').strip("'"))
i += 1
# Handle --exclude pattern
elif arg == '--exclude':
if i + 1 < len(args):
pattern = args[i+1]
exclude_patterns.append(pattern.strip('"').strip("'"))
i += 2
else:
return "rsync: error: --exclude requires a pattern"
# Handle options with separate parameters e.g. -e ssh
elif arg == '-e':
if i + 1 < len(args):
options.append(args[i+1]) # Store the value of -e
i += 2
else:
return "rsync: error: -e requires an argument"
else:
# Other options like -avz combined, just skip
i += 1
else:
# Positional argument (source or destination)
positional_args.append(arg)
i += 1
# Check if we have enough positional arguments
if len(positional_args) < 2:
return "rsync: missing source or destination"
# The source is the second-to-last positional argument
source = positional_args[0]
# The target is the last positional argument
target = positional_args[1]
def parse_remote_path(path):
# remote path like user@ip:/dir
if ':' in path:
h, p = path.split(':', 1)
if h in self.known_hosts:
return h, p
return None, path
src_remote, src_path = parse_remote_path(source)
tgt_remote, tgt_path = parse_remote_path(target)
def is_excluded(filename: str):
for pat in exclude_patterns:
if pat == ".*":
if filename.startswith('.'):
return True
# Extend support as needed
return False
# Local->Remote copy
if tgt_remote and not src_remote:
remote_vm = self.known_hosts.get(tgt_remote)
if not remote_vm:
return f"rsync: connection failed to {tgt_remote}: No such host"
# Support directory copy syntax
prefix = src_path.rstrip('/')
matched_files = []
for fpath in self.fs.files:
if prefix == '.' or fpath == prefix or fpath.startswith(prefix + '/'):
fname = Path(fpath).name
if is_excluded(fname):
continue
matched_files.append(fpath)
if not matched_files:
return f"rsync: failed to stat {source}: No such file or directory (after exclude)"
for fpath in matched_files:
content = self.fs.cat(fpath)
if prefix == '.' or prefix == '':
relative_part = Path(fpath)
else:
relative_part = Path(fpath).relative_to(prefix)
dest_path = str(Path(tgt_path) / relative_part)
logger.info(f"Content: {content}")
if(type(content) == list):
content = content[0]
remote_vm.fs.write(dest_path, content)
return f"rsync: copied local {source} to remote {tgt_remote}:{tgt_path} with exclusions {exclude_patterns}"
# Remote->Local copy
if src_remote and not tgt_remote:
remote_vm = self.known_hosts.get(src_remote)
if not remote_vm:
return f"rsync: connection failed to {src_remote}: No such host"
prefix = src_path.rstrip('/')
matched_files = []
for fpath in remote_vm.fs.files:
if prefix == '.' or fpath == prefix or fpath.startswith(prefix + '/'):
fname = Path(fpath).name
if is_excluded(fname):
continue
matched_files.append(fpath)
if not matched_files:
return f"rsync: failed to stat {source}: No such file or directory (after exclude)"
for fpath in matched_files:
content = remote_vm.fs.cat(fpath)
if prefix == '.' or prefix == '':
relative_part = Path(fpath)
else:
relative_part = Path(fpath).relative_to(prefix)
dest_path = str(Path(tgt_path) / relative_part)
if(type(content) == list):
content = content[0]
self.fs.write(dest_path, content)
return f"rsync: copied remote {src_remote}:{src_path} to local {tgt_path} with exclusions {exclude_patterns}"
return "rsync: simulation only supports local<->remote copies"
def _handle_scp(self, args: List[str]) -> str:
"""
Simulate scp command, including recursive copy -r of multiple local paths to remote.
Example: scp -r ./config ./models ... user@ip:/remote/path
"""
if not args:
return "scp: missing file operand"
recursive = False
paths = []
# parse flags and paths
for arg in args:
if arg == '-r':
recursive = True
else:
paths.append(arg)
if not paths:
return "scp: missing source or destination file"
# last path is destination
dest = paths[-1]
sources = paths[:-1]
# Parse destination user@ip:path
if ':' not in dest:
return "scp: target destination missing remote host"
dest_host, dest_path = dest.split(':', 1)
# Validate remote VM exists
remote_vm = self.known_hosts.get(dest_host)
if remote_vm is None:
return f"scp: Could not resolve hostname {dest_host}: Name or service not known"
# Normalize remote target directory path
norm_dest_path = remote_vm.fs._norm(dest_path)
if not recursive and len(sources) > 1:
return "scp: when copying multiple files, -r must be specified"
# Helper: recursively copy files/dirs from src_path in local fs to dest_path in remote fs
def recursive_copy_local_to_remote(src_path: str, target_remote_dir: str):
norm_src_path = self.fs._norm(src_path)
# Handle wildcard '*' manually (expand files in local virtual fs)
if '*' in norm_src_path:
# Split the path into directory and pattern part
dir_path, pattern = norm_src_path.rsplit('/', 1)
dir_path = Path(dir_path)
# Match all files in this directory that match the pattern
matching_files = [
f for f in self.fs.files if re.match(f'{dir_path}/{pattern.replace("*", ".*")}', f)
]
if not matching_files:
return f"scp: cannot stat '{src_path}': No such file or directory"
else:
# If no wildcard, check if it's a single file or directory
if norm_src_path not in self.fs.files:
return f"scp: cannot stat '{src_path}': No such file or directory"
matching_files = [norm_src_path]
# Check if src_path is a file or directory (simulate directory if any file under this path)
files_to_copy = []
for f in matching_files:
files_to_copy.append(Path(f))
# Copy files maintaining relative structure under target_remote_dir
for f in files_to_copy:
try:
rel_path = f.relative_to(norm_src_path) if f != norm_src_path else Path(f.name)
except ValueError:
# f == norm_src_path file itself, rel path is just filename
rel_path = Path(f.name)
dest_file_path = Path(target_remote_dir) / rel_path
content = self.fs.cat(str(f))
if(type(content) == list):
content = content[0]
remote_vm.fs.write(str(dest_file_path), content)
return None # success
# Iterate sources and copy
errors = []
for src in sources:
err = recursive_copy_local_to_remote(src, norm_dest_path)
if err:
errors.append(err)
return "\n".join(errors) if errors else f"scp: copied {len(sources)} item(s) to {dest_host}:{norm_dest_path}"
def logout_remote(self) -> str:
"""Logout from remote ssh session."""
if self.remote_context:
disconnected = f"Disconnected from {self.remote_context.user}@{self.remote_context.ip}"
self.remote_context = None
return disconnected
return "Not connected to any remote VM."
def _run_simple_command(self, cmd: str, input_data: str = "") -> str:
if not cmd.strip():
return input_data
parts = shlex.split(cmd)
if not parts:
return ""
b = parts[0]
if b == "pwd":
return self.fs.pwd()
elif b == "cd":
if len(parts) > 1:
self.fs.cd(parts[1])
return ""
elif b == "ls":
if len(parts) == 1:
return "\n".join(self.fs.ls())
elif len(parts) == 2:
if parts[1].startswith('-'):
flags = parts[1]
return "\n".join(self.fs.ls(None, flags=flags))
else:
return "\n".join(self.fs.ls(parts[1]))
elif len(parts) == 3:
path = parts[1]
flags = parts[2]
return "\n".join(self.fs.ls(path, flags=flags))
elif b == "tree":
return self.fs.tree()
elif b == "echo":
return cmd.partition(" ")[2]
elif b == "cat":
if len(parts) > 1:
return self.fs.cat(parts[1])
return ""
elif b == "touch":
if len(parts) > 1:
self.fs.write(parts[1], "")
return ""
elif b in {"apt", "apt-get"}:
return self._apt(parts[1:])
elif b == "pip":
return self._pip(parts[1:])
elif b.startswith("python"):
return self._python(parts[1:])
elif b == "exit":
return "Session terminated."
elif b == "ps":
return self._ps()
elif b == "grep":
if len(parts) > 1:
return self._grep(parts[1], input_data)
return input_data
return self.query_llm(cmd)
# summarize_output function as you defined earlier or import
def summarize_output(self, output, head_lines=10, tail_lines=10):
lines = output.splitlines()
total_lines = len(lines)
if total_lines <= head_lines + tail_lines:
return output # short enough, no truncation
else:
omitted = total_lines - (head_lines + tail_lines)
summary_lines = (
lines[:head_lines]
+ [f"... [omitted {omitted} lines] ..."]
+ lines[-tail_lines:]
)
return "\n".join(summary_lines)
def query_llm(self, user_command):
system_prompt = self.build_system_prompt()
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_command},
]
# Invoke the LLM and get the response
response = remove_fence(self.llm.invoke(messages).content)
# Parse the response for file and process updates
update_info = self.parse_response(response)
cleaned_response = re.sub(r'<UPDATE_FILE>.*?</UPDATE_FILE>', '', response, flags=re.DOTALL)
cleaned_response = re.sub(r'<CREATE_FILE>.*?</CREATE_FILE>', '', cleaned_response, flags=re.DOTALL)
cleaned_response = re.sub(r'<REMOVE_FILE>.*?</REMOVE_FILE>', '', cleaned_response, flags=re.DOTALL)
cleaned_response = re.sub(r'<UPDATE_PROCESS>.*?</UPDATE_PROCESS>', '', cleaned_response, flags=re.DOTALL)
return cleaned_response # Return parsed updates if available, else return original response
def parse_response(self, response: str):
"""
Parse the LLM response to extract file updates and process information,
and apply those updates to the virtual file system and process table.
:param response: The raw response string from the LLM.
:return: A structured summary of updates, or None if no structured
output is found.
"""
files_updated = []
processes_created = []
if "<UPDATE_FILE>" in response:
# Extract files updated
updated_files = response.split("<UPDATE_FILE>")[1:]
for file_info in updated_files:
file_name = file_info.split("</UPDATE_FILE>")[0].strip()
# Update the virtual file system
if file_name not in self.fs.files:
self.fs.write(file_name, "") # Create if not exists
files_updated.append(file_name)
if "<CREATE_FILE>" in response:
# Extract files created
created_files = response.split("<CREATE_FILE>")[1:]
for file_info in created_files:
file_name = file_info.split("</CREATE_FILE>")[0].strip()
# Update the virtual file system
self.fs.write(file_name, "") # Create the file
files_updated.append(file_name)
if "<REMOVE_FILE>" in response:
# Extract files removed
removed_files = response.split("<REMOVE_FILE>")[1:]
for file_info in removed_files:
file_name = file_info.split("</REMOVE_FILE>")[0].strip()
# Remove the file from the virtual file system
if file_name in self.fs.files:
del self.fs.files[file_name] # Remove the file
files_updated.append(file_name)
if "<UPDATE_PROCESS>" in response:
# Extract processes created
updated_processes = response.split("<UPDATE_PROCESS>")[1:]
for process_info in updated_processes:
process_detail = process_info.split("</UPDATE_PROCESS>")[0].strip()
# Update the process table
pid = str(uuid.uuid4())[:8] # Simulate a unique PID
self.process_table.append({"pid": pid, "cmd": process_detail, "status": "Running"})
processes_created.append(process_detail)
# Build a structured response with updates found
structured_response = []
if files_updated:
structured_response.append(f"Updated files: {', '.join(files_updated)}.")
if processes_created:
structured_response.append(f"Created processes: {', '.join(processes_created)}.")