# How Agent Reach's `_detect_environment` Automatically Differentiates Local and Server Environments

> Agent Reach's _detect_environment automatically differentiates local and server environments by scoring OS indicators like SSH and container files. Learn how it works.

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

---

**Agent Reach's `_detect_environment()` function assigns weighted points to OS-level indicators such as SSH connections, container files, and cloud metadata, returning `"server"` when the cumulative score reaches 2 or higher and `"local"` otherwise.**

Agent Reach is an open-source CLI tool that adapts its behavior based on whether it's running on a developer workstation or a headless server. At the heart of this capability is the **`_detect_environment()`** helper implemented in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py). When you invoke commands like `agent-reach install` with the default `--env=auto` flag, this function inspects the underlying operating system to determine the deployment context without requiring manual configuration.

## How the Point-Based Detection Algorithm Works

The detection system implemented in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) (lines 975–1014) uses a weighted scoring mechanism that tallies "indicator" points based on universal OS-level clues. Each check looks for specific files or environment variables commonly present in server or containerized environments.

### SSH Session Detection

Remote administrative access is a strong server indicator. The function checks for the presence of `SSH_CONNECTION` or `SSH_CLIENT` environment variables:

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

```

This check adds **2 points** to the score, recognizing that SSH sessions almost always indicate remote server access rather than local desktop usage.

### Container and Docker Detection

Containerized environments are typically headless servers. The function probes for container-specific marker files:

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

```

Detecting either `/.dockerenv` or `/run/.containerenv` contributes **2 points**, as these files exist only inside Docker or podman containers.

### Display and Graphics Environment

Local machines usually have graphical displays. The function checks for the absence of display server variables:

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

```

Missing both `DISPLAY` and `WAYLAND_DISPLAY` environment variables adds **1 point**, indicating a likely headless server environment.

### Cloud Provider Identifiers

Major cloud vendors leave specific fingerprints in the system filesystem. The function reads `/sys/hypervisor/uuid` or `/sys/class/dmi/id/product_name` for strings such as "amazon", "google", "microsoft", "digitalocean", "linode", "vultr", or "hetzner":

```python

# Simplified logic from lines 990-999 of agent_reach/cli.py

cloud_files = ["/sys/hypervisor/uuid", "/sys/class/dmi/id/product_name"]
for f in cloud_files:
    if os.path.exists(f):
        content = open(f).read().lower()
        if any(vendor in content for vendor in ["amazon", "google", "microsoft"]):
            indicators += 2

```

Each cloud vendor match adds **2 points**, providing reliable detection of virtualized cloud instances.

### Virtualization Detection

As a fallback for other virtualized environments, the function executes `systemd-detect-virt`:

```python
import subprocess
result = subprocess.run(["systemd-detect-virt"], capture_output=True, text=True)
if result.stdout.strip() != "none":
    indicators += 1

```

When `systemd-detect-virt` returns anything other than `"none"`, the function adds **1 point** to the indicator score.

## The Threshold Logic and Return Values

After evaluating all indicators, the function applies a simple threshold to classify the environment:

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

```

According to the source code in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py), any environment scoring **2 or more points** is classified as `"server"`, while scores of 0 or 1 return `"local"`. This lightweight approach works across Linux distributions, macOS, and CI containers without external dependencies.

## Practical Usage and Code Examples

You can observe this detection in action when running the Agent Reach installer:

```bash
$ agent-reach install --env=auto
Environment: Server/VPS (auto-detected)

# or on a laptop:

Environment: Local computer (auto-detected)

```

To programmatically check the current environment, import the function directly:

```python
>>> from agent_reach.cli import _detect_environment
>>> _detect_environment()
'server'  # or 'local' depending on your context

```

The complete implementation handles edge cases and multiple cloud providers, as seen in the full source at [lines 975–1014 of agent_reach/cli.py](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py#L975-L1014).

## Summary

- Agent Reach uses **`_detect_environment()`** in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py) to automatically distinguish between local and server environments.
- The function employs a **weighted point system** checking SSH variables (+2), container files (+2), display absence (+1), cloud metadata (+2), and virtualization (+1).
- Environments scoring **2 or more points** return `"server"`; lower scores return `"local"`.
- This detection enables context-aware behavior, such as providing server-specific proxy configurations for Bilibili or other regional services.
- The logic relies only on standard OS files and environment variables, ensuring compatibility across Linux, macOS, and containerized CI environments.

## Frequently Asked Questions

### What triggers a "server" classification in Agent Reach?

Any combination of indicators totaling 2 or more points triggers a server classification. Common triggers include running inside an SSH session (+2), detecting a Docker container (+2), or identifying as a cloud VM (+2). Even a headless display environment (+1) combined with virtualization detection (+1) will reach the threshold.

### Can I override the automatic environment detection?

Yes. While the default `agent-reach install` command uses `--env=auto`, you can explicitly specify `--env=local` or `--env=server` to bypass the `_detect_environment()` logic entirely. This is documented in the project's [`README.md`](https://github.com/Panniantong/Agent-Reach/blob/main/README.md) and useful when the heuristic incorrectly identifies specialized development environments.

### Does the detection work on macOS and Windows?

The `_detect_environment()` function relies primarily on Unix-specific files (like `/.dockerenv` and `/sys/class/dmi/id`) and Linux utilities (`systemd-detect-virt`). While the SSH and DISPLAY checks work across platforms, macOS and Windows may not trigger container or cloud-specific indicators, typically causing them to classify as "local" environments unless running in specific virtualized contexts.

### Where is the environment detection logic located in the repository?

The core detection algorithm resides in **[`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py)** between lines 975 and 1014. The [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) module consumes this detection result to perform environment-specific health checks, but does not perform the detection itself. The CLI flag handling that invokes this logic is also implemented in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py).