File size: 12,065 Bytes
e85db04
9f88063
 
e85db04
 
 
 
 
 
 
9f88063
e85db04
 
9f88063
e85db04
 
 
 
 
 
 
 
9f88063
e85db04
9f88063
 
e85db04
 
9f88063
 
e85db04
9f88063
 
e85db04
 
9f88063
 
e85db04
9f88063
 
e85db04
 
9f88063
e85db04
 
 
9f88063
 
 
e85db04
9f88063
 
e85db04
9f88063
 
 
e85db04
9f88063
 
 
 
 
 
 
 
 
e85db04
 
 
 
 
 
 
9f88063
 
 
e85db04
9f88063
 
 
 
e85db04
 
 
 
 
 
 
 
 
9f88063
e85db04
9f88063
e85db04
 
9f88063
 
e85db04
 
9f88063
 
 
 
 
 
 
 
 
 
 
 
 
 
e85db04
 
 
 
9f88063
 
 
 
 
 
 
 
 
 
 
 
e85db04
 
 
 
9f88063
 
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
 
e85db04
 
9f88063
e85db04
9f88063
 
 
 
 
 
e85db04
 
 
9f88063
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85db04
 
9f88063
e85db04
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
e85db04
9f88063
 
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
e85db04
 
9f88063
 
 
 
 
 
 
 
 
e85db04
 
9f88063
e85db04
9f88063
 
 
 
 
 
e85db04
9f88063
 
 
 
 
 
 
 
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
Execution API Routes β€” Terminal, FileSystem, GitHub, DAG
Real agent execution endpoints
"""

import asyncio
import json
import os
import time
import uuid
from typing import Dict, List, Optional

import structlog
from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect
from pydantic import BaseModel

log = structlog.get_logger()
router = APIRouter()

WORKSPACE = os.environ.get("WORKSPACE_DIR", "/tmp/god_workspace")


# ─── Request Models ───────────────────────────────────────────────────────────

class ExecRequest(BaseModel):
    command: str
    session_id: str = ""
    task_id: str = ""
    cwd: str = ""
    timeout: int = 120

class ExecChainRequest(BaseModel):
    commands: List[str]
    session_id: str = ""
    task_id: str = ""
    cwd: str = ""
    stop_on_error: bool = True

class FileReadRequest(BaseModel):
    filename: str

class FileWriteRequest(BaseModel):
    filename: str
    content: str

class FilePatchRequest(BaseModel):
    filename: str
    old_str: str
    new_str: str

class FileDeleteRequest(BaseModel):
    filename: str

class FileMoveRequest(BaseModel):
    src: str
    dst: str

class FileSearchRequest(BaseModel):
    query: str
    path: str = ""
    pattern: str = "*"

class GitHubCloneRequest(BaseModel):
    repo_url: str
    dest: str = ""
    branch: str = ""

class GitHubCreateRepoRequest(BaseModel):
    name: str
    description: str = ""
    private: bool = False

class GitHubCommitRequest(BaseModel):
    message: str
    cwd: str = ""
    files: Optional[List[str]] = None

class GitHubPushRequest(BaseModel):
    branch: str = ""
    cwd: str = ""
    force: bool = False

class GitHubPRRequest(BaseModel):
    owner: str
    repo: str
    title: str
    body: str = ""
    head: str = "main"
    base: str = "main"

class DAGCreateRequest(BaseModel):
    goal: str
    steps: List[Dict]
    session_id: str = ""

class FilesWriteRequest(BaseModel):
    files: List[Dict]


# ─── Terminal Routes ──────────────────────────────────────────────────────────

@router.post("/execute")
async def execute_command(req: ExecRequest, request: Request):
    """Execute a shell command in the sandbox."""
    terminal = getattr(request.app.state, "terminal_engine", None)
    if not terminal:
        return {"success": False, "error": "Terminal engine not available"}
    result = await terminal.execute(
        req.command,
        session_id=req.session_id,
        task_id=req.task_id,
        cwd=req.cwd or WORKSPACE,
        timeout=req.timeout,
    )
    return result


@router.post("/execute/chain")
async def execute_chain(req: ExecChainRequest, request: Request):
    """Execute a chain of shell commands."""
    terminal = getattr(request.app.state, "terminal_engine", None)
    if not terminal:
        return {"success": False, "error": "Terminal engine not available"}
    result = await terminal.execute_chain(
        req.commands,
        session_id=req.session_id,
        task_id=req.task_id,
        cwd=req.cwd or WORKSPACE,
        stop_on_error=req.stop_on_error,
    )
    return result


@router.post("/execute/kill/{session_id}")
async def kill_process(session_id: str, request: Request):
    """Kill a running process."""
    terminal = getattr(request.app.state, "terminal_engine", None)
    if not terminal:
        return {"success": False, "error": "Terminal engine not available"}
    return await terminal.kill(session_id)


@router.get("/execute/history/{session_id}")
async def get_history(session_id: str, request: Request):
    """Get command history for a session."""
    terminal = getattr(request.app.state, "terminal_engine", None)
    if not terminal:
        return {"history": []}
    return {"history": terminal.get_session_history(session_id)}


# ─── FileSystem Routes ────────────────────────────────────────────────────────

@router.post("/fs/read")
async def read_file(req: FileReadRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.read_file(req.filename)


@router.post("/fs/write")
async def write_file(req: FileWriteRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.write_file(req.filename, req.content)


@router.post("/fs/write-many")
async def write_files(req: FilesWriteRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.write_files(req.files)


@router.post("/fs/patch")
async def patch_file(req: FilePatchRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.patch_file(req.filename, req.old_str, req.new_str)


@router.post("/fs/delete")
async def delete_file(req: FileDeleteRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.delete_file(req.filename)


@router.post("/fs/move")
async def move_file(req: FileMoveRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.move_file(req.src, req.dst)


@router.post("/fs/search")
async def search_files(req: FileSearchRequest, request: Request):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.search_files(req.query, req.path, req.pattern)


@router.get("/fs/tree")
async def get_tree(path: str = "", request: Request = None):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.tree(path)


@router.get("/fs/list")
async def list_dir(path: str = "", request: Request = None):
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"success": False, "error": "FileSystem tool not available"}
    return await fs.list_dir(path)


@router.get("/workspace")
async def get_workspace_info(request: Request):
    """Get workspace info and file tree."""
    fs = getattr(request.app.state, "fs_tool", None)
    if not fs:
        return {"path": WORKSPACE, "files": [], "file_count": 0}
    tree = await fs.tree()
    files_list = []
    for root, dirs, files in os.walk(WORKSPACE):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("node_modules", "__pycache__")]
        for f in files:
            files_list.append(os.path.relpath(os.path.join(root, f), WORKSPACE))
        if len(files_list) > 200:
            break
    return {
        "path": WORKSPACE,
        "file_count": len(files_list),
        "files": files_list[:100],
        "tree": tree.get("tree", ""),
    }


# ─── GitHub Routes ────────────────────────────────────────────────────────────

@router.post("/github/clone")
async def github_clone(req: GitHubCloneRequest, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.clone_repo(req.repo_url, req.dest, req.branch)


@router.post("/github/create-repo")
async def github_create_repo(req: GitHubCreateRepoRequest, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.create_repo(req.name, req.description, req.private)


@router.post("/github/commit")
async def github_commit(req: GitHubCommitRequest, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.commit_changes(req.message, req.cwd or WORKSPACE, req.files)


@router.post("/github/push")
async def github_push(req: GitHubPushRequest, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.push_changes(req.branch, req.cwd or WORKSPACE, req.force)


@router.post("/github/pr")
async def github_open_pr(req: GitHubPRRequest, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.open_pr(req.owner, req.repo, req.title, req.body, req.head, req.base)


@router.get("/github/status")
async def github_status(cwd: str = "", request: Request = None):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.status(cwd or WORKSPACE)


@router.get("/github/issues/{owner}/{repo}")
async def github_issues(owner: str, repo: str, request: Request):
    gh = getattr(request.app.state, "github_tool", None)
    if not gh:
        return {"success": False, "error": "GitHub tool not available"}
    return await gh.read_issues(owner, repo)


# ─── DAG Routes ───────────────────────────────────────────────────────────────

@router.post("/dag/create")
async def create_dag(req: DAGCreateRequest, request: Request):
    dag_engine = getattr(request.app.state, "dag_engine", None)
    if not dag_engine:
        return {"success": False, "error": "DAG engine not available"}
    dag = dag_engine.build_from_steps(req.steps, req.goal)
    return {"success": True, "dag_id": dag.id, "dag": dag.to_dict()}


@router.get("/dag/list")
async def list_dags(request: Request):
    dag_engine = getattr(request.app.state, "dag_engine", None)
    if not dag_engine:
        return {"dags": []}
    return {"dags": dag_engine.get_all_dags()}


@router.get("/dag/{dag_id}")
async def get_dag(dag_id: str, request: Request):
    dag_engine = getattr(request.app.state, "dag_engine", None)
    if not dag_engine:
        return {"success": False, "error": "DAG engine not available"}
    dag = dag_engine.get_dag(dag_id)
    if not dag:
        raise HTTPException(status_code=404, detail="DAG not found")
    return dag.to_dict()


# ─── Self-Repair Route ────────────────────────────────────────────────────────

class SelfRepairRequest(BaseModel):
    command: str
    error_output: str
    session_id: str = ""
    task_id: str = ""
    max_attempts: int = 3

@router.post("/self-repair")
async def self_repair(req: SelfRepairRequest, request: Request):
    terminal = getattr(request.app.state, "terminal_engine", None)
    ai_router = getattr(request.app.state, "ai_router", None)
    if not terminal:
        return {"success": False, "error": "Terminal engine not available"}
    return await terminal.self_repair(
        req.command,
        req.error_output,
        ai_router=ai_router,
        session_id=req.session_id,
        task_id=req.task_id,
        max_attempts=req.max_attempts,
    )