File size: 2,148 Bytes
93be2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
    )