# Terminal Tool

Install via Admin UI → Tools → "+" → paste code → save.

```python
"""
Terminal — execute shell commands on the server.

WARNING: This tool runs commands directly on the host. Only enable for trusted users.
"""

import subprocess
from typing import Optional


async def run_command(
    command: str,
    timeout: Optional[int] = 30,
    workdir: Optional[str] = "/tmp",
) -> str:
    """
    Execute a shell command on the server and return its output.

    Use for file operations, git commands, package management,
    system admin, running scripts, or any shell task.

    Args:
        command: The shell command to execute
        timeout: Max execution time in seconds (default: 30, max: 120)
        workdir: Working directory (default: /tmp)

    Returns:
        Command output (stdout + stderr combined)
    """
    timeout = min(timeout or 30, 120)
    cwd = workdir or "/tmp"

    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=cwd,
        )
        output = result.stdout
        if result.stderr:
            if output:
                output += "\n"
            output += result.stderr
        if result.returncode != 0:
            output += f"\n--- exit code: {result.returncode} ---"
        return output.strip() or f"(empty — exit code {result.returncode})"

    except subprocess.TimeoutExpired:
        return f"Error: command timed out after {timeout}s"
    except FileNotFoundError:
        return f"Error: working directory not found: {cwd}"
    except PermissionError:
        return f"Error: permission denied in {cwd}"
    except Exception as e:
        return f"Error: {e}"
```
