-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
308 lines (265 loc) · 10.6 KB
/
Copy pathapi.py
File metadata and controls
308 lines (265 loc) · 10.6 KB
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
import os
import sys
import json
import uuid
import subprocess
from datetime import datetime
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from utils import (
load_all_sandboxes,
save_all_sandboxes,
get_sandbox_path,
init_or_get_repo,
revert_sandbox_to_commit,
DEFAULT_CONFIG,
CONFIG_PATH,
SANDBOXES_DIR
)
from agent import runAgent
# --- FastAPI App ---
app = FastAPI()
app.mount("/static", StaticFiles(directory=os.path.dirname(os.path.abspath(__file__))), name="static")
# --- Agent Endpoint ---
@app.post("/agent")
async def run_agent(request: Request):
data = await request.json()
return StreamingResponse(runAgent(data.get("sandbox_id")), media_type="text/plain")
# --- Static Files ---
@app.get("/")
async def serve_index():
try:
if hasattr(sys, '_MEIPASS'):
index_path = os.path.join(sys._MEIPASS, "index.html")
else:
index_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html")
with open(index_path, "rb") as f:
content = f.read()
return Response(content, media_type="text/html")
except Exception as e:
return Response(f"Error loading interface: {e}", status_code=500)
# --- Configuration Endpoints ---
@app.get("/config.json")
async def get_config():
if not os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, "w") as f:
json.dump(DEFAULT_CONFIG, f, indent=2)
return JSONResponse(content=DEFAULT_CONFIG)
with open(CONFIG_PATH, "r") as f:
return JSONResponse(content=json.load(f))
@app.post("/config.json")
async def set_config(request: Request):
data = await request.json()
with open(CONFIG_PATH, "w") as f:
json.dump(data, f, indent=2)
return {"status": "ok"}
# --- Sandbox CRUD Endpoints ---
@app.get("/sandboxes")
async def api_list_sandboxes():
convs = load_all_sandboxes()
return [{"id": cid, "title": c.get("title", f"Sandbox {cid}"), "read_only": c.get("read_only", False)} for cid, c in convs.items()]
@app.get("/sandboxes/{conv_id}")
async def api_get_sandbox(conv_id: str):
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Not found"})
return conv
@app.post("/sandboxes")
async def api_create_sandbox(request: Request):
data = await request.json()
conv_id = str(uuid.uuid4())
now = datetime.now().strftime("%Y-%m-%d %H:%M")
title = data.get("title") or f"{now}"
read_only = data.get("read_only", False)
messages = data.get("messages")
source_id = data.get("source_id")
if not isinstance(messages, list):
messages = []
# Handle file copying for forks
original_commits = []
if source_id:
convs = load_all_sandboxes()
if source_id in convs:
source_conv = convs[source_id]
original_commits = source_conv.get("commits", [])
source_path = get_sandbox_path(source_id)
if os.path.exists(source_path):
import shutil
target_path = os.path.join(SANDBOXES_DIR, conv_id)
try:
# Create target directory and copy files
# We copy everything including .git to preserve history
shutil.copytree(source_path, target_path, ignore=shutil.ignore_patterns('conversation.json', '__pycache__', '*.pyc'))
except Exception as e:
print(f"Error copying files during fork: {e}")
conv = {
"id": conv_id,
"title": title,
"read_only": read_only,
"messages": messages,
"commits": original_commits
}
convs = load_all_sandboxes()
convs[conv_id] = conv
save_all_sandboxes(convs)
sandbox_path = get_sandbox_path(conv_id)
init_or_get_repo(sandbox_path)
return conv
@app.post("/sandboxes/{conv_id}")
async def api_add_message(conv_id: str, request: Request):
data = await request.json()
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Not found"})
conv.setdefault("messages", []).append(data)
convs[conv_id] = conv
save_all_sandboxes(convs)
return {"status": "ok"}
@app.delete("/sandboxes/{conv_id}")
async def api_delete_sandbox(conv_id: str, delete_folder: bool = True):
convs = load_all_sandboxes()
if conv_id not in convs:
return JSONResponse(status_code=404, content={"error": "Not found"})
sandbox_path = get_sandbox_path(conv_id)
del convs[conv_id]
save_all_sandboxes(convs)
if delete_folder:
import shutil
if os.path.exists(sandbox_path):
shutil.rmtree(sandbox_path)
return {"status": "deleted", "folder_deleted": delete_folder}
@app.post("/sandboxes/{conv_id}/clean")
async def api_clean_conversation(conv_id: str):
"""Clean conversation messages but keep the sandbox and files intact."""
convs = load_all_sandboxes()
if conv_id not in convs:
return JSONResponse(status_code=404, content={"error": "Not found"})
conv = convs[conv_id]
# Clear messages and commits but keep everything else
conv["messages"] = []
conv["commits"] = []
convs[conv_id] = conv
save_all_sandboxes(convs)
return {"status": "cleaned", "conversation_id": conv_id}
@app.patch("/sandboxes/{conv_id}")
async def api_patch_sandbox(conv_id: str, request: Request):
data = await request.json()
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Not found"})
if "title" in data:
conv["title"] = data["title"]
if "read_only" in data:
conv["read_only"] = data["read_only"]
update_commit = False
if "messages" in data:
old_messages = conv.get("messages", [])
new_messages = data["messages"]
conv["messages"] = new_messages
if len(new_messages) < len(old_messages):
update_commit = True
convs[conv_id] = conv
save_all_sandboxes(convs)
if update_commit:
commits = conv.get("commits", [])
target_step = len(new_messages) - 1
target_commit = next((c for c in reversed(commits) if c["step"] == target_step), None)
if target_commit:
sandbox_path = get_sandbox_path(conv_id)
revert_sandbox_to_commit(sandbox_path, target_commit["hash"])
return {"status": "ok"}
# --- Git Endpoints ---
@app.get("/sandboxes/{conv_id}/commits")
async def api_get_sandbox_commits(conv_id: str):
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Sandbox not found"})
return {"commits": conv.get("commits", [])}
@app.post("/sandboxes/{conv_id}/revert")
async def api_revert_sandbox(conv_id: str, request: Request):
data = await request.json()
commit_hash = data.get("commit_hash")
step = data.get("step")
if not commit_hash and step is None:
return JSONResponse(status_code=400, content={"error": "Either commit_hash or step must be provided"})
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Sandbox not found"})
if step is not None and commit_hash is None:
commits = conv.get("commits", [])
target_commit = next((c for c in reversed(commits) if c["step"] == step), None)
if not target_commit:
return JSONResponse(status_code=404, content={"error": "Commit for step not found"})
commit_hash = target_commit["hash"]
sandbox_path = get_sandbox_path(conv_id)
if not os.path.exists(sandbox_path):
return JSONResponse(status_code=404, content={"error": "Sandbox folder not found"})
success = revert_sandbox_to_commit(sandbox_path, commit_hash)
if success:
if step is not None:
conv["messages"] = conv["messages"][:step+1]
convs[conv_id] = conv
save_all_sandboxes(convs)
return {"status": "reverted", "commit_hash": commit_hash}
else:
return JSONResponse(status_code=500, content={"error": "Failed to revert sandbox"})
# --- Utility Endpoints ---
@app.post("/sandboxes/{conv_id}/change_folder")
async def api_change_sandbox_folder(conv_id: str, request: Request):
data = await request.json()
new_path = data.get("path", "").strip()
if not new_path:
return JSONResponse(status_code=400, content={"error": "Path is required"})
if not os.path.exists(new_path):
try:
os.makedirs(new_path, exist_ok=True)
except Exception as e:
return JSONResponse(status_code=400, content={"error": f"Cannot create directory: {str(e)}"})
if not os.path.isdir(new_path):
return JSONResponse(status_code=400, content={"error": "Path must be a directory"})
convs = load_all_sandboxes()
conv = convs.get(conv_id)
if conv is None:
return JSONResponse(status_code=404, content={"error": "Sandbox not found"})
old_path = get_sandbox_path(conv_id)
if old_path != new_path and os.path.exists(old_path) and os.listdir(old_path):
copy_files = data.get("copy_files", True)
if copy_files:
import shutil
try:
for item in os.listdir(old_path):
s = os.path.join(old_path, item)
d = os.path.join(new_path, item)
if os.path.isdir(s):
if os.path.exists(d): shutil.rmtree(d)
shutil.copytree(s, d)
else:
shutil.copy2(s, d)
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"Failed to copy files: {str(e)}"})
conv["custom_path"] = new_path
convs[conv_id] = conv
save_all_sandboxes(convs)
init_or_get_repo(new_path)
return {"status": "ok", "new_path": new_path}
@app.post("/open_sandbox_folder/{sandbox_id}")
async def open_sandbox_folder(sandbox_id: str):
sandbox_path = get_sandbox_path(sandbox_id)
if not os.path.exists(sandbox_path):
os.makedirs(sandbox_path)
try:
if sys.platform.startswith("darwin"):
subprocess.Popen(["open", sandbox_path])
elif sys.platform.startswith("win"):
os.startfile(sandbox_path)
else:
subprocess.Popen(["xdg-open", sandbox_path])
return {"status": "ok"}
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})