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.

4.7 KB
Raw Blame
"""Durable tool-call settlement before resume (C-5/C-7 recovery.md).

The adapter calls this under its Session writer lock, before Agent.run or any
projection. A restarted call loads committed results again and skips them; each
remaining result is appended immediately. It never executes a tool/command.
"""

from __future__ import annotations

from copy import deepcopy
from typing import Awaitable, Callable, Mapping, Optional

from core.agent_core.harness.projection import interrupted_result, open_tool_calls, validate_message_append
from core.agent_core.harness.store import ContextEntry, TranscriptStore
from core.agent_core.messages import ToolCallBlock, ToolResultMessage, text
from core.agent_core.tools.base import CallInstance, JobHost, JobStatus, ToolResult

#: ``None`` means the job holds no result for the call (it never ran, or ended for an unrecorded reason).
RecoveryRenderer = Callable[[ToolCallBlock, str, JobStatus, Optional[str]], Awaitable[Optional[ToolResult]]]
#: For a job still running: settle it as its live call would; its status then, and the Watch it went to, if any.
ForegroundWait = Callable[[ToolCallBlock, str], Awaitable[tuple[JobStatus, Optional[str]]]]

# recovery.md T2: no job evidence can establish whether a file mutation ran.
UNRECORDED_EFFECT = "[tool call interrupted; it may or may not have completed; re-read the file before continuing]"
#: ``details`` key on every result T2 commits: the call's run ended before the tool returned one.
RECOVERED = "recovered"


async def settle_open_calls(
    *,
    session_id: str,
    store: TranscriptStore,
    jobs: JobHost,
    job_ids: Mapping[CallInstance, str],
    render_result: RecoveryRenderer,
    wait_running: Optional[ForegroundWait] = None,
) -> tuple[ContextEntry, ...]:
    """Commit one result per open call, using original-owner job lookup.

    ``job_ids`` is keyed by call instance, whose response may be one a fork
    inherited. The adapter supplies bash's output-governance renderer; it
    receives (call, job_id, status, watch_id). ``JobHost.hand_over``
    must reuse a job's existing Watch when recovery retries after an interrupted
    commit. The job host owns the launch-handshake reconciliation behind status.

    Store writes remain under the caller's single-writer ownership. A concurrent
    second recovery or Agent.run for that Session is not permitted.
    Without job state, the result explicitly leaves the effect uncertain.
    No tool or model is invoked here; after this step the Turn owner continues
    the interrupted Turn from the committed transcript or settles it (T4). The
    adapter also runs it when a run ends without completing (a Stop), so the
    calls that run left open carry their jobs' recorded reason at once.

    ``wait_running`` is the Turn that continues after a restart: a job still
    running is settled as its live call would settle it (its foreground window
    from the job's launch, then a Watch, or the foreground when no Watch can take
    it; a Stop ends it), so only a job still running then is handed over. The
    wait commits nothing, so a crash during it leaves the call open for the next
    settlement, and no job is ever started here.
    """
    committed: list[ContextEntry] = []
    rows = list(await store.load(session_id))
    for owner, call in open_tool_calls(rows):
        job_id = job_ids.get(CallInstance(owner.session_id, owner.row_id, owner.context_seq, call.id))
        message = interrupted_result(call)
        details = {RECOVERED: True}
        if job_id is None:
            message = ToolResultMessage(call.id, call.name, (text(UNRECORDED_EFFECT),), is_error=True)
        else:
            status = jobs.status(job_id)
            details["job_id"] = job_id
            if status.state == "running" and wait_running is not None:
                status, watch_id = await wait_running(deepcopy(call), job_id)
            else:
                watch_id = await jobs.hand_over(job_id) if status.state == "running" else None
            result = await render_result(deepcopy(call), job_id, status, watch_id)
            if result is not None:
                message = ToolResultMessage(call.id, call.name, result.content, result.is_error)
                details.update(deepcopy(dict(result.details)))
                details.update({RECOVERED: True, "job_id": job_id})
                if watch_id is not None:
                    details["watch_id"] = watch_id
                if status.state == "exited":
                    details["exit_code"] = status.exit_code
        validate_message_append(rows, session_id=session_id, kind="tool_result", message=message)
        row = await store.append_tool_result(session_id, deepcopy(message), details=details)
        rows.append(row)
        committed.append(row)
    return tuple(committed)