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.

13.2 KB
Raw Blame
"""Small hermetic C-2/C-5/C-7 fakes shared by agent-core lanes.

The provider records detached requests before running each script. The store
implements the ``TranscriptStore`` contract (committed entries and fork ancestry),
not loop/projection logic; the contract suite runs it against the SQLite store.
Jobs have explicit test-controlled state and never spawn processes.
"""

from __future__ import annotations

import asyncio
import time
from collections import deque
from copy import deepcopy
from typing import AsyncIterator, Callable, Mapping, Optional, Sequence

from core.agent_core.agent.hooks import AgentInput, Snapshot
from core.agent_core.agent.models import ModelSelection
from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ModelRequest, ProviderEvent
from core.agent_core.cancel import CancelToken
from core.agent_core.harness.store import ContextEntry
from core.agent_core.messages import AssistantMessage, Origin, ToolResultMessage, UserMessage, text
from core.agent_core.tools.base import JobStatus, ToolContext, ToolResult, ToolSpec

ORIGIN = Origin("test-provider", "anthropic", "test-model")
ENDPOINT = ModelEndpoint("anthropic", "http://model.invalid", "test-model", "", provider="test-provider")
SELECTION = ModelSelection(
    ENDPOINT, ModelCapabilities(context_window=32000, max_output_tokens=4096, supports_tools=True, supports_images=True)
)
Script = Sequence[ProviderEvent] | Callable[[ModelRequest, CancelToken], AsyncIterator[ProviderEvent]]

#: How an Anthropic model before Claude 4.5 refuses a request whose input plus ``max_tokens`` exceeds its window.
WINDOW_REFUSAL = (
    "input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000, "
    "decrease input length or `max_tokens` and try again"
)


def anthropic_error(message: str) -> dict:
    """An Anthropic endpoint's 400 body for a request it refuses."""
    return {"type": "error", "error": {"type": "invalid_request_error", "message": message}}


def model_hub_error(message: str) -> dict:
    """Model Hub's gateway body for a request its upstream refused (Vibey's route): the gateway's own code, and the
    upstream's message inside the copy the gateway's renderer writes."""
    from core.handlers.model_hub.provenance import produce_turn_outcome, render_turn_outcome_copy

    copy = render_turn_outcome_copy(produce_turn_outcome("turn.request_nonfallback", upstream_detail=message), "en")
    return {"error": {"type": "upstream_request_invalid", "code": "upstream_request_invalid", "message": copy}}


def user(value: str) -> UserMessage:
    return UserMessage((text(value),))


def input_row(row_id: str, value: str) -> AgentInput:
    return AgentInput(row_id, user(value))


def assistant(value: str = "done", *, calls=(), stop_reason=None) -> AssistantMessage:
    content = ((text(value),) if value else ()) + tuple(calls)
    return AssistantMessage(content, ORIGIN, stop_reason or ("tool_use" if calls else "stop"))


class ScriptedProvider:
    protocol = "anthropic"

    def __init__(self, scripts: Sequence[Script]) -> None:
        self.scripts = deque(scripts)
        self.requests: list[ModelRequest] = []
        self.closed_streams = 0

    async def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[ProviderEvent]:
        self.requests.append(deepcopy(request))
        if not self.scripts:
            raise AssertionError("the loop made an unscripted provider call")
        script = self.scripts.popleft()
        try:
            if callable(script):
                async for event in script(request, cancel):
                    yield event
            else:
                for event in script:
                    yield deepcopy(event)
        finally:
            self.closed_streams += 1


class FakeModelRouter:
    def __init__(self, provider: ScriptedProvider, selections: Sequence[ModelSelection] = (SELECTION,)) -> None:
        self.provider = provider
        self.selections = tuple(selections)
        self.resolutions = 0
        self.protocols: list[str] = []

    async def resolve(self) -> ModelSelection:
        index = min(self.resolutions, len(self.selections) - 1)
        self.resolutions += 1
        return self.selections[index]

    def provider_for(self, protocol):
        self.protocols.append(protocol)
        return self.provider


class InMemoryTranscriptStore:
    """The ``TranscriptStore`` contract in memory, and nothing more.

    ``tests/test_transcript_store_contract.py`` runs the same contract tests on this store and on the SQLite one.
    What tests read besides the protocol is observation only: ``final``, the audit rows (``audits``,
    ``attempts``), and the kinds each ``append_payloads`` transaction committed (``transactions``).
    """

    def __init__(self, *, clock: Callable[[], float] = time.time) -> None:
        self.rows: dict[str, list[ContextEntry]] = {}
        self.forks: dict[str, Snapshot] = {}
        self.final: dict[str, bool] = {}
        # C-9 checkpoint-turn audit rows: (session_id, row id, payload), never context.
        self.audits: list[tuple[str, str, dict]] = []
        # C-9 model-attempt audit rows (usage of attempts that never became context).
        self.attempts: list[tuple[str, str, dict]] = []
        # Kinds committed by each ``append_payloads`` transaction.
        self.transactions: list[list[str]] = []
        self._clock = clock
        self._next_id = 0

    def fork(self, snapshot: Snapshot, *, session_id: str) -> None:
        if session_id in self.rows or session_id in self.forks:
            raise ValueError("child already exists")
        self.forks[session_id] = deepcopy(snapshot)

    async def load(self, session_id: str) -> Sequence[ContextEntry]:
        prefix = []
        anchor = self.forks.get(session_id)
        if anchor is not None:
            prefix = [row for row in await self.load(anchor.session_id) if row.context_seq <= anchor.context_seq]
        return deepcopy(prefix + self.rows.get(session_id, []))

    async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping]:
        from core.agent_core.harness.cache_metrics import CacheTracker

        tracker = CacheTracker()
        for records in (self.attempts, self.audits):
            payload = next((payload for owner, _, payload in reversed(records) if owner == session_id), {})
            tracker.restore((), payload.get("cache_state", []))
        return deepcopy(list(tracker.latest.values()))

    def _entries(self, session_id, items) -> list[ContextEntry]:
        """Rows for ``(kind, message, payload, row_id)`` items, numbered after the Session's context."""
        entries = self.rows.get(session_id, [])
        anchor = self.forks.get(session_id)
        seq = max([entry.context_seq for entry in entries] + [anchor.context_seq if anchor else 0])
        rows = []
        for kind, message, payload, row_id in items:
            seq += 1
            if row_id is None:
                self._next_id += 1
                row_id = f"row_{self._next_id}"
            rows.append(ContextEntry(session_id, seq, kind, row_id, deepcopy(message), deepcopy(payload), self._clock()))
        return rows

    async def _append(self, session_id, items) -> list[ContextEntry]:
        rows = self._entries(session_id, items)
        self.rows.setdefault(session_id, []).extend(rows)  # all of them or none
        return deepcopy(rows)

    async def consume_input(self, session_id, message_id, message: UserMessage) -> ContextEntry:
        for entry in await self.load(session_id):
            if entry.row_id == message_id:
                # A retried commit of the same input is the committed entry; anything else would rewrite it.
                if entry.message != message:
                    raise ValueError(f"input {message_id} is already in the context")
                return entry
        return (await self._append(session_id, [("input", message, {}, message_id)]))[0]

    async def append_response(
        self, session_id, message: AssistantMessage, *, final: bool, request=None, cache=None, replied=None, images=(), superseded=False
    ) -> ContextEntry:
        payload = {"request": dict(request)} if request is not None else {}
        if cache is not None:
            payload["cache"] = dict(cache)
        row = (await self._append(session_id, [("response", message, payload, None)]))[0]
        self.final[row.row_id] = final
        return row

    async def append_tool_result(self, session_id, message: ToolResultMessage, *, details: Mapping) -> ContextEntry:
        settled = _settled_result(await self.load(session_id), message.tool_call_id)
        if settled is not None:
            return settled  # a call instance is settled once, whoever writes
        payload = {"details": dict(details)} if details else {}
        return (await self._append(session_id, [("tool_result", message, payload, None)]))[0]

    async def append_payload(self, session_id, kind, payload: Mapping) -> ContextEntry:
        return (await self._append(session_id, [(kind, None, _payload(kind, payload), None)]))[0]

    async def append_payloads(self, session_id, entries) -> list[ContextEntry]:
        committed = await self._append(session_id, [(kind, None, _payload(kind, payload), None) for kind, payload in entries])
        self.transactions.append([row.kind for row in committed])
        return committed

    async def append_audit(self, session_id, kind, payload: Mapping) -> str:
        if kind not in ("attempt", "fork_turn"):
            raise ValueError(f"not an audit kind: {kind!r}")
        self._next_id += 1
        row_id = f"audit_{self._next_id}"
        record = (session_id, row_id, deepcopy(dict(payload)))
        (self.audits if kind == "fork_turn" else self.attempts).append(record)
        return row_id


def _payload(kind, payload: Mapping) -> dict:
    """A payload row's content, as the contract admits it: a payload kind, at the current version."""
    if kind not in ("compaction", "context_edit", "agent_state", "replay_refusal"):
        raise ValueError(f"not a payload entry kind: {kind!r}")
    if payload.get("version") != 1:
        raise ValueError(f"a {kind} payload needs version 1")
    return deepcopy(dict(payload))


def _settled_result(entries: Sequence[ContextEntry], tool_call_id: str) -> Optional[ContextEntry]:
    """The first result after the latest response carrying a call with this id, as the SQLite store finds it."""
    owner = None
    for index, entry in enumerate(entries):
        if entry.kind == "response" and any(call.id == tool_call_id for call in entry.message.tool_calls):
            owner = index
    if owner is None:
        return None
    return next(
        (
            entry
            for entry in entries[owner + 1 :]
            if entry.kind == "tool_result" and entry.message.tool_call_id == tool_call_id
        ),
        None,
    )


class FakeTool:
    def __init__(self, name="echo", execute=None, result: Optional[ToolResult] = None) -> None:
        self.spec = ToolSpec(name, "Test tool", {"type": "object"})
        self.calls: list[tuple[dict, ToolContext]] = []
        self._execute = execute
        self.result = result or ToolResult((text("tool result"),))

    async def execute(self, arguments, ctx: ToolContext) -> ToolResult:
        self.calls.append((deepcopy(dict(arguments)), ctx))
        if self._execute is not None:
            return await self._execute(arguments, ctx)
        return deepcopy(self.result)


class FakeJobHost:
    def __init__(self) -> None:
        self.states: dict[str, JobStatus] = {}
        self.outputs: dict[str, bytes] = {}
        self.starts: list[dict] = []
        self.killed: list[str] = []
        self.stop_reasons: dict[str, str] = {}
        self.watches: dict[str, str] = {}
        self.changed = asyncio.Event()

    async def start(self, command, *, cwd, env, timeout_s, call) -> str:
        job_id = f"job_{len(self.starts) + 1}"
        self.starts.append(
            dict(command=command, cwd=cwd, env=dict(env), timeout_s=timeout_s, call=call, job_id=job_id)
        )
        self.states[job_id] = JobStatus("running")
        self.outputs[job_id] = b""
        return job_id

    def status(self, job_id) -> JobStatus:
        return self.states.get(job_id, JobStatus("gone"))

    def meta(self, job_id) -> dict:
        """No launch record: a surviving job's foreground window counts as already spent."""
        return {}

    async def wait(self, job_id, *, deadline_s) -> JobStatus:
        while self.status(job_id).state == "running":
            self.changed.clear()
            await self.changed.wait()
        return self.status(job_id)

    def output(self, job_id, since=0) -> tuple[bytes, int]:
        output = self.outputs[job_id]
        return output[since:], len(output)

    def output_path(self, job_id) -> str:
        return f"/test-owned/jobs/{job_id}/output.log"

    async def kill(self, job_id, *, reason="killed") -> None:
        self.killed.append(job_id)
        self.stop_reasons.setdefault(job_id, reason)  # the first recorded reason wins
        self.states[job_id] = JobStatus("gone")
        self.changed.set()

    def stop_reason(self, job_id):
        return self.stop_reasons.get(job_id)

    async def hand_over(self, job_id) -> str:
        watch_id = f"watch_{job_id}"
        self.watches[job_id] = watch_id
        return watch_id