A modern and elegant dashboard for network traffic visualization and analysis.
refactor: Reorganize documentation into `agent`, `dev`, and `research` subdirectories, add English translations, and update existing documents.
luoleic5321580fbc2
diff --git a/README.en.md b/README.en.mdindex 4fe2948..acfd7d7 100644--- a/README.en.md+++ b/README.en.md@@ -21,7 +21,7 @@<a href="https://github.com/foru17/neko-master/blob/main/LICENSE"><img src="https://img.shields.io/github/license/foru17/neko-master?style=flat-square&color=green" alt="License"></a><img src="https://img.shields.io/badge/Node.js-22-339933?style=flat-square&logo=node.js"><a href="https://github.com/foru17/neko-master/actions/workflows/docker-build.yml"><img src="https://img.shields.io/github/actions/workflow/status/foru17/neko-master/docker-build.yml?style=flat-square&label=Docker%20CI" alt="Docker CI"></a>- <a href="./docs/architecture.md"><img src="https://img.shields.io/badge/docs-architecture-0ea5e9?style=flat-square" alt="Architecture Docs"></a>+ <a href="./docs/architecture.en.md"><img src="https://img.shields.io/badge/docs-architecture-0ea5e9?style=flat-square" alt="Architecture Docs"></a></p>> [!IMPORTANT]@@ -242,14 +242,56 @@ Open <http://localhost:3000> to configure.## 🤖 Agent Deployment-Use Agent mode when you want one centralized Neko Master service and multiple remote devices collecting local gateway data.+Use Agent mode when you want one centralized Neko Master service and multiple remote devices (OpenWrt, Linux, macOS) collecting local gateway data. The agent runs near the gateway, pulls data, and reports to the panel — the panel never connects to the gateway directly.-- Overview: `docs/agent/overview.md`-- Quick Start: `docs/agent/quick-start.md`-- Install: `docs/agent/install.md`-- Config: `docs/agent/config.md`-- Release Flow: `docs/agent/release.md`-- Troubleshooting: `docs/agent/troubleshooting.md`+Supported gateway types: **Clash / Mihomo** (WebSocket real-time) and **Surge v5+** (HTTP polling).++### Quick Install (UI-generated command)++1. In the dashboard, go to `Settings → Backends`, add an `Agent` backend, select gateway type+2. Click **"View Agent Script"** and copy the one-line install command, then run it on the target host:++```bash+# Clash / Mihomo gateway example+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='1' \+ NEKO_BACKEND_TOKEN='ag_xxx' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ sh++# Surge gateway example+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='2' \+ NEKO_BACKEND_TOKEN='ag_yyy' \+ NEKO_GATEWAY_TYPE='surge' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9091' \+ sh+```++After install, manage instances with `nekoagent`:++```bash+nekoagent list # list all instances+nekoagent status <instance> # check running state+nekoagent logs <instance> # tail live logs+nekoagent restart <instance> # restart+nekoagent update <instance> # update to latest version+```++> The script auto-detects an existing installation — if `neko-agent` is already present, it only adds the new instance without re-downloading.+> Multiple instances can run on the same host (different `NEKO_INSTANCE_NAME`), each pointing to a different gateway.++### Agent Documentation++- [Overview](./docs/agent/overview.en.md): architecture, Direct vs Agent comparison, security model+- [Quick Start](./docs/agent/quick-start.en.md): end-to-end setup from UI to running agent+- [Install Guide](./docs/agent/install.en.md): install methods, systemd / launchd autostart+- [Configuration](./docs/agent/config.en.md): full flag and env variable reference+- [Release Flow](./docs/agent/release.en.md): versioning and compatibility policy+- [Troubleshooting](./docs/agent/troubleshooting.en.md): common errors and fixes## 📖 First Use@@ -459,7 +501,8 @@ Read source is controlled by `STATS_QUERY_SOURCE` (default: `sqlite`).#### Step 1: Start the ClickHouse container-The `docker-compose.yml` includes a ClickHouse service gated by `profiles: [clickhouse]`:+The repository's built-in `docker-compose.yml` already includes a ClickHouse service, gated by+`profiles: [clickhouse]` so it does not start by default. From the repository root, run:```bashdocker compose --profile clickhouse up -d@@ -467,6 +510,55 @@ docker compose --profile clickhouse up -d> ClickHouse data is persisted to `./data/clickhouse`, separate from the main app data directory.+If you use a **custom `docker-compose.yml`** (such as Scenario A/B above), add the ClickHouse+service block manually:++```yaml+services:+ neko-master:+ # ... your existing config ...+ environment:+ # append to existing environment section:+ - CH_ENABLED=${CH_ENABLED:-0}+ - CH_HOST=${CH_HOST:-clickhouse}+ - CH_PORT=${CH_PORT:-8123}+ - CH_DATABASE=${CH_DATABASE:-neko_master}+ - CH_USER=${CH_USER:-neko}+ - CH_PASSWORD=${CH_PASSWORD:-neko_master}+ - CH_WRITE_ENABLED=${CH_WRITE_ENABLED:-0}+ - STATS_QUERY_SOURCE=${STATS_QUERY_SOURCE:-sqlite}+ networks:+ - neko-master-network++ clickhouse:+ image: clickhouse/clickhouse-server:24.8+ container_name: neko-master-clickhouse+ restart: unless-stopped+ profiles: ["clickhouse"]+ ports:+ - "${CH_EXTERNAL_HTTP_PORT:-8123}:8123"+ - "${CH_EXTERNAL_NATIVE_PORT:-9000}:9000"+ volumes:+ - ./data/clickhouse:/var/lib/clickhouse+ environment:+ - CLICKHOUSE_DB=${CH_DATABASE:-neko_master}+ - CLICKHOUSE_USER=${CH_USER:-neko}+ - CLICKHOUSE_PASSWORD=${CH_PASSWORD:-neko_master}+ - CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1+ networks:+ - neko-master-network+ healthcheck:+ test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8123/ping || exit 1"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 40s++networks:+ neko-master-network:+ driver: bridge+```+#### Step 2: Configure environment variablesAdd to your `.env` (same directory as `docker-compose.yml`):@@ -825,14 +917,14 @@ docker compose up -dIf you want to quickly understand the system design depth, read in this order:-1. **System Architecture Diagram**: end-to-end layering and module responsibilities- Chinese: [`docs/architecture.md`](./docs/architecture.md)- English: [`docs/architecture.en.md`](./docs/architecture.en.md)+1. **System Architecture Diagram**: end-to-end layering and module responsibilities → [docs/architecture.en.md](./docs/architecture.en.md)2. **Data Flow**: Clash / Surge collection pipelines and aggregation3. **Data Model & Storage**: SQLite schema, ClickHouse Buffer tables, retention policy4. **Realtime Channel Design**: `RealtimeStore` merge strategy and WS push5. **ClickHouse Module**: dual-write architecture, health fallback, read routing+Full documentation index: [docs/README.en.md](./docs/README.en.md)+> This documentation covers the core design of collection, aggregation, caching, realtime push, and multi-backend management.## 🤝 Feedback & Issues@@ -856,12 +948,25 @@ neko-master/├── setup.sh # One-click setup script├── docker-start.sh # Docker container startup script├── start.sh # Source code dev startup script-├── docs/ # Architecture and design docs-│ ├── architecture.md # Chinese architecture docs-│ └── architecture.en.md # English architecture docs+├── docs/ # Documentation (see docs/README.en.md)+│ ├── README.md # Documentation index (Chinese)+│ ├── README.en.md # Documentation index (English)+│ ├── architecture.md # System architecture (Chinese)+│ ├── architecture.en.md # System architecture (English)+│ ├── release-checklist.md+│ ├── agent/ # Agent docs (bilingual)+│ │ ├── overview.md / overview.en.md+│ │ ├── quick-start.md / quick-start.en.md+│ │ ├── install.md / install.en.md+│ │ ├── config.md / config.en.md+│ │ ├── release.md / release.en.md+│ │ └── troubleshooting.md / troubleshooting.en.md+│ ├── research/ # Research reports+│ └── dev/ # Internal development docs├── assets/ # Screenshots and icons├── apps/│ ├── collector/ # Data collection service (Node.js + WebSocket)+│ ├── agent/ # Agent daemon (Go)│ └── web/ # Next.js frontend app└── packages/└── shared/ # Shared types and utilitiesdiff --git a/README.md b/README.mdindex 4f2a193..352d0a1 100644--- a/README.md+++ b/README.md@@ -234,14 +234,56 @@ pnpm dev## 🤖 Agent 部署-当你希望中心化部署一个 Neko Master 服务,并在不同设备(OpenWrt、Linux、macOS)本地采集网关数据时,推荐使用 Agent 模式。+当你希望中心化部署一个 Neko Master 服务,并在不同设备(OpenWrt、Linux、macOS)本地采集网关数据时,推荐使用 Agent 模式。Agent 运行在网关旁边,主动拉取数据并上报至面板,面板无需主动连接网关。-- 总览: `docs/agent/overview.md`-- 快速开始: `docs/agent/quick-start.md`-- 安装指南: `docs/agent/install.md`-- 参数配置: `docs/agent/config.md`-- 发布流程: `docs/agent/release.md`-- 常见问题: `docs/agent/troubleshooting.md`+支持网关类型:**Clash / Mihomo**(WebSocket 实时)和 **Surge v5+**(HTTP 轮询)。++### 快速安装(UI 生成命令)++1. 在面板「设置 → 后端」中添加一个 `Agent` 类型后端,选择网关类型(Clash 或 Surge)+2. 点击「查看安装脚本」,复制一键安装命令,在目标主机上执行:++```bash+# Clash / Mihomo 网关示例+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='1' \+ NEKO_BACKEND_TOKEN='ag_xxx' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ sh++# Surge 网关示例+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='2' \+ NEKO_BACKEND_TOKEN='ag_yyy' \+ NEKO_GATEWAY_TYPE='surge' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9091' \+ sh+```++安装完成后,使用 `nekoagent` 管理实例:++```bash+nekoagent list # 列出所有实例+nekoagent status <instance> # 查看运行状态+nekoagent logs <instance> # 实时日志+nekoagent restart <instance> # 重启+nekoagent update <instance> # 更新到最新版+```++> 脚本会自动检测已有安装,若已存在则只添加新实例而不重新下载二进制。+> 同一主机可同时运行多个实例(不同 `NEKO_INSTANCE_NAME`),对应不同网关。++### Agent 文档++- [总览](./docs/agent/overview.md):架构说明、直连 vs Agent 对比、安全模型+- [快速开始](./docs/agent/quick-start.md):从 UI 到运行的完整步骤+- [安装指南](./docs/agent/install.md):安装方式、systemd / launchd / OpenWrt 开机自启+- [参数配置](./docs/agent/config.md):完整参数列表与示例+- [发布流程](./docs/agent/release.md):版本命名与兼容性策略+- [常见问题](./docs/agent/troubleshooting.md):常见错误与解决方法## 📖 首次使用@@ -450,7 +492,8 @@ BatchBuffer.flush()#### 步骤一:启动 ClickHouse 容器-`docker-compose.yml` 内置了 ClickHouse 服务,通过 `profiles: [clickhouse]` 隔离。启动时加上 profile:+仓库内置的 `docker-compose.yml` 已包含 ClickHouse 服务,通过 `profiles: [clickhouse]` 隔离,默认不启动。+直接在仓库根目录执行:```bashdocker compose --profile clickhouse up -d@@ -458,6 +501,54 @@ docker compose --profile clickhouse up -d> ClickHouse 数据持久化到 `./data/clickhouse`,与主应用数据分目录存储。+如果你使用的是**自定义 `docker-compose.yml`**(如上方场景 A/B),需手动添加 ClickHouse 服务块:++```yaml+services:+ neko-master:+ # ... 你的现有配置 ...+ environment:+ # 在现有 environment 中追加:+ - CH_ENABLED=${CH_ENABLED:-0}+ - CH_HOST=${CH_HOST:-clickhouse}+ - CH_PORT=${CH_PORT:-8123}+ - CH_DATABASE=${CH_DATABASE:-neko_master}+ - CH_USER=${CH_USER:-neko}+ - CH_PASSWORD=${CH_PASSWORD:-neko_master}+ - CH_WRITE_ENABLED=${CH_WRITE_ENABLED:-0}+ - STATS_QUERY_SOURCE=${STATS_QUERY_SOURCE:-sqlite}+ networks:+ - neko-master-network++ clickhouse:+ image: clickhouse/clickhouse-server:24.8+ container_name: neko-master-clickhouse+ restart: unless-stopped+ profiles: ["clickhouse"]+ ports:+ - "${CH_EXTERNAL_HTTP_PORT:-8123}:8123"+ - "${CH_EXTERNAL_NATIVE_PORT:-9000}:9000"+ volumes:+ - ./data/clickhouse:/var/lib/clickhouse+ environment:+ - CLICKHOUSE_DB=${CH_DATABASE:-neko_master}+ - CLICKHOUSE_USER=${CH_USER:-neko}+ - CLICKHOUSE_PASSWORD=${CH_PASSWORD:-neko_master}+ - CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1+ networks:+ - neko-master-network+ healthcheck:+ test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8123/ping || exit 1"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 40s++networks:+ neko-master-network:+ driver: bridge+```+#### 步骤二:配置环境变量在 `.env` 中添加(与 `docker-compose.yml` 同目录):@@ -816,14 +907,14 @@ docker compose up -d如果你想快速理解系统设计与实现深度,建议按下面顺序阅读:-1. **整体架构图**:端到端分层与模块职责- 中文:[`docs/architecture.md`](./docs/architecture.md)- English: [`docs/architecture.en.md`](./docs/architecture.en.md)+1. **整体架构图**:端到端分层与模块职责 → [docs/architecture.md](./docs/architecture.md)2. **数据流详解**:Clash / Surge 两条采集链路与聚合过程3. **数据模型与存储**:SQLite 表结构、ClickHouse Buffer 表、保留策略4. **实时通道设计**:`RealtimeStore` 合并策略与 WS 推送机制5. **ClickHouse 模块**:双写架构、健康回退、读取路由+完整文档索引:[docs/README.md](./docs/README.md)+> 该文档覆盖采集、聚合、缓存、实时推送与多后端管理的核心设计。## 🤝 反馈与 Issue@@ -847,12 +938,25 @@ neko-master/├── setup.sh # 一键配置脚本├── docker-start.sh # Docker 容器启动脚本├── start.sh # 源码开发启动脚本-├── docs/ # 架构与设计文档-│ ├── architecture.md # 中文架构文档-│ └── architecture.en.md # 英文架构文档+├── docs/ # 文档(见 docs/README.md)+│ ├── README.md # 文档总索引(中文)+│ ├── README.en.md # 文档总索引(英文)+│ ├── architecture.md # 系统架构(中文)+│ ├── architecture.en.md # 系统架构(英文)+│ ├── release-checklist.md+│ ├── agent/ # Agent 模式文档(中英文双语)+│ │ ├── overview.md / overview.en.md+│ │ ├── quick-start.md / quick-start.en.md+│ │ ├── install.md / install.en.md+│ │ ├── config.md / config.en.md+│ │ ├── release.md / release.en.md+│ │ └── troubleshooting.md / troubleshooting.en.md+│ ├── research/ # 研究报告+│ └── dev/ # 内部开发文档├── assets/ # 预览图和图标├── apps/│ ├── collector/ # 数据收集服务(Node.js + WebSocket)+│ ├── agent/ # Agent 守护进程(Go)│ └── web/ # Next.js 前端应用└── packages/└── shared/ # 共享类型定义和工具diff --git a/docs/README.en.md b/docs/README.en.mdnew file mode 100644index 0000000..11aabf2--- /dev/null+++ b/docs/README.en.md@@ -0,0 +1,35 @@+# Documentation Index++[中文](./README.md) | **English**++## Architecture++- [System Architecture](./architecture.en.md) — end-to-end architecture, data flow, module design, ClickHouse integration+- [Release Checklist](./release-checklist.md) — version release steps++## Agent++- [Documentation Index](./agent/README.en.md) — Agent docs navigation+- [Overview](./agent/overview.en.md) — how it works, Direct vs Agent comparison, security model+- [Quick Start](./agent/quick-start.en.md) — end-to-end setup from UI to running agent+- [Install Guide](./agent/install.en.md) — script install, systemd / launchd / OpenWrt autostart+- [Configuration](./agent/config.en.md) — full flag reference and examples+- [Release Flow](./agent/release.en.md) — versioning conventions and CI/CD pipeline+- [Troubleshooting](./agent/troubleshooting.en.md) — common errors and fixes++## Research Reports++- [Kimi 2.5](./research/kimi2.5.en.md) / [中文](./research/kimi2.5.zh.md)+- [GPT-5.3](./research/GPT5.3.en.md) / [中文](./research/GPT5.3.zh.md)+- [GLM-5](./research/glm5.en.md) / [中文](./research/glm5.zh.md)++## Internal Development Docs++> Internal analysis and planning documents from development. Not intended for end users.++- [ClickHouse Dataflow Analysis](./dev/clickhouse-dataflow-analysis.md)+- [ClickHouse Dataflow Analysis Report](./dev/clickhouse-dataflow-analysis-report.md)+- [ClickHouse Migration I/O Analysis](./dev/clickhouse-migration-io-analysis.md)+- [ClickHouse Refactor Plan](./dev/clickhouse-refactor-plan.md)+- [ClickHouse Review Report](./dev/clickhouse-review-report.md)+- [refactor/clickhouse Branch Review](./dev/review-refactor-clickhouse-branch.md)diff --git a/docs/README.md b/docs/README.mdindex 1e13a06..e274282 100644--- a/docs/README.md+++ b/docs/README.md@@ -1,38 +1,35 @@-# Documentation Index+# 文档索引-## Architecture+**中文 | [English](./README.en.md)**-- Chinese: `docs/architecture.md`-- English: `docs/architecture.en.md`-- ClickHouse Refactor Plan: `docs/clickhouse-refactor-plan.md`+## 架构-## Agent--- Index: `docs/agent/README.md`-- Overview: `docs/agent/overview.md`-- Quick Start: `docs/agent/quick-start.md`-- Install: `docs/agent/install.md`-- Config: `docs/agent/config.md`-- Release: `docs/agent/release.md`-- Troubleshooting: `docs/agent/troubleshooting.md`--## Release+- [系统架构](./architecture.md) — 端到端架构、数据流、模块设计、ClickHouse 集成+- [发布清单](./release-checklist.md) — 版本发布操作步骤-- Checklist: `docs/release-checklist.md`--## Research Reports+## Agent-### Kimi 2.5+- [文档总览](./agent/README.md) — Agent 文档导航+- [架构说明](./agent/overview.md) — 工作原理、直连 vs Agent 模式对比、安全模型+- [快速开始](./agent/quick-start.md) — 从 UI 到运行的完整步骤+- [安装指南](./agent/install.md) — 脚本安装、systemd / launchd / OpenWrt 开机自启+- [参数配置](./agent/config.md) — 完整运行时参数列表与示例+- [发布流程](./agent/release.md) — 版本命名规范与 CI/CD 流程+- [常见问题](./agent/troubleshooting.md) — 常见错误与解决方法-- Chinese: `docs/research-kimi2.5.zh.md`-- English: `docs/research-kimi2.5.en.md`+## 研究报告-### GPT-5.3+- [Kimi 2.5](./research/kimi2.5.zh.md) / [English](./research/kimi2.5.en.md)+- [GPT-5.3](./research/GPT5.3.zh.md) / [English](./research/GPT5.3.en.md)+- [GLM-5](./research/glm5.zh.md) / [English](./research/glm5.en.md)-- Chinese: `docs/research-GPT5.3.zh.md`-- English: `docs/research-GPT5.3.en.md`+## 内部开发文档-### GLM-5+> 以下为开发过程中的内部分析与计划文档,不面向最终用户。-- Chinese: `docs/research-glm5.zh.md`-- English: `docs/research-glm5.en.md`+- [ClickHouse 数据流分析](./dev/clickhouse-dataflow-analysis.md)+- [ClickHouse 数据流分析报告](./dev/clickhouse-dataflow-analysis-report.md)+- [ClickHouse 迁移 I/O 分析](./dev/clickhouse-migration-io-analysis.md)+- [ClickHouse 重构计划](./dev/clickhouse-refactor-plan.md)+- [ClickHouse 评审报告](./dev/clickhouse-review-report.md)+- [refactor/clickhouse 分支评审](./dev/review-refactor-clickhouse-branch.md)diff --git a/docs/agent/README.en.md b/docs/agent/README.en.mdnew file mode 100644index 0000000..2b25f51--- /dev/null+++ b/docs/agent/README.en.md@@ -0,0 +1,12 @@+# Agent Documentation++[中文](./README.md) | **English**++Use this guide set when deploying Neko Master in a centralized mode with remote agents.++- [`overview.en.md`](./overview.en.md): architecture and mode comparison+- [`quick-start.en.md`](./quick-start.en.md): minimal setup from UI to running agent+- [`install.en.md`](./install.en.md): install methods, supported platforms, service startup+- [`config.en.md`](./config.en.md): full runtime flags and environment variables+- [`release.en.md`](./release.en.md): release artifact naming and CI/CD workflow+- [`troubleshooting.en.md`](./troubleshooting.en.md): common errors and fixesdiff --git a/docs/agent/README.md b/docs/agent/README.mdindex 3f7378b..88344bc 100644--- a/docs/agent/README.md+++ b/docs/agent/README.md@@ -1,10 +1,12 @@-# Agent Documentation+# Agent 文档-Use this guide set when deploying Neko Master in a centralized mode with remote agents.+本文档组适用于将 Neko Master 以中心化面板模式部署、并通过远程 Agent 采集数据的场景。-- `docs/agent/overview.md`: architecture and mode comparison-- `docs/agent/quick-start.md`: minimal setup from UI to running agent-- `docs/agent/install.md`: install methods, supported platforms, service startup-- `docs/agent/config.md`: full runtime flags and environment variables-- `docs/agent/release.md`: release artifact naming and CI/CD workflow-- `docs/agent/troubleshooting.md`: common errors and fixes+**中文 | [English](./README.en.md)**++- [`overview.md`](./overview.md):架构说明、直连 vs Agent 对比、安全模型+- [`quick-start.md`](./quick-start.md):从 UI 到运行的完整快速上手步骤+- [`install.md`](./install.md):安装方式、支持平台、systemd / launchd 开机自启+- [`config.md`](./config.md):完整运行时参数与环境变量说明+- [`release.md`](./release.md):发布产物命名规范与 CI/CD 流程+- [`troubleshooting.md`](./troubleshooting.md):常见错误与解决方法diff --git a/docs/agent/config.en.md b/docs/agent/config.en.mdnew file mode 100644index 0000000..cc54a8b--- /dev/null+++ b/docs/agent/config.en.md@@ -0,0 +1,55 @@+# Agent Configuration++[中文](./config.md) | **English**++## Required flags++- `--server-url`: panel server URL (without `/api` suffix is fine)+- `--backend-id`: backend numeric id+- `--backend-token`: backend auth token+- `--gateway-type`: `clash` or `surge`+- `--gateway-url`: gateway API URL++## Optional flags++- `--gateway-token`: gateway auth token (`Authorization` for Clash, `x-key` for Surge)+- `--agent-id`: custom agent ID (default: auto-generated from SHA256 of backend token, stable across restarts)+- `--report-interval`: report loop interval (default `2s`)+- `--heartbeat-interval`: heartbeat interval (default `30s`)+- `--gateway-poll-interval`: gateway pull interval (default `2s`)+- `--request-timeout`: HTTP timeout (default `15s`)+- `--report-batch-size`: max updates per report (default `1000`)+- `--max-pending-updates`: memory queue cap (default `50000`)+- `--stale-flow-timeout`: stale flow eviction timeout (default `5m`)+- `--log`: enable logs, set `--log=false` to quiet mode+- `--version`: print version++## Example: Clash++```bash+./neko-agent \+ --server-url 'http://10.0.0.2:3000' \+ --backend-id 8 \+ --backend-token 'ag_xxx' \+ --gateway-type 'clash' \+ --gateway-url 'http://127.0.0.1:9090' \+ --gateway-token 'clash-secret'+```++## Example: Surge++```bash+./neko-agent \+ --server-url 'http://10.0.0.2:3000' \+ --backend-id 9 \+ --backend-token 'ag_xxx' \+ --gateway-type 'surge' \+ --gateway-url 'http://127.0.0.1:9091' \+ --gateway-token 'surge-key'+```++## Best-practice defaults for remote LAN++- `--gateway-poll-interval=2s`+- `--report-interval=2s`+- `--heartbeat-interval=10s` (faster offline detection)diff --git a/docs/agent/config.md b/docs/agent/config.mdindex dd81ae2..2706575 100644--- a/docs/agent/config.md+++ b/docs/agent/config.md@@ -1,28 +1,30 @@-# Agent Configuration+# Agent 参数配置-## Required flags+**中文 | [English](./config.en.md)**-- `--server-url`: panel server URL (without `/api` suffix is fine)-- `--backend-id`: backend numeric id-- `--backend-token`: backend auth token-- `--gateway-type`: `clash` or `surge`-- `--gateway-url`: gateway API URL+## 必填参数-## Optional flags+- `--server-url`:面板服务器 URL(无需添加 `/api` 后缀)+- `--backend-id`:后端数字 ID+- `--backend-token`:后端认证 token+- `--gateway-type`:`clash` 或 `surge`+- `--gateway-url`:网关 API URL-- `--gateway-token`: gateway auth token (`Authorization` for Clash, `x-key` for Surge)-- `--agent-id`: custom agent ID (default `hostname-pid`)-- `--report-interval`: report loop interval (default `2s`)-- `--heartbeat-interval`: heartbeat interval (default `30s`)-- `--gateway-poll-interval`: gateway pull interval (default `2s`)-- `--request-timeout`: HTTP timeout (default `15s`)-- `--report-batch-size`: max updates per report (default `1000`)-- `--max-pending-updates`: memory queue cap (default `50000`)-- `--stale-flow-timeout`: stale flow eviction timeout (default `5m`)-- `--log`: enable logs, set `--log=false` to quiet mode-- `--version`: print version+## 可选参数-## Example: Clash+- `--gateway-token`:网关认证 token(Clash 使用 `Authorization`,Surge 使用 `x-key`)+- `--agent-id`:自定义 Agent ID(默认:从 backend token 的 SHA256 自动生成,重启稳定)+- `--report-interval`:上报循环间隔(默认 `2s`)+- `--heartbeat-interval`:心跳间隔(默认 `30s`)+- `--gateway-poll-interval`:网关拉取间隔(默认 `2s`)+- `--request-timeout`:HTTP 超时(默认 `15s`)+- `--report-batch-size`:每次上报最大条目数(默认 `1000`)+- `--max-pending-updates`:内存队列上限(默认 `50000`)+- `--stale-flow-timeout`:过期流量清除超时(默认 `5m`)+- `--log`:启用日志,`--log=false` 为静默模式+- `--version`:打印版本号++## 示例:Clash```bash./neko-agent \@@ -34,7 +36,7 @@--gateway-token 'clash-secret'```-## Example: Surge+## 示例:Surge```bash./neko-agent \@@ -46,8 +48,8 @@--gateway-token 'surge-key'```-## Best-practice defaults for remote LAN+## 远程 LAN 推荐默认值- `--gateway-poll-interval=2s`- `--report-interval=2s`-- `--heartbeat-interval=10s` (faster offline detection)+- `--heartbeat-interval=10s`(加快离线检测)diff --git a/docs/agent/install.en.md b/docs/agent/install.en.mdnew file mode 100644index 0000000..200637b--- /dev/null+++ b/docs/agent/install.en.md@@ -0,0 +1,248 @@+# Agent Install Guide++[中文](./install.md) | **English**++## Supported targets++Release artifacts are published for:++- `darwin-amd64`+- `darwin-arm64`+- `linux-amd64`+- `linux-arm64`+- `linux-armv7`+- `linux-mips`+- `linux-mipsle`++## Install via script (recommended)++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='13' \+ NEKO_BACKEND_TOKEN='ag_xxx' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ sh+```++Optional env:++- `NEKO_GATEWAY_TOKEN`: gateway auth token+- `NEKO_AGENT_VERSION`: `latest` (default) or explicit tag like `agent-v0.2.0`+- `NEKO_INSTALL_DIR`: install directory (default `$HOME/.local/bin`)+- `NEKO_AUTO_START`: `true|false` (default `true`)+- `NEKO_LOG`: `true|false` (default `true`)+- `NEKO_LOG_FILE`: runtime log file path+- `NEKO_PACKAGE_URL`: custom package URL override+- `NEKO_CHECKSUMS_URL`: custom checksums URL override+- `NEKO_INSTANCE_NAME`: instance name for `nekoagent` manager (default `backend-<id>`)+- `NEKO_BIN_LINK_MODE`: `auto|true|false` for symlink into global bin dir (default `auto`)+- `NEKO_LINK_DIR`: global bin dir for symlink (default `/usr/local/bin`)++After install, manage agent with:++```bash+nekoagent status <instance>+nekoagent logs <instance>+nekoagent restart <instance>+nekoagent update <instance> agent-vX.Y.Z+nekoagent remove <instance>+```++Uninstall binaries:++```bash+nekoagent uninstall+```++## Manual install++1. Download the correct tarball from GitHub Releases+2. Verify hash using `checksums.txt`+3. Extract `neko-agent`+4. Run executable with backend parameters++## OpenWrt note++Before build selection, check architecture:++```sh+uname -m+opkg print-architecture+```++Common mapping:++- `x86_64` -> `linux-amd64`+- `aarch64` -> `linux-arm64`+- `armv7*` -> `linux-armv7`+- `mips` -> `linux-mips`+- `mipsle` -> `linux-mipsle`++## What gets installed++The install script places two binaries into `NEKO_INSTALL_DIR` (default `~/.local/bin`):++- `neko-agent` — the data collection daemon (runs continuously, reports to panel)+- `nekoagent` — the CLI manager for lifecycle operations (start / stop / update / remove)++The `nekoagent` manager stores:++- Instance configs in `CONFIG_DIR` (default `/etc/neko-agent/<name>.env`)+- PID and log files in `STATE_DIR` (default `/var/run/neko-agent/`)++## Autostart on system boot++By default `neko-agent` runs as a background process managed by `nekoagent`. It does not+register a system service automatically. For production deployments, set up a system service+so the agent survives reboots.++### Linux — systemd++Create `/etc/systemd/system/neko-agent-<instance>.service` (replace `<instance>` with your+instance name, e.g. `backend-1`):++```ini+[Unit]+Description=Neko Agent (<instance>)+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+User=root+EnvironmentFile=/etc/neko-agent/<instance>.env+ExecStart=/usr/local/bin/neko-agent \+ --server-url ${NEKO_SERVER} \+ --backend-id ${NEKO_BACKEND_ID} \+ --backend-token ${NEKO_BACKEND_TOKEN} \+ --gateway-type ${NEKO_GATEWAY_TYPE} \+ --gateway-url ${NEKO_GATEWAY_URL}+Restart=on-failure+RestartSec=10+StandardOutput=journal+StandardError=journal++[Install]+WantedBy=multi-user.target+```++If `NEKO_GATEWAY_TOKEN` is set, append it to `ExecStart`:++```ini+ExecStart=/usr/local/bin/neko-agent \+ ...+ --gateway-token ${NEKO_GATEWAY_TOKEN}+```++Enable and start:++```bash+systemctl daemon-reload+systemctl enable neko-agent-<instance>+systemctl start neko-agent-<instance>+systemctl status neko-agent-<instance>+```++View logs:++```bash+journalctl -u neko-agent-<instance> -f+```++> Note: If `neko-agent` is installed to `~/.local/bin` (non-root), adjust `ExecStart` path+> accordingly and consider running the service under a non-root user.++### macOS — launchd++Create `~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist`:++```xml+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>io.neko-master.agent.<instance></string>++ <key>ProgramArguments</key>+ <array>+ <string>/usr/local/bin/neko-agent</string>+ <string>--server-url</string>+ <string>http://your-panel:3000</string>+ <string>--backend-id</string>+ <string>1</string>+ <string>--backend-token</string>+ <string>ag_xxx</string>+ <string>--gateway-type</string>+ <string>clash</string>+ <string>--gateway-url</string>+ <string>http://127.0.0.1:9090</string>+ </array>++ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/tmp/neko-agent-<instance>.log</string>+ <key>StandardErrorPath</key>+ <string>/tmp/neko-agent-<instance>.log</string>+</dict>+</plist>+```++Load the service:++```bash+launchctl load ~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist+```++Unload:++```bash+launchctl unload ~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist+```++### OpenWrt — init.d++Create `/etc/init.d/neko-agent`:++```sh+#!/bin/sh /etc/rc.common+USE_PROCD=1+START=95+STOP=10++PROG=/usr/local/bin/neko-agent+INSTANCE=backend-1 # change as needed+CONF=/etc/neko-agent/${INSTANCE}.env++start_service() {+ # load config+ [ -f "$CONF" ] && . "$CONF"+ procd_open_instance+ procd_set_param command "$PROG" \+ --server-url "$NEKO_SERVER" \+ --backend-id "$NEKO_BACKEND_ID" \+ --backend-token "$NEKO_BACKEND_TOKEN" \+ --gateway-type "$NEKO_GATEWAY_TYPE" \+ --gateway-url "$NEKO_GATEWAY_URL"+ [ -n "$NEKO_GATEWAY_TOKEN" ] && \+ procd_append_param command --gateway-token "$NEKO_GATEWAY_TOKEN"+ procd_set_param respawn 3600 5 5+ procd_set_param stdout 1+ procd_set_param stderr 1+ procd_close_instance+}+```++Enable:++```bash+chmod +x /etc/init.d/neko-agent+/etc/init.d/neko-agent enable+/etc/init.d/neko-agent start+```diff --git a/docs/agent/install.md b/docs/agent/install.mdindex cd65c31..e1e4d82 100644--- a/docs/agent/install.md+++ b/docs/agent/install.md@@ -1,8 +1,10 @@-# Agent Install Guide+# Agent 安装指南-## Supported targets+**中文 | [English](./install.en.md)**-Release artifacts are published for:+## 支持的目标平台++发布产物覆盖:- `darwin-amd64`- `darwin-arm64`@@ -12,7 +14,7 @@ Release artifacts are published for:- `linux-mips`- `linux-mipsle`-## Install via script (recommended)+## 通过脚本安装(推荐)```bashcurl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \@@ -24,21 +26,21 @@ curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/sh```-Optional env:+可选环境变量:-- `NEKO_GATEWAY_TOKEN`: gateway auth token-- `NEKO_AGENT_VERSION`: `latest` (default) or explicit tag like `agent-v0.2.0`-- `NEKO_INSTALL_DIR`: install directory (default `$HOME/.local/bin`)-- `NEKO_AUTO_START`: `true|false` (default `true`)-- `NEKO_LOG`: `true|false` (default `true`)-- `NEKO_LOG_FILE`: runtime log file path-- `NEKO_PACKAGE_URL`: custom package URL override-- `NEKO_CHECKSUMS_URL`: custom checksums URL override-- `NEKO_INSTANCE_NAME`: instance name for `nekoagent` manager (default `backend-<id>`)-- `NEKO_BIN_LINK_MODE`: `auto|true|false` for symlink into global bin dir (default `auto`)-- `NEKO_LINK_DIR`: global bin dir for symlink (default `/usr/local/bin`)+- `NEKO_GATEWAY_TOKEN`:网关认证 token+- `NEKO_AGENT_VERSION`:`latest`(默认)或具体标签如 `agent-v0.2.0`+- `NEKO_INSTALL_DIR`:安装目录(默认 `$HOME/.local/bin`)+- `NEKO_AUTO_START`:`true|false`(默认 `true`)+- `NEKO_LOG`:`true|false`(默认 `true`)+- `NEKO_LOG_FILE`:运行时日志文件路径+- `NEKO_PACKAGE_URL`:自定义软件包 URL+- `NEKO_CHECKSUMS_URL`:自定义校验和 URL+- `NEKO_INSTANCE_NAME`:`nekoagent` 管理器中的实例名(默认 `backend-<id>`)+- `NEKO_BIN_LINK_MODE`:全局 bin 目录软链模式(`auto|true|false`,默认 `auto`)+- `NEKO_LINK_DIR`:软链目标目录(默认 `/usr/local/bin`)-After install, manage agent with:+安装完成后,使用以下命令管理 Agent:```bashnekoagent status <instance>@@ -48,32 +50,196 @@ nekoagent update <instance> agent-vX.Y.Znekoagent remove <instance>```-Uninstall binaries:+卸载二进制:```bashnekoagent uninstall```-## Manual install+## 手动安装++1. 从 GitHub Releases 下载对应平台的压缩包+2. 使用 `checksums.txt` 验证哈希+3. 解压 `neko-agent`+4. 携带后端参数直接运行可执行文件++## 安装了哪些文件++安装脚本在 `NEKO_INSTALL_DIR`(默认 `~/.local/bin`)中放置两个二进制文件:++- `neko-agent` — 数据采集守护进程(持续运行,向面板上报数据)+- `nekoagent` — CLI 管理器(Shell 脚本,管理实例生命周期:start / stop / update / remove)++`nekoagent` 管理器的存储位置:++- 实例配置:`CONFIG_DIR`(默认 `/etc/neko-agent/<name>.env`)+- PID 与日志文件:`STATE_DIR`(默认 `/var/run/neko-agent/`)++## 开机自启配置++`neko-agent` 默认以后台进程方式运行,由 `nekoagent` 管理,不自动注册系统服务。+生产环境建议配置系统服务,确保重启后自动恢复运行。++### Linux — systemd++创建 `/etc/systemd/system/neko-agent-<instance>.service`(将 `<instance>` 替换为实例名,如 `backend-1`):++```ini+[Unit]+Description=Neko Agent (<instance>)+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+User=root+EnvironmentFile=/etc/neko-agent/<instance>.env+ExecStart=/usr/local/bin/neko-agent \+ --server-url ${NEKO_SERVER} \+ --backend-id ${NEKO_BACKEND_ID} \+ --backend-token ${NEKO_BACKEND_TOKEN} \+ --gateway-type ${NEKO_GATEWAY_TYPE} \+ --gateway-url ${NEKO_GATEWAY_URL}+Restart=on-failure+RestartSec=10+StandardOutput=journal+StandardError=journal++[Install]+WantedBy=multi-user.target+```++若设置了 `NEKO_GATEWAY_TOKEN`,在 `ExecStart` 末尾追加:++```ini+ExecStart=/usr/local/bin/neko-agent \+ ...+ --gateway-token ${NEKO_GATEWAY_TOKEN}+```++启用并启动:++```bash+systemctl daemon-reload+systemctl enable neko-agent-<instance>+systemctl start neko-agent-<instance>+systemctl status neko-agent-<instance>+```++查看日志:++```bash+journalctl -u neko-agent-<instance> -f+```++> 注意:若 `neko-agent` 安装在 `~/.local/bin`(非 root),需相应调整 `ExecStart` 路径,并考虑以非 root 用户运行服务。++### macOS — launchd++创建 `~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist`:++```xml+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>io.neko-master.agent.<instance></string>++ <key>ProgramArguments</key>+ <array>+ <string>/usr/local/bin/neko-agent</string>+ <string>--server-url</string>+ <string>http://your-panel:3000</string>+ <string>--backend-id</string>+ <string>1</string>+ <string>--backend-token</string>+ <string>ag_xxx</string>+ <string>--gateway-type</string>+ <string>clash</string>+ <string>--gateway-url</string>+ <string>http://127.0.0.1:9090</string>+ </array>++ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/tmp/neko-agent-<instance>.log</string>+ <key>StandardErrorPath</key>+ <string>/tmp/neko-agent-<instance>.log</string>+</dict>+</plist>+```++加载服务:++```bash+launchctl load ~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist+```++卸载服务:-1. Download the correct tarball from GitHub Releases-2. Verify hash using `checksums.txt`-3. Extract `neko-agent`-4. Run executable with backend parameters+```bash+launchctl unload ~/Library/LaunchAgents/io.neko-master.agent.<instance>.plist+```++### OpenWrt — init.d++创建 `/etc/init.d/neko-agent`:++```sh+#!/bin/sh /etc/rc.common+USE_PROCD=1+START=95+STOP=10++PROG=/usr/local/bin/neko-agent+INSTANCE=backend-1 # 按需修改+CONF=/etc/neko-agent/${INSTANCE}.env++start_service() {+ # 加载配置+ [ -f "$CONF" ] && . "$CONF"+ procd_open_instance+ procd_set_param command "$PROG" \+ --server-url "$NEKO_SERVER" \+ --backend-id "$NEKO_BACKEND_ID" \+ --backend-token "$NEKO_BACKEND_TOKEN" \+ --gateway-type "$NEKO_GATEWAY_TYPE" \+ --gateway-url "$NEKO_GATEWAY_URL"+ [ -n "$NEKO_GATEWAY_TOKEN" ] && \+ procd_append_param command --gateway-token "$NEKO_GATEWAY_TOKEN"+ procd_set_param respawn 3600 5 5+ procd_set_param stdout 1+ procd_set_param stderr 1+ procd_close_instance+}+```++启用:++```bash+chmod +x /etc/init.d/neko-agent+/etc/init.d/neko-agent enable+/etc/init.d/neko-agent start+```-## OpenWrt note+## OpenWrt 注意事项-Before build selection, check architecture:+安装前确认架构:```shuname -mopkg print-architecture```-Common mapping:+常见对应关系:-- `x86_64` -> `linux-amd64`-- `aarch64` -> `linux-arm64`-- `armv7*` -> `linux-armv7`-- `mips` -> `linux-mips`-- `mipsle` -> `linux-mipsle`+- `x86_64` → `linux-amd64`+- `aarch64` → `linux-arm64`+- `armv7*` → `linux-armv7`+- `mips` → `linux-mips`+- `mipsle` → `linux-mipsle`diff --git a/docs/agent/overview.en.md b/docs/agent/overview.en.mdnew file mode 100644index 0000000..ccc2f38--- /dev/null+++ b/docs/agent/overview.en.md@@ -0,0 +1,69 @@+# Agent Mode Overview++[中文](./overview.md) | **English**++## What Agent mode solves++Agent mode allows a centralized Neko Master panel to receive data from remote LAN gateways without direct collector-to-gateway access.++- Panel service runs in one central location (cloud VPS, NAS, server)+- Agent runs close to each gateway (OpenWrt, Linux host, router companion box)+- Agent pulls local gateway data and reports to panel over HTTP API++This is ideal for multi-site homes/labs and distributed deployments.++## Data flow++1. Neko Master backend creates an `agent://<agent-id>` backend with system-managed token+2. Agent polls Clash/Surge gateway API locally+3. Agent submits batch deltas to `/api/agent/report`+4. Agent sends periodic heartbeat to `/api/agent/heartbeat`+5. Dashboard reads unified backend statistics and realtime cache++## Direct vs Agent++- `Direct`+ - collector connects gateway directly+ - lowest latency for local setup+ - requires network reachability from collector to gateway+- `Agent`+ - collector does not pull remote gateway directly+ - one extra hop (agent report), better network isolation+ - easier for cross-LAN / NAT / private subnet deployments++## Security model++- Agent backend token is system-generated and treated as a credential+- Token rotation invalidates old running agents+- `agentId` is derived from the backend token: `"agent-" + sha256(token)[:16]` — stable across restarts, unique per token+- A backend token is bound to one `agentId`; using the same token from a different host with a different custom `--agent-id` will be rejected+- To use `--agent-id` explicitly, set it consistently — changing it breaks the binding++## Gateway type support++The agent supports two gateway types:++- `clash` — connects to Clash / Mihomo via WebSocket (`/connections` endpoint); real-time push+- `surge` — polls Surge HTTP API (`/v1/requests/recent`) every 2 seconds; no WebSocket required++Both types go through the same report pipeline to the panel. Set `--gateway-type` accordingly.++## Multi-instance support++A single host can run multiple agent instances simultaneously, each reporting to a different+backend on the same or different panels. The `nekoagent` CLI manager handles instance+isolation using separate config and PID files per instance name.++Example: one host running both a Clash and a Surge gateway:++```+nekoagent list+home-clash running backend-id=1 gateway=clash+home-surge running backend-id=2 gateway=surge+```++## Process isolation (PID lock)++Each agent instance holds a PID lock to prevent duplicate processes for the same backend.+If an instance crashes and leaves a stale PID file, `nekoagent start` will report it as+already running. See troubleshooting guide for how to resolve this.diff --git a/docs/agent/overview.md b/docs/agent/overview.mdindex 2e0d069..806ac6d 100644--- a/docs/agent/overview.md+++ b/docs/agent/overview.md@@ -1,36 +1,68 @@-# Agent Mode Overview+# Agent 模式概览-## What Agent mode solves+**中文 | [English](./overview.en.md)**-Agent mode allows a centralized Neko Master panel to receive data from remote LAN gateways without direct collector-to-gateway access.+## Agent 模式解决的问题-- Panel service runs in one central location (cloud VPS, NAS, server)-- Agent runs close to each gateway (OpenWrt, Linux host, router companion box)-- Agent pulls local gateway data and reports to panel over HTTP API+Agent 模式允许一个中心化的 Neko Master 面板接收来自远程 LAN 网关的数据,无需 collector 直连网关。-This is ideal for multi-site homes/labs and distributed deployments.+- 面板部署在中心位置(云服务器、NAS、服务器)+- Agent 运行在每个网关旁边(OpenWrt、Linux 主机、路由器伴机)+- Agent 本地拉取网关数据,通过 HTTP API 上报至面板-## Data flow+适用于多站点家庭/实验室和分布式部署场景。-1. Neko Master backend creates an `agent://<agent-id>` backend with system-managed token-2. Agent polls Clash/Surge gateway API locally-3. Agent submits batch deltas to `/api/agent/report`-4. Agent sends periodic heartbeat to `/api/agent/heartbeat`-5. Dashboard reads unified backend statistics and realtime cache+## 数据流-## Direct vs Agent+1. Neko Master 后端创建一个 `agent://` 类型后端,系统自动生成 token+2. Agent 在本地轮询 Clash/Surge 网关 API+3. Agent 批量上报流量增量到 `/api/agent/report`+4. Agent 定时发送心跳到 `/api/agent/heartbeat`+5. 面板读取统一后端统计与实时缓存-- `Direct`- - collector connects gateway directly- - lowest latency for local setup- - requires network reachability from collector to gateway-- `Agent`- - collector does not pull remote gateway directly- - one extra hop (agent report), better network isolation- - easier for cross-LAN / NAT / private subnet deployments+## 支持的网关类型-## Security model+Agent 支持两种网关类型:-- Agent backend token is system-generated and treated as a credential-- Token rotation invalidates old running agents-- One backend token is bound to one `agentId` (multi-agent token reuse is rejected)+- `clash` — 通过 WebSocket 连接 Clash / Mihomo(`/connections` 端点);实时推送+- `surge` — 轮询 Surge HTTP API(`/v1/requests/recent`),每 2 秒一次;无需 WebSocket++两种类型均走相同的上报流水线到面板。使用 `--gateway-type` 指定。++## 直连模式 vs Agent 模式++- **直连(Direct)**+ - collector 直接连接网关+ - 本地部署延迟最低+ - 需要 collector 到网关网络可达+- **Agent**+ - collector 不主动拉取远程网关+ - 多一跳(agent 上报),网络隔离更好+ - 适合跨 LAN / NAT / 私有子网部署++## 多实例支持++同一台主机可同时运行多个 Agent 实例,分别上报到同一或不同面板的不同后端。`nekoagent` CLI 管理器通过独立的配置文件和 PID 文件实现实例隔离。++示例:同一主机同时运行 Clash 和 Surge 网关:++```+nekoagent list+home-clash running backend-id=1 gateway=clash+home-surge running backend-id=2 gateway=surge+```++## 进程隔离(PID 锁)++每个 Agent 实例持有 PID 锁,防止同一后端运行重复进程。+若实例崩溃后遗留 PID 文件,`nekoagent start` 会报告其仍在运行。+参见故障排查文档了解处理方法。++## 安全模型++- 面板为每个 Agent 后端生成唯一 token+- `agentId` 由 backend token 派生:`"agent-" + sha256(token)[:16]`,重启后保持稳定,无需手动指定+- Token 与 `agentId` 绑定,同一 token 不能以不同 `agentId` 注册(服务端拒绝)+- 如需使用 `--agent-id` 自定义,需保持一致——修改后会破坏绑定关系+- Token 轮换后旧进程的请求立即被拒绝(需重新配置新 token 再启动)+- 配置同步与策略同步均有 MD5 去重,减少无效 POSTdiff --git a/docs/agent/quick-start.en.md b/docs/agent/quick-start.en.mdnew file mode 100644index 0000000..62ec1b2--- /dev/null+++ b/docs/agent/quick-start.en.md@@ -0,0 +1,78 @@+# Agent Quick Start++[中文](./quick-start.md) | **English**++## 1) Create an Agent backend in UI++In `Settings -> Backends`:++1. Click "Add Backend"+2. Set mode to `Agent`+3. Choose gateway type: `Clash / Mihomo` or `Surge`+4. Save — the panel generates a backend token automatically++Then open **"View Agent Script"** and copy the one-line install command.++## 2) Install on remote host++### Clash / Mihomo gateway++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='1' \+ NEKO_BACKEND_TOKEN='ag_xxx' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ NEKO_GATEWAY_TOKEN='clash-secret' \+ sh+```++### Surge gateway++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='2' \+ NEKO_BACKEND_TOKEN='ag_yyy' \+ NEKO_GATEWAY_TYPE='surge' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9091' \+ NEKO_GATEWAY_TOKEN='surge-key' \+ sh+```++- `NEKO_GATEWAY_TYPE`: `clash` for Clash/Mihomo, `surge` for Surge v5++- `NEKO_GATEWAY_TOKEN`: Clash uses it as `Authorization` bearer; Surge uses it as `x-key` header+- `NEKO_GATEWAY_TOKEN` is optional — omit if no auth is configured on the gateway++The install script detects an existing installation automatically. If `neko-agent` is already+present, it adds the new instance without re-downloading the binary.++## 3) Manage the agent++After install, use `nekoagent` to manage instances:++```bash+nekoagent list # list all configured instances+nekoagent status <instance> # check running state+nekoagent logs <instance> # tail live logs+nekoagent restart <instance> # restart the process+nekoagent stop <instance> # graceful stop (up to ~12s for final flush)+nekoagent update <instance> # update to latest version+nekoagent remove <instance> # stop + delete config+```++The default instance name is `backend-<id>` unless you set `NEKO_INSTANCE_NAME`.++## 4) Verify in dashboard++- In backend list, click **"Test Connection"**+- Confirm agent health becomes `online`+- Confirm traffic is visible in the dashboard after ~30 seconds (first flush interval)++## Important notes++- Use the actual panel address in `NEKO_SERVER`; avoid `localhost` unless panel is on the same host+- Each backend token is bound to one agent ID — do not reuse the same token across multiple hosts+- Rotate token in UI if leaked; old agent process will be rejected until reconfigured with new token+- Adding a second gateway on the same host: run the install script again with a different `NEKO_BACKEND_ID` and `NEKO_INSTANCE_NAME`; the script detects the existing binary and only adds the new instancediff --git a/docs/agent/quick-start.md b/docs/agent/quick-start.mdindex 1ca6552..2a0625d 100644--- a/docs/agent/quick-start.md+++ b/docs/agent/quick-start.md@@ -1,41 +1,77 @@-# Agent Quick Start+# Agent 快速开始-## 1) Create an Agent backend in UI+**中文 | [English](./quick-start.en.md)**-In `Settings -> Backends`:+## 1)在 UI 中创建 Agent 后端-1. Add backend-2. Set mode to `Agent`-3. Choose gateway type (`Clash` or `Surge`)-4. Save backend+在「设置 → 后端」中:-Then open `View Agent Script` and copy either:+1. 点击「添加后端」+2. 将模式设置为 `Agent`+3. 选择网关类型:`Clash / Mihomo` 或 `Surge`+4. 保存——面板自动生成后端 token-- Run command (`./neko-agent ...`)-- Install command (`curl | sh`)+然后点击「**查看安装脚本**」,复制一键安装命令。-## 2) Install on remote host+## 2)在远程主机上安装-Example:+### Clash / Mihomo 网关```bashcurl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \| env NEKO_SERVER='http://your-panel:3000' \- NEKO_BACKEND_ID='13' \+ NEKO_BACKEND_ID='1' \NEKO_BACKEND_TOKEN='ag_xxx' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ NEKO_GATEWAY_TOKEN='clash-secret' \+ sh+```++### Surge 网关++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://your-panel:3000' \+ NEKO_BACKEND_ID='2' \+ NEKO_BACKEND_TOKEN='ag_yyy' \NEKO_GATEWAY_TYPE='surge' \NEKO_GATEWAY_URL='http://127.0.0.1:9091' \- NEKO_GATEWAY_TOKEN='optional' \+ NEKO_GATEWAY_TOKEN='surge-key' \sh```-## 3) Verify status+- `NEKO_GATEWAY_TYPE`:`clash` 对应 Clash/Mihomo,`surge` 对应 Surge v5++- `NEKO_GATEWAY_TOKEN`:Clash 中作为 `Authorization` Bearer;Surge 中作为 `x-key` 请求头+- `NEKO_GATEWAY_TOKEN` 可选——若网关未配置认证则省略++安装脚本会自动检测已有安装。若 `neko-agent` 已存在,只添加新实例,不重新下载二进制。++## 3)管理 Agent 实例++安装完成后,使用 `nekoagent` 管理实例:++```bash+nekoagent list # 列出所有已配置实例+nekoagent status <instance> # 查看运行状态+nekoagent logs <instance> # 实时查看日志+nekoagent restart <instance> # 重启进程+nekoagent stop <instance> # 优雅停止(最多等待约 12 秒完成最终 flush)+nekoagent update <instance> # 更新到最新版本+nekoagent remove <instance> # 停止并删除配置+```++默认实例名为 `backend-<id>`,可通过 `NEKO_INSTANCE_NAME` 自定义。++## 4)在面板中验证-- In backend list, click `Test Connection`-- Confirm agent health becomes online-- Confirm traffic is visible in dashboard+- 在后端列表中点击「**测试连接**」+- 确认 Agent 健康状态变为 `在线`+- 约 30 秒后(首次 flush 间隔)在面板中确认流量数据可见-## Important notes+## 注意事项-- Use actual panel address in `NEKO_SERVER`; avoid `localhost` unless panel runs on same host-- Rotate token if leaked; old agent process will be rejected until reconfigured+- `NEKO_SERVER` 填写实际面板地址;除非面板运行在同一主机,否则避免使用 `localhost`+- 每个 backend token 只绑定一个 agent ID——不要在多台主机间共用同一 token+- 若 token 泄露,在 UI 中轮换 token;旧进程将被拒绝,需用新 token 重新配置后启动+- 在同一主机上添加第二个网关:使用不同的 `NEKO_BACKEND_ID` 和 `NEKO_INSTANCE_NAME` 再次执行安装脚本;脚本检测到已有二进制后只添加新实例diff --git a/docs/agent/release.en.md b/docs/agent/release.en.mdnew file mode 100644index 0000000..3d15348--- /dev/null+++ b/docs/agent/release.en.md@@ -0,0 +1,59 @@+# Agent Release and Packaging++[中文](./release.md) | **English**++## Tagging strategy++- Agent release workflow triggers on tags: `agent-v*`+- Example: `agent-v0.2.0`++## Generated assets++For each target OS/arch, workflow publishes two tarballs:++- Versioned: `neko-agent_<tag>_<os>_<arch>.tar.gz`+- Latest alias: `neko-agent_<os>_<arch>.tar.gz`++Also publishes:++- `checksums.txt` (SHA256 for all tarballs)++## CI workflows++- `.github/workflows/agent-build.yml`+ - Runs on PR/push+ - Executes `go test ./...`+ - Cross-build matrix validation++- `.github/workflows/agent-release.yml`+ - Runs on `agent-v*` tag push+ - Cross-builds, archives, generates checksums+ - Publishes release assets to GitHub Releases++## Compatibility gate (recommended)++Collector validates incoming agent compatibility on heartbeat/report:++- `MIN_AGENT_PROTOCOL_VERSION` (default `1`)+- `MIN_AGENT_VERSION` (optional, e.g. `1.3.8`)++When incompatible, API returns `426` with machine-readable code:++- `AGENT_PROTOCOL_TOO_OLD`+- `AGENT_VERSION_REQUIRED`+- `AGENT_VERSION_TOO_OLD`++## Compatibility matrix template++| Agent Version | Min Server Version | Protocol |+| --- | --- | --- |+| `agent-v1.3.1` | `v1.3.1` | `1` |+| `agent-v1.3.8` | `v1.3.1` | `1` |++Numbers may skip when no agent release is needed.++## Naming conventions++- Binary inside tarball is always `neko-agent`+- Tarball name carries platform identity for user download and script detection+- Linux variants explicitly distinguish `amd64/arm64/armv7/mips/mipsle`diff --git a/docs/agent/release.md b/docs/agent/release.mdindex d0cac80..7b90160 100644--- a/docs/agent/release.md+++ b/docs/agent/release.md@@ -1,57 +1,59 @@-# Agent Release and Packaging+# Agent 发布与打包-## Tagging strategy+**中文 | [English](./release.en.md)**-- Agent release workflow triggers on tags: `agent-v*`-- Example: `agent-v0.2.0`+## 标签策略-## Generated assets+- Agent 发布工作流由 `agent-v*` 格式的标签触发+- 示例:`agent-v0.2.0`-For each target OS/arch, workflow publishes two tarballs:+## 生成的产物-- Versioned: `neko-agent_<tag>_<os>_<arch>.tar.gz`-- Latest alias: `neko-agent_<os>_<arch>.tar.gz`+每个目标 OS/架构均发布两个压缩包:-Also publishes:+- 带版本号:`neko-agent_<tag>_<os>_<arch>.tar.gz`+- latest 别名:`neko-agent_<os>_<arch>.tar.gz`-- `checksums.txt` (SHA256 for all tarballs)+同时发布:-## CI workflows+- `checksums.txt`(所有压缩包的 SHA256)++## CI 工作流- `.github/workflows/agent-build.yml`- - Runs on PR/push- - Executes `go test ./...`- - Cross-build matrix validation+ - 在 PR/push 时触发+ - 执行 `go test ./...`+ - 交叉编译矩阵验证- `.github/workflows/agent-release.yml`- - Runs on `agent-v*` tag push- - Cross-builds, archives, generates checksums- - Publishes release assets to GitHub Releases+ - 在推送 `agent-v*` 标签时触发+ - 交叉编译、打包、生成校验和+ - 将发布产物发布到 GitHub Releases-## Compatibility gate (recommended)+## 兼容性门控(推荐)-Collector validates incoming agent compatibility on heartbeat/report:+Collector 在心跳/上报时验证 Agent 兼容性:-- `MIN_AGENT_PROTOCOL_VERSION` (default `1`)-- `MIN_AGENT_VERSION` (optional, e.g. `1.3.8`)+- `MIN_AGENT_PROTOCOL_VERSION`(默认 `1`)+- `MIN_AGENT_VERSION`(可选,如 `1.3.8`)-When incompatible, API returns `426` with machine-readable code:+不兼容时,API 返回 `426` 并附带机器可读代码:- `AGENT_PROTOCOL_TOO_OLD`- `AGENT_VERSION_REQUIRED`- `AGENT_VERSION_TOO_OLD`-## Compatibility matrix template+## 兼容性矩阵模板-| Agent Version | Min Server Version | Protocol |+| Agent 版本 | 最低服务端版本 | 协议版本 || --- | --- | --- || `agent-v1.3.1` | `v1.3.1` | `1` || `agent-v1.3.8` | `v1.3.1` | `1` |-Numbers may skip when no agent release is needed.+版本号不连续时,表示该版本无需独立 Agent 发布。-## Naming conventions+## 命名规范-- Binary inside tarball is always `neko-agent`-- Tarball name carries platform identity for user download and script detection-- Linux variants explicitly distinguish `amd64/arm64/armv7/mips/mipsle`+- 压缩包内二进制文件始终命名为 `neko-agent`+- 压缩包名称包含平台信息,便于用户下载和脚本识别+- Linux 变体明确区分 `amd64/arm64/armv7/mips/mipsle`diff --git a/docs/agent/troubleshooting.en.md b/docs/agent/troubleshooting.en.mdnew file mode 100644index 0000000..de4a973--- /dev/null+++ b/docs/agent/troubleshooting.en.md@@ -0,0 +1,115 @@+# Agent Troubleshooting++[中文](./troubleshooting.md) | **English**++## `exec format error`++Cause: binary architecture mismatch.++Check:++```sh+file ./neko-agent+uname -m+```++Fix: use matching release package for current target.++## Agent always offline++Checklist:++- `--server-url` points to panel host (not remote machine localhost)+- backend token is current (not rotated/expired)+- backend is in Agent mode+- heartbeat endpoint reachable from agent host++## `Invalid agent token`++- token mismatch between agent process and backend config+- rotate token in UI and restart agent with new token++## `AGENT_TOKEN_ALREADY_BOUND`++Cause: same backend token used by another `agentId`.++Fix:++- do not share one backend token across multiple agent instances+- create separate backend per agent, or rotate token and rebind intentionally++## `426` compatibility errors++Possible codes:++- `AGENT_PROTOCOL_TOO_OLD`+- `AGENT_VERSION_REQUIRED`+- `AGENT_VERSION_TOO_OLD`++Fix:++- upgrade agent to a newer release package+- check collector env requirements:+ - `MIN_AGENT_PROTOCOL_VERSION`+ - `MIN_AGENT_VERSION`++## Surge decode errors++Recent agent parser supports mixed field formats (`id` number/string, numeric strings).+If still failing, collect error logs and open an issue with response sample.++## Agent won't start: PID file / already running++The agent binary uses a PID lock file to prevent running the same backend ID twice.+If a previous crash left a stale PID file, the new process exits immediately.++Check:++```bash+nekoagent status <instance>+```++If it says "stopped" but the agent won't start:++```bash+# locate and remove stale PID file+ls /var/run/neko-agent/+rm /var/run/neko-agent/<instance>.pid+nekoagent start <instance>+```++## `nekoagent stop` takes a long time++This is expected. When stopped, the agent waits up to 10 seconds to flush the final batch+of traffic data to the panel before exiting. The stop command waits up to 12 seconds before+sending SIGKILL.++If you need to force-kill immediately:++```bash+pid=$(cat /var/run/neko-agent/<instance>.pid)+kill -9 "$pid"+rm -f /var/run/neko-agent/<instance>.pid+```++Note: force-killing may lose the last ~30s of traffic data that has not yet been flushed.++## `nekoagent logs` shows no output++The log file is created after the first successful start. If the agent fails immediately on+start, check for errors with:++```bash+journalctl -u neko-agent-<instance> -n 50 # if using systemd+# or check the log file directly+cat /var/run/neko-agent/<instance>.log+```++## Agent reports but dashboard shows no data++Possible causes:++1. Gateway type mismatch — verify `--gateway-type` matches actual gateway (`clash` vs `surge`)+2. Gateway URL unreachable from agent host — test with `curl http://<gateway-url>/version`+3. First flush hasn't happened yet — wait 30 seconds (default flush interval)+4. Backend is in Direct mode, not Agent mode — check backend settings in UIdiff --git a/docs/agent/troubleshooting.md b/docs/agent/troubleshooting.mdindex 3bf6236..46d72bd 100644--- a/docs/agent/troubleshooting.md+++ b/docs/agent/troubleshooting.md@@ -1,57 +1,112 @@-# Agent Troubleshooting+# Agent 故障排查++**中文 | [English](./troubleshooting.en.md)**## `exec format error`-Cause: binary architecture mismatch.+原因:二进制架构与主机不匹配。-Check:+检查:```shfile ./neko-agentuname -m```-Fix: use matching release package for current target.+修复:使用与当前目标匹配的发布包。-## Agent always offline+## Agent 始终离线-Checklist:+检查清单:-- `--server-url` points to panel host (not remote machine localhost)-- backend token is current (not rotated/expired)-- backend is in Agent mode-- heartbeat endpoint reachable from agent host+- `--server-url` 指向面板主机地址(而非远程机器的 localhost)+- backend token 为最新(未轮换/过期)+- 后端已设置为 Agent 模式+- Agent 主机可访问面板的心跳端点## `Invalid agent token`-- token mismatch between agent process and backend config-- rotate token in UI and restart agent with new token+- Agent 进程与后端配置的 token 不匹配+- 在 UI 中轮换 token,并使用新 token 重启 Agent## `AGENT_TOKEN_ALREADY_BOUND`-Cause: same backend token used by another `agentId`.+原因:同一 backend token 被另一个 `agentId` 使用。-Fix:+修复:-- do not share one backend token across multiple agent instances-- create separate backend per agent, or rotate token and rebind intentionally+- 不要在多个 Agent 实例间共用同一 backend token+- 每个 Agent 对应独立后端,或故意轮换 token 后重新绑定-## `426` compatibility errors+## `426` 兼容性错误-Possible codes:+可能的错误码:- `AGENT_PROTOCOL_TOO_OLD`- `AGENT_VERSION_REQUIRED`- `AGENT_VERSION_TOO_OLD`-Fix:+修复:-- upgrade agent to a newer release package-- check collector env requirements:+- 升级 Agent 到更新的发布版本+- 检查 collector 环境变量要求:- `MIN_AGENT_PROTOCOL_VERSION`- `MIN_AGENT_VERSION`-## Surge decode errors+## Agent 无法启动:PID 文件 / 已在运行++Agent 二进制使用 PID 锁文件防止同一 backendId 运行两个进程。+若上次崩溃遗留了过期 PID 文件,新进程会立即退出。++检查:++```bash+nekoagent status <instance>+```++若显示"已停止"但仍无法启动:++```bash+# 找到并删除过期 PID 文件+ls /var/run/neko-agent/+rm /var/run/neko-agent/<instance>.pid+nekoagent start <instance>+```++## `nekoagent stop` 耗时较长++这是预期行为。停止时,Agent 会等待最多 10 秒以将最后一批流量数据 flush 至面板后再退出。stop 命令最多等待 12 秒,之后才发送 SIGKILL。++如需立即强制终止:++```bash+pid=$(cat /var/run/neko-agent/<instance>.pid)+kill -9 "$pid"+rm -f /var/run/neko-agent/<instance>.pid+```++注意:强制终止可能丢失最后约 30 秒尚未 flush 的流量数据。++## `nekoagent logs` 无输出++日志文件在首次成功启动后才会创建。若 Agent 启动即失败,可通过以下方式排查:++```bash+journalctl -u neko-agent-<instance> -n 50 # 使用 systemd 时+# 或直接查看日志文件+cat /var/run/neko-agent/<instance>.log+```++## Agent 有上报但面板无数据++可能原因:++1. 网关类型不匹配——确认 `--gateway-type` 与实际网关一致(`clash` vs `surge`)+2. Agent 主机无法访问网关 URL——测试:`curl http://<gateway-url>/version`+3. 首次 flush 尚未发生——等待 30 秒(默认 flush 间隔)+4. 后端处于直连模式而非 Agent 模式——检查 UI 中的后端设置++## Surge 解析错误-Recent agent parser supports mixed field formats (`id` number/string, numeric strings).-If still failing, collect error logs and open an issue with response sample.+最新 Agent 解析器支持混合字段格式(`id` 字段为数字或字符串、数字字符串)。+若仍然报错,请收集错误日志并附响应样本提交 Issue。diff --git a/docs/architecture.en.md b/docs/architecture.en.mdindex 12d39ea..654cb24 100644--- a/docs/architecture.en.md+++ b/docs/architecture.en.md@@ -233,6 +233,98 @@---+## Agent Mode Architecture++Agent mode allows a centralized Neko Master panel to receive data from remote LAN gateways+without requiring direct collector-to-gateway network access.++### Components++| Component | Description |+|---|---|+| `neko-agent` | Data collection daemon — runs near the gateway, pulls data and reports to panel |+| `nekoagent` | CLI manager (shell script) — manages `neko-agent` instance lifecycle |++### Architecture Diagram++```+┌─────────────────────────────────────────────────────────────────┐+│ Central Panel (Neko Master) │+│ │+│ Fastify API Server │+│ ├─ POST /api/agent/report ← receive batch traffic deltas │+│ ├─ POST /api/agent/heartbeat ← receive heartbeat (online) │+│ ├─ POST /api/agent/config-sync ← receive rules/proxies config │+│ └─ POST /api/agent/policy-state ← receive current policy state │+│ │+│ Backend type: agent://, system-generated token, bound to agentId│+└─────────────────────────────────────────────────────────────────┘+ ↑+ HTTP (token auth)+ │+┌─────────────────────────────────────────────────────────────────┐+│ Remote Host (near gateway) │+│ │+│ nekoagent (CLI manager) │+│ ├─ /etc/neko-agent/<instance>.env (config file) │+│ └─ /var/run/neko-agent/<instance>.pid (PID file) │+│ │+│ neko-agent (daemon) │+│ │ │+│ ├── 1. Pull gateway data │+│ │ ├─ Clash/Mihomo: WebSocket /connections (real-time push) │+│ │ └─ Surge: HTTP GET /v1/requests/recent (2s poll) │+│ │ │+│ ├── 2. Delta calculation │+│ │ - Identify new/updated connections │+│ │ - Compute upload/download deltas │+│ │ - Aggregate by domain + proxy + rule │+│ │ │+│ ├── 3. Batch report (every 2s) │+│ │ POST /api/agent/report │+│ │ - Up to 1000 entries/batch, queue cap 50000 │+│ │ │+│ ├── 4. Heartbeat (every 30s) │+│ │ POST /api/agent/heartbeat │+│ │ │+│ ├── 5. Config sync (every 2min, MD5 dedup) │+│ │ POST /api/agent/config-sync │+│ │ - rules / proxies / providers │+│ │ │+│ └── 6. Policy state sync (every 30s, only on state change) │+│ POST /api/agent/policy-state │+│ │+│ PID lock: only one process per backendId at a time │+└─────────────────────────────────────────────────────────────────┘+ │+ Local Network (LAN)+ │+ ┌─────────────────────────────┐+ │ Clash/Mihomo or Surge │+ │ Gateway API │+ └─────────────────────────────┘+```++### Direct vs Agent Mode++| Dimension | Direct | Agent |+|---|---|---|+| Does collector connect to gateway? | ✅ Yes | ❌ No |+| Data latency | Milliseconds (WS) | ~2s report interval |+| Network isolation | Requires collector → gateway access | Agent initiates; no inbound needed |+| Multi-site | Complex (VPN / tunnels) | Natively supported |+| Security boundary | Shared gateway API token | Panel token isolated from gateway token |++### Security Model++- Panel generates a unique token per Agent backend+- `agentId` is derived from the backend token: `"agent-" + sha256(token)[:16]` — stable across restarts, no manual configuration needed+- A token is bound to one `agentId`; registering with the same token under a different `agentId` is rejected by the server+- Token rotation immediately invalidates old agent processes (must reconfigure with new token before restarting)+- Config sync and policy sync use MD5 dedup to skip unchanged POSTs++---+## Data Flow### 1. Clash Data Collection Flow@@ -656,7 +748,21 @@ neko-master/│├── docs/│ ├── architecture.md # This doc (Chinese)-│ └── architecture.en.md # This doc (English)+│ ├── architecture.en.md # This doc (English)+│ └── agent/ # Agent mode documentation+│ ├── overview.md # Architecture and mode comparison+│ ├── quick-start.md # End-to-end quick start+│ ├── install.md # Install guide (systemd / launchd / OpenWrt)+│ ├── config.md # Configuration reference+│ ├── release.md # Release and compatibility policy+│ └── troubleshooting.md # Common errors and fixes+│+├── apps/+│ └── agent/ # Agent daemon (Go)+│ ├── internal/agent/ # Core logic+│ │ └── runner.go # Collection loop, report, heartbeat, config sync+│ ├── install.sh # Agent one-click install script+│ └── nekoagent # CLI manager (shell script)│└── docker-compose.yml```diff --git a/docs/architecture.md b/docs/architecture.mdindex 24e31b3..6536221 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -234,6 +234,97 @@---+## Agent 模式架构++Agent 模式允许一个中心化的 Neko Master 面板接收来自远程 LAN 网关的数据,无需 collector 直连网关。++### 组件说明++| 组件 | 说明 |+|---|---|+| `neko-agent` | 数据采集守护进程,运行于网关旁边,周期性拉取并上报到面板 |+| `nekoagent` | CLI 管理器(Shell 脚本),管理 `neko-agent` 实例的生命周期 |++### 架构图++```+┌─────────────────────────────────────────────────────────────────┐+│ 中心面板 (Neko Master) │+│ │+│ Fastify API Server │+│ ├─ POST /api/agent/report ← 接收批量流量增量 │+│ ├─ POST /api/agent/heartbeat ← 接收心跳(在线状态更新) │+│ ├─ POST /api/agent/config-sync ← 接收规则/代理/Provider 配置 │+│ └─ POST /api/agent/policy-state ← 接收当前策略状态 │+│ │+│ Backend 类型:agent://,系统生成 token,绑定 agentId │+└─────────────────────────────────────────────────────────────────┘+ ↑+ HTTP (token 鉴权)+ │+┌─────────────────────────────────────────────────────────────────┐+│ 网关旁边的主机 (Remote Host) │+│ │+│ nekoagent(CLI 管理器) │+│ ├─ /etc/neko-agent/<instance>.env (配置文件) │+│ └─ /var/run/neko-agent/<instance>.pid (PID 文件) │+│ │+│ neko-agent(守护进程) │+│ │ │+│ ├── 1. 拉取网关数据 │+│ │ ├─ Clash/Mihomo: WebSocket /connections (实时推送) │+│ │ └─ Surge: HTTP GET /v1/requests/recent (2s 轮询) │+│ │ │+│ ├── 2. 增量计算 (Delta) │+│ │ - 识别新连接 / 更新连接 │+│ │ - 计算 upload/download 增量 │+│ │ - 聚合 domain + proxy + rule │+│ │ │+│ ├── 3. 批量上报 (每 2s) │+│ │ POST /api/agent/report │+│ │ - 最多 1000 条/批,积压上限 50000 条 │+│ │ │+│ ├── 4. 心跳 (每 30s) │+│ │ POST /api/agent/heartbeat │+│ │ │+│ ├── 5. 配置同步 (每 2min,MD5 去重) │+│ │ POST /api/agent/config-sync │+│ │ - rules / proxies / providers │+│ │ │+│ └── 6. 策略状态同步 (每 30s,状态变化才上报) │+│ POST /api/agent/policy-state │+│ │+│ PID 锁:同一 backendId 同时只允许一个进程运行 │+└─────────────────────────────────────────────────────────────────┘+ │+ 本地网络 (LAN)+ │+ ┌─────────────────────────────┐+ │ Clash/Mihomo or Surge │+ │ Gateway API │+ └─────────────────────────────┘+```++### 直连模式 vs Agent 模式++| 维度 | 直连(Direct) | Agent |+|---|---|---|+| collector 是否需连接网关 | ✅ 是 | ❌ 否 |+| 数据实时性 | 毫秒级 (WS) | 约 2s 上报周期 |+| 网络隔离 | 需要 collector → 网关可达 | agent 发起连接,无需入站 |+| 多站点场景 | 复杂(需 VPN/内网穿透) | 原生支持,每站点独立 agent |+| 安全边界 | 需要共享网关 API token | 面板 token 与网关 token 隔离 |++### 安全模型++- 面板为每个 Agent backend 生成唯一 token+- `agentId` 由 backend token 派生:`"agent-" + sha256(token)[:16]`,重启后保持稳定,无需手动指定+- Token 与 `agentId` 绑定,同一 token 不能以不同 `agentId` 注册(跨实例复用被服务端拒绝)+- Token 轮换后旧进程的请求立即被拒绝(需重新配置新 token 再启动)+- 配置同步与策略同步均有 MD5 去重,减少无效 POST++---+## 数据流详解### 1. Clash 数据采集流程@@ -654,7 +745,22 @@ neko-master/│ └── shared/ # 共享类型定义│├── docs/-│ └── architecture.md # 本文档+│ ├── architecture.md # 本文档(中文)+│ ├── architecture.en.md # 架构文档(英文)+│ └── agent/ # Agent 模式文档+│ ├── overview.md # 架构说明与模式对比+│ ├── quick-start.md # 快速开始+│ ├── install.md # 安装指南(含 systemd/launchd)+│ ├── config.md # 参数配置参考+│ ├── release.md # 发布与兼容策略+│ └── troubleshooting.md # 常见问题+│+├── apps/+│ └── agent/ # Agent 守护进程(Go)+│ ├── internal/agent/ # 核心逻辑+│ │ └── runner.go # 采集循环、上报、心跳、配置同步+│ ├── install.sh # Agent 一键安装脚本+│ └── nekoagent # CLI 管理器(Shell 脚本)│└── docker-compose.yml```diff --git a/docs/clickhouse-dataflow-analysis-report.md b/docs/dev/clickhouse-dataflow-analysis-report.mdsimilarity index 100%rename from docs/clickhouse-dataflow-analysis-report.mdrename to docs/dev/clickhouse-dataflow-analysis-report.mddiff --git a/docs/clickhouse-dataflow-analysis.md b/docs/dev/clickhouse-dataflow-analysis.mdsimilarity index 100%rename from docs/clickhouse-dataflow-analysis.mdrename to docs/dev/clickhouse-dataflow-analysis.mddiff --git a/docs/clickhouse-migration-io-analysis.md b/docs/dev/clickhouse-migration-io-analysis.mdsimilarity index 100%rename from docs/clickhouse-migration-io-analysis.mdrename to docs/dev/clickhouse-migration-io-analysis.mddiff --git a/docs/clickhouse-refactor-plan.md b/docs/dev/clickhouse-refactor-plan.mdsimilarity index 100%rename from docs/clickhouse-refactor-plan.mdrename to docs/dev/clickhouse-refactor-plan.mddiff --git a/docs/clickhouse-review-report.md b/docs/dev/clickhouse-review-report.mdsimilarity index 100%rename from docs/clickhouse-review-report.mdrename to docs/dev/clickhouse-review-report.mddiff --git a/docs/review-refactor-clickhouse-branch.md b/docs/dev/review-refactor-clickhouse-branch.mdsimilarity index 100%rename from docs/review-refactor-clickhouse-branch.mdrename to docs/dev/review-refactor-clickhouse-branch.mddiff --git a/docs/plans/2026-02-22-fix-clickhouse-agent-issues.md b/docs/plans/2026-02-22-fix-clickhouse-agent-issues.mddeleted file mode 100644index df9572b..0000000--- a/docs/plans/2026-02-22-fix-clickhouse-agent-issues.md+++ /dev/null@@ -1,510 +0,0 @@-# ClickHouse + Agent 问题修复实施计划--> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.--**Goal:** 修复 refactor/clickhouse 分支 review 中识别的 P0/P1/P2 级别问题,提升系统在 ClickHouse 故障场景下的健壮性。--**Architecture:** 最小化改动原则——每个修复只改动其直接相关代码,不做额外重构。修复后运行现有测试确认无回归。--**Tech Stack:** TypeScript (Node.js, vitest), Go (1.21+), POSIX sh-------## Task 1:ClickHouseWriter 增加运行时健康追踪(P0-1)--**Files:**-- Modify: `apps/collector/src/modules/clickhouse/clickhouse.writer.ts`-- Modify: `apps/collector/src/modules/collector/batch-buffer.ts`-- Modify: `apps/collector/src/modules/stats/stats-write-mode.ts`-- Modify: `apps/collector/src/modules/stats/stats-write-mode.test.ts`--**背景:** `isEnabled()` 是静态配置判断,CH 宕机时仍返回 true,导致 SQLite 写入被错误跳过而 CH 写入失败,数据双丢失。--**Step 1:在 `ClickHouseWriter` 中增加健康追踪字段和方法**--在 `clickhouse.writer.ts` 中,于 `pendingBatches = 0;` 下方增加:--```typescript-private consecutiveFailures = 0;-private readonly maxConsecutiveFailures = Math.max(- 1,- Number.parseInt(process.env.CH_UNHEALTHY_THRESHOLD || '5', 10) || 5,-);-```--在 `isEnabled()` 方法后增加:--```typescript-isHealthy(): boolean {- return this.writeEnabled && this.consecutiveFailures < this.maxConsecutiveFailures;-}-```--在 `insertRows` 的 catch 块中(`this.metrics.failures += 1;` 之后)增加:--```typescript-this.consecutiveFailures += 1;-if (this.consecutiveFailures === this.maxConsecutiveFailures) {- console.warn(- `[ClickHouse Writer] Marked unhealthy after ${this.maxConsecutiveFailures} consecutive failures. SQLite writes will resume as fallback.`,- );-}-```--在 `insertRows` 成功路径(`this.metrics.trafficBatches += 1;` 之前)增加:--```typescript-if (this.consecutiveFailures > 0) {- console.info('[ClickHouse Writer] Recovered from failure, marking healthy again.');- this.consecutiveFailures = 0;-}-```--**Step 2:更新 `shouldSkipSqliteStatsWrites` 的参数语义**--`apps/collector/src/modules/stats/stats-write-mode.ts`:-- 将参数名 `clickHouseWriterEnabled` 改为 `clickHouseWriterHealthy`(语义更准确,实际行为不变)--**Step 3:更新 `batch-buffer.ts` 调用点**--`apps/collector/src/modules/collector/batch-buffer.ts`:--```typescript-// 旧:-const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(- clickHouseWriter.isEnabled(),-);-// 改为:-const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(- clickHouseWriter.isHealthy(),-);-```--```typescript-// 旧(第 139 行):-const reduceSQLiteWrites = clickHouseWriter.isEnabled() && process.env.CH_DISABLE_SQLITE_REDUCTION !== '1';-// 改为:-const reduceSQLiteWrites = clickHouseWriter.isHealthy() && process.env.CH_DISABLE_SQLITE_REDUCTION !== '1';-```--(第 143、179 行的 `clickHouseWriter.isEnabled()` 用于判断是否发起 CH 写入,保持不变——我们仍尝试写入,失败会计入 consecutiveFailures。)--**Step 4:更新测试**--`apps/collector/src/modules/stats/stats-write-mode.test.ts` 中测试描述和变量名更新为使用 `healthy` 语义,测试用例本身 `true/false` 逻辑不变:--```typescript-it('should keep sqlite writes when CH_ONLY_MODE is disabled', async () => {- const mode = await import('./stats-write-mode.js');- expect(mode.shouldSkipSqliteStatsWrites(true)).toBe(false); // healthy=true but mode off- expect(mode.shouldSkipSqliteStatsWrites(false)).toBe(false); // healthy=false and mode off-});-it('should keep sqlite writes and warn when writer is unhealthy', async () => {- process.env.CH_ONLY_MODE = '1';- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- const mode = await import('./stats-write-mode.js');- expect(mode.shouldSkipSqliteStatsWrites(false)).toBe(false); // healthy=false → keep sqlite- expect(warn).toHaveBeenCalledTimes(1);-});-it('should skip sqlite writes when writer is healthy', async () => {- process.env.CH_ONLY_MODE = '1';- const info = vi.spyOn(console, 'info').mockImplementation(() => {});- const mode = await import('./stats-write-mode.js');- expect(mode.shouldSkipSqliteStatsWrites(true)).toBe(true); // healthy=true → skip sqlite- expect(info).toHaveBeenCalledTimes(1);-});-```--**Step 5:运行测试**--```bash-pnpm --filter collector test -- --reporter=verbose-```--Expected: 所有 stats-write-mode 测试通过--**Step 6:TypeScript 检查**--```bash-pnpm --filter collector exec tsc --noEmit-```--Expected: 无错误--**Step 7:提交**--```bash-git add apps/collector/src/modules/clickhouse/clickhouse.writer.ts \- apps/collector/src/modules/collector/batch-buffer.ts \- apps/collector/src/modules/stats/stats-write-mode.ts \- apps/collector/src/modules/stats/stats-write-mode.test.ts-git commit -m "fix(clickhouse): track runtime health in writer to prevent data loss when CH is down"-```-------## Task 2:nekoagent stop 等待时间修复(P0-2)--**Files:**-- Modify: `apps/agent/nekoagent`--**背景:** agent 的优雅停机需要 10 秒,但 `nekoagent stop` 只等 1 秒就 SIGKILL,丢失最后一批数据。--**Step 1:定位并修改等待时间**--在 `apps/agent/nekoagent` 中找到 `cmd_stop()` 函数(约第 317-333 行):--```sh-# 旧:-kill "$pid" >/dev/null 2>&1 || true-sleep 1-if kill -0 "$pid" >/dev/null 2>&1; then- kill -9 "$pid" >/dev/null 2>&1 || true-fi--# 改为:-kill "$pid" >/dev/null 2>&1 || true-# Wait up to 12s for graceful shutdown (agent needs up to 10s for final flush)-i=0-while [ $i -lt 12 ] && kill -0 "$pid" >/dev/null 2>&1; do- sleep 1- i=$((i + 1))-done-if kill -0 "$pid" >/dev/null 2>&1; then- kill -9 "$pid" >/dev/null 2>&1 || true-fi-```--**Step 2:手动验证(可选)**--```bash-# 启动一个测试实例后立即停止,确认 stop 等待行为-nekoagent status <instance_name>-time nekoagent stop <instance_name>-# Expected: 进程在 12 秒内自然退出,耗时 < 12 秒-```--**Step 3:提交**--```bash-git add apps/agent/nekoagent-git commit -m "fix(agent): extend stop grace period to 12s to allow final flush"-```-------## Task 3:ClickHouseReader 改用 POST body 传 SQL(P1-1)--**Files:**-- Modify: `apps/collector/src/modules/clickhouse/clickhouse.reader.ts`--**背景:** 将 SQL 放 URL query 参数,长查询可能超过 URL 长度限制(8-16KB)。--**Step 1:修改 `query()` 方法**--找到 `clickhouse.reader.ts` 末尾的 `private async query<T>` 方法(约第 1193 行),修改 fetch 调用:--```typescript-// 旧:-const response = await fetch(- `${baseUrl}/?database=${encodeURIComponent(this.config.database)}&query=${encodeURIComponent(`${query}\nFORMAT JSON`)}`,- {- method: 'POST',- headers: {- ...(authHeader ? { Authorization: authHeader } : {}),- },- signal: AbortSignal.timeout(this.config.timeoutMs),- },-);--// 改为:-const response = await fetch(- `${baseUrl}/?database=${encodeURIComponent(this.config.database)}`,- {- method: 'POST',- headers: {- 'Content-Type': 'text/plain; charset=utf-8',- ...(authHeader ? { Authorization: authHeader } : {}),- },- body: `${query}\nFORMAT JSON`,- signal: AbortSignal.timeout(this.config.timeoutMs),- },-);-```--**Step 2:TypeScript 检查**--```bash-pnpm --filter collector exec tsc --noEmit-```--**Step 3:提交**--```bash-git add apps/collector/src/modules/clickhouse/clickhouse.reader.ts-git commit -m "fix(clickhouse): send reader SQL via POST body instead of URL query param"-```-------## Task 4:`toDateTime` 无效日期保护(P1-2)--**Files:**-- Modify: `apps/collector/src/modules/clickhouse/clickhouse.reader.ts`--**背景:** 无效日期时返回 epoch(1970-01-01),导致全表扫描。--**Step 1:修改 `toDateTime` 返回 null 并更新调用点**--将 `toDateTime` 方法修改为返回 `string | null`:--```typescript-private toDateTime(value: string): string | null {- const date = new Date(value);- if (Number.isNaN(date.getTime())) {- return null;- }- return date.toISOString().slice(0, 19).replace('T', ' ');-}-```--在所有使用 `this.toDateTime(start)` / `this.toDateTime(end)` 的查询方法顶部增加守卫:--```typescript-// 在每个使用 toDateTime 的 async 方法开头-const startDT = this.toDateTime(start);-const endDT = this.toDateTime(end);-if (!startDT || !endDT) return null;-// 然后在 SQL 中使用 startDT / endDT 代替内联调用-```--注意:`toDateTime` 在模板字符串中被内联调用(如 `toDateTime('${this.toDateTime(start)}')`),需要将这些改为先赋值再使用,避免出现 `'null'` 字符串进入 SQL。--**Step 2:TypeScript 检查**--```bash-pnpm --filter collector exec tsc --noEmit-```--**Step 3:提交**--```bash-git add apps/collector/src/modules/clickhouse/clickhouse.reader.ts-git commit -m "fix(clickhouse): guard against invalid dates in reader to prevent full table scans"-```-------## Task 5:恢复路由指标日志输出(P1-3)--**Files:**-- Modify: `apps/collector/src/modules/stats/stats.service.ts`--**背景:** 路由统计数据被收集但 console.info 被注释掉,形成无意义的计算和运维盲点。--**Step 1:找到 `maybeLogRouteMetrics` 中被注释的日志行**--位置约 `stats.service.ts:137`:--```typescript-// 旧(被注释):-// Stats route metrics logging removed--// 改为:-console.info(- `[StatsService] Route metrics: ${parts} window_sec=${(elapsedMs / 1000).toFixed(1)}`,-);-```--完整的修复区域是在 `if (entries.length > 0)` 块内,变量 `parts` 已经在上方正确构建,只需恢复 `console.info` 调用。--**Step 2:TypeScript 检查**--```bash-pnpm --filter collector exec tsc --noEmit-```--**Step 3:提交**--```bash-git add apps/collector/src/modules/stats/stats.service.ts-git commit -m "fix(stats): restore route metrics logging for observability"-```-------## Task 6:`syncPolicyState` 增加 MD5 去重(P1-4)--**Files:**-- Modify: `apps/agent/internal/agent/runner.go`--**背景:** 每 30 秒无条件 POST 策略状态,即使没有变化。--**Step 1:在 `Runner` struct 中增加 `lastPolicyHash` 字段**--```go-// 在 lastConfigHash string 下方增加:-lastPolicyHash string-```--**Step 2:修改 `syncPolicyState` 方法增加去重逻辑**--```go-func (r *Runner) syncPolicyState(ctx context.Context) error {- snap, err := r.gatewayClient.GetPolicyStateSnapshot(ctx)- if err != nil {- return err- }-- // Skip POST if policy state unchanged- data, _ := json.Marshal(snap)- hash := fmt.Sprintf("%x", md5.Sum(data))-- r.mu.Lock()- unchanged := hash == r.lastPolicyHash- r.mu.Unlock()-- if unchanged {- return nil- }-- snap.Timestamp = time.Now().UnixMilli()-- payload := policyStatePayload{- BackendID: r.cfg.BackendID,- AgentID: r.cfg.AgentID,- PolicyState: snap,- }-- if err := r.postJSON(ctx, "/agent/policy-state", payload); err != nil {- return err- }-- r.mu.Lock()- r.lastPolicyHash = hash- r.mu.Unlock()- return nil-}-```--**Step 3:编译验证**--```bash-cd apps/agent && go build ./...-```--Expected: 无错误--**Step 4:提交**--```bash-git add apps/agent/internal/agent/runner.go-git commit -m "fix(agent): skip policy state sync POST when state is unchanged"-```-------## Task 7:`install.sh` 参数拼接安全修复(P2-1)--**Files:**-- Modify: `apps/agent/install.sh`--**背景:** 第 332-333 行使用 `$()` 展开加参数,依赖 word splitting,存在空格安全隐患。--**Step 1:找到末尾的 `nekoagent add` 调用(约第 326-334 行)**--```sh-# 旧:-"$cli_target" add "$NEKO_INSTANCE_NAME" \- --server-url "$NEKO_SERVER" \- --backend-id "$NEKO_BACKEND_ID" \- --backend-token "$NEKO_BACKEND_TOKEN" \- --gateway-type "$NEKO_GATEWAY_TYPE" \- --gateway-url "$NEKO_GATEWAY_URL" \- $(if [ -n "$NEKO_GATEWAY_TOKEN" ]; then echo "--gateway-token $NEKO_GATEWAY_TOKEN"; fi) \- $(if [ "$NEKO_AUTO_START" = "true" ]; then echo "--auto-start"; fi)--# 改为:-set -- \- "$cli_target" add "$NEKO_INSTANCE_NAME" \- --server-url "$NEKO_SERVER" \- --backend-id "$NEKO_BACKEND_ID" \- --backend-token "$NEKO_BACKEND_TOKEN" \- --gateway-type "$NEKO_GATEWAY_TYPE" \- --gateway-url "$NEKO_GATEWAY_URL"--if [ -n "$NEKO_GATEWAY_TOKEN" ]; then- set -- "$@" --gateway-token "$NEKO_GATEWAY_TOKEN"-fi-if [ "$NEKO_AUTO_START" = "true" ]; then- set -- "$@" --auto-start-fi--"$@"-```--**Step 2:同文件修复 `detect_existing_install` 重复调用(P2-2)**--```sh-# 旧(约第 195-198 行):-existing_agent=""-if detect_existing_install; then- existing_agent="$(detect_existing_install)"-fi--# 改为:-existing_agent=""-if existing_agent="$(detect_existing_install 2>/dev/null)"; then- : # existing_agent 已赋值-fi-```--注意:`detect_existing_install` 成功时 echo 路径到 stdout 并 return 0;失败时 return 1。上述写法同时捕获输出和返回值。--**Step 3:手动验证语法**--```bash-sh -n apps/agent/install.sh-```--Expected: 无语法错误输出--**Step 4:提交**--```bash-git add apps/agent/install.sh-git commit -m "fix(agent): use set -- pattern for safe argument passing in install.sh"-```-------## 最终验证--```bash-# TypeScript 完整检查-pnpm --filter collector exec tsc --noEmit--# 运行所有测试-pnpm --filter collector test--# Go 编译-cd apps/agent && go build ./...--# Shell 语法检查-sh -n apps/agent/install.sh-sh -n apps/agent/nekoagent-```-------## 变更范围总结--| Task | 文件数 | 重要性 |-|---|---|---|-| Task 1: CH 运行时健康追踪 | 4 | P0 |-| Task 2: nekoagent stop 等待 | 1 | P0 |-| Task 3: Reader POST body | 1 | P1 |-| Task 4: toDateTime 保护 | 1 | P1 |-| Task 5: 路由指标日志 | 1 | P1 |-| Task 6: syncPolicyState 去重 | 1 | P1 |-| Task 7: install.sh 参数安全 | 1 | P2 |diff --git a/docs/research-GPT5.3.en.md b/docs/research/GPT5.3.en.mdsimilarity index 100%rename from docs/research-GPT5.3.en.mdrename to docs/research/GPT5.3.en.mddiff --git a/docs/research-GPT5.3.zh.md b/docs/research/GPT5.3.zh.mdsimilarity index 100%rename from docs/research-GPT5.3.zh.mdrename to docs/research/GPT5.3.zh.mddiff --git a/docs/research-glm5.en.md b/docs/research/glm5.en.mdsimilarity index 100%rename from docs/research-glm5.en.mdrename to docs/research/glm5.en.mddiff --git a/docs/research-glm5.zh.md b/docs/research/glm5.zh.mdsimilarity index 100%rename from docs/research-glm5.zh.mdrename to docs/research/glm5.zh.mddiff --git a/docs/research-kimi2.5.en.md b/docs/research/kimi2.5.en.mdsimilarity index 100%rename from docs/research-kimi2.5.en.mdrename to docs/research/kimi2.5.en.mddiff --git a/docs/research-kimi2.5.zh.md b/docs/research/kimi2.5.zh.mdsimilarity index 100%rename from docs/research-kimi2.5.zh.mdrename to docs/research/kimi2.5.zh.md