# How Agent Reach Auto-Detects Local vs Server Environments

> Learn how Agent Reach auto-detects local vs server environments using a weighted heuristic system. Inspects SSH, containers, cloud VMs & more for accurate classification.

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

---

**Agent Reach uses a weighted heuristic system in `_detect_environment()` that inspects SSH sessions, container files, display variables, cloud VM identifiers, and virtualization status to classify the machine as "server" (2+ indicators) or "local".**

Agent Reach is an open-source CLI tool that automatically determines whether it is running on a local workstation or a remote server using environment heuristics. The detection logic resides in the [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) file and triggers by default when using the `--env auto` flag during installation. This automatic classification ensures that server-specific configurations like safe mode and proxy settings are applied only when appropriate.

## The Detection Engine in agent_reach/cli.py

When the CLI is invoked with `--env auto` (the default for `agent-reach install`), Agent Reach executes an internal helper named **`_detect_environment`** located at lines 955–994 in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py). The function aggregates weighted indicators from five distinct environmental checks. If the total score reaches **2 or more**, the environment is classified as **`"server"`**; otherwise it returns **`"local"`**.

The threshold of 2 prevents false positives—a single indicator (such as a missing DISPLAY variable on a headless local laptop) is insufficient to trigger server mode, while two modest signals or one strong signal (like a Docker container) reliably indicates a non-interactive server environment.

## The Five Detection Heuristics

### SSH Session Detection

The function checks for the presence of `SSH_CONNECTION` or `SSH_CLIENT` environment variables, which indicate an active SSH session typical of remote server administration.

```python

# agent_reach/cli.py

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

```

**Weight:** +2 points

### Docker and Container Detection

The code inspects for container-specific files that exist inside Docker or Podman environments.

```python

# agent_reach/cli.py

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

```

**Weight:** +2 points

### Headless Display Check

The function verifies the absence of graphical display servers by checking for `DISPLAY` or `WAYLAND_DISPLAY` environment variables.

```python

# agent_reach/cli.py

if not os.environ.get("DISPLAY") and not os.environ.get("WAYLAND_DISPLAY"):
    indicators += 1

```

**Weight:** +1 point

### Cloud VM Identifier Inspection

The detection reads system files that expose hypervisor or cloud provider metadata, specifically `/sys/hypervisor/uuid` and `/sys/class/dmi/id/product_name`. It scans for cloud provider strings including "amazon", "google", "microsoft", "digitalocean", "linode", "vultr", and "hetzner".

```python

# agent_reach/cli.py

for cloud_file in ["/sys/hypervisor/uuid", "/sys/class/dmi/id/product_name"]:
    if os.path.exists(cloud_file):
        try:
            with open(cloud_file) as f:
                content = f.read().lower()
            if any(x in content for x in [
                "amazon", "google", "microsoft",
                "digitalocean", "linode", "vultr", "hetzner"
            ]):
                indicators += 2
        except Exception:
            pass

```

**Weight:** +2 points (if any match)

### systemd-detect-virt Integration

The function executes `systemd-detect-virt` to query the operating system's virtualization status, adding a point if the output is anything other than "none".

```python

# agent_reach/cli.py

try:
    import subprocess
    result = subprocess.run(
        ["systemd-detect-virt"], capture_output=True,
        encoding="utf-8", errors="replace", timeout=3
    )
    if result.returncode == 0 and result.stdout.strip() != "none":
        indicators += 1
except Exception:
    pass

```

**Weight:** +1 point

This subprocess call relies on UTF-8 environment handling implemented in [`agent_reach/utils/process.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/utils/process.py) (lines 14–22) to ensure proper encoding across different Linux distributions.

## Scoring Threshold and Classification Logic

The scoring system uses integer weights to distinguish between strong and weak signals:

| Indicator | Weight | Signal Strength |
|-----------|--------|-----------------|
| SSH session | +2 | High |
| Docker/container | +2 | High |
| Cloud VM files | +2 | High |
| Headless display | +1 | Low |
| systemd-detect-virt | +1 | Low |

The final classification logic follows this simple rule:

```python

# agent_reach/cli.py

return "server" if indicators >= 2 else "local"

```

This means a machine running inside an AWS EC2 instance (cloud VM detection, +2) automatically triggers server mode, while a local laptop running Docker Desktop for Mac would need a second indicator (such as SSH or missing display) to reach the threshold.

## Usage Examples

### CLI Auto-Detection

To let Agent Reach decide the environment automatically during installation:

```bash
python -m agent_reach.cli install --env auto

```

This internally triggers `env = _detect_environment()` and applies server-specific configurations like MC-Porter safe mode or proxy settings when the result is `"server"`.

### Direct Python API Access

You can query the detection logic directly in Python:

```python
from agent_reach.cli import _detect_environment

result = _detect_environment()
print(result)  # Outputs: 'server' or 'local'

```

The test suite in [`tests/test_cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/tests/test_cli.py) (lines 88–100) verifies that `--env auto` correctly switches behavior based on mocked environments, ensuring the heuristics work across different deployment scenarios.

## Summary

- **Agent Reach auto-detects local vs server environments** using the `_detect_environment()` function in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py).
- **Five weighted heuristics** inspect SSH sessions, container files, display variables, cloud VM identifiers, and virtualization status.
- **A threshold of 2+ indicators** triggers `"server"` classification; otherwise it returns `"local"`.
- **Strong signals** (SSH, containers, cloud VMs) contribute +2 points; **weak signals** (headless display, virtualization) contribute +1 point.
- The detection influences downstream logic such as safe mode installation and proxy configuration.

## Frequently Asked Questions

### How accurate is Agent Reach's server detection?

The weighted scoring system minimizes false positives by requiring at least two indicators or one strong indicator (like a Docker container or cloud VM file) before classifying as server. This prevents headless local laptops from being misidentified while reliably catching remote servers accessed via SSH or running on major cloud providers.

### Can I force a specific environment if auto-detection fails?

Yes, the `--env` flag accepts explicit values. While `--env auto` triggers the `_detect_environment()` heuristics, you can override this with `--env local` or `--env server` to bypass automatic detection and force a specific configuration profile.

### Why does the detection check for systemd-detect-virt?

The `systemd-detect-virt` command provides a standardized way to identify virtual machines and containers on Linux systems that might not expose Docker-specific files or clear SSH environment variables. This catches KVM, QEMU, Xen, and other virtualization platforms that indicate server environments, adding a +1 weight to the indicator count.

### Where are the tests for environment detection located?

The test coverage for `--env auto` behavior resides in [`tests/test_cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/tests/test_cli.py) at lines 88–100, which mocks various environment variables and file system states to verify that the `_detect_environment()` function correctly identifies server vs local contexts under different conditions.