Skip to content

Latest commit

 

History

History
140 lines (120 loc) · 9.24 KB

ARCHITECTURE.md

File metadata and controls

140 lines (120 loc) · 9.24 KB

NerveForge architecture (Arena.ai ↔ PC & Android)

English · Русский

NerveForge is a small bridge (a receiving gateway) that connects agents of Arena.ai (running in isolated cloud containers) to a developer's local machine (Linux, Windows 10/11, macOS, Android / Termux).

+--------------------------------------------------------------------------------------------------+
|                                       DATA AND COMMAND FLOW                                      |
+---------------------+             +--------------------+             +---------------------------+
|      Arena.ai       |  (HTTPS)    | Cloudflare tunnel  |  (Loopback) |  Your machine (NerveForge)|
|    (Agent Mode)     | <=========> |    / Tailscale     | <=========> |  • Linux (Ubuntu/Mint)    |
|  Cloud container    |  Bearer Auth|  Auto-published    |  127.0.0.1  |  • Windows 10/11          |
|   running an agent  |             |        URL         |  :8766      |  • Android (Termux)       |
+---------------------+             +--------------------+             +---------------------------+

Key components

  1. HTTP bridge (src/nerveforge/bridge.py):

    • accepts requests from Arena.ai over the tunnel with bearer-token authorization;
    • serves them from a worker pool (concurrent.futures.ThreadPoolExecutor) with TCP_NODELAY;
    • exposes self-documentation (/api/docs, /llms.txt, /api/agent-prompt);
    • dispatches to the terminal runner, the file manager and the configuration handlers.
  2. Cross-platform layer (src/nerveforge/platform_support.py):

    • detects the OS: Linux, Windows, Android (Termux), macOS;
    • discovers available shells through a data registry (bash, zsh, sh, fish, powershell, pwsh, cmd, wsl, wsl-bash);
    • reports platform-specific capabilities (for example termux-api on Android).
  3. Full-access shell runner (src/nerveforge/uzhas_manager.py):

    • runs commands in the selected shell with a timeout and a working directory;
    • validates limits (up to 40 MB command / 50 MB output);
    • cancels whole process trees (killpg on Linux/Android, taskkill /T /F on Windows).
  4. Tunnel manager (src/nerveforge/tunnel/):

    • providers.py — CloudflaredProvider (child process, URL taken from the log after Your quick Tunnel has been created) and TailscaleProvider (funnel --bg; stop() resets the Funnel only if this run started it, so a failed start cannot leave a public entry point behind).
    • manager.py — TunnelManager: exactly one active provider, start/switch/stop/shutdown, resolution of auto (cloudflared → tailscale → local), writes tunnel.json (0600).
    • cli.py — python -m nerveforge / the nerveforge console script: starts the receiver as a child, waits for /api/health, brings up the tunnel, prints the banner, watches both.
    • commands.py — the control channel between the bridge and the tunnel process (see below).

    Who owns what. The process that started a tunnel is the only one that can switch it. Therefore POST /api/tunnel/config from the panel does not switch anything itself: it drops a request into tunnel-request.json (TTL 120 s) and answers 202 immediately. The tunnel process polls that request while it watches the receiver, applies it, writes the result to tunnel.json and — on failure — to tunnel-error.json (TTL 10 min), which GET /api/tunnel reads back. The panel therefore cannot "switch" a provider that does not live in this process, and a request nobody consumed never fires later.

    Signals and exit codes. SIGINT/SIGTERM/SIGBREAK do not interrupt work in the middle: they set a flag, the current step finishes, then the receiver and the tunnel stop. Exit codes: 0 clean shutdown, 1 failure (receiver did not start or died on its own), 2 bad arguments, missing provider or a refused privilege confirmation, 3 interrupted during startup.

  5. File layer (src/nerveforge/workspace_manager.py):

    • file operations are sandboxed to the workspace root, plus a fail-closed bwrap runner;
    • anonymous endpoints /api/public/scripts and /api/public/assets create new text files with an allowlisted extension (shell, Python, JSON/YAML, Dockerfile, systemd units, C#/shaders and more); extend the list with NERVEFORGE_PUBLIC_UPLOAD_EXTRA.
  6. Toolbox (src/nerveforge/toolkit/):

    • tools.py — 24 ToolSpec entries (reverse engineering, debugging, mobile, forensics, network) with the release asset each one would use and how to detect it here;
    • skillcatalog.py / skilldoc.py — twelve skill files and their readiness (ready, partial, blocked) computed from what is installed, never declared;
    • installer.py — download one GitHub release asset, verify the SHA-256 from the same API response, unpack one member, chmod 0700 into the data dir; never touches PATH;
    • mcp.py — MCP 2025-06-18 over stdio and Streamable HTTP: handshake, tools/list paging, tools/call, timeouts, one pending map keyed by request id;
    • registry.py / mcpservice.py — twelve presets with the reason each is blocked, live sessions, a 120 s tool cache, the mutation gate and the JSONL audit;
    • mcpserver.py — the same bridge as an MCP server (nine tools, allow_writes off by default);
    • cli.py — python -m nerveforge.toolkit [--serve | --list-skills | --list-tools | --install].

    Two rules worth stating. A skill is knowledge, not a runner: it declares the tools it needs and read_skill returns the verdict with the body, so an agent cannot start a procedure it cannot finish. And MCP is a client and a server: the client never spawns a stdio server at startup, and the server half needs --allow-write before workspace_write or run_command even appear as callable. See docs/TOOLKIT.md and docs/ADR/0006-toolkit-safety.md.

  7. Local web panel (static/):

    • developer dashboard with connection monitoring, web terminal, file manager, tunnel switcher, the Skills and MCP tabs, and an event log.
  8. Infrastructure services (src/nerveforge/core/):

    • audit.py — one AuditLog (JSONL, 512 KiB rotation, tail(limit)) used by the yolo, workspace and uzhas journals.
    • ratelimit.py — FixedWindowRateLimiter for public uploads, workspace and YOLO requests.
    • jobstore.py — JobStore with automatic eviction of finished jobs.
    • limits.py — strict limit validation (coerce_limit, mb_to_bytes, Limits), 1 byte – 64 MiB.
    • errors.py — ApiError hierarchy (400/401/403/404/409/429/500) mapped to JSON by _dispatch.
    • logging_setup.py — structured JSON logger on the standard logging module.
    • safe_path.py — one path-containment primitive (PathPolicy, resolve_within, contains_escape).
    • process.py — process_options, signal_tree, terminate_all for whole-tree termination.

Layers after the refactor (stages 1–8, version 8.0.0)

bridge.py (composition root: port, token, servers, startup)
   └── http/            transport
        ├── base_handler.py   auth, read_json, send_bytes/send_json, ApiError mapping
        ├── router.py         RouteTable: exact/prefix/regex, public flags, 405
        ├── app.py            AppContext + LocalBridgeHandler + LocalAdminHandler
        └── routes/           system, commands, full_access, workspace, configs
   └── services/        domain (no HTTP)
        approval · full_access · workspace · configs · system
   └── service/state.py ReceiverState: limits, JobStore, audit, ratelimits, flags
   └── config/monitor.py ConfigMonitor: systemd/autostart snapshots and drift events
   └── tunnel/          cli.py · manager.py · providers.py · commands.py
   └── toolkit/         skills · tools · installer · mcp client · mcp server · registry
   └── core/            AuditLog · RateLimiter · JobStore · Limits · ApiError · logging
                        safe_path: one "path inside an allowed root" check
                        process: process_options · signal_tree · terminate_all

Layer rules:

  • a route only reads the body, calls a service and returns JSON; errors go through ApiError;
  • a service never imports http modules and knows nothing about status codes;
  • state changes only through ReceiverState methods under one RLock;
  • adding an endpoint means one table.add(...) in the right domain, with no handler edits;
  • an endpoint without a description in scripts/gen_api_doc.py breaks a test — docs/API.md is always current;
  • the tunnel is owned by a separate process; the receiver only queues a request (see docs/ADR/0002-tunnel-ownership.md);
  • the toolbox reaches outside the process only on request: GET never downloads or spawns, an install writes one file into the data dir, and an MCP stdio server starts on connect (see docs/ADR/0006-toolkit-safety.md).

Public (token-free) routes are declared with public=True in the route table: the panel, /docs, /llms.txt, /api/agent-prompt, /api/health and POST to /api/public/*. Every other GET/POST requires Authorization: Bearer <TOKEN>.