Skydata001 commited on
Commit
aacc530
·
1 Parent(s): 4891b1c

Rename app.py to main.py

Browse files
Files changed (2) hide show
  1. app.py +0 -788
  2. main.py +83 -0
app.py DELETED
@@ -1,788 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- import difflib
5
- import hashlib
6
- import hmac
7
- import json
8
- import os
9
- import re
10
- import shlex
11
- import signal
12
- import subprocess
13
- import time
14
- import uuid
15
- from pathlib import Path
16
- from typing import Any, Literal
17
-
18
- import httpx
19
- from fastapi import FastAPI, File, HTTPException, Request, UploadFile, WebSocket, WebSocketDisconnect
20
- from fastapi.responses import FileResponse, JSONResponse
21
- from fastapi.staticfiles import StaticFiles
22
- from pydantic import BaseModel, Field
23
-
24
- APP_DIR = Path(__file__).resolve().parent
25
- WORKSPACE = Path(os.getenv("WORKSPACE_DIR", str(APP_DIR / "workspace"))).expanduser().resolve()
26
- WORKSPACE.mkdir(parents=True, exist_ok=True)
27
-
28
- def env_text(name: str, default: str = "") -> str:
29
- value = os.getenv(name)
30
- return default if value is None or not value.strip() else value.strip()
31
-
32
-
33
- def env_int(name: str, default: int) -> int:
34
- value = os.getenv(name)
35
- if value is None or not value.strip():
36
- return default
37
- try:
38
- return int(value.strip())
39
- except ValueError:
40
- return default
41
-
42
-
43
- def env_float(name: str, default: float) -> float:
44
- value = os.getenv(name)
45
- if value is None or not value.strip():
46
- return default
47
- try:
48
- return float(value.strip())
49
- except ValueError:
50
- return default
51
-
52
-
53
- LLM_BASE_URL = env_text("LLM_BASE_URL", "https://top-tools-ai.com/api/v1").rstrip("/")
54
- LLM_API_KEY = env_text("LLM_API_KEY")
55
- LLM_MODEL = env_text("LLM_MODEL", "Kimi-K2.7-Code")
56
- LLM_TEMPERATURE = env_float("LLM_TEMPERATURE", 0.2)
57
- LLM_MAX_TOKENS = env_int("LLM_MAX_TOKENS", 12000)
58
- MAX_AGENT_TURNS = env_int("MAX_AGENT_TURNS", 12)
59
- TERMINAL_ENABLED = env_text("TERMINAL_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
60
- COMMAND_TIMEOUT = env_int("COMMAND_TIMEOUT", 30)
61
- MAX_UPLOAD_MB = env_int("MAX_UPLOAD_MB", 25)
62
- MAX_FILE_BYTES = env_int("MAX_FILE_BYTES", 1000000)
63
- APP_ACCESS_TOKEN = env_text("APP_ACCESS_TOKEN")
64
-
65
- DENIED_COMMAND_PATTERNS = [
66
- r"(^|\s)shutdown(\s|$)",
67
- r"(^|\s)reboot(\s|$)",
68
- r"(^|\s)poweroff(\s|$)",
69
- r"(^|\s)mkfs(\s|$)",
70
- r"(^|\s)mount(\s|$)",
71
- r"(^|\s)umount(\s|$)",
72
- r"(^|\s)iptables(\s|$)",
73
- r"(^|\s)useradd(\s|$)",
74
- r"(^|\s)passwd(\s|$)",
75
- r"(^|\s)chmod\s+-R\s+777(\s|$)",
76
- r"(^|\s)dd\s+if=",
77
- r">\s*/dev/",
78
- ]
79
-
80
- app = FastAPI(title="AgentSpace Code", version="1.0.0")
81
-
82
- sessions: dict[str, dict[str, Any]] = {}
83
-
84
-
85
- def auth_ok(token: str | None) -> bool:
86
- if not APP_ACCESS_TOKEN:
87
- return True
88
- if not token:
89
- return False
90
- return hmac.compare_digest(token, APP_ACCESS_TOKEN)
91
-
92
-
93
- def clean_rel_path(value: str) -> Path:
94
- value = value.replace("\\", "/").strip()
95
- if not value or value.startswith("/") or "\x00" in value:
96
- raise HTTPException(400, "Invalid relative path")
97
- p = Path(value)
98
- if any(part in {"", ".", ".."} for part in p.parts):
99
- raise HTTPException(400, "Path traversal is not allowed")
100
- target = (WORKSPACE / p).resolve()
101
- if target != WORKSPACE and WORKSPACE not in target.parents:
102
- raise HTTPException(400, "Path outside workspace")
103
- return p
104
-
105
-
106
- def abs_path(rel: str) -> Path:
107
- return (WORKSPACE / clean_rel_path(rel)).resolve()
108
-
109
-
110
- def is_text_file(path: Path) -> bool:
111
- try:
112
- data = path.read_bytes()[:8192]
113
- except Exception:
114
- return False
115
- if b"\x00" in data:
116
- return False
117
- return True
118
-
119
-
120
- def tree() -> list[dict[str, Any]]:
121
- output: list[dict[str, Any]] = []
122
- for path in sorted(WORKSPACE.rglob("*"), key=lambda p: (len(p.parts), str(p).lower())):
123
- if any(part in {".git", ".agent_state", "node_modules", "__pycache__"} for part in path.parts):
124
- continue
125
- rel = path.relative_to(WORKSPACE).as_posix()
126
- output.append({"path": rel, "type": "dir" if path.is_dir() else "file", "size": path.stat().st_size if path.is_file() else None})
127
- return output
128
-
129
-
130
- def list_files_compact(max_items: int = 250) -> list[str]:
131
- items = []
132
- for x in tree():
133
- if x["type"] == "file":
134
- items.append(x["path"])
135
- if len(items) >= max_items:
136
- break
137
- return items
138
-
139
-
140
- def sha(path: Path) -> str:
141
- h = hashlib.sha256()
142
- with path.open("rb") as f:
143
- for chunk in iter(lambda: f.read(65536), b""):
144
- h.update(chunk)
145
- return h.hexdigest()
146
-
147
-
148
- def snapshot() -> dict[str, str]:
149
- out: dict[str, str] = {}
150
- for item in tree():
151
- if item["type"] == "file":
152
- p = WORKSPACE / item["path"]
153
- try:
154
- out[item["path"]] = sha(p)
155
- except Exception:
156
- pass
157
- return out
158
-
159
-
160
- def diff_snapshot(before: dict[str, str]) -> tuple[list[str], list[str], list[str]]:
161
- after = snapshot()
162
- changed = sorted(k for k in set(before) & set(after) if before[k] != after[k])
163
- created = sorted(k for k in set(after) - set(before))
164
- deleted = sorted(k for k in set(before) - set(after))
165
- return changed, created, deleted
166
-
167
-
168
- class LLMClient:
169
- async def chat(self, messages: list[dict[str, Any]], *, temperature: float | None = None, max_tokens: int | None = None) -> str:
170
- if not LLM_API_KEY:
171
- raise RuntimeError("LLM_API_KEY is not configured")
172
- payload = {
173
- "model": LLM_MODEL,
174
- "messages": messages,
175
- "temperature": LLM_TEMPERATURE if temperature is None else temperature,
176
- "max_tokens": LLM_MAX_TOKENS if max_tokens is None else max_tokens,
177
- }
178
- async with httpx.AsyncClient(timeout=120) as client:
179
- r = await client.post(
180
- f"{LLM_BASE_URL}/chat/completions",
181
- headers={"Authorization": f"Bearer {LLM_API_KEY}", "Content-Type": "application/json"},
182
- json=payload,
183
- )
184
- if r.status_code >= 400:
185
- raise RuntimeError(f"LLM gateway HTTP {r.status_code}: {r.text[:800]}")
186
- data = r.json()
187
- try:
188
- return data["choices"][0]["message"]["content"] or ""
189
- except Exception as exc:
190
- raise RuntimeError(f"Unexpected LLM response: {exc}; body={str(data)[:800]}") from exc
191
-
192
-
193
- llm = LLMClient()
194
-
195
-
196
- def extract_json(text: str) -> dict[str, Any]:
197
- text = text.strip()
198
- if text.startswith("```"):
199
- text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
200
- text = re.sub(r"\s*```$", "", text)
201
- try:
202
- obj = json.loads(text)
203
- if isinstance(obj, dict):
204
- return obj
205
- except json.JSONDecodeError:
206
- pass
207
- starts = [m.start() for m in re.finditer(r"\{", text)]
208
- for s in starts:
209
- depth = 0
210
- in_str = False
211
- esc = False
212
- for i in range(s, len(text)):
213
- ch = text[i]
214
- if in_str:
215
- if esc:
216
- esc = False
217
- elif ch == "\\":
218
- esc = True
219
- elif ch == '"':
220
- in_str = False
221
- else:
222
- if ch == '"':
223
- in_str = True
224
- elif ch == "{":
225
- depth += 1
226
- elif ch == "}":
227
- depth -= 1
228
- if depth == 0:
229
- try:
230
- obj = json.loads(text[s : i + 1])
231
- if isinstance(obj, dict):
232
- return obj
233
- except json.JSONDecodeError:
234
- break
235
- raise ValueError("Agent returned invalid JSON")
236
-
237
-
238
- async def emit(session_id: str, event: dict[str, Any]) -> None:
239
- session = sessions.get(session_id)
240
- if not session:
241
- return
242
- session["events"].append(event)
243
- session["events"] = session["events"][-600:]
244
- dead = []
245
- for ws in session["sockets"]:
246
- try:
247
- await ws.send_json(event)
248
- except Exception:
249
- dead.append(ws)
250
- for ws in dead:
251
- session["sockets"].discard(ws)
252
-
253
-
254
- async def emit_text(session_id: str, kind: str, text: str, **extra: Any) -> None:
255
- await emit(session_id, {"type": kind, "text": text, "ts": time.time(), **extra})
256
-
257
-
258
- def terminal_guard(command: str) -> None:
259
- if not TERMINAL_ENABLED:
260
- raise RuntimeError("Terminal is disabled. Set TERMINAL_ENABLED=true in Space variables.")
261
- for pattern in DENIED_COMMAND_PATTERNS:
262
- if re.search(pattern, command, flags=re.I):
263
- raise RuntimeError("Command blocked by terminal safety policy")
264
-
265
-
266
- async def run_command(command: str, timeout: int | None = None) -> dict[str, Any]:
267
- terminal_guard(command)
268
- if len(command) > 4000:
269
- raise RuntimeError("Command is too long")
270
- timeout = timeout or COMMAND_TIMEOUT
271
- env = os.environ.copy()
272
- env["PWD"] = str(WORKSPACE)
273
- proc = await asyncio.create_subprocess_shell(
274
- command,
275
- cwd=str(WORKSPACE),
276
- env=env,
277
- stdout=asyncio.subprocess.PIPE,
278
- stderr=asyncio.subprocess.PIPE,
279
- start_new_session=True,
280
- )
281
- try:
282
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
283
- except asyncio.TimeoutError:
284
- try:
285
- os.killpg(proc.pid, signal.SIGKILL)
286
- except Exception:
287
- proc.kill()
288
- await proc.communicate()
289
- return {"exit_code": -1, "stdout": "", "stderr": f"Timed out after {timeout}s"}
290
- return {"exit_code": proc.returncode, "stdout": stdout.decode(errors="replace")[-12000:], "stderr": stderr.decode(errors="replace")[-12000:]}
291
-
292
-
293
- async def tool_call(action: dict[str, Any]) -> dict[str, Any]:
294
- name = action.get("tool") or action.get("name")
295
- args = action.get("args") or {}
296
- if name == "list_files":
297
- return {"files": list_files_compact(int(args.get("max_items", 250)))}
298
- if name == "read_file":
299
- p = abs_path(str(args.get("path", "")))
300
- if not p.exists() or not p.is_file():
301
- raise RuntimeError("File not found")
302
- if p.stat().st_size > MAX_FILE_BYTES:
303
- raise RuntimeError(f"File too large; max {MAX_FILE_BYTES} bytes")
304
- data = p.read_text(encoding="utf-8", errors="replace")
305
- return {"path": str(args.get("path")), "content": data}
306
- if name == "search":
307
- query = str(args.get("query", ""))
308
- if not query:
309
- raise RuntimeError("search query is required")
310
- matches = []
311
- rx = re.compile(query, re.I) if bool(args.get("regex")) else None
312
- for item in tree():
313
- if item["type"] != "file":
314
- continue
315
- p = WORKSPACE / item["path"]
316
- if p.stat().st_size > MAX_FILE_BYTES or not is_text_file(p):
317
- continue
318
- try:
319
- content = p.read_text(encoding="utf-8", errors="replace")
320
- except Exception:
321
- continue
322
- for lineno, line in enumerate(content.splitlines(), start=1):
323
- hit = bool(rx.search(line)) if rx else query.lower() in line.lower()
324
- if hit:
325
- matches.append({"path": item["path"], "line": lineno, "text": line[:500]})
326
- if len(matches) >= 200:
327
- return {"matches": matches}
328
- return {"matches": matches}
329
- if name == "write_file":
330
- rel = str(args.get("path", ""))
331
- p = abs_path(rel)
332
- content = str(args.get("content", ""))
333
- if len(content.encode("utf-8")) > MAX_FILE_BYTES:
334
- raise RuntimeError(f"File too large; max {MAX_FILE_BYTES} bytes")
335
- p.parent.mkdir(parents=True, exist_ok=True)
336
- p.write_text(content, encoding="utf-8")
337
- return {"written": rel, "bytes": p.stat().st_size}
338
- if name == "patch_file":
339
- rel = str(args.get("path", ""))
340
- p = abs_path(rel)
341
- if not p.exists():
342
- raise RuntimeError("File not found")
343
- old = str(args.get("old", ""))
344
- new = str(args.get("new", ""))
345
- content = p.read_text(encoding="utf-8", errors="replace")
346
- if old not in content:
347
- raise RuntimeError("Exact old text was not found")
348
- count = content.count(old)
349
- if count != 1 and not bool(args.get("replace_all")):
350
- raise RuntimeError(f"Old text matches {count} locations; set replace_all=true or provide more context")
351
- p.write_text(content.replace(old, new, -1 if bool(args.get("replace_all")) else 1), encoding="utf-8")
352
- return {"patched": rel, "replacements": count if bool(args.get("replace_all")) else 1}
353
- if name == "mkdir":
354
- p = abs_path(str(args.get("path", "")))
355
- p.mkdir(parents=True, exist_ok=True)
356
- return {"created": str(args.get("path"))}
357
- if name == "delete_file":
358
- p = abs_path(str(args.get("path", "")))
359
- if p.is_dir():
360
- raise RuntimeError("Directory deletion is disabled through the agent tool")
361
- if not p.exists():
362
- return {"deleted": False}
363
- p.unlink()
364
- return {"deleted": True, "path": str(args.get("path"))}
365
- if name == "run_command":
366
- command = str(args.get("command", ""))
367
- return await run_command(command, int(args.get("timeout", COMMAND_TIMEOUT)))
368
- raise RuntimeError(f"Unknown tool: {name}")
369
-
370
-
371
- TOOLS_SCHEMA = r'''
372
- Available tools. Return tool requests inside the `actions` array.
373
- - list_files: {"tool":"list_files","args":{"max_items":250}}
374
- - read_file: {"tool":"read_file","args":{"path":"relative/path"}}
375
- - search: {"tool":"search","args":{"query":"text","regex":false}}
376
- - write_file: {"tool":"write_file","args":{"path":"relative/path","content":"full file content"}}
377
- - patch_file: {"tool":"patch_file","args":{"path":"relative/path","old":"exact old text","new":"replacement","replace_all":false}}
378
- - mkdir: {"tool":"mkdir","args":{"path":"relative/dir"}}
379
- - delete_file: {"tool":"delete_file","args":{"path":"relative/file"}}
380
- - run_command: {"tool":"run_command","args":{"command":"npm test","timeout":30}}
381
- '''
382
-
383
-
384
- def planner_system() -> str:
385
- return """You are the planning agent in a professional agentic coding IDE. Analyze the user's request and produce a concise implementation plan. Do not modify files. Return ONLY valid JSON with keys: summary (string), steps (array of strings), risks (array of strings), likely_files (array of strings)."""
386
-
387
-
388
- def coder_system(mode: str, instructions: str) -> str:
389
- return f"""You are the primary coding agent in a professional agentic IDE. You work directly in a real project workspace through tools. Mode: {mode}. Additional project instructions: {instructions or 'none'}.
390
-
391
- You must inspect the project before making substantial changes. Prefer precise patches when editing an existing file; use write_file for new files or full rewrites when justified. Keep changes focused on the requested outcome.
392
-
393
- Every response MUST be ONLY one JSON object with this structure:
394
- {{
395
- "message": "brief human-readable progress update",
396
- "actions": [{{"tool":"read_file","args":{{...}}}}],
397
- "done": false
398
- }}
399
-
400
- When you have enough information and no more tool work is necessary, set done=true and actions=[] . Never wrap the JSON in markdown.
401
-
402
- {TOOLS_SCHEMA}"""
403
-
404
-
405
- def reviewer_system() -> str:
406
- return """You are the review agent in a professional coding IDE. Inspect the requested work and changed files conceptually from the supplied diff/context. Identify correctness, regressions, security issues, missing requirements, and concrete fixes. Do not make changes. Return ONLY valid JSON: {\"approved\":true/false,\"summary\":\"...\",\"issues\":[\"...\"],\"fix_plan\":[\"...\"]}."""
407
-
408
-
409
- async def run_agent(session_id: str, prompt: str, mode: str, instructions: str) -> None:
410
- session = sessions[session_id]
411
- if session.get("running"):
412
- return
413
- session["running"] = True
414
- session["stop"] = False
415
- before = snapshot()
416
- try:
417
- if not LLM_API_KEY:
418
- raise RuntimeError("LLM_API_KEY is missing. Add it under Space Settings → Secrets.")
419
-
420
- await emit_text(session_id, "agent_status", "Planner is analyzing the task…", stage="planner")
421
- plan_raw = await llm.chat([
422
- {"role": "system", "content": planner_system()},
423
- {"role": "user", "content": f"Project files:\n{json.dumps(list_files_compact(), ensure_ascii=False)}\n\nUser request:\n{prompt}"},
424
- ], temperature=0.1, max_tokens=2500)
425
- try:
426
- plan = extract_json(plan_raw)
427
- except Exception:
428
- plan = {"summary": plan_raw[:2000], "steps": [], "risks": [], "likely_files": []}
429
- session["plan"] = plan
430
- await emit(session_id, {"type": "plan", "plan": plan, "ts": time.time()})
431
-
432
- if mode == "plan":
433
- await emit_text(session_id, "agent_status", "Plan complete. No files were changed.", stage="complete")
434
- return
435
-
436
- if mode == "review-first":
437
- session["approval"] = asyncio.Event()
438
- await emit(session_id, {"type": "approval_required", "plan": plan, "ts": time.time()})
439
- await emit_text(session_id, "agent_status", "Waiting for your approval before the Coder can write files…", stage="approval")
440
- try:
441
- await asyncio.wait_for(session["approval"].wait(), timeout=900)
442
- except asyncio.TimeoutError:
443
- await emit_text(session_id, "agent_status", "Approval timed out after 15 minutes.", stage="stopped")
444
- return
445
- if session.get("stop") or session.get("approval") is None:
446
- await emit_text(session_id, "agent_status", "Agent stopped before approval.", stage="stopped")
447
- return
448
- session["approval"] = None
449
-
450
- coder_messages: list[dict[str, Any]] = [
451
- {"role": "system", "content": coder_system(mode, instructions)},
452
- {"role": "user", "content": f"User request:\n{prompt}\n\nPlan:\n{json.dumps(plan, ensure_ascii=False)}\n\nCurrent project file list:\n{json.dumps(list_files_compact(), ensure_ascii=False)}"},
453
- ]
454
-
455
- for turn in range(1, MAX_AGENT_TURNS + 1):
456
- if session.get("stop"):
457
- await emit_text(session_id, "agent_status", "Agent stopped by user.", stage="stopped")
458
- return
459
- await emit_text(session_id, "agent_status", f"Coder pass {turn}/{MAX_AGENT_TURNS}…", stage="coder", turn=turn)
460
- raw = await llm.chat(coder_messages, temperature=LLM_TEMPERATURE)
461
- try:
462
- obj = extract_json(raw)
463
- except Exception as exc:
464
- coder_messages.append({"role": "assistant", "content": raw})
465
- coder_messages.append({"role": "user", "content": f"Your previous response was not valid JSON ({exc}). Return only the required JSON object."})
466
- continue
467
-
468
- msg = str(obj.get("message", ""))
469
- if msg:
470
- await emit_text(session_id, "agent_message", msg, stage="coder", turn=turn)
471
- actions = obj.get("actions") or []
472
- if not isinstance(actions, list):
473
- actions = []
474
-
475
- if not actions:
476
- if obj.get("done"):
477
- break
478
- coder_messages.append({"role": "assistant", "content": json.dumps(obj, ensure_ascii=False)})
479
- coder_messages.append({"role": "user", "content": "Continue the implementation. Inspect or modify files as needed; do not stop until the requested task is actually implemented. Return JSON only."})
480
- continue
481
-
482
- results = []
483
- if mode == "review-first":
484
- write_tools = set()
485
-
486
- for action in actions[:8]:
487
- if session.get("stop"):
488
- break
489
- tool_name = action.get("tool") or action.get("name")
490
- if tool_name in write_tools:
491
- result = {"blocked": True, "reason": "Write blocked by the active agent policy."}
492
- await emit(session_id, {"type": "tool_blocked", "tool": tool_name, "action": action, "result": result, "ts": time.time()})
493
- else:
494
- await emit(session_id, {"type": "tool_start", "tool": tool_name, "args": action.get("args") or {}, "ts": time.time()})
495
- try:
496
- result = await tool_call(action)
497
- await emit(session_id, {"type": "tool_result", "tool": tool_name, "result": result, "ok": True, "ts": time.time()})
498
- except Exception as exc:
499
- result = {"error": str(exc)}
500
- await emit(session_id, {"type": "tool_result", "tool": tool_name, "result": result, "ok": False, "ts": time.time()})
501
- results.append({"tool": tool_name, "result": result})
502
-
503
- coder_messages.append({"role": "assistant", "content": json.dumps(obj, ensure_ascii=False)})
504
- coder_messages.append({"role": "user", "content": "Tool results:\n" + json.dumps(results, ensure_ascii=False) + "\nContinue. Return JSON only."})
505
-
506
- changed, created, deleted = diff_snapshot(before)
507
- summary_diff = []
508
- for rel in changed + created:
509
- p = WORKSPACE / rel
510
- if p.exists() and p.is_file() and p.stat().st_size <= 200000 and is_text_file(p):
511
- try:
512
- current = p.read_text(encoding="utf-8", errors="replace")
513
- except Exception:
514
- continue
515
- old = ""
516
- if rel in before:
517
- # We do not retain original content in snapshot; identify changed paths here.
518
- old = "[existing file changed]"
519
- summary_diff.append({"path": rel, "before": old, "after_excerpt": current[:12000]})
520
- await emit(session_id, {"type": "changes", "changed": changed, "created": created, "deleted": deleted, "ts": time.time()})
521
-
522
- if mode != "plan":
523
- await emit_text(session_id, "agent_status", "Reviewer is checking the result…", stage="reviewer")
524
- review_raw = await llm.chat([
525
- {"role": "system", "content": reviewer_system()},
526
- {"role": "user", "content": json.dumps({
527
- "request": prompt,
528
- "plan": plan,
529
- "changed": changed,
530
- "created": created,
531
- "deleted": deleted,
532
- "file_excerpts": summary_diff,
533
- }, ensure_ascii=False)},
534
- ], temperature=0.1, max_tokens=4000)
535
- try:
536
- review = extract_json(review_raw)
537
- except Exception:
538
- review = {"approved": False, "summary": review_raw[:3000], "issues": [], "fix_plan": []}
539
- await emit(session_id, {"type": "review", "review": review, "ts": time.time()})
540
- if mode == "autonomous" and not review.get("approved", False) and review.get("fix_plan"):
541
- await emit_text(session_id, "agent_status", "Reviewer found issues; running one focused fix pass…", stage="fix")
542
- fix_prompt = "Review findings:\n" + json.dumps(review, ensure_ascii=False) + "\nApply the concrete fixes only. Then report done."
543
- fix_messages = [
544
- {"role": "system", "content": coder_system("autonomous-fix", instructions)},
545
- {"role": "user", "content": fix_prompt + "\n\nCurrent files:\n" + json.dumps(list_files_compact(), ensure_ascii=False)},
546
- ]
547
- for _ in range(4):
548
- raw = await llm.chat(fix_messages, temperature=0.1, max_tokens=7000)
549
- try:
550
- obj = extract_json(raw)
551
- except Exception:
552
- fix_messages.append({"role": "assistant", "content": raw})
553
- fix_messages.append({"role": "user", "content": "Return only valid JSON."})
554
- continue
555
- acts = obj.get("actions") or []
556
- results = []
557
- for action in acts[:8]:
558
- try:
559
- r = await tool_call(action)
560
- except Exception as exc:
561
- r = {"error": str(exc)}
562
- results.append({"tool": action.get("tool"), "result": r})
563
- await emit(session_id, {"type": "tool_result", "tool": action.get("tool"), "result": r, "ok": "error" not in r, "ts": time.time()})
564
- if obj.get("done") and not acts:
565
- break
566
- fix_messages.append({"role": "assistant", "content": json.dumps(obj, ensure_ascii=False)})
567
- fix_messages.append({"role": "user", "content": "Tool results:\n" + json.dumps(results, ensure_ascii=False)})
568
-
569
- changed, created, deleted = diff_snapshot(before)
570
- await emit(session_id, {"type": "complete", "changed": changed, "created": created, "deleted": deleted, "ts": time.time()})
571
- except Exception as exc:
572
- await emit_text(session_id, "error", str(exc), stage="error")
573
- finally:
574
- session["running"] = False
575
- session["stop"] = False
576
- await emit_text(session_id, "agent_status", "Ready.", stage="ready")
577
-
578
-
579
- class CreateSession(BaseModel):
580
- pass
581
-
582
-
583
- class ChatRequest(BaseModel):
584
- session_id: str
585
- prompt: str = Field(min_length=1, max_length=20000)
586
- mode: Literal["autonomous", "review-first", "plan"] = "autonomous"
587
- instructions: str = Field(default="", max_length=10000)
588
-
589
-
590
- class TerminalRequest(BaseModel):
591
- command: str = Field(min_length=1, max_length=4000)
592
- timeout: int = Field(default=30, ge=1, le=120)
593
-
594
-
595
- class SaveFile(BaseModel):
596
- path: str
597
- content: str
598
-
599
-
600
- class DeleteRequest(BaseModel):
601
- path: str
602
-
603
-
604
- @app.get("/api/auth/status")
605
- async def auth_status():
606
- return {"required": bool(APP_ACCESS_TOKEN)}
607
-
608
-
609
- @app.post("/api/auth/login")
610
- async def auth_login(request: Request, payload: dict[str, str]):
611
- if not APP_ACCESS_TOKEN:
612
- return {"ok": True}
613
- if not auth_ok(payload.get("token")):
614
- raise HTTPException(401, "Invalid access token")
615
- response = JSONResponse({"ok": True})
616
- response.set_cookie(
617
- "agent_access",
618
- payload["token"],
619
- httponly=True,
620
- samesite="none",
621
- secure=True,
622
- path="/",
623
- max_age=86400,
624
- )
625
- return response
626
-
627
-
628
- def require_request_auth(token: str | None = None) -> None:
629
- if APP_ACCESS_TOKEN and not auth_ok(token):
630
- raise HTTPException(401, "Authentication required")
631
-
632
-
633
- @app.middleware("http")
634
- async def auth_middleware(request: Request, call_next):
635
- if APP_ACCESS_TOKEN and request.url.path.startswith("/api/") and request.url.path not in {"/api/auth/status", "/api/auth/login"}:
636
- if not auth_ok(request.cookies.get("agent_access")):
637
- return JSONResponse({"detail": "Authentication required"}, status_code=401)
638
- return await call_next(request)
639
-
640
-
641
- @app.get("/api/status")
642
- async def status():
643
- return {
644
- "ok": True,
645
- "model": LLM_MODEL,
646
- "base_url": LLM_BASE_URL,
647
- "has_api_key": bool(LLM_API_KEY),
648
- "terminal_enabled": TERMINAL_ENABLED,
649
- "workspace": WORKSPACE.name,
650
- }
651
-
652
-
653
- @app.get("/api/tree")
654
- async def get_tree():
655
- return {"items": tree()}
656
-
657
-
658
- @app.get("/api/file")
659
- async def get_file(path: str):
660
- p = abs_path(path)
661
- if not p.exists() or not p.is_file():
662
- raise HTTPException(404, "File not found")
663
- if p.stat().st_size > MAX_FILE_BYTES:
664
- raise HTTPException(413, "File too large")
665
- if not is_text_file(p):
666
- return FileResponse(p)
667
- return {"path": path, "content": p.read_text(encoding="utf-8", errors="replace")}
668
-
669
-
670
- @app.put("/api/file")
671
- async def put_file(body: SaveFile):
672
- p = abs_path(body.path)
673
- if len(body.content.encode("utf-8")) > MAX_FILE_BYTES:
674
- raise HTTPException(413, "File too large")
675
- p.parent.mkdir(parents=True, exist_ok=True)
676
- p.write_text(body.content, encoding="utf-8")
677
- return {"ok": True, "path": body.path, "size": p.stat().st_size}
678
-
679
-
680
- @app.delete("/api/file")
681
- async def remove_file(body: DeleteRequest):
682
- p = abs_path(body.path)
683
- if p.exists() and p.is_file():
684
- p.unlink()
685
- return {"ok": True}
686
-
687
-
688
- @app.post("/api/upload")
689
- async def upload_file(file: UploadFile = File(...), path: str | None = None):
690
- filename = Path(path or file.filename or "upload.bin").name
691
- rel = clean_rel_path(filename)
692
- content = await file.read(MAX_UPLOAD_MB * 1024 * 1024 + 1)
693
- if len(content) > MAX_UPLOAD_MB * 1024 * 1024:
694
- raise HTTPException(413, "Upload too large")
695
- dest = WORKSPACE / rel
696
- dest.parent.mkdir(parents=True, exist_ok=True)
697
- dest.write_bytes(content)
698
- return {"ok": True, "path": rel.as_posix(), "size": len(content)}
699
-
700
-
701
- @app.get("/api/download")
702
- async def download_file(path: str):
703
- p = abs_path(path)
704
- if not p.exists() or not p.is_file():
705
- raise HTTPException(404, "File not found")
706
- return FileResponse(p, filename=p.name)
707
-
708
-
709
- @app.post("/api/terminal")
710
- async def terminal(body: TerminalRequest):
711
- result = await run_command(body.command, body.timeout)
712
- return result
713
-
714
-
715
- @app.post("/api/session")
716
- async def create_session():
717
- session_id = uuid.uuid4().hex
718
- sessions[session_id] = {"events": [], "sockets": set(), "running": False, "stop": False, "messages": [], "plan": None, "approval": None}
719
- return {"session_id": session_id}
720
-
721
-
722
- @app.post("/api/agent")
723
- async def start_agent(req: ChatRequest):
724
- session = sessions.get(req.session_id)
725
- if not session:
726
- raise HTTPException(404, "Session not found")
727
- if session.get("running"):
728
- raise HTTPException(409, "Agent is already running")
729
- session["messages"].append({"role": "user", "content": req.prompt, "ts": time.time()})
730
- asyncio.create_task(run_agent(req.session_id, req.prompt, req.mode, req.instructions))
731
- return {"ok": True}
732
-
733
-
734
- @app.post("/api/agent/stop")
735
- async def stop_agent(body: dict[str, str]):
736
- session = sessions.get(body.get("session_id", ""))
737
- if not session:
738
- raise HTTPException(404, "Session not found")
739
- session["stop"] = True
740
- if isinstance(session.get("approval"), asyncio.Event):
741
- session["approval"].set()
742
- return {"ok": True}
743
-
744
-
745
- @app.post("/api/agent/approve")
746
- async def approve_agent(body: dict[str, str]):
747
- session = sessions.get(body.get("session_id", ""))
748
- if not session:
749
- raise HTTPException(404, "Session not found")
750
- approval = session.get("approval")
751
- if not isinstance(approval, asyncio.Event):
752
- raise HTTPException(409, "No approval is currently pending")
753
- approval.set()
754
- return {"ok": True}
755
-
756
-
757
- @app.get("/api/session/{session_id}")
758
- async def get_session(session_id: str):
759
- session = sessions.get(session_id)
760
- if not session:
761
- raise HTTPException(404, "Session not found")
762
- return {"events": session["events"], "messages": session["messages"], "plan": session["plan"], "running": session["running"]}
763
-
764
-
765
- @app.websocket("/ws/{session_id}")
766
- async def websocket_endpoint(ws: WebSocket, session_id: str):
767
- token = ws.cookies.get("agent_access") if APP_ACCESS_TOKEN else None
768
- if APP_ACCESS_TOKEN and not auth_ok(token):
769
- await ws.close(code=4401)
770
- return
771
- session = sessions.get(session_id)
772
- if not session:
773
- await ws.close(code=4404)
774
- return
775
- await ws.accept()
776
- session["sockets"].add(ws)
777
- try:
778
- for event in session["events"][-250:]:
779
- await ws.send_json(event)
780
- while True:
781
- await ws.receive_text()
782
- except WebSocketDisconnect:
783
- pass
784
- finally:
785
- session["sockets"].discard(ws)
786
-
787
-
788
- app.mount("/", StaticFiles(directory=APP_DIR / "static", html=True), name="static")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uvicorn
3
+ import httpx
4
+ from fastapi import (
5
+ FastAPI,
6
+ Request,
7
+ )
8
+ from fastapi.responses import (
9
+ JSONResponse,
10
+ )
11
+ from fastapi.staticfiles import (
12
+ StaticFiles,
13
+ )
14
+
15
+ app = FastAPI(
16
+ title="WebApp Builder Core"
17
+ )
18
+
19
+ @app.get("/api/health")
20
+ async def health():
21
+ return {
22
+ "status": "healthy",
23
+ "env": "huggingface"
24
+ }
25
+
26
+ @app.post("/api/proxy")
27
+ async def proxy_pass(
28
+ request: Request
29
+ ):
30
+ try:
31
+ body = await request.json()
32
+ target = body.get("url")
33
+ method = body.get(
34
+ "method", "GET"
35
+ )
36
+ headers = body.get(
37
+ "headers", {}
38
+ )
39
+ data = body.get("data")
40
+
41
+ if not target:
42
+ return JSONResponse(
43
+ {"error": "Missing URL"},
44
+ status_code=400
45
+ )
46
+
47
+ async with httpx.AsyncClient(
48
+ timeout=12.0
49
+ ) as client:
50
+ resp = await client.request(
51
+ method=method,
52
+ url=target,
53
+ headers=headers,
54
+ json=data
55
+ )
56
+ return JSONResponse(
57
+ content={
58
+ "status": resp.status_code,
59
+ "text": resp.text
60
+ },
61
+ status_code=200
62
+ )
63
+ except Exception as err:
64
+ return JSONResponse(
65
+ {"error": str(err)},
66
+ status_code=500
67
+ )
68
+
69
+ app.mount(
70
+ "/",
71
+ StaticFiles(
72
+ directory="static",
73
+ html=True
74
+ ),
75
+ name="static"
76
+ )
77
+
78
+ if __name__ == "__main__":
79
+ uvicorn.run(
80
+ app,
81
+ host="0.0.0.0",
82
+ port=7860
83
+ )