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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
ΩFFΣLLIα Kernel — Text/Code Edition
|
| 5 |
+
Proxy + login + UI unificada, focado 100% em texto e código.
|
| 6 |
+
|
| 7 |
+
Recursos:
|
| 8 |
+
- chat/código → llama-server externo (:8080), streaming
|
| 9 |
+
- upload de .txt / .pdf → extração de texto e injeção no contexto (ctx alto)
|
| 10 |
+
- LaTeX (KaTeX) + Markdown + emojis + highlight de código
|
| 11 |
+
- métricas em tempo real: ctx usado da janela, tokens/s ao vivo,
|
| 12 |
+
total de tokens e tempo total ao fim de cada resposta
|
| 13 |
+
- memória de conversas (persistência local em JSON) + sidebar para ver/excluir
|
| 14 |
+
- personas (persistência local em JSON) + sidebar para criar/ver/excluir,
|
| 15 |
+
injetadas como system prompt na conversa ativa (sem limite de caracteres)
|
| 16 |
+
- AGÊNTICA: 1 único agente real, roda em segundo plano (intervalo), memória
|
| 17 |
+
própria persistente e em tempo real, relatórios por ação em pasta dedicada,
|
| 18 |
+
ações reais (shell/python/http/escrita de arquivo/llm), permissão root opcional
|
| 19 |
+
via senha. Ativar/desativar/excluir/recriar — nunca mais de um.
|
| 20 |
+
- login, sessão assinada, rate-limit, TLS autoassinado
|
| 21 |
+
- ZERO telemetria, zero ping externo
|
| 22 |
+
|
| 23 |
+
═══ v2 — UPGRADES CIRÚRGICOS (base intacta; tudo marcado com [UPGRADE]) ═══
|
| 24 |
+
- TUDO orquestrado num único llama-server externo (:8080)
|
| 25 |
+
- /api/health: ping no upstream LLM com pill na sidebar
|
| 26 |
+
- parar geração (AbortController) + regenerar última resposta
|
| 27 |
+
- detecção de stream robusta no proxy (parsing JSON, sem falso-positivo)
|
| 28 |
+
- TLS SAN ampliado (IPs LAN + 10.42.0.1 do hotspot kernel-local)
|
| 29 |
+
- exportar conversa em .md (frontend puro)
|
| 30 |
+
|
| 31 |
+
Deps:
|
| 32 |
+
pip install "fastapi[standard]" uvicorn httpx itsdangerous "passlib[argon2]" \
|
| 33 |
+
cryptography pypdf
|
| 34 |
+
|
| 35 |
+
Assets offline (1x — opcional; há fallback por CDN comentado):
|
| 36 |
+
Coloque em offsellia_data/static/:
|
| 37 |
+
marked.min.js, katex.min.js, katex.min.css, auto-render.min.js,
|
| 38 |
+
highlight.min.js, github-dark.min.css (+ pasta de fonts do KaTeX)
|
| 39 |
+
|
| 40 |
+
Rode:
|
| 41 |
+
python ΩFFΣLLIα_Kernel.py
|
| 42 |
+
"""
|
| 43 |
+
import os, sys, json, secrets, time, ipaddress, uuid, threading, subprocess, asyncio
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
from contextlib import asynccontextmanager
|
| 46 |
+
|
| 47 |
+
import httpx
|
| 48 |
+
from fastapi import FastAPI, Request, Response, Form
|
| 49 |
+
from fastapi.responses import (HTMLResponse, RedirectResponse, StreamingResponse,
|
| 50 |
+
JSONResponse, FileResponse)
|
| 51 |
+
from itsdangerous import URLSafeTimedSerializer, BadSignature
|
| 52 |
+
from passlib.hash import argon2
|
| 53 |
+
|
| 54 |
+
# ═══════════════════════════ Config local (sem telemetria) ═══════════════════════════
|
| 55 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 56 |
+
DATA_DIR = BASE_DIR / "offsellia_data"
|
| 57 |
+
CONF_PATH = DATA_DIR / "kernel.json"
|
| 58 |
+
DATA_DIR.mkdir(exist_ok=True)
|
| 59 |
+
|
| 60 |
+
STATIC_DIR = DATA_DIR / "static"
|
| 61 |
+
CHATS_DIR = DATA_DIR / "chats"
|
| 62 |
+
PERSONAS_DIR = DATA_DIR / "personas"
|
| 63 |
+
AGENT_DIR = DATA_DIR / "agent"
|
| 64 |
+
AGENT_MEM_DIR = AGENT_DIR / "memory"
|
| 65 |
+
AGENT_REPORTS_DIR = AGENT_DIR / "reports"
|
| 66 |
+
for d in (STATIC_DIR, CHATS_DIR, PERSONAS_DIR, AGENT_DIR, AGENT_MEM_DIR, AGENT_REPORTS_DIR):
|
| 67 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
|
| 69 |
+
AGENT_CONF_PATH = AGENT_DIR / "agent.json"
|
| 70 |
+
AGENT_MEM_PATH = AGENT_MEM_DIR / "memory.json"
|
| 71 |
+
|
| 72 |
+
KERNEL_NAME = "ΩFFΣLLIα"
|
| 73 |
+
SESSION_MAX_AGE = 60 * 60 * 8
|
| 74 |
+
COOKIE = "offsellia_session"
|
| 75 |
+
|
| 76 |
+
DEFAULTS = {
|
| 77 |
+
"port": 5000,
|
| 78 |
+
"bind": "0.0.0.0",
|
| 79 |
+
"use_tls": True,
|
| 80 |
+
"n_ctx": 50000, # janela de contexto reportada na UI (ajuste ao seu llama-server)
|
| 81 |
+
"upstreams": {
|
| 82 |
+
"llm": "http://127.0.0.1:8080", # único llama-server externo, tudo orquestrado aqui
|
| 83 |
+
},
|
| 84 |
+
"secret": secrets.token_hex(32),
|
| 85 |
+
"pwd_hash": None,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
def load_conf() -> dict:
|
| 89 |
+
if CONF_PATH.exists():
|
| 90 |
+
conf = json.loads(CONF_PATH.read_text())
|
| 91 |
+
for k, v in DEFAULTS.items():
|
| 92 |
+
conf.setdefault(k, v)
|
| 93 |
+
for k, v in DEFAULTS["upstreams"].items():
|
| 94 |
+
conf["upstreams"].setdefault(k, v)
|
| 95 |
+
return conf
|
| 96 |
+
conf = dict(DEFAULTS)
|
| 97 |
+
pw = os.environ.get("OFFSELLIA_PASS")
|
| 98 |
+
if not pw:
|
| 99 |
+
print(f"\n[{KERNEL_NAME}] Primeiro boot — defina a senha de acesso.")
|
| 100 |
+
import getpass
|
| 101 |
+
while True:
|
| 102 |
+
pw = getpass.getpass(" Nova senha: ")
|
| 103 |
+
if pw and pw == getpass.getpass(" Confirme: "):
|
| 104 |
+
break
|
| 105 |
+
print(" Não conferem, tente de novo.")
|
| 106 |
+
conf["pwd_hash"] = argon2.using(rounds=4, memory_cost=65536).hash(pw)
|
| 107 |
+
CONF_PATH.write_text(json.dumps(conf, indent=2))
|
| 108 |
+
print(f"[{KERNEL_NAME}] Config salva em {CONF_PATH}\n")
|
| 109 |
+
return conf
|
| 110 |
+
|
| 111 |
+
CONF = load_conf()
|
| 112 |
+
signer = URLSafeTimedSerializer(CONF["secret"], salt="offsellia-auth")
|
| 113 |
+
|
| 114 |
+
# ═══════════════════════════ Auth ═══════════════════════════
|
| 115 |
+
def issue_token() -> str:
|
| 116 |
+
return signer.dumps({"t": time.time()})
|
| 117 |
+
|
| 118 |
+
def valid_session(req: Request) -> bool:
|
| 119 |
+
tok = req.cookies.get(COOKIE)
|
| 120 |
+
if not tok:
|
| 121 |
+
return False
|
| 122 |
+
try:
|
| 123 |
+
signer.loads(tok, max_age=SESSION_MAX_AGE)
|
| 124 |
+
return True
|
| 125 |
+
except BadSignature:
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
_login_hits: dict[str, list[float]] = {}
|
| 129 |
+
def login_allowed(ip: str) -> bool:
|
| 130 |
+
now = time.time()
|
| 131 |
+
hits = [t for t in _login_hits.get(ip, []) if now - t < 300]
|
| 132 |
+
_login_hits[ip] = hits
|
| 133 |
+
return len(hits) < 8
|
| 134 |
+
|
| 135 |
+
# ═══════════════════════════ Persistência de conversas ═══════════════════════════
|
| 136 |
+
def _safe_id(cid: str) -> str:
|
| 137 |
+
return "".join(c for c in cid if c.isalnum() or c in "-_")[:64]
|
| 138 |
+
|
| 139 |
+
def list_chats() -> list[dict]:
|
| 140 |
+
out = []
|
| 141 |
+
for f in CHATS_DIR.glob("*.json"):
|
| 142 |
+
try:
|
| 143 |
+
d = json.loads(f.read_text())
|
| 144 |
+
out.append({"id": d.get("id", f.stem),
|
| 145 |
+
"title": d.get("title", "Sem título"),
|
| 146 |
+
"updated": d.get("updated", 0)})
|
| 147 |
+
except Exception:
|
| 148 |
+
pass
|
| 149 |
+
out.sort(key=lambda x: x["updated"], reverse=True)
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
def load_chat(cid: str) -> dict | None:
|
| 153 |
+
f = CHATS_DIR / f"{_safe_id(cid)}.json"
|
| 154 |
+
if f.exists():
|
| 155 |
+
try:
|
| 156 |
+
return json.loads(f.read_text())
|
| 157 |
+
except Exception:
|
| 158 |
+
return None
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
def save_chat(cid: str, title: str, messages: list, persona_id=None) -> dict:
|
| 162 |
+
cid = _safe_id(cid) or uuid.uuid4().hex
|
| 163 |
+
data = {"id": cid, "title": title[:120] or "Sem título",
|
| 164 |
+
"updated": time.time(), "messages": messages,
|
| 165 |
+
"persona_id": persona_id}
|
| 166 |
+
(CHATS_DIR / f"{cid}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1))
|
| 167 |
+
return data
|
| 168 |
+
|
| 169 |
+
def delete_chat(cid: str) -> bool:
|
| 170 |
+
f = CHATS_DIR / f"{_safe_id(cid)}.json"
|
| 171 |
+
if f.exists():
|
| 172 |
+
f.unlink()
|
| 173 |
+
return True
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
# ═══════════════════════════ Persistência de personas ═══════════════════════════
|
| 177 |
+
def list_personas() -> list[dict]:
|
| 178 |
+
out = []
|
| 179 |
+
for f in PERSONAS_DIR.glob("*.json"):
|
| 180 |
+
try:
|
| 181 |
+
d = json.loads(f.read_text())
|
| 182 |
+
out.append({"id": d.get("id", f.stem),
|
| 183 |
+
"title": d.get("title", "Sem título"),
|
| 184 |
+
"updated": d.get("updated", 0)})
|
| 185 |
+
except Exception:
|
| 186 |
+
pass
|
| 187 |
+
out.sort(key=lambda x: x["updated"], reverse=True)
|
| 188 |
+
return out
|
| 189 |
+
|
| 190 |
+
def load_persona(pid: str) -> dict | None:
|
| 191 |
+
f = PERSONAS_DIR / f"{_safe_id(pid)}.json"
|
| 192 |
+
if f.exists():
|
| 193 |
+
try:
|
| 194 |
+
return json.loads(f.read_text())
|
| 195 |
+
except Exception:
|
| 196 |
+
return None
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
def save_persona(pid: str, title: str, description: str) -> dict:
|
| 200 |
+
pid = _safe_id(pid) or uuid.uuid4().hex
|
| 201 |
+
data = {"id": pid, "title": title[:120] or "Sem título",
|
| 202 |
+
"description": description, "updated": time.time()}
|
| 203 |
+
(PERSONAS_DIR / f"{pid}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1))
|
| 204 |
+
return data
|
| 205 |
+
|
| 206 |
+
def delete_persona(pid: str) -> bool:
|
| 207 |
+
f = PERSONAS_DIR / f"{_safe_id(pid)}.json"
|
| 208 |
+
if f.exists():
|
| 209 |
+
f.unlink()
|
| 210 |
+
return True
|
| 211 |
+
return False
|
| 212 |
+
|
| 213 |
+
# ═══════════════════════════ AGÊNTICA — agente único, real, em segundo plano ═══════════════════════════
|
| 214 |
+
# Estrutura local:
|
| 215 |
+
# offsellia_data/agent/agent.json -> config do agente
|
| 216 |
+
# offsellia_data/agent/memory/memory.json -> memória própria persistente (tempo real)
|
| 217 |
+
# offsellia_data/agent/reports/*.json -> relatório por ação
|
| 218 |
+
_agent_lock = threading.Lock()
|
| 219 |
+
_agent_thread: threading.Thread | None = None
|
| 220 |
+
_agent_stop = threading.Event()
|
| 221 |
+
_agent_root_secret: str | None = None # senha root em memória apenas (nunca em disco)
|
| 222 |
+
|
| 223 |
+
AGENT_DEFAULT = {
|
| 224 |
+
"exists": False,
|
| 225 |
+
"name": "",
|
| 226 |
+
"function": "", # descrição/objetivo do agente (system prompt agêntico)
|
| 227 |
+
"interval": 300, # período de ação em segundos
|
| 228 |
+
"enabled": False,
|
| 229 |
+
# quais ações reais ele pode tomar:
|
| 230 |
+
"actions": {
|
| 231 |
+
"shell": False, # executar comandos de shell
|
| 232 |
+
"python": False, # executar código python
|
| 233 |
+
"http": False, # requisições HTTP de saída
|
| 234 |
+
"file_write": False, # escrever arquivos no diretório de trabalho
|
| 235 |
+
"llm": True, # raciocinar via llama-server
|
| 236 |
+
},
|
| 237 |
+
# configurações de última geração:
|
| 238 |
+
"workdir": str((AGENT_DIR / "workspace").resolve()),
|
| 239 |
+
"max_steps": 4, # passos de raciocínio/ação por ciclo
|
| 240 |
+
"autonomy": "supervised",# supervised | autonomous
|
| 241 |
+
"allow_root": False, # permissão de agir no sistema com senha root
|
| 242 |
+
"model": "", # modelo opcional para o llama-server
|
| 243 |
+
"temperature": 0.4,
|
| 244 |
+
"memory_window": 40, # nº de entradas de memória injetadas no contexto
|
| 245 |
+
"created": 0,
|
| 246 |
+
"last_run": 0,
|
| 247 |
+
"runs": 0,
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
def _ensure_agent_workspace():
|
| 251 |
+
try:
|
| 252 |
+
Path(AGENT_DEFAULT["workdir"]).mkdir(parents=True, exist_ok=True)
|
| 253 |
+
except Exception:
|
| 254 |
+
pass
|
| 255 |
+
|
| 256 |
+
def load_agent() -> dict:
|
| 257 |
+
if AGENT_CONF_PATH.exists():
|
| 258 |
+
try:
|
| 259 |
+
d = json.loads(AGENT_CONF_PATH.read_text())
|
| 260 |
+
except Exception:
|
| 261 |
+
d = dict(AGENT_DEFAULT)
|
| 262 |
+
else:
|
| 263 |
+
d = dict(AGENT_DEFAULT)
|
| 264 |
+
# preenche campos faltantes
|
| 265 |
+
for k, v in AGENT_DEFAULT.items():
|
| 266 |
+
if k == "actions":
|
| 267 |
+
d.setdefault("actions", {})
|
| 268 |
+
for ak, av in AGENT_DEFAULT["actions"].items():
|
| 269 |
+
d["actions"].setdefault(ak, av)
|
| 270 |
+
else:
|
| 271 |
+
d.setdefault(k, v)
|
| 272 |
+
return d
|
| 273 |
+
|
| 274 |
+
def save_agent(d: dict) -> dict:
|
| 275 |
+
AGENT_CONF_PATH.write_text(json.dumps(d, ensure_ascii=False, indent=1))
|
| 276 |
+
return d
|
| 277 |
+
|
| 278 |
+
def agent_public(d: dict) -> dict:
|
| 279 |
+
# versão exposta à UI (sem segredo root; indica se root está armado em memória)
|
| 280 |
+
out = dict(d)
|
| 281 |
+
out["root_armed"] = bool(_agent_root_secret)
|
| 282 |
+
out["running"] = bool(_agent_thread and _agent_thread.is_alive())
|
| 283 |
+
return out
|
| 284 |
+
|
| 285 |
+
def load_agent_memory() -> list:
|
| 286 |
+
if AGENT_MEM_PATH.exists():
|
| 287 |
+
try:
|
| 288 |
+
return json.loads(AGENT_MEM_PATH.read_text())
|
| 289 |
+
except Exception:
|
| 290 |
+
return []
|
| 291 |
+
return []
|
| 292 |
+
|
| 293 |
+
def append_agent_memory(entry: dict):
|
| 294 |
+
mem = load_agent_memory()
|
| 295 |
+
entry = {"ts": time.time(), **entry}
|
| 296 |
+
mem.append(entry)
|
| 297 |
+
# mantém memória enxuta em disco (tempo real), preserva relatórios completos à parte
|
| 298 |
+
if len(mem) > 2000:
|
| 299 |
+
mem = mem[-2000:]
|
| 300 |
+
AGENT_MEM_PATH.write_text(json.dumps(mem, ensure_ascii=False, indent=1))
|
| 301 |
+
|
| 302 |
+
def clear_agent_memory():
|
| 303 |
+
AGENT_MEM_PATH.write_text(json.dumps([], ensure_ascii=False, indent=1))
|
| 304 |
+
|
| 305 |
+
def write_agent_report(report: dict) -> str:
|
| 306 |
+
ts = time.strftime("%Y%m%d-%H%M%S", time.localtime())
|
| 307 |
+
rid = f"{ts}-{uuid.uuid4().hex[:6]}"
|
| 308 |
+
report = {"id": rid, "ts": time.time(), **report}
|
| 309 |
+
(AGENT_REPORTS_DIR / f"{rid}.json").write_text(json.dumps(report, ensure_ascii=False, indent=1))
|
| 310 |
+
return rid
|
| 311 |
+
|
| 312 |
+
def list_agent_reports(limit: int = 60) -> list[dict]:
|
| 313 |
+
out = []
|
| 314 |
+
for f in AGENT_REPORTS_DIR.glob("*.json"):
|
| 315 |
+
try:
|
| 316 |
+
d = json.loads(f.read_text())
|
| 317 |
+
out.append({"id": d.get("id", f.stem),
|
| 318 |
+
"ts": d.get("ts", 0),
|
| 319 |
+
"ok": d.get("ok", True),
|
| 320 |
+
"summary": d.get("summary", "")[:160]})
|
| 321 |
+
except Exception:
|
| 322 |
+
pass
|
| 323 |
+
out.sort(key=lambda x: x["ts"], reverse=True)
|
| 324 |
+
return out[:limit]
|
| 325 |
+
|
| 326 |
+
def load_agent_report(rid: str) -> dict | None:
|
| 327 |
+
f = AGENT_REPORTS_DIR / f"{_safe_id(rid)}.json"
|
| 328 |
+
if f.exists():
|
| 329 |
+
try:
|
| 330 |
+
return json.loads(f.read_text())
|
| 331 |
+
except Exception:
|
| 332 |
+
return None
|
| 333 |
+
return None
|
| 334 |
+
|
| 335 |
+
# ---------- execução real de ações ----------
|
| 336 |
+
def _root_prefix(use_root: bool) -> list[str]:
|
| 337 |
+
"""Prefixo de elevação se root permitido e senha armada (Linux/macOS via sudo -S)."""
|
| 338 |
+
if use_root and _agent_root_secret:
|
| 339 |
+
return ["sudo", "-S", "-p", ""]
|
| 340 |
+
return []
|
| 341 |
+
|
| 342 |
+
def _run_shell(cmd: str, agent: dict) -> dict:
|
| 343 |
+
use_root = agent.get("allow_root") and _agent_root_secret
|
| 344 |
+
workdir = agent.get("workdir") or str(AGENT_DIR)
|
| 345 |
+
try:
|
| 346 |
+
if use_root:
|
| 347 |
+
full = _root_prefix(True) + ["/bin/sh", "-c", cmd]
|
| 348 |
+
proc = subprocess.run(full, input=(_agent_root_secret or "") + "\n",
|
| 349 |
+
capture_output=True, text=True, timeout=120, cwd=workdir)
|
| 350 |
+
else:
|
| 351 |
+
proc = subprocess.run(cmd, shell=True, capture_output=True, text=True,
|
| 352 |
+
timeout=120, cwd=workdir)
|
| 353 |
+
return {"action": "shell", "cmd": cmd, "root": bool(use_root),
|
| 354 |
+
"code": proc.returncode,
|
| 355 |
+
"stdout": (proc.stdout or "")[-8000:],
|
| 356 |
+
"stderr": (proc.stderr or "")[-4000:], "ok": proc.returncode == 0}
|
| 357 |
+
except subprocess.TimeoutExpired:
|
| 358 |
+
return {"action": "shell", "cmd": cmd, "ok": False, "error": "timeout"}
|
| 359 |
+
except Exception as e:
|
| 360 |
+
return {"action": "shell", "cmd": cmd, "ok": False, "error": str(e)}
|
| 361 |
+
|
| 362 |
+
def _run_python(code: str, agent: dict) -> dict:
|
| 363 |
+
workdir = agent.get("workdir") or str(AGENT_DIR)
|
| 364 |
+
try:
|
| 365 |
+
proc = subprocess.run([sys.executable, "-c", code], capture_output=True,
|
| 366 |
+
text=True, timeout=120, cwd=workdir)
|
| 367 |
+
return {"action": "python", "code": code[:4000], "rc": proc.returncode,
|
| 368 |
+
"stdout": (proc.stdout or "")[-8000:],
|
| 369 |
+
"stderr": (proc.stderr or "")[-4000:], "ok": proc.returncode == 0}
|
| 370 |
+
except subprocess.TimeoutExpired:
|
| 371 |
+
return {"action": "python", "ok": False, "error": "timeout"}
|
| 372 |
+
except Exception as e:
|
| 373 |
+
return {"action": "python", "ok": False, "error": str(e)}
|
| 374 |
+
|
| 375 |
+
def _run_http(url: str, method: str, body, agent: dict) -> dict:
|
| 376 |
+
try:
|
| 377 |
+
with httpx.Client(timeout=60) as c:
|
| 378 |
+
r = c.request(method or "GET", url,
|
| 379 |
+
content=(json.dumps(body) if isinstance(body, (dict, list)) else body))
|
| 380 |
+
return {"action": "http", "url": url, "method": method or "GET",
|
| 381 |
+
"status": r.status_code, "body": r.text[:8000], "ok": r.is_success}
|
| 382 |
+
except Exception as e:
|
| 383 |
+
return {"action": "http", "url": url, "ok": False, "error": str(e)}
|
| 384 |
+
|
| 385 |
+
def _run_file_write(path: str, content: str, agent: dict) -> dict:
|
| 386 |
+
try:
|
| 387 |
+
base = Path(agent.get("workdir") or str(AGENT_DIR)).resolve()
|
| 388 |
+
target = (base / path).resolve()
|
| 389 |
+
if base not in target.parents and target != base:
|
| 390 |
+
return {"action": "file_write", "path": path, "ok": False,
|
| 391 |
+
"error": "fora do workspace do agente"}
|
| 392 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 393 |
+
target.write_text(content, encoding="utf-8")
|
| 394 |
+
return {"action": "file_write", "path": str(target), "bytes": len(content), "ok": True}
|
| 395 |
+
except Exception as e:
|
| 396 |
+
return {"action": "file_write", "path": path, "ok": False, "error": str(e)}
|
| 397 |
+
|
| 398 |
+
def _llm_complete(messages: list, agent: dict) -> str:
|
| 399 |
+
up = CONF["upstreams"]["llm"].rstrip("/") + "/v1/chat/completions"
|
| 400 |
+
payload = {"messages": messages, "stream": False,
|
| 401 |
+
"temperature": agent.get("temperature", 0.4)}
|
| 402 |
+
if agent.get("model"):
|
| 403 |
+
payload["model"] = agent["model"]
|
| 404 |
+
try:
|
| 405 |
+
with httpx.Client(timeout=300) as c:
|
| 406 |
+
r = c.post(up, json=payload)
|
| 407 |
+
j = r.json()
|
| 408 |
+
return j.get("choices", [{}])[0].get("message", {}).get("content", "") or ""
|
| 409 |
+
except Exception as e:
|
| 410 |
+
return f"[ERRO LLM: {e}]"
|
| 411 |
+
|
| 412 |
+
def _allowed(agent: dict, name: str) -> bool:
|
| 413 |
+
return bool(agent.get("actions", {}).get(name))
|
| 414 |
+
|
| 415 |
+
def _execute_action(act: dict, agent: dict) -> dict:
|
| 416 |
+
t = (act or {}).get("type")
|
| 417 |
+
if t == "shell" and _allowed(agent, "shell"):
|
| 418 |
+
return _run_shell(act.get("cmd", ""), agent)
|
| 419 |
+
if t == "python" and _allowed(agent, "python"):
|
| 420 |
+
return _run_python(act.get("code", ""), agent)
|
| 421 |
+
if t == "http" and _allowed(agent, "http"):
|
| 422 |
+
return _run_http(act.get("url", ""), act.get("method", "GET"), act.get("body"), agent)
|
| 423 |
+
if t == "file_write" and _allowed(agent, "file_write"):
|
| 424 |
+
return _run_file_write(act.get("path", "out.txt"), act.get("content", ""), agent)
|
| 425 |
+
if t == "note":
|
| 426 |
+
return {"action": "note", "text": act.get("text", ""), "ok": True}
|
| 427 |
+
return {"action": t or "desconhecida", "ok": False, "error": "ação não permitida ou inválida"}
|
| 428 |
+
|
| 429 |
+
AGENT_SYS_TEMPLATE = """Você é {name}, um agente autônomo real executando em ciclos em segundo plano.
|
| 430 |
+
Objetivo/Função: {function}
|
| 431 |
+
|
| 432 |
+
Você decide as próximas ações e responde ESTRITAMENTE em JSON, sem markdown, no formato:
|
| 433 |
+
{{"thoughts":"...", "actions":[{{"type":"shell|python|http|file_write|note", ...}}], "summary":"resumo curto do ciclo", "done": true|false}}
|
| 434 |
+
|
| 435 |
+
Campos por tipo de ação:
|
| 436 |
+
- shell: {{"type":"shell","cmd":"..."}}
|
| 437 |
+
- python: {{"type":"python","code":"..."}}
|
| 438 |
+
- http: {{"type":"http","url":"...","method":"GET|POST","body":{{}}}}
|
| 439 |
+
- file_write: {{"type":"file_write","path":"relativo-ao-workspace","content":"..."}}
|
| 440 |
+
- note: {{"type":"note","text":"observação a guardar na memória"}}
|
| 441 |
+
|
| 442 |
+
Ações habilitadas neste agente: {allowed}
|
| 443 |
+
Permissão root no sistema: {root}
|
| 444 |
+
Use somente ações habilitadas. Seja objetivo. Responda apenas o JSON."""
|
| 445 |
+
|
| 446 |
+
def _build_agent_messages(agent: dict) -> list:
|
| 447 |
+
allowed = [k for k, v in agent.get("actions", {}).items() if v]
|
| 448 |
+
sys = AGENT_SYS_TEMPLATE.format(
|
| 449 |
+
name=agent.get("name", "Agente"),
|
| 450 |
+
function=agent.get("function", ""),
|
| 451 |
+
allowed=", ".join(allowed) or "nenhuma",
|
| 452 |
+
root=("permitida" if (agent.get("allow_root") and _agent_root_secret) else "negada"),
|
| 453 |
+
)
|
| 454 |
+
mem = load_agent_memory()
|
| 455 |
+
win = agent.get("memory_window", 40)
|
| 456 |
+
recent = mem[-win:] if win else mem
|
| 457 |
+
mem_txt = "\n".join(
|
| 458 |
+
f"[{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(m.get('ts',0)))}] "
|
| 459 |
+
f"{m.get('kind','')}: {json.dumps(m.get('data', m), ensure_ascii=False)[:600]}"
|
| 460 |
+
for m in recent
|
| 461 |
+
)
|
| 462 |
+
user = ("Estado da memória própria (recente):\n" + (mem_txt or "(vazia)") +
|
| 463 |
+
"\n\nInicie ou continue trabalhando em direção ao objetivo. "
|
| 464 |
+
"Decida as próximas ações para este ciclo.")
|
| 465 |
+
return [{"role": "system", "content": sys}, {"role": "user", "content": user}]
|
| 466 |
+
|
| 467 |
+
def _parse_agent_json(text: str) -> dict:
|
| 468 |
+
s = text.strip()
|
| 469 |
+
if s.startswith("```"):
|
| 470 |
+
s = s.strip("`")
|
| 471 |
+
if s[:4].lower() == "json":
|
| 472 |
+
s = s[4:]
|
| 473 |
+
i, j = s.find("{"), s.rfind("}")
|
| 474 |
+
if i >= 0 and j > i:
|
| 475 |
+
s = s[i:j+1]
|
| 476 |
+
try:
|
| 477 |
+
return json.loads(s)
|
| 478 |
+
except Exception:
|
| 479 |
+
return {"thoughts": "", "actions": [], "summary": text[:200], "done": False, "_raw": text[:2000]}
|
| 480 |
+
|
| 481 |
+
def _agent_cycle(agent: dict) -> dict:
|
| 482 |
+
_ensure_agent_workspace()
|
| 483 |
+
cycle_log = {"steps": [], "ok": True}
|
| 484 |
+
plan_text = ""
|
| 485 |
+
if _allowed(agent, "llm"):
|
| 486 |
+
plan_text = _llm_complete(_build_agent_messages(agent), agent)
|
| 487 |
+
else:
|
| 488 |
+
plan_text = '{"actions":[{"type":"note","text":"LLM desabilitado; ciclo sem raciocínio."}],"summary":"ciclo manual","done":false}'
|
| 489 |
+
plan = _parse_agent_json(plan_text)
|
| 490 |
+
cycle_log["plan"] = plan
|
| 491 |
+
append_agent_memory({"kind": "plan", "data": {"thoughts": plan.get("thoughts", ""),
|
| 492 |
+
"summary": plan.get("summary", "")}})
|
| 493 |
+
actions = plan.get("actions", []) or []
|
| 494 |
+
max_steps = max(1, int(agent.get("max_steps", 4)))
|
| 495 |
+
for act in actions[:max_steps]:
|
| 496 |
+
res = _execute_action(act, agent)
|
| 497 |
+
cycle_log["steps"].append({"request": act, "result": res})
|
| 498 |
+
append_agent_memory({"kind": "action", "data": {"req": act, "ok": res.get("ok"),
|
| 499 |
+
"summary": res.get("summary") or res.get("error") or res.get("stdout", "")[:300]}})
|
| 500 |
+
if not res.get("ok", True):
|
| 501 |
+
cycle_log["ok"] = False
|
| 502 |
+
cycle_log["summary"] = plan.get("summary", "")[:300]
|
| 503 |
+
cycle_log["done"] = bool(plan.get("done"))
|
| 504 |
+
return cycle_log
|
| 505 |
+
|
| 506 |
+
def _agent_loop():
|
| 507 |
+
while not _agent_stop.is_set():
|
| 508 |
+
agent = load_agent()
|
| 509 |
+
if not (agent.get("exists") and agent.get("enabled")):
|
| 510 |
+
break
|
| 511 |
+
try:
|
| 512 |
+
log = _agent_cycle(agent)
|
| 513 |
+
rid = write_agent_report({"agent": agent.get("name"),
|
| 514 |
+
"ok": log.get("ok", True),
|
| 515 |
+
"summary": log.get("summary", ""),
|
| 516 |
+
"cycle": log})
|
| 517 |
+
agent = load_agent()
|
| 518 |
+
agent["last_run"] = time.time()
|
| 519 |
+
agent["runs"] = int(agent.get("runs", 0)) + 1
|
| 520 |
+
save_agent(agent)
|
| 521 |
+
append_agent_memory({"kind": "cycle_done", "data": {"report": rid,
|
| 522 |
+
"ok": log.get("ok", True)}})
|
| 523 |
+
except Exception as e:
|
| 524 |
+
write_agent_report({"agent": agent.get("name"), "ok": False,
|
| 525 |
+
"summary": f"erro no ciclo: {e}", "error": str(e)})
|
| 526 |
+
interval = max(5, int(load_agent().get("interval", 300)))
|
| 527 |
+
# espera responsiva ao stop
|
| 528 |
+
waited = 0
|
| 529 |
+
while waited < interval and not _agent_stop.is_set():
|
| 530 |
+
time.sleep(1)
|
| 531 |
+
waited += 1
|
| 532 |
+
|
| 533 |
+
def start_agent_thread() -> bool:
|
| 534 |
+
global _agent_thread, _agent_stop
|
| 535 |
+
with _agent_lock:
|
| 536 |
+
if _agent_thread and _agent_thread.is_alive():
|
| 537 |
+
return True
|
| 538 |
+
_agent_stop = threading.Event()
|
| 539 |
+
_agent_thread = threading.Thread(target=_agent_loop, daemon=True)
|
| 540 |
+
_agent_thread.start()
|
| 541 |
+
return True
|
| 542 |
+
|
| 543 |
+
def stop_agent_thread():
|
| 544 |
+
global _agent_thread
|
| 545 |
+
with _agent_lock:
|
| 546 |
+
_agent_stop.set()
|
| 547 |
+
_agent_thread = None
|
| 548 |
+
|
| 549 |
+
# ═══════════════════════════ Extração de texto (.txt / .pdf) ═══════════════════════════
|
| 550 |
+
def extract_pdf(raw: bytes) -> str:
|
| 551 |
+
try:
|
| 552 |
+
from pypdf import PdfReader
|
| 553 |
+
except ImportError:
|
| 554 |
+
return "[ERRO: pypdf não instalado — pip install pypdf]"
|
| 555 |
+
import io
|
| 556 |
+
try:
|
| 557 |
+
reader = PdfReader(io.BytesIO(raw))
|
| 558 |
+
parts = []
|
| 559 |
+
for i, page in enumerate(reader.pages):
|
| 560 |
+
txt = page.extract_text() or ""
|
| 561 |
+
parts.append(f"\n--- [página {i+1}] ---\n{txt.strip()}")
|
| 562 |
+
return "\n".join(parts).strip()
|
| 563 |
+
except Exception as e:
|
| 564 |
+
return f"[ERRO ao ler PDF: {e}]"
|
| 565 |
+
|
| 566 |
+
def extract_txt(raw: bytes) -> str:
|
| 567 |
+
for enc in ("utf-8", "latin-1", "cp1252"):
|
| 568 |
+
try:
|
| 569 |
+
return raw.decode(enc)
|
| 570 |
+
except UnicodeDecodeError:
|
| 571 |
+
continue
|
| 572 |
+
return raw.decode("utf-8", errors="replace")
|
| 573 |
+
|
| 574 |
+
# ═══════════════════════════ TLS autoassinado ═══════════════════════════
|
| 575 |
+
# [UPGRADE] descobre IPs locais (sem tráfego externo) p/ incluir no SAN do cert.
|
| 576 |
+
def _local_ips() -> set[str]:
|
| 577 |
+
ips: set[str] = set()
|
| 578 |
+
try:
|
| 579 |
+
import socket
|
| 580 |
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
| 581 |
+
try:
|
| 582 |
+
s.connect(("10.255.255.255", 1)) # não envia pacote; só resolve a rota local
|
| 583 |
+
ips.add(s.getsockname()[0])
|
| 584 |
+
except Exception:
|
| 585 |
+
pass
|
| 586 |
+
finally:
|
| 587 |
+
s.close()
|
| 588 |
+
except Exception:
|
| 589 |
+
pass
|
| 590 |
+
try:
|
| 591 |
+
import socket
|
| 592 |
+
for info in socket.getaddrinfo(socket.gethostname(), None):
|
| 593 |
+
ip = info[4][0]
|
| 594 |
+
if ":" not in ip: # mantém só IPv4 por simplicidade
|
| 595 |
+
ips.add(ip)
|
| 596 |
+
except Exception:
|
| 597 |
+
pass
|
| 598 |
+
return ips
|
| 599 |
+
|
| 600 |
+
def ensure_tls():
|
| 601 |
+
cert = DATA_DIR / "tls_cert.pem"
|
| 602 |
+
key = DATA_DIR / "tls_key.pem"
|
| 603 |
+
if cert.exists() and key.exists():
|
| 604 |
+
return str(cert), str(key)
|
| 605 |
+
try:
|
| 606 |
+
from cryptography import x509
|
| 607 |
+
from cryptography.x509.oid import NameOID
|
| 608 |
+
from cryptography.hazmat.primitives import hashes, serialization
|
| 609 |
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
| 610 |
+
import datetime
|
| 611 |
+
k = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
| 612 |
+
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "offsellia.local")])
|
| 613 |
+
# [UPGRADE] SAN ampliado: localhost + 127.0.0.1 + IPs LAN + gateway do hotspot (10.42.0.1).
|
| 614 |
+
san_entries = [
|
| 615 |
+
x509.DNSName("localhost"),
|
| 616 |
+
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
|
| 617 |
+
]
|
| 618 |
+
extra = set(_local_ips())
|
| 619 |
+
extra.add("10.42.0.1") # hotspot SSID kernel-local
|
| 620 |
+
for ip in sorted(extra):
|
| 621 |
+
try:
|
| 622 |
+
san_entries.append(x509.IPAddress(ipaddress.ip_address(ip)))
|
| 623 |
+
except Exception:
|
| 624 |
+
pass
|
| 625 |
+
san = x509.SubjectAlternativeName(san_entries)
|
| 626 |
+
now = datetime.datetime.now(datetime.timezone.utc)
|
| 627 |
+
cert_obj = (x509.CertificateBuilder()
|
| 628 |
+
.subject_name(name).issuer_name(name).public_key(k.public_key())
|
| 629 |
+
.serial_number(x509.random_serial_number())
|
| 630 |
+
.not_valid_before(now)
|
| 631 |
+
.not_valid_after(now + datetime.timedelta(days=3650))
|
| 632 |
+
.add_extension(san, critical=False)
|
| 633 |
+
.sign(k, hashes.SHA256()))
|
| 634 |
+
key.write_bytes(k.private_bytes(serialization.Encoding.PEM,
|
| 635 |
+
serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()))
|
| 636 |
+
cert.write_bytes(cert_obj.public_bytes(serialization.Encoding.PEM))
|
| 637 |
+
print(f"[{KERNEL_NAME}] TLS gerado: {cert}")
|
| 638 |
+
print(f"[{KERNEL_NAME}] SAN: localhost, 127.0.0.1, {', '.join(sorted(extra))}")
|
| 639 |
+
return str(cert), str(key)
|
| 640 |
+
except ImportError:
|
| 641 |
+
print(f"[{KERNEL_NAME}] AVISO: 'cryptography' ausente — HTTP. pip install cryptography")
|
| 642 |
+
return None
|
| 643 |
+
|
| 644 |
+
# ═══════════════════════════ App + middleware ═══════════════════════════
|
| 645 |
+
@asynccontextmanager
|
| 646 |
+
async def lifespan(app: FastAPI):
|
| 647 |
+
app.state.client = httpx.AsyncClient(timeout=None)
|
| 648 |
+
print(f"[{KERNEL_NAME}] Kernel ativo em {CONF['bind']}:{CONF['port']}")
|
| 649 |
+
# retoma agente se estava habilitado
|
| 650 |
+
ag = load_agent()
|
| 651 |
+
if ag.get("exists") and ag.get("enabled"):
|
| 652 |
+
start_agent_thread()
|
| 653 |
+
print(f"[{KERNEL_NAME}] Agente '{ag.get('name')}' retomado em segundo plano.")
|
| 654 |
+
yield
|
| 655 |
+
stop_agent_thread()
|
| 656 |
+
await app.state.client.aclose()
|
| 657 |
+
|
| 658 |
+
app = FastAPI(title=f"{KERNEL_NAME} Kernel", lifespan=lifespan, docs_url=None, redoc_url=None)
|
| 659 |
+
|
| 660 |
+
@app.middleware("http")
|
| 661 |
+
async def gate(request: Request, call_next):
|
| 662 |
+
p = request.url.path
|
| 663 |
+
if p == "/login" or p.startswith("/static"):
|
| 664 |
+
return await call_next(request)
|
| 665 |
+
if not valid_session(request):
|
| 666 |
+
if p.startswith(("/v1", "/api", "/proxy")):
|
| 667 |
+
return JSONResponse({"error": "unauthorized"}, status_code=401)
|
| 668 |
+
return RedirectResponse("/login")
|
| 669 |
+
resp = await call_next(request)
|
| 670 |
+
resp.headers["X-Content-Type-Options"] = "nosniff"
|
| 671 |
+
resp.headers["X-Frame-Options"] = "DENY"
|
| 672 |
+
resp.headers["Referrer-Policy"] = "no-referrer"
|
| 673 |
+
return resp
|
| 674 |
+
|
| 675 |
+
# ═══════════════════════════ Login ═══════════════════════════
|
| 676 |
+
LOGIN_HTML = """<!doctype html><html><head><meta charset=utf-8>
|
| 677 |
+
<meta name=viewport content="width=device-width,initial-scale=1">
|
| 678 |
+
<title>ΩFFΣLLIα</title><style>
|
| 679 |
+
*{box-sizing:border-box;font-family:system-ui,sans-serif}
|
| 680 |
+
body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;
|
| 681 |
+
background:radial-gradient(1200px 600px at 50% -10%,#15151f,#0a0a0f);color:#e8e8ea}
|
| 682 |
+
.card{background:#16161d;padding:40px;border-radius:18px;width:340px;
|
| 683 |
+
box-shadow:0 8px 50px #000a;border:1px solid #26262e}
|
| 684 |
+
h1{font-size:30px;margin:0 0 4px;letter-spacing:1px;
|
| 685 |
+
background:linear-gradient(90deg,#fff,#9aa7ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 686 |
+
p{color:#8a8a93;margin:0 0 24px;font-size:13px}
|
| 687 |
+
input{width:100%;padding:12px 14px;margin:8px 0;background:#0e0e14;
|
| 688 |
+
border:1px solid #2a2a33;border-radius:10px;color:#fff;font-size:15px}
|
| 689 |
+
button{width:100%;padding:12px;margin-top:14px;background:#fff;color:#000;
|
| 690 |
+
border:0;border-radius:10px;font-size:15px;font-weight:600;cursor:pointer}
|
| 691 |
+
.err{color:#ff6b6b;font-size:13px;min-height:18px;margin-top:8px}
|
| 692 |
+
</style></head><body><form class=card method=post action=/login>
|
| 693 |
+
<h1>ΩFFΣLLIα</h1><p>Kernel — acesso restrito</p>
|
| 694 |
+
<input name=password type=password placeholder=Senha autofocus required>
|
| 695 |
+
<button>Entrar</button><div class=err>__ERR__</div>
|
| 696 |
+
</form></body></html>"""
|
| 697 |
+
|
| 698 |
+
@app.get("/login", response_class=HTMLResponse)
|
| 699 |
+
async def login_page():
|
| 700 |
+
return LOGIN_HTML.replace("__ERR__", "")
|
| 701 |
+
|
| 702 |
+
@app.post("/login")
|
| 703 |
+
async def login_submit(request: Request, password: str = Form(...)):
|
| 704 |
+
ip = request.client.host if request.client else "?"
|
| 705 |
+
if not login_allowed(ip):
|
| 706 |
+
return HTMLResponse(LOGIN_HTML.replace("__ERR__", "Muitas tentativas. Aguarde."), status_code=429)
|
| 707 |
+
_login_hits.setdefault(ip, []).append(time.time())
|
| 708 |
+
if argon2.verify(password, CONF["pwd_hash"]):
|
| 709 |
+
_login_hits[ip] = []
|
| 710 |
+
r = RedirectResponse("/", status_code=303)
|
| 711 |
+
r.set_cookie(COOKIE, issue_token(), max_age=SESSION_MAX_AGE,
|
| 712 |
+
httponly=True, samesite="lax")
|
| 713 |
+
return r
|
| 714 |
+
return HTMLResponse(LOGIN_HTML.replace("__ERR__", "Senha incorreta."), status_code=401)
|
| 715 |
+
|
| 716 |
+
@app.get("/logout")
|
| 717 |
+
async def logout():
|
| 718 |
+
r = RedirectResponse("/login")
|
| 719 |
+
r.delete_cookie(COOKIE)
|
| 720 |
+
return r
|
| 721 |
+
|
| 722 |
+
# ═══════════════════════════ Estáticos ═══════════════════════════
|
| 723 |
+
@app.get("/static/{path:path}")
|
| 724 |
+
async def serve_static(path: str):
|
| 725 |
+
f = (STATIC_DIR / path).resolve()
|
| 726 |
+
if STATIC_DIR.resolve() in f.parents and f.exists() and f.is_file():
|
| 727 |
+
return FileResponse(f)
|
| 728 |
+
return JSONResponse({"error": "not found"}, status_code=404)
|
| 729 |
+
|
| 730 |
+
@app.get("/api/config")
|
| 731 |
+
async def api_config():
|
| 732 |
+
return {"n_ctx": CONF.get("n_ctx", 32768), "kernel": KERNEL_NAME}
|
| 733 |
+
|
| 734 |
+
# [UPGRADE] /api/health — ping no único upstream LLM (:8080) para a sidebar.
|
| 735 |
+
@app.get("/api/health")
|
| 736 |
+
async def api_health():
|
| 737 |
+
client: httpx.AsyncClient = app.state.client
|
| 738 |
+
base = CONF["upstreams"]["llm"]
|
| 739 |
+
try:
|
| 740 |
+
r = await client.get(base.rstrip("/") + "/health", timeout=3)
|
| 741 |
+
llm = {"configured": True, "online": r.status_code == 200,
|
| 742 |
+
"status": r.status_code, "url": base}
|
| 743 |
+
except Exception:
|
| 744 |
+
llm = {"configured": True, "online": False, "url": base}
|
| 745 |
+
return {"llm": llm}
|
| 746 |
+
|
| 747 |
+
# ═══════════════════════════ Upload / extração ═══════════════════════════
|
| 748 |
+
@app.post("/api/extract")
|
| 749 |
+
async def api_extract(request: Request):
|
| 750 |
+
form = await request.form()
|
| 751 |
+
up = form.get("file")
|
| 752 |
+
if up is None:
|
| 753 |
+
return JSONResponse({"error": "sem arquivo"}, status_code=400)
|
| 754 |
+
raw = await up.read()
|
| 755 |
+
name = (getattr(up, "filename", "") or "").lower()
|
| 756 |
+
if name.endswith(".pdf") or raw[:5] == b"%PDF-":
|
| 757 |
+
text = extract_pdf(raw)
|
| 758 |
+
else:
|
| 759 |
+
text = extract_txt(raw)
|
| 760 |
+
return JSONResponse({"filename": getattr(up, "filename", "arquivo"),
|
| 761 |
+
"chars": len(text), "text": text})
|
| 762 |
+
|
| 763 |
+
# ═══════════════════════════ Conversas (CRUD) ═══════════════════════════
|
| 764 |
+
@app.get("/api/chats")
|
| 765 |
+
async def api_chats():
|
| 766 |
+
return {"chats": list_chats()}
|
| 767 |
+
|
| 768 |
+
@app.get("/api/chats/{cid}")
|
| 769 |
+
async def api_chat_get(cid: str):
|
| 770 |
+
d = load_chat(cid)
|
| 771 |
+
if not d:
|
| 772 |
+
return JSONResponse({"error": "não encontrada"}, status_code=404)
|
| 773 |
+
return d
|
| 774 |
+
|
| 775 |
+
@app.post("/api/chats/{cid}")
|
| 776 |
+
async def api_chat_save(cid: str, request: Request):
|
| 777 |
+
body = await request.json()
|
| 778 |
+
d = save_chat(cid, body.get("title", ""), body.get("messages", []),
|
| 779 |
+
body.get("persona_id"))
|
| 780 |
+
return d
|
| 781 |
+
|
| 782 |
+
@app.delete("/api/chats/{cid}")
|
| 783 |
+
async def api_chat_delete(cid: str):
|
| 784 |
+
return {"deleted": delete_chat(cid)}
|
| 785 |
+
|
| 786 |
+
# ═══════════════════════════ Personas (CRUD) ═══════════════════════════
|
| 787 |
+
@app.get("/api/personas")
|
| 788 |
+
async def api_personas():
|
| 789 |
+
return {"personas": list_personas()}
|
| 790 |
+
|
| 791 |
+
@app.get("/api/personas/{pid}")
|
| 792 |
+
async def api_persona_get(pid: str):
|
| 793 |
+
d = load_persona(pid)
|
| 794 |
+
if not d:
|
| 795 |
+
return JSONResponse({"error": "não encontrada"}, status_code=404)
|
| 796 |
+
return d
|
| 797 |
+
|
| 798 |
+
@app.post("/api/personas/{pid}")
|
| 799 |
+
async def api_persona_save(pid: str, request: Request):
|
| 800 |
+
body = await request.json()
|
| 801 |
+
d = save_persona(pid, body.get("title", ""), body.get("description", ""))
|
| 802 |
+
return d
|
| 803 |
+
|
| 804 |
+
@app.delete("/api/personas/{pid}")
|
| 805 |
+
async def api_persona_delete(pid: str):
|
| 806 |
+
return {"deleted": delete_persona(pid)}
|
| 807 |
+
|
| 808 |
+
# ═══════════════════════════ AGÊNTICA (CRUD + controle) ═══════════════════════════
|
| 809 |
+
@app.get("/api/agent")
|
| 810 |
+
async def api_agent_get():
|
| 811 |
+
return agent_public(load_agent())
|
| 812 |
+
|
| 813 |
+
@app.post("/api/agent")
|
| 814 |
+
async def api_agent_save(request: Request):
|
| 815 |
+
body = await request.json()
|
| 816 |
+
cur = load_agent()
|
| 817 |
+
if cur.get("exists") and not body.get("_overwrite"):
|
| 818 |
+
# já existe: atualiza o único agente (nunca cria um segundo)
|
| 819 |
+
pass
|
| 820 |
+
new = dict(cur)
|
| 821 |
+
new["exists"] = True
|
| 822 |
+
if not new.get("created"):
|
| 823 |
+
new["created"] = time.time()
|
| 824 |
+
for k in ("name", "function", "interval", "max_steps", "autonomy",
|
| 825 |
+
"model", "temperature", "memory_window", "workdir", "allow_root"):
|
| 826 |
+
if k in body:
|
| 827 |
+
new[k] = body[k]
|
| 828 |
+
if "actions" in body and isinstance(body["actions"], dict):
|
| 829 |
+
acts = dict(AGENT_DEFAULT["actions"])
|
| 830 |
+
acts.update(new.get("actions", {}))
|
| 831 |
+
for ak in AGENT_DEFAULT["actions"]:
|
| 832 |
+
if ak in body["actions"]:
|
| 833 |
+
acts[ak] = bool(body["actions"][ak])
|
| 834 |
+
new["actions"] = acts
|
| 835 |
+
# normalizações
|
| 836 |
+
try: new["interval"] = max(5, int(new.get("interval", 300)))
|
| 837 |
+
except Exception: new["interval"] = 300
|
| 838 |
+
try: new["max_steps"] = max(1, int(new.get("max_steps", 4)))
|
| 839 |
+
except Exception: new["max_steps"] = 4
|
| 840 |
+
try: new["memory_window"] = max(0, int(new.get("memory_window", 40)))
|
| 841 |
+
except Exception: new["memory_window"] = 40
|
| 842 |
+
save_agent(new)
|
| 843 |
+
_ensure_agent_workspace()
|
| 844 |
+
return agent_public(new)
|
| 845 |
+
|
| 846 |
+
@app.delete("/api/agent")
|
| 847 |
+
async def api_agent_delete():
|
| 848 |
+
global _agent_root_secret
|
| 849 |
+
stop_agent_thread()
|
| 850 |
+
_agent_root_secret = None
|
| 851 |
+
save_agent(dict(AGENT_DEFAULT))
|
| 852 |
+
return {"deleted": True}
|
| 853 |
+
|
| 854 |
+
@app.post("/api/agent/enable")
|
| 855 |
+
async def api_agent_enable(request: Request):
|
| 856 |
+
body = await request.json()
|
| 857 |
+
en = bool(body.get("enabled"))
|
| 858 |
+
ag = load_agent()
|
| 859 |
+
if not ag.get("exists"):
|
| 860 |
+
return JSONResponse({"error": "nenhum agente criado"}, status_code=400)
|
| 861 |
+
ag["enabled"] = en
|
| 862 |
+
save_agent(ag)
|
| 863 |
+
if en:
|
| 864 |
+
start_agent_thread()
|
| 865 |
+
else:
|
| 866 |
+
stop_agent_thread()
|
| 867 |
+
return agent_public(load_agent())
|
| 868 |
+
|
| 869 |
+
@app.post("/api/agent/root")
|
| 870 |
+
async def api_agent_root(request: Request):
|
| 871 |
+
"""Arma/desarma a senha root em memória (nunca gravada em disco)."""
|
| 872 |
+
global _agent_root_secret
|
| 873 |
+
body = await request.json()
|
| 874 |
+
if body.get("clear"):
|
| 875 |
+
_agent_root_secret = None
|
| 876 |
+
return {"root_armed": False}
|
| 877 |
+
pw = body.get("password") or ""
|
| 878 |
+
ag = load_agent()
|
| 879 |
+
if not ag.get("allow_root"):
|
| 880 |
+
return JSONResponse({"error": "permissão root desativada nas configurações do agente"}, status_code=400)
|
| 881 |
+
_agent_root_secret = pw if pw else None
|
| 882 |
+
return {"root_armed": bool(_agent_root_secret)}
|
| 883 |
+
|
| 884 |
+
@app.post("/api/agent/run")
|
| 885 |
+
async def api_agent_run():
|
| 886 |
+
"""Dispara um ciclo imediato (não bloqueia o loop em segundo plano)."""
|
| 887 |
+
ag = load_agent()
|
| 888 |
+
if not ag.get("exists"):
|
| 889 |
+
return JSONResponse({"error": "nenhum agente criado"}, status_code=400)
|
| 890 |
+
def _one():
|
| 891 |
+
try:
|
| 892 |
+
log = _agent_cycle(load_agent())
|
| 893 |
+
rid = write_agent_report({"agent": ag.get("name"), "ok": log.get("ok", True),
|
| 894 |
+
"summary": log.get("summary", ""), "cycle": log})
|
| 895 |
+
a = load_agent(); a["last_run"] = time.time(); a["runs"] = int(a.get("runs", 0)) + 1
|
| 896 |
+
save_agent(a)
|
| 897 |
+
except Exception as e:
|
| 898 |
+
write_agent_report({"agent": ag.get("name"), "ok": False,
|
| 899 |
+
"summary": f"erro: {e}", "error": str(e)})
|
| 900 |
+
threading.Thread(target=_one, daemon=True).start()
|
| 901 |
+
return {"started": True}
|
| 902 |
+
|
| 903 |
+
@app.get("/api/agent/memory")
|
| 904 |
+
async def api_agent_memory():
|
| 905 |
+
mem = load_agent_memory()
|
| 906 |
+
return {"memory": mem[-200:]}
|
| 907 |
+
|
| 908 |
+
@app.delete("/api/agent/memory")
|
| 909 |
+
async def api_agent_memory_clear():
|
| 910 |
+
clear_agent_memory()
|
| 911 |
+
return {"cleared": True}
|
| 912 |
+
|
| 913 |
+
@app.get("/api/agent/reports")
|
| 914 |
+
async def api_agent_reports():
|
| 915 |
+
return {"reports": list_agent_reports()}
|
| 916 |
+
|
| 917 |
+
@app.get("/api/agent/reports/{rid}")
|
| 918 |
+
async def api_agent_report_get(rid: str):
|
| 919 |
+
d = load_agent_report(rid)
|
| 920 |
+
if not d:
|
| 921 |
+
return JSONResponse({"error": "não encontrado"}, status_code=404)
|
| 922 |
+
return d
|
| 923 |
+
|
| 924 |
+
# ═══════════════════════════ Token count (proxy p/ llama-server /tokenize) ═══════════════════════════
|
| 925 |
+
@app.post("/api/tokenize")
|
| 926 |
+
async def api_tokenize(request: Request):
|
| 927 |
+
body = await request.body()
|
| 928 |
+
up = CONF["upstreams"]["llm"].rstrip("/") + "/tokenize"
|
| 929 |
+
try:
|
| 930 |
+
r = await app.state.client.post(up, content=body,
|
| 931 |
+
headers={"content-type": "application/json"}, timeout=30)
|
| 932 |
+
return Response(content=r.content, status_code=r.status_code,
|
| 933 |
+
media_type=r.headers.get("content-type"))
|
| 934 |
+
except httpx.ConnectError:
|
| 935 |
+
return JSONResponse({"error": "llama-server offline"}, status_code=502)
|
| 936 |
+
|
| 937 |
+
# ═══════════════════════════ UI ═══════════════════════════
|
| 938 |
+
UI_HTML = r"""<!doctype html><html lang=pt-br><head><meta charset=utf-8>
|
| 939 |
+
<meta name=viewport content="width=device-width,initial-scale=1,viewport-fit=cover"><title>ΩFFΣLLIα</title>
|
| 940 |
+
|
| 941 |
+
<!-- Assets locais (offline). Substitua por CDN se preferir:
|
| 942 |
+
https://cdn.jsdelivr.net/npm/marked/marked.min.js
|
| 943 |
+
https://cdn.jsdelivr.net/npm/katex/dist/katex.min.css
|
| 944 |
+
https://cdn.jsdelivr.net/npm/katex/dist/katex.min.js
|
| 945 |
+
https://cdn.jsdelivr.net/npm/katex/dist/contrib/auto-render.min.js
|
| 946 |
+
https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/highlight.min.js
|
| 947 |
+
https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/github-dark.min.css
|
| 948 |
+
-->
|
| 949 |
+
<link rel="stylesheet" href="/static/katex.min.css">
|
| 950 |
+
<link rel="stylesheet" href="/static/github-dark.min.css">
|
| 951 |
+
<script src="/static/marked.min.js"></script>
|
| 952 |
+
<script src="/static/katex.min.js"></script>
|
| 953 |
+
<script src="/static/auto-render.min.js"></script>
|
| 954 |
+
<script src="/static/highlight.min.js"></script>
|
| 955 |
+
<style>
|
| 956 |
+
:root{--bg:#0a0a0f;--panel:#0e0e14;--panel2:#16161d;--bd:#1e1e26;--bd2:#26262e;--fg:#e8e8ea;--mut:#7a7a83;--acc:#6d83ff}
|
| 957 |
+
*{box-sizing:border-box;font-family:system-ui,-apple-system,sans-serif}
|
| 958 |
+
html,body{height:100%}
|
| 959 |
+
body{margin:0;height:100dvh;display:flex;background:var(--bg);color:var(--fg);overflow:hidden}
|
| 960 |
+
.side{width:268px;background:var(--panel);border-right:1px solid var(--bd);padding:16px 12px;display:flex;flex-direction:column;gap:6px;flex:none}
|
| 961 |
+
.side h1{font-size:22px;letter-spacing:1px;margin:6px 8px 14px;
|
| 962 |
+
background:linear-gradient(90deg,#fff,#9aa7ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 963 |
+
.btn-new{padding:11px 12px;border-radius:10px;cursor:pointer;color:var(--fg);font-size:14px;
|
| 964 |
+
border:1px solid var(--bd2);background:#13131a;text-align:left}
|
| 965 |
+
.btn-new:hover{background:#1a1a22}
|
| 966 |
+
.seclbl{font-size:11px;letter-spacing:1px;text-transform:uppercase;color:#5a5a63;margin:14px 8px 4px;display:flex;align-items:center;justify-content:space-between}
|
| 967 |
+
.seclbl .add{cursor:pointer;color:#9aa7ff;font-size:15px;line-height:1}
|
| 968 |
+
.seclbl .add:hover{color:#fff}
|
| 969 |
+
.clist{overflow:auto;display:flex;flex-direction:column;gap:3px}
|
| 970 |
+
.clist.chats{flex:1;min-height:60px}
|
| 971 |
+
.clist.personas{max-height:24vh}
|
| 972 |
+
.clist.agentic{max-height:30vh}
|
| 973 |
+
.citem{display:flex;align-items:center;gap:6px;padding:9px 10px;border-radius:9px;cursor:pointer;color:#c7c7cf;font-size:13px}
|
| 974 |
+
.citem:hover{background:#15151d}.citem.active{background:#1c1c26}
|
| 975 |
+
.citem .t{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 976 |
+
.citem .del{opacity:0;color:#ff6b6b;font-size:15px;flex:none;border:0;background:none;cursor:pointer}
|
| 977 |
+
.citem:hover .del{opacity:.7}.citem .del:hover{opacity:1}
|
| 978 |
+
.citem.persona.active{background:#1c2436;border:1px solid #2c3a5c}
|
| 979 |
+
.citem.agent{background:#161a2c;border:1px solid #2c3a5c}
|
| 980 |
+
.citem.agent.on{background:#16261c;border:1px solid #2c5c3a}
|
| 981 |
+
.citem.agent .dot{width:8px;height:8px;border-radius:50%;background:#777;flex:none}
|
| 982 |
+
.citem.agent.on .dot{background:#4ade80;box-shadow:0 0 8px #4ade80}
|
| 983 |
+
.agent-empty{font-size:12px;color:#6a6a73;padding:6px 10px}
|
| 984 |
+
/* [UPGRADE] pill de saúde do upstream */
|
| 985 |
+
.hpill{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--mut);font-family:ui-monospace,monospace;cursor:default}
|
| 986 |
+
.hpill .hdot{width:8px;height:8px;border-radius:50%;background:#777;transition:background .2s}
|
| 987 |
+
.hpill.on .hdot{background:#4ade80;box-shadow:0 0 6px #4ade80}
|
| 988 |
+
.hpill.off .hdot{background:#ff6b6b}
|
| 989 |
+
.hpill.na .hdot{background:#444}
|
| 990 |
+
.foot{margin-top:auto;border-top:1px solid var(--bd);padding-top:10px}
|
| 991 |
+
.foot a{color:#6a6a73;font-size:12px;text-decoration:none;padding:6px 8px;display:block}
|
| 992 |
+
.foot a:hover{color:#9aa7ff}
|
| 993 |
+
.main{flex:1;display:flex;flex-direction:column;min-width:0;min-height:0}
|
| 994 |
+
.topbar{display:none;align-items:center;gap:10px;padding:10px 12px;border-bottom:1px solid var(--bd);background:var(--panel)}
|
| 995 |
+
.topbar .hamb{width:38px;height:38px;border-radius:9px;border:1px solid var(--bd2);background:#13131a;color:#fff;font-size:18px;cursor:pointer}
|
| 996 |
+
.topbar .tt{font-size:18px;letter-spacing:1px;background:linear-gradient(90deg,#fff,#9aa7ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 997 |
+
.backdrop{display:none;position:fixed;inset:0;background:#0009;z-index:40}
|
| 998 |
+
.hello{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:20px}
|
| 999 |
+
.hello h2{font-size:44px;margin:0;background:linear-gradient(90deg,#fff,#9aa7ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 1000 |
+
.hello p{color:var(--mut)}
|
| 1001 |
+
.personatag{display:none;align-items:center;gap:7px;font-size:12px;color:#9aa7ff;
|
| 1002 |
+
background:#15192a;border:1px solid #2c3a5c;border-radius:9px;padding:7px 12px;margin:10px 12% 0;align-self:flex-start;font-family:ui-monospace,monospace}
|
| 1003 |
+
.personatag .clr{cursor:pointer;color:#ff6b6b;font-weight:700}
|
| 1004 |
+
#log{flex:1;overflow:auto;padding:28px 12%;display:none;overflow-anchor:none}
|
| 1005 |
+
.msg{margin:16px 0;line-height:1.6}.msg.u{text-align:right}
|
| 1006 |
+
.bub{display:inline-block;padding:12px 16px;border-radius:14px;max-width:78%;text-align:left;word-wrap:break-word;overflow-wrap:anywhere}
|
| 1007 |
+
.u .bub{background:linear-gradient(135deg,#2563eb,#3b4fd6)}
|
| 1008 |
+
.a .bub{background:var(--panel2);white-space:normal;max-width:100%}
|
| 1009 |
+
.bub p{margin:.4em 0}.bub pre{background:#0c0c12;border:1px solid var(--bd2);border-radius:10px;padding:12px;overflow:auto;position:relative}
|
| 1010 |
+
.bub code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:13.5px}
|
| 1011 |
+
.bub :not(pre)>code{background:#0c0c12;padding:2px 6px;border-radius:6px;border:1px solid var(--bd2)}
|
| 1012 |
+
.bub table{border-collapse:collapse;margin:.5em 0}.bub th,.bub td{border:1px solid var(--bd2);padding:6px 10px}
|
| 1013 |
+
.copybtn{position:absolute;top:6px;right:6px;font-size:11px;padding:3px 8px;border-radius:6px;border:1px solid var(--bd2);background:#16161d;color:#aaa;cursor:pointer;opacity:0;transition:.15s}
|
| 1014 |
+
pre:hover .copybtn{opacity:1}
|
| 1015 |
+
.respmeta{font-size:11px;color:var(--mut);font-family:ui-monospace,monospace;margin-top:4px}
|
| 1016 |
+
.attach{display:inline-flex;align-items:center;gap:6px;background:#1c1c26;border:1px solid var(--bd2);border-radius:8px;padding:5px 9px;font-size:12px;margin:4px 6px 0 0;color:#c7c7cf}
|
| 1017 |
+
.attach .x{cursor:pointer;color:#ff6b6b;font-weight:700}
|
| 1018 |
+
.bar{padding:12px 12% 18px;border-top:1px solid var(--bd);position:relative}
|
| 1019 |
+
.attachrow{display:flex;flex-wrap:wrap;margin-bottom:6px}
|
| 1020 |
+
.box{display:flex;gap:10px;background:var(--panel2);border:1px solid var(--bd2);border-radius:18px;padding:11px;align-items:flex-end}
|
| 1021 |
+
.plus{width:38px;height:38px;border-radius:50%;border:0;background:#222;color:#fff;font-size:22px;cursor:pointer;flex:none;line-height:1}
|
| 1022 |
+
.plus:hover{background:#2c2c36}
|
| 1023 |
+
.plus.regen{font-size:18px}
|
| 1024 |
+
textarea{flex:1;background:none;border:0;color:#fff;resize:none;font-size:15px;outline:none;max-height:220px;line-height:1.5}
|
| 1025 |
+
.send{width:42px;height:42px;border-radius:50%;border:0;background:#fff;color:#000;font-size:18px;cursor:pointer;flex:none}
|
| 1026 |
+
.send:disabled{opacity:.4;cursor:default}
|
| 1027 |
+
.send[data-mode=stop]{background:#ff6b6b;color:#fff}
|
| 1028 |
+
.statusbar{display:flex;gap:18px;justify-content:center;font-size:11px;color:var(--mut);
|
| 1029 |
+
font-family:ui-monospace,monospace;padding:6px 0 0}
|
| 1030 |
+
.statusbar b{color:#9aa7ff;font-weight:600}
|
| 1031 |
+
.ctxwrap{flex:1;max-width:220px;height:6px;background:#1c1c26;border-radius:4px;overflow:hidden;align-self:center}
|
| 1032 |
+
.ctxfill{height:100%;width:0;background:linear-gradient(90deg,#3b4fd6,#6d83ff);transition:width .2s}
|
| 1033 |
+
.spin{display:inline-block;width:13px;height:13px;border:2px solid #555;border-top-color:#fff;border-radius:50%;animation:r 1s linear infinite;vertical-align:middle}
|
| 1034 |
+
@keyframes r{to{transform:rotate(360deg)}}
|
| 1035 |
+
::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background:#2a2a33;border-radius:5px}
|
| 1036 |
+
.modal{position:fixed;inset:0;background:#000a;display:none;align-items:center;justify-content:center;z-index:50}
|
| 1037 |
+
.modal.open{display:flex}
|
| 1038 |
+
.modalcard{background:var(--panel2);border:1px solid var(--bd2);border-radius:16px;padding:24px;width:min(620px,92vw);max-height:90vh;display:flex;flex-direction:column;gap:12px;box-shadow:0 8px 50px #000a;overflow:auto}
|
| 1039 |
+
.modalcard h3{margin:0;font-size:20px;background:linear-gradient(90deg,#fff,#9aa7ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 1040 |
+
.modalcard label{font-size:12px;color:var(--mut);margin-top:6px}
|
| 1041 |
+
.modalcard input,.modalcard textarea,.modalcard select{width:100%;background:#0e0e14;border:1px solid #2a2a33;border-radius:10px;color:#fff;font-size:14px;padding:11px 13px;outline:none}
|
| 1042 |
+
.modalcard textarea{resize:vertical;min-height:120px;max-height:40vh;line-height:1.5;font-family:ui-monospace,Menlo,Consolas,monospace}
|
| 1043 |
+
.modalrow{display:flex;gap:10px;justify-content:flex-end;margin-top:8px;flex-wrap:wrap}
|
| 1044 |
+
.modalrow button{padding:10px 18px;border-radius:10px;font-size:14px;cursor:pointer;border:1px solid var(--bd2)}
|
| 1045 |
+
.modalrow .cancel{background:#13131a;color:#c7c7cf}
|
| 1046 |
+
.modalrow .save{background:#fff;color:#000;font-weight:600;border:0}
|
| 1047 |
+
.modalrow .save:disabled{opacity:.4;cursor:default}
|
| 1048 |
+
.modalrow .danger{background:#2a1414;color:#ff8a8a;border:1px solid #4a2222}
|
| 1049 |
+
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
| 1050 |
+
.chips{display:flex;flex-wrap:wrap;gap:8px}
|
| 1051 |
+
.chip{display:flex;align-items:center;gap:7px;background:#0e0e14;border:1px solid #2a2a33;border-radius:9px;padding:8px 11px;font-size:13px;cursor:pointer;user-select:none}
|
| 1052 |
+
.chip input{width:auto;margin:0}
|
| 1053 |
+
.tabs{display:flex;gap:6px;border-bottom:1px solid var(--bd2);margin-bottom:4px}
|
| 1054 |
+
.tab{padding:8px 12px;font-size:13px;color:var(--mut);cursor:pointer;border-bottom:2px solid transparent}
|
| 1055 |
+
.tab.active{color:#fff;border-bottom-color:var(--acc)}
|
| 1056 |
+
.tabpane{display:none}.tabpane.active{display:block}
|
| 1057 |
+
.logbox{background:#0c0c12;border:1px solid var(--bd2);border-radius:10px;padding:10px;font-family:ui-monospace,monospace;font-size:12px;max-height:46vh;overflow:auto;white-space:pre-wrap;word-break:break-word}
|
| 1058 |
+
.repitem{padding:8px 10px;border:1px solid var(--bd2);border-radius:9px;margin-bottom:6px;cursor:pointer;font-size:12.5px}
|
| 1059 |
+
.repitem:hover{background:#15151d}
|
| 1060 |
+
.repok{color:#4ade80}.reperr{color:#ff8a8a}
|
| 1061 |
+
.hint{font-size:11px;color:#6a6a73;margin-top:2px}
|
| 1062 |
+
|
| 1063 |
+
/* ===== Responsivo: PC vs Smartphone ===== */
|
| 1064 |
+
@media (min-width:861px){
|
| 1065 |
+
.side{position:relative !important;transform:none !important}
|
| 1066 |
+
}
|
| 1067 |
+
@media (max-width:860px){
|
| 1068 |
+
body{flex-direction:column}
|
| 1069 |
+
.topbar{display:flex}
|
| 1070 |
+
.side{position:fixed;top:0;left:0;height:100dvh;width:84vw;max-width:320px;z-index:45;
|
| 1071 |
+
transform:translateX(-105%);transition:transform .22s ease;box-shadow:0 0 40px #000a}
|
| 1072 |
+
.side.open{transform:translateX(0)}
|
| 1073 |
+
.backdrop.open{display:block}
|
| 1074 |
+
.main{width:100%}
|
| 1075 |
+
#log{padding:16px 14px}
|
| 1076 |
+
.bub{max-width:90%}
|
| 1077 |
+
.personatag{margin:10px 14px 0}
|
| 1078 |
+
.bar{padding:10px 12px calc(12px + env(safe-area-inset-bottom))}
|
| 1079 |
+
.hello h2{font-size:34px}
|
| 1080 |
+
.statusbar{gap:12px;flex-wrap:wrap}
|
| 1081 |
+
.grid2{grid-template-columns:1fr}
|
| 1082 |
+
.modalcard{width:94vw;border-radius:16px;padding:18px;max-height:92dvh}
|
| 1083 |
+
.modalcard textarea{max-height:30vh}
|
| 1084 |
+
}
|
| 1085 |
+
</style></head><body>
|
| 1086 |
+
<div class=backdrop id=backdrop onclick="closeSidebar()"></div>
|
| 1087 |
+
<div class=side id=sidebar>
|
| 1088 |
+
<h1>ΩFFΣLLIα</h1>
|
| 1089 |
+
<button class=btn-new onclick="newChat()">✎ Nova conversa</button>
|
| 1090 |
+
<div class=seclbl>Conversas</div>
|
| 1091 |
+
<div class="clist chats" id=clist></div>
|
| 1092 |
+
<div class=seclbl>Agêntica <span class=add title="Criar/Configurar agente" onclick="openAgentModal()">⚙</span></div>
|
| 1093 |
+
<div class="clist agentic" id=alist></div>
|
| 1094 |
+
<div class=seclbl>Personas <span class=add title="Nova persona" onclick="openPersonaModal()">+</span></div>
|
| 1095 |
+
<div class="clist personas" id=plist></div>
|
| 1096 |
+
<div class=foot>
|
| 1097 |
+
<!-- [UPGRADE] saúde do upstream LLM (:8080) -->
|
| 1098 |
+
<div class=statusbar id=healthbar style="justify-content:flex-start;gap:12px;padding:2px 8px 6px">
|
| 1099 |
+
<span class="hpill na" id=hpill-llm><span class=hdot></span> LLM :8080</span>
|
| 1100 |
+
</div>
|
| 1101 |
+
<div class=statusbar style="justify-content:flex-start;gap:8px;padding:0 8px 6px">
|
| 1102 |
+
<span>ctx <b id=ctxnum>0</b>/<span id=ctxmax>0</span></span>
|
| 1103 |
+
</div>
|
| 1104 |
+
<div class=ctxwrap style="max-width:none;margin:0 8px 8px"><div class=ctxfill id=ctxfill></div></div>
|
| 1105 |
+
<a href="javascript:void(0)" onclick="exportChat()">⤓ Exportar conversa (.md)</a>
|
| 1106 |
+
<a href=/logout>⤿ Sair</a>
|
| 1107 |
+
</div>
|
| 1108 |
+
</div>
|
| 1109 |
+
<div class=main>
|
| 1110 |
+
<div class=topbar>
|
| 1111 |
+
<button class=hamb onclick="openSidebar()">☰</button>
|
| 1112 |
+
<div class=tt>ΩFFΣLLIα</div>
|
| 1113 |
+
</div>
|
| 1114 |
+
<div class=hello id=hello><h2>Hello there</h2><p>Converse, cole código ou injete um .txt / .pdf com o botão +</p></div>
|
| 1115 |
+
<div class=personatag id=personatag><span>● Persona Ativa: <b id=personatagname></b></span><span class=clr title="Remover persona desta conversa" onclick="clearPersona()">✕</span></div>
|
| 1116 |
+
<div id=log></div>
|
| 1117 |
+
<div class=bar>
|
| 1118 |
+
<div class=statusbar id=livebar style="display:none">
|
| 1119 |
+
<span><b id=tpsLive>0</b> tok/s</span>
|
| 1120 |
+
<span><b id=tokLive>0</b> tokens</span>
|
| 1121 |
+
<span><b id=timeLive>0.0</b>s</span>
|
| 1122 |
+
</div>
|
| 1123 |
+
<div class=attachrow id=attachrow></div>
|
| 1124 |
+
<div class=box>
|
| 1125 |
+
<button class=plus onclick="document.getElementById('fileinp').click()" title="Injetar .txt / .pdf">+</button>
|
| 1126 |
+
<!-- [UPGRADE] regenerar última resposta -->
|
| 1127 |
+
<button class="plus regen" id=regenbtn onclick="regen()" title="Regenerar última resposta" style="display:none">↻</button>
|
| 1128 |
+
<input type=file id=fileinp accept=".txt,.md,.pdf,text/plain,application/pdf" multiple style=display:none>
|
| 1129 |
+
<textarea id=inp rows=1 placeholder="Digite uma mensagem..."
|
| 1130 |
+
onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();go()}"
|
| 1131 |
+
oninput="autoGrow(this)"></textarea>
|
| 1132 |
+
<!-- [UPGRADE] botão enviar/parar -->
|
| 1133 |
+
<button class=send id=sendbtn onclick=sendClick() title="Enviar">↑</button>
|
| 1134 |
+
</div>
|
| 1135 |
+
</div>
|
| 1136 |
+
</div>
|
| 1137 |
+
|
| 1138 |
+
<!-- Modal criar persona -->
|
| 1139 |
+
<div class=modal id=personamodal>
|
| 1140 |
+
<div class=modalcard>
|
| 1141 |
+
<h3>Nova Persona</h3>
|
| 1142 |
+
<label>Título Persona</label>
|
| 1143 |
+
<input id=pmtitle placeholder="Ex.: Revisor de código sênior" oninput="pmValidate()">
|
| 1144 |
+
<label>Descrição Persona ativa:</label>
|
| 1145 |
+
<textarea id=pmdesc placeholder="Descreva o comportamento, tom, regras e identidade da persona. Sem limite de caracteres." oninput="pmValidate()"></textarea>
|
| 1146 |
+
<div class=modalrow>
|
| 1147 |
+
<button class=cancel onclick="closePersonaModal()">Cancelar</button>
|
| 1148 |
+
<button class=save id=pmsave onclick="savePersona()" disabled>Salvar</button>
|
| 1149 |
+
</div>
|
| 1150 |
+
</div>
|
| 1151 |
+
</div>
|
| 1152 |
+
|
| 1153 |
+
<!-- Modal Agêntica -->
|
| 1154 |
+
<div class=modal id=agentmodal>
|
| 1155 |
+
<div class=modalcard>
|
| 1156 |
+
<h3>Agêntica — Agente Único</h3>
|
| 1157 |
+
<div class=tabs>
|
| 1158 |
+
<div class="tab active" data-tab=cfg onclick="agentTab('cfg')">Configuração</div>
|
| 1159 |
+
<div class=tab data-tab=mem onclick="agentTab('mem')">Memória</div>
|
| 1160 |
+
<div class=tab data-tab=rep onclick="agentTab('rep')">Relatórios</div>
|
| 1161 |
+
</div>
|
| 1162 |
+
|
| 1163 |
+
<div class="tabpane active" id=tab-cfg>
|
| 1164 |
+
<div class=grid2>
|
| 1165 |
+
<div><label>Nome do agente</label>
|
| 1166 |
+
<input id=agname placeholder="Ex.: Sentinela" oninput="agValidate()"></div>
|
| 1167 |
+
<div><label>Intervalo de ação (segundos)</label>
|
| 1168 |
+
<input id=aginterval type=number min=5 value=300></div>
|
| 1169 |
+
</div>
|
| 1170 |
+
<label>Função / Objetivo (o que ele deve fazer)</label>
|
| 1171 |
+
<textarea id=agfunction placeholder="Descreva a missão real do agente: o que monitorar, o que produzir, regras, limites..." oninput="agValidate()"></textarea>
|
| 1172 |
+
|
| 1173 |
+
<label>Ações reais permitidas</label>
|
| 1174 |
+
<div class=chips id=agactions>
|
| 1175 |
+
<label class=chip><input type=checkbox data-act=shell> Shell</label>
|
| 1176 |
+
<label class=chip><input type=checkbox data-act=python> Python</label>
|
| 1177 |
+
<label class=chip><input type=checkbox data-act=http> HTTP</label>
|
| 1178 |
+
<label class=chip><input type=checkbox data-act=file_write> Escrever arquivo</label>
|
| 1179 |
+
<label class=chip><input type=checkbox data-act=llm checked> Raciocínio (LLM)</label>
|
| 1180 |
+
</div>
|
| 1181 |
+
|
| 1182 |
+
<div class=grid2>
|
| 1183 |
+
<div><label>Passos por ciclo</label><input id=agmaxsteps type=number min=1 value=4></div>
|
| 1184 |
+
<div><label>Janela de memória (entradas)</label><input id=agmemwin type=number min=0 value=40></div>
|
| 1185 |
+
</div>
|
| 1186 |
+
<div class=grid2>
|
| 1187 |
+
<div><label>Autonomia</label>
|
| 1188 |
+
<select id=agautonomy>
|
| 1189 |
+
<option value=supervised>Supervisionado</option>
|
| 1190 |
+
<option value=autonomous>Autônomo</option>
|
| 1191 |
+
</select></div>
|
| 1192 |
+
<div><label>Temperatura</label><input id=agtemp type=number step=0.1 min=0 max=2 value=0.4></div>
|
| 1193 |
+
</div>
|
| 1194 |
+
<div class=grid2>
|
| 1195 |
+
<div><label>Modelo (opcional)</label><input id=agmodel placeholder="deixe vazio p/ padrão do llama-server"></div>
|
| 1196 |
+
<div><label>Workspace (pasta de trabalho)</label><input id=agworkdir placeholder="auto"></div>
|
| 1197 |
+
</div>
|
| 1198 |
+
|
| 1199 |
+
<label class=chip style="margin-top:8px"><input type=checkbox id=agallowroot onchange="agRootToggle()"> Permitir agir em todo o sistema (root)</label>
|
| 1200 |
+
<div id=agrootbox style="display:none">
|
| 1201 |
+
<label>Senha root (mantida só em memória, nunca gravada em disco)</label>
|
| 1202 |
+
<input id=agrootpw type=password placeholder="senha sudo/root">
|
| 1203 |
+
<div class=hint id=agrootstatus>root não armado</div>
|
| 1204 |
+
</div>
|
| 1205 |
+
|
| 1206 |
+
<div class=modalrow>
|
| 1207 |
+
<button class=danger id=agdelete onclick="deleteAgent()" style="display:none">Excluir agente</button>
|
| 1208 |
+
<button class=cancel onclick="closeAgentModal()">Fechar</button>
|
| 1209 |
+
<button class=save id=agtoggle onclick="toggleAgent()" style="display:none">Ativar</button>
|
| 1210 |
+
<button class=save id=agrunnow onclick="runAgentNow()" style="display:none">Rodar agora</button>
|
| 1211 |
+
<button class=save id=agsave onclick="saveAgent()" disabled>Salvar</button>
|
| 1212 |
+
</div>
|
| 1213 |
+
<div class=hint id=aginfo></div>
|
| 1214 |
+
</div>
|
| 1215 |
+
|
| 1216 |
+
<div class=tabpane id=tab-mem>
|
| 1217 |
+
<div class=modalrow style="justify-content:space-between">
|
| 1218 |
+
<span class=hint>Memória própria persistente (tempo real)</span>
|
| 1219 |
+
<button class=danger onclick="clearAgentMemory()">Limpar memória</button>
|
| 1220 |
+
</div>
|
| 1221 |
+
<div class=logbox id=agmemview>(vazia)</div>
|
| 1222 |
+
</div>
|
| 1223 |
+
|
| 1224 |
+
<div class=tabpane id=tab-rep>
|
| 1225 |
+
<div class=hint>Relatórios gerados a cada ação (pasta dedicada)</div>
|
| 1226 |
+
<div id=agreplist></div>
|
| 1227 |
+
<div class=logbox id=agrepview style="display:none"></div>
|
| 1228 |
+
</div>
|
| 1229 |
+
</div>
|
| 1230 |
+
</div>
|
| 1231 |
+
|
| 1232 |
+
<script>
|
| 1233 |
+
// ---------- libs com fallback ----------
|
| 1234 |
+
const MD=(typeof marked!=='undefined')?(t)=>marked.parse(t,{breaks:true,gfm:true}):(t)=>esc(t);
|
| 1235 |
+
function esc(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML;}
|
| 1236 |
+
if(typeof marked!=='undefined'){
|
| 1237 |
+
marked.setOptions({highlight:function(code,lang){
|
| 1238 |
+
try{ if(typeof hljs!=='undefined'){
|
| 1239 |
+
return lang&&hljs.getLanguage(lang)?hljs.highlight(code,{language:lang}).value:hljs.highlightAuto(code).value;
|
| 1240 |
+
}}catch(e){} return esc(code);
|
| 1241 |
+
}});
|
| 1242 |
+
}
|
| 1243 |
+
function renderMath(el){
|
| 1244 |
+
if(typeof renderMathInElement==='undefined')return;
|
| 1245 |
+
try{renderMathInElement(el,{delimiters:[
|
| 1246 |
+
{left:'$$',right:'$$',display:true},{left:'\\[',right:'\\]',display:true},
|
| 1247 |
+
{left:'$',right:'$',display:false},{left:'\\(',right:'\\)',display:false}],
|
| 1248 |
+
throwOnError:false});}catch(e){}
|
| 1249 |
+
}
|
| 1250 |
+
function decorate(el){
|
| 1251 |
+
el.querySelectorAll('pre code').forEach(c=>{
|
| 1252 |
+
try{if(typeof hljs!=='undefined')hljs.highlightElement(c);}catch(e){}
|
| 1253 |
+
const pre=c.parentElement;
|
| 1254 |
+
if(!pre.querySelector('.copybtn')){
|
| 1255 |
+
const b=document.createElement('button');b.className='copybtn';b.textContent='copiar';
|
| 1256 |
+
b.onclick=()=>{navigator.clipboard.writeText(c.textContent);b.textContent='copiado!';setTimeout(()=>b.textContent='copiar',1200);};
|
| 1257 |
+
pre.appendChild(b);
|
| 1258 |
+
}
|
| 1259 |
+
});
|
| 1260 |
+
renderMath(el);
|
| 1261 |
+
}
|
| 1262 |
+
|
| 1263 |
+
// ---------- responsivo / sidebar ----------
|
| 1264 |
+
function openSidebar(){document.getElementById('sidebar').classList.add('open');document.getElementById('backdrop').classList.add('open');}
|
| 1265 |
+
function closeSidebar(){document.getElementById('sidebar').classList.remove('open');document.getElementById('backdrop').classList.remove('open');}
|
| 1266 |
+
function isMobile(){return window.matchMedia('(max-width:860px)').matches;}
|
| 1267 |
+
function maybeCloseSidebar(){if(isMobile())closeSidebar();}
|
| 1268 |
+
|
| 1269 |
+
// ---------- estado ----------
|
| 1270 |
+
let hist=[]; // [{role,content}]
|
| 1271 |
+
let attachments=[]; // [{name,text}]
|
| 1272 |
+
let currentId=null;
|
| 1273 |
+
let N_CTX=32768;
|
| 1274 |
+
let busy=false;
|
| 1275 |
+
let activePersona=null; // {id,title,description} ou null
|
| 1276 |
+
let agentState=null; // estado do agente
|
| 1277 |
+
let abortCtrl=null; // [UPGRADE] controle de aborto do stream
|
| 1278 |
+
|
| 1279 |
+
fetch('/api/config').then(r=>r.json()).then(c=>{N_CTX=c.n_ctx||32768;
|
| 1280 |
+
document.getElementById('ctxmax').textContent=N_CTX;updateCtxBar();});
|
| 1281 |
+
|
| 1282 |
+
function autoGrow(t){t.style.height='auto';t.style.height=Math.min(t.scrollHeight,220)+'px';}
|
| 1283 |
+
function uid(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7);}
|
| 1284 |
+
|
| 1285 |
+
// ---------- [UPGRADE] saúde do upstream ----------
|
| 1286 |
+
function setPill(id,st){
|
| 1287 |
+
const el=document.getElementById(id);if(!el)return;
|
| 1288 |
+
if(!st||!st.configured){el.className='hpill na';el.title='não configurado';return;}
|
| 1289 |
+
const on=!!st.online;
|
| 1290 |
+
el.className='hpill '+(on?'on':'off');
|
| 1291 |
+
el.title=(st.url||'')+' — '+(on?'online':('offline'+(st.status?(' ('+st.status+')'):'')));
|
| 1292 |
+
}
|
| 1293 |
+
async function refreshHealth(){
|
| 1294 |
+
try{
|
| 1295 |
+
const r=await fetch('/api/health');const j=await r.json();
|
| 1296 |
+
setPill('hpill-llm',j.llm);
|
| 1297 |
+
}catch(e){setPill('hpill-llm',null);}
|
| 1298 |
+
}
|
| 1299 |
+
|
| 1300 |
+
// ---------- [UPGRADE] enviar / parar ----------
|
| 1301 |
+
function setBusyUI(b){
|
| 1302 |
+
busy=b;
|
| 1303 |
+
const btn=document.getElementById('sendbtn');
|
| 1304 |
+
if(b){btn.disabled=false;btn.textContent='■';btn.dataset.mode='stop';btn.title='Parar geração';}
|
| 1305 |
+
else{btn.disabled=false;btn.textContent='↑';btn.dataset.mode='';btn.title='Enviar';}
|
| 1306 |
+
updateRegen();
|
| 1307 |
+
}
|
| 1308 |
+
function sendClick(){
|
| 1309 |
+
const b=document.getElementById('sendbtn');
|
| 1310 |
+
if(b.dataset.mode==='stop'){stopGen();}else{go();}
|
| 1311 |
+
}
|
| 1312 |
+
function stopGen(){if(abortCtrl){try{abortCtrl.abort();}catch(e){}}}
|
| 1313 |
+
|
| 1314 |
+
// ---------- [UPGRADE] regenerar ----------
|
| 1315 |
+
function updateRegen(){
|
| 1316 |
+
const b=document.getElementById('regenbtn');
|
| 1317 |
+
const show=!busy&&hist.length&&hist[hist.length-1].role==='assistant';
|
| 1318 |
+
b.style.display=show?'inline-flex':'none';
|
| 1319 |
+
}
|
| 1320 |
+
async function regen(){
|
| 1321 |
+
if(busy)return;
|
| 1322 |
+
if(!(hist.length&&hist[hist.length-1].role==='assistant'))return;
|
| 1323 |
+
hist.pop();
|
| 1324 |
+
const log=document.getElementById('log');
|
| 1325 |
+
const msgs=log.querySelectorAll('.msg.a');
|
| 1326 |
+
if(msgs.length)msgs[msgs.length-1].remove();
|
| 1327 |
+
await stream();
|
| 1328 |
+
}
|
| 1329 |
+
|
| 1330 |
+
// ---------- [UPGRADE] exportar conversa em markdown ----------
|
| 1331 |
+
function exportChat(){
|
| 1332 |
+
if(!hist.length){alert('Conversa vazia.');return;}
|
| 1333 |
+
const titleEl=document.querySelector('#clist .citem.active .t');
|
| 1334 |
+
const title=titleEl?titleEl.textContent:'Conversa';
|
| 1335 |
+
let md='# '+title+'\n\n';
|
| 1336 |
+
if(activePersona)md+='> Persona: '+activePersona.title+'\n\n';
|
| 1337 |
+
hist.forEach(m=>{
|
| 1338 |
+
md+=(m.role==='user'?'## 🧑 Usuário\n\n':'## 🤖 '+(activePersona?activePersona.title:'Assistente')+'\n\n');
|
| 1339 |
+
md+=m.content+'\n\n';
|
| 1340 |
+
});
|
| 1341 |
+
const blob=new Blob([md],{type:'text/markdown;charset=utf-8'});
|
| 1342 |
+
const a=document.createElement('a');
|
| 1343 |
+
a.href=URL.createObjectURL(blob);
|
| 1344 |
+
a.download=(currentId||'conversa')+'.md';
|
| 1345 |
+
document.body.appendChild(a);a.click();a.remove();
|
| 1346 |
+
setTimeout(()=>URL.revokeObjectURL(a.href),2000);
|
| 1347 |
+
maybeCloseSidebar();
|
| 1348 |
+
}
|
| 1349 |
+
|
| 1350 |
+
// ---------- contexto (token count em tempo real) ----------
|
| 1351 |
+
async function countTokens(text){
|
| 1352 |
+
try{const r=await fetch('/api/tokenize',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1353 |
+
body:JSON.stringify({content:text})});
|
| 1354 |
+
const j=await r.json();
|
| 1355 |
+
if(Array.isArray(j.tokens))return j.tokens.length;
|
| 1356 |
+
}catch(e){}
|
| 1357 |
+
return Math.ceil((text||'').length/4); // fallback aproximado
|
| 1358 |
+
}
|
| 1359 |
+
async function updateCtxBar(){
|
| 1360 |
+
const personaTxt=activePersona?activePersona.description:'';
|
| 1361 |
+
const blob=personaTxt+'\n'+hist.map(m=>m.content).join('\n')+attachments.map(a=>a.text).join('\n');
|
| 1362 |
+
const n=await countTokens(blob);
|
| 1363 |
+
document.getElementById('ctxnum').textContent=n;
|
| 1364 |
+
const pct=Math.min(100,Math.round(n/N_CTX*100));
|
| 1365 |
+
document.getElementById('ctxfill').style.width=pct+'%';
|
| 1366 |
+
}
|
| 1367 |
+
|
| 1368 |
+
// ---------- persona ativa (UI) ----------
|
| 1369 |
+
function renderPersonaTag(){
|
| 1370 |
+
const tag=document.getElementById('personatag');
|
| 1371 |
+
if(activePersona){
|
| 1372 |
+
document.getElementById('personatagname').textContent=activePersona.title;
|
| 1373 |
+
tag.style.display='flex';
|
| 1374 |
+
}else{
|
| 1375 |
+
tag.style.display='none';
|
| 1376 |
+
}
|
| 1377 |
+
refreshPersonas();
|
| 1378 |
+
}
|
| 1379 |
+
async function activatePersona(id){
|
| 1380 |
+
const r=await fetch('/api/personas/'+id);if(!r.ok)return;
|
| 1381 |
+
activePersona=await r.json();
|
| 1382 |
+
renderPersonaTag();
|
| 1383 |
+
updateCtxBar();
|
| 1384 |
+
persist();
|
| 1385 |
+
maybeCloseSidebar();
|
| 1386 |
+
}
|
| 1387 |
+
function clearPersona(){
|
| 1388 |
+
activePersona=null;
|
| 1389 |
+
renderPersonaTag();
|
| 1390 |
+
updateCtxBar();
|
| 1391 |
+
persist();
|
| 1392 |
+
}
|
| 1393 |
+
|
| 1394 |
+
// ---------- sidebar / conversas ----------
|
| 1395 |
+
async function refreshChats(){
|
| 1396 |
+
const r=await fetch('/api/chats');const j=await r.json();
|
| 1397 |
+
const c=document.getElementById('clist');c.innerHTML='';
|
| 1398 |
+
(j.chats||[]).forEach(ch=>{
|
| 1399 |
+
const d=document.createElement('div');d.className='citem'+(ch.id===currentId?' active':'');
|
| 1400 |
+
d.innerHTML='<span class=t></span><button class=del title=Excluir>✕</button>';
|
| 1401 |
+
d.querySelector('.t').textContent=ch.title;
|
| 1402 |
+
d.querySelector('.t').onclick=()=>openChat(ch.id);
|
| 1403 |
+
d.querySelector('.del').onclick=(e)=>{e.stopPropagation();delChat(ch.id);};
|
| 1404 |
+
c.appendChild(d);
|
| 1405 |
+
});
|
| 1406 |
+
}
|
| 1407 |
+
async function openChat(id){
|
| 1408 |
+
const r=await fetch('/api/chats/'+id);if(!r.ok)return;
|
| 1409 |
+
const d=await r.json();currentId=d.id;hist=d.messages||[];attachments=[];
|
| 1410 |
+
// restaura persona da conversa, se houver
|
| 1411 |
+
activePersona=null;
|
| 1412 |
+
if(d.persona_id){
|
| 1413 |
+
try{const pr=await fetch('/api/personas/'+d.persona_id);
|
| 1414 |
+
if(pr.ok)activePersona=await pr.json();}catch(e){}
|
| 1415 |
+
}
|
| 1416 |
+
renderAttachments();renderPersonaTag();document.getElementById('log').innerHTML='';
|
| 1417 |
+
document.getElementById('hello').style.display='none';
|
| 1418 |
+
document.getElementById('log').style.display='block';
|
| 1419 |
+
hist.forEach(m=>renderMsg(m.role,m.content));
|
| 1420 |
+
refreshChats();updateCtxBar();updateRegen();maybeCloseSidebar();
|
| 1421 |
+
}
|
| 1422 |
+
async function delChat(id){
|
| 1423 |
+
if(!confirm('Excluir esta conversa?'))return;
|
| 1424 |
+
await fetch('/api/chats/'+id,{method:'DELETE'});
|
| 1425 |
+
if(id===currentId)newChat();
|
| 1426 |
+
refreshChats();
|
| 1427 |
+
}
|
| 1428 |
+
async function persist(){
|
| 1429 |
+
if(!currentId)currentId=uid();
|
| 1430 |
+
let title=hist.find(m=>m.role==='user');
|
| 1431 |
+
title=title?title.content.slice(0,60):'Nova conversa';
|
| 1432 |
+
await fetch('/api/chats/'+currentId,{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1433 |
+
body:JSON.stringify({title,messages:hist,persona_id:activePersona?activePersona.id:null})});
|
| 1434 |
+
refreshChats();
|
| 1435 |
+
}
|
| 1436 |
+
function newChat(){
|
| 1437 |
+
hist=[];attachments=[];currentId=null;activePersona=null;
|
| 1438 |
+
renderAttachments();renderPersonaTag();
|
| 1439 |
+
document.getElementById('log').innerHTML='';
|
| 1440 |
+
document.getElementById('log').style.display='none';
|
| 1441 |
+
document.getElementById('hello').style.display='flex';
|
| 1442 |
+
refreshChats();updateCtxBar();updateRegen();maybeCloseSidebar();
|
| 1443 |
+
}
|
| 1444 |
+
|
| 1445 |
+
// ---------- sidebar / personas ----------
|
| 1446 |
+
async function refreshPersonas(){
|
| 1447 |
+
const r=await fetch('/api/personas');const j=await r.json();
|
| 1448 |
+
const c=document.getElementById('plist');c.innerHTML='';
|
| 1449 |
+
(j.personas||[]).forEach(p=>{
|
| 1450 |
+
const act=activePersona&&p.id===activePersona.id;
|
| 1451 |
+
const d=document.createElement('div');d.className='citem persona'+(act?' active':'');
|
| 1452 |
+
d.innerHTML='<span class=t></span><button class=del title=Excluir>✕</button>';
|
| 1453 |
+
d.querySelector('.t').textContent=p.title;
|
| 1454 |
+
d.querySelector('.t').onclick=()=>activatePersona(p.id);
|
| 1455 |
+
d.querySelector('.del').onclick=(e)=>{e.stopPropagation();delPersona(p.id);};
|
| 1456 |
+
c.appendChild(d);
|
| 1457 |
+
});
|
| 1458 |
+
}
|
| 1459 |
+
async function delPersona(id){
|
| 1460 |
+
if(!confirm('Excluir esta persona?'))return;
|
| 1461 |
+
await fetch('/api/personas/'+id,{method:'DELETE'});
|
| 1462 |
+
if(activePersona&&activePersona.id===id)clearPersona();
|
| 1463 |
+
refreshPersonas();
|
| 1464 |
+
}
|
| 1465 |
+
|
| 1466 |
+
// ---------- sidebar / agêntica ----------
|
| 1467 |
+
async function refreshAgent(){
|
| 1468 |
+
const r=await fetch('/api/agent');const j=await r.json();agentState=j;
|
| 1469 |
+
const c=document.getElementById('alist');c.innerHTML='';
|
| 1470 |
+
if(j&&j.exists){
|
| 1471 |
+
const on=j.enabled&&j.running;
|
| 1472 |
+
const d=document.createElement('div');
|
| 1473 |
+
d.className='citem agent'+(on?' on':'');
|
| 1474 |
+
d.innerHTML='<span class=dot></span><span class=t></span><button class=del title=Excluir>✕</button>';
|
| 1475 |
+
d.querySelector('.t').textContent=j.name||'Agente';
|
| 1476 |
+
d.querySelector('.t').onclick=()=>openAgentModal();
|
| 1477 |
+
d.querySelector('.del').onclick=(e)=>{e.stopPropagation();deleteAgent();};
|
| 1478 |
+
c.appendChild(d);
|
| 1479 |
+
}else{
|
| 1480 |
+
const e=document.createElement('div');e.className='agent-empty';
|
| 1481 |
+
e.textContent='Nenhum agente. Clique em ⚙ para criar.';
|
| 1482 |
+
c.appendChild(e);
|
| 1483 |
+
}
|
| 1484 |
+
}
|
| 1485 |
+
|
| 1486 |
+
// ---------- modal persona ----------
|
| 1487 |
+
function openPersonaModal(){
|
| 1488 |
+
document.getElementById('pmtitle').value='';
|
| 1489 |
+
document.getElementById('pmdesc').value='';
|
| 1490 |
+
document.getElementById('pmsave').disabled=true;
|
| 1491 |
+
document.getElementById('personamodal').classList.add('open');
|
| 1492 |
+
setTimeout(()=>document.getElementById('pmtitle').focus(),50);
|
| 1493 |
+
}
|
| 1494 |
+
function closePersonaModal(){
|
| 1495 |
+
document.getElementById('personamodal').classList.remove('open');
|
| 1496 |
+
}
|
| 1497 |
+
function pmValidate(){
|
| 1498 |
+
const t=document.getElementById('pmtitle').value.trim();
|
| 1499 |
+
const d=document.getElementById('pmdesc').value.trim();
|
| 1500 |
+
document.getElementById('pmsave').disabled=!(t&&d);
|
| 1501 |
+
}
|
| 1502 |
+
async function savePersona(){
|
| 1503 |
+
const title=document.getElementById('pmtitle').value.trim();
|
| 1504 |
+
const description=document.getElementById('pmdesc').value;
|
| 1505 |
+
if(!title||!description.trim())return;
|
| 1506 |
+
const id=uid();
|
| 1507 |
+
await fetch('/api/personas/'+id,{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1508 |
+
body:JSON.stringify({title,description})});
|
| 1509 |
+
closePersonaModal();
|
| 1510 |
+
refreshPersonas();
|
| 1511 |
+
}
|
| 1512 |
+
document.getElementById('personamodal').addEventListener('click',(e)=>{
|
| 1513 |
+
if(e.target.id==='personamodal')closePersonaModal();
|
| 1514 |
+
});
|
| 1515 |
+
|
| 1516 |
+
// ---------- modal agêntica ----------
|
| 1517 |
+
function agentTab(name){
|
| 1518 |
+
document.querySelectorAll('#agentmodal .tab').forEach(t=>t.classList.toggle('active',t.dataset.tab===name));
|
| 1519 |
+
document.querySelectorAll('#agentmodal .tabpane').forEach(p=>p.classList.remove('active'));
|
| 1520 |
+
document.getElementById('tab-'+name).classList.add('active');
|
| 1521 |
+
if(name==='mem')loadAgentMemory();
|
| 1522 |
+
if(name==='rep')loadAgentReports();
|
| 1523 |
+
}
|
| 1524 |
+
function agValidate(){
|
| 1525 |
+
const n=document.getElementById('agname').value.trim();
|
| 1526 |
+
const f=document.getElementById('agfunction').value.trim();
|
| 1527 |
+
document.getElementById('agsave').disabled=!(n&&f);
|
| 1528 |
+
}
|
| 1529 |
+
function agRootToggle(){
|
| 1530 |
+
const on=document.getElementById('agallowroot').checked;
|
| 1531 |
+
document.getElementById('agrootbox').style.display=on?'block':'none';
|
| 1532 |
+
}
|
| 1533 |
+
function fillAgentForm(a){
|
| 1534 |
+
document.getElementById('agname').value=a.name||'';
|
| 1535 |
+
document.getElementById('aginterval').value=a.interval||300;
|
| 1536 |
+
document.getElementById('agfunction').value=a.function||'';
|
| 1537 |
+
document.querySelectorAll('#agactions input[data-act]').forEach(cb=>{
|
| 1538 |
+
cb.checked=!!(a.actions&&a.actions[cb.dataset.act]);
|
| 1539 |
+
});
|
| 1540 |
+
document.getElementById('agmaxsteps').value=a.max_steps||4;
|
| 1541 |
+
document.getElementById('agmemwin').value=(a.memory_window!=null?a.memory_window:40);
|
| 1542 |
+
document.getElementById('agautonomy').value=a.autonomy||'supervised';
|
| 1543 |
+
document.getElementById('agtemp').value=(a.temperature!=null?a.temperature:0.4);
|
| 1544 |
+
document.getElementById('agmodel').value=a.model||'';
|
| 1545 |
+
document.getElementById('agworkdir').value=a.workdir||'';
|
| 1546 |
+
document.getElementById('agallowroot').checked=!!a.allow_root;
|
| 1547 |
+
agRootToggle();
|
| 1548 |
+
document.getElementById('agrootstatus').textContent=a.root_armed?'root ARMADO (em memória)':'root não armado';
|
| 1549 |
+
}
|
| 1550 |
+
function updateAgentButtons(a){
|
| 1551 |
+
const exists=a&&a.exists;
|
| 1552 |
+
document.getElementById('agdelete').style.display=exists?'inline-block':'none';
|
| 1553 |
+
document.getElementById('agrunnow').style.display=exists?'inline-block':'none';
|
| 1554 |
+
const tg=document.getElementById('agtoggle');
|
| 1555 |
+
tg.style.display=exists?'inline-block':'none';
|
| 1556 |
+
if(exists){
|
| 1557 |
+
const on=a.enabled&&a.running;
|
| 1558 |
+
tg.textContent=on?'Desativar':'Ativar';
|
| 1559 |
+
}
|
| 1560 |
+
let info='';
|
| 1561 |
+
if(exists){
|
| 1562 |
+
info='Criado · execuções: '+(a.runs||0);
|
| 1563 |
+
if(a.last_run)info+=' · última: '+new Date(a.last_run*1000).toLocaleString();
|
| 1564 |
+
info+=' · estado: '+((a.enabled&&a.running)?'ATIVO em segundo plano':'parado');
|
| 1565 |
+
}
|
| 1566 |
+
document.getElementById('aginfo').textContent=info;
|
| 1567 |
+
}
|
| 1568 |
+
async function openAgentModal(){
|
| 1569 |
+
const r=await fetch('/api/agent');const a=await r.json();agentState=a;
|
| 1570 |
+
fillAgentForm(a);updateAgentButtons(a);agValidate();
|
| 1571 |
+
agentTab('cfg');
|
| 1572 |
+
document.getElementById('agentmodal').classList.add('open');
|
| 1573 |
+
maybeCloseSidebar();
|
| 1574 |
+
}
|
| 1575 |
+
function closeAgentModal(){document.getElementById('agentmodal').classList.remove('open');}
|
| 1576 |
+
document.getElementById('agentmodal').addEventListener('click',(e)=>{
|
| 1577 |
+
if(e.target.id==='agentmodal')closeAgentModal();
|
| 1578 |
+
});
|
| 1579 |
+
function collectActions(){
|
| 1580 |
+
const o={};
|
| 1581 |
+
document.querySelectorAll('#agactions input[data-act]').forEach(cb=>{o[cb.dataset.act]=cb.checked;});
|
| 1582 |
+
return o;
|
| 1583 |
+
}
|
| 1584 |
+
async function saveAgent(){
|
| 1585 |
+
const allowRoot=document.getElementById('agallowroot').checked;
|
| 1586 |
+
const body={
|
| 1587 |
+
name:document.getElementById('agname').value.trim(),
|
| 1588 |
+
function:document.getElementById('agfunction').value,
|
| 1589 |
+
interval:parseInt(document.getElementById('aginterval').value)||300,
|
| 1590 |
+
actions:collectActions(),
|
| 1591 |
+
max_steps:parseInt(document.getElementById('agmaxsteps').value)||4,
|
| 1592 |
+
memory_window:parseInt(document.getElementById('agmemwin').value)||0,
|
| 1593 |
+
autonomy:document.getElementById('agautonomy').value,
|
| 1594 |
+
temperature:parseFloat(document.getElementById('agtemp').value)||0.4,
|
| 1595 |
+
model:document.getElementById('agmodel').value.trim(),
|
| 1596 |
+
workdir:document.getElementById('agworkdir').value.trim(),
|
| 1597 |
+
allow_root:allowRoot
|
| 1598 |
+
};
|
| 1599 |
+
const r=await fetch('/api/agent',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1600 |
+
body:JSON.stringify(body)});
|
| 1601 |
+
let a=await r.json();
|
| 1602 |
+
// arma/desarma senha root
|
| 1603 |
+
if(allowRoot){
|
| 1604 |
+
const pw=document.getElementById('agrootpw').value;
|
| 1605 |
+
if(pw){
|
| 1606 |
+
const rr=await fetch('/api/agent/root',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1607 |
+
body:JSON.stringify({password:pw})});
|
| 1608 |
+
const j=await rr.json();a.root_armed=!!j.root_armed;
|
| 1609 |
+
}
|
| 1610 |
+
}else{
|
| 1611 |
+
await fetch('/api/agent/root',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1612 |
+
body:JSON.stringify({clear:true})});
|
| 1613 |
+
a.root_armed=false;
|
| 1614 |
+
}
|
| 1615 |
+
agentState=a;fillAgentForm(a);updateAgentButtons(a);refreshAgent();
|
| 1616 |
+
}
|
| 1617 |
+
async function toggleAgent(){
|
| 1618 |
+
const a=agentState||{};
|
| 1619 |
+
const on=a.enabled&&a.running;
|
| 1620 |
+
const r=await fetch('/api/agent/enable',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 1621 |
+
body:JSON.stringify({enabled:!on})});
|
| 1622 |
+
const j=await r.json();agentState=j;updateAgentButtons(j);refreshAgent();
|
| 1623 |
+
}
|
| 1624 |
+
async function runAgentNow(){
|
| 1625 |
+
await fetch('/api/agent/run',{method:'POST'});
|
| 1626 |
+
document.getElementById('aginfo').textContent='Ciclo disparado em segundo plano...';
|
| 1627 |
+
setTimeout(()=>{loadAgentReports();},1500);
|
| 1628 |
+
}
|
| 1629 |
+
async function deleteAgent(){
|
| 1630 |
+
if(!confirm('Excluir o agente? Isso para a execução e zera a configuração.'))return;
|
| 1631 |
+
await fetch('/api/agent',{method:'DELETE'});
|
| 1632 |
+
closeAgentModal();refreshAgent();
|
| 1633 |
+
}
|
| 1634 |
+
async function loadAgentMemory(){
|
| 1635 |
+
const r=await fetch('/api/agent/memory');const j=await r.json();
|
| 1636 |
+
const box=document.getElementById('agmemview');
|
| 1637 |
+
const mem=j.memory||[];
|
| 1638 |
+
if(!mem.length){box.textContent='(vazia)';return;}
|
| 1639 |
+
box.textContent=mem.map(m=>{
|
| 1640 |
+
const t=new Date((m.ts||0)*1000).toLocaleString();
|
| 1641 |
+
return '['+t+'] '+(m.kind||'')+': '+JSON.stringify(m.data!==undefined?m.data:m);
|
| 1642 |
+
}).join('\n');
|
| 1643 |
+
box.scrollTop=box.scrollHeight;
|
| 1644 |
+
}
|
| 1645 |
+
async function clearAgentMemory(){
|
| 1646 |
+
if(!confirm('Limpar toda a memória do agente?'))return;
|
| 1647 |
+
await fetch('/api/agent/memory',{method:'DELETE'});
|
| 1648 |
+
loadAgentMemory();
|
| 1649 |
+
}
|
| 1650 |
+
async function loadAgentReports(){
|
| 1651 |
+
const r=await fetch('/api/agent/reports');const j=await r.json();
|
| 1652 |
+
const list=document.getElementById('agreplist');list.innerHTML='';
|
| 1653 |
+
document.getElementById('agrepview').style.display='none';
|
| 1654 |
+
(j.reports||[]).forEach(rep=>{
|
| 1655 |
+
const d=document.createElement('div');d.className='repitem';
|
| 1656 |
+
const t=new Date((rep.ts||0)*1000).toLocaleString();
|
| 1657 |
+
d.innerHTML='<span class="'+(rep.ok?'repok':'reperr')+'">'+(rep.ok?'✓':'✕')+'</span> '+
|
| 1658 |
+
esc(t)+' — '+esc(rep.summary||'(sem resumo)');
|
| 1659 |
+
d.onclick=()=>openReport(rep.id);
|
| 1660 |
+
list.appendChild(d);
|
| 1661 |
+
});
|
| 1662 |
+
if(!(j.reports||[]).length)list.innerHTML='<div class=hint>Nenhum relatório ainda.</div>';
|
| 1663 |
+
}
|
| 1664 |
+
async function openReport(rid){
|
| 1665 |
+
const r=await fetch('/api/agent/reports/'+rid);if(!r.ok)return;
|
| 1666 |
+
const j=await r.json();
|
| 1667 |
+
const v=document.getElementById('agrepview');
|
| 1668 |
+
v.style.display='block';
|
| 1669 |
+
v.textContent=JSON.stringify(j,null,2);
|
| 1670 |
+
v.scrollTop=0;
|
| 1671 |
+
}
|
| 1672 |
+
|
| 1673 |
+
// ---------- anexos ----------
|
| 1674 |
+
document.getElementById('fileinp').addEventListener('change',async(e)=>{
|
| 1675 |
+
for(const f of e.target.files){
|
| 1676 |
+
const fd=new FormData();fd.append('file',f);
|
| 1677 |
+
const ph={name:f.name,text:'',loading:true};attachments.push(ph);renderAttachments();
|
| 1678 |
+
try{const r=await fetch('/api/extract',{method:'POST',body:fd});const j=await r.json();
|
| 1679 |
+
ph.text=j.text||'';ph.chars=j.chars||0;ph.loading=false;
|
| 1680 |
+
}catch(err){ph.text='';ph.loading=false;ph.err=true;}
|
| 1681 |
+
renderAttachments();updateCtxBar();
|
| 1682 |
+
}
|
| 1683 |
+
e.target.value='';
|
| 1684 |
+
});
|
| 1685 |
+
function renderAttachments(){
|
| 1686 |
+
const row=document.getElementById('attachrow');row.innerHTML='';
|
| 1687 |
+
attachments.forEach((a,i)=>{
|
| 1688 |
+
const d=document.createElement('span');d.className='attach';
|
| 1689 |
+
d.innerHTML=(a.loading?'<span class=spin></span> ':'📄 ')+esc(a.name)+
|
| 1690 |
+
(a.chars?(' · '+a.chars+' ch'):'')+' <span class=x>✕</span>';
|
| 1691 |
+
d.querySelector('.x').onclick=()=>{attachments.splice(i,1);renderAttachments();updateCtxBar();};
|
| 1692 |
+
row.appendChild(d);
|
| 1693 |
+
});
|
| 1694 |
+
}
|
| 1695 |
+
|
| 1696 |
+
// ---------- render de mensagens ----------
|
| 1697 |
+
function renderMsg(role,txt){
|
| 1698 |
+
const l=document.getElementById('log');
|
| 1699 |
+
document.getElementById('hello').style.display='none';l.style.display='block';
|
| 1700 |
+
const d=document.createElement('div');d.className='msg '+(role==='user'?'u':'a');
|
| 1701 |
+
const bub=document.createElement('span');bub.className='bub';
|
| 1702 |
+
if(role==='user'){bub.textContent=txt;}else{bub.innerHTML=MD(txt);decorate(bub);}
|
| 1703 |
+
d.appendChild(bub);l.appendChild(d);l.scrollTo({top:l.scrollHeight});
|
| 1704 |
+
return bub;
|
| 1705 |
+
}
|
| 1706 |
+
|
| 1707 |
+
// ---------- envio ----------
|
| 1708 |
+
async function go(){
|
| 1709 |
+
if(busy)return;
|
| 1710 |
+
const inp=document.getElementById('inp');let t=inp.value.trim();
|
| 1711 |
+
if(!t&&attachments.length===0)return;
|
| 1712 |
+
|
| 1713 |
+
// monta conteúdo com anexos injetados
|
| 1714 |
+
let full=t;
|
| 1715 |
+
if(attachments.length){
|
| 1716 |
+
const docs=attachments.map(a=>`\n\n[DOCUMENTO: ${a.name}]\n${a.text}\n[FIM DO DOCUMENTO]`).join('');
|
| 1717 |
+
full=(t?t+'\n':'')+docs;
|
| 1718 |
+
}
|
| 1719 |
+
const displayText=t+(attachments.length?('\n\n'+attachments.map(a=>'📄 '+a.name).join('\n')):'');
|
| 1720 |
+
inp.value='';autoGrow(inp);
|
| 1721 |
+
renderMsg('user',displayText);
|
| 1722 |
+
hist.push({role:'user',content:full});
|
| 1723 |
+
attachments=[];renderAttachments();
|
| 1724 |
+
await stream();
|
| 1725 |
+
}
|
| 1726 |
+
|
| 1727 |
+
async function stream(){
|
| 1728 |
+
setBusyUI(true); // [UPGRADE] entra em modo "parar"
|
| 1729 |
+
const bub=renderMsg('assistant','');
|
| 1730 |
+
const live=document.getElementById('livebar');live.style.display='flex';
|
| 1731 |
+
document.getElementById('tpsLive').textContent='0';
|
| 1732 |
+
document.getElementById('tokLive').textContent='0';
|
| 1733 |
+
document.getElementById('timeLive').textContent='0.0';
|
| 1734 |
+
|
| 1735 |
+
let acc='',tokCount=0,t0=performance.now(),firstTok=null,raf=null,aborted=false;
|
| 1736 |
+
function tick(){
|
| 1737 |
+
const el=(performance.now()-t0)/1000;
|
| 1738 |
+
document.getElementById('timeLive').textContent=el.toFixed(1);
|
| 1739 |
+
const genT=firstTok?(performance.now()-firstTok)/1000:0;
|
| 1740 |
+
const tps=genT>0?(tokCount/genT):0;
|
| 1741 |
+
document.getElementById('tpsLive').textContent=tps.toFixed(1);
|
| 1742 |
+
document.getElementById('tokLive').textContent=tokCount;
|
| 1743 |
+
raf=requestAnimationFrame(tick);
|
| 1744 |
+
}
|
| 1745 |
+
raf=requestAnimationFrame(tick);
|
| 1746 |
+
|
| 1747 |
+
// injeta persona ativa como system prompt (não exibida na tela)
|
| 1748 |
+
const outMsgs = activePersona
|
| 1749 |
+
? [{role:'system',content:activePersona.description}, ...hist]
|
| 1750 |
+
: hist;
|
| 1751 |
+
|
| 1752 |
+
let usage=null;
|
| 1753 |
+
try{
|
| 1754 |
+
abortCtrl=new AbortController(); // [UPGRADE]
|
| 1755 |
+
const r=await fetch('/v1/chat/completions',{method:'POST',
|
| 1756 |
+
headers:{'Content-Type':'application/json'},
|
| 1757 |
+
body:JSON.stringify({messages:outMsgs,stream:true,cache_prompt:true}),
|
| 1758 |
+
signal:abortCtrl.signal});
|
| 1759 |
+
if(!r.ok){const e=await r.json().catch(()=>({}));bub.innerHTML='⚠ '+(e.error||r.status);}
|
| 1760 |
+
else{
|
| 1761 |
+
const rd=r.body.getReader();const dec=new TextDecoder();let buf='';
|
| 1762 |
+
while(true){const{done,value}=await rd.read();if(done)break;
|
| 1763 |
+
buf+=dec.decode(value,{stream:true});
|
| 1764 |
+
let idx;while((idx=buf.indexOf('\n'))>=0){
|
| 1765 |
+
const line=buf.slice(0,idx);buf=buf.slice(idx+1);
|
| 1766 |
+
if(!line.startsWith('data:'))continue;
|
| 1767 |
+
const p=line.slice(5).trim();if(p==='[DONE]')continue;
|
| 1768 |
+
try{const j=JSON.parse(p);
|
| 1769 |
+
const c=j.choices?.[0]?.delta?.content;
|
| 1770 |
+
if(c){if(firstTok===null)firstTok=performance.now();acc+=c;tokCount++;
|
| 1771 |
+
bub.innerHTML=MD(acc);
|
| 1772 |
+
{const _l=document.getElementById('log');_l.scrollTo({top:_l.scrollHeight});}}
|
| 1773 |
+
if(j.usage)usage=j.usage;
|
| 1774 |
+
if(j.timings)usage={...(usage||{}),timings:j.timings};
|
| 1775 |
+
}catch(e){}
|
| 1776 |
+
}
|
| 1777 |
+
}
|
| 1778 |
+
decorate(bub);
|
| 1779 |
+
}
|
| 1780 |
+
}catch(e){
|
| 1781 |
+
if(e&&e.name==='AbortError'){ // [UPGRADE] aborto limpo: preserva parcial
|
| 1782 |
+
aborted=true;
|
| 1783 |
+
bub.innerHTML=MD(acc||'_(sem conteúdo)_');decorate(bub);
|
| 1784 |
+
}else{
|
| 1785 |
+
bub.innerHTML='⚠ '+e;
|
| 1786 |
+
}
|
| 1787 |
+
}finally{
|
| 1788 |
+
abortCtrl=null;
|
| 1789 |
+
}
|
| 1790 |
+
|
| 1791 |
+
cancelAnimationFrame(raf);
|
| 1792 |
+
const elapsed=(performance.now()-t0)/1000;
|
| 1793 |
+
const genT=firstTok?(performance.now()-firstTok)/1000:elapsed;
|
| 1794 |
+
// métricas finais: usa contagem do servidor se disponível
|
| 1795 |
+
let outTok=tokCount, tps=genT>0?tokCount/genT:0;
|
| 1796 |
+
if(usage){
|
| 1797 |
+
if(usage.completion_tokens)outTok=usage.completion_tokens;
|
| 1798 |
+
if(usage.timings&&usage.timings.predicted_per_second)tps=usage.timings.predicted_per_second;
|
| 1799 |
+
}
|
| 1800 |
+
document.getElementById('livebar').style.display='none';
|
| 1801 |
+
const meta=document.createElement('div');meta.className='respmeta';
|
| 1802 |
+
meta.textContent=(aborted?'⏹ interrompido · ':'✓ ')+outTok+' tokens · '+tps.toFixed(1)+' tok/s · '+elapsed.toFixed(2)+'s';
|
| 1803 |
+
bub.parentElement.appendChild(meta);
|
| 1804 |
+
|
| 1805 |
+
hist.push({role:'assistant',content:acc});
|
| 1806 |
+
setBusyUI(false); // [UPGRADE] volta para modo "enviar"
|
| 1807 |
+
document.getElementById('inp').focus();
|
| 1808 |
+
await persist();await updateCtxBar();
|
| 1809 |
+
}
|
| 1810 |
+
|
| 1811 |
+
refreshChats();
|
| 1812 |
+
refreshPersonas();
|
| 1813 |
+
refreshAgent();
|
| 1814 |
+
refreshHealth(); // [UPGRADE]
|
| 1815 |
+
updateRegen(); // [UPGRADE]
|
| 1816 |
+
setInterval(refreshAgent, 8000); // status do agente em tempo real na sidebar
|
| 1817 |
+
setInterval(refreshHealth, 8000); // [UPGRADE] saúde do upstream
|
| 1818 |
+
</script></body></html>"""
|
| 1819 |
+
|
| 1820 |
+
@app.get("/", response_class=HTMLResponse)
|
| 1821 |
+
async def ui_root():
|
| 1822 |
+
return HTMLResponse(UI_HTML)
|
| 1823 |
+
|
| 1824 |
+
# ═══════════════════════════ Proxy llama-server (catch-all) — único :8080 ═══════════════════════════
|
| 1825 |
+
PROXY_PREFIXES = ("/v1", "/props", "/health", "/slots", "/completion",
|
| 1826 |
+
"/tokenize", "/detokenize", "/embedding")
|
| 1827 |
+
|
| 1828 |
+
# [UPGRADE] detecção de stream robusta (parsing JSON, sem falso-positivo com qualquer 'true').
|
| 1829 |
+
def _wants_stream(body: bytes) -> bool:
|
| 1830 |
+
if not body:
|
| 1831 |
+
return False
|
| 1832 |
+
try:
|
| 1833 |
+
return bool(json.loads(body).get("stream"))
|
| 1834 |
+
except Exception:
|
| 1835 |
+
return b'"stream"' in body and b'true' in body # fallback conservador
|
| 1836 |
+
|
| 1837 |
+
@app.api_route("/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
| 1838 |
+
async def proxy(path: str, request: Request):
|
| 1839 |
+
full = "/" + path
|
| 1840 |
+
if not full.startswith(PROXY_PREFIXES):
|
| 1841 |
+
return HTMLResponse(UI_HTML)
|
| 1842 |
+
base = CONF["upstreams"]["llm"] # único upstream orquestrado (:8080)
|
| 1843 |
+
upstream = base.rstrip("/") + full
|
| 1844 |
+
body = await request.body()
|
| 1845 |
+
headers = {k: v for k, v in request.headers.items()
|
| 1846 |
+
if k.lower() not in ("host", "cookie", "content-length")}
|
| 1847 |
+
client: httpx.AsyncClient = app.state.client
|
| 1848 |
+
is_stream = _wants_stream(body) # [UPGRADE]
|
| 1849 |
+
if is_stream:
|
| 1850 |
+
async def gen():
|
| 1851 |
+
async with client.stream(request.method, upstream, content=body,
|
| 1852 |
+
headers=headers, params=request.query_params) as r:
|
| 1853 |
+
async for chunk in r.aiter_raw():
|
| 1854 |
+
yield chunk
|
| 1855 |
+
return StreamingResponse(gen(), media_type="text/event-stream")
|
| 1856 |
+
try:
|
| 1857 |
+
req = client.build_request(request.method, upstream, content=body,
|
| 1858 |
+
headers=headers, params=request.query_params)
|
| 1859 |
+
r = await client.send(req)
|
| 1860 |
+
except httpx.ConnectError:
|
| 1861 |
+
return JSONResponse({"error": f"llama-server offline em {base}"}, status_code=502)
|
| 1862 |
+
return Response(content=r.content, status_code=r.status_code,
|
| 1863 |
+
media_type=r.headers.get("content-type"))
|
| 1864 |
+
|
| 1865 |
+
# ═══════════════════════════ Entry ═══════════════════════════
|
| 1866 |
+
if __name__ == "__main__":
|
| 1867 |
+
import uvicorn
|
| 1868 |
+
tls = ensure_tls() if CONF.get("use_tls", True) else None
|
| 1869 |
+
if tls:
|
| 1870 |
+
cert, key = tls
|
| 1871 |
+
print(f"[{KERNEL_NAME}] HTTPS — https://<seu-ip-local>:{CONF['port']}")
|
| 1872 |
+
uvicorn.run(app, host=CONF["bind"], port=CONF["port"],
|
| 1873 |
+
ssl_certfile=cert, ssl_keyfile=key, log_level="info")
|
| 1874 |
+
else:
|
| 1875 |
+
uvicorn.run(app, host=CONF["bind"], port=CONF["port"], log_level="info")
|