Send a debug command and return the response.
(cmd, session_id=None, timeout=10)
| 16 | REPO_ROOT = Path(__file__).resolve().parent.parent |
| 17 | |
| 18 | def send_cmd(cmd, session_id=None, timeout=10): |
| 19 | """Send a debug command and return the response.""" |
| 20 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 21 | sock.settimeout(timeout) |
| 22 | sock.connect(SOCKET_PATH) |
| 23 | |
| 24 | req = {"type": "debug_command", "id": 1, "command": cmd} |
| 25 | if session_id: |
| 26 | req["session_id"] = session_id |
| 27 | |
| 28 | sock.send((json.dumps(req) + '\n').encode()) |
| 29 | |
| 30 | # Read response with non-blocking to handle slow responses |
| 31 | data = b'' |
| 32 | sock.setblocking(False) |
| 33 | start = time.time() |
| 34 | while time.time() - start < timeout: |
| 35 | try: |
| 36 | chunk = sock.recv(4096) |
| 37 | if chunk: |
| 38 | data += chunk |
| 39 | # Check if we have a complete JSON response |
| 40 | try: |
| 41 | resp = json.loads(data.decode()) |
| 42 | sock.close() |
| 43 | return resp.get('ok', False), resp.get('output', '') |
| 44 | except json.JSONDecodeError: |
| 45 | pass |
| 46 | except BlockingIOError: |
| 47 | time.sleep(0.05) |
| 48 | |
| 49 | sock.close() |
| 50 | if data: |
| 51 | try: |
| 52 | resp = json.loads(data.decode()) |
| 53 | return resp.get('ok', False), resp.get('output', '') |
| 54 | except json.JSONDecodeError: |
| 55 | return False, f"Invalid JSON: {data.decode()[:100]}" |
| 56 | raise TimeoutError("timed out") |
| 57 | |
| 58 | def create_session(cwd="/tmp"): |
| 59 | """Create a headless session for testing.""" |
no test coverage detected