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.

11.1 KB
Raw Blame
"""The ``TranscriptStore`` the loop writes through, over ``SQLiteTranscriptStore``.

Two adapter rules live at this boundary, where the loop consumes an input:

* the environment block (C-7 tools.md section 8) is rendered into the input as
  it is consumed, with the fields the projected context does not already show
  (after a checkpoint, the summarized inputs' fields are not shown), so what
  ``consume_input`` stores is exactly what the model is sent;
* a fork's first own input carries the fork notice (C-10 fork.md section 8):
  whose history the model inherited, and that its work stays with the Session
  that started it;
* a steered input's ``messages`` row is inserted by the Delivery manager right
  after the backend accepts the steer. The loop can reach that input first, so
  consumption waits, bounded, for the row to exist.

Each committed response is handed to ``on_response`` once, with the loop's
decision whether it replies and the images a final delivers, for the run that
owns it; nothing here keeps responses after that.
"""

from __future__ import annotations

import asyncio
import json
from contextlib import contextmanager
import time
from typing import Any, Callable, Iterator, Literal, Mapping, Optional, Sequence

from sqlalchemy import select
from sqlalchemy.engine import Engine

from core.agent_core.harness.projection import context_view
from core.agent_core.harness.store import ContextEntry
from core.agent_core.messages import AssistantMessage, HostedImage, ToolResultMessage, UserMessage
from core.agent_core.tools.paths import to_thread_joined
from modules.agents.vibey.prompt import (
    EnvironmentValue,
    displayed_environment,
    environment_delta,
    environment_state,
    with_environment,
    with_fork_notice,
)
from storage.agent_transcript import SQLiteTranscriptStore, fork_link
from storage.models import agent_sessions, messages

EnvironmentSource = Callable[[str], Mapping[str, EnvironmentValue]]
ResponseObserver = Callable[[str, str, AssistantMessage, Optional[bool], tuple[HostedImage, ...]], None]
ResponseMetadata = Callable[[str, AssistantMessage], Mapping[str, Any]]

#: How long consumption waits for an accepted steer's row before failing the run.
INPUT_ROW_TIMEOUT_S = 10.0


class InputRowMissing(RuntimeError):
    """An accepted input's ``messages`` row did not appear in time."""


class AdapterTranscriptStore:
    def __init__(
        self,
        store: SQLiteTranscriptStore,
        engine: Engine,
        *,
        environment: EnvironmentSource,
        on_response: ResponseObserver,
        response_metadata: Optional[ResponseMetadata] = None,
        file_write: Optional[Callable[[str, str, str], None]] = None,
        input_row_timeout_s: float = INPUT_ROW_TIMEOUT_S,
    ) -> None:
        self._store = store
        self._engine = engine
        self._environment = environment
        self._on_response = on_response
        self._response_metadata = response_metadata
        self._file_write = file_write
        self._input_row_timeout_s = input_row_timeout_s
        # Per Session, the environment the projected context shows; evicted by ``forget`` when
        # the adapter retires the Session's runtime, and when a checkpoint commits.
        self._env_state: dict[str, dict[str, str]] = {}
        # Per Session, the Agent of the Turn writing it (its request snapshot), so a
        # mid-Turn change of the Session's selected Agent never re-attributes its rows.
        self._agents: dict[str, str] = {}
        self._turns: dict[str, str] = {}

    def bind_agent(self, session_id: str, agent_name: Optional[str], *, turn_id: Optional[str] = None) -> None:
        """Attribute the Session's next writes to the running Turn's Agent."""
        if agent_name:
            self._agents[session_id] = agent_name
        else:
            self._agents.pop(session_id, None)
        if turn_id:
            self._turns[session_id] = turn_id
        else:
            self._turns.pop(session_id, None)

    @contextmanager
    def writing_as(
        self, session_id: str, agent_name: Optional[str], *, turn_id: Optional[str] = None
    ) -> Iterator[None]:
        """Use the owning response's identity for recovery writes; restore the active Turn after."""
        previous = self._agents.get(session_id)
        previous_turn = self._turns.get(session_id)
        self.bind_agent(session_id, agent_name or previous, turn_id=turn_id)
        try:
            yield
        finally:
            self.bind_agent(session_id, previous, turn_id=previous_turn)

    def forget(self, session_id: str) -> None:
        """Drop per-Session state; the next consumption reads the environment from the rows again."""
        self._env_state.pop(session_id, None)
        self._agents.pop(session_id, None)
        self._turns.pop(session_id, None)
        self._store.forget(session_id)

    # --- TranscriptStore -----------------------------------------------------

    async def load(self, session_id: str) -> Sequence[ContextEntry]:
        return await self._store.load(session_id)

    async def load_turn(self, session_id: str, turn_id: str) -> Sequence[ContextEntry]:
        return await self._store.load_turn(session_id, turn_id)

    async def load_turn_response_metadata(
        self, session_id: str, turn_id: str
    ) -> Sequence[tuple[Mapping[str, Any], Optional[AssistantMessage]]]:
        """Small response facts; only legacy rows need their canonical body decoded."""
        return await self._store.load_turn_response_metadata(session_id, turn_id)

    async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping[str, Any]]:
        return await self._store.load_cache_attempts(session_id)

    async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:
        await self._await_input_row(session_id, message_id)
        previous = self._env_state.get(session_id)
        if previous is None:
            # What the model still sees: the inputs the projected context keeps. After a checkpoint the
            # summarized inputs are gone, so the next input carries every field the context no longer shows.
            entries = await self._store.load(session_id)
            view = context_view(entries)
            previous = environment_state([unit.lead for unit in view.units if unit.lead.kind == "input"])
            if not any(entry.session_id == session_id for entry in entries):
                # No row of its own yet: a fork's first own input carries the notice, an empty prefix included.
                message = await asyncio.to_thread(self._with_fork_notice, session_id, message)
        current = self._environment(session_id)
        rendered = with_environment(message, environment_delta(previous, current))
        entry = await self._store.consume_input(session_id, message_id, rendered)
        self._env_state[session_id] = {**previous, **displayed_environment(current)}
        return entry

    async def append_response(
        self,
        session_id: str,
        message: AssistantMessage,
        *,
        final: bool,
        request: Optional[Mapping[str, Any]] = None,
        cache: Optional[Mapping[str, Any]] = None,
        replied: Optional[bool] = None,
        images: Sequence[HostedImage] = (),
        superseded: bool = False,
    ) -> ContextEntry:
        entry = await self._store.append_response(
            session_id,
            message,
            final=final,
            request=request,
            cache=cache,
            replied=replied,
            images=images,
            superseded=superseded,
            metadata=self._response_metadata(session_id, message) if self._response_metadata else None,
            agent_name=self._agents.get(session_id),
            turn_id=self._turns.get(session_id),
        )
        self._on_response(session_id, entry.row_id, message, replied, tuple(images))
        return entry

    async def append_tool_result(
        self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]
    ) -> ContextEntry:
        receipt = details.get("file_write")
        if (not message.is_error and self._file_write is not None and isinstance(receipt, Mapping)
                and isinstance(receipt.get("path"), str) and isinstance(receipt.get("revision"), str)):
            await to_thread_joined(self._file_write, session_id, receipt["path"], receipt["revision"])
        return await self._store.append_tool_result(
            session_id, message, details=details, agent_name=self._agents.get(session_id),
            turn_id=self._turns.get(session_id),
        )

    async def append_payload(
        self, session_id: str, kind: Literal["compaction", "context_edit", "agent_state", "replay_refusal"], payload: Mapping[str, Any]
    ) -> ContextEntry:
        return await self._store.append_payload(
            session_id, kind, payload, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)
        )

    async def append_payloads(
        self,
        session_id: str,
        entries: Sequence[tuple[Literal["compaction", "context_edit", "agent_state", "replay_refusal"], Mapping[str, Any]]],
    ) -> Sequence[ContextEntry]:
        committed = await self._store.append_payloads(
            session_id, entries, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)
        )
        if any(kind == "compaction" for kind, _ in entries):
            self._env_state.pop(session_id, None)  # the summarized inputs' environment is no longer seen
        return committed

    async def append_audit(
        self, session_id: str, kind: Literal["attempt", "fork_turn"], payload: Mapping[str, Any]
    ) -> str:
        return await self._store.append_audit(
            session_id, kind, payload, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)
        )

    # --- implementation ------------------------------------------------------

    async def _await_input_row(self, session_id: str, message_id: str) -> None:
        deadline = time.monotonic() + self._input_row_timeout_s
        delay = 0.01
        while not await asyncio.to_thread(self._input_row_exists, session_id, message_id):
            if time.monotonic() >= deadline:
                raise InputRowMissing(f"input {message_id} of Session {session_id} was never materialized")
            await asyncio.sleep(delay)
            delay = min(delay * 2, 0.25)

    def _with_fork_notice(self, session_id: str, message: UserMessage) -> UserMessage:
        with self._engine.connect() as conn:
            link = fork_link(conn, session_id)
            raw = conn.execute(select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)).scalar()
        if link is None:
            return message
        metadata = json.loads(raw or "{}")
        title = metadata.get("fork_source_session_title") if isinstance(metadata, dict) else None
        return with_fork_notice(
            message, source_session_id=link[0], source_title=str(title or ""), through_seq=link[1]
        )

    def _input_row_exists(self, session_id: str, message_id: str) -> bool:
        with self._engine.connect() as conn:
            owner = conn.execute(select(messages.c.session_id).where(messages.c.id == message_id)).scalar()
        return owner == session_id