Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: enhance agent installation script to support adding multiple backend instances and detect existing installations, with corresponding UI updates.

luoleic536e337a4cb
diff --git a/apps/agent/install.sh b/apps/agent/install.sh
index 7d211d5..5a2ed1c 100755
--- a/apps/agent/install.sh
+++ b/apps/agent/install.sh
@@ -1,6 +1,14 @@
#!/usr/bin/env sh
set -eu
+# Neko Agent Install Script
+# Features:
+# - Detects existing nekoagent installation
+# - Uses local nekoagent if available
+# - Supports adding multiple backend instances
+
+VERSION="0.2.0"
+
require_env() {
key="$1"
eval "val=\${$key:-}"
@@ -28,24 +36,23 @@ Agent docs:
EOF
}
-show_plan() {
- token_mode="not set"
- if [ -n "$NEKO_GATEWAY_TOKEN" ]; then
- token_mode="provided"
+detect_existing_install() {
+ # Check for nekoagent in common locations
+ if command -v nekoagent >/dev/null 2>&1; then
+ echo "$(command -v nekoagent)"
+ return 0
fi
-
- cat <<EOF
-[neko-agent] install plan:
- target: ${os}/${arch}
- version: ${NEKO_AGENT_VERSION}
- backend id: ${NEKO_BACKEND_ID}
- instance: ${NEKO_INSTANCE_NAME}
- gateway type: ${NEKO_GATEWAY_TYPE}
- gateway url: ${NEKO_GATEWAY_URL}
- gateway token: ${token_mode}
- install dir: ${NEKO_INSTALL_DIR}
- auto start: ${NEKO_AUTO_START}
-EOF
+
+ # Check default install locations
+ for path in "$HOME/.local/bin/nekoagent" "/usr/local/bin/nekoagent"; do
+ if [ -x "$path" ]; then
+ echo "$path"
+ return 0
+ fi
+ done
+
+ # Not found
+ return 1
}
download_file() {
@@ -108,171 +115,234 @@ compute_sha256() {
echo ""
}
-require_env "NEKO_SERVER"
-require_env "NEKO_BACKEND_ID"
-require_env "NEKO_BACKEND_TOKEN"
-require_env "NEKO_GATEWAY_URL"
-
-show_intro
-
-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_CLI_URL="${NEKO_CLI_URL:-}"
-NEKO_INSTALL_DIR="${NEKO_INSTALL_DIR:-$HOME/.local/bin}"
-NEKO_BIN_LINK_MODE="${NEKO_BIN_LINK_MODE:-auto}"
-NEKO_LINK_DIR="${NEKO_LINK_DIR:-/usr/local/bin}"
-NEKO_LOG="${NEKO_LOG:-true}"
-NEKO_AUTO_START="${NEKO_AUTO_START:-true}"
-NEKO_INSTANCE_NAME="${NEKO_INSTANCE_NAME:-backend-${NEKO_BACKEND_ID}}"
-
-os="$(normalize_os)"
-arch="$(normalize_arch)"
-
-if [ "$NEKO_AGENT_VERSION" = "latest" ]; then
- release_path="releases/latest/download"
- asset="neko-agent_${os}_${arch}.tar.gz"
-else
- release_path="releases/download/${NEKO_AGENT_VERSION}"
- 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
-
-if [ -n "$NEKO_CLI_URL" ]; then
- cli_url="$NEKO_CLI_URL"
-else
- if [ "$NEKO_AGENT_VERSION" = "latest" ]; then
- cli_ref="main"
- else
- cli_ref="$NEKO_AGENT_VERSION"
+# Use local nekoagent to add instance
+use_local_agent() {
+ nekoagent_path="$1"
+ instance_name="${NEKO_INSTANCE_NAME:-backend-${NEKO_BACKEND_ID}}"
+
+ echo "[neko-agent] detected existing installation: $nekoagent_path"
+ echo "[neko-agent] using local nekoagent to add instance..."
+
+ # Build add command
+ set -- \
+ "$nekoagent_path" add "$instance_name" \
+ --server-url "$NEKO_SERVER" \
+ --backend-id "$NEKO_BACKEND_ID" \
+ --backend-token "$NEKO_BACKEND_TOKEN" \
+ --gateway-type "$NEKO_GATEWAY_TYPE" \
+ --gateway-url "$NEKO_GATEWAY_URL"
+
+ if [ -n "${NEKO_GATEWAY_TOKEN:-}" ]; then
+ set -- "$@" --gateway-token "$NEKO_GATEWAY_TOKEN"
fi
- cli_url="https://raw.githubusercontent.com/${NEKO_AGENT_REPO}/${cli_ref}/apps/agent/nekoagent"
-fi
+
+ if [ "${NEKO_AUTO_START:-true}" = "true" ]; then
+ set -- "$@" --auto-start
+ fi
+
+ # Execute
+ "$@"
+}
-show_plan
+show_plan() {
+ token_mode="not set"
+ if [ -n "${NEKO_GATEWAY_TOKEN:-}" ]; then
+ token_mode="provided"
+ fi
-tmp_dir="${TMPDIR:-/tmp}/neko-agent.$$"
-mkdir -p "$tmp_dir"
-trap 'rm -rf "$tmp_dir"' EXIT INT TERM
+ cat <<EOF
+[neko-agent] install plan:
+ target: ${os}/${arch}
+ version: ${NEKO_AGENT_VERSION}
+ backend id: ${NEKO_BACKEND_ID}
+ instance: ${NEKO_INSTANCE_NAME}
+ gateway type: ${NEKO_GATEWAY_TYPE}
+ gateway url: ${NEKO_GATEWAY_URL}
+ gateway token: ${token_mode}
+ install dir: ${NEKO_INSTALL_DIR}
+ auto start: ${NEKO_AUTO_START}
+EOF
+}
-archive_path="$tmp_dir/neko-agent.tar.gz"
-checksums_path="$tmp_dir/checksums.txt"
-cli_path="$tmp_dir/nekoagent"
+# Main installation flow
+main() {
+ require_env "NEKO_SERVER"
+ require_env "NEKO_BACKEND_ID"
+ require_env "NEKO_BACKEND_TOKEN"
+ require_env "NEKO_GATEWAY_URL"
+
+ show_intro
+
+ # Environment defaults
+ 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_CLI_URL="${NEKO_CLI_URL:-}"
+ NEKO_INSTALL_DIR="${NEKO_INSTALL_DIR:-$HOME/.local/bin}"
+ NEKO_BIN_LINK_MODE="${NEKO_BIN_LINK_MODE:-auto}"
+ NEKO_LINK_DIR="${NEKO_LINK_DIR:-/usr/local/bin}"
+ NEKO_LOG="${NEKO_LOG:-true}"
+ NEKO_AUTO_START="${NEKO_AUTO_START:-true}"
+ NEKO_INSTANCE_NAME="${NEKO_INSTANCE_NAME:-backend-${NEKO_BACKEND_ID}}"
+
+ os="$(normalize_os)"
+ arch="$(normalize_arch)"
+
+ # Check if nekoagent is already installed
+ existing_agent=""
+ if detect_existing_install; then
+ existing_agent="$(detect_existing_install)"
+ fi
-echo "[neko-agent] downloading package: $package_url"
-download_file "$package_url" "$archive_path"
+ # If already installed, just add the new instance
+ if [ -n "$existing_agent" ] && [ "${NEKO_FORCE_INSTALL:-false}" != "true" ]; then
+ use_local_agent "$existing_agent"
+ exit 0
+ fi
-if [ -z "$NEKO_PACKAGE_URL" ]; then
- echo "[neko-agent] downloading checksums: $checksums_url"
- download_file "$checksums_url" "$checksums_path"
+ # Full installation needed
+ show_plan
- 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
+ if [ "$NEKO_AGENT_VERSION" = "latest" ]; then
+ release_path="releases/latest/download"
+ asset="neko-agent_${os}_${arch}.tar.gz"
+ else
+ release_path="releases/download/${NEKO_AGENT_VERSION}"
+ asset="neko-agent_${NEKO_AGENT_VERSION}_${os}_${arch}.tar.gz"
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
+ 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 [ "$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
+ 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
-fi
-mkdir -p "$tmp_dir/extract"
-tar -xzf "$archive_path" -C "$tmp_dir/extract"
+ if [ -n "$NEKO_CLI_URL" ]; then
+ cli_url="$NEKO_CLI_URL"
+ else
+ if [ "$NEKO_AGENT_VERSION" = "latest" ]; then
+ cli_ref="main"
+ else
+ cli_ref="$NEKO_AGENT_VERSION"
+ fi
+ cli_url="https://raw.githubusercontent.com/${NEKO_AGENT_REPO}/${cli_ref}/apps/agent/nekoagent"
+ fi
-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"
-
-echo "[neko-agent] downloading manager cli: $cli_url"
-download_file "$cli_url" "$cli_path"
-chmod +x "$cli_path"
-cli_target="$NEKO_INSTALL_DIR/nekoagent"
-mv "$cli_path" "$cli_target"
-chmod +x "$cli_target"
-
-linked_to_path="false"
-if [ "$NEKO_BIN_LINK_MODE" != "false" ]; then
- can_link="false"
- if [ "$NEKO_BIN_LINK_MODE" = "true" ]; then
- can_link="true"
- elif [ -d "$NEKO_LINK_DIR" ] && [ -w "$NEKO_LINK_DIR" ]; then
- can_link="true"
+ 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"
+ cli_path="$tmp_dir/nekoagent"
+
+ 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
- if [ "$can_link" = "true" ]; then
- if mkdir -p "$NEKO_LINK_DIR" 2>/dev/null; then
- if ln -sf "$install_target" "$NEKO_LINK_DIR/neko-agent" 2>/dev/null &&
- ln -sf "$cli_target" "$NEKO_LINK_DIR/nekoagent" 2>/dev/null; then
- linked_to_path="true"
- echo "[neko-agent] linked binaries into: $NEKO_LINK_DIR"
+ 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"
+
+ echo "[neko-agent] downloading manager cli: $cli_url"
+ download_file "$cli_url" "$cli_path"
+ chmod +x "$cli_path"
+ cli_target="$NEKO_INSTALL_DIR/nekoagent"
+ mv "$cli_path" "$cli_target"
+ chmod +x "$cli_target"
+
+ linked_to_path="false"
+ if [ "$NEKO_BIN_LINK_MODE" != "false" ]; then
+ can_link="false"
+ if [ "$NEKO_BIN_LINK_MODE" = "true" ]; then
+ can_link="true"
+ elif [ -d "$NEKO_LINK_DIR" ] && [ -w "$NEKO_LINK_DIR" ]; then
+ can_link="true"
+ fi
+
+ if [ "$can_link" = "true" ]; then
+ if mkdir -p "$NEKO_LINK_DIR" 2>/dev/null; then
+ if ln -sf "$install_target" "$NEKO_LINK_DIR/neko-agent" 2>/dev/null &&
+ ln -sf "$cli_target" "$NEKO_LINK_DIR/nekoagent" 2>/dev/null; then
+ linked_to_path="true"
+ echo "[neko-agent] linked binaries into: $NEKO_LINK_DIR"
+ fi
fi
fi
fi
-fi
-
-if [ "$linked_to_path" = "false" ] && ! echo ":$PATH:" | grep -q ":$NEKO_INSTALL_DIR:"; then
- echo "[neko-agent] warning: $NEKO_INSTALL_DIR is not in PATH"
- echo "[neko-agent] hint: use full path: $cli_target status $NEKO_INSTANCE_NAME"
- echo "[neko-agent] hint: add PATH in shell profile: export PATH=\"$NEKO_INSTALL_DIR:\$PATH\""
-fi
-
-"$cli_target" init "$NEKO_INSTANCE_NAME" \
- "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_LOG=$NEKO_LOG"
-
-echo "[neko-agent] installed to: $install_target"
-echo "[neko-agent] management cli: $cli_target"
-echo "[neko-agent] configured instance: $NEKO_INSTANCE_NAME"
-echo "[neko-agent] common commands:"
-echo " $cli_target start $NEKO_INSTANCE_NAME"
-echo " $cli_target stop $NEKO_INSTANCE_NAME"
-echo " $cli_target status $NEKO_INSTANCE_NAME"
-echo " $cli_target logs $NEKO_INSTANCE_NAME"
-echo " $cli_target update $NEKO_INSTANCE_NAME [agent-vX.Y.Z]"
-echo " $cli_target remove $NEKO_INSTANCE_NAME"
-echo " $cli_target uninstall"
-
-if [ "$NEKO_AUTO_START" = "true" ]; then
- "$cli_target" start "$NEKO_INSTANCE_NAME"
-else
- echo "[neko-agent] auto-start disabled (NEKO_AUTO_START=false)"
-fi
+
+ if [ "$linked_to_path" = "false" ] && ! echo ":$PATH:" | grep -q ":$NEKO_INSTALL_DIR:"; then
+ echo "[neko-agent] warning: $NEKO_INSTALL_DIR is not in PATH"
+ echo "[neko-agent] hint: use full path: $cli_target status $NEKO_INSTANCE_NAME"
+ echo "[neko-agent] hint: add PATH in shell profile: export PATH=\"$NEKO_INSTALL_DIR:\$PATH\""
+ fi
+
+ # Use the newly installed nekoagent to add instance
+ "$cli_target" add "$NEKO_INSTANCE_NAME" \
+ --server-url "$NEKO_SERVER" \
+ --backend-id "$NEKO_BACKEND_ID" \
+ --backend-token "$NEKO_BACKEND_TOKEN" \
+ --gateway-type "$NEKO_GATEWAY_TYPE" \
+ --gateway-url "$NEKO_GATEWAY_URL" \
+ $(if [ -n "$NEKO_GATEWAY_TOKEN" ]; then echo "--gateway-token $NEKO_GATEWAY_TOKEN"; fi) \
+ $(if [ "$NEKO_AUTO_START" = "true" ]; then echo "--auto-start"; fi)
+
+ echo "[neko-agent] installed to: $install_target"
+ echo "[neko-agent] management cli: $cli_target"
+ echo "[neko-agent] configured instance: $NEKO_INSTANCE_NAME"
+ echo "[neko-agent] common commands:"
+ echo " nekoagent list"
+ echo " nekoagent start $NEKO_INSTANCE_NAME"
+ echo " nekoagent stop $NEKO_INSTANCE_NAME"
+ echo " nekoagent status $NEKO_INSTANCE_NAME"
+ echo " nekoagent logs $NEKO_INSTANCE_NAME"
+ echo " nekoagent update $NEKO_INSTANCE_NAME"
+ echo " nekoagent remove $NEKO_INSTANCE_NAME"
+}
+
+main "$@"
diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go
index 0007723..7bdd1c5 100644
--- a/apps/agent/internal/config/config.go
+++ b/apps/agent/internal/config/config.go
@@ -1,10 +1,11 @@
package config
import (
+ "crypto/sha256"
+ "encoding/hex"
"errors"
"flag"
"fmt"
- "os"
"strings"
"time"
)
@@ -42,7 +43,7 @@ func Parse(args []string) (Config, error) {
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)")
+ agentID := fs.String("agent-id", "", "Agent ID (optional, auto-generated from backend-token if not provided)")
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)")
@@ -88,13 +89,16 @@ func Parse(args []string) (Config, error) {
return Config{}, errors.New("report-batch-size and max-pending-updates must be positive")
}
- hostname, _ := os.Hostname()
- if hostname == "" {
- hostname = "agent"
- }
+ // Generate stable agent ID based on backend token
+ // This ensures the same agent always uses the same ID across restarts
+ backendTokenTrimmed := strings.TrimSpace(*backendToken)
finalAgentID := strings.TrimSpace(*agentID)
if finalAgentID == "" {
- finalAgentID = fmt.Sprintf("%s-%d", sanitizeID(hostname), os.Getpid())
+ // Use first 16 chars of backend token hash as agent ID
+ // This is stable across restarts and unique per backend
+ hash := sha256.Sum256([]byte(backendTokenTrimmed))
+ hashStr := hex.EncodeToString(hash[:])
+ finalAgentID = "agent-" + hashStr[:16]
}
if len(finalAgentID) > 128 {
finalAgentID = finalAgentID[:128]
@@ -131,7 +135,7 @@ func Usage() string {
" --gateway-url Gateway API URL",
"",
"Optional:",
- " --agent-id Agent ID (default hostname-pid)",
+ " --agent-id Agent ID (auto-generated from backend-token if not set)",
" --log enable runtime logs (default true, set --log=false to disable)",
" --gateway-type clash|surge (default clash)",
" --gateway-token Gateway secret",
diff --git a/apps/agent/nekoagent b/apps/agent/nekoagent
index 7322701..cb90766 100755
--- a/apps/agent/nekoagent
+++ b/apps/agent/nekoagent
@@ -7,6 +7,7 @@ INSTALL_DIR="${NEKO_INSTALL_DIR:-$INSTALL_DIR_DEFAULT}"
AGENT_BIN="${NEKO_AGENT_BIN:-$INSTALL_DIR/neko-agent}"
CONFIG_DIR="${NEKO_AGENT_CONFIG_DIR:-/etc/neko-agent}"
STATE_DIR="${NEKO_AGENT_STATE_DIR:-/var/run/neko-agent}"
+VERSION="0.2.0"
log() {
printf '[%s] %s\n' "$PROG" "$1"
@@ -48,20 +49,39 @@ is_running() {
kill -0 "$pid" >/dev/null 2>&1
}
+version() {
+ printf '%s\n' "$VERSION"
+}
+
usage() {
cat <<EOF
+Neko Agent Manager v${VERSION}
+
Usage:
- $PROG init <name> [KEY=VALUE ...] Create/overwrite config file
- $PROG start <name> Start agent instance
- $PROG stop <name> Stop agent instance
- $PROG restart <name> Restart agent instance
- $PROG status <name> Show instance status
- $PROG logs <name> Tail logs
- $PROG list List configured instances
- $PROG update <name> [version] Update agent binary and restart instance
- $PROG remove <name> Remove one instance config/runtime data
- $PROG delete <name> Alias of remove
- $PROG uninstall Uninstall nekoagent + neko-agent binaries
+ $PROG init <name> [KEY=VALUE ...] Create/overwrite config file
+ $PROG add <name> [flags/options] Quick add new backend instance
+ $PROG start <name> Start agent instance
+ $PROG stop <name> Stop agent instance
+ $PROG restart <name> Restart agent instance
+ $PROG status <name> Show instance status
+ $PROG logs <name> Tail logs
+ $PROG list List configured instances
+ $PROG update <name> [version] Update agent binary and restart
+ $PROG remove <name> Remove instance config/runtime
+ $PROG delete <name> Alias of remove
+ $PROG uninstall Uninstall nekoagent + binaries
+ $PROG version Show version
+ $PROG help Show this help
+
+Quick add with flags:
+ $PROG add <name> \
+ --server-url <url> \
+ --backend-id <id> \
+ --backend-token <token> \
+ --gateway-type <clash|surge> \
+ --gateway-url <url> \
+ [--gateway-token <token>] \
+ [--auto-start]
Config and runtime paths:
CONFIG_DIR=$CONFIG_DIR
@@ -74,6 +94,27 @@ Optional keys:
NEKO_GATEWAY_TOKEN, NEKO_LOG, NEKO_AGENT_ID, NEKO_REPORT_INTERVAL,
NEKO_HEARTBEAT_INTERVAL, NEKO_GATEWAY_POLL_INTERVAL, NEKO_REQUEST_TIMEOUT,
NEKO_REPORT_BATCH_SIZE, NEKO_MAX_PENDING_UPDATES, NEKO_STALE_FLOW_TIMEOUT
+
+Examples:
+ # Add and start a new backend
+ $PROG add home-surge --server-url http://10.0.0.210:3000 --backend-id 3 \\
+ --backend-token ag_xxx --gateway-type surge --gateway-url http://10.0.0.210:9091 \\
+ --gateway-token xxx --auto-start
+
+ # List all instances
+ $PROG list
+
+ # Check status
+ $PROG status home-surge
+
+ # View logs
+ $PROG logs home-surge
+
+ # Update to latest version
+ $PROG update home-surge
+
+ # Remove instance
+ $PROG remove home-surge
EOF
}
@@ -163,6 +204,93 @@ cmd_init() {
log "config written: $cf"
}
+# Quick add with flags instead of KEY=VALUE pairs
+cmd_add() {
+ if [ "$#" -lt 6 ]; then
+ err "add requires: <name> --server-url <url> --backend-id <id> --backend-token <token> --gateway-type <type> --gateway-url <url>"
+ echo ""
+ echo "Usage: $PROG add <name> --server-url <url> --backend-id <id> --backend-token <token> --gateway-type <clash|surge> --gateway-url <url> [--gateway-token <token>] [--auto-start]"
+ exit 1
+ fi
+
+ name="$1"
+ shift
+
+ # Parse flags
+ server_url=""
+ backend_id=""
+ backend_token=""
+ gateway_type=""
+ gateway_url=""
+ gateway_token=""
+ auto_start="false"
+
+ while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --server-url)
+ server_url="$2"
+ shift 2
+ ;;
+ --backend-id)
+ backend_id="$2"
+ shift 2
+ ;;
+ --backend-token)
+ backend_token="$2"
+ shift 2
+ ;;
+ --gateway-type)
+ gateway_type="$2"
+ shift 2
+ ;;
+ --gateway-url)
+ gateway_url="$2"
+ shift 2
+ ;;
+ --gateway-token)
+ gateway_token="$2"
+ shift 2
+ ;;
+ --auto-start)
+ auto_start="true"
+ shift
+ ;;
+ *)
+ err "unknown flag: $1"
+ exit 1
+ ;;
+ esac
+ done
+
+ # Validate required fields
+ if [ -z "$server_url" ] || [ -z "$backend_id" ] || [ -z "$backend_token" ] || [ -z "$gateway_type" ] || [ -z "$gateway_url" ]; then
+ err "missing required flags"
+ echo "Required: --server-url, --backend-id, --backend-token, --gateway-type, --gateway-url"
+ exit 1
+ fi
+
+ # Build config
+ config_vars=""
+ config_vars="$config_vars NEKO_SERVER=$server_url"
+ config_vars="$config_vars NEKO_BACKEND_ID=$backend_id"
+ config_vars="$config_vars NEKO_BACKEND_TOKEN=$backend_token"
+ config_vars="$config_vars NEKO_GATEWAY_TYPE=$gateway_type"
+ config_vars="$config_vars NEKO_GATEWAY_URL=$gateway_url"
+ if [ -n "$gateway_token" ]; then
+ config_vars="$config_vars NEKO_GATEWAY_TOKEN=$gateway_token"
+ fi
+
+ # Initialize config
+ cmd_init "$name" $config_vars
+
+ log "instance '$name' added successfully"
+
+ # Auto-start if requested
+ if [ "$auto_start" = "true" ]; then
+ cmd_start "$name"
+ fi
+}
+
cmd_start() {
name="$1"
ensure_dirs
@@ -238,7 +366,10 @@ cmd_list() {
else
status="stopped"
fi
- printf '%s\t%s\n' "$name" "$status"
+ # Load config to show backend info
+ # shellcheck disable=SC1090
+ . "$f"
+ printf '%-20s %-10s backend-id=%s gateway=%s\n' "$name" "$status" "${NEKO_BACKEND_ID:-?}" "${NEKO_GATEWAY_TYPE:-?}"
done
if [ "$found" = false ]; then
log "no instances configured"
@@ -329,6 +460,13 @@ main() {
fi
cmd_init "$@"
;;
+ add)
+ if [ "$#" -lt 6 ]; then
+ usage
+ exit 1
+ fi
+ cmd_add "$@"
+ ;;
start|stop|restart|status|logs)
if [ "$#" -ne 1 ]; then
usage
@@ -367,6 +505,9 @@ main() {
list)
cmd_list
;;
+ version|-v|--version)
+ version
+ ;;
help|-h|--help)
usage
;;
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index 51aad57..46dc68b 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -382,8 +382,9 @@ export async function createApp(options: AppOptions) {
}
// Allow rebinding if the existing agent has been offline for a while
- // Use a longer timeout (60s) than the health check to avoid race conditions
- const AGENT_BINDING_TIMEOUT_MS = 60000;
+ // Agent heartbeat interval is 30s, so 10s timeout allows quick restart
+ // while preventing accidental duplicate bindings
+ const AGENT_BINDING_TIMEOUT_MS = 10000;
const lastSeenMs = new Date(heartbeat.lastSeen).getTime();
const ageMs = Number.isFinite(lastSeenMs) ? Math.max(0, Date.now() - lastSeenMs) : Number.POSITIVE_INFINITY;
@@ -393,9 +394,12 @@ export async function createApp(options: AppOptions) {
}
reply.status(409).send({
- error: `Agent token is already bound to '${heartbeat.agentId}'. Rotate token before binding '${agentId}'.`,
+ error: `Agent token is already bound to '${heartbeat.agentId}'. ` +
+ `Wait ${Math.round((AGENT_BINDING_TIMEOUT_MS - ageMs) / 1000)}s for previous agent to timeout. ` +
+ `If you need to run multiple agents on the same backend, use different --agent-id values.`,
code: 'AGENT_TOKEN_ALREADY_BOUND',
boundAgentId: heartbeat.agentId,
+ remainingSeconds: Math.round((AGENT_BINDING_TIMEOUT_MS - ageMs) / 1000),
});
return false;
};
diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
index 39e51a8..1465ac3 100644
--- a/apps/web/components/features/backend/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -610,6 +610,33 @@ function buildAgentInstallScriptCommand(info: AgentBootstrapInfo): string {
return generated;
}
+function buildAgentQuickAddCommand(info: AgentBootstrapInfo): string {
+ const gatewayUrlWithConfig = buildGatewayUrl(
+ info.type,
+ info.gatewayHost,
+ info.gatewayPort,
+ info.gatewaySsl,
+ );
+ const backendToken = info.token.trim() || "<backend-token>";
+ const instanceName = `backend-${info.backendId}`;
+
+ const lines = [
+ "nekoagent add " + shellQuote(instanceName) + " \\",
+ " --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()));
+ }
+
+ return lines.join("\n");
+}
+
export function BackendConfigDialog({
open,
onOpenChange,
@@ -664,6 +691,7 @@ export function BackendConfigDialog({
useState(false);
const [agentBootstrapInfo, setAgentBootstrapInfo] =
useState<AgentBootstrapInfo | null>(null);
+ const [activeScriptTab, setActiveScriptTab] = useState<"install" | "add" | "run">("install");
const [rotatingAgentToken, setRotatingAgentToken] = useState(false);
const [rotateAgentTokenDialogOpen, setRotateAgentTokenDialogOpen] = useState(false);
@@ -3180,65 +3208,111 @@ export function BackendConfigDialog({
</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">
+ {/* Script Tabs */}
+ <div className="space-y-3">
+ {/* Tab Headers - Mobile: full width, Desktop: auto */}
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
+ <div className="flex items-center gap-1 p-1 bg-muted rounded-lg overflow-x-auto">
+ <button
+ onClick={() => setActiveScriptTab("install")}
+ className={`px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-colors whitespace-nowrap flex-1 sm:flex-none text-center ${
+ activeScriptTab === "install"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {t("scriptTabInstall")}
+ </button>
+ <button
+ onClick={() => setActiveScriptTab("add")}
+ className={`px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-colors whitespace-nowrap flex-1 sm:flex-none text-center ${
+ activeScriptTab === "add"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {t("scriptTabAdd")}
+ </button>
+ <button
+ onClick={() => setActiveScriptTab("run")}
+ className={`px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-colors whitespace-nowrap flex-1 sm:flex-none text-center ${
+ activeScriptTab === "run"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {t("scriptTabRun")}
+ </button>
+ </div>
<Button
- variant="outline"
+ variant="ghost"
size="sm"
- className="w-full sm:w-auto"
+ className="h-8 px-2 w-full sm:w-auto"
disabled={!agentBootstrapInfo.token.trim()}
- onClick={() =>
+ onClick={() => {
+ const text =
+ activeScriptTab === "install"
+ ? buildAgentInstallScriptCommand(agentBootstrapInfo)
+ : activeScriptTab === "add"
+ ? buildAgentQuickAddCommand(agentBootstrapInfo)
+ : buildAgentRunCommand(agentBootstrapInfo);
void copyText(
- buildAgentRunCommand(agentBootstrapInfo),
- "agentCommandCopied",
- )
- }>
- <Copy className="w-4 h-4 mr-2" />
- {t("copyAgentCommand")}
+ text,
+ activeScriptTab === "install"
+ ? "agentInstallScriptCopied"
+ : activeScriptTab === "add"
+ ? "agentQuickAddCopied"
+ : "agentCommandCopied",
+ );
+ }}>
+ <Copy className="w-4 h-4 mr-1.5" />
+ {t("copy")}
</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>
+ {/* Tab Content */}
+ <div className="relative">
+ {activeScriptTab === "install" && (
+ <div className="space-y-2">
+ <p className="text-[11px] text-muted-foreground">
+ {t("agentInstallScriptHint")}
+ </p>
+ <textarea
+ readOnly
+ value={buildAgentInstallScriptCommand(agentBootstrapInfo)}
+ className="w-full min-h-[140px] sm:min-h-[180px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
+ />
+ </div>
+ )}
+ {activeScriptTab === "add" && (
+ <div className="space-y-2">
+ <p className="text-[11px] text-muted-foreground">
+ {t("agentQuickAddHint")}
+ </p>
+ <textarea
+ readOnly
+ value={buildAgentQuickAddCommand(agentBootstrapInfo)}
+ className="w-full min-h-[120px] sm:min-h-[160px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
+ />
+ </div>
+ )}
+ {activeScriptTab === "run" && (
+ <div className="space-y-2">
+ <p className="text-[11px] text-muted-foreground">
+ {t("agentRunHint")}
+ </p>
+ <textarea
+ readOnly
+ value={buildAgentRunCommand(agentBootstrapInfo)}
+ className="w-full min-h-[120px] sm:min-h-[160px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
+ />
+ </div>
+ )}
+ {!agentBootstrapInfo.token.trim() && (
+ <p className="text-[11px] text-muted-foreground mt-2">
+ {t("agentTokenGenerateFirstHint")}
+ </p>
+ )}
</div>
</div>
</div>
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index a0b03b9..e2e0e32 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -396,6 +396,7 @@
"agentInfoCopied": "Agent info copied",
"copyBackendId": "Copy backend ID",
"copyAgentId": "Copy agent ID",
+ "copy": "Copy",
"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).",
@@ -412,6 +413,11 @@
"agentRotateTokenFailed": "Failed to rotate agent token",
"agentTokenLocalOnlyHint": "This token input is only used for script generation.",
"openAgentSetup": "View Agent Script",
+ "scriptTabInstall": "Install",
+ "scriptTabAdd": "Add",
+ "scriptTabRun": "Run",
+ "agentQuickAddHint": "If nekoagent is already installed, use this command to add the backend directly",
+ "agentRunHint": "Run agent temporarily without installing (for testing only)",
"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.",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 8c97563..d26a039 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -395,6 +395,7 @@
"agentInfoCopied": "Agent 信息已复制",
"copyBackendId": "复制后端 ID",
"copyAgentId": "复制 Agent 标识",
+ "copy": "复制",
"agentTokenPlaceholder": "粘贴 backend-token(用于生成完整脚本)",
"agentTokenEditHint": "请手动填写 backend-token。",
"agentTokenInputHint": "可手动填写 backend-token 生成脚本(不会保存到服务端)。",
@@ -411,6 +412,11 @@
"agentRotateTokenFailed": "重置 agent 令牌失败",
"agentTokenLocalOnlyHint": "此处令牌仅用于生成复制脚本。",
"openAgentSetup": "查看 Agent 脚本",
+ "scriptTabInstall": "首次安装",
+ "scriptTabAdd": "快速添加",
+ "scriptTabRun": "直接运行",
+ "agentQuickAddHint": "如果 nekoagent 已安装,使用此命令直接添加新 backend",
+ "agentRunHint": "临时运行 Agent(不安装服务,仅用于测试)",
"agentGatewayOptionalHint": "可选:填写网关 host / 端口 / token,复制脚本时会自动带上。",
"agentGatewaySectionTitle": "Gateway 连接参数(写入脚本)",
"agentGatewaySectionHint": "下面参数会用于生成运行命令和安装脚本。",