Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

16.3 KB
Raw Blame
"""``CliStatusProber`` — checks binary installation and auth status of a CLI.

Two independent checks:

1. **Binary check**: ``shutil.which(binary_name)`` + invoke ``check_command`` +
   match ``version_parse_regex``. Returns ``(installed, version, binary_path)``.
2. **Auth check**: when ``auth.type != "none"``, ``auth.status_command`` is
   executed and routed through one of the 10 ``StatusParseStrategy`` functions.

Both calls have tight timeouts (10s / 15s) because CLIs tend to hang. On
timeout → ``unknown``, never an exception to the caller.
"""

from __future__ import annotations

import asyncio
import json
import logging
import os
import re
import shutil
from asyncio.subprocess import DEVNULL, PIPE
from typing import Literal

from dodaios.clis.spec import CliSpec, CliStatus, StatusParseStrategy
from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS, resolve_executable

log = logging.getLogger(__name__)

CHECK_TIMEOUT_S = 10.0
AUTH_TIMEOUT_S = 15.0
# After a timed-out probe is kill()ed, how long to wait for the OS to reap it
# before giving up. A .cmd/.bat shim's actual child process can survive
# kill() (the shim exits, the grandchild lives on) — an unbounded
# ``await proc.wait()`` here would then hang the probe (and the synchronous
# bootstrap path that awaits it, see dodaios/clis/loader.py) forever. A leaked
# zombie process beats an infinite hang.
KILL_WAIT_TIMEOUT_S = 2.0
# Budget for a WHOLE catalog sweep. Derived from the per-probe bounds above so
# the two can never drift out of order: a single legitimate probe may spend
# CHECK_TIMEOUT_S + KILL_WAIT_TIMEOUT_S on the binary and AUTH_TIMEOUT_S +
# KILL_WAIT_TIMEOUT_S on the auth check (29s today) before it is anything but
# healthy. The extra headroom covers OS scheduling when ~20 probes each spawn
# their own subprocess at once — on Windows an AV scanner alone can add
# seconds. A sweep budget BELOW the single-probe worst case would fire during
# normal operation instead of acting as a backstop (see BUG: the 30s registry
# ceiling blanked all 22 CLIs on 2026-07-25).
PROBE_ALL_TIMEOUT_S = CHECK_TIMEOUT_S + AUTH_TIMEOUT_S + 2 * KILL_WAIT_TIMEOUT_S + 15.0
# How many catalog probes run at once. Every probe is up to two child
# processes (the binary check, then the auth check), and most of the catalog
# is a Node or Python CLI that spends a second of CPU just printing its
# version. All 22 at once on a machine that had booted a minute earlier meant
# forty interpreter starts inside a second, while the wake-word models were
# still loading off a cold disk — 14 probes were still running at the sweep
# ceiling and the app's own event loop stalled behind the load (2026-08-27,
# BUG-189). Six lanes keep a calm sweep under ten seconds and turn the
# cold-boot burst into a queue.
PROBE_CONCURRENCY = 6
# POSIX: every probe leads its own process group, so a stop reaches what the
# CLI spawned too. ``wrangler --version`` re-launches itself as a child node;
# killing only the parent left that child running past ``jarvis serve``'s exit
# and holding the pipes, so the wait timed out and the transport was collected
# after the loop closed ("Event loop is closed", #534).
_OWN_GROUP = os.name != "nt"


def _kill_probe(proc: asyncio.subprocess.Process) -> None:
    """SIGKILL the probe's whole process group (POSIX), else just the child."""
    pid = getattr(proc, "pid", None)
    killpg = getattr(os, "killpg", None)
    if _OWN_GROUP and killpg is not None and isinstance(pid, int) and pid > 0:
        try:
            killpg(pid, 9)  # SIGKILL; the group id is the leader's pid
            return
        except ProcessLookupError:
            return  # the whole group is already gone
        except OSError:
            pass  # not our group after all: fall back to the child alone
    proc.kill()


async def _cancel_probes(tasks: list[asyncio.Future[CliStatus]]) -> None:
    """Cancel and join the sweep's children even when the sweep is cancelled."""
    if not tasks:
        return

    async def settle() -> None:
        for task in tasks:
            if not task.done() and not getattr(task, "cancelling", lambda: 0)():
                task.cancel()
        done, pending = await asyncio.wait(tasks, timeout=KILL_WAIT_TIMEOUT_S)
        for task in done:
            if not task.cancelled():
                task.exception()  # Retrieve failures from children whose caller is gone.
        if pending:
            log.warning("%d CLI probe(s) did not finish cancellation", len(pending))

    cleanup = asyncio.create_task(settle(), name="cli-probe-cleanup")
    interrupted = False
    while not cleanup.done():
        try:
            await asyncio.shield(cleanup)
        except asyncio.CancelledError:
            # Preserve the bounded cleanup owner when the caller is cancelled
            # during a timeout cleanup, including repeated stop requests.
            interrupted = True
    cleanup.result()
    if interrupted:
        raise asyncio.CancelledError


async def _stop_probe_process(proc: asyncio.subprocess.Process, name: str) -> None:
    """Reap a cancelled or timed-out probe within the existing cleanup budget."""
    # Even a child that already exited may have left its own children in the
    # group (they hold the pipes), so the group is always signalled.
    if proc.returncode is None or _OWN_GROUP:
        try:
            _kill_probe(proc)
        except ProcessLookupError:
            pass  # The child exited between the returncode check and kill.
    try:
        await asyncio.wait_for(proc.wait(), timeout=KILL_WAIT_TIMEOUT_S)
    except TimeoutError:
        log.warning("probe(%s): child did not exit after kill", name)


class CliStatusProber:
    async def probe(self, spec: CliSpec) -> CliStatus:
        installed, version, binary_path = await self._probe_binary(spec)
        if not installed:
            return CliStatus(
                installed=False,
                version=None,
                binary_path=None,
                auth_status="unknown",
            )
        auth_status = await self._probe_auth(spec)
        return CliStatus(
            installed=True,
            version=version,
            binary_path=binary_path,
            auth_status=auth_status,
        )

    async def probe_all(self, specs: list[CliSpec]) -> dict[str, CliStatus]:
        """Probe every spec concurrently and ALWAYS return one row per spec.

        Bounded per spec, not just in aggregate: probes that outlive
        ``PROBE_ALL_TIMEOUT_S`` are cancelled individually and reported as
        unknown, while every probe that finished keeps its real result. The
        old ``wait_for(gather(...))`` shape cancelled the whole sweep, so a
        few wedged Windows ``.cmd`` shims discarded the results of every
        healthy CLI as well (0 tools exposed for the rest of the session).

        A timed-out probe is ``CliStatus()`` — unknown, deliberately WITHOUT
        ``error``: ``cli_routes._status_string`` renders any error as the red
        "error" label, and "we could not finish checking" is not the same
        claim as "this CLI is broken".
        """
        if not specs:
            return {}
        lanes = asyncio.Semaphore(PROBE_CONCURRENCY)

        async def _gated(spec: CliSpec) -> CliStatus:
            async with lanes:
                return await self.probe(spec)

        tasks = [asyncio.ensure_future(_gated(spec)) for spec in specs]
        try:
            await asyncio.wait(tasks, timeout=PROBE_ALL_TIMEOUT_S)
        except asyncio.CancelledError:
            await _cancel_probes(tasks)
            raise

        out: dict[str, CliStatus] = {}
        wedged: list[asyncio.Future[CliStatus]] = []
        for spec, task in zip(specs, tasks, strict=False):
            if not task.done():
                task.cancel()
                wedged.append(task)
                log.warning(
                    "probe(%s): still running after %.0fs — reporting it as "
                    "unknown so the rest of the catalog keeps its results.",
                    spec.name,
                    PROBE_ALL_TIMEOUT_S,
                )
                out[spec.name] = CliStatus()
                continue
            if task.cancelled():
                out[spec.name] = CliStatus()
                continue
            exc = task.exception()
            if exc is not None:
                log.warning("probe(%s) exception: %s", spec.name, exc)
                out[spec.name] = CliStatus(error=str(exc))
            else:
                out[spec.name] = task.result()

        if wedged:
            await _cancel_probes(wedged)
        return out

    async def _probe_binary(self, spec: CliSpec) -> tuple[bool, str | None, str | None]:
        path = shutil.which(spec.binary_name)
        if not path:
            return False, None, None
        # On Windows the binary may be a .cmd/.bat/.ps1 shim (gcloud, npm, ...).
        # ``create_subprocess_exec`` (shell=False) cannot exec a bare name in
        # that case — substitute the resolved full path for argv[0]. See
        # ``process_utils.resolve_executable``.
        check_argv = (path, *spec.check_command[1:])
        try:
            proc = await asyncio.create_subprocess_exec(
                *check_argv,
                stdin=DEVNULL,
                stdout=PIPE,
                stderr=PIPE,
                env={**os.environ, "CI": "true"},
                creationflags=NO_WINDOW_CREATIONFLAGS,
                start_new_session=_OWN_GROUP,
            )
            try:
                out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=CHECK_TIMEOUT_S)
            except (TimeoutError, asyncio.CancelledError) as exc:
                await _stop_probe_process(proc, spec.name)
                if isinstance(exc, asyncio.CancelledError):
                    raise
                return True, None, path
        except FileNotFoundError:
            return False, None, None
        except Exception as exc:  # noqa: BLE001
            log.debug("probe-binary(%s) failed: %s", spec.name, exc)
            return True, None, path
        text = (out_b or b"").decode("utf-8", errors="replace")
        if not text:
            text = (err_b or b"").decode("utf-8", errors="replace")
        version = None
        if spec.version_parse_regex:
            m = re.search(spec.version_parse_regex, text)
            if m and m.groups():
                version = m.group(1)
        return True, version, path

    async def _probe_auth(
        self, spec: CliSpec
    ) -> Literal["connected", "expired", "not_connected", "unknown"]:
        if spec.auth.type == "none" or not spec.auth.status_command:
            return "connected"
        # Resolve argv[0] to the full path so .cmd/.bat shims (gcloud auth list)
        # are exec'able on Windows.
        status_argv = (
            resolve_executable(spec.auth.status_command[0]),
            *spec.auth.status_command[1:],
        )
        try:
            # Status checks must never start an interactive login. In particular,
            # Neon opens a browser from `me` when credentials are missing unless
            # CI is set. Keep this child-local so explicit OAuth login still works.
            proc = await asyncio.create_subprocess_exec(
                *status_argv,
                stdin=DEVNULL,
                stdout=PIPE,
                stderr=PIPE,
                env={**os.environ, "CI": "true"},
                creationflags=NO_WINDOW_CREATIONFLAGS,
                start_new_session=_OWN_GROUP,
            )
            try:
                out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=AUTH_TIMEOUT_S)
            except (TimeoutError, asyncio.CancelledError) as exc:
                await _stop_probe_process(proc, spec.name)
                if isinstance(exc, asyncio.CancelledError):
                    raise
                return "unknown"
            exit_code = proc.returncode or 0
        except FileNotFoundError:
            return "not_connected"
        except Exception as exc:  # noqa: BLE001
            log.debug("probe-auth(%s) failed: %s", spec.name, exc)
            return "unknown"
        stdout = (out_b or b"").decode("utf-8", errors="replace")
        stderr = (err_b or b"").decode("utf-8", errors="replace")
        return _apply_parse_strategy(spec.auth.status_parse, stdout, stderr, exit_code)


def _apply_parse_strategy(
    strategy: StatusParseStrategy,
    stdout: str,
    stderr: str,
    exit_code: int,
) -> Literal["connected", "expired", "not_connected", "unknown"]:
    if exit_code != 0 and strategy not in ("json_array_nonempty_or_error",):
        return "not_connected"

    if strategy == "json_accounts":
        try:
            data = json.loads(stdout or "[]")
        except json.JSONDecodeError:
            return "unknown"
        if isinstance(data, list) and any(
            isinstance(a, dict) and a.get("status") == "ACTIVE" for a in data
        ):
            return "connected"
        return "not_connected"

    if strategy == "json_object_exists":
        try:
            data = json.loads(stdout or "null")
        except json.JSONDecodeError:
            return "not_connected"
        if isinstance(data, dict) and data:
            return "connected"
        return "not_connected"

    if strategy == "json_array_nonempty":
        try:
            data = json.loads(stdout or "[]")
        except json.JSONDecodeError:
            return "not_connected"
        if isinstance(data, list) and len(data) > 0:
            return "connected"
        return "not_connected"

    if strategy == "json_array_nonempty_or_error":
        if exit_code != 0:
            combined = (stderr + stdout).lower()
            if "not logged in" in combined or "unauthorized" in combined or "login" in combined:
                return "not_connected"
            return "unknown"
        return "connected"

    if strategy == "json_has_field_username":
        try:
            data = json.loads(stdout or "null")
        except json.JSONDecodeError:
            return "unknown"
        if not isinstance(data, dict):
            return "unknown"
        if data.get("Username"):
            return "connected"
        return "not_connected"

    if strategy == "json_token_valid":
        # For a CLI that reports its OAuth state as a JSON object with an
        # explicit validity flag (gws). Stored credentials and a *working*
        # token are two different things: `gws auth status` happily prints a
        # full credential block with ``"token_valid": false`` when the refresh
        # call fails. Treating "a credential file exists" as connected is how a
        # CLI ends up green in the UI and broken on first use — so a dead token
        # over stored credentials reports ``expired``, which the UI renders as
        # disconnected and offers Connect for.
        try:
            data = json.loads(stdout or "null")
        except json.JSONDecodeError:
            # Output we cannot read is not evidence either way, and "unknown"
            # is the return value that says exactly that — the caller renders
            # it, so nothing is being swallowed here.
            return "unknown"
        if not isinstance(data, dict):
            return "unknown"
        if data.get("token_valid") is True:
            return "connected"
        has_credentials = any(
            data.get(key)
            for key in ("has_refresh_token", "encrypted_credentials_exists",
                        "plain_credentials_exists", "token_cache_exists")
        )
        return "expired" if has_credentials else "not_connected"

    if strategy == "text_contains_email":
        pattern = r"[\w.+-]+@[\w-]+\.[\w.-]+"
        if re.search(pattern, stdout):
            return "connected"
        return "not_connected"

    if strategy == "text_contains_username":
        if stdout.strip() and "error" not in stdout.lower()[:50]:
            return "connected"
        return "not_connected"

    if strategy == "text_contains_logged_in":
        if re.search(r"logged in", stdout, re.IGNORECASE):
            return "connected"
        return "not_connected"

    if strategy == "text_contains_key":
        if re.search(r"api[_-]?key\s*=\s*\S+", stdout, re.IGNORECASE):
            return "connected"
        return "not_connected"

    if strategy == "text_nonempty":
        return "connected" if stdout.strip() else "not_connected"

    log.warning("unknown status_parse strategy: %r", strategy)
    return "unknown"


__all__ = ["CliStatusProber"]