Spaces:
Paused
Paused
Update backend/main.py
Browse files- backend/main.py +52 -15
backend/main.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os, json, asyncio, subprocess, uuid
|
| 2 |
-
from
|
|
|
|
| 3 |
from fastapi.responses import FileResponse, StreamingResponse
|
| 4 |
from pydantic import BaseModel
|
| 5 |
from typing import List, Optional, Dict, Any
|
|
@@ -22,10 +23,25 @@ def get_codebase_index():
|
|
| 22 |
raise HTTPException(status_code=503, detail="Codebase indexing unavailable – rebuild with updated sentence-transformers")
|
| 23 |
return CodebaseIndex
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
STATIC_DIR = "static"
|
| 30 |
|
| 31 |
# ---------- API Models ----------
|
|
@@ -62,6 +78,10 @@ class ReviewRequest(BaseModel):
|
|
| 62 |
pr_diff: str
|
| 63 |
project_path: str
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
# ---------- API Routes ----------
|
| 66 |
@app.get("/api/models")
|
| 67 |
async def get_models():
|
|
@@ -72,9 +92,18 @@ async def chat(req: ChatRequest):
|
|
| 72 |
context = ""
|
| 73 |
if req.context_files:
|
| 74 |
for f in req.context_files:
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
req.messages.insert(0, {"role": "system", "content": f"Relevant codebase context:\n{context}"})
|
| 79 |
async def event_stream():
|
| 80 |
try:
|
|
@@ -86,6 +115,21 @@ async def chat(req: ChatRequest):
|
|
| 86 |
yield "data: [DONE]\n\n"
|
| 87 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
@app.post("/api/agent/run")
|
| 90 |
async def run_agent(req: AgentTaskRequest, background_tasks: BackgroundTasks):
|
| 91 |
agent = CodingAgent(project_path=req.project_path, model=req.model)
|
|
@@ -117,7 +161,6 @@ async def index_project(req: IndexRequest):
|
|
| 117 |
@app.post("/api/search")
|
| 118 |
async def search_codebase(query: str, project_path: str = "/app/sandbox", top_k: int = 5):
|
| 119 |
if project_path not in indexers:
|
| 120 |
-
# Auto-build index if not present
|
| 121 |
CBI = get_codebase_index()
|
| 122 |
idx = CBI(project_path)
|
| 123 |
try:
|
|
@@ -156,7 +199,6 @@ async def git_operation(action: str, project_path: str, args: Optional[dict] = N
|
|
| 156 |
branches = [b.name for b in repo.branches]
|
| 157 |
return {"branches": branches}
|
| 158 |
elif action == "diff":
|
| 159 |
-
# Return the diff of unstaged changes, or HEAD if no changes
|
| 160 |
diff_output = repo.git.diff(repo.head.commit.tree) if repo.head.is_valid() else ""
|
| 161 |
return {"diff": diff_output}
|
| 162 |
else:
|
|
@@ -200,18 +242,13 @@ async def get_agent_status(task_id: str):
|
|
| 200 |
|
| 201 |
@app.get("/api/files")
|
| 202 |
async def list_files(project_path: str = "/app/sandbox"):
|
| 203 |
-
"""Return a tree of the project folder"""
|
| 204 |
def build_tree(path):
|
| 205 |
tree = []
|
| 206 |
for item in sorted(os.listdir(path)):
|
| 207 |
if item.startswith('.') or item == '__pycache__':
|
| 208 |
continue
|
| 209 |
full = os.path.join(path, item)
|
| 210 |
-
node = {
|
| 211 |
-
"name": item,
|
| 212 |
-
"path": full.replace(project_path, "").lstrip("/"),
|
| 213 |
-
"type": "folder" if os.path.isdir(full) else "file"
|
| 214 |
-
}
|
| 215 |
if os.path.isdir(full):
|
| 216 |
node["children"] = build_tree(full)
|
| 217 |
tree.append(node)
|
|
|
|
| 1 |
import os, json, asyncio, subprocess, uuid
|
| 2 |
+
from contextlib import asynccontextmanager
|
| 3 |
+
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, BackgroundTasks
|
| 4 |
from fastapi.responses import FileResponse, StreamingResponse
|
| 5 |
from pydantic import BaseModel
|
| 6 |
from typing import List, Optional, Dict, Any
|
|
|
|
| 23 |
raise HTTPException(status_code=503, detail="Codebase indexing unavailable – rebuild with updated sentence-transformers")
|
| 24 |
return CodebaseIndex
|
| 25 |
|
| 26 |
+
# Auto-index sandbox on startup
|
| 27 |
+
async def startup_index():
|
| 28 |
+
try:
|
| 29 |
+
from codebase_index import CodebaseIndex
|
| 30 |
+
idx = CodebaseIndex("/app/sandbox")
|
| 31 |
+
idx.build_index()
|
| 32 |
+
indexers["/app/sandbox"] = idx
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Startup indexing failed: {e}")
|
| 35 |
+
|
| 36 |
+
@asynccontextmanager
|
| 37 |
+
async def lifespan(app: FastAPI):
|
| 38 |
+
await startup_index()
|
| 39 |
+
yield
|
| 40 |
|
| 41 |
+
app = FastAPI(title="Codeki API", lifespan=lifespan)
|
| 42 |
+
|
| 43 |
+
indexers = {}
|
| 44 |
+
agents = {}
|
| 45 |
STATIC_DIR = "static"
|
| 46 |
|
| 47 |
# ---------- API Models ----------
|
|
|
|
| 78 |
pr_diff: str
|
| 79 |
project_path: str
|
| 80 |
|
| 81 |
+
class ApplyRequest(BaseModel):
|
| 82 |
+
task_id: str
|
| 83 |
+
approved_indices: List[int]
|
| 84 |
+
|
| 85 |
# ---------- API Routes ----------
|
| 86 |
@app.get("/api/models")
|
| 87 |
async def get_models():
|
|
|
|
| 92 |
context = ""
|
| 93 |
if req.context_files:
|
| 94 |
for f in req.context_files:
|
| 95 |
+
if f == "__git__":
|
| 96 |
+
import git
|
| 97 |
+
try:
|
| 98 |
+
repo = git.Repo(req.project_path)
|
| 99 |
+
diff = repo.git.diff(repo.head.commit.tree) if repo.head.is_valid() else ""
|
| 100 |
+
context += f"\n--- Git Diff ---\n{diff}\n"
|
| 101 |
+
except:
|
| 102 |
+
pass
|
| 103 |
+
else:
|
| 104 |
+
p = Path(req.project_path) / f
|
| 105 |
+
if p.exists():
|
| 106 |
+
context += f"\n--- {f} ---\n{p.read_text()}\n"
|
| 107 |
req.messages.insert(0, {"role": "system", "content": f"Relevant codebase context:\n{context}"})
|
| 108 |
async def event_stream():
|
| 109 |
try:
|
|
|
|
| 115 |
yield "data: [DONE]\n\n"
|
| 116 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
| 117 |
|
| 118 |
+
@app.post("/api/agent/plan")
|
| 119 |
+
async def agent_plan(req: AgentTaskRequest):
|
| 120 |
+
agent = CodingAgent(project_path=req.project_path, model=req.model)
|
| 121 |
+
changes = await agent.plan_task(req.prompt)
|
| 122 |
+
agents["default"] = agent
|
| 123 |
+
return {"changes": changes}
|
| 124 |
+
|
| 125 |
+
@app.post("/api/agent/apply")
|
| 126 |
+
async def agent_apply(req: ApplyRequest):
|
| 127 |
+
agent = agents.get(req.task_id)
|
| 128 |
+
if not agent:
|
| 129 |
+
raise HTTPException(404, "Agent not found")
|
| 130 |
+
await agent.apply_changes(req.approved_indices)
|
| 131 |
+
return {"status": agent.status, "logs": agent.logs}
|
| 132 |
+
|
| 133 |
@app.post("/api/agent/run")
|
| 134 |
async def run_agent(req: AgentTaskRequest, background_tasks: BackgroundTasks):
|
| 135 |
agent = CodingAgent(project_path=req.project_path, model=req.model)
|
|
|
|
| 161 |
@app.post("/api/search")
|
| 162 |
async def search_codebase(query: str, project_path: str = "/app/sandbox", top_k: int = 5):
|
| 163 |
if project_path not in indexers:
|
|
|
|
| 164 |
CBI = get_codebase_index()
|
| 165 |
idx = CBI(project_path)
|
| 166 |
try:
|
|
|
|
| 199 |
branches = [b.name for b in repo.branches]
|
| 200 |
return {"branches": branches}
|
| 201 |
elif action == "diff":
|
|
|
|
| 202 |
diff_output = repo.git.diff(repo.head.commit.tree) if repo.head.is_valid() else ""
|
| 203 |
return {"diff": diff_output}
|
| 204 |
else:
|
|
|
|
| 242 |
|
| 243 |
@app.get("/api/files")
|
| 244 |
async def list_files(project_path: str = "/app/sandbox"):
|
|
|
|
| 245 |
def build_tree(path):
|
| 246 |
tree = []
|
| 247 |
for item in sorted(os.listdir(path)):
|
| 248 |
if item.startswith('.') or item == '__pycache__':
|
| 249 |
continue
|
| 250 |
full = os.path.join(path, item)
|
| 251 |
+
node = {"name": item, "path": full.replace(project_path, "").lstrip("/"), "type": "folder" if os.path.isdir(full) else "file"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
if os.path.isdir(full):
|
| 253 |
node["children"] = build_tree(full)
|
| 254 |
tree.append(node)
|