# How Does Agent-Reach Doctor Identify the Active Backend for Each Platform?

> Agent-Reach doctor identifies active backends by running platform-specific health probes via channel check methods, storing results in the active_backend attribute.

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

---

**Agent-Reach's `doctor` command determines the active backend for each platform by delegating detection to individual channel `check` methods, which execute health probes and store the result in an `active_backend` attribute.**

The `doctor` diagnostic tool in the Panniantong/Agent-Reach repository provides transparent visibility into which external tools (like `yt-dlp`, `curl`, or custom extractors) are currently functional for each supported platform. Rather than guessing or relying on static configuration, the system probes actual command availability and executability at runtime.

## The Three-Phase Detection Flow

The identification process follows a delegation pattern where the `doctor` module orchestrates checks while individual channels implement platform-specific validation logic.

### 1. Channel Registry Iteration

In [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py), the `check_all` function retrieves the complete channel registry by calling `agent_reach.channels.get_all_channels()` at line 12. This returns every supported platform (YouTube, Bilibili, Twitter/X, etc.) that Agent-Reach can potentially interact with.

The function then iterates over this registry, preparing to assess each channel independently.

### 2. Channel-Specific Health Probing

For each channel instance `ch`, the system invokes `ch.check(config)`, passing the current user configuration. Concrete channel implementations override this method to perform real validation.

Consider the YouTube implementation in [`agent_reach/channels/youtube.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/youtube.py) (lines 35-50):

```python
def check(self, config=None):
    probe = probe_command("yt-dlp", ["--version"], timeout=10, package="yt-dlp")
    if probe.status != "ok":
        self.active_backend = None
        return "off", "yt-dlp 未安装。安装：pip install yt-dlp"
    # backend is alive

    self.active_backend = "yt-dlp"
    # further warnings (JS runtime) do NOT change the active backend

    return "ok", "可提取视频信息和字幕"

```

Here, `probe_command` (implemented in [`agent_reach/probe.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/probe.py)) attempts to execute `yt-dlp --version` with a 10-second timeout. If the command succeeds, the channel sets `self.active_backend = "yt-dlp"`. If the probe fails or the executable is missing, it explicitly sets `self.active_backend = None`, ensuring the system never reports a broken backend as active.

### 3. Active Backend Extraction

After the health probe completes, `doctor.check_all` captures the result using `getattr(ch, "active_backend", None)` at lines 21-23 of [`doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/doctor.py). This defensive extraction handles channels that may not implement backend detection by defaulting to `None`.

The function compiles a status dictionary for each channel containing:
- `"active_backend"`: The string name of the working backend (e.g., `"yt-dlp"`, `"curl"`) or `None`
- Status, message, tier, and other diagnostic metadata

During report rendering, the `_name_msg` function (lines 38-44) conditionally appends a "当前后端" (current backend) label when an active backend exists and the channel offers multiple backend candidates.

## Base Class Architecture and Defaults

The abstract `Channel` class in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py) (lines 34-70) defines the `active_backend` attribute and provides a fallback `check` implementation. The default behavior simply reports the first entry in `self.backends` as the active one:

```python
def check(self, config=None) -> Tuple[str, str]:
    self.active_backend = self.backends[0] if self.backends else "内置"
    return "ok", f"{'、'.join(self.backends) if self.backends else '内置'}"

```

However, robust channel implementations override this behavior to perform actual executable validation via `probe_command`, ensuring `active_backend` reflects reality rather than configuration intent.

## Practical Code Examples

To inspect active backends programmatically:

```python
from agent_reach.doctor import check_all
from agent_reach.config import Config

cfg = Config()                     # loads user configuration

status = check_all(cfg)            # → dict keyed by channel name

# Example of inspecting the active backend for YouTube

youtube_info = status["youtube"]
print(f"YouTube backend: {youtube_info['active_backend']}")

# → "yt-dlp" if probe succeeded, otherwise None

# Iterate all platforms

for platform, info in status.items():
    backend = info.get('active_backend')
    print(f"{platform}: {backend if backend else 'No active backend'}")

```

The probe utility handles cross-platform executable detection, timeout management, and error categorization, allowing channel implementations to focus on business logic rather than subprocess boilerplate.

## Summary

- **Delegation Pattern**: The `doctor` command does not centrally detect backends; it delegates to each channel's `check` method in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) (line 12).
- **Runtime Verification**: Concrete channels like YouTube use `probe_command` from [`agent_reach/probe.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/probe.py) to verify executables (e.g., `yt-dlp --version`) before marking them active.
- **Explicit Storage**: Validated backends are stored in the `active_backend` instance attribute, extracted via `getattr` at lines 21-23 of [`doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/doctor.py).
- **Graceful Degradation**: Missing or broken backends result in `active_backend = None`, ensuring the system reports accurate availability status.
- **Configurable Fallbacks**: The base class in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py) provides default ordering logic that respects user configuration overrides.

## Frequently Asked Questions

### What happens if a backend executable is installed but broken?

If a command exists but returns a non-zero exit code or times out, `probe_command` captures this as a failed status. The channel's `check` method then sets `active_backend` to `None` and reports the channel as "off" or degraded, preventing Agent-Reach from attempting to use the broken tool during actual operations.

### Can users override which backend is selected when multiple are available?

Yes. The base `Channel` class implements `ordered_backends` (in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py)) which respects user configuration overrides. While the `check` method verifies availability, the ordering logic determines which available backend is preferred and reported as "active" when multiple candidates exist.

### How does the doctor command handle platforms with no external dependencies?

Channels that rely solely on internal Python implementations (no external CLI tools) set `active_backend` to `"内置"` (built-in) or `None` depending on the implementation. The base class default at lines 34-70 of [`base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/base.py) handles this by returning the first configured backend or a built-in identifier when the backends list is empty.

### Is the active backend detection performed every time I run agent-reach?

The `doctor` command performs detection on-demand when invoked. However, individual channels may cache probe results or configuration states during the lifetime of the Agent-Reach process. For persistent scripts, calling `check_all` provides a fresh snapshot of backend availability accurate to the moment of execution.