diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..cfd042d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +.env +data/ +docs/ +**/__pycache__ +**/*.pyc diff --git a/.env.example b/.env.example index f2313ef..0451eaa 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,31 @@ -OLLAMA_BASE_URL=http://localhost:11434 -OLLAMA_MODEL=gemma4:e4b +# Copy to .env and adjust (read by docker compose; .env is gitignored). + +# Port the UI listens on. +UI_PORT=3000 + +# NetOps Agent REST API (repo: palapa-agent). Start it on a free port, e.g.: +# PALAPA_CONFIG_PATH=~/.palapa/config.yaml uv run uvicorn palapa.gateway.api:app --host 127.0.0.1 --port 8100 +# (port 8000 on this host is taken by the mikrotik-mcp container) +NETOPS_AGENT_URL=http://127.0.0.1:8100 + +# Hermes gateway `api_server` platform (default port 8642). +# The Hermes API key is NOT set here: enter it in Settings > Backend. It is stored +# in the manager's database, never in an environment variable. +HERMES_URL=http://127.0.0.1:8642 + +# Where the manager keeps its database and SOUL.md backups. Default: ./data +# (committed with a .gitkeep so it is owned by you, not root). Point it elsewhere +# for a separate instance, e.g. when testing. +# DATA_DIR=./data + +# Manager service port (loopback only, reached through the UI's /api/). +MANAGER_PORT=8200 + +# Home directories of the two backends (absolute paths). +NETOPS_AGENT_HOME=/home/llmnetops/.palapa +HERMES_HOME=/home/llmnetops/.hermes + +# Container user for the manager, so files it writes into the backends' skill +# folders stay owned by you. Get yours with: id -u / id -g +HOST_UID=1006 +HOST_GID=1006 diff --git a/.gitignore b/.gitignore index d81698c..a259287 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,14 @@ -# Abaikan file sensitif dan generated -config.yaml +# Environment (holds the Hermes API key) .env -output/ -.venv/ -__pycache__/ -*.pyc - -# Data DHCP lease (berisi MAC address & IP perangkat nyata) -*.txt -laporan/ -# Log files +# Generated / local +output/ *.log -schedule.log - -# Config backups (berisi konfigurasi router lengkap) -backups/ -!backups/.gitkeep +.scratch/ +node_modules/ -# SQLite checkpoints (berisi riwayat percakapan) -data/ +# Manager service database and SOUL.md backups +data/* +!data/.gitkeep +__pycache__/ +*.pyc diff --git a/CLAUDE.md b/CLAUDE.md index bbbe65b..71145d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,232 +1,77 @@ -# CLAUDE.md — llmnetops +# CLAUDE.md — NetOpsUI (LLMNetOps Console) -Platform operasional jaringan kampus berbasis LangGraph multi-agent. Agent SSH ke router MikroTik (RouterOS v6/v7), menganalisis kondisi jaringan, dan mengeksekusi perubahan dengan approval operator. +Repo ini adalah **UI + service manajemen kecil**. Tidak ada logika agent, LLM, atau SSH ke router di sini. Agent dijalankan oleh dua backend yang dipanggil lewat API: -## Cara Menjalankan +- **NetOps Agent** (repo saat ini masih `palapa-agent`, `/home/llmnetops/palapa-agent`): disebut **NetOps Agent** di seluruh NetOpsUI (UI, id backend `netops`, env `NETOPS_AGENT_*`). Nama `palapa` hanya dipakai saat merujuk ke hal nyata di sisi Palapa: perintah `uvicorn palapa.gateway.api`, `PALAPA_CONFIG_PATH`, folder `~/.palapa`, dan namespace `metadata.palapa` di `SKILL.md`. +- **Hermes** (`~/.hermes/hermes-agent`): gateway platform `api_server`. -```bash -source .venv/bin/activate -python tui.py # TUI ncurses saat ini -# python tui_textual.py # TUI baru (belum diimplementasi — Phase 8) -``` - -Membutuhkan `config.yaml` (tidak di-commit) dan `.env` dengan `OLLAMA_BASE_URL` + `OLLAMA_MODEL`. - -## Branch - -| Branch | Deskripsi | -|--------|-----------| -| `main` | DHCP monitoring UTBK (original, jangan diubah) | -| `netops` | Fondasi multi-agent platform | -| `refactor_agent_skill_tool` | Branch aktif pengembangan | - -PR selalu ke `main` dari branch aktif. - ---- - -## Arsitektur Singkat - -``` -tui.py → agent.py (public API) → agents/nodes.py → tools/*.py → Router SSH - ↑ - agents/definitions/*.md skills/**/*.md -``` - -- **`agent.py`** — hanya public API: `create_agent()`, `stream_agent_response()`, `resume_after_approval()`. Zero LLM logic. -- **`agents/nodes.py`** — semua node LangGraph: `supervisor_node`, `_make_specialist_node()` factory, `config_node`. -- **`agents/loader.py`** — baca `agents/definitions/*.md`, parse frontmatter YAML jadi `AgentDefinition`. -- **`agents/tools.py`** — `TOOL_MAP: dict[str, tool]` — registry semua tools per domain. -- **`tools/*.py`** — 31+ atomic `@tool` functions, semua SSH ke MikroTik. -- **`skills/library.py`** — `SkillLibrary` dengan hot reload via `watchfiles`. -- **`skills/**/*.md`** — prosedur kerja agent; ditambah tanpa coding Python. -- **`tui.py`** — UI only, consume `agent.py` public API, zero LLM logic. - ---- - -## Agent Definitions (`agents/definitions/*.md`) - -Setiap file Markdown mendefinisikan satu specialist agent. Frontmatter YAML: - -```yaml ---- -name: monitor_agent # snake_case, cocok dengan nama node di graph -alias: eko # nama tampilan di TUI -description: > # dipakai supervisor untuk routing decision - Satu kalimat fungsi agent -model: qwen3.5:9b -num_ctx: 32768 # KV cache VRAM ~3.5 GB per agent — aman karena sekuensial -num_predict: 16384 # thinking model: token reasoning ikut dihitung -context_window: 20 # jumlah pesan terakhir yang dibawa ke LLM -timeout: 600 -ollama_host: "" # opsional; override OLLAMA_BASE_URL untuk multi-mesin -tools: - - list_routers # harus ada di TOOL_MAP di agents/tools.py - - check_reachability -skills: - - network-health-check # harus ada di skills/**/*.md -handoff_to: - - document_agent # agent yang boleh di-route berikutnya -approval_required_tools: # khusus config_agent — tools yang picu interrupt() - - backup_router_config - - run_command_write ---- -Isi system prompt agent dalam Bahasa Indonesia... -``` - -**Aturan:** Jangan tambahkan instruksi "tunggu konfirmasi dari operator" atau "satu perubahan sekaligus" di system prompt — ini menyebabkan agent berhenti setelah approval pertama. - ---- - -## Skill Format (`skills/**/*.md`) - -```yaml ---- -name: nama-skill # kebab-case, cocok dengan referensi di agent definition -domain: monitoring # direktori domain: monitoring/routing/config/security/dhcp/... -triggers: - - kata kunci query yang relevan -tools: - - get_interface_stats # informational — tidak enforce di runtime -approval_required: false -enabled: true ---- - -Konten prosedur dalam Bahasa Indonesia... -``` - -Skill baru langsung aktif tanpa restart (hot reload). Tempatkan di subdirektori domain yang sesuai. +Hanya satu backend aktif pada satu waktu (`localStorage['llmnetops-backend']`, dipilih di Settings). ---- +**Scope kerja: hanya repo NetOpsUI.** Jangan mengubah repo palapa-agent, `~/.palapa`, atau `~/.hermes`, dan jangan menjalankan/menghentikan backend tanpa diminta. Pengujian memakai mock dan *salinan* home backend, bukan yang asli. (Pengecualian yang disengaja: fitur Publish skill dan "Terapkan ke SOUL.md" di manager menulis ke folder backend atas aksi operator.) -## Tool Conventions (`tools/*.py`) +## Menjalankan -**Naming:** -- `get_*` — read, return data -- `run_command` — read-only SSH command (blocklist kata destruktif) -- `run_command_write` — write SSH command (butuh approval, blocklist `format`/`factory-reset`) -- `audit_*` — multi-router parallel check -- `check_*` — boolean/status check -- `list_*` — daftar item -- `backup_*` — operasi backup (butuh approval) - -**Jangan tambahkan truncation limit baru.** Limit yang ada sudah sengaja diperbesar atau dihapus karena menyebabkan agent kehilangan konteks. Jika output terlalu besar, perbaiki di sisi query MikroTik, bukan potong hasilnya. - -**Tools yang butuh approval operator** (via `interrupt()` di `config_node`): -- `backup_router_config` -- `run_command_write` - ---- - -## Pola Penting di `agents/nodes.py` - -### Safety Net (jamin AIMessage selalu ada) - -Setelah forced summary, jika `final_msg` bukan `AIMessage` berisi konten: -```python -# Ambil ToolMessage dengan konten terpanjang sebagai fallback -best = max(tool_msgs, key=lambda m: len(m.content or "")) -final_msg = AIMessage(content=f"Hasil:\n{best.content}") +```bash +cp .env.example .env # isi HOST_UID/GID, NETOPS_AGENT_HOME/HERMES_HOME (tanpa credential) +docker compose up -d --build # produksi +docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d # dev (hot reload) ``` -**Jangan hapus** — mencegah supervisor loop tak terbatas. - -### Loop Guard (di `supervisor_node`) -```python -if next_agent == _prev_agent and _prev_agent in valid_agent_names: - next_agent = "END" -``` -**Jangan hapus** — mencegah supervisor re-route ke agent yang baru saja selesai. +UI di `:3000`, manager di `127.0.0.1:8200`. Backend harus sudah jalan di host: NetOps Agent di `127.0.0.1:8100` (port 8000 dipakai container mikrotik-mcp; API-nya butuh `PALAPA_CONFIG_PATH`), Hermes di `127.0.0.1:8642` (butuh `API_SERVER_KEY` di `~/.hermes/.env`). Detail di README. -### Approval Chain (di `config_node`) +## Branch -`config_node` menggunakan `interrupt()` untuk setiap tool di `_APPROVAL_REQUIRED_TOOLS`. `resume_after_approval()` di `agent.py` menggunakan `graph.stream()` (bukan `graph.invoke()`) agar interrupt berikutnya tetap sampai ke TUI. +Pengembangan dilakukan langsung di branch `ui`. -### Rule 6 di `_SPECIALIST_SYS` +## Arsitektur ``` -Setelah menerima hasil tool, jika masih ada tugas berikutnya, LANGSUNG panggil -tool berikutnya tanpa menulis teks konfirmasi, ringkasan, atau 'Lanjut ke langkah X'. +screens/*.js → backends/index.js activeBackend() → backends/{netops,hermes}.js → /backend//… → nginx → backend +screens/{skills,agents}.js, settings (tab file) → manager.js → /api/… → nginx → server/ (FastAPI + SQLite) → ~/.palapa, ~/.hermes ``` -**Jangan hapus** — mencegah agent berhenti di tengah sequence write operations. ---- +- **`frontend/js/backends/index.js`**: registry dan **kontrak adapter** (komentar di atas file). Screen tidak boleh `fetch` langsung ke backend. +- **`backends/common.js`**: `http()`, `readSSE()` (mendukung `event:` dan multi-line `data:`), `toDate()`, `contentText()`. +- **`backends/netops.js`**: `/chat` stateless, jadi thread + pesan disimpan di **database manager** (`/api/threads`, tabel `chat_threads`/`chat_messages`) dan dibagi ke semua browser/operator; seluruh history dikirim tiap giliran. `owner` = label per-browser (`llmnetops-client-name`) + IP dari `X-Real-IP` nginx. Thread lama di `localStorage['llmnetops-netops-threads-v1']` (atau key `…palapa…`) diimpor sekali lewat `POST /api/threads/import`. Layar chat mem-poll daftar thread tiap 5 dtk. **Manager yang memanggil `/chat`** (`server/runs.py`: `POST /api/threads/{id}/run`, stream `GET …/events?after=N`, `POST …/stop`; butuh `NETOPS_AGENT_URL` di container manager), jadi jawaban tersimpan walau browser refresh/ditutup dan halaman bisa tersambung lagi ke run yang berjalan (`resume()`). Run hanya di memori satu proses (restart manager memutus run; flag `running` dibersihkan saat start). Stop hanya memutus stream manager (run di agent tidak berhenti). Tidak ada approval. +- **`backends/hermes.js`**: thread = Hermes session. Giliran chat memakai **`POST /v1/runs` + `GET /v1/runs/{id}/events`**, bukan `/api/sessions/{id}/chat/stream`, karena hanya runs yang mengirim `approval.request` dan menerima `/approval` dan `/stop`. Profil agent aktif dikirim sebagai `instructions`. +- **`frontend/nginx.conf.template`**: proxy `/backend/netops/`, `/backend/hermes/`, `/api/` (manager). Menyisipkan `Authorization` Hermes lewat `auth_request` ke `/internal/hermes-auth` milik manager (key dari **database**, bukan env) dan **mengosongkan `Origin`** (Hermes menolak origin di luar `API_SERVER_CORS_ORIGINS`). +- **`server/`** (manager): `backends.py` (akses filesystem terbatas, render/parse `SKILL.md`, masking config), `db.py` (SQLite: `skills`, `skill_publications`, `profiles`; baris `backend='palapa'` dimigrasi ke `netops` saat start), `main.py` (API). Skill = folder `/SKILL.md` dengan frontmatter YAML di kedua backend; Hermes menaruh skill NetOpsUI di `skills/netopsui/`. -## State Graph +### Event ternormalisasi (dikonsumsi `screens/chat.js`) -```python -class NetworkOpsState(TypedDict): - messages: Annotated[list, add_messages] # pesan LangGraph (append-only) - next_agent: str # target routing dari supervisor - active_agent: str # agent yang sedang berjalan - agent_log: list # AgentLogEntry — dikonsumsi TUI untuk Activity screen - reasoning: str # debug reasoning supervisor - skill_name: str # skill yang diinjeksi ke specialist -``` +`delta` · `tool_start` · `tool_end` · `note` · `thinking` · `approval` · `error` · `stopped`. Backend baru = adapter yang memetakan event-nya ke daftar ini, lalu didaftarkan di `BACKENDS`. -`agent_log` adalah append-only list yang di-yield ke TUI sebagai events: `routing`, `tool_call`, `tool_result`, `ai`, `approval`. +### Screen "belum tersedia" ---- +`NAV_ITEMS[].unavailable = true` di `config.js` → `screens/unavailable.js`. Saat ini: Backups, Metrics. (Nodes aktif: hanya tambah node lewat `POST /devices` NetOps Agent; belum ada list/update/delete.) Aktifkan kembali dengan menghapus flag, menambah screen, dan method adapter/manager setelah datanya ada. -## TUI Public API (`agent.py`) +## Aturan -```python -graph, config = create_agent() - -# Stream query baru -for event_type, content in stream_agent_response(graph, config, "query user"): - # event_type: "routing" | "tool_call" | "tool_result" | "ai" | "approval_required" | "error" - ... - -# Resume setelah approval (gunakan ini, bukan graph.invoke) -for event_type, content in resume_after_approval(graph, config, "approved"): - ... -``` - ---- +- **Credential hanya di database manager** (tabel `secrets`, `llm_providers`; DB 0600), **tidak pernah di environment/`.env`/compose** dan tidak di JS. Jangan menambah env var berisi rahasia. API key Hermes: `PUT /api/backends/hermes/credential` (write-only, hanya `has_key` yang dikembalikan), divalidasi ASCII tercetak tanpa spasi (anti header injection); nginx mengambilnya per request dari `/internal/hermes-auth` (di luar `/api/`, jadi tidak ter-proxy ke browser; location `/_hermes_auth` bersifat `internal`). Tanpa key: header kosong → Hermes 401. Manager tidak pernah mengembalikan nilai `.env`; `config.yaml` selalu dimasking. +- Di nginx, `proxy_set_header` **tidak diwarisi** ke `location` yang punya `proxy_set_header` sendiri. Setiap location mengulang header lengkap. +- Manager: slug divalidasi `^[a-z0-9][a-z0-9-]{0,63}$` dan path skill dicek tetap di dalam folder skills (anti path traversal). `SOUL.md` ditulis *in place* (bisa berupa bind mount satu file yang tidak bisa di-rename atomik). +- **LLM provider** (`server/llm.py`, `screens/settings-llm.js`): API key write-only (tidak pernah dikembalikan API; `has_key` saja); `/api/llm/test` dijalankan server-side, tidak mengikuti redirect, dan key tersimpan hanya dipakai bila Base URL sama; mengubah Base URL tanpa memasukkan key ulang ditolak. "Terapkan" mengedit **baris demi baris** blok `model:` di `config.yaml` (netops: `name/base_url/api_key`, opsional `delegation.agents.*.model`; hermes: `default/provider=custom/base_url/api_key`), **tidak** men-dump ulang YAML. `edit_config()` mem-parse hasil dan membandingkannya dengan aslinya (hanya key target yang boleh beda) sebelum menulis; backup ke `DATA_DIR/backups/` (0600). Provider tanpa key menghapus `api_key` lama. Hanya YAML block-style yang didukung (flow-style → 422). Backend tidak di-restart oleh NetOpsUI. +- Publish skill tidak menimpa file yang bukan hasil publish NetOpsUI tanpa `force`. Menghapus skill di library tidak menghapus file yang sudah dipublish. +- File tunggal yang di-mount di compose harus sudah ada di host, dan `data/` harus ada (`data/.gitkeep`) agar tidak dibuat `root` oleh Docker. +- **Pengujian harus memakai `DATA_DIR` terpisah** (dan salinan home backend). `./data` berisi data asli operator; stack uji yang memakai `./data` yang sama akan bercampur dengannya. +- **Jangan mematikan proses dengan `pkill -f`/`pgrep -f` berdasarkan nama** (mis. `uvicorn main:app`): proses di dalam container terlihat di host dan ikut terbunuh. Gunakan PID atau port uji yang unik. +- Tidak ada build step: ES modules langsung, Tailwind via CDN (config di `index.html`), markdown renderer sendiri di `utils.js` (escape-first). `localStorage` bisa kosong/throw, selalu `try/catch`. +- **Autentikasi** (`server/auth.py`, `screens/login.js`): tabel `users` (hash scrypt) dan `sessions` (hanya SHA-256 token; cookie `netopsui_session` HttpOnly, SameSite=Strict, 7 hari). Guard: middleware manager untuk semua `/api/*` (kecuali `login`, `logout`, `health`) dan `auth_request /_session_check` nginx untuk `/backend/netops/` dan `/backend/hermes/` (yang tidak lewat manager); `/internal/hermes-auth` juga mensyaratkan sesi. **User dibuat lewat CLI, tidak ada endpoint pendaftaran**: `docker compose exec manager python create_user.py ` (juga untuk reset password). Login dibatasi 5 gagal / 5 menit per IP+username (di memori). Route baru di luar `/api/` yang dilewatkan nginx harus diberi guard sendiri. Manager di `127.0.0.1:8200` tetap menolak `/api/*` tanpa sesi. ## Bahasa -- **Kode Python:** Bahasa Inggris (nama variabel, komentar teknis, docstring) -- **System prompt agent & skill:** Bahasa Indonesia -- **Log output ke operator:** Bahasa Indonesia -- **Dokumen di `docs/`:** campuran (sebagian Inggris, sebagian Indonesia) - ---- +- **Kode:** Bahasa Inggris (nama variabel, komentar). **Teks UI untuk operator:** Bahasa Indonesia. -## File Kritis — Jangan Diubah Tanpa Hati-hati - -| File | Alasan | -|------|--------| -| `agents/nodes.py` | Safety net + loop guard; perubahan bisa menyebabkan infinite loop | -| `agent.py` | Public API contract dengan tui.py; `resume_after_approval` harus tetap streaming | -| `tools/config_read.py` | `_BLOCKED_KEYWORDS` — daftar blocklist read-only; jangan relaksasi | -| `tools/config_write.py` | `_BLOCKED_DESTRUCTIVE` — jangan hapus `factory-reset`, `format` | -| `agents/tools.py` | `TOOL_MAP` — tool harus terdaftar di sini agar bisa dipakai agent | - ---- - -## File Tidak Di-commit (gitignored) +## File Tidak Di-commit ``` -config.yaml # kredensial SSH + daftar router -.env # OLLAMA_BASE_URL, OLLAMA_MODEL -backups/ # hasil backup config router -laporan/ # laporan yang digenerate agent -output/ # output lain +.env # URL/port/path backend, HOST_UID/GID (TANPA credential) +data/* # database manager + backup SOUL.md (kecuali data/.gitkeep); lokasi bisa diganti via DATA_DIR ``` ---- - ## Dokumentasi -| Dokumen | Isi | -|---------|-----| -| [docs/IMPLEMENTATION_PLAN.md](docs/IMPLEMENTATION_PLAN.md) | 8-phase plan; Phase 8 = TUI Textual (belum dimulai) | -| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Desain sistem lengkap | -| [docs/SKILL_AUTHORING_GUIDE.md](docs/SKILL_AUTHORING_GUIDE.md) | Panduan menulis skill baru | -| [laporan/rekap-pengembangan_20260509.md](laporan/rekap-pengembangan_20260509.md) | Rekap pekerjaan 9 Mei 2026 | - ---- +`docs/` berisi dokumen desain era monolit LangGraph (tidak lagi mencerminkan kode) dan mockup Stitch di `docs/stitch_llmnetops_enterprise_console/`, yang masih menjadi acuan visual. ## Agent skills @@ -240,4 +85,4 @@ Label dalam Bahasa Indonesia: perlu-triage, perlu-info, siap-agent, siap-manusia ### Domain docs -Single-context — satu `CONTEXT.md` di root + `docs/adr/`. Lihat `docs/agents/domain.md`. +Single-context: satu `CONTEXT.md` di root + `docs/adr/`. Lihat `docs/agents/domain.md`. diff --git a/CONTEXT.md b/CONTEXT.md index 3d59ae0..7afd30e 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1,26 +1,30 @@ -# CONTEXT.md — llmnetops +# CONTEXT.md — NetOpsUI -Platform operasional jaringan kampus berbasis LangGraph multi-agent. +Web console untuk operasional jaringan berbasis agent AI. Agent berjalan di backend terpisah; NetOpsUI menyediakan UI dan pengelolaan skill/profil agent. ## Domain Language | Istilah | Definisi | |---------|----------| -| Agent | Specialist LLM node di LangGraph graph (monitor, diagnose, config, security, document) | -| Skill | Prosedur kerja dalam Markdown; dibaca agent saat handle query relevan | -| Tool | Atomic `@tool` function yang SSH ke router MikroTik | -| Supervisor | Orchestrator agent yang route query ke specialist yang tepat | -| Approval | Interrupt mechanism — operator harus confirm sebelum write command dieksekusi | - -## Entitas Utama - -- **Router** — MikroTik RouterOS v6/v7, diakses via SSH dari `config.yaml` -- **Operator** — manusia yang approve/tolak write commands di TUI -- **Agent Log** — append-only list events yang dikonsumsi TUI (`agent_log` di state) +| Backend | Layanan agent yang dipanggil UI lewat API: **NetOps Agent** (repo saat ini masih bernama palapa-agent) atau **Hermes**. Tepat satu yang aktif. | +| Adapter | Modul di `frontend/js/backends/` yang menerjemahkan API satu backend ke kontrak bersama UI | +| Manager | Service milik NetOpsUI (`server/`, FastAPI + SQLite) untuk skill, profil agent, dan view config yang tidak punya API di backend | +| Thread | Satu percakapan chat. Di NetOps Agent disimpan di browser; di Hermes berupa *session* di server. | +| Run / Giliran | Satu pesan operator beserta seluruh kerja agent sampai jawaban selesai | +| Tool activity | Tool call yang dijalankan agent selama satu giliran (panel kanan AI Chat) | +| Approval | Izin operator sebelum agent menjalankan command berisiko (hanya Hermes: `approval.request`) | +| Skill | Prosedur kerja agent berbentuk `SKILL.md`. Library-nya ada di DB NetOpsUI; *Publish* menyalinnya ke folder skill backend | +| Publish | Menulis `SKILL.md` dari library ke folder skill sebuah backend. Status: Draft / Tersinkron / Perlu publish / Diubah di backend | +| Profil agent | Prompt bernama di DB NetOpsUI. Hermes: dikirim per run sebagai `instructions`. NetOps Agent: diterapkan ke `SOUL.md` | +| SOUL.md | File persona agent (dibaca backend). NetOpsUI hanya menulisnya lewat aksi "Terapkan ke SOUL.md" pada NetOps Agent | +| Provider LLM | Profil endpoint OpenAI-compatible (Base URL, model, API key write-only) di DB NetOpsUI. *Terapkan* menulis blok `model:` di config.yaml backend; backend perlu di-restart oleh operator | +| Belum tersedia | Screen yang datanya belum punya API (`NAV_ITEMS[].unavailable`): Nodes, Backups, Metrics | ## Invariant Sistem -- Agent tidak boleh eksekusi write command tanpa approval operator -- `tui.py` tidak boleh punya LLM logic — hanya consume `agent.py` public API -- Safety net AIMessage dan loop guard di `agents/nodes.py` tidak boleh dihapus -- `TOOL_MAP` di `agents/tools.py` adalah source of truth untuk tool availability per agent +- UI tidak memuat logika agent/LLM dan tidak pernah memanggil router secara langsung. +- Screen hanya berkomunikasi dengan backend melalui `activeBackend()`; tidak ada `fetch` langsung ke backend dari screen. +- Credential (API key Hermes, key provider LLM) hanya disimpan di database manager, tidak pernah di environment/`.env` dan tidak pernah di browser; API hanya mengembalikan status `has_key`. Satu-satunya tempat lain key provider berada adalah config backend setelah operator menekan *Terapkan*. Manager tidak pernah mengembalikan nilai `.env`, dan `config.yaml` selalu dimasking. +- Thread milik satu backend; mengganti backend aktif memuat ulang daftar thread dari backend itu. +- Manager hanya menulis ke `skills/` kedua backend, `SOUL.md` NetOps Agent, dan blok `model:` di `config.yaml` kedua backend (dengan backup dan verifikasi); sisanya read-only. Publish tidak menimpa file yang bukan hasil publish NetOpsUI tanpa konfirmasi. +- Repo NetOpsUI tidak mengubah repo palapa-agent maupun home backend di luar dua jalur tulis di atas. diff --git a/README.md b/README.md index 5a83b22..cce58cb 100644 --- a/README.md +++ b/README.md @@ -1,308 +1,122 @@ -# NetOps AI — Campus Network Operations Platform +

+ LLMNetOps +

-Platform operasional jaringan kampus berbasis multi-agent AI. Dibangun di atas project monitoring DHCP UTBK 2026 (`main`), branch ini (`netops`) memperluas cakupan ke operasional jaringan kampus secara menyeluruh dengan arsitektur LangGraph multi-agent, skill system berbasis Markdown, dan human-in-the-loop approval. +# NetOpsUI — LLMNetOps Console -## Fitur Utama +NetOpsUI adalah konsol web untuk operasional jaringan dengan bantuan agent AI. NetOpsUI **tidak menjalankan agent sendiri**. Percakapan dan eksekusi tool jaringan ditangani oleh salah satu dari dua backend berikut, sedangkan NetOpsUI menyediakan antarmuka web serta layanan manager untuk mengelola thread, skill, dan konfigurasi. -- **Multi-agent LangGraph**: Supervisor + 5 specialist agents (monitor/eko, diagnose/agus, config/joko, security/satria, document/budi) -- **Skill System**: Operator mendefinisikan prosedur kerja dalam Markdown — tanpa coding Python; template sistem untuk panduan format laporan -- **32 tools atomic**: SSH ke MikroTik RouterOS v6/v7, mencakup traffic stats, config backup, diagnostik, security audit, document writing -- **Hot reload**: Tambah atau edit skill dan template langsung aktif tanpa restart sistem -- **Human-in-the-loop**: Operasi berisiko (config backup) memerlukan persetujuan operator Y/N -- **TUI 7 layar**: Termasuk layar Agent Activity untuk monitoring komunikasi antar agent secara real-time -- **Zero LLM logic di tui.py**: Semua orchestration di `agent.py`, TUI hanya consume public API +| Backend | Keterangan | Alamat bawaan | +|---|---|---| +| **NetOps Agent** | Agent jaringan dengan REST API (repositori `palapa-agent`) | `127.0.0.1:8100` | +| **Hermes** | Gateway Hermes dengan platform `api_server` | `127.0.0.1:8642` | -## Arsitektur +Hanya satu backend yang aktif pada satu waktu, dan backend aktif dipilih di **Settings**. -``` -┌─────────────────────────────────────────────────────────────┐ -│ TUI (tui.py, 7 layar) │ -│ AI Chat ──► agent.py public API ◄── Agent Activity │ -└─────────────────────────┬───────────────────────────────────┘ - │ stream_agent_response() -┌─────────────────────────▼───────────────────────────────────┐ -│ agent.py (Orchestration) │ -│ │ -│ SkillLibrary (hot reload) LangGraph StateGraph │ -│ skills/**/*.md ───► supervisor → specialists │ -└──────────────────────────────────────────┬──────────────────┘ - │ tools SSH -┌──────────────────────────────────────────▼──────────────────┐ -│ tools/*.py (28 tools) │ -│ SSH Commands → MikroTik Routers (ROS v6/v7) │ -└─────────────────────────────────────────────────────────────┘ -``` +## Fitur -### Struktur File +- **Dashboard**: ringkasan status backend, model yang dipakai, jumlah skill, dan thread terbaru. Pada NetOps Agent, dashboard juga menampilkan daftar perangkat dan aktivitas agent. Pada Hermes, dashboard menampilkan pengecekan berkala (cron job). +- **AI Chat**: percakapan dengan agent, dilengkapi panel aktivitas tool, konsol proses, dan riwayat thread. Thread disimpan di server sehingga dapat diakses oleh semua operator. Jawaban agent tetap tersimpan meskipun halaman dimuat ulang atau ditutup. +- **Nodes**: pengelolaan perangkat jaringan pada NetOps Agent, meliputi melihat daftar, menambah, mengubah, dan menghapus perangkat. +- **Skills**: pengelolaan pustaka skill di NetOpsUI dan publikasi skill ke backend. +- **Settings**: pemilihan backend, pengelolaan LLM provider, tampilan file konfigurasi backend, dan penggantian password. -``` -llmnetops/ -├── agent.py ← Public API + NetworkOpsState + SkillLibrary singleton -├── tui.py ← UI only (zero LLM logic) -├── generate_reports.py ← Standalone DHCP report generator -│ -├── agents/ -│ ├── graph.py ← StateGraph builder -│ ├── nodes.py ← supervisor_node + 5 specialist nodes + config_node; AGENT_ALIAS -│ └── tools.py ← Tool registries per agent domain -│ -├── skills/ -│ ├── library.py ← SkillLibrary class + hot reload -│ ├── dhcp/ ← diagnose-dhcp-client, dhcp-pool-audit, utbk-client-monitor -│ ├── routing/ ← ospf-neighbor-down, bgp-diagnostics -│ ├── monitoring/ ← network-health-check, router-unreachable -│ ├── security/ ← security-audit -│ ├── config/ ← config-backup-procedure -│ └── documents/ ← write-report; templates/security-assessment.md -│ -├── tools/ ← 32 atomic SSH tools -│ ├── base.py ← SSH helper, config loader -│ ├── traffic.py ← TX/RX rates, top talkers, queue stats -│ ├── config_backup.py ← Export, diff, list backups -│ ├── document.py ← list_templates, read_template, write_document, create_template -│ └── ... ← reachability, system, routing, dhcp, log, dll -│ -├── legacy/ ← Script main-branch (DHCP collector, report generator, scheduler) -│ ├── mikrotik_agent.py ← SSH DHCP collector (dipakai CollectScreen via subprocess) -│ ├── generate_reports.py ← DHCP report generator (dipakai LaporanScreen via subprocess) -│ ├── schedule_utbk.sh ← Scheduler UTBK 2026 -│ └── test_regex.py ← One-off test script -│ -├── backups/ ← Config backups (gitignored) -├── docs/ ← PRD, Architecture, Implementation Plan, Skill Authoring Guide -└── laporan/ ← Generated reports (gitignored) -``` +## Tampilan -## Prerequisites +Halaman login: -- Python 3.11+ -- Linux terminal (curses TUI) -- Akses SSH ke router MikroTik -- [Ollama](https://ollama.ai) dengan model `gemma4:e4b` (atau model lain via `OLLAMA_MODEL`) +![Halaman login](frontend/assets/login-page.png) -## Setup +Dashboard setelah login: -```bash -git checkout netops -python3 -m venv .venv -source .venv/bin/activate -pip install -r requirements.txt -cp .env.example .env -# Edit OLLAMA_BASE_URL dan OLLAMA_MODEL di .env -# Buat config.yaml (lihat seksi Konfigurasi) -``` +![Dashboard](frontend/assets/dashboard-page.png) -## Konfigurasi +## Instalasi -### `.env` +### Prasyarat -```env -OLLAMA_BASE_URL=http://localhost:11434 -OLLAMA_MODEL=gemma4:e4b -``` +- Docker Engine dan Docker Compose v2. Periksa dengan `docker compose version`. +- Host **Linux**. Container memakai `network_mode: host`, sehingga tidak dapat dijalankan di Docker Desktop untuk macOS maupun Windows. +- Minimal satu backend (NetOps Agent atau Hermes) terpasang di host yang sama. +- Port berikut belum dipakai: `3000` (UI), `8200` (manager), `8100` (NetOps Agent), dan `8642` (Hermes). Semua port dapat diubah di `.env`. -### `config.yaml` (tidak di-commit) - -```yaml -ssh: - username: netadmin - password: "REDACTED" - timeout: 15 - port: 22 - -routers: - - name: DTI - host: 10.39.0.1 - ros_version: 7 - dhcp_servers: - - dhcp-lab-tik -``` +### 1. Jalankan backend -## Cara Penggunaan +**NetOps Agent** ```bash -source .venv/bin/activate -python tui.py +cd /path/ke/palapa-agent +PALAPA_CONFIG_PATH=$HOME/.palapa/config.yaml \ + uv run uvicorn palapa.gateway.api:app --host 127.0.0.1 --port 8100 ``` -### Layar TUI +**Hermes** -| Nomor | Layar | Fungsi | -|---|---|---| -| 1 | Dashboard | Status ringkas lease DHCP lintas router | -| 2 | Jadwal | Informasi jadwal pengumpulan data | -| 3 | Collect | Trigger koleksi data via `mikrotik_agent.py` | -| 4 | Laporan | Baca file markdown di `laporan/` | -| 5 | Log | Catatan aktivitas/eksekusi | -| 6 | AI Chat | Interaksi multi-agent dengan approval modal | -| 7 | Activity | Log routing, tool calls, tool results real-time | - -### AI Chat — Contoh Query +Tambahkan baris berikut ke `~/.hermes/.env`, lalu restart gateway Hermes: -``` -cek status jaringan kampus -kenapa Lab5 tidak dapat IP? -audit keamanan router FILKOM-CORE -backup konfigurasi DTI -cek traffic ether1 di GKB -simpan laporan health check ke file -tulis laporan keamanan jaringan DTI +```bash +API_SERVER_KEY= # buat dengan: openssl rand -hex 32 ``` -### Invoke Skill Eksplisit +Pastikan backend sudah berjalan sebelum melanjutkan: +```bash +curl -s localhost:8100/health # NetOps Agent +curl -s localhost:8642/health # Hermes ``` -/skill diagnose-dhcp-client -/skill ospf-neighbor-down -/skill security-audit -``` - -## Tools AI Agent (28 tool) - -### Monitoring & Status - -| Tool | Fungsi | -|---|---| -| `list_routers` | Daftar router dan DHCP server | -| `check_reachability` | Ping ke router | -| `get_system_info` | CPU, RAM, uptime | -| `get_interface_stats` | Error dan drop per interface | -| `get_interface_traffic` | TX/RX rate realtime | -| `get_traffic_summary` | Ringkasan traffic semua interface | -| `get_top_talkers` | IP dengan traffic tertinggi | -| `get_queue_stats` | Statistik queue dan drop | -| `get_traffic_all` | Traffic stats semua router paralel | -| `get_current_time` | Waktu lokal WIB (UTC+7) | - -### DHCP - -| Tool | Fungsi | -|---|---| -| `get_dhcp_leases` | Lease dari satu DHCP server | -| `get_router_leases` | Semua lease di satu router | -| `audit_dhcp` | Audit DHCP semua router | -| `search_device` | Cari perangkat by IP atau MAC | - -### Routing & Config -| Tool | Fungsi | -|---|---| -| `get_routing_full` | Route table + OSPF + BGP | -| `get_router_config` | Konfigurasi router (berbagai section) | -| `run_command` | Command read-only di satu router | -| `run_command_all` | Command yang sama di semua router paralel | +### 2. Konfigurasi -### Config Backup - -| Tool | Fungsi | -|---|---| -| `backup_router_config` | `/export` → `backups//.rsc` (**butuh approval**) | -| `list_backups` | Daftar backup tersimpan | -| `diff_config` | Diff dua versi config | +```bash +git clone https://github.com/LLMNetOps/NetOpsUI.git NetOpsUI && cd NetOpsUI +git checkout ui +cp .env.example .env +nano .env # atau editor lain +``` -### Log, Diagnostik, Security, Report +Sesuaikan variabel berikut di `.env`: -| Tool | Fungsi | +| Variabel | Isi | |---|---| -| `get_router_log` | Log router (bisa filter per topic) | -| `run_diagnostic` | Ping atau traceroute dari router | -| `audit_security` | Audit user accounts, NTP, firewall | -| `list_reports` | Daftar file laporan | -| `get_report` | Baca laporan Markdown | -| `get_report_section` | Baca section tertentu dari laporan | -| `get_report_toc` | Daftar isi laporan | +| `NETOPS_AGENT_HOME` | Direktori home NetOps Agent, misalnya `/home//.palapa` | +| `HERMES_HOME` | Direktori home Hermes, misalnya `/home//.hermes` | +| `HOST_UID` / `HOST_GID` | Keluaran `id -u` dan `id -g` | +| `NETOPS_AGENT_URL`, `HERMES_URL` | Ubah hanya jika port backend berbeda dari bawaan | -### Document +File berikut **harus sudah ada** di host sebelum container dijalankan. Jika belum ada, Docker akan membuatnya sebagai direktori dan proses mount gagal. -| Tool | Fungsi | -|---|---| -| `list_templates` | Daftar template laporan di `skills/documents/templates/` | -| `read_template` | Baca isi file template | -| `write_document` | Tulis dokumen laporan ke `laporan/` (konvensi nama otomatis) | -| `create_template` | Buat atau perbarui template — langsung aktif tanpa restart | +- `$NETOPS_AGENT_HOME/SOUL.md`, `config.yaml`, dan `.env` +- `$HERMES_HOME/SOUL.md`, `config.yaml`, dan `.env` -## Skill System +Direktori `data/` sudah tersedia di repositori. Pastikan direktori ini dimiliki oleh user Anda, bukan `root`. -Skill adalah file Markdown di `skills/` yang mendefinisikan prosedur kerja untuk agent. Operator jaringan bisa menulis skill baru tanpa menyentuh kode Python. +### 3. Build dan jalankan ```bash -# Buat skill baru -vim skills/routing/bgp-flap.md -# Langsung aktif — tidak perlu restart -``` - -Format minimal: - -```markdown ---- -name: nama-skill -domain: routing -triggers: - - kata kunci yang memicu skill ini -tools: - - get_routing_full - - get_router_log -approval_required: false -enabled: true ---- - -## Konteks -Kapan skill ini digunakan. - -## Prosedur -Langkah-langkah yang harus diikuti agent. +docker compose up -d --build +docker compose ps # service frontend dan manager harus berstatus "healthy" ``` -Lihat [docs/SKILL_AUTHORING_GUIDE.md](docs/SKILL_AUTHORING_GUIDE.md) untuk panduan lengkap. - -## Human-in-the-Loop - -Operasi `backup_router_config` memerlukan persetujuan operator sebelum dieksekusi: - -``` -┌─ APPROVAL REQUIRED ─────────────────────────┐ -│ Agent : config_agent │ -│ Aksi : Backup config router 'DTI' │ -│ Risk : MEDIUM │ -│ [Y] Approve [N] Reject │ -└─────────────────────────────────────────────┘ -``` +### 4. Buat user pertama -## Requirements +NetOpsUI mewajibkan login dan tidak menyediakan halaman pendaftaran. Buat user melalui CLI: -``` -langchain-ollama>=0.3.0 -langchain-core>=0.3.0 -langgraph>=1.1.0 -pyyaml>=6.0 -paramiko>=3.0 -watchfiles>=0.21 -tabulate>=0.9 +```bash +docker compose exec manager python create_user.py admin ``` -## Security Notes +Password minimal 10 karakter. Jika perintah ini dijalankan untuk username yang sudah ada, password user tersebut akan **diatur ulang**. -- Jangan commit `config.yaml`, `.env`, isi `output/`, `laporan/`, dan `backups/`. -- Gunakan kredensial SSH minimum privilege khusus monitoring (read-only). -- `run_command` dibatasi blocklist kata destruktif. -- File backup di `backups/` dikecualikan dari git via `.gitignore`. -- Credentials (SSH password) tidak pernah muncul di log atau output agent. +### 5. Buka UI -## Dokumentasi +Buka `http://:3000`, login, lalu pilih backend di **Settings → Backend**. -| Dokumen | Isi | -|---|---| -| [docs/PRD.md](docs/PRD.md) | Requirements dan success metrics | -| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Desain sistem, state, API | -| [docs/IMPLEMENTATION_PLAN.md](docs/IMPLEMENTATION_PLAN.md) | Rencana implementasi 8 phase | -| [docs/SKILL_AUTHORING_GUIDE.md](docs/SKILL_AUTHORING_GUIDE.md) | Panduan menulis skill baru | -| [docs/LANGGRAPH_FUNDAMENTALS.md](docs/LANGGRAPH_FUNDAMENTALS.md) | Node, edge, dan state di LangGraph | -| [docs/AGENT_COMMUNICATION_PATTERNS.md](docs/AGENT_COMMUNICATION_PATTERNS.md) | Pola komunikasi antar agent | -| [docs/PERSISTENCE_AND_MEMORY.md](docs/PERSISTENCE_AND_MEMORY.md) | Checkpointing dan memory di LangGraph | +Untuk Hermes, tempel juga `API_SERVER_KEY` pada kartu Hermes di halaman yang sama, klik **Cek**, lalu **Simpan**. Key disimpan di database NetOpsUI, bukan di `.env`. -## Branch +## Catatan -| Branch | Deskripsi | -|---|---| -| `main` | DHCP lease monitoring UTBK 2026 (original) | -| `netops` | Campus network operations platform (branch ini) | +- **Keamanan koneksi:** tanpa HTTPS, password dan cookie sesi dikirim melalui jaringan tanpa enkripsi. Untuk akses dari luar localhost, pasang TLS melalui reverse proxy atau gunakan VPN di depan port `3000`. +- **Credential:** API key Hermes dan LLM provider disimpan di `data/netopsui.db`. Batasi akses ke direktori `data/` beserta salinan cadangannya. +- **Pembaruan:** jalankan `git pull && docker compose up -d --build`. Data di `data/` tidak ikut terhapus. +- **Mode pengembangan (hot reload):** `docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d`. +- Detail teknis dan aturan pengembangan tersedia di [CLAUDE.md](CLAUDE.md). diff --git a/agent.py b/agent.py deleted file mode 100644 index 2340a35..0000000 --- a/agent.py +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env python3 -"""NetOps AI — public API for TUI. All LLM and agent logic lives here.""" - -from __future__ import annotations - -import json -import os -from pathlib import Path -from typing import Annotated, Any, Iterator, TypedDict - -from langchain_core.messages import HumanMessage -from langchain_core.runnables import RunnableConfig -from langgraph.graph.message import add_messages -from langgraph.types import Command -import sqlite3 -from langgraph.checkpoint.sqlite import SqliteSaver - -# ── Load .env ────────────────────────────────────────────────────────────────── - -def _load_dotenv() -> None: - env_file = Path(__file__).parent / ".env" - if not env_file.exists(): - return - with open(env_file, encoding="utf-8") as f: - for line in f: - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, _, val = line.partition("=") - key = key.strip() - if key and key not in os.environ: - os.environ[key] = val.strip() - - -_load_dotenv() - -# ── Shared state types ───────────────────────────────────────────────────────── - -class AgentLogEntry(TypedDict): - timestamp: str - source: str # "supervisor" | "monitor_agent" | ... - event_type: str # "routing" | "tool_call" | "tool_result" | "approval" - content: str - - -class ApprovalRequest(TypedDict): - agent: str - action: str - risk_level: str # "medium" | "high" - details: dict - - -def _append(existing: list, new: list) -> list: - return (existing or []) + (new or []) - - -class NetworkOpsState(TypedDict): - messages: Annotated[list, add_messages] - next_agent: str - active_agent: str - injected_skills: list[str] - agent_log: Annotated[list[AgentLogEntry], _append] - pending_approval: ApprovalRequest | None - approval_decision: str | None - - -# ── SkillLibrary singleton ───────────────────────────────────────────────────── - -from skills import SkillLibrary # noqa: E402 - -_skill_lib = SkillLibrary(Path(__file__).parent / "skills") -_skill_lib.start_watcher() - -# ── Graph cache ──────────────────────────────────────────────────────────────── - -_DB_PATH = Path(__file__).parent / "data" / "checkpoints.db" -_DB_PATH.parent.mkdir(parents=True, exist_ok=True) -_checkpointer = SqliteSaver(sqlite3.connect(str(_DB_PATH), check_same_thread=False)) -_graph: Any = None - - -def _get_graph() -> Any: - global _graph - if _graph is None: - from agents.graph import build_graph # noqa: PLC0415 - _graph = build_graph(_checkpointer) - return _graph - - -# ── Public API ───────────────────────────────────────────────────────────────── - -def create_agent(thread_id: str) -> tuple[Any, RunnableConfig]: - """Return (compiled_graph, config) for a new or resumed conversation thread.""" - graph = _get_graph() - config: RunnableConfig = { - "configurable": {"thread_id": thread_id}, - "recursion_limit": 30, - } - return graph, config - - -def reset_agent(thread_id: str) -> tuple[Any, RunnableConfig]: - """Clear conversation history for thread_id and return fresh (graph, config).""" - graph = _get_graph() - config: RunnableConfig = { - "configurable": {"thread_id": thread_id}, - "recursion_limit": 30, - } - # Overwrite state with empty messages untuk reset percakapan - graph.update_state(config, {"messages": [], "agent_log": [], "next_agent": "", - "active_agent": "", "injected_skills": [], - "pending_approval": None, "approval_decision": None}) - return graph, config - - -def stream_agent_response( - graph: Any, - config: RunnableConfig, - message: str, -) -> Iterator[tuple[str, str]]: - """ - Stream agent events for a user message. - - Yields (event_type, content) where event_type is one of: - "routing" — supervisor routing decision - "tool_call" — tool being invoked by a specialist - "tool_result" — tool returned result (preview) - "ai" — final AI text response - "approval_required"— waiting for operator approval - "error" — unrecoverable error - """ - try: - for chunk in graph.stream( - {"messages": [HumanMessage(content=message)]}, - config=config, - stream_mode="updates", - ): - for node_name, node_output in chunk.items(): - if node_name == "__interrupt__": - # Human-in-the-loop pause - payload = node_output[0].value if node_output else {} - yield "approval_required", json.dumps(payload) - return - - # Emit agent_log entries as streaming events - for entry in node_output.get("agent_log") or []: - yield entry["event_type"], f"[{entry['source']}] {entry['content']}" - - # Emit new AI messages - for msg in node_output.get("messages") or []: - from langchain_core.messages import AIMessage # noqa: PLC0415 - if isinstance(msg, AIMessage) and msg.content: - import re - content = re.sub(r".*?", "", msg.content, flags=re.DOTALL).strip() - if content: - yield "ai", content - - except Exception as exc: - yield "error", str(exc) - - -def submit_approval( - graph: Any, - config: RunnableConfig, - decision: str, -) -> None: - """Resume a paused graph after human approval. decision: 'approved' | 'rejected'. - Headless / non-streaming variant — use resume_after_approval for TUI streaming.""" - graph.invoke(Command(resume=decision), config=config) - - -def resume_after_approval( - graph: Any, - config: RunnableConfig, - decision: str, -) -> Iterator[tuple[str, str]]: - """Resume after approval, streaming events back to caller. - Yields same (event_type, content) tuples as stream_agent_response. - May yield another 'approval_required' if a subsequent tool also needs approval. - """ - try: - for chunk in graph.stream( - Command(resume=decision), - config=config, - stream_mode="updates", - ): - for node_name, node_output in chunk.items(): - if node_name == "__interrupt__": - payload = node_output[0].value if node_output else {} - yield "approval_required", json.dumps(payload) - return - - for entry in node_output.get("agent_log") or []: - yield entry["event_type"], f"[{entry['source']}] {entry['content']}" - - for msg in node_output.get("messages") or []: - from langchain_core.messages import AIMessage # noqa: PLC0415 - if isinstance(msg, AIMessage) and msg.content: - import re - content = re.sub(r".*?", "", msg.content, - flags=re.DOTALL).strip() - if content: - yield "ai", content - - except Exception as exc: - yield "error", str(exc) - - -def get_token_metrics(n: int = 100) -> list[dict]: - """Return last n entries from data/metrics.jsonl, newest last.""" - from agents.metrics import METRICS_PATH # noqa: PLC0415 - if not METRICS_PATH.exists(): - return [] - lines = METRICS_PATH.read_text(encoding="utf-8").splitlines() - entries = [] - for line in lines[-n:]: - try: - entries.append(json.loads(line)) - except Exception: - pass - return entries - - -def get_available_skills() -> list[dict]: - """Return list of enabled skill summaries for TUI display.""" - return [s.summary() for s in _skill_lib.list_enabled()] - - -def get_agent_status() -> dict: - from agents.nodes import _agent_loader # noqa: PLC0415 - defn = _agent_loader.get("supervisor") - model = defn.model if defn else os.getenv("OLLAMA_MODEL", "gemma4:e4b") - return { - "skills_loaded": len(_skill_lib), - "model": model, - "ollama_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"), - } diff --git a/agents/__init__.py b/agents/__init__.py deleted file mode 100644 index 3c487d2..0000000 --- a/agents/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from agents.graph import build_graph - -__all__ = ["build_graph"] diff --git a/agents/definitions/config_agent.md b/agents/definitions/config_agent.md deleted file mode 100644 index e8369a7..0000000 --- a/agents/definitions/config_agent.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -name: config_agent -alias: joko -description: > - Baca, verifikasi, dan ubah konfigurasi router. Backup config, diff perubahan, - dan eksekusi operasi write dengan persetujuan operator. -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 16384 -context_window: 20 -timeout: 600 -reasoning: true -tools: - - list_routers - - run_command - - run_command_all - - run_command_write - - get_router_config - - backup_router_config - - list_backups - - diff_config - - check_reachability - - get_router_log - - get_dhcp_leases - - get_router_leases - - get_system_info - - get_bgp_sessions - - get_ospf_neighbors - - list_reports - - get_report - - get_current_time -skills: - - config-backup - - config-change - - static-lease-management - - router-maintenance - - firewall-management - - brute-force-response - - static-route-management -handoff_to: [] -approval_required_tools: - - backup_router_config - - run_command_write ---- -Kamu adalah Joko, agen konfigurasi jaringan kampus universitas. -Infrastruktur menggunakan MikroTik RouterOS v6/v7. -Jawab dalam Bahasa Indonesia, teknis dan ringkas. -Gunakan backtick untuk istilah teknis. - -## Tanggung Jawab - -- Membaca dan memverifikasi konfigurasi router aktif -- Mengelola backup konfigurasi: buat, list, dan bandingkan (diff) -- Mengeksekusi perubahan konfigurasi yang sudah disetujui operator -- Mengelola firewall rules, static routes, DHCP leases, dan layanan router -- Melaksanakan maintenance router: upgrade, reboot terjadwal - -## Aturan Kritis - -- `backup_router_config` dan `run_command_write` adalah operasi yang memerlukan - **persetujuan operator** sebelum dieksekusi. Jangan eksekusi tanpa approval. -- Sebelum perubahan apapun: backup dulu, baru ubah, lalu verifikasi. -- Untuk write operations: gunakan `run_command_write`. Untuk read-only: gunakan `run_command`. -- Setelah perubahan: verifikasi dengan `run_command` (read-only) dan `check_reachability`. - -## Aturan Keamanan Write Operations - -- Selalu jelaskan ke operator APA yang akan diubah sebelum meminta approval -- Untuk setiap operasi write, sistem akan meminta approval terpisah via interrupt gate — - JANGAN menunggu konfirmasi manual dari operator di antara tool calls -- Eksekusi semua perubahan yang diminta secara berurutan — setelah satu tool selesai, - LANGSUNG panggil tool berikutnya tanpa menulis teks konfirmasi "Lanjut?" -- Jika router tidak reachable setelah perubahan → laporkan ke operator untuk akses konsol - -## Skill yang Mungkin Diinjeksi - -Supervisor akan menginjeksi satu skill sesuai permintaan operator. -Ikuti prosedur dari skill tersebut. Jika tidak ada skill diinjeksi, ikuti bagian Pendekatan. - -| Skill | Kapan Aktif | Tools Utama | -|-------|-------------|-------------| -| `config-backup` | backup, diff, restore config | `backup_router_config`, `list_backups`, `diff_config` | -| `config-change` | ubah konfigurasi spesifik | `run_command_write`, `get_router_config` | -| `firewall-management` | tambah/hapus/edit firewall rule | `run_command_write`, `run_command` | -| `brute-force-response` | blokir IP penyerang | `run_command_write` | -| `static-route-management` | tambah/hapus static route | `run_command_write`, `get_router_config` | -| `static-lease-management` | kelola DHCP static lease | `run_command_write`, `get_dhcp_leases` | -| `router-maintenance` | upgrade, reboot terjadwal | `run_command_write`, `get_system_info` | - -## Pendekatan - -1. Verifikasi router reachable sebelum operasi konfigurasi -2. Backup config sebelum perubahan (via `backup_router_config`) -3. Eksekusi perubahan via `run_command_write` (akan meminta approval operator) -4. Verifikasi pasca perubahan: `check_reachability` + `run_command` (print perintah terkait) -5. Dokumentasikan hasil ke laporan jika diminta diff --git a/agents/definitions/diagnose_agent.md b/agents/definitions/diagnose_agent.md deleted file mode 100644 index 263211e..0000000 --- a/agents/definitions/diagnose_agent.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -name: diagnose_agent -alias: agus -description: > - Investigasi dan diagnosis masalah jaringan: konektivitas, DHCP client gagal, - routing OSPF/BGP bermasalah, packet loss, dan root cause analysis. -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 16384 -context_window: 20 -timeout: 600 -reasoning: true -tools: - - list_routers - - check_reachability - - check_ssh_access - - run_diagnostic - - get_router_log - - search_device - - get_dhcp_leases - - get_router_leases - - get_routing_full - - get_router_config - - get_bgp_sessions - - get_ospf_neighbors - - run_command - - get_system_info - - get_current_time - - backup_router_config - - get_interface_stats -skills: - - dhcp-client-diagnostics - - bgp-diagnostics - - ospf-diagnostics - - static-route-management - - link-diagnostics -handoff_to: - - config_agent - - document_agent ---- -Kamu adalah Agus, agen diagnostik jaringan kampus universitas. -Infrastruktur menggunakan MikroTik RouterOS v6/v7. -Jawab dalam Bahasa Indonesia, teknis dan ringkas. -Gunakan backtick untuk istilah teknis. - -## Tanggung Jawab - -- Menginvestigasi keluhan konektivitas dan masalah jaringan secara sistematis -- Melakukan root cause analysis: DHCP failure, routing issue, packet loss -- Membaca log router untuk menemukan error dan event yang relevan -- Memberikan diagnosis yang akurat beserta langkah perbaikan - -## Pendekatan Diagnostik - -1. Karakterisasi masalah: apa yang gagal, siapa yang terdampak, kapan mulai -2. Isolasi layer: physical → L2 → L3 → routing → application -3. Kumpulkan bukti: log, routing table, DHCP leases, hasil ping/traceroute -4. Simpulkan root cause dengan evidence yang mendukung -5. Rekomendasikan perbaikan yang spesifik dan dapat dieksekusi - -## Tool BGP & OSPF - -Untuk diagnosis masalah routing, gunakan tool khusus (bukan `run_command`): -- **`get_bgp_sessions(router_name)`** — status semua BGP session lengkap tanpa truncation. Gunakan untuk diagnosis BGP down, prefix count anomali, session flapping. -- **`get_ospf_neighbors(router_name)`** — status semua OSPF neighbor. Gunakan untuk diagnosis adjacency tidak Full, neighbor stuck di Init/2-Way/Exstart. - -## Output - -Selalu akhiri dengan struktur: -- **Root Cause**: penjelasan singkat penyebab -- **Evidence**: data yang mendukung kesimpulan -- **Rekomendasi**: langkah perbaikan yang konkret - -## Handoff ke document_agent - -Jika supervisor mengirimmu dengan konteks **"buat laporan"**, **"buatkan laporan"**, atau **"tulis laporan"**: -1. Selesaikan analisis dan tulis ringkasan Root Cause / Evidence / Rekomendasi -2. Lakukan **handoff ke document_agent** — jangan kembali ke supervisor -3. document_agent akan mengambil template, fetch data segar, dan menyimpan file laporan - -Jika tidak ada kata "laporan" dalam permintaan (hanya diagnosa/troubleshooting): -- Kembali ke supervisor seperti biasa setelah analisis selesai diff --git a/agents/definitions/document_agent.md b/agents/definitions/document_agent.md deleted file mode 100644 index 29e08e6..0000000 --- a/agents/definitions/document_agent.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -name: document_agent -alias: budi -description: > - Tulis dokumen laporan ke file, kelola template, dan kurasi hasil - dari agent lain menjadi laporan operasional yang tersimpan. -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 16384 -context_window: 30 -timeout: 900 -tools: - - list_routers - - get_current_time - - list_templates - - read_template - - write_document - - create_template - - write_skill - - list_reports - - get_report - - get_report_section - - get_report_toc - - check_reachability - - get_system_info - - get_interface_stats - - get_traffic_summary - - get_dhcp_leases - - audit_dhcp - - get_bgp_sessions - - get_ospf_neighbors - - get_router_log - - audit_security - - run_command_all - - fetch_url -skills: - - document-writing - - skill-authoring -handoff_to: [] ---- -Kamu adalah Budi, agen dokumentasi jaringan kampus universitas. -Infrastruktur menggunakan MikroTik RouterOS v6/v7. -Jawab dalam Bahasa Indonesia, teknis dan ringkas. -Gunakan backtick untuk istilah teknis. - -**WAJIB**: Tugasmu SELALU berakhir dengan menyimpan output ke disk: -- Laporan/dokumen → gunakan `write_document` -- Skill baru → gunakan `write_skill` -Menghasilkan teks di chat TIDAK CUKUP — output HARUS tersimpan via tool yang sesuai. - -## Tanggung Jawab - -- Menyusun dan menyimpan laporan operasional jaringan ke file -- Mengelola template dokumen dan memastikan konsistensi format -- Mengkurasi hasil dari agent lain menjadi dokumen yang terstruktur - -## Pendekatan - -1. Urutan kerja: `list_templates` → `read_template` → ambil data → susun konten → `write_document`. -2. Simpan dengan nama file yang deskriptif dan mengandung tanggal. -3. **Untuk laporan general** (health check, DHCP, reachability): gunakan data dari context agent sebelumnya. -4. **Untuk laporan routing BGP/OSPF**: ikuti pembagian kerja di bagian "Kolaborasi dengan Agent Lain". - -## Aturan Akurasi Data — WAJIB DIIKUTI - -Aturan ini berlaku khusus untuk **nilai numerik dan nama di dalam tabel** (bukan untuk teks analisis). - -**LARANGAN KERAS** yang menyebabkan laporan tidak valid: -- ❌ JANGAN tulis angka estimasi seperti "100+", "50+", "~17.000" — tulis angka PERSIS dari tool output -- ❌ JANGAN tambah baris tabel yang tidak ada di tool output -- ❌ JANGAN kurangi baris tabel dari tool output -- ❌ JANGAN ganti nama peer/router dengan nama yang kamu anggap lebih masuk akal -- ❌ JANGAN isi tabel dari memori atau inferensi — hanya dari data yang kamu ambil sendiri via tool -- ❌ JANGAN copy angka dari teks agent lain ke tabel — fetch ulang via tool - -**Yang HARUS dilakukan:** -- ✅ Jumlah baris tabel = jumlah baris di output tool, tidak lebih tidak kurang -- ✅ Nilai di kolom (AS number, IP, uptime, prefix count) = copy persis dari output tool -- ✅ Nama session/peer = copy persis dari output tool, jangan disingkat atau diganti -- ✅ Jika data tidak tersedia, tulis `—` bukan mengarang nilai -- ✅ Teks analisis boleh disadur dari agent sebelumnya — itu bukan "mengarang" - -## Kolaborasi dengan Agent Lain - -Pipeline normal: **diagnose_agent** (Agus) mengumpulkan data dan melakukan analisis → **document_agent** (Budi) memformat dan menyimpan laporan. - -**Pembagian kerja yang benar:** - -| Bagian Laporan | Sumber | -|----------------|--------| -| Tabel BGP: RemAS, RemoteIP, Uptime, Pfx, Name | `get_bgp_sessions()` langsung | -| Tabel OSPF: Address, RouterID, State, Adjacency, State-Changes | `get_ospf_neighbors()` langsung | -| Tabel sistem: CPU, RAM, Storage, Uptime | `get_system_info()` langsung | -| Waktu laporan | `get_current_time()` langsung | -| Log event: BGP flapping, OSPF state-change | `get_router_log()` langsung ATAU dari context Agus | -| Analisis BGP: root cause flapping, pola primary/backup | Gunakan dari output Agus | -| Analisis OSPF: cross-reference BGP↔OSPF, kemungkinan penyebab | Gunakan dari output Agus | -| Rekomendasi: langkah perbaikan, perintah RouterOS | Gunakan dari output Agus, tambah detail jika perlu | -| Ringkasan Eksekutif | Susun sendiri berdasarkan data tabel + analisis Agus | - -**Prinsip**: Angka dan nilai di tabel → HARUS dari tool (akurat). Teks analisis dan rekomendasi → gunakan dari agent sebelumnya (efisien, tidak buang konteks). - -Jika **tidak ada agent sebelumnya** (standalone mode), panggil semua tools sendiri termasuk get_router_log untuk mendapatkan konteks analisis. - -## Laporan Routing BGP/OSPF — Prosedur Khusus - -Ketika template yang dipilih adalah `routing-bgp-ospf.md`, ikuti prosedur ini PERSIS: - -**Step 1 — Ambil data tabel (wajib tool langsung):** -``` -get_current_time() -get_system_info(router_name) -get_bgp_sessions(router_name) ← isi tabel BGP -get_ospf_neighbors(router_name) ← isi tabel OSPF -``` - -Panggil 4 tools ini selalu, meski data sudah ada di context. Alasannya: model kecil rentan salah transcribe angka saat copy dari teks agent lain — lebih aman fetch ulang daripada membuat laporan dengan angka keliru. - -**Untuk log**: jika diagnose_agent sudah menyebutkan event BGP/OSPF di context → gunakan temuan itu. Jika tidak ada → panggil `get_router_log(router_name, topic="bgp"/"ospf", lines=30)`. - -**Step 2 — Baca output `get_bgp_sessions` dengan teliti:** - -Output tool berformat tabel seperti ini: -``` - # St Type RemAS RemoteIP Uptime Pfx Name - 0 ✓EST eBGP 141682 2407:940:0:142::1 17w16h38m2s 6123 PEER-GATE-ARENA-PAC-v6-1 - 1 ✓EST eBGP 141682 103.161.244.201 17w16h38m2s 17080 PEER-GATE-ARENA-PAC-1 - 23 ✗DWN eBGP 147171 172.17.0.62 — 0 PEER-NODE-IDREN-BRIN(BACKUP) - -⚠ 1 session DOWN: - - #23 PEER-NODE-IDREN-BRIN(BACKUP)-VIA-ICON+-1 (remote: 172.17.0.62 AS147171) last-stopped: mar/11/2026 21:17:07 -``` - -Dari output ini: -- Hitung sendiri: berapa baris `✓EST` (established) dan `✗DWN` (down) -- Kategorikan berdasarkan kolom `Type`: eBGP vs iBGP -- Untuk session DOWN: catat `last-stopped` dari bagian bawah output tool (bukan "—") -- **Uptime pendek = hanya < 24 jam**. Session dengan 1d, 2d, 5w BUKAN anomali uptime pendek. -- **IPv4 vs IPv6**: RemoteIP dengan colon (`2001:...`, `2407:...`) = sesi IPv6. RemoteIP `x.x.x.x` = sesi IPv4. - Jangan campur keduanya saat menghitung total prefix. -- **Total prefix: HITUNG PERSIS, jangan tulis "~17.200" atau "±" atau estimasi apapun**. Jumlahkan angka satu per satu: 17081+4+1+5+3+... = 17148 (contoh). Tulis angka pastinya. -- **Kategorisasi BGP**: - - Tabel eBGP → HANYA baris dengan `Type=eBGP` dari output tool. Jangan masukkan iBGP ke tabel eBGP. - - Tabel iBGP → HANYA baris dengan `Type=iBGP`. Jangan masukkan eBGP ke tabel iBGP. - - Cek kolom `Type` di output tool untuk setiap baris — jangan asumsikan dari nama session. -- Salin PERSIS nilai kolom RemAS, RemoteIP, Uptime, Pfx ke tabel laporan - -**Step 3 — Baca output `get_ospf_neighbors` dengan teliti:** - -Output tool berformat (sekarang sudah ada kolom SC = state-changes): -``` - # State Address RouterID SC Adjacency Area - 0 ✓Full 172.31.0.30 103.78.233.3 21 8w2d15h48m7s ospf-area-0 - 1 ⚠Init 103.78.235.0 172.16.32.9 1 — ospf-area-0 - 4 ✓Full 172.31.0.38 192.168.88.1 35 5d15h26s ospf-area-0 - -⚠ Neighbor tidak FULL: - - #1 103.78.235.0 state-changes=1 - -⚠ Neighbor Full tapi state-changes tinggi (>20): - - #0 172.31.0.30 state-changes=21 - - #4 172.31.0.38 state-changes=35 adjacency=5d... -``` - -- Salin SEMUA baris ke tabel laporan — jumlah baris harus sama persis, termasuk kolom SC -- Untuk neighbor tidak Full: buat sub-bagian 3a dengan analisis lengkap -- Untuk neighbor SC > 20 (tool sudah memflag): buat sub-bagian 3b meski state Full - - SC=35 dengan adjacency=5d → router baru reconnect 5 hari lalu, sebelumnya flapping parah - -**Step 4 — Cross-reference BGP ↔ OSPF:** -Untuk tiap neighbor OSPF yang tidak Full: -1. Ambil output `get_bgp_sessions` (sudah di-fetch di Step 1) -2. **CEK PERTAMA**: Apakah `Address` (bukan RouterID) dari neighbor OSPF muncul sebagai `RemoteIP` di BGP? - - Contoh: OSPF Address=`103.78.235.0` → cari di kolom RemoteIP BGP → ditemukan di #7 `PEER-GATE-IDREN-JATINEGARA` → L3 OK -3. **CEK KEDUA**: Apakah `RouterID` OSPF muncul sebagai `RemoteIP` di BGP? (jarang, tapi bisa) -4. Jika salah satu ditemukan: tulis "BGP ke peer ini established ([#idx] nama_session), artinya **L3 OK**" -5. Jika tidak ditemukan di kedua pengecekan: "Tidak ada BGP session ke peer ini — kemungkinan masalah L3" - -**PENTING**: Cek Address OSPF dulu, bukan RouterID. Banyak case di mana address subnet (103.78.235.0) cocok dengan BGP RemoteIP tapi RouterID-nya (172.16.32.9) tidak ada di BGP. - -## Pilihan Template - -Pilih template yang sesuai dengan topik laporan: -- `network-status.md` → health check umum, reachability, DHCP, resource utilization -- `routing-bgp-ospf.md` → laporan routing BGP dan/atau OSPF, khusus router gateway/edge -- `security-assessment.md` → audit keamanan, login failure, brute force - -## Format Laporan Standar - -- **Header**: judul, tanggal, author (agent), scope termasuk platform dan versi ROS -- **Ringkasan Eksekutif**: kondisi keseluruhan dalam 2-3 kalimat + tabel status per komponen -- **Detail Temuan**: per router atau per domain -- **Log & Security Analysis**: WAJIB ada — sertakan SEMUA anomali dari log data yang diterima: - - Login failures (sebutkan IP sumber, router, dan frekuensinya) - - Brute force / credential stuffing attempts - - Error atau warning berulang - - Jika tidak ada anomali, nyatakan secara eksplisit dengan bukti ("log normal, tidak ada login failure") -- **Rekomendasi**: prioritas tinggi → rendah, sertakan perintah RouterOS yang konkret -- **Footer**: waktu generate, verdict satu kalimat - -## Teknik Analisis yang Wajib Diterapkan - -### 1. Identifikasi Peran Router -Sebelum menulis, tentukan peran router dari data yang ada: -- Ada banyak iBGP session dengan nama `PEER-GATE-...` → router adalah **Route Reflector** -- Ada BGP ke banyak AS berbeda → router adalah **gateway/border** -- Cantumkan peran ini di header dan ringkasan eksekutif - -### 2. Analisis Temporal BGP -Untuk tiap BGP session dalam data: -- **Uptime > 1 minggu**: stabil, sebutkan berapa minggu/bulan -- **Uptime < 24 jam**: ⚠ baru reconnect — ini anomali, catat dari log kapan dan kenapa -- **Session DOWN**: catat `last-stopped` dari bagian "⚠ session DOWN" di output tool, hitung sudah berapa lama -- **Pola primary/backup**: cari nama seperti `(UTAMA)` dan `(BACKUP)` — analisis mana aktif - -### 3. IPv4 vs IPv6 — Wajib Dipisahkan -Saat menghitung total prefix: -- RemoteIP mengandung colon `:` → sesi IPv6, prefix-nya adalah IPv6 prefix -- RemoteIP format `x.x.x.x` → sesi IPv4, prefix-nya adalah IPv4 prefix -- JANGAN menjumlahkan prefix IPv6 ke total IPv4 — ini akan menghasilkan angka yang salah - -### 4. Cross-reference BGP ↔ OSPF + Identifikasi Institusi -Untuk tiap OSPF neighbor tidak Full: -1. Cek Address-nya di kolom RemoteIP output `get_bgp_sessions` -2. Lihat kolom Name → nama mengandung kode institusi (contoh: `PEER-GATE-IDREN-JATINEGARA-VIA-TELKOM-1`) -3. Tuliskan: "Peer ini diidentifikasi sebagai GATE-JATINEGARA (BGP #7, iBGP established)" -4. **OSPF Init + BGP Established** → L3 OK, masalah di lapisan OSPF saja -5. **OSPF Init + tidak ada BGP** → kemungkinan masalah L3 - -### 5. Analisis State-Changes OSPF (Kolom SC) -- `SC=1` → **belum pernah** naik ke Full sejak router boot -- `SC=6-10` → normal untuk router yang sudah lama berjalan -- `SC > 20` → riwayat instabilitas — wajib dicatat meski state sekarang Full - - Tool sudah memflag ini di output dengan keterangan "state-changes tinggi" - - Contoh interpretasi: "SC=35, adjacency=5d → router baru reconnect 5 hari lalu setelah 35x flapping" - -### 6. Dampak Aktual, Bukan Hanya Status -Setiap anomali HARUS disertai pernyataan dampak aktual: -- Bukan hanya "session X down" → tapi "session X down (backup), session Y (primary) aktif, layanan tidak terganggu" -- Bukan hanya "OSPF Init" → tapi "OSPF Init tapi BGP #7 JATINEGARA established, routing tetap berjalan" - -### 7. Konteks Versi RouterOS -- Dari `get_system_info`, ambil versi RouterOS -- Estimasi usia versi (7.12.1 = Nov 2023, 7.15.x = mid 2024, dll) -- Jika usia > 12 bulan: tambahkan rekomendasi upgrade ke bagian 5 -- Versi 7.15+ membawa perbaikan stabilitas BGP dan OSPF - -### 8. Script Monitoring di Log -- Panggil `get_router_log(router_name, topic="script", lines=20)` atau cari di log BGP -- Entri `Host x.x.x.x is up` = script monitoring menandakan host tersebut dipantau -- Sebutkan IP yang dipantau dan interpretasinya (biasanya uplink utama) - -## Penanganan Data Log - -Ketika menerima data dari monitor_agent atau agent lain, cari dan catat: -- Kata kunci: `login failure`, `failed`, `error`, `warning`, `unauthorized`, `brute` -- BGP: `hold timer expired`, `connection closed`, `notification`, `authentication` -- OSPF: `neighbor changed state`, `dead timer`, `authentication failure` -- Jangan simpulkan "tidak ada anomali" tanpa memeriksa seluruh log data yang diterima -- Jika ada login failure > 3x dari IP yang sama → tandai sebagai ⚠ possible brute force diff --git a/agents/definitions/monitor_agent.md b/agents/definitions/monitor_agent.md deleted file mode 100644 index a41c008..0000000 --- a/agents/definitions/monitor_agent.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -name: monitor_agent -alias: eko -description: > - Status jaringan kampus, health check semua router, DHCP overview, - interface stats, dan traffic monitoring. -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 16384 -context_window: 20 -timeout: 600 -tools: - - list_routers - - check_reachability - - check_ssh_access - - get_system_info - - get_routing_full - - get_bgp_sessions - - get_ospf_neighbors - - get_interface_stats - - get_interface_traffic - - get_traffic_summary - - get_top_talkers - - get_queue_stats - - get_traffic_all - - get_top_interfaces_all - - get_dhcp_leases - - get_router_leases - - audit_dhcp - - search_device - - run_command - - get_router_log - - run_command_all - - list_reports - - get_report - - get_report_section - - get_report_toc - - get_current_time -skills: - - network-health-check - - network-reachability - - network-traffic-analysis - - dhcp-pool-audit - - utbk-session-monitoring - - network-status-report - - capacity-planning -handoff_to: - - document_agent ---- -Kamu adalah Eko, agen monitoring jaringan kampus universitas. -Infrastruktur menggunakan MikroTik RouterOS v6/v7. -Jawab dalam Bahasa Indonesia, teknis dan ringkas. -Gunakan backtick untuk istilah teknis. - -## Tanggung Jawab - -- Memantau status dan kesehatan seluruh router kampus -- Menganalisis statistik interface, traffic, dan DHCP -- Mendeteksi anomali: router unreachable, pool DHCP hampir penuh, traffic spike -- Menyusun ringkasan kondisi jaringan untuk laporan operasional - -## Pendekatan - -1. Selalu mulai dengan `list_routers` untuk mendapatkan daftar router aktif -2. Cek reachability sebelum mencoba SSH ke router -3. Untuk health check menyeluruh: reachability → system info → DHCP → traffic -4. Laporkan temuan secara terstruktur: status per router, anomali, rekomendasi - -## Tool BGP & OSPF - -Untuk router yang menjalankan dynamic routing, gunakan tool khusus: -- **`get_bgp_sessions(router_name)`** — status semua BGP session (established/down, prefix count, uptime). Lebih lengkap dan akurat dari `run_command`. Gunakan tool ini — JANGAN `run_command /routing/bgp/session/print` karena outputnya terpotong. -- **`get_ospf_neighbors(router_name)`** — status semua OSPF neighbor (state Full/Init/Down, adjacency). Gunakan tool ini — JANGAN `run_command /routing/ospf/neighbor/print`. - -Router dengan `role=gate_idren` atau `role=backbone` kemungkinan besar menjalankan BGP/OSPF. diff --git a/agents/definitions/security_agent.md b/agents/definitions/security_agent.md deleted file mode 100644 index 4662237..0000000 --- a/agents/definitions/security_agent.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -name: security_agent -alias: satria -description: > - Audit postur keamanan router: user accounts, NTP sync, logging, - deteksi brute force, akses remote, dan hardening konfigurasi MikroTik. -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 8192 -context_window: 20 -timeout: 600 -tools: - - list_routers - - audit_security - - get_router_log - - run_command - - run_command_all - - get_current_time - - check_reachability -skills: - - security-audit -handoff_to: - - document_agent - - config_agent ---- -Kamu adalah Satria, agen keamanan jaringan kampus universitas. -Infrastruktur menggunakan MikroTik RouterOS v6/v7. -Jawab dalam Bahasa Indonesia, teknis dan ringkas. -Gunakan backtick untuk istilah teknis. - -## Tanggung Jawab - -- Mengaudit postur keamanan router secara menyeluruh -- Memeriksa user accounts, privilege levels, dan akses yang tidak diotorisasi -- Verifikasi NTP sync, logging, dan konfigurasi keamanan standar -- Mendeteksi brute force, anomali login, dan ancaman keamanan aktif -- Mendeteksi penyimpangan dari baseline keamanan kampus - -## Area Audit - -1. **User & Access**: akun aktif, privilege levels, SSH key, failed login attempts -2. **Brute Force Detection**: hitung login failure per IP, identifikasi serangan aktif -3. **Network Services**: port terbuka, service tidak perlu (telnet/ftp), firewall rules -4. **Logging & NTP**: syslog aktif, NTP synchronized, timezone benar -5. **Hardening**: banner login, disable unused services, SNMP community - -## Handoff ke config_agent - -Tugasku adalah **deteksi dan analisis** — bukan eksekusi perubahan. -Jika ditemukan masalah yang memerlukan tindakan write (blokir IP, disable service, -tambah firewall rule), selesaikan analisis dan **handoff ke config_agent (Joko)**: - -1. Tulis ringkasan temuan + rekomendasi konkret (perintah RouterOS spesifik) -2. Handoff ke config_agent untuk eksekusi dengan approval operator - -Contoh rekomendasi yang diserahkan ke config_agent: -``` -IP 1.2.3.4 melakukan 127x login failure ke GATE-X. Blokir dengan: -/ip/firewall/address-list/add list=blacklist address=1.2.3.4 comment="Brute force" -``` - -## Output Audit - -Laporan audit harus mencakup: -- **Temuan Kritis**: risiko tinggi yang butuh tindakan segera -- **Brute Force Log**: IP penyerang + jumlah attempt + router target -- **Temuan Minor**: peningkatan yang direkomendasikan -- **Status Kepatuhan**: sesuai/tidak sesuai standar per area -- **Rekomendasi**: perintah spesifik untuk remediation (diserahkan ke config_agent) diff --git a/agents/definitions/supervisor.md b/agents/definitions/supervisor.md deleted file mode 100644 index 7f02fe4..0000000 --- a/agents/definitions/supervisor.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -name: supervisor -alias: bambang -description: > - Orchestrator utama. Analisis permintaan operator, pilih specialist agent - yang tepat, dan rumuskan task yang jelas (WHAT, bukan HOW). -model: qwen3.5:9b -num_ctx: 32768 -num_predict: 4096 -context_window: 10 -timeout: 120 -chat_prompt: > - Kamu adalah Bambang, supervisor operasional jaringan kampus universitas. - Balas sapaan atau pertanyaan umum dengan ramah dan singkat dalam Bahasa Indonesia. - Sebutkan bahwa kamu siap membantu kebutuhan operasional jaringan kampus. -tools: [] -skills: [] -handoff_to: - - monitor_agent - - diagnose_agent - - config_agent - - security_agent - - document_agent ---- -Kamu adalah Bambang, supervisor operasional jaringan kampus universitas. -Tugasmu menganalisis permintaan operator dan mendelegasikan ke specialist -agent yang paling tepat. - -## Prinsip Delegasi - -Delegasikan **APA** yang perlu dilakukan, bukan **BAGAIMANA** melakukannya. - -- BENAR: "Cek status semua router dan identifikasi yang tidak merespons" -- SALAH: "Panggil check_reachability lalu get_system_info untuk tiap router" - -## Aturan Routing - -### Permintaan laporan dengan file ("buat laporan", "buatkan laporan", "tulis laporan") - -Jika permintaan mengandung kata **"laporan"**, **"buat dokumen"**, **"tulis file"**, **"catat ke file"**: - -**A. Laporan routing BGP/OSPF** (kata kunci: "bgp", "ospf", "routing"): -1. Route ke **diagnose_agent** untuk analisis -2. Setelah diagnose_agent selesai dan kembali, WAJIB route ke **document_agent** -3. Baru kemudian END - -**B. Laporan health check / monitoring** (kata kunci: "health", "status semua router", "reachability"): -1. Route ke **monitor_agent** untuk kumpulkan data -2. Setelah monitor_agent selesai, WAJIB route ke **document_agent** -3. Baru kemudian END - -**C. Laporan keamanan** (kata kunci: "security", "audit", "brute force"): -1. Route ke **security_agent** -2. Setelah selesai, route ke **document_agent** -3. Baru kemudian END - -**PENTING**: Teks laporan di chat BUKAN file tersimpan. WAJIB route ke document_agent untuk menulis file. Jangan END sebelum document_agent memanggil write_document. - -### Permintaan tanpa laporan file - -- Diagnosa teknis tanpa kata "laporan" → diagnose_agent, lalu END -- Monitoring status → monitor_agent, lalu END -- **Konfigurasi / perubahan / write ops** → config_agent, lalu END - Contoh: "blokir IP", "tambah route", "disable service", "reboot router", - "tambah firewall rule", "ubah konfigurasi", "backup config" -- **Audit keamanan** (deteksi saja) → security_agent, lalu END -- **Audit + eksekusi remediation** (blokir IP, tambah rule setelah audit) → - security_agent → config_agent → END -- **Buat/tambah skill baru** (kata kunci: "buat skill", "tambah skill", "ajarkan agent", "tambah kemampuan", "buat prosedur baru") → - document_agent langsung, relevant_skills: ["skill-authoring"], lalu END - Contoh: "buat skill baru untuk diagnosa MTU", "ajarkan agent cara cek VLAN", "tambah prosedur backup harian" - -### Follow-up dan pertanyaan lanjutan - -Jika operator mengirim pertanyaan singkat yang merujuk ke hasil analisis sebelumnya -("kok tidak ada log?", "kenapa?", "coba cek lagi", "masih bermasalah?", "bagaimana dengan X?"): -→ Route ke specialist yang **sama** dengan percakapan sebelumnya -→ JANGAN route ke END untuk pertanyaan yang jelas butuh investigasi lanjut -→ Contoh: setelah diagnose_agent → "kok tidak ada log?" → diagnose_agent lagi diff --git a/agents/graph.py b/agents/graph.py deleted file mode 100644 index 11e912f..0000000 --- a/agents/graph.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Build and compile the NetOps LangGraph StateGraph.""" - -from __future__ import annotations - -from langgraph.graph import END, START, StateGraph - -from agents.nodes import ( - config_node, diagnose_node, document_node, monitor_node, - route_from_supervisor, security_node, supervisor_node, -) - - -def build_graph(checkpointer) -> object: - """Compile and return the full NetOps multi-agent graph.""" - from agent import NetworkOpsState # noqa: PLC0415 — avoid circular at module level - - builder = StateGraph(NetworkOpsState) - - builder.add_node("supervisor", supervisor_node) - builder.add_node("monitor_agent", monitor_node) - builder.add_node("diagnose_agent", diagnose_node) - builder.add_node("config_agent", config_node) - builder.add_node("security_agent", security_node) - builder.add_node("document_agent", document_node) - - builder.add_edge(START, "supervisor") - - builder.add_conditional_edges( - "supervisor", - route_from_supervisor, - { - "monitor_agent": "monitor_agent", - "diagnose_agent": "diagnose_agent", - "config_agent": "config_agent", - "security_agent": "security_agent", - "document_agent": "document_agent", - "END": END, - }, - ) - - # All specialists report back to supervisor - for agent in ("monitor_agent", "diagnose_agent", "config_agent", "security_agent", "document_agent"): - builder.add_edge(agent, "supervisor") - - return builder.compile(checkpointer=checkpointer) diff --git a/agents/loader.py b/agents/loader.py deleted file mode 100644 index d44bd10..0000000 --- a/agents/loader.py +++ /dev/null @@ -1,197 +0,0 @@ -"""AgentLoader: load dan validasi agent definitions dari file Markdown.""" - -from __future__ import annotations - -import logging -from dataclasses import dataclass, field -from pathlib import Path -from typing import Optional - -import yaml - -logger = logging.getLogger(__name__) - -DEFINITIONS_DIR = Path(__file__).parent / "definitions" - - -@dataclass -class AgentDefinition: - name: str - alias: str - description: str - model: str - tools: list[str] - skills: list[str] - handoff_to: list[str] - approval_required_tools: list[str] - body: str - path: Path - # LLM tuning params (per-agent, from frontmatter) - num_ctx: int = 8192 - num_predict: int = 2048 - context_window: int = 10 - timeout: int = 300 - # Optional chat fallback prompt (supervisor only) - chat_prompt: str = "" - # Optional per-agent Ollama host (overrides OLLAMA_BASE_URL env var) - ollama_host: str = "" - # Enable think/reasoning mode (qwen3.5 and compatible models only) - reasoning: bool = False - - -def _parse_definition_file(path: Path) -> Optional[AgentDefinition]: - """Parse a single agent definition Markdown file. Returns None on error.""" - try: - text = path.read_text(encoding="utf-8") - except OSError as e: - logger.warning("Cannot read agent definition %s: %s", path, e) - return None - - if not text.startswith("---"): - logger.warning("Agent definition %s missing frontmatter, skipping", path.name) - return None - - end = text.find("---", 3) - if end == -1: - logger.warning("Agent definition %s has unclosed frontmatter, skipping", path.name) - return None - - frontmatter_raw = text[3:end].strip() - body = text[end + 3:].strip() - - try: - fm = yaml.safe_load(frontmatter_raw) or {} - except yaml.YAMLError as e: - logger.warning("Agent definition %s YAML parse error: %s", path.name, e) - return None - - name = fm.get("name", path.stem) - if not isinstance(name, str) or not name: - name = path.stem - - return AgentDefinition( - name=name, - alias=str(fm.get("alias", name)), - description=str(fm.get("description", "")), - model=str(fm.get("model", "")), - tools=[str(t) for t in (fm.get("tools") or [])], - skills=[str(s) for s in (fm.get("skills") or [])], - handoff_to=[str(a) for a in (fm.get("handoff_to") or [])], - approval_required_tools=[str(t) for t in (fm.get("approval_required_tools") or [])], - body=body, - path=path, - num_ctx=int(fm.get("num_ctx", 8192)), - num_predict=int(fm.get("num_predict", 2048)), - context_window=int(fm.get("context_window", 10)), - timeout=int(fm.get("timeout", 300)), - chat_prompt=str(fm.get("chat_prompt", "")), - ollama_host=str(fm.get("ollama_host", "")), - reasoning=bool(fm.get("reasoning", False)), - ) - - -class AgentLoader: - """Registry of agent definitions loaded from Markdown files.""" - - def __init__(self, definitions_dir: Path = DEFINITIONS_DIR) -> None: - self._dir = definitions_dir - self._agents: dict[str, AgentDefinition] = {} - self._load_all() - - # ── Loading ──────────────────────────────────────────────────────────── - - def _load_all(self) -> None: - loaded: dict[str, AgentDefinition] = {} - for md_file in sorted(self._dir.glob("*.md")): - defn = _parse_definition_file(md_file) - if defn: - if defn.name in loaded: - logger.warning( - "Duplicate agent name '%s' in %s (already from %s) — skipping", - defn.name, md_file.name, loaded[defn.name].path.name, - ) - else: - loaded[defn.name] = defn - self._agents = loaded - logger.info("AgentLoader: loaded %d agent definitions from %s", len(loaded), self._dir) - - def reload(self) -> None: - """Re-read all definition files from disk.""" - self._load_all() - - # ── Validation ───────────────────────────────────────────────────────── - - def validate( - self, - tool_map: dict[str, object], - skill_library=None, - ) -> list[str]: - """ - Validate all loaded definitions. Returns list of warning strings. - - Checks: - - agent.tools entries exist in tool_map - - agent.skills entries exist in skill_library (if provided) - - skill.tools ⊆ agent.tools for each skill assigned to the agent - """ - warnings: list[str] = [] - - for defn in self._agents.values(): - agent_tool_set = set(defn.tools) - - # Check tool existence - for tool_name in defn.tools: - if tool_name not in tool_map: - warnings.append( - f"[{defn.name}] tool '{tool_name}' not found in TOOL_MAP" - ) - - if skill_library is None: - continue - - # Check skill existence and tool subset constraint - for skill_name in defn.skills: - skill = skill_library.get_by_name(skill_name) - if skill is None: - warnings.append( - f"[{defn.name}] skill '{skill_name}' not found in SkillLibrary" - ) - continue - - missing = set(skill.tools) - agent_tool_set - if missing: - warnings.append( - f"[{defn.name}] skill '{skill_name}' requires tools not in agent: " - + ", ".join(sorted(missing)) - ) - - return warnings - - # ── Query ────────────────────────────────────────────────────────────── - - def get(self, name: str) -> Optional[AgentDefinition]: - return self._agents.get(name) - - def all(self) -> list[AgentDefinition]: - return list(self._agents.values()) - - def tool_list(self, agent_name: str) -> list[str]: - """Return the tool name list for an agent, or [] if not found.""" - defn = self._agents.get(agent_name) - return defn.tools if defn else [] - - def skill_list(self, agent_name: str) -> list[str]: - """Return the skill name list for an agent, or [] if not found.""" - defn = self._agents.get(agent_name) - return defn.skills if defn else [] - - def system_prompt(self, agent_name: str) -> str: - """Return the body (system prompt) from the definition file.""" - defn = self._agents.get(agent_name) - return defn.body if defn else "" - - def __len__(self) -> int: - return len(self._agents) - - def __repr__(self) -> str: - return f"AgentLoader(agents={len(self)}, dir={self._dir})" diff --git a/agents/metrics.py b/agents/metrics.py deleted file mode 100644 index 8d5e704..0000000 --- a/agents/metrics.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Token utilization metrics — LangChain callback that records Ollama LLM stats.""" -from __future__ import annotations - -import json -import logging -from datetime import datetime -from pathlib import Path -from typing import Any - -from langchain_core.callbacks import BaseCallbackHandler -from langchain_core.outputs import LLMResult - -logger = logging.getLogger(__name__) - -METRICS_PATH = Path(__file__).parent.parent / "data" / "metrics.jsonl" - - -class TokenMetricsCallback(BaseCallbackHandler): - """Append one JSON line to data/metrics.jsonl after every LLM call.""" - - def __init__(self, agent_name: str, num_ctx: int, num_predict: int) -> None: - super().__init__() - self.agent_name = agent_name - self.num_ctx = num_ctx - self.num_predict = num_predict - - def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: - try: - for gen_list in response.generations: - for gen in gen_list: - info: dict = getattr(gen, "generation_info", None) or {} - prompt_tokens = info.get("prompt_eval_count", 0) - gen_tokens = info.get("eval_count", 0) - done_reason = info.get("done_reason", "unknown") - eval_ns = info.get("eval_duration", 0) - total_ns = info.get("total_duration", 0) - tps = round(gen_tokens / (eval_ns / 1e9), 1) if eval_ns > 0 else 0.0 - - entry = { - "ts": datetime.now().isoformat(timespec="seconds"), - "agent": self.agent_name, - "prompt_tokens": prompt_tokens, - "num_ctx": self.num_ctx, - "ctx_util": round(prompt_tokens / self.num_ctx * 100, 1) if self.num_ctx else 0, - "gen_tokens": gen_tokens, - "num_predict": self.num_predict, - "predict_util": round(gen_tokens / self.num_predict * 100, 1) if self.num_predict else 0, - "done_reason": done_reason, - "tps": tps, - "total_ms": round(total_ns / 1e6), - } - - METRICS_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(METRICS_PATH, "a", encoding="utf-8") as f: - f.write(json.dumps(entry) + "\n") - except Exception: - logger.debug("TokenMetricsCallback error", exc_info=True) diff --git a/agents/nodes.py b/agents/nodes.py deleted file mode 100644 index d282e86..0000000 --- a/agents/nodes.py +++ /dev/null @@ -1,652 +0,0 @@ -"""LangGraph node functions: supervisor + 5 specialist agents.""" - -from __future__ import annotations - -import json -import logging -import os -from datetime import datetime, timezone, timedelta -from typing import TYPE_CHECKING, Any - -from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage -from langchain_ollama import ChatOllama - -from agents.loader import AgentLoader -from agents.tools import TOOL_MAP - -if TYPE_CHECKING: - from agent import NetworkOpsState - -logger = logging.getLogger(__name__) - -OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434") -OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "gemma4:e4b") - -WIB = timezone(timedelta(hours=7)) - -# ── Agent loader (single source of truth for tools, skills, system prompts) ─── - -_agent_loader = AgentLoader() - -# Alias map derived from definitions (display only) -AGENT_ALIAS: dict[str, str] = {d.name: d.alias for d in _agent_loader.all()} - - -def _resolve_tools(agent_name: str) -> list: - """Return callable tool list for an agent from its definition.""" - names = _agent_loader.tool_list(agent_name) - tools = [TOOL_MAP[n] for n in names if n in TOOL_MAP] - missing = [n for n in names if n not in TOOL_MAP] - if missing: - logger.warning("Agent '%s' references unknown tools: %s", agent_name, missing) - return tools - -# ── LLM factory ─────────────────────────────────────────────────────────────── - -def _make_llm( - temperature: float = 0.3, - json_mode: bool = False, - model: str | None = None, - num_ctx: int = 8192, - num_predict: int = 2048, - timeout: int = 300, - agent_name: str | None = None, - base_url: str | None = None, - reasoning: bool = False, -) -> ChatOllama: - from agents.metrics import TokenMetricsCallback # noqa: PLC0415 - kwargs: dict[str, Any] = dict( - base_url=base_url or OLLAMA_BASE_URL, - model=model or OLLAMA_MODEL, - temperature=temperature, - num_predict=num_predict, - num_ctx=num_ctx, - timeout=timeout, - reasoning=reasoning, - callbacks=[TokenMetricsCallback(agent_name or "unknown", num_ctx, num_predict)], - ) - if json_mode: - kwargs["format"] = "json" - return ChatOllama(**kwargs) - - -# ── Helpers ─────────────────────────────────────────────────────────────────── - -def _now_str() -> str: - return datetime.now(WIB).strftime("%H:%M:%S") - - -def _clean(text: str) -> str: - return text.strip() - - -def _log(source: str, event_type: str, content: str) -> dict: - """Build a log entry, resolving source to its display alias if defined.""" - display = AGENT_ALIAS.get(source, source) - return {"timestamp": _now_str(), "source": display, - "event_type": event_type, "content": content} - - -def _last_specialist_from_log(state: dict, valid_agent_names: set[str]) -> str | None: - """Scan agent_log backwards to find the last specialist that ran.""" - agent_log = state.get("agent_log", []) - if not agent_log: - return None - alias_to_agent = {alias: name for name, alias in AGENT_ALIAS.items()} - for entry in reversed(agent_log): - source = entry.get("source", "") - agent_name = alias_to_agent.get(source, source) - if agent_name in valid_agent_names: - return agent_name - return None - - -def _react_loop( - llm_with_tools: Any, - messages: list, - tool_map: dict, - agent_name: str, - max_iters: int = 20, -) -> tuple[list, list]: - """ - Run a ReAct tool-calling loop. Returns (updated_messages, log_entries). - Stops when the LLM produces a response with no tool calls. - """ - logs: list[dict] = [] - for _ in range(max_iters): - response = llm_with_tools.invoke(messages) - messages = messages + [response] - - if not getattr(response, "tool_calls", None): - break - - for tc in response.tool_calls: - name = tc["name"] - args = tc.get("args", {}) - args_str = ", ".join(f"{k}={json.dumps(v)}" for k, v in args.items()) - logs.append(_log(agent_name, "tool_call", f"{name}({args_str})")) - - tool_fn = tool_map.get(name) - if tool_fn is None: - result = f"Error: tool '{name}' not found." - else: - try: - result = tool_fn.invoke(args) - except Exception as exc: - result = f"Error: {exc}" - - preview = str(result)[:120].replace("\n", " ") - if len(str(result)) > 120: - preview += "…" - logs.append(_log(agent_name, "tool_result", preview)) - messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"])) - - return messages, logs - - -# ── Supervisor helpers ──────────────────────────────────────────────────────── - -import re as _re - -_KEYWORD_ROUTES: list[tuple[list[str], str]] = [ - (["status", "monitor", "ping", "reachability", "traffic", "bandwidth", - "interface", "brief", "ringkasan", "uptime", "latency", "packet loss", - "cek jaringan", "cek router", "kondisi jaringan"], "monitor_agent"), - (["diagnos", "troubleshoot", "error", "down", "gangguan", "masalah", - "ospf", "bgp", "routing", "neighbor", "tidak bisa", "putus", "lambat", - "analisis"], "diagnose_agent"), - (["backup", "restore", "konfigurasi", "config", "setting", "ubah", - "ganti", "terapkan"], "config_agent"), - (["security", "keamanan", "firewall", "intrusion", "audit keamanan", - "serangan", "vulnerability", "port scan"], "security_agent"), - (["laporan", "report", "dokumen", "tulis laporan", "buat laporan", - "dokumentasi", "skill"], "document_agent"), -] - - -def _keyword_route(messages: list, valid_agents: set[str]) -> str | None: - """Keyword fallback routing dari pesan user terakhir. None jika tidak cocok.""" - last_human = next( - (m.content for m in reversed(messages) if isinstance(m, HumanMessage)), "" - ) - text = last_human.lower() - for keywords, agent in _KEYWORD_ROUTES: - if any(k in text for k in keywords) and agent in valid_agents: - return agent - return None - - -def _parse_supervisor_response(raw: str) -> dict | None: - """Extract JSON dari respons supervisor, toleran terhadap think-tags dan teks extra.""" - text = _re.sub(r".*?", "", raw, flags=_re.DOTALL).strip() - if not text: - return None - try: - return json.loads(text) - except json.JSONDecodeError: - pass - match = _re.search(r'\{[^{}]+\}', text, _re.DOTALL) - if match: - try: - return json.loads(match.group()) - except json.JSONDecodeError: - pass - return None - - -# ── Supervisor node ─────────────────────────────────────────────────────────── - -_SUPERVISOR_SYS = """\ -{supervisor_body} - -Agent tersedia: -{agent_descriptions} - -Skill tersedia (nama → trigger): -{skill_list} - -Balas HANYA dengan JSON valid, tanpa teks lain sebelum atau sesudah JSON. -Contoh format yang benar: -{{"next_agent":"monitor_agent","relevant_skills":[],"reasoning":"query status jaringan"}} - -Field next_agent harus salah satu: {valid_agents}, END -Gunakan END jika pertanyaan sudah dijawab AI sebelumnya dalam percakapan ini. -""" - - -def supervisor_node(state: "NetworkOpsState") -> dict: - from agent import _skill_lib # noqa: PLC0415 - - messages = state["messages"] - - last = messages[-1] if messages else None - if isinstance(last, AIMessage) and _clean(last.content or ""): - _early_save_kw = {"simpan", "tulis file", "buat laporan", "buatkan laporan", - "buat dokumen", "buatkan dokumen", "catat ke file", - "write report", "save", "write file", "laporan routing", - "laporan bgp", "laporan ospf", "laporan jaringan"} - _early_human = next((m for m in reversed(messages) if isinstance(m, HumanMessage)), None) - _early_wants_file = bool(_early_human and any( - kw in (_early_human.content or "").lower() for kw in _early_save_kw - )) - _early_prev = state.get("active_agent", "") - # Jika data-agent baru selesai dan user minta file → langsung route ke document_agent - if _early_wants_file and _early_prev in ("monitor_agent", "security_agent", "diagnose_agent"): - _doc_log = f"→ document_agent skills: ['document-writing'] | file-save: {_early_prev} selesai, route ke document_agent" - # Deteksi tipe laporan untuk memilih template yang tepat - _orig_req = (_early_human.content or "").lower() if _early_human else "" - if any(kw in _orig_req for kw in ("bgp", "ospf", "routing")): - _template_hint = "routing-bgp-ospf" - _router_hint = "" - # Cari nama router dari permintaan asli - import re as _re - _rm = _re.search(r'(gate-\S+|router\s+(\S+))', _orig_req, _re.IGNORECASE) - if _rm: - _router_hint = f" untuk router {_rm.group(0).strip()}" - _doc_content = ( - f"Analisis routing BGP/OSPF dari Agus sudah lengkap{_router_hint}. " - "Buat laporan file menggunakan template `routing-bgp-ospf`. " - "WAJIB panggil: get_current_time(), get_system_info(), get_bgp_sessions(), get_ospf_neighbors() " - "untuk mendapatkan data tabel yang akurat. " - "Gunakan analisis di atas (cross-reference, root cause, rekomendasi) untuk bagian teks analisis. " - "Simpan dengan write_document() — file HARUS tersimpan ke disk." - ) - else: - _doc_content = ( - "Data dari agent sebelumnya sudah lengkap. " - "Simpan sekarang ke file menggunakan tool `write_document`. " - "Mulai dengan `list_templates`, pilih template yang sesuai, lalu panggil `write_document`. " - "JANGAN hanya menulis teks — file HARUS tersimpan ke disk." - ) - _doc_instruction = HumanMessage(content=_doc_content) - return { - "next_agent": "document_agent", - "active_agent": "supervisor", - "injected_skills": ["document-writing"], - "messages": [_doc_instruction], - "agent_log": [_log("supervisor", "routing", _doc_log)], - } - return { - "next_agent": "END", - "active_agent": "supervisor", - "agent_log": [_log("supervisor", "routing", "→ END (respons sudah ada)")], - } - - specialist_defs = [d for d in _agent_loader.all() if d.name != "supervisor"] - agent_descriptions = "\n".join( - f"- {d.name:20s} [{d.alias}] : {d.description}" - for d in specialist_defs - ) - valid_agent_names = {d.name for d in specialist_defs} - valid_agents_str = ", ".join(sorted(valid_agent_names)) - - skill_list = "\n".join( - f" {s.name}: {', '.join(s.triggers[:3])}" - for s in _skill_lib.list_enabled() - ) or " (tidak ada skill aktif)" - - _supervisor_defn = _agent_loader.get("supervisor") - _supervisor_model = _supervisor_defn.model if _supervisor_defn else None - - sys_msg = SystemMessage(content=_SUPERVISOR_SYS.format( - supervisor_body=_agent_loader.system_prompt("supervisor"), - agent_descriptions=agent_descriptions, - skill_list=skill_list, - valid_agents=valid_agents_str, - )) - _sup_ctx_window = _supervisor_defn.context_window if _supervisor_defn else 6 - recent = [m for m in messages if isinstance(m, (HumanMessage, AIMessage))][-_sup_ctx_window:] - llm = _make_llm( - temperature=0.1, - json_mode=True, - model=_supervisor_model, - num_ctx=_supervisor_defn.num_ctx if _supervisor_defn else 4096, - num_predict=_supervisor_defn.num_predict if _supervisor_defn else 256, - timeout=_supervisor_defn.timeout if _supervisor_defn else 60, - agent_name="supervisor", - base_url=(_supervisor_defn.ollama_host if _supervisor_defn else "") or None, - reasoning=False, - ) - try: - resp = llm.invoke([sys_msg] + recent) - logger.debug("Supervisor raw content: %r | metadata: %s", - resp.content[:300] if resp.content else "(empty)", - getattr(resp, "response_metadata", {})) - data = _parse_supervisor_response(resp.content) or {} - if not data: - raise ValueError("empty or unparseable supervisor response") - except Exception as exc: - logger.warning("Supervisor routing parse error: %s", exc) - keyword_agent = _keyword_route(messages, valid_agent_names) - context_agent = ( - _last_specialist_from_log(state, valid_agent_names) - if not keyword_agent else None - ) - fallback = keyword_agent or context_agent or "END" - route_type = "context" if context_agent and not keyword_agent else "keyword" - data = {"next_agent": fallback, "relevant_skills": [], - "reasoning": f"{route_type}-fallback({fallback}): {exc}"} - - next_agent = data.get("next_agent", "END") - if next_agent not in valid_agent_names | {"END"}: - next_agent = _keyword_route(messages, valid_agent_names) or "END" - - _save_kw = {"simpan", "tulis file", "buat laporan", "buatkan laporan", - "buat dokumen", "buatkan dokumen", "catat ke file", - "write report", "save", "write file", "laporan routing", - "laporan bgp", "laporan ospf", "laporan jaringan"} - _last_human = next((m for m in reversed(messages) if isinstance(m, HumanMessage)), None) - _wants_file = bool(_last_human and any( - kw in (_last_human.content or "").lower() for kw in _save_kw - )) - _prev_agent = state.get("active_agent", "") - - # Override END → document_agent jika user minta simpan file dan data-agent baru selesai - if next_agent == "END" and "document_agent" in valid_agent_names: - if _wants_file and _prev_agent in ("monitor_agent", "security_agent", "diagnose_agent"): - next_agent = "document_agent" - data["reasoning"] = f"file-save override: {_prev_agent} returned data, routing to document_agent" - - # Override → END jika document_agent baru selesai (cegah loop) - # document_agent selalu terminal (handoff_to: []) — apapun yang ditulis, selalu END - if next_agent != "END" and _prev_agent == "document_agent": - next_agent = "END" - data["reasoning"] = "document_agent selesai, routing ke END" - - # Loop guard: jangan route ke specialist yang sama yang baru saja selesai. - # Cegah skenario: specialist → supervisor (empty JSON) → keyword-fallback → specialist sama → loop - if next_agent == _prev_agent and _prev_agent in valid_agent_names: - next_agent = "END" - data["reasoning"] = f"loop guard: {_prev_agent} baru selesai, cegah re-route ke agent sama" - - skills = data.get("relevant_skills", []) - log_msg = f"→ {next_agent} skills: {skills} | {data.get('reasoning','')}" - base_result = { - "next_agent": next_agent, - "active_agent": "supervisor", - "injected_skills": skills, - "agent_log": [_log("supervisor", "routing", log_msg)], - } - - # Supervisor menjawab langsung jika END tapi belum ada respons AI (sapaan, pertanyaan umum) - if next_agent == "END": - # Cari posisi HumanMessage terakhir — cek AI reply hanya setelah itu - last_human_idx = max( - (i for i, m in enumerate(recent) if isinstance(m, HumanMessage)), - default=-1, - ) - has_ai_reply = any( - isinstance(m, AIMessage) and _clean(m.content or "") - for m in recent[last_human_idx + 1:] - ) - if not has_ai_reply: - _chat_prompt = ( - _supervisor_defn.chat_prompt if _supervisor_defn and _supervisor_defn.chat_prompt - else ( - f"Kamu adalah {_supervisor_defn.alias.capitalize() if _supervisor_defn else 'Supervisor'}, " - "supervisor operasional jaringan kampus universitas. " - "Balas sapaan atau pertanyaan umum dengan ramah dan singkat dalam Bahasa Indonesia." - ) - ) - llm_chat = _make_llm( - temperature=0.5, - model=_supervisor_model, - num_ctx=_supervisor_defn.num_ctx if _supervisor_defn else 8192, - num_predict=_supervisor_defn.num_predict if _supervisor_defn else 2048, - timeout=_supervisor_defn.timeout if _supervisor_defn else 60, - agent_name="supervisor", - base_url=(_supervisor_defn.ollama_host if _supervisor_defn else "") or None, - reasoning=False, - ) - chat_sys = SystemMessage(content=_chat_prompt) - try: - reply = llm_chat.invoke([chat_sys] + recent) - base_result["messages"] = [reply] - except Exception: - pass - - return base_result - - -def route_from_supervisor(state: dict) -> str: - return state.get("next_agent", "END") - - -# ── Specialist node factory ─────────────────────────────────────────────────── - -_SPECIALIST_SYS = """\ -{agent_body} - -Tool yang tersedia (HANYA ini yang boleh dipanggil): {tool_names} - -ATURAN WAJIB — TOOL CALLING: -1. LANGSUNG panggil tool tanpa pengantar teks apapun. -2. DILARANG menulis "Mohon tunggu", "Saya akan menjalankan", "Saya akan memanggil", - "Saya akan mensimulasikan", atau deskripsi rencana sebelum memanggil tool. -3. DILARANG mensimulasikan atau mengarang data — gunakan tool untuk mendapatkan data nyata. -4. Teks respons hanya boleh ditulis SETELAH semua tool selesai dipanggil. -5. Jika butuh data dari beberapa router, panggil tool satu per satu secara langsung. -6. Setelah menerima hasil tool, jika masih ada tugas berikutnya, LANGSUNG panggil tool - berikutnya tanpa menulis teks konfirmasi, ringkasan, atau "Lanjut ke langkah X". - -{skill_context} -""" - - -def _make_specialist_node(agent_name: str): - defn = _agent_loader.get(agent_name) - tools = _resolve_tools(agent_name) - tool_map_local = {t.name: t for t in tools} - tool_names_str = ", ".join(t.name for t in tools) - agent_body = defn.body if defn else "" - context_window = defn.context_window if defn else 10 - _model = defn.model if defn else None - _num_ctx = defn.num_ctx if defn else 8192 - _num_predict = defn.num_predict if defn else 2048 - _timeout = defn.timeout if defn else 300 - _ollama_host = defn.ollama_host if defn else "" - _reasoning = defn.reasoning if defn else False - llm_with_tools = _make_llm( - temperature=0.3, - model=_model, - num_ctx=_num_ctx, - num_predict=_num_predict, - timeout=_timeout, - agent_name=agent_name, - base_url=_ollama_host or None, - reasoning=_reasoning, - ).bind_tools(tools) - - def _node(state: "NetworkOpsState") -> dict: - from agent import _skill_lib # noqa: PLC0415 - - skill_names = state.get("injected_skills") or [] - skill_objs = [s for n in skill_names if (s := _skill_lib.get_by_name(n))] - skill_ctx = _skill_lib.inject_context(skill_objs) if skill_objs else "" - - sys_content = _SPECIALIST_SYS.format( - agent_body=agent_body, - tool_names=tool_names_str, - skill_context=skill_ctx, - ).strip() - sys_msg = SystemMessage(content=sys_content) - - context_msgs = list(state["messages"])[-context_window:] - all_msgs, logs = _react_loop( - llm_with_tools, - [sys_msg] + context_msgs, - tool_map_local, - agent_name, - ) - - final_msg = all_msgs[-1] - need_summary = True - if isinstance(final_msg, AIMessage): - content = _clean(final_msg.content or "") - if content: - final_msg = AIMessage(content=content) - need_summary = False - - if need_summary: - # AIMessage kosong ATAU ToolMessage (max_iters tercapai) — force summary - try: - llm_plain = _make_llm( - temperature=0.3, model=_model, - num_ctx=_num_ctx, num_predict=_num_predict, timeout=_timeout, - agent_name=agent_name, - base_url=_ollama_host or None, - reasoning=False, - ) - summary = llm_plain.invoke(all_msgs) - summary_content = _clean(summary.content or "") - if summary_content: - final_msg = AIMessage(content=summary_content) - logs.append(_log(agent_name, "tool_result", "(forced summary generated)")) - except Exception as exc: - logger.warning("Forced summary failed for %s: %s", agent_name, exc) - - # Safety net: final_msg HARUS selalu AIMessage dengan content. - # Jika masih ToolMessage atau AIMessage kosong, ekstrak hasil tool terpanjang - # (biasanya paling informatif, hindari ambil tool terakhir yang arbitrary). - if not (isinstance(final_msg, AIMessage) and _clean(getattr(final_msg, "content", "") or "")): - tool_msgs = [m for m in all_msgs if isinstance(m, ToolMessage)] - if tool_msgs: - best = max(tool_msgs, key=lambda m: len(m.content or "")) - raw = best.content - else: - raw = "(tidak ada data)" - final_msg = AIMessage(content=f"Hasil:\n{raw}") - logs.append(_log(agent_name, "tool_result", "(safety net: paksa AIMessage dari tool result)")) - - logs.append(_log(agent_name, "routing", "← kembali ke supervisor")) - - return { - "messages": [final_msg], - "active_agent": agent_name, - "next_agent": "supervisor", - "agent_log": logs, - } - - _node.__name__ = agent_name - return _node - - -# ── Config node with human-in-the-loop approval ─────────────────────────────── - -_config_defn = _agent_loader.get("config_agent") -_CONFIG_TOOLS = _resolve_tools("config_agent") -_CONFIG_TOOLS_MAP = {t.name: t for t in _CONFIG_TOOLS} -_CONFIG_LLM = _make_llm( - temperature=0.3, - model=_config_defn.model if _config_defn else None, - num_ctx=_config_defn.num_ctx if _config_defn else 8192, - num_predict=_config_defn.num_predict if _config_defn else 2048, - timeout=_config_defn.timeout if _config_defn else 180, - agent_name="config_agent", - base_url=(_config_defn.ollama_host if _config_defn else "") or None, - reasoning=_config_defn.reasoning if _config_defn else False, -).bind_tools(_CONFIG_TOOLS) -_APPROVAL_REQUIRED_TOOLS = set( - _config_defn.approval_required_tools if _config_defn else ["backup_router_config"] -) - - -def config_node(state: dict) -> dict: - """Config specialist with interrupt() gate for destructive tools.""" - from agent import _skill_lib # noqa: PLC0415 - from langgraph.types import interrupt # noqa: PLC0415 - - skill_names = state.get("injected_skills") or [] - skill_objs = [s for n in skill_names if (s := _skill_lib.get_by_name(n))] - skill_ctx = _skill_lib.inject_context(skill_objs) if skill_objs else "" - - _config_tool_names = ", ".join(t.name for t in _CONFIG_TOOLS) - sys_msg = SystemMessage(content=_SPECIALIST_SYS.format( - agent_body=_agent_loader.system_prompt("config_agent"), - tool_names=_config_tool_names, - skill_context=skill_ctx, - ).strip()) - - messages = [sys_msg] + list(state["messages"])[-10:] - logs: list[dict] = [] - - for _ in range(12): - response = _CONFIG_LLM.invoke(messages) - messages = messages + [response] - - if not getattr(response, "tool_calls", None): - break - - for tc in response.tool_calls: - name = tc["name"] - args = tc.get("args", {}) - args_str = ", ".join(f"{k}={json.dumps(v)}" for k, v in args.items()) - logs.append(_log("config_agent", "tool_call", f"{name}({args_str})")) - - if name in _APPROVAL_REQUIRED_TOOLS: - router = args.get("router_name", "router") - if name == "backup_router_config": - action_desc = f"Backup config router '{router}'" - risk = "medium" - elif name == "run_command_write": - cmd = args.get("command", "") - action_desc = f"Write command di '{router}': {cmd}" - risk = "high" - else: - action_desc = f"Operasi write di '{router}' via {name}" - risk = "medium" - approval_req = { - "agent": "config_agent", - "action": action_desc, - "risk_level": risk, - "details": args, - } - logs.append(_log("config_agent", "approval_required", - f"Menunggu approval: {approval_req['action']}")) - decision = interrupt(approval_req) - - if decision != "approved": - result = f"Aksi dibatalkan oleh operator (keputusan: {decision})." - logs.append(_log("config_agent", "tool_result", result)) - messages.append(ToolMessage(content=result, tool_call_id=tc["id"])) - continue - - logs.append(_log("config_agent", "tool_result", f"Operator menyetujui — eksekusi {name}...")) - - tool_fn = _CONFIG_TOOLS_MAP.get(name) - if tool_fn is None: - result = f"Error: tool '{name}' tidak ditemukan." - else: - try: - result = tool_fn.invoke(args) - except Exception as exc: - result = f"Error: {exc}" - - preview = str(result)[:120].replace("\n", " ") - if len(str(result)) > 120: - preview += "…" - logs.append(_log("config_agent", "tool_result", preview)) - messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"])) - - final_msg = messages[-1] - if isinstance(final_msg, AIMessage): - content = _clean(final_msg.content or "") - if content: - final_msg = AIMessage(content=content) - - logs.append(_log("config_agent", "routing", "← kembali ke supervisor")) - return { - "messages": [final_msg], - "active_agent": "config_agent", - "next_agent": "supervisor", - "agent_log": logs, - } - - -# ── Exported node functions ─────────────────────────────────────────────────── - -monitor_node = _make_specialist_node("monitor_agent") -diagnose_node = _make_specialist_node("diagnose_agent") -security_node = _make_specialist_node("security_agent") -document_node = _make_specialist_node("document_agent") -# config_node defined above with interrupt() support diff --git a/agents/tools.py b/agents/tools.py deleted file mode 100644 index f1fc0b1..0000000 --- a/agents/tools.py +++ /dev/null @@ -1,41 +0,0 @@ -"""All tools imported and indexed in TOOL_MAP. Per-agent lists are derived from AgentLoader.""" - -from __future__ import annotations - -from tools.reachability import check_reachability, check_ssh_access -from tools.system import get_system_info -from tools.routing import get_routing_full, get_router_config, get_bgp_sessions, get_ospf_neighbors -from tools.interface import get_interface_stats -from tools.traffic import get_interface_traffic, get_traffic_summary, get_top_talkers, get_queue_stats, get_traffic_all, get_top_interfaces_all -from tools.dhcp import get_dhcp_leases, get_router_leases, search_device, audit_dhcp -from tools.log import get_router_log -from tools.config_read import run_command, run_command_all -from tools.config_write import run_command_write -from tools.config_backup import backup_router_config, list_backups, diff_config -from tools.security import audit_security -from tools.diagnostic import run_diagnostic -from tools.report import list_reports, get_report, get_report_section, get_report_toc -from tools.utility import list_routers, get_current_time -from tools.document import list_templates, read_template, write_document, create_template, write_skill -from tools.web import fetch_url - -_ALL_TOOLS = [ - list_routers, get_current_time, - check_reachability, check_ssh_access, - get_system_info, - get_routing_full, get_router_config, get_bgp_sessions, get_ospf_neighbors, - get_interface_stats, - get_interface_traffic, get_traffic_summary, get_top_talkers, get_queue_stats, get_traffic_all, get_top_interfaces_all, - get_dhcp_leases, get_router_leases, search_device, audit_dhcp, - get_router_log, - run_command, run_command_all, run_command_write, - backup_router_config, list_backups, diff_config, - audit_security, - run_diagnostic, - list_reports, get_report, get_report_section, get_report_toc, - list_templates, read_template, write_document, create_template, write_skill, - fetch_url, -] - -# Flat map: tool name → callable -TOOL_MAP: dict[str, object] = {t.name: t for t in _ALL_TOOLS} diff --git a/config.yaml.example b/config.yaml.example deleted file mode 100644 index 01a5c71..0000000 --- a/config.yaml.example +++ /dev/null @@ -1,57 +0,0 @@ -# Konfigurasi MikroTik DHCP Lease Agent — CONTOH -# --------------------------------------------------- -# Salin file ini ke config.yaml dan sesuaikan nilainya: -# cp config.yaml.example config.yaml -# -# PERINGATAN: Jangan commit config.yaml ke repository publik -# karena berisi password SSH! -# File ini (config.yaml.example) aman untuk di-commit. - -ssh: - username: netadmin # Username SSH router MikroTik - password: YOUR_SSH_PASSWORD # Ganti dengan password SSH yang sebenarnya - timeout: 15 # Timeout koneksi SSH dalam detik - port: 22 # Port SSH (default 22) - -routers: - # ── Contoh router RouterOS v7 ───────────────────────────── - - name: DTI - host: 10.39.0.1 - ros_version: 7 # RouterOS v7: gunakan sintaks /ip/dhcp-server/lease/print - dhcp_servers: - - dhcp-lab-tik # Nama DHCP server di router (bisa lebih dari satu) - - # ── Contoh router RouterOS v6 ───────────────────────────── - - name: FAKULTAS-A - host: 192.168.1.1 - ros_version: 6 # RouterOS v6: gunakan sintaks ip dhcp-server lease print - dhcp_servers: - - server-lab - - # ── Contoh router dengan beberapa DHCP server ───────────── - # Router yang memiliki lebih dari satu DHCP server didaftarkan - # sebagai entri terpisah dengan nama yang sama. - - name: FAKULTAS-B - host: 192.168.2.1 - ros_version: 6 - dhcp_servers: - - dhcp-vlan-100 - - - name: FAKULTAS-B - host: 192.168.2.1 - ros_version: 6 - dhcp_servers: - - dhcp-vlan-200 - - - name: FAKULTAS-B - host: 192.168.2.1 - ros_version: 6 - dhcp_servers: - - dhcp-vlan-300 - - # ── Tambahkan router lain di bawah ini ──────────────────── - # - name: NAMA_ROUTER - # host: IP_ROUTER - # ros_version: 6 # atau 7 - # dhcp_servers: - # - nama-dhcp-server diff --git a/tests/__init__.py b/data/.gitkeep similarity index 100% rename from tests/__init__.py rename to data/.gitkeep diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..0937e2f --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,12 @@ +# Development override: serve the frontend straight from the working tree so +# edits show up on reload (no image rebuild). nginx is told to revalidate JS/CSS +# on every request, so a plain reload picks changes up. +services: + frontend: + volumes: + - ./frontend/index.html:/usr/share/nginx/html/index.html:ro + - ./frontend/css:/usr/share/nginx/html/css:ro + - ./frontend/js:/usr/share/nginx/html/js:ro + - ./frontend/assets:/usr/share/nginx/html/assets:ro + - ./frontend/fonts:/usr/share/nginx/html/fonts:ro + - ./frontend/nginx.conf.template:/etc/nginx/templates/default.conf.template:ro diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a716bf2 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,52 @@ +# NetOpsUI — UI (nginx) + manager (skills / agent profiles / config views). +# +# Both containers use the host network so they can reach NetOps Agent and +# Hermes, which listen on 127.0.0.1 only; neither backend is exposed publicly. +# +# cp .env.example .env # then edit +# docker compose up -d --build +# +# Live-editing the frontend: docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d +services: + frontend: + build: ./frontend + image: netopsui-frontend + network_mode: host + environment: + UI_PORT: ${UI_PORT:-3000} + NETOPS_AGENT_URL: ${NETOPS_AGENT_URL:-http://127.0.0.1:8100} + HERMES_URL: ${HERMES_URL:-http://127.0.0.1:8642} + MANAGER_URL: http://127.0.0.1:${MANAGER_PORT:-8200} + depends_on: + manager: + condition: service_healthy + restart: unless-stopped + + # Mounts are the minimum the manager needs. Writable: skills/, NetOps Agent's + # SOUL.md, and both config.yaml (Settings > LLM Provider edits only the + # `model:` block, with a backup and a verification step). .env is read-only; + # sessions.db and the rest of each home directory are not mounted at all. + # NOTE: single-file mounts must exist on the host first, or Docker creates a + # directory in their place. ./data is committed (data/.gitkeep) for the same + # reason: if it were missing Docker would create it root-owned and the + # non-root manager could not write its database there. + manager: + build: ./server + image: netopsui-manager + network_mode: host + user: "${HOST_UID:-1000}:${HOST_GID:-1000}" + environment: + MANAGER_PORT: ${MANAGER_PORT:-8200} + HERMES_URL: ${HERMES_URL:-http://127.0.0.1:8642} # only to test the stored key + NETOPS_AGENT_URL: ${NETOPS_AGENT_URL:-http://127.0.0.1:8100} # the manager runs chats against it + volumes: + - ${DATA_DIR:-./data}:/data/netopsui + - ${NETOPS_AGENT_HOME:?set NETOPS_AGENT_HOME in .env}/skills:/data/netops/skills + - ${NETOPS_AGENT_HOME}/SOUL.md:/data/netops/SOUL.md + - ${NETOPS_AGENT_HOME}/config.yaml:/data/netops/config.yaml + - ${NETOPS_AGENT_HOME}/.env:/data/netops/.env:ro + - ${HERMES_HOME:?set HERMES_HOME in .env}/skills:/data/hermes/skills + - ${HERMES_HOME}/SOUL.md:/data/hermes/SOUL.md:ro + - ${HERMES_HOME}/config.yaml:/data/hermes/config.yaml + - ${HERMES_HOME}/.env:/data/hermes/.env:ro + restart: unless-stopped diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6144cc7..88ac950 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,7 +1,7 @@ # Architecture Document — NetOps AI -**Versi:** 2.1 -**Tanggal:** 2026-05-09 +**Versi:** 2.2 +**Tanggal:** 2026-05-16 **Status:** Selesai --- @@ -12,8 +12,9 @@ NetOps AI adalah platform operasional jaringan kampus berbasis multi-agent LangG ``` ┌─────────────────────────────────────────────────────────────┐ -│ TUI (tui.py) │ -│ Input ──► agent.py public API ◄── Agent Activity Panel │ +│ TUI (tui_textual.py — aktif) │ +│ TUI (tui.py — legacy ncurses) │ +│ Input ──► agent.py public API ◄── Approval Modal │ └─────────────────────────┬───────────────────────────────────┘ │ stream_agent_response() ┌─────────────────────────▼───────────────────────────────────┐ @@ -39,10 +40,11 @@ NetOps AI adalah platform operasional jaringan kampus berbasis multi-agent LangG ``` llmnetops/ ├── agent.py ← Public API + NetworkOpsState + SkillLibrary singleton -├── tui.py ← UI only (zero LLM logic) +├── tui_textual.py ← UI aktif (Textual framework) +├── tui.py ← UI legacy (ncurses, zero LLM logic) ├── generate_reports.py ← Standalone DHCP report generator │ -├── tools/ ← 34 atomic SSH operations +├── tools/ ← 61 atomic SSH operations │ ├── base.py ← SSH helper, config loader, _validate_router │ ├── reachability.py ← ICMP ping, SSH access check │ ├── system.py ← CPU, RAM, uptime @@ -52,40 +54,34 @@ llmnetops/ │ ├── dhcp.py ← DHCP lease queries, search device, audit_dhcp │ ├── log.py ← Router log pull │ ├── config_read.py ← Run command (read-only), run_command_all +│ ├── config_write.py ← run_command_write (butuh approval) │ ├── config_backup.py ← Export + save, diff, list backups +│ ├── config_yaml.py ← Update config.yaml via agent │ ├── security.py ← User audit, firewall, NTP check │ ├── diagnostic.py ← Ping/traceroute dari router +│ ├── netbox.py ← NetBox IPAM: drift check, sync │ ├── report.py ← List/read/section/toc laporan Markdown │ ├── document.py ← list/read/write template, write_document, write_skill │ └── utility.py ← list_routers, get_current_time │ -├── skills/ ← Operator-defined Markdown knowledge files +├── skills/ ← Operator-defined Markdown knowledge files (32 skill) │ ├── __init__.py ← from skills.library import Skill, SkillLibrary │ ├── library.py ← SkillLibrary class + Skill dataclass + hot reload -│ ├── dhcp/ -│ │ ├── dhcp-client-diagnostics.md ← diagnosa client gagal dapat IP -│ │ ├── dhcp-pool-audit.md ← audit utilisasi pool DHCP -│ │ └── utbk-session-monitoring.md ← monitoring peserta UTBK -│ ├── routing/ -│ │ ├── ospf-diagnostics.md ← diagnosa OSPF neighbor/state -│ │ └── bgp-diagnostics.md ← diagnosa BGP session/prefix -│ ├── monitoring/ -│ │ ├── network-health-check.md ← health check menyeluruh -│ │ ├── network-reachability.md ← investigasi router unreachable -│ │ ├── network-traffic-analysis.md ← analisis bandwidth & top talkers -│ │ └── network-status-report.md ← ringkasan status jaringan -│ ├── security/ -│ │ └── security-audit.md ← audit postur keamanan router -│ ├── config/ -│ │ └── config-backup.md ← prosedur backup konfigurasi -│ └── documents/ -│ └── document-writing.md ← penulisan laporan ke file +│ ├── pedoman-agent.md ← GLOBAL: conduct rules semua agent (dimuat otomatis) +│ ├── dhcp/ ← 3 skill +│ ├── routing/ ← 4 skill +│ ├── monitoring/ ← 6 skill (termasuk morning-check) +│ ├── security/ ← 3 skill +│ ├── config/ ← 6 skill (termasuk commissioning) +│ ├── interface/ ← 1 skill +│ ├── maintenance/ ← 1 skill +│ └── documents/ ← 5 file (skill + template) │ ├── agents/ ← Multi-agent LangGraph │ ├── __init__.py ← from agents.graph import build_graph │ ├── graph.py ← StateGraph builder (START→supervisor→specialists→END) -│ ├── nodes.py ← supervisor_node + 5 specialist nodes (loader-driven) -│ ├── tools.py ← TOOL_MAP (flat, semua 34 tools) +│ ├── nodes.py ← supervisor_node + 6 specialist nodes (loader-driven) +│ ├── tools.py ← TOOL_MAP (flat, semua 61 tools) │ ├── loader.py ← AgentLoader + AgentDefinition dataclass │ └── definitions/ ← Agent definition files (single source of truth) │ ├── supervisor.md @@ -93,7 +89,8 @@ llmnetops/ │ ├── diagnose_agent.md │ ├── config_agent.md │ ├── security_agent.md -│ └── document_agent.md +│ ├── document_agent.md +│ └── netbox_agent.md │ ├── docs/ ← Project documentation ├── backups/ ← Config backups (gitignored) @@ -128,17 +125,22 @@ START │ └─────────────────────────────────────────►┤ │ │ ├──► [config_agent] → tools: config_read, │ - │ config_backup (10 tools) │ - │ │ ← interrupt() jika backup │ + │ config_write, config_backup │ + │ │ ← interrupt() backup + write │ │ └─────────────────────────────────────────►┤ │ │ ├──► [security_agent] → tools: security, log, │ - │ config_read (6 tools) │ + │ config_read │ + │ │ │ + │ └─────────────────────────────────────────►┤ + │ │ + ├──► [netbox_agent] → tools: netbox, list_routers │ + │ check_reachability │ │ │ │ │ └─────────────────────────────────────────►┤ │ │ └──► [document_agent] → tools: document, report, │ - template (20 tools) │ + template │ │ │ └───────────────────────────────────────── ┘ │ @@ -155,7 +157,7 @@ Supervisor menggunakan LLM untuk menentukan: ```python # Supervisor routing decision (JSON-mode LLM output) { - "next_agent": "monitor_agent | diagnose_agent | config_agent | security_agent | END", + "next_agent": "monitor_agent | diagnose_agent | config_agent | security_agent | netbox_agent | document_agent | END", "relevant_skills": ["skill-name-1", "skill-name-2"], "reasoning": "<1 kalimat alasan>" } @@ -189,7 +191,8 @@ class NetworkOpsState(TypedDict): next_agent: str # supervisor routing decision active_agent: str # currently executing agent injected_skills: list[str] # skill names yang sedang aktif - agent_log: Annotated[list[AgentLogEntry], _append] # visible di TUI Agent Activity + agent_log: Annotated[list[AgentLogEntry], _append] # visible di TUI + reasoning: str # debug reasoning supervisor pending_approval: ApprovalRequest | None # blocked waiting for operator approval_decision: str | None # "approved" | "rejected" ``` @@ -249,22 +252,42 @@ enabled: true **Frontmatter YAML** → dibaca runtime untuk routing dan tool-loading. **Body Markdown** → di-inject sebagai system context ke specialist agent. -### 5.3 Daftar Skill (12 skill aktif) - -| Skill | Domain | Agent | Keterangan | -|-------|--------|-------|------------| -| `network-health-check` | monitoring | monitor | Health check menyeluruh semua router | -| `network-reachability` | monitoring | monitor | Investigasi router unreachable | -| `network-traffic-analysis` | monitoring | monitor | Analisis bandwidth & top talkers | -| `network-status-report` | monitoring | monitor | Ringkasan status jaringan | -| `dhcp-pool-audit` | dhcp | monitor | Audit utilisasi DHCP pool | -| `dhcp-client-diagnostics` | dhcp | diagnose | Diagnosa client gagal dapat IP | -| `utbk-session-monitoring` | dhcp | monitor | Monitoring peserta UTBK | -| `bgp-diagnostics` | routing | diagnose | Diagnosa BGP session/prefix | -| `ospf-diagnostics` | routing | diagnose | Diagnosa OSPF neighbor/state | -| `security-audit` | security | security | Audit postur keamanan router | -| `config-backup` | config | config | Prosedur backup konfigurasi | -| `document-writing` | documents | document | Penulisan laporan ke file | +### 5.3 Daftar Skill (32 skill aktif) + +| Domain | Skill | Agent | Keterangan | +|--------|-------|-------|------------| +| monitoring | `network-health-check` | monitor | Health check menyeluruh semua router | +| monitoring | `network-reachability` | monitor | Investigasi router unreachable | +| monitoring | `network-traffic-analysis` | monitor | Analisis bandwidth & top talkers | +| monitoring | `network-status-report` | monitor | Ringkasan status jaringan | +| monitoring | `morning-check` | monitor | Morning check harian — reachability + BGP + traffic | +| monitoring | `capacity-planning` | monitor | Analisis utilisasi dan proyeksi kapasitas | +| monitoring | `mtu-mismatch-diagnostics` | diagnose | Diagnosa MTU mismatch antar segmen | +| monitoring | `netbox-read` | monitor/netbox | Query NetBox via agent | +| dhcp | `dhcp-pool-audit` | monitor | Audit utilisasi DHCP pool | +| dhcp | `dhcp-client-diagnostics` | diagnose | Diagnosa client gagal dapat IP | +| dhcp | `utbk-session-monitoring` | monitor | Monitoring peserta UTBK | +| dhcp | `static-lease-management` | config | Kelola static lease DHCP | +| routing | `bgp-diagnostics` | diagnose | Diagnosa BGP session/prefix | +| routing | `ospf-diagnostics` | diagnose | Diagnosa OSPF neighbor/state | +| routing | `bgp-prefix-leak` | diagnose | Deteksi dan respons BGP prefix leak | +| routing | `static-route-management` | config | Kelola static route | +| security | `security-audit` | security | Audit postur keamanan router | +| security | `brute-force-response` | security | Deteksi dan blokir brute force | +| security | `firewall-management` | security/config | Kelola aturan firewall | +| config | `config-backup` | config | Prosedur backup konfigurasi | +| config | `config-change` | config | Workflow perubahan konfigurasi dengan approval | +| config | `commissioning` | config | Komisioning router baru dari fresh | +| config | `vlan-provisioning` | config | Provisioning VLAN baru | +| config | `router-discovery` | config | Deteksi dan registrasi router baru | +| config | `netbox-sync` | config/netbox | Sync konfigurasi ke NetBox | +| interface | `link-diagnostics` | diagnose | Diagnosa masalah interface/link | +| maintenance | `router-maintenance` | config | Prosedur maintenance router | +| documents | `document-writing` | document | Penulisan laporan ke file | +| documents | `skill-authoring` | document | Membuat skill baru | + +**File khusus (bukan skill biasa):** +- `skills/pedoman-agent.md` — Conduct rules global, dimuat otomatis ke semua agent system prompt. Tidak perlu dicantumkan di definisi agent manapun. Edit file ini untuk mengubah perilaku semua agent sekaligus. ### 5.4 SkillLibrary @@ -368,10 +391,11 @@ Model aktif: **qwen3.5:9b** (lihat Section 6.8 untuk alasan pemilihan model). | Agent | num_ctx | num_predict | context_window | timeout | Alasan | |-------|---------|-------------|----------------|---------|--------| | supervisor | 8192 | 2048 | 6 | 60s | Output JSON routing; qwen tokenizer 2.2× lebih verbose | -| monitor_agent | 16384 | 2048 | 10 | 300s | Tool results 17+ router menumpuk di context | +| monitor_agent | 32768 | 16384 | 20 | 600s | Tool results 17+ router + morning check multi-step | | diagnose_agent | 16384 | 2048 | 10 | 300s | Logs + routing table + analisis RCA | -| config_agent | 16384 | 2048 | 10 | 180s | Config export per router | +| config_agent | 16384 | 2048 | 10 | 180s | Config export per router + commissioning | | security_agent | 16384 | 2048 | 10 | 300s | Audit results + log parsing | +| netbox_agent | 16384 | 2048 | 10 | 300s | NetBox API results bisa verbose | | document_agent | 24576 | 4096 | 20 | 600s | Seluruh history percakapan + template | > **Catatan tokenizer:** qwen3.5:9b menghasilkan ~2.2× lebih banyak token dibanding gemma4:e4b @@ -736,12 +760,14 @@ config_agent memutuskan perlu backup | Level | Contoh Aksi | Default | |---|---|---| | `medium` | Config backup, export config | Require approval | -| `high` | (future) write operations | Require approval | +| `high` | Write operations (`run_command_write`) | Require approval | | `low` | Read-only queries | Auto-proceed | +**Auto-backup enforcement:** `config_node` menjamin backup selalu dilakukan sebelum `run_command_write` pertama ke setiap router, terlepas dari urutan tool yang dipilih LLM. Ini enforced di code level (`_backed_up_routers` set per invocation), bukan di instruksi LLM. + --- -## 8. Public API (agent.py → tui.py) +## 8. Public API (agent.py → tui.py / tui_textual.py) ```python # Inisialisasi @@ -757,53 +783,68 @@ def stream_agent_response( # Yields: (event_type, content) # event_type: "routing" | "tool_call" | "tool_result" | "ai" | "approval_required" | "error" -# Approval +# Approval — dua varian: def submit_approval( graph: CompiledStateGraph, config: RunnableConfig, decision: str # "approved" | "rejected" ) -> None +# Headless/non-streaming. Pakai ini untuk testing atau CLI satu-shot. + +def resume_after_approval( + graph: CompiledStateGraph, + config: RunnableConfig, + decision: str +) -> Iterator[tuple[str, str]] +# Streaming variant — WAJIB dipakai TUI agar interrupt berikutnya +# (multi-step write chain) tetap sampai ke UI. # Info def get_available_skills() -> list[dict] # untuk TUI display def get_agent_status() -> dict +def get_token_metrics(n: int = 100) -> list[dict] # ctx/pred usage per message ``` --- -## 9. TUI Interface Changes +## 9. TUI Interface -### 9.1 Perubahan AIScreen +### 9.1 tui_textual.py (aktif — Phase 8) -**Sebelum:** -- `AIScreen` berisi `_call_agent()`, `_call_ollama()`, LangGraph imports -- Import `agent` module langsung +Textual framework. Layout: single-panel chat mendominasi layar penuh. -**Sesudah:** -- `AIScreen` hanya memanggil `agent.stream_agent_response()` -- Handle event types yang di-yield -- Zero LLM logic di `tui.py` - -### 9.2 Screen Baru: AgentActivityScreen (Menu item 7) +``` +┌─ [eko — idle] ───────────────────────────────────────────────┐ +│ [14:32:01] → routing ke monitor_agent (skill: morning-check) │ +│ [14:32:01] ⚙ check_reachability(DTI) ✓ 1.2ms │ +│ [14:32:02] ⚙ get_system_info(DTI) ✓ CPU 12%, up 14d │ +│ ... │ +│ ┌ AI ──────────────────────────────────────────────────────┐ │ +│ │ ✅ 15 normal · ⚠️ 1 perhatian · 🚨 0 kritis │ │ +│ │ ... │ │ +│ └──────────────────────────────────────────────────────────┘ │ +├───────────────────────────────────────────────────────────────┤ +│ ctx ████░░ 19% · pred ████░░ 26% · 8 tools · 00:02:14 │ +└───────────────────────────────────────────────────────────────┘ +``` +**Approval modal** — Textual `ModalScreen`, muncul saat `approval_required`: ``` -┌─ Agent Activity ──────────────────────────────────────────┐ -│ [14:32:01] supervisor → routing ke monitor_agent │ -│ [14:32:01] monitor ⚙ tool_call: check_reachability │ -│ └─ DTI (10.39.0.1): ✓ 1.2ms │ -│ [14:32:02] monitor ⚙ tool_call: get_system_info │ -│ └─ CPU 12%, RAM 45%, up 14d │ -│ [14:32:03] monitor ← kembali ke supervisor │ -│ [14:32:04] supervisor ✓ synthesis selesai │ -├───────────────────────────────────────────────────────────┤ -│ ⚠ APPROVAL REQUIRED │ -│ Agent : config_agent │ -│ Aksi : Backup config FILKOM-CORE │ -│ Risk : MEDIUM │ -│ [Y] Approve [N] Reject │ -└───────────────────────────────────────────────────────────┘ +╔══════════════════════════════════════╗ +║ ⚠ KONFIRMASI TINDAKAN ║ +║ Agent : joko (config_agent) ║ +║ Aksi : Backup FILKOM-CORE ║ +║ Risk : MEDIUM ║ +║ [Setuju, jalankan] [Tolak] ║ +╚══════════════════════════════════════╝ ``` +**Keyboard shortcuts:** `ctrl+y` copy, `ctrl+b` copy raw, `ctrl+e` suspend + view log di `less` + +### 9.2 tui.py (legacy ncurses) + +Tetap berfungsi. Dipertahankan sampai `tui_textual.py` verified stable di produksi. + --- ## 10. Tools per Agent (Tool Access Matrix) @@ -845,9 +886,11 @@ def get_agent_status() -> dict | `write_skill` | | | | | ✓ | | `get_current_time` | ✓ | ✓ | ✓ | ✓ | ✓ | -⚠ `backup_router_config` memerlukan persetujuan operator (interrupt gate). +⚠ `backup_router_config` dan `run_command_write` memerlukan persetujuan operator (interrupt gate). + +**Total: 61 tool atomic** | Source of truth: `agents/definitions/*.md` + `AgentLoader.validate()` -**Total: 34 tool atomic** | Source of truth: `agents/definitions/*.md` + `AgentLoader.validate()` +> Tabel di atas merepresentasikan tool utama. Tool tambahan (netbox, config_write, config_yaml, dll) terdaftar di `agents/tools.py:TOOL_MAP`. Kolom `netbox_agent` belum ditampilkan — lihat `agents/definitions/netbox_agent.md`. --- diff --git a/docs/FRONTEND_IMPLEMENTATION.md b/docs/FRONTEND_IMPLEMENTATION.md new file mode 100644 index 0000000..4f9ef1b --- /dev/null +++ b/docs/FRONTEND_IMPLEMENTATION.md @@ -0,0 +1,894 @@ +# Frontend Implementation Plan — NetOps AI Web Interface + +**Versi:** 1.0 +**Tanggal:** 2026-06-29 +**Status:** Draft +**Branch:** `feature/web-server` +**Deployment:** Dockerized di `frontend/` + +--- + +## 1. Tujuan + +Membangun web interface untuk NetOps AI yang menggantikan TUI curses (`tui.py`) dengan pengalaman yang lebih accessible — mendukung multi-user, bisa diakses dari browser manapun di jaringan kampus, dan memudahkan konfigurasi/manajemen sistem. + +### 1.1 Kenapa Web Interface + +| Aspek | TUI (saat ini) | Web Interface | +|-------|---------------|---------------| +| Akses | Hanya dari terminal SSH ke server | Browser dari manapun | +| Multi-user | Satu sesi per terminal | Banyak operator simultan | +| Visualisasi | Teks monospace, terbatas curses | Chart, tabel interaktif, Markdown rendering | +| Konfigurasi | Edit file YAML manual | Form-based, validasi langsung | +| Mobile | Tidak bisa | Responsive | + +### 1.2 Scope + +Web interface mencakup **semua** kapabilitas TUI saat ini plus fitur manajemen yang sebelumnya dilakukan manual (edit config.yaml, manage skills, review pending skills, NetBox integration). + +--- + +## 2. Current State — What Already Exists + +### 2.1 Backend: `server.py` (Functional) + +A FastAPI web server already exists at project root. It wraps `agent.py` public API over HTTP with SSE streaming. + +**Existing endpoints:** + +| Method | Endpoint | Deskripsi | Status | +|--------|----------|-----------|--------| +| `POST` | `/chat` | Send message, SSE stream response | Working | +| `POST` | `/approve` | Approve/reject pending action, SSE stream | Working | +| `GET` | `/info` | Model name + Ollama host | Working | +| `GET` | `/metrics?n=100` | Token usage (last N entries) | Working | +| `POST` | `/session/new` | Create new thread, return thread_id | Working | +| `GET` | `/` | Serve `frontend/index.html` | Working | + +**SSE stream format** (current `server.py` output): +``` +data: {"type": "routing", "content": "[bambang] → monitor_agent"} + +data: {"type": "tool_call", "content": "[eko] get_interface_stats(router=\"DTI\")"} + +data: {"type": "tool_result", "content": "[eko] ether1 UP 1Gbps ↑234Mbps..."} + +data: {"type": "ai", "content": "Status jaringan kampus:\n..."} + +data: {"type": "approval_required", "content": "{\"agent\":\"joko\",\"action\":\"backup\",\"risk_level\":\"medium\"}"} + +: ping +``` + +**Key patterns already solved:** +- Async streaming wrapper (`_stream_events`) — runs sync `agent.stream_agent_response()` in threadpool, feeds events via `asyncio.Queue`, sends `:ping` heartbeats every 3s +- Session store — `_sessions` dict maps `thread_id → (graph, config)` +- CORS configured for `*` +- Static file serving for `frontend/fonts/` and `frontend/assets/` + +**Run:** +```bash +python server.py +# or: uvicorn server:app --reload +``` + +### 2.2 Frontend Assets (Committed) + +``` +frontend/ +├── index.html ← Existing HTML prototype (static, sample data) +├── assets/ +│ ├── glyph.svg ← App icon glyph +│ └── logo.svg ← App logo +└── fonts/ + ├── IBMPlexMono-Regular.woff2 + ├── IBMPlexMono-Medium.woff2 + ├── IBMPlexMono-SemiBold.woff2 + ├── IBMPlexSans-Regular.woff2 + ├── IBMPlexSans-Medium.woff2 + ├── IBMPlexSansCondensed-Medium.woff2 + └── IBMPlexSansCondensed-SemiBold.woff2 +``` + +### 2.3 Dependencies (Already in requirements.txt) + +``` +fastapi>=0.115 +uvicorn[standard]>=0.32 +``` + +--- + +## 3. System Inventory + +### 3.1 Agents (7 specialist + 1 supervisor) + +| Agent | Alias | Domain | Key Capabilities | +|-------|-------|--------|-----------------| +| `supervisor` | bambang | orchestration | Route queries, skill matching, intent tracking | +| `monitor_agent` | eko | monitoring | Health check, traffic, reachability, DHCP overview | +| `diagnose_agent` | agus | diagnostics | OSPF/BGP troubleshoot, error analysis, RCA | +| `config_agent` | joko | configuration | Backup, write commands (needs approval), config read | +| `security_agent` | satria | security | Firewall audit, user accounts, brute-force detection | +| `document_agent` | budi | documentation | Reports, templates, skill authoring | +| `netbox_agent` | yanto | IPAM/DCIM | NetBox queries, drift detection, VLAN provisioning, BGP sync | +| `validasi_agent` | wati | validation | Verify action items, confirm issues, assess impact | + +Agents can be **enabled/disabled** via `enabled: false` in their frontmatter. + +### 3.2 Tools (52+ atomic functions) + +#### SSH/Router Tools (original) + +| Domain | Tools | +|--------|-------| +| **Monitoring** | `list_routers`, `check_reachability`, `check_ssh_access`, `get_system_info`, `get_interface_stats`, `get_interface_traffic`, `get_traffic_summary`, `get_top_talkers`, `get_queue_stats`, `get_traffic_all`, `get_top_interfaces_all` | +| **DHCP** | `get_dhcp_leases`, `get_router_leases`, `audit_dhcp`, `search_device` | +| **Routing** | `get_routing_full`, `get_router_config`, `get_bgp_sessions`, `get_ospf_neighbors` | +| **Config** | `run_command`, `run_command_all`, `run_command_write` (approval) | +| **Backup** | `backup_router_config` (approval), `list_backups`, `diff_config` | +| **Security** | `audit_security` | +| **Diagnostic** | `run_diagnostic`, `get_router_log` | +| **Document** | `write_document`, `list_templates`, `read_template`, `create_template`, `write_skill` | +| **Utility** | `list_routers`, `get_current_time`, `fetch_url` | + +#### NetBox IPAM Tools (new on this branch) + +| Tool | Type | Deskripsi | +|------|------|-----------| +| `get_netbox_devices` | read | List devices dari NetBox | +| `get_netbox_device_interfaces` | read | Interfaces per device | +| `get_netbox_device_ips` | read | IP addresses per device | +| `get_netbox_drift_report` | read | Compare NetBox vs router (actual) | +| `add_netbox_ip_address` | write | Tambah IP di NetBox | +| `update_netbox_interface` | write | Update interface di NetBox | +| `populate_netbox_from_router` | write | Sync router data → NetBox | +| `get_netbox_vlan_groups` | read | VLAN groups | +| `get_next_available_vlan` | read | Next available VLAN ID | +| `get_netbox_vlan_group_detail` | read | VLAN group detail | +| `create_netbox_vlan_interface` | write | Provision VLAN + interface | +| `populate_netbox_bgp` | write | Sync BGP sessions → NetBox | +| `get_netbox_bgp_drift` | read | BGP drift detection | +| `resolve_router_host` | read | Resolve router name → host IP | + +#### Config YAML Tools (new on this branch) + +| Tool | Deskripsi | +|------|-----------| +| `patch_router_host` | Update host IP di config.yaml | +| `patch_router_field` | Update any field di config.yaml | +| `add_router_to_config` | Tambah router baru ke config.yaml | +| `remove_router_from_config` | Hapus router dari config.yaml | + +#### Agent Memory Tools (new on this branch) + +| Tool | Deskripsi | +|------|-----------| +| `remember_router_fact` | Save fact tentang router (persists cross-session) | +| `recall_router_facts` | Recall facts untuk satu router | +| `recall_all_router_facts` | Recall semua facts | +| `forget_router_facts` | Hapus facts | + +### 3.3 Skills (33+ active) + +| Domain | Count | Key Skills | +|--------|-------|------------| +| monitoring | 8 | `network-health-check`, `morning-check`, `mtu-mismatch-diagnostics`, `capacity-planning`, `action-validation`, `netbox-read` | +| config | 8 | `config-backup`, `config-change`, `commissioning`, `netbox-sync`, `netbox-bgp-sync`, `router-discovery`, `router-to-netbox-sync`, `vlan-provisioning` | +| routing | 4 | `bgp-diagnostics`, `ospf-diagnostics`, `bgp-prefix-leak`, `static-route-management` | +| security | 3 | `security-audit`, `brute-force-response`, `firewall-management` | +| dhcp | 4 | `dhcp-client-diagnostics`, `dhcp-pool-audit`, `static-lease-management`, `utbk-session-monitoring` | +| documents | 2 | `document-writing`, `skill-authoring` | +| interface | 1 | `link-diagnostics` | +| maintenance | 1 | `router-maintenance` | +| global | 1 | `pedoman-agent` (global agent guidelines) | + +### 3.4 NetworkOpsState + +```python +class NetworkOpsState(TypedDict): + messages: Annotated[list, add_messages] + next_agent: str + active_agent: str + injected_skills: list[str] + agent_log: Annotated[list[AgentLogEntry], _append] + pending_approval: ApprovalRequest | None + approval_decision: str | None + original_intent: str # ← new: tracks user's original query across agent hops +``` + +### 3.5 Test Scenarios (17) + +`tests/scenarios/*.yaml` — covers health-check, BGP/OSPF, DHCP, security, NetBox drift, NetBox BGP, NetBox VLAN provisioning, validation flows, greeting, config-direct, scope-idren. + +--- + +## 4. Architecture + +### 4.1 Deployment Overview + +``` +┌──────────────────────────────────────────────────────────┐ +│ Docker Compose │ +│ │ +│ ┌──────────────┐ ┌────────────────────────┐ │ +│ │ frontend │ HTTP │ backend │ │ +│ │ (Nginx + │───────►│ (server.py + uvicorn) │ │ +│ │ static SPA)│ :3000 │ :8000 │ │ +│ └──────────────┘ │ │ │ +│ │ agent.py (public API) │ │ +│ │ tools/*.py (SSH) │ │ +│ │ skills/ (hot reload) │ │ +│ │ agents/ (LangGraph) │ │ +│ └──┬─────────────┬───────┘ │ +│ │ SSH │ HTTP │ +└─────────────────────────────┼─────────────┼─────────────┘ + │ │ + ┌────────▼──────┐ ┌───▼───────┐ + │ MikroTik │ │ NetBox │ + │ Routers │ │ IPAM │ + │ (campus LAN) │ │ (HTTP) │ + └───────────────┘ └───────────┘ +``` + +### 4.2 Directory Structure (Target) + +``` +frontend/ +├── Dockerfile ← Multi-stage: build SPA → serve via Nginx +├── docker-compose.yml ← frontend + backend services +├── nginx.conf ← Reverse proxy: /api/* → backend:8000 +│ +├── assets/ ← (existing) glyph.svg, logo.svg +├── fonts/ ← (existing) IBMPlex woff2 files +│ +├── src/ ← SPA source (new) +│ ├── index.html +│ ├── main.js ← Entry point, router, app init +│ ├── api.js ← HTTP + SSE client +│ ├── store.js ← Reactive state management +│ │ +│ ├── components/ ← Reusable UI components +│ │ ├── Sidebar.js +│ │ ├── Header.js +│ │ ├── Footer.js +│ │ ├── AgentCard.js +│ │ ├── ApprovalModal.js +│ │ └── ... +│ │ +│ ├── screens/ ← One file per screen/page +│ │ ├── Dashboard.js +│ │ ├── Chat.js +│ │ ├── NetworkMonitor.js +│ │ ├── DhcpMonitor.js +│ │ ├── NetBox.js +│ │ ├── Skills.js +│ │ ├── Reports.js +│ │ ├── Backups.js +│ │ ├── Metrics.js +│ │ └── Settings.js +│ │ +│ └── styles/ +│ └── theme.css ← Design tokens (CSS custom properties) +│ +└── backend/ ← (not needed — server.py is at project root) +``` + +### 4.3 Backend Strategy + +`server.py` already handles the core chat/approve/metrics/session flow. It needs **extension** (not replacement) with additional API routes for dashboard data, skills management, config CRUD, and NetBox integration. + +Two approaches: + +**Option A (recommended): Extend `server.py` in-place** +- Add route modules as functions in `server.py` or import from a `routes/` package +- Keeps deployment simple: one FastAPI app, one process +- `server.py` already has the session store and agent imports + +**Option B: Separate backend service** +- New `frontend/backend/main.py` imports from project root +- More Docker complexity, but cleaner separation +- Only needed if backend needs different Python environment + +--- + +## 5. Backend API Design — New Endpoints + +Endpoints below extend the existing `server.py`. The chat/approve/metrics/session endpoints are already implemented. + +### 5.1 Status & System Info + +| Method | Endpoint | Deskripsi | Maps to | +|--------|----------|-----------|---------| +| `GET` | `/api/status` | Full agent status | `agent.get_agent_status()` | +| `GET` | `/api/skills` | List all skills (enabled + disabled) | `agent.get_available_skills()` + all | +| `GET` | `/api/agents` | List agent definitions | `_agent_loader.all()` | + +```python +@app.get("/api/status") +def status(): + st = _agent.get_agent_status() + st["agents"] = [ + {"name": d.name, "alias": d.alias, "description": d.description, + "model": d.model, "enabled": d.enabled, "tools_count": len(d.tools)} + for d in _agent_loader.all() + ] + st["skills_count"] = len(_agent._skill_lib) + return st +``` + +### 5.2 Direct Tool Invocation (Dashboard) + +Tools dipanggil langsung tanpa melalui agent — untuk dashboard real-time. + +| Method | Endpoint | Deskripsi | Maps to | +|--------|----------|-----------|---------| +| `GET` | `/api/tools/routers` | Daftar router | `list_routers.invoke({})` | +| `POST` | `/api/tools/reachability` | Ping satu router | `check_reachability.invoke()` | +| `POST` | `/api/tools/reachability/all` | Ping semua router paralel | loop `check_reachability` | +| `POST` | `/api/tools/system-info` | CPU/RAM/uptime | `get_system_info.invoke()` | +| `POST` | `/api/tools/traffic` | Traffic satu interface | `get_interface_traffic.invoke()` | +| `POST` | `/api/tools/traffic/all` | Traffic semua router | `get_traffic_all.invoke({})` | +| `POST` | `/api/tools/dhcp/audit` | Audit DHCP semua router | `audit_dhcp.invoke({})` | +| `POST` | `/api/tools/dhcp/search` | Cari device by IP/MAC | `search_device.invoke()` | +| `POST` | `/api/tools/security/audit` | Audit security satu router | `audit_security.invoke()` | +| `POST` | `/api/tools/diagnostic` | Ping/traceroute dari router | `run_diagnostic.invoke()` | +| `GET` | `/api/tools/router-log` | Log router | `get_router_log.invoke()` | + +```python +from agents.tools import TOOL_MAP + +@app.get("/api/tools/routers") +def get_routers(): + return {"result": TOOL_MAP["list_routers"].invoke({})} + +@app.post("/api/tools/reachability") +def check_reach(body: RouterBody): + return {"result": TOOL_MAP["check_reachability"].invoke({"router_name": body.router_name})} +``` + +### 5.3 NetBox Integration + +| Method | Endpoint | Deskripsi | Maps to | +|--------|----------|-----------|---------| +| `GET` | `/api/netbox/devices` | List NetBox devices | `get_netbox_devices.invoke()` | +| `GET` | `/api/netbox/devices/{name}/interfaces` | Interfaces | `get_netbox_device_interfaces.invoke()` | +| `GET` | `/api/netbox/devices/{name}/ips` | IPs | `get_netbox_device_ips.invoke()` | +| `GET` | `/api/netbox/drift/{name}` | Drift report | `get_netbox_drift_report.invoke()` | +| `GET` | `/api/netbox/vlans` | VLAN groups | `get_netbox_vlan_groups.invoke()` | +| `GET` | `/api/netbox/bgp/drift` | BGP drift | `get_netbox_bgp_drift.invoke()` | + +### 5.4 Skills Management + +| Method | Endpoint | Deskripsi | +|--------|----------|-----------| +| `GET` | `/api/skills` | List semua skills (enabled + disabled) | +| `GET` | `/api/skills/{name}` | Detail skill + body Markdown | +| `PUT` | `/api/skills/{name}` | Update skill (frontmatter + body) | +| `POST` | `/api/skills` | Buat skill baru | +| `DELETE` | `/api/skills/{name}` | Delete skill | +| `GET` | `/api/skills/pending` | List pending skills (`skills/.pending/`) | +| `POST` | `/api/skills/pending/{name}/approve` | Approve pending | +| `POST` | `/api/skills/pending/{name}/reject` | Reject pending | + +### 5.5 Configuration Management + +| Method | Endpoint | Deskripsi | +|--------|----------|-----------| +| `GET` | `/api/config/routers` | Router list dari config.yaml | +| `POST` | `/api/config/routers` | Add router | +| `PUT` | `/api/config/routers/{name}` | Update router | +| `DELETE` | `/api/config/routers/{name}` | Remove router | +| `GET` | `/api/config/agents` | Agent definitions list | +| `GET` | `/api/config/agents/{name}` | Agent definition detail | +| `PUT` | `/api/config/agents/{name}` | Update agent definition | +| `POST` | `/api/config/agents/{name}/toggle` | Enable/disable agent | +| `GET` | `/api/config/env` | Non-sensitive env settings | +| `PUT` | `/api/config/env` | Update OLLAMA_BASE_URL, OLLAMA_MODEL | + +Note: Router config CRUD can reuse the existing `config_yaml.py` tools internally: +```python +@app.post("/api/config/routers") +def add_router(body: RouterConfigBody): + from tools.config_yaml import add_router_to_config + result = add_router_to_config.invoke({ + "name": body.name, "host": body.host, + "ros_version": body.ros_version, + }) + return {"result": result} +``` + +### 5.6 Reports & Backups + +| Method | Endpoint | Maps to | +|--------|----------|---------| +| `GET` | `/api/reports` | `list_reports.invoke({})` | +| `GET` | `/api/reports/{filename}` | `get_report.invoke()` | +| `GET` | `/api/reports/{filename}/toc` | `get_report_toc.invoke()` | +| `GET` | `/api/backups` | `list_backups.invoke({})` | +| `GET` | `/api/backups/diff` | `diff_config.invoke()` | +| `GET` | `/api/templates` | `list_templates.invoke({})` | + +### 5.7 Agent Memory + +| Method | Endpoint | Maps to | +|--------|----------|---------| +| `GET` | `/api/memory` | `recall_all_router_facts.invoke({})` | +| `GET` | `/api/memory/{router}` | `recall_router_facts.invoke()` | +| `DELETE` | `/api/memory/{router}` | `forget_router_facts.invoke()` | + +--- + +## 6. Frontend Screens + +### 6.1 Screen Map + +| # | Screen | Path | Deskripsi | +|---|--------|------|-----------| +| 1 | Dashboard | `/` | System overview: agent status, router grid, recent reports | +| 2 | AI Chat | `/chat` | Multi-agent chat with SSE streaming + approval modal | +| 3 | Network Monitor | `/network` | Router status, traffic, reachability, top talkers | +| 4 | DHCP Monitor | `/dhcp` | Pool utilization, device search, lease browser | +| 5 | NetBox | `/netbox` | Device inventory, drift detection, VLAN management | +| 6 | Skills | `/skills` | Browse, edit, create, review pending | +| 7 | Reports | `/reports` | Markdown viewer + TOC | +| 8 | Backups | `/backups` | List per router + diff viewer | +| 9 | Metrics | `/metrics` | Token usage per agent | +| 10 | Settings | `/settings` | Routers, agents, environment config | + +### 6.2 Screen Details + +#### 6.2.1 Dashboard (`/`) + +``` +┌─────────────────────────────────────────────────────────────┐ +│ NETOPS AI Campus Network Operations ● IDLE │ +├────────┬────────────────────────────────────────────────────┤ +│ Menu │ │ +│ │ ┌─ System ──────────┐ ┌─ Router Status ────────┐│ +│ ● Dash │ │ Model: qwen3.5:9b│ │ DTI 10.10.1.1 ✓ ││ +│ Chat │ │ Skills: 33 loaded │ │ FIKES 10.10.2.1 ✗ ││ +│ Net │ │ Agents: 7 (6 on) │ │ LIBRARY 10.10.3.1 ✓ ││ +│ DHCP │ │ Ollama: ✓ online │ │ REKTORAT 10.10.4.1 ✓ ││ +│ NBox │ │ NetBox: ✓ online │ └────────────────────────┘│ +│ Skill│ └───────────────────┘ │ +│ Reprt│ ┌─ Agent Registry ──────────────────────────────┐│ +│ Back │ │ bambang(super) eko(mon) agus(diag) joko(cfg) ││ +│ Metr │ │ satria(sec) budi(doc) yanto(nbox) wati(val) ││ +│ Sett │ └───────────────────────────────────────────────┘│ +└────────┴────────────────────────────────────────────────────┘ +``` + +#### 6.2.2 AI Chat (`/chat`) + +``` +┌────────────────────────────────────────────┬──────────────┐ +│ AI Chat Thread: [session-abc ▾] │ Agent Status │ +│ │ │ +│ ┌─ ANDA ─────────────── 14:32:00 ───┐ │ ● BAMBANG │ +│ │ cek status jaringan kampus │ │ supervisor │ +│ └────────────────────────────────────┘ │ ✓ SELESAI │ +│ │ │ +│ ┌─ AGENT ────────────── 14:32:01 ───┐ │ ● EKO │ +│ │ → [bambang] routing → eko │ │ monitor │ +│ │ ⚙ [eko] get_interface_stats(DTI) │ │ ▶ RUNNING │ +│ │ ✓ [eko] 12 interfaces retrieved │ │ │ +│ │ │ │ ○ AGUS │ +│ │ Status jaringan kampus: │ │ ○ JOKO │ +│ │ (rendered Markdown) │ │ ○ SATRIA │ +│ └────────────────────────────────────┘ │ ○ BUDI │ +│ │ ○ YANTO │ +│ ┌────────────────────────────────────┐ │ ○ WATI │ +│ │ › ketik pertanyaan... [SEND] │ └──────────────┘ +│ └────────────────────────────────────┘ +``` + +SSE client consumes existing `POST /chat` format: +```javascript +async function sendMessage(threadId, message, onEvent) { + const res = await fetch('/chat', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({thread_id: threadId, message}), + }); + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + while (true) { + const {done, value} = await reader.read(); + if (done) break; + buffer += decoder.decode(value, {stream: true}); + const lines = buffer.split('\n\n'); + buffer = lines.pop(); + for (const block of lines) { + if (block.startsWith('data: ')) { + const payload = JSON.parse(block.slice(6)); + onEvent(payload.type, payload.content); + } + } + } +} +``` + +#### 6.2.3 Network Monitor (`/network`) + +Router grid + traffic + interface stats + top talkers. Data from direct tool invocation API. + +#### 6.2.4 DHCP Monitor (`/dhcp`) + +Pool utilization bars, device search form, lease table per router/server. + +#### 6.2.5 NetBox (`/netbox`) — New + +``` +┌─────────────────────────────────────────────────────────────┐ +│ NetBox Integration [⟳ Refresh] │ +│ │ +│ ┌─ Devices ──────────────────────────────────────────────┐│ +│ │ Name Site Role Status Interfaces IP ││ +│ │ DTI Kampus Router Active 24 12 ││ +│ │ FIKES Kampus Router Active 16 8 ││ +│ └────────────────────────────────────────────────────────┘│ +│ │ +│ ┌─ Drift Detection ─────────────────────────────────────┐│ +│ │ DTI: 3 drifts detected ││ +│ │ ether1: NetBox says 10.39.1.1/24, router has none ││ +│ │ ether5: missing from NetBox ││ +│ │ [Sync to NetBox] ││ +│ ├────────────────────────────────────────────────────────┤│ +│ │ BGP Drift: 1 session mismatch ││ +│ │ AS65001: NetBox says active, router shows idle ││ +│ └────────────────────────────────────────────────────────┘│ +│ │ +│ ┌─ VLAN Groups ──────────────────────────────────────────┐│ +│ │ Kampus-VLANs: 45 VLANs, next available: 146 ││ +│ └────────────────────────────────────────────────────────┘│ +└─────────────────────────────────────────────────────────────┘ +``` + +#### 6.2.6 Skills (`/skills`) + +Browse all 33+ skills, filter by domain, edit with Markdown editor, review pending skills from `skills/.pending/`. + +#### 6.2.7 Settings (`/settings`) + +Tabs: **Routers** | **Agents** | **Environment** | **NetBox** | **Memory** + +- **Routers:** CRUD via `config_yaml.py` tools (already exist) +- **Agents:** View/edit definitions, toggle enable/disable +- **Environment:** OLLAMA_BASE_URL, OLLAMA_MODEL +- **NetBox:** Connection settings (URL, token per instance) +- **Memory:** View/clear agent memory facts per router + +--- + +## 7. Design System + +### 7.1 Typography (fonts already committed) + +| Usage | Font | File | +|-------|------|------| +| Body text, code | IBM Plex Mono | `fonts/IBMPlexMono-*.woff2` | +| UI labels, navigation | IBM Plex Sans | `fonts/IBMPlexSans-*.woff2` | +| Headers, badges | IBM Plex Sans Condensed | `fonts/IBMPlexSansCondensed-*.woff2` | + +### 7.2 Color Tokens + +```css +:root { + /* Backgrounds */ + --bg-primary: #0a0f1a; + --bg-secondary: #111827; + --bg-elevated: #1a2332; + --bg-hover: #1f2d3d; + + /* Status */ + --color-success: #10b981; /* UP, healthy, done */ + --color-warning: #f59e0b; /* waiting, approval, degraded */ + --color-danger: #ef4444; /* DOWN, failed, error */ + --color-info: #3b82f6; /* routing, queued */ + + /* Text */ + --text-primary: #e2e8f0; + --text-secondary:#94a3b8; + --text-muted: #475569; + + /* Accent */ + --accent: #06b6d4; /* cyan — links, active states */ + --accent-dim: rgba(6, 182, 212, 0.15); + + /* Borders */ + --border: rgba(148, 163, 184, 0.1); + --border-active: rgba(6, 182, 212, 0.4); + + /* Fonts */ + --font-mono: 'IBM Plex Mono', monospace; + --font-sans: 'IBM Plex Sans', system-ui, sans-serif; + --font-condensed: 'IBM Plex Sans Condensed', sans-serif; +} +``` + +### 7.3 Agent States (8 agents) + +| State | Color | Indicator | +|-------|-------|-----------| +| `standby` | muted | dim dot | +| `queued` | info/blue | solid dot | +| `running` | success/green | pulsing dot | +| `waiting` | warning/amber | blinking dot | +| `done` | secondary | static dimmed | +| `failed` | danger/red | static dot | +| `nonaktif` | muted | strikethrough (agent disabled) | + +### 7.4 Layout + +``` +┌─ Header ─────────────────────────────────────── 48px ─┐ +│ Logo │ Title │ Status pill │ Clock │ +├─ Body ─────────────────────────────────── flex: 1 ────┤ +│ Sidebar│ Main Content │ Right Panel │ +│ 200px │ │ (chat only) │ +│ │ │ 220px │ +│ Nav │ │ 8 agent cards│ +├─ Footer ─────────────────────────────────────── 32px ─┤ +│ CTX% │ PRED% │ TOOLS │ TIME │ State │ +└───────────────────────────────────────────────────────┘ +``` + +--- + +## 8. Docker Configuration + +### 8.1 docker-compose.yml + +```yaml +services: + backend: + build: + context: .. + dockerfile: frontend/Dockerfile.backend + ports: + - "8000:8000" + volumes: + - ../config.yaml:/app/config.yaml + - ../.env:/app/.env:ro + - ../backups:/app/backups + - ../laporan:/app/laporan + - ../data:/app/data + - ../skills:/app/skills + - ../agents/definitions:/app/agents/definitions + environment: + - PYTHONUNBUFFERED=1 + networks: + - netops + restart: unless-stopped + + frontend: + build: + context: . + dockerfile: Dockerfile + ports: + - "3000:80" + depends_on: + - backend + networks: + - netops + restart: unless-stopped + +networks: + netops: + driver: bridge +``` + +### 8.2 Backend Dockerfile (`Dockerfile.backend`) + +```dockerfile +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +EXPOSE 8000 +CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"] +``` + +### 8.3 Frontend Dockerfile + +```dockerfile +FROM nginx:alpine + +COPY src/ /usr/share/nginx/html/ +COPY assets/ /usr/share/nginx/html/assets/ +COPY fonts/ /usr/share/nginx/html/fonts/ +COPY nginx.conf /etc/nginx/conf.d/default.conf + +EXPOSE 80 +``` + +### 8.4 Nginx Config + +```nginx +server { + listen 80; + server_name _; + + location / { + root /usr/share/nginx/html; + index index.html; + try_files $uri $uri/ /index.html; + } + + # Proxy existing endpoints (server.py) + location ~ ^/(chat|approve|info|metrics|session) { + proxy_pass http://backend:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 600s; + } + + # Proxy new API endpoints + location /api/ { + proxy_pass http://backend:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 600s; + } + + # WebSocket + location /ws/ { + proxy_pass http://backend:8000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + } +} +``` + +### 8.5 Ollama Connectivity from Docker + +```yaml +backend: + extra_hosts: + - "host.docker.internal:host-gateway" # Ollama on host + environment: + - OLLAMA_BASE_URL=http://host.docker.internal:11434 + # Or remote: OLLAMA_BASE_URL=http://rogbox.local.id:11434 +``` + +--- + +## 9. Key Implementation Notes + +### 9.1 SSE Streaming is Already Solved + +`server.py` has a production-ready async SSE wrapper (`_stream_events`) that: +- Runs the sync `agent.stream_agent_response()` in a threadpool +- Feeds events via `asyncio.Queue` with `call_soon_threadsafe` +- Sends `:ping` heartbeat every 3s to keep connections alive +- Handles `approval_required` events correctly + +Frontend just needs to parse `data: {"type": "...", "content": "..."}` lines. + +### 9.2 Thread Safety + +- `SkillLibrary` — thread-safe (`threading.Lock`) +- `SqliteSaver` — `check_same_thread=False` +- `memory.db` — separate SQLite, `check_same_thread=False` +- `config.yaml` writes (via `config_yaml.py`) — need mutex in backend for concurrent requests +- SSH tools — stateless, safe for parallel calls + +### 9.3 Parsing Tool Output + +Tools return plain text strings. For dashboard structured data, parse in backend: +```python +@app.post("/api/tools/system-info") +def system_info(body: RouterBody): + raw = TOOL_MAP["get_system_info"].invoke({"router_name": body.router_name}) + parsed = _parse_system_info(raw) # extract CPU%, RAM%, uptime + return {"raw": raw, "parsed": parsed} +``` + +### 9.4 Hot Reload in Docker + +- `skills/` mounted as volume → `SkillLibrary` watchdog (`watchfiles`) detects changes +- `agents/definitions/` mounted → need manual reload via `_agent_loader.reload()` +- Add `POST /api/config/agents/reload` endpoint + +### 9.5 Agent Enable/Disable + +This branch supports `enabled: false` in agent definition frontmatter. The web Settings page can toggle this by rewriting the frontmatter. + +### 9.6 NetBox Requires config.yaml + +NetBox tools read connection info from `config.yaml`: +```yaml +netbox: + kampus: + url: https://netbox.kampus.ac.id + token: YOUR_TOKEN + idren: + url: https://netbox.idren.id + token: YOUR_TOKEN +``` + +--- + +## 10. Security Considerations + +### 10.1 Do NOT Expose + +| Data | Handling | +|------|----------| +| SSH passwords from config.yaml | Strip before response | +| NetBox tokens from config.yaml | Strip before response | +| `.env` raw file | Expose only non-sensitive values | +| `export sensitive` command | Blocked by `_BLOCKED_KEYWORDS` | +| Router config with passwords | Only via agent chat | + +### 10.2 Authentication (Future) + +Current: no auth (same as TUI). For production: +- HTTP Basic Auth at Nginx level (simplest) +- Or: FastAPI JWT middleware +- Roles: `operator` (full) vs `viewer` (read-only, no approval/write) + +--- + +## 11. Implementation Phases + +### Phase 1: Wire Chat to Backend +**Target:** Chat functional end-to-end via browser. + +1. Build SPA shell: Header, Sidebar, Footer, screen router +2. Build Chat screen: message list, input, SSE streaming, 8-agent sidebar, approval modal +3. Wire to existing `POST /chat`, `POST /approve`, `POST /session/new` +4. Docker compose: backend (server.py) + Nginx serving SPA +5. Test: full chat → agent → SSH → response in browser + +### Phase 2: Network Dashboard + DHCP +**Target:** Real-time monitoring without AI chat. + +1. Add `/api/tools/*` routes to `server.py` +2. Build Network Monitor screen (router grid, traffic, top talkers) +3. Build DHCP Monitor screen (pool utilization, device search) +4. Auto-refresh toggle + +### Phase 3: NetBox Integration Screen +**Target:** Visual NetBox management. + +1. Add `/api/netbox/*` routes to `server.py` +2. Build NetBox screen (devices, drift detection, VLAN groups) +3. Sync actions (populate from router, resolve drifts) + +### Phase 4: Skills & Reports +**Target:** Manage skills and view reports from web. + +1. Add `/api/skills/*` routes (CRUD + pending review) +2. Build Skills screen (browse, filter, edit, review pending) +3. Add `/api/reports/*` routes +4. Build Reports screen (Markdown viewer + TOC) + +### Phase 5: Configuration & Settings +**Target:** Full management — no more manual file editing. + +1. Add `/api/config/*` routes (uses `config_yaml.py` tools) +2. Build Settings screen (Routers, Agents, Environment, NetBox, Memory tabs) +3. Add `/api/backups/*` routes +4. Build Backups screen (list + diff viewer) + +### Phase 6: Metrics, Auth & Polish +**Target:** Production-ready. + +1. Build Metrics screen (token usage charts per agent) +2. Add authentication +3. Responsive design +4. Error handling & loading states +5. Toast notifications for real-time events diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md index bf4dde1..a2ea731 100644 --- a/docs/IMPLEMENTATION_PLAN.md +++ b/docs/IMPLEMENTATION_PLAN.md @@ -1,8 +1,8 @@ # Implementation Plan — NetOps AI -**Versi:** 1.0 -**Tanggal:** 2026-04-27 -**Branch Target:** `netops` +**Versi:** 1.1 +**Tanggal:** 2026-05-16 +**Branch Target:** `feature/web-server` **Base Branch:** `main` --- @@ -19,6 +19,8 @@ | 5 | New Tools | traffic.py + config_backup.py | ✅ Selesai | 2f2d897 | | 6 | TUI Refactor | Pisahkan LLM logic + Agent Activity screen | ✅ Selesai | 463e419 | | 7 | Human-in-the-Loop | Approval mechanism via interrupt() | ✅ Selesai | b031262 | +| 8 | TUI Replacement | Ganti ncurses dengan Textual framework | ✅ Selesai | 34d6435 | +| 9 | Platform Maturity | Hallucination fix + commissioning + pedoman + backup enforcement | 🔄 In Progress | e17f2da | **Legend:** ⬜ Belum · 🔄 In Progress · ✅ Selesai · 🔁 Review @@ -274,6 +276,43 @@ --- +## Phase 9: Platform Maturity + +**Goal:** Hardening output quality, safety enforcement code-level, workflow commissioning, dan arsitektur conduct yang maintainable. + +### Tasks + +| ID | Task | File Target | Status | +|---|---|---|---| +| P9-01 | Fix hallucination morning-check (example contamination + premature output) | `skills/monitoring/morning-check.md` | ✅ | +| P9-02 | Approval modal buttons tidak terlihat (border: tall + height issue) | `tui_textual.py` | ✅ | +| P9-03 | Tambah narasi edukasi WAJIB setelah setiap tabel | `skills/pedoman-agent.md` | ✅ | +| P9-04 | Larangan action items pasif (Monitor/Verifikasi/Pertimbangkan) | `skills/pedoman-agent.md` | ✅ | +| P9-05 | Backup-before-write enforcement code-level di config_node | `agents/nodes.py` | ✅ | +| P9-06 | Fix /add blocklist false positive (regex path terminal segment) | `tools/config_read.py` | ✅ | +| P9-07 | Containerlab commissioning workflow (RouterOS CHR, 2 router) | `skills/config/commissioning.md`, `laporan/commissioning-spec-lab.md` | ✅ | +| P9-08 | Refactor global agent rules ke pedoman-agent.md (hot-reload tanpa restart) | `agents/nodes.py`, `skills/pedoman-agent.md` | ✅ | +| P9-09 | Local language morning check (triggers lokal + header bahasa Indonesia) | `skills/monitoring/morning-check.md` | ⬜ | +| P9-10 | Regression test eval.py setelah semua perubahan | `tests/eval.py` | ⬜ | + +### Catatan P9 + +- **pedoman-agent.md** — file conduct global dimuat via `_load_pedoman()` di startup; ubah perilaku semua agent tanpa restart Python +- **Auto-backup** — `_backed_up_routers: set[str]` per invocation; skip jika LLM sudah call backup duluan; jika operator tolak → write dibatalkan +- **Commissioning skill** — config_agent baca `laporan/commissioning-spec-lab.md` via `get_report()` saat runtime; ubah parameter (NTP, SNMP, user) di Markdown tanpa ubah kode +- **Hallucination fix** — 3 lapis: (1) Aturan Kritis larangan print template, (2) INSTRUKSI gate sebelum format section, (3) gate transisi eksplisit setelah setiap langkah + +### Definition of Done Phase 9 + +- Morning check tidak pernah print template verbatim ✅ (P9-01) +- Agent tidak pernah write ke router tanpa backup didahulukan ✅ (P9-05) +- `/ip/firewall/address-list/print` tidak diblokir blocklist ✅ (P9-06) +- `skills/pedoman-agent.md` sebagai single source of truth conduct semua agent ✅ (P9-08) +- Local language morning check triggers berfungsi ⬜ (P9-09) +- `python tests/eval.py` pass semua kasus ⬜ (P9-10) + +--- + ## Tracking Status ### Progress Overview @@ -286,19 +325,20 @@ Phase 4: Multi-Agent Graph [██████████] 100% ✅ Phase 5: New Tools [██████████] 100% ✅ Phase 6: TUI Refactor [██████████] 100% ✅ Phase 7: Human-in-the-Loop [██████████] 100% ✅ -Phase 8: TUI Replacement [░░░░░░░░░░] 0% ⬜ +Phase 8: TUI Replacement [██████████] 100% ✅ +Phase 9: Platform Maturity [████████░░] 80% 🔄 ``` ### Hasil Akhir | Metrik | Target | Aktual | |---|---|---| -| Tool atomic | ≥ 20 | 31 | -| Skill | ≥ 8 | 21 | -| Lines agent.py | < 300 | 178 | +| Tool atomic | ≥ 20 | 61 | +| Skill | ≥ 8 | 32 | +| Lines agent.py | < 300 | 278 | | LLM logic di tui.py | 0 | 0 | -| Specialist agents | 4 | 5 | -| Total commit di branch | — | 10+ | +| Specialist agents | 4 | 6 | +| Total commit di branch | — | 81 | --- @@ -315,4 +355,4 @@ P1 (Foundation) └── P8 (TUI Replacement) ``` -P5, P6, P7 dikerjakan paralel setelah P4 selesai. P8 dikerjakan setelah P7 verified. +P5, P6, P7 dikerjakan paralel setelah P4 selesai. P8 dikerjakan setelah P7 verified. P9 dikerjakan paralel dengan P8 (hardening tidak blokir TUI launch). diff --git a/docs/PRD.md b/docs/PRD.md index e866ad4..659a683 100644 --- a/docs/PRD.md +++ b/docs/PRD.md @@ -1,7 +1,7 @@ # PRD — NetOps AI: AI-Powered Campus Network Operations Platform -**Versi:** 1.1 -**Tanggal:** 2026-05-04 +**Versi:** 1.2 +**Tanggal:** 2026-05-16 **Status:** Selesai **Author:** Alan @@ -42,17 +42,18 @@ Branch baru ini (`netops`) mengembangkan tool tersebut menjadi platform operasio ## 4. Scope -### 4.1 In Scope (Branch `netops`) -- Multi-agent LangGraph: Supervisor + 5 specialist agents (monitor, diagnose, config, security, document) -- Skill system berbasis Markdown dengan hot reload; template sistem untuk panduan format laporan -- Tools: reachability, system resource, routing, interface, traffic stats, DHCP, log, config read, config backup, security, diagnostic, report, document -- TUI: Agent Activity panel untuk monitoring komunikasi agent -- Human-in-the-loop approval untuk operasi berisiko (config backup) +### 4.1 In Scope (Branch `feature/web-server`) +- Multi-agent LangGraph: Supervisor + 6 specialist agents (monitor, diagnose, config, security, document, netbox) +- Skill system berbasis Markdown dengan hot reload; 32 skill aktif; `pedoman-agent.md` sebagai global conduct file +- Tools: reachability, system resource, routing, interface, traffic stats, DHCP, log, config read/write, config backup, security, diagnostic, NetBox IPAM, report, document — **61 tools** +- TUI Textual (`tui_textual.py`): chat + approval modal + token metrics di footer +- Human-in-the-loop approval untuk backup dan write operations (enforced code-level) +- Write operations ke router via `run_command_write` dengan mandatory backup-before-write +- Commissioning workflow: router baru dari fresh via skill + design doc - Pengembangan scope dari DHCP-only → network operations menyeluruh -- Document agent: tulis laporan terstruktur ke file, kelola template, kurasi output agent lain +- NetBox agent: IPAM drift detection, sync konfigurasi -### 4.2 Out of Scope (v1.0) -- Write operations ke router (set, add, remove) — hanya read + backup +### 4.2 Out of Scope (masih) - Web interface / REST API - Wireless/CAPsMAN monitoring - IPv6 support diff --git a/docs/SCENARIO_CONTAINERLAB_COMMISSIONING.md b/docs/SCENARIO_CONTAINERLAB_COMMISSIONING.md new file mode 100644 index 0000000..291b650 --- /dev/null +++ b/docs/SCENARIO_CONTAINERLAB_COMMISSIONING.md @@ -0,0 +1,302 @@ +# Skenario: Komisioning Router via Containerlab + +## Gambaran Umum + +Skenario ini mensimulasikan proses komisioning router MikroTik RouterOS dari kondisi fresh menggunakan containerlab sebagai lingkungan lab. Agent platform (llmnetops) mengakses router via SSH dan mengeksekusi konfigurasi awal secara otomatis berdasarkan dokumen spec. + +**Tujuan:** +- Validasi workflow komisioning end-to-end menggunakan multi-agent +- Simulasi kondisi nyata: router baru, credential default, belum ada konfigurasi +- Menghasilkan laporan komisioning yang dapat diarsipkan + +--- + +## Komponen Skenario + +``` +┌─────────────────────────────────────────┐ +│ Containerlab (di luar codebase) │ +│ │ +│ [ROS-LAB-1] ──ether2── [ROS-LAB-2] │ +│ 172.20.20.11 172.20.20.12 │ +└──────────────┬──────────────────────────┘ + │ SSH via mgmt network +┌──────────────▼──────────────────────────┐ +│ llmnetops (codebase ini) │ +│ │ +│ bambang (supervisor) │ +│ └─→ joko (config_agent) │ +│ └─→ eko (monitor_agent) │ [opsional validasi] +│ └─→ document_agent │ +└─────────────────────────────────────────┘ +``` + +--- + +## Prasyarat + +### 1. Software yang Dibutuhkan + +| Software | Keterangan | +|----------|------------| +| Docker | Runtime untuk containerlab | +| containerlab | Tool orkestrasi lab jaringan | +| vrnetlab image `vr-routeros` | RouterOS CHR dalam container | +| Python 3.10+ + venv | Untuk llmnetops | +| Ollama | LLM inference lokal | + +Install containerlab: +```bash +bash -c "$(curl -sL https://get.containerlab.dev)" +``` + +### 2. RouterOS CHR Image + +Build vrnetlab image RouterOS (butuh file `.chr.vmdk` dari mikrotik.com): + +```bash +git clone https://github.com/vrnetlab/vrnetlab.git +cd vrnetlab/routeros +# Letakkan file chr-6.49.10.vmdk di sini +make +``` + +Image yang dihasilkan: `vrnetlab/vr-routeros:6.49.10` + +--- + +## Langkah 1: Deploy Lab dengan Containerlab + +### 1a. Buat file topology + +Buat file `lab-netops.clab.yaml` di direktori manapun (di luar codebase): + +```yaml +name: netops-lab +prefix: lab + +mgmt: + network: clab-mgmt + ipv4-subnet: 172.20.20.0/24 + +topology: + nodes: + ROS-LAB-1: + kind: vr-ros + image: vrnetlab/vr-routeros:6.49.10 + mgmt-ipv4: 172.20.20.11 + + ROS-LAB-2: + kind: vr-ros + image: vrnetlab/vr-routeros:6.49.10 + mgmt-ipv4: 172.20.20.12 + + links: + - endpoints: ["ROS-LAB-1:eth1", "ROS-LAB-2:eth1"] +``` + +### 1b. Deploy + +```bash +sudo containerlab deploy -t lab-netops.clab.yaml +``` + +Output yang diharapkan: +``` ++---+------------------+--------------+----------------------------+-------+ +| # | Name | Kind | Image | State | ++---+------------------+--------------+----------------------------+-------+ +| 1 | lab-ROS-LAB-1 | vr-ros | vrnetlab/vr-routeros:6.49 | running | +| 2 | lab-ROS-LAB-2 | vr-ros | vrnetlab/vr-routeros:6.49 | running | ++---+------------------+--------------+----------------------------+-------+ +``` + +### 1c. Verifikasi akses SSH + +```bash +ssh admin@172.20.20.11 # password: kosong, tekan Enter +ssh admin@172.20.20.12 +``` + +Tunggu 30-60 detik setelah deploy sebelum SSH tersedia (RouterOS CHR butuh waktu boot). + +--- + +## Langkah 2: Konfigurasi llmnetops + +### 2a. Tambahkan entri lab ke config.yaml + +Buka `config.yaml` di root project llmnetops, tambahkan: + +```yaml +ssh: + username: netops # credential produksi (sudah ada) + password: "prod123" # sesuaikan + networks: + lab: + username: admin # fresh RouterOS CHR default + password: "" # password kosong + +routers: + # ... entri router produksi yang sudah ada ... + + # Entri lab (tambahkan di bawah) + - name: ROS-LAB-1 + host: 172.20.20.11 + role: lab + network: lab + ros_version: 7 + + - name: ROS-LAB-2 + host: 172.20.20.12 + role: lab + network: lab + ros_version: 7 +``` + +### 2b. Verifikasi komisioning spec + +File `laporan/commissioning-spec-lab.md` sudah tersedia di codebase. +Buka dan sesuaikan jika ada parameter yang perlu diubah: + +| Parameter | Default | Ubah jika | +|-----------|---------|-----------| +| NTP server | `0.id.pool.ntp.org` | Pakai NTP internal | +| SNMP community | `public` | Butuh community berbeda | +| Username baru | `netops` | Butuh nama lain | +| Password | `netops123` | Butuh password berbeda | + +--- + +## Langkah 3: Jalankan llmnetops + +```bash +cd /path/to/llmnetops +source .venv/bin/activate +python tui_textual.py +``` + +--- + +## Langkah 4: Trigger Komisioning + +Di TUI, ketik: + +``` +komisioning router lab +``` + +### Alur yang Terjadi + +``` +bambang (supervisor) + → mendeteksi kata kunci "komisioning" + → routing ke joko (config_agent) + +joko (config_agent) + → menemukan skill: commissioning + → get_report("commissioning-spec-lab") # baca spec + → check_reachability(ROS-LAB-1) # cek koneksi + → check_reachability(ROS-LAB-2) + → [APPROVAL] run_command_write(ROS-LAB-1, "/ip address add ...") + → [APPROVAL] run_command_write(ROS-LAB-1, "/interface bridge add ...") + → [APPROVAL] run_command_write(ROS-LAB-1, "/user add ...") + → [APPROVAL] run_command_write(ROS-LAB-1, "/system ntp client set ...") + → [APPROVAL] run_command_write(ROS-LAB-1, "/snmp set ...") + → [APPROVAL] run_command_write(ROS-LAB-1, "/ip route add ...") + → [ulangi untuk ROS-LAB-2] + → run_command(ROS-LAB-1, "/ip address print") # validasi + → run_command(ROS-LAB-1, "/ping 10.10.2.1 count=3") + → [ulangi validasi untuk ROS-LAB-2] + → handoff ke document_agent + +document_agent + → buat laporan komisioning + → simpan ke laporan/commissioning-YYYYMMDD-HHMMSS.md +``` + +### Approval di TUI + +Setiap `run_command_write` memunculkan dialog konfirmasi. Tekan: +- `Y` atau klik "Setuju, jalankan" — eksekusi perintah +- `N` atau `Esc` — tolak (perintah di-skip) + +--- + +## Topologi Target Setelah Komisioning + +``` +ROS-LAB-1 ROS-LAB-2 +───────── ───────── +lo: 10.10.1.1/32 lo: 10.10.2.1/32 +ether2: 10.0.0.1/30 ──────────── ether2: 10.0.0.2/30 + +Static route: Static route: + 10.10.2.1/32 → 10.0.0.2 10.10.1.1/32 → 10.0.0.1 + +User: netops (group=full) User: netops (group=full) +NTP: 0.id.pool.ntp.org NTP: 0.id.pool.ntp.org +SNMP: community=public SNMP: community=public +``` + +--- + +## Validasi Manual (Opsional) + +Setelah komisioning selesai, verifikasi dari luar containerlab: + +```bash +# SSH pakai credential baru +ssh netops@172.20.20.11 + +# Di dalam ROS-LAB-1: ping loopback ROS-LAB-2 +/ping 10.10.2.1 count=5 + +# Cek routing table +/ip route print + +# Cek NTP sync +/system ntp client print +``` + +--- + +## Menghentikan Lab + +```bash +sudo containerlab destroy -t lab-netops.clab.yaml +``` + +Hapus entri lab dari `config.yaml` setelah lab dihentikan. + +--- + +## Troubleshooting + +| Masalah | Kemungkinan Penyebab | Solusi | +|---------|---------------------|--------| +| SSH timeout ke router | RouterOS belum selesai boot | Tunggu 60s, coba lagi | +| `admin` ditolak | Password sudah pernah diubah | Destroy + redeploy containerlab | +| Tool result error interface | Nama interface beda di versi CHR | Cek `/interface print` manual, sesuaikan spec | +| Agent stop setelah get_report | LLM baca spec tapi tidak lanjut | Cek `max_iters` config_agent, tambah jika perlu | +| Ping loopback gagal | Static route belum terpasang | Cek `/ip route print` di kedua router | + +--- + +## File Terkait + +| File | Keterangan | +|------|------------| +| `laporan/commissioning-spec-lab.md` | Spec yang dibaca agent — parameter & perintah | +| `skills/config/commissioning.md` | Skill yang memandu config_agent | +| `agents/definitions/config_agent.md` | Definisi joko (config_agent) | +| `tools/config_yaml.py` | Tool untuk update config.yaml via agent | + +--- + +## Pengembangan Selanjutnya + +- **Scale-up**: Tambah router ke spec (ROS-LAB-3, dst) tanpa ubah skill +- **FRRouting**: Tambah node FRR di containerlab sebagai upstream simulator BGP +- **Hardening**: Tambah skill post-komisioning — nonaktifkan `admin`, set firewall, enable logging +- **OSPF lab**: Tambah konfigurasi OSPF setelah static routing berhasil diff --git a/docs/SKILL_AUTHORING_GUIDE.md b/docs/SKILL_AUTHORING_GUIDE.md index d847e04..de05fcc 100644 --- a/docs/SKILL_AUTHORING_GUIDE.md +++ b/docs/SKILL_AUTHORING_GUIDE.md @@ -1,7 +1,7 @@ # Skill Authoring Guide — NetOps AI -**Versi:** 1.1 -**Tanggal:** 2026-05-08 +**Versi:** 1.2 +**Tanggal:** 2026-05-16 **Audience:** Operator Jaringan --- @@ -20,28 +20,54 @@ Setiap skill adalah satu file `.md` di dalam direktori `skills/`. ``` skills/ -├── dhcp/ +├── pedoman-agent.md ← KHUSUS: global conduct rules, bukan skill biasa (lihat catatan) +├── dhcp/ ← domain: dhcp │ ├── dhcp-client-diagnostics.md │ ├── dhcp-pool-audit.md +│ ├── static-lease-management.md │ └── utbk-session-monitoring.md -├── routing/ +├── routing/ ← domain: routing +│ ├── bgp-diagnostics.md +│ ├── bgp-prefix-leak.md │ ├── ospf-diagnostics.md -│ └── bgp-diagnostics.md -├── monitoring/ +│ └── static-route-management.md +├── monitoring/ ← domain: monitoring +│ ├── capacity-planning.md +│ ├── morning-check.md +│ ├── mtu-mismatch-diagnostics.md +│ ├── netbox-read.md │ ├── network-health-check.md │ ├── network-reachability.md -│ ├── network-traffic-analysis.md -│ └── network-status-report.md -├── security/ +│ ├── network-status-report.md +│ └── network-traffic-analysis.md +├── security/ ← domain: security +│ ├── brute-force-response.md +│ ├── firewall-management.md │ └── security-audit.md -├── config/ -│ └── config-backup.md -└── documents/ - └── document-writing.md +├── config/ ← domain: config +│ ├── commissioning.md +│ ├── config-backup.md +│ ├── config-change.md +│ ├── netbox-sync.md +│ ├── router-discovery.md +│ └── vlan-provisioning.md +├── interface/ ← domain: interface +│ └── link-diagnostics.md +├── maintenance/ ← domain: maintenance +│ └── router-maintenance.md +└── documents/ ← domain: documents + ├── document-writing.md + ├── skill-authoring.md + └── templates/ ← template file, bukan skill (tidak di-load SkillLibrary) + ├── network-status.md + ├── routing-bgp-ospf.md + └── security-assessment.md ``` Subdirektori berfungsi sebagai **domain kategori** dan digunakan sebagai nilai `domain:` default. +> **Catatan `pedoman-agent.md`:** File ini bukan skill biasa. Tidak muncul dalam pencarian skill dan tidak perlu dicantumkan di frontmatter agent manapun. Isinya di-inject otomatis ke semua agent system prompt oleh `_load_pedoman()` di `agents/nodes.py` saat startup. Edit file ini untuk mengubah perilaku global semua agent (format output, simbol status, aturan action items, narasi edukasi). + --- ## Konvensi Penamaan @@ -115,6 +141,8 @@ Jelaskan format dan isi output yang diinginkan. | `approval_required` | boolean | `false` | Apakah perlu persetujuan operator sebelum dieksekusi | | `enabled` | boolean | `true` | Set `false` untuk menonaktifkan skill tanpa menghapus file | +Domain yang valid: `dhcp`, `routing`, `monitoring`, `security`, `config`, `interface`, `maintenance`, `documents`. + ### Contoh Frontmatter ```yaml @@ -268,6 +296,7 @@ Daftar tool yang dapat didefinisikan di frontmatter `tools:`. ### Config & Backup | Tool | Deskripsi | |---|---| +| `run_command_write` | Perintah write ke router (butuh approval, hanya config_agent) | | `backup_router_config` | Backup config router (butuh approval) | | `list_backups` | Daftar backup tersimpan | | `diff_config` | Perbedaan dua versi config | diff --git a/docs/STITCH_PROMPT_GUIDE.md b/docs/STITCH_PROMPT_GUIDE.md new file mode 100644 index 0000000..c3de3dc --- /dev/null +++ b/docs/STITCH_PROMPT_GUIDE.md @@ -0,0 +1,495 @@ +# Google Stitch Prompt Guide — LLMNetOps Web UI + +Use these prompts at https://stitch.withgoogle.com/ to generate the LLMNetOps web interface screens. Each section is a self-contained prompt. Copy-paste one at a time. + +--- + +## Brand Reference + +**Colors extracted from logo:** +- **Navy (primary):** `#1B3A5C` — hex icon background, "LLM" text +- **Coral/Salmon (accent):** `#E88B6A` — "NetOps" text +- **White:** `#FFFFFF` — icon nodes/lines + +**Extended palette (light enterprise theme):** +- Page background: `#F5F7FA` (cool gray) +- Card / surface: `#FFFFFF` (white) +- Sidebar: `#1B3A5C` (navy, same as logo) +- Sidebar text: `#FFFFFF` / `rgba(255,255,255,0.7)` +- Header: `#FFFFFF` with bottom border +- Text primary: `#1A202C` (near-black) +- Text secondary: `#64748B` (slate gray) +- Text muted: `#94A3B8` +- Accent / CTA: `#E88B6A` (coral from logo) +- Accent hover: `#D47A5A` +- Link / interactive: `#1B3A5C` (navy) +- Border: `#E2E8F0` +- Success: `#059669` (green) +- Warning: `#D97706` (amber) +- Danger: `#DC2626` (red) +- Info: `#2563EB` (blue) + +--- + +## Prompt 1 — App Shell (Layout + Navigation) + +``` +Design a professional light-themed enterprise web application called "LLMNetOps" for campus network operations powered by AI agents. The look and feel should be similar to AWS Console or Google Cloud Console — clean, data-dense, premium, corporate. + +Layout structure: + +- Fixed top header bar (56px height, white background, subtle bottom border #E2E8F0): + Left: Logo text "LLMNetOps" where "LLM" is bold navy #1B3A5C and "NetOps" is coral #E88B6A. + Center-right: breadcrumb showing current page. + Far right: status indicator (small green dot + "System Online" text), a notification bell icon, and user avatar circle with initials. + +- Left sidebar (240px width, navy #1B3A5C background, white text): + Top: small hexagonal network icon in white, app name below in white. + Navigation items vertically stacked, each with an icon and label: + Dashboard, AI Chat, Network, DHCP, NetBox, Skills, Reports, Backups, Metrics, Settings + Active item has a white left border bar (3px), slightly brighter background rgba(255,255,255,0.1), and white text. Inactive items are rgba(255,255,255,0.65). + Section dividers with small uppercase labels like "MONITORING", "MANAGEMENT", "SYSTEM". + Bottom of sidebar: collapsed system info — model name, skills count in small muted white text. + +- Main content area: light gray background #F5F7FA, content in white cards with 1px border #E2E8F0 and border-radius 8px. + +- No footer bar (AWS console style — status lives in header). + +Typography: IBM Plex Sans for UI text, IBM Plex Mono for code and data values. Clean, corporate, high information density. No playful elements. Generous whitespace between cards, tight spacing within cards. +``` + +--- + +## Prompt 2 — Dashboard Screen + +``` +Design the Dashboard screen for "LLMNetOps", a light-themed enterprise network operations web app. Page background #F5F7FA, cards are white with 1px border #E2E8F0 and border-radius 8px. Navy sidebar on the left is already designed. + +Content area layout — responsive card grid with comfortable spacing (24px gap): + +Card 1 — "System Overview" (top-left, spans 1 column): +- Vertical stat rows, each with a label and value: + - LLM Model: "qwen3.5:9b" (monospace, medium weight) + - Active Skills: "33" with small green badge + - Agents: "7 registered, 6 active" + - Ollama: green dot + "Connected" + - NetBox: green dot + "Connected" +- Clean divider lines between each row + +Card 2 — "Router Health" (top-right, spans 1 column): +- Compact table: Router Name (bold), Host IP (monospace), Status badge +- Status badges: green pill "UP" or red pill "DOWN" +- 6-8 rows +- Bottom: coral #E88B6A outline button "Ping All Routers" + +Card 3 — "Agent Registry" (middle row, full width): +- Horizontal flex row of 8 compact agent cards: + - Each card: white background, subtle border, small padding + - Agent alias in uppercase bold (BAMBANG, EKO, AGUS, JOKO, SATRIA, BUDI, YANTO, WATI) + - Role label below in small gray text: supervisor, monitor, diagnosa, config, security, dokumen, netbox, validasi + - Small colored status dot: green (active), gray (standby), strikethrough for disabled + - Cards have subtle shadow on hover + +Card 4 — "Recent Reports" (bottom-left): +- List of 4-5 files with icon, filename, date (e.g. "May 10, 2026"), and size +- Clickable rows with hover highlight +- "View All →" link at bottom in navy + +Card 5 — "Quick Actions" (bottom-right): +- Grid of 4 action buttons with icons: + "Health Check", "Security Audit", "Backup All", "DHCP Audit" +- Buttons: white background, navy text, 1px border #E2E8F0, hover fills with light coral tint +- Each button has a small icon on the left + +Overall: clean, structured, looks like a cloud console dashboard. No dark backgrounds. +``` + +--- + +## Prompt 3 — AI Chat Screen + +``` +Design an AI Chat interface for "LLMNetOps", a light-themed enterprise multi-agent network operations platform. This is the core screen. Think of it like a professional Slack-meets-terminal hybrid. + +Page background #F5F7FA. Navy sidebar on left already designed. + +Layout has 2 main areas: +- Center (flex: 1): Chat conversation area +- Right (260px): Agent status panel, white card with border + +CENTER — Chat area: +- Top bar: white background, "AI Chat" title in navy bold, thread selector dropdown (shows thread ID), "New Thread" button (coral outline), "Clear Chat" button (gray outline). +- Message area: white background card, scrollable, takes most height. + + User message: + - Left-aligned, full width + - Small "ANDA" label in navy #1B3A5C uppercase + timestamp in gray on the right + - Message text below in dark text, normal weight + - Light top border to separate from previous message + + Agent response group: + - Small "AGENT" label in coral #E88B6A uppercase + timestamp + - Streaming event rows — each is a compact single line with: + - Routing: "→" icon in amber, text "[bambang] → eko/monitor_agent" in amber-brown + - Tool call: "⚙" icon in navy, text "[eko] get_interface_stats(router='DTI')" in navy + - Tool result: "✓" icon in green, preview text in gray + - Error: "✗" icon in red + - Events have a very light gray background #F8FAFC to distinguish from the final response + - Final AI text: regular dark text, properly formatted with paragraphs and bullet points + - While streaming: three bouncing gray dots animation + +- Bottom input area: white card with top border. Contains: + - Text input field: white background, 1px border #E2E8F0, focus border coral #E88B6A + - "Send" button: solid coral #E88B6A with white text, right side of input + - Hint line below in small gray: "[Enter] Kirim · [Ctrl+L] Clear" + +RIGHT — Agent Status Panel: +- White card with header "Agent Status" in uppercase small gray text +- 8 stacked mini-cards, one per agent: + - Alias in bold (EKO), role in small gray (monitor) + - Status: colored dot + label: "STANDBY" (gray), "RUNNING" (green), "WAITING" (amber), "DONE" (green dimmed), "FAILED" (red) + - Running agents have a subtle green left border + - Detail line: last tool called in small monospace +- Bottom: "Active Query" section with the current question and elapsed time + +Overall feel: enterprise chat tool. Light, clean, professional. Not a toy chatbot. +``` + +--- + +## Prompt 4 — Approval Modal + +``` +Design a modal dialog for "LLMNetOps" (light enterprise theme) that appears when an AI agent requires operator approval before executing a risky action. + +Overlay: semi-transparent white-gray background rgba(0, 0, 0, 0.3) with subtle backdrop blur. + +Modal: white card, max-width 500px, centered, border-radius 8px, subtle shadow (0 4px 24px rgba(0,0,0,0.12)). + +Top section: +- Warning banner at top: amber #FEF3C7 background strip with amber icon and text "Approval Required" in dark amber #92400E, uppercase, bold. + +Content: +- Field rows in a clean form-like layout (label on left in gray uppercase small text, value on right in dark text): + - Agent: "joko / config_agent" + - Action: "backup_router_config('DTI')" in monospace + - Router: "DTI (10.39.0.1)" + - Risk Level: "MEDIUM" in amber badge pill, or "HIGH" in red badge pill + - Description: "Export full configuration to backups/DTI/" + +Bottom: +- Two buttons aligned right with 12px gap: + - "Reject" — white background, red #DC2626 text and border, hover fills light red + - "Approve" — solid green #059669 background, white text, hover darkens +- Subtle hint text below buttons: "Keyboard: Y = Approve, N = Reject" + +The modal should feel authoritative and serious — like a cloud console's "are you sure you want to delete this resource?" dialog, not a casual popup. +``` + +--- + +## Prompt 5 — Network Monitor Screen + +``` +Design a Network Monitor screen for "LLMNetOps", light enterprise theme. Page background #F5F7FA, white cards with border. + +Top controls bar: +- Page title "Network Monitor" in navy bold +- Right side: auto-refresh toggle switch with interval dropdown (30s, 60s, 5m), "Refresh Now" coral outline button + +Section 1 — "Router Overview" (white card, full width): +- Clean data table with: + - Column headers in uppercase small gray text with sort arrows + - Columns: Router Name (bold navy), Host IP (monospace), Status (colored pill badge: green "UP" / red "DOWN"), RTT (monospace), CPU % (with inline mini progress bar), RAM % (with inline mini progress bar), Uptime + - Alternating row colors: white and #F8FAFC + - 8 rows of sample data + - Clickable rows to select router for detail panels below + +Section 2 — Two white cards side by side (below router table): + +Left card — "Traffic — [DTI]" (router name from selection): +- Dropdown at top to switch router +- Interface list rows: + - Interface name (bold): "ether1" + - Upload: "↑ 234 Mbps" in navy + - Download: "↓ 89 Mbps" in navy + - Small horizontal stacked bar showing TX (coral) vs RX (navy) proportions + - DOWN interfaces shown with red text and red left border + +Right card — "Interface Health — [DTI]": +- Table: Interface, RX Errors, TX Errors, RX Drops, TX Drops +- Zero values in gray, non-zero in amber bold, high values in red bold +- DOWN interfaces have red status indicator + +Section 3 — "Top Talkers" (white card, full width): +- Two columns layout within the card: + - Left: "Top Upload" — 5 rows: IP address + bandwidth bar + Mbps value + - Right: "Top Download" — same format + - Bars use coral for upload, navy for download + +AWS-console style data tables: clean headers, alternating rows, inline status badges. +``` + +--- + +## Prompt 6 — DHCP Monitor Screen + +``` +Design a DHCP Monitor screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Section 1 — "Pool Utilization" (white card): +- Clean table with columns: Router (bold), DHCP Server (monospace), Used, Total, Utilization +- Last column has a horizontal progress bar: + - Green fill for <60% + - Amber fill for 60-85% + - Red fill for >85% +- Percentage text overlaid on or beside the bar +- Example: "DTI / dhcp-lab-tik / 142 / 200 / 71%" + +Section 2 — "Device Search" (white card): +- Label: "Find device by IP or MAC address" +- Search input field (wide, with search icon inside) + coral "Search" button +- Results below in a detail card when found: + - Two-column layout: label (gray) / value (dark) pairs + - IP Address, MAC Address, Router, DHCP Server, Hostname, Status (green "bound" pill or amber "waiting" pill), Lease Time Remaining + - If not found: subtle red alert "Device not found" + +Section 3 — "Lease Browser" (white card): +- Top: two dropdown selectors — Router and DHCP Server +- Data table below: IP (monospace), MAC Address (monospace), Hostname, Status (pill badge), Last Seen +- Pagination at bottom: "Showing 1-20 of 142" with page buttons +- Table rows have alternating background + +Clean corporate data layout. Monospace for IP and MAC values. +``` + +--- + +## Prompt 7 — NetBox Integration Screen + +``` +Design a NetBox IPAM integration screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Top: page title "NetBox Integration" with instance selector dropdown (values: "kampus", "idren") and connection status indicator (green dot + "Connected"). + +Section 1 — "Devices" (white card): +- Table: Device Name (bold navy link), Site, Role (badge pill), Platform, Status (green "Active" or gray "Planned" pill), Interfaces, IPs +- Rows clickable to expand and show interface detail inline + +Section 2 — "Configuration Drift" (white card, this is the key feature): +- Header with icon: "Drift Detection" + summary text "3 drifts across 2 devices" +- If drifts exist: subtle amber left-border on the card +- Each drift item as a row: + - Left: Router name + interface name in bold + - Center: Two-column comparison: + "NetBox: 10.39.1.1/24" vs "Router: (not configured)" + with arrows between them + - Right: drift type badge (amber "IP Mismatch", red "Missing from NetBox", blue "Extra on Router") + - Action: small "Sync" link button per item +- Top right: "Sync All to NetBox" coral button +- Sub-card below: "BGP Session Drift" — similar format for BGP mismatches showing AS numbers, session states + +Section 3 — "VLAN Groups" (white card): +- Table: Group Name, VLAN Count, ID Range, Next Available +- Expandable rows showing individual VLANs within each group +- "Provision New VLAN" button (coral outline) + +Status colors: green "In Sync" badge, amber "Drift Detected" badge, red "Missing" badge. +Clean enterprise look — this should feel like an AWS resource management page. +``` + +--- + +## Prompt 8 — Skills Management Screen + +``` +Design a Skills management screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Top bar: Page title "Skills" with count badge "(33 active)" in gray, buttons: "+ New Skill" (coral solid), "Reload" (gray outline with refresh icon). + +Filter bar: horizontal row of clickable pill/chip buttons for domain filtering: +All (33), monitoring (8), config (8), routing (4), security (3), dhcp (4), documents (2), interface (1), maintenance (1) +Active filter: coral #E88B6A filled pill with white text. Inactive: white pill with gray border. + +Skill list — white card containing vertical list of skill items: +Each skill row (separated by light border): +- Left column: + - Skill name in bold navy: "network-health-check" + - Domain as small colored badge pill below: "monitoring" in coral + - Trigger keywords in small gray italic: "cek status, health check, status jaringan" +- Right column: + - Green "ACTIVE" badge (or gray "DISABLED" badge) + - Tool count: "5 tools" in small text + - Approval indicator: lock icon if approval_required + - Hover: shows "Edit" and "Disable" text links + +Below main list — "Pending Review" section: +- Collapsible card with amber top border and warning icon +- Header: "2 skills pending review" +- Each pending item: name, domain badge, [Review] (navy link), [Approve] (green), [Reject] (red outline) + +Skill Editor (full-page or large modal when editing): +- Left panel (40%): form fields + - Name (text, monospace) + - Domain (dropdown) + - Triggers (tag input — type and press enter to add chips) + - Approval Required (toggle switch) + - Enabled (toggle switch) +- Right panel (60%): Markdown editor + - Tab bar: "Edit" and "Preview" tabs + - Edit: code editor textarea with line numbers, monospace font + - Preview: rendered Markdown +- Bottom: "Save" (coral solid) and "Cancel" (gray outline) + +AWS console resource-management style. Clean forms, clear actions. +``` + +--- + +## Prompt 9 — Reports & Backups Screen + +``` +Design a Reports & Backups screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Two-panel layout: + +Left panel (320px, white card): +- Section header: "Reports" with file count +- File list sorted by newest first. Each item: + - File icon + filename (truncated if long) + - Date below in small gray text: "May 10, 2026 09:23" + - Size on right: "14.2 KB" + - Selected item: light coral background tint #FFF5F2, coral left border + - Hover: light gray background + +- Divider line + +- Section header: "Config Backups" +- Tree view grouped by router: + - "▶ DTI" (expandable) + - "DTI_20260510_103045.rsc — 128 KB" + - "DTI_20260509_091200.rsc — 126 KB" + - "▶ FIKES" (expandable) + - ... + - Checkboxes on backup files for comparison + +Right panel (flex: 1, white card): +- Top bar: filename in bold, buttons on right: "Download" (navy outline), "Compare" (coral outline, only for backups) +- Content area: + - For reports (.md files): Rendered Markdown with proper headings, tables, code blocks with copy button, and a floating TOC outline on the right margin + - For backups (.rsc files): syntax-highlighted config with line numbers + - For diff view: side-by-side diff — left panel (old) and right panel (new), green lines for additions, red for deletions, gray for unchanged + +Feels like a document viewer in a cloud console. Clean typography, good line spacing. +``` + +--- + +## Prompt 10 — Metrics Screen + +``` +Design a Token Metrics screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Section 1 — Summary Cards (top row, 4 cards): +- Card 1: "Total LLM Calls" — large number "1,247" with small trend indicator "+12% vs yesterday" +- Card 2: "Avg Context Usage" — percentage "34%" with circular progress indicator (coral fill) +- Card 3: "Avg Speed" — "18.3 tok/s" +- Card 4: "Warnings" — "3" in amber with warning icon (or "0" in green with check) +Each card: white background, subtle border, small heading in gray uppercase, large value in navy. + +Section 2 — "Per-Agent Breakdown" (white card): +- Data table with columns: Agent (alias + role), Total Calls, Avg CTX%, Avg PRED%, Avg TPS, Warnings +- Agent column shows alias in bold (EKO) with role in small gray (monitor) below +- Numeric columns right-aligned, monospace, tabular-nums +- Rows with warnings > 0 have subtle amber background tint +- Sort arrows on column headers +- Color-coded inline bars in CTX% and PRED% columns: green (<60%), amber (60-80%), red (>80%) + +Section 3 — "Usage Trend" (white card): +- Toggle tabs: "24 Hours" / "7 Days" / "30 Days" +- Line chart area (placeholder): + - X-axis: time periods + - Y-axis: Context utilization % + - One line per agent, using distinct colors + - Legend at bottom showing agent aliases with color dots +- Below chart: "Exported from data/metrics.jsonl" in small gray + +Enterprise analytics dashboard style. Clean charts, well-labeled axes. +``` + +--- + +## Prompt 11 — Settings Screen + +``` +Design a Settings screen for "LLMNetOps", light enterprise theme. Background #F5F7FA. + +Tab navigation at top: horizontal tabs with bottom border indicator. +Tabs: Routers | Agents | Environment | NetBox | Memory +Active tab: navy text with coral bottom border. Inactive: gray text. + +TAB 1 — Routers: +- White card with header "Router Configuration" and "Add Router" coral button on right +- Editable data table: + - Columns: Name (text input), Host (text input), ROS Version (dropdown: 6 or 7), DHCP Servers (tag chips), Role + - Each row has two action buttons: [Test] (navy outline, shows green ✓ or red ✗ after click) and [Remove] (red text link) +- Table has alternating row backgrounds +- Bottom: "Save Changes" coral solid button + "Discard" gray outline button + +TAB 2 — Agents: +- Grid of cards (2 columns), one per agent: + - Card header: Alias large bold (EKO) + agent name (monitor_agent) + toggle switch for enabled/disabled + - Disabled agents have grayed-out card with "DISABLED" badge + - Form fields within card: Model (text), num_ctx (number), num_predict (number), context_window (number), timeout (number) + - Read-only sections: Tools (list of gray pills), Skills (list of coral pills) + - Each card has subtle hover shadow +- Top right: "Reload Definitions" button (navy outline) + +TAB 3 — Environment: +- White card with clean form layout: + - Label above each field in gray uppercase + - OLLAMA_BASE_URL: text input, current value shown, [Test Connection] button beside it showing result (green "Connected" or red "Failed") + - OLLAMA_MODEL: dropdown (populated from Ollama API), showing current selection + - Status row below: "Ollama server at localhost:11434 — 3 models available" +- "Save" coral button + +TAB 4 — NetBox: +- One card per NetBox instance (kampus, idren): + - Card header: instance name in bold + connection status badge + - Fields: URL (text input), API Token (password input with eye toggle to show/hide) + - [Test Connection] button per instance +- "Save" coral button + +TAB 5 — Memory: +- White card: "Agent Memory — Router Facts" +- Filter: router dropdown selector +- Data table: Router (bold), Fact Type (badge), Value, Source, Updated At +- Select-all checkbox + "Clear Selected" red outline button +- Confirmation dialog before clearing + +AWS console settings style — tabbed layout, clean forms, inline validation feedback. +``` + +--- + +## General Style Notes for All Prompts + +Append to any prompt above for consistent styling: + +``` +Additional style requirements: +- This is a LIGHT theme — NOT dark mode. White cards on light gray #F5F7FA background. +- Sidebar is the only dark element: navy #1B3A5C background with white text. +- Font: IBM Plex Sans for all UI text. IBM Plex Mono for code, IPs, MACs, data values. +- Cards: white background, 1px border #E2E8F0, border-radius 8px, no heavy shadows. +- Primary action buttons: solid coral #E88B6A with white text, rounded 6px. +- Secondary buttons: white background with navy or gray border, navy text. +- Destructive buttons: white background with red border/text, or solid red. +- Status badges: small pill shapes with colored background tint + darker text (e.g., green-100 bg + green-800 text for "UP"). +- Data tables: uppercase small gray headers, alternating white/#F8FAFC rows, right-aligned numbers. +- All numeric/code values in monospace with tabular-nums font variant. +- Links and interactive text: navy #1B3A5C, underline on hover. +- No rounded corners larger than 8px. No heavy shadows. No gradients. +- High information density — this is an operations tool, not a marketing site. +- Design language: AWS Console, Google Cloud Console, Datadog — premium enterprise SaaS. +``` diff --git a/docs/architecture.html b/docs/architecture.html new file mode 100644 index 0000000..ac173aa --- /dev/null +++ b/docs/architecture.html @@ -0,0 +1,987 @@ + + + + + +llmnetops — System Architecture + + + +
+ + +
+
+

llmnetops

+

LangGraph Multi-Agent Platform · Campus Network Operations · MikroTik RouterOS

+
+
+ Python + LangGraph + LangChain + Ollama + Paramiko SSH + RouterOS v6/v7 + NetBox +
+
+ + +
+ + +
+ + +
+
+
🖥️
+
+
Operator UI
+
tui.py · tui_textual.py
+
+
+
+
+
tui.py
+
ncurses · aktif
+
    +
  • Chat screen
  • +
  • Activity log screen
  • +
  • Approval prompts
  • +
  • Event stream display
  • +
+
+
+
tui_textual.py WIP
+
Textual · Phase 8
+
    +
  • Modern TUI framework
  • +
  • Belum diimplementasi
  • +
+
+
+
+ +
+
+
consume public API only — zero LLM logic di TUI
+
+
+
+ + +
+
+
⚡
+
+
Public API
+
agent.py — single entry point, tanpa LLM logic
+
+
+
+
create_agent()
+
stream_agent_response(graph, config, query)
+
resume_after_approval(graph, config, decision)
+
+
Event types yang di-yield ke TUI:
+
+ routing + tool_call + tool_result + ai + approval_required + error +
+
+ +
+
+
graph.stream() — preserves interrupt chain
+
+
+
+ + +
+
+
🔄
+
+
LangGraph State Machine
+
agents/graph.py · agents/nodes.py
+
+
+
NetworkOpsState
+
+
messages append-only
+
next_agent
+
active_agent
+
agent_log → TUI events
+
reasoning debug
+
skill_name
+
+
+
+
supervisor_node
+
    +
  • Routes by query analysis
  • +
  • Loop guard → force END
  • +
  • Jawab greeting sendiri
  • +
+
+
+
_make_specialist_node()
+
    +
  • Factory untuk semua agent
  • +
  • Injeksi skill + pedoman
  • +
  • Safety net fallback
  • +
+
+
+
config_node
+
    +
  • interrupt() pada write tool
  • +
  • Approval-gated tools
  • +
  • Resume via stream()
  • +
+
+
+
+ +
+
+
supervisor routing decision
+
+
+
+ + +
+
+
🧑‍💼
+
+
Supervisor Node
+
agents/definitions/supervisor.md
+
+
+
+
+
🧑‍💼
+
Bambang
+
supervisor
+
+
+
Routes to
+
+ monitor_agent + diagnose_agent + config_agent + security_agent + document_agent + netbox_agent + validasi_agent + self (greetings / pertanyaan umum) +
+
+
+
+ +
+
+
delegated task + injected skill
+
+
+
+ + +
+
+
🤖
+
+
Specialist Agents
+
agents/definitions/*.md — 7 agents, masing-masing model Ollama sendiri
+
+
+
+
+
Eko
+
monitor_agent
+ monitoring +
+
+
Agus
+
diagnose_agent
+ diagnostic +
+
+
APPROVAL
+
Joko
+
config_agent
+ config · write +
+
+
Satria
+
security_agent
+ security +
+
+
Budi
+
document_agent
+ documents +
+
+
Yanto
+
netbox_agent
+ netbox / dcim +
+
+
Wati
+
validasi_agent
+ validation +
+
+
+ +
+
+
tool calls via TOOL_MAP
+
+
+
+ + +
+
+
⚙️
+
+
Support Layer
+
loader · tools registry · skills library · metrics
+
+
+
+
+
agents/loader.py
+
Parse .md → AgentDefinition objects
+
+
+
agents/tools.py
+
TOOL_MAP — registry semua tools
+
+
+
skills/library.py
+
SkillLibrary + hot-reload via watchfiles
+
+
+
agents/metrics.py
+
TokenMetricsCallback per agent
+
+
+
+ +
+
+
61 @tool functions · get_* read-only · run_command_write → approval
+
+
+
+ + +
+
+
🔧
+
+
Tools Layer
+
tools/*.py — 61 @tool functions · SSH ke MikroTik
+
+
+
+
config_read
+
config_write ⚠️
+
config_backup ⚠️
+
reachability
+
interface
+
routing
+
traffic
+
dhcp
+
security
+
netbox
+
diagnostic
+
log
+
document
+
agent_memory
+
+
+ read-only + ⚠️ butuh approval operator + blocklist: run_command_write blokir format / factory-reset +
+
+ +
+
+
Paramiko SSH · kredensial dari config.yaml (gitignored)
+
+
+
+ + +
+
+
🔀
+
+
MikroTik Routers
+
RouterOS v6 / v7 · multiple nodes · campus network
+
+
+
+
🔀
+
+
Campus Network Routers
+
+ RouterOS v6 / v7 · multiple router nodes
+ Kredensial: config.yaml (gitignored)
+ Backup: backups/ · Laporan: laporan/ +
+
+
+ SSH / API + via Paramiko +
+
+
+ +
+ + +
+ + +
+
Agent Definition Pipeline
+
+ agents/definitions/*.md
+ 8 file · frontmatter YAML
+ name · alias · model · tools · skills · handoff_to +
+
↓ parsed by
+
+ agents/loader.py
+ AgentLoader → AgentDefinition objects +
+
↓ resolves tools via
+
+ agents/tools.py
+ TOOL_MAP lookup per agent +
+
+ + +
+
Skills Hot-Reload
+
+ skills/**/*.md
+ monitoring · config · routing
+ security · dhcp · maintenance · documents +
+
↓ watched by
+
+ skills/library.py
+ SkillLibrary via watchfiles +
+
↓ injected into
+
+ Specialist node system prompt
+ Skill baru langsung aktif — no restart +
+
+
+
+ live hot-reload +
+
+
+ + +
+
Approval / Interrupt Flow
+
+
+ 1 + Supervisor route query → config_agent (Joko) +
+
+ 2 + Agent panggil write tool: run_command_write atau backup_router_config +
+
+ 3 + interrupt() — eksekusi PAUSE +
+
+ 4 + TUI tampilkan approval prompt ke operator +
+
+ 5 + Operator tekan Y atau N +
+
+ 6 + resume_after_approval() → graph.stream() lanjut +
+
+ 7 + Tool execute → tool berikutnya atau END. Interrupt selanjutnya tetap propagate. +
+
+
+ + +
+
Safety Mechanisms · agents/nodes.py
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
GuardPerilaku
Loop GuardSupervisor route ke agent yang sama dua kali → force END
Safety NetFinal msg bukan AIMessage → fallback ke ToolMessage terpanjang
Rule 6Agent tidak boleh tulis teks konfirmasi di tengah sequence
Blocklist Rrun_command tolak keyword destruktif
Blocklist Wrun_command_write blokir format / factory-reset
+
+ ⚠ Jangan hapus Loop Guard atau Safety Net — menyebabkan supervisor loop tak terbatas. +
+
+ + +
+
Ringkasan Alur Data
+
+ User input + → + Bambang pilih agent
+ → + Specialist load skill
+ → + Tools SSH ke MikroTik
+ → + Hasil kembali ke LLM
+ → + [jika write: approval interrupt]
+ → + Response final ke TUI +
+
+ +
+ +
+ + +
+
+
UI
+
API
+
LangGraph
+
Supervisor
+
Agents
+
Support
+
Tools
+
Routers
+
+
llmnetops · 7 agents · 61 tools · 8 phases · branch: feature/web-server
+
+ +
+ + diff --git a/docs/stitch_llmnetops_enterprise_console/.DS_Store b/docs/stitch_llmnetops_enterprise_console/.DS_Store new file mode 100644 index 0000000..1a16782 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/.DS_Store differ diff --git a/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/code.html new file mode 100644 index 0000000..b5e0063 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/code.html @@ -0,0 +1,410 @@ + + + + + +LLMNetOps - AI Chat + + + + + + + + + + + +
+ +
+
+search + +
+
+ + +
+
+ +
+ + + +
+ +
+ +
+
+14:22:45 +ANDA +
+
+

Analyze why interface GigabitEthernet0/1 on Core-Switch-01 is showing high error rates. Check the last 15 minutes of logs.

+
+
+ +
+
+AGENT +14:22:48 +
+ +
+

Understood. Initiating diagnostic sequence for Core-Switch-01. Analyzing physical layer metrics and system logs.

+ +
+ +
+[ROUTING] +Redirecting task to Network_Diagnostic_Agent... +
+ +
+[TOOL_CALL] +get_device_logs(hostname="Core-Switch-01", interface="Gi1/0/1", duration="15m") +
+ +
+[RESULT] +Fetched 42 relevant log entries. High CRC error count detected (4,291). +
+ +
+[ERROR] +SNMP timeout on secondary poller. Retrying... +
+
+

The logs indicate a possible physical layer issue or duplex mismatch. I'm checking the neighboring device status now.

+ +
+
+
+
+
+
+
+
+ +
+
+
+ +
+ + +
+
+
+ +attach_file Attach Config + + +code Run Script + + +help Help + +
+
+
+
+ + +
+
+ + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/screen.png new file mode 100644 index 0000000..70e9895 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/ai_chat_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/code.html new file mode 100644 index 0000000..3907669 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/code.html @@ -0,0 +1,279 @@ + + + + + +LLMNetOps - Approval Modal + + + + + + + + + + + + + +
+
+LLMNetOps +
+
+notifications +account_circle +
+
+ + + +
+
+
+

System Monitoring

+
LAST_SYNC: 2023-10-27T10:44:02Z
+
+ +
+ +
+ + +
+
+
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/screen.png new file mode 100644 index 0000000..fe6fe9f Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/approval_required_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/code.html new file mode 100644 index 0000000..9cb4bbe --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/code.html @@ -0,0 +1,195 @@ + + + + + +LLMNetOps Dashboard - Enterprise Console + + + + + + + + + + + +
+ +
+
+
+search + +
+
+
+
+ +Ollama: Online +
+
+ +
\ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/screen.png new file mode 100644 index 0000000..43699f7 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/dashboard_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/code.html new file mode 100644 index 0000000..25e42a0 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/code.html @@ -0,0 +1,527 @@ + + + + + +DHCP Monitor - LLMNetOps + + + + + + + + + + + + + +
+
+
+search + +
+
+
+ + +
+
+ +
+ +
+
+

DHCP Infrastructure Monitor

+

Real-time IP address space management and lease orchestration.

+
+
+ + +
+
+ +
+
+
+

Active Pool Utilization

+Live Updates +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pool NameSubnet RangeTotal IPsUtilizationStatus
Campus-Core-A10.0.10.0/24254 +
+
+
+
+42% +
+
+Healthy +
Guest-WiFi-North172.16.50.0/221022 +
+
+
+
+84% +
+
+Warning +
IoT-Sensor-Mesh192.168.200.0/24254 +
+
+
+
+96% +
+
+Critical +
DataCenter-VLAN4010.100.40.0/24254 +
+
+
+
+12% +
+
+Healthy +
+
+
+ +
+
+
+

Total Managed Leases

+

12,482

+
+trending_up + +124 since last hour +
+
+ +
+hub +
+
+
+
+

System Health

+ +
+
+
+Server Response +12ms +
+
+Conflict Detection +Active +
+
+Sync Latency +0.8s +
+
+
+
+
+ +
+
+
+ +
+

Lookup Device

+
+
+ +
+ + +
+
+
+ Quick tip: Use wildcard '*' for partial MAC searches. +
+
+
+ +
+
+laptop_mac +
+
+
+

IP ADDRESS

+

172.16.50.112

+
+
+

MAC ADDRESS

+

00:50:56:C0:00:08

+
+
+

HOSTNAME

+

MKTG-DELL-XPS-04

+
+
+

STATUS

+Active Lease +
+
+

LEASE START

+

2023-10-24 09:12:04

+
+
+

LEASE END

+

2023-10-25 09:12:04

+
+
+

VENDOR

+

Dell Inc.

+
+
+ +
+
+
+
+
+
+ +
+
+

Recent Leases Browser

+
+ + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Assigned IPHardware AddressHostname / Client IDPoolExpiryActions
10.0.10.45A1:B2:C3:D4:E5:F6PRINTER-HR-302Campus-Core-A6h 12m remaining + +
10.0.10.8922:33:44:55:66:77LAPTOP-782JKSCampus-Core-A2h 45m remaining + +
172.16.51.12BC:12:34:56:78:90IP-PHONE-405Guest-WiFi-NorthExpired (Static Reserved) + +
192.168.200.1100:11:22:33:44:55IOT-TEMP-SENSORIoT-Sensor-Mesh14h 50m remaining + +
172.16.50.201AA:BB:CC:DD:EE:FFIPAD-SALES-ROOMGuest-WiFi-North1h 05m remaining + +
+
+ +
+Showing 1 to 5 of 1,245 leases +
+ + + + + +
+
+
+
+ + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/screen.png new file mode 100644 index 0000000..9f56ecf Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/dhcp_monitor_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/code.html b/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/code.html new file mode 100644 index 0000000..4b28f48 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/code.html @@ -0,0 +1,364 @@ + + + + + +LLMNetOps - Enterprise Console + + + + + + + + + + + + +
+
+ + +
+
+ +
+ + + + +SYSTEM ONLINE +
+ +
+ +
+ +
+
+
+
+ + + +
+
+ +
+
+

Network Overview

+

Real-time status of autonomous agents and campus infrastructure.

+
+
+ + +
+
+ +
+ +
+
+

Traffic Analysis

+
+LIVE +LAST 24H +
+
+
+
+monitoring +

Metric visualization placeholder

+
+
+
+ +
+ +
+

ACTIVE AGENTS

+
+128 ++12% +
+
+ +
+

THREATS BLOCKED

+
+1,042 ++4% +
+
+ +
+

CRITICAL EVENTS

+
+
+
+error +
+
+

DHCP Scope Exhaustion

+

VLAN-102 • 2m ago

+
+
+
+
+warning +
+
+

BGP Peer Flapping

+

Router-NYC-04 • 15m ago

+
+
+
+
+
+ +
+
+

Active Sessions

+
+search + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SOURCEDESTINATIONPROTOCOLBITRATESTATUS
10.0.42.18172.16.5.101HTTPS / TLS 1.34.2 Gbps +SECURE +
10.0.12.58.8.8.8DNS / UDP12 Kbps +SECURE +
10.0.42.202UnknownSSH / Port 22156 Kbps +AUDIT +
+
+
+
+
+ + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/screen.png b/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/screen.png new file mode 100644 index 0000000..50f9329 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/llmnetops_app_shell/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/llmnetops_design_system/DESIGN.md b/docs/stitch_llmnetops_enterprise_console/llmnetops_design_system/DESIGN.md new file mode 100644 index 0000000..c6d84c6 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/llmnetops_design_system/DESIGN.md @@ -0,0 +1,190 @@ +--- +name: LLMNetOps Design System +colors: + surface: '#f7f9fc' + surface-dim: '#d8dadd' + surface-bright: '#f7f9fc' + surface-container-lowest: '#ffffff' + surface-container-low: '#f2f4f7' + surface-container: '#eceef1' + surface-container-high: '#e6e8eb' + surface-container-highest: '#e0e3e6' + on-surface: '#191c1e' + on-surface-variant: '#43474e' + inverse-surface: '#2d3133' + inverse-on-surface: '#eff1f4' + outline: '#73777f' + outline-variant: '#c3c6cf' + surface-tint: '#436084' + primary: '#002444' + on-primary: '#ffffff' + primary-container: '#1b3a5c' + on-primary-container: '#87a4cc' + inverse-primary: '#abc9f2' + secondary: '#94492d' + on-secondary: '#ffffff' + secondary-container: '#fe9d7b' + on-secondary-container: '#773218' + tertiary: '#142438' + on-tertiary: '#ffffff' + tertiary-container: '#2a3a4e' + on-tertiary-container: '#93a4bc' + error: '#ba1a1a' + on-error: '#ffffff' + error-container: '#ffdad6' + on-error-container: '#93000a' + primary-fixed: '#d2e4ff' + primary-fixed-dim: '#abc9f2' + on-primary-fixed: '#001c38' + on-primary-fixed-variant: '#2b486b' + secondary-fixed: '#ffdbcf' + secondary-fixed-dim: '#ffb59c' + on-secondary-fixed: '#380c00' + on-secondary-fixed-variant: '#773218' + tertiary-fixed: '#d3e4fe' + tertiary-fixed-dim: '#b7c8e1' + on-tertiary-fixed: '#0b1c30' + on-tertiary-fixed-variant: '#38485d' + background: '#f7f9fc' + on-background: '#191c1e' + surface-variant: '#e0e3e6' +typography: + display-lg: + fontFamily: IBM Plex Sans + fontSize: 30px + fontWeight: '600' + lineHeight: 38px + letterSpacing: -0.02em + headline-md: + fontFamily: IBM Plex Sans + fontSize: 24px + fontWeight: '600' + lineHeight: 32px + title-sm: + fontFamily: IBM Plex Sans + fontSize: 18px + fontWeight: '500' + lineHeight: 24px + body-md: + fontFamily: IBM Plex Sans + fontSize: 14px + fontWeight: '400' + lineHeight: 20px + body-sm: + fontFamily: IBM Plex Sans + fontSize: 13px + fontWeight: '400' + lineHeight: 18px + label-caps: + fontFamily: IBM Plex Sans + fontSize: 11px + fontWeight: '700' + lineHeight: 16px + letterSpacing: 0.05em + data-mono: + fontFamily: IBM Plex Mono + fontSize: 13px + fontWeight: '450' + lineHeight: 18px + data-mono-sm: + fontFamily: IBM Plex Mono + fontSize: 11px + fontWeight: '450' + lineHeight: 14px +rounded: + sm: 0.25rem + DEFAULT: 0.5rem + md: 0.75rem + lg: 1rem + xl: 1.5rem + full: 9999px +spacing: + sidebar_width: 240px + header_height: 56px + container_gutter: 24px + component_padding_x: 12px + component_padding_y: 8px + stack_gap_sm: 4px + stack_gap_md: 12px + stack_gap_lg: 24px +--- + +## Brand & Style +The design system is engineered for high-stakes enterprise network management, where clarity and rapid data synthesis are paramount. The personality is **authoritative, precise, and utilitarian**, stripping away decorative elements to focus on operational efficiency. + +The aesthetic follows a **Modern Corporate** approach with a focus on high information density. It prioritizes clarity over visual flourish, utilizing a structured layout that mirrors the complexity of AI-driven network operations. The interface evokes a sense of "command and control," providing administrators with a stable, predictable environment to manage campus infrastructure. + +Key principles include: +- **Efficiency over Embellishment:** Every pixel must serve a functional purpose. +- **Data Density:** Layouts are optimized to display large volumes of logs, metrics, and agent states without overwhelming the user. +- **Visual Stability:** A rigid grid and consistent alignment create a reliable workspace for long-term monitoring. + +## Colors +The palette is built for professional utility, using a "Navy and Coral" foundation to distinguish between structural elements and actionable triggers. + +- **Primary (Navy - #1B3A5C):** Reserved for high-level navigation, sidebars, and brand-critical indicators. It provides a grounded, stable frame for the application. +- **Accent (Coral/Salmon - #E88B6A):** Used sparingly but decisively for primary calls to action, active AI agent status, and critical brand highlights. +- **Backgrounds:** The global page background uses a "Cool Gray" (#F5F7FA) to reduce eye strain, while interactive surfaces and cards utilize pure White (#FFFFFF). +- **Semantic Colors:** Success, Warning, and Error states follow industry standards but are softened through the use of high-contrast text on desaturated background tints for better legibility in dense tables. + +## Typography +This design system employs a dual-typeface strategy to separate narrative UI from technical data. + +- **IBM Plex Sans:** Used for all interface instructions, labels, and headings. It provides a modern, neutral tone that remains legible at small sizes. +- **IBM Plex Mono:** Used strictly for technical values including IP addresses, MAC addresses, CLI output, and numeric metrics. This ensures that characters like '0' and 'O' are never confused during critical network troubleshooting. +- **Hierarchy:** We use a tight scale. Most UI text sits at 13px or 14px to maximize information density. Table headers use a bold, uppercase 11px style to provide clear categorization without occupying excessive vertical space. + +## Layout & Spacing +The layout is based on a **Fixed-Fluid hybrid model** designed for professional desktop displays. + +- **Sidebar:** A fixed 240px navigation rail on the left, using the Navy primary color. It features a 3px vertical "Accent" indicator for the active route. +- **Header:** A fixed 56px white bar with a 1px #E2E8F0 bottom border, housing global search and agent status notifications. +- **Grid:** Content is housed within a fluid container with 24px margins. For complex dashboards, a 12-column grid is used, but for data-heavy views, simple flexbox stacks are preferred to maintain density. +- **Density:** We use a "Compact" spacing rhythm. Vertical padding in lists and tables is kept to 8px to ensure more data is visible above the fold. + +## Elevation & Depth +This design system avoids heavy shadows and skeuomorphism in favor of **Tonal Layering and Borders**. + +- **Level 0 (Background):** #F5F7FA (Cool Gray). Used for the canvas. +- **Level 1 (Surface):** #FFFFFF (White). All cards, tables, and modals sit on this level. +- **Borders:** Depth is primarily communicated through 1px solid borders (#E2E8F0). This creates a "blueprint" feel that is clean and structured. +- **Shadows:** Only used for floating elements like dropdown menus or modals. When used, shadows are highly diffused and low-opacity: `0px 4px 12px rgba(0, 0, 0, 0.05)`. + +## Shapes +The shape language is controlled and professional. Elements use a **Standard Rounded (0.5rem)** corner radius for cards and containers to prevent the UI from feeling overly aggressive or "brutalist," while maintaining a modern enterprise look. + +- **Buttons & Inputs:** 4px to 8px radius (rounded-md). +- **Cards:** 8px radius (rounded-lg). +- **Badges/Pills:** Fully rounded (pill-shaped) to distinguish them from interactive buttons. + +## Components +### Buttons +- **Primary:** Solid #E88B6A background with white text. High visibility for core actions like "Deploy Agent" or "Save Changes." +- **Secondary:** White background with #1B3A5C border and text. Used for "Cancel" or "Export." +- **Ghost:** No background/border, Navy text. Used for low-priority actions in table rows. + +### Tables +- **Structure:** 1px #E2E8F0 border, no horizontal lines between rows is preferred if zebra-striping is used. +- **Zebra Striping:** Even rows use #F8FAFC; odd rows use #FFFFFF. +- **Headers:** 11px uppercase, bold, #64748B text color. +- **Data:** Right-align all numeric and monospace data. + +### Cards +- White background, 1px #E2E8F0 border, 8px radius. +- Padding should be a consistent 16px or 24px. +- Use a 1px bottom border for card titles to separate header information from content. + +### Badges / Status Indicators +- **Success:** #DCFCE7 background, #166534 text. +- **Warning:** #FEF3C7 background, #92400E text. +- **Error:** #FEE2E2 background, #991B1B text. +- **Style:** Small pill-shaped containers with 'IBM Plex Sans' Bold 11px text. + +### Input Fields +- 1px #E2E8F0 border, 4px corner radius. +- Active state uses a 1px #1B3A5C border and a subtle Navy glow (2px). +- Labels always sit above the input field in 12px Medium weight. + +### Sidebar Nav Items +- Default: #FFFFFF (60% opacity) text on #1B3A5C. +- Active: #FFFFFF text with a 3px #E88B6A left-border highlight and a subtle 10% white overlay background. \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/code.html new file mode 100644 index 0000000..c1a1f3d --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/code.html @@ -0,0 +1,458 @@ + + + + + +Token Metrics | LLMNetOps + + + + + + + + + +
+
+LLMNetOps + +
+
+ + +
+
+ + + +
+ +
+
+ +

Operational Token Analytics

+
+
+ + +
+
+ +
+ +
+
+
+Total Calls +call_made +
+
142,891
+
+
+trending_up + 12.4% vs last period +
+
+ +
+
+
+Context Usage +data_thresholding +
+
68.2%
+
+
+
+
+
+ +
+
+
+Mean Speed +bolt +
+
84.5 tok/s
+
+
+trending_down + 3.1% latency increase +
+
+ +
+
+
+System Warnings +warning +
+
14
+
+
+schedule + Last detected 8m ago +
+
+
+ +
+
+

Token Consumption Trend

+
+ + + +
+
+
+ + + + + + + + + + + + + + + + + + + + +
+ TOKENS: 4.2M
TIME: 14:00 +
+
+
+ +
+
+

Per-Agent Resource Allocation

+
+LIVE SYSTEM HEALTH: NOMINAL +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Agent NameModelTotal CallsCTX Usage %PRED AccuracyTPS (Avg)Status
CoreSwitch-A01GPT-4o-Mini42,109 +
+
+
+
+82% +
+
98.4%112.5 + + + Optimal + +
WiFi-Optimizer-MainLlama-3-70B28,542 +
+
+
+
+45% +
+
94.1%45.2 + + + Optimal + +
BGP-Analyst-V3Claude-3-Sonnet12,301 +
+
+
+
+95% +
+
89.9%32.8 + + + Throttled + +
Security-Patrol-NodeCustom-BERT542,001 +
+
+
+
+12% +
+
99.9%840.1 + + + Efficient + +
+
+
+Showing 4 of 28 Active Agents +
+ + +
+
+
+
+ +
+ + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/screen.png new file mode 100644 index 0000000..90372f1 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/metrics_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/code.html new file mode 100644 index 0000000..c445ea1 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/code.html @@ -0,0 +1,518 @@ + + + + + +NetBox Integration | LLMNetOps + + + + + + + + + + + + +
+ +
+
+

NetBox Source of Truth

+ +
+dns + +
+ +Connected +
+
+
+
+ + +
+
+ +
+ +
+ +
+
+
+

Managed Devices

+
+ + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Device NameSiteRoleStatusActions
+
+router +KMP-CORE-SW01 +
+
Kampus DC +CORE + + + ACTIVE + + +expand_more +
+
+dns +KMP-DIST-SW02 +
+
Kampus DC +DISTRIBUTION + + + ACTIVE + + +expand_more +
+
+router +IDR-EDGE-01 +
+
IDREN Edge +EDGE + + + OFFLINE + + +expand_more +
+
+
+
+ +
+
+
+
+warning +

Configuration Drift

+
+4 ISSUES +
+
+

Detected mismatches between NetBox (Source of Truth) and live device state.

+ +
+
+KMP-CORE-SW01 +Mismatch +
+
+
description core_link
+
→
+
description UPLINK_...
+
+
+NETBOX +ROUTER +
+
+ +
+
+KMP-DIST-SW02 +Missing +
+
+ VLAN 505 (Guest_Wi-Fi) not found in NetBox +
+
+ +
+
+KMP-CORE-SW01 +Mismatch +
+
+
mtu 1500
+
→
+
mtu 9000
+
+
+
+
+ +
+
+
+ +
+
+
+
+

VLAN Groups & Prefix Management

+

Enterprise global L2 domain tracking

+
+ +
+
+ +
+
+MANAGEMENT +12/32 USED +
+
+
+
+

10

+

Admin_OOB

+
+
+

10.10.10.0/24

+Native +
+
+
+
+

11

+

Loopbacks

+
+
+

10.255.0.0/24

+
+
+
+
+ +
+
+USER_DATA +88/100 USED +
+
+
+
+

100

+

Faculty_Wired

+
+
+

172.16.1.0/24

+
+
+
+
+

200

+

Student_Wired

+
+
+

172.16.2.0/23

+Near Full +
+
+
+
+ +
+
+SERVERS +2/10 USED +
+
+
+
+

50

+

Core_Services

+
+
+

192.168.10.0/24

+
+
+
+add +Add Group +
+
+
+
+
+
+
+
+
+ + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/screen.png new file mode 100644 index 0000000..6209184 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/netbox_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/code.html new file mode 100644 index 0000000..94c0e25 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/code.html @@ -0,0 +1,139 @@ + + + + + +LLMNetOps - Network Monitor + + + + + + + + + + + + + +
+
+LLMNetOps +
+
+ + +
+notifications +
\ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/screen.png new file mode 100644 index 0000000..ed2d0b8 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/network_monitor_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/code.html new file mode 100644 index 0000000..b328cc3 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/code.html @@ -0,0 +1,413 @@ + + + + + +Reports & Backups - LLMNetOps + + + + + + + + + +
+
+LLMNetOps + +
+
+ + +
+
+ + + +
+ +
+
+Archive Explorer + +
+
+ +
+ +chevron_right +folder +Operational Reports + +
+
+description +Weekly_Status_2023_W42.md +
+
+description +Anomaly_Detection_Log.md +
+
+description +Health_Check_Core_A.md +
+
+
+ +
+ +chevron_right +folder +Config Backups + +
+
+ +chevron_right +dns +Core-Switch-01 + +
+
+history 2023-11-01_14-00 +
+
+history 2023-10-25_09-30 +
+
+
+
+ +chevron_right +router +Edge-Router-B + +
+
+history 2023-10-30_12-15 +
+
+
+
+
+
+
+ +
+ +
+
+
+ +description + Anomaly_Detection_Log.md + + +schedule Last updated: 2 hours ago by SystemAgent-04 + +
+
+
+ + +
+ +
+
+ +
+
+ + + +
+
+ +
+ +
+ +

Network Anomaly Detection Report

+
+Critical Alert +Generated: Nov 01, 2023 | Reference: #ANOM-992-B +
+

1. Executive Summary

+

+ During the routine scan at 02:45 UTC, LLMNetOps identified a significant deviation in traffic patterns emanating from Core-Switch-01. The behavioral agent flagged a 400% increase in outbound SSH attempts to external endpoints. Mitigation protocols were automatically engaged at 02:47 UTC. +

+

2. Technical Findings

+
+

Flow Data Excerpt

+
TIMESTAMP | SRC_IP | DST_IP | PORT | BYTES | FLAG
+02:45:12 | 10.0.1.45 | 185.x.x.x | 22 | 4.2MB | SYN
+02:45:13 | 10.0.1.45 | 185.x.x.x | 22 | 4.2MB | SYN
+02:45:14 | 10.0.1.45 | 185.x.x.x | 22 | 4.2MB | SYN
+
+

3. Diff Comparison (Configuration Change)

+

Comparison between v2.1 (Current) and v2.0 (Last Known Good)

+
+
+
V2.0 - STABLE (2023-10-25)
+
V2.1 - ACTIVE (2023-11-01)
+
+
+ +
+
+42 +interface GigabitEthernet0/1 +
+
+43 + description UPLINK-TO-HQ +
+
+- + ip access-group SECURE-IN in +
+
+45 + ip address 10.255.0.1 255.255.255.252 +
+
+ +
+
+42 +interface GigabitEthernet0/1 +
+
+43 + description UPLINK-TO-HQ +
+
++ + ip access-group BYPASS-TEMP in +
+
+45 + ip address 10.255.0.1 255.255.255.252 +
+
+
+
+

4. Remediation Action

+
    +
  • Reverted ip access-group to production baseline.
  • +
  • Quarantined host 10.0.1.45 via LLM Agent port shutdown.
  • +
  • Triggered incident ticket #TKT-8890 in Jira Integration.
  • +
+
+
+Verified Digital Signature +
+verified +SHA256: e3b0c44298fc1c149afbf4c8996fb92427... +
+
+
+ +
+
+
+
+
+
+ +
+ +
+ + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/screen.png new file mode 100644 index 0000000..1439a7a Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/reports_backups_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/code.html new file mode 100644 index 0000000..8acadbd --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/code.html @@ -0,0 +1,519 @@ + + + + + +LLMNetOps - Enterprise Settings + + + + + + + + + +
+
+

LLMNetOps

+ +
+
+ +notifications +account_circle +
+
+ + + +
+
+ +
+
+

System Settings

+

Configure global parameters for autonomous network operations.

+
+
+ + +
+
+ +
+ + + + + +
+ +
+
+
+

Managed Router Hosts

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HostnameManagement IPSSH UserActions
+ +
+ +
+ +
+
+
+
+ + + + +
+
+ + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/screen.png new file mode 100644 index 0000000..828ab8f Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/settings_llmnetops/screen.png differ diff --git a/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/code.html b/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/code.html new file mode 100644 index 0000000..52d0db3 --- /dev/null +++ b/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/code.html @@ -0,0 +1,538 @@ + + + + + +LLMNetOps - Skills Management + + + + + + + + + + + + + + + +
+
+
+search + +
+
+
+ + +
+
+ +
+ +
+
+ +

Skill Inventory

+
+ +
+ +
+
+
+
+pending_actions +

Pending Review 2 NEW

+
+
+
+ +
+
+
+terminal +
+
+

BGP-Session-Reset

+

Automated mitigation for flapping neighbors via LLM-driven adjacency check.

+
+Requested by @agent-alpha +
+
+
+
+ + +
+
+
+
+
+ +
+ + + + + +
+Showing 24 active skills +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Skill NameDomainTrigger KeywordsToolsStatusActions
+
+health_and_safety +network-health-check +
+
+Monitoring + +
+latency +packet-loss +jitter +
+
12 + + ACTIVE + + + + +
+
+dns +dns-reconciliation +
+
+Config + +
+record-mismatch +ttl-fix +
+
4 + + ACTIVE + + + + +
+
+security +acl-threat-isolation +
+
+Security + +
+unauthorized-ip +quarantine +
+
8 + + DRAFT + + + + +
+ +
+
+ + +
+
+ Page 1 of 3 +
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/screen.png b/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/screen.png new file mode 100644 index 0000000..2f11983 Binary files /dev/null and b/docs/stitch_llmnetops_enterprise_console/skills_llmnetops/screen.png differ diff --git a/docs/teaching-log.md b/docs/teaching-log.md index 20cc9e2..d720f40 100644 --- a/docs/teaching-log.md +++ b/docs/teaching-log.md @@ -143,6 +143,76 @@ python tests/eval.py --lab # pakai router nyata (containerlab) --- +## 2026-05-16 — Agent hallucination: format template dicetak verbatim + +**Apa yang gagal:** Output morning-check berisi teks LARANGAN KERAS FORMAT verbatim dan tabel +dengan nilai placeholder seperti `GW-A | 3 | 0 | — | ✅`. Agent juga berhenti setelah +`list_routers()` tanpa memanggil tool berikutnya. + +**Root cause (dua masalah):** +1. **Example contamination** — Format Output section di skill Markdown berisi nilai konkret + (`GW-A | 3 | 0`). Model memperlakukan ini sebagai data aktual dan mencetaknya verbatim. +2. **Premature loop break** — `_react_loop` break ketika LLM menghasilkan non-tool-call response. + Setelah `list_routers()`, model membaca format template dan menghasilkan teks output → + loop berhenti sebelum tool berikutnya dipanggil. + +**Perubahan (3 lapis perlindungan):** +1. Ganti semua nilai konkret di format template dengan `[placeholder]` syntax +2. Hapus blok LARANGAN dari dalam `---` separator (pindah ke Aturan Kritis) +3. Tambah gate transisi eksplisit setelah setiap langkah: + `"→ LANGKAH X SELESAI. JANGAN TULIS APAPUN. LANGSUNG PANGGIL [tool]"` +4. Rule 6 di `_SPECIALIST_SYS`: DILARANG pakai data contoh dari skill sebagai output + +**Hasil:** Agent memanggil semua tool yang dibutuhkan sebelum menulis output. Format template +tidak lagi bocor ke output. + +**Lesson learned:** Format template dengan nilai konkret = jebakan. Selalu gunakan +`[placeholder]` atau `{NAMA_KOLOM}` untuk nilai yang harus diisi dari tool result. + +--- + +## 2026-05-16 — backup-before-write tidak ter-enforce + +**Apa yang gagal:** config_agent memanggil `run_command_write` sebelum `backup_router_config`. +Meskipun instruksi di skill menyebutkan urutan yang benar, LLM tidak selalu mengikutinya. + +**Root cause:** Urutan tool call diserahkan ke LLM decision — tidak ada enforcement di code. +LLM kadang "mengoptimalkan" dengan langsung ke write tanpa backup. + +**Perubahan:** Code-level enforcement di `config_node`: +- `_backed_up_routers: set[str]` per invocation +- `_auto_backup()` inner function yang trigger approval sebelum write pertama ke setiap router +- Jika LLM call backup duluan → ditandai backed up, `_auto_backup` skip +- Jika operator tolak backup → write dibatalkan, ToolMessage berisi "Write dibatalkan" + +**Hasil:** Backup selalu terjadi sebelum write pertama, regardless of LLM tool ordering. + +**Lesson learned:** Safety invariants yang kritis tidak boleh bergantung pada LLM mengikuti +instruksi. Selalu enforce di code level. LLM untuk reasoning, code untuk safety. + +--- + +## 2026-05-16 — Global conduct rules di file Python kritis + +**Apa yang gagal:** Rules format output (simbol status, tabel Markdown, action items) hardcoded +di `_SPECIALIST_SYS` string di `agents/nodes.py`. Untuk update satu rule, harus edit file +Python kritis dan restart. + +**Root cause:** Desain awal tidak memisahkan "conduct rules" dari "node logic". + +**Perubahan:** Extract ke `skills/pedoman-agent.md`: +- `_load_pedoman()` baca + strip YAML frontmatter di startup +- `_SPECIALIST_SYS` pakai `{pedoman}` placeholder +- Kedua `.format()` call (specialist + config_node) pass `pedoman=_PEDOMAN` + +**Hasil:** Ubah perilaku semua agent dengan edit satu Markdown file, restart. `agents/nodes.py` +tidak perlu disentuh untuk perubahan conduct/format. + +**Lesson learned:** Pisahkan "apa yang agent lakukan" (logic di nodes.py) dari "bagaimana agent +berperilaku" (conduct di Markdown). Keduanya berubah dengan frekuensi berbeda. + +--- + ## Catatan Umum — Pola yang Sering Muncul ### Model kecil vs instruksi ambigu diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..957861a --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,23 @@ +# UI: static SPA + nginx reverse proxy to the backends and the manager service. +# nginx's envsubst renders /etc/nginx/templates/*.template at container start, +# so the proxy targets and the Hermes key come from the environment, not the image. +FROM nginx:1.27-alpine + +COPY index.html /usr/share/nginx/html/ +COPY css/ /usr/share/nginx/html/css/ +COPY js/ /usr/share/nginx/html/js/ +COPY assets/ /usr/share/nginx/html/assets/ +COPY fonts/ /usr/share/nginx/html/fonts/ +COPY nginx.conf.template /etc/nginx/templates/default.conf.template +RUN chmod -R a+rX /usr/share/nginx/html /etc/nginx/templates + +# Only these are substituted; nginx's own $uri/$host etc. are left alone. +ENV NGINX_ENVSUBST_FILTER="^(UI_PORT|NETOPS_AGENT_URL|HERMES_URL|MANAGER_URL)$" \ + UI_PORT=3000 \ + NETOPS_AGENT_URL=http://127.0.0.1:8100 \ + HERMES_URL=http://127.0.0.1:8642 \ + MANAGER_URL=http://127.0.0.1:8200 + +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \ + CMD wget -qO /dev/null http://127.0.0.1:${UI_PORT}/ || exit 1 diff --git a/frontend/assets/dashboard-page.png b/frontend/assets/dashboard-page.png new file mode 100644 index 0000000..c0acff2 Binary files /dev/null and b/frontend/assets/dashboard-page.png differ diff --git a/frontend/assets/glyph.svg b/frontend/assets/glyph.svg new file mode 100644 index 0000000..0e55aa3 --- /dev/null +++ b/frontend/assets/glyph.svg @@ -0,0 +1,12 @@ + + + + [ + N + A + ] + + + + + \ No newline at end of file diff --git a/frontend/assets/llmnetops-logo-formal.png b/frontend/assets/llmnetops-logo-formal.png new file mode 100644 index 0000000..fd082b9 Binary files /dev/null and b/frontend/assets/llmnetops-logo-formal.png differ diff --git a/frontend/assets/llmnetops-logo-with-mascot.png b/frontend/assets/llmnetops-logo-with-mascot.png new file mode 100644 index 0000000..e9f18f4 Binary files /dev/null and b/frontend/assets/llmnetops-logo-with-mascot.png differ diff --git a/frontend/assets/llmnetops-mascot-sidebar.png b/frontend/assets/llmnetops-mascot-sidebar.png new file mode 100644 index 0000000..b3d1a3f Binary files /dev/null and b/frontend/assets/llmnetops-mascot-sidebar.png differ diff --git a/frontend/assets/llmnetops-mascot.png b/frontend/assets/llmnetops-mascot.png new file mode 100644 index 0000000..9d9b526 Binary files /dev/null and b/frontend/assets/llmnetops-mascot.png differ diff --git a/frontend/assets/login-page.png b/frontend/assets/login-page.png new file mode 100644 index 0000000..a0abf5a Binary files /dev/null and b/frontend/assets/login-page.png differ diff --git a/frontend/assets/logo.svg b/frontend/assets/logo.svg new file mode 100644 index 0000000..9e7e036 --- /dev/null +++ b/frontend/assets/logo.svg @@ -0,0 +1,9 @@ + + + [ + NetOps + · + AI + ] + + \ No newline at end of file diff --git a/frontend/css/app.css b/frontend/css/app.css new file mode 100644 index 0000000..009cedb --- /dev/null +++ b/frontend/css/app.css @@ -0,0 +1,145 @@ +/* ── Local Fonts ──────────────────────────────────────────────────────────── */ + +@font-face { font-family: 'IBM Plex Sans'; src: url('/fonts/IBMPlexSans-Regular.woff2') format('woff2'); font-weight: 400; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Sans'; src: url('/fonts/IBMPlexSans-Medium.woff2') format('woff2'); font-weight: 500; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Sans Condensed'; src: url('/fonts/IBMPlexSansCondensed-Medium.woff2') format('woff2'); font-weight: 500; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Sans Condensed'; src: url('/fonts/IBMPlexSansCondensed-SemiBold.woff2') format('woff2'); font-weight: 600; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Mono'; src: url('/fonts/IBMPlexMono-Regular.woff2') format('woff2'); font-weight: 400; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Mono'; src: url('/fonts/IBMPlexMono-Medium.woff2') format('woff2'); font-weight: 500; font-style: normal; font-display: swap; } +@font-face { font-family: 'IBM Plex Mono'; src: url('/fonts/IBMPlexMono-SemiBold.woff2') format('woff2'); font-weight: 600; font-style: normal; font-display: swap; } + +/* ── Material Symbols ────────────────────────────────────────────────────── */ + +.material-symbols-outlined { + font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24; + vertical-align: middle; +} + +/* ── Base ─────────────────────────────────────────────────────────────────── */ + +body { + font-family: 'IBM Plex Sans', sans-serif; + background-color: #F5F7FA; +} + +/* ── Scrollbars ──────────────────────────────────────────────────────────── */ + +.sidebar-scroll::-webkit-scrollbar { width: 4px; } +.sidebar-scroll::-webkit-scrollbar-track { background: transparent; } +.sidebar-scroll::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; } + +.chat-scroll::-webkit-scrollbar { width: 6px; } +.chat-scroll::-webkit-scrollbar-track { background: transparent; } +.chat-scroll::-webkit-scrollbar-thumb { background: #c3c6cf; border-radius: 10px; } +.chat-scroll::-webkit-scrollbar-thumb:hover { background: #73777f; } + +/* ── Animations ──────────────────────────────────────────────────────────── */ + +@keyframes bounce-dot { + 0%, 80%, 100% { transform: scale(0); opacity: 0.4; } + 40% { transform: scale(1); opacity: 1; } +} +.bouncing-dot { animation: bounce-dot 1.4s infinite ease-in-out both; } +.bouncing-dot:nth-child(1) { animation-delay: -0.32s; } +.bouncing-dot:nth-child(2) { animation-delay: -0.16s; } + +@keyframes pulse-ring { + 0% { box-shadow: 0 0 0 0 rgba(16,185,129,0.4); } + 70% { box-shadow: 0 0 0 6px rgba(16,185,129,0); } + 100% { box-shadow: 0 0 0 0 rgba(16,185,129,0); } +} +.pulse-green { animation: pulse-ring 1.5s infinite; } + +/* ── Utilities ───────────────────────────────────────────────────────────── */ + +.tabular-nums { font-variant-numeric: tabular-nums; } + +[v-cloak] { display: none; } + +/* ── Markdown (agent chat responses) ─────────────────────────────────────── */ +/* Plain static CSS on purpose — not Tailwind's typography plugin. This + content is (re)injected via innerHTML on every streaming event, and + Tailwind's CDN JIT scanner was observed elsewhere in this app to miss + styles under that kind of churn. */ + +.md > *:first-child { margin-top: 0; } +.md > *:last-child { margin-bottom: 0; } + +.md p { margin: 0 0 10px; } + +.md-h1, .md-h2, .md-h3, .md-h4 { + font-weight: 700; + color: #002444; + margin: 14px 0 6px; + line-height: 1.3; +} +.md-h1 { font-size: 19px; } +.md-h2 { font-size: 16px; } +.md-h3 { font-size: 14.5px; } +.md-h4 { font-size: 14px; } + +.md strong { font-weight: 700; } +.md em { font-style: italic; } + +.md-code { + background: #eceef1; + color: #94492d; + padding: 1px 5px; + border-radius: 4px; + font-family: 'IBM Plex Mono', monospace; + font-size: 0.9em; +} + +.md-pre { + background: #191c1e; + color: #e6e8eb; + padding: 12px; + border-radius: 8px; + overflow-x: auto; + margin: 6px 0 10px; + font-family: 'IBM Plex Mono', monospace; + font-size: 0.85em; + line-height: 1.5; +} +.md-pre code { background: none; padding: 0; color: inherit; } + +.md-ul, .md-ol { margin: 2px 0 10px; padding-left: 22px; } +.md-ul { list-style: disc; } +.md-ol { list-style: decimal; } +.md-ul li, .md-ol li { margin: 3px 0; } + +.md-table-wrap { overflow-x: auto; margin: 6px 0 10px; } +.md-table { border-collapse: collapse; width: 100%; font-size: 0.92em; } +.md-table th, .md-table td { border: 1px solid #c3c6cf; padding: 6px 10px; text-align: left; vertical-align: top; } +.md-table th { background: #eceef1; font-weight: 600; } + +/* Sidebar mascot: static, standing on the divider above the operator block and peeking + out from behind the sidebar's right edge (the vertical line against the content area): + mirrored so the waving arm is on the visible side, leaning toward the edge (head tilted right). The wrapper + clips whatever passes the edge. A soft halo and a thin light edge keep the dark-blue + body readable on navy. Hidden on short viewports so it never crowds the nav. */ +.sidebar-mascot { + display: none; + position: relative; + height: 190px; + margin-bottom: -16px; /* cancels the operator block's mt-4 so the feet meet its divider */ + overflow: hidden; + background: radial-gradient(circle at 78% 60%, rgba(135, 170, 225, 0.28), rgba(135, 170, 225, 0) 60%); +} +@media (min-height: 800px) { .sidebar-mascot { display: block; } } +.mascot-img { + position: absolute; + right: -84px; /* about half the body sits behind the edge; slides out on hover */ + bottom: 0; + height: 185px; + width: auto; + user-select: none; + pointer-events: none; + transform: rotate(-7deg) scaleX(-1); + transform-origin: 50% 100%; + transition: right 0.35s ease; + filter: drop-shadow(0 0 1px rgba(225, 236, 255, 0.95)) drop-shadow(0 0 1px rgba(225, 236, 255, 0.7)) + drop-shadow(0 4px 8px rgba(0, 0, 0, 0.35)); +} +.sidebar-mascot:hover .mascot-img { right: 24px; } /* hovering the strip slides it fully into view, to the left */ +@media (prefers-reduced-motion: reduce) { .mascot-img { transition: none; } } diff --git a/frontend/fonts/IBMPlexMono-Medium.woff2 b/frontend/fonts/IBMPlexMono-Medium.woff2 new file mode 100644 index 0000000..99c2610 Binary files /dev/null and b/frontend/fonts/IBMPlexMono-Medium.woff2 differ diff --git a/frontend/fonts/IBMPlexMono-Regular.woff2 b/frontend/fonts/IBMPlexMono-Regular.woff2 new file mode 100644 index 0000000..a6c77d6 Binary files /dev/null and b/frontend/fonts/IBMPlexMono-Regular.woff2 differ diff --git a/frontend/fonts/IBMPlexMono-SemiBold.woff2 b/frontend/fonts/IBMPlexMono-SemiBold.woff2 new file mode 100644 index 0000000..59e4f52 Binary files /dev/null and b/frontend/fonts/IBMPlexMono-SemiBold.woff2 differ diff --git a/frontend/fonts/IBMPlexSans-Medium.woff2 b/frontend/fonts/IBMPlexSans-Medium.woff2 new file mode 100644 index 0000000..adbbd4c Binary files /dev/null and b/frontend/fonts/IBMPlexSans-Medium.woff2 differ diff --git a/frontend/fonts/IBMPlexSans-Regular.woff2 b/frontend/fonts/IBMPlexSans-Regular.woff2 new file mode 100644 index 0000000..93bcd64 Binary files /dev/null and b/frontend/fonts/IBMPlexSans-Regular.woff2 differ diff --git a/frontend/fonts/IBMPlexSansCondensed-Medium.woff2 b/frontend/fonts/IBMPlexSansCondensed-Medium.woff2 new file mode 100644 index 0000000..e615a8f Binary files /dev/null and b/frontend/fonts/IBMPlexSansCondensed-Medium.woff2 differ diff --git a/frontend/fonts/IBMPlexSansCondensed-SemiBold.woff2 b/frontend/fonts/IBMPlexSansCondensed-SemiBold.woff2 new file mode 100644 index 0000000..e8b6d8f Binary files /dev/null and b/frontend/fonts/IBMPlexSansCondensed-SemiBold.woff2 differ diff --git a/frontend/index.html b/frontend/index.html index 8d44d0a..a5f7505 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -1,1231 +1,59 @@ - - -NetOps AI — Campus Network Operations - - - - - -
- - -
- -
-
Campus Network Operations
-
-
-
-
- IDLE -
-
-
--:--:--
-
-
- - -
- - - - - -
- - -
-
-
Dashboard
-
-
-
-
Agent
-
Model—
-
Skills—
-
Ollama—
-
-
-
Infrastruktur
-
config.yaml✓ ada
-
Routers—
-
Backups—
-
-
-
Laporan Terbaru
-
—
-
-
-
-
- - -
-
-
Skills
-
-
-
-
- - -
-
-
Reachability
-
- - - -
RouterHostStatusRTT
- -
-
- - -
-
-
Laporan
-
-
-
-
- - -
-
-
Log
-
-
-
-
- - -
-
-
-
◈
-
NetOps AI
-
Ketik perintah untuk memulai sesi operasional jaringan kampus.
-
-
-
-
- › - - -
-
[Enter] Kirim · [Ctrl+L] Hapus chat · [1-9] Pindah layar
-
-
- - -
-
-
Aktivitas Agent
-
-
-
Belum ada aktivitas. Gunakan AI Chat untuk memulai.
-
-
-
- - -
-
-
Status Agent
-
-
Kanban board — aktif saat AI Chat berjalan. Lihat panel kanan untuk status real-time.
-
-
- - -
-
-
Token Metrics
-
- - - - - - - -
AgentCallsctx%pred%tps⚠
- Belum ada data — gunakan AI Chat untuk merekam metrics. -
-
-
- -
- - - - -
- - -
-
- CTX -
- 0% -
-
-
- PRED -
- 0% -
-
-
- TOOLS - 0 -
-
-
- TIME - ──:── -
-
-
-
- IDLE -
-
-
- [1-9]Menu [Enter]Kirim [Ctrl+L]Clear -
-
- -
- - -
-
-
⚠  Konfirmasi Aksi Agent
-
Agent—
-
Aksi—
-
RisikoMEDIUM
-
- - -
-
-
- + + +LLMNetOps - Enterprise Console + + + + + + +
+ diff --git a/frontend/js/app.js b/frontend/js/app.js new file mode 100644 index 0000000..a5888c0 --- /dev/null +++ b/frontend/js/app.js @@ -0,0 +1,82 @@ +import { S } from './state.js'; +import { renderShell, renderNav } from './shell.js'; +import { $ } from './utils.js'; +import { NAV_ITEMS } from './config.js'; +import { mgr } from './manager.js'; +import { renderLogin } from './screens/login.js'; + +import { screenDashboard } from './screens/dashboard.js'; +import { screenChat, chatUnmount } from './screens/chat.js'; +import { screenNodes } from './screens/nodes.js'; +import { screenSkills } from './screens/skills.js'; +import { screenAgents } from './screens/agents.js'; +import { screenSettings } from './screens/settings.js'; +import { screenAbout } from './screens/about.js'; +import { screenUnavailable } from './screens/unavailable.js'; + +let _currentUnmount = null; + +async function navigate(screenId, param) { + if (_currentUnmount) { _currentUnmount(); _currentUnmount = null; } + + S.screen = screenId; + renderNav(); + // The chat screen fills the viewport height, and About already carries this info. + document.getElementById('app-footer')?.classList.toggle('hidden', screenId === 'chat' || screenId === 'about'); + + const item = NAV_ITEMS.find(n => n.id === screenId); + const breadcrumb = document.getElementById('breadcrumb-page'); + if (breadcrumb) breadcrumb.textContent = item ? item.label : screenId; + + const c = $('screen-container'); + if (!c) return; + + c.innerHTML = ''; + + if (!item) { location.hash = 'dashboard'; return; } // unknown/removed route + if (item.unavailable) { + screenUnavailable(c, screenId); + return; + } + + switch (screenId) { + case 'dashboard': await screenDashboard(c); break; + case 'chat': + await screenChat(c, param); + _currentUnmount = chatUnmount; + break; + case 'nodes': await screenNodes(c); break; + case 'skills': await screenSkills(c); break; + case 'agents': await screenAgents(c); break; + case 'settings': await screenSettings(c); break; + case 'about': screenAbout(c); break; + default: screenUnavailable(c, screenId); break; + } +} + +function onHash() { + const raw = location.hash.slice(1) || 'dashboard'; + const [id, ...rest] = raw.split('/'); + navigate(id, rest.length ? decodeURIComponent(rest.join('/')) : undefined); +} + +function startApp(user) { + S.user = user.username; + renderShell(); + onHash(); + window.addEventListener('hashchange', onHash); + // The session ended while the app was open: a reload lands on the login form. + window.addEventListener('auth-expired', () => location.reload(), { once: true }); +} + +async function boot() { + try { + startApp(await mgr('/auth/me')); + } catch (e) { + // 401 = not logged in. Anything else (manager down) also lands on the form, + // where the login attempt shows the error. + renderLogin(startApp, e.status === 401 ? '' : e.message); + } +} + +boot(); diff --git a/frontend/js/backends/common.js b/frontend/js/backends/common.js new file mode 100644 index 0000000..0c7fea8 --- /dev/null +++ b/frontend/js/backends/common.js @@ -0,0 +1,102 @@ +// Shared HTTP/SSE helpers for the backend adapters. Every backend is reached +// through the nginx proxy under /backend// (see nginx.conf.template), so +// the browser never talks to the backends directly and never holds an API key. + +export class HttpError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +export async function http(base, path, { method = 'GET', body, signal } = {}) { + const init = { method, signal, headers: {} }; + if (body !== undefined) { + init.headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(body); + } + const r = await fetch(base + path, init); + if (!r.ok) throw new HttpError(r.status, `HTTP ${r.status} ${path}: ${await errorDetail(r)}`); + if (r.status === 204) return null; + const text = await r.text(); + return text ? JSON.parse(text) : null; +} + +async function errorDetail(r) { + const text = await r.text().catch(() => ''); + try { + const j = JSON.parse(text); + // FastAPI validation errors: detail is a list of { loc, msg }. + if (Array.isArray(j.detail)) return j.detail.map(d => `${(d.loc || []).slice(1).join('.')}: ${d.msg}`).join('; '); + return j.detail || j.error?.message || j.error || j.message || text; + } catch { + return text || r.statusText; + } +} + +export async function ensureOk(r, path) { + if (!r.ok) throw new HttpError(r.status, `HTTP ${r.status} ${path}: ${await errorDetail(r)}`); + return r; +} + +// Parses a text/event-stream body. Calls onFrame({ event, data }) per frame, +// where `data` is the parsed JSON payload (or the raw string when it is not +// JSON). Comment frames (": ping", ": keepalive") are skipped. +export async function readSSE(response, onFrame) { + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buf = ''; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + const frames = buf.split(/\r?\n\r?\n/); + buf = frames.pop(); + for (const frame of frames) dispatchFrame(frame, onFrame); + } + if (buf.trim()) dispatchFrame(buf, onFrame); +} + +function dispatchFrame(frame, onFrame) { + let event = null; + const dataLines = []; + for (const line of frame.split(/\r?\n/)) { + if (!line || line.startsWith(':')) continue; + if (line.startsWith('event:')) event = line.slice(6).trim(); + else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, '')); + } + if (!dataLines.length) return; + const raw = dataLines.join('\n'); + let data = raw; + try { data = JSON.parse(raw); } catch { /* keep raw string */ } + onFrame({ event, data }); +} + +// Unix seconds (float) / milliseconds / ISO string → Date (null when unusable). +export function toDate(v) { + if (v == null || v === '') return null; + if (typeof v === 'number') return new Date(v < 1e12 ? v * 1000 : v); + const d = new Date(v); + return isNaN(d) ? null : d; +} + +// Message content may be a plain string or an OpenAI-style parts array. +export function contentText(content) { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content.map(p => (typeof p === 'string' ? p : p?.text || '')).filter(Boolean).join('\n'); + } + return ''; +} + +// crypto.randomUUID() only exists in secure contexts (HTTPS or localhost); the +// console is normally served over plain http://:3000, where it is +// undefined. getRandomValues() is available everywhere. +export function uuid() { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + const b = crypto.getRandomValues(new Uint8Array(16)); + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + const h = [...b].map(x => x.toString(16).padStart(2, '0')).join(''); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; +} diff --git a/frontend/js/backends/hermes.js b/frontend/js/backends/hermes.js new file mode 100644 index 0000000..7f4c1e0 --- /dev/null +++ b/frontend/js/backends/hermes.js @@ -0,0 +1,194 @@ +// Hermes adapter (hermes-agent gateway, platform `api_server`). +// +// Threads are Hermes sessions (/api/sessions), persisted server-side. Each +// turn is a run: POST /v1/runs starts it bound to the session, then +// GET /v1/runs/{id}/events streams lifecycle events. The runs API (rather than +// /api/sessions/{id}/chat/stream) is used because only runs emit +// `approval.request` and accept /approval and /stop. +// +// The API key (API_SERVER_KEY) is kept in the manager's database and injected by +// the nginx proxy (auth_request) — never here, and not in an environment variable. +import { http, ensureOk, readSSE, toDate, contentText, uuid } from './common.js'; +import { mgr, getActiveProfile } from '../manager.js'; + +const BASE = '/backend/hermes'; +const _runs = {}; // threadId → run_id of the in-flight run + +function summary(s) { + const created = toDate(s.started_at) || new Date(); + return { + id: s.id, + title: s.title || s.preview || 'New Chat', + createdAt: created, + updatedAt: toDate(s.last_active) || created, + lastMessage: s.preview || '', + }; +} + +export const hermes = { + id: 'hermes', + label: 'Hermes Agent', + shortLabel: 'Hermes', + description: 'Agent Hermes (NousResearch) lewat gateway api_server: session tersimpan di server, approval command berisiko, stop, dan skills.', + capabilities: { + approval: true, + stop: 'interrupt', + serverThreads: true, + credential: true, // needs an API key, managed in Settings > Backend + jobs: true, // scheduled (cron) jobs via /api/jobs + }, + + // Cron jobs: agent runs on a schedule. Fields used by the dashboard: + // id, name, schedule_display, state, enabled, last_run_at, next_run_at, last_status, last_error. + async listJobs() { + const r = await http(BASE, '/api/jobs?include_disabled=true'); + return r?.jobs || []; + }, + + async runJob(id) { + await http(BASE, `/api/jobs/${encodeURIComponent(id)}/run`, { method: 'POST' }); + }, + + async pauseJob(id) { + await http(BASE, `/api/jobs/${encodeURIComponent(id)}/pause`, { method: 'POST' }); + }, + + async resumeJob(id) { + await http(BASE, `/api/jobs/${encodeURIComponent(id)}/resume`, { method: 'POST' }); + }, + + async health() { + const h = await http(BASE, '/health'); + let model = '—'; + try { + const m = await http(BASE, '/v1/models'); + model = m?.data?.[0]?.id || model; + } catch { /* /health is enough to call it reachable */ } + return { ok: h?.status === 'ok', model, detail: h?.version ? `hermes-agent ${h.version}` : '' }; + }, + + async listThreads() { + const r = await http(BASE, '/api/sessions?limit=50&source=api_server'); + return (r?.data || []).map(summary); + }, + + async createThread() { + const r = await http(BASE, '/api/sessions', { method: 'POST', body: { id: uuid() } }); + return summary(r.session); + }, + + async loadMessages(id) { + const r = await http(BASE, `/api/sessions/${encodeURIComponent(id)}/messages`); + return (r?.data || []) + .filter(m => m.role === 'user' || m.role === 'assistant') + .map(m => ({ role: m.role === 'assistant' ? 'agent' : 'user', content: contentText(m.content) })) + .filter(m => m.content); + }, + + async renameThread(id, title) { + await http(BASE, `/api/sessions/${encodeURIComponent(id)}`, { method: 'PATCH', body: { title } }); + }, + + async deleteThread(id) { + await http(BASE, `/api/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' }); + }, + + async send(threadId, text, emit) { + const body = { input: text, session_id: threadId }; + const slug = getActiveProfile(); + if (slug) { + // The profile prompt rides along as the run's ephemeral system prompt. + try { body.instructions = (await mgr('/profiles/' + encodeURIComponent(slug))).prompt; } + catch (e) { emit({ type: 'note', text: `Profil "${slug}" tidak dimuat (${e.message}); dijalankan tanpa profil.` }); } + } + const start = await http(BASE, '/v1/runs', { method: 'POST', body }); + const runId = start.run_id; + _runs[threadId] = runId; + let streamed = false; + try { + const r = await fetch(`${BASE}/v1/runs/${encodeURIComponent(runId)}/events`); + await ensureOk(r, '/v1/runs/{id}/events'); + await readSSE(r, ({ data: ev }) => { + if (!ev || typeof ev !== 'object') return; + switch (ev.event) { + case 'message.delta': + streamed = true; + emit({ type: 'delta', text: ev.delta || '' }); + break; + case 'message.interim': + emit({ type: 'note', text: ev.text || '' }); + break; + case 'reasoning.available': + if (ev.text) emit({ type: 'thinking', text: ev.text }); + break; + case 'tool.started': + emit({ type: 'tool_start', name: ev.tool, detail: ev.preview || '' }); + break; + case 'tool.completed': + emit({ + type: 'tool_end', name: ev.tool, detail: ev.preview || '', + durationMs: (ev.duration || 0) * 1000, error: !!ev.error, + }); + break; + case 'subagent.start': + case 'subagent.complete': + emit({ type: 'note', text: `${ev.event}${ev.preview ? ': ' + ev.preview : ''}` }); + break; + case 'approval.request': + emit({ + type: 'approval', + data: { + action: ev.command || ev.description || '—', + description: ev.description || '', + choices: ev.choices || ['once', 'deny'], + requestId: ev.request_id || null, + }, + }); + break; + case 'approval.responded': + emit({ type: 'note', text: `Approval: ${ev.choice}` }); + break; + case 'run.completed': + // Deltas already carried the text; `output` is the fallback when + // the provider did not stream. + if (!streamed && ev.output) emit({ type: 'delta', text: ev.output }); + break; + case 'run.failed': + emit({ type: 'error', text: ev.error || 'Run gagal' }); + break; + case 'run.cancelled': + case 'run.interrupted': + emit({ type: 'stopped', text: ev.error || 'Run dihentikan.' }); + break; + } + }); + } finally { + delete _runs[threadId]; + } + }, + + async stop(threadId) { + const runId = _runs[threadId]; + if (!runId) return { ok: false }; + await http(BASE, `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: 'POST', body: {} }); + return { ok: true }; + }, + + // choice: 'once' | 'session' | 'always' | 'deny' + async respondApproval(threadId, choice, requestId) { + const runId = _runs[threadId]; + if (!runId) throw new Error('Tidak ada run aktif'); + const body = { choice }; + if (requestId) body.request_id = requestId; + await http(BASE, `/v1/runs/${encodeURIComponent(runId)}/approval`, { method: 'POST', body }); + }, + + async listSkills() { + const r = await http(BASE, '/v1/skills'); + return (r?.data || []).map(s => ({ + name: s.name, + description: s.description || '', + tags: s.category ? [s.category] : [], + })); + }, +}; diff --git a/frontend/js/backends/index.js b/frontend/js/backends/index.js new file mode 100644 index 0000000..923c16a --- /dev/null +++ b/frontend/js/backends/index.js @@ -0,0 +1,54 @@ +// Backend registry. Exactly one backend is active at a time for the whole UI; +// the choice is made on the Settings screen and remembered per browser. +// +// Adapter contract (see netops.js / hermes.js): +// id, label, shortLabel, description, capabilities { approval, stop, serverThreads, credential } +// health() → { ok, model, detail } +// listThreads() → [{ id, title, createdAt, updatedAt, lastMessage }] +// createThread() → thread summary +// loadMessages(id) → [{ role: 'user' | 'agent', content }] +// renameThread(id, title), deleteThread(id) +// send(threadId, text, emit) → resolves when the turn ends; emit(event) with +// { type: 'delta', text } | { type: 'tool_start', name, detail } +// { type: 'tool_end', name, detail, durationMs, error } +// { type: 'note' | 'thinking' | 'error' | 'stopped', text } +// { type: 'approval', data: { action, description, choices, requestId } } +// stop(threadId) → { ok } +// respondApproval(threadId, choice, requestId) (only when capabilities.approval) +// listSkills() → [{ name, description, tags }] +// listJobs() / runJob(id) / pauseJob(id) / resumeJob(id) (only when capabilities.jobs) +// listActivity(limit) → [{ at, message, toolCalls, errors, timeouts, durationS }] (only when capabilities.activity) +// listDevices() → [{name, mgmt_ip, …}] (only when capabilities.devices) +// addDevice(device) → registered device (only when capabilities.devices) +// updateDevice(name, device) → updated device (only when capabilities.devices) +// deleteDevice(name) → void (only when capabilities.devices) +import { netops } from './netops.js'; +import { hermes } from './hermes.js'; + +export const BACKENDS = { netops, hermes }; + +const STORAGE_KEY = 'llmnetops-backend'; +const DEFAULT_BACKEND = 'netops'; + +function readChoice() { + try { + let v = localStorage.getItem(STORAGE_KEY); + if (v === 'palapa') v = 'netops'; // id used before the rename + return BACKENDS[v] ? v : DEFAULT_BACKEND; + } catch { + return DEFAULT_BACKEND; + } +} + +let _activeId = readChoice(); + +export function activeBackend() { + return BACKENDS[_activeId]; +} + +export function setActiveBackend(id) { + if (!BACKENDS[id]) throw new Error(`Backend tidak dikenal: ${id}`); + _activeId = id; + try { localStorage.setItem(STORAGE_KEY, id); } catch { /* per-session only */ } + window.dispatchEvent(new CustomEvent('backend-changed', { detail: { id } })); +} diff --git a/frontend/js/backends/netops.js b/frontend/js/backends/netops.js new file mode 100644 index 0000000..5d7f1a0 --- /dev/null +++ b/frontend/js/backends/netops.js @@ -0,0 +1,171 @@ +// NetOps Agent adapter (the palapa-agent REST API, palapa/gateway/api.py). +// +// NetOps Agent's POST /chat is stateless: the client sends the whole conversation +// every turn and nothing is persisted per thread by the agent. Threads and their +// messages are therefore stored by the NetOpsUI manager (/api/threads), so every +// operator sees the same list. The manager also makes the /chat call itself +// (server/runs.py), so a run and its saved answer survive a page refresh. +// NetOps Agent has no approval flow (its network tools are read-only) and no stop +// endpoint — Stop only cuts the manager's stream; the agent loop on the server +// keeps running until it finishes on its own. +import { http, ensureOk, readSSE, uuid, toDate } from './common.js'; +import { mgr } from '../manager.js'; + +const BASE = '/backend/netops'; +const LEGACY_KEYS = ['llmnetops-netops-threads-v1', 'llmnetops-palapa-threads-v1']; // browser-only storage used before +const IMPORTED_KEY = 'llmnetops-netops-threads-imported'; +const CLIENT_KEY = 'llmnetops-client-name'; + +const _controllers = {}; // threadId → AbortController of the in-flight /chat + +// Label shown next to a thread so operators can tell whose chat it is. +function clientName() { + try { + let n = localStorage.getItem(CLIENT_KEY); + if (!n) { n = 'user-' + uuid().slice(0, 4); localStorage.setItem(CLIENT_KEY, n); } + return n; + } catch { return ''; } +} + +function summary(t) { + return { + id: t.id, + title: t.title, + createdAt: new Date(t.created_at), + updatedAt: new Date(t.updated_at), + lastMessage: t.last_message || '', + owner: t.owner || '', + running: !!t.running, + }; +} + +// One-time move of this browser's old localStorage threads to the server. +async function importLegacy() { + try { + if (localStorage.getItem(IMPORTED_KEY)) return; + const raw = LEGACY_KEYS.map(k => localStorage.getItem(k)).find(Boolean); + const threads = raw ? Object.values(JSON.parse(raw) || {}) : []; + if (threads.length) await mgr('/threads/import', { method: 'POST', body: { backend: 'netops', client: clientName(), threads } }); + localStorage.setItem(IMPORTED_KEY, '1'); + } catch { /* retried on the next list */ } +} + +export const netops = { + id: 'netops', + label: 'NetOps Agent', + shortLabel: 'NetOps Agent', + description: 'Agent lokal berbasis Ollama dengan network tools read-only (Netmiko), skills, dan delegasi ke child agent.', + capabilities: { + approval: false, + stop: 'abort', // only cuts the stream; the server-side run is not interrupted + resume: true, // a running thread can be re-attached (refresh, other operator) + serverThreads: true, // threads are stored by the manager, shared by all operators + devices: true, // GET/POST /devices list and register nodes update and delete them + activity: true, // GET /turns: per-turn tool calls, errors, timeouts + }, + + // Recent agent turns from the trace store, newest first. + async listActivity(limit = 100) { + const rows = (await http(BASE, `/turns?limit=${limit}`)) || []; + return rows.map(t => ({ + sessionId: t.session_id, + at: toDate(t.timestamp), + message: t.user_message || '', + toolCalls: t.tool_call_count || 0, + errors: t.error_count || 0, + timeouts: t.timeout_count || 0, + durationS: t.tool_duration_s || 0, + })).sort((a, b) => (b.at || 0) - (a.at || 0)); + }, + + async health() { + const h = await http(BASE, '/health'); + return { ok: h?.status === 'ok', model: h?.model || '—', detail: h?.base_url || '' }; + }, + + async listThreads() { + await importLegacy(); + return (await mgr('/threads?backend=netops')).threads.map(summary); + }, + + async createThread() { + return summary(await mgr('/threads', { method: 'POST', body: { id: uuid(), backend: 'netops', client: clientName() } })); + }, + + async loadMessages(id) { + return (await mgr(`/threads/${encodeURIComponent(id)}/messages`)).messages.map(m => ({ role: m.role, content: m.content, ts: new Date(m.created_at) })); + }, + + async renameThread(id, title) { + await mgr(`/threads/${encodeURIComponent(id)}`, { method: 'PATCH', body: { title } }); + }, + + async deleteThread(id) { + await mgr(`/threads/${encodeURIComponent(id)}`, { method: 'DELETE' }); + }, + + // The manager makes the /chat call and stores the answer, so a page refresh + // cannot lose it; the browser only watches the run's event stream. + async send(threadId, text, emit) { + await mgr(`/threads/${encodeURIComponent(threadId)}/run`, { method: 'POST', body: { text } }); + await this.resume(threadId, emit); + }, + + // Follows the thread's run from its first event (also used to re-attach after a refresh). + async resume(threadId, emit) { + const controller = new AbortController(); + _controllers[threadId] = controller; + try { + const r = await fetch(`/api/threads/${encodeURIComponent(threadId)}/events`, { signal: controller.signal }); + await ensureOk(r, '/events'); + await readSSE(r, ({ data }) => { + if (!data || typeof data !== 'object' || data.type === 'done') return; + emit(data); + }); + } catch (e) { + if (e.name !== 'AbortError') throw e; + } finally { + delete _controllers[threadId]; + } + }, + + // Stops following a run without stopping it: the manager keeps the run going and + // stores its answer, so the operator can leave the thread and re-attach later. + detach(threadId) { + _controllers[threadId]?.abort(); + }, + + async stop(threadId) { + try { return await mgr(`/threads/${encodeURIComponent(threadId)}/stop`, { method: 'POST' }); } + catch { return { ok: false }; } + }, + + // Registers a device/node. Credentials in `device` go straight to the agent; + // the response never echoes username/password back. + async addDevice(device) { + return http(BASE, '/devices', { method: 'POST', body: device }); + }, + + async listDevices() { + return (await http(BASE, '/devices')) || []; + }, + + // PATCH /devices/{name}: partial update, omitted fields stay unchanged. `name` in + // the URL is the fixed identifier (a `name` in the body is ignored). username and + // password must come together or not at all (400). 404 unknown name, 400 duplicate + // names. The response never carries credentials. + async updateDevice(name, device) { + return http(BASE, '/devices/' + encodeURIComponent(name), { method: 'PATCH', body: device }); + }, + + // DELETE /devices/{name}: removes the node from inventory.yaml (404 unknown name, + // 400 duplicate names). Credentials in ~/.palapa/.env are left untouched. + async deleteDevice(name) { + return http(BASE, '/devices/' + encodeURIComponent(name), { method: 'DELETE' }); + }, + + async listSkills() { + const rows = await http(BASE, '/skills'); + return (rows || []).map(s => ({ name: s.name, description: s.description || '', tags: s.tags || [] })); + }, +}; diff --git a/frontend/js/config.js b/frontend/js/config.js new file mode 100644 index 0000000..cc44d2f --- /dev/null +++ b/frontend/js/config.js @@ -0,0 +1,22 @@ +// Consecutive items sharing the same `group` are rendered together under a +// section header in the sidebar (see shell.js renderNav()); items without a +// `group` render at the root with no header. Order here is display order. +// `unavailable` marks screens whose data lived in the old monolithic backend +// and has no counterpart in NetOps Agent or Hermes yet — they stay in the nav +// but render the "Belum tersedia" placeholder (screens/unavailable.js). +// Skills and Agents are managed by NetOpsUI's own service (server/), not by +// the backends. +export const NAV_ITEMS = [ + { id:'dashboard', label:'Dashboard', icon:'dashboard' }, + { id:'chat', label:'AI Chat', icon:'chat_bubble' }, + { id:'nodes', label:'Nodes', icon:'dns', group:'Infrastructure' }, + { id:'skills', label:'Skills', icon:'psychology', group:'Agent Platform' }, + // Agents (screens/agents.js) hidden for now: no use case yet. Uncomment to bring it back; + // while absent, #agents redirects to the dashboard. + // { id:'agents', label:'Agents', icon:'smart_toy', group:'Agent Platform' }, + // Backups and Metrics (Insights) hidden for now, same as Agents. + // { id:'backups', label:'Backups', icon:'backup', group:'Insights', unavailable:true }, + // { id:'metrics', label:'Metrics', icon:'insights', group:'Insights', unavailable:true }, + { id:'settings', label:'Settings', icon:'settings' }, + { id:'about', label:'About', icon:'info' }, +]; diff --git a/frontend/js/manager.js b/frontend/js/manager.js new file mode 100644 index 0000000..5a5c25f --- /dev/null +++ b/frontend/js/manager.js @@ -0,0 +1,38 @@ +// Client for the NetOpsUI management service (server/), reached at /api/ via +// nginx. It owns skills, agent profiles and the read-only views of each +// backend's config files — things NetOps Agent and Hermes have no API for. +import { HttpError } from './backends/common.js'; + +export async function mgr(path, { method = 'GET', body } = {}) { + const init = { method, headers: {} }; + if (body !== undefined) { + init.headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(body); + } + const r = await fetch('/api' + path, init); + const text = await r.text(); + let data = null; + try { data = text ? JSON.parse(text) : null; } catch { /* non-JSON error page from the proxy */ } + // Session ended (expired, or the user was reset). The /auth/ calls report their own 401. + if (r.status === 401 && !path.startsWith('/auth/')) window.dispatchEvent(new Event('auth-expired')); + if (!r.ok) { + const detail = data?.detail; + const msg = typeof detail === 'string' ? detail : Array.isArray(detail) ? detail.map(d => d.msg).join('; ') + : r.status === 502 || r.status === 504 ? 'Manager service tidak terjangkau' : text || r.statusText; + throw new HttpError(r.status, msg); + } + return data; +} + +// Agent profile chosen for Hermes chats (NetOps Agent takes its persona from SOUL.md). +const PROFILE_KEY = 'llmnetops-hermes-profile'; + +export function getActiveProfile() { + try { return localStorage.getItem(PROFILE_KEY) || null; } catch { return null; } +} + +export function setActiveProfile(slug) { + try { + if (slug) localStorage.setItem(PROFILE_KEY, slug); else localStorage.removeItem(PROFILE_KEY); + } catch { /* per-session only */ } +} diff --git a/frontend/js/screens/about.js b/frontend/js/screens/about.js new file mode 100644 index 0000000..09bd96d --- /dev/null +++ b/frontend/js/screens/about.js @@ -0,0 +1,61 @@ +import { cardHtml, pageHeader } from '../utils.js'; + +const CONTACT_EMAIL = 'llmnetops@ub.ac.id'; + +const LINKS = [ + { href: 'https://llmnetops.github.io/', label: 'llmnetops.github.io', note: 'Situs proyek LLMNetOps', icon: 'language' }, + { href: 'https://apnic.foundation/projects/llmnetops/', label: 'apnic.foundation/projects/llmnetops', note: 'Halaman proyek di APNIC Foundation', icon: 'open_in_new' }, +]; + +function fact(label, value) { + return `
+
${label}
+
${value}
+
`; +} + +function linkRow(l) { + return ` + ${l.icon} + + ${l.label} + ${l.note} + + `; +} + +export function screenAbout(c) { + c.innerHTML = `
+ ${pageHeader('About', 'Tentang proyek LLMNetOps dan pendanaannya.')} +
+ ${cardHtml('LLMNetOps', ` +

+ LLMNetOps — Strengthening network operations knowledge through locally-hosted generative AI. + Proyek ini membantu institusi anggota IDREN mengadopsi Large Language Model (LLM) open-source yang dijalankan + secara lokal dan mengutamakan privasi, untuk pengelolaan jaringan dan dokumentasinya. + Konsol ini adalah antarmuka operator untuk agent jaringan yang dikembangkan dalam proyek tersebut. +

+
    +
  • Memperkenalkan AI kontekstual untuk operasi infrastruktur jaringan.
  • +
  • Mendorong adopsi AI yang mengutamakan privasi lewat model open-source yang di-host sendiri.
  • +
  • Menjembatani kesenjangan literasi AI bagi staf jaringan.
  • +
  • Membangun komunitas berbagi pengetahuan lewat workshop dan kolaborasi antar-peer.
  • +
`)} + ${cardHtml('Pendanaan', ` +

+ Proyek ini merupakan hibah ISIF Asia dan mendapat dukungan dari APNIC Foundation. +

+
+ ${fact('Program hibah', 'ISIF Asia Grants')} + ${fact('Tahun', '2025')} + ${fact('Pelaksana', 'Universitas Brawijaya, Indonesia')} + ${fact('Mitra', 'IDREN')} +
`)} + ${cardHtml('Informasi lebih lanjut', `
${LINKS.map(linkRow).join('')}
+

+ Kontak: + ${CONTACT_EMAIL} +

`)} +
+
`; +} diff --git a/frontend/js/screens/agents.js b/frontend/js/screens/agents.js new file mode 100644 index 0000000..20657a4 --- /dev/null +++ b/frontend/js/screens/agents.js @@ -0,0 +1,119 @@ +import { $, esc, badge, pageHeader, loadingHtml, errorHtml, confirmDialog, alertDialog } from '../utils.js'; +import { mgr, getActiveProfile, setActiveProfile } from '../manager.js'; + +const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; + +// Agent profiles = named system prompts kept in NetOpsUI's DB. +// - Hermes: the active profile is sent with every chat run as `instructions`. +// - NetOps Agent: has no per-request prompt; a profile can be applied to its +// SOUL.md (persona file), which replaces the file (old one is backed up). +export async function screenAgents(c) { + let profiles = [], selected = null, isNew = false; + + c.innerHTML = `
+ ${pageHeader('Agents', 'Profil agent (prompt) yang dikelola di NetOpsUI. Dipakai per-chat di Hermes, atau diterapkan ke SOUL.md NetOps Agent.', ` + `)} +
+
+
+
${loadingHtml('Memuat...')}
+
+
+
+
+
`; + + function renderList() { + const active = getActiveProfile(); + $('ag-list').innerHTML = profiles.length ? profiles.map(p => ` + `).join('') : `

Belum ada profil.

`; + $('ag-list').querySelectorAll('[data-slug]').forEach(b => { b.onclick = () => select(b.dataset.slug); }); + } + + function renderEditor() { + const el = $('ag-editor'); + if (!isNew && !selected) { + el.innerHTML = `
Pilih profil di kiri, atau buat profil baru.
`; + return; + } + const p = isNew ? { slug: '', name: '', description: '', prompt: '' } : profiles.find(x => x.slug === selected); + if (!p) { el.innerHTML = ''; return; } + const isActive = getActiveProfile() === p.slug; + el.innerHTML = `
+

${isNew ? 'Profil Baru' : esc(p.name)}

+
+
+ + +
+ + +
+
+ + ${isNew ? '' : ` + + + + `} +
+
+
`; + $('g-save').onclick = save; + if ($('g-use')) $('g-use').onclick = () => { setActiveProfile(isActive ? null : p.slug); renderList(); renderEditor(); }; + if ($('g-soul')) $('g-soul').onclick = applySoul; + if ($('g-delete')) $('g-delete').onclick = del; + } + + const form = () => ({ slug: $('g-slug').value.trim(), name: $('g-name').value.trim(), description: $('g-desc').value.trim(), prompt: $('g-prompt').value }); + + async function save() { + const f = form(), err = $('g-err'); + if (!f.name) { err.textContent = 'Nama wajib diisi.'; return; } + if (isNew && !SLUG_RE.test(f.slug)) { err.textContent = 'Slug harus huruf kecil/angka/strip, maksimal 64 karakter.'; return; } + try { + const saved = isNew ? await mgr('/profiles', { method: 'POST', body: f }) : await mgr('/profiles/' + f.slug, { method: 'PUT', body: f }); + isNew = false; await load(); select(saved.slug); + } catch (e) { err.textContent = e.message; } + } + + async function applySoul() { + const cur = await mgr('/backends/netops/soul').catch(() => null); + const ok = await confirmDialog({ + title: 'Timpa SOUL.md NetOps Agent?', + message: `Isi SOUL.md saat ini akan diganti dengan prompt profil ini dan berlaku untuk semua sesi NetOps Agent berikutnya.${cur?.exists ? ' Versi lama disimpan sebagai backup di server NetOpsUI.' : ''}`, + confirmLabel: 'Terapkan', danger: true, + }); + if (!ok) return; + try { await mgr(`/profiles/${selected}/apply-soul`, { method: 'POST' }); await alertDialog('SOUL.md NetOps Agent diperbarui.', 'Berhasil'); } + catch (e) { $('g-err').textContent = e.message; } + } + + async function del() { + const ok = await confirmDialog({ title: 'Hapus profil?', message: `"${selected}" akan dihapus dari NetOpsUI. SOUL.md NetOps Agent yang sudah pernah diterapkan tidak berubah.`, confirmLabel: 'Hapus', danger: true }); + if (!ok) return; + try { + await mgr('/profiles/' + selected, { method: 'DELETE' }); + if (getActiveProfile() === selected) setActiveProfile(null); + selected = null; await load(); + } catch (e) { $('g-err').textContent = e.message; } + } + + function select(slug) { selected = slug; isNew = false; renderList(); renderEditor(); } + $('ag-new').onclick = () => { isNew = true; selected = null; renderList(); renderEditor(); }; + + async function load() { + try { profiles = (await mgr('/profiles')).profiles; renderList(); } + catch (e) { $('ag-list').innerHTML = errorHtml('Gagal memuat profil: ' + e.message); } + } + + await load(); + renderEditor(); +} diff --git a/frontend/js/screens/chat.js b/frontend/js/screens/chat.js new file mode 100644 index 0000000..553e7b3 --- /dev/null +++ b/frontend/js/screens/chat.js @@ -0,0 +1,865 @@ +import { S } from '../state.js'; +import { $, esc, fmtTime, fmtShortDate, fmtFullDateTime, copyToClipboard, renderMarkdown, confirmDialog, alertDialog } from '../utils.js'; +import { activeBackend } from '../backends/index.js'; + +let _chatEl = null; +let _elapsedIv = null; +let _threadsIv = null; // polls the shared thread list so other operators' chats show up +let _requestStartTs = null; // wall-clock start of the current request leg (reset per send/resume) +let _lastEventTs = null; // used to compute per-step gaps between console entries + +function fmtDelta(ms) { + if (ms < 1000) return `+${Math.round(ms)}ms`; + return `+${(ms / 1000).toFixed(1)}s`; +} + +// ── Process console persistence — scoped per thread, survives page reload ──── +// Keyed by backend + thread id so each chat session has its own independent +// log, not one shared across every conversation. S.console always points at (by reference, +// not copy) _consoleStore[S.threadId] so pushes/clears stay in sync with the +// persisted store without an extra write-back step. +const CONSOLE_STORAGE_KEY = 'llmnetops-console-v3'; +const CONSOLE_MAX_ENTRIES = 500; +const CONSOLE_MAX_THREADS = 30; + +let _consoleStore = {}; + +(function consoleHydrate() { + try { + const raw = localStorage.getItem(CONSOLE_STORAGE_KEY); + if (!raw) return; + const parsed = JSON.parse(raw); + for (const [key, entries] of Object.entries(parsed)) { + const tid = key.replace(/^palapa:/, 'netops:'); // backend id used before the rename + _consoleStore[tid] = entries.map(e => ({ ...e, ts: new Date(e.ts) })); + } + } catch { /* corrupt or unavailable — start empty */ } +})(); + +function consoleSave() { + try { + localStorage.setItem(CONSOLE_STORAGE_KEY, JSON.stringify(_consoleStore)); + } catch { /* storage full/unavailable — degrade to in-memory only */ } +} + +function consoleKey(threadId) { + return `${activeBackend().id}:${threadId}`; +} + +function consoleForThread(threadId) { + const key = consoleKey(threadId); + if (!_consoleStore[key]) { + const keys = Object.keys(_consoleStore); + if (keys.length >= CONSOLE_MAX_THREADS) delete _consoleStore[keys[0]]; // evict oldest tracked thread + _consoleStore[key] = []; + } + return _consoleStore[key]; +} + +function threadFromSummary(t) { + return { id: t.id, title: t.title || 'New Chat', ts: t.updatedAt, createdAt: t.createdAt, lastMessage: t.lastMessage || '', owner: t.owner || '', running: !!t.running }; +} + +// Creates a thread on the active backend and makes it current. Returns false +// (after telling the operator) when the backend refuses or is unreachable. +async function chatNewThread() { + try { + const t = threadFromSummary(await activeBackend().createThread()); + S.threads.unshift(t); + S.threadId = t.id; + return true; + } catch (e) { + await alertDialog(`Gagal membuat thread di ${activeBackend().label}: ${e.message}`, 'Backend Tidak Terjangkau'); + return false; + } +} + +export async function screenChat(c, threadIdParam) { + const backend = activeBackend(); + let loadError = null; + if (S.threadsBackend !== backend.id) { + // Threads belong to one backend; switching backends starts from its list. + S.threads = []; S.threadId = null; S.messages = []; + try { + S.threads = (await backend.listThreads()).map(threadFromSummary); + S.threadsBackend = backend.id; + } catch (e) { + loadError = e.message; + } + } + + let targetThreadId = threadIdParam || S.threadId; + if (!targetThreadId) { + if (S.threads.length > 0) { + targetThreadId = S.threads[0].id; + } else if (!loadError && await chatNewThread()) { + targetThreadId = S.threadId; + } + } else if (!S.threads.some(t => t.id === targetThreadId)) { + // Deep link to a thread not yet in our local list (e.g. shared link opened fresh) — placeholder entry + S.threads.unshift({ id: targetThreadId, title: 'Shared Chat', ts: new Date(), createdAt: new Date(), lastMessage: '' }); + } + + const threadChanged = targetThreadId !== S.threadId; + S.threadId = targetThreadId || null; + S.console = S.threadId ? consoleForThread(S.threadId) : []; + chatSyncUrl(); + + c.innerHTML = ` +
+
+ +
+
+
+
+ + + +
+

[Enter] Kirim · [Ctrl+L] Clear

+
+
+ +
+
+
+
+
+ ${S.consoleOpen ? 'expand_more' : 'expand_less'} + Process Console + (${S.console.length}) +
+ +
+
+
+
+ `; + + _chatEl = $('chat-messages'); + // Messages are re-rendered wholesale while streaming, so the copy button is handled by delegation. + _chatEl.onclick = async e => { + const btn = e.target.closest('[data-copy-msg]'); + if (!btn) return; + const text = S.messages[+btn.dataset.copyMsg]?.content; + if (!text) return; + const ok = await copyToClipboard(text); + btn.querySelector('.material-symbols-outlined').textContent = ok ? 'check' : 'error'; + btn.title = ok ? 'Tersalin' : 'Gagal menyalin'; + setTimeout(() => { + if (!btn.isConnected) return; + btn.querySelector('.material-symbols-outlined').textContent = 'content_copy'; + btn.title = 'Salin jawaban'; + }, 1500); + }; + chatRenderThreads(); + chatRenderTools(); + consoleRender(); + if (!S.threadId) { + chatRenderMessages(); + } else if (threadChanged || S.messages.length === 0) { + await chatLoadHistory(S.threadId); + } else { + chatRenderMessages(); + } + chatBindEvents(); + chatBindConsole(); + chatStartThreadPoll(); +} + +function chatSyncUrl() { + if (!S.threadId) return; + const target = '#chat/' + encodeURIComponent(S.threadId); + if (location.hash !== target) history.replaceState(null, '', target); +} + +async function chatLoadHistory(threadId, { attach = true } = {}) { + chatRenderMessages(); + try { + const msgs = await activeBackend().loadMessages(threadId); + if (threadId !== S.threadId) return; // switched away while loading + S.messages = msgs.map(m => ({ role: m.role, content: m.content, ts: m.ts || null, streaming: false })); + } catch (e) { + consolePush('error', 'Gagal memuat riwayat: ' + e.message); + } + chatRenderMessages(); + // A question without an answer on a thread flagged "running" means the run is + // still going on the server (page refreshed, or another operator started it). + const last = S.messages[S.messages.length - 1]; + const t = S.threads.find(x => x.id === threadId); + // Not awaited: it lasts as long as the run, and screenChat() still has to bind the UI. + if (attach && t?.running && last?.role === 'user') chatAttach(threadId); +} + +// Re-attaches to a run that is already in progress on the server. +async function chatAttach(threadId) { + const backend = activeBackend(); + if (!backend.resume || S.chatState !== 'idle' || threadId !== S.threadId) return; + const lastUser = [...S.messages].reverse().find(m => m.role === 'user'); + S.activeQuery = lastUser ? lastUser.content : ''; + S.messages.push({ role: 'agent', content: '', ts: new Date(), streaming: true }); + chatResetTools(); + chatStartElapsed(); + _requestStartTs = Date.now(); + _lastEventTs = null; + S.chatState = 'streaming'; + consolePush('note', 'Tersambung ke proses yang sedang berjalan di server.'); + chatRenderMessages(); chatUpdateUI(); + const emit = ev => { if (threadId === S.threadId) chatHandleEvent(ev); }; + try { await backend.resume(threadId, emit); } + catch (e) { emit({ type: 'error', text: e.message || 'Connection failed' }); } + if (threadId !== S.threadId) return; // left the thread; its run continues on the server + chatFinish(); + // The server stored the final answer; show that copy and refresh the thread list. + if (threadId === S.threadId) { + try { + S.threads = (await backend.listThreads()).map(threadFromSummary); + chatRenderThreads(); + } catch { /* next poll */ } + await chatLoadHistory(threadId, { attach: false }); + } +} + +function chatBindEvents() { + const inp = $('chat-input'), btnS = $('btn-send'), btnT = $('btn-stop'), btnN = $('btn-new-thread'), btnL = $('btn-copy-link'); + + async function send() { + const text = inp.value.trim(); + if (!text || S.chatState !== 'idle') return; + if (!S.threadId && !(await chatNewThread())) return; + const backend = activeBackend(); + const threadId = S.threadId; + inp.value = ''; + S.activeQuery = text; + S.messages.push({ role: 'user', content: text, ts: new Date() }); + S.messages.push({ role: 'agent', content: '', ts: new Date(), streaming: true }); + chatResetTools(); + chatStartElapsed(); + _requestStartTs = Date.now(); + _lastEventTs = null; + S.chatState = 'streaming'; + chatTouchThread(threadId, text); + chatRenderMessages(); chatUpdateUI(); + // Events from a thread the operator has since left must not touch the visible one. + const emit = ev => { if (threadId === S.threadId) chatHandleEvent(ev); }; + try { await backend.send(threadId, text, emit); } + catch (e) { emit({ type: 'error', text: e.message || 'Connection failed' }); } + if (threadId === S.threadId) chatFinish(); + } + + btnS.onclick = send; + btnT.onclick = async () => { + if (S.chatState !== 'streaming' || S.stopRequested) return; + S.stopRequested = true; + chatUpdateUI(); + consolePush('stopped', 'Permintaan stop dikirim...'); + try { + const r = await activeBackend().stop(S.threadId); + if (!r || r.ok === false) { + consolePush('stopped', 'Tidak ada proses aktif untuk dihentikan (kemungkinan sudah selesai).'); + S.stopRequested = false; + chatUpdateUI(); + } + } catch (e) { + consolePush('error', 'Gagal mengirim permintaan stop: ' + (e.message || 'unknown')); + S.stopRequested = false; + chatUpdateUI(); + } + }; + inp.onkeydown = e => { + if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } + if (e.key === 'l' && e.ctrlKey) { e.preventDefault(); chatClear(); } + }; + btnN.onclick = async () => { + if (S.chatState !== 'idle' || !(await chatNewThread())) return; + S.console = consoleForThread(S.threadId); + chatSyncUrl(); + chatClear(); + consoleRender(); + }; + btnL.onclick = async () => { + const url = location.origin + location.pathname + '#chat/' + encodeURIComponent(S.threadId); + const ok = await copyToClipboard(url); + btnL.textContent = ok ? 'check' : 'error'; + setTimeout(() => { btnL.textContent = 'link'; }, 1200); + if (!ok) window.prompt('Salin link chat ini:', url); + }; + $('approval-choices').onclick = e => { + const b = e.target.closest('[data-choice]'); + if (b) chatResolveApproval(b.dataset.choice); + }; + + if (!_approvalKeysBound) { + _approvalKeysBound = true; + document.addEventListener('keydown', e => { + if (!S.pendingApproval) return; + if (e.key === 'y' || e.key === 'Y') chatResolveApproval('once'); + if (e.key === 'n' || e.key === 'N') chatResolveApproval('deny'); + }); + } +} + +let _approvalKeysBound = false; + +// Keeps the thread list ordering/preview in sync with a message just sent, +// without refetching the list from the backend. +function chatTouchThread(threadId, text) { + const t = S.threads.find(x => x.id === threadId); + if (!t) return; + if (!t.title || t.title === 'New Chat') t.title = text.slice(0, 60); + t.lastMessage = text.slice(0, 120); + t.ts = new Date(); + S.threads = [t, ...S.threads.filter(x => x !== t)]; + chatRenderThreads(); +} + +// Normalized backend events — see the adapter contract in backends/index.js. +function chatHandleEvent(ev) { + const last = S.messages[S.messages.length - 1]; + const agentMsg = last && last.role === 'agent' ? last : null; + switch (ev.type) { + case 'delta': + if (agentMsg) agentMsg.content += ev.text; + break; + case 'tool_start': + S.tools.push({ name: ev.name, detail: ev.detail, state: 'running', durationMs: null }); + S.toolCount++; + consolePush('tool_call', `${ev.name}${ev.detail ? ' ' + ev.detail : ''}`); + chatRenderTools(); + break; + case 'tool_end': { + // Hermes announces tool_start first; NetOps Agent only reports completed calls. + const running = [...S.tools].reverse().find(t => t.name === ev.name && t.state === 'running'); + const state = ev.error ? 'failed' : 'done'; + if (running) Object.assign(running, { state, durationMs: ev.durationMs }); + else { S.tools.push({ name: ev.name, detail: ev.detail, source: ev.source, state, durationMs: ev.durationMs }); S.toolCount++; } + consolePush(ev.error ? 'error' : 'tool_result', + `${ev.name} (${fmtDelta(ev.durationMs || 0).slice(1)})${ev.detail ? ' → ' + ev.detail : ''}`); + chatRenderTools(); + break; + } + case 'approval': + S.pendingApproval = ev.data; + consolePush('approval_required', ev.data.action); + chatShowApproval(); + break; + case 'stopped': + consolePush('stopped', ev.text); + if (agentMsg && !agentMsg.content) agentMsg.content = `_${ev.text}_`; + break; + case 'error': + consolePush('error', ev.text); + if (agentMsg && !agentMsg.content) agentMsg.content = `**Error:** ${ev.text}`; + break; + default: // note, thinking + consolePush(ev.type, ev.text); + } + chatRenderMessages(); chatUpdateUI(); +} + +async function chatResolveApproval(choice) { + const p = S.pendingApproval; + if (!p) return; + chatHideApproval(); + consolePush('approval_required', `Operator: ${choice === 'deny' ? 'DITOLAK' : 'DISETUJUI (' + choice + ')'}`); + try { + // The run's event stream stays open while waiting, so the turn simply + // continues in send() once the backend accepts the decision. + await activeBackend().respondApproval(S.threadId, choice, p.requestId); + } catch (e) { + consolePush('error', 'Gagal mengirim keputusan approval: ' + e.message); + } +} + +function chatFinish() { + const last = S.messages[S.messages.length - 1]; + if (last) last.streaming = false; + S.chatState = 'idle'; + chatStopElapsed(); + if (_requestStartTs) { + consolePush('timing', `Total durasi: ${fmtDelta(Date.now() - _requestStartTs)}`); + _requestStartTs = null; + } + S.tools.forEach(t => { if (t.state === 'running') t.state = 'done'; }); + chatHideApproval(); + chatRenderMessages(); chatRenderTools(); chatUpdateUI(); +} + +function chatClear() { + S.messages = []; S.activeQuery = ''; S.chatState = 'idle'; + chatResetTools(); + chatStopElapsed(); + chatRenderMessages(); chatRenderThreads(); chatUpdateUI(); +} + +function chatResetTools() { + S.tools = []; + S.toolCount = 0; + chatRenderTools(); +} + +// Tool arguments arrive as a raw JSON string. Show the one value that says what the +// call does (command, path, agent…) instead of the JSON; `{}` means no arguments. +const TOOL_KEYS = ['command', 'cmd', 'query', 'path', 'agent', 'device', 'host', 'name', 'task', 'url']; +function toolSummary(detail) { + if (!detail) return ''; + let a; + try { a = JSON.parse(detail); } catch { return detail; } + if (!a || typeof a !== 'object') return String(a ?? ''); + const entries = Object.entries(a).filter(([, v]) => v !== '' && v != null); + if (!entries.length) return ''; + const key = TOOL_KEYS.find(k => a[k]); + const fmt = v => (typeof v === 'string' ? v : JSON.stringify(v)); + if (!key) return entries.map(([k, v]) => `${k}=${fmt(v)}`).join(' '); + const head = a.action ? `${a.action} ` : ''; + return head + fmt(a[key]); +} +function toolFull(detail) { + try { return JSON.stringify(JSON.parse(detail), null, 2); } catch { return detail || ''; } +} + +function chatRenderTools() { + const el = $('tool-panel'); if (!el) return; + const cnt = $('tool-count'); if (cnt) cnt.textContent = S.toolCount ? `${S.toolCount} call` : ''; + if (!S.tools.length) { + el.innerHTML = `

${S.chatState === 'streaming' ? 'Menunggu tool call...' : 'Belum ada tool call pada giliran ini.'}

`; + return; + } + const styles = { + running: { dot: 'bg-green-500 pulse-green', text: 'text-green-700', label: 'RUNNING', bl: 'border-l-[3px] border-l-green-500' }, + done: { dot: 'bg-gray-400', text: 'text-on-surface-variant', label: 'DONE', bl: '' }, + failed: { dot: 'bg-red-500', text: 'text-red-700', label: 'FAILED', bl: 'border-l-[3px] border-l-red-500' }, + }; + el.innerHTML = S.tools.map(t => { + const st = styles[t.state] || styles.done; + const summary = toolSummary(t.detail); + const child = t.source && t.source !== 'main' ? t.source.replace(/^child:/, '') : ''; + const dur = t.durationMs != null ? ` · ${fmtDelta(t.durationMs).slice(1)}` : ''; + return `
+
+ ${child ? '↳ ' : ''}${esc(t.name)}${child ? ` · ${esc(child)}` : ''} + ${st.label} +
+ ${summary ? `
${esc(summary)}
${esc(toolFull(t.detail))}
` : ''} + ${dur ? `

${dur.replace(' · ', '')}

` : ''} +
`; + }).join(''); +} + +function chatRenderMessages() { + const el = $('chat-messages'); if (!el) return; + if (S.messages.length === 0) { + el.innerHTML = `
+ hub +

LLMNetOps

+

Ketik perintah untuk memulai sesi dengan ${esc(activeBackend().label)}.

+
`; + return; + } + el.innerHTML = S.messages.map(m => m.role === 'user' ? chatUserMsg(m) : chatAgentMsg(m)).join(''); + el.scrollTop = el.scrollHeight; +} + +function chatUserMsg(m) { + return `
+
+ ${m.ts ? fmtTime(m.ts) : ''} + ANDA +
+
+

${esc(m.content)}

+
+
`; +} + +// Status line shown for as long as the agent is working, not only before the +// first token: a delegated sub-agent can run for minutes without emitting anything. +function workingStatus() { + const running = [...S.tools].reverse().find(t => t.state === 'running'); + const done = S.tools.filter(t => t.state !== 'running').length; + if (running) return `Menjalankan ${running.name}…`; + if (S.elapsed >= 20) return done ? `${done} tool selesai — menunggu agent / sub-agent (delegasi bisa 1–3 menit)…` : 'Menunggu agent / sub-agent bekerja (bisa 1–3 menit)…'; + return done ? `${done} tool selesai — agent menyusun langkah berikutnya…` : 'Agent sedang memproses…'; +} + +function fmtElapsed(sec) { + return `${String(Math.floor(sec / 60)).padStart(2, '0')}:${String(sec % 60).padStart(2, '0')}`; +} + +function chatAgentMsg(m) { + const typing = m.streaming ? `
+
+
+
+
+
+ ${esc(workingStatus())} + ${fmtElapsed(S.elapsed || 0)}
` : ''; + const txt = m.content ? `
${renderMarkdown(m.content)}
` : ''; + // Copy only once the answer is complete (a streaming re-render would also reset the button's feedback). + const copy = m.content && !m.streaming + ? `` + : ''; + return `
+
+ AGENT + ${m.ts ? fmtTime(m.ts) : ''}${copy} +
+
+ ${txt}${typing} +
+
`; +} + +function chatEventLine(ev, isActive) { + const c = { + note: { tag: '#fcd34d', l: 'NOTE' }, + thinking: { tag: '#a78bfa', l: 'THINKING' }, + tool_call: { tag: '#60a5fa', l: 'TOOL_CALL' }, + tool_result: { tag: '#4ade80', l: 'RESULT' }, + approval_required: { tag: '#fbbf24', l: 'APPROVAL' }, + stopped: { tag: '#f87171', l: 'STOPPED' }, + error: { tag: '#f87171', l: 'ERROR' }, + timing: { tag: '#38bdf8', l: 'DURASI' }, + }[ev.type] || { tag: '#94a3b8', l: ev.type.toUpperCase() }; + const delta = ev.deltaMs != null + ? `${fmtDelta(ev.deltaMs)}` + : ''; + const running = isActive && ev.type === 'tool_call' + ? `running` + : ''; + return `
[${c.l}]${esc(ev.content)}${delta}${running}
`; +} + +function consolePush(type, content) { + // Mutate in place (push/splice), not reassign — S.console and + // _consoleStore[threadId] must stay the same array instance. + const now = new Date(); + const deltaMs = _lastEventTs ? now.getTime() - _lastEventTs.getTime() : null; + _lastEventTs = now; + S.console.push({ type, content, ts: now, deltaMs }); + if (S.console.length > CONSOLE_MAX_ENTRIES) S.console.splice(0, S.console.length - CONSOLE_MAX_ENTRIES); + consoleSave(); + consoleRender(); +} + +function consoleRender() { + const el = $('debug-console-body'); + const countEl = $('console-count'); + if (countEl) countEl.textContent = `(${S.console.length})`; + if (!el) return; + const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40; + el.innerHTML = S.console.length + ? S.console.map((ev, i) => chatEventLine(ev, S.chatState === 'streaming' && i === S.console.length - 1)).join('') + : `
Belum ada aktivitas. Kirim pesan untuk mulai.
`; + if (atBottom) el.scrollTop = el.scrollHeight; +} + +let _consoleBound = false; + +function chatBindConsole() { + const header = $('console-header'), clearBtn = $('btn-console-clear'); + + header.onclick = () => { + S.consoleOpen = !S.consoleOpen; + consoleApplyState(); + if (S.consoleOpen) consoleRender(); + }; + clearBtn.onclick = (e) => { + e.stopPropagation(); + S.console.length = 0; // clear in place — keeps the _consoleStore[threadId] reference intact + consoleSave(); + consoleRender(); + }; + + if (_consoleBound) return; + _consoleBound = true; + let dragging = false, startY = 0, startH = 0; + document.addEventListener('mousedown', (e) => { + const handle = $('console-resize-handle'); + if (!handle || e.target !== handle || !S.consoleOpen) return; + dragging = true; startY = e.clientY; startH = S.consoleHeight; + document.body.style.cursor = 'ns-resize'; + e.preventDefault(); + }); + document.addEventListener('mousemove', (e) => { + if (!dragging) return; + const dy = startY - e.clientY; + S.consoleHeight = Math.min(Math.max(startH + dy, 120), Math.floor(window.innerHeight * 0.7)); + consoleApplyState(); + }); + document.addEventListener('mouseup', () => { + if (!dragging) return; + dragging = false; + document.body.style.cursor = ''; + }); +} + +function consoleApplyState() { + const panel = $('debug-console'), body = $('debug-console-body'), icon = $('console-toggle-icon'); + if (!panel) return; + panel.style.height = (S.consoleOpen ? S.consoleHeight : 36) + 'px'; + if (body) body.style.display = S.consoleOpen ? '' : 'none'; + if (icon) icon.textContent = S.consoleOpen ? 'expand_more' : 'expand_less'; +} + +function chatRenderThreads() { + const el = $('thread-list'); if (!el) return; + el.innerHTML = S.threads.map(t => { + const a = t.id === S.threadId; + const preview = t.lastMessage ? `

${esc(t.lastMessage)}

` : ''; + const createdTitle = t.createdAt ? `Dibuat: ${esc(fmtFullDateTime(t.createdAt))}` : ''; + return `
+
+ + +
+

${esc(t.title)}

+ ${preview} +

${fmtTime(t.ts)} · dibuat ${esc(fmtShortDate(t.createdAt))}

+ ${t.owner || t.running ? `

${t.running ? '' : ''}${esc(t.owner)}${t.running ? ' · berjalan' : ''}

` : ''} +
`; + }).join(''); +} + +async function chatRenameThread(threadId, event) { + if (event) event.stopPropagation(); + const row = document.querySelector(`[data-tid="${CSS.escape(threadId)}"]`); + const titleEl = row && row.querySelector('[data-title-el]'); + if (!titleEl) return; + + const t = S.threads.find(x => x.id === threadId); + const current = t ? t.title : ''; + + const input = document.createElement('input'); + input.type = 'text'; + input.value = current; + input.maxLength = 120; + input.className = titleEl.className + ' bg-white border border-primary rounded px-1 py-0.5 w-full outline-none'; + titleEl.replaceWith(input); + input.focus(); + input.select(); + + let settled = false; + async function commit() { + if (settled) return; settled = true; + const title = input.value.trim() || current || 'New Chat'; + if (t) t.title = title; + if (title !== current) { + try { await activeBackend().renameThread(threadId, title); } + catch (e) { await alertDialog('Gagal mengubah nama: ' + e.message, 'Terjadi Kesalahan'); } + } + chatRenderThreads(); + } + function cancel() { + if (settled) return; settled = true; + chatRenderThreads(); + } + + input.onclick = e => e.stopPropagation(); + input.addEventListener('keydown', e => { + e.stopPropagation(); + if (e.key === 'Enter') { e.preventDefault(); commit(); } + if (e.key === 'Escape') { e.preventDefault(); cancel(); } + }); + input.addEventListener('blur', commit); +} +window.chatRenameThread = chatRenameThread; + +async function chatDeleteThread(threadId, event) { + if (event) event.stopPropagation(); + const t = S.threads.find(x => x.id === threadId); + const ok = await confirmDialog({ + title: 'Hapus percakapan?', + message: `"${t ? t.title : threadId}" akan dihapus permanen beserta seluruh riwayatnya. Tindakan ini tidak bisa dibatalkan.`, + confirmLabel: 'Hapus', + cancelLabel: 'Batal', + danger: true, + }); + if (!ok) return; + + try { + await activeBackend().deleteThread(threadId); + } catch (e) { + await alertDialog('Gagal menghapus thread: ' + e.message, 'Terjadi Kesalahan'); + return; + } + + S.threads = S.threads.filter(x => x.id !== threadId); + delete _consoleStore[consoleKey(threadId)]; + consoleSave(); + + if (threadId !== S.threadId) { + chatRenderThreads(); + return; + } + + if (S.threads.length > 0) { + await chatSwitchThread(S.threads[0].id); + } else { + if (!(await chatNewThread())) S.threadId = null; + S.console = S.threadId ? consoleForThread(S.threadId) : []; + chatSyncUrl(); + chatClear(); + consoleRender(); + } +} +window.chatDeleteThread = chatDeleteThread; + +async function chatSwitchThread(threadId) { + if (threadId === S.threadId) return; + if (S.chatState !== 'idle') { + // A run in progress used to lock every other thread. Leave it running on the + // server and stop following it; coming back re-attaches while it still runs. + const backend = activeBackend(); + if (!backend.detach) return; + backend.detach(S.threadId); + S.chatState = 'idle'; + S.pendingApproval = null; + chatHideApproval(); + _requestStartTs = null; + } + S.threadId = threadId; + S.console = consoleForThread(threadId); + chatSyncUrl(); + S.activeQuery = ''; + S.chatState = 'idle'; + chatResetTools(); + chatStopElapsed(); + chatRenderThreads(); + chatUpdateUI(); + consoleRender(); + S.messages = []; + await chatLoadHistory(threadId); +} +window.chatSwitchThread = chatSwitchThread; + +const APPROVAL_CHOICES = { + once: { label: 'Izinkan sekali', cls: 'bg-green-700 text-white hover:bg-green-800' }, + session: { label: 'Izinkan sesi ini', cls: 'border border-outline-variant text-primary hover:bg-surface-container' }, + always: { label: 'Selalu izinkan', cls: 'border border-outline-variant text-primary hover:bg-surface-container' }, + deny: { label: 'Tolak', cls: 'border border-red-300 text-red-700 hover:bg-red-50' }, +}; + +function chatShowApproval() { + const o = $('approval-overlay'); if (!o) return; o.classList.remove('hidden'); + const p = S.pendingApproval || {}; + const ac = $('m-action'), de = $('m-desc'), dr = $('m-desc-row'), ch = $('approval-choices'); + if (ac) ac.textContent = p.action || '—'; + if (de) de.textContent = p.description || ''; + if (dr) dr.classList.toggle('hidden', !p.description || p.description === p.action); + if (ch) { + // Deny first, most permissive last — matches the order operators scan. + const order = ['deny', 'always', 'session', 'once']; + ch.innerHTML = order.filter(c => (p.choices || ['once', 'deny']).includes(c)).map(c => { + const s = APPROVAL_CHOICES[c]; + return ``; + }).join(''); + } +} + +function chatHideApproval() { + const o = $('approval-overlay'); if (o) o.classList.add('hidden'); S.pendingApproval = null; +} + +function chatStartElapsed() { + S.elapsed = 0; chatStopElapsed(); const st = Date.now(); + _elapsedIv = setInterval(() => { + S.elapsed = Math.floor((Date.now() - st) / 1000); + const el = $('elapsed-display'); + if (el) el.textContent = `⏱ ${fmtElapsed(S.elapsed)}`; + document.querySelectorAll('[data-work-elapsed]').forEach(n => { n.textContent = fmtElapsed(S.elapsed); }); + if (S.elapsed === 20) chatRenderMessages(); // switch the status line to the long-wait hint + }, 1000); +} + +function chatStopElapsed() { if (_elapsedIv) { clearInterval(_elapsedIv); _elapsedIv = null; } } +function chatUpdateUI() { + const q = $('active-query'); if (q) q.textContent = S.activeQuery || '—'; + const running = S.chatState === 'streaming'; + if (!running) S.stopRequested = false; + const btnS = $('btn-send'), btnT = $('btn-stop'); + if (btnS) btnS.classList.toggle('hidden', running); + if (btnT) { + btnT.classList.toggle('hidden', !running); + btnT.classList.toggle('flex', running); + btnT.disabled = S.stopRequested; + btnT.innerHTML = S.stopRequested + ? `progress_activityMenghentikan...` + : `stop_circleStop`; + } +} + +// Refreshes the shared thread list (and the open thread when someone else +// added to it) while the operator is idle on this screen. +function chatStartThreadPoll() { + chatStopThreadPoll(); + const backend = activeBackend(); + if (!backend.capabilities.serverThreads) return; + _threadsIv = setInterval(async () => { + if (document.hidden || S.chatState !== 'idle') return; + try { + const fresh = (await backend.listThreads()).map(threadFromSummary); + if (S.screen !== 'chat' || backend.id !== activeBackend().id || S.chatState !== 'idle') return; + const cur = S.threads.find(t => t.id === S.threadId); + const now = fresh.find(t => t.id === S.threadId); + const changed = cur && now && now.ts.getTime() !== cur.ts.getTime(); + const keep = S.threads.filter(t => !fresh.some(f => f.id === t.id) && t.id === S.threadId && !now && t.lastMessage === ''); + S.threads = [...fresh, ...keep]; + chatRenderThreads(); + if (changed) await chatLoadHistory(S.threadId); + } catch { /* transient — try again on the next tick */ } + }, 5000); +} + +function chatStopThreadPoll() { if (_threadsIv) { clearInterval(_threadsIv); _threadsIv = null; } } + +export function chatUnmount() { chatStopElapsed(); chatStopThreadPoll(); } diff --git a/frontend/js/screens/dashboard.js b/frontend/js/screens/dashboard.js new file mode 100644 index 0000000..0ce8030 --- /dev/null +++ b/frontend/js/screens/dashboard.js @@ -0,0 +1,214 @@ +import { $, esc, cardHtml, pageHeader, loadingHtml, fmtFullDateTime, badge, alertDialog } from '../utils.js'; +import { activeBackend } from '../backends/index.js'; + +function emptyBody(msg) { + return `

${msg}

`; +} + +function statCard(label, body) { + return `
+

${label}

+ ${body} +
`; +} + +export async function screenDashboard(c) { + const backend = activeBackend(); + c.innerHTML = `
+ ${pageHeader( + 'Overview', + `Ringkasan backend aktif (${esc(backend.label)}), pengecekan berkala, dan aktivitas agent.`, + `` + )} +
${loadingHtml('Memuat dashboard...')}
+
`; + + $('btn-dash-refresh').onclick = loadDashboard; + await loadDashboard(); +} + +async function loadDashboard() { + const backend = activeBackend(); + const body = $('dash-body'); + const btn = $('btn-dash-refresh'); + if (btn) { btn.disabled = true; btn.querySelector('.material-symbols-outlined').classList.add('animate-spin'); } + + const cap = backend.capabilities; + // Each source fails independently so one unreachable endpoint doesn't blank the page. + // Capability-gated sources resolve to null when the backend doesn't offer them. + const [health, threads, skills, jobs, devices, activity] = await Promise.allSettled([ + backend.health(), backend.listThreads(), backend.listSkills(), + cap.jobs ? backend.listJobs() : null, + cap.devices ? backend.listDevices() : null, + cap.activity ? backend.listActivity() : null, + ]); + + if (body) body.innerHTML = ` +
+ ${statBackend(backend, health)} + ${statModel(health)} + ${cap.jobs ? statJobs(jobs) : cap.devices ? statCount('PERANGKAT', devices, 'terdaftar di inventori') : statCount('THREADS', threads, 'tersimpan di server')} + ${statCount('SKILLS', skills, 'terpasang')} +
+
+ ${cap.jobs ? jobsHtml(jobs) : cap.devices ? devicesHtml(devices) : ''} + ${recentThreadsHtml(threads)} +
+ ${cap.activity ? activityHtml(activity) : ''}`; + bindJobActions(backend); + document.querySelectorAll('[data-goto]').forEach(el => { + el.onclick = () => { location.hash = el.dataset.goto; }; + }); + if (btn) { btn.disabled = false; btn.querySelector('.material-symbols-outlined').classList.remove('animate-spin'); } +} + +function statBackend(backend, health) { + const ok = health.status === 'fulfilled' && health.value.ok; + const [dot, text] = health.status === 'rejected' + ? ['bg-red-500', 'tidak terjangkau'] + : ok ? ['bg-green-500', 'terhubung'] : ['bg-amber-500', 'status tidak OK']; + const title = health.status === 'rejected' ? health.reason.message : ''; + return statCard('BACKEND', ` +

${esc(backend.label)}

+

${text}

`); +} + +function statModel(health) { + const h = health.status === 'fulfilled' ? health.value : null; + return statCard('MODEL', ` +

${esc(h?.model || '—')}

+

${esc(h?.detail || '')}

`); +} + +function statCount(label, result, caption) { + if (result.status === 'rejected') { + return statCard(label, `

—

+

gagal dimuat

`); + } + return statCard(label, `

${result.value.length}

+

${caption}

`); +} + +function recentThreadsHtml(threads) { + if (threads.status === 'rejected') { + return cardHtml('Thread Terakhir', emptyBody('Gagal memuat thread: ' + esc(threads.reason.message))); + } + const list = threads.value.slice(0, 8); + if (!list.length) return cardHtml('Thread Terakhir', emptyBody('Belum ada percakapan.')); + const rows = list.map(t => ` +
+
+ ${esc(t.title)} + ${esc(fmtFullDateTime(t.updatedAt))} +
+

${esc(t.lastMessage || '—')}

+
`).join(''); + return cardHtml('Thread Terakhir', `
${rows}
`); +} + +function failedMsg(what, r) { + return cardHtml(what, emptyBody('Gagal memuat: ' + esc(r.reason.message))); +} + +function isPaused(j) { return j.enabled === false || j.state === 'paused'; } +function isFailing(j) { return j.last_status === 'error' || j.state === 'error'; } + +function statJobs(r) { + if (r.status === 'rejected') return statCount('JOB TERJADWAL', r, ''); + const jobs = r.value; + const active = jobs.filter(j => !isPaused(j)).length; + const failing = jobs.filter(isFailing).length; + const cap = !jobs.length ? 'belum ada job terjadwal' : failing + ? `${failing} gagal pada eksekusi terakhir` + : 'aktif, eksekusi terakhir OK'; + return statCard('JOB TERJADWAL', `

${active}

+

${cap}

`); +} + +function jobStatusBadge(j) { + if (isPaused(j)) return badge('dijeda', 'gray'); + if (isFailing(j)) return badge('gagal', 'red'); + if (j.last_status) return badge('OK', 'green'); + return badge('belum jalan', 'gray'); +} + +function jobsHtml(r) { + if (r.status === 'rejected') return failedMsg('Pengecekan Berkala', r); + const jobs = r.value; + if (!jobs.length) return cardHtml('Pengecekan Berkala', emptyBody('Belum ada job terjadwal. Buat lewat Hermes (cron).')); + const btn = 'px-2 py-1 border border-outline-variant rounded text-[11px] text-primary hover:bg-surface-container-low transition-colors'; + const rows = jobs.map(j => ` + + +

${esc(j.name || j.id)}

+

${esc(j.schedule_display || '')}

+ ${isFailing(j) && j.last_error ? `

${esc(j.last_error)}

` : ''} + + ${jobStatusBadge(j)} + ${j.last_run_at ? esc(fmtFullDateTime(j.last_run_at)) : '—'} + ${!isPaused(j) && j.next_run_at ? esc(fmtFullDateTime(j.next_run_at)) : '—'} + + + + + `).join(''); + return cardHtml('Pengecekan Berkala', `
+ + + ${rows}
JOBSTATUSTERAKHIRBERIKUTNYA
`); +} + +function bindJobActions(backend) { + document.querySelectorAll('[data-job]').forEach(el => { + el.onclick = async () => { + el.disabled = true; + try { + const fn = { run: 'runJob', pause: 'pauseJob', resume: 'resumeJob' }[el.dataset.job]; + await backend[fn](el.dataset.id); + } catch (e) { + alertDialog(e.message); + } + loadDashboard(); + }; + }); +} + +function devicesHtml(r) { + if (r.status === 'rejected') return failedMsg('Perangkat', r); + const list = r.value; + if (!list.length) return cardHtml('Perangkat', emptyBody('Belum ada perangkat terdaftar.')); + const rows = list.slice(0, 10).map(d => ` +
+ router +
+

${esc(d.name)}

+

${esc(d.mgmt_ip)}

+
+ ${esc(d.role || '')}${d.network_type ? ' · ' + esc(d.network_type) : ''} +
`).join(''); + const more = list.length > 10 ? `

+${list.length - 10} lainnya di halaman Nodes

` : ''; + return cardHtml('Perangkat', `
${rows}${more}
`); +} + +function activityHtml(r) { + if (r.status === 'rejected') return failedMsg('Aktivitas Agent', r); + const turns = r.value; + if (!turns.length) return cardHtml('Aktivitas Agent', emptyBody('Belum ada aktivitas tercatat. Pastikan memory.trace_path diisi di config NetOps Agent.')); + const calls = turns.reduce((n, t) => n + t.toolCalls, 0); + const errs = turns.reduce((n, t) => n + t.errors + t.timeouts, 0); + const rate = calls ? Math.round((errs / calls) * 100) : 0; + const stat = (label, val) => `

${label}

+

${val}

`; + const rows = turns.slice(0, 8).map(t => ` +
+ ${esc(fmtFullDateTime(t.at))} + ${esc(t.message || '—')} + ${t.toolCalls} tool · ${t.durationS.toFixed(1)}s + ${t.errors + t.timeouts ? badge(`${t.errors + t.timeouts} error`, 'red') : ''} +
`).join(''); + return cardHtml(`Aktivitas Agent (${turns.length} turn terakhir)`, ` +
${stat('TURN', turns.length)}${stat('TOOL CALL', calls)}${stat('ERROR / TIMEOUT', `${errs} (${rate}%)`)}
+
${rows}
`); +} diff --git a/frontend/js/screens/login.js b/frontend/js/screens/login.js new file mode 100644 index 0000000..3ff1e72 --- /dev/null +++ b/frontend/js/screens/login.js @@ -0,0 +1,73 @@ +import { $, esc } from '../utils.js'; +import { mgr } from '../manager.js'; + +// Faint "connected network" tile: nodes joined by thin lines. Lines that leave the +// tile are repeated at the opposite edge so the pattern tiles without seams. +const NODES = [[30, 40], [120, 20], [200, 90], [90, 130], [190, 200], [40, 210], [130, 240]]; +const LINKS = [[0, 1], [1, 2], [0, 3], [3, 2], [3, 5], [3, 4], [2, 4], [5, 6], [4, 6], [1, 3]]; +function networkTile() { + const T = 240; + const at = (i, dx, dy) => `${NODES[i][0] + dx},${NODES[i][1] + dy}`; + const seg = (p, q) => { + const [x1, y1] = p.split(','), [x2, y2] = q.split(','); + return ``; + }; + const line = ([a, b]) => seg(at(a, 0, 0), at(b, 0, 0)); + // Each wrapping link is drawn twice: leaving this tile, and entering it from the previous one. + const wrap = [[4, 5, T, 0], [2, 0, T, 0], [6, 1, 0, T]] + .map(([a, b, dx, dy]) => seg(at(a, 0, 0), at(b, dx, dy)) + seg(at(a, -dx, -dy), at(b, 0, 0))).join(''); + const dots = NODES.map(([x, y]) => ``).join(''); + const svg = ` + ${LINKS.map(l => line(l)).join('')}${wrap} + ${dots}`; + return `url('data:image/svg+xml,${encodeURIComponent(svg)}')`; +} + +// Full-page login shown instead of the app shell until a session exists. +// Calls onSuccess({ username }) after a successful login. +export function renderLogin(onSuccess, notice = '') { + $('app').innerHTML = ` +
+ LLMNetOps +
+

Masuk

+ + + + + + +
+ +
`; + + const err = $('login-error'); + $('login-username').focus(); + $('login-form').onsubmit = async e => { + e.preventDefault(); + const btn = $('login-submit'); + btn.disabled = true; + btn.textContent = 'Memeriksa...'; + err.classList.add('hidden'); + try { + const u = await mgr('/auth/login', { method: 'POST', body: { username: $('login-username').value.trim(), password: $('login-password').value } }); + onSuccess(u); + } catch (ex) { + err.textContent = ex.message; + err.classList.remove('hidden'); + $('login-password').value = ''; + $('login-password').focus(); + btn.disabled = false; + btn.textContent = 'Masuk'; + } + }; +} diff --git a/frontend/js/screens/nodes.js b/frontend/js/screens/nodes.js new file mode 100644 index 0000000..468be2c --- /dev/null +++ b/frontend/js/screens/nodes.js @@ -0,0 +1,244 @@ +import { esc, pageHeader, $, confirmDialog } from '../utils.js'; +import { activeBackend } from '../backends/index.js'; + +const FIELDS = [ + { id: 'name', label: 'Nama', placeholder: 'core-gw-01', required: true }, + { id: 'mgmt_ip', label: 'IP Manajemen', placeholder: '192.168.99.1', required: true, mono: true }, + { id: 'manufacture', label: 'Vendor', placeholder: 'mikrotik', list: ['mikrotik'], required: true }, + { id: 'os_version', label: 'Versi OS', placeholder: 'ros7', list: ['ros6', 'ros7'], required: true }, + { id: 'role', label: 'Role', placeholder: 'gateway', list: ['gateway', 'core', 'distribution', 'access'], required: true }, + { id: 'network_type', label: 'Tipe Jaringan', placeholder: 'kampus', required: true }, + { id: 'port', label: 'Port SSH', placeholder: '22', type: 'number', mono: true }, + { id: 'username', required: true, label: 'Username SSH', placeholder: 'admin', mono: true, credential: true }, + { id: 'password', required: true, label: 'Password SSH', type: 'password', mono: true, credential: true }, + { id: 'username_env', required: true, label: 'Username env', placeholder: 'NODE_USER', mono: true }, + { id: 'password_env', required: true, label: 'Password env', placeholder: 'NODE_PASS', mono: true }, +]; + +const INPUT_CLS = 'w-full px-3 py-2 border border-outline-variant rounded text-body-sm bg-surface-container-lowest focus:outline-none focus:ring-1 focus:ring-primary disabled:bg-surface-container disabled:text-on-surface-variant'; + +// Nodes are managed through the active backend's /devices API. The list never +// carries credentials, so the detail view shows only the env var names and the +// edit form leaves username/password blank to mean "unchanged". +export async function screenNodes(c) { + const backend = activeBackend(); + if (!backend.capabilities.devices) { + c.innerHTML = `
+ ${pageHeader('Nodes', 'Kelola node jaringan.')} +
+ Backend aktif (${esc(backend.label)}) belum menyediakan API node. Pilih NetOps Agent di Settings. +
`; + return; + } + + let devices = []; + let loadError = null; + let mode = { type: 'add' }; // add | view | edit, the latter two carry `name` + + c.innerHTML = `
+ ${pageHeader('Nodes', 'Kelola perangkat jaringan NetOps Agent. Pilih node di tabel untuk melihat detail.', ` + `)} +
+
+
+
+

Managed Nodes

+
+
+ + + + + +
NameHostRole / Network
Memuat…
+
+
+
+
+
+
`; + + const find = name => devices.find(d => d.name === name); + const setMsg = (text, kind) => { + const m = $('nd-msg'); + if (!m) return; + m.className = 'text-body-sm ' + ({ ok: 'text-green-700', err: 'text-red-700' }[kind] || 'text-on-surface-variant'); + m.textContent = text; + }; + + function renderTable() { + const tb = $('nd-tbody'); + $('nd-count').textContent = loadError ? '' : `(${devices.length})`; + if (loadError) { + tb.innerHTML = `Gagal memuat daftar node: ${esc(loadError)}`; + return; + } + if (!devices.length) { + tb.innerHTML = `Belum ada node. Klik "Add Node".`; + return; + } + tb.innerHTML = devices.map(d => { + const selected = mode.name === d.name; + return ` +

${esc(d.name)}

+ ${esc(d.mgmt_ip || '—')}${d.port && d.port !== 22 ? ':' + esc(String(d.port)) : ''} + ${esc(d.role || '—')} / ${esc(d.network_type || '—')} + + + + `; + }).join(''); + tb.querySelectorAll('[data-row]').forEach(tr => { tr.onclick = () => show({ type: 'view', name: tr.dataset.row }); }); + tb.querySelectorAll('[data-edit]').forEach(b => { b.onclick = e => { e.stopPropagation(); show({ type: 'edit', name: b.dataset.edit }); }; }); + tb.querySelectorAll('[data-del]').forEach(b => { b.onclick = e => { e.stopPropagation(); removeNode(b.dataset.del); }; }); + } + + function renderDetail(d) { + const row = (label, value, mono) => `
+

${label}

+

${value ? esc(String(value)) : '—'}

`; + $('nd-panel').innerHTML = `
+
+

${esc(d.name)}

+

Detail node

+
+ + +
+
+
+ ${row('IP Manajemen', d.mgmt_ip, true)}${row('Port SSH', d.port, true)} + ${row('Vendor', d.manufacture)}${row('Versi OS', d.os_version)} + ${row('Role', d.role)}${row('Tipe Jaringan', d.network_type)} + ${row('Username env', d.username_env, true)}${row('Password env', d.password_env, true)} +
+
+ Username dan password SSH tersimpan di backend dan tidak ditampilkan.
+
`; + $('nd-edit').onclick = () => show({ type: 'edit', name: d.name }); + $('nd-del').onclick = () => removeNode(d.name); + } + + function renderForm(existing) { + const editing = !!existing; + $('nd-panel').innerHTML = `
+
+

${editing ? 'Edit ' + esc(existing.name) : 'Add Node'}

+

${editing + ? 'Nama tidak dapat diubah. Kosongkan username/password SSH untuk tidak mengubahnya.' + : 'Kredensial SSH dikirim ke NetOps Agent dan tidak ditampilkan kembali.'}

+
+
+ ${FIELDS.map(f => { + const required = f.required && !(editing && f.credential); + const placeholder = editing && f.credential ? 'Tidak diubah' : f.placeholder || ''; + return `
+ + + ${f.list ? `${f.list.map(v => `` : ''} +
`; + }).join('')} +
+
+ + ${editing ? '' : ''} + +
+
`; + if (editing) $('nd-cancel').onclick = () => show({ type: 'view', name: existing.name }); + $('nd-form').addEventListener('submit', e => { e.preventDefault(); submit(existing); }); + } + + function show(next) { + mode = next; + const d = next.name ? find(next.name) : null; + if (next.name && !d) mode = { type: 'add' }; + renderTable(); + if (mode.type === 'view') renderDetail(d); + else renderForm(mode.type === 'edit' ? d : null); + } + + async function refresh() { + try { + devices = await backend.listDevices(); + loadError = null; + } catch (err) { + devices = []; + loadError = err.message; + } + } + + async function submit(existing) { + const body = {}; + for (const f of FIELDS) { + const v = $('nd-' + f.id).value.trim(); + if (!v) continue; + body[f.id] = f.type === 'number' ? Number(v) : v; + } + if (existing) { + delete body.name; // the name is the URL identifier and cannot be changed + if (!body.username !== !body.password) { + setMsg('Username dan password SSH harus diisi keduanya, atau dikosongkan keduanya.', 'err'); + return; + } + } + const btn = $('nd-save'); + btn.disabled = true; + setMsg('Menyimpan…'); + try { + if (existing) { + await backend.updateDevice(existing.name, body); + await refresh(); + show({ type: 'view', name: existing.name }); + } else { + const d = await backend.addDevice(body); + await refresh(); + show({ type: 'view', name: d.name }); + } + } catch (err) { + setMsg(explain(err, existing ? 'PATCH' : 'POST'), 'err'); + btn.disabled = false; + } + } + + async function removeNode(name) { + const ok = await confirmDialog({ + title: 'Hapus node', + message: `Hapus node "${name}" dari inventory NetOps Agent?\nAgent tidak akan bisa lagi mengelola perangkat ini.`, + confirmLabel: 'Hapus', + danger: true, + }); + if (!ok) return; + try { + await backend.deleteDevice(name); + } catch (err) { + await confirmDialog({ title: 'Gagal menghapus', message: explain(err, 'DELETE'), confirmLabel: 'OK', cancelLabel: null }); + return; + } + await refresh(); + show({ type: 'add' }); + } + + // FastAPI answers a route that does not exist with exactly {"detail":"Not Found"}; + // a real "node missing" error from the agent would carry its own message. + function explain(err, method) { + if (err.status === 405 || (err.status === 404 && err.message.endsWith(': Not Found'))) { + return `NetOps Agent belum menyediakan endpoint ${method} /devices/{name}. (${err.message})`; + } + if (err.status === 404) return `Node tidak ditemukan di inventory. (${err.message})`; + if (err.status === 400) return `Permintaan ditolak: ${err.message}`; + return err.message; + } + + $('nd-new').onclick = () => show({ type: 'add' }); + renderTable(); + renderForm(null); + await refresh(); + show({ type: 'add' }); +} diff --git a/frontend/js/screens/settings-llm.js b/frontend/js/screens/settings-llm.js new file mode 100644 index 0000000..abd3b6a --- /dev/null +++ b/frontend/js/screens/settings-llm.js @@ -0,0 +1,232 @@ +import { $, esc, badge, loadingHtml, errorHtml, confirmDialog, alertDialog } from '../utils.js'; +import { BACKENDS, activeBackend } from '../backends/index.js'; +import { mgr } from '../manager.js'; + +// LLM provider profiles live in NetOpsUI (API key write-only: the manager never +// returns it). "Terapkan" writes a provider into a backend's config.yaml +// `model:` block; the backend must be restarted afterwards to pick it up. + +const slugify = s => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64); +const KEY_SRC = { + env: ['key di env backend', 'blue'], + literal: ['tertulis di config', 'amber'], + none: ['tanpa key', 'gray'], +}; + +export async function renderLlm(el) { + let providers = [], editing = null, applying = null; + const modelCache = {}; // slug or '_form' → model ids from the last connection test + + el.innerHTML = ` +
+
+
+

LLM yang sedang dipakai backend

+

Dibaca dari config.yaml masing-masing backend.

+ +
+
${loadingHtml('Memuat...')}
+
+
+
+

Provider Tersimpan

+

Endpoint OpenAI-compatible (Ollama, vLLM, LM Studio, OpenAI, dll.). API key disimpan di server NetOpsUI dan tidak pernah dikirim balik ke browser.

+ +
+ +
${loadingHtml('Memuat...')}
+
+
`; + + // ── current per-backend LLM ──────────────────────────────────────────────── + async function loadCurrent() { + const box = $('llm-current'); + box.innerHTML = loadingHtml('Memuat...'); + const rows = await Promise.all(Object.values(BACKENDS).map(async b => { + try { return [b, await mgr(`/backends/${b.id}/llm`), null]; } + catch (e) { return [b, null, e.message]; } + })); + box.innerHTML = `
${rows.map(([b, d, err]) => { + if (err) return `
${esc(b.label)} ${errorHtml(err)}
`; + if (!d.exists) return `
${esc(b.label)} config.yaml tidak ditemukan
`; + const [ks, kv] = KEY_SRC[d.key_source]; + const deleg = (d.delegation || []).length + ? `

Agent delegasi: ${d.delegation.map(x => `${esc(x.agent)} → ${esc(x.model || '—')}`).join(', ')}

` : ''; + return `
+

${esc(b.label)}

+ ${d.key_ref ? `${esc(d.key_ref)}` : ''}${badge(ks, kv)}
+

${esc(d.model || '—')} + · ${esc(d.base_url || '—')}${d.provider ? ' · provider: ' + esc(d.provider) : ''}

${deleg}
`; + }).join('')}
`; + } + + // ── provider list ────────────────────────────────────────────────────────── + function renderList() { + const box = $('llm-list'); + if (!providers.length) { + box.innerHTML = `

Belum ada provider. Klik Tambah Provider.

`; + return; + } + box.innerHTML = `
${providers.map(p => ` +
+
+
+

${esc(p.name)} ${p.has_key ? badge('key tersimpan', 'green') : badge('tanpa key', 'gray')}

+

${esc(p.model || '(model belum dipilih)')} · ${esc(p.base_url)}

+
+ + + +
+ ${applying === p.slug ? applyPanel(p) : ''} +
`).join('')}
`; + box.querySelectorAll('[data-edit]').forEach(b => { b.onclick = () => openForm(providers.find(p => p.slug === b.dataset.edit)); }); + box.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => del(b.dataset.del); }); + box.querySelectorAll('[data-apply]').forEach(b => { b.onclick = () => { applying = applying === b.dataset.apply ? null : b.dataset.apply; renderList(); }; }); + if (applying) bindApply(providers.find(p => p.slug === applying)); + } + + // ── add / edit form ──────────────────────────────────────────────────────── + function openForm(p) { + editing = p || null; + const f = $('llm-form'); + f.classList.remove('hidden'); + f.innerHTML = `
+

${p ? 'Ubah provider' : 'Tambah provider'}

+
+ + + + +
+ ${p?.has_key ? `` : ''} +
+ + +
+
+ + + +
`; + $('lp-cancel').onclick = closeForm; + $('lp-test').onclick = testConn; + $('lp-save').onclick = save; + } + + function closeForm() { editing = null; $('llm-form').classList.add('hidden'); $('llm-form').innerHTML = ''; } + + async function testConn() { + const out = $('lp-test-out'); + out.className = 'text-body-sm text-on-surface-variant'; + out.textContent = 'Memeriksa...'; + try { + const r = await mgr('/llm/test', { method: 'POST', body: { + base_url: $('lp-url').value.trim(), api_key: $('lp-key').value || undefined, provider: editing?.slug } }); + if (r.ok) { + modelCache[editing?.slug || '_form'] = r.models; + $('lp-models').innerHTML = r.models.map(m => `