A modern and elegant dashboard for network traffic visualization and analysis.
feat: Introduce a new Go-based agent application with dedicated documentation and integrate its support across the collector, web, and build systems.
luolei1d52e319a9ed
diff --git a/.github/workflows/agent-build.yml b/.github/workflows/agent-build.ymlnew file mode 100644index 0000000..156dece--- /dev/null+++ b/.github/workflows/agent-build.yml@@ -0,0 +1,81 @@+name: Agent Build++on:+ pull_request:+ paths:+ - "apps/agent/**"+ - ".github/workflows/agent-build.yml"+ - ".github/workflows/agent-release.yml"+ push:+ branches:+ - main+ paths:+ - "apps/agent/**"+ - ".github/workflows/agent-build.yml"++jobs:+ test:+ name: Test Agent+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: apps/agent+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: apps/agent/go.mod++ - name: Run tests+ run: go test ./...++ cross-build:+ name: Build ${{ matrix.os }}-${{ matrix.arch }}+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: apps/agent+ strategy:+ fail-fast: false+ matrix:+ include:+ - os: linux+ arch: amd64+ - os: linux+ arch: arm64+ - os: linux+ arch: armv7+ goarch: arm+ goarm: "7"+ - os: linux+ arch: mips+ gomips: softfloat+ - os: linux+ arch: mipsle+ gomips: softfloat+ - os: darwin+ arch: amd64+ - os: darwin+ arch: arm64+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: apps/agent/go.mod++ - name: Build binary+ env:+ CGO_ENABLED: "0"+ GOOS: ${{ matrix.os }}+ GOARCH: ${{ matrix.goarch || matrix.arch }}+ GOARM: ${{ matrix.goarm || '' }}+ GOMIPS: ${{ matrix.gomips || '' }}+ run: |+ mkdir -p dist+ go build -trimpath -ldflags "-s -w" -o "dist/neko-agent-${{ matrix.os }}-${{ matrix.arch }}" .diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.ymlnew file mode 100644index 0000000..cb8750b--- /dev/null+++ b/.github/workflows/agent-release.yml@@ -0,0 +1,140 @@+name: Agent Release++on:+ push:+ tags:+ - "agent-v*"++permissions:+ contents: write++jobs:+ test:+ name: Test Agent+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: apps/agent+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: apps/agent/go.mod++ - name: Run tests+ run: go test ./...++ build:+ name: Package ${{ matrix.os }}-${{ matrix.arch }}+ runs-on: ubuntu-latest+ needs: test+ defaults:+ run:+ working-directory: apps/agent+ strategy:+ fail-fast: false+ matrix:+ include:+ - os: linux+ arch: amd64+ - os: linux+ arch: arm64+ - os: linux+ arch: armv7+ goarch: arm+ goarm: "7"+ - os: linux+ arch: mips+ gomips: softfloat+ - os: linux+ arch: mipsle+ gomips: softfloat+ - os: darwin+ arch: amd64+ - os: darwin+ arch: arm64+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: apps/agent/go.mod++ - name: Build archive+ env:+ CGO_ENABLED: "0"+ GOOS: ${{ matrix.os }}+ GOARCH: ${{ matrix.goarch || matrix.arch }}+ GOARM: ${{ matrix.goarm || '' }}+ GOMIPS: ${{ matrix.gomips || '' }}+ VERSION: ${{ github.ref_name }}+ run: |+ set -eu+ mkdir -p dist/release+ workdir="dist/pkg"+ rm -rf "$workdir"+ mkdir -p "$workdir"++ go build -trimpath -ldflags "-s -w" -o "$workdir/neko-agent" .+ chmod +x "$workdir/neko-agent"++ versioned_archive="neko-agent_${VERSION}_${{ matrix.os }}_${{ matrix.arch }}.tar.gz"+ latest_archive="neko-agent_${{ matrix.os }}_${{ matrix.arch }}.tar.gz"+ tar -C "$workdir" -czf "dist/release/$versioned_archive" neko-agent+ cp "dist/release/$versioned_archive" "dist/release/$latest_archive"++ - name: Upload package artifact+ uses: actions/upload-artifact@v4+ with:+ name: agent-release-${{ matrix.os }}-${{ matrix.arch }}+ path: apps/agent/dist/release/*.tar.gz++ checksums:+ name: Generate checksums+ runs-on: ubuntu-latest+ needs: build+ steps:+ - name: Download release artifacts+ uses: actions/download-artifact@v4+ with:+ path: dist/release+ pattern: agent-release-*+ merge-multiple: true++ - name: Create checksums file+ run: |+ set -eu+ cd dist/release+ sha256sum *.tar.gz > checksums.txt++ - name: Upload checksums+ uses: actions/upload-artifact@v4+ with:+ name: agent-release-checksums+ path: dist/release/checksums.txt++ publish:+ name: Publish GitHub Release+ runs-on: ubuntu-latest+ needs:+ - checksums+ steps:+ - name: Download release artifacts+ uses: actions/download-artifact@v4+ with:+ path: dist/release+ pattern: agent-release-*+ merge-multiple: true++ - name: Publish release assets+ uses: softprops/action-gh-release@v2+ with:+ generate_release_notes: true+ files: |+ dist/release/*.tar.gz+ dist/release/checksums.txtdiff --git a/README.en.md b/README.en.mdindex d5298f5..3023445 100644--- a/README.en.md+++ b/README.en.md@@ -67,6 +67,7 @@ It is a lightweight analytics dashboard designed for modern gateway environments- [โจ Features](#-features)- [๐ Quick Start](#-quick-start)+- [๐ค Agent Deployment](#-agent-deployment)- [๐ First Use](#-first-use)- [๐ง Port Conflict Resolution](#-port-conflict-resolution)- [๐ณ Docker Configuration](#-docker-configuration)@@ -238,6 +239,17 @@ Open <http://localhost:3000> to configure.> If you changed `API_PORT` (not 3001), set `API_URL` accordingly (for example `API_URL=http://localhost:4001`) so web `/api` rewrite targets the correct API.> `apps/collector/.env.local` takes precedence over `apps/collector/.env`.+## ๐ค Agent Deployment++Use Agent mode when you want one centralized Neko Master service and multiple remote devices collecting local gateway data.++- 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`+## ๐ First Use@@ -415,6 +427,8 @@ Additional recommendations:`GeoLite2-City.mmdb`, `GeoLite2-ASN.mmdb` (required), and `GeoLite2-Country.mmdb` (optional).Recommended source: <https://github.com/P3TERX/GeoLite.mmdb>.+> Advanced Agent details (install, config, release, compatibility) are maintained under `docs/agent/*`.+## ๐ Reverse Proxy & TunnelRecommended approach: keep Web and WS under the same domain, with path routing:diff --git a/README.md b/README.mdindex c73100b..e6ad819 100644--- a/README.md+++ b/README.md@@ -72,16 +72,17 @@ Neko Master ไธๆณจไบๅฏน็ฝ็ปๆต้่ฟ่ก่ฝป้ใ็ฒพ็กฎ็ๅๆไธๅฏ่งๅ## ๐ ็ฎๅฝ- [๐ ๅฟซ้ๅผๅง](#-ๅฟซ้ๅผๅง)+- [๐ค Agent ้จ็ฝฒ](#-agent-้จ็ฝฒ)- [๐ ้ฆๆฌกไฝฟ็จ](#-้ฆๆฌกไฝฟ็จ)- [๐ง ็ซฏๅฃๅฒ็ช่งฃๅณ](#-็ซฏๅฃๅฒ็ช่งฃๅณ)- [๐ณ Docker ้ ็ฝฎ](#-docker-้ ็ฝฎ)- [๐ ๅๅไปฃ็ไธ Tunnel](#-ๅๅไปฃ็ไธ-tunnel)- [๐ ่ฎค่ฏไธๅฎๅ จ](#-่ฎค่ฏไธๅฎๅ จ)- [โ ๅธธ่ง้ฎ้ข](#-ๅธธ่ง้ฎ้ข)-- [๐๏ธ ๆถๆๆๆกฃๆๅผ](#๏ธ-ๆถๆๆๆกฃๆๅผ)+- [๐๏ธ ๆถๆๆๆกฃๆๅผ](#-ๆถๆๆๆกฃๆๅผ)- [๐ค ๅ้ฆไธ Issue](#-ๅ้ฆไธ-issue)- [๐ ้กน็ฎ็ปๆ](#-้กน็ฎ็ปๆ)-- [๐ ๏ธ ๆๆฏๆ ](#๏ธ-ๆๆฏๆ )+- [๐ ๏ธ ๆๆฏๆ ](#-ๆๆฏๆ )- [๐ ๆดๆฐๆฅๅฟ](./CHANGELOG.md)- [๐ ่ฎธๅฏ่ฏ](#-่ฎธๅฏ่ฏ)@@ -230,6 +231,17 @@ pnpm dev> ๅฆๆไฝ ไฟฎๆนไบ `API_PORT`๏ผ้ 3001๏ผ๏ผ่ฏทๅๆญฅ่ฎพ็ฝฎ `API_URL`๏ผไพๅฆ `API_URL=http://localhost:4001`๏ผไพ web ็ `/api` ่ฝฌๅไฝฟ็จใ> `apps/collector/.env.local` ็ไผๅ ็บง้ซไบ `apps/collector/.env`ใ+## ๐ค Agent ้จ็ฝฒ++ๅฝไฝ ๅธๆไธญๅฟๅ้จ็ฝฒไธไธช Neko Master ๆๅก๏ผๅนถๅจไธๅ่ฎพๅค๏ผOpenWrtใLinuxใmacOS๏ผๆฌๅฐ้้็ฝๅ ณๆฐๆฎๆถ๏ผๆจ่ไฝฟ็จ 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`+## ๐ ้ฆๆฌกไฝฟ็จ@@ -406,6 +418,8 @@ COOKIE_SECRET=<่ณๅฐ32ๅญ่้ๆบๅญ็ฌฆไธฒ>`GeoLite2-City.mmdb`ใ`GeoLite2-ASN.mmdb`๏ผๅฟ ้๏ผ๏ผ`GeoLite2-Country.mmdb`๏ผๅฏ้๏ผใๆจ่ๆฅๆบ๏ผ<https://github.com/P3TERX/GeoLite.mmdb>ใ+> ่ฟ้ถ่ฏดๆ๏ผAgent ๆจกๅผ็ๅฎ่ฃ ใๅๆฐใๅๅธไธๅ ผๅฎน็ญ็ฅๅทฒ่ฟ็งปๅฐ `docs/agent/*`๏ผ่ฏทไปฅๆๆกฃไธบๅใ+## ๐ ๅๅไปฃ็ไธ Tunnelๆจ่ๅฐ Web ้กต้ขไธ WS ้ฝๆพๅจๅไธไธชๅๅไธ๏ผ้่ฟไธๅ่ทฏๅพ่ฝฌๅ๏ผ`/` โ `3000`๏ผ`/_cm_ws` โ `3002`ใdiff --git a/apps/agent/README.md b/apps/agent/README.mdnew file mode 100644index 0000000..cdfce59--- /dev/null+++ b/apps/agent/README.md@@ -0,0 +1,117 @@+# Neko Agent (Go)++A standalone executable agent for LAN data collection and reporting to Neko Master.++## Architecture++The agent follows a layered Go structure so that `main` stays thin and business logic is testable.++- `main.go`: process entrypoint, wiring, signal handling+- `internal/config`: CLI parsing, validation, endpoint normalization+- `internal/agent`: runtime loops (collector/report/heartbeat), queue/retry/state management+- `internal/gateway`: Clash/Surge adapters, payload decoding, protocol-specific normalization+- `internal/domain`: shared domain models (`FlowSnapshot`, `TrafficUpdate`)++## Build++```bash+cd apps/agent++# local build+GOCACHE=/tmp/go-build go build -o neko-agent .++# linux amd64+CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOCACHE=/tmp/go-build go build -trimpath -ldflags "-s -w" -o dist/neko-agent-linux-amd64 .++# linux arm64+CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOCACHE=/tmp/go-build go build -trimpath -ldflags "-s -w" -o dist/neko-agent-linux-arm64 .+```++## Run++### Clash++```bash+./neko-agent \+ --server-url https://your-neko.example.com \+ --backend-id 1 \+ --backend-token <backend-token> \+ --gateway-type clash \+ --gateway-url http://192.168.1.1:9090 \+ --gateway-token <optional-clash-secret>+```++### One-line Install Script (`curl | sh`)++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER="https://your-neko.example.com" \+ NEKO_BACKEND_ID="1" \+ NEKO_BACKEND_TOKEN="<backend-token>" \+ NEKO_GATEWAY_TYPE="clash" \+ NEKO_GATEWAY_URL="http://192.168.1.1:9090" \+ sh+```++Pin release version (recommended for production):++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_AGENT_VERSION="agent-v0.2.0" \+ NEKO_SERVER="https://your-neko.example.com" \+ NEKO_BACKEND_ID="1" \+ NEKO_BACKEND_TOKEN="<backend-token>" \+ NEKO_GATEWAY_TYPE="clash" \+ NEKO_GATEWAY_URL="http://192.168.1.1:9090" \+ sh+```++Quiet mode (no runtime logs):++```bash+./neko-agent ... --log=false+```++### Surge++```bash+./neko-agent \+ --server-url https://your-neko.example.com \+ --backend-id 2 \+ --backend-token <backend-token> \+ --gateway-type surge \+ --gateway-url http://127.0.0.1:9091 \+ --gateway-token <optional-surge-key>+```++## Key flags++- `--agent-id`: custom agent id (default: `hostname-pid`)+- `--report-interval`: report interval (default `2s`)+- `--heartbeat-interval`: heartbeat interval (default `30s`)+- `--gateway-poll-interval`: gateway polling interval (default `2s`)+- `--report-batch-size`: max updates per report (default `1000`)+- `--max-pending-updates`: local queue cap (default `50000`)+- `--request-timeout`: HTTP timeout (default `15s`)+- `--log`: enable runtime logs (default `true`, set `--log=false` to disable)+- `--version`: print version++Install script env (optional):++- `NEKO_GATEWAY_TOKEN`: gateway token+- `NEKO_AUTO_START`: `true|false` (default `true`)+- `NEKO_LOG`: `true|false` (default `true`)+- `NEKO_INSTALL_DIR`: install path (default `$HOME/.local/bin`)+- `NEKO_AGENT_VERSION`: release tag, default `latest` (for tagged version use `agent-vX.Y.Z`)+- `NEKO_PACKAGE_URL`: direct package URL override (tar.gz)+- `NEKO_CHECKSUMS_URL`: checksums URL override++## Release artifact naming++Per release tag (`agent-v*`), CI publishes:++- `neko-agent_<tag>_<os>_<arch>.tar.gz` (versioned)+- `neko-agent_<os>_<arch>.tar.gz` (latest alias)+- `checksums.txt`++Binary name inside tarball is always `neko-agent`.diff --git a/apps/agent/go.mod b/apps/agent/go.modnew file mode 100644index 0000000..83ab770--- /dev/null+++ b/apps/agent/go.mod@@ -0,0 +1,3 @@+module github.com/foru17/neko-master/apps/agent++go 1.22diff --git a/apps/agent/install.sh b/apps/agent/install.shnew file mode 100644index 0000000..4751479--- /dev/null+++ b/apps/agent/install.sh@@ -0,0 +1,200 @@+#!/usr/bin/env sh+set -eu++require_env() {+ key="$1"+ eval "val=\${$key:-}"+ if [ -z "$val" ]; then+ echo "[neko-agent] error: env $key is required" >&2+ exit 1+ fi+}++download_file() {+ url="$1"+ output="$2"+ if command -v curl >/dev/null 2>&1; then+ curl -fsSL "$url" -o "$output"+ return 0+ fi+ if command -v wget >/dev/null 2>&1; then+ wget -qO "$output" "$url"+ return 0+ fi+ echo "[neko-agent] error: curl or wget is required" >&2+ exit 1+}++normalize_os() {+ raw="$(uname -s | tr '[:upper:]' '[:lower:]')"+ case "$raw" in+ linux) echo "linux" ;;+ darwin) echo "darwin" ;;+ *)+ echo "[neko-agent] error: unsupported OS: $raw" >&2+ exit 1+ ;;+ esac+}++normalize_arch() {+ raw="$(uname -m | tr '[:upper:]' '[:lower:]')"+ case "$raw" in+ x86_64 | amd64) echo "amd64" ;;+ aarch64 | arm64) echo "arm64" ;;+ armv7l | armv7 | armhf) echo "armv7" ;;+ mips) echo "mips" ;;+ mipsle) echo "mipsle" ;;+ *)+ echo "[neko-agent] error: unsupported architecture: $raw" >&2+ echo "[neko-agent] hint: set NEKO_PACKAGE_URL manually if your target is exotic" >&2+ exit 1+ ;;+ esac+}++compute_sha256() {+ file="$1"+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$file" | awk '{print $1}'+ return 0+ fi+ if command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$file" | awk '{print $1}'+ return 0+ fi+ if command -v openssl >/dev/null 2>&1; then+ openssl dgst -sha256 "$file" | awk '{print $2}'+ return 0+ fi+ echo ""+}++require_env "NEKO_SERVER"+require_env "NEKO_BACKEND_ID"+require_env "NEKO_BACKEND_TOKEN"+require_env "NEKO_GATEWAY_URL"++NEKO_GATEWAY_TYPE="${NEKO_GATEWAY_TYPE:-clash}"+NEKO_GATEWAY_TOKEN="${NEKO_GATEWAY_TOKEN:-}"+NEKO_AGENT_REPO="${NEKO_AGENT_REPO:-foru17/neko-master}"+NEKO_AGENT_VERSION="${NEKO_AGENT_VERSION:-latest}"+NEKO_PACKAGE_URL="${NEKO_PACKAGE_URL:-}"+NEKO_CHECKSUMS_URL="${NEKO_CHECKSUMS_URL:-}"+NEKO_INSTALL_DIR="${NEKO_INSTALL_DIR:-$HOME/.local/bin}"+NEKO_LOG="${NEKO_LOG:-true}"+NEKO_AUTO_START="${NEKO_AUTO_START:-true}"+NEKO_LOG_FILE="${NEKO_LOG_FILE:-$HOME/.cache/neko-agent-${NEKO_BACKEND_ID}.log}"++os="$(normalize_os)"+arch="$(normalize_arch)"++if [ "$NEKO_AGENT_VERSION" = "latest" ]; then+ release_path="releases/latest/download"+else+ release_path="releases/download/${NEKO_AGENT_VERSION}"+fi++if [ "$NEKO_AGENT_VERSION" = "latest" ]; then+ asset="neko-agent_${os}_${arch}.tar.gz"+else+ asset="neko-agent_${NEKO_AGENT_VERSION}_${os}_${arch}.tar.gz"+fi+checksums_asset="checksums.txt"++if [ -n "$NEKO_PACKAGE_URL" ]; then+ package_url="$NEKO_PACKAGE_URL"+else+ package_url="https://github.com/${NEKO_AGENT_REPO}/${release_path}/${asset}"+fi++if [ -n "$NEKO_CHECKSUMS_URL" ]; then+ checksums_url="$NEKO_CHECKSUMS_URL"+else+ checksums_url="https://github.com/${NEKO_AGENT_REPO}/${release_path}/${checksums_asset}"+fi++tmp_dir="${TMPDIR:-/tmp}/neko-agent.$$"+mkdir -p "$tmp_dir"+trap 'rm -rf "$tmp_dir"' EXIT INT TERM++archive_path="$tmp_dir/neko-agent.tar.gz"+checksums_path="$tmp_dir/checksums.txt"++echo "[neko-agent] downloading package: $package_url"+download_file "$package_url" "$archive_path"++if [ -z "$NEKO_PACKAGE_URL" ]; then+ echo "[neko-agent] downloading checksums: $checksums_url"+ download_file "$checksums_url" "$checksums_path"++ expected_hash="$(awk '$2 == "'"$asset"'" {print $1}' "$checksums_path" | head -n 1)"+ if [ -z "$expected_hash" ]; then+ echo "[neko-agent] error: cannot find checksum for $asset" >&2+ exit 1+ fi++ actual_hash="$(compute_sha256 "$archive_path")"+ if [ -z "$actual_hash" ]; then+ echo "[neko-agent] error: missing sha256 tooling (sha256sum/shasum/openssl)" >&2+ exit 1+ fi++ if [ "$expected_hash" != "$actual_hash" ]; then+ echo "[neko-agent] error: checksum mismatch for $asset" >&2+ echo "[neko-agent] expected: $expected_hash" >&2+ echo "[neko-agent] actual: $actual_hash" >&2+ exit 1+ fi+fi++mkdir -p "$tmp_dir/extract"+tar -xzf "$archive_path" -C "$tmp_dir/extract"++binary_source="$tmp_dir/extract/neko-agent"+if [ ! -f "$binary_source" ]; then+ echo "[neko-agent] error: extracted archive does not contain neko-agent" >&2+ exit 1+fi++chmod +x "$binary_source"+mkdir -p "$NEKO_INSTALL_DIR"+install_target="$NEKO_INSTALL_DIR/neko-agent"+mv "$binary_source" "$install_target"+chmod +x "$install_target"++if ! echo ":$PATH:" | grep -q ":$NEKO_INSTALL_DIR:"; then+ echo "[neko-agent] warning: $NEKO_INSTALL_DIR is not in PATH"+fi++set -- "$install_target" \+ --server-url "$NEKO_SERVER" \+ --backend-id "$NEKO_BACKEND_ID" \+ --backend-token "$NEKO_BACKEND_TOKEN" \+ --gateway-type "$NEKO_GATEWAY_TYPE" \+ --gateway-url "$NEKO_GATEWAY_URL" \+ --log="$NEKO_LOG"++if [ -n "$NEKO_GATEWAY_TOKEN" ]; then+ set -- "$@" --gateway-token "$NEKO_GATEWAY_TOKEN"+fi++echo "[neko-agent] installed to: $install_target"+echo "[neko-agent] run command:"+cat <<EOF+$install_target \\+ --server-url "$NEKO_SERVER" \\+ --backend-id "$NEKO_BACKEND_ID" \\+ --backend-token "$NEKO_BACKEND_TOKEN" \\+ --gateway-type "$NEKO_GATEWAY_TYPE" \\+ --gateway-url "$NEKO_GATEWAY_URL" \\+ --log="$NEKO_LOG"$(if [ -n "$NEKO_GATEWAY_TOKEN" ]; then printf " \\\n+ --gateway-token \"$NEKO_GATEWAY_TOKEN\""; fi)+EOF++if [ "$NEKO_AUTO_START" = "true" ]; then+ mkdir -p "$(dirname "$NEKO_LOG_FILE")"+ nohup "$@" >"$NEKO_LOG_FILE" 2>&1 &+ echo "[neko-agent] started in background, pid=$!, log=$NEKO_LOG_FILE"+else+ echo "[neko-agent] auto-start disabled (NEKO_AUTO_START=false)"+fidiff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.gonew file mode 100644index 0000000..ba021a8--- /dev/null+++ b/apps/agent/internal/agent/runner.go@@ -0,0 +1,372 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net/http"+ "os"+ "strings"+ "sync"+ "time"++ "github.com/foru17/neko-master/apps/agent/internal/config"+ "github.com/foru17/neko-master/apps/agent/internal/domain"+ "github.com/foru17/neko-master/apps/agent/internal/gateway"+)++type trackedFlow struct {+ LastUpload int64+ LastDown int64+ LastSeenMs int64+}++type reportPayload struct {+ BackendID int `json:"backendId"`+ AgentID string `json:"agentId"`+ AgentVersion string `json:"agentVersion,omitempty"`+ ProtocolVersion int `json:"protocolVersion"`+ Updates []domain.TrafficUpdate `json:"updates"`+}++type heartbeatPayload struct {+ BackendID int `json:"backendId"`+ AgentID string `json:"agentId"`+ Hostname string `json:"hostname,omitempty"`+ Version string `json:"version,omitempty"`+ AgentVersion string `json:"agentVersion,omitempty"`+ ProtocolVersion int `json:"protocolVersion"`+ GatewayType string `json:"gatewayType,omitempty"`+ GatewayURL string `json:"gatewayUrl,omitempty"`+}++type Runner struct {+ cfg config.Config+ httpClient *http.Client+ gatewayClient *gateway.Client+ hostname string++ mu sync.Mutex+ queue []domain.TrafficUpdate+ flows map[string]trackedFlow+ dropped int64+}++func NewRunner(cfg config.Config) *Runner {+ httpClient := &http.Client{Timeout: cfg.RequestTimeout}+ hostname, _ := os.Hostname()+ if hostname == "" {+ hostname = "unknown-host"+ }++ return &Runner{+ cfg: cfg,+ httpClient: httpClient,+ gatewayClient: gateway.NewClient(httpClient, cfg.GatewayType, cfg.GatewayEndpoint, cfg.GatewayToken),+ hostname: hostname,+ queue: make([]domain.TrafficUpdate, 0, cfg.ReportBatchSize*2),+ flows: make(map[string]trackedFlow, 2048),+ }+}++func (r *Runner) Run(ctx context.Context) {+ log.Printf("[agent:%s] starting, backend=%d, gateway_type=%s, server=%s", r.cfg.AgentID, r.cfg.BackendID, r.cfg.GatewayType, r.cfg.ServerAPIBase)++ var wg sync.WaitGroup+ wg.Add(3)+ go r.runCollectorLoop(ctx, &wg)+ go r.runReportLoop(ctx, &wg)+ go r.runHeartbeatLoop(ctx, &wg)++ <-ctx.Done()+ log.Printf("[agent:%s] stopping...", r.cfg.AgentID)++ shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := r.flushOnce(shutdownCtx); err != nil {+ log.Printf("[agent:%s] final flush failed: %v", r.cfg.AgentID, err)+ }++ wg.Wait()+ pending, dropped := r.queueStats()+ if pending > 0 {+ log.Printf("[agent:%s] exit with %d pending updates", r.cfg.AgentID, pending)+ }+ if dropped > 0 {+ log.Printf("[agent:%s] dropped updates due to queue overflow: %d", r.cfg.AgentID, dropped)+ }+}++func (r *Runner) runCollectorLoop(ctx context.Context, wg *sync.WaitGroup) {+ defer wg.Done()++ failures := 0+ for {+ snapshots, err := r.gatewayClient.Collect(ctx)+ delay := r.cfg.GatewayPollInterval+ if err != nil {+ failures+++ delay = calculateBackoff(r.cfg.GatewayPollInterval, failures, 60*time.Second)+ log.Printf("[agent:%s] collector error (%d): %v", r.cfg.AgentID, failures, err)+ } else {+ failures = 0+ r.ingestSnapshots(snapshots, time.Now().UnixMilli())+ }++ select {+ case <-ctx.Done():+ return+ case <-time.After(delay):+ }+ }+}++func (r *Runner) runReportLoop(ctx context.Context, wg *sync.WaitGroup) {+ defer wg.Done()+ ticker := time.NewTicker(r.cfg.ReportInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if err := r.flushOnce(ctx); err != nil {+ log.Printf("[agent:%s] report error: %v", r.cfg.AgentID, err)+ }+ }+ }+}++func (r *Runner) runHeartbeatLoop(ctx context.Context, wg *sync.WaitGroup) {+ defer wg.Done()++ if err := r.sendHeartbeat(ctx); err != nil {+ log.Printf("[agent:%s] heartbeat error: %v", r.cfg.AgentID, err)+ }++ ticker := time.NewTicker(r.cfg.HeartbeatInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if err := r.sendHeartbeat(ctx); err != nil {+ log.Printf("[agent:%s] heartbeat error: %v", r.cfg.AgentID, err)+ }+ }+ }+}++func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {+ active := make(map[string]struct{}, len(snapshots))+ updates := make([]domain.TrafficUpdate, 0, len(snapshots))++ r.mu.Lock()+ defer r.mu.Unlock()++ for _, s := range snapshots {+ active[s.ID] = struct{}{}++ prev, hasPrev := r.flows[s.ID]+ deltaUp := s.Upload+ deltaDown := s.Download+ if hasPrev {+ if s.Upload >= prev.LastUpload {+ deltaUp = s.Upload - prev.LastUpload+ } else {+ deltaUp = 0+ }+ if s.Download >= prev.LastDown {+ deltaDown = s.Download - prev.LastDown+ } else {+ deltaDown = 0+ }+ }++ r.flows[s.ID] = trackedFlow{LastUpload: s.Upload, LastDown: s.Download, LastSeenMs: nowMs}+ if deltaUp <= 0 && deltaDown <= 0 {+ continue+ }++ ts := s.TimestampMs+ if ts <= 0 {+ ts = nowMs+ }++ updates = append(updates, domain.TrafficUpdate{+ Domain: s.Domain,+ IP: s.IP,+ Chain: firstChain(s.Chains),+ Chains: s.Chains,+ Rule: defaultString(s.Rule, "Match"),+ RulePayload: s.RulePayload,+ Upload: deltaUp,+ Download: deltaDown,+ SourceIP: s.SourceIP,+ TimestampMs: ts,+ })+ }++ for id, f := range r.flows {+ if _, ok := active[id]; ok {+ continue+ }+ if nowMs-f.LastSeenMs > r.cfg.StaleFlowTimeout.Milliseconds() {+ delete(r.flows, id)+ }+ }++ if len(updates) == 0 {+ return+ }++ r.queue = append(r.queue, updates...)+ if len(r.queue) > r.cfg.MaxPendingUpdates {+ overflow := len(r.queue) - r.cfg.MaxPendingUpdates+ r.queue = r.queue[overflow:]+ r.dropped += int64(overflow)+ }+}++func (r *Runner) flushOnce(ctx context.Context) error {+ batch := r.takeBatch(r.cfg.ReportBatchSize)+ if len(batch) == 0 {+ return nil+ }++ payload := reportPayload{+ BackendID: r.cfg.BackendID,+ AgentID: r.cfg.AgentID,+ AgentVersion: config.AgentVersion,+ ProtocolVersion: config.AgentProtocolVersion,+ Updates: batch,+ }++ if err := r.postJSON(ctx, "/agent/report", payload); err != nil {+ r.requeueFront(batch)+ return err+ }+ return nil+}++func (r *Runner) sendHeartbeat(ctx context.Context) error {+ payload := heartbeatPayload{+ BackendID: r.cfg.BackendID,+ AgentID: r.cfg.AgentID,+ Hostname: r.hostname,+ Version: config.AgentVersion,+ AgentVersion: config.AgentVersion,+ ProtocolVersion: config.AgentProtocolVersion,+ GatewayType: r.cfg.GatewayType,+ GatewayURL: r.cfg.GatewayEndpoint,+ }+ return r.postJSON(ctx, "/agent/heartbeat", payload)+}++func (r *Runner) postJSON(ctx context.Context, path string, payload interface{}) error {+ body, err := json.Marshal(payload)+ if err != nil {+ return err+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.cfg.ServerAPIBase+path, bytes.NewReader(body))+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+r.cfg.BackendToken)++ resp, err := r.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 200 && resp.StatusCode < 300 {+ return nil+ }++ respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))+ msg := string(bytes.TrimSpace(respBody))+ if msg == "" {+ msg = resp.Status+ }+ return fmt.Errorf("server http %d: %s", resp.StatusCode, msg)+}++func (r *Runner) takeBatch(limit int) []domain.TrafficUpdate {+ r.mu.Lock()+ defer r.mu.Unlock()+ if len(r.queue) == 0 {+ return nil+ }+ if limit > len(r.queue) {+ limit = len(r.queue)+ }+ out := make([]domain.TrafficUpdate, limit)+ copy(out, r.queue[:limit])+ r.queue = r.queue[limit:]+ return out+}++func (r *Runner) requeueFront(batch []domain.TrafficUpdate) {+ if len(batch) == 0 {+ return+ }+ r.mu.Lock()+ defer r.mu.Unlock()++ newQueue := make([]domain.TrafficUpdate, 0, len(batch)+len(r.queue))+ newQueue = append(newQueue, batch...)+ newQueue = append(newQueue, r.queue...)++ if len(newQueue) > r.cfg.MaxPendingUpdates {+ overflow := len(newQueue) - r.cfg.MaxPendingUpdates+ newQueue = newQueue[overflow:]+ r.dropped += int64(overflow)+ }+ r.queue = newQueue+}++func (r *Runner) queueStats() (pending int, dropped int64) {+ r.mu.Lock()+ defer r.mu.Unlock()+ return len(r.queue), r.dropped+}++func firstChain(chains []string) string {+ if len(chains) == 0 {+ return "DIRECT"+ }+ if strings.TrimSpace(chains[0]) == "" {+ return "DIRECT"+ }+ return strings.TrimSpace(chains[0])+}++func defaultString(v string, fallback string) string {+ if strings.TrimSpace(v) == "" {+ return fallback+ }+ return strings.TrimSpace(v)+}++func calculateBackoff(base time.Duration, failures int, max time.Duration) time.Duration {+ if failures <= 0 {+ return base+ }+ delay := base+ for i := 0; i < failures; i++ {+ delay *= 2+ if delay >= max {+ return max+ }+ }+ return delay+}diff --git a/apps/agent/internal/agent/runner_test.go b/apps/agent/internal/agent/runner_test.gonew file mode 100644index 0000000..8e0d6dd--- /dev/null+++ b/apps/agent/internal/agent/runner_test.go@@ -0,0 +1,72 @@+package agent++import (+ "testing"+ "time"++ "github.com/foru17/neko-master/apps/agent/internal/config"+ "github.com/foru17/neko-master/apps/agent/internal/domain"+)++func TestIngestSnapshotsDeltaCalculation(t *testing.T) {+ runner := NewRunner(config.Config{+ ServerAPIBase: "http://localhost:3000/api",+ BackendID: 1,+ BackendToken: "token",+ AgentID: "agent-test",+ GatewayType: "surge",+ GatewayEndpoint: "http://127.0.0.1:9091/v1/requests/recent",+ ReportInterval: time.Second,+ HeartbeatInterval: time.Second,+ GatewayPollInterval: time.Second,+ RequestTimeout: time.Second,+ ReportBatchSize: 100,+ MaxPendingUpdates: 1000,+ StaleFlowTimeout: time.Minute,+ })++ runner.ingestSnapshots([]domain.FlowSnapshot{{+ ID: "flow-1",+ Upload: 10,+ Download: 20,+ Chains: []string{"Proxy"},+ Rule: "MATCH",+ }}, 1000)++ first := runner.takeBatch(10)+ if len(first) != 1 {+ t.Fatalf("expected first batch len 1, got %d", len(first))+ }+ if first[0].Upload != 10 || first[0].Download != 20 {+ t.Fatalf("expected first delta 10/20, got %d/%d", first[0].Upload, first[0].Download)+ }++ runner.ingestSnapshots([]domain.FlowSnapshot{{+ ID: "flow-1",+ Upload: 25,+ Download: 50,+ Chains: []string{"Proxy"},+ Rule: "MATCH",+ }}, 2000)++ second := runner.takeBatch(10)+ if len(second) != 1 {+ t.Fatalf("expected second batch len 1, got %d", len(second))+ }+ if second[0].Upload != 15 || second[0].Download != 30 {+ t.Fatalf("expected second delta 15/30, got %d/%d", second[0].Upload, second[0].Download)+ }++ runner.ingestSnapshots([]domain.FlowSnapshot{{+ ID: "flow-1",+ Upload: 5,+ Download: 3,+ Chains: []string{"Proxy"},+ Rule: "MATCH",+ }}, 3000)++ third := runner.takeBatch(10)+ if len(third) != 0 {+ t.Fatalf("expected third batch len 0 when counters reset, got %d", len(third))+ }+}diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.gonew file mode 100644index 0000000..b1ace3a--- /dev/null+++ b/apps/agent/internal/config/config.go@@ -0,0 +1,191 @@+package config++import (+ "errors"+ "flag"+ "fmt"+ "os"+ "strings"+ "time"+)++const AgentVersion = "0.1.0"+const AgentProtocolVersion = 1++var (+ ErrHelp = errors.New("help requested")+ ErrVersion = errors.New("version requested")+)++type Config struct {+ ServerAPIBase string+ BackendID int+ BackendToken string+ AgentID string+ LogEnabled bool+ GatewayType string+ GatewayEndpoint string+ GatewayToken string+ ReportInterval time.Duration+ HeartbeatInterval time.Duration+ GatewayPollInterval time.Duration+ RequestTimeout time.Duration+ ReportBatchSize int+ MaxPendingUpdates int+ StaleFlowTimeout time.Duration+}++func Parse(args []string) (Config, error) {+ fs := flag.NewFlagSet("neko-agent", flag.ContinueOnError)+ fs.SetOutput(new(strings.Builder))++ serverURL := fs.String("server-url", "", "Neko Master server URL, e.g. https://neko.example.com")+ backendID := fs.Int("backend-id", 0, "Backend ID configured in Neko Master")+ backendToken := fs.String("backend-token", "", "Backend token for agent authentication")+ agentID := fs.String("agent-id", "", "Agent ID (optional, defaults to hostname-pid)")+ gatewayType := fs.String("gateway-type", "clash", "Gateway type: clash or surge")+ gatewayURL := fs.String("gateway-url", "", "Gateway control endpoint URL")+ gatewayToken := fs.String("gateway-token", "", "Gateway secret token (optional)")+ logEnabled := fs.Bool("log", true, "Enable runtime logs (set false to disable)")++ reportInterval := fs.Duration("report-interval", 2*time.Second, "Report interval, e.g. 2s")+ heartbeatInterval := fs.Duration("heartbeat-interval", 30*time.Second, "Heartbeat interval")+ gatewayPollInterval := fs.Duration("gateway-poll-interval", 2*time.Second, "Gateway polling interval")+ requestTimeout := fs.Duration("request-timeout", 15*time.Second, "HTTP request timeout")+ reportBatchSize := fs.Int("report-batch-size", 1000, "Maximum updates per report request")+ maxPending := fs.Int("max-pending-updates", 50000, "Maximum buffered updates in memory")+ staleFlowTimeout := fs.Duration("stale-flow-timeout", 5*time.Minute, "Flow state stale timeout")+ showVersion := fs.Bool("version", false, "Print version and exit")+ help := fs.Bool("help", false, "Show help")++ if err := fs.Parse(args); err != nil {+ if errors.Is(err, flag.ErrHelp) {+ return Config{}, ErrHelp+ }+ return Config{}, err+ }++ if *help {+ return Config{}, ErrHelp+ }+ if *showVersion {+ return Config{}, ErrVersion+ }++ if strings.TrimSpace(*serverURL) == "" || *backendID <= 0 || strings.TrimSpace(*backendToken) == "" || strings.TrimSpace(*gatewayURL) == "" {+ return Config{}, errors.New("server-url, backend-id, backend-token, gateway-url are required")+ }++ gt := strings.ToLower(strings.TrimSpace(*gatewayType))+ if gt != "clash" && gt != "surge" {+ return Config{}, fmt.Errorf("invalid gateway-type: %s", *gatewayType)+ }++ if *reportInterval <= 0 || *heartbeatInterval <= 0 || *gatewayPollInterval <= 0 || *requestTimeout <= 0 {+ return Config{}, errors.New("interval and timeout flags must be positive")+ }+ if *reportBatchSize <= 0 || *maxPending <= 0 {+ return Config{}, errors.New("report-batch-size and max-pending-updates must be positive")+ }++ hostname, _ := os.Hostname()+ if hostname == "" {+ hostname = "agent"+ }+ finalAgentID := strings.TrimSpace(*agentID)+ if finalAgentID == "" {+ finalAgentID = fmt.Sprintf("%s-%d", sanitizeID(hostname), os.Getpid())+ }+ if len(finalAgentID) > 128 {+ finalAgentID = finalAgentID[:128]+ }++ return Config{+ ServerAPIBase: normalizeServerAPIBase(*serverURL),+ BackendID: *backendID,+ BackendToken: strings.TrimSpace(*backendToken),+ AgentID: finalAgentID,+ LogEnabled: *logEnabled,+ GatewayType: gt,+ GatewayEndpoint: normalizeGatewayEndpoint(gt, *gatewayURL),+ GatewayToken: strings.TrimSpace(*gatewayToken),+ ReportInterval: *reportInterval,+ HeartbeatInterval: *heartbeatInterval,+ GatewayPollInterval: *gatewayPollInterval,+ RequestTimeout: *requestTimeout,+ ReportBatchSize: *reportBatchSize,+ MaxPendingUpdates: *maxPending,+ StaleFlowTimeout: *staleFlowTimeout,+ }, nil+}++func Usage() string {+ lines := []string{+ "Usage:",+ " neko-agent --server-url <url> --backend-id <id> --backend-token <token> --gateway-type <clash|surge> --gateway-url <url> [options]",+ "",+ "Required:",+ " --server-url Neko Master server URL",+ " --backend-id Backend ID in Neko Master",+ " --backend-token Backend token",+ " --gateway-url Gateway API URL",+ "",+ "Optional:",+ " --agent-id Agent ID (default hostname-pid)",+ " --log enable runtime logs (default true, set --log=false to disable)",+ " --gateway-type clash|surge (default clash)",+ " --gateway-token Gateway secret",+ " --report-interval default 2s",+ " --heartbeat-interval default 30s",+ " --gateway-poll-interval default 2s",+ " --request-timeout default 15s",+ " --report-batch-size default 1000",+ " --max-pending-updates default 50000",+ " --stale-flow-timeout default 5m",+ " --version print version",+ }+ return strings.Join(lines, "\n") + "\n"+}++func sanitizeID(v string) string {+ v = strings.TrimSpace(v)+ if v == "" {+ return "agent"+ }+ builder := strings.Builder{}+ builder.Grow(len(v))+ for _, r := range v {+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' {+ builder.WriteRune(r)+ } else {+ builder.WriteByte('-')+ }+ }+ out := strings.Trim(builder.String(), "-")+ if out == "" {+ return "agent"+ }+ return out+}++func normalizeServerAPIBase(raw string) string {+ trimmed := strings.TrimRight(strings.TrimSpace(raw), "/")+ if strings.HasSuffix(trimmed, "/api") {+ return trimmed+ }+ return trimmed + "/api"+}++func normalizeGatewayEndpoint(gatewayType, raw string) string {+ trimmed := strings.TrimRight(strings.TrimSpace(raw), "/")+ if gatewayType == "clash" {+ trimmed = strings.Replace(trimmed, "ws://", "http://", 1)+ trimmed = strings.Replace(trimmed, "wss://", "https://", 1)+ trimmed = strings.TrimSuffix(trimmed, "/connections")+ return trimmed + "/connections"+ }+ if strings.HasSuffix(trimmed, "/v1/requests/recent") {+ return trimmed+ }+ return trimmed + "/v1/requests/recent"+}diff --git a/apps/agent/internal/domain/types.go b/apps/agent/internal/domain/types.gonew file mode 100644index 0000000..ed32014--- /dev/null+++ b/apps/agent/internal/domain/types.go@@ -0,0 +1,27 @@+package domain++type TrafficUpdate struct {+ Domain string `json:"domain,omitempty"`+ IP string `json:"ip,omitempty"`+ Chain string `json:"chain"`+ Chains []string `json:"chains"`+ Rule string `json:"rule"`+ RulePayload string `json:"rulePayload,omitempty"`+ Upload int64 `json:"upload"`+ Download int64 `json:"download"`+ SourceIP string `json:"sourceIP,omitempty"`+ TimestampMs int64 `json:"timestampMs"`+}++type FlowSnapshot struct {+ ID string+ Domain string+ IP string+ SourceIP string+ Chains []string+ Rule string+ RulePayload string+ Upload int64+ Download int64+ TimestampMs int64+}diff --git a/apps/agent/internal/gateway/client.go b/apps/agent/internal/gateway/client.gonew file mode 100644index 0000000..944f8a4--- /dev/null+++ b/apps/agent/internal/gateway/client.go@@ -0,0 +1,514 @@+package gateway++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net"+ "net/http"+ "regexp"+ "strings"+ "time"++ "github.com/foru17/neko-master/apps/agent/internal/domain"+)++var (+ domainPattern = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)+ policyPathRegex = regexp.MustCompile(`\[Rule\] Policy decision path: (.+)`)+)++type Client struct {+ httpClient *http.Client+ gatewayType string+ endpoint string+ token string+}++func NewClient(httpClient *http.Client, gatewayType, endpoint, token string) *Client {+ return &Client{+ httpClient: httpClient,+ gatewayType: gatewayType,+ endpoint: endpoint,+ token: token,+ }+}++func (c *Client) Collect(ctx context.Context) ([]domain.FlowSnapshot, error) {+ if c.gatewayType == "clash" {+ return c.collectClash(ctx)+ }+ return c.collectSurge(ctx)+}++type clashConnectionsResponse struct {+ Connections []struct {+ ID string `json:"id"`+ Upload float64 `json:"upload"`+ Download float64 `json:"download"`+ Rule string `json:"rule"`+ RulePayload string `json:"rulePayload"`+ Chains []string `json:"chains"`+ Metadata struct {+ Host string `json:"host"`+ SniffHost string `json:"sniffHost"`+ DestinationIP string `json:"destinationIP"`+ SourceIP string `json:"sourceIP"`+ } `json:"metadata"`+ } `json:"connections"`+}++type flexibleID string++func (v *flexibleID) UnmarshalJSON(data []byte) error {+ trimmed := bytes.TrimSpace(data)+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {+ *v = ""+ return nil+ }++ var strVal string+ if err := json.Unmarshal(trimmed, &strVal); err == nil {+ *v = flexibleID(strVal)+ return nil+ }++ var numVal json.Number+ if err := json.Unmarshal(trimmed, &numVal); err == nil {+ *v = flexibleID(numVal.String())+ return nil+ }++ return fmt.Errorf("unsupported id value: %s", string(trimmed))+}++type flexibleFloat64 float64++func (v *flexibleFloat64) UnmarshalJSON(data []byte) error {+ trimmed := bytes.TrimSpace(data)+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {+ *v = 0+ return nil+ }++ var numVal json.Number+ if err := json.Unmarshal(trimmed, &numVal); err == nil {+ f, err := numVal.Float64()+ if err != nil {+ return fmt.Errorf("invalid numeric value: %s", string(trimmed))+ }+ *v = flexibleFloat64(f)+ return nil+ }++ var strVal string+ if err := json.Unmarshal(trimmed, &strVal); err == nil {+ strVal = strings.TrimSpace(strVal)+ if strVal == "" {+ *v = 0+ return nil+ }+ f, err := json.Number(strVal).Float64()+ if err != nil {+ return fmt.Errorf("invalid numeric string: %q", strVal)+ }+ *v = flexibleFloat64(f)+ return nil+ }++ return fmt.Errorf("unsupported numeric value: %s", string(trimmed))+}++type flexibleStringList []string++func (v *flexibleStringList) UnmarshalJSON(data []byte) error {+ trimmed := bytes.TrimSpace(data)+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {+ *v = nil+ return nil+ }++ var list []string+ if err := json.Unmarshal(trimmed, &list); err == nil {+ *v = list+ return nil+ }++ var single string+ if err := json.Unmarshal(trimmed, &single); err == nil {+ single = strings.TrimSpace(single)+ if single == "" {+ *v = nil+ return nil+ }+ *v = []string{single}+ return nil+ }++ return fmt.Errorf("unsupported notes value: %s", string(trimmed))+}++type surgeRequestsResponse struct {+ Requests []struct {+ ID flexibleID `json:"id"`+ RemoteHost string `json:"remoteHost"`+ RemoteAddress string `json:"remoteAddress"`+ LocalAddress string `json:"localAddress"`+ SourceAddress string `json:"sourceAddress"`+ PolicyName string `json:"policyName"`+ OriginalPolicyName string `json:"originalPolicyName"`+ Rule string `json:"rule"`+ Notes flexibleStringList `json:"notes"`+ OutBytes flexibleFloat64 `json:"outBytes"`+ InBytes flexibleFloat64 `json:"inBytes"`+ Time flexibleFloat64 `json:"time"`+ } `json:"requests"`+}++func (c *Client) collectClash(ctx context.Context) ([]domain.FlowSnapshot, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Accept", "application/json")+ if c.token != "" {+ req.Header.Set("Authorization", "Bearer "+c.token)+ }++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))+ return nil, fmt.Errorf("gateway http %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ }++ var payload clashConnectionsResponse+ if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {+ return nil, fmt.Errorf("decode clash response: %w", err)+ }++ nowMs := time.Now().UnixMilli()+ snapshots := make([]domain.FlowSnapshot, 0, len(payload.Connections))+ for _, item := range payload.Connections {+ id := strings.TrimSpace(item.ID)+ if id == "" {+ continue+ }+ domainName := strings.TrimSpace(item.Metadata.Host)+ if domainName == "" {+ domainName = strings.TrimSpace(item.Metadata.SniffHost)+ }+ snapshots = append(snapshots, domain.FlowSnapshot{+ ID: id,+ Domain: domainName,+ IP: strings.TrimSpace(item.Metadata.DestinationIP),+ SourceIP: strings.TrimSpace(item.Metadata.SourceIP),+ Chains: normalizeChains(item.Chains),+ Rule: defaultString(strings.TrimSpace(item.Rule), "Match"),+ RulePayload: strings.TrimSpace(item.RulePayload),+ Upload: toInt64(item.Upload),+ Download: toInt64(item.Download),+ TimestampMs: nowMs,+ })+ }++ return snapshots, nil+}++func (c *Client) collectSurge(ctx context.Context) ([]domain.FlowSnapshot, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Accept", "application/json")+ if c.token != "" {+ req.Header.Set("x-key", c.token)+ }++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))+ return nil, fmt.Errorf("gateway http %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ }++ body, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024))+ if err != nil {+ return nil, fmt.Errorf("read surge response: %w", err)+ }++ var payload surgeRequestsResponse+ if err := json.Unmarshal(body, &payload); err != nil {+ return nil, fmt.Errorf("decode surge response: %w (debug: %s)", err, inspectSurgeDecodeError(body))+ }++ nowMs := time.Now().UnixMilli()+ snapshots := make([]domain.FlowSnapshot, 0, len(payload.Requests))+ for _, reqItem := range payload.Requests {+ id := strings.TrimSpace(string(reqItem.ID))+ if id == "" {+ continue+ }++ remoteHost := strings.TrimSpace(reqItem.RemoteHost)+ remoteAddress := strings.TrimSpace(strings.Split(remoteAddressFirst(reqItem.RemoteAddress), " ")[0])+ hostWithoutPort := extractHost(remoteHost)++ domainName := ""+ if isDomainName(remoteHost) {+ domainName = hostWithoutPort+ }+ ip := ""+ if isIPHost(remoteHost) {+ ip = hostWithoutPort+ } else if isIPHost(remoteAddress) {+ ip = extractHost(remoteAddress)+ }++ sourceIP := extractHost(defaultString(strings.TrimSpace(reqItem.LocalAddress), strings.TrimSpace(reqItem.SourceAddress)))+ chains := convertSurgeChains(reqItem.PolicyName, reqItem.OriginalPolicyName, []string(reqItem.Notes))+ rule := defaultString(strings.TrimSpace(lastChain(chains)), defaultString(strings.TrimSpace(reqItem.OriginalPolicyName), "Match"))+ rulePayload := strings.TrimSpace(reqItem.Rule)++ timestampMs := nowMs+ if reqItem.Time > 0 {+ timestampMs = toInt64(float64(reqItem.Time))+ }++ snapshots = append(snapshots, domain.FlowSnapshot{+ ID: id,+ Domain: domainName,+ IP: ip,+ SourceIP: sourceIP,+ Chains: chains,+ Rule: defaultString(rule, "Match"),+ RulePayload: rulePayload,+ Upload: toInt64(float64(reqItem.OutBytes)),+ Download: toInt64(float64(reqItem.InBytes)),+ TimestampMs: timestampMs,+ })+ }++ return snapshots, nil+}++func normalizeChains(chains []string) []string {+ if len(chains) == 0 {+ return []string{"DIRECT"}+ }+ out := make([]string, 0, len(chains))+ for _, chain := range chains {+ trimmed := strings.TrimSpace(chain)+ if trimmed == "" {+ continue+ }+ out = append(out, trimmed)+ if len(out) >= 12 {+ break+ }+ }+ if len(out) == 0 {+ return []string{"DIRECT"}+ }+ return out+}++func lastChain(chains []string) string {+ if len(chains) == 0 {+ return ""+ }+ return strings.TrimSpace(chains[len(chains)-1])+}++func toInt64(v float64) int64 {+ if v <= 0 {+ return 0+ }+ if v > float64(^uint64(0)>>1) {+ return int64(^uint64(0) >> 1)+ }+ return int64(v)+}++func defaultString(v string, fallback string) string {+ if strings.TrimSpace(v) == "" {+ return fallback+ }+ return strings.TrimSpace(v)+}++func remoteAddressFirst(v string) string {+ parts := strings.Split(v, ",")+ if len(parts) == 0 {+ return ""+ }+ return strings.TrimSpace(parts[0])+}++func extractHost(hostWithPort string) string {+ hostWithPort = strings.TrimSpace(hostWithPort)+ if hostWithPort == "" {+ return ""+ }++ if strings.HasPrefix(hostWithPort, "[") {+ closing := strings.Index(hostWithPort, "]")+ if closing > 1 {+ return hostWithPort[1:closing]+ }+ }++ host, _, err := net.SplitHostPort(hostWithPort)+ if err == nil {+ return host+ }++ return strings.TrimSpace(hostWithPort)+}++func isIPHost(host string) bool {+ h := extractHost(host)+ if h == "" {+ return false+ }+ ip := net.ParseIP(h)+ return ip != nil+}++func isDomainName(host string) bool {+ h := extractHost(host)+ if h == "" {+ return false+ }+ if isIPHost(h) {+ return false+ }+ return domainPattern.MatchString(h)+}++func convertSurgeChains(policyName string, originalPolicyName string, notes []string) []string {+ if fromNotes := extractPolicyPathFromNotes(notes); len(fromNotes) >= 2 {+ return fromNotes+ }++ chains := make([]string, 0, 2)+ if p := strings.TrimSpace(policyName); p != "" {+ chains = append(chains, p)+ }+ o := strings.TrimSpace(originalPolicyName)+ if o != "" && o != strings.TrimSpace(policyName) {+ chains = append(chains, o)+ }+ if len(chains) == 0 {+ return []string{"DIRECT"}+ }+ return chains+}++func extractPolicyPathFromNotes(notes []string) []string {+ if len(notes) == 0 {+ return nil+ }+ for _, note := range notes {+ m := policyPathRegex.FindStringSubmatch(note)+ if len(m) < 2 {+ continue+ }+ segments := strings.Split(m[1], " -> ")+ cleaned := make([]string, 0, len(segments))+ for _, segment := range segments {+ s := strings.TrimSpace(segment)+ if s != "" {+ cleaned = append(cleaned, s)+ }+ }+ if len(cleaned) >= 2 {+ for i, j := 0, len(cleaned)-1; i < j; i, j = i+1, j-1 {+ cleaned[i], cleaned[j] = cleaned[j], cleaned[i]+ }+ return cleaned+ }+ }+ return nil+}++func inspectSurgeDecodeError(body []byte) string {+ if len(body) == 0 {+ return "empty response body"+ }++ var root map[string]json.RawMessage+ if err := json.Unmarshal(body, &root); err != nil {+ return "invalid json: " + truncateForLog(string(bytes.TrimSpace(body)), 240)+ }++ rawRequests, ok := root["requests"]+ if !ok {+ keys := make([]string, 0, len(root))+ for k := range root {+ keys = append(keys, k)+ }+ return "missing requests field, available keys: " + strings.Join(keys, ",")+ }++ var requests []map[string]json.RawMessage+ if err := json.Unmarshal(rawRequests, &requests); err != nil {+ return "requests is not array: " + truncateForLog(string(bytes.TrimSpace(rawRequests)), 240)+ }+ if len(requests) == 0 {+ return "requests array is empty"+ }++ rawID, ok := requests[0]["id"]+ if !ok {+ keys := make([]string, 0, len(requests[0]))+ for k := range requests[0] {+ keys = append(keys, k)+ }+ return "first request missing id, available keys: " + strings.Join(keys, ",")+ }++ return "first request id type=" + detectJSONType(rawID) + " value=" + truncateForLog(string(bytes.TrimSpace(rawID)), 80)+}++func detectJSONType(raw json.RawMessage) string {+ trimmed := bytes.TrimSpace(raw)+ if len(trimmed) == 0 {+ return "empty"+ }+ switch trimmed[0] {+ case '"':+ return "string"+ case '{':+ return "object"+ case '[':+ return "array"+ case 't', 'f':+ return "boolean"+ case 'n':+ return "null"+ default:+ if (trimmed[0] >= '0' && trimmed[0] <= '9') || trimmed[0] == '-' {+ return "number"+ }+ return "unknown"+ }+}++func truncateForLog(s string, limit int) string {+ s = strings.TrimSpace(s)+ if limit <= 0 || len(s) <= limit {+ return s+ }+ return s[:limit] + "..."+}diff --git a/apps/agent/internal/gateway/client_test.go b/apps/agent/internal/gateway/client_test.gonew file mode 100644index 0000000..5ba8c6e--- /dev/null+++ b/apps/agent/internal/gateway/client_test.go@@ -0,0 +1,82 @@+package gateway++import (+ "context"+ "strings"+ "testing"++ "net/http"+ "net/http/httptest"+)++func TestCollectSurgeSupportsFlexibleFields(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "requests": [+ {+ "id": 123,+ "remoteHost": "example.com:443",+ "remoteAddress": "93.184.216.34:443",+ "localAddress": "192.168.1.2:56123",+ "policyName": "Proxy",+ "originalPolicyName": "MATCH",+ "rule": "DOMAIN-SUFFIX,example.com",+ "notes": "single-note",+ "outBytes": "100.9",+ "inBytes": 200,+ "time": "1700000000123"+ }+ ]+ }`))+ }))+ defer server.Close()++ client := NewClient(server.Client(), "surge", server.URL+"/v1/requests/recent", "")+ snapshots, err := client.Collect(context.Background())+ if err != nil {+ t.Fatalf("Collect returned error: %v", err)+ }+ if len(snapshots) != 1 {+ t.Fatalf("expected 1 snapshot, got %d", len(snapshots))+ }++ s := snapshots[0]+ if s.ID != "123" {+ t.Fatalf("expected id 123, got %q", s.ID)+ }+ if s.Domain != "example.com" {+ t.Fatalf("expected domain example.com, got %q", s.Domain)+ }+ if s.Upload != 100 {+ t.Fatalf("expected upload 100, got %d", s.Upload)+ }+ if s.Download != 200 {+ t.Fatalf("expected download 200, got %d", s.Download)+ }+ if s.TimestampMs != 1700000000123 {+ t.Fatalf("expected timestamp 1700000000123, got %d", s.TimestampMs)+ }+}++func TestCollectSurgeDecodeErrorIncludesDebugHint(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"requests":[{"id":{"bad":1}}]}`))+ }))+ defer server.Close()++ client := NewClient(server.Client(), "surge", server.URL+"/v1/requests/recent", "")+ _, err := client.Collect(context.Background())+ if err == nil {+ t.Fatal("expected decode error, got nil")+ }++ msg := err.Error()+ if !strings.Contains(msg, "decode surge response") {+ t.Fatalf("expected decode error message, got: %s", msg)+ }+ if !strings.Contains(msg, "first request id type=object") {+ t.Fatalf("expected debug id type hint, got: %s", msg)+ }+}diff --git a/apps/agent/main.go b/apps/agent/main.gonew file mode 100644index 0000000..b21627e--- /dev/null+++ b/apps/agent/main.go@@ -0,0 +1,41 @@+package main++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log"+ "os"+ "os/signal"+ "syscall"++ "github.com/foru17/neko-master/apps/agent/internal/agent"+ "github.com/foru17/neko-master/apps/agent/internal/config"+)++func main() {+ cfg, err := config.Parse(os.Args[1:])+ if err != nil {+ switch {+ case errors.Is(err, config.ErrHelp):+ fmt.Fprint(os.Stderr, config.Usage())+ return+ case errors.Is(err, config.ErrVersion):+ fmt.Println(config.AgentVersion)+ return+ default:+ log.Fatalf("config error: %v", err)+ }+ }++ if !cfg.LogEnabled {+ log.SetOutput(io.Discard)+ }++ runner := agent.NewRunner(cfg)+ ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)+ defer cancel()++ runner.Run(ctx)+}diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.tsindex ccc5fb4..a35b9cc 100644--- a/apps/collector/src/app.ts+++ b/apps/collector/src/app.ts@@ -10,7 +10,8 @@ import cors from '@fastify/cors';import cookie from '@fastify/cookie';import type { StatsDatabase } from './db.js';import type { RealtimeStore } from './realtime.js';-import { buildGatewayHeaders, getGatewayBaseUrl, parseSurgeRule } from '@neko-master/shared';+import { buildGatewayHeaders, getGatewayBaseUrl, isAgentBackendUrl, parseSurgeRule } from '@neko-master/shared';+import type { TrafficUpdate } from './db.js';import { SurgePolicySyncService } from './modules/surge/surge-policy-sync.js';// Import modules@@ -36,8 +37,41 @@ export interface AppOptions {logger?: boolean;policySyncService?: SurgePolicySyncService;autoListen?: boolean;+ onTrafficIngested?: (backendId: number) => void;}+type AgentTrafficUpdatePayload = {+ domain?: string;+ ip?: string;+ chain?: string;+ chains?: string[];+ rule?: string;+ rulePayload?: string;+ upload?: number;+ download?: number;+ sourceIP?: string;+ timestampMs?: number;+};++type AgentHeartbeatPayload = {+ backendId?: number;+ agentId?: string;+ protocolVersion?: number;+ agentVersion?: string;+ hostname?: string;+ version?: string;+ gatewayType?: string;+ gatewayUrl?: string;+};++type AgentReportPayload = {+ backendId?: number;+ agentId?: string;+ protocolVersion?: number;+ agentVersion?: string;+ updates?: AgentTrafficUpdatePayload[];+};+export async function createApp(options: AppOptions) {const {port,@@ -46,6 +80,7 @@ export async function createApp(options: AppOptions) {logger = false,policySyncService,autoListen = true,+ onTrafficIngested,} = options;// Create Fastify instance@@ -97,6 +132,317 @@ export async function createApp(options: AppOptions) {return buildGatewayHeaders(backend);};+ const parseAgentToken = (request: { headers: Record<string, unknown> }): string => {+ const authHeader = request.headers.authorization;+ if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {+ return authHeader.slice(7).trim();+ }+ const customHeader = request.headers['x-agent-token'];+ return typeof customHeader === 'string' ? customHeader.trim() : '';+ };++ const parseBackendId = (raw: unknown): number | null => {+ const parsed = Number.parseInt(String(raw), 10);+ if (!Number.isFinite(parsed) || parsed <= 0) return null;+ return parsed;+ };++ const parseAgentId = (raw: unknown): string | null => {+ const value = String(raw || '').trim().slice(0, 128);+ return value || null;+ };++ const getMinAgentProtocolVersion = (): number => {+ const v = Number.parseInt(process.env.MIN_AGENT_PROTOCOL_VERSION || '1', 10);+ return Number.isFinite(v) && v > 0 ? v : 1;+ };++ const getMinAgentVersion = (): string => {+ return String(process.env.MIN_AGENT_VERSION || '').trim();+ };++ const parseProtocolVersion = (raw: unknown): number | null => {+ if (raw === undefined || raw === null || raw === '') return null;+ const parsed = Number.parseInt(String(raw), 10);+ if (!Number.isFinite(parsed) || parsed <= 0) return null;+ return parsed;+ };++ const normalizeVersion = (raw: unknown): string => {+ return String(raw || '')+ .trim()+ .replace(/^agent-v/i, '')+ .replace(/^v/i, '');+ };++ const parseVersionParts = (raw: unknown): [number, number, number] | null => {+ const normalized = normalizeVersion(raw);+ if (!normalized) return null;++ const match = normalized.match(/^(\d+)\.(\d+)(?:\.(\d+))?/);+ if (!match) return null;++ return [+ Number.parseInt(match[1], 10),+ Number.parseInt(match[2], 10),+ Number.parseInt(match[3] || '0', 10),+ ];+ };++ const compareVersionParts = (a: [number, number, number], b: [number, number, number]): number => {+ for (let i = 0; i < 3; i++) {+ if (a[i] > b[i]) return 1;+ if (a[i] < b[i]) return -1;+ }+ return 0;+ };++ const isAgentCompatible = (+ body: AgentHeartbeatPayload | AgentReportPayload,+ reply: { status: (code: number) => { send: (payload: Record<string, unknown>) => unknown } },+ ): boolean => {+ const requiredProtocol = getMinAgentProtocolVersion();+ const incomingProtocol = parseProtocolVersion(body.protocolVersion) ?? 1;+ if (incomingProtocol < requiredProtocol) {+ reply.status(426).send({+ error: `Agent protocol version ${incomingProtocol} is too old. Minimum required is ${requiredProtocol}.`,+ code: 'AGENT_PROTOCOL_TOO_OLD',+ minProtocolVersion: requiredProtocol,+ receivedProtocolVersion: incomingProtocol,+ });+ return false;+ }++ const requiredVersion = getMinAgentVersion();+ if (!requiredVersion) {+ return true;+ }++ const incomingVersionRaw = body.agentVersion || (body as AgentHeartbeatPayload).version;+ const requiredParts = parseVersionParts(requiredVersion);+ const incomingParts = parseVersionParts(incomingVersionRaw);+ if (!requiredParts || !incomingParts) {+ reply.status(426).send({+ error: `Agent version is missing or invalid. Minimum required is ${requiredVersion}.`,+ code: 'AGENT_VERSION_REQUIRED',+ minAgentVersion: requiredVersion,+ });+ return false;+ }++ if (compareVersionParts(incomingParts, requiredParts) < 0) {+ reply.status(426).send({+ error: `Agent version ${normalizeVersion(incomingVersionRaw)} is too old. Minimum required is ${requiredVersion}.`,+ code: 'AGENT_VERSION_TOO_OLD',+ minAgentVersion: requiredVersion,+ receivedAgentVersion: normalizeVersion(incomingVersionRaw),+ });+ return false;+ }++ return true;+ };++ const sanitizeAgentTrafficUpdate = (raw: AgentTrafficUpdatePayload): TrafficUpdate | null => {+ if (!raw || typeof raw !== 'object') return null;++ const upload = Number.isFinite(raw.upload) ? Math.max(0, Math.floor(raw.upload || 0)) : 0;+ const download = Number.isFinite(raw.download) ? Math.max(0, Math.floor(raw.download || 0)) : 0;+ if (upload === 0 && download === 0) return null;++ const rawChains = Array.isArray(raw.chains) ? raw.chains : [];+ const chains = rawChains+ .map((chain) => String(chain || '').trim())+ .filter(Boolean)+ .slice(0, 12);++ const normalizedChains = chains.length > 0 ? chains : [String(raw.chain || 'DIRECT').trim() || 'DIRECT'];+ const timestampMs = Number.isFinite(raw.timestampMs)+ ? Math.max(0, Math.floor(raw.timestampMs || 0))+ : Date.now();++ return {+ domain: String(raw.domain || '').trim().slice(0, 253),+ ip: String(raw.ip || '').trim().slice(0, 64),+ chain: normalizedChains[0] || 'DIRECT',+ chains: normalizedChains,+ rule: String(raw.rule || 'Match').trim().slice(0, 256) || 'Match',+ rulePayload: String(raw.rulePayload || '').trim().slice(0, 512),+ upload,+ download,+ sourceIP: String(raw.sourceIP || '').trim().slice(0, 64),+ timestampMs,+ };+ };++ const isAgentBackendAuthorized = (+ backendId: number,+ request: { headers: Record<string, unknown> },+ reply: { status: (code: number) => { send: (payload: Record<string, unknown>) => unknown } },+ ): backendId is number => {+ const backend = db.getBackend(backendId);+ if (!backend) {+ reply.status(404).send({ error: 'Backend not found' });+ return false;+ }+ if (!isAgentBackendUrl(backend.url)) {+ reply.status(400).send({ error: 'Backend is not in agent mode (url must start with agent://)' });+ return false;+ }++ const expected = (backend.token || '').trim();+ if (!expected) {+ reply.status(403).send({ error: 'Agent backend token is not configured' });+ return false;+ }++ const provided = parseAgentToken(request);+ if (!provided || provided !== expected) {+ reply.status(401).send({ error: 'Invalid agent token' });+ return false;+ }+ return true;+ };++ const isAgentBindingAllowed = (+ backendId: number,+ agentId: string,+ reply: { status: (code: number) => { send: (payload: Record<string, unknown>) => unknown } },+ ): boolean => {+ const heartbeat = db.getAgentHeartbeat(backendId);+ if (!heartbeat) {+ return true;+ }+ if (heartbeat.agentId === agentId) {+ return true;+ }++ reply.status(409).send({+ error: `Agent token is already bound to '${heartbeat.agentId}'. Rotate token before binding '${agentId}'.`,+ code: 'AGENT_TOKEN_ALREADY_BOUND',+ boundAgentId: heartbeat.agentId,+ });+ return false;+ };++ app.post('/api/agent/heartbeat', async (request, reply) => {+ const body = request.body as AgentHeartbeatPayload;+ const backendId = parseBackendId(body?.backendId);+ if (backendId === null) {+ return reply.status(400).send({ error: 'Invalid backendId' });+ }+ if (!isAgentBackendAuthorized(backendId, request, reply)) {+ return;+ }+ if (!isAgentCompatible(body, reply)) {+ return;+ }++ const agentId = parseAgentId(body.agentId);+ if (!agentId) {+ return reply.status(400).send({ error: 'Invalid agentId' });+ }+ if (!isAgentBindingAllowed(backendId, agentId, reply)) {+ return;+ }+ const hostname = String(body.hostname || '').trim().slice(0, 128) || undefined;+ const version = String(body.agentVersion || body.version || '').trim().slice(0, 64) || undefined;+ const gatewayType = String(body.gatewayType || '').trim().slice(0, 16) || undefined;+ const gatewayUrl = String(body.gatewayUrl || '').trim().slice(0, 512) || undefined;+ const remoteIP = request.ip || request.headers['x-forwarded-for']?.toString().split(',')[0]?.trim();++ db.upsertAgentHeartbeat({+ backendId,+ agentId,+ hostname,+ version,+ gatewayType,+ gatewayUrl,+ remoteIP,+ lastSeen: new Date().toISOString(),+ });++ return { success: true, backendId, agentId, serverTime: new Date().toISOString() };+ });++ app.post('/api/agent/report', async (request, reply) => {+ const body = request.body as AgentReportPayload;+ const backendId = parseBackendId(body?.backendId);+ if (backendId === null) {+ return reply.status(400).send({ error: 'Invalid backendId' });+ }+ if (!isAgentBackendAuthorized(backendId, request, reply)) {+ return;+ }+ if (!isAgentCompatible(body, reply)) {+ return;+ }++ const agentId = parseAgentId(body.agentId);+ if (!agentId) {+ return reply.status(400).send({ error: 'Invalid agentId' });+ }+ if (!isAgentBindingAllowed(backendId, agentId, reply)) {+ return;+ }++ const rawUpdates = Array.isArray(body?.updates) ? body.updates : [];+ if (rawUpdates.length === 0) {+ return { success: true, backendId, accepted: 0, dropped: 0 };+ }++ const maxBatchSize = Math.max(+ 1,+ Number.parseInt(process.env.AGENT_INGEST_MAX_BATCH_SIZE || '5000', 10) || 5000,+ );+ const picked = rawUpdates.slice(0, maxBatchSize);+ const updates: TrafficUpdate[] = [];++ for (const update of picked) {+ const sanitized = sanitizeAgentTrafficUpdate(update);+ if (sanitized) updates.push(sanitized);+ }++ if (updates.length === 0) {+ return { success: true, backendId, accepted: 0, dropped: picked.length };+ }++ db.batchUpdateTrafficStats(backendId, updates);+ for (const update of updates) {+ realtimeStore.recordTraffic(+ backendId,+ {+ domain: update.domain,+ ip: update.ip,+ sourceIP: update.sourceIP,+ chains: update.chains,+ rule: update.rule,+ rulePayload: update.rulePayload,+ upload: update.upload,+ download: update.download,+ },+ 1,+ update.timestampMs || Date.now(),+ );+ }++ db.upsertAgentHeartbeat({+ backendId,+ agentId,+ lastSeen: new Date().toISOString(),+ remoteIP: request.ip || request.headers['x-forwarded-for']?.toString().split(',')[0]?.trim(),+ });++ onTrafficIngested?.(backendId);++ return {+ success: true,+ backendId,+ accepted: updates.length,+ dropped: picked.length - updates.length,+ };+ });+// Compatibility routes: Gateway APIsapp.get('/api/gateway/proxies', async (request, reply) => {const backendId = getBackendIdFromQuery(request.query as Record<string, unknown>);@@ -108,6 +454,9 @@ export async function createApp(options: AppOptions) {if (!backend) {return reply.status(404).send({ error: 'Backend not found' });}+ if (isAgentBackendUrl(backend.url)) {+ return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });+ }const gatewayBaseUrl = getGatewayBaseUrl(backend.url);const isSurge = backend.type === 'surge';@@ -190,6 +539,9 @@ export async function createApp(options: AppOptions) {if (!backend) {return reply.status(404).send({ error: 'Backend not found' });}+ if (isAgentBackendUrl(backend.url)) {+ return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });+ }const gatewayBaseUrl = getGatewayBaseUrl(backend.url);const isSurge = backend.type === 'surge';@@ -328,6 +680,9 @@ export async function createApp(options: AppOptions) {if (!backend || backend.type !== 'surge') {return reply.status(400).send({ error: 'Only Surge backend supports this operation' });}+ if (isAgentBackendUrl(backend.url)) {+ return reply.status(400).send({ error: 'Agent mode backend does not support this operation' });+ }if (!policySyncService) {return reply.status(503).send({ error: 'Policy sync service not available' });@@ -357,6 +712,9 @@ export async function createApp(options: AppOptions) {if (!backend) {return reply.status(404).send({ error: 'Backend not found' });}+ if (isAgentBackendUrl(backend.url)) {+ return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });+ }const gatewayBaseUrl = getGatewayBaseUrl(backend.url);const isSurge = backend.type === 'surge';@@ -414,6 +772,8 @@ export async function createApp(options: AppOptions) {'/api/auth/state','/api/auth/verify','/api/auth/logout', // Add logout as public so we can clear cookies even if invalid+ '/api/agent/heartbeat',+ '/api/agent/report',];// Check if route is public@@ -473,17 +833,20 @@ export class APIServer {private realtimeStore: RealtimeStore;private port: number;private policySyncService?: SurgePolicySyncService;+ private onTrafficIngested?: (backendId: number) => void;constructor(port: number,db: StatsDatabase,realtimeStore: RealtimeStore,- policySyncService?: SurgePolicySyncService+ policySyncService?: SurgePolicySyncService,+ onTrafficIngested?: (backendId: number) => void,) {this.port = port;this.db = db;this.realtimeStore = realtimeStore;this.policySyncService = policySyncService;+ this.onTrafficIngested = onTrafficIngested;}async start() {@@ -492,6 +855,7 @@ export class APIServer {db: this.db,realtimeStore: this.realtimeStore,policySyncService: this.policySyncService,+ onTrafficIngested: this.onTrafficIngested,logger: false,});return this.app;diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.tsindex f32eca5..4df009c 100644--- a/apps/collector/src/database/schema.ts+++ b/apps/collector/src/database/schema.ts@@ -367,6 +367,22 @@ export const SCHEMA = {);`,+ // Agent heartbeat status per backend (for agent:// passive mode)+ AGENT_HEARTBEATS: `+ CREATE TABLE IF NOT EXISTS agent_heartbeats (+ backend_id INTEGER PRIMARY KEY,+ agent_id TEXT NOT NULL,+ hostname TEXT,+ version TEXT,+ gateway_type TEXT,+ gateway_url TEXT,+ remote_ip TEXT,+ last_seen DATETIME NOT NULL,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE+ );+ `,+// App configurationAPP_CONFIG: `CREATE TABLE IF NOT EXISTS app_config (@@ -458,6 +474,9 @@ export const INDEXES = [// Backend configs unique index`CREATE UNIQUE INDEX IF NOT EXISTS idx_backend_configs_name ON backend_configs(name);`,+ // Agent heartbeat indexes+ `CREATE INDEX IF NOT EXISTS idx_agent_heartbeats_last_seen ON agent_heartbeats(last_seen);`,+// Surge policy cache indexes`CREATE INDEX IF NOT EXISTS idx_surge_policy_backend ON surge_policy_cache(backend_id);`,`CREATE INDEX IF NOT EXISTS idx_surge_policy_updated ON surge_policy_cache(updated_at);`,@@ -507,6 +526,7 @@ export function getAllSchemaStatements(): string[] {SCHEMA.RULE_DOMAIN_TRAFFIC,SCHEMA.RULE_IP_TRAFFIC,SCHEMA.BACKEND_CONFIGS,+ SCHEMA.AGENT_HEARTBEATS,SCHEMA.APP_CONFIG,SCHEMA.SURGE_POLICY_CACHE,SCHEMA.AUTH_CONFIG,diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.tsindex 06e49e3..ce51153 100644--- a/apps/collector/src/db.ts+++ b/apps/collector/src/db.ts@@ -46,6 +46,17 @@ export interface BackendConfig {updated_at: string;}+export interface AgentHeartbeat {+ backendId: number;+ agentId: string;+ hostname?: string;+ version?: string;+ gatewayType?: string;+ gatewayUrl?: string;+ remoteIP?: string;+ lastSeen: string;+}+function normalizeIPStatsGeoIP(items: IPStats[]): IPStats[] {return items.map((item) => {const normalizedGeoIP = normalizeGeoIP(item.geoIP as unknown);@@ -942,6 +953,68 @@ export class StatsDatabase {deleteBackendData(id: number) { this.repos.backend.deleteBackendData(id); }getGlobalSummary() { return this.repos.backend.getGlobalSummary(); }+ upsertAgentHeartbeat(input: {+ backendId: number;+ agentId: string;+ hostname?: string;+ version?: string;+ gatewayType?: string;+ gatewayUrl?: string;+ remoteIP?: string;+ lastSeen?: string;+ }): void {+ const stmt = this.db.prepare(`+ INSERT INTO agent_heartbeats (+ backend_id, agent_id, hostname, version, gateway_type, gateway_url, remote_ip, last_seen, updated_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)+ ON CONFLICT(backend_id) DO UPDATE SET+ agent_id = excluded.agent_id,+ hostname = excluded.hostname,+ version = excluded.version,+ gateway_type = excluded.gateway_type,+ gateway_url = excluded.gateway_url,+ remote_ip = excluded.remote_ip,+ last_seen = excluded.last_seen,+ updated_at = CURRENT_TIMESTAMP+ `);++ const lastSeen = input.lastSeen || new Date().toISOString();+ stmt.run(+ input.backendId,+ input.agentId,+ input.hostname || null,+ input.version || null,+ input.gatewayType || null,+ input.gatewayUrl || null,+ input.remoteIP || null,+ lastSeen,+ );+ }++ getAgentHeartbeat(backendId: number): AgentHeartbeat | undefined {+ const stmt = this.db.prepare(`+ SELECT+ backend_id as backendId,+ agent_id as agentId,+ hostname,+ version,+ gateway_type as gatewayType,+ gateway_url as gatewayUrl,+ remote_ip as remoteIP,+ last_seen as lastSeen+ FROM agent_heartbeats+ WHERE backend_id = ?+ LIMIT 1+ `);+ return stmt.get(backendId) as AgentHeartbeat | undefined;+ }++ clearAgentHeartbeat(backendId: number): void {+ const stmt = this.db.prepare('DELETE FROM agent_heartbeats WHERE backend_id = ?');+ stmt.run(backendId);+ }+// AuthgetAuthConfig() { return this.repos.auth.getAuthConfig(); }updateAuthConfig(updates: { enabled?: boolean; tokenHash?: string | null }) { this.repos.auth.updateAuthConfig(updates); }diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.tsindex 5ee42d3..5009ee6 100644--- a/apps/collector/src/index.ts+++ b/apps/collector/src/index.ts@@ -1,6 +1,7 @@import { config } from 'dotenv';import path from 'path';import fs from 'fs';+import { isAgentBackendUrl } from '@neko-master/shared';// Load .env.local if it exists (takes precedence over .env, but not shell)const envLocalPath = path.join(process.cwd(), '.env.local');@@ -58,7 +59,15 @@ async function main() {// Initialize API serverconsole.log('[Main] Starting API server on port', API_PORT);- apiServer = new APIServer(API_PORT, db, realtimeStore, policySyncService);+ apiServer = new APIServer(+ API_PORT,+ db,+ realtimeStore,+ policySyncService,+ (backendId: number) => {+ wsServer.broadcastStats(backendId);+ },+ );apiServer.start();// Start backend management loop@@ -108,9 +117,10 @@ async function manageBackends() {for (const backend of backends) {const existingCollector = collectors.get(backend.id);const lastConfig = lastBackendConfigs.get(backend.id);+ const isAgentBackend = isAgentBackendUrl(backend.url);// Check if we need to start or restart this backend connection- const needsStart = backend.listening && backend.enabled && !existingCollector;+ const needsStart = backend.listening && backend.enabled && !existingCollector && !isAgentBackend;const needsRestart = existingCollector && lastConfig && (lastConfig.url !== backend.url ||lastConfig.token !== backend.token ||@@ -125,7 +135,7 @@ async function manageBackends() {}if (needsStart || needsRestart) {- if (backend.listening && backend.enabled) {+ if (backend.listening && backend.enabled && !isAgentBackend) {startCollector(backend);}}@@ -154,6 +164,11 @@ async function manageBackends() {// Start a collector for a specific backendfunction startCollector(backend: BackendConfig) {+ if (isAgentBackendUrl(backend.url)) {+ console.log(`[Collector] Backend "${backend.name}" (ID: ${backend.id}) is agent mode, skip direct pulling`);+ return;+ }+if (collectors.has(backend.id)) {console.log(`[Collector] Backend "${backend.name}" (ID: ${backend.id}) already has a collector running`);return;diff --git a/apps/collector/src/modules/backend/backend.controller.ts b/apps/collector/src/modules/backend/backend.controller.tsindex 527d92b..c0990f8 100644--- a/apps/collector/src/modules/backend/backend.controller.ts+++ b/apps/collector/src/modules/backend/backend.controller.ts@@ -155,6 +155,24 @@ const backendController: FastifyPluginAsync = async (fastify: FastifyInstance):return result;});+ // Rotate agent token for a backend+ fastify.post<{ Params: BackendParams }>('/:id/rotate-agent-token', async (request, reply) => {+ if (fastify.authService.isShowcaseMode()) {+ return reply.status(403).send({ error: 'Forbidden' });+ }++ const { id } = request.params;+ const backendId = parseInt(id);++ const backend = service.getBackend(backendId);+ if (!backend) {+ return reply.status(404).send({ error: 'Backend not found' });+ }++ const result = service.rotateAgentToken(backendId);+ return result;+ });+// Test backend connectionfastify.post<{ Body: TestConnectionInput }>('/test', async (request, reply) => {if (fastify.authService.isShowcaseMode()) {diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.tsindex b5c217d..5a8dfaf 100644--- a/apps/collector/src/modules/backend/backend.service.ts+++ b/apps/collector/src/modules/backend/backend.service.ts@@ -5,6 +5,7 @@import type { StatsDatabase } from '../../db.js';import type { RealtimeStore } from '../../realtime.js';+import { randomBytes } from 'node:crypto';import type {BackendConfig,CreateBackendInput,@@ -14,7 +15,9 @@ import type {TestConnectionInput,TestConnectionResult,CreateBackendResult,+ RotateAgentTokenResult,} from './backend.types.js';+import { isAgentBackendUrl } from '@neko-master/shared';import type { AuthService } from '../auth/auth.service.js';@@ -34,10 +37,17 @@ function maskUrl(url: string): string {}}+function generateAgentBackendToken(): string {+ return `ag_${randomBytes(24).toString('base64url')}`;+}+export class BackendService {private healthStatus = new Map<number, BackendHealthInfo>();private healthCheckInterval: NodeJS.Timeout | null = null;- private readonly HEALTH_CHECK_INTERVAL_MS = 30000; // 30 seconds+ private readonly HEALTH_CHECK_INTERVAL_MS = Math.max(+ 5_000,+ Number.parseInt(process.env.BACKEND_HEALTH_CHECK_INTERVAL_MS || '30000', 10) || 30_000,+ );constructor(private db: StatsDatabase,@@ -85,9 +95,21 @@ export class BackendService {*/private async runHealthChecks(): Promise<void> {const backends = this.db.getListeningBackends();+ const now = Date.now();for (const backend of backends) {try {+ if (isAgentBackendUrl(backend.url)) {+ const health = this.buildAgentHealthStatus(backend.id, now);++ const prevHealth = this.healthStatus.get(backend.id);+ if (prevHealth?.status !== health.status) {+ console.log(`[BackendService] Health check for ${backend.name}: ${health.status}${health.message ? ` - ${health.message}` : ''}`);+ }+ this.healthStatus.set(backend.id, health);+ continue;+ }+const startTime = Date.now();const result = await this.testConnection({url: backend.url,@@ -126,6 +148,16 @@ export class BackendService {* Attach health status to backend response*/private attachHealthStatus(backend: BackendResponse): BackendResponse {+ if (isAgentBackendUrl(backend.url)) {+ const dynamicHealth = this.buildAgentHealthStatus(+ backend.id,+ Date.now(),+ this.getAgentManualTestTimeoutMs(),+ );+ this.healthStatus.set(backend.id, dynamicHealth);+ return { ...backend, health: dynamicHealth };+ }+const health = this.healthStatus.get(backend.id);if (health) {return { ...backend, health };@@ -204,12 +236,17 @@ export class BackendService {*/createBackend(input: CreateBackendInput): CreateBackendResult {const { name, url, token, type = 'clash' } = input;+ const isAgentMode = isAgentBackendUrl(url);+ const normalizedToken = (token || '').trim();+ const finalToken = isAgentMode+ ? (normalizedToken || generateAgentBackendToken())+ : normalizedToken;// Check if this is the first backendconst existingBackends = this.db.getAllBackends();const isFirstBackend = existingBackends.length === 0;- const id = this.db.createBackend({ name, url, token, type });+ const id = this.db.createBackend({ name, url, token: finalToken, type });// If this is the first backend, automatically set it as activeif (isFirstBackend) {@@ -217,14 +254,42 @@ export class BackendService {console.log(`[API] First backend created, automatically set as active: ${name} (ID: ${id})`);}- return { id, isActive: isFirstBackend, message: 'Backend created successfully' };+ return {+ id,+ isActive: isFirstBackend,+ message: 'Backend created successfully',+ agentToken: isAgentMode ? finalToken : undefined,+ };}/*** Update a backend*/updateBackend(id: number, input: UpdateBackendInput): { message: string } {+ const existing = this.db.getBackend(id);+ if (!existing) {+ throw new Error('Backend not found');+ }++ const prevAgentMode = isAgentBackendUrl(existing.url);+ const nextUrl = typeof input.url === 'string' ? input.url : existing.url;+ const nextAgentMode = isAgentBackendUrl(nextUrl);+this.db.updateBackend(id, input);++ if (prevAgentMode && !nextAgentMode) {+ this.db.clearAgentHeartbeat(id);+ this.healthStatus.delete(id);+ }++ if (!prevAgentMode && nextAgentMode) {+ this.healthStatus.set(id, {+ status: 'unknown',+ lastChecked: Date.now(),+ message: 'Waiting for first agent heartbeat',+ });+ }+return { message: 'Backend updated successfully' };}@@ -236,6 +301,31 @@ export class BackendService {return { message: 'Backend deleted successfully' };}+ rotateAgentToken(id: number): RotateAgentTokenResult {+ const backend = this.db.getBackend(id);+ if (!backend) {+ throw new Error('Backend not found');+ }+ if (!isAgentBackendUrl(backend.url)) {+ throw new Error('Token rotation is only supported for agent mode backends');+ }++ const nextToken = generateAgentBackendToken();+ this.db.updateBackend(id, { token: nextToken });+ this.db.clearAgentHeartbeat(id);++ this.healthStatus.set(id, {+ status: 'unknown',+ lastChecked: Date.now(),+ message: 'Agent token rotated. Waiting for new heartbeat',+ });++ return {+ message: 'Agent token rotated successfully',+ agentToken: nextToken,+ };+ }+/*** Set active backend*/@@ -271,6 +361,16 @@ export class BackendService {throw new Error('Backend not found');}+ if (isAgentBackendUrl(backend.url)) {+ const health = this.buildAgentHealthStatus(id, Date.now(), this.getAgentManualTestTimeoutMs());+ this.healthStatus.set(id, health);++ return {+ success: health.status === 'healthy',+ message: health.message || 'Agent status unavailable',+ };+ }+return this.testConnection({url: backend.url,token: backend.token,@@ -283,6 +383,10 @@ export class BackendService {*/async testConnection(input: TestConnectionInput): Promise<TestConnectionResult> {const { url, token, type = 'clash' } = input;++ if (isAgentBackendUrl(url)) {+ return { success: true, message: 'Agent mode backend configured (use backend test by id for realtime online status)' };+ }if (type === 'surge') {return this.testSurgeConnection(url, token);@@ -291,6 +395,51 @@ export class BackendService {return this.testClashConnection(url, token);}+ private getAgentHeartbeatTimeoutMs(): number {+ return Math.max(+ 15_000,+ Number.parseInt(process.env.AGENT_HEARTBEAT_TIMEOUT_MS || '30000', 10) || 30_000,+ );+ }++ private getAgentManualTestTimeoutMs(): number {+ return Math.max(+ 3_000,+ Number.parseInt(process.env.AGENT_MANUAL_TEST_TIMEOUT_MS || '8000', 10) || 8_000,+ );+ }++ private buildAgentHealthStatus(+ backendId: number,+ now = Date.now(),+ timeoutMsOverride?: number,+ ): BackendHealthInfo {+ const heartbeat = this.db.getAgentHeartbeat(backendId);+ const timeoutMs = timeoutMsOverride ?? this.getAgentHeartbeatTimeoutMs();++ if (!heartbeat) {+ return {+ status: 'unknown',+ lastChecked: now,+ message: 'Waiting for first agent heartbeat',+ };+ }++ const lastSeenMs = new Date(heartbeat.lastSeen).getTime();+ const ageMs = Number.isFinite(lastSeenMs) ? Math.max(0, now - lastSeenMs) : Number.POSITIVE_INFINITY;+ const ageText = Number.isFinite(ageMs) ? `${Math.round(ageMs / 1000)}s ago` : 'unknown';+ const timeoutText = `${Math.round(timeoutMs / 1000)}s`;+ const isOnline = Number.isFinite(ageMs) && ageMs <= timeoutMs;++ return {+ status: isOnline ? 'healthy' : 'unhealthy',+ lastChecked: now,+ message: isOnline+ ? `Agent ${heartbeat.agentId} online (last seen ${ageText})`+ : `Agent offline (last seen ${ageText}, timeout ${timeoutText})`,+ };+ }+/*** Test Clash WebSocket connection*/diff --git a/apps/collector/src/modules/backend/backend.types.ts b/apps/collector/src/modules/backend/backend.types.tsindex d76c626..7f6765d 100644--- a/apps/collector/src/modules/backend/backend.types.ts+++ b/apps/collector/src/modules/backend/backend.types.ts@@ -82,4 +82,10 @@ export interface CreateBackendResult {id: number;isActive: boolean;message: string;+ agentToken?: string;+}++export interface RotateAgentTokenResult {+ message: string;+ agentToken: string;}diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsxindex 22a119a..c481a9f 100644--- a/apps/web/components/features/backend/backend-config-dialog.tsx+++ b/apps/web/components/features/backend/backend-config-dialog.tsx@@ -26,6 +26,8 @@ import {Lock,EyeOff,Key,+ Copy,+ Terminal,} from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -57,6 +59,7 @@ import {} from "@/components/ui/dialog";import { cn, formatBytes, formatNumber } from "@/lib/utils";import { api, type GeoLookupConfig, type GeoLookupProvider } from "@/lib/api";+import { isAgentBackendUrl } from "@neko-master/shared";import { toast } from "sonner";import { BackendVerifyAnimation } from "@/components/features/backend/backend-verify-animation";import { BackendListSkeleton } from "@/components/ui/insight-skeleton";@@ -253,7 +256,9 @@ interface Backend {name: string;url: string;host: string;- port: number;+ port?: number;+ mode: BackendMode;+ agentId: string;token: string;type?: 'clash' | 'surge';enabled: boolean;@@ -272,6 +277,18 @@ interface BackendConfigDialogProps {onBackendChange?: () => void;}+interface AgentBootstrapInfo {+ backendId: number;+ agentId: string;+ token: string;+ tokenLocked?: boolean;+ type: 'clash' | 'surge';+ gatewayHost: string;+ gatewayPort: string;+ gatewaySsl: boolean;+ gatewayToken: string;+}+interface DbStats {size: number;totalConnectionsCount: number;@@ -293,26 +310,304 @@ interface RetentionConfig {autoCleanup: boolean;}-// Parse URL to host and port-function parseUrl(url: string): { host: string; port: string; ssl: boolean } {+type BackendMode = "direct" | "agent";++interface ParsedBackendUrl {+ mode: BackendMode;+ host: string;+ port: string;+ ssl: boolean;+ agentId: string;+}++interface BackendFormState {+ name: string;+ mode: BackendMode;+ host: string;+ port: string;+ ssl: boolean;+ token: string;+ type: 'clash' | 'surge';+ agentId: string;+ agentGatewayHost: string;+ agentGatewayPort: string;+ agentGatewaySsl: boolean;+ agentGatewayToken: string;+}++const DEFAULT_BACKEND_PORT = "9090";+const DEFAULT_AGENT_GATEWAY_HOST = "127.0.0.1";+const AGENT_BOOTSTRAP_CONFIG_STORAGE_KEY = "neko-agent-bootstrap-config-v1";++interface AgentGatewayConfig {+ gatewayHost: string;+ gatewayPort: string;+ gatewaySsl: boolean;+ gatewayToken: string;+}++function getDefaultGatewayPort(type: 'clash' | 'surge'): string {+ return type === "surge" ? "9091" : "9090";+}++function getDefaultAgentGatewayConfig(type: 'clash' | 'surge'): AgentGatewayConfig {+ return {+ gatewayHost: DEFAULT_AGENT_GATEWAY_HOST,+ gatewayPort: getDefaultGatewayPort(type),+ gatewaySsl: false,+ gatewayToken: "",+ };+}++function buildGatewayUrl(type: 'clash' | 'surge', host: string, port: string, ssl: boolean): string {+ const normalizedHost = host.trim() || DEFAULT_AGENT_GATEWAY_HOST;+ const normalizedPort = port.trim() || getDefaultGatewayPort(type);+ const protocol = ssl ? "https" : "http";+ return `${protocol}://${normalizedHost}:${normalizedPort}`;+}++function loadAgentGatewayConfig(+ backendId: number,+ type: 'clash' | 'surge',+): AgentGatewayConfig {+ const fallback = getDefaultAgentGatewayConfig(type);+ if (typeof window === "undefined") {+ return fallback;+ }++ try {+ const raw = window.localStorage.getItem(AGENT_BOOTSTRAP_CONFIG_STORAGE_KEY);+ if (!raw) return fallback;+ const parsed = JSON.parse(raw) as Record<string, Partial<AgentGatewayConfig>>;+ const stored = parsed[String(backendId)] || {};+ return {+ gatewayHost: String(stored.gatewayHost || fallback.gatewayHost),+ gatewayPort: String(stored.gatewayPort || fallback.gatewayPort),+ gatewaySsl: Boolean(stored.gatewaySsl),+ gatewayToken: String(stored.gatewayToken || ""),+ };+ } catch {+ return fallback;+ }+}++function saveAgentGatewayConfig(backendId: number, config: AgentGatewayConfig): void {+ if (typeof window === "undefined") {+ return;+ }++ try {+ const raw = window.localStorage.getItem(AGENT_BOOTSTRAP_CONFIG_STORAGE_KEY);+ const parsed = raw+ ? (JSON.parse(raw) as Record<string, Partial<AgentGatewayConfig>>)+ : {};+ parsed[String(backendId)] = {+ gatewayHost: config.gatewayHost.trim() || DEFAULT_AGENT_GATEWAY_HOST,+ gatewayPort: config.gatewayPort.trim(),+ gatewaySsl: config.gatewaySsl,+ gatewayToken: config.gatewayToken,+ };+ window.localStorage.setItem(+ AGENT_BOOTSTRAP_CONFIG_STORAGE_KEY,+ JSON.stringify(parsed),+ );+ } catch {+ // Ignore storage write errors.+ }+}++function sanitizeAgentId(value: string): string {+ const normalized = value+ .trim()+ .replace(/[^a-zA-Z0-9._-]+/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-|-$/g, "");+ return normalized || "agent";+}++function generateAgentMarker(seed: string): string {+ const base = sanitizeAgentId(seed || "agent");+ try {+ const bytes = new Uint8Array(4);+ globalThis.crypto?.getRandomValues?.(bytes);+ const hash = Array.from(bytes)+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("");+ return `${base}-${hash}`;+ } catch {+ const fallback = Math.random().toString(16).slice(2, 10);+ return `${base}-${fallback}`;+ }+}++function getInitialFormState(): BackendFormState {+ return {+ name: "",+ mode: "direct",+ host: "",+ port: DEFAULT_BACKEND_PORT,+ ssl: false,+ token: "",+ type: "clash",+ agentId: "",+ agentGatewayHost: DEFAULT_AGENT_GATEWAY_HOST,+ agentGatewayPort: getDefaultGatewayPort("clash"),+ agentGatewaySsl: false,+ agentGatewayToken: "",+ };+}++function parseAgentId(url: string): string {+ const raw = url.replace(/^agent:\/\//i, "").split(/[/?#]/)[0] || "";+ try {+ return decodeURIComponent(raw);+ } catch {+ return raw;+ }+}++// Parse backend URL for form/view rendering+function parseBackendUrl(url: string): ParsedBackendUrl {+ if (isAgentBackendUrl(url)) {+ return {+ mode: "agent",+ host: "",+ port: "",+ ssl: false,+ agentId: parseAgentId(url),+ };+ }+try {const urlObj = new URL(url);return {+ mode: "direct",host: decodeURIComponent(urlObj.hostname),port: urlObj.port || (urlObj.protocol === "https:" ? "443" : "80"),ssl: urlObj.protocol === "https:",+ agentId: "",};} catch {- return { host: "", port: "9090", ssl: false };+ return {+ mode: "direct",+ host: "",+ port: DEFAULT_BACKEND_PORT,+ ssl: false,+ agentId: "",+ };}}-// Build URL from host, port, ssl-function buildUrl(host: string, port: string, ssl: boolean): string {+function buildDirectUrl(host: string, port: string, ssl: boolean): string {const protocol = ssl ? "https" : "http";return `${protocol}://${host}:${port}`;}+function buildAgentUrl(agentId: string): string {+ return `agent://${sanitizeAgentId(agentId)}`;+}++const AGENT_INSTALL_SCRIPT_URL =+ "https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh";++function getSuggestedServerUrl(): string {+ if (typeof window !== "undefined" && window.location?.origin) {+ return window.location.origin;+ }+ return "http://localhost:3000";+}++function shellQuote(value: string): string {+ return `'${String(value).replace(/'/g, `'\"'\"'`)}'`;+}++function buildAgentRunCommand(info: AgentBootstrapInfo): string {+ let generated = "";+ {+ const gatewayUrlWithConfig = buildGatewayUrl(+ info.type,+ info.gatewayHost,+ info.gatewayPort,+ info.gatewaySsl,+ );+ const backendToken = info.token.trim() || "<backend-token>";+ const lines = [+ "./neko-agent \\",+ " --server-url " + shellQuote(getSuggestedServerUrl()) + " \\",+ " --backend-id " + info.backendId + " \\",+ " --backend-token " + shellQuote(backendToken) + " \\",+ " --gateway-type " + shellQuote(info.type) + " \\",+ " --gateway-url " + shellQuote(gatewayUrlWithConfig),+ ];++ if (info.gatewayToken.trim()) {+ lines[lines.length - 1] = lines[lines.length - 1] + " \\";+ lines.push(" --gateway-token " + shellQuote(info.gatewayToken.trim()));+ }++ generated = lines.join("\n");+ }++ const gatewayUrl =+ info.type === "surge" ? "http://127.0.0.1:9091" : "http://127.0.0.1:9090";++ const _legacy = [+ "./neko-agent \\",+ ` --server-url ${getSuggestedServerUrl()} \\`,+ ` --backend-id ${info.backendId} \\`,+ ` --backend-token ${info.token} \\`,+ ` --gateway-type ${info.type} \\`,+ ` --gateway-url ${gatewayUrl}`,+ ].join("\n");+ void _legacy;+ return generated;+}++function buildAgentInstallScriptCommand(info: AgentBootstrapInfo): string {+ let generated = "";+ {+ const gatewayUrlWithConfig = buildGatewayUrl(+ info.type,+ info.gatewayHost,+ info.gatewayPort,+ info.gatewaySsl,+ );+ const backendToken = info.token.trim() || "<backend-token>";+ const lines = [+ "curl -fsSL " + AGENT_INSTALL_SCRIPT_URL + " \\",+ " | env NEKO_SERVER=" + shellQuote(getSuggestedServerUrl()) + " \\",+ " NEKO_BACKEND_ID=" + shellQuote(String(info.backendId)) + " \\",+ " NEKO_BACKEND_TOKEN=" + shellQuote(backendToken) + " \\",+ " NEKO_GATEWAY_TYPE=" + shellQuote(info.type) + " \\",+ " NEKO_GATEWAY_URL=" + shellQuote(gatewayUrlWithConfig) + " \\",+ ];++ if (info.gatewayToken.trim()) {+ lines.push(+ " NEKO_GATEWAY_TOKEN=" + shellQuote(info.gatewayToken.trim()) + " \\",+ );+ }++ lines.push(" sh");+ generated = lines.join("\n");+ }++ const gatewayUrl =+ info.type === "surge" ? "http://127.0.0.1:9091" : "http://127.0.0.1:9090";++ const _legacy = [+ `curl -fsSL ${AGENT_INSTALL_SCRIPT_URL} \\`,+ ` | env NEKO_SERVER=${shellQuote(getSuggestedServerUrl())} \\`,+ ` NEKO_BACKEND_ID=${shellQuote(String(info.backendId))} \\`,+ ` NEKO_BACKEND_TOKEN=${shellQuote(info.token)} \\`,+ ` NEKO_GATEWAY_TYPE=${shellQuote(info.type)} \\`,+ ` NEKO_GATEWAY_URL=${shellQuote(gatewayUrl)} \\`,+ ` sh`,+ ].join("\n");+ void _legacy;+ return generated;+}+export function BackendConfigDialog({open,onOpenChange,@@ -363,6 +658,12 @@ export function BackendConfigDialog({const [clearDataBackendId, setClearDataBackendId] = useState<number | null>(null,);+ const [agentBootstrapDialogOpen, setAgentBootstrapDialogOpen] =+ useState(false);+ const [agentBootstrapInfo, setAgentBootstrapInfo] =+ useState<AgentBootstrapInfo | null>(null);+ const [rotatingAgentToken, setRotatingAgentToken] = useState(false);+ const [rotateAgentTokenDialogOpen, setRotateAgentTokenDialogOpen] = useState(false);// Error Alert Dialog Stateconst [errorDialogOpen, setErrorDialogOpen] = useState(false);@@ -405,25 +706,16 @@ export function BackendConfigDialog({type: 'clash' | 'surge';} | null>(null);- const [formData, setFormData] = useState({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash" as 'clash' | 'surge',- });+ const [formData, setFormData] = useState<BackendFormState>(+ getInitialFormState(),+ );- const [editFormData, setEditFormData] = useState({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash" as 'clash' | 'surge',- });+ const [editFormData, setEditFormData] = useState<BackendFormState>(+ getInitialFormState(),+ );const [showAddForm, setShowAddForm] = useState(false);+ const [autoOpenedAddDialog, setAutoOpenedAddDialog] = useState(false);useEffect(() => {if (open) {@@ -434,14 +726,39 @@ export function BackendConfigDialog({}}, [open]);+ useEffect(() => {+ if (!open || !isFirstTime || backendsLoading || autoOpenedAddDialog) return;+ if (backends.length === 0) {+ setShowAddForm(true);+ setAutoOpenedAddDialog(true);+ }+ }, [open, isFirstTime, backendsLoading, backends.length, autoOpenedAddDialog]);++ useEffect(() => {+ if (!open) {+ setAutoOpenedAddDialog(false);+ }+ }, [open]);+const loadBackends = async () => {setBackendsLoading(true);try {const data = await api.getBackends();- // Parse URL to host/port for display+ // Parse URL for display/form renderingconst parsedData: Backend[] = data.map((b) => {- const parsed = parseUrl(b.url);- return { ...b, type: b.type || 'clash', host: parsed.host, port: parseInt(parsed.port) || 9090 };+ const parsed = parseBackendUrl(b.url);+ return {+ ...b,+ type: b.type || "clash",+ mode: parsed.mode,+ host: parsed.host,+ port:+ parsed.mode === "direct"+ ? Number.parseInt(parsed.port || DEFAULT_BACKEND_PORT, 10) ||+ Number.parseInt(DEFAULT_BACKEND_PORT, 10)+ : undefined,+ agentId: parsed.agentId,+ };});setBackends(parsedData);} catch (error) {@@ -582,12 +899,70 @@ export function BackendConfigDialog({};const handleAdd = async () => {- if (!formData.name || !formData.host) return;+ const name = formData.name.trim();+ if (!name) return;++ const isAgentMode = formData.mode === "agent";++ if (isAgentMode) {+ const agentId = generateAgentMarker(name);+ setLoading(true);+ try {+ const result = await api.createBackend({+ name,+ url: buildAgentUrl(agentId),+ type: formData.type,+ });++ setFormData(getInitialFormState());+ setShowAddForm(false);+ await loadBackends();+ await onBackendChange?.();++ toast.success(t("agentBackendCreated", { id: result.id }));+ const agentGatewayConfig: AgentGatewayConfig = {+ gatewayHost: formData.agentGatewayHost.trim() || DEFAULT_AGENT_GATEWAY_HOST,+ gatewayPort: formData.agentGatewayPort.trim() || getDefaultGatewayPort(formData.type),+ gatewaySsl: formData.agentGatewaySsl,+ gatewayToken: formData.agentGatewayToken,+ };+ saveAgentGatewayConfig(result.id, agentGatewayConfig);+ if (result.agentToken) {+ setAgentBootstrapInfo({+ backendId: result.id,+ agentId,+ token: result.agentToken,+ tokenLocked: true,+ type: formData.type,+ gatewayHost: agentGatewayConfig.gatewayHost,+ gatewayPort: agentGatewayConfig.gatewayPort,+ gatewaySsl: agentGatewayConfig.gatewaySsl,+ gatewayToken: agentGatewayConfig.gatewayToken,+ });+ setAgentBootstrapDialogOpen(true);+ }+ if (result.isActive) {+ toast.success(t("firstBackendAutoActive"));+ }++ if (isFirstTime && onConfigComplete && !result.agentToken) {+ await onConfigComplete();+ onOpenChange(false);+ }+ } catch (error: any) {+ setErrorMessage(error.message || "Failed to create backend");+ setErrorDialogOpen(true);+ } finally {+ setLoading(false);+ }+ return;+ }- const url = buildUrl(formData.host, formData.port, formData.ssl);+ if (!formData.host.trim()) return;+ const url = buildDirectUrl(formData.host, formData.port, formData.ssl);// Show verification animation immediately- setPendingBackend({ name: formData.name, url, token: formData.token, type: formData.type });+ setPendingBackend({ name, url, token: formData.token, type: formData.type });setVerifyPhase("pending");setVerifyMessage("");setShowVerifyAnimation(true);@@ -623,14 +998,7 @@ export function BackendConfigDialog({type: pendingBackend.type,});- setFormData({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash",- });+ setFormData(getInitialFormState());setShowAddForm(false);setShowVerifyAnimation(false);setPendingBackend(null);@@ -660,28 +1028,30 @@ export function BackendConfigDialog({};const handleUpdate = async (id: number) => {+ const name = editFormData.name.trim();+ if (!name) return;++ const current = backends.find((b) => b.id === id);+ const isAgentMode = editFormData.mode === "agent";+ const token = isAgentMode ? "" : editFormData.token.trim();++ if (!isAgentMode && !editFormData.host.trim()) return;+setLoading(true);try {- const url = buildUrl(- editFormData.host,- editFormData.port,- editFormData.ssl,- );+ const url = isAgentMode+ ? current && isAgentBackendUrl(current.url)+ ? current.url+ : buildAgentUrl(generateAgentMarker(name))+ : buildDirectUrl(editFormData.host, editFormData.port, editFormData.ssl);await api.updateBackend(id, {- name: editFormData.name,+ name,url,- token: editFormData.token || undefined,+ token: token ? token : undefined,type: editFormData.type,});setEditingId(null);- setEditFormData({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash",- });+ setEditFormData(getInitialFormState());await loadBackends();await onBackendChange?.();} catch (error: any) {@@ -777,11 +1147,22 @@ export function BackendConfigDialog({setTestingId(backend.id);try {const result = await api.testBackendById(backend.id);+ const nextHealth: BackendHealth = {+ status: result.success ? "healthy" : "unhealthy",+ lastChecked: Date.now(),+ message: result.message,+ };+ setBackends((prev) =>+ prev.map((item) => (item.id === backend.id ? { ...item, health: nextHealth } : item)),+ );+if (result.success) {toast.success(result.message);} else {toast.error(result.message);}+ await loadBackends();+ await onBackendChange?.();} catch (error: any) {toast.error(error.message || "Test failed");} finally {@@ -811,8 +1192,76 @@ export function BackendConfigDialog({}};+ const copyText = async (text: string, successKey: string) => {+ try {+ await navigator.clipboard.writeText(text);+ toast.success(t(successKey));+ } catch {+ toast.error(commonT("error"));+ }+ };++ const openAgentSetup = (backend: Backend) => {+ const backendType = backend.type || "clash";+ const gatewayConfig = loadAgentGatewayConfig(backend.id, backendType);+ setAgentBootstrapInfo({+ backendId: backend.id,+ agentId: backend.agentId,+ token: "",+ tokenLocked: true,+ type: backendType,+ gatewayHost: gatewayConfig.gatewayHost,+ gatewayPort: gatewayConfig.gatewayPort,+ gatewaySsl: gatewayConfig.gatewaySsl,+ gatewayToken: gatewayConfig.gatewayToken,+ });+ setAgentBootstrapDialogOpen(true);+ };++ const handleRotateAgentToken = async () => {+ if (!agentBootstrapInfo) return;++ setRotatingAgentToken(true);+ try {+ const result = await api.rotateAgentToken(agentBootstrapInfo.backendId);+ setAgentBootstrapInfo({+ ...agentBootstrapInfo,+ token: result.agentToken,+ tokenLocked: true,+ });+ toast.success(t("agentRotateTokenSuccess"));+ await loadBackends();+ await onBackendChange?.();+ setRotateAgentTokenDialogOpen(false);+ } catch (error: unknown) {+ const message = error instanceof Error ? error.message : t("agentRotateTokenFailed");+ toast.error(message || t("agentRotateTokenFailed"));+ } finally {+ setRotatingAgentToken(false);+ }+ };++ const closeAgentBootstrapDialog = async () => {+ if (agentBootstrapInfo) {+ saveAgentGatewayConfig(agentBootstrapInfo.backendId, {+ gatewayHost: agentBootstrapInfo.gatewayHost,+ gatewayPort: agentBootstrapInfo.gatewayPort,+ gatewaySsl: agentBootstrapInfo.gatewaySsl,+ gatewayToken: agentBootstrapInfo.gatewayToken,+ });+ }+ setAgentBootstrapDialogOpen(false);+ setAgentBootstrapInfo(null);+ if (isFirstTime && onConfigComplete) {+ await onConfigComplete();+ onOpenChange(false);+ }+ };+const [isTokenInvalid, setIsTokenInvalid] = useState(false);const tokenInputRef = useRef<HTMLInputElement>(null);+ const editingBackend =+ editingId !== null ? backends.find((backend) => backend.id === editingId) || null : null;// Validate token formatconst isValidToken = (token: string): boolean => {@@ -904,25 +1353,24 @@ export function BackendConfigDialog({setEditingId(backend.id);setEditFormData({name: backend.name,- host: backend.host,- port: String(backend.port || 9090),- ssl: backend.url.startsWith("https"),+ mode: backend.mode,+ host: backend.host || "",+ port: String(backend.port || DEFAULT_BACKEND_PORT),+ ssl: backend.mode === "direct" && backend.url.startsWith("https"),token: "",type: backend.type || "clash",+ agentId: backend.agentId || "",+ agentGatewayHost: DEFAULT_AGENT_GATEWAY_HOST,+ agentGatewayPort: getDefaultGatewayPort(backend.type || "clash"),+ agentGatewaySsl: false,+ agentGatewayToken: "",});setShowAddForm(false);};const cancelEdit = () => {setEditingId(null);- setEditFormData({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash",- });+ setEditFormData(getInitialFormState());};if (!open) return null;@@ -1002,7 +1450,7 @@ export function BackendConfigDialog({: "border-border bg-card",!backend.enabled && "opacity-60",)}>- {editingId === backend.id ? (+ {false && editingId === backend.id ? (// Edit Mode<div className="space-y-3"><div className="grid grid-cols-2 gap-3">@@ -1024,66 +1472,96 @@ export function BackendConfigDialog({</div><div><label className="text-xs font-medium">- {t("type")}+ {t("connectionMode")}</label><select- value={editFormData.type}+ value={editFormData.mode}onChange={(e) =>- setEditFormData({ ...editFormData, type: e.target.value as 'clash' | 'surge' })+ setEditFormData({+ ...editFormData,+ mode: e.target.value as BackendMode,+ })}className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">- <option value="clash">Clash / Mihomo</option>- <option value="surge">Surge</option>+ <option value="direct">{t("modeDirect")}</option>+ <option value="agent">{t("modeAgent")}</option></select></div></div>- <div className="grid grid-cols-2 gap-3">- <div>- <label className="text-xs font-medium">- {t("host")}- </label>- <Input- value={editFormData.host}- onChange={(e) =>- setEditFormData({- ...editFormData,- host: e.target.value,- })- }- placeholder="192.168.1.1"- className="h-9 mt-1"- />- </div>+ <div+ className={cn(+ "grid gap-3",+ editFormData.mode === "direct" ? "grid-cols-2" : "grid-cols-1",+ )}><div><label className="text-xs font-medium">- {t("port")}+ {t("type")}</label>- <Input- value={editFormData.port}+ <select+ value={editFormData.type}onChange={(e) =>- setEditFormData({- ...editFormData,- port: e.target.value,- })+ setEditFormData({ ...editFormData, type: e.target.value as 'clash' | 'surge' })}- placeholder="9090"- className="h-9 mt-1"- />+ className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <option value="clash">Clash / Mihomo</option>+ <option value="surge">Surge</option>+ </select></div>+ {editFormData.mode === "direct" && (+ <div>+ <label className="text-xs font-medium">+ {t("host")}+ </label>+ <Input+ value={editFormData.host}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ host: e.target.value,+ })+ }+ placeholder="192.168.1.1"+ className="h-9 mt-1"+ />+ </div>+ )}</div>- <div className="flex items-center gap-2">- <Switch- checked={editFormData.ssl}- onCheckedChange={(checked) =>- setEditFormData({- ...editFormData,- ssl: checked,- })- }- />- <label className="text-sm">{t("useSsl")}</label>- </div>+ {editFormData.mode === "direct" && (+ <>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">+ {t("port")}+ </label>+ <Input+ value={editFormData.port}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ port: e.target.value,+ })+ }+ placeholder={DEFAULT_BACKEND_PORT}+ className="h-9 mt-1"+ />+ </div>+ <div className="flex items-center gap-2 pt-6">+ <Switch+ checked={editFormData.ssl}+ onCheckedChange={(checked) =>+ setEditFormData({+ ...editFormData,+ ssl: checked,+ })+ }+ />+ <label className="text-sm">{t("useSsl")}</label>+ </div>+ </div>+ </>+ )}<div><label className="text-xs font-medium">{t("token")}@@ -1100,10 +1578,19 @@ export function BackendConfigDialog({placeholder={backend.hasToken? t("tokenKeepPlaceholder")- : t("tokenPlaceholder")+ : editFormData.mode === "agent"+ ? t("tokenRequiredPlaceholder")+ : editFormData.type === "surge"+ ? t("tokenPlaceholderSurge")+ : t("tokenPlaceholder")}className="h-9 mt-1"/>+ {editFormData.mode === "agent" && (+ <p className="text-[11px] text-muted-foreground mt-1">+ {t("agentTokenHint")}+ </p>+ )}</div><div className="flex gap-2 justify-end"><Button@@ -1131,6 +1618,11 @@ export function BackendConfigDialog({<span className="font-medium text-base">{backend.name}</span>+ <span className="px-2 py-0.5 rounded-full bg-muted text-muted-foreground text-[10px] font-medium uppercase tracking-wide">+ {backend.mode === "agent"+ ? t("modeAgent")+ : t("modeDirect")}+ </span>{/* Backend Type Icon */}<divclassName="w-4 h-4 rounded-sm bg-white/90 flex items-center justify-center p-0.5"@@ -1150,8 +1642,14 @@ export function BackendConfigDialog({</div><divclassName="text-sm text-muted-foreground mt-1 break-all sm:break-normal sm:truncate"- title={`${backend.host}:${backend.port}`}>- {backend.host}:{backend.port}+ title={+ backend.mode === "agent"+ ? backend.url+ : `${backend.host}:${backend.port}`+ }>+ {backend.mode === "agent"+ ? `${backend.url} ยท #${backend.id}`+ : `${backend.host}:${backend.port}`}</div></div>@@ -1247,6 +1745,28 @@ export function BackendConfigDialog({</Tooltip></TooltipProvider>+ {backend.mode === "agent" && (+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={() => openAgentSetup(backend)}+ title={t("openAgentSetup")}+ disabled={isShowcase}>+ <Terminal className="w-4 h-4" />+ </Button>+ )}+ {backend.mode !== "agent" && (+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8 invisible pointer-events-none"+ tabIndex={-1}+ aria-hidden="true">+ <Terminal className="w-4 h-4" />+ </Button>+ )}+<Buttonvariant="ghost"size="icon"@@ -1276,7 +1796,7 @@ export function BackendConfigDialog({)}{/* Add New Backend */}- {showAddForm || (isFirstTime && backends.length === 0) ? (+ {false && (showAddForm || (isFirstTime && backends.length === 0)) ? (<div className="p-4 rounded-lg border border-dashed border-border bg-muted/50"><h4 className="text-sm font-medium mb-3 flex items-center gap-2"><Plus className="w-4 h-4" />@@ -1298,7 +1818,10 @@ export function BackendConfigDialog({<Inputvalue={formData.name}onChange={(e) =>- setFormData({ ...formData, name: e.target.value })+ setFormData({+ ...formData,+ name: e.target.value,+ })}placeholder={t("namePlaceholder")}className="h-9 mt-1"@@ -1306,85 +1829,188 @@ export function BackendConfigDialog({</div><div><label className="text-xs font-medium">- {t("type")}+ {t("connectionMode")}</label><select- value={formData.type}+ value={formData.mode}onChange={(e) =>- setFormData({ ...formData, type: e.target.value as 'clash' | 'surge' })+ setFormData({+ ...formData,+ mode: e.target.value as BackendMode,+ })}className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">- <option value="clash">Clash / Mihomo</option>- <option value="surge">Surge</option>+ <option value="direct">{t("modeDirect")}</option>+ <option value="agent">{t("modeAgent")}</option></select></div></div>- <div className="grid grid-cols-2 gap-3">+ <div+ className={cn(+ "grid gap-3",+ formData.mode === "direct" ? "grid-cols-2" : "grid-cols-1",+ )}><div><label className="text-xs font-medium">- {t("host")} *+ {t("type")}</label>- <Input- value={formData.host}- onChange={(e) =>- setFormData({ ...formData, host: e.target.value })- }- placeholder="192.168.1.1"- className="h-9 mt-1"- />+ <select+ value={formData.type}+ onChange={(e) => {+ const nextType = e.target.value as 'clash' | 'surge';+ const currentDefaultPort = getDefaultGatewayPort(formData.type);+ const nextDefaultPort = getDefaultGatewayPort(nextType);+ setFormData({+ ...formData,+ type: nextType,+ agentGatewayPort:+ formData.agentGatewayPort === currentDefaultPort+ ? nextDefaultPort+ : formData.agentGatewayPort,+ });+ }}+ className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <option value="clash">Clash / Mihomo</option>+ <option value="surge">Surge</option>+ </select>+ </div>+ {formData.mode === "direct" && (+ <div>+ <label className="text-xs font-medium">+ {t("host")} *+ </label>+ <Input+ value={formData.host}+ onChange={(e) =>+ setFormData({+ ...formData,+ host: e.target.value,+ })+ }+ placeholder="192.168.1.1"+ className="h-9 mt-1"+ />+ </div>+ )}+ </div>+ {formData.mode === "direct" && (+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">+ {t("port")}+ </label>+ <Input+ value={formData.port}+ onChange={(e) =>+ setFormData({+ ...formData,+ port: e.target.value,+ })+ }+ placeholder={DEFAULT_BACKEND_PORT}+ className="h-9 mt-1"+ />+ </div>+ <div className="flex items-center gap-2 pt-6">+ <Switch+ checked={formData.ssl}+ onCheckedChange={(checked) =>+ setFormData({ ...formData, ssl: checked })+ }+ />+ <label className="text-sm">{t("useSsl")}</label>+ </div></div>+ )}+ {formData.mode === "direct" ? (<div><label className="text-xs font-medium">- {t("port")}+ {t("token")}</label><Input- value={formData.port}+ type="password"+ value={formData.token}onChange={(e) =>- setFormData({ ...formData, port: e.target.value })+ setFormData({ ...formData, token: e.target.value })+ }+ placeholder={+ formData.type === "surge"+ ? t("tokenPlaceholderSurge")+ : t("tokenPlaceholder")}- placeholder="9090"className="h-9 mt-1"/></div>- </div>- <div className="flex items-center gap-2">- <Switch- checked={formData.ssl}- onCheckedChange={(checked) =>- setFormData({ ...formData, ssl: checked })- }- />- <label className="text-sm">{t("useSsl")}</label>- </div>- <div>- <label className="text-xs font-medium">- {t("token")}- </label>- <Input- type="password"- value={formData.token}- onChange={(e) =>- setFormData({ ...formData, token: e.target.value })- }- placeholder={formData.type === 'surge' ? t("tokenPlaceholderSurge") || "Surge API Key (x-key)" : t("tokenPlaceholder")}- className="h-9 mt-1"- />- </div>+ ) : (+ <div className="space-y-3 rounded-md border border-dashed p-3">+ <p className="text-[11px] text-muted-foreground">+ {t("agentTokenAutoHint")}+ </p>+ <p className="text-[11px] text-muted-foreground">+ {t("agentGatewayOptionalHint")}+ </p>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">+ {t("host")}+ </label>+ <Input+ value={formData.agentGatewayHost}+ onChange={(e) =>+ setFormData({+ ...formData,+ agentGatewayHost: e.target.value,+ })+ }+ placeholder={DEFAULT_AGENT_GATEWAY_HOST}+ className="h-9 mt-1"+ />+ </div>+ <div>+ <label className="text-xs font-medium">+ {t("port")}+ </label>+ <Input+ value={formData.agentGatewayPort}+ onChange={(e) =>+ setFormData({+ ...formData,+ agentGatewayPort: e.target.value,+ })+ }+ placeholder={getDefaultGatewayPort(formData.type)}+ className="h-9 mt-1"+ />+ </div>+ </div>+ <div>+ <label className="text-xs font-medium">+ {t("gatewayToken")}+ </label>+ <Input+ type="password"+ value={formData.agentGatewayToken}+ onChange={(e) =>+ setFormData({+ ...formData,+ agentGatewayToken: e.target.value,+ })+ }+ placeholder={t("agentGatewayTokenPlaceholder")}+ className="h-9 mt-1"+ />+ </div>+ </div>+ )}<div className="flex gap-2">{backends.length > 0 && (<Buttonvariant="ghost"onClick={() => {setShowAddForm(false);- setFormData({- name: "",- host: "",- port: "9090",- ssl: false,- token: "",- type: "clash",- });+ setFormData(getInitialFormState());}}className="flex-shrink-0"><X className="w-4 h-4 mr-2" />@@ -1393,7 +2019,11 @@ export function BackendConfigDialog({)}<ButtononClick={handleAdd}- disabled={loading || !formData.name || !formData.host}+ disabled={+ loading ||+ !formData.name.trim() ||+ (formData.mode === "direct" && !formData.host.trim())+ }className="flex-1"><Plus className="w-4 h-4 mr-2" />{isFirstTime && backends.length === 0@@ -1404,20 +2034,21 @@ export function BackendConfigDialog({</div>)}</div>- ) : backends.length > 0 ? (+ ) : (!isShowcase && (<Buttonvariant="outline"className="w-full border-dashed"onClick={() => {cancelEdit();+ setFormData(getInitialFormState());setShowAddForm(true);}}><Plus className="w-4 h-4 mr-2" />{t("addNew")}</Button>)- ) : null}+ )}</div>) : activeTab === "preferences" ? (<div className="space-y-6">@@ -1796,6 +2427,355 @@ export function BackendConfigDialog({</Card></div>+ <Dialog+ open={editingId !== null}+ onOpenChange={(open) => {+ if (!open) {+ cancelEdit();+ }+ }}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{commonT("edit")}</DialogTitle>+ <DialogDescription>{t("description")}</DialogDescription>+ </DialogHeader>+ <div className="space-y-3 py-2">+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">{t("name")}</label>+ <Input+ value={editFormData.name}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ name: e.target.value,+ })+ }+ placeholder={t("namePlaceholder")}+ className="h-9 mt-1"+ />+ </div>+ <div>+ <label className="text-xs font-medium">{t("connectionMode")}</label>+ <select+ value={editFormData.mode}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ mode: e.target.value as BackendMode,+ })+ }+ className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">+ <option value="direct">{t("modeDirect")}</option>+ <option value="agent">{t("modeAgent")}</option>+ </select>+ </div>+ </div>++ <div+ className={cn(+ "grid gap-3",+ editFormData.mode === "direct" ? "grid-cols-2" : "grid-cols-1",+ )}>+ <div>+ <label className="text-xs font-medium">{t("type")}</label>+ <select+ value={editFormData.type}+ onChange={(e) =>+ setEditFormData({ ...editFormData, type: e.target.value as 'clash' | 'surge' })+ }+ disabled+ className="h-9 mt-1 w-full rounded-md border border-input bg-muted px-3 py-1 text-sm text-muted-foreground shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed">+ <option value="clash">Clash / Mihomo</option>+ <option value="surge">Surge</option>+ </select>+ </div>+ {editFormData.mode === "direct" && (+ <div>+ <label className="text-xs font-medium">{t("host")}</label>+ <Input+ value={editFormData.host}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ host: e.target.value,+ })+ }+ placeholder="192.168.1.1"+ className="h-9 mt-1"+ />+ </div>+ )}+ </div>++ {editFormData.mode === "direct" && (+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">{t("port")}</label>+ <Input+ value={editFormData.port}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ port: e.target.value,+ })+ }+ placeholder={DEFAULT_BACKEND_PORT}+ className="h-9 mt-1"+ />+ </div>+ <div className="flex items-center gap-2 pt-6">+ <Switch+ checked={editFormData.ssl}+ onCheckedChange={(checked) =>+ setEditFormData({+ ...editFormData,+ ssl: checked,+ })+ }+ />+ <label className="text-sm">{t("useSsl")}</label>+ </div>+ </div>+ )}++ {editFormData.mode === "direct" ? (+ <div>+ <label className="text-xs font-medium">{t("token")}</label>+ <Input+ type="password"+ value={editFormData.token}+ onChange={(e) =>+ setEditFormData({+ ...editFormData,+ token: e.target.value,+ })+ }+ placeholder={+ editingBackend?.hasToken+ ? t("tokenKeepPlaceholder")+ : editFormData.type === "surge"+ ? t("tokenPlaceholderSurge")+ : t("tokenPlaceholder")+ }+ className="h-9 mt-1"+ />+ </div>+ ) : (+ <p className="text-[11px] text-muted-foreground">{t("agentTokenManagedHint")}</p>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={cancelEdit}>+ {commonT("cancel")}+ </Button>+ <Button+ onClick={() => editingId && handleUpdate(editingId)}+ disabled={loading || editingId === null}>+ {commonT("save")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog+ open={showAddForm}+ onOpenChange={(open) => {+ if (!open) {+ setShowAddForm(false);+ setFormData(getInitialFormState());+ }+ }}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{t("addNew")}</DialogTitle>+ <DialogDescription>{t("description")}</DialogDescription>+ </DialogHeader>+ <div className="space-y-3 py-2">+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">{t("name")} *</label>+ <Input+ value={formData.name}+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}+ placeholder={t("namePlaceholder")}+ className="h-9 mt-1"+ />+ </div>+ <div>+ <label className="text-xs font-medium">{t("connectionMode")}</label>+ <select+ value={formData.mode}+ onChange={(e) =>+ setFormData({ ...formData, mode: e.target.value as BackendMode })+ }+ className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">+ <option value="direct">{t("modeDirect")}</option>+ <option value="agent">{t("modeAgent")}</option>+ </select>+ </div>+ </div>++ <div className={cn("grid gap-3", formData.mode === "direct" ? "grid-cols-2" : "grid-cols-1")}>+ <div>+ <label className="text-xs font-medium">{t("type")}</label>+ <select+ value={formData.type}+ onChange={(e) => {+ const nextType = e.target.value as 'clash' | 'surge';+ const currentDefaultPort = getDefaultGatewayPort(formData.type);+ const nextDefaultPort = getDefaultGatewayPort(nextType);+ setFormData({+ ...formData,+ type: nextType,+ agentGatewayPort:+ formData.agentGatewayPort === currentDefaultPort+ ? nextDefaultPort+ : formData.agentGatewayPort,+ });+ }}+ className="h-9 mt-1 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">+ <option value="clash">Clash / Mihomo</option>+ <option value="surge">Surge</option>+ </select>+ </div>+ {formData.mode === "direct" && (+ <div>+ <label className="text-xs font-medium">{t("host")} *</label>+ <Input+ value={formData.host}+ onChange={(e) => setFormData({ ...formData, host: e.target.value })}+ placeholder="192.168.1.1"+ className="h-9 mt-1"+ />+ </div>+ )}+ </div>++ {formData.mode === "direct" ? (+ <>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">{t("port")}</label>+ <Input+ value={formData.port}+ onChange={(e) => setFormData({ ...formData, port: e.target.value })}+ placeholder={DEFAULT_BACKEND_PORT}+ className="h-9 mt-1"+ />+ </div>+ <div className="flex items-center gap-2 pt-6">+ <Switch+ checked={formData.ssl}+ onCheckedChange={(checked) => setFormData({ ...formData, ssl: checked })}+ />+ <label className="text-sm">{t("useSsl")}</label>+ </div>+ </div>+ <div>+ <label className="text-xs font-medium">{t("token")}</label>+ <Input+ type="password"+ value={formData.token}+ onChange={(e) => setFormData({ ...formData, token: e.target.value })}+ placeholder={+ formData.type === "surge" ? t("tokenPlaceholderSurge") : t("tokenPlaceholder")+ }+ className="h-9 mt-1"+ />+ </div>+ </>+ ) : (+ <div className="space-y-3 rounded-md border border-dashed p-3">+ <p className="text-[11px] text-muted-foreground">{t("agentTokenAutoHint")}</p>+ <p className="text-[11px] text-muted-foreground">{t("agentGatewayOptionalHint")}</p>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs font-medium">{t("host")}</label>+ <Input+ value={formData.agentGatewayHost}+ onChange={(e) => setFormData({ ...formData, agentGatewayHost: e.target.value })}+ placeholder={DEFAULT_AGENT_GATEWAY_HOST}+ className="h-9 mt-1"+ />+ </div>+ <div>+ <label className="text-xs font-medium">{t("port")}</label>+ <Input+ value={formData.agentGatewayPort}+ onChange={(e) => setFormData({ ...formData, agentGatewayPort: e.target.value })}+ placeholder={getDefaultGatewayPort(formData.type)}+ className="h-9 mt-1"+ />+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Switch+ checked={formData.agentGatewaySsl}+ onCheckedChange={(checked) => setFormData({ ...formData, agentGatewaySsl: checked })}+ />+ <label className="text-xs font-medium">{t("useSsl")}</label>+ </div>+ <div>+ <label className="text-xs font-medium">{t("gatewayToken")}</label>+ <Input+ type="password"+ value={formData.agentGatewayToken}+ onChange={(e) => setFormData({ ...formData, agentGatewayToken: e.target.value })}+ placeholder={t("agentGatewayTokenPlaceholder")}+ className="h-9 mt-1"+ />+ </div>+ </div>+ )}+ </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => {+ setShowAddForm(false);+ setFormData(getInitialFormState());+ }}>+ {commonT("cancel")}+ </Button>+ <Button+ onClick={handleAdd}+ disabled={+ loading || !formData.name.trim() || (formData.mode === "direct" && !formData.host.trim())+ }>+ <Plus className="w-4 h-4 mr-2" />+ {isFirstTime && backends.length === 0 ? t("saveAndContinue") : t("addBackend")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <AlertDialog+ open={rotateAgentTokenDialogOpen}+ onOpenChange={setRotateAgentTokenDialogOpen}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("rotateAgentToken")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("agentRotateTokenConfirm")}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={rotatingAgentToken}>+ {commonT("cancel")}+ </AlertDialogCancel>+ <AlertDialogAction+ onClick={() => void handleRotateAgentToken()}+ disabled={rotatingAgentToken}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {rotatingAgentToken ? t("rotating") : t("rotateAgentToken")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+{/* Delete Confirmation Dialog */}<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}><AlertDialogContent>@@ -2001,6 +2981,263 @@ export function BackendConfigDialog({</DialogContent></Dialog>+ {/* Agent Bootstrap Dialog */}+ <Dialog+ open={agentBootstrapDialogOpen}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) {+ void closeAgentBootstrapDialog();+ return;+ }+ setAgentBootstrapDialogOpen(true);+ }}>+ <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-hidden p-0">+ <DialogHeader className="px-6 pt-6 pb-2 border-b">+ <DialogTitle>{t("agentSetupTitle")}</DialogTitle>+ <DialogDescription>+ {t("agentSetupDescription", {+ id: agentBootstrapInfo?.backendId ?? 0,+ })}+ </DialogDescription>+ </DialogHeader>++ <div className="max-h-[calc(90vh-180px)] overflow-y-auto px-6 py-4">+ {agentBootstrapInfo && (+ <div className="space-y-4">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="space-y-1">+ <label className="text-sm font-medium">{t("backendId")}</label>+ <div className="flex items-center gap-2">+ <Input+ readOnly+ disabled+ value={String(agentBootstrapInfo.backendId)}+ className="font-mono text-xs"+ />+ <Button+ variant="outline"+ size="icon"+ onClick={() =>+ void copyText(+ String(agentBootstrapInfo.backendId),+ "agentInfoCopied",+ )+ }+ title={t("copyBackendId")}>+ <Copy className="w-4 h-4" />+ </Button>+ </div>+ </div>+ <div className="space-y-1">+ <label className="text-sm font-medium">{t("agentId")}</label>+ <div className="flex items-center gap-2">+ <Input+ readOnly+ disabled+ value={agentBootstrapInfo.agentId || "-"}+ className="font-mono text-xs"+ />+ <Button+ variant="outline"+ size="icon"+ onClick={() =>+ void copyText(agentBootstrapInfo.agentId, "agentInfoCopied")+ }+ title={t("copyAgentId")}+ disabled={!agentBootstrapInfo.agentId.trim()}>+ <Copy className="w-4 h-4" />+ </Button>+ </div>+ </div>+ </div>++ <div className="space-y-1">+ <label className="text-sm font-medium">{t("token")}</label>+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">+ <Input+ readOnly+ disabled+ value={agentBootstrapInfo.token}+ placeholder={t("agentTokenHidden")}+ className="font-mono text-xs"+ />+ <Button+ variant="outline"+ size="icon"+ onClick={() =>+ void copyText(+ agentBootstrapInfo.token,+ "agentTokenCopied",+ )+ }+ title={t("copyAgentToken")}+ disabled={!agentBootstrapInfo.token.trim()}>+ <Copy className="w-4 h-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setRotateAgentTokenDialogOpen(true)}+ disabled={rotatingAgentToken}+ className="w-full sm:w-auto"+ >+ {rotatingAgentToken ? t("rotating") : t("rotateAgentToken")}+ </Button>+ </div>+ <p className="text-[11px] text-muted-foreground">+ {agentBootstrapInfo.token+ ? t("agentTokenRotateHint")+ : t("agentTokenUnavailableHint")}+ </p>+ </div>++ <div className="space-y-3 rounded-md border border-dashed p-3">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t("agentGatewaySectionTitle")}</p>+ <p className="text-[11px] text-muted-foreground">{t("agentGatewaySectionHint")}</p>+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label className="text-sm font-medium">{t("type")}</label>+ <select+ value={agentBootstrapInfo.type}+ disabled+ className="h-9 mt-1 w-full rounded-md border border-input bg-muted px-3 py-1 text-sm text-muted-foreground shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed">+ <option value="clash">Clash / Mihomo</option>+ <option value="surge">Surge</option>+ </select>+ </div>+ <div>+ <label className="text-sm font-medium">{t("host")}</label>+ <Input+ value={agentBootstrapInfo.gatewayHost}+ onChange={(e) =>+ setAgentBootstrapInfo({+ ...agentBootstrapInfo,+ gatewayHost: e.target.value,+ })+ }+ placeholder={DEFAULT_AGENT_GATEWAY_HOST}+ className="h-9 mt-1"+ />+ </div>+ <div>+ <label className="text-sm font-medium">{t("port")}</label>+ <Input+ value={agentBootstrapInfo.gatewayPort}+ onChange={(e) =>+ setAgentBootstrapInfo({+ ...agentBootstrapInfo,+ gatewayPort: e.target.value,+ })+ }+ placeholder={getDefaultGatewayPort(agentBootstrapInfo.type)}+ className="h-9 mt-1"+ />+ </div>+ <div className="flex items-center gap-2 sm:pt-7">+ <Switch+ checked={agentBootstrapInfo.gatewaySsl}+ onCheckedChange={(checked) =>+ setAgentBootstrapInfo({+ ...agentBootstrapInfo,+ gatewaySsl: checked,+ })+ }+ />+ <label className="text-sm font-medium">{t("useSsl")}</label>+ </div>+ </div>+ <div>+ <label className="text-sm font-medium">{t("gatewayToken")}</label>+ <Input+ type="text"+ value={agentBootstrapInfo.gatewayToken}+ onChange={(e) =>+ setAgentBootstrapInfo({+ ...agentBootstrapInfo,+ gatewayToken: e.target.value,+ })+ }+ placeholder={t("agentGatewayTokenPlaceholder")}+ className="h-9 mt-1 font-mono"+ />+ </div>+ </div>++ <div className="space-y-1">+ <label className="text-sm font-medium">+ {t("agentCommand")}+ </label>+ <textarea+ readOnly+ value={buildAgentRunCommand(agentBootstrapInfo)}+ className="w-full min-h-[120px] sm:min-h-[150px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"+ />+ {!agentBootstrapInfo.token.trim() && (+ <p className="text-[11px] text-muted-foreground">+ {t("agentTokenGenerateFirstHint")}+ </p>+ )}+ <div className="flex justify-end">+ <Button+ variant="outline"+ size="sm"+ className="w-full sm:w-auto"+ disabled={!agentBootstrapInfo.token.trim()}+ onClick={() =>+ void copyText(+ buildAgentRunCommand(agentBootstrapInfo),+ "agentCommandCopied",+ )+ }>+ <Copy className="w-4 h-4 mr-2" />+ {t("copyAgentCommand")}+ </Button>+ </div>+ </div>++ <div className="space-y-1">+ <label className="text-sm font-medium">+ {t("agentInstallScriptCommand")}+ </label>+ <textarea+ readOnly+ value={buildAgentInstallScriptCommand(agentBootstrapInfo)}+ className="w-full min-h-[140px] sm:min-h-[170px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"+ />+ <p className="text-[11px] text-muted-foreground">+ {t("agentInstallScriptHint")}+ </p>+ <div className="flex justify-end">+ <Button+ variant="outline"+ size="sm"+ className="w-full sm:w-auto"+ disabled={!agentBootstrapInfo.token.trim()}+ onClick={() =>+ void copyText(+ buildAgentInstallScriptCommand(agentBootstrapInfo),+ "agentInstallScriptCopied",+ )+ }>+ <Copy className="w-4 h-4 mr-2" />+ {t("copyAgentInstallScript")}+ </Button>+ </div>+ </div>+ </div>+ )}+ </div>++ <DialogFooter className="px-6 py-4 border-t">+ <Button onClick={() => void closeAgentBootstrapDialog()}>+ {commonT("confirm")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+{/* Verification Animation */}<BackendVerifyAnimationshow={showVerifyAnimation}diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex b8d4881..25f3db8 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -522,7 +522,7 @@ export const api = {fetchJson<Backend[]>(`${API_BASE}/backends`),createBackend: (backend: { name: string; url: string; token?: string; type?: 'clash' | 'surge' }) =>- fetchJson<{ id: number; isActive?: boolean; message: string }>(`${API_BASE}/backends`, 'POST', backend),+ fetchJson<{ id: number; isActive?: boolean; message: string; agentToken?: string }>(`${API_BASE}/backends`, 'POST', backend),updateBackend: (id: number, backend: { name?: string; url?: string; token?: string; type?: 'clash' | 'surge'; enabled?: boolean; listening?: boolean }) =>fetchJson<{ message: string }>(`${API_BASE}/backends/${id}`, 'PUT', backend),@@ -544,6 +544,9 @@ export const api = {testBackendById: (id: number) =>fetchJson<{ success: boolean; message: string }>(`${API_BASE}/backends/${id}/test`, 'POST'),++ rotateAgentToken: (id: number) =>+ fetchJson<{ message: string; agentToken: string }>(`${API_BASE}/backends/${id}/rotate-agent-token`, 'POST'),// Database managementgetDbStats: async () => {diff --git a/apps/web/messages/en.json b/apps/web/messages/en.jsonindex 29be02e..d077087 100644--- a/apps/web/messages/en.json+++ b/apps/web/messages/en.json@@ -368,9 +368,57 @@"token": "Auth Token","useSsl": "Use HTTPS","namePlaceholder": "e.g., Router",+ "connectionMode": "Connection Mode",+ "modeDirect": "Direct",+ "modeAgent": "Agent","type": "Type",+ "backendId": "Backend ID",+ "agentId": "Agent ID","tokenPlaceholder": "Optional, if set please fill in",+ "tokenRequiredPlaceholder": "Required","tokenPlaceholderSurge": "Surge API Key (x-key)",+ "agentTokenHint": "Use the same token in agent flag --backend-token.",+ "agentModeHint": "Agent mode does not connect to LAN directly. Create first, then run neko-agent with backend-id and this token.",+ "agentTokenAutoHint": "Backend token is generated automatically after creation and shown once for copy.",+ "agentTokenRequired": "Backend token is required in agent mode",+ "agentBackendCreated": "Agent backend created (ID #{id})",+ "agentSetupTitle": "Agent Setup",+ "agentSetupDescription": "Backend #{id} created. Copy the token and startup command below.",+ "copyAgentToken": "Copy token",+ "agentTokenCopied": "Agent token copied",+ "agentCommand": "Run Command",+ "copyAgentCommand": "Copy Command",+ "agentCommandCopied": "Agent command copied",+ "agentInstallScriptCommand": "Install Script Command (curl | sh)",+ "agentInstallScriptHint": "Optional: set NEKO_GATEWAY_TOKEN before `sh` when your gateway API has auth.",+ "copyAgentInstallScript": "Copy Install Script",+ "agentInstallScriptCopied": "Install script command copied",+ "agentInfoCopied": "Agent info copied",+ "copyBackendId": "Copy backend ID",+ "copyAgentId": "Copy agent ID",+ "agentTokenPlaceholder": "Paste backend-token to generate full scripts",+ "agentTokenEditHint": "Please fill backend-token manually.",+ "agentTokenInputHint": "You can paste backend-token to generate scripts (it is not saved to backend settings).",+ "agentTokenManagedHint": "Agent token is system-managed. Use \"View Agent Script\" to rotate token.",+ "agentTokenHidden": "Token hidden",+ "agentTokenUnavailableHint": "Historical token is not shown. Click \"Rotate Token\" to generate a new random token.",+ "agentTokenMissingHint": "backend-token is empty, scripts will use the `backend-token` placeholder.",+ "agentTokenGenerateFirstHint": "Click \"Rotate Token\" to generate a new random token before copying full scripts.",+ "rotateAgentToken": "Rotate Token",+ "rotating": "Rotating...",+ "agentTokenRotateHint": "Rotating token invalidates old agents. Update token and restart the agent.",+ "agentRotateTokenConfirm": "Rotate this agent token now? Existing agents using the old token will be disconnected until reconfigured.",+ "agentRotateTokenSuccess": "Agent token rotated. Update and restart your agent.",+ "agentRotateTokenFailed": "Failed to rotate agent token",+ "agentTokenLocalOnlyHint": "This token input is only used for script generation.",+ "openAgentSetup": "View Agent Script",+ "agentGatewayOptionalHint": "Optional: fill gateway host / port / token and copied scripts will include them.",+ "agentGatewaySectionTitle": "Gateway Connection Params (Used in Scripts)",+ "agentGatewaySectionHint": "These values are included when generating run and install scripts.",+ "gatewayToken": "Gateway Token",+ "showGatewayToken": "Show gateway token",+ "hideGatewayToken": "Hide gateway token",+ "agentGatewayTokenPlaceholder": "Optional, e.g. Clash secret or Surge x-key","tokenKeepPlaceholder": "Token already set, leave blank to keep","active": "Active","disabled": "Disabled",diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.jsonindex c9194bc..8fb2783 100644--- a/apps/web/messages/zh.json+++ b/apps/web/messages/zh.json@@ -367,9 +367,57 @@"token": "่ฎค่ฏไปค็","useSsl": "ไฝฟ็จ HTTPS","namePlaceholder": "ไพๅฆ๏ผ่ทฏ็ฑๅจ",+ "connectionMode": "่ฟๆฅๆจกๅผ",+ "modeDirect": "็ด่ฟ",+ "modeAgent": "Agent","type": "็ฑปๅ",+ "backendId": "ๅ็ซฏ ID",+ "agentId": "Agent ๆ ่ฏ","tokenPlaceholder": "ๅฏ้๏ผๅฆๆ่ฎพ็ฝฎ่ฏทๅกซๅ",+ "tokenRequiredPlaceholder": "ๅฟ ๅกซ","tokenPlaceholderSurge": "Surge API Key (x-key)",+ "agentTokenHint": "่ฏทไธ agent ๅฏๅจๅๆฐ --backend-token ไฟๆไธ่ดใ",+ "agentModeHint": "Agent ๆจกๅผไธไผไธปๅจ่ฟๆฅๅ ็ฝ็ฝๅ ณใๅ ๅๅปบๅ็ซฏ๏ผๅ็จ backend-id ๅ่ฏฅ token ่ฟ่ก neko-agent ไธๆฅใ",+ "agentTokenAutoHint": "ๅ็ซฏไปค็ๅฐๅจๅๅปบๅ่ชๅจ็ๆ๏ผๅนถไป ๅฑ็คบไธๆฌกไพๅคๅถใ",+ "agentTokenRequired": "Agent ๆจกๅผๅฟ ้กปๅกซๅๅ็ซฏไปค็",+ "agentBackendCreated": "Agent ๅ็ซฏๅทฒๅๅปบ๏ผID #{id}๏ผ",+ "agentSetupTitle": "Agent ้ ็ฝฎ",+ "agentSetupDescription": "ๅ็ซฏ #{id} ๅทฒๅๅปบใ่ฏทๅคๅถไธ้ข็ไปค็ๅๅฏๅจๅฝไปคใ",+ "copyAgentToken": "ๅคๅถไปค็",+ "agentTokenCopied": "Agent ไปค็ๅทฒๅคๅถ",+ "agentCommand": "่ฟ่กๅฝไปค",+ "copyAgentCommand": "ๅคๅถๅฝไปค",+ "agentCommandCopied": "Agent ๅฝไปคๅทฒๅคๅถ",+ "agentInstallScriptCommand": "ๅฎ่ฃ ่ๆฌๅฝไปค๏ผcurl | sh๏ผ",+ "agentInstallScriptHint": "ๅฏ้๏ผ่ฅ็ฝๅ ณ API ้่ฆ่ฎค่ฏ๏ผๅฏๅจ `sh` ๅๅขๅ NEKO_GATEWAY_TOKEN ็ฏๅขๅ้ใ",+ "copyAgentInstallScript": "ๅคๅถๅฎ่ฃ ่ๆฌ",+ "agentInstallScriptCopied": "ๅฎ่ฃ ่ๆฌๅฝไปคๅทฒๅคๅถ",+ "agentInfoCopied": "Agent ไฟกๆฏๅทฒๅคๅถ",+ "copyBackendId": "ๅคๅถๅ็ซฏ ID",+ "copyAgentId": "ๅคๅถ Agent ๆ ่ฏ",+ "agentTokenPlaceholder": "็ฒ่ดด backend-token๏ผ็จไบ็ๆๅฎๆด่ๆฌ๏ผ",+ "agentTokenEditHint": "่ฏทๆๅจๅกซๅ backend-tokenใ",+ "agentTokenInputHint": "ๅฏๆๅจๅกซๅ backend-token ็ๆ่ๆฌ๏ผไธไผไฟๅญๅฐๆๅก็ซฏ๏ผใ",+ "agentTokenManagedHint": "Agent ไปค็็ฑ็ณป็ป็ฎก็๏ผ่ฏทๅจโๆฅ็ Agent ่ๆฌโไธญ้็ฝฎไปค็ใ",+ "agentTokenHidden": "ไปค็ๅทฒ้่",+ "agentTokenUnavailableHint": "ๅฝๅไธๅฑ็คบๅๅฒไปค็๏ผ็นๅปโ้็ฝฎไปค็โ็ๆๆฐ้ๆบไปค็ใ",+ "agentTokenMissingHint": "ๆชๅกซๅ backend-token๏ผ่ๆฌไธญๅฐไฝฟ็จ `backend-token` ๅ ไฝ็ฌฆใ",+ "agentTokenGenerateFirstHint": "่ฏทๅ ็นๅปโ้็ฝฎไปค็โ็ๆๆฐ้ๆบไปค็๏ผๅๅคๅถๅฎๆด่ๆฌใ",+ "rotateAgentToken": "้็ฝฎไปค็",+ "rotating": "้็ฝฎไธญ...",+ "agentTokenRotateHint": "้็ฝฎๅๆง agent ไผๅคฑๆ๏ผ่ฏทๆน็จๆฐ token ๅนถ้ๅฏใ",+ "agentRotateTokenConfirm": "็กฎๅฎ็ฐๅจ้็ฝฎ่ฟไธช agent ไปค็ๅ๏ผไฝฟ็จๆง token ็ agent ไผๆญๅผ๏ผ็ดๅฐ้ๆฐ้ ็ฝฎใ",+ "agentRotateTokenSuccess": "Agent ไปค็ๅทฒ้็ฝฎ๏ผ่ฏทๆดๆฐๅนถ้ๅฏ agentใ",+ "agentRotateTokenFailed": "้็ฝฎ agent ไปค็ๅคฑ่ดฅ",+ "agentTokenLocalOnlyHint": "ๆญคๅคไปค็ไป ็จไบ็ๆๅคๅถ่ๆฌใ",+ "openAgentSetup": "ๆฅ็ Agent ่ๆฌ",+ "agentGatewayOptionalHint": "ๅฏ้๏ผๅกซๅ็ฝๅ ณ host / ็ซฏๅฃ / token๏ผๅคๅถ่ๆฌๆถไผ่ชๅจๅธฆไธใ",+ "agentGatewaySectionTitle": "Gateway ่ฟๆฅๅๆฐ๏ผๅๅ ฅ่ๆฌ๏ผ",+ "agentGatewaySectionHint": "ไธ้ขๅๆฐไผ็จไบ็ๆ่ฟ่กๅฝไปคๅๅฎ่ฃ ่ๆฌใ",+ "gatewayToken": "็ฝๅ ณไปค็",+ "showGatewayToken": "ๆพ็คบ็ฝๅ ณไปค็",+ "hideGatewayToken": "้่็ฝๅ ณไปค็",+ "agentGatewayTokenPlaceholder": "ๅฏ้๏ผไพๅฆ Clash secret ๆ Surge x-key","tokenKeepPlaceholder": "ๅทฒ่ฎพ็ฝฎไปค็๏ผ็็ฉบไฟๆไธๅ","active": "ๅฝๅๆดป่ท","disabled": "ๅทฒ็ฆ็จ",diff --git a/docs/README.md b/docs/README.mdindex 7da9e12..3f96c45 100644--- a/docs/README.md+++ b/docs/README.md@@ -5,6 +5,20 @@- Chinese: `docs/architecture.md`- English: `docs/architecture.en.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++- Checklist: `docs/release-checklist.md`+## Research Reports### Kimi 2.5diff --git a/docs/agent/README.md b/docs/agent/README.mdnew file mode 100644index 0000000..3f7378b--- /dev/null+++ b/docs/agent/README.md@@ -0,0 +1,10 @@+# Agent Documentation++Use this guide set when deploying Neko Master in a centralized mode with remote agents.++- `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 fixesdiff --git a/docs/agent/config.md b/docs/agent/config.mdnew file mode 100644index 0000000..dd81ae2--- /dev/null+++ b/docs/agent/config.md@@ -0,0 +1,53 @@+# Agent Configuration++## 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 `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++```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/install.md b/docs/agent/install.mdnew file mode 100644index 0000000..4f6728c--- /dev/null+++ b/docs/agent/install.md@@ -0,0 +1,60 @@+# Agent Install Guide++## 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++## 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`diff --git a/docs/agent/overview.md b/docs/agent/overview.mdnew file mode 100644index 0000000..2e0d069--- /dev/null+++ b/docs/agent/overview.md@@ -0,0 +1,36 @@+# Agent Mode Overview++## 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+- One backend token is bound to one `agentId` (multi-agent token reuse is rejected)diff --git a/docs/agent/quick-start.md b/docs/agent/quick-start.mdnew file mode 100644index 0000000..1ca6552--- /dev/null+++ b/docs/agent/quick-start.md@@ -0,0 +1,41 @@+# Agent Quick Start++## 1) Create an Agent backend in UI++In `Settings -> Backends`:++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:++- Run command (`./neko-agent ...`)+- Install command (`curl | sh`)++## 2) Install on remote host++Example:++```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='surge' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9091' \+ NEKO_GATEWAY_TOKEN='optional' \+ sh+```++## 3) Verify status++- In backend list, click `Test Connection`+- Confirm agent health becomes online+- Confirm traffic is visible in dashboard++## 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 reconfigureddiff --git a/docs/agent/release.md b/docs/agent/release.mdnew file mode 100644index 0000000..d0cac80--- /dev/null+++ b/docs/agent/release.md@@ -0,0 +1,57 @@+# Agent Release and Packaging++## 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/troubleshooting.md b/docs/agent/troubleshooting.mdnew file mode 100644index 0000000..3bf6236--- /dev/null+++ b/docs/agent/troubleshooting.md@@ -0,0 +1,57 @@+# Agent Troubleshooting++## `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.diff --git a/docs/release-checklist.md b/docs/release-checklist.mdnew file mode 100644index 0000000..80a6077--- /dev/null+++ b/docs/release-checklist.md@@ -0,0 +1,87 @@+# Release Checklist++Use this checklist before shipping a new Neko Master release that includes Agent mode.++## Release lines++- Main product release tag: `vX.Y.Z` (builds Docker images)+- Agent client release tag: `agent-vX.Y.Z` (publishes multi-arch agent packages)++`agent-v*` does not publish Docker images.++## Pre-release validation++Run locally from repo root:++```bash+pnpm --filter @neko-master/collector build+pnpm --filter @neko-master/web exec tsc --noEmit+```++Run agent checks:++```bash+cd apps/agent+go test ./...+sh -n install.sh+cd ../..+sh -n setup.sh+```++## Publish steps++### 1) Main product (Docker)++```bash+git tag vX.Y.Z+git push origin vX.Y.Z+```++Expected result:++- Docker workflow runs+- Docker Hub / GHCR updated++### 2) Agent packages++```bash+git tag agent-vX.Y.Z+git push origin agent-vX.Y.Z+```++Expected result:++- `Agent Release` workflow runs+- Release assets uploaded:+ - `neko-agent_<tag>_<os>_<arch>.tar.gz`+ - `neko-agent_<os>_<arch>.tar.gz`+ - `checksums.txt`++## Post-release checks++1. Open GitHub release page and verify all target architectures are present.+2. Validate one Linux host install using script:++```bash+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh \+ | env NEKO_SERVER='http://<panel>:3000' \+ NEKO_BACKEND_ID='<id>' \+ NEKO_BACKEND_TOKEN='<token>' \+ NEKO_GATEWAY_TYPE='clash' \+ NEKO_GATEWAY_URL='http://127.0.0.1:9090' \+ sh+```++3. In UI, verify:+ - backend health can become online+ - rotate token invalidates old process+ - updated token works after restart++## Compatibility policy++- Agent version can skip numbers when no agent release is needed.+- Maintain matrix in `docs/agent/release.md`:+ - `Agent version -> minimum server version`+ - optional server gate:+ - `MIN_AGENT_PROTOCOL_VERSION`+ - `MIN_AGENT_VERSION`diff --git a/package.json b/package.jsonindex cf8fef5..2aff390 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "neko-master",- "version": "1.3.0",+ "version": "1.3.1","description": "Modern traffic analytics for edge gateways","private": true,"workspaces": [diff --git a/packages/shared/src/gateway-utils.ts b/packages/shared/src/gateway-utils.tsindex 29032b8..d5c59ed 100644--- a/packages/shared/src/gateway-utils.ts+++ b/packages/shared/src/gateway-utils.ts@@ -118,3 +118,11 @@ export function getGatewayBaseUrl(url: string): string {.replace(/\/connections\/?$/, '').replace(/\/$/, '');}++/**+ * ๅคๆญๆฏๅฆไธบ Agent ่ขซๅจไธๆฅๅ็ซฏ+ * ็บฆๅฎ๏ผbackend.url ไปฅ agent:// ๅผๅคด+ */+export function isAgentBackendUrl(url: string): boolean {+ return /^agent:\/\//i.test((url || '').trim());+}diff --git a/setup.sh b/setup.shindex 18dbe0b..6fe790c 100755--- a/setup.sh+++ b/setup.sh@@ -24,139 +24,231 @@ WS_PORT=$DEFAULT_WS_PORT# Print colored messagesprint_info() {- echo -e "${BLUE}[INFO]${NC} $1"+ echo -e "${BLUE}[INFO]${NC} $1"}print_success() {- echo -e "${GREEN}[โ]${NC} $1"+ echo -e "${GREEN}[โ]${NC} $1"}print_warning() {- echo -e "${YELLOW}[!]${NC} $1"+ echo -e "${YELLOW}[!]${NC} $1"}print_error() {- echo -e "${RED}[โ]${NC} $1"+ echo -e "${RED}[โ]${NC} $1"+}++download_to_file() {+ local url=$1+ local output=$2+ if command -v curl >/dev/null 2>&1; then+ curl -fsSL "$url" -o "$output"+ return 0+ fi+ if command -v wget >/dev/null 2>&1; then+ wget -qO "$output" "$url"+ return 0+ fi+ return 1+}++prompt_if_empty() {+ local var_name=$1+ local prompt=$2+ local secret=${3:-false}+ local current_value="${!var_name:-}"++ if [ -n "$current_value" ]; then+ return 0+ fi++ if [ "$secret" = "true" ]; then+ read -s -p "$prompt: " current_value+ echo ""+ else+ read -p "$prompt: " current_value+ fi++ if [ -z "$current_value" ]; then+ print_error "$var_name is required"+ exit 1+ fi++ export "$var_name=$current_value"+}++run_agent_installer() {+ local script_url="https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh"++ echo ""+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo "โ Neko Agent - One-Click Install โ"+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo ""++ print_info "Prepare required variables for agent install"+ print_info "Tip: you can pre-export env vars to run non-interactively"++ prompt_if_empty "NEKO_SERVER" "Neko server URL (e.g. http://10.0.0.2:3000)"+ prompt_if_empty "NEKO_BACKEND_ID" "Backend ID"+ prompt_if_empty "NEKO_BACKEND_TOKEN" "Backend token" true+ prompt_if_empty "NEKO_GATEWAY_TYPE" "Gateway type (clash/surge)"+ prompt_if_empty "NEKO_GATEWAY_URL" "Gateway URL (e.g. http://127.0.0.1:9090)"++ if [ -z "${NEKO_GATEWAY_TOKEN:-}" ]; then+ read -s -p "Gateway token (optional, press Enter to skip): " NEKO_GATEWAY_TOKEN+ echo ""+ export NEKO_GATEWAY_TOKEN+ fi++ if [ -z "${NEKO_AGENT_VERSION:-}" ]; then+ read -p "Agent version [latest]: " NEKO_AGENT_VERSION+ export NEKO_AGENT_VERSION="${NEKO_AGENT_VERSION:-latest}"+ fi++ print_info "Downloading installer..."+ local tmp_script+ tmp_script="$(mktemp)"+ trap 'rm -f "$tmp_script"' EXIT INT TERM++ if ! download_to_file "$script_url" "$tmp_script"; then+ print_error "Failed to download agent installer (curl/wget required)"+ exit 1+ fi++ print_info "Running agent installer..."+ env \+ NEKO_SERVER="$NEKO_SERVER" \+ NEKO_BACKEND_ID="$NEKO_BACKEND_ID" \+ NEKO_BACKEND_TOKEN="$NEKO_BACKEND_TOKEN" \+ NEKO_GATEWAY_TYPE="$NEKO_GATEWAY_TYPE" \+ NEKO_GATEWAY_URL="$NEKO_GATEWAY_URL" \+ NEKO_GATEWAY_TOKEN="${NEKO_GATEWAY_TOKEN:-}" \+ NEKO_AGENT_VERSION="${NEKO_AGENT_VERSION:-latest}" \+ sh "$tmp_script"++ print_success "Agent install flow finished"}# Check if port is in usecheck_port() {- local port=$1- if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then- return 0 # Port in use- else- return 1 # Port available- fi+ local port=$1+ if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then+ return 0 # Port in use+ else+ return 1 # Port available+ fi}# Find available portfind_available_port() {- local start_port=$1- local port=$start_port-- while check_port $port; do- port=$((port + 1))- done-- echo $port+ local start_port=$1+ local port=$start_port++ while check_port $port; do+ port=$((port + 1))+ done++ echo $port}# Show welcome messageshow_welcome() {- echo ""- echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"- echo "โ Neko Master - One-Click Setup โ"- echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"- echo ""- print_info "This script will help you quickly configure Neko Master"- echo ""+ echo ""+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo "โ Neko Master - One-Click Setup โ"+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo ""+ print_info "This script will help you quickly configure Neko Master"+ echo ""}# Check port conflicts and ask usercheck_ports() {- print_info "Checking if default ports are available..."- echo ""-- local conflict_found=false- local suggested_web=$DEFAULT_WEB_PORT- local suggested_api=$DEFAULT_API_PORT- local suggested_ws=$DEFAULT_WS_PORT-- # Check each port- if check_port $DEFAULT_WEB_PORT; then- suggested_web=$(find_available_port $DEFAULT_WEB_PORT)- print_warning "Port $DEFAULT_WEB_PORT (Web UI) is already in use"- print_info " Suggested alternative: $suggested_web"- conflict_found=true- fi-- if check_port $DEFAULT_API_PORT; then- suggested_api=$(find_available_port $DEFAULT_API_PORT)- print_warning "Port $DEFAULT_API_PORT (API) is already in use"- print_info " Suggested alternative: $suggested_api"- conflict_found=true- fi-- if check_port $DEFAULT_WS_PORT; then- suggested_ws=$(find_available_port $DEFAULT_WS_PORT)- print_warning "Port $DEFAULT_WS_PORT (WebSocket) is already in use"- print_info " Suggested alternative: $suggested_ws"- conflict_found=true- fi-- echo ""-- if [ "$conflict_found" = true ]; then- print_warning "Port conflicts detected!"- echo ""- echo "Please choose an option:"- echo " 1) Use suggested ports ($suggested_web/$suggested_api/$suggested_ws)"- echo " 2) Enter custom ports manually"- echo " 3) Exit and configure manually later"- echo ""- read -p "Enter your choice [1-3]: " choice-- case $choice in- 1)- WEB_PORT=$suggested_web- API_PORT=$suggested_api- WS_PORT=$suggested_ws- print_success "Using suggested ports"- ;;- 2)- echo ""- read -p "Web UI port [$suggested_web]: " input_web- read -p "API port [$suggested_api]: " input_api- read -p "WebSocket port [$suggested_ws]: " input_ws- WEB_PORT=${input_web:-$suggested_web}- API_PORT=${input_api:-$suggested_api}- WS_PORT=${input_ws:-$suggested_ws}- ;;- 3)- echo ""- print_info "You can manually configure later using one of these methods:"- echo " 1. Copy .env.example to .env and modify ports"- echo " 2. Edit docker-compose.yml directly"- echo ""- exit 0- ;;- *)- print_error "Invalid option"- exit 1- ;;- esac- else- print_success "All default ports are available"- fi-- echo ""+ print_info "Checking if default ports are available..."+ echo ""++ local conflict_found=false+ local suggested_web=$DEFAULT_WEB_PORT+ local suggested_api=$DEFAULT_API_PORT+ local suggested_ws=$DEFAULT_WS_PORT++ # Check each port+ if check_port $DEFAULT_WEB_PORT; then+ suggested_web=$(find_available_port $DEFAULT_WEB_PORT)+ print_warning "Port $DEFAULT_WEB_PORT (Web UI) is already in use"+ print_info " Suggested alternative: $suggested_web"+ conflict_found=true+ fi++ if check_port $DEFAULT_API_PORT; then+ suggested_api=$(find_available_port $DEFAULT_API_PORT)+ print_warning "Port $DEFAULT_API_PORT (API) is already in use"+ print_info " Suggested alternative: $suggested_api"+ conflict_found=true+ fi++ if check_port $DEFAULT_WS_PORT; then+ suggested_ws=$(find_available_port $DEFAULT_WS_PORT)+ print_warning "Port $DEFAULT_WS_PORT (WebSocket) is already in use"+ print_info " Suggested alternative: $suggested_ws"+ conflict_found=true+ fi++ echo ""++ if [ "$conflict_found" = true ]; then+ print_warning "Port conflicts detected!"+ echo ""+ echo "Please choose an option:"+ echo " 1) Use suggested ports ($suggested_web/$suggested_api/$suggested_ws)"+ echo " 2) Enter custom ports manually"+ echo " 3) Exit and configure manually later"+ echo ""+ read -p "Enter your choice [1-3]: " choice++ case $choice in+ 1)+ WEB_PORT=$suggested_web+ API_PORT=$suggested_api+ WS_PORT=$suggested_ws+ print_success "Using suggested ports"+ ;;+ 2)+ echo ""+ read -p "Web UI port [$suggested_web]: " input_web+ read -p "API port [$suggested_api]: " input_api+ read -p "WebSocket port [$suggested_ws]: " input_ws+ WEB_PORT=${input_web:-$suggested_web}+ API_PORT=${input_api:-$suggested_api}+ WS_PORT=${input_ws:-$suggested_ws}+ ;;+ 3)+ echo ""+ print_info "You can manually configure later using one of these methods:"+ echo " 1. Copy .env.example to .env and modify ports"+ echo " 2. Edit docker-compose.yml directly"+ echo ""+ exit 0+ ;;+ *)+ print_error "Invalid option"+ exit 1+ ;;+ esac+ else+ print_success "All default ports are available"+ fi++ echo ""}# Create .env filecreate_env_file() {- print_info "Creating configuration file..."-- cat > .env << EOF+ print_info "Creating configuration file..."++ cat >.env <<EOF# =============================================================================# Neko Master Environment Configuration# =============================================================================@@ -198,135 +290,149 @@ WEB_EXTERNAL_PORT=$WEB_PORT# Then access: http://localhost:$WEB_PORT# =============================================================================EOF-- print_success "Configuration file created: .env"- echo ""++ print_success "Configuration file created: .env"+ echo ""}# Create data directorycreate_data_dir() {- if [ ! -d "./data" ]; then- mkdir -p ./data- print_success "Data directory created: ./data"- fi+ if [ ! -d "./data" ]; then+ mkdir -p ./data+ print_success "Data directory created: ./data"+ fi}# Show configuration summaryshow_summary() {- echo ""- echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"- echo "โ Configuration Summary โ"- echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"- echo ""- echo " Web UI Port: $WEB_PORT"- echo " API Port: $API_PORT"- echo " WebSocket Port: $WS_PORT"- echo ""- echo " Access URL:"- echo " http://localhost:$WEB_PORT"- echo ""- echo " Config file: .env"- echo ""+ echo ""+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo "โ Configuration Summary โ"+ echo "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"+ echo ""+ echo " Web UI Port: $WEB_PORT"+ echo " API Port: $API_PORT"+ echo " WebSocket Port: $WS_PORT"+ echo ""+ echo " Access URL:"+ echo " http://localhost:$WEB_PORT"+ echo ""+ echo " Config file: .env"+ echo ""}# Ask if user wants to start serviceask_start() {- read -p "Start the service now? [Y/n]: " start_now- start_now=${start_now:-Y}-- if [[ $start_now =~ ^[Yy]$ ]]; then- echo ""- print_info "Starting Neko Master..."- echo ""-- if command -v docker-compose &> /dev/null; then- docker-compose up -d- else- docker compose up -d- fi-- echo ""- print_success "Service started!"- echo ""- echo " Please wait 10-20 seconds for services to fully initialize"- echo " Then access: http://localhost:$WEB_PORT"- echo ""- echo " Common commands:"- echo " View logs: docker logs -f neko-master"- echo " Stop: docker compose down"- echo " Restart: docker compose restart"- echo ""- else- echo ""- print_info "Configuration complete. Start later with:"- echo " docker compose up -d"- echo ""- fi+ read -p "Start the service now? [Y/n]: " start_now+ start_now=${start_now:-Y}++ if [[ $start_now =~ ^[Yy]$ ]]; then+ echo ""+ print_info "Starting Neko Master..."+ echo ""++ if command -v docker-compose &>/dev/null; then+ docker-compose up -d+ else+ docker compose up -d+ fi++ echo ""+ print_success "Service started!"+ echo ""+ echo " Please wait 10-20 seconds for services to fully initialize"+ echo " Then access: http://localhost:$WEB_PORT"+ echo ""+ echo " Common commands:"+ echo " View logs: docker logs -f neko-master"+ echo " Stop: docker compose down"+ echo " Restart: docker compose restart"+ echo ""+ else+ echo ""+ print_info "Configuration complete. Start later with:"+ echo " docker compose up -d"+ echo ""+ fi}# Download docker-compose.yml if not presentdownload_compose_file() {- if [ ! -f "docker-compose.yml" ]; then- print_info "Downloading docker-compose.yml..."- if command -v curl &> /dev/null; then- curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml- elif command -v wget &> /dev/null; then- wget -qO docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml- else- print_error "Neither curl nor wget is available"- exit 1- fi- print_success "docker-compose.yml downloaded"- fi+ if [ ! -f "docker-compose.yml" ]; then+ print_info "Downloading docker-compose.yml..."+ if command -v curl &>/dev/null; then+ curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml+ elif command -v wget &>/dev/null; then+ wget -qO docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml+ else+ print_error "Neither curl nor wget is available"+ exit 1+ fi+ print_success "docker-compose.yml downloaded"+ fi}# Main functionmain() {- show_welcome-- # Check if Docker is installed- if ! command -v docker &> /dev/null; then- print_error "Docker is not installed"- echo ""- echo "Please install Docker first:"- echo " https://docs.docker.com/get-docker/"- echo ""- exit 1- fi-- # Check docker-compose- if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then- print_error "Docker Compose is not installed"- echo ""- exit 1- fi-- # Check if .env already exists- if [ -f ".env" ]; then- print_warning "Existing .env file detected"- read -p "Reconfigure? [y/N]: " reconfig- if [[ ! $reconfig =~ ^[Yy]$ ]]; then- print_info "Using existing configuration"- show_summary- ask_start- exit 0- fi- fi-- # Check ports- check_ports-- # Create configuration- create_env_file- create_data_dir- download_compose_file-- # Show summary- show_summary-- # Ask to start- ask_start+ show_welcome++ # Check if Docker is installed+ if ! command -v docker &>/dev/null; then+ print_error "Docker is not installed"+ echo ""+ echo "Please install Docker first:"+ echo " https://docs.docker.com/get-docker/"+ echo ""+ exit 1+ fi++ # Check docker-compose+ if ! command -v docker-compose &>/dev/null && ! docker compose version &>/dev/null; then+ print_error "Docker Compose is not installed"+ echo ""+ exit 1+ fi++ # Check if .env already exists+ if [ -f ".env" ]; then+ print_warning "Existing .env file detected"+ read -p "Reconfigure? [y/N]: " reconfig+ if [[ ! $reconfig =~ ^[Yy]$ ]]; then+ print_info "Using existing configuration"+ show_summary+ ask_start+ exit 0+ fi+ fi++ # Check ports+ check_ports++ # Create configuration+ create_env_file+ create_data_dir+ download_compose_file++ # Show summary+ show_summary++ # Ask to start+ ask_start}-# Run main function-main+# Entry point dispatcher+case "${1:-}" in+agent | agent-install)+ run_agent_installer+ ;;+"")+ main+ ;;+*)+ print_error "Unknown command: $1"+ echo "Usage:"+ echo " ./setup.sh # setup Neko Master service"+ echo " ./setup.sh agent-install # install and run Neko Agent"+ exit 1+ ;;+esac