""" Web backend for the maker harness — a chat API + served chat UI. Runs locally (uvicorn) and online (bind 0.0.0.0, PORT from env). The chat UI talks to /api/chat; each message is routed by the agent to a tool and executed. Any image the tool produces is served via /api/img (a URL) for the UI to show. """ from __future__ import annotations import asyncio import json import mimetypes import threading import time import uuid from pathlib import Path from urllib.parse import quote from fastapi import FastAPI, File, UploadFile from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse from pydantic import BaseModel from fastapi import Request from . import auth as auth_mod from . import config from .agent import Harness from .db import engine as db_engine from .memory import ConversationState STATIC = Path(__file__).resolve().parent / "static" app = FastAPI(title="Agent") auth_mod.register_routes(app) # /api/me, /api/auth/*, /auth/* def _uid(request: Request) -> int | None: """User id hiệu lực cho request (auth) — dùng để scope hội thoại theo người dùng.""" u = auth_mod.current_user(request) if u is not None: return u.get("id") return db_engine.default_user_id() _harness: Harness | None = None _lock = threading.Lock() @app.on_event("startup") async def _startup(): """Khởi tạo DB (nếu có DATABASE_URL) + bus (Redis nếu có REDIS_URL).""" if db_engine.is_enabled(): await asyncio.to_thread(db_engine.init) from . import bus await asyncio.to_thread(bus.get_bus) # log kind sớm; degrade nếu Redis chết def _db() -> bool: return db_engine.ready() def get_harness() -> Harness: global _harness if _harness is None: _harness = Harness() return _harness class ChatIn(BaseModel): message: str model: str | None = None conversation_id: str | None = None history: list[dict] = [] # prior turns [{role, text, tool}] from the client attachment: str | None = None # server path of an uploaded file (see /api/upload) ALLOWED_UPLOAD = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".svg", ".pdf", ".stl", ".gcode", ".nc") @app.post("/api/upload") async def upload(file: UploadFile = File(...)): """Accept a file to act on (e.g. an image to 3D-print/engrave). Saved under var/uploads so the modules + /api/img can read it. Returns its server path.""" ext = Path(file.filename or "").suffix.lower() if ext not in ALLOWED_UPLOAD: return JSONResponse({"error": f"Loại file không hỗ trợ ({ext or '?'})"}, status_code=400) data = await file.read() if len(data) > 12 * 1024 * 1024: return JSONResponse({"error": "File quá lớn (>12MB)"}, status_code=400) updir = config.UPLOADS_DIR updir.mkdir(parents=True, exist_ok=True) dest = updir / f"up_{uuid.uuid4().hex[:8]}{ext}" dest.write_bytes(data) return {"path": str(dest), "url": "/api/img?p=" + quote(str(dest)), "name": file.filename or dest.name} def _path_allowed(path: Path) -> bool: """Chỉ phục vụ file nằm dưới modules/ hoặc var/uploads.""" for base in (config.MODULES_DIR, config.UPLOADS_DIR): if base == path or base in path.parents: return True return False def _state_from(history: list[dict]) -> ConversationState: """Build conversation memory from the client-provided transcript.""" st = ConversationState("_") for h in (history or [])[-16:]: role, text = h.get("role"), h.get("text") if role in ("user", "assistant") and text: st.add(role, text, h.get("tool", "")) return st def _first_image(data: dict) -> str | None: """Find an image the tool produced and return an inline-image URL (not base64, so the conversation stays small in localStorage and the image reloads from disk when the user returns to the chat).""" if not isinstance(data, dict): return None cand: list[str] = [] for k in ("image", "screenshot", "file", "path", "placed_path"): v = data.get(k) if isinstance(v, str): cand.append(v) fr = data.get("frames") if isinstance(fr, list) and fr: cand.append(fr[-1]) for p in cand: try: path = Path(p).resolve() if path.exists() and _path_allowed(path) and path.suffix.lower() in (".gif", ".png", ".jpg", ".jpeg", ".webp"): return "/api/img?p=" + quote(str(path)) except Exception: pass return None def _artifact_files(data: dict) -> list[dict]: """Downloadable result files (gcode/stl/video/image) the tool produced.""" if not isinstance(data, dict): return [] vals = [data[k] for k in ("gcode_file", "stl_file", "video", "screenshot", "image", "file", "path") if isinstance(data.get(k), str)] fr = data.get("frames") if isinstance(fr, list) and fr: vals.append(fr[-1]) out, seen = [], set() for p in vals: try: path = Path(p).resolve() if path.exists() and _path_allowed(path) and path.name not in seen: seen.add(path.name) out.append({"name": path.name, "url": "/api/download?p=" + quote(str(path))}) except Exception: pass return out @app.get("/api/download") def download(p: str): path = Path(p).resolve() if not _path_allowed(path) or not path.exists(): return JSONResponse({"error": "not allowed"}, status_code=403) return FileResponse(str(path), filename=path.name, media_type="application/octet-stream") @app.get("/api/img") def img(p: str): """Serve an image INLINE (correct mime, no attachment) so works and the browser can cache it. Restricted to files under modules/ + var/uploads.""" path = Path(p).resolve() if not _path_allowed(path) or not path.exists(): return JSONResponse({"error": "not allowed"}, status_code=403) mime = mimetypes.guess_type(str(path))[0] or "image/png" return FileResponse(str(path), media_type=mime) @app.get("/healthz") def healthz(): """Liveness probe for hosting platforms (no API key required).""" return {"ok": True, "model": config.DEFAULT_MODEL, "groq_key": bool(config.key_for("groq"))} @app.get("/", response_class=HTMLResponse) def index() -> str: return (STATIC / "index.html").read_text(encoding="utf-8") @app.get("/api/providers") async def api_providers(): """Trạng thái hạn mức từng provider (token còn lại + reset) cho nút chọn provider.""" from . import providers return {"providers": await asyncio.to_thread(providers.status)} @app.get("/api/models") def models(): h = get_harness() return {"current": h.model_name, "models": [{"name": m, "available": config.model_available(m)} for m in config.list_models()]} @app.get("/api/tools") def tools(): h = get_harness() return {"tools": [{"name": n, "description": t.description} for n, t in h.tools.items()]} @app.get("/api/conversations") async def api_conversations(request: Request): """Danh sách hội thoại đã lưu server (theo user khi bật auth). {db:false} nếu không bật DB -> frontend fallback localStorage.""" if auth_mod.enabled() and auth_mod.current_user(request) is None: return JSONResponse({"error": "chưa đăng nhập", "auth": True}, status_code=401) if not _db(): return {"db": False, "conversations": []} uid = _uid(request) def run(): from .db import store return {"db": True, "conversations": store.list_conversations(uid)} return await asyncio.to_thread(run) @app.get("/api/conversations/{conv_id}/messages") async def api_conversation_messages(conv_id: int): if not _db(): return {"db": False, "messages": []} def run(): from .db import store return {"db": True, "messages": store.get_messages(conv_id)} return await asyncio.to_thread(run) @app.delete("/api/conversations/{conv_id}") async def api_delete_conversation(conv_id: int, request: Request): if not _db(): return {"ok": False, "db": False} uid = _uid(request) def run(): from .db import store return {"ok": store.delete_conversation(conv_id, uid)} return await asyncio.to_thread(run) @app.post("/api/modules/reload") async def modules_reload(): """Nạp lại modules/ từ đĩa (thay cho filesystem watcher — an toàn trên Windows/OneDrive). Harness rebuild để router thấy danh sách tool mới.""" from .modules.registry import get_registry def run(): global _harness with _lock: reg = get_registry() reg.load_all() _harness = None # rebuild lazily với tool list mới return {"ok": True, "version": reg.version, "modules": reg.names()} return await asyncio.to_thread(run) class TitleIn(BaseModel): message: str @app.post("/api/title") async def api_title(inp: TitleIn): def run(): with _lock: return {"title": get_harness().title_for(inp.message)} try: return await asyncio.to_thread(run) except Exception: return {"title": inp.message[:42]} def _run(message: str, model: str | None, history: list[dict], attachment: str | None = None) -> dict: with _lock: # single shared harness -> serialize h = get_harness() if model and model != h.model_name: h.set_model(model) name, res = h.handle(message, _state_from(history), attachment=attachment) return {"tool": name, "ok": res.ok, "summary": res.summary, "image": _first_image(res.data or {}), "files": _artifact_files(res.data or {}), "reasoning": (res.data or {}).get("reasoning") or "", "steps": (res.data or {}).get("steps") or [], "model": h.model_name} @app.post("/api/chat") async def chat(inp: ChatIn): if not inp.message.strip() and not inp.attachment: return JSONResponse({"error": "empty message"}, status_code=400) try: return await asyncio.to_thread(_run, inp.message, inp.model, inp.history, inp.attachment) except Exception as e: return JSONResponse({"error": str(e)}, status_code=500) def _sse(ev: dict) -> str: return f"data: {json.dumps(ev, ensure_ascii=False)}\n\n" def _persist_turn(conv_id: int, user_text: str, result_ev: dict, data: dict) -> None: """Lưu 1 lượt vào DB. blocks = payload UI (text/tool/files/image/reasoning), kèm _data để trích artifact (đường dẫn server, không gửi qua SSE).""" try: from .db import store as db_store blocks = {"text": result_ev.get("summary", ""), "tool": result_ev.get("tool"), "ok": result_ev.get("ok", True), "reasoning": result_ev.get("reasoning") or "", "files": result_ev.get("files") or [], "image": result_ev.get("image"), "usage": result_ev.get("usage"), "_data": data} db_store.add_turn(conv_id, user_text, blocks) except Exception as e: # persistence không được làm hỏng chat import logging logging.getLogger("harness.webapp").warning("persist lỗi: %s", e) @app.post("/api/chat/stream") async def chat_stream(inp: ChatIn, request: Request): """SSE: status -> route -> (chat: token deltas | tool: run) -> result -> done. Chat replies are streamed token-by-token; the 'rewritten' flag marks when the message was resolved from context; results carry downloadable 'files'.""" if auth_mod.enabled() and auth_mod.current_user(request) is None: return JSONResponse({"error": "chưa đăng nhập", "auth": True}, status_code=401) uid = _uid(request) async def gen(): try: with _lock: h = get_harness() if inp.model and inp.model != h.model_name: h.set_model(inp.model) # DB bật -> nạp ngữ cảnh từ server (theo conversation_id), tạo hội thoại # nếu chưa có; không bật -> dùng transcript client như cũ. conv_id = inp.conversation_id if _db(): from .db import store as db_store cid = int(conv_id) if (conv_id and str(conv_id).isdigit()) else None if cid is None: cid = await asyncio.to_thread(db_store.create_conversation, uid, inp.message[:60], h.model_name) conv_id = cid yield _sse({"type": "conversation", "id": cid}) state = await asyncio.to_thread(db_store.load_state, cid) else: state = _state_from(inp.history) # ReAct mode: một agent tool-calling; sự kiện route/step/reasoning phát # ra từ trong agent qua callback emit -> forward thành SSE. if getattr(h, "react", None) is not None: from . import bus _bus = bus.get_bus() _conv_key = str(conv_id or "anon") loop = asyncio.get_running_loop() queue: asyncio.Queue = asyncio.Queue() def emit(ev): loop.call_soon_threadsafe(queue.put_nowait, ev) # SSE in-process _bus.publish(_conv_key, ev) # + bus (Redis nếu có) yield _sse({"type": "status", "text": "Đang suy nghĩ…", "model": h.model_name}) t = time.time() fut = asyncio.ensure_future(asyncio.to_thread( h.stream, inp.message, state, inp.attachment, emit)) while not (fut.done() and queue.empty()): try: yield _sse(await asyncio.wait_for(queue.get(), timeout=0.25)) except asyncio.TimeoutError: pass target, res = await fut data = res.data or {} if data.get("reasoning"): yield _sse({"type": "reasoning", "text": data["reasoning"]}) result_ev = {"type": "result", "tool": target, "ok": res.ok, "summary": res.summary, "image": _first_image(data), "files": _artifact_files(data), "reasoning": data.get("reasoning") or "", "steps": [], "usage": data.get("usage"), "rewritten": False, "seconds": round(time.time() - t, 1)} yield _sse(result_ev) if _db() and conv_id: await asyncio.to_thread(_persist_turn, int(conv_id), inp.message, result_ev, data) yield _sse({"type": "done"}) return yield _sse({"type": "status", "text": "Đang phân loại…", "model": h.model_name}) standalone = await asyncio.to_thread(h.contextualize, inp.message, state) rewritten = standalone.strip().lower() != inp.message.strip().lower() target, reason = await asyncio.to_thread(h.route, standalone, inp.message, inp.attachment) yield _sse({"type": "route", "tool": target, "reason": reason, "rewritten": rewritten, "standalone": standalone}) t = time.time() legacy_result, legacy_data = None, {} if target == "chat": yield _sse({"type": "status", "text": "Đang soạn trả lời…"}) # Groq streaming + tool-calling (web_search) is unreliable, so run # non-streamed; the frontend typewriter animates the full text. def _reply(): from . import usage as _u _u.reset() out = h.chat_reply(h.chat_prompt(inp.message, state)) return out[0], out[1], _u.get() full, reasoning, usg = await asyncio.to_thread(_reply) if reasoning: yield _sse({"type": "reasoning", "text": reasoning}) yield _sse({"type": "delta", "text": full}) legacy_result = {"type": "result", "tool": "chat", "ok": True, "summary": full, "reasoning": reasoning, "rewritten": rewritten, "files": [], "usage": usg, "seconds": round(time.time() - t, 1)} legacy_data = {"usage": usg} yield _sse(legacy_result) else: yield _sse({"type": "status", "text": f"Đang chạy {target}…"}) # Live per-station progress: the tool (in a worker thread) pushes # events through a thread-safe callback; we forward them as SSE. loop = asyncio.get_running_loop() queue: asyncio.Queue = asyncio.Queue() def on_progress(ev): loop.call_soon_threadsafe(queue.put_nowait, {"type": "step", **ev}) fut = asyncio.ensure_future(asyncio.to_thread( h.run_target, target, standalone, state, inp.message, inp.attachment, on_progress)) while not (fut.done() and queue.empty()): try: yield _sse(await asyncio.wait_for(queue.get(), timeout=0.25)) except asyncio.TimeoutError: pass res = await fut data = res.data or {} legacy_data = data if data.get("reasoning"): yield _sse({"type": "reasoning", "text": data["reasoning"]}) legacy_result = {"type": "result", "tool": target, "ok": res.ok, "summary": res.summary, "image": _first_image(data), "files": _artifact_files(data), "reasoning": data.get("reasoning") or "", "steps": data.get("steps") or [], "usage": data.get("usage"), "rewritten": rewritten, "seconds": round(time.time() - t, 1)} yield _sse(legacy_result) # persist lượt legacy (cả chat lẫn tool) — cùng seam với nhánh react if _db() and conv_id and legacy_result: await asyncio.to_thread(_persist_turn, int(conv_id), inp.message, legacy_result, legacy_data) except Exception as e: yield _sse({"type": "result", "tool": "?", "ok": False, "summary": f"lỗi: {e}"}) finally: yield _sse({"type": "done"}) return StreamingResponse(gen(), media_type="text/event-stream") if __name__ == "__main__": import os import uvicorn uvicorn.run("harness.webapp:app", host="0.0.0.0", port=int(os.getenv("PORT", "8080")), reload=False)