| from __future__ import annotations | |
| import json | |
| import os | |
| import shlex | |
| import shutil | |
| import subprocess | |
| from typing import Any, Dict | |
| from .registry import ToolRegistry | |
| def _run(cmd: str, timeout: int = 60) -> str: | |
| proc = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=timeout) | |
| return json.dumps({"returncode": proc.returncode, "stdout": proc.stdout[-4000:], "stderr": proc.stderr[-4000:]}) | |
| def t_shell_exec(args: Dict[str, Any]) -> str: | |
| cmd = args.get("command") or args.get("cmd") | |
| if not cmd or not isinstance(cmd, str): | |
| return json.dumps({"error": "command required"}) | |
| return _run(cmd, timeout=int(args.get("timeout", 120))) | |
| def t_process_list(_: Dict[str, Any]) -> str: | |
| try: | |
| out = subprocess.check_output(["ps", "aux"], text=True) | |
| return json.dumps({"stdout": out[-8000:]}) | |
| except Exception as e: | |
| return json.dumps({"error": str(e)}) | |
| def t_gpu_stats(_: Dict[str, Any]) -> str: | |
| nvsmi = shutil.which("nvidia-smi") | |
| if not nvsmi: | |
| return json.dumps({"error": "nvidia-smi not found"}) | |
| try: | |
| out = subprocess.check_output([nvsmi, "--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu", "--format=csv,noheader"], text=True) | |
| return json.dumps({"gpus": [line.strip() for line in out.strip().splitlines()]}) | |
| except Exception as e: | |
| return json.dumps({"error": str(e)}) | |
| def register_tools(reg: ToolRegistry) -> None: | |
| reg.register( | |
| name="shell_exec", | |
| description="Execute a shell command (unconstrained).", | |
| parameters={"type": "object", "properties": {"command": {"type": "string"}, "timeout": {"type": "integer"}}, "required": ["command"]}, | |
| handler=t_shell_exec, | |
| ) | |
| reg.register( | |
| name="process_list", | |
| description="List running processes (ps aux).", | |
| parameters={"type": "object", "properties": {}}, | |
| handler=t_process_list, | |
| ) | |
| reg.register( | |
| name="gpu_stats", | |
| description="Show GPU stats via nvidia-smi.", | |
| parameters={"type": "object", "properties": {}}, | |
| handler=t_gpu_stats, | |
| ) | |