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.

3.6 KB
Raw Blame
"""PR3 supervisor handlers that re-enter existing guarded durable owners."""

from __future__ import annotations

import asyncio
from collections.abc import Callable
from typing import TYPE_CHECKING, Any

from core.runtime_work import RuntimeWorkItem

if TYPE_CHECKING:
    from core.session_turns import RuntimeDeliveryObservation, SessionTurnManager
    from storage.background import SQLiteBackgroundTaskStore


class SessionDeliveryRecoveryHandler:
    def __init__(self, manager: "SessionTurnManager") -> None:
        self.manager = manager

    def scan(
        self,
        *,
        limit: int,
        occupied: frozenset[str],
        cursor: str | None = None,
    ) -> tuple[list[RuntimeWorkItem], bool]:
        observations, has_more = self.manager.scan_runtime_delivery_recovery(
            limit=limit,
            occupied=occupied,
            cursor=cursor,
        )
        items = [
            # A head held for its owner's explicit retry only moves the cursor:
            # re-entering it would find nothing to start, back off and rescan
            # it every second until that retry.
            RuntimeWorkItem(
                observation.session_id,
                observation,
                cursor_only=observation.awaits_explicit_retry,
            )
            for observation in observations
        ]
        if not has_more:
            # On the last page a held head must not leave the cursor behind it:
            # no worker re-arms the lane for it, so the next wake would scan
            # only the Sessions after it and miss earlier ones.
            while items and items[-1].cursor_only:
                items.pop()
        return items, has_more

    async def process(self, item: RuntimeWorkItem) -> bool:
        return await self.manager.recover_runtime_delivery_observation(
            item.observation
        )


class FallbackRequestRecoveryHandler:
    """Recover only claimed pre-execution fallback Runs; never admit queued Runs."""

    def __init__(
        self,
        store: "SQLiteBackgroundTaskStore",
        *,
        live_claims: Callable[[], frozenset[str]] | None = None,
        partition_key: Callable[[dict[str, Any]], str] | None = None,
    ) -> None:
        self.store = store
        self._live_claims = live_claims or frozenset
        self._partition_key = partition_key or (
            lambda row: str(row["id"])
        )

    def scan(
        self,
        *,
        limit: int,
        occupied: frozenset[str],
        cursor: str | None = None,
    ) -> tuple[list[RuntimeWorkItem], bool]:
        live_claims = self._live_claims()
        rows, has_more = self.store.scan_claimed_pre_execution_runs(
            limit=limit,
            # Store exclusion is by Run id. Supervisor occupancy is by the
            # canonical execution partition and is applied after mapping below.
            occupied=live_claims,
            cursor=cursor,
        )
        return [
            RuntimeWorkItem(
                self._partition_key(row),
                row,
                cursor_key=str(row["id"]),
            )
            for row in rows
        ], has_more

    async def process(self, item: RuntimeWorkItem) -> bool:
        return await asyncio.to_thread(self.process_sync, item)

    def process_sync(self, item: RuntimeWorkItem) -> bool:
        row = item.observation
        if str(row["id"]) in self._live_claims():
            return True
        return self.store.recover_claimed_pre_execution_run(
            run_id=str(row["id"]),
            expected_status=str(row["status"]),
            expected_updated_at=str(row["updated_at"]),
        )