File size: 3,625 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""
id: shell
title: Persistent Shell (unsafe)
author: admin
description: Stateful shell with persistent cwd/env; run commands without writing scripts.
version: 0.1.0
license: Proprietary
"""

import os
import subprocess
from typing import Optional, Dict


class Tools:
    def __init__(self):
        # Default cwd to /data/adaptai if present (quality of life)
        try:
            import os

            if os.path.isdir("/data/adaptai"):
                self.cwd = "/data/adaptai"
        except Exception:
            pass
        # Persist across calls (module instance cached by Open WebUI)
        self.cwd: Optional[str] = None
        self.env: Dict[str, str] = {}

    def set_cwd(self, path: str) -> dict:
        """Set working directory for subsequent runs."""
        if not os.path.isdir(path):
            return {"ok": False, "error": f"Not a directory: {path}"}
        self.cwd = path
        return {"ok": True, "cwd": self.cwd}

    def set_env(self, key: str, value: str) -> dict:
        """Set/override an environment variable for subsequent runs."""
        self.env[key] = value
        return {"ok": True, "env": {key: value}}

    def get_state(self) -> dict:
        """Return current cwd and env overrides."""
        return {"cwd": self.cwd, "env": self.env}

    def run(self, cmd: str, timeout: int = 600) -> dict:
        """
        Run a shell command using bash -lc with persistent cwd and env.
        :param cmd: Command string (supports pipes, &&, heredocs).
        :param timeout: Seconds before kill (default 10min).
        :return: {stdout, stderr, exit_code, cwd}
        """
        env = os.environ.copy()
        env.update(
            {
                k: v
                for k, v in self.env.items()
                if isinstance(k, str) and isinstance(v, str)
            }
        )
        try:
            p = subprocess.run(
                ["bash", "-lc", cmd],
                capture_output=True,
                text=True,
                cwd=self.cwd or None,
                env=env,
                timeout=timeout,
            )
            return {
                "stdout": p.stdout,
                "stderr": p.stderr,
                "exit_code": p.returncode,
                "cwd": self.cwd,
            }
        except subprocess.TimeoutExpired as e:
            return {
                "stdout": e.stdout or "",
                "stderr": (e.stderr or "") + "\n[timeout]",
                "exit_code": 124,
                "cwd": self.cwd,
            }
        except Exception as e:
            return {"stdout": "", "stderr": str(e), "exit_code": 1, "cwd": self.cwd}

    def pwd(self) -> dict:
        """Return current working directory (resolved)."""
        return {"cwd": os.path.realpath(self.cwd or os.getcwd())}

    def set_state(self, cwd: str = "", env_json: str = "") -> dict:
        """Set cwd and bulk env via JSON string (optional)."""
        import json
        import os

        out = {"ok": True}
        if cwd:
            if not os.path.isdir(cwd):
                return {"ok": False, "error": f"Not a directory: {cwd}"}
            self.cwd = cwd
            out["cwd"] = self.cwd
        if env_json:
            try:
                data = json.loads(env_json)
                if isinstance(data, dict):
                    for k, v in data.items():
                        if isinstance(k, str) and isinstance(v, str):
                            self.env[k] = v
                    out["env"] = self.env
            except Exception as e:
                return {"ok": False, "error": str(e)}
        return out