File size: 11,155 Bytes
cb62d6b
23101ef
78ad01c
 
 
b1258b3
35a4549
 
17dc889
b1258b3
 
 
78ad01c
1c99e6b
 
78ad01c
35a4549
 
 
 
 
 
 
 
78ad01c
35a4549
 
 
 
 
 
 
 
21c3b73
35a4549
 
21c3b73
35a4549
 
 
 
 
 
 
 
 
 
21c3b73
 
 
 
 
35a4549
 
 
21c3b73
35a4549
 
 
 
21c3b73
35a4549
 
 
 
 
23101ef
 
cb62d6b
1c99e6b
 
78ad01c
 
 
 
 
 
575fa6f
b48db23
 
97db5ca
 
b48db23
 
 
97db5ca
 
 
 
 
 
 
 
 
b48db23
97db5ca
 
 
 
 
 
 
 
 
 
575fa6f
 
 
21c3b73
 
 
 
 
 
 
 
 
 
 
 
 
97db5ca
 
 
 
 
 
 
 
 
 
b48db23
 
21c3b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575fa6f
17dc889
 
 
 
 
 
575fa6f
17dc889
 
 
78ad01c
cb62d6b
78ad01c
 
 
cb62d6b
78ad01c
 
cb62d6b
78ad01c
21c3b73
 
 
35a4549
b48db23
35a4549
 
 
21c3b73
 
 
b48db23
 
78ad01c
 
35a4549
78ad01c
 
 
35a4549
78ad01c
b48db23
 
575fa6f
b48db23
78ad01c
cb62d6b
78ad01c
cb62d6b
 
 
35a4549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1258b3
 
 
cb62d6b
 
 
 
35a4549
cb62d6b
b1258b3
 
f86947c
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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)