""" 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