import gradio as gr import spaces import subprocess import shlex import os import sys import time import threading import json print(">>> app.py loading", file=sys.stderr) sys.stderr.flush() SAFE_COMMANDS = "*" ALLOWLIST = {} GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "") LINKED_REPO_OWNER = os.environ.get("LINKED_REPO_OWNER", "") LINKED_REPO_NAME = os.environ.get("LINKED_REPO_NAME", "") LINKED_REPO_URL = os.environ.get("LINKED_REPO_URL", "") REPO_ROOT = "/home/user/repos" SYNC_INTERVAL = 30 _repo_mtimes: dict[str, float] = {} _repo_lock = threading.Lock() def repo_path(owner: str, repo: str) -> str: return os.path.join(REPO_ROOT, f"{owner}_{repo}") def set_git_config(repo_dir: str): subprocess.run(["git", "config", "user.email", "codexa-agent@users.noreply.github.com"], cwd=repo_dir, capture_output=True) subprocess.run(["git", "config", "user.name", "Codexa Agent"], cwd=repo_dir, capture_output=True) subprocess.run(["git", "config", "credential.helper", ""], cwd=repo_dir, capture_output=True) def init_repo(owner: str, repo: str, remote_url: str = "", user_token: str = "") -> str: path = repo_path(owner, repo) os.makedirs(path, exist_ok=True) if remote_url: pass elif LINKED_REPO_URL: remote_url = LINKED_REPO_URL else: remote_url = f"https://github.com/{owner}/{repo}.git" token = user_token or GITHUB_TOKEN if token and "github.com" in remote_url: remote_url = remote_url.replace("https://", f"https://{token}@") elif GITHUB_TOKEN and "github.com" in remote_url and not user_token: remote_url = remote_url.replace("https://", f"https://{GITHUB_TOKEN}@") if not os.path.exists(os.path.join(path, ".git")): result = subprocess.run( ["git", "clone", remote_url, path], capture_output=True, text=True, timeout=120, cwd=path ) if result.returncode != 0: subprocess.run(["git", "init", "-b", "main"], cwd=path, capture_output=True) subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=path, capture_output=True) subprocess.run(["git", "add", "."], cwd=path, capture_output=True) subprocess.run(["git", "commit", "-m", "init"], cwd=path, capture_output=True) set_git_config(path) return path def is_allowed(args): if SAFE_COMMANDS == "*": return True base = args[0] if args else "" if base in ALLOWLIST: return args == ALLOWLIST[base] return base in SAFE_COMMANDS def _try_sync_repo(owner: str, repo: str, user_token: str = ""): path = repo_path(owner, repo) if not os.path.isdir(path) or not os.path.exists(os.path.join(path, ".git")): print(f">>> _try_sync_repo skip: no repo at {path}", file=sys.stderr) sys.stderr.flush() return try: branch = subprocess.run(["git", "branch", "--show-current"], cwd=path, capture_output=True, text=True).stdout.strip() or "main" print(f">>> _try_sync_repo pull {owner}/{repo} branch={branch}", file=sys.stderr) sys.stderr.flush() pull = subprocess.run(["git", "pull", "--rebase", "origin", branch], cwd=path, capture_output=True, text=True, timeout=30) if pull.returncode != 0: print(f">>> _try_sync_repo pull failed: rc={pull.returncode} {pull.stderr.strip()}", file=sys.stderr) sys.stderr.flush() status = subprocess.run(["git", "status", "--short", "--branch"], cwd=path, capture_output=True, text=True).stdout.strip() print(f">>> _try_sync_repo status: {status!r}", file=sys.stderr) sys.stderr.flush() if status: add = subprocess.run(["git", "add", "-A"], cwd=path, capture_output=True, text=True) if add.returncode != 0: print(f">>> _try_sync_repo add failed: {add.stderr.strip()}", file=sys.stderr) commit = subprocess.run(["git", "commit", "-m", "codexa: auto-sync"], cwd=path, capture_output=True, text=True) if commit.returncode != 0: print(f">>> _try_sync_repo commit failed: rc={commit.returncode} {commit.stderr.strip()}", file=sys.stderr) sys.stderr.flush() else: print(f">>> _try_sync_repo committed: {commit.stdout.strip()}", file=sys.stderr) sys.stderr.flush() token = user_token or os.environ.get("GITHUB_TOKEN", "") if token: remote_url = subprocess.run(["git", "remote", "get-url", "origin"], cwd=path, capture_output=True, text=True).stdout.strip() if "github.com" in remote_url: if remote_url.startswith("git@"): remote_url = "https://github.com/" + remote_url.split(":", 1)[1] auth_url = remote_url.replace("https://", f"https://{token}@", 1) subprocess.run(["git", "remote", "set-url", "origin", auth_url], cwd=path, capture_output=True) print(f">>> _try_sync_repo set-url {auth_url.split('@')[1]}", file=sys.stderr) sys.stderr.flush() elif token: print(f">>> _try_sync_repo skip set-url, non-github remote: {remote_url!r}", file=sys.stderr) sys.stderr.flush() elif not token and "github.com" in (subprocess.run(["git", "remote", "get-url", "origin"], cwd=path, capture_output=True, text=True).stdout.strip() or ""): print(">>> _try_sync_repo WARNING: pushing to github.com without a token", file=sys.stderr) sys.stderr.flush() push = subprocess.run(["git", "push", "origin", f"HEAD:{branch}"], cwd=path, capture_output=True, text=True, timeout=30) if push.returncode != 0: print(f">>> _try_sync_repo push failed: rc={push.returncode} {push.stderr.strip()}", file=sys.stderr) sys.stderr.flush() else: print(f">>> _try_sync_repo pushed to {branch}", file=sys.stderr) sys.stderr.flush() except Exception as e: print(f">>> _try_sync_repo exception: {e}", file=sys.stderr) sys.stderr.flush() def _ensure_auth_remote(path: str, user_token: str): token = user_token or GITHUB_TOKEN if not token: return try: remote_url = subprocess.run(["git", "remote", "get-url", "origin"], cwd=path, capture_output=True, text=True).stdout.strip() if "github.com" in remote_url: if remote_url.startswith("git@"): remote_url = "https://github.com/" + remote_url.split(":", 1)[1] auth_url = remote_url.replace("https://", f"https://{token}@", 1) subprocess.run(["git", "remote", "set-url", "origin", auth_url], cwd=path, capture_output=True) except Exception: pass def spawn(command: str, owner: str = "", repo: str = "", user_token: str = ""): try: parsed = json.loads(command) if isinstance(parsed, dict): command = parsed.get("command", "") owner = parsed.get("owner", "") repo = parsed.get("repo", "") user_token = parsed.get("user_token", parsed.get("github_token", "")) except Exception: pass if not command: return "" try: args = shlex.split(command) except Exception: return f"Error: invalid command: {command}\n" if not is_allowed(args): return f"Error: command '{args[0]}' not allowed in demo container\n" print(f">>> spawn cmd={command!r} owner={owner!r} repo={repo!r} token={bool(user_token)}", file=sys.stderr) sys.stderr.flush() cwd = os.environ.get("SPACE_ROOT", "/home/user") repo_dir = "" if owner and repo: rpath = repo_path(owner, repo) if not os.path.exists(rpath): init_repo(owner, repo, "", user_token) if user_token: _ensure_auth_remote(rpath, user_token) repo_dir = rpath cwd = repo_dir try: result = subprocess.run( ['sh', '-lc', command], capture_output=True, text=True, timeout=10, cwd=cwd, ) output = (result.stdout + result.stderr).strip() or "(no output)" if owner and repo: threading.Thread(target=_try_sync_repo, args=(owner, repo, user_token), daemon=True).start() return output except subprocess.TimeoutExpired: return "Error: command timed out\n" except Exception as e: return f"Error: {e}\n" def link_repo(owner: str, repo: str, remote_url: str = ""): path = init_repo(owner, repo, remote_url) with _repo_lock: _repo_mtimes[path] = 0 return f"Linked {owner}/{repo} -> {path}" def sync_status(owner: str, repo: str): path = repo_path(owner, repo) if not os.path.exists(path) or not os.path.exists(os.path.join(path, ".git")): return "Not initialized" result = subprocess.run(["git", "status", "--short", "--branch"], cwd=path, capture_output=True, text=True) return result.stdout or "Clean, up to date" def _recent_mtime(path: str) -> float: latest = 0.0 for root, dirs, files in os.walk(path): dirs[:] = [d for d in dirs if d != ".git"] for f in files: try: m = os.path.getmtime(os.path.join(root, f)) if m > latest: latest = m except OSError: pass return latest def background_sync(): while True: time.sleep(SYNC_INTERVAL) if not os.path.isdir(REPO_ROOT): continue for name in os.listdir(REPO_ROOT): path = os.path.join(REPO_ROOT, name) if not os.path.isdir(path) or not os.path.exists(os.path.join(path, ".git")): continue try: subprocess.run(["git", "pull", "--rebase", "origin", "main"], cwd=path, capture_output=True, text=True, timeout=30) mtime = _recent_mtime(path) with _repo_lock: prev = _repo_mtimes.get(path, 0) _repo_mtimes[path] = mtime if mtime > prev: subprocess.run(["git", "add", "-A"], cwd=path, capture_output=True) subprocess.run(["git", "commit", "-m", "codexa: auto-sync"], cwd=path, capture_output=True) subprocess.run(["git", "push", "origin", "HEAD"], cwd=path, capture_output=True, text=True, timeout=30) except Exception: pass @spaces.GPU def _gpu_marker(): return "ok" if LINKED_REPO_OWNER and LINKED_REPO_NAME: init_repo(LINKED_REPO_OWNER, LINKED_REPO_NAME) if GITHUB_TOKEN: t = threading.Thread(target=background_sync, daemon=True) t.start() print(">>> building demo", file=sys.stderr) sys.stderr.flush() demo = gr.Interface( fn=spawn, inputs=gr.Textbox(label="command", lines=1), outputs=gr.Textbox(label="output", lines=10), api_name="exec_ctx", ) demo.queue() if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)