Files
NeoTachyon/tachyon/files/usr/lib/tachyon/rag_index.json
T
Dushnilin 7f0b085a07 feat(tailscale): нативный режим tailscaled и компонент Tailscale
- новый компонент Tailscale: установка пакета из фида, карточка в Обновлениях
- режим native для секций Tailscale: системный tailscaled вместо sing-box endpoint
- доступ к тейлнету с LAN без клиента: маршруты 100.64.0.0/10 и MagicDNS через dnsmasq
- masquerade и exit-node (opt-in) с обходом tproxy по зарезервированной маске
- validator: требование tailscaled и auth-key для native; bypass-правила в mangle
- тесты: генерация конфига, смоук рантайма с моками, обновлена сигнатура состояния
2026-08-26 11:30:52 +03:00

1 line
76 KiB
JSON
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"version": 1, "chunk_size": 2000, "chunk_overlap": 200, "total_chunks": 40, "files": ["01_SYSTEM_ARCHITECTURE.md", "02_UCODE_MODULE_REFERENCE.md", "03_NETWORKING_NFTABLES_AND_ROUTING.md", "04_DPI_BYPASS_ENGINES.md", "05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md", "06_FRONTEND_LUCI_TYPESCRIPT.md", "07_BUILD_TESTS_AND_DEPLOYMENT.md", "08_UCI_CONFIGURATION_SCHEMA.md", "09_TELEGRAM_BOT_ARCHITECTURE.md", "10_HOSTS_ENGINE_AND_BLOCKLISTS.md", "11_TROUBLESHOOTING_AND_FIELD_MANUAL.md", "12_UCODE_PROGRAMMING_PATTERNS.md", "13_REST_API_AND_MCP_SPECIFICATION.md", "INDEX.md"], "chunks": [{"id": 0, "file": "01_SYSTEM_ARCHITECTURE.md", "heading": "2.2. Deterministic State & Atomic Writes", "text": "# 01. System Architecture & Core Concepts\n\n## 1. High-Level Overview\n\n**Tachyon** is an enterprise-grade, lightweight traffic orchestration, multi-protocol proxying, and DPI anti-censorship platform built natively for **OpenWrt** (supporting 23.05, 24.10, 25.x, and SNAPSHOT).\n\n```mermaid\ngraph TD\n Client[LAN Clients] -->|TCP/UDP| Router[OpenWrt Router]\n Router --> NFT[nftables: inet TachyonTable]\n \n NFT -->|Direct List / 0ms| WAN[Direct WAN Gateway]\n NFT -->|NFQueue Desync| Zapret[Zapret v1 / v2 nfqws/2]\n NFT -->|SOCKS Desync| ByeDPI[ByeDPI ciadpi]\n NFT -->|TProxy / Redirect| SingBox[sing-box Core v1.11+]\n \n SingBox -->|VLESS Reality / H2 / WG| VPS[External VPS / Global Web]\n Zapret --> WAN\n ByeDPI --> WAN\n \n subgraph Tachyon Control Plane\n UCODE[ucode Core Runtime] --> NFT\n UCODE --> SingBox\n UCODE --> Zapret\n UCODE --> ByeDPI\n Watchdog[Autonomous Watchdog 5-15s] --> UCODE\n AIDoctor[AI Doctor v2.5 / Local Doctor] --> Watchdog\n Telegram[Telegram Bot Daemon] --> UCODE\n RestAPI[HTTP REST Agent API / OpenAPI 3.0] --> UCODE\n LuCI[LuCI TypeScript Web UI] --> UCODE\n end\n```\n\n---\n\n## 2. Core Architectural Pillars\n\n### 2.1. Native ucode Runtime (Zero Heavy Runtimes)\n* All control plane logic, UCI manipulation, config generation, health checks, and JSON APIs are written in **ucode**, OpenWrt's native C-like scripting language.\n* **Benefits**:\n * Consumes $\\approx$ 1–3 MB RAM (contrasted with 30–60 MB for Python/Node).\n * Executes directly in C-speed with native bindings to `libuci`, `libubus`, `libblobmsg`, and posix syscalls (`fs`, `math`, `socket`).\n * Runs on routers with as little as 128 MB RAM.\n\n### 2.2. Deterministic State & Atomic Writes\n* All configuration changes (`/etc/config/tachyon`) and JSON runtime configurations (`/tmp/tachyon/sing-box.json`) use an **atomic write pattern** (`tmp_file + rename`):\n ```ucode\n fs.writefile(tmp_path, json_str);\n fs.rename(tmp_path, target_path);", "embedding": []}, {"id": 1, "file": "01_SYSTEM_ARCHITECTURE.md", "heading": "3. Directory Layout & Repository Anatomy", "text": "* All configuration changes (`/etc/config/tachyon`) and JSON runtime configurations (`/tmp/tachyon/sing-box.json`) use an **atomic write pattern** (`tmp_file + rename`):\n ```ucode\n fs.writefile(tmp_path, json_str);\n fs.rename(tmp_path, target_path);\n ```\n This prevents file corruption during sudden power losses or kernel panics.\n\n### 2.3. Dual Control Interfaces: LuCI & Headless Telegram/REST\n1. **LuCI Web UI**: Modern TypeScript SPA (`fe-app-tachyon`) compiled into LuCI JS assets (`luci-app-tachyon`).\n2. **Interactive Telegram Bot**: Embedded polling daemon with inline keyboards for on-the-fly server switching, rule updates, and instant diagnostics.\n3. **HTTP REST Agent API**: Secure CGI endpoint (`/cgi-bin/tachyon-agent/`) with OpenAPI 3.0.3 spec for integration with LLM agents (ChatGPT Custom GPTs, Cursor, Claude Code, N8N).\n\n---\n\n## 3. Directory Layout & Repository Anatomy\n\n```\ntachyon/\n├── tachyon/files/ # Core backend package root\n│ ├── etc/\n│ │ ├── config/tachyon # Main UCI configuration (chmod 600)\n│ │ ├── init.d/tachyon # Procd service init script\n│ │ └── uci-defaults/ # Post-installation default configs\n│ ├── usr/\n│ │ ├── bin/tachyon # Main CLI entrypoint wrapper\n│ │ └── lib/tachyon/ # Modular ucode libraries (60+ modules)\n│ │ ├── core/ # Low-level helpers, UCI, constants\n│ │ ├── service/ # Lifecycle, Watchdog, APIs, Telegram\n│ │ ├── diagnostics/ # AI Doctor, Local Doctor, Quick Fixes\n│ │ ├── singbox/ # Config generator, DNS, routing\n│ │ ├── providers/ # Zapret v1/v2, ByeDPI, NFQueue\n│ │ ├── nft/ # nftables ruleset compiler & applier\n│ │ ├── dns/ # dnsmasq & DNS routing coordinator\n│ │ ├── components/ # Updater, package manager, hosts\n│ │ ├── config/ # Validator, rule engine, migrations", "embedding": []}, {"id": 2, "file": "01_SYSTEM_ARCHITECTURE.md", "heading": "4. Key Runtime Processes & Daemons", "text": "│ │ ├── dns/ # dnsmasq & DNS routing coordinator\n│ │ ├── components/ # Updater, package manager, hosts\n│ │ ├── config/ # Validator, rule engine, migrations\n│ │ └── subscription/ # Subscriptions fetcher & parser\n├── luci-app-tachyon/ # OpenWrt LuCI package\n│ ├── htdocs/luci-static/resources/view/tachyon/ # Compiled frontend JS bundle\n│ ├── root/etc/uci-defaults/ # LuCI menu registration\n│ └── po/ # Translations (ru, en)\n├── fe-app-tachyon/ # Frontend TypeScript source\n│ ├── src/ # TypeScript SPA source\n│ ├── tsup.config.ts # Builds and patches LuCI baseclass\n│ └── package.json # Dependencies (vitest, typescript, tsup)\n├── tests/ # Comprehensive test suite (100+ shell tests)\n├── build.sh # Release packager (ipk + apk)\n├── install.sh # One-liner end-user installer\n└── docs/ # Technical documentation & Knowledge Base\n```\n\n---\n\n## 4. Key Runtime Processes & Daemons\n\n| Process | Role | Execution Model |\n|---|---|---|\n| `sing-box` | Core proxying & packet tunneling engine | Managed by procd (`/etc/init.d/tachyon`) |\n| `nfqws` / `nfqws2` | Local TCP/UDP packet desynchronizer (Zapret) | Spawned into background per configured rule |\n| `ciadpi` | Local SOCKS desync proxy (ByeDPI) | Spawned on `127.0.0.1:1080` / custom port |\n| `watchdog.uc` | State supervision, loop mitigation, self-healing | Background periodic daemon (every 5–15s) |\n| `telegram.uc` | Telegram Bot Long-Polling Daemon | Procd-supervised background worker |\n| `agent_api.uc` | HTTP REST Agent API Handler | Invoked on-demand via `uhttpd` CGI |", "embedding": []}, {"id": 3, "file": "02_UCODE_MODULE_REFERENCE.md", "heading": "2. Service Management Subsystem (`service/`)", "text": "# 02. ucode Backend Module Reference\n\nTachyon's backend is modularized under `tachyon/files/usr/lib/tachyon/`. Modules are loaded dynamically via ucode's `require()` or executed directly via `ucode -L <lib_dir> <module> <command>`.\n\n---\n\n## 1. Core Subsystem (`core/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `constants.uc` | Central repository of paths, default ports, mark values, version detection (`detect_installed_version()`), commit SHA resolver (`detect_installed_commit_sha()`), UCI config names. |\n| `common.uc` | String manipulation (`trim`, `split_lines`), file helpers (`read_file`, `write_atomic`), logging formatters (`log_info`, `log_error`, `log_debug`). |\n| `helpers.uc` | Process management (`popen_read`, `system_exec`), CIDR formatting, MAC address validators, integer conversions with safety fallbacks. |\n| `ip.uc` | IP v4/v6 parser, subnet containment (`ip_in_subnet`), CIDR validator, loopback & private IP range detection. |\n| `url.uc` | RFC 3986 URL parser, extraction of scheme, host, port, path, query params, hash fragment, safe URL encoding/decoding. |\n| `uci.uc` | High-level wrapper over OpenWrt `libuci`: `get_section`, `set_option`, `add_section`, `delete_section`, atomic commit with lock. |\n| `packages.uc` | Package manager abstraction: detects `opkg` vs `apk` (OpenWrt 25.x+), checks installed packages, versions, and dependencies. |\n| `events.uc` | Internal event bus mechanism: publish/subscribe for service state transitions and notification dispatching. |\n\n---\n\n## 2. Service Management Subsystem (`service/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `lifecycle.uc` | Service start, stop, restart, enable, disable. Coordinates teardown order (nftables -> singbox -> zapret -> dnsmasq) to prevent routing deadlocks. |\n| `state.uc` | Comprehensive runtime state reader (`get_runtime_state()`): active proxy server, watchdog status, interface health, uptime, memory consumption. |\n| `reload.uc` | Hot-reload planner (`plan_reload()`): inspects what changed in UCI and applies the minimal necessary restart (e.g. soft-reload sing-box vs full nftables rebuild). |", "embedding": []}, {"id": 4, "file": "02_UCODE_MODULE_REFERENCE.md", "heading": "3. Diagnostics & AI Subsystem (`diagnostics/`)", "text": "| `state.uc` | Comprehensive runtime state reader (`get_runtime_state()`): active proxy server, watchdog status, interface health, uptime, memory consumption. |\n| `reload.uc` | Hot-reload planner (`plan_reload()`): inspects what changed in UCI and applies the minimal necessary restart (e.g. soft-reload sing-box vs full nftables rebuild). |\n| `reset.uc` | Factory reset routines: wipes `/etc/config/tachyon`, cleans up temporary caches, restores default templates. |\n| `watchdog.uc` | Autonomous supervisor loop: checks sing-box process, memory thresholds (OOM guard), DNS resolution, loop-restart mitigation (`safe_proxy_restart`). |\n| `snapshot.uc` | Assembles a structured system snapshot JSON for AI Doctor and external diagnostics. |\n| `agent_api.uc` | CGI handler for `/cgi-bin/tachyon-agent/`: handles routing, Bearer authentication validation, endpoint dispatch, JSON serialization. |\n| `agent_mcp.uc` | Model Context Protocol (MCP) tool schema and handlers for integration with MCP clients (Cursor, Claude Desktop). |\n| `telegram.uc` | Telegram Bot daemon: polling loop (`getUpdates`), command dispatcher (`/doctor`, `/ai_doctor`, `/fix`, `/restart`, `/status`), inline keyboards. |\n| `warp_generator.uc` | Cloudflare WARP account generator & key exchange for auto-provisioning WireGuard outbounds. |\n| `event_controller.uc` | Coordinates async background job workers, PID tracking, lock files, and log ring-buffer management. |\n\n---\n\n## 3. Diagnostics & AI Subsystem (`diagnostics/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `runtime.uc` | **Local Rule Doctor & AI Doctor engine**: runs 10+ local heuristic checks, detects NTP desync, conntrack overflow, MTU issues, bootstrap DNS deadlock; applies 13+ quick fix codes (`apply_quick_fix()`), executes emergency internet restoration (`restore_native_internet()`). |\n| `service_check.uc` | Health probes: tests sing-box TCP/UDP proxying, DNS response latency, WAN internet connectivity, gateway reachability. |\n| `status.uc` | Detailed diagnostics status assembler for LuCI Diagnostic tab and CLI `tachyon doctor`. |", "embedding": []}, {"id": 5, "file": "02_UCODE_MODULE_REFERENCE.md", "heading": "5. Providers & DPI Bypass Subsystem (`providers/`)", "text": "| `service_check.uc` | Health probes: tests sing-box TCP/UDP proxying, DNS response latency, WAN internet connectivity, gateway reachability. |\n| `status.uc` | Detailed diagnostics status assembler for LuCI Diagnostic tab and CLI `tachyon doctor`. |\n\n---\n\n## 4. sing-box Subsystem (`singbox/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `generator.uc` | Master sing-box JSON configuration compiler (`/tmp/tachyon/sing-box.json`): binds inbounds, outbounds, routing rules, DNS, experimental. |\n| `generator_outbounds.uc` | Compiles VLESS (Reality/gRPC/WS), VMess, Shadowsocks, Trojan, Hysteria2, WireGuard, Direct, and Block outbounds. |\n| `generator_routes.uc` | Compiles routing rules: domain matchers, IP CIDR matchers, GeoIP rules, client MAC/IP matchers, detour assignments. |\n| `dns.uc` | Compiles sing-box DNS configuration: local DNS, remote DoH/DoT/UDP DNS, fakeip/direct resolution rules. |\n| `dns_failover.uc` | High-availability DNS failover logic: switches between primary and secondary bootstrap DNS upon timeouts. |\n| `dns_prefetch.uc` | Domain pre-fetching & cache warming for frequently accessed sites. |\n| `dns_presets.uc` | Built-in DNS presets (Cloudflare, Google, AdGuard, Quad9, OpenDNS, Custom DoH). |\n| `priority.uc` | Outbound group priority manager: auto-failover, fallback groups, URL-test latency sorting. |\n| `route.uc` | Low-level sing-box route rule builder & selector logic. |\n| `rulesets.uc` | Rule-set binary (`.srs`) and JSON ruleset compiler and parser. |\n| `servers.uc` | Server node parser, validator, and URI serializer (VLESS, VMess, SS, Trojan, H2). |\n| `subscription.uc` | Subscriptions processor: download, base64 decoding, node deduplication, format normalizer. |\n| `urltest.uc` | RTT ping & latency testing worker: measures real response times across proxy servers. |\n\n---\n\n## 5. Providers & DPI Bypass Subsystem (`providers/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `zapret/runtime.uc` | Manages **Zapret v1 (`nfqws`)** process arguments, queue numbers, NFQueue bindings, daemon start/stop. |", "embedding": []}, {"id": 6, "file": "02_UCODE_MODULE_REFERENCE.md", "heading": "7. Configuration & Components Subsystem (`config/`, `components/`, `subscription/`)", "text": "## 5. Providers & DPI Bypass Subsystem (`providers/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `zapret/runtime.uc` | Manages **Zapret v1 (`nfqws`)** process arguments, queue numbers, NFQueue bindings, daemon start/stop. |\n| `zapret2/runtime.uc` | Manages **Zapret v2 (`nfqws2`)** advanced multi-vector desync arguments (`--dpi-desync=multisplit`, `--dpi-desync-seqovl`). |\n| `byedpi/runtime.uc` | Manages **ByeDPI (`ciadpi`)** SOCKS5 proxy daemon, port allocation, payload split parameters. |\n| `nfqueue/runtime.uc` | Kernel NFQueue allocation table, prevents queue ID collisions between Zapret v1 and v2. |\n| `rules.uc` | Maps UCI routing rules to specific provider action handlers (`action = zapret | zapret2 | byedpi | proxy`). |\n| `status.uc` | Real-time process inspection and health monitoring of all active DPI bypass daemons. |\n\n---\n\n## 6. Networking & Firewall Subsystem (`nft/`, `dns/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `nft/apply.uc` | Generates and commits nftables ruleset (`inet TachyonTable`): prerouting, output, divert chains, marks, fwmark, bypass sets. |\n| `dns/apply.uc` | Coordinates DNS interception: configures dnsmasq forwarders, port redirection (`127.0.0.1:5353`), ipset / nftset auto-population. |\n\n---\n\n## 7. Configuration & Components Subsystem (`config/`, `components/`, `subscription/`)\n\n| Module | Key Functions & Responsibilities |\n|---|---|\n| `config/validator.uc` | Strict UCI schema validation: validates IP addresses, ports, UUIDs, private keys, domain names, action modes. |\n| `config/migration.uc` | Automatic migration engine: migrates configurations from legacy Forkop, Podkop Plus, and Podkop configs without data loss. |\n| `components/updater.uc` | Background component installer/updater: handles downloading, unpacking, installing, and version checking of binaries. |\n| `components/hosts.uc` | Remote hosts lists ingestor: fetches blocklists, merges into unified `combined.txt`, handles GitHub mirror failovers. |", "embedding": []}, {"id": 7, "file": "02_UCODE_MODULE_REFERENCE.md", "heading": "7. Configuration & Components Subsystem (`config/`, `components/`, `subscription/`)", "text": "| `components/updater.uc` | Background component installer/updater: handles downloading, unpacking, installing, and version checking of binaries. |\n| `components/hosts.uc` | Remote hosts lists ingestor: fetches blocklists, merges into unified `combined.txt`, handles GitHub mirror failovers. |\n| `subscription/cache.uc` | Atomic subscription cache store, prevents redundant network downloads. |\n| `subscription/parser.uc` | Universal proxy URI parser: parses `vless://`, `vmess://`, `ss://`, `trojan://`, `hysteria2://`, `wireguard://`. |", "embedding": []}, {"id": 8, "file": "03_NETWORKING_NFTABLES_AND_ROUTING.md", "heading": "2.1. Key Chains", "text": "# 03. Networking, nftables & Traffic Routing\n\n## 1. Packet Journey & Routing Lifecycle\n\nTachyon intercepts traffic at the OpenWrt kernel level using **nftables** and policy routing (`ip rule` + routing table `100`).\n\n```mermaid\nsequenceDiagram\n autonumber\n participant Client as LAN Client\n participant PREROUTING as nftables PREROUTING\n participant Sets as nftables Sets (Bypass / Target)\n participant Divert as Detour Action\n participant SingBox as sing-box / Zapret / ByeDPI\n participant WAN as WAN / Internet\n\n Client->>PREROUTING: TCP/UDP SYN Packet (e.g. 192.168.1.100 -> 1.1.1.1:443)\n PREROUTING->>Sets: Check destination IP / Port against Tachyon sets\n alt IP in Bypass Set (Local Subnet / RuNet / Direct)\n Sets->>WAN: Direct Forwarding (0 ms overhead)\n else IP in Target Set or Default Detour\n Sets->>Divert: Mark packet with FWMARK (e.g. 0x10000000)\n Divert->>SingBox: Divert via TProxy / Redir / NFQueue\n SingBox->>WAN: Processed / Encrypted / Desynchronized Outbound\n end\n```\n\n---\n\n## 2. nftables Table Structure (`inet TachyonTable`)\n\nTachyon encapsulates all its firewall rules inside a dedicated table `inet TachyonTable`. This ensures clean isolation from the system `inet fw4` firewall.\n\n### 2.1. Key Chains\n\n1. **`dstnat` / `prerouting` (Hook `prerouting`, priority `-100` / `dstnat`)**:\n * Intercepts incoming LAN client packets before routing decisions.\n * Checks client MAC / IP exclusion lists.\n * Matches destination IP against `tachyon_bypass_v4` / `tachyon_target_v4` sets.\n * Performs TProxy redirect (`tproxy to :10080 meta mark set 0x10000000 accept`) or Port redirect.\n2. **`output` (Hook `output`, priority `-100`)**:\n * Intercepts router's own locally generated packets (e.g. DNS lookups, curl, router traffic).\n * Prevents self-interception loops (`meta skuid == \"tachyon\" return`).\n3. **`nfqueue_chain`**:\n * Directs packets destined for Zapret v1 / v2 to kernel NFQueue numbers (`queue num 200`, `queue num 201`).", "embedding": []}, {"id": 9, "file": "03_NETWORKING_NFTABLES_AND_ROUTING.md", "heading": "3.3. Bootstrap DNS Dead-Lock Prevention", "text": "* Prevents self-interception loops (`meta skuid == \"tachyon\" return`).\n3. **`nfqueue_chain`**:\n * Directs packets destined for Zapret v1 / v2 to kernel NFQueue numbers (`queue num 200`, `queue num 201`).\n\n### 2.2. Bitmask & Firewall Marks\n\n| Mark Value | Meaning | Action |\n|---|---|---|\n| `0x10000000` | Redirected to sing-box TProxy | Routed to local loopback via table 100 |\n| `0x20000000` | Processed by Zapret / NFQueue | Dispatched to nfqws daemon |\n| `0x40000000` | Marked for ByeDPI SOCKS | Forwarded to local SOCKS redirect |\n| `0x80000000` | Bypass marker (Direct WAN) | Accepted immediately without inspection |\n\n---\n\n## 3. DNS Architecture & Interception\n\n### 3.1. DNS Resolution Pipeline\n\n```\n[LAN Client DNS Query: 53]\n │\n ▼\n [dnsmasq / Router]\n │\n ├─► If Domain in Direct / RuNet / Local ──► Local Upstream DNS (ISP / DoH)\n │\n ├─► If Domain in Hosts Section ──────────► Static IP from dns_hosts\n │\n └─► If Domain in Target Proxy / Desync ──► sing-box DNS (127.0.0.1:5353)\n │\n ▼\n [Remote Secure DoH/DoT]\n [Populates nftables set]\n```\n\n### 3.2. Dynamic nftables Set Population (`nftset`)\n* When dnsmasq resolves a domain associated with a proxy or Zapret rule, it automatically adds the resolved IP address to the corresponding kernel nftables set (e.g. `tachyon_target_v4`).\n* This enables sub-millisecond, line-rate packet redirection without re-evaluating domain names in user-space for every packet.\n\n### 3.3. Bootstrap DNS Dead-Lock Prevention\n* A critical failure mode in proxy routers is a **DNS loop**: sing-box needs to resolve the VPS hostname (e.g. `vps.example.com`), but its own DNS resolver routes queries through sing-box, which is not yet connected.", "embedding": []}, {"id": 10, "file": "03_NETWORKING_NFTABLES_AND_ROUTING.md", "heading": "4.1. Emergency Internet Restoration Mechanism", "text": "* A critical failure mode in proxy routers is a **DNS loop**: sing-box needs to resolve the VPS hostname (e.g. `vps.example.com`), but its own DNS resolver routes queries through sing-box, which is not yet connected.\n* **Tachyon's Solution**:\n * Dedicated `direct_resolvers` (Cloudflare `1.1.1.1`, Google `8.8.8.8`) bypass all proxy rules.\n * Local Rule Doctor monitors bootstrap DNS reachability and automatically executes `fix_bootstrap_dns` if a circular dependency is detected.\n\n---\n\n## 4. Policy Routing (`ip rule` & Routing Tables)\n\nTachyon provisions routing table `100`:\n```sh\n# Routing rule for marked packets\nip rule add fwmark 0x10000000/0x10000000 lookup 100 priority 10000\n\n# Local loopback route in table 100\nip route add local default dev lo table 100\n```\n\n### 4.1. Emergency Internet Restoration Mechanism\nWhen `tachyon restore_native_internet` is triggered:\n1. `inet TachyonTable` is atomically deleted: `nft delete table inet TachyonTable`.\n2. Policy routing rule `ip rule del lookup 100` is removed.\n3. dnsmasq configuration is reverted to native upstream forwarders.\n4. sing-box process is stopped cleanly.\n5. Result: Full, native WAN connectivity is restored in under 200 ms without rebooting the router.", "embedding": []}, {"id": 11, "file": "04_DPI_BYPASS_ENGINES.md", "heading": "2.1. Key Desync Strategies", "text": "# 04. DPI Bypass & Desynchronization Engines\n\nTachyon integrates three distinct local packet desynchronization engines that operate entirely on the router hardware without requiring an external proxy server (Zero-VPS mode).\n\n---\n\n## 1. Comparison Matrix: Zapret v1 vs Zapret v2 vs ByeDPI\n\n| Feature | Zapret v1 (`nfqws`) | Zapret v2 (`nfqws2`) | ByeDPI (`ciadpi`) |\n|---|---|---|---|\n| **Binary** | `/usr/bin/nfqws` | `/usr/bin/nfqws2` | `/usr/bin/ciadpi` |\n| **Operating Model** | Kernel NFQueue Intercept | Kernel NFQueue Multi-Q | Local SOCKS5 / TProxy |\n| **Target Protocols** | HTTP, TLS (ClientHello) | HTTP, TLS, QUIC, WireGuard | HTTP, TLS |\n| **Packet Splitting** | `split2`, `disorder`, `fake` | `multisplit`, `seqovl`, `wsize`, `fake` | `--split-pos`, `--disorder`, `--fake` |\n| **Multi-Vector Chains** | Single strategy per rule | Multi-phase composite chains | Composite SOCKS args |\n| **CPU Overhead** | Minimal (< 1%) | Low (< 2%) | Low (< 2%) |\n| **Best For** | Legacy OpenWrt, Basic DPI | YouTube 4K, Discord, TSPU | Non-root users, SOCKS routing |\n\n---\n\n## 2. Desynchronization Techniques Explained\n\nDeep Packet Inspection (DPI) systems inspect packet headers (such as TLS Server Name Indication `SNI` or HTTP `Host` headers) to detect and block access. Desynchronization tricks the DPI into losing track of the connection state while the destination server reconstructs the stream normally.\n\n```\nOriginal Stream: [TLS ClientHello with SNI] ──────────► (Blocked by DPI)\n\nDesynchronized: [Fake Bad Checksum Packet] ──────────► (DPI resets state)\n [Payload Part 1: Snippet] ──────────► (DPI misses SNI)\n [Payload Part 2: Remainder] ─────────► (Server merges stream)\n```\n\n### 2.1. Key Desync Strategies\n\n1. **`split2` / `multisplit`**:\n * Splits the TCP segment right inside the TLS SNI or HTTP Host header. The DPI does not reassemble small fragments, while the end server's TCP stack reconstructs the full buffer seamlessly.\n2. **`disorder` / `disorder2`**:", "embedding": []}, {"id": 12, "file": "04_DPI_BYPASS_ENGINES.md", "heading": "4. NFQueue Multiplexing & Conflict Prevention", "text": "* Splits the TCP segment right inside the TLS SNI or HTTP Host header. The DPI does not reassemble small fragments, while the end server's TCP stack reconstructs the full buffer seamlessly.\n2. **`disorder` / `disorder2`**:\n * Sends the second half of the packet before the first half with appropriate TCP sequence numbers. The DPI sees out-of-order data and skips inspection.\n3. **`fake` / `fake_sni`**:\n * Sends a fake TLS ClientHello packet with a low TTL (Time To Live). The DPI intercepts the fake packet and approves the connection; the packet dies before reaching the destination server.\n4. **`seqovl` (Sequence Overlap)**:\n * Sends a fake packet with overlapping sequence numbers that the server's TCP stack discards while the DPI's state machine is fooled.\n5. **`wsize` (Window Size Manipulation)**:\n * Forces a small TCP window size to prevent DPI from receiving full payloads in single bursts.\n\n---\n\n## 3. Configuration & Runtime Management\n\n### 3.1. Zapret v2 Configuration Example (`/etc/config/tachyon`)\n\n```ini\nconfig provider 'zapret2'\n option enabled '1'\n option daemon_bin '/usr/bin/nfqws2'\n option qnum '201'\n option args_tcp '--dpi-desync=multisplit --dpi-desync-split-pos=1,midsld --dpi-desync-seqovl=1 --dpi-desync-fooling=badseq'\n option args_udp '--dpi-desync=fake --dpi-desync-any-protocol=1 --dpi-desync-cutoff=d4'\n\nconfig rule 'youtube_rule'\n option enabled '1'\n option name 'YouTube 4K Desync'\n option action 'zapret2'\n list domain_pattern 'googlevideo.com'\n list domain_pattern 'youtube.com'\n list domain_pattern 'ytimg.com'\n list domain_pattern 'discord.gg'\n list domain_pattern 'discord.com'\n```\n\n### 3.2. ByeDPI Configuration Example\n\n```ini\nconfig provider 'byedpi'\n option enabled '1'\n option daemon_bin '/usr/bin/ciadpi'\n option listen_ip '127.0.0.1'\n option listen_port '1080'\n option args '--split-pos 1 --disorder 1 --fake -1 --ttl 8'\n```\n\n---\n\n## 4. NFQueue Multiplexing & Conflict Prevention\n\n* Kernel `nfnetlink_queue` requires unique queue numbers per daemon instance.", "embedding": []}, {"id": 13, "file": "04_DPI_BYPASS_ENGINES.md", "heading": "4. AmneziaWG в sing-box-extended: верификация (2026-08)", "text": "option args '--split-pos 1 --disorder 1 --fake -1 --ttl 8'\n```\n\n---\n\n## 4. NFQueue Multiplexing & Conflict Prevention\n\n* Kernel `nfnetlink_queue` requires unique queue numbers per daemon instance.\n* Tachyon's `providers/nfqueue/runtime.uc` dynamically manages queue allocation:\n * Default Zapret v1 queue: `200`\n * Default Zapret v2 queue: `201`\n* If both Zapret v1 and v2 are enabled simultaneously for different rules, Tachyon enforces strict queue isolation and prevents PID collisions.\n\n## 4. AmneziaWG в sing-box-extended: верификация (2026-08)\n\nПроверено против бинарника релиза `v1.13.18-extended-2.6.5` (shtorm-7/sing-box-extended):\n\n- `endpoint.amnezia` полностью реализован: `AmneziaOptions` (`transport/wireguard/endpoint_options.go`)\n → IPC `jc/jmin/jmax/s1-s4/h1-h4/i1-i5` (`transport/wireguard/endpoint.go`)\n → wireguard-go форк `shtorm-7/wireguard-go v0.0.4-extended-1.5.3`:\n I1-I5 шлются отдельными пакетами ПЕРЕД handshake initiation\n (`device/send.go SendHandshakeInitiation`), формат значения — hex-строка.\n- Парсер конфига строгий: неизвестные поля и мусорные значения в `amnezia.*`\n дают FATAL при старте, «молчаливого игнорирования» не существует.\n- Генерация Tachyon (`generator_outbounds.uc add_awg_endpoint`) совпадает со\n схемой форка: peer содержит required `allowed_ips`, `pre_shared_key` и\n `persistent_keepalive_interval` опциональны, hex i1-i5 проходит\n `uci_bin_to_hex` без двойного кодирования.\n\nСледствие для диагностики: если AWG/WARP-туннель «TX есть, RX нет» на\nsing-box-extended, конфиг секции применён корректно — причина вне Tachyon\n(сервер, провайдер, UDP-фильтрация). Чек 6c доктора (1.2.91+) сообщает это\nпользователю по свидетельствам из лога ядра.\n\nКейс «kernel работает, sing-box нет» с идентичным conf остаётся внешним:\nразличие в реализации special-handshake между amneziawg-linux kernel-модом\nи userspace-форком может быть критично только для конкретных строгих\nсерверов. Шаги диагностики для таких случаев:\n\n1. `tcpdump -i any -X udp port <порт>` — сравнить первые байты I1-пакетов", "embedding": []}, {"id": 14, "file": "04_DPI_BYPASS_ENGINES.md", "heading": "4. AmneziaWG в sing-box-extended: верификация (2026-08)", "text": "различие в реализации special-handshake между amneziawg-linux kernel-модом\nи userspace-форком может быть критично только для конкретных строгих\nсерверов. Шаги диагностики для таких случаев:\n\n1. `tcpdump -i any -X udp port <порт>` — сравнить первые байты I1-пакетов\n kernel vs sing-box (у special-handshake пакетов префикс `c7`).\n2. Временно убрать i1-i5 из секции: если handshake поднимется — сервер\n не требует special handshake, а требует его некорректную передачу.\n3. Попробовать вариант ядра sing-box-lx как эксперимент.", "embedding": []}, {"id": 15, "file": "05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md", "heading": "3. Local Rule Doctor & 13 Quick Fix Codes", "text": "# 05. AI Stack, AI Doctor & Autonomous Self-Healing\n\n## 1. Overview of Tachyon AI Stack\n\nTachyon provides a dual-layer AI and autonomous resilience stack:\n1. **Autonomous Layer (Local Rule Doctor & Watchdog)**: Runs locally on the router every 5–15 seconds, detects network drops, memory leaks, DNS deadlocks, and time desync without requiring internet access or API tokens.\n2. **Cognitive Layer (AI Doctor v2.5)**: Deep diagnostics powered by LLMs (OpenAI, Anthropic Claude, DeepSeek, or local Ollama/OpenRouter models) with contextual prompt enrichment and automated Multi-Fix generation.\n3. **Agent Integration Layer (HTTP REST Agent API & OpenAPI 3.0)**: Programmatic interface for autonomous AI agents (Cursor, Claude Code, AutoGPT, ChatGPT Custom GPTs, N8N, Dify).\n\n---\n\n## 2. AI Doctor Architecture (v2.5)\n\n```mermaid\ngraph TD\n subgraph Data Collection\n R1[Process Probes: singbox/zapret/dnsmasq]\n R2[Kernel Metrics: conntrack, mem, uptime]\n R3[Watchdog History: failure streaks, OOM events]\n R4[System Logs: 15 most recent critical lines]\n end\n\n R1 --> Aggregator[snapshot.uc Assembler]\n R2 --> Aggregator\n R3 --> Aggregator\n R4 --> Aggregator\n\n Aggregator --> Prompt[Deep Context LLM Prompt]\n Prompt --> LLM[LLM Provider: OpenAI / Claude / DeepSeek / Custom]\n \n LLM --> Verdict[Structured Diagnosis Report]\n LLM --> MultiFix[Multi-Fix Action Plan: FIX: code1, code2]\n \n MultiFix --> Exec[Local Rule Doctor Execution Engine]\n Exec --> Result[Applied Fixes & Service State Refresh]\n```\n\n---\n\n## 3. Local Rule Doctor & 13 Quick Fix Codes\n\nThe execution engine in `diagnostics/runtime.uc` maps standardized fix codes to automated shell/ucode repair procedures:\n\n| Code | Target Subsystem | Action Performed |\n|---|---|---|\n| `start_singbox` | sing-box | Restarts failed sing-box process via procd. |\n| `rebuild_rules` | nftables | Flushes and recompiles `inet TachyonTable` ruleset. |\n| `fix_dnsmasq` | dnsmasq | Restarts dnsmasq and checks `/tmp/etc/dnsmasq.conf.*`. |", "embedding": []}, {"id": 16, "file": "05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md", "heading": "4.1. Authentication Model", "text": "| `start_singbox` | sing-box | Restarts failed sing-box process via procd. |\n| `rebuild_rules` | nftables | Flushes and recompiles `inet TachyonTable` ruleset. |\n| `fix_dnsmasq` | dnsmasq | Restarts dnsmasq and checks `/tmp/etc/dnsmasq.conf.*`. |\n| `fix_resolv_symlink` | DNS | Restores broken `/etc/resolv.conf` -> `/tmp/resolv.conf.d/resolv.conf.auto` link. |\n| `start_watchdog` | Watchdog | Restarts the background watchdog supervisor process. |\n| `restart_singbox_dns` | sing-box DNS | Resets internal sing-box DNS server module and cache. |\n| `fix_uci_config` | UCI | Restores `/etc/config/tachyon` from the latest valid atomic backup. |\n| `fix_wan_interface` | Networking | Runs `ifup wan` to bounce the primary uplink interface. |\n| `fix_gateway` | Networking | Re-establishes default routing gateway via `/etc/init.d/network restart`. |\n| `clear_dns_cache` | Cache | Flushes dnsmasq cache, deletes sing-box `cache.db`, and restarts DNS. |\n| `update_subscriptions`| Subscriptions | Triggers asynchronous background download and refresh of proxy subscriptions. |\n| `reset_firewall` | Firewall | Full restart of OpenWrt firewall (`/etc/init.d/firewall restart`). |\n| `restart_network` | Network Stack | Full restart of OpenWrt network daemon (`/etc/init.d/network restart`). |\n| `fix_system_time` | System NTP | Resynchronizes router clock via NTP pool servers (`ntpd -q -p ...`). |\n| `flush_conntrack` | Kernel | Flushes congested `nf_conntrack` table during connection floods. |\n| `fix_bootstrap_dns` | Resolver | Unblocks sing-box primary bootstrap resolvers and breaks circular loops. |\n| `optimize_mtu` | Tunnels | Auto-calculates optimal MTU (1280–1420) for WireGuard / AmneziaWG interfaces. |\n| `restore_native_internet` | Emergency | One-click full teardown of Tachyon proxying; returns pure native WAN routing. |\n\n---\n\n## 4. HTTP REST Agent API & OpenAPI 3.0.3\n\nTachyon exposes a standardized REST API hosted under `/cgi-bin/tachyon-agent/` via OpenWrt's native `uhttpd`.\n\n### 4.1. Authentication Model", "embedding": []}, {"id": 17, "file": "05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md", "heading": "4.3. Full Endpoint Index", "text": "| `restore_native_internet` | Emergency | One-click full teardown of Tachyon proxying; returns pure native WAN routing. |\n\n---\n\n## 4. HTTP REST Agent API & OpenAPI 3.0.3\n\nTachyon exposes a standardized REST API hosted under `/cgi-bin/tachyon-agent/` via OpenWrt's native `uhttpd`.\n\n### 4.1. Authentication Model\n* **Read-Only Endpoints**: Accessible within LAN without authentication (or secured via firewall).\n* **Write Endpoints**: Require Bearer token authentication:\n ```http\n POST /cgi-bin/tachyon-agent/ai-doctor/fix\n Authorization: Bearer <agent_api_token>\n Content-Type: application/json\n\n {\"fix\": \"clear_dns_cache,start_singbox\"}\n ```\n\n### 4.2. OpenAPI 3.0.3 Specification\n* The live OpenAPI JSON schema is available at:\n ```\n GET /cgi-bin/tachyon-agent/openapi.json\n ```\n* This schema allows instant import into **ChatGPT Custom GPT Actions**, **N8N HTTP Request Nodes**, **Dify**, and **Flowise**.\n\n### 4.3. Full Endpoint Index\n\n| Method | Endpoint | Auth Required | Description |\n|---|---|---|---|\n| `GET` | `/health` | No | Lightweight JSON health status probe. |\n| `GET` | `/snapshot` | No | Full system snapshot (interfaces, memory, proxy status). |\n| `GET` | `/diagnose` | No | Local Rule Doctor diagnosis report. |\n| `GET` | `/logs` | No | Returns last 100 lines of Tachyon system log. |\n| `GET` | `/config` | No | Returns sanitized UCI configuration. |\n| `GET` | `/tools` | No | OpenAI Function Calling / MCP tool definitions. |\n| `GET` | `/openapi.json` | No | OpenAPI 3.0.3 specification JSON. |\n| `POST`| `/heal` | **Bearer** | Triggers manual Watchdog self-healing cycle. |\n| `POST`| `/ai-doctor/fix` | **Bearer** | Applies one or more quick-fix codes. |\n| `POST`| `/restart` | **Bearer** | Restarts specified service (`singbox`, `watchdog`, `dnsmasq`). |\n| `POST`| `/reload` | **Bearer** | Soft-reloads configuration and routing tables. |\n| `POST`| `/config/set` | **Bearer** | Updates specific UCI options. |\n| `POST`| `/section/toggle` | **Bearer** | Enables or disables a routing rule section. |", "embedding": []}, {"id": 18, "file": "05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md", "heading": "4.3. Full Endpoint Index", "text": "| `POST`| `/reload` | **Bearer** | Soft-reloads configuration and routing tables. |\n| `POST`| `/config/set` | **Bearer** | Updates specific UCI options. |\n| `POST`| `/section/toggle` | **Bearer** | Enables or disables a routing rule section. |\n| `POST`| `/domain/add` | **Bearer** | Appends domain pattern to target rule list. |", "embedding": []}, {"id": 19, "file": "06_FRONTEND_LUCI_TYPESCRIPT.md", "heading": "3.1. Key Services (`src/tachyon/services/`)", "text": "# 06. Frontend Architecture (LuCI & TypeScript)\n\n## 1. Frontend Architecture Overview\n\nTachyon's web UI is authored as a single-page application in **TypeScript** under `fe-app-tachyon/` and compiled into a standalone JavaScript view under `luci-app-tachyon/htdocs/luci-static/resources/view/tachyon/main.js`.\n\n```\nfe-app-tachyon/ (TypeScript Source)\n │\n ▼ (npm run build: tsc --noEmit && tsup)\n │\n[tsup build + baseclass.extend transformation]\n │\n ▼\nluci-app-tachyon/htdocs/luci-static/resources/view/tachyon/main.js (LuCI Asset)\n```\n\n---\n\n## 2. The LuCI `baseclass.extend()` Patch Mechanism\n\nLuCI uses a custom asynchronous class system (`baseclass.extend({...})`) rather than standard ES modules or Webpack bundles.\n\n* `fe-app-tachyon/tsup.config.ts` compiles the TypeScript entry point (`src/main.ts`) into an ES module.\n* A custom post-processing step inside `tsup.config.ts` transforms the compiled file:\n 1. Strips ESM `export default` statements.\n 2. Wraps the controller inside LuCI's expected `return baseclass.extend({...})` pattern.\n 3. Injects global LuCI helper references (`ui`, `rpc`, `uci`, `fs`, `_`).\n\n> [!IMPORTANT]\n> **Do not attempt to convert `main.js` back into a standard ES module export.** This LuCI bridge is intentional and strictly required for compatibility with all OpenWrt web themes (Bootstrap, Material, Argon, OpenWrt-Two).\n\n---\n\n## 3. Reactive State Management & Services\n\nThe frontend does not use heavy external frameworks (like React or Vue) to keep package size minimal ($\\approx$ 500 KB uncompressed, $\\approx$ 90 KB gzipped). Instead, it uses lightweight TypeScript observable stores:\n\n### 3.1. Key Services (`src/tachyon/services/`)\n\n| Service | File | Purpose |\n|---|---|---|\n| `StoreService` | `store.service.ts` | Central reactive data store with subscription listeners. |\n| `UiStateService` | `uiState.service.ts` | Tracks UI view state, tab switching, and modal states. |\n| `RuntimeUiStateService`| `runtimeUiState.service.ts`| Polling and caching of backend service metrics and active jobs. |", "embedding": []}, {"id": 20, "file": "06_FRONTEND_LUCI_TYPESCRIPT.md", "heading": "4.1. The Updates & Installation Modal (`renderUpdateProgressModal.ts`)", "text": "| `UiStateService` | `uiState.service.ts` | Tracks UI view state, tab switching, and modal states. |\n| `RuntimeUiStateService`| `runtimeUiState.service.ts`| Polling and caching of backend service metrics and active jobs. |\n| `SocketService` | `socket.service.ts` | WebSocket client for real-time log streaming when available. |\n| `TachyonLogWatcher` | `tachyonLogWatcher.service.ts`| Logread stream deduplication and notification dispatcher. |\n\n---\n\n## 4. Tabs & UI View Structure\n\n```\nsrc/tachyon/tabs/\n├── dashboard/ # Live status, RTT ping matrix, traffic toggles\n├── diagnostic/ # AI Doctor modal, Local Rule Doctor, Emergency Fallback\n├── rules/ # Selective routing rules, domain/IP lists, client matchers\n├── providers/ # Zapret v1, Zapret v2, ByeDPI configurations\n├── updates/ # Component installer, version checks, streaming log modal\n└── settings/ # DNS settings, Telegram bot credentials, AI Doctor API keys\n```\n\n### 4.1. The Updates & Installation Modal (`renderUpdateProgressModal.ts`)\n* Provides a streaming log console that polls `/usr/bin/tachyon` output asynchronously via `componentActionLog(jobId, offset)`.\n* Features:\n * Non-blocking operation: router performs installation in background.\n * Real-time timer and progress badge.\n * Preserves output logs and green success/red error banners.\n * Prevents premature auto-close so users can inspect package manager details.\n * Graceful countdown timer for Tachyon package reloads.", "embedding": []}, {"id": 21, "file": "07_BUILD_TESTS_AND_DEPLOYMENT.md", "heading": "2.1. Installer Lifecycle", "text": "# 07. Build System, Testing & Deployment Pipeline\n\n## 1. Release Package Compilation (`build.sh`)\n\nTachyon produces both legacy **IPK** (opkg) and modern **APK** (apk-tools, OpenWrt 25.x+) packages.\n\n### 1.1. Running the Build\n\n```bash\nbash build.sh <x.y.z> [output-dir]\n```\n\n* **Semver Requirement**: `build.sh` strictly enforces semantic versioning (`x.y.z`).\n* **Cross-Filesystem WSL Protection**: When executed under Windows Subsystem for Linux (WSL), `build.sh` automatically clones the source repository into the native Linux filesystem (`/tmp/tachyon-build-...`) before packaging to avoid Windows filesystem metadata and permission corruption.\n* **Outputs**:\n * `dist/release-final/tachyon_<version>_all.ipk`\n * `dist/release-final/luci-app-tachyon_<version>_all.ipk`\n * `dist/release-final/tachyon-<version>.apk`\n * `dist/release-final/luci-app-tachyon-<version>.apk`\n\n---\n\n## 2. End-User Installer (`install.sh`)\n\nTachyon provides an automated one-liner installer:\n\n```bash\nwget -O /tmp/tachyon-setup.sh https://raw.githubusercontent.com/Dushnilin/tachyon/main/install.sh && sh /tmp/tachyon-setup.sh\n```\n\n### 2.1. Installer Lifecycle\n1. **Architecture & OS Detection**: Detects OpenWrt version (23.05, 24.10, 25.x, SNAPSHOT), CPU architecture (`mips`, `mipsel`, `arm_cortex-a7`, `aarch64_cortex-a53`, `x86_64`), and package manager (`opkg` vs `apk`).\n2. **Dependency Resolution**: Ensures `ucode`, `ucode-mod-fs`, `ucode-mod-uci`, `ucode-mod-ubus`, `kmod-nft-tproxy`, `kmod-nft-queue`, `ca-bundle` are installed.\n3. **Legacy Migration**: Automatically detects `/etc/config/forkop` or `/etc/config/podkop` and seamlessly migrates all rules and servers to `/etc/config/tachyon`.\n4. **Binary Provisioning**: Downloads pre-compiled, optimized sing-box, Zapret, or ByeDPI binaries tailored for the router's target architecture.\n5. **Zero-Reboot Initialization**: Configures UCI defaults, registers LuCI menus, builds initial rulesets, and starts services without requiring a full router reboot.", "embedding": []}, {"id": 22, "file": "07_BUILD_TESTS_AND_DEPLOYMENT.md", "heading": "4. Key Developer Gotchas & Conventions", "text": "4. **Binary Provisioning**: Downloads pre-compiled, optimized sing-box, Zapret, or ByeDPI binaries tailored for the router's target architecture.\n5. **Zero-Reboot Initialization**: Configures UCI defaults, registers LuCI menus, builds initial rulesets, and starts services without requiring a full router reboot.\n\n---\n\n## 3. Testing Workflows\n\n### 3.1. Frontend Unit Tests (vitest)\n\n```bash\ncd fe-app-tachyon\nnpm test # Runs all 522+ vitest unit tests\nnpm run build # Verifies TypeScript compilation and LuCI bundle packaging\n```\n\n### 3.2. Backend Integration Tests & ucode Syntax Linting\n\nBackend tests require the `ucode` binary. On development machines without local ucode, tests run inside the Docker CI image:\n\n```bash\n# 1. ucode syntax check across all 60+ modules\ndocker run --rm -v \"$(pwd):/mnt\" -w /mnt ucode-ci-img:latest bash tests/ucode_syntax_lint.sh\n\n# 2. Run all backend behavioral and unit tests in parallel (-P4)\ndocker run --rm -v \"$(pwd):/mnt\" -w /mnt ucode-ci-img:latest bash tests/run_all.sh\n\n# 3. Run a specific test\ndocker run --rm -v \"$(pwd):/mnt\" -w /mnt ucode-ci-img:latest bash tests/ai_doctor_local.sh\n```\n\n### 3.3. ShellCheck Linting\n\n```bash\nshellcheck --severity=error build.sh install.sh tachyon/files/etc/init.d/* tests/**/*.sh\n```\n\n---\n\n## 4. Key Developer Gotchas & Conventions\n\n1. **LF Line Endings**: Enforced via `.gitattributes`. Committing CRLF will break shell scripts on OpenWrt target systems.\n2. **`fe-app-tachyon` Package Manager**: Always use `npm` (`npm install`, `npm test`, `npm run build`), not `yarn`.\n3. **Version Placeholder**: `__COMPILED_VERSION_VARIABLE__` in `src/constants.ts` is replaced during `build.sh` packaging. Do not remove it.\n4. **UCI Config Permissions**: `/etc/config/tachyon` must remain `chmod 600` because it can store sensitive Telegram bot tokens and API keys.", "embedding": []}, {"id": 23, "file": "08_UCI_CONFIGURATION_SCHEMA.md", "heading": "1. Section: `config settings 'settings'`", "text": "# 08. Complete UCI Configuration Schema Reference\n\nThe primary configuration for Tachyon is stored at `/etc/config/tachyon` (UCI format, mode `0600`).\n\n---\n\n## 1. Section: `config settings 'settings'`\n\nGlobal settings defining service behaviour, DNS resolution, watchdog parameters, Telegram integration, and AI Doctor.\n\n| Option | Type | Default | Description |\n|---|---|---|---|\n| `enabled` | `boolean` (`0`/`1`) | `1` | Master toggle for Tachyon service. |\n| `log_level` | `string` | `info` | Logging verbosity: `debug`, `info`, `warn`, `error`. |\n| `dns_mode` | `string` | `doh` | DNS routing mode: `direct`, `doh`, `dot`, `udp`, `hosts_only`. |\n| `remote_dns_server` | `string` | `https://1.1.1.1/dns-query` | Upstream secure DNS resolver for proxied domains. |\n| `direct_dns_server` | `string` | `77.88.8.8` | Fallback DNS resolver for direct / local domains. |\n| `tproxy_port` | `integer` | `10080` | Local TCP/UDP transparent proxy port for sing-box. |\n| `dns_port` | `integer` | `5353` | Local DNS listening port for sing-box DNS engine. |\n| `clash_api_port` | `integer` | `9090` | sing-box Clash REST API controller port. |\n| `clash_api_secret` | `string` | `\"\"` | Secret token for sing-box Clash API. |\n| `watchdog_interval` | `integer` | `10` | Watchdog polling interval in seconds (5–60s). |\n| `memory_limit_mb` | `integer` | `0` | Dynamic `GOMEMLIMIT` cap in MB (`0` = auto 50% free RAM). |\n| `enable_telegram` | `boolean` | `0` | Enable interactive Telegram management bot. |\n| `telegram_token` | `string` | `\"\"` | Telegram Bot API token from `@BotFather`. |\n| `telegram_chat_id` | `string` | `\"\"` | Allowed Admin Telegram Chat ID(s) (comma-separated). |\n| `enable_ai_doctor` | `boolean` | `0` | Enable LLM AI Doctor diagnostic engine. |\n| `ai_doctor_provider`| `string` | `openai` | LLM Provider: `openai`, `anthropic`, `deepseek`, `custom`. |\n| `ai_doctor_model` | `string` | `\"\"` | Model override (e.g. `gpt-4o-mini`, `claude-3-5-haiku`). |\n| `ai_doctor_api_key`| `string` | `\"\"` | API key for the chosen LLM provider. |", "embedding": []}, {"id": 24, "file": "08_UCI_CONFIGURATION_SCHEMA.md", "heading": "3. Section: `config subscription 'name'`", "text": "| `ai_doctor_provider`| `string` | `openai` | LLM Provider: `openai`, `anthropic`, `deepseek`, `custom`. |\n| `ai_doctor_model` | `string` | `\"\"` | Model override (e.g. `gpt-4o-mini`, `claude-3-5-haiku`). |\n| `ai_doctor_api_key`| `string` | `\"\"` | API key for the chosen LLM provider. |\n| `ai_doctor_custom_url`| `string` | `\"\"` | Custom OpenAI-compatible endpoint URL (e.g. OpenRouter/Ollama). |\n| `agent_api_token` | `string` | `\"\"` | Bearer token for HTTP REST Agent API write access. |\n\n---\n\n## 2. Section: `config server 'name'`\n\nDefines an individual manual proxy outbound node.\n\n| Option | Type | Required | Description |\n|---|---|---|---|\n| `type` | `string` | Yes | Protocol: `vless`, `vmess`, `shadowsocks`, `trojan`, `hysteria2`, `wireguard`. |\n| `server` | `string` | Yes | Remote server hostname or IPv4/IPv6 address. |\n| `server_port` | `integer` | Yes | Remote server port (e.g. `443`, `8443`). |\n| `uuid` | `string` | Conditional | User UUID for VLESS / VMess. |\n| `password` | `string` | Conditional | Password for Shadowsocks / Trojan / Hysteria2. |\n| `flow` | `string` | No | Flow control: `xtls-rprx-vision` (VLESS). |\n| `security` | `string` | No | Security type: `reality`, `tls`, `none`. |\n| `sni` | `string` | Conditional | Server Name Indication for TLS / Reality. |\n| `pbk` | `string` | Conditional | Public Key for VLESS Reality. |\n| `sid` | `string` | Conditional | Short ID for VLESS Reality (hex string). |\n| `fingerprint` | `string` | No | TLS fingerprint: `chrome`, `firefox`, `safari`, `randomized`. |\n| `method` | `string` | Conditional | Cipher method for Shadowsocks (e.g. `2022-blake3-aes-128-gcm`). |\n\n---\n\n## 3. Section: `config subscription 'name'`\n\nDefines a remote subscription URL for automated batch node fetching.\n\n| Option | Type | Default | Description |\n|---|---|---|---|\n| `enabled` | `boolean` | `1` | Enable this subscription source. |\n| `url` | `string` | Required | HTTPS / HTTP link to subscription (Base64, Clash, SIP002). |\n| `update_interval`| `integer` | `86400` | Auto-update interval in seconds (default 24 hours). |", "embedding": []}, {"id": 25, "file": "08_UCI_CONFIGURATION_SCHEMA.md", "heading": "Recipe A: Zero-VPS Local DPI Bypass (YouTube + Discord)", "text": "| `enabled` | `boolean` | `1` | Enable this subscription source. |\n| `url` | `string` | Required | HTTPS / HTTP link to subscription (Base64, Clash, SIP002). |\n| `update_interval`| `integer` | `86400` | Auto-update interval in seconds (default 24 hours). |\n| `custom_user_agent`| `string` | `\"\"` | Custom User-Agent header for subscription request. |\n| `filter_keywords` | `list string` | `[]` | Include nodes matching regex/keywords. |\n| `exclude_keywords`| `list string` | `[]` | Exclude nodes matching regex/keywords. |\n\n---\n\n## 4. Section: `config rule 'name'`\n\nDefines a selective routing policy.\n\n| Option | Type | Default | Description |\n|---|---|---|---|\n| `enabled` | `boolean` | `1` | Enable this routing rule. |\n| `name` | `string` | `\"\"` | Human-readable label for UI. |\n| `action` | `string` | `proxy` | Route target: `proxy`, `zapret`, `zapret2`, `byedpi`, `direct`, `hosts`. |\n| `target_server` | `string` | `\"\"` | Bound server ID or outbound tag when `action = 'proxy'`. |\n| `domain_pattern` | `list string` | `[]` | List of target domains or wildcards (e.g. `*.youtube.com`). |\n| `ip_cidr` | `list string` | `[]` | List of IP subnets (e.g. `104.16.0.0/12`). |\n| `client_group` | `string` | `\"\"` | Restrict this rule to a specific client device group. |\n\n---\n\n## 5. Section: `config hosts 'name'`\n\nConfigures static DNS overrides and remote blocklists ingestion.\n\n| Option | Type | Default | Description |\n|---|---|---|---|\n| `enabled` | `boolean` | `1` | Enable hosts mapping. |\n| `dns_hosts` | `list string` | `[]` | Static mappings in format `domain:ip` (e.g. `example.com:1.2.3.4`). |\n| `hosts_list_urls` | `list string` | `[]` | External URLs for blocklists (AdAway, StevenBlack). |\n| `update_interval` | `integer` | `86400` | Auto-refresh interval in seconds. |\n\n---\n\n## 6. Ready-to-Use Configuration Recipes\n\n### Recipe A: Zero-VPS Local DPI Bypass (YouTube + Discord)\n```ini\nconfig settings 'settings'\n option enabled '1'\n option dns_mode 'doh'\n\nconfig provider 'zapret2'", "embedding": []}, {"id": 26, "file": "08_UCI_CONFIGURATION_SCHEMA.md", "heading": "Recipe B: Hybrid Mode (Local Desync for Media + VLESS Reality for Blocked Sites)", "text": "## 6. Ready-to-Use Configuration Recipes\n\n### Recipe A: Zero-VPS Local DPI Bypass (YouTube + Discord)\n```ini\nconfig settings 'settings'\n option enabled '1'\n option dns_mode 'doh'\n\nconfig provider 'zapret2'\n option enabled '1'\n option daemon_bin '/usr/bin/nfqws2'\n option qnum '201'\n option args_tcp '--dpi-desync=multisplit --dpi-desync-split-pos=1,midsld --dpi-desync-seqovl=1 --dpi-desync-fooling=badseq'\n\nconfig rule 'youtube_discord'\n option enabled '1'\n option name 'YouTube & Discord Local Desync'\n option action 'zapret2'\n list domain_pattern 'googlevideo.com'\n list domain_pattern 'youtube.com'\n list domain_pattern 'ytimg.com'\n list domain_pattern 'discord.com'\n list domain_pattern 'discord.gg'\n```\n\n### Recipe B: Hybrid Mode (Local Desync for Media + VLESS Reality for Blocked Sites)\n```ini\nconfig server 'my_vps'\n option type 'vless'\n option server 'vps.example.com'\n option server_port '443'\n option uuid '12345678-1234-1234-1234-123456789abc'\n option flow 'xtls-rprx-vision'\n option security 'reality'\n option sni 'yahoo.com'\n option pbk 'XYZ...PUBLIC_KEY...'\n option sid '1a2b3c4d'\n\nconfig rule 'media_rule'\n option enabled '1'\n option action 'zapret2'\n list domain_pattern 'youtube.com'\n list domain_pattern 'googlevideo.com'\n\nconfig rule 'blocked_rule'\n option enabled '1'\n option action 'proxy'\n option target_server 'my_vps'\n list domain_pattern 'instagram.com'\n list domain_pattern 'twitter.com'\n list domain_pattern 'x.com'\n```", "embedding": []}, {"id": 27, "file": "09_TELEGRAM_BOT_ARCHITECTURE.md", "heading": "2. Command Set Reference", "text": "# 09. Telegram Bot Architecture & Management Protocol\n\nTachyon includes an embedded, high-performance Telegram management bot written entirely in **ucode** (`service/telegram.uc`).\n\n---\n\n## 1. Architectural Highlights\n\n```mermaid\ngraph LR\n User[Telegram Client] -->|Encrypted HTTPS| TGAPI[Telegram Bot API Servers]\n TGAPI -->|Long Polling: getUpdates| Daemon[Tachyon telegram.uc Daemon]\n \n Daemon --> Auth{Admin Chat ID Match?}\n Auth -->|No| Reject[Silent Ignore / Warning]\n Auth -->|Yes| Router[Command & Callback Dispatcher]\n \n Router -->|/doctor, /ai_doctor| AIDoc[AI Doctor Engine]\n Router -->|/server, /switch| SrvMgr[Server Manager]\n Router -->|/restart| SvcLife[Service Lifecycle]\n Router -->|/status| StateRep[State Assembler]\n```\n\n* **No Public IP or Port Forwarding Required**: Uses outbound long-polling (`getUpdates` with 30s timeout) to securely communicate through NAT/firewalls.\n* **Zero Overhead Memory Footprint**: Runs as a lightweight ucode process consuming under 2 MB RAM.\n* **Role-Based Access Control**: Rejects any commands from chat IDs not explicitly listed in UCI option `telegram_chat_id`.\n\n---\n\n## 2. Command Set Reference\n\n| Command | Arguments | Action |\n|---|---|---|\n| `/start` | — | Displays main welcome card and interactive control keyboard. |\n| `/status` | — | Returns real-time health card: uptime, active server, RAM usage, ping RTT. |\n| `/doctor` | — | Executes Local Rule Doctor and returns offline diagnostic report. |\n| `/ai_doctor`| — | Invokes AI Doctor with LLM reasoning and returns diagnosis + fix buttons. |\n| `/fix` | `<fix_code>` | Applies specific automated repair code (e.g. `/fix clear_dns_cache`). |\n| `/server` | — | Opens interactive server selector with inline pagination and RTT pings. |\n| `/rules` | — | Shows active routing rules with 1-click toggle switches. |\n| `/restart` | `[service]` | Restarts sing-box, dnsmasq, watchdog, or entire network stack. |\n| `/backup` | — | Sends latest atomic configuration backup directly to Telegram chat. |", "embedding": []}, {"id": 28, "file": "09_TELEGRAM_BOT_ARCHITECTURE.md", "heading": "Commit and restart service", "text": "| `/rules` | — | Shows active routing rules with 1-click toggle switches. |\n| `/restart` | `[service]` | Restarts sing-box, dnsmasq, watchdog, or entire network stack. |\n| `/backup` | — | Sends latest atomic configuration backup directly to Telegram chat. |\n\n---\n\n## 3. Inline Keyboard & Callback Query Protocol\n\nThe bot uses dynamic inline keyboards (`InlineKeyboardMarkup`) for single-tap actions without typing commands.\n\n### 3.1. Callback Data Scheme\nCallbacks follow a structured token format: `action:target:param`\n\n```\nsrv:select:node_1 # Switch active proxy server to node_1\nrule:toggle:youtube # Toggle routing rule 'youtube' on/off\nfix:apply:clear_dns_cache# Execute repair code 'clear_dns_cache'\npage:srv:2 # Navigate to page 2 of server list\n```\n\n### 3.2. Example: Server Switcher Response\n\n```json\n{\n \"chat_id\": 123456789,\n \"text\": \"⚡ <b>Выберите активный сервер:</b>\\nТекущий: <i>🇩🇪 Frankfurt VLESS (18 ms)</i>\",\n \"parse_mode\": \"HTML\",\n \"reply_markup\": {\n \"inline_keyboard\": [\n [\n {\"text\": \"🇩🇪 Frankfurt (18 ms) ✅\", \"callback_data\": \"srv:select:de_1\"},\n {\"text\": \"🇳🇱 Amsterdam (24 ms)\", \"callback_data\": \"srv:select:nl_1\"}\n ],\n [\n {\"text\": \"🇫🇮 Helsinki (31 ms)\", \"callback_data\": \"srv:select:fi_1\"},\n {\"text\": \"🇺🇸 New York (95 ms)\", \"callback_data\": \"srv:select:us_1\"}\n ],\n [\n {\"text\": \"🔄 Замерить пинг\", \"callback_data\": \"srv:ping:all\"},\n {\"text\": \"🩺 Запустить Доктора\", \"callback_data\": \"cmd:doctor\"}\n ]\n ]\n }\n}\n```\n\n---\n\n## 4. Configuration via CLI\n\n```sh\n# Set Bot Token\nuci set tachyon.settings.enable_telegram='1'\nuci set tachyon.settings.telegram_token='123456789:ABCdefGHIjklMNOpqrsTUVwxyz'\n\n# Set Authorized Chat ID(s)\nuci set tachyon.settings.telegram_chat_id='123456789'\n\n# Commit and restart service\nuci commit tachyon\n/etc/init.d/tachyon restart\n```", "embedding": []}, {"id": 29, "file": "10_HOSTS_ENGINE_AND_BLOCKLISTS.md", "heading": "Example UCI Configuration:", "text": "# 10. Hosts Engine, Blocklists & Smart Caching\n\nThe Hosts Engine (`components/hosts.uc`) provides automated background ingestion, normalization, deduplication, and caching of external host lists and static DNS overrides.\n\n---\n\n## 1. Architecture of Hosts Engine\n\n```mermaid\ngraph TD\n Sources[External Remote URLs: AdAway, StevenBlack, Custom] --> Downloader[HTTP Fetcher with Mirror Retry]\n Static[Static dns_hosts in UCI] --> Downloader\n \n Downloader --> Parser[Multi-Format Parser: Hosts, AdBlock, Domains]\n Parser --> Deduper[Deduplication & Sorting Engine]\n Deduper --> Cache[Unified Cache: /tmp/tachyon/hosts/combined.txt]\n \n Cache --> DNSMasq[dnsmasq /etc/dnsmasq.d/tachyon-hosts.conf]\n Cache --> SingboxDNS[sing-box DNS hosts rule]\n```\n\n---\n\n## 2. Multi-Format Ingestion\n\nThe parser automatically detects and normalizes multiple common blocklist formats:\n\n1. **Standard `/etc/hosts` format**:\n ```\n 0.0.0.0 ads.example.com\n 127.0.0.1 tracker.adserver.net\n ```\n2. **Domain-only list format**:\n ```\n malware-domain.org\n telemetry.app.com\n ```\n3. **AdBlock / DNSmasq syntax**:\n ```\n ||badsite.com^\n server=/blocked.com/\n address=/ads.org/0.0.0.0\n ```\n\n---\n\n## 3. GitHub Mirror Retry Resiliency\n\nWhen fetching blocklists hosted on GitHub (e.g. `raw.githubusercontent.com`), access may be blocked or throttled by regional DPI.\n\nTachyon implements an automated fallback retry chain:\n1. **Primary**: Direct HTTPS request to target URL.\n2. **Mirror 1**: `https://gh-proxy.com/<original_url>`\n3. **Mirror 2**: `https://ghfast.top/<original_url>`\n4. **Mirror 3**: `https://ghproxy.net/<original_url>`\n\nIf direct connection fails with timeout or SSL handshake error, Tachyon transparently cycles through available mirrors before reporting an error.\n\n---\n\n## 4. Dedicated Hosts Routing (`action = 'hosts'`)\n\nTachyon supports routing sections that operate purely as DNS-overriding engines without requiring an outbound proxy association.\n\n### Example UCI Configuration:", "embedding": []}, {"id": 30, "file": "10_HOSTS_ENGINE_AND_BLOCKLISTS.md", "heading": "Example UCI Configuration:", "text": "## 4. Dedicated Hosts Routing (`action = 'hosts'`)\n\nTachyon supports routing sections that operate purely as DNS-overriding engines without requiring an outbound proxy association.\n\n### Example UCI Configuration:\n```ini\nconfig rule 'adblock_section'\n option enabled '1'\n option name 'AdBlock & Anti-Tracker'\n option action 'hosts'\n list hosts_list_urls 'https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts'\n list hosts_list_urls 'https://adaway.org/hosts.txt'\n```\n\n* Domains in this section are redirected directly to `0.0.0.0` or custom IPs in dnsmasq / sing-box DNS.\n* Zero traffic is routed to external proxies, preserving VPS bandwidth and minimizing latency.", "embedding": []}, {"id": 31, "file": "11_TROUBLESHOOTING_AND_FIELD_MANUAL.md", "heading": "2. Run AI Doctor with LLM analysis", "text": "# 11. Troubleshooting & Field Diagnostic Manual\n\nA comprehensive guide for diagnosing and resolving common network, proxy, and routing issues on OpenWrt routers running Tachyon.\n\n---\n\n## 1. Quick Emergency Recovery\n\nIf router traffic drops completely or DNS resolution is broken, use the **Emergency Native Internet Restoration** command:\n\n```sh\ntachyon restore_native_internet\n```\n\nThis performs the following actions in under 200 ms:\n1. Atomically drops all nftables interception tables (`nft delete table inet TachyonTable`).\n2. Clears policy routing `table 100` and `ip rule` entries.\n3. Restores dnsmasq to stock upstream forwarders.\n4. Stops sing-box and DPI bypass daemons without rebooting the router.\n\n---\n\n## 2. Symptom Resolution Matrix\n\n| Symptom | Likely Cause | Recommended Fix / Command |\n|---|---|---|\n| **Websites fail to open, ping to 8.8.8.8 works** | DNS loop or dnsmasq forwarder crash. | `tachyon apply_quick_fix clear_dns_cache,fix_dnsmasq` |\n| **YouTube 4K buffers indefinitely** | Zapret strategy out-of-date for current ISP. | Switch Zapret v2 strategy to `multisplit` with `seqovl=1`. |\n| **sing-box fails to start after config change** | Syntax error in custom outbound or invalid UUID. | Check `/var/log/tachyon_service.log` and run `tachyon doctor`. |\n| **System clock desynchronized, TLS fails** | Router rebooted without RTC battery, NTP desync. | `tachyon apply_quick_fix fix_system_time` |\n| **High latency or packet drop under heavy load** | Kernel `nf_conntrack` table overflow. | `tachyon apply_quick_fix flush_conntrack` |\n| **VLESS Reality connection timeout** | Reality SNI domain blocked or expired short ID. | Update server SNI to accessible target (e.g. `yahoo.com`). |\n| **Router runs out of RAM (OOM Crash)** | sing-box buffer explosion on low-RAM device (128 MB). | Lower `memory_limit_mb` in UCI settings (`GOMEMLIMIT=40MiB`). |\n\n---\n\n## 3. Diagnostic Commands Reference\n\n```sh\n# 1. Run local offline rule checks\ntachyon doctor\n\n# 2. Run AI Doctor with LLM analysis", "embedding": []}, {"id": 32, "file": "11_TROUBLESHOOTING_AND_FIELD_MANUAL.md", "heading": "4. Log Inspection Paths", "text": "| **Router runs out of RAM (OOM Crash)** | sing-box buffer explosion on low-RAM device (128 MB). | Lower `memory_limit_mb` in UCI settings (`GOMEMLIMIT=40MiB`). |\n\n---\n\n## 3. Diagnostic Commands Reference\n\n```sh\n# 1. Run local offline rule checks\ntachyon doctor\n\n# 2. Run AI Doctor with LLM analysis\ntachyon ai_doctor\n\n# 3. View real-time Watchdog telemetry\ntachyon ai_status_full\n\n# 4. Inspect active nftables firewall tables\nnft list table inet TachyonTable\n\n# 5. Inspect policy routing table 100\nip route show table 100\nip rule show\n\n# 6. Stream live Tachyon system logs\nlogread -f -e tachyon\n\n# 7. Check listening ports (TProxy 10080, DNS 5353, Clash 9090)\nnetstat -tulpn | grep -E 'sing-box|tachyon|5353|10080'\n```\n\n---\n\n## 4. Log Inspection Paths\n\n| Log Location | Content Description |\n|---|---|\n| `/var/log/tachyon_service.log` | Core service lifecycle events (start, stop, reload). |\n| `/var/log/tachyon_watchdog.log` | Background supervisor health checks and loop warnings. |\n| `/tmp/ai_doctor_last.json` | JSON report of the most recent AI Doctor diagnosis. |\n| `/tmp/tachyon/sing-box.json` | Generated live configuration compiled for sing-box. |\n| `/tmp/tachyon/hosts/combined.txt` | Consolidated deduplicated hosts list. |", "embedding": []}, {"id": 33, "file": "12_UCODE_PROGRAMMING_PATTERNS.md", "heading": "2.3. Safe Error Handling (`try-catch`)", "text": "# 12. ucode Programming Patterns & Conventions\n\nA developer's guide to writing safe, high-performance, and idiomatic **ucode** modules for Tachyon on OpenWrt.\n\n---\n\n## 1. ucode vs JavaScript: Critical Distinctions\n\nWhile ucode syntax resembles JavaScript, its runtime semantics differ significantly:\n\n1. **Variables & Scope**:\n * Always declare variables with `let` or `const`.\n * Unassigned variables are `null` (not `undefined`).\n2. **Arrays vs Dictionaries**:\n * Arrays: `[1, 2, 3]`. Iterated with `for (let item in array)`.\n * Dictionaries (Objects): `{\"key\": \"value\"}`. Iterated with `for (let key, val in dict)`.\n3. **Regular Expressions**:\n * Use `match(str, /regex/)` or `replace(str, /regex/g, \"replacement\")`.\n * Global flag `/g` works with `replace()`, while `match()` returns capture groups array `[full_match, group1, ...]`.\n4. **Boolean Coercion**:\n * Empty strings `\"\"`, `0`, and `null` are falsy. Everything else is truthy.\n\n---\n\n## 2. Mandatory Core Design Patterns\n\n### 2.1. Atomic Configuration Writes\nNever overwrite active configuration files in-place. Always write to a temporary file in `/tmp/` and atomically rename:\n\n```ucode\nlet fs = require(\"fs\");\n\nfunction write_atomic(path, content) {\n let tmp_path = path + \".tmp.\" + int(time());\n let f = fs.open(tmp_path, \"w\");\n if (!f) return false;\n \n f.write(content);\n f.close();\n \n return fs.rename(tmp_path, path);\n}\n```\n\n### 2.2. Shell Argument Quoting\nWhen executing external shell commands, all user inputs must be quoted safely:\n\n```ucode\nfunction shell_quote(value) {\n return \"'\" + replace(\"\" + value, /'/g, \"'\\\\''\") + \"'\";\n}\n\nfunction safe_exec(cmd_args) {\n let parts = [];\n for (let arg in cmd_args)\n push(parts, shell_quote(arg));\n return system(join(\" \", parts));\n}\n```\n\n### 2.3. Safe Error Handling (`try-catch`)\nAll external library loading or file parsing must be wrapped in `try-catch` blocks to avoid unhandled script panics:\n\n```ucode\nlet uci_data = null;", "embedding": []}, {"id": 34, "file": "12_UCODE_PROGRAMMING_PATTERNS.md", "heading": "3. Performance & Memory Optimization Guidelines", "text": "return system(join(\" \", parts));\n}\n```\n\n### 2.3. Safe Error Handling (`try-catch`)\nAll external library loading or file parsing must be wrapped in `try-catch` blocks to avoid unhandled script panics:\n\n```ucode\nlet uci_data = null;\ntry {\n let uci = require(\"uci\").cursor();\n uci_data = uci.get_all(\"tachyon\", \"settings\");\n}\ncatch (e) {\n warn(\"Failed to load UCI settings: \" + e + \"\\n\");\n}\n```\n\n---\n\n## 3. Performance & Memory Optimization Guidelines\n\n1. **Stream Large Files**: Avoid loading multi-megabyte blocklists entirely into RAM with `fs.readfile()`. Use line-by-line streaming via `fs.open()` and `f.read(\"line\")`.\n2. **Avoid Spawning Subprocesses in Loops**: Invoking `system()` or `fs.popen()` spawns a fork-exec sequence in Linux. Use native ucode functions for string manipulation and path operations whenever possible.\n3. **Keep Modules Stateless**: Module files under `usr/lib/tachyon/` should export reusable pure functions or class definitions rather than maintaining mutable global state.", "embedding": []}, {"id": 35, "file": "13_REST_API_AND_MCP_SPECIFICATION.md", "heading": "4. Model Context Protocol (MCP) Tool Definitions", "text": "# 13. HTTP REST Agent API & Model Context Protocol (MCP) Specification\n\nTachyon provides a standardized RESTful Agent API and Model Context Protocol (MCP) integration, enabling seamless orchestration by autonomous LLM agents (ChatGPT Actions, Claude Code, Cursor, Windsurf, N8N, Dify).\n\n---\n\n## 1. REST API Overview\n\n* **Base URL**: `http://<router-ip>/cgi-bin/tachyon-agent/`\n* **OpenAPI Schema**: `http://<router-ip>/cgi-bin/tachyon-agent/openapi.json`\n* **Content-Type**: `application/json`\n\n---\n\n## 2. Authentication Model\n\n1. **Read-Only Endpoints**: Unrestricted when accessed from local LAN.\n2. **Write Endpoints**: Require HTTP Authorization header:\n ```http\n Authorization: Bearer <agent_api_token>\n ```\n\n---\n\n## 3. Endpoint Reference & Payloads\n\n### 3.1. `GET /health`\nReturns lightweight status of all core daemons.\n```json\n{\n \"status\": \"healthy\",\n \"version\": \"1.2.86\",\n \"uptime_seconds\": 18450,\n \"singbox_running\": true,\n \"watchdog_running\": true,\n \"active_server\": \"Frankfurt_VLESS_Reality\"\n}\n```\n\n### 3.2. `GET /diagnose`\nReturns Local Rule Doctor checks and suggested repair codes.\n```json\n{\n \"status\": \"warning\",\n \"checks\": {\n \"dns_loop\": false,\n \"conntrack_full\": false,\n \"time_desync\": true,\n \"singbox_ok\": true\n },\n \"suggested_fixes\": [\"fix_system_time\"]\n}\n```\n\n### 3.3. `POST /ai-doctor/fix`\nApplies one or more quick-fix codes.\n* **Request**:\n ```json\n {\n \"fix\": \"clear_dns_cache,start_singbox\"\n }\n ```\n* **Response**:\n ```json\n {\n \"success\": true,\n \"applied_fixes\": [\"clear_dns_cache\", \"start_singbox\"],\n \"details\": \"DNS cache cleared. sing-box process restarted.\"\n }\n ```\n\n---\n\n## 4. Model Context Protocol (MCP) Tool Definitions\n\nFor MCP-compatible agents (Cursor, Claude Desktop), Tachyon exports tools via `GET /cgi-bin/tachyon-agent/tools`:\n\n```json\n[\n {\n \"name\": \"tachyon_diagnose\",\n \"description\": \"Run diagnostic checks on OpenWrt router network and proxy health\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {}", "embedding": []}, {"id": 36, "file": "13_REST_API_AND_MCP_SPECIFICATION.md", "heading": "4. Model Context Protocol (MCP) Tool Definitions", "text": "```json\n[\n {\n \"name\": \"tachyon_diagnose\",\n \"description\": \"Run diagnostic checks on OpenWrt router network and proxy health\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {}\n }\n },\n {\n \"name\": \"tachyon_apply_fix\",\n \"description\": \"Apply automated repair codes to fix router network or proxy issues\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"fix_codes\": {\n \"type\": \"string\",\n \"description\": \"Comma-separated list of fix codes (e.g. clear_dns_cache,restart_singbox)\"\n }\n },\n \"required\": [\"fix_codes\"]\n }\n },\n {\n \"name\": \"tachyon_switch_server\",\n \"description\": \"Switch active proxy server node\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"server_id\": {\n \"type\": \"string\",\n \"description\": \"Identifier of target proxy server\"\n }\n },\n \"required\": [\"server_id\"]\n }\n }\n]\n```", "embedding": []}, {"id": 37, "file": "INDEX.md", "heading": "📚 Knowledge Base Table of Contents", "text": "# Tachyon Knowledge Base & Architecture Index\n\nWelcome to the comprehensive technical knowledge base for **Tachyon**. This directory contains deep architectural specifications, module references, packet flow maps, and developer guidelines compiled directly from the codebase.\n\n---\n\n## 📚 Knowledge Base Table of Contents\n\n| Document | Description | Key Topics Covered |\n|---|---|---|\n| [**01. System Architecture**](01_SYSTEM_ARCHITECTURE.md) | High-level system architecture & control plane | ucode runtime, atomic writes, repository layout, daemon lifecycle |\n| [**02. ucode Module Reference**](02_UCODE_MODULE_REFERENCE.md) | Comprehensive reference for all 60+ `.uc` files | `core/`, `service/`, `diagnostics/`, `singbox/`, `providers/`, `nft/`, `dns/` |\n| [**03. Networking & nftables**](03_NETWORKING_NFTABLES_AND_ROUTING.md) | Packet lifecycle, firewall tables & DNS routing | `inet TachyonTable`, fwmark bitmasks, TProxy, bootstrap DNS loops |\n| [**04. DPI Bypass Engines**](04_DPI_BYPASS_ENGINES.md) | Local packet desynchronization deep dive | Zapret v1 (`nfqws`), Zapret v2 (`nfqws2`), ByeDPI (`ciadpi`), multisplit, seqovl |\n| [**05. AI Stack & AI Doctor**](05_AI_STACK_AND_AUTONOMOUS_DOCTOR.md) | AI Doctor v2.5, Watchdog & REST Agent API | 13 Quick Fixes, Local Rule Doctor, NTP/MTU tuning, OpenAPI 3.0.3, REST API |\n| [**06. Frontend LuCI Architecture**](06_FRONTEND_LUCI_TYPESCRIPT.md) | TypeScript SPA & LuCI view integration | `baseclass.extend` patch, reactive stores, live log streaming modal |\n| [**07. Build & Testing Pipeline**](07_BUILD_TESTS_AND_DEPLOYMENT.md) | Compilation, testing & release workflows | `build.sh` (ipk/apk), `install.sh`, Docker CI container, vitest tests |\n| [**08. UCI Configuration Schema**](08_UCI_CONFIGURATION_SCHEMA.md) | Complete `/etc/config/tachyon` reference | All UCI sections, options, validators, default values, ready recipes |\n| [**09. Telegram Bot Architecture**](09_TELEGRAM_BOT_ARCHITECTURE.md) | Remote Telegram control daemon protocol | Long-polling model, inline keyboards, callback query routing, security |", "embedding": []}, {"id": 38, "file": "INDEX.md", "heading": "Frontend vitest suite", "text": "| [**08. UCI Configuration Schema**](08_UCI_CONFIGURATION_SCHEMA.md) | Complete `/etc/config/tachyon` reference | All UCI sections, options, validators, default values, ready recipes |\n| [**09. Telegram Bot Architecture**](09_TELEGRAM_BOT_ARCHITECTURE.md) | Remote Telegram control daemon protocol | Long-polling model, inline keyboards, callback query routing, security |\n| [**10. Hosts Engine & Blocklists**](10_HOSTS_ENGINE_AND_BLOCKLISTS.md) | Hosts ingestion, parsing & smart caching | `combined.txt`, multi-format parsing, GitHub mirror retry resiliency |\n| [**11. Troubleshooting Manual**](11_TROUBLESHOOTING_AND_FIELD_MANUAL.md) | Field diagnostics & emergency recovery | Symptom resolution matrix, diagnostic commands, log inspection paths |\n| [**12. ucode Programming Patterns**](12_UCODE_PROGRAMMING_PATTERNS.md) | Developer guidelines for OpenWrt ucode | Atomic file writes, shell quoting, libuci bindings, RAM efficiency |\n| [**13. REST API & MCP Specification**](13_REST_API_AND_MCP_SPECIFICATION.md) | REST Agent API & MCP tool definitions | OpenAPI 3.0.3, Bearer Auth, OpenAI Function Calling, MCP JSON schema |\n\n---\n\n## ⚡ Quick Operational Cheat Sheet\n\n### Common CLI Commands\n```sh\n# Diagnostics & AI\ntachyon doctor # Local offline rule diagnostics\ntachyon ai_doctor # AI Doctor LLM analysis\ntachyon apply_quick_fix <code1,code2> # Apply automated repair codes\ntachyon restore_native_internet # 1-Click emergency WAN restore\n\n# Service & Watchdog\ntachyon ai_heal # Trigger immediate self-healing cycle\ntachyon ai_status # Concise Watchdog status JSON\ntachyon ai_status_full # Full Watchdog telemetry JSON\n\n# Component Management\ntachyon check_update <component> # Check for component updates\ntachyon component_action install <comp> # Install or update component\n```\n\n### Local Test Execution\n```sh\n# Frontend vitest suite\nnpm --prefix fe-app-tachyon test", "embedding": []}, {"id": 39, "file": "INDEX.md", "heading": "Full backend suite in Docker CI", "text": "tachyon check_update <component> # Check for component updates\ntachyon component_action install <comp> # Install or update component\n```\n\n### Local Test Execution\n```sh\n# Frontend vitest suite\nnpm --prefix fe-app-tachyon test\n\n# Full backend suite in Docker CI\ndocker run --rm -v \"$(pwd):/mnt\" -w /mnt ucode-ci-img:latest bash tests/run_all.sh\n```", "embedding": []}]}