How Agent Reach's `_detect_environment()` Differentiates Local vs. Server Environments

Agent Reach's _detect_environment() function uses a weighted scoring system that inspects OS-level indicators—SSH sessions, container files, display variables, cloud vendor identifiers, and virtualization status—to classify the runtime as "server" when the score reaches 2 or higher, otherwise returning "local".

The Agent-Reach CLI tool must automatically determine whether it is running on a developer's workstation or a headless cloud instance to select the appropriate installation strategy. The _detect_environment() function in agent_reach/cli.py (lines 977–1016) implements this detection logic by aggregating multiple environment indicators and applying a conservative threshold to minimize false positives.

How the Detection Algorithm Works

The function employs a best-effort scoring mechanism that assigns weights to specific filesystem and environment conditions commonly found in server or containerized deployments.

Weighted Environment Indicators

Each indicator carries a specific point value that contributes to the final classification:

  • SSH Session Detection (+2) – Checks for the presence of SSH_CONNECTION or SSH_CLIENT environment variables using os.environ.get(), indicating a remote shell session.
  • Container Detection (+2) – Verifies existence of /.dockerenv or /run/.containerenv via os.path.exists(), signaling Docker or container runtime environments.
  • Headless Display (+1) – Detects absence of graphical display by confirming both DISPLAY and WAYLAND_DISPLAY environment variables are unset.
  • Cloud VM Identification (+2) – Reads /sys/hypervisor/uuid and /sys/class/dmi/id/product_name to search for vendor strings (amazon, google, microsoft, digitalocean, linode, vultr, hetzner) that indicate cloud hosting.
  • Virtualization Check (+1) – Executes systemd-detect-virt via subprocess.run() and awards points if the result is anything other than "none".

The Conservative Threshold

The function maintains a deliberately conservative stance to avoid misclassifying local workstations as servers. It sums all matched indicators into a single indicators variable and applies a strict threshold: if indicators >= 2, the function returns "server"; otherwise, it returns "local". This ensures that a single strong signal—such as an active SSH session—is sufficient to trigger server mode, while multiple weaker signals must combine to reach the threshold.

Source Code Implementation

According to the Agent-Reach source code, the implementation resides in agent_reach/cli.py and handles edge cases gracefully with exception suppression:

def _detect_environment():
    import os, subprocess
    indicators = 0

    if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_CLIENT"):
        indicators += 2
    if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
        indicators += 2
    if not os.environ.get("DISPLAY") and not os.environ.get("WAYLAND_DISPLAY"):
        indicators += 1
    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:
                    if any(x in f.read().lower()
                           for x in ["amazon", "google", "microsoft",
                                     "digitalocean", "linode", "vultr", "hetzner"]):
                        indicators += 2
            except Exception:
                pass
    try:
        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

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

The function uses defensive programming with try/except blocks when reading cloud vendor files and executing subprocess commands, ensuring the detection logic never crashes the installation process.

Practical Implementation Examples

The _detect_environment() function enables dynamic behavior throughout the Agent Reach codebase.

Detecting Environment in Scripts

You can import the function directly to adjust behavior based on the detected environment:

from agent_reach.cli import _detect_environment

env = _detect_environment()
print(f"Running in a {env} environment")

# Output: "Running in a local environment" on laptops

# Output: "Running in a server environment" on headless VMs or containers

Conditional Dependency Installation

The primary use case within the CLI involves routing to different installation paths based on the detected environment:

from agent_reach.cli import _detect_environment, _install_opencli_deps, _install_rdt_cli

if _detect_environment() == "server":
    _install_rdt_cli()      # headless-friendly client

else:
    _install_opencli_deps() # desktop-friendly client with GUI support

Unit Testing with Mocks

The test suite in tests/test_cli.py (lines 916–931) verifies environment detection by mocking the function return values:

import pytest
import agent_reach.cli as cli

def test_detect_environment_local(monkeypatch):
    monkeypatch.setattr(cli, "_detect_environment", lambda: "local")
    assert cli._detect_environment() == "local"

def test_detect_environment_server(monkeypatch):
    monkeypatch.setattr(cli, "_detect_environment", lambda: "server")
    assert cli._detect_environment() == "server"

Integration Across the Codebase

The environment detection logic extends beyond the CLI into other system components:

  • agent_reach/doctor.py – Uses the detected environment to tailor diagnostic output and system health checks for headless versus graphical systems.
  • agent_reach/config.py – References the environment type when determining default configuration paths and display-related settings.

Summary

  • _detect_environment() in agent_reach/cli.py implements a weighted scoring system to classify runtime environments.
  • Server indicators include SSH sessions (+2), container files (+2), cloud vendor IDs (+2), missing displays (+1), and virtualization (+1).
  • The threshold requires a minimum score of 2 to classify as "server", ensuring conservative detection that tolerates ambiguous environments.
  • Downstream components use this classification to select between desktop-oriented tools (OpenCLI) and headless-friendly alternatives (rdt-cli).

Frequently Asked Questions

What happens if _detect_environment() cannot determine the environment?

If all indicator checks fail or raise exceptions, the function returns "local" by default. This conservative fallback prevents misconfiguration of graphical tools on potentially unknown systems, ensuring the CLI remains functional even in exotic or restricted environments.

Can the detection logic be overridden by users?

While the source code does not expose a direct command-line flag to force the environment type, users can manipulate the underlying indicators—such as setting SSH_CONNECTION or creating /.dockerenv—to influence the scoring. For testing purposes, developers can monkeypatch the function as demonstrated in the tests/test_cli.py suite.

Why does the function check for both Docker and container environment files?

The function checks for both /.dockerenv and /run/.containerenv to support multiple container runtimes. While /.dockerenv is Docker-specific, /run/.containerenv is used by Podman and other OCI-compliant runtimes, ensuring broad compatibility across different containerization technologies.

How does this detection impact the Agent Reach installation process?

The detected environment determines whether the installer configures desktop-oriented dependencies (requiring display capabilities) or headless server tools (optimized for remote/cloud usage). This automatic routing prevents installation failures on containers lacking X11 or Wayland support while ensuring workstations receive full graphical functionality.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →