# How Agent Reach Auto-Environment Detection Distinguishes Server from Desktop

> Learn how Agent Reach's auto-environment detection uses a scoring heuristic to differentiate between server and desktop environments based on SSH sessions, headless displays, and VM identifiers.

- Repository: [Pnant/Agent-Reach](https://github.com/Panniantong/Agent-Reach)
- Tags: internals
- Published: 2026-07-11

---

**Agent Reach uses a scoring-based heuristic in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) that assigns points for SSH sessions, container markers, headless displays, cloud VM identifiers, and virtualization status, classifying the environment as "server" when the accumulated score reaches 2 or higher.**

Agent Reach, an open-source automation framework maintained in the `Panniantong/Agent-Reach` repository, automatically determines whether it is running on a headless VPS or a local desktop to tailor its installation process. The detection logic resides in the private function `_detect_environment()` within [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) (lines 777–816) and evaluates multiple environmental indicators to ensure appropriate component selection without requiring manual configuration.

## The Scoring-Based Detection Algorithm

The core algorithm implements a weighted scoring system where specific environmental clues contribute points to an `indicators` counter. The function returns `"server"` when `indicators >= 2`, otherwise returning `"local"`.

### SSH Session Detection (+2 Points)

The function checks for the presence of `SSH_CONNECTION` or `SSH_CLIENT` environment variables. If either exists, the algorithm adds **2 points**, strongly indicating a remote server environment where the user connected via SSH.

### Container Environment Markers (+2 Points)

The detection logic inspects the filesystem for container-specific marker files. Existence of either `/.dockerenv` or `/run/.containerenv` contributes **2 points**, immediately pushing most Docker and containerized environments toward the server classification.

### Headless Display Detection (+1 Point)

For desktop identification, the algorithm verifies display server availability. Absence of both `DISPLAY` (X11) and `WAYLAND_DISPLAY` (Wayland) environment variables adds **1 point**, suggesting a headless machine without a graphical session.

### Cloud Provider Identification (+2 Points)

The function reads system files `/sys/hypervisor/uuid` and `/sys/class/dmi/id/product_name` to detect cloud virtualization. If these files contain vendor strings such as "amazon", "google", "microsoft", or "digitalocean", the algorithm assigns **2 points**, recognizing common cloud VPS environments.

### Virtualization Detection (+1 Point)

Finally, the code executes `systemd-detect-virt` and checks whether the output differs from `"none"`. Any virtualization result (e.g., "kvm", "qemu", "xen") contributes **1 point**, helping identify virtual machines versus bare-metal desktops.

## Source Code Implementation

The `_detect_environment()` function aggregates these checks as implemented in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py):

```python
def _detect_environment():
    """Auto-detect if running on local computer or server."""
    import os
    import subprocess
    
    indicators = 0
    
    # SSH detection (+2)

    if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_CLIENT"):
        indicators += 2
    
    # Container detection (+2)

    if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
        indicators += 2
    
    # Headless detection (+1)

    if not os.environ.get("DISPLAY") and not os.environ.get("WAYLAND_DISPLAY"):
        indicators += 1
    
    # Cloud VM detection (+2)

    try:
        with open("/sys/class/dmi/id/product_name") as f:
            product = f.read().lower()
            if any(vendor in product for vendor in ["amazon", "google", "microsoft", "digitalocean"]):
                indicators += 2
    except FileNotFoundError:
        pass
    
    # Virtualization detection (+1)

    try:
        result = subprocess.run(["systemd-detect-virt"], capture_output=True, text=True)
        if result.stdout.strip() != "none":
            indicators += 1
    except (FileNotFoundError, subprocess.CalledProcessError):
        pass
    
    return "server" if indicators >= 2 else "local"

```

## Using Auto-Detection in Practice

### Command-Line Installation

When running the installer, the `--env=auto` flag invokes the detection automatically:

```bash
agent-reach install --env=auto

```

The CLI prints the determined mode:
- `Environment: Server/VPS (auto-detected)` when the score reaches 2+
- `Environment: Local computer (auto-detected)` when the score remains below 2

### Programmatic Access

You can import and call the detection function directly in Python:

```python
from agent_reach.cli import _detect_environment

env = _detect_environment()
print(f"The current environment is: {env}")

# Outputs: "server" or "local"

```

### Manual Override

Bypass the heuristic for testing or specific deployment scenarios:

```bash
agent-reach install --env=server   # Force server mode

agent-reach install --env=local    # Force desktop mode

```

## Integration with Installation Workflow

According to the `Panniantong/Agent-Reach` source code, the `_cmd_install` function consumes `_detect_environment()`'s output to conditionally enable components. When `"server"` is detected, the installer skips OpenCLI-only channels that require a real desktop Chrome session and suppresses desktop-specific dependencies. Conversely, `"local"` mode ensures graphical automation tools are included.

## Related Configuration Files

The detection result propagates through three key files:

- **[`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py)** – Contains the `_detect_environment()` implementation and installation logic (lines 777–816)
- **[`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py)** – Stores the detected environment flag for downstream component access
- **[`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py)** – Uses the environment classification to run appropriate diagnostics and verify platform availability

## Summary

- Agent Reach requires **2 or more points** to classify an environment as a server; otherwise it treats it as a local desktop.
- **SSH sessions** and **container markers** provide the highest weights (2 points each) for immediate server classification.
- The algorithm inspects environment variables, filesystem markers (`/.dockerenv`, `/run/.containerenv`), display variables, cloud provider strings in DMI data, and `systemd-detect-virt` output.
- The logic resides in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) and directly influences the `_cmd_install` routine to skip incompatible desktop components on headless systems.

## Frequently Asked Questions

### What is the threshold for classifying an environment as a server in Agent Reach?

The threshold is **2 points**. The `_detect_environment()` function sums weighted indicators and returns `"server"` only when the accumulated score is 2 or higher; otherwise it returns `"local"`. This ensures that single indicators (like missing displays) do not incorrectly classify a desktop as a server if other desktop markers are present.

### Can I override the automatic environment detection in Agent Reach?

Yes. You can bypass the heuristic entirely by passing `--env=server` or `--env=local` to the `agent-reach install` command. This forces the specific mode regardless of the detected SSH sessions, container files, or display variables, which is useful for testing or deployment scenarios where the heuristic might misidentify the hardware.

### Why does Agent Reach check for cloud provider strings in system files?

The function reads `/sys/hypervisor/uuid` and `/sys/class/dmi/id/product_name` to identify cloud VMs from providers like AWS, Google Cloud, Azure, and DigitalOcean, assigning **2 points** when detected. These environments are typically headless servers, and identifying them prevents the installer from attempting to configure desktop automation components that require a graphical interface.

### How does the detection handle Docker containers?

The presence of `/.dockerenv` or `/run/.containerenv` files adds **2 points** to the score. Since containers typically run without displays and often on servers, this weighting immediately pushes most containerized environments into the `"server"` classification, ensuring appropriate component selection for containerized deployments.