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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Silnik agenta: modele (Gemini / NVIDIA NIM przez API zgodne z OpenAI),
|
| 2 |
+
narzędzia do plików i terminala oraz pętla pracy działająca w tle."""
|
| 3 |
+
import fnmatch
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import secrets
|
| 8 |
+
import shutil
|
| 9 |
+
import signal
|
| 10 |
+
import subprocess
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
import traceback
|
| 14 |
+
import urllib.error
|
| 15 |
+
import urllib.request
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
# ---------------------------------------------------------------------------
|
| 19 |
+
# Dostawcy modeli
|
| 20 |
+
# ---------------------------------------------------------------------------
|
| 21 |
+
PROVIDERS = {
|
| 22 |
+
"gemini": {
|
| 23 |
+
"name": "Google Gemini",
|
| 24 |
+
"base_url": os.environ.get("GEMINI_BASE_URL", "https://generativelanguage.googleapis.com/v1beta/openai"),
|
| 25 |
+
"key_env": "GEMINI_API_KEY",
|
| 26 |
+
"default_model": "gemini-flash-latest",
|
| 27 |
+
"suggested": ["gemini-flash-latest", "gemini-pro-latest", "gemini-flash-lite-latest"],
|
| 28 |
+
},
|
| 29 |
+
"nvidia": {
|
| 30 |
+
"name": "NVIDIA NIM",
|
| 31 |
+
"base_url": os.environ.get("NVIDIA_BASE_URL", "https://integrate.api.nvidia.com/v1"),
|
| 32 |
+
"key_env": "NVIDIA_API_KEY",
|
| 33 |
+
"default_model": "nvidia/nemotron-3-super-120b-a12b",
|
| 34 |
+
"suggested": [
|
| 35 |
+
"nvidia/nemotron-3-super-120b-a12b",
|
| 36 |
+
"qwen/qwen3-coder-480b-a35b-instruct",
|
| 37 |
+
"moonshotai/kimi-k2-instruct",
|
| 38 |
+
"openai/gpt-oss-120b",
|
| 39 |
+
],
|
| 40 |
+
},
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
MAX_OUTPUT_TOKENS = int(os.environ.get("MAX_OUTPUT_TOKENS", "16384"))
|
| 44 |
+
MAX_CONTEXT_CHARS = int(os.environ.get("MAX_CONTEXT_CHARS", "300000"))
|
| 45 |
+
CMD_TIMEOUT_MAX = int(os.environ.get("CMD_TIMEOUT_MAX", "600"))
|
| 46 |
+
IGNORED_DIRS = {"node_modules", ".git", "__pycache__", ".venv", "venv", ".next", ".cache", "dist", "build", ".gradle"}
|
| 47 |
+
SECRET_ENV = {"GEMINI_API_KEY", "NVIDIA_API_KEY", "APP_PASSWORD", "NTFY_TOPIC"}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class LLMError(Exception):
|
| 51 |
+
def __init__(self, msg, status=None, retryable=False, retry_after=None):
|
| 52 |
+
super().__init__(msg)
|
| 53 |
+
self.status = status
|
| 54 |
+
self.retryable = retryable
|
| 55 |
+
self.retry_after = retry_after
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_api_key(store, provider):
|
| 59 |
+
p = PROVIDERS[provider]
|
| 60 |
+
return (store.get_setting(f"key_{provider}") or os.environ.get(p["key_env"]) or "").strip()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _http_json(url, key, body=None, timeout=300):
|
| 64 |
+
data = json.dumps(body).encode() if body is not None else None
|
| 65 |
+
req = urllib.request.Request(url, data=data, method="POST" if body is not None else "GET")
|
| 66 |
+
req.add_header("Authorization", f"Bearer {key}")
|
| 67 |
+
req.add_header("Content-Type", "application/json")
|
| 68 |
+
req.add_header("Accept", "application/json")
|
| 69 |
+
try:
|
| 70 |
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
| 71 |
+
return json.loads(r.read().decode("utf-8", "replace"))
|
| 72 |
+
except urllib.error.HTTPError as e:
|
| 73 |
+
text = e.read().decode("utf-8", "replace")[:2000]
|
| 74 |
+
ra = e.headers.get("Retry-After") if e.headers else None
|
| 75 |
+
try:
|
| 76 |
+
ra = float(ra) if ra else None
|
| 77 |
+
except ValueError:
|
| 78 |
+
ra = None
|
| 79 |
+
raise LLMError(f"HTTP {e.code}: {text}", status=e.code,
|
| 80 |
+
retryable=e.code in (408, 409, 425, 429, 500, 502, 503, 504), retry_after=ra)
|
| 81 |
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
|
| 82 |
+
raise LLMError(f"Błąd sieci: {e}", retryable=True)
|
| 83 |
+
except json.JSONDecodeError as e:
|
| 84 |
+
raise LLMError(f"Niepoprawna odpowiedź JSON: {e}", retryable=True)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def list_models(store, provider):
|
| 88 |
+
key = get_api_key(store, provider)
|
| 89 |
+
if not key:
|
| 90 |
+
raise LLMError("Brak klucza API dla " + PROVIDERS[provider]["name"])
|
| 91 |
+
res = _http_json(PROVIDERS[provider]["base_url"].rstrip("/") + "/models", key, timeout=30)
|
| 92 |
+
ids = []
|
| 93 |
+
for m in res.get("data", []):
|
| 94 |
+
mid = m.get("id", "")
|
| 95 |
+
if mid.startswith("models/"):
|
| 96 |
+
mid = mid[7:]
|
| 97 |
+
if provider == "gemini" and "gemini" not in mid:
|
| 98 |
+
continue
|
| 99 |
+
if any(bad in mid for bad in ("embed", "rerank", "guard", "parse", "tts", "image", "vision-only", "clip")):
|
| 100 |
+
continue
|
| 101 |
+
ids.append(mid)
|
| 102 |
+
return sorted(set(ids))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def chat(store, provider, model, messages, tools):
|
| 106 |
+
key = get_api_key(store, provider)
|
| 107 |
+
if not key:
|
| 108 |
+
raise LLMError("Brak klucza API dla " + PROVIDERS[provider]["name"] + " — dodaj go w Ustawieniach.")
|
| 109 |
+
url = PROVIDERS[provider]["base_url"].rstrip("/") + "/chat/completions"
|
| 110 |
+
max_tokens = MAX_OUTPUT_TOKENS
|
| 111 |
+
while True:
|
| 112 |
+
body = {"model": model, "messages": messages, "tools": tools, "tool_choice": "auto", "max_tokens": max_tokens}
|
| 113 |
+
try:
|
| 114 |
+
return _http_json(url, key, body)
|
| 115 |
+
except LLMError as e:
|
| 116 |
+
# część modeli NIM ma niższy limit tokenów wyjścia — zmniejszamy i próbujemy ponownie
|
| 117 |
+
if e.status == 400 and "token" in str(e).lower() and max_tokens > 2048:
|
| 118 |
+
max_tokens //= 2
|
| 119 |
+
continue
|
| 120 |
+
raise
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ---------------------------------------------------------------------------
|
| 124 |
+
# Narzędzia
|
| 125 |
+
# ---------------------------------------------------------------------------
|
| 126 |
+
TOOLS = [
|
| 127 |
+
{"type": "function", "function": {
|
| 128 |
+
"name": "update_plan",
|
| 129 |
+
"description": "Ustaw/aktualizuj listę kroków planu (widoczną dla użytkownika). Wywołaj na początku i odhaczaj kroki w trakcie.",
|
| 130 |
+
"parameters": {"type": "object", "properties": {
|
| 131 |
+
"items": {"type": "array", "items": {"type": "object", "properties": {
|
| 132 |
+
"text": {"type": "string"}, "done": {"type": "boolean"}}, "required": ["text", "done"]}}},
|
| 133 |
+
"required": ["items"]}}},
|
| 134 |
+
{"type": "function", "function": {
|
| 135 |
+
"name": "list_files",
|
| 136 |
+
"description": "Pokaż drzewo plików i folderów projektu (ścieżki względne). Pomija node_modules, .git itp.",
|
| 137 |
+
"parameters": {"type": "object", "properties": {
|
| 138 |
+
"path": {"type": "string", "description": "Folder, domyślnie '.'"},
|
| 139 |
+
"max_depth": {"type": "integer", "description": "Głębokość, domyślnie 4"}}}}},
|
| 140 |
+
{"type": "function", "function": {
|
| 141 |
+
"name": "read_file",
|
| 142 |
+
"description": "Odczytaj plik tekstowy. Dla dużych plików podaj zakres linii.",
|
| 143 |
+
"parameters": {"type": "object", "properties": {
|
| 144 |
+
"path": {"type": "string"},
|
| 145 |
+
"start_line": {"type": "integer"}, "end_line": {"type": "integer"}},
|
| 146 |
+
"required": ["path"]}}},
|
| 147 |
+
{"type": "function", "function": {
|
| 148 |
+
"name": "write_file",
|
| 149 |
+
"description": "Zapisz plik (tworzy brakujące foldery, nadpisuje). Zapisuj PEŁNĄ treść. Bardzo duże pliki zapisuj w częściach z append=true.",
|
| 150 |
+
"parameters": {"type": "object", "properties": {
|
| 151 |
+
"path": {"type": "string"}, "content": {"type": "string"},
|
| 152 |
+
"append": {"type": "boolean", "description": "Dopisz na końcu zamiast nadpisywać"}},
|
| 153 |
+
"required": ["path", "content"]}}},
|
| 154 |
+
{"type": "function", "function": {
|
| 155 |
+
"name": "edit_file",
|
| 156 |
+
"description": "Zamień dokładny fragment tekstu w pliku na nowy. old_text musi wystąpić dokładnie raz (chyba że replace_all=true).",
|
| 157 |
+
"parameters": {"type": "object", "properties": {
|
| 158 |
+
"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"},
|
| 159 |
+
"replace_all": {"type": "boolean"}},
|
| 160 |
+
"required": ["path", "old_text", "new_text"]}}},
|
| 161 |
+
{"type": "function", "function": {
|
| 162 |
+
"name": "make_dir",
|
| 163 |
+
"description": "Utwórz folder (z rodzicami).",
|
| 164 |
+
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
|
| 165 |
+
{"type": "function", "function": {
|
| 166 |
+
"name": "move_path",
|
| 167 |
+
"description": "Przenieś lub zmień nazwę pliku/folderu.",
|
| 168 |
+
"parameters": {"type": "object", "properties": {"src": {"type": "string"}, "dst": {"type": "string"}},
|
| 169 |
+
"required": ["src", "dst"]}}},
|
| 170 |
+
{"type": "function", "function": {
|
| 171 |
+
"name": "delete_path",
|
| 172 |
+
"description": "Usuń plik lub folder (rekurencyjnie).",
|
| 173 |
+
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
|
| 174 |
+
{"type": "function", "function": {
|
| 175 |
+
"name": "search_files",
|
| 176 |
+
"description": "Szukaj wyrażenia regularnego w plikach projektu. Zwraca plik:linia: treść.",
|
| 177 |
+
"parameters": {"type": "object", "properties": {
|
| 178 |
+
"pattern": {"type": "string"}, "path": {"type": "string"},
|
| 179 |
+
"glob": {"type": "string", "description": "np. *.py"}},
|
| 180 |
+
"required": ["pattern"]}}},
|
| 181 |
+
{"type": "function", "function": {
|
| 182 |
+
"name": "run_command",
|
| 183 |
+
"description": "Uruchom polecenie powłoki (bash) w folderze projektu, np. instalacja zależności, testy, kompilacja, git. "
|
| 184 |
+
"NIE uruchamiaj serwerów działających bez końca — do sprawdzenia użyj np. `timeout 10 ...`.",
|
| 185 |
+
"parameters": {"type": "object", "properties": {
|
| 186 |
+
"command": {"type": "string"},
|
| 187 |
+
"timeout": {"type": "integer", "description": "Sekundy, domyślnie 120"}},
|
| 188 |
+
"required": ["command"]}}},
|
| 189 |
+
{"type": "function", "function": {
|
| 190 |
+
"name": "finish",
|
| 191 |
+
"description": "Zakończ zadanie, gdy WSZYSTKO jest gotowe i sprawdzone. Podaj podsumowanie dla użytkownika (co powstało, jak uruchomić).",
|
| 192 |
+
"parameters": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": ["summary"]}}},
|
| 193 |
+
]
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class Workspace:
|
| 197 |
+
def __init__(self, root):
|
| 198 |
+
self.root = Path(root).resolve()
|
| 199 |
+
self.root.mkdir(parents=True, exist_ok=True)
|
| 200 |
+
|
| 201 |
+
def path(self, rel):
|
| 202 |
+
rel = (rel or ".").strip()
|
| 203 |
+
if rel.startswith("/workspace"):
|
| 204 |
+
rel = rel[len("/workspace"):] or "."
|
| 205 |
+
p = (self.root / rel.lstrip("/")).resolve()
|
| 206 |
+
if p != self.root and self.root not in p.parents:
|
| 207 |
+
raise ValueError(f"Ścieżka poza projektem jest zabroniona: {rel}")
|
| 208 |
+
return p
|
| 209 |
+
|
| 210 |
+
def rel(self, p):
|
| 211 |
+
return str(Path(p).relative_to(self.root)) or "."
|
| 212 |
+
|
| 213 |
+
def tree(self, rel=".", max_depth=4, limit=600):
|
| 214 |
+
base = self.path(rel)
|
| 215 |
+
if not base.exists():
|
| 216 |
+
raise FileNotFoundError(f"Nie istnieje: {rel}")
|
| 217 |
+
lines, count = [], 0
|
| 218 |
+
|
| 219 |
+
def walk(d, depth, prefix):
|
| 220 |
+
nonlocal count
|
| 221 |
+
try:
|
| 222 |
+
entries = sorted(d.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower()))
|
| 223 |
+
except PermissionError:
|
| 224 |
+
return
|
| 225 |
+
for e in entries:
|
| 226 |
+
if count >= limit:
|
| 227 |
+
return
|
| 228 |
+
count += 1
|
| 229 |
+
if e.is_dir():
|
| 230 |
+
if e.name in IGNORED_DIRS:
|
| 231 |
+
lines.append(f"{prefix}{e.name}/ (pominięto)")
|
| 232 |
+
continue
|
| 233 |
+
lines.append(f"{prefix}{e.name}/")
|
| 234 |
+
if depth < max_depth:
|
| 235 |
+
walk(e, depth + 1, prefix + " ")
|
| 236 |
+
else:
|
| 237 |
+
lines.append(f"{prefix}{e.name} ({e.stat().st_size} B)")
|
| 238 |
+
|
| 239 |
+
walk(base, 1, "")
|
| 240 |
+
if count >= limit:
|
| 241 |
+
lines.append(f"... (ucięto po {limit} wpisach)")
|
| 242 |
+
return "\n".join(lines) or "(pusty folder)"
|
| 243 |
+
|
| 244 |
+
def all_files(self, limit=3000):
|
| 245 |
+
out = []
|
| 246 |
+
for dirpath, dirnames, filenames in os.walk(self.root):
|
| 247 |
+
dirnames[:] = sorted(d for d in dirnames if d not in IGNORED_DIRS)
|
| 248 |
+
for f in sorted(filenames):
|
| 249 |
+
fp = Path(dirpath) / f
|
| 250 |
+
try:
|
| 251 |
+
out.append({"path": self.rel(fp), "size": fp.stat().st_size})
|
| 252 |
+
except OSError:
|
| 253 |
+
pass
|
| 254 |
+
if len(out) >= limit:
|
| 255 |
+
return out
|
| 256 |
+
return out
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _clip(text, limit=15000):
|
| 260 |
+
if len(text) <= limit:
|
| 261 |
+
return text
|
| 262 |
+
head = limit // 5
|
| 263 |
+
return text[:head] + f"\n\n... [pominięto {len(text) - limit} znaków] ...\n\n" + text[-(limit - head):]
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _safe_env(ws_root):
|
| 267 |
+
env = {k: v for k, v in os.environ.items() if k not in SECRET_ENV}
|
| 268 |
+
env.update({"CI": "1", "npm_config_yes": "true", "PYTHONUNBUFFERED": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1",
|
| 269 |
+
"TERM": "dumb", "PROJECT_DIR": str(ws_root)})
|
| 270 |
+
return env
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def run_tool(ws, name, args, job_ctx):
|
| 274 |
+
"""Wykonuje narzędzie; zwraca tekst wyniku dla modelu."""
|
| 275 |
+
if name == "update_plan":
|
| 276 |
+
items = args.get("items") or []
|
| 277 |
+
job_ctx["plan"] = [{"text": str(i.get("text", "")), "done": bool(i.get("done"))} for i in items if isinstance(i, dict)]
|
| 278 |
+
return "Plan zaktualizowany."
|
| 279 |
+
if name == "list_files":
|
| 280 |
+
return ws.tree(args.get("path") or ".", int(args.get("max_depth") or 4))
|
| 281 |
+
if name == "read_file":
|
| 282 |
+
p = ws.path(args["path"])
|
| 283 |
+
if not p.is_file():
|
| 284 |
+
return f"BŁĄD: plik nie istnieje: {args['path']}"
|
| 285 |
+
if p.stat().st_size > 5_000_000:
|
| 286 |
+
return "BŁĄD: plik jest za duży (>5 MB)."
|
| 287 |
+
text = p.read_text("utf-8", errors="replace")
|
| 288 |
+
lines = text.splitlines()
|
| 289 |
+
s, e = args.get("start_line"), args.get("end_line")
|
| 290 |
+
if s or e:
|
| 291 |
+
s = max(int(s or 1), 1)
|
| 292 |
+
e = min(int(e or len(lines)), len(lines))
|
| 293 |
+
chunk = "\n".join(f"{i}: {lines[i - 1]}" for i in range(s, e + 1))
|
| 294 |
+
return _clip(f"[{args['path']} linie {s}-{e} z {len(lines)}]\n{chunk}", 40000)
|
| 295 |
+
return _clip(f"[{args['path']} — {len(lines)} linii]\n{text}", 40000)
|
| 296 |
+
if name == "write_file":
|
| 297 |
+
p = ws.path(args["path"])
|
| 298 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 299 |
+
content = args.get("content", "")
|
| 300 |
+
if args.get("append"):
|
| 301 |
+
with open(p, "a", encoding="utf-8") as f:
|
| 302 |
+
f.write(content)
|
| 303 |
+
return f"Dopisano {len(content)} znaków do {args['path']} (rozmiar: {p.stat().st_size} B)."
|
| 304 |
+
p.write_text(content, encoding="utf-8")
|
| 305 |
+
return f"Zapisano {args['path']} ({len(content)} znaków, {content.count(chr(10)) + 1} linii)."
|
| 306 |
+
if name == "edit_file":
|
| 307 |
+
p = ws.path(args["path"])
|
| 308 |
+
if not p.is_file():
|
| 309 |
+
return f"BŁĄD: plik nie istnieje: {args['path']}"
|
| 310 |
+
text = p.read_text("utf-8", errors="replace")
|
| 311 |
+
old, new = args.get("old_text", ""), args.get("new_text", "")
|
| 312 |
+
n = text.count(old) if old else 0
|
| 313 |
+
if n == 0:
|
| 314 |
+
return "BŁĄD: nie znaleziono old_text w pliku. Odczytaj plik i spróbuj ponownie z dokładnym fragmentem."
|
| 315 |
+
if n > 1 and not args.get("replace_all"):
|
| 316 |
+
return f"BŁĄD: old_text występuje {n} razy. Podaj dłuższy, unikalny fragment albo ustaw replace_all=true."
|
| 317 |
+
text = text.replace(old, new) if args.get("replace_all") else text.replace(old, new, 1)
|
| 318 |
+
p.write_text(text, encoding="utf-8")
|
| 319 |
+
return f"Zmieniono {args['path']} ({n if args.get('replace_all') else 1} zamian)."
|
| 320 |
+
if name == "make_dir":
|
| 321 |
+
ws.path(args["path"]).mkdir(parents=True, exist_ok=True)
|
| 322 |
+
return f"Utworzono folder {args['path']}."
|
| 323 |
+
if name == "move_path":
|
| 324 |
+
src, dst = ws.path(args["src"]), ws.path(args["dst"])
|
| 325 |
+
if not src.exists():
|
| 326 |
+
return f"BŁĄD: nie istnieje: {args['src']}"
|
| 327 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 328 |
+
shutil.move(str(src), str(dst))
|
| 329 |
+
return f"Przeniesiono {args['src']} -> {args['dst']}."
|
| 330 |
+
if name == "delete_path":
|
| 331 |
+
p = ws.path(args["path"])
|
| 332 |
+
if p == ws.root:
|
| 333 |
+
return "BŁĄD: nie można usunąć całego projektu."
|
| 334 |
+
if not p.exists():
|
| 335 |
+
return f"Nie istnieje: {args['path']}"
|
| 336 |
+
shutil.rmtree(p) if p.is_dir() else p.unlink()
|
| 337 |
+
return f"Usunięto {args['path']}."
|
| 338 |
+
if name == "search_files":
|
| 339 |
+
try:
|
| 340 |
+
rx = re.compile(args["pattern"])
|
| 341 |
+
except re.error as e:
|
| 342 |
+
return f"BŁĄD: niepoprawny regex: {e}"
|
| 343 |
+
base, glob, hits = ws.path(args.get("path") or "."), args.get("glob"), []
|
| 344 |
+
for dirpath, dirnames, filenames in os.walk(base):
|
| 345 |
+
dirnames[:] = [d for d in dirnames if d not in IGNORED_DIRS]
|
| 346 |
+
for f in filenames:
|
| 347 |
+
if glob and not fnmatch.fnmatch(f, glob):
|
| 348 |
+
continue
|
| 349 |
+
fp = Path(dirpath) / f
|
| 350 |
+
try:
|
| 351 |
+
if fp.stat().st_size > 1_000_000:
|
| 352 |
+
continue
|
| 353 |
+
for i, line in enumerate(fp.read_text("utf-8", errors="ignore").splitlines(), 1):
|
| 354 |
+
if rx.search(line):
|
| 355 |
+
hits.append(f"{ws.rel(fp)}:{i}: {line.strip()[:200]}")
|
| 356 |
+
if len(hits) >= 200:
|
| 357 |
+
return "\n".join(hits) + "\n... (limit 200 wyników)"
|
| 358 |
+
except OSError:
|
| 359 |
+
continue
|
| 360 |
+
return "\n".join(hits) or "Brak wyników."
|
| 361 |
+
if name == "run_command":
|
| 362 |
+
cmd = args["command"]
|
| 363 |
+
timeout = max(1, min(int(args.get("timeout") or 120), CMD_TIMEOUT_MAX))
|
| 364 |
+
proc = subprocess.Popen(["bash", "-lc", cmd], cwd=str(ws.root), stdout=subprocess.PIPE,
|
| 365 |
+
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, env=_safe_env(ws.root),
|
| 366 |
+
start_new_session=True)
|
| 367 |
+
job_ctx["proc"] = proc
|
| 368 |
+
try:
|
| 369 |
+
out, _ = proc.communicate(timeout=timeout)
|
| 370 |
+
code = proc.returncode
|
| 371 |
+
timed_out = False
|
| 372 |
+
except subprocess.TimeoutExpired:
|
| 373 |
+
try:
|
| 374 |
+
os.killpg(proc.pid, signal.SIGKILL)
|
| 375 |
+
except OSError:
|
| 376 |
+
pass
|
| 377 |
+
out, _ = proc.communicate()
|
| 378 |
+
code, timed_out = -9, True
|
| 379 |
+
finally:
|
| 380 |
+
job_ctx["proc"] = None
|
| 381 |
+
out = (out or b"").decode("utf-8", "replace")
|
| 382 |
+
status = f"PRZEKROCZONO CZAS ({timeout}s), proces zabity" if timed_out else f"kod wyjścia {code}"
|
| 383 |
+
return f"[{status}]\n{_clip(out, 12000) or '(brak wyjścia)'}"
|
| 384 |
+
return f"BŁĄD: nieznane narzędzie {name}"
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# ---------------------------------------------------------------------------
|
| 388 |
+
# Pętla agenta
|
| 389 |
+
# ---------------------------------------------------------------------------
|
| 390 |
+
SYSTEM_PROMPT = """You are an autonomous senior software engineer working ALONE on a server, with no human watching.
|
| 391 |
+
The user gave you a task from their phone and closed the browser; you must complete it end-to-end without asking questions.
|
| 392 |
+
|
| 393 |
+
Environment:
|
| 394 |
+
- Your project folder is the workspace root. All tool paths are RELATIVE to it (e.g. "src/app.js").
|
| 395 |
+
- Linux shell via run_command (bash). Available tools: {tooling}.
|
| 396 |
+
- Commands time out (default 120 s, max {cmd_max} s). Never start servers/watchers that run forever; to smoke-test use e.g. `timeout 10 node server.js`.
|
| 397 |
+
|
| 398 |
+
How to work:
|
| 399 |
+
1. Start with update_plan (5-12 concrete steps). Keep it updated (mark done) as you progress.
|
| 400 |
+
2. Explore with list_files/read_file when the workspace already has files.
|
| 401 |
+
3. Write COMPLETE, working files — no placeholders, no "TODO: implement", no truncated code.
|
| 402 |
+
For very large files write them in parts with write_file(append=true).
|
| 403 |
+
4. Verify your work: install dependencies, run tests/linters/build, run the program briefly. Fix every error you see.
|
| 404 |
+
5. Always add a README.md with what it is and exact steps to run it.
|
| 405 |
+
6. If something is ambiguous, choose sensible defaults and mention them in the summary.
|
| 406 |
+
7. When everything works, call finish(summary). Write the summary in the same language as the user's request
|
| 407 |
+
(Polish if the user writes Polish): what was built, file structure overview, how to run it, known limitations.
|
| 408 |
+
Never stop with plain text before calling finish — keep using tools until the task is done."""
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _tooling_info():
|
| 412 |
+
found = [t for t in ("python3", "pip", "node", "npm", "git", "gcc", "java", "go", "cargo") if shutil.which(t)]
|
| 413 |
+
return ", ".join(found) or "basic shell only"
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def repair_history(messages):
|
| 417 |
+
"""Każde wywołanie narzędzia musi mieć odpowiedź (ważne po restarcie serwera w trakcie kroku)."""
|
| 418 |
+
out, i = [], 0
|
| 419 |
+
while i < len(messages):
|
| 420 |
+
m = messages[i]
|
| 421 |
+
out.append(m)
|
| 422 |
+
i += 1
|
| 423 |
+
if m.get("role") == "assistant" and m.get("tool_calls"):
|
| 424 |
+
ids = [tc.get("id") for tc in m["tool_calls"]]
|
| 425 |
+
answered = set()
|
| 426 |
+
while i < len(messages) and messages[i].get("role") == "tool":
|
| 427 |
+
answered.add(messages[i].get("tool_call_id"))
|
| 428 |
+
out.append(messages[i])
|
| 429 |
+
i += 1
|
| 430 |
+
for tc in m["tool_calls"]:
|
| 431 |
+
if tc.get("id") not in answered:
|
| 432 |
+
out.append({"role": "tool", "tool_call_id": tc.get("id"),
|
| 433 |
+
"name": tc.get("function", {}).get("name", ""),
|
| 434 |
+
"content": "PRZERWANO (restart serwera) — sprawdź stan plików i kontynuuj."})
|
| 435 |
+
_ = ids
|
| 436 |
+
return out
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def compact(messages):
|
| 440 |
+
"""Ogranicza rozmiar historii: skraca stare wyniki narzędzi i treść zapisanych plików."""
|
| 441 |
+
def size():
|
| 442 |
+
return sum(len(json.dumps(m, ensure_ascii=False)) for m in messages)
|
| 443 |
+
if size() <= MAX_CONTEXT_CHARS:
|
| 444 |
+
return
|
| 445 |
+
keep_tail = 14
|
| 446 |
+
end = max(2, len(messages) - keep_tail)
|
| 447 |
+
for m in messages[2:end]: # najpierw duże argumenty write_file/edit_file
|
| 448 |
+
for tc in m.get("tool_calls") or []:
|
| 449 |
+
fn = tc.get("function", {})
|
| 450 |
+
if fn.get("name") in ("write_file", "edit_file") and len(fn.get("arguments", "")) > 600:
|
| 451 |
+
try:
|
| 452 |
+
a = json.loads(fn["arguments"])
|
| 453 |
+
for k in ("content", "old_text", "new_text"):
|
| 454 |
+
if k in a and len(a[k]) > 200:
|
| 455 |
+
a[k] = a[k][:120] + " …[pominięto — treść jest już w pliku]"
|
| 456 |
+
fn["arguments"] = json.dumps(a, ensure_ascii=False)
|
| 457 |
+
except Exception:
|
| 458 |
+
pass
|
| 459 |
+
if size() <= MAX_CONTEXT_CHARS:
|
| 460 |
+
return
|
| 461 |
+
for m in messages[2:end]:
|
| 462 |
+
if m.get("role") == "tool" and len(m.get("content") or "") > 400:
|
| 463 |
+
m["content"] = m["content"][:300] + "\n…[skrócono stary wynik — uruchom/odczytaj ponownie, jeśli potrzebny]"
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _short(s, n=160):
|
| 467 |
+
s = " ".join(str(s).split())
|
| 468 |
+
return s if len(s) <= n else s[:n] + "…"
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _describe_call(name, a):
|
| 472 |
+
if name in ("write_file",):
|
| 473 |
+
return f"{'dopisuje' if a.get('append') else 'zapisuje'} {a.get('path')} ({len(a.get('content', ''))} zn.)"
|
| 474 |
+
if name in ("read_file", "edit_file", "make_dir", "delete_path"):
|
| 475 |
+
return f"{name} {a.get('path')}"
|
| 476 |
+
if name == "move_path":
|
| 477 |
+
return f"move {a.get('src')} → {a.get('dst')}"
|
| 478 |
+
if name == "run_command":
|
| 479 |
+
return f"$ {_short(a.get('command', ''), 300)}"
|
| 480 |
+
if name == "search_files":
|
| 481 |
+
return f"szuka /{a.get('pattern')}/"
|
| 482 |
+
if name == "list_files":
|
| 483 |
+
return f"lista plików {a.get('path') or '.'}"
|
| 484 |
+
if name == "update_plan":
|
| 485 |
+
return "aktualizuje plan"
|
| 486 |
+
return f"{name} {_short(json.dumps(a, ensure_ascii=False))}"
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _parse_args(raw):
|
| 490 |
+
if isinstance(raw, dict):
|
| 491 |
+
return raw
|
| 492 |
+
raw = (raw or "").strip()
|
| 493 |
+
if not raw:
|
| 494 |
+
return {}
|
| 495 |
+
try:
|
| 496 |
+
v = json.loads(raw)
|
| 497 |
+
return v if isinstance(v, dict) else {}
|
| 498 |
+
except json.JSONDecodeError:
|
| 499 |
+
m = re.search(r"\{.*\}", raw, re.S) # czasem modele otaczają JSON tekstem
|
| 500 |
+
if m:
|
| 501 |
+
return json.loads(m.group(0))
|
| 502 |
+
raise
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class Runner:
|
| 506 |
+
def __init__(self, store, data_dir, max_parallel=2):
|
| 507 |
+
self.store = store
|
| 508 |
+
self.ws_dir = Path(data_dir) / "workspaces"
|
| 509 |
+
self.ws_dir.mkdir(parents=True, exist_ok=True)
|
| 510 |
+
self.max_parallel = max_parallel
|
| 511 |
+
self.active = {} # job_id -> ctx
|
| 512 |
+
self.lock = threading.Lock()
|
| 513 |
+
self._last_ping = 0
|
| 514 |
+
self._recover()
|
| 515 |
+
threading.Thread(target=self._dispatch, daemon=True, name="dispatcher").start()
|
| 516 |
+
|
| 517 |
+
def workspace(self, job_id):
|
| 518 |
+
return Workspace(self.ws_dir / job_id)
|
| 519 |
+
|
| 520 |
+
def _recover(self):
|
| 521 |
+
# zadania przerwane restartem serwera wznawiamy automatycznie (max 3 razy)
|
| 522 |
+
for j in self.store.q("SELECT id, resumes FROM jobs WHERE status='running'"):
|
| 523 |
+
if (j["resumes"] or 0) < 3:
|
| 524 |
+
self.store.update_job(j["id"], status="queued", resumes=(j["resumes"] or 0) + 1)
|
| 525 |
+
self.store.add_event(j["id"], "info", "Serwer został zrestartowany — wznawiam pracę.")
|
| 526 |
+
else:
|
| 527 |
+
self.store.update_job(j["id"], status="interrupted", error="Zbyt wiele restartów serwera.")
|
| 528 |
+
self.store.add_event(j["id"], "error", "Przerwano: zbyt wiele restartów serwera.")
|
| 529 |
+
|
| 530 |
+
def stop(self, job_id):
|
| 531 |
+
with self.lock:
|
| 532 |
+
ctx = self.active.get(job_id)
|
| 533 |
+
if ctx:
|
| 534 |
+
ctx["stop"] = True
|
| 535 |
+
proc = ctx.get("proc")
|
| 536 |
+
if proc:
|
| 537 |
+
try:
|
| 538 |
+
os.killpg(proc.pid, signal.SIGKILL)
|
| 539 |
+
except OSError:
|
| 540 |
+
pass
|
| 541 |
+
else:
|
| 542 |
+
job = self.store.get_job(job_id)
|
| 543 |
+
if job and job["status"] == "queued":
|
| 544 |
+
self.store.update_job(job_id, status="stopped")
|
| 545 |
+
self.store.add_event(job_id, "info", "Zatrzymano przed startem.")
|
| 546 |
+
|
| 547 |
+
def is_active(self, job_id):
|
| 548 |
+
with self.lock:
|
| 549 |
+
return job_id in self.active
|
| 550 |
+
|
| 551 |
+
def _dispatch(self):
|
| 552 |
+
while True:
|
| 553 |
+
try:
|
| 554 |
+
with self.lock:
|
| 555 |
+
free = self.max_parallel - len(self.active)
|
| 556 |
+
if free > 0:
|
| 557 |
+
for row in self.store.q("SELECT id FROM jobs WHERE status='queued' ORDER BY updated LIMIT ?", (free,)):
|
| 558 |
+
jid = row["id"]
|
| 559 |
+
with self.lock:
|
| 560 |
+
if jid in self.active:
|
| 561 |
+
continue
|
| 562 |
+
ctx = {"stop": False, "proc": None, "plan": None}
|
| 563 |
+
self.active[jid] = ctx
|
| 564 |
+
self.store.update_job(jid, status="running", error=None)
|
| 565 |
+
threading.Thread(target=self._run_safe, args=(jid, ctx), daemon=True, name=f"job-{jid}").start()
|
| 566 |
+
self._keepalive()
|
| 567 |
+
except Exception:
|
| 568 |
+
traceback.print_exc()
|
| 569 |
+
time.sleep(1)
|
| 570 |
+
|
| 571 |
+
def _keepalive(self):
|
| 572 |
+
"""Na darmowych hostingach (np. Render free) serwer usypia bez ruchu — pingujemy sami siebie w trakcie pracy."""
|
| 573 |
+
url = os.environ.get("KEEPALIVE_URL") or os.environ.get("RENDER_EXTERNAL_URL") or (f"https://{os.environ['SPACE_HOST']}" if os.environ.get("SPACE_HOST") else None)
|
| 574 |
+
with self.lock:
|
| 575 |
+
busy = bool(self.active)
|
| 576 |
+
if not url or not busy or time.time() - self._last_ping < 240:
|
| 577 |
+
return
|
| 578 |
+
self._last_ping = time.time()
|
| 579 |
+
|
| 580 |
+
def ping():
|
| 581 |
+
try:
|
| 582 |
+
urllib.request.urlopen(url.rstrip("/") + "/api/health", timeout=20).read()
|
| 583 |
+
except Exception:
|
| 584 |
+
pass
|
| 585 |
+
threading.Thread(target=ping, daemon=True).start()
|
| 586 |
+
|
| 587 |
+
def _notify(self, job, text):
|
| 588 |
+
topic = self.store.get_setting("ntfy_topic") or os.environ.get("NTFY_TOPIC")
|
| 589 |
+
if not topic:
|
| 590 |
+
return
|
| 591 |
+
try:
|
| 592 |
+
req = urllib.request.Request(f"https://ntfy.sh/{topic.strip()}", data=text.encode("utf-8"), method="POST")
|
| 593 |
+
req.add_header("Title", f"Agent: {job.get('title') or job['id']}"[:200].encode("utf-8").decode("latin-1", "ignore"))
|
| 594 |
+
urllib.request.urlopen(req, timeout=15).read()
|
| 595 |
+
except Exception:
|
| 596 |
+
pass
|
| 597 |
+
|
| 598 |
+
def _run_safe(self, job_id, ctx):
|
| 599 |
+
try:
|
| 600 |
+
self._run(job_id, ctx)
|
| 601 |
+
except Exception as e:
|
| 602 |
+
traceback.print_exc()
|
| 603 |
+
self.store.update_job(job_id, status="error", error=str(e)[:2000])
|
| 604 |
+
self.store.add_event(job_id, "error", f"Nieoczekiwany błąd: {e}")
|
| 605 |
+
job = self.store.get_job(job_id) or {"id": job_id}
|
| 606 |
+
self._notify(job, f"❌ Błąd: {str(e)[:300]}")
|
| 607 |
+
finally:
|
| 608 |
+
with self.lock:
|
| 609 |
+
self.active.pop(job_id, None)
|
| 610 |
+
|
| 611 |
+
def _call_llm(self, job_id, ctx, provider, model, messages):
|
| 612 |
+
delays = [3, 6, 12, 25, 45, 60, 90, 120]
|
| 613 |
+
attempt = 0
|
| 614 |
+
while True:
|
| 615 |
+
if ctx["stop"]:
|
| 616 |
+
return None
|
| 617 |
+
try:
|
| 618 |
+
return chat(self.store, provider, model, messages, TOOLS)
|
| 619 |
+
except LLMError as e:
|
| 620 |
+
if not e.retryable or attempt >= len(delays):
|
| 621 |
+
raise
|
| 622 |
+
wait = min(e.retry_after or delays[attempt], 180)
|
| 623 |
+
attempt += 1
|
| 624 |
+
self.store.add_event(job_id, "info", f"Model chwilowo niedostępny ({_short(str(e), 120)}). Ponowienie za {int(wait)} s…")
|
| 625 |
+
for _ in range(int(wait)):
|
| 626 |
+
if ctx["stop"]:
|
| 627 |
+
return None
|
| 628 |
+
time.sleep(1)
|
| 629 |
+
|
| 630 |
+
def _run(self, job_id, ctx):
|
| 631 |
+
store = self.store
|
| 632 |
+
job = store.get_job(job_id, with_messages=True)
|
| 633 |
+
ws = self.workspace(job_id)
|
| 634 |
+
provider, model = job["provider"], job["model"]
|
| 635 |
+
if provider not in PROVIDERS:
|
| 636 |
+
raise ValueError(f"Nieznany dostawca: {provider}")
|
| 637 |
+
messages = json.loads(job["messages"] or "[]")
|
| 638 |
+
ctx["plan"] = json.loads(job["plan"] or "[]")
|
| 639 |
+
if not messages:
|
| 640 |
+
system = SYSTEM_PROMPT.format(tooling=_tooling_info(), cmd_max=CMD_TIMEOUT_MAX)
|
| 641 |
+
messages = [{"role": "system", "content": system},
|
| 642 |
+
{"role": "user", "content": job["prompt"]}]
|
| 643 |
+
store.add_event(job_id, "user", job["prompt"])
|
| 644 |
+
store.update_job(job_id, messages=messages)
|
| 645 |
+
messages = repair_history(messages)
|
| 646 |
+
store.add_event(job_id, "info", f"Start pracy · {PROVIDERS[provider]['name']} · {model}")
|
| 647 |
+
|
| 648 |
+
steps, run_steps = job["steps"] or 0, job["run_steps"] or 0
|
| 649 |
+
max_steps = job["max_steps"] or 80
|
| 650 |
+
nudges = 0
|
| 651 |
+
|
| 652 |
+
def save(**extra):
|
| 653 |
+
store.update_job(job_id, messages=messages, plan=ctx["plan"] or [], steps=steps, run_steps=run_steps, **extra)
|
| 654 |
+
|
| 655 |
+
while True:
|
| 656 |
+
if ctx["stop"]:
|
| 657 |
+
save(status="stopped")
|
| 658 |
+
store.add_event(job_id, "info", "Zatrzymano na prośbę użytkownika.")
|
| 659 |
+
return
|
| 660 |
+
if run_steps >= max_steps:
|
| 661 |
+
save(status="paused")
|
| 662 |
+
store.add_event(job_id, "info", f"Osiągnięto limit {max_steps} kroków. Napisz „kontynuuj”, aby agent pracował dalej.")
|
| 663 |
+
self._notify(job, f"⏸ Limit kroków ({max_steps}). Wyślij 'kontynuuj', by dokończyć.")
|
| 664 |
+
return
|
| 665 |
+
|
| 666 |
+
compact(messages)
|
| 667 |
+
resp = self._call_llm(job_id, ctx, provider, model, messages)
|
| 668 |
+
if resp is None:
|
| 669 |
+
continue # stop
|
| 670 |
+
usage = resp.get("usage") or {}
|
| 671 |
+
store.add_tokens(job_id, usage.get("prompt_tokens"), usage.get("completion_tokens"))
|
| 672 |
+
choices = resp.get("choices") or []
|
| 673 |
+
if not choices:
|
| 674 |
+
raise LLMError(f"Pusta odpowiedź modelu: {_short(json.dumps(resp), 300)}")
|
| 675 |
+
choice = choices[0]
|
| 676 |
+
msg = choice.get("message") or {}
|
| 677 |
+
steps += 1
|
| 678 |
+
run_steps += 1
|
| 679 |
+
|
| 680 |
+
content = msg.get("content")
|
| 681 |
+
if isinstance(content, list): # niektóre API zwracają listę części
|
| 682 |
+
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
| 683 |
+
tool_calls = msg.get("tool_calls") or []
|
| 684 |
+
for tc in tool_calls:
|
| 685 |
+
tc.setdefault("type", "function")
|
| 686 |
+
if not tc.get("id"):
|
| 687 |
+
tc["id"] = "call_" + secrets.token_hex(6)
|
| 688 |
+
|
| 689 |
+
assistant = {"role": "assistant", "content": content if content else (None if tool_calls else "")}
|
| 690 |
+
if tool_calls:
|
| 691 |
+
assistant["tool_calls"] = tool_calls
|
| 692 |
+
messages.append(assistant)
|
| 693 |
+
save() # zapis przed wykonaniem narzędzi — po restarcie historia zostanie naprawiona i praca wznowiona
|
| 694 |
+
if content and content.strip():
|
| 695 |
+
store.add_event(job_id, "assistant", content.strip())
|
| 696 |
+
|
| 697 |
+
if not tool_calls:
|
| 698 |
+
if choice.get("finish_reason") == "length":
|
| 699 |
+
messages.append({"role": "user", "content": "Your reply was cut off (output limit). Continue, and write big files in smaller parts with write_file(append=true)."})
|
| 700 |
+
save()
|
| 701 |
+
continue
|
| 702 |
+
nudges += 1
|
| 703 |
+
if nudges >= 2:
|
| 704 |
+
summary = (content or "").strip() or "Agent zakończył pracę."
|
| 705 |
+
save(status="done", summary=summary)
|
| 706 |
+
store.add_event(job_id, "done", summary)
|
| 707 |
+
self._notify(job, "✅ Gotowe: " + _short(summary, 300))
|
| 708 |
+
return
|
| 709 |
+
messages.append({"role": "user", "content": "Continue working autonomously using the tools. When everything is complete and verified, call the finish tool with a summary."})
|
| 710 |
+
save()
|
| 711 |
+
continue
|
| 712 |
+
nudges = 0
|
| 713 |
+
|
| 714 |
+
finished_summary = None
|
| 715 |
+
for tc in tool_calls:
|
| 716 |
+
fn = tc.get("function") or {}
|
| 717 |
+
name = fn.get("name", "")
|
| 718 |
+
try:
|
| 719 |
+
args = _parse_args(fn.get("arguments"))
|
| 720 |
+
except Exception:
|
| 721 |
+
result = ("BŁĄD: argumenty narzędzia nie są poprawnym JSON-em (prawdopodobnie ucięte przez limit długości). "
|
| 722 |
+
"Zapisuj duże pliki w mniejszych częściach (write_file z append=true).")
|
| 723 |
+
store.add_event(job_id, "tool_error", f"{name}: niepoprawne argumenty")
|
| 724 |
+
messages.append({"role": "tool", "tool_call_id": tc["id"], "name": name, "content": result})
|
| 725 |
+
continue
|
| 726 |
+
if name == "finish":
|
| 727 |
+
finished_summary = str(args.get("summary") or "Gotowe.")
|
| 728 |
+
messages.append({"role": "tool", "tool_call_id": tc["id"], "name": name, "content": "OK"})
|
| 729 |
+
continue
|
| 730 |
+
store.add_event(job_id, "tool", _describe_call(name, args), {"name": name})
|
| 731 |
+
t0 = time.time()
|
| 732 |
+
try:
|
| 733 |
+
result = run_tool(ws, name, args, ctx)
|
| 734 |
+
except Exception as e:
|
| 735 |
+
result = f"BŁĄD: {type(e).__name__}: {e}"
|
| 736 |
+
is_err = result.startswith("BŁĄD") or (name == "run_command" and not result.startswith("[kod wyjścia 0]"))
|
| 737 |
+
store.add_event(job_id, "tool_error" if is_err else "result", _clip(result, 4000),
|
| 738 |
+
{"name": name, "secs": round(time.time() - t0, 1)})
|
| 739 |
+
messages.append({"role": "tool", "tool_call_id": tc["id"], "name": name, "content": result})
|
| 740 |
+
if ctx["stop"]:
|
| 741 |
+
break
|
| 742 |
+
messages[:] = repair_history(messages)
|
| 743 |
+
|
| 744 |
+
if finished_summary is not None:
|
| 745 |
+
save(status="done", summary=finished_summary)
|
| 746 |
+
store.add_event(job_id, "done", finished_summary)
|
| 747 |
+
self._notify(job, "✅ Gotowe: " + _short(finished_summary, 300))
|
| 748 |
+
return
|
| 749 |
+
save()
|
app.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serwer HTTP: panel mobilny + API. Uruchom: python app.py (zero zależności — tylko biblioteka standardowa)."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import hmac
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import mimetypes
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import secrets
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
import traceback
|
| 14 |
+
import urllib.parse
|
| 15 |
+
import zipfile
|
| 16 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from agent import IGNORED_DIRS, PROVIDERS, LLMError, Runner, get_api_key, list_models
|
| 20 |
+
from store import Store
|
| 21 |
+
|
| 22 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 23 |
+
DATA_DIR = Path(os.environ.get("DATA_DIR", BASE_DIR / "data")).resolve()
|
| 24 |
+
PORT = int(os.environ.get("PORT", "7860"))
|
| 25 |
+
|
| 26 |
+
store = Store(str(DATA_DIR / "agent.db"))
|
| 27 |
+
runner = Runner(store, DATA_DIR, max_parallel=int(os.environ.get("MAX_PARALLEL_JOBS", "2")))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def app_password():
|
| 31 |
+
pw = os.environ.get("APP_PASSWORD") or store.get_setting("_generated_password")
|
| 32 |
+
if not pw:
|
| 33 |
+
pw = secrets.token_urlsafe(9)
|
| 34 |
+
store.set_setting("_generated_password", pw)
|
| 35 |
+
return pw
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def make_token():
|
| 39 |
+
return hmac.new(store.secret().encode(), app_password().encode(), hashlib.sha256).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def mask(key):
|
| 43 |
+
return ("•••• " + key[-4:]) if key else ""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Handler(BaseHTTPRequestHandler):
|
| 47 |
+
server_version = "CodingAgent/1.0"
|
| 48 |
+
|
| 49 |
+
# --- pomocnicze ---
|
| 50 |
+
def log_message(self, fmt, *args):
|
| 51 |
+
if "/api/health" not in (self.path or ""):
|
| 52 |
+
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
|
| 53 |
+
|
| 54 |
+
def send_json(self, obj, code=200):
|
| 55 |
+
body = json.dumps(obj, ensure_ascii=False).encode()
|
| 56 |
+
self.send_response(code)
|
| 57 |
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
| 58 |
+
self.send_header("Content-Length", str(len(body)))
|
| 59 |
+
self.send_header("Cache-Control", "no-store")
|
| 60 |
+
self.end_headers()
|
| 61 |
+
self.wfile.write(body)
|
| 62 |
+
|
| 63 |
+
def err(self, msg, code=400):
|
| 64 |
+
self.send_json({"error": msg}, code)
|
| 65 |
+
|
| 66 |
+
def body_json(self):
|
| 67 |
+
n = int(self.headers.get("Content-Length") or 0)
|
| 68 |
+
if n > 5_000_000:
|
| 69 |
+
raise ValueError("Za duże żądanie")
|
| 70 |
+
raw = self.rfile.read(n) if n else b"{}"
|
| 71 |
+
return json.loads(raw.decode() or "{}")
|
| 72 |
+
|
| 73 |
+
def authed(self, query):
|
| 74 |
+
token = ""
|
| 75 |
+
auth = self.headers.get("Authorization", "")
|
| 76 |
+
if auth.startswith("Bearer "):
|
| 77 |
+
token = auth[7:].strip()
|
| 78 |
+
token = token or (query.get("t") or [""])[0]
|
| 79 |
+
return bool(token) and hmac.compare_digest(token, make_token())
|
| 80 |
+
|
| 81 |
+
def job_or_404(self, job_id):
|
| 82 |
+
job = store.get_job(job_id)
|
| 83 |
+
if not job:
|
| 84 |
+
self.err("Nie znaleziono zadania", 404)
|
| 85 |
+
return job
|
| 86 |
+
|
| 87 |
+
# --- routing ---
|
| 88 |
+
def do_GET(self):
|
| 89 |
+
self.route("GET")
|
| 90 |
+
|
| 91 |
+
def do_POST(self):
|
| 92 |
+
self.route("POST")
|
| 93 |
+
|
| 94 |
+
def do_DELETE(self):
|
| 95 |
+
self.route("DELETE")
|
| 96 |
+
|
| 97 |
+
def route(self, method):
|
| 98 |
+
try:
|
| 99 |
+
u = urllib.parse.urlparse(self.path)
|
| 100 |
+
path, query = u.path, urllib.parse.parse_qs(u.query)
|
| 101 |
+
if method == "GET" and path in ("/", "/index.html"):
|
| 102 |
+
return self.static("index.html")
|
| 103 |
+
if method == "GET" and path in ("/manifest.json", "/icon.svg"):
|
| 104 |
+
return self.static(path.lstrip("/"))
|
| 105 |
+
if path == "/api/health":
|
| 106 |
+
return self.send_json({"ok": True, "time": time.time()})
|
| 107 |
+
if path == "/api/login" and method == "POST":
|
| 108 |
+
data = self.body_json()
|
| 109 |
+
if hmac.compare_digest(str(data.get("password", "")), app_password()):
|
| 110 |
+
return self.send_json({"token": make_token()})
|
| 111 |
+
time.sleep(1.5)
|
| 112 |
+
return self.err("Złe hasło", 401)
|
| 113 |
+
if not path.startswith("/api/"):
|
| 114 |
+
return self.err("Nie znaleziono", 404)
|
| 115 |
+
if not self.authed(query):
|
| 116 |
+
return self.err("Wymagane logowanie", 401)
|
| 117 |
+
return self.api(method, path, query)
|
| 118 |
+
except (BrokenPipeError, ConnectionResetError):
|
| 119 |
+
pass
|
| 120 |
+
except Exception as e:
|
| 121 |
+
traceback.print_exc()
|
| 122 |
+
try:
|
| 123 |
+
self.err(f"Błąd serwera: {e}", 500)
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
def static(self, name):
|
| 128 |
+
p = BASE_DIR / "static" / name
|
| 129 |
+
if not p.is_file():
|
| 130 |
+
p = BASE_DIR / name # Hugging Face: pliki wgrane bez folderu static/
|
| 131 |
+
if not p.is_file():
|
| 132 |
+
return self.err("Nie znaleziono", 404)
|
| 133 |
+
body = p.read_bytes()
|
| 134 |
+
self.send_response(200)
|
| 135 |
+
self.send_header("Content-Type", mimetypes.guess_type(name)[0] or "text/html; charset=utf-8")
|
| 136 |
+
self.send_header("Content-Length", str(len(body)))
|
| 137 |
+
self.send_header("Cache-Control", "no-cache")
|
| 138 |
+
self.end_headers()
|
| 139 |
+
self.wfile.write(body)
|
| 140 |
+
|
| 141 |
+
def api(self, method, path, query):
|
| 142 |
+
# ustawienia
|
| 143 |
+
if path == "/api/settings":
|
| 144 |
+
if method == "GET":
|
| 145 |
+
return self.send_json({
|
| 146 |
+
"providers": {k: {"name": v["name"], "default_model": v["default_model"], "suggested": v["suggested"],
|
| 147 |
+
"key": mask(get_api_key(store, k)),
|
| 148 |
+
"key_from_env": bool(os.environ.get(v["key_env"])) and not store.get_setting(f"key_{k}")}
|
| 149 |
+
for k, v in PROVIDERS.items()},
|
| 150 |
+
"default_provider": store.get_setting("default_provider", "gemini"),
|
| 151 |
+
"default_model_gemini": store.get_setting("default_model_gemini", ""),
|
| 152 |
+
"default_model_nvidia": store.get_setting("default_model_nvidia", ""),
|
| 153 |
+
"ntfy_topic": store.get_setting("ntfy_topic", ""),
|
| 154 |
+
})
|
| 155 |
+
data = self.body_json()
|
| 156 |
+
for k in ("gemini", "nvidia"):
|
| 157 |
+
if f"key_{k}" in data and data[f"key_{k}"] is not None:
|
| 158 |
+
store.set_setting(f"key_{k}", data[f"key_{k}"].strip())
|
| 159 |
+
for k in ("default_provider", "default_model_gemini", "default_model_nvidia", "ntfy_topic"):
|
| 160 |
+
if k in data:
|
| 161 |
+
store.set_setting(k, str(data[k]).strip())
|
| 162 |
+
return self.send_json({"ok": True})
|
| 163 |
+
|
| 164 |
+
if path == "/api/models" and method == "GET":
|
| 165 |
+
prov = (query.get("provider") or ["gemini"])[0]
|
| 166 |
+
if prov not in PROVIDERS:
|
| 167 |
+
return self.err("Nieznany dostawca")
|
| 168 |
+
try:
|
| 169 |
+
return self.send_json({"models": list_models(store, prov)})
|
| 170 |
+
except LLMError as e:
|
| 171 |
+
return self.send_json({"models": [], "error": str(e)[:500]})
|
| 172 |
+
|
| 173 |
+
# zadania
|
| 174 |
+
if path == "/api/jobs":
|
| 175 |
+
if method == "GET":
|
| 176 |
+
jobs = store.list_jobs()
|
| 177 |
+
for j in jobs:
|
| 178 |
+
j.pop("plan", None)
|
| 179 |
+
j["prompt"] = (j["prompt"] or "")[:200]
|
| 180 |
+
return self.send_json({"jobs": jobs})
|
| 181 |
+
if method == "POST":
|
| 182 |
+
data = self.body_json()
|
| 183 |
+
prompt = (data.get("prompt") or "").strip()
|
| 184 |
+
provider = data.get("provider") or "gemini"
|
| 185 |
+
if not prompt:
|
| 186 |
+
return self.err("Wpisz polecenie dla agenta")
|
| 187 |
+
if provider not in PROVIDERS:
|
| 188 |
+
return self.err("Nieznany dostawca")
|
| 189 |
+
if not get_api_key(store, provider):
|
| 190 |
+
return self.err(f"Brak klucza API {PROVIDERS[provider]['name']} — dodaj go w Ustawieniach")
|
| 191 |
+
model = (data.get("model") or PROVIDERS[provider]["default_model"]).strip()
|
| 192 |
+
title = (data.get("title") or "").strip() or prompt.splitlines()[0][:60]
|
| 193 |
+
max_steps = max(5, min(int(data.get("max_steps") or 80), 1000))
|
| 194 |
+
job_id = store.create_job(title, prompt, provider, model, max_steps)
|
| 195 |
+
return self.send_json({"id": job_id})
|
| 196 |
+
|
| 197 |
+
m = re.match(r"^/api/jobs/([\w\-]+)(/.*)?$", path)
|
| 198 |
+
if m:
|
| 199 |
+
job_id, sub = m.group(1), m.group(2) or ""
|
| 200 |
+
job = self.job_or_404(job_id)
|
| 201 |
+
if not job:
|
| 202 |
+
return
|
| 203 |
+
ws = runner.workspace(job_id)
|
| 204 |
+
|
| 205 |
+
if sub == "" and method == "GET":
|
| 206 |
+
job["plan"] = json.loads(job.get("plan") or "[]")
|
| 207 |
+
job["active"] = runner.is_active(job_id)
|
| 208 |
+
return self.send_json(job)
|
| 209 |
+
if sub == "" and method == "DELETE":
|
| 210 |
+
runner.stop(job_id)
|
| 211 |
+
for _ in range(20):
|
| 212 |
+
if not runner.is_active(job_id):
|
| 213 |
+
break
|
| 214 |
+
time.sleep(0.5)
|
| 215 |
+
store.delete_job(job_id)
|
| 216 |
+
shutil.rmtree(ws.root, ignore_errors=True)
|
| 217 |
+
return self.send_json({"ok": True})
|
| 218 |
+
if sub == "/events" and method == "GET":
|
| 219 |
+
after = int((query.get("after") or ["0"])[0])
|
| 220 |
+
return self.send_json({"events": store.events(job_id, after)})
|
| 221 |
+
if sub == "/stop" and method == "POST":
|
| 222 |
+
runner.stop(job_id)
|
| 223 |
+
return self.send_json({"ok": True})
|
| 224 |
+
if sub == "/message" and method == "POST":
|
| 225 |
+
if job["status"] in ("running", "queued") or runner.is_active(job_id):
|
| 226 |
+
return self.err("Agent jeszcze pracuje — poczekaj albo go zatrzymaj")
|
| 227 |
+
data = self.body_json()
|
| 228 |
+
text = (data.get("text") or "").strip()
|
| 229 |
+
if not text:
|
| 230 |
+
return self.err("Pusta wiadomość")
|
| 231 |
+
full = store.get_job(job_id, with_messages=True)
|
| 232 |
+
msgs = json.loads(full["messages"] or "[]")
|
| 233 |
+
upd = {}
|
| 234 |
+
if data.get("provider") in PROVIDERS:
|
| 235 |
+
upd["provider"] = data["provider"]
|
| 236 |
+
if data.get("model"):
|
| 237 |
+
upd["model"] = data["model"].strip()
|
| 238 |
+
if not msgs: # zadanie nigdy nie wystartowało — traktuj jako nowe polecenie
|
| 239 |
+
upd["prompt"] = (job["prompt"] + "\n\n" + text)
|
| 240 |
+
else:
|
| 241 |
+
msgs.append({"role": "user", "content": text})
|
| 242 |
+
store.add_event(job_id, "user", text)
|
| 243 |
+
store.update_job(job_id, messages=msgs, status="queued", run_steps=0, error=None, resumes=0, **upd)
|
| 244 |
+
return self.send_json({"ok": True})
|
| 245 |
+
if sub == "/files" and method == "GET":
|
| 246 |
+
return self.send_json({"files": ws.all_files()})
|
| 247 |
+
if sub == "/file" and method == "GET":
|
| 248 |
+
rel = (query.get("path") or [""])[0]
|
| 249 |
+
p = ws.path(rel)
|
| 250 |
+
if not p.is_file():
|
| 251 |
+
return self.err("Brak pliku", 404)
|
| 252 |
+
if (query.get("raw") or ["0"])[0] == "1":
|
| 253 |
+
body = p.read_bytes()
|
| 254 |
+
self.send_response(200)
|
| 255 |
+
self.send_header("Content-Type", mimetypes.guess_type(p.name)[0] or "application/octet-stream")
|
| 256 |
+
self.send_header("Content-Disposition", f"attachment; filename*=UTF-8''{urllib.parse.quote(p.name)}")
|
| 257 |
+
self.send_header("Content-Length", str(len(body)))
|
| 258 |
+
self.end_headers()
|
| 259 |
+
self.wfile.write(body)
|
| 260 |
+
return
|
| 261 |
+
size = p.stat().st_size
|
| 262 |
+
raw = p.read_bytes()[:400_000]
|
| 263 |
+
binary = b"\x00" in raw[:8000]
|
| 264 |
+
return self.send_json({"path": rel, "size": size, "binary": binary,
|
| 265 |
+
"content": "" if binary else raw.decode("utf-8", "replace"),
|
| 266 |
+
"truncated": size > 400_000})
|
| 267 |
+
if sub == "/download" and method == "GET":
|
| 268 |
+
buf = io.BytesIO()
|
| 269 |
+
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 270 |
+
for dirpath, dirnames, filenames in os.walk(ws.root):
|
| 271 |
+
dirnames[:] = [d for d in dirnames if d not in IGNORED_DIRS - {".git"}]
|
| 272 |
+
for f in filenames:
|
| 273 |
+
fp = Path(dirpath) / f
|
| 274 |
+
z.write(fp, str(fp.relative_to(ws.root)))
|
| 275 |
+
body = buf.getvalue()
|
| 276 |
+
name = re.sub(r"[^\w\-]+", "_", job.get("title") or job_id)[:50] or job_id
|
| 277 |
+
self.send_response(200)
|
| 278 |
+
self.send_header("Content-Type", "application/zip")
|
| 279 |
+
self.send_header("Content-Disposition", f'attachment; filename="{name}.zip"')
|
| 280 |
+
self.send_header("Content-Length", str(len(body)))
|
| 281 |
+
self.end_headers()
|
| 282 |
+
self.wfile.write(body)
|
| 283 |
+
return
|
| 284 |
+
return self.err("Nie znaleziono", 404)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def main():
|
| 288 |
+
pw_source = "APP_PASSWORD" if os.environ.get("APP_PASSWORD") else "wygenerowane"
|
| 289 |
+
print(f"▶ Agent programowania działa na porcie {PORT} · dane: {DATA_DIR}", flush=True)
|
| 290 |
+
print(f"▶ Hasło do panelu ({pw_source}): {app_password() if pw_source != 'APP_PASSWORD' else '(z APP_PASSWORD)'}", flush=True)
|
| 291 |
+
srv = ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
|
| 292 |
+
srv.daemon_threads = True
|
| 293 |
+
try:
|
| 294 |
+
srv.serve_forever()
|
| 295 |
+
except KeyboardInterrupt:
|
| 296 |
+
pass
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
if __name__ == "__main__":
|
| 300 |
+
main()
|
icon.svg
ADDED
|
|
index.html
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="pl">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
| 6 |
+
<meta name="theme-color" content="#0e1116">
|
| 7 |
+
<link rel="manifest" href="/manifest.json">
|
| 8 |
+
<link rel="icon" href="/icon.svg">
|
| 9 |
+
<title>Agent Kodu</title>
|
| 10 |
+
<style>
|
| 11 |
+
:root{
|
| 12 |
+
--bg:#0e1116; --panel:#161b22; --panel2:#1c232c; --line:#2a323d; --text:#e6edf3; --muted:#8b97a5;
|
| 13 |
+
--acc:#7ee787; --acc2:#3fb950; --blue:#79c0ff; --warn:#e3b341; --err:#ff7b72; --r:14px;
|
| 14 |
+
--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
| 15 |
+
}
|
| 16 |
+
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
|
| 17 |
+
html,body{margin:0;background:var(--bg);color:var(--text);font:15px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
|
| 18 |
+
a{color:var(--blue)}
|
| 19 |
+
header{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:10px;padding:12px 16px;
|
| 20 |
+
padding-top:max(12px,env(safe-area-inset-top));background:rgba(14,17,22,.92);backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}
|
| 21 |
+
header h1{font-size:17px;margin:0;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 22 |
+
.logo{width:26px;height:26px;border-radius:8px;background:linear-gradient(135deg,var(--acc),var(--blue));display:grid;place-items:center;color:#0e1116;font-weight:800;font-family:var(--mono);font-size:13px;flex:none}
|
| 23 |
+
main{max-width:760px;margin:0 auto;padding:16px 16px 120px}
|
| 24 |
+
button,.btn{font:inherit;border:1px solid var(--line);background:var(--panel2);color:var(--text);border-radius:12px;padding:10px 14px;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:6px;justify-content:center}
|
| 25 |
+
button:active{transform:scale(.98)}
|
| 26 |
+
button.primary{background:var(--acc2);border-color:var(--acc2);color:#04130a;font-weight:650}
|
| 27 |
+
button.danger{color:var(--err)}
|
| 28 |
+
button.ghost{background:transparent;border-color:transparent;color:var(--muted);padding:8px}
|
| 29 |
+
button:disabled{opacity:.45}
|
| 30 |
+
input,textarea,select{width:100%;font:inherit;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:11px 12px;outline:none}
|
| 31 |
+
input:focus,textarea:focus,select:focus{border-color:var(--blue)}
|
| 32 |
+
textarea{resize:vertical;min-height:110px}
|
| 33 |
+
label{display:block;font-size:13px;color:var(--muted);margin:14px 0 6px}
|
| 34 |
+
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:14px;margin-bottom:10px}
|
| 35 |
+
.row{display:flex;gap:8px;align-items:center}
|
| 36 |
+
.row > *{flex:1}
|
| 37 |
+
.muted{color:var(--muted)}
|
| 38 |
+
.small{font-size:12.5px}
|
| 39 |
+
.job{display:block;color:inherit;text-decoration:none}
|
| 40 |
+
.job .t{font-weight:600;margin-bottom:4px}
|
| 41 |
+
.badge{display:inline-flex;align-items:center;gap:5px;font-size:12px;padding:3px 8px;border-radius:99px;background:var(--panel2);border:1px solid var(--line);white-space:nowrap}
|
| 42 |
+
.badge::before{content:"";width:7px;height:7px;border-radius:50%;background:var(--muted)}
|
| 43 |
+
.s-running::before,.s-queued::before{background:var(--warn);animation:pulse 1.2s infinite}
|
| 44 |
+
.s-done::before{background:var(--acc)}
|
| 45 |
+
.s-error::before,.s-interrupted::before{background:var(--err)}
|
| 46 |
+
.s-paused::before,.s-stopped::before{background:var(--blue)}
|
| 47 |
+
@keyframes pulse{50%{opacity:.25}}
|
| 48 |
+
.fab{position:fixed;right:18px;bottom:max(18px,env(safe-area-inset-bottom));z-index:6;border-radius:99px;padding:14px 20px;box-shadow:0 8px 30px rgba(0,0,0,.5)}
|
| 49 |
+
.tabs{display:flex;gap:6px;margin:12px 0;position:sticky;top:57px;z-index:4;background:var(--bg);padding:6px 0}
|
| 50 |
+
.tabs button{flex:1;padding:8px}
|
| 51 |
+
.tabs button.on{background:var(--text);color:var(--bg);border-color:var(--text);font-weight:600}
|
| 52 |
+
.ev{border-left:3px solid var(--line);padding:6px 10px;margin:6px 0;white-space:pre-wrap;word-break:break-word;font-size:14px}
|
| 53 |
+
.ev .k{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin-bottom:2px}
|
| 54 |
+
.ev.user{border-color:var(--blue);background:rgba(121,192,255,.07);border-radius:0 10px 10px 0}
|
| 55 |
+
.ev.assistant{border-color:var(--acc)}
|
| 56 |
+
.ev.tool{font-family:var(--mono);font-size:12.5px;color:var(--blue);border-color:transparent;padding:2px 10px}
|
| 57 |
+
.ev.result,.ev.tool_error{font-family:var(--mono);font-size:12px;color:var(--muted);border-color:transparent;padding:0 10px}
|
| 58 |
+
.ev.tool_error{color:#ffa198}
|
| 59 |
+
.ev.info{color:var(--muted);font-size:13px;border-color:transparent}
|
| 60 |
+
.ev.error{border-color:var(--err);color:var(--err)}
|
| 61 |
+
.ev.done{border-color:var(--acc);background:rgba(126,231,135,.08);border-radius:0 10px 10px 0}
|
| 62 |
+
details summary{cursor:pointer;list-style:none}
|
| 63 |
+
details summary::-webkit-details-marker{display:none}
|
| 64 |
+
details pre{margin:4px 0 0;max-height:260px;overflow:auto;background:var(--panel);padding:8px;border-radius:8px}
|
| 65 |
+
.plan li{margin:6px 0;list-style:none;padding-left:26px;position:relative}
|
| 66 |
+
.plan li::before{content:"○";position:absolute;left:4px;color:var(--muted)}
|
| 67 |
+
.plan li.d{color:var(--muted);text-decoration:line-through}
|
| 68 |
+
.plan li.d::before{content:"✓";color:var(--acc);text-decoration:none}
|
| 69 |
+
.plan ul{padding:0;margin:0}
|
| 70 |
+
.file{display:flex;justify-content:space-between;gap:10px;padding:9px 4px;border-bottom:1px solid var(--line);font-family:var(--mono);font-size:13px;cursor:pointer;word-break:break-all}
|
| 71 |
+
.file span:last-child{color:var(--muted);white-space:nowrap}
|
| 72 |
+
.composer{position:fixed;left:0;right:0;bottom:0;z-index:6;background:rgba(14,17,22,.96);border-top:1px solid var(--line);padding:10px 12px;padding-bottom:max(10px,env(safe-area-inset-bottom))}
|
| 73 |
+
.composer .in{max-width:760px;margin:0 auto;display:flex;gap:8px;align-items:flex-end}
|
| 74 |
+
.composer textarea{min-height:44px;max-height:160px;padding:10px 12px}
|
| 75 |
+
.composer button{height:44px}
|
| 76 |
+
.modal{position:fixed;inset:0;z-index:20;background:rgba(0,0,0,.6);display:flex;align-items:flex-end}
|
| 77 |
+
.modal .sheet{background:var(--bg);width:100%;max-height:92vh;border-radius:18px 18px 0 0;border-top:1px solid var(--line);display:flex;flex-direction:column}
|
| 78 |
+
.modal .sheet header{position:static;border-radius:18px 18px 0 0}
|
| 79 |
+
.modal pre{margin:0;padding:14px;overflow:auto;font:12.5px/1.5 var(--mono);flex:1;white-space:pre}
|
| 80 |
+
.stats{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
|
| 81 |
+
.toast{position:fixed;left:50%;transform:translateX(-50%);bottom:90px;z-index:30;background:var(--text);color:var(--bg);padding:10px 16px;border-radius:12px;font-weight:500;max-width:90vw}
|
| 82 |
+
.center{text-align:center}
|
| 83 |
+
.empty{padding:40px 10px;text-align:center;color:var(--muted)}
|
| 84 |
+
.hint{font-size:12.5px;color:var(--muted);margin-top:6px}
|
| 85 |
+
.summary{white-space:pre-wrap}
|
| 86 |
+
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--muted);border-top-color:transparent;border-radius:50%;animation:sp 0.8s linear infinite;vertical-align:-2px}
|
| 87 |
+
@keyframes sp{to{transform:rotate(360deg)}}
|
| 88 |
+
</style>
|
| 89 |
+
</head>
|
| 90 |
+
<body>
|
| 91 |
+
<div id="app"></div>
|
| 92 |
+
<script>
|
| 93 |
+
const $ = (s, el=document) => el.querySelector(s);
|
| 94 |
+
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
| 95 |
+
const STATUS = {queued:"w kolejce", running:"pracuje", done:"gotowe", error:"błąd", stopped:"zatrzymane", paused:"wstrzymane (limit)", interrupted:"przerwane"};
|
| 96 |
+
let token = localStorage.getItem("agent_token") || "";
|
| 97 |
+
let timers = [];
|
| 98 |
+
let settingsCache = null;
|
| 99 |
+
|
| 100 |
+
function clearTimers(){ timers.forEach(clearTimeout); timers = []; }
|
| 101 |
+
function toast(msg){ const t=document.createElement("div"); t.className="toast"; t.textContent=msg; document.body.append(t); setTimeout(()=>t.remove(),2600); }
|
| 102 |
+
function ago(ts){ const s=(Date.now()/1000-ts); if(s<60) return "przed chwilą"; if(s<3600) return Math.floor(s/60)+" min temu"; if(s<86400) return Math.floor(s/3600)+" godz. temu"; return new Date(ts*1000).toLocaleString("pl-PL"); }
|
| 103 |
+
function fmtSize(b){ return b<1024? b+" B" : b<1048576? (b/1024).toFixed(1)+" KB" : (b/1048576).toFixed(1)+" MB"; }
|
| 104 |
+
|
| 105 |
+
async function api(path, opts={}){
|
| 106 |
+
const res = await fetch(path, {...opts, headers:{"Content-Type":"application/json", "Authorization":"Bearer "+token, ...(opts.headers||{})},
|
| 107 |
+
body: opts.body && typeof opts.body!=="string" ? JSON.stringify(opts.body) : opts.body});
|
| 108 |
+
if(res.status===401 && path!=="/api/login"){ token=""; localStorage.removeItem("agent_token"); location.hash="#/login"; throw new Error("Zaloguj się"); }
|
| 109 |
+
const data = await res.json().catch(()=>({}));
|
| 110 |
+
if(!res.ok) throw new Error(data.error || ("HTTP "+res.status));
|
| 111 |
+
return data;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
function shell(title, inner, {back=null, right=""}={}){
|
| 115 |
+
$("#app").innerHTML = `
|
| 116 |
+
<header>${back? `<button class="ghost" onclick="location.hash='${back}'">←</button>` : `<div class="logo"></></div>`}
|
| 117 |
+
<h1>${esc(title)}</h1>${right}</header>
|
| 118 |
+
<main>${inner}</main>`;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// ---------------- widoki ----------------
|
| 122 |
+
function viewLogin(){
|
| 123 |
+
shell("Agent Kodu", `
|
| 124 |
+
<div class="card" style="margin-top:30px">
|
| 125 |
+
<h2 style="margin:0 0 6px">Zaloguj się</h2>
|
| 126 |
+
<p class="muted small" style="margin:0">Hasło ustawiasz zmienną <code>APP_PASSWORD</code> na serwerze (albo znajdziesz wygenerowane w logach przy starcie).</p>
|
| 127 |
+
<form id="f"><label>Hasło</label><input type="password" id="pw" autocomplete="current-password" required>
|
| 128 |
+
<button class="primary" style="width:100%;margin-top:14px">Wejdź</button></form>
|
| 129 |
+
</div>`);
|
| 130 |
+
$("#f").onsubmit = async e => {
|
| 131 |
+
e.preventDefault();
|
| 132 |
+
try{ const r = await api("/api/login",{method:"POST", body:{password:$("#pw").value}}); token=r.token; localStorage.setItem("agent_token",token); location.hash="#/"; }
|
| 133 |
+
catch(err){ toast(err.message); }
|
| 134 |
+
};
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
async function viewList(){
|
| 138 |
+
shell("Agent Kodu", `<div id="list"><div class="empty"><span class="spin"></span></div></div>
|
| 139 |
+
<button class="primary fab" onclick="location.hash='#/new'">+ Nowe zadanie</button>`,
|
| 140 |
+
{right:`<button class="ghost" onclick="location.hash='#/settings'" aria-label="Ustawienia">⚙︎</button>`});
|
| 141 |
+
const load = async () => {
|
| 142 |
+
try{
|
| 143 |
+
const {jobs} = await api("/api/jobs");
|
| 144 |
+
const el = $("#list"); if(!el) return;
|
| 145 |
+
el.innerHTML = jobs.length ? jobs.map(j => `
|
| 146 |
+
<a class="card job" href="#/job/${j.id}">
|
| 147 |
+
<div class="row" style="align-items:flex-start"><div class="t">${esc(j.title)}</div>
|
| 148 |
+
<div style="flex:none"><span class="badge s-${j.status}">${STATUS[j.status]||j.status}</span></div></div>
|
| 149 |
+
<div class="muted small">${esc(j.provider)} · ${esc(j.model)} · ${j.steps} kroków · ${ago(j.updated)}</div>
|
| 150 |
+
</a>`).join("") :
|
| 151 |
+
`<div class="empty"><div style="font-size:40px">🤖</div><p>Brak zadań.<br>Napisz agentowi, co ma zbudować — będzie pracował na serwerze, nawet gdy zamkniesz przeglądarkę.</p></div>`;
|
| 152 |
+
if(jobs.some(j=>["running","queued"].includes(j.status))) timers.push(setTimeout(load, 4000));
|
| 153 |
+
}catch(e){ toast(e.message); }
|
| 154 |
+
};
|
| 155 |
+
load();
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
async function getSettings(force){ if(!settingsCache || force) settingsCache = await api("/api/settings"); return settingsCache; }
|
| 159 |
+
|
| 160 |
+
async function fillModels(provider, input, listEl, force=false){
|
| 161 |
+
const s = await getSettings();
|
| 162 |
+
const p = s.providers[provider];
|
| 163 |
+
let opts = [...p.suggested];
|
| 164 |
+
listEl.innerHTML = opts.map(m=>`<option value="${esc(m)}">`).join("");
|
| 165 |
+
if(force || !input.value) input.value = s["default_model_"+provider] || p.default_model;
|
| 166 |
+
try{
|
| 167 |
+
const r = await api("/api/models?provider="+provider);
|
| 168 |
+
if(r.models && r.models.length){ opts = [...new Set([...opts, ...r.models])]; listEl.innerHTML = opts.map(m=>`<option value="${esc(m)}">`).join(""); }
|
| 169 |
+
return r;
|
| 170 |
+
}catch(e){ return {error:e.message}; }
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
async function viewNew(){
|
| 174 |
+
const s = await getSettings(true).catch(e=>{toast(e.message); return null;}); if(!s) return;
|
| 175 |
+
const noKeys = !s.providers.gemini.key && !s.providers.nvidia.key;
|
| 176 |
+
shell("Nowe zadanie", `
|
| 177 |
+
${noKeys? `<div class="card" style="border-color:var(--warn)">⚠️ Nie masz jeszcze klucza API. <a href="#/settings">Dodaj go w Ustawieniach</a>.</div>`:""}
|
| 178 |
+
<form id="f">
|
| 179 |
+
<label>Co agent ma zbudować?</label>
|
| 180 |
+
<textarea id="prompt" rows="9" placeholder="Np. Zrób aplikację webową do śledzenia wydatków: dodawanie kategorii, wykres miesięczny, zapis w localStorage, ciemny motyw. Ma działać na telefonie." required></textarea>
|
| 181 |
+
<div class="row">
|
| 182 |
+
<div><label>Model od</label><select id="provider"><option value="gemini">Google Gemini</option><option value="nvidia">NVIDIA NIM</option></select></div>
|
| 183 |
+
<div><label>Limit kroków</label><input id="steps" type="number" min="5" max="1000" value="80"></div>
|
| 184 |
+
</div>
|
| 185 |
+
<label>Model</label>
|
| 186 |
+
<div class="row"><input id="model" list="models" autocomplete="off" spellcheck="false"><button type="button" id="refresh" style="flex:none">↻</button></div>
|
| 187 |
+
<datalist id="models"></datalist>
|
| 188 |
+
<div class="hint" id="mhint">Wpisz lub wybierz z listy. ↻ pobiera aktualną listę modeli z API.</div>
|
| 189 |
+
<label>Nazwa (opcjonalnie)</label><input id="title" placeholder="np. Tracker wydatków">
|
| 190 |
+
<button class="primary" style="width:100%;margin-top:18px;padding:14px">🚀 Uruchom agenta</button>
|
| 191 |
+
<p class="hint center">Po starcie możesz zamknąć przeglądarkę — praca trwa na serwerze.</p>
|
| 192 |
+
</form>`, {back:"#/"});
|
| 193 |
+
const prov=$("#provider"), model=$("#model"), list=$("#models");
|
| 194 |
+
prov.value = s.default_provider || "gemini";
|
| 195 |
+
if(!s.providers[prov.value].key && s.providers.nvidia.key) prov.value = "nvidia";
|
| 196 |
+
const load = async (force) => { const r = await fillModels(prov.value, model, list, force); $("#mhint").textContent = r && r.error ? "Nie udało się pobrać listy: "+r.error : "Wpisz lub wybierz z listy. ↻ pobiera aktualną listę modeli z API."; };
|
| 197 |
+
load(true);
|
| 198 |
+
prov.onchange = () => load(true);
|
| 199 |
+
$("#refresh").onclick = () => { toast("Pobieram listę modeli…"); load(false); };
|
| 200 |
+
const draft = localStorage.getItem("agent_draft"); if(draft) $("#prompt").value = draft;
|
| 201 |
+
$("#prompt").oninput = e => localStorage.setItem("agent_draft", e.target.value);
|
| 202 |
+
$("#f").onsubmit = async e => {
|
| 203 |
+
e.preventDefault();
|
| 204 |
+
const btn = e.submitter; btn.disabled = true;
|
| 205 |
+
try{
|
| 206 |
+
const r = await api("/api/jobs",{method:"POST", body:{prompt:$("#prompt").value, provider:prov.value, model:model.value, max_steps:+$("#steps").value, title:$("#title").value}});
|
| 207 |
+
localStorage.removeItem("agent_draft");
|
| 208 |
+
location.hash = "#/job/"+r.id;
|
| 209 |
+
}catch(err){ toast(err.message); btn.disabled=false; }
|
| 210 |
+
};
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
let jobState = {};
|
| 214 |
+
async function viewJob(id){
|
| 215 |
+
jobState = {id, lastEv:0, tab:"log", job:null, autoscroll:true};
|
| 216 |
+
shell("Zadanie", `<div id="head"><div class="empty"><span class="spin"></span></div></div>
|
| 217 |
+
<div class="tabs"><button data-t="log" class="on">Przebieg</button><button data-t="plan">Plan</button><button data-t="files">Pliki</button></div>
|
| 218 |
+
<div id="tab-log"><div id="events"></div></div>
|
| 219 |
+
<div id="tab-plan" hidden></div>
|
| 220 |
+
<div id="tab-files" hidden></div>
|
| 221 |
+
<div class="composer"><div class="in">
|
| 222 |
+
<textarea id="msg" rows="1" placeholder="Kolejne polecenie dla agenta…"></textarea>
|
| 223 |
+
<button class="primary" id="send" style="flex:none">➤</button></div></div>`, {back:"#/"});
|
| 224 |
+
document.querySelectorAll(".tabs button").forEach(b => b.onclick = () => switchTab(b.dataset.t));
|
| 225 |
+
$("#send").onclick = sendMessage;
|
| 226 |
+
$("#msg").addEventListener("input", e => { e.target.style.height="auto"; e.target.style.height=Math.min(e.target.scrollHeight,160)+"px"; });
|
| 227 |
+
window.onscroll = () => { jobState.autoscroll = (window.innerHeight + window.scrollY) >= document.body.scrollHeight - 120; };
|
| 228 |
+
pollJob();
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
function switchTab(t){
|
| 232 |
+
jobState.tab = t;
|
| 233 |
+
document.querySelectorAll(".tabs button").forEach(b => b.classList.toggle("on", b.dataset.t===t));
|
| 234 |
+
["log","plan","files"].forEach(x => $("#tab-"+x).hidden = x!==t);
|
| 235 |
+
if(t==="files") loadFiles();
|
| 236 |
+
if(t==="plan") renderPlan();
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
async function pollJob(){
|
| 240 |
+
const id = jobState.id;
|
| 241 |
+
try{
|
| 242 |
+
const job = await api("/api/jobs/"+id);
|
| 243 |
+
if(jobState.id!==id) return;
|
| 244 |
+
jobState.job = job;
|
| 245 |
+
renderHead(job);
|
| 246 |
+
const {events} = await api(`/api/jobs/${id}/events?after=${jobState.lastEv}`);
|
| 247 |
+
if(events.length){ renderEvents(events); jobState.lastEv = events[events.length-1].id; }
|
| 248 |
+
if(jobState.tab==="plan") renderPlan();
|
| 249 |
+
const busy = ["running","queued"].includes(job.status);
|
| 250 |
+
$("#send").disabled = busy;
|
| 251 |
+
$("#msg").placeholder = busy ? "Agent pracuje… możesz zamknąć przeglądarkę" : (job.status==="paused" ? "Napisz „kontynuuj”, aby pracował dalej" : "Kolejne polecenie dla agenta…");
|
| 252 |
+
timers.push(setTimeout(pollJob, busy ? 2000 : 8000));
|
| 253 |
+
}catch(e){ if(String(e.message).includes("Nie znaleziono")){ location.hash="#/"; return; } timers.push(setTimeout(pollJob, 5000)); }
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
function renderHead(j){
|
| 257 |
+
$("header h1").textContent = j.title;
|
| 258 |
+
const busy = ["running","queued"].includes(j.status);
|
| 259 |
+
$("#head").innerHTML = `<div class="card">
|
| 260 |
+
<div class="row"><span class="badge s-${j.status}" style="flex:none">${STATUS[j.status]||j.status}</span><span></span>
|
| 261 |
+
${busy? `<button class="danger" style="flex:none" onclick="stopJob()">■ Stop</button>`:""}
|
| 262 |
+
<a class="btn" style="flex:none" href="/api/jobs/${j.id}/download?t=${token}">⬇ ZIP</a>
|
| 263 |
+
<button class="ghost" style="flex:none" onclick="deleteJob()" aria-label="Usuń">🗑</button></div>
|
| 264 |
+
<div class="stats small muted">
|
| 265 |
+
<span>${esc(j.provider)} · ${esc(j.model)}</span><span>· krok ${j.run_steps}/${j.max_steps} (łącznie ${j.steps})</span>
|
| 266 |
+
<span>· tokeny ${((j.tokens_in||0)/1000).toFixed(1)}k / ${((j.tokens_out||0)/1000).toFixed(1)}k</span></div>
|
| 267 |
+
${j.error? `<div class="small" style="color:var(--err);margin-top:8px;white-space:pre-wrap">${esc(j.error)}</div>`:""}
|
| 268 |
+
</div>`;
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
function renderEvents(evs){
|
| 272 |
+
const box = $("#events"); if(!box) return;
|
| 273 |
+
const html = evs.map(e => {
|
| 274 |
+
const t = esc(e.text);
|
| 275 |
+
if(e.kind==="result" || e.kind==="tool_error"){
|
| 276 |
+
const first = e.text.split("\n")[0].slice(0,110);
|
| 277 |
+
return `<div class="ev ${e.kind}"><details><summary>↳ ${esc(first)}${e.text.length>first.length? " …":""}</summary><pre>${t}</pre></details></div>`;
|
| 278 |
+
}
|
| 279 |
+
const label = {user:"Ty", assistant:"Agent", done:"✅ Gotowe — podsumowanie", error:"Błąd"}[e.kind];
|
| 280 |
+
return `<div class="ev ${e.kind}">${label? `<div class="k">${label}</div>`:""}${e.kind==="tool"? "▸ ":""}${t}</div>`;
|
| 281 |
+
}).join("");
|
| 282 |
+
box.insertAdjacentHTML("beforeend", html);
|
| 283 |
+
if(jobState.autoscroll && jobState.tab==="log") window.scrollTo(0, document.body.scrollHeight);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
function renderPlan(){
|
| 287 |
+
const el = $("#tab-plan"); const j = jobState.job; if(!el || !j) return;
|
| 288 |
+
const plan = j.plan || [];
|
| 289 |
+
el.innerHTML = `<div class="card plan">${plan.length? `<ul>${plan.map(p=>`<li class="${p.done?"d":""}">${esc(p.text)}</li>`).join("")}</ul>` : `<span class="muted">Agent jeszcze nie ułożył planu.</span>`}</div>
|
| 290 |
+
${j.summary? `<div class="card"><div class="k muted small">PODSUMOWANIE</div><div class="summary">${esc(j.summary)}</div></div>`:""}
|
| 291 |
+
<div class="card"><div class="k muted small">POLECENIE</div><div class="summary">${esc(j.prompt)}</div></div>`;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
async function loadFiles(){
|
| 295 |
+
const el = $("#tab-files"); el.innerHTML = `<div class="empty"><span class="spin"></span></div>`;
|
| 296 |
+
try{
|
| 297 |
+
const {files} = await api(`/api/jobs/${jobState.id}/files`);
|
| 298 |
+
el.innerHTML = files.length ? `<div class="card" style="padding:4px 12px">${files.map(f=>`<div class="file" data-p="${esc(f.path)}"><span>${esc(f.path)}</span><span>${fmtSize(f.size)}</span></div>`).join("")}</div>
|
| 299 |
+
<div class="row"><button onclick="loadFiles()">↻ Odśwież</button><a class="btn" href="/api/jobs/${jobState.id}/download?t=${token}">⬇ Pobierz wszystko (ZIP)</a></div>`
|
| 300 |
+
: `<div class="empty">Brak plików — agent jeszcze nic nie zapisał.</div>`;
|
| 301 |
+
el.querySelectorAll(".file").forEach(f => f.onclick = () => openFile(f.dataset.p));
|
| 302 |
+
}catch(e){ el.innerHTML = `<div class="empty">${esc(e.message)}</div>`; }
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
async function openFile(path){
|
| 306 |
+
try{
|
| 307 |
+
const f = await api(`/api/jobs/${jobState.id}/file?path=${encodeURIComponent(path)}`);
|
| 308 |
+
const m = document.createElement("div"); m.className="modal";
|
| 309 |
+
const raw = `/api/jobs/${jobState.id}/file?raw=1&path=${encodeURIComponent(path)}&t=${token}`;
|
| 310 |
+
m.innerHTML = `<div class="sheet"><header><h1 style="font-size:14px;font-family:var(--mono)">${esc(path)}</h1>
|
| 311 |
+
<a class="btn" href="${raw}">⬇</a><button class="ghost" id="cl">✕</button></header>
|
| 312 |
+
<pre>${f.binary? "(plik binarny — pobierz go przyciskiem ⬇)" : esc(f.content)}${f.truncated? "\n\n… (ucięto podgląd)":""}</pre></div>`;
|
| 313 |
+
document.body.append(m);
|
| 314 |
+
m.onclick = e => { if(e.target===m) m.remove(); };
|
| 315 |
+
$("#cl", m).onclick = () => m.remove();
|
| 316 |
+
}catch(e){ toast(e.message); }
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
async function sendMessage(){
|
| 320 |
+
const t = $("#msg").value.trim(); if(!t) return;
|
| 321 |
+
$("#send").disabled = true;
|
| 322 |
+
try{ await api(`/api/jobs/${jobState.id}/message`,{method:"POST", body:{text:t}}); $("#msg").value=""; $("#msg").style.height="auto"; jobState.autoscroll=true; clearTimers(); pollJob(); }
|
| 323 |
+
catch(e){ toast(e.message); $("#send").disabled=false; }
|
| 324 |
+
}
|
| 325 |
+
async function stopJob(){ if(!confirm("Zatrzymać agenta?")) return; await api(`/api/jobs/${jobState.id}/stop`,{method:"POST"}).catch(e=>toast(e.message)); toast("Zatrzymuję…"); }
|
| 326 |
+
async function deleteJob(){ if(!confirm("Usunąć zadanie razem z plikami?")) return; await api(`/api/jobs/${jobState.id}`,{method:"DELETE"}).catch(e=>toast(e.message)); location.hash="#/"; }
|
| 327 |
+
|
| 328 |
+
async function viewSettings(){
|
| 329 |
+
const s = await getSettings(true).catch(e=>{toast(e.message); return null;}); if(!s) return;
|
| 330 |
+
const keyField = (k, name, url) => `
|
| 331 |
+
<label>${name} — klucz API ${s.providers[k].key? `<span style="color:var(--acc)">✓ ustawiony (${esc(s.providers[k].key)}${s.providers[k].key_from_env?", ze zmiennej środowiskowej":""})</span>`:""}</label>
|
| 332 |
+
<input id="key_${k}" type="password" placeholder="${s.providers[k].key? "zostaw puste, by nie zmieniać":"wklej klucz"}" autocomplete="off">
|
| 333 |
+
<div class="hint">Klucz zdobędziesz na <a href="${url}" target="_blank" rel="noopener">${url.replace("https://","")}</a></div>`;
|
| 334 |
+
shell("Ustawienia", `
|
| 335 |
+
<div class="card">
|
| 336 |
+
${keyField("gemini","Google Gemini","https://aistudio.google.com/apikey")}
|
| 337 |
+
${keyField("nvidia","NVIDIA NIM","https://build.nvidia.com")}
|
| 338 |
+
</div>
|
| 339 |
+
<div class="card">
|
| 340 |
+
<label>Domyślny dostawca</label><select id="dp"><option value="gemini">Google Gemini</option><option value="nvidia">NVIDIA NIM</option></select>
|
| 341 |
+
<label>Domyślny model Gemini</label><input id="dmg" list="lg" placeholder="${esc(s.providers.gemini.default_model)}" value="${esc(s.default_model_gemini)}"><datalist id="lg">${s.providers.gemini.suggested.map(m=>`<option value="${esc(m)}">`).join("")}</datalist>
|
| 342 |
+
<label>Domyślny model NVIDIA</label><input id="dmn" list="ln" placeholder="${esc(s.providers.nvidia.default_model)}" value="${esc(s.default_model_nvidia)}"><datalist id="ln">${s.providers.nvidia.suggested.map(m=>`<option value="${esc(m)}">`).join("")}</datalist>
|
| 343 |
+
</div>
|
| 344 |
+
<div class="card">
|
| 345 |
+
<label>Powiadomienia push (ntfy.sh) — temat</label>
|
| 346 |
+
<input id="ntfy" placeholder="np. mati-agent-8f3k2" value="${esc(s.ntfy_topic)}">
|
| 347 |
+
<div class="hint">Zainstaluj aplikację <b>ntfy</b> na telefonie i zasubskrybuj ten sam temat — dostaniesz powiadomienie, gdy agent skończy. Wymyśl trudny do zgadnięcia temat.</div>
|
| 348 |
+
</div>
|
| 349 |
+
<button class="primary" id="save" style="width:100%;padding:14px">Zapisz</button>
|
| 350 |
+
<button class="ghost" style="width:100%;margin-top:14px" onclick="localStorage.removeItem('agent_token');token='';location.hash='#/login'">Wyloguj</button>
|
| 351 |
+
`, {back:"#/"});
|
| 352 |
+
$("#dp").value = s.default_provider || "gemini";
|
| 353 |
+
$("#save").onclick = async () => {
|
| 354 |
+
const body = {default_provider:$("#dp").value, default_model_gemini:$("#dmg").value, default_model_nvidia:$("#dmn").value, ntfy_topic:$("#ntfy").value};
|
| 355 |
+
if($("#key_gemini").value.trim()) body.key_gemini = $("#key_gemini").value.trim();
|
| 356 |
+
if($("#key_nvidia").value.trim()) body.key_nvidia = $("#key_nvidia").value.trim();
|
| 357 |
+
try{ await api("/api/settings",{method:"POST", body}); toast("Zapisano ✓"); viewSettings(); }catch(e){ toast(e.message); }
|
| 358 |
+
};
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
function router(){
|
| 362 |
+
clearTimers(); window.onscroll = null;
|
| 363 |
+
document.querySelectorAll(".modal").forEach(m => m.remove());
|
| 364 |
+
const h = location.hash || "#/";
|
| 365 |
+
if(!token && h!=="#/login"){ location.hash="#/login"; return; }
|
| 366 |
+
if(h==="#/login") return viewLogin();
|
| 367 |
+
if(h==="#/new") return viewNew();
|
| 368 |
+
if(h==="#/settings") return viewSettings();
|
| 369 |
+
const m = h.match(/^#\/job\/([\w\-]+)/); if(m) return viewJob(m[1]);
|
| 370 |
+
return viewList();
|
| 371 |
+
}
|
| 372 |
+
window.addEventListener("hashchange", router);
|
| 373 |
+
router();
|
| 374 |
+
</script>
|
| 375 |
+
</body>
|
| 376 |
+
</html>
|
manifest.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"name":"Agent Kodu","short_name":"Agent","start_url":"/","display":"standalone","background_color":"#0e1116","theme_color":"#0e1116","icons":[{"src":"/icon.svg","sizes":"any","type":"image/svg+xml"}]}
|
store.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trwały magazyn: zadania, zdarzenia (log) i ustawienia w SQLite."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import secrets
|
| 5 |
+
import sqlite3
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
SCHEMA = """
|
| 10 |
+
CREATE TABLE IF NOT EXISTS jobs(
|
| 11 |
+
id TEXT PRIMARY KEY,
|
| 12 |
+
title TEXT,
|
| 13 |
+
prompt TEXT,
|
| 14 |
+
provider TEXT,
|
| 15 |
+
model TEXT,
|
| 16 |
+
status TEXT,
|
| 17 |
+
created REAL,
|
| 18 |
+
updated REAL,
|
| 19 |
+
max_steps INTEGER,
|
| 20 |
+
steps INTEGER DEFAULT 0,
|
| 21 |
+
run_steps INTEGER DEFAULT 0,
|
| 22 |
+
messages TEXT,
|
| 23 |
+
plan TEXT,
|
| 24 |
+
summary TEXT,
|
| 25 |
+
error TEXT,
|
| 26 |
+
resumes INTEGER DEFAULT 0,
|
| 27 |
+
tokens_in INTEGER DEFAULT 0,
|
| 28 |
+
tokens_out INTEGER DEFAULT 0
|
| 29 |
+
);
|
| 30 |
+
CREATE TABLE IF NOT EXISTS events(
|
| 31 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 32 |
+
job_id TEXT,
|
| 33 |
+
ts REAL,
|
| 34 |
+
kind TEXT,
|
| 35 |
+
text TEXT,
|
| 36 |
+
data TEXT
|
| 37 |
+
);
|
| 38 |
+
CREATE INDEX IF NOT EXISTS ev_job ON events(job_id, id);
|
| 39 |
+
CREATE TABLE IF NOT EXISTS settings(k TEXT PRIMARY KEY, v TEXT);
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
JOB_FIELDS = (
|
| 43 |
+
"id", "title", "prompt", "provider", "model", "status", "created", "updated",
|
| 44 |
+
"max_steps", "steps", "run_steps", "plan", "summary", "error", "resumes",
|
| 45 |
+
"tokens_in", "tokens_out",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Store:
|
| 50 |
+
def __init__(self, path):
|
| 51 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 52 |
+
self.lock = threading.RLock()
|
| 53 |
+
self.db = sqlite3.connect(path, check_same_thread=False, timeout=30)
|
| 54 |
+
self.db.row_factory = sqlite3.Row
|
| 55 |
+
with self.lock:
|
| 56 |
+
self.db.execute("PRAGMA journal_mode=WAL")
|
| 57 |
+
self.db.executescript(SCHEMA)
|
| 58 |
+
self.db.commit()
|
| 59 |
+
|
| 60 |
+
# --- niskopoziomowe ---
|
| 61 |
+
def q(self, sql, args=(), one=False):
|
| 62 |
+
with self.lock:
|
| 63 |
+
cur = self.db.execute(sql, args)
|
| 64 |
+
rows = cur.fetchall()
|
| 65 |
+
if one:
|
| 66 |
+
return dict(rows[0]) if rows else None
|
| 67 |
+
return [dict(r) for r in rows]
|
| 68 |
+
|
| 69 |
+
def x(self, sql, args=()):
|
| 70 |
+
with self.lock:
|
| 71 |
+
cur = self.db.execute(sql, args)
|
| 72 |
+
self.db.commit()
|
| 73 |
+
return cur.lastrowid
|
| 74 |
+
|
| 75 |
+
# --- ustawienia ---
|
| 76 |
+
def get_setting(self, key, default=None):
|
| 77 |
+
row = self.q("SELECT v FROM settings WHERE k=?", (key,), one=True)
|
| 78 |
+
return row["v"] if row and row["v"] is not None else default
|
| 79 |
+
|
| 80 |
+
def set_setting(self, key, value):
|
| 81 |
+
self.x("INSERT INTO settings(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v", (key, value))
|
| 82 |
+
|
| 83 |
+
def secret(self):
|
| 84 |
+
s = self.get_setting("_secret")
|
| 85 |
+
if not s:
|
| 86 |
+
s = secrets.token_hex(32)
|
| 87 |
+
self.set_setting("_secret", s)
|
| 88 |
+
return s
|
| 89 |
+
|
| 90 |
+
# --- zadania ---
|
| 91 |
+
def create_job(self, title, prompt, provider, model, max_steps):
|
| 92 |
+
job_id = time.strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(3)
|
| 93 |
+
now = time.time()
|
| 94 |
+
self.x(
|
| 95 |
+
"INSERT INTO jobs(id,title,prompt,provider,model,status,created,updated,max_steps,messages,plan)"
|
| 96 |
+
" VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
| 97 |
+
(job_id, title, prompt, provider, model, "queued", now, now, max_steps, "[]", "[]"),
|
| 98 |
+
)
|
| 99 |
+
return job_id
|
| 100 |
+
|
| 101 |
+
def get_job(self, job_id, with_messages=False):
|
| 102 |
+
cols = ",".join(JOB_FIELDS) + (",messages" if with_messages else "")
|
| 103 |
+
return self.q(f"SELECT {cols} FROM jobs WHERE id=?", (job_id,), one=True)
|
| 104 |
+
|
| 105 |
+
def list_jobs(self, limit=100):
|
| 106 |
+
cols = ",".join(JOB_FIELDS)
|
| 107 |
+
return self.q(f"SELECT {cols} FROM jobs ORDER BY created DESC LIMIT ?", (limit,))
|
| 108 |
+
|
| 109 |
+
def update_job(self, job_id, **fields):
|
| 110 |
+
if not fields:
|
| 111 |
+
return
|
| 112 |
+
fields["updated"] = time.time()
|
| 113 |
+
for k, v in list(fields.items()):
|
| 114 |
+
if isinstance(v, (list, dict)):
|
| 115 |
+
fields[k] = json.dumps(v, ensure_ascii=False)
|
| 116 |
+
sets = ",".join(f"{k}=?" for k in fields)
|
| 117 |
+
self.x(f"UPDATE jobs SET {sets} WHERE id=?", (*fields.values(), job_id))
|
| 118 |
+
|
| 119 |
+
def add_tokens(self, job_id, tin, tout):
|
| 120 |
+
self.x("UPDATE jobs SET tokens_in=tokens_in+?, tokens_out=tokens_out+? WHERE id=?", (tin or 0, tout or 0, job_id))
|
| 121 |
+
|
| 122 |
+
def delete_job(self, job_id):
|
| 123 |
+
self.x("DELETE FROM events WHERE job_id=?", (job_id,))
|
| 124 |
+
self.x("DELETE FROM jobs WHERE id=?", (job_id,))
|
| 125 |
+
|
| 126 |
+
# --- zdarzenia (log widoczny w panelu) ---
|
| 127 |
+
def add_event(self, job_id, kind, text, data=None):
|
| 128 |
+
return self.x(
|
| 129 |
+
"INSERT INTO events(job_id,ts,kind,text,data) VALUES(?,?,?,?,?)",
|
| 130 |
+
(job_id, time.time(), kind, text, json.dumps(data, ensure_ascii=False) if data is not None else None),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def events(self, job_id, after=0, limit=500):
|
| 134 |
+
return self.q(
|
| 135 |
+
"SELECT id,ts,kind,text,data FROM events WHERE job_id=? AND id>? ORDER BY id LIMIT ?",
|
| 136 |
+
(job_id, after, limit),
|
| 137 |
+
)
|