| 12 | pass |
| 13 | |
| 14 | class AgentVMClient: |
| 15 | def __init__(self): |
| 16 | # Path to bridge script relative to this file |
| 17 | self.bridge_path = os.path.join(os.path.dirname(__file__), 'agent_bridge.js') |
| 18 | self.process = None |
| 19 | |
| 20 | def start(self): |
| 21 | print("Booting VM...", file=sys.stderr) |
| 22 | self.process = subprocess.Popen( |
| 23 | ['node', self.bridge_path], |
| 24 | stdin=subprocess.PIPE, |
| 25 | stdout=subprocess.PIPE, |
| 26 | stderr=sys.stderr, # Forward stderr (logs) to user console |
| 27 | text=True, |
| 28 | bufsize=1 |
| 29 | ) |
| 30 | |
| 31 | # Wait for READY signal |
| 32 | while True: |
| 33 | line = self.process.stdout.readline() |
| 34 | if not line: |
| 35 | raise RuntimeError("VM process exited unexpectedly") |
| 36 | if line.strip() == "READY": |
| 37 | break |
| 38 | |
| 39 | print("VM Ready.", file=sys.stderr) |
| 40 | |
| 41 | def exec(self, command): |
| 42 | if not self.process: |
| 43 | raise RuntimeError("VM not started") |
| 44 | |
| 45 | req = json.dumps({"cmd": "exec", "command": command}) |
| 46 | self.process.stdin.write(req + "\n") |
| 47 | self.process.stdin.flush() |
| 48 | |
| 49 | resp_line = self.process.stdout.readline() |
| 50 | if not resp_line: |
| 51 | raise RuntimeError("VM closed connection") |
| 52 | |
| 53 | resp = json.loads(resp_line) |
| 54 | if resp.get('status') == 'ok': |
| 55 | return resp['result'] |
| 56 | else: |
| 57 | raise RuntimeError(f"VM Error: {resp.get('error')}") |
| 58 | |
| 59 | def stop(self): |
| 60 | if self.process: |
| 61 | try: |
| 62 | self.process.stdin.write(json.dumps({"cmd": "stop"}) + "\n") |
| 63 | self.process.stdin.flush() |
| 64 | self.process.wait(timeout=2) |
| 65 | except: |
| 66 | self.process.kill() |
| 67 | self.process = None |
| 68 | |
| 69 | def run_agent(): |
| 70 | vm = AgentVMClient() |