Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

7.1 KB
Raw Blame
#!/usr/bin/env python3
"""Run Avibe service + Web UI inside the Incus regression systemd service."""

from __future__ import annotations

import os
import signal
import sys
import time
from pathlib import Path

from config import paths
from config.v2_config import V2Config
from scripts.incus_regression import SERVICE_HOME, regression_show_runtime_env
from vibe import runtime
from vibe.upgrade import restart_record_is_pending


def _read_pid_file(pid_path: Path) -> int | None:
    try:
        pid = int(pid_path.read_text(encoding="utf-8").strip())
    except (OSError, ValueError):
        return None
    return pid if pid > 0 else None


def _reap_child(pid: int | None) -> None:
    if not isinstance(pid, int) or pid <= 0 or os.name == "nt":
        return
    try:
        os.waitpid(pid, os.WNOHANG)
    except ChildProcessError:
        return
    except OSError:
        return


def _adoptable_service_pid(pid: int | None) -> bool:
    """Whether a replacement pid may be tracked as this supervisor's service.

    Two questions, and both have to be answered yes. `service_pid_recorded` asks
    whether this is the process the system considers the service: alive, named by
    the pid file, holding the instance lock. `service_instance_started` asks the
    one the lock cannot answer -- whether it finished starting. A restart that
    takes the lock and then hangs in migration satisfies the first for as long as
    it stays alive, so adopting on that alone is exactly how a hung generation
    gets tracked as healthy: the supervisor keeps looping, never exits nonzero,
    and the unit's `Restart=on-failure` never gets its chance.

    Deferring adoption is not refusing it. A healthy replacement is still
    starting for a moment, fails this on that iteration, and is adopted on a
    later one; the only case that never converges is the one that never starts,
    which is the case that must reach the recovery exit.
    """

    return bool(
        pid
        and runtime.service_pid_recorded(pid)
        and runtime.service_instance_started(pid)
    )


def _restart_in_progress() -> bool:
    path = runtime.get_restart_status_path()
    status = runtime.read_json(path) or {}
    # Only the active stop/start phase ("running") should suppress the supervisor's
    # own recovery. A "scheduled" (delayed) restart is just sleeping and hasn't
    # touched the service yet, so a crash during the delay must still be recovered
    # immediately rather than waiting for the job to wake.
    if status.get("ok") is not None or status.get("state") != "running":
        return False
    # And only while the job process is still alive: a stale status left by a
    # killed restart job or a reboot would otherwise keep this true forever, so the
    # supervisor would loop writing "restarting" instead of exiting nonzero to let
    # systemd recover the service.
    restart_pid = status.get("supervisor_pid")
    if not (isinstance(restart_pid, int) and restart_pid > 0 and runtime.pid_alive(restart_pid)):
        return False
    # A live pid is the job only while its recorded identity matches (pid reuse,
    # notably across a reboot), and one that cannot be verified only for a bounded time.
    return restart_record_is_pending(status, path)


def _config() -> V2Config:
    runtime.ensure_dirs()
    return runtime.ensure_config()


def _normalize_show_runtime_source_environment() -> None:
    os.environ.update(
        regression_show_runtime_env(
            os.environ.get("VIBE_SHOW_RUNTIME_SOURCE"),
            SERVICE_HOME,
        )
    )


def main() -> int:
    stopping = False

    def request_stop(signum, frame):  # noqa: ANN001
        nonlocal stopping
        stopping = True

    signal.signal(signal.SIGTERM, request_stop)
    signal.signal(signal.SIGINT, request_stop)

    _normalize_show_runtime_source_environment()
    config = _config()
    service_pid = runtime.start_service(
        wait_for_ready=False,
    )
    bind_host = runtime.effective_ui_bind_host(config)
    ui_pid = runtime.start_ui(
        bind_host,
        config.ui.setup_port,
    )

    # Asked unconditionally: the predicate that used to guard this is the lock,
    # which is held by a process that has not finished migrating and may never.
    ready_service_pid = runtime.wait_for_service_ready(
        service_pid,
        timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
    )
    if ready_service_pid is None:
        runtime.write_status("error", "service did not become ready", service_pid, ui_pid)
        runtime.stop_ui()
        runtime.stop_service()
        return 1
    service_pid = ready_service_pid
    runtime.write_status("running", "incus regression started", service_pid, ui_pid)

    while not stopping:
        # _restart_in_progress() is read fresh at each decision below rather than
        # snapshotted here: a managed restart can begin mid-iteration, and a stale
        # snapshot would let the supervisor kill a healthy restart.
        current_service_pid = _read_pid_file(paths.get_runtime_pid_path())
        # Only track a service pid that has reported it finished starting --
        # see `_adoptable_service_pid`. Adopting a pid just because the file
        # changed, or just because it holds the lock, would let a hung restart
        # masquerade as healthy and block recovery.
        if (
            current_service_pid
            and current_service_pid != service_pid
            and _adoptable_service_pid(current_service_pid)
        ):
            _reap_child(service_pid)
            service_pid = current_service_pid

        # The service starts a UI that died again (core/web_ui_watchdog.py), as
        # it does outside Incus; this loop only reaps the one it started itself.
        current_ui_pid = _read_pid_file(paths.get_runtime_ui_pid_path()) or ui_pid
        if not current_ui_pid or not runtime.pid_alive(current_ui_pid):
            _reap_child(current_ui_pid)
        elif current_ui_pid != ui_pid:
            ui_pid = current_ui_pid

        if not runtime.pid_alive(service_pid):
            _reap_child(service_pid)
            current_service_pid = _read_pid_file(paths.get_runtime_pid_path())
            if (
                current_service_pid
                and current_service_pid != service_pid
                and _adoptable_service_pid(current_service_pid)
            ):
                service_pid = current_service_pid
                time.sleep(1)
                continue
            # Re-read right before the recovery exit: a managed restart may have
            # begun after the dead-service check above, and exiting for systemd
            # would interrupt a healthy restart.
            if _restart_in_progress():
                runtime.write_status("restarting", "incus regression restart in progress", service_pid, ui_pid)
                time.sleep(1)
                continue
            runtime.write_status("error", "service exited in incus regression", service_pid, ui_pid)
            runtime.stop_ui()
            return 1
        time.sleep(1)

    runtime.stop_ui()
    runtime.stop_service()
    runtime.write_status("stopped", "incus regression stopped")
    return 0


if __name__ == "__main__":
    sys.exit(main())