How the Agent-Reach Probe Command Checks if a Backend Is Functional

The probe_command utility classifies backend health into five distinct statuses—ok, missing, broken, timeout, or error—by locating the binary, executing a test command, and analyzing exit codes and exceptions.

The probe_command function in the Agent-Reach repository provides channels with a reliable mechanism to verify that required external CLI tools are present, executable, and behaving correctly before use. Defined in agent_reach/probe.py, this utility enables the doctor command to report accurate health diagnostics by determining whether a backend is functional through systematic binary validation and controlled subprocess execution.

Five Status Classifications

The probe system categorizes backend availability into one of five states defined in the ProbeResult dataclass:

  • ok – The command executed successfully with a zero exit code.
  • missing – The binary is not found on PATH via shutil.which.
  • broken – The binary exists but cannot be executed due to missing interpreters or stale virtual environments.
  • timeout – The command exceeded the configured time limit.
  • error – The command returned a non-zero exit code that does not indicate a broken installation.

Step-by-Step Execution Flow

The probe_command function orchestrates the health check through a precise sequence implemented in agent_reach/probe.py.

1. Binary Location Verification

First, the utility locates the executable using shutil.which(cmd) (lines 63‑65). If the binary is absent from the system PATH, the function immediately returns a ProbeResult with status="missing", avoiding unnecessary subprocess overhead.

2. Subprocess Execution with Safety Controls

Once located, the binary is executed via _run_once (lines 79‑103). This helper invokes subprocess.run with the following safeguards:

  • capture_output=True to collect stdout and stderr
  • encoding="utf-8" with errors="replace" for safe text decoding
  • A configurable timeout parameter to prevent hangs
  • A sanitized environment from utf8_subprocess_env() (provided by agent_reach/utils/process.py)

3. Exception-Based Error Classification

The _run_once function traps specific exceptions to determine failure modes (lines 89‑95):

  • FileNotFoundError or OSError – Indicates the shim was found but the underlying interpreter is missing, resulting in a broken status.
  • subprocess.TimeoutExpired – Results in a timeout status when the command hangs.

4. Exit Code Interpretation

After execution, the function analyzes the process return code (lines 97‑102):

  • Exit codes 126 or 127 (standard shell codes for "command found but not executable" or "command not found") map to broken.
  • Any other non-zero exit code is classified as error, preserving the captured output for debugging.
  • A zero exit code yields ok with trimmed output (line 103).

5. Retry Mechanism for Transient Failures

If the retries parameter is greater than zero, probe_command implements a retry loop (lines 68‑76). The logic stops early for definitive results (ok, missing, or broken), but retries transient failures (timeout or error) until the retry limit is exhausted.

ProbeResult Data Structure

The ProbeResult dataclass (lines 27‑32) encapsulates the check outcome with three fields:

status: str   # "ok" | "missing" | "broken" | "timeout" | "error"

output: str   # Captured stdout/stderr if available

hint: str     # Optional guidance for fixing the issue

When a backend is marked broken, the reinstall_hint helper (lines 38‑44) generates user-friendly remediation advice using the supplied package parameter (defaulting to the command name) to suggest reinstallation steps.

Practical Implementation Examples

The following examples demonstrate how channels invoke the probe system:

from agent_reach.probe import probe_command

# Check if yt-dlp is installed and responsive

result = probe_command("yt-dlp")
if result.ok:
    print("yt-dlp is functional:", result.output)
else:
    print(f"yt-dlp probe failed ({result.status}); hint: {result.hint}")

# Advanced check with custom arguments and retry logic

result = probe_command(
    cmd="opencli",
    args=("--daemon-status",),
    timeout=5,
    retries=1,
    package="opencli"  # Used in reinstall hints if broken

)
print(result.status, result.hint)

Integration with Agent-Reach Architecture

Channel implementations such as agent_reach/channels/twitter.py and agent_reach/channels/xiaohongshu.py call probe_command inside their respective check() methods to verify required CLI tools before attempting reads or searches. The agent_reach/doctor.py module aggregates these probe results across all channels to produce a comprehensive system health report, ensuring that only functional backends are utilized.

Summary

  • The probe_command function in agent_reach/probe.py validates backend functionality through a five-status classification system.
  • Binary presence is verified via shutil.which before execution, returning missing immediately if absent.
  • The _run_once helper executes commands with UTF-8 encoding, timeout protection, and sanitized environments.
  • Exit codes 126 and 127 specifically indicate broken installations, while other non-zero codes return error.
  • A retry mechanism handles transient timeout and error states while bypassing retries for definitive missing or broken results.
  • Channel implementations integrate this utility to ensure external CLI dependencies are operational before use.

Frequently Asked Questions

What exit codes indicate a "broken" backend in Agent-Reach?

Exit codes 126 (command found but not executable) and 127 (command not found) specifically trigger the broken status in agent_reach/probe.py (lines 97‑99). These codes typically indicate stale virtual environments or missing interpreters rather than mere absence from PATH.

How does probe_command handle transient network or timeout issues?

The probe_command function accepts a retries parameter that re-invokes _run_once when encountering timeout or error statuses (lines 68‑76). The loop terminates early for definitive failures (missing or broken), ensuring retries are reserved exclusively for potentially recoverable transient conditions.

What information does ProbeResult provide when a probe fails?

The ProbeResult dataclass (lines 27‑32) returns three fields: status (the classification string), output (captured stdout/stderr from the attempt), and hint (optional remediation guidance generated by reinstall_hint). For broken backends, the hint suggests reinstallation commands using the specified package name.

How can I customize the health-check arguments for a specific backend?

Pass a tuple of arguments to the args parameter when calling probe_command. For example, args=("--version",) or args=("--daemon-status",) allows you to invoke side-effect-free status commands appropriate to the specific CLI tool, ensuring the probe accurately reflects the backend's operational state.

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 →