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.

12.7 KB
Raw Blame
"""Stable supervisor for one managed watch command."""

from __future__ import annotations

import json
import os
import signal
import subprocess
import sys
import threading
import time
from typing import Any, BinaryIO

import psutil

PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
HIDE_CONSOLE_ENV = "AVIBE_SUPERVISOR_HIDE_CONSOLE"
WATCH_WORKER_PROTOCOL_VERSION = 1
WATCH_WORKER_ERROR_PREFIX = "AVIBE_WATCH_WORKER_ERROR:"
_MAX_SPEC_BYTES = 16 * 1024 * 1024


class WatchWorkerProtocolError(ValueError):
    def __init__(self, code: str):
        super().__init__(code)
        self.code = code


class _CommandSpawnError(Exception):
    """The operating system refused to start the requested command."""

    def __init__(self, error: OSError):
        super().__init__(str(error))
        self.os_errno = error.errno if isinstance(error.errno, int) else None


def encode_watch_worker_spec(
    *,
    command: list[str],
    shell_command: str | None,
) -> bytes:
    payload = {
        "version": WATCH_WORKER_PROTOCOL_VERSION,
        "command": command,
        "shell_command": shell_command,
    }
    return json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("ascii")


def encode_watch_worker_error(
    code: str,
    detail: str | None = None,
    *,
    spawn_errno: int | None = None,
) -> str:
    payload: dict[str, Any] = {"code": code}
    if detail:
        payload["detail"] = detail
    if spawn_errno is not None:
        payload["spawnErrno"] = spawn_errno
    return WATCH_WORKER_ERROR_PREFIX + json.dumps(
        payload,
        ensure_ascii=True,
        separators=(",", ":"),
    )


def _watch_worker_error_payload(stderr: str) -> dict[str, Any] | None:
    if not stderr.startswith(WATCH_WORKER_ERROR_PREFIX):
        return None
    try:
        payload = json.loads(stderr[len(WATCH_WORKER_ERROR_PREFIX) :].strip())
    except (json.JSONDecodeError, UnicodeDecodeError):
        return {}
    return payload if isinstance(payload, dict) else {}


def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:
    payload = _watch_worker_error_payload(stderr)
    if payload is None:
        return None
    if not isinstance(payload.get("code"), str):
        return ("supervisorFailed", None)
    detail = payload.get("detail")
    return payload["code"], detail if isinstance(detail, str) else None


def decode_watch_worker_spawn_errno(stderr: str) -> int | None:
    """The OS error number that stopped the worker from starting its command.

    Structured, so a caller can tell a missing executable from one it may not
    run without reading the platform's wording of either.
    """

    code = (_watch_worker_error_payload(stderr) or {}).get("spawnErrno")
    return code if type(code) is int else None


#: The leaf i18n key per handshake failure the worker can report. The PROTOCOL is one
#: thing whichever lane spawned the supervisor, but the SENTENCE is not: the same
#: failure has to read as "watch worker" to somebody managing a watch and as "command"
#: to somebody managing a scheduled command task, so the namespace is the caller's and
#: only the leaf is fixed here.
_PROTOCOL_ERROR_I18N_LEAVES = {
    "specTooLarge": "protocolErrors.specTooLarge",
    "invalidEncoding": "protocolErrors.invalidEncoding",
    "invalidJson": "protocolErrors.invalidJson",
    "unsupportedVersion": "protocolErrors.unsupportedVersion",
    "invalidCommand": "protocolErrors.invalidCommand",
}


def localize_worker_error(
    stderr: str, translate: Any, *, namespace: str = "harness.watch"
) -> str:
    """Turn a worker's machine-readable error line into a sentence, or pass it through.

    LIVES HERE, beside the encoder, because both spawning lanes need it and only this
    module knows the wire format. ``core/watches.py`` had the only copy, so a scheduled
    command task whose executable did not exist stored the raw
    ``AVIBE_WATCH_WORKER_ERROR:{...}`` JSON as its ``last_error`` -- and then repeated
    it verbatim in the failure notice and in the Agent escalation prompt.

    ``translate`` is injected rather than imported: this module is also the child
    process's entry point, and it must stay importable without pulling the service's
    i18n stack in behind it. ``namespace`` selects which lane's copy to read, so the
    scheduled lane does not tell a user managing a cron job about a "watch worker".

    Anything that is not a worker error line is returned UNCHANGED -- ordinary command
    stderr is the common case, and it is nobody's to rewrite.
    """

    error = decode_watch_worker_error(stderr)
    if error is None:
        return stderr
    code, detail = error
    leaf = _PROTOCOL_ERROR_I18N_LEAVES.get(code)
    if leaf:
        detail = translate(f"{namespace}.{leaf}")
    elif not detail:
        detail = translate(f"{namespace}.unknownSupervisorFailure")
    return translate(f"{namespace}.supervisorFailed", detail=detail)


def _read_watch_worker_spec() -> tuple[list[str], str | None]:
    payload = sys.stdin.buffer.read(_MAX_SPEC_BYTES + 1)
    if len(payload) > _MAX_SPEC_BYTES:
        raise WatchWorkerProtocolError("specTooLarge")
    try:
        decoded = payload.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise WatchWorkerProtocolError("invalidEncoding") from exc
    try:
        parsed = json.loads(decoded)
    except json.JSONDecodeError as exc:
        raise WatchWorkerProtocolError("invalidJson") from exc
    if not isinstance(parsed, dict) or parsed.get("version") != WATCH_WORKER_PROTOCOL_VERSION:
        raise WatchWorkerProtocolError("unsupportedVersion")

    command = parsed.get("command")
    shell_command = parsed.get("shell_command")
    if (
        not isinstance(command, list)
        or any(not isinstance(part, str) for part in command)
        or not isinstance(shell_command, (str, type(None)))
        or bool(command) == bool(shell_command)
        or (command and not command[0])
        or (isinstance(shell_command, str) and not shell_command.strip())
    ):
        raise WatchWorkerProtocolError("invalidCommand")
    return command, shell_command


def _install_windows_kill_on_close_job() -> Any:
    if os.name != "nt":
        return None
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "windows_job.py")
    if os.path.exists(path):
        import importlib.util

        # Beside this file, where the runner copies it with this one (``core.frozen_script``): the installed
        # package may already hold a newer version.
        spec = importlib.util.spec_from_file_location("avibe_windows_job", path)
        windows_job = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(windows_job)
    else:
        # Started from the installed package, as a runner released before the copies starts it while an
        # upgrade waits for its restart: the package's own version then matches this file.
        from core.agent_core.tools import windows_job
    return windows_job.create_kill_on_close_job()


def _forward_stream(source: BinaryIO, target: BinaryIO) -> None:
    while True:
        chunk = source.read(64 * 1024)
        if not chunk:
            return
        target.write(chunk)
        target.flush()


def _handle_posix_termination(_signal_number: int, _frame: Any) -> None:
    # The signal is delivered to the entire process group. The command should
    # decide whether to exit; the supervisor must remain for forced escalation.
    return None


def _install_posix_supervisor_signal_handlers() -> None:
    if os.name != "nt":
        signal.signal(signal.SIGTERM, _handle_posix_termination)


def _posix_process_group_has_other_members(identity_anchor_pid: int | None = None) -> bool:
    if os.name == "nt":
        return False
    own_pid = os.getpid()
    try:
        own_pgid = os.getpgrp()
        processes = psutil.process_iter(["pid"])
        for process in processes:
            pid = process.info.get("pid")
            if (
                not isinstance(pid, int)
                or isinstance(pid, bool)
                or pid <= 0
                or pid == own_pid
                or pid == identity_anchor_pid
            ):
                continue
            try:
                if os.getpgid(pid) == own_pgid:
                    return True
            except (ProcessLookupError, PermissionError, psutil.Error):
                continue
    except (OSError, psutil.Error):
        # Fail closed: retaining the supervisor is safer than orphaning an
        # unverified descendant and clearing its persisted recovery identity.
        return True
    return False


def _wait_for_posix_process_group_exit(identity_anchor_pid: int | None = None) -> None:
    while _posix_process_group_has_other_members(identity_anchor_pid):
        time.sleep(0.1)


def _run_posix_identity_anchor() -> int:
    signal.signal(signal.SIGTERM, _handle_posix_termination)
    while True:
        signal.pause()


def _start_posix_identity_anchor() -> subprocess.Popen[bytes] | None:
    marker = os.environ.get(PROCESS_IDENTITY_ENV)
    if os.name == "nt" or not marker:
        return None
    # The anchor's environment carries only the marker, so the caller's
    # PYTHONDONTWRITEBYTECODE is gone; -B keeps it from writing bytecode into
    # the interpreter's tree, which a desktop Runtime verifies before each use.
    return subprocess.Popen(
        [sys.executable, "-B", os.path.abspath(__file__), "--identity-anchor"],
        env={PROCESS_IDENTITY_ENV: marker},
        stdin=subprocess.DEVNULL,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def _stop_posix_identity_anchor(anchor: subprocess.Popen[bytes] | None) -> None:
    if anchor is None or anchor.poll() is not None:
        return
    anchor.kill()
    anchor.wait()


def _run_watch_worker() -> int:
    _install_posix_supervisor_signal_handlers()
    # The handle must stay open for the supervisor lifetime so Windows keeps
    # every descendant in the kill-on-close job.
    _job_handle = _install_windows_kill_on_close_job()
    command, shell_command = _read_watch_worker_spec()
    child_env = dict(os.environ)
    child_env.pop(PROCESS_IDENTITY_ENV, None)
    hide_console = child_env.pop(HIDE_CONSOLE_ENV, None) == "1"
    creation_options = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" and hide_console else {}
    identity_anchor = _start_posix_identity_anchor()

    try:
        popen_args: Any = shell_command if shell_command is not None else command
        try:
            process = subprocess.Popen(
                popen_args,
                shell=shell_command is not None,
                env=child_env,
                stdin=subprocess.DEVNULL,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                **creation_options,
            )
        except OSError as exc:
            raise _CommandSpawnError(exc) from exc
        if process.stdout is None or process.stderr is None:
            raise RuntimeError("watch worker output pipes are unavailable")

        stdout_thread = threading.Thread(
            target=_forward_stream,
            args=(process.stdout, sys.stdout.buffer),
            daemon=False,
        )
        stderr_thread = threading.Thread(
            target=_forward_stream,
            args=(process.stderr, sys.stderr.buffer),
            daemon=False,
        )
        stdout_thread.start()
        stderr_thread.start()
        return_code = process.wait()
        stdout_thread.join()
        stderr_thread.join()
        _wait_for_posix_process_group_exit(
            identity_anchor.pid if identity_anchor is not None else None
        )
        return return_code
    finally:
        _stop_posix_identity_anchor(identity_anchor)


def main() -> int:
    if os.name != "nt" and sys.argv[1:] == ["--identity-anchor"]:
        return _run_posix_identity_anchor()
    try:
        return_code = _run_watch_worker()
    except WatchWorkerProtocolError as exc:
        print(encode_watch_worker_error(exc.code), file=sys.stderr, flush=True)
        return 1
    except _CommandSpawnError as exc:
        print(
            encode_watch_worker_error(
                "supervisorFailed", str(exc), spawn_errno=exc.os_errno
            ),
            file=sys.stderr,
            flush=True,
        )
        return 1
    except Exception as exc:
        print(
            encode_watch_worker_error("supervisorFailed", str(exc)),
            file=sys.stderr,
            flush=True,
        )
        return 1

    if os.name == "nt":
        return return_code
    if os.name != "nt" and return_code < 0:
        signal_number = -return_code
        if signal_number == signal.SIGTERM:
            signal.signal(signal.SIGTERM, signal.SIG_DFL)
        os.kill(os.getpid(), signal_number)
        return 128 + signal_number
    if 0 <= return_code <= 255:
        return return_code
    return 1


if __name__ == "__main__":
    raise SystemExit(main())