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.

feat(agents): Avibe Agent backend adapter over the agent-core loop (#2345)

Call Whitedbd36e890f50
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 0a234f949..4d7e29343 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -2303,6 +2303,14 @@ class AgentAuthService:
self.controller.config.opencode = runtime_config
agent_service.register(OpenCodeAgent(self.controller, runtime_config))
+ elif backend == "avibe":
+ from modules.agents.avibe import AvibeAgent
+
+ if not getattr(runtime_config, "enabled", True):
+ return False
+
+ self.controller.config.avibe = runtime_config
+ agent_service.register(AvibeAgent(self.controller))
else:
return False
@@ -2311,6 +2319,21 @@ class AgentAuthService:
logger.info("Registered %s backend after runtime config refresh", backend)
return True
+ async def _recover_after_live_registration(self, backend: str) -> None:
+ """A backend registered after startup: its recovery owner hands over to the registered adapter.
+
+ For ``avibe`` the controller's single ``AvibeRecovery`` retires any pending retry
+ (an unregistered adapter's) and runs the next pass on the registered adapter, so
+ two adapters never settle the same Session at once.
+ """
+ recovery = getattr(self.controller, "avibe_recovery", None) if backend == "avibe" else None
+ if recovery is None:
+ return
+ try:
+ await recovery.start()
+ except Exception:
+ logger.exception("Failed to recover %s runtime state after live registration", backend)
+
async def _refresh_backend_runtime(self, backend: str) -> None:
coordinator = getattr(self.controller, "backend_restart_coordinator", None)
if coordinator is not None:
@@ -2336,6 +2359,7 @@ class AgentAuthService:
backend,
runtime_config,
):
+ await self._recover_after_live_registration(backend)
return
if force and backend == "opencode":
agent = getattr(agent_service, "agents", {}).get(backend)
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.md
index 0861a7e89..7a271ef1b 100644
--- a/core/agent_core/agent/README.md
+++ b/core/agent_core/agent/README.md
@@ -27,8 +27,12 @@ pending = await agent.take_pending_inputs()
`steer` and `follow_up` are async and return whether the active run accepted the
input. `False` means the adapter keeps the persisted input in the P3 queue.
An accepted input remains owned by the Agent until consumed or returned by
-`take_pending_inputs()`. Early termination preserves those queues; the adapter
-returns their durable rows to P3. A new run is refused until they are collected.
+`take_pending_inputs()`. Early termination preserves those queues, and a new run
+is refused until they are collected. A returned input belongs to the Turn that
+accepted it and is never re-queued as a new P3 Turn (`recovery.md` T3): after a
+run that ended by design (a terminating tool or a hook `end`), the Avibe adapter
+runs again for the returned inputs within the same Turn; after a stop or an
+error, it admits them into the context, and they share the Turn's outcome.
`abort`, `set_tools`, and `snapshot` are synchronous on the same event loop.
Only one run can use an Agent at a time. The adapter remains responsible for
excluding multiple Agent instances writing the same Session.
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index f6f8d1429..eb76310fe 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -154,11 +154,13 @@ class Agent:
return True
async def take_pending_inputs(self) -> tuple[AgentInput, ...]:
- """Return accepted but unconsumed inputs to the adapter's P3 queue.
+ """Return accepted but unconsumed inputs to the adapter.
Call after the run closes admission (normally after RunEnded). The
adapter still has the original durable rows; this transfers admission
- ownership back in steer/follow-up priority order, exactly once.
+ ownership back in steer/follow-up priority order, exactly once. The
+ inputs still belong to the Turn that accepted them, never to a new P3
+ Turn (``recovery.md`` T3).
"""
async with self._lock:
if self._open:
diff --git a/core/agent_core/agent/recovery.py b/core/agent_core/agent/recovery.py
index 6e2eb21de..85f9a72c0 100644
--- a/core/agent_core/agent/recovery.py
+++ b/core/agent_core/agent/recovery.py
@@ -8,14 +8,14 @@ remaining result is appended immediately. It never executes a tool/command.
from __future__ import annotations
from copy import deepcopy
-from typing import Callable, Mapping, Optional
+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 JobHost, JobStatus, ToolResult
-RecoveryRenderer = Callable[[ToolCallBlock, str, JobStatus, Optional[str]], ToolResult]
+RecoveryRenderer = Callable[[ToolCallBlock, str, JobStatus, Optional[str]], Awaitable[ToolResult]]
# 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]"
@@ -56,7 +56,7 @@ async def settle_open_calls(
details["job_id"] = job_id
if status.state in {"running", "exited"}:
watch_id = await jobs.hand_over(job_id) if status.state == "running" else None
- result = render_result(deepcopy(call), job_id, status, watch_id)
+ result = await render_result(deepcopy(call), job_id, status, watch_id)
message = ToolResultMessage(call.id, call.name, result.content, result.is_error)
details.update(deepcopy(dict(result.details)))
details["job_id"] = job_id
diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.py
index f1bd83ec0..22f684b16 100644
--- a/core/agent_core/tools/jobs.py
+++ b/core/agent_core/tools/jobs.py
@@ -121,6 +121,27 @@ def _iso(moment: datetime) -> str:
return moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
+def instant_text(moment: datetime) -> str:
+ """A UTC instant at full microsecond precision, the form job and transcript times compare in."""
+ return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
+
+
+def instant(value: object) -> Optional[datetime]:
+ """Parse a recorded UTC time (``...Z`` or an offset) at full precision, or ``None``.
+
+ The one parser for every time the job and recovery paths compare: a job's
+ ``created_at``, a response's commit, a tool result's commit.
+ """
+ text = str(value or "").strip()
+ if not text:
+ return None
+ try:
+ moment = datetime.fromisoformat(text[:-1] + "+00:00" if text.endswith("Z") else text)
+ except ValueError:
+ return None
+ return moment if moment.tzinfo is not None else moment.replace(tzinfo=timezone.utc)
+
+
def _ceil_ms(moment: datetime) -> datetime:
"""Round up to the millisecond ``_iso`` keeps, so a recorded deadline is never early."""
rest = moment.microsecond % 1000
@@ -213,16 +234,30 @@ class LocalJobHost:
def _write_meta(self, job_id: str, meta: Mapping[str, Any]) -> None:
_write_atomic(self._path(job_id, "meta.json"), _meta_text(meta))
- def find_job(self, session_id: str, tool_call_id: str) -> Optional[str]:
- """The job started for a tool call, for settling it at resume."""
+ def find_job(
+ self, session_id: str, tool_call_id: str, *, created_since: Optional[datetime] = None
+ ) -> Optional[str]:
+ """The job started for a tool call, for settling it at resume.
+
+ A provider may reuse a tool-call id in a later response, so several jobs can
+ match: the newest is returned. ``created_since``, the commit time of the
+ response that made the call, excludes jobs an earlier call with the same id
+ started.
+ """
+ newest: Optional[tuple[datetime, str]] = None
for name in self._job_ids():
try:
meta = self.meta(name)
except (KeyError, ValueError, OSError):
continue
- if meta.get("session_id") == session_id and meta.get("tool_call_id") == tool_call_id:
- return name
- return None
+ if meta.get("session_id") != session_id or meta.get("tool_call_id") != tool_call_id:
+ continue
+ created = instant(meta.get("created_at"))
+ if created is None or (created_since is not None and created < created_since):
+ continue
+ if newest is None or created > newest[0]:
+ newest = (created, name)
+ return newest[1] if newest is not None else None
def _job_ids(self) -> list[str]:
try:
@@ -325,7 +360,9 @@ class LocalJobHost:
"command": command,
"cwd": cwd,
"timeout_s": timeout_s,
- "created_at": _iso(created),
+ # Full precision: recovery tells apart jobs a reused tool-call id started
+ # within one millisecond (``find_job``).
+ "created_at": instant_text(created),
"state_dir": job_dir,
"process": None,
"terminal": None,
diff --git a/core/controller.py b/core/controller.py
index 8420c7eef..b040b4b50 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -313,6 +313,10 @@ class Controller:
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
+ from modules.agents.avibe.recovery import AvibeRecovery
+
+ # The single owner of the Avibe Agent's settlement outside a Turn.
+ self.avibe_recovery = AvibeRecovery(self)
self.trace_retention_task: Optional[asyncio.Task] = None
self._trace_retention_executor: Optional[Any] = None
self._trace_retention_cancel_event: Optional[threading.Event] = None
@@ -751,6 +755,14 @@ class Controller:
self.agent_service.register(OpenCodeAgent(self, self.config.opencode))
except Exception as e:
logger.error(f"Failed to initialize OpenCode agent: {e}")
+ avibe_config = getattr(self.config, "avibe", None)
+ if avibe_config is not None and getattr(avibe_config, "enabled", True):
+ try:
+ from modules.agents.avibe import AvibeAgent
+
+ self.agent_service.register(AvibeAgent(self))
+ except Exception as e:
+ logger.error(f"Failed to initialize Avibe Agent: {e}")
def _setup_callbacks(self):
"""Setup callback connections between modules"""
@@ -1008,6 +1020,15 @@ class Controller:
except Exception as e:
logger.error(f"Failed to restore active polls: {e}", exc_info=True)
+ async def _recover_avibe_agent_runtime_state(self) -> None:
+ """Settle what the previous process left of the Avibe Agent's work (T2, T3 admission, J5).
+
+ Not gated on ``agents.avibe.enabled``: a foreground job the previous process left
+ running must be handed to its Watch even when the backend admits no new Turns.
+ ``avibe_recovery`` is the single owner, retrying until every Session has settled.
+ """
+ await self.avibe_recovery.start()
+
async def _on_im_ready(self, *, platform: str) -> None:
"""Restore transport-owned state only after that transport can deliver."""
logger.info("IM transport ready, restoring state for %s", platform)
@@ -1085,6 +1106,10 @@ class Controller:
# A no-op in any process that does not hold the service lock, so the
# embedded and test paths that run a controller are unaffected.
self._publish_readiness_unless_im_runtime_failed()
+ try:
+ await self._recover_avibe_agent_runtime_state()
+ except Exception:
+ logger.exception("Failed to recover the Avibe Agent's runtime state")
try:
await self.update_checker.check_and_send_post_update_notification(ready_platform="avibe")
except Exception as e:
@@ -2330,6 +2355,11 @@ class Controller:
if show_git_checkpoint_service is not None:
show_git_checkpoint_service.stop()
+ # The Avibe Agent's recovery retries end with the service; the next start recovers again.
+ avibe_recovery = getattr(self, "avibe_recovery", None)
+ if avibe_recovery is not None:
+ _stop_loop_coroutine(avibe_recovery.stop(), "Avibe Agent recovery")
+
try:
codex_agent = self.agent_service.agents.get("codex")
if codex_agent and hasattr(codex_agent, "shutdown_runtime"):
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 9aae9dfb5..0cd8a8995 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -2854,6 +2854,9 @@ class ConsolidatedMessageDispatcher:
"delivery_suppressed": True,
}
native_output_id = output_semantics.native_message_id(target_context) if output is not None else None
+ # A backend that commits its own transcript row passes it here: every persist
+ # site below then writes that row's display columns instead of a second row.
+ existing_row_id = output_semantics.persisted_row_id
# For a result, persist the SAME cleaned text the user receives:
# process_reply() strips file:// markdown links + the trailing
@@ -3033,6 +3036,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
citations=citations,
+ existing_row_id=existing_row_id,
)
else:
persisted_output = persist_agent_message(
@@ -3043,6 +3047,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
citations=citations,
+ existing_row_id=existing_row_id,
)
else:
persisted_output = persist_agent_message(
@@ -3052,6 +3057,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
citations=citations,
+ existing_row_id=existing_row_id,
)
local_message_id = (persisted_output or {}).get("id") or (
f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"
@@ -3479,6 +3485,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
citations=citations,
+ existing_row_id=existing_row_id,
)
else:
persisted_output = persist_agent_message(
@@ -3489,6 +3496,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
citations=citations,
+ existing_row_id=existing_row_id,
)
if settlement_waits_for_persistence:
@@ -3621,7 +3629,9 @@ class ConsolidatedMessageDispatcher:
# Persist the intermediate log row BEFORE the mute filter so muted
# assistant / tool_call messages still land in the store (product
# requirement: the process log is complete even when a channel hides it).
- persist_agent_message(target_context, canonical_type, persist_text, citations=citations)
+ persist_agent_message(
+ target_context, canonical_type, persist_text, citations=citations, existing_row_id=existing_row_id
+ )
# Web only: the same text additionally lands as a transcript-visible
# ``interim`` row. Every backend emits ``assistant`` only once later output
# has proved the text is not the Turn's final answer, so this never
diff --git a/core/message_mirror.py b/core/message_mirror.py
index d6eb7b989..4932283f9 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -298,9 +298,15 @@ def persist_agent_message(
metadata: Optional[dict[str, Any]] = None,
native_message_id: Optional[str] = None,
error_sink: Optional[list] = None,
+ existing_row_id: Optional[str] = None,
) -> Optional[dict]:
"""Persist one agent output into the workbench ``messages`` store.
+ ``existing_row_id`` names a row the backend already committed as its transcript
+ (the Avibe Agent): its display columns are written instead of inserting a
+ second row, and everything after the write (rank, ``message.new``, inbox) is
+ unchanged (``_write_committed_row``).
+
Unified across **all** platforms (including avibe, which has no IM mirror)
and called BEFORE any IM delivery/mute decision, so assistant messages and
tool-call trace events land even when a channel hides them. Each ``emit_agent_message``
@@ -427,23 +433,40 @@ def persist_agent_message(
# survives reload because it lives on the row, not in the delivery.
if citation_rows:
content = {**(content or {}), "citations": citation_rows}
- appended_row = _append_quietly(
- conn,
- scope_id=scope_id,
- session_id=row_session_id,
- platform=context.platform,
- author="agent",
- source="agent",
- author_name=agent_name,
- message_type=message_type,
- text=text,
- metadata=metadata,
- native_message_id=native_message_id,
- parent_native_message_id=context.thread_id,
- content=content,
- )
+ if existing_row_id:
+ appended_row = _write_committed_row(
+ conn,
+ existing_row_id,
+ session_id=row_session_id,
+ platform=context.platform,
+ scope_id=scope_id,
+ message_type=message_type,
+ text=text,
+ content=content,
+ metadata=metadata,
+ native_message_id=native_message_id,
+ parent_native_message_id=context.thread_id,
+ suppress_delivery=suppress_delivery,
+ )
+ else:
+ appended_row = _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=row_session_id,
+ platform=context.platform,
+ author="agent",
+ source="agent",
+ author_name=agent_name,
+ message_type=message_type,
+ text=text,
+ metadata=metadata,
+ native_message_id=native_message_id,
+ parent_native_message_id=context.thread_id,
+ content=content,
+ )
if (
- appended_row is None
+ existing_row_id is None
+ and appended_row is None
and native_message_id
and not suppress_delivery
and spec_for(message_type)["inboxPreview"]
@@ -575,6 +598,95 @@ def persist_agent_message(
return None
+# Display keys ``persist_agent_message`` owns in ``content_json``; ``model`` (the
+# transcript payload of a committed row) is never among them.
+_DISPLAY_CONTENT_KEYS = ("text", "kind", "quick_replies", "result_footer", "citations")
+_FINAL_ROW_TYPES = ("result", "error")
+
+
+def _write_committed_row(
+ conn,
+ row_id: str,
+ *,
+ session_id: Optional[str],
+ platform: str,
+ scope_id: Optional[str],
+ message_type: str,
+ text: str,
+ content: Optional[dict],
+ metadata: Optional[dict],
+ native_message_id: Optional[str],
+ parent_native_message_id: Optional[str],
+ suppress_delivery: bool,
+) -> Optional[dict]:
+ """Write the display columns of an agent row its backend committed; never insert one.
+
+ The same rules as an inserted row, applied to the committed one:
+
+ * the row is attributed to the delivery target (``platform``, ``scope_id``);
+ * a terminal write types the row ``result`` or ``error`` (the dispatcher's
+ failure classification), including a final the backend committed hidden
+ because it had nothing to show; any other write keeps the row's type;
+ * the row takes the output's ``native_message_id``, which is how the
+ dispatcher recognizes a retry of the same output, but never one another row
+ holds, so the unique index cannot break (a concurrent duplicate, which
+ ``_append_quietly`` swallows for an inserted row);
+ * an outward send clears a ``delivery_suppressed`` marker, the promotion
+ ``promote_suppressed_native_message`` performs for an inserted row.
+
+ The transcript payload (``content_json.model``), the row's place in the
+ transcript (``created_at``, ``delivered_at``), and its context identity stay as
+ committed.
+ """
+ import json
+
+ from sqlalchemy import select, update
+
+ from storage.models import messages
+
+ row = conn.execute(
+ select(messages).where(messages.c.id == row_id, messages.c.author == "agent")
+ ).mappings().first()
+ if row is None or (session_id is not None and row["session_id"] != session_id):
+ logger.warning("persist_agent_message: committed row %s is not an agent row of this Session", row_id)
+ return None
+ try:
+ body = json.loads(row["content_json"] or "{}")
+ old_metadata = json.loads(row["metadata_json"] or "{}")
+ except (TypeError, ValueError):
+ body, old_metadata = {}, {}
+ body = {key: value for key, value in body.items() if key not in _DISPLAY_CONTENT_KEYS}
+ body.update({key: value for key, value in (content or {}).items() if key != "model"})
+ body["text"] = text
+ merged_metadata = {key: value for key, value in old_metadata.items() if key != "delivery_suppressed"}
+ merged_metadata.update(metadata or {})
+ if suppress_delivery:
+ merged_metadata["delivery_suppressed"] = True
+ values: dict = {
+ "content_text": text,
+ "content_json": json.dumps(body),
+ "metadata_json": json.dumps(merged_metadata),
+ "updated_at": messages_service.canonical_message_timestamp(_now()),
+ }
+ if scope_id is not None:
+ values.update(platform=platform, scope_id=scope_id)
+ if message_type in _FINAL_ROW_TYPES:
+ values["type"] = message_type
+ if parent_native_message_id and not row["parent_native_message_id"]:
+ values["parent_native_message_id"] = parent_native_message_id
+ if native_message_id and native_message_id != row["native_message_id"]:
+ target_platform, target_scope = values.get("platform", row["platform"]), values.get("scope_id", row["scope_id"])
+ holder = messages_service.get_native_message(
+ conn, platform=target_platform, scope_id=target_scope, native_message_id=native_message_id
+ )
+ if holder is None:
+ values["native_message_id"] = native_message_id
+ else:
+ logger.warning("persist_agent_message: native id %s already belongs to row %s", native_message_id, holder["id"])
+ conn.execute(update(messages).where(messages.c.id == row_id).values(**values))
+ return messages_service.get_message(conn, row_id, include_local_error_detail=True)
+
+
def persist_silent_terminal(
context: MessageContext,
*,
diff --git a/core/message_output.py b/core/message_output.py
index 3e1f1b4a6..03d57452c 100644
--- a/core/message_output.py
+++ b/core/message_output.py
@@ -63,6 +63,10 @@ class MessageOutput:
requires_delivery_for_run_settlement: bool = False
settled_by: str | None = None
metadata: Mapping[str, Any] = field(default_factory=dict)
+ # ``messages.id`` of a row the backend already committed as its transcript (the
+ # Avibe Agent). Persistence then writes that row's display columns instead of
+ # inserting a second row; nothing else about delivery changes.
+ persisted_row_id: str | None = None
@property
def settles_run(self) -> bool:
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 8ae4596e0..f352dd1ce 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -363,6 +363,8 @@ def reserve_forked_session(
metadata.pop("fork_opencode_message_id", None)
metadata.pop("fork_opencode_fork_empty_history", None)
metadata.pop("fork_opencode_boundary_from_active_run", None)
+ # A source that is itself a fork carries its own anchor; the child's is resolved below.
+ metadata.pop("fork_source_context_seq", None)
metadata.update(
{
"created_via": "session_fork",
@@ -376,6 +378,25 @@ def reserve_forked_session(
"fork_created_at": now,
}
)
+ if source_backend == "avibe":
+ # The Avibe Agent's context is the source's rows up to the anchor, resolved
+ # once now so later rows never enter the prefix (C-5 section 4). With no
+ # running Turn the anchor is the whole context, as a native fork keeps the
+ # whole settled session: a silent or stopped Turn shows no row to name.
+ from storage.agent_transcript import context_bound, resolve_fork_anchor_seq
+ from storage.models import session_turns
+
+ running = conn.execute(
+ select(session_turns.c.id).where(
+ session_turns.c.session_id == str(row["id"]),
+ session_turns.c.state.in_(("starting", "active")),
+ ).limit(1)
+ ).first()
+ metadata["fork_source_context_seq"] = (
+ resolve_fork_anchor_seq(conn, str(row["id"]), source_message_id)
+ if running is not None
+ else context_bound(conn, str(row["id"]))
+ )
if opencode_fork_message_id:
metadata["fork_opencode_message_id"] = opencode_fork_message_id
if opencode_fork_empty_history:
diff --git a/core/session_titles.py b/core/session_titles.py
index 8714056b5..0d7016323 100644
--- a/core/session_titles.py
+++ b/core/session_titles.py
@@ -7,6 +7,8 @@ from typing import Any
from core.inbox_events import bus
from core.services import sessions as workbench_sessions_service
+from modules.agents.catalog import NATIVE_CLI_BACKENDS
+from modules.agents.native_sessions.base import derive_first_prompt_title
from modules.agents.native_sessions.service import AgentNativeSessionService
from storage import messages_service
from storage.db import create_sqlite_engine
@@ -47,6 +49,10 @@ def backfill_agent_session_title(
native_session_id=native_session_id,
first_user_message=first_user_message or fallback_first_user_message,
)
+ if candidate is None and backend not in NATIVE_CLI_BACKENDS:
+ # A backend with no native session store (the Avibe Agent) is titled the way
+ # the native providers title a session without metadata: from its first prompt.
+ candidate = derive_first_prompt_title(first_user_message or fallback_first_user_message)
if candidate is None:
return None
updated = workbench_sessions_service.backfill_session_title(
diff --git a/core/session_turns.py b/core/session_turns.py
index 18663e4c9..2982b1afd 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -207,7 +207,9 @@ _EXECUTION_ROUTING_KEYS = _FLUSH_REBUILT_KEYS | frozenset(
)
SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"
-_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex"})
+# Runtimes bound to the controller process: an accepted Turn cannot survive a
+# service restart. ``avibe`` runs its loop in this process.
+_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex", "avibe"})
_MAX_AUTOMATIC_UNKNOWN_START_REPLAYS = 1
_MAX_PREWRITE_START_ATTEMPTS = 3
_UNKNOWN_START_REPLAY_INSTRUCTION = (
@@ -2710,7 +2712,7 @@ class SessionTurnManager:
)
else:
receipt = await self._attempt_steer(backend, request)
- return await self._finish_steer(delivery_id, receipt, context=context)
+ return await self._finish_steer(delivery_id, receipt, context=context, expected_attempt_id=attempt_id)
async def _reconcile_steer_attempt(
self,
@@ -3250,6 +3252,7 @@ class SessionTurnManager:
receipt: Any,
*,
context: Optional["MessageContext"],
+ expected_attempt_id: Optional[str] = None,
) -> DeliveryResult:
outcome = getattr(receipt, "outcome", SteerOutcome.UNKNOWN)
outcome_value = str(getattr(outcome, "value", outcome))
@@ -3277,6 +3280,16 @@ class SessionTurnManager:
target_turn_id = str(delivery.get("current_target_turn_id") or "")
session_id = str(delivery["session_id"])
attempt_id = str(delivery.get("current_attempt_id") or "")
+ if expected_attempt_id is not None and attempt_id != expected_attempt_id:
+ # A receipt for an attempt this Delivery no longer has (settled, or
+ # superseded by a newer attempt) changes nothing.
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str(delivery.get("state") or "reconciling_steer"),
+ target_turn_id or None,
+ "receipt_cas_lost",
+ )
attempt_rows = (
delivery_store.attempt_deliveries(conn, attempt_id)
if attempt_id
@@ -3328,6 +3341,20 @@ class SessionTurnManager:
target_turn_id or None, "receipt_cas_lost",
)
elif not materialized:
+ # A negative receipt is fenced like the ACCEPTED and UNKNOWN branches:
+ # it settles only a current attempt whose Deliveries are still steering
+ # or reconciling. A late or duplicate one for an attempt already settled
+ # would otherwise move a Delivery a newer Turn has since claimed.
+ if not attempt_id or not attempt_rows or any(
+ row["state"] not in {"steering", "reconciling_steer"} for row in attempt_rows
+ ):
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str(delivery.get("state") or "reconciling_steer"),
+ target_turn_id or None,
+ "receipt_cas_lost",
+ )
session_status = conn.execute(
select(agent_sessions.c.status).where(
agent_sessions.c.id == str(delivery["session_id"])
@@ -6232,6 +6259,7 @@ class SessionTurnManager:
str(delivery["id"]),
receipt,
context=None,
+ expected_attempt_id=attempt_id,
)
return result.state != "reconciling_steer"
return False
@@ -6819,6 +6847,7 @@ class SessionTurnManager:
str(attempt["id"]),
receipt,
context=None,
+ expected_attempt_id=attempt_id,
)
if result.state != "reconciling_steer":
recovered.append(str(attempt["session_id"]))
diff --git a/core/watches.py b/core/watches.py
index b8f82e105..5da8460d1 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -765,6 +765,7 @@ class ManagedWatchStore:
message: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
user_context: Any = None,
+ unverifiable_remote: bool = False,
) -> str:
"""The id of the Watch that owns ``job`` (its ``meta.json``), created if none does.
@@ -795,6 +796,7 @@ class ManagedWatchStore:
message=message,
metadata=metadata,
user_context=user_context,
+ unverifiable_remote=unverifiable_remote,
)
except Exception:
try:
@@ -816,17 +818,23 @@ class ManagedWatchStore:
message: Optional[str],
metadata: Optional[dict[str, Any]],
user_context: Any,
+ unverifiable_remote: bool = False,
) -> str:
from core.vibe_agents import ensure_agent_name_access
- from storage.resource_access_service import (
- ensure_harness_definition_write,
- metadata_with_resource_user_context,
- )
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY, ensure_harness_definition_write
- ensure_harness_definition_write(user_context)
- ensure_agent_name_access(agent_name, user_context=user_context)
target = _job_target_from_meta(job)
- watch_metadata = metadata_with_resource_user_context(metadata, user_context)
+ if unverifiable_remote:
+ # The job's Turn was remote but its authorization cannot be verified: the
+ # Watch still owns the job (no command runs without an owner), and it never
+ # follows up (``watch_allows_runtime``).
+ authority = (RESOURCE_USER_CONTEXT_METADATA_KEY, JOB_WATCH_AUTHORIZATION_METADATA_KEY)
+ watch_metadata = {key: value for key, value in (metadata or {}).items() if key not in authority}
+ watch_metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] = dict(UNVERIFIABLE_REMOTE_AUTHORIZATION)
+ else:
+ ensure_harness_definition_write(user_context)
+ ensure_agent_name_access(agent_name, user_context=user_context)
+ watch_metadata = _with_job_watch_authority(metadata, user_context)
watch_metadata[WATCH_TARGET_METADATA_KEY] = target
watch = ManagedWatch(
id=uuid4().hex[:12],
@@ -1069,10 +1077,12 @@ class ManagedWatchStore:
watch.retry_delay_seconds = retry_delay_seconds
watch.post_to = post_to
watch.deliver_key = deliver_key
- watch.metadata = metadata_with_resource_user_context(
- metadata if metadata is not None else watch.metadata,
- user_context,
+ # An update re-authors the Watch to its updater; a job Watch records that
+ # authority explicitly, like its hand-over did.
+ with_authority = (
+ _with_job_watch_authority if watch.job_target is not None else metadata_with_resource_user_context
)
+ watch.metadata = with_authority(metadata if metadata is not None else watch.metadata, user_context)
if waiter_lifecycle_changed:
watch.metadata = dict(watch.metadata)
watch.metadata.pop(RECENT_EVENT_TIMESTAMPS_METADATA_KEY, None)
@@ -2590,10 +2600,7 @@ class ManagedWatchService:
await asyncio.sleep(delay)
async def _run_watch(self, watch_id: str) -> None:
- from storage.resource_access_service import (
- HARNESS_ACCESS_FORBIDDEN_CODE,
- metadata_allows_harness_runtime,
- )
+ from storage.resource_access_service import HARNESS_ACCESS_FORBIDDEN_CODE
lifetime_started: float | None = None
self._watch_started_at[watch_id] = _utc_now_iso()
@@ -2614,7 +2621,7 @@ class ManagedWatchService:
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
return
- if not metadata_allows_harness_runtime(watch.metadata):
+ if not watch_allows_runtime(watch):
self._watch_store_call(
watch.id,
"suspend_remote_origin",
@@ -3334,6 +3341,50 @@ def _format_elapsed(seconds: float) -> str:
return f"{secs}s"
+# A job Watch records whose authority its follow-up runs under: a remote snapshot, or
+# this marker for the installation's own (local) Turns. Never implied by absence.
+JOB_WATCH_AUTHORIZATION_METADATA_KEY = "job_watch_authorization"
+JOB_WATCH_LOCAL_AUTHORIZATION = "local"
+# The snapshot of a remote Turn whose authorization could not be found.
+UNVERIFIABLE_REMOTE_AUTHORIZATION = {"unverifiable": True}
+
+
+def _with_job_watch_authority(metadata: Optional[Mapping[str, Any]], user_context: Any) -> dict[str, Any]:
+ """``metadata`` recording ``user_context`` as a job Watch's authority: its snapshot, or the local marker."""
+ from storage.resource_access_service import metadata_with_resource_user_context, resolve_resource_access_context
+
+ result = metadata_with_resource_user_context(metadata, user_context)
+ result.pop(JOB_WATCH_AUTHORIZATION_METADATA_KEY, None)
+ if not resolve_resource_access_context(user_context).is_remote:
+ result[JOB_WATCH_AUTHORIZATION_METADATA_KEY] = JOB_WATCH_LOCAL_AUTHORIZATION
+ return result
+
+
+def watch_allows_runtime(watch: "ManagedWatch") -> bool:
+ """Whether a Watch may keep running and follow up, under the authority it recorded.
+
+ A legacy (waiter-command) Watch keeps the rule that a missing snapshot means a
+ local definition. A job Watch must carry its authorization explicitly: a remote
+ snapshot that still passes the recheck, or the local marker; anything else,
+ including an unverifiable snapshot, is denied.
+ """
+ from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ metadata_allows_harness_runtime,
+ metadata_has_remote_resource_context,
+ )
+
+ metadata = watch.metadata
+ if watch.job_target is None:
+ return metadata_allows_harness_runtime(metadata)
+ if metadata_has_remote_resource_context(metadata):
+ return (
+ metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] != UNVERIFIABLE_REMOTE_AUTHORIZATION
+ and metadata_allows_harness_runtime(metadata)
+ )
+ return isinstance(metadata, dict) and metadata.get(JOB_WATCH_AUTHORIZATION_METADATA_KEY) == JOB_WATCH_LOCAL_AUTHORIZATION
+
+
async def hand_over_job(
job: Mapping[str, Any],
*,
diff --git a/docs/plans/agent-core-contracts/job.schema.json b/docs/plans/agent-core-contracts/job.schema.json
index 4b5dbd646..0971fbb0f 100644
--- a/docs/plans/agent-core-contracts/job.schema.json
+++ b/docs/plans/agent-core-contracts/job.schema.json
@@ -52,7 +52,8 @@
},
"created_at": {
"type": "string",
- "format": "date-time"
+ "format": "date-time",
+ "description": "UTC creation time at full microsecond precision; recovery compares it with a response's commit time to tell apart jobs a reused tool-call id started."
},
"state_dir": {
"type": "string",
@@ -127,7 +128,7 @@
"command": "pytest -q",
"cwd": "/work/repo",
"timeout_s": null,
- "created_at": "2026-10-02T04:12:09.512Z",
+ "created_at": "2026-10-02T04:12:09.512345Z",
"state_dir": "/home/u/.avibe/state/agent_core/jobs/job_31c",
"process": {
"pid": 48211,
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index 99c943838..6ca439611 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -35,13 +35,15 @@ commit input → loop:
else, holding the queue lock:
if a steer or follow-up is pending: commit the response as `assistant`, commit the pending inputs,
release the lock → continue loop
- else: commit the response as `result` (final) and close the queues for this run, release the lock → end
+ else: commit the response as final (`result`, or `error` when it failed) and close the queues, release the lock → end
```
-Finality is decided before the response row is inserted, so a `result` row is always the run's last response. A final
-response with `stop_reason` `refusal` or `safety` and no text is still committed as `result`; its rendered display text
-is the localized explanation, written in the same transaction, so re-delivery after a crash shows it too. The run also
-ends with an `error` event of that kind. Refusal text from the provider is kept as the reply. A
+Finality is decided before the response row is inserted, so a final (`result` or `error`) row is always the run's last
+response. A final response with `stop_reason` `refusal` or `safety` and no text is still committed as the final
+response, typed `error` ([`transcript.md`](transcript.md) §1); its commit-time display text is the localized
+explanation. (That it is written in the same transaction so that re-delivery after a crash shows it is moot: Avibe
+delivers committed rows through the shared emit path and nothing re-delivers them, [`recovery.md`](recovery.md)
+§Delivery.) The run also ends with an `error` event of that kind. Refusal text from the provider is kept as the reply. A
steer that arrives after the queues closed is refused by the running Turn, and Avibe's delivery falls back to the P3
queue, which starts the next run.
@@ -88,10 +90,10 @@ sent with that request gets the error result `Tool <name> is not available.`
| Event | Avibe effect |
| --- | --- |
| `run_started` | none; the Turn was opened by its delivery |
-| `text_delta`, `thinking_delta` | streaming progress (status bubble, Workbench live text) |
+| `text_delta`, `thinking_delta` | dropped in v1: no backend shows live partial text, so progress comes from the committed narration and tool lines, as for the other backends (live partial text is a follow-up that needs a new UI surface for every backend, `avibe-agent-core.md` §10) |
| `message_committed` | the committed `messages` row is delivered: `assistant` as activity, `result` as the reply |
| `tool_started` | `agent_events` `tool_call` trace row; IM progress line |
-| `tool_progress` | status bubble update |
+| `tool_progress` | dropped in v1: no backend shows live tool output, so a running tool shows its `tool_started` line, as for the other backends (live tool output joins the live partial text and progress follow-up, `avibe-agent-core.md` §10) |
| `tool_finished` | the committed `tool_result` row; a handed-over job names its Watch |
| `steer_applied` | the steer delivery is accepted into the running Turn |
| `compaction_started`, `compaction_finished`, `compaction_failed` | optional status line; failures always reported |
diff --git a/docs/plans/agent-core-contracts/recovery.md b/docs/plans/agent-core-contracts/recovery.md
index 4a677304f..0fd4a9d9a 100644
--- a/docs/plans/agent-core-contracts/recovery.md
+++ b/docs/plans/agent-core-contracts/recovery.md
@@ -24,19 +24,19 @@ at-least-once, and that is stated where it applies.
| ID | Invariant | Proof |
| --- | --- | --- |
| T1 | `project()` reads only committed rows; the same rows always produce the same request. | projection before and after job state changes |
-| T2 | At resume, before the first projection, every tool call without a committed `tool_result` gets exactly one, chosen from its job state (exited: the output; running: handover; never ran: the interrupted result). A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice. | crash between settlement steps, then resume twice |
-| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context or are returned to the adapter for the P3 queue, including after a crash (the adapter re-queues accepted but unconsumed inputs at resume). | a terminating tool while a steer is queued; a crash before consumption |
+| T2 | At resume, before the first projection, every tool call without a committed `tool_result` gets exactly one, chosen from its job state (exited: the output; running: handover; never ran: the interrupted result). A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice, and neither do concurrent writers: the store's `append_tool_result` returns the result already committed for the call instance instead of writing a second. | crash between settlement steps, then resume twice |
+| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context, including after a crash. They belong to the Turn that accepted them and are never re-queued as a new P3 Turn. A run that ended by design runs again for them within its Turn; after a stop, an error, or a crash they are admitted into the context (at the end of the run, or at the Session's resume) and share the Turn's outcome. | a terminating tool while a steer is queued; a crash before consumption |
| T4 | An unsettled Turn found at startup is settled as interrupted after T2; the agent never continues it on its own (a hook `end`, an abort, or a crash all leave the same safe state). The user's next message starts a new Turn with the full context. | crash after an `end` hook and after a mid-turn commit |
## Delivery (adapter wave)
-| ID | Invariant | Proof |
-| --- | --- | --- |
-| D1 | A committed response is delivered completely: every part a surface splits it into is either confirmed or retried. A partial delivery is never recorded as delivered. | failure on a later part, and a crash between parts |
-| D2 | Workbench delivery is exactly once (the row is the message). IM delivery is at least once per part: `BaseIMClient.send_message` has no idempotency key, so a crash after the platform accepted a part but before its receipt was committed resends that part. | crash after accept, before receipt |
-
-Today `core/message_dispatcher.py` swallows failures of later split chunks and returns the first chunk's id. The
-adapter wave must not reuse that path as is for agent rows; D1 is the requirement it meets.
+D1 and D2 are withdrawn (owner decision, 2026-10-03, PR #2345). The Avibe Agent delivers each committed response
+through the same emit path as the other backends: splitting, file upload, failure handling, and narration settings
+are the dispatcher's. The one difference is persistence: the response row already exists, so the dispatcher writes
+its display columns instead of inserting a second row (`transcript.md` §2). A crash or send failure between commit
+and send loses that delivery, as it does for the other backends; the transcript, and so the context, is unaffected.
+A Turn interrupted after its final commit is settled by T4 like any other, so the user sees the interruption
+notice, and the committed reply stays in the Workbench transcript with its commit-time display.
## Shared fields
@@ -44,5 +44,7 @@ The only cross-lane shapes recovery adds:
- `meta.json` (`job.schema.json`): `deadline_at` (absolute, nullable), and `process` with the identity fields of
`PersistedProcessIdentity` (`core/process_isolation.py`), recorded before the command can run (J2).
-- Watch `job` target: keyed by `job_id`, created by adopt-or-create (J6).
-- Response rows: `metadata_json.delivery` with one entry per part (`transcript.md` §2).
+- Watch `job` target: keyed by `job_id`, created by adopt-or-create (J6). The hand-over takes the Watch's Agent and
+ authority from the job's owning Turn, never from the caller of the hand-over, and records that authority
+ explicitly: the Turn's remote snapshot, a local marker, or an unverifiable snapshot (a remote Turn whose
+ authorization cannot be found). A job Watch without a verifiable authority still owns its job but never follows up.
diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.md
index a634a0a7d..a6c690795 100644
--- a/docs/plans/agent-core-contracts/tools.md
+++ b/docs/plans/agent-core-contracts/tools.md
@@ -202,6 +202,6 @@ os: macOS 26.0 (arm64)
shell: /bin/zsh
date: 2026-10-02
timezone: Asia/Shanghai
-watches: wch_8f2k "pytest -q" running 6m
+watches: wch_8f2k "nightly sync" command running; wch_3c1d job running
</environment>
```
diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.md
index d78961877..9859e1501 100644
--- a/docs/plans/agent-core-contracts/transcript.md
+++ b/docs/plans/agent-core-contracts/transcript.md
@@ -12,15 +12,21 @@ unique per Session across both tables (partial unique index on each table, plus
| --- | --- | --- | --- | --- |
| user or steer input | `messages` | `user` | — | `content_json.model` = `ModelInput` |
| harness input | `messages` | `harness`, `agent_initiated`, `annotation` | — | `content_json.model` = `ModelInput` |
-| model response | `messages` | `assistant` (not final), `result` (final) | — | `content_json.model` = `ModelResponse` |
+| model response | `messages` | `assistant` (not final), `result` or `error` (final) | — | `content_json.model` = `ModelResponse` |
| tool result | `agent_events` | `tool_result` | `context` | `content_json` = `ToolResult` |
| checkpoint | `agent_events` | `context_compaction` | `context` | `content_json` = `Compaction` |
| cleared result | `agent_events` | `context_edit` | `context` | `content_json` = `ContextEdit` |
| hook state | `agent_events` | `agent_state` | `context` | `content_json` = `AgentState` |
-Display-only rows keep `context_seq` null: `interim`, `notify`, `error`, `vault`, `output`, queued or removed inputs,
-and the `tool_call` trace row written at tool start (its `metadata_json` carries `tool_call_id` and `job_id` so the
-activity panel can pair it with the result).
+A final response is `error` when it failed by itself (no text of its own: an empty answer, or a refusal or safety
+stop without an explanation), as the other backends' failed terminal rows are. A successful final with nothing to show
+(a silent reply) is the hidden response type `assistant`: context, but no transcript row, inbox reply, or unread
+result, as the other backends persist nothing visible for it; a terminal write at delivery (a run that failed after
+the commit) types it `error`. Context loading accepts all three.
+
+Display-only rows keep `context_seq` null: `interim`, `notify`, an `error` that reports a run failure, `vault`,
+`output`, queued or removed inputs, and the `tool_call` trace row written at tool start (its `metadata_json` carries
+`tool_call_id` and `job_id` so the activity panel can pair it with the result).
## 2. Writing
@@ -29,19 +35,19 @@ activity panel can pair it with the result).
fork's first entry follows its inherited prefix.
- Inputs already exist as rows when they are submitted. The loop sets `context_seq` and `content_json.model` on that
row when it consumes the input. Each entry is its own transaction; an input accepted by `steer` but not yet
- consumed when a crash happens is re-queued by the adapter at resume (`recovery.md` T3).
-- A response row is inserted at `message_end` with both `content_json.model` and its rendered `content_text`.
+ consumed when a crash happens is admitted into the context by the adapter at resume (`recovery.md` T3).
+- A response row is inserted at `message_end` with both `content_json.model` and its commit-time display
+ `content_text`.
- A tool result row is inserted at `tool_finished`. The `tool_call` trace row is inserted at tool start without a
`context_seq`.
-- Each commit is one SQLite transaction. The adapter delivers a row to surfaces only after it commits; the
- dispatcher does not persist it again.
-- **Output outbox.** Every row a run produces for a surface (`assistant`, `result`, and the `notify` / `error` rows
- that report its failures) is in the outbox. Such a row is committed with `metadata_json.delivery = {"state":
- "pending", "parts": []}` in the same transaction; each part a surface sends is recorded with its receipt, and the
- row is `delivered` only when every part is (`recovery.md` D1). After the surface accepts it, the adapter sets `{"state": "delivered"}` with
- the platform receipt (`native_message_id` where the platform returns one). At startup, and before a Session
- resumes, the adapter re-delivers its `pending` rows in `context_seq` order. Nothing is lost or regenerated;
- duplicates are possible on IM in one window ([`recovery.md`](recovery.md) §Delivery).
+- Each commit is one SQLite transaction. The adapter delivers a row to surfaces only after it commits, through the
+ same emit path as the other backends, naming the row (`MessageOutput.persisted_row_id`). Every dispatcher persist
+ site then writes that row's display columns instead of inserting a second row: `content_text`, the display keys
+ of `content_json` (`text`, `kind`, `quick_replies`, `result_footer`, `citations`), the delivery target's
+ `platform` and `scope_id`, `metadata_json` (including the `delivery_suppressed` marker and its promotion), the
+ output's `native_message_id` unless another row holds it, and a final's `result` / `error` type. Nothing is
+ replayed: a delivery a crash or send failure interrupts is lost, as for the other backends
+ ([`recovery.md`](recovery.md) §Delivery).
## 3. Projection
@@ -78,6 +84,6 @@ The child Session's metadata already records its parent as top-level keys `fork_
- Trace retention never selects `visibility = 'context'`; a contract test pins this.
- The context content of a row never changes after commit: `context_seq` and `content_json.model` are written once
- (on an input row, when it is consumed). Delivery state in `metadata_json.delivery` is the one field that changes
- afterwards, and only through the outbox helpers. Context rows are never deleted while a Session or a fork descendant
- references them.
+ (on an input row, when it is consumed). A response row's display columns (§2) may be written again when it is
+ delivered; they are never context. Context rows are never deleted while a Session or a fork descendant references
+ them.
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index a528b076e..fe7f05c09 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -400,3 +400,12 @@ contracts and checked against the implementing lane's code before they are close
| P1 | `avibe-agent-core.md` | Keep background descendants inside the job lifecycle |
| P2 | `loop-control.md` | Avoid delivering refusal errors twice |
| P2 | `message.schema.json` | Require content in canonical tool results |
+
+## 10. Follow-ups
+
+| Item | Owner | Note |
+| --- | --- | --- |
+| Product-wide media retention | `storage/media_service.py` | No media file is removed from disk today, whether Workbench upload, IM attachment, or Avibe Agent context snapshot (`<state>/agent_core/media`); session deletion only clears or cascades `media_objects` references. Retention needs one owner for every source. It must be fork-aware: a fork descendant keeps replaying the image tokens of a source Session that was deleted. Recorded as a v1 known limit in PR #2345. |
+| Steer receipt fencing in the shared Turn owner | `core/session_turns.py` (`_finish_steer`) | **Done in PR #2345** (orchestrator-authorized cross-lane fix): a negative receipt settles only a current attempt whose Deliveries are still steering or reconciling, and a caller that knows the attempt passes `expected_attempt_id`, so a late or duplicate receipt can no longer pull a Delivery out of a Turn that claimed it. Regression: `test_a_late_negative_steer_receipt_never_moves_a_delivery_its_attempt_no_longer_owns`. |
+| Live partial text and progress | every backend, Workbench and IM | No backend shows streamed partial text or live tool output today; the Avibe Agent drops `text_delta`, `thinking_delta`, and `tool_progress` (`loop-control.md` §6). Showing them needs a new UI surface for every backend, not an Avibe Agent change. |
+| Call-instance identity for job files | `core/agent_core/tools/` (`ToolContext`, job `meta.json`), the adapter | A tool call's identity is its instance: the owning response plus the call id, because providers reuse ids. Rows are matched by context order; job files still fall back to the clock (`find_job(created_since)`, J5's result-after-creation check), which assumes a non-decreasing wall clock between a response's commit and its job's start. Threading the call instance (owning response row and `context_seq`) into `ToolContext` and the job meta would remove that last residual. |
diff --git a/modules/agents/avibe/__init__.py b/modules/agents/avibe/__init__.py
new file mode 100644
index 000000000..697951e42
--- /dev/null
+++ b/modules/agents/avibe/__init__.py
@@ -0,0 +1,5 @@
+"""The Avibe Agent backend (``avibe``): Avibe's own agent loop as a ``BaseAgent``."""
+
+from modules.agents.avibe.agent import AvibeAgent
+
+__all__ = ["AvibeAgent"]
diff --git a/modules/agents/avibe/agent.py b/modules/agents/avibe/agent.py
new file mode 100644
index 000000000..f37977ef5
--- /dev/null
+++ b/modules/agents/avibe/agent.py
@@ -0,0 +1,1305 @@
+"""``AvibeAgent``: the Avibe Agent engine (``core.agent_core``) as an Avibe backend.
+
+One Turn is one ``Agent.run`` (plan section 4). The adapter
+
+* resolves the model through Model Hub (``resolve_hop``) before the input is
+ written, so a refused route fails like any backend that never started;
+* marks native acceptance, which materializes the input's ``messages`` row, and
+ then runs the loop, whose rows *are* the transcript (C-5);
+* delivers every committed response through the same emit path as the other
+ backends; the dispatcher writes the committed row's display columns instead
+ of persisting a second row (``MessageOutput.persisted_row_id``);
+* steers the running loop with P1 deliveries and lets a refused steer fall back
+ to the P3 queue; Stop aborts the run;
+* before any run of a Session in this process, under the Session writer lock,
+ settles open tool calls (T2) and admits accepted inputs that were never
+ consumed (T3); at startup it settles every Session's open calls eagerly. The
+ Turn a restart interrupted is settled by the Turn owner (T4; ``avibe`` is a
+ process-bound runtime).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import secrets
+import time
+from contextlib import asynccontextmanager
+from dataclasses import dataclass, field, replace
+from datetime import datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, AsyncIterator, Callable, Mapping, Optional, Sequence
+
+from sqlalchemy import and_, select
+from sqlalchemy.engine import Engine
+
+from config import paths
+from core.agent_core.agent.events import (
+ AgentError,
+ AgentEvent,
+ MessageCommitted,
+ RunEnded,
+ ToolStarted,
+)
+from core.agent_core.agent.hooks import AgentInput
+from core.agent_core.agent.loop import Agent
+from core.agent_core.agent.models import ModelSelection
+from core.agent_core.agent.recovery import settle_open_calls
+from core.agent_core.harness.projection import open_tool_calls
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.tools.jobs import instant
+from core.agent_core.messages import (
+ IMAGE_MIME_TYPES,
+ AssistantMessage,
+ ToolCallBlock,
+ UserMessage,
+ text as text_block,
+)
+from core.agent_input import AgentInputMetadata
+from core.services.agent_steering import (
+ ActiveSteerTarget,
+ SteerOutcome,
+ SteerReconcileRequest,
+ SteerRequest,
+ SteerResult,
+ result as steer_result,
+)
+from core.backend_failure import emit_backend_failure
+from core.message_output import MessageOutput, stop_output_for, terminal_output_for
+from core.native_dispatch_phase import mark_backend_dispatch_attempted
+from core.processing_indicator import STOPPED_REACTION_EMOJI
+from core.reply_enhancer import strip_silent_blocks
+from core.skill_observability import accept_catalog
+from modules.agents.avibe.errors import error_text
+from modules.agents.avibe.media import MediaSnapshots
+from modules.agents.avibe.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hop
+from modules.agents.avibe.prompt import current_environment, system_prompt
+from modules.agents.avibe.store import AdapterTranscriptStore
+from modules.agents.avibe.tools import ToolSuite, local_tool_suite
+from modules.agents.base import AGENT_RUNTIME_TURN_KEY, AgentRequest, BaseAgent
+from modules.im.base import FileAttachment
+from storage import message_deliveries as delivery_store
+from storage.agent_transcript import (
+ INPUT_TYPES,
+ RESPONSE_TYPES,
+ SQLiteTranscriptStore,
+ final_outcome,
+ render_text,
+ source_tool_result,
+)
+from storage.db import get_cached_sqlite_engine
+from storage.models import agent_events, agent_sessions, message_deliveries, messages, session_turns
+
+logger = logging.getLogger(__name__)
+
+BACKEND = "avibe"
+# Final responses whose empty text is explained by the stop itself (loop-control.md section 2).
+_EXPLAINED_STOPS = ("refusal", "safety")
+_COMPLETED = ("completed", "ended_by_hook")
+_JOB_PRUNE_INTERVAL_S = 3600.0
+
+
+def _relative_to(cwd: str) -> Callable[[str], str]:
+ """Tool-call paths relative to the run's cwd, as the Claude backend shows them."""
+
+ def relative(path: str) -> str:
+ # A relative argument names a path under the run's cwd, as the tool resolves it.
+ absolute = os.path.abspath(os.path.join(cwd, os.path.expanduser(path)) if cwd else os.path.expanduser(path))
+ if not cwd:
+ return absolute
+ shown = os.path.relpath(absolute, cwd)
+ return absolute if shown.startswith("../..") else shown
+
+ return relative
+
+
+@dataclass
+class _Run:
+ """One Turn's state, published before its first await (``handle_message``)."""
+
+ request: AgentRequest
+ session_id: str
+ turn_id: str
+ instance: str
+ agent: Optional[Agent] = None
+ router: Optional[HubModelRouter] = None
+ cwd: str = ""
+ settled: bool = False
+ reason: Optional[str] = None
+ # Model Hub's copy for a route it refused during the run (``_preflight``).
+ refusal: Optional[str] = None
+ errors: list[tuple[str, str]] = field(default_factory=list)
+ final_row: Optional[str] = None
+ tool_calls: dict[str, ToolCallBlock] = field(default_factory=dict)
+ # This run's committed responses by row id, for delivering them; released with the run.
+ responses: dict[str, AssistantMessage] = field(default_factory=dict)
+ # Steer attempts ``Agent.steer`` accepted into this run: reconcile's in-process evidence.
+ accepted_steers: set[str] = field(default_factory=set)
+ stop_requested: bool = False
+
+ @property
+ def native_turn_id(self) -> str:
+ """``avibe:<adapter instance>:<turn>``: the instance that runs the Turn, for steer reconcile."""
+ return f"{BACKEND}:{self.instance}:{self.turn_id}"
+
+
+@dataclass
+class _SessionRuntime:
+ """A Session's writer lock and run while some caller holds it; retired when idle."""
+
+ session_id: str
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ run: Optional[_Run] = None
+ cwd: str = ""
+ holders: int = 0
+
+
+class AvibeAgent(BaseAgent):
+ """Backend ``avibe``: the first-party agent loop over Avibe's own transcript rows."""
+
+ name = BACKEND
+
+ def __init__(
+ self,
+ controller: Any,
+ *,
+ engine: Optional[Engine] = None,
+ providers: Optional[ProviderFactory] = None,
+ tool_suite: Optional[ToolSuite] = None,
+ state_dir: Optional[Path] = None,
+ ) -> None:
+ super().__init__(controller)
+ self._engine = engine or get_cached_sqlite_engine()
+ state = Path(state_dir) if state_dir is not None else paths.get_state_dir() / "agent_core"
+ self._state_dir = state
+ self.media = MediaSnapshots(self._engine, state / "media")
+ self.store = AdapterTranscriptStore(
+ SQLiteTranscriptStore(self._engine, render=self._display_source),
+ self._engine,
+ environment=self._environment,
+ on_response=self._on_response,
+ )
+ self._providers = providers or registry_providers(media_loader=self.media)
+ self._tool_suite = tool_suite
+ # Per-Session state lives only while a caller holds the Session (``_held``);
+ # the last holder retires it, together with the store's per-Session state.
+ self._runtimes: dict[str, _SessionRuntime] = {}
+ # This adapter instance, named in every native turn id it reports: a steer attempt
+ # whose Turn another instance ran (a retired adapter or a previous process) has no
+ # live call here that could settle it.
+ self._instance = secrets.token_hex(4)
+ # Steer attempts whose live call is in flight in this instance: until it returns,
+ # that call owns the attempt's receipt.
+ self._steering: set[str] = set()
+ # J5 while the service runs: when the jobs directory was last pruned, and the pass in flight.
+ self._pruned_at: Optional[float] = None
+ self._prune_task: Optional[asyncio.Task] = None
+
+ # --- BaseAgent -----------------------------------------------------------
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ """One Turn, with a single entry and a single exit.
+
+ The Turn's state (its Stop intent, router, and failure route) is published
+ before anything is awaited, so a Stop in any phase is honored: before the
+ dispatch marks it settles the Turn as stopped with nothing dispatched. Every
+ exception raised before settlement goes to the Hub-aware ``_fail``; one raised during
+ or after it propagates to ``AgentService``, whose fallback releases the runtime gate;
+ every exit closes the router.
+ """
+ context = request.context
+ payload = context.platform_specific or {}
+ session_id = self.ensure_agent_session_id(request)
+ turn_id = str(payload.get("turn_token") or "").strip()
+ input_id = str(payload.get("delivery_id") or "").strip()
+ if not session_id or not turn_id or not input_id:
+ await self._fail(request, "generic", "Avibe Agent turn has no Session, Turn, or input identity.")
+ return
+ turn = _Run(request, session_id, turn_id, self._instance)
+ async with self._held(session_id, run=turn) as runtime:
+ try:
+ await self._run_turn(runtime, turn, input_id)
+ except Exception as error:
+ if turn.settled:
+ # Raised during or after settlement (its emits, or a failure notice): the
+ # shared owner's fallback releases the runtime gate, so it must see it.
+ raise
+ logger.exception("Avibe Agent turn failed for Session %s", session_id)
+ turn.settled = True
+ await self._fail(request, "generic", f"turn failed: {error}", cause=error)
+ finally:
+ await self._admit_returned_inputs(turn)
+ self.store.bind_agent(session_id, None)
+ if turn.router is not None:
+ await turn.router.aclose()
+ self._prune_jobs_soon()
+
+ async def _run_turn(self, runtime: _SessionRuntime, turn: _Run, input_id: str) -> None:
+ request, session_id = turn.request, turn.session_id
+ context = request.context
+ # Rows this Turn writes are the Turn's Agent's, from its request snapshot, even if the
+ # Session's selected Agent changes while it runs.
+ self.store.bind_agent(session_id, request.vibe_agent_name)
+ await self._resume(runtime)
+ if turn.stop_requested:
+ return await self._settle_stopped(turn)
+ cwd = request.working_path or runtime.cwd
+ try:
+ turn.router = await self._preflight(turn)
+ except Exception as error:
+ turn.settled = True
+ await self._fail_preflight(request, error)
+ return
+ if turn.stop_requested:
+ return await self._settle_stopped(turn)
+ sections, skill_catalog = await self._avibe_sections(request, cwd)
+ environment = await asyncio.to_thread(self._turn_environment, request, cwd)
+ self._start_agent(turn, cwd, sections, environment)
+ runtime.cwd = cwd
+ # Prepared before anything is dispatched (``core.native_dispatch_phase``).
+ message = await self._render_input(session_id, request.message, request.files, request.input_metadata)
+ if turn.stop_requested:
+ return await self._settle_stopped(turn)
+ # Native acceptance materializes the input row the loop consumes.
+ self.bind_agent_session_id(request, session_id)
+ mark_backend_dispatch_attempted(context)
+ self.mark_runtime_turn_started(context)
+ indicator = getattr(self.controller, "processing_indicator", None)
+ if indicator is not None:
+ # The ack message goes once the native write is accepted, as for the other backends.
+ await indicator.delete_ack_message(request)
+ accept_catalog(self.controller, context, skill_catalog, backend=BACKEND)
+ agent_input: Optional[AgentInput] = AgentInput(input_id, message)
+ while agent_input is not None:
+ if turn.stop_requested:
+ # A Stop acknowledged before this run could abort: no run starts. An input
+ # left unconsumed is admitted at the Session's next resume (T3).
+ turn.reason = "aborted"
+ break
+ async for event in turn.agent.run(agent_input, turn_id=turn.turn_id):
+ await self._on_event(turn, event)
+ agent_input = await self._continuing_input(turn)
+ await self._settle(turn)
+ self._maybe_backfill_session_title(request, session_id)
+
+ async def _settle_stopped(self, turn: _Run) -> None:
+ """A Stop before the loop started: the Turn settles as stopped, nothing dispatched."""
+ turn.reason = "aborted"
+ await self._settle(turn)
+
+ async def handle_stop(self, request: AgentRequest) -> bool:
+ run = self._stop_target(request)
+ if run is None:
+ request.stop_failure_reason = "not_active"
+ return False
+ run.stop_requested = True
+ if run.agent is not None:
+ run.agent.abort("stopped by user")
+ return True
+
+ def _stop_target(self, request: AgentRequest) -> Optional[_Run]:
+ """The Turn a Stop addresses: by its Session, or by the runtime key the shared layer gates on.
+
+ An IM ``/stop`` names no Session; like the other backends, it finds the Turn by
+ the runtime identity ``AgentService`` stamped on the request.
+ """
+ runtime = self._runtimes.get(self._session_id(request.context) or "")
+ if runtime is not None and runtime.run is not None:
+ return runtime.run
+ payload = getattr(request.context, "platform_specific", None) or {}
+ key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip() or self.runtime_turn_key(request)
+ return next(
+ (rt.run for rt in self._runtimes.values() if rt.run is not None and self.runtime_turn_key(rt.run.request) == key),
+ None,
+ )
+
+ async def clear_sessions(self, session_key: str) -> int:
+ cleared = 0
+ for runtime in list(self._runtimes.values()):
+ run = runtime.run
+ if run is not None and run.request.session_key == session_key:
+ run.stop_requested = True
+ if run.agent is not None:
+ run.agent.abort("session cleared")
+ cleared += 1
+ return cleared
+
+ def runtime_turn_keys(self) -> set[str]:
+ return {self.runtime_turn_key(rt.run.request) for rt in self._runtimes.values() if rt.run is not None}
+
+ def runtime_turn_keys_for_session_key(self, session_key: str) -> set[str]:
+ return {
+ self.runtime_turn_key(rt.run.request)
+ for rt in self._runtimes.values()
+ if rt.run is not None and rt.run.request.session_key == session_key
+ }
+
+ async def recover_runtime_state(self) -> list[str]:
+ """One settlement pass outside a Turn: T2, T3 admission, then J5; return the unsettled Sessions.
+
+ Candidates come from the rows: Sessions whose context can hold an open call, and
+ Sessions with accepted inputs no run consumed. Each runs the same resume a Turn
+ runs (T2 and T3, no model call). A Session a run holds is skipped: its own resume
+ settles it. J5 pruning follows a pass that settled everything. Never reports
+ success over a failure; ``AvibeRecovery`` owns the retries.
+ """
+ candidates = await asyncio.to_thread(self._recovery_candidates)
+ unsettled: list[str] = []
+ for session_id in candidates:
+ async with self._held(session_id, wait=False) as runtime:
+ if runtime is None:
+ continue
+ try:
+ await self._resume(runtime)
+ except Exception:
+ logger.exception("Avibe Agent could not settle Session %s outside a Turn", session_id)
+ unsettled.append(session_id)
+ if not unsettled:
+ await self._prune_settled_jobs()
+ return unsettled
+
+ def _recovery_candidates(self) -> list[str]:
+ return sorted({*self._sessions_with_open_tail(), *self._sessions_with_unconsumed_inputs()})
+
+ def _schedule_recovery(self) -> None:
+ """Hand what this Turn could not settle to the process's recovery owner."""
+ recovery = getattr(self.controller, "avibe_recovery", None)
+ if recovery is not None:
+ recovery.ensure()
+
+ def _prune_jobs_soon(self) -> None:
+ """J5 while the service runs: runs create jobs, so a run's end prunes, at most hourly, off the Turn."""
+ if self._pruned_at is not None and time.monotonic() - self._pruned_at < _JOB_PRUNE_INTERVAL_S:
+ return
+ if self._prune_task is not None and not self._prune_task.done():
+ return
+ self._prune_task = asyncio.create_task(self._prune_settled_jobs(), name="avibe-agent-job-prune")
+
+ async def _prune_settled_jobs(self) -> None:
+ """J5: remove finished jobs whose call has a durable result and whose Watch settled."""
+ self._pruned_at = time.monotonic()
+ try:
+ suite = self._tools()
+ if suite.prune is not None:
+ removed = await asyncio.to_thread(suite.prune, self._job_call_settled)
+ if removed:
+ logger.info("Avibe Agent pruned %d settled job(s)", len(removed))
+ except Exception:
+ logger.exception("Avibe Agent job pruning failed")
+
+ def _job_call_settled(self, meta: Any) -> bool:
+ """Whether the job's tool call has a durable ``tool_result`` row (the adapter's half of J5).
+
+ Only a result committed after the job was created counts: a provider may reuse
+ a tool-call id, and an earlier call's result does not settle a later one. The
+ same rule as T2's job lookup (``_settle_open_calls``).
+ """
+ from sqlalchemy import func
+
+ session_id, call_id = str(meta.get("session_id") or ""), str(meta.get("tool_call_id") or "")
+ created = instant(meta.get("created_at"))
+ if not session_id or not call_id or created is None:
+ return False
+ with self._engine.connect() as conn:
+ committed = conn.execute(
+ select(agent_events.c.created_at).where(
+ agent_events.c.session_id == session_id,
+ agent_events.c.event_type == "tool_result",
+ agent_events.c.context_seq.is_not(None),
+ func.json_extract(agent_events.c.content_json, "$.message.tool_call_id") == call_id,
+ )
+ ).scalars()
+ return any((moment := instant(value)) is not None and moment >= created for value in committed)
+
+ async def shutdown_runtime(self) -> None:
+ """Disabling the backend ends its runs; the rolling refresh drains Turns before this."""
+ for runtime in list(self._runtimes.values()):
+ if runtime.run is not None:
+ runtime.run.stop_requested = True
+ if runtime.run.agent is not None:
+ runtime.run.agent.abort("backend disabled")
+
+ async def prepare_resume_binding(self, *, base_session_id: str, session_key: str, working_path: str) -> None:
+ """Nothing to prepare: the transcript is the Session's own rows, read at the next run."""
+ return None
+
+ def backend_alive(self, context: Any) -> Optional[bool]:
+ runtime = self._runtimes.get(self._session_id(context) or "")
+ return True if runtime is not None and runtime.run is not None else None
+
+ # --- steering (core.agent_steering) --------------------------------------
+
+ def steering_native_turn_id(self, target: ActiveSteerTarget) -> Optional[str]:
+ run = self._run_for(self._session_id(target.context), target.logical_turn_id)
+ return run.native_turn_id if run is not None else None
+
+ async def steer_active_turn(self, request: SteerRequest, target: ActiveSteerTarget) -> SteerResult:
+ run = self._run_for(request.target_session_id, request.expected_logical_turn_id)
+ if run is None or request.expected_native_turn_id != run.native_turn_id:
+ return steer_result(SteerOutcome.NOT_ACTIVE, reason="not_active")
+ self._steering.add(request.attempt_id)
+ try:
+ return await self._steer(run, request)
+ finally:
+ self._steering.discard(request.attempt_id)
+
+ async def _steer(self, run: _Run, request: SteerRequest) -> SteerResult:
+ try:
+ message_id = await asyncio.to_thread(self._attempt_leader_id, request.attempt_id)
+ if message_id is None:
+ return steer_result(SteerOutcome.REFUSED, reason="attempt_unknown")
+ message = await self._render_input(
+ request.target_session_id, request.text, request.files, request.input_metadata
+ )
+ except Exception:
+ logger.exception("Avibe Agent could not prepare a steer for Session %s", request.target_session_id)
+ return steer_result(SteerOutcome.REFUSED, reason="preparation_failed")
+ if run.agent is not None and await run.agent.steer(AgentInput(message_id, message)):
+ run.accepted_steers.add(request.attempt_id)
+ return steer_result(SteerOutcome.ACCEPTED, turn_id=run.turn_id)
+ return steer_result(SteerOutcome.REFUSED, reason="run_closed")
+
+ def reconciliation_steer_target(self, request: SteerReconcileRequest) -> ActiveSteerTarget:
+ return ActiveSteerTarget(
+ runtime_key="",
+ logical_turn_id=request.expected_logical_turn_id,
+ context=None,
+ agent_request=None,
+ agent=self,
+ )
+
+ async def reconcile_steer_attempt(self, request: SteerReconcileRequest, target: Any) -> SteerResult:
+ """Evidence about a prior steer attempt, as the Codex and OpenCode reconcilers give it.
+
+ ACCEPTED when its row was consumed or the live run accepted it; UNKNOWN only
+ while this instance has the attempt's live call in flight (that call owns the
+ receipt); otherwise NOT_ACTIVE. A live call that starts after a NOT_ACTIVE finds
+ its attempt settled and refuses (``_steer``), and the Turn owner fences any late
+ receipt for an attempt it no longer has, so a second negative changes nothing.
+ """
+ message_id = await asyncio.to_thread(self._attempt_leader_id, request.attempt_id)
+ if message_id is not None and await asyncio.to_thread(self._consumed, message_id):
+ return steer_result(SteerOutcome.ACCEPTED, turn_id=request.expected_logical_turn_id)
+ run = self._run_for(request.target_session_id, request.expected_logical_turn_id)
+ if (
+ run is not None
+ and run.native_turn_id == request.expected_native_turn_id
+ and request.attempt_id in run.accepted_steers
+ ):
+ # The accepted steer is still queued in the live run that owns it.
+ return steer_result(SteerOutcome.ACCEPTED, turn_id=run.turn_id)
+ if request.attempt_id in self._steering:
+ return steer_result(SteerOutcome.UNKNOWN, reason="in_progress")
+ return steer_result(SteerOutcome.NOT_ACTIVE, reason="no_live_call")
+
+ # --- one run ---------------------------------------------------------------
+
+ async def _preflight(self, turn: _Run) -> HubModelRouter:
+ """Resolve the route before the input is written; the run's first model call reuses it.
+
+ A later attempt resolves again (C-6 item 3); a Model Hub refusal there is kept on
+ the Turn, so its failure shows the Hub's copy, as a refusal at preflight does.
+ """
+ from modules.agents.model_hub import bind_launch, launch_refusal_copy, resolve_model_hub_launch
+
+ request, session_id = turn.request, turn.session_id
+
+ model = request.subagent_model or request.vibe_agent_model
+ if not model:
+ raise ValueError("The Avibe Agent has no model selected.")
+ context = request.context
+
+ async def resolve() -> ModelSelection:
+ try:
+ launch = await resolve_model_hub_launch(
+ self.controller, BACKEND, model, process_scope=f"{BACKEND}:{session_id}", context=context
+ )
+ except Exception as error:
+ turn.refusal = launch_refusal_copy(self.controller, error)
+ raise
+ bind_launch(context, launch)
+ return selection_from_hop(launch.to_hop_resolution(), gateway_base_url=launch.gateway_base_url)
+
+ return HubModelRouter(resolve, self._providers, first=await resolve())
+
+ def _start_agent(self, turn: _Run, cwd: str, sections: str, environment: Mapping[str, str]) -> None:
+ """The Turn's loop, over its router, tools, system prompt, and the environment its commands run in."""
+ request, session_id = turn.request, turn.session_id
+ suite = self._tools()
+ agent = Agent(
+ session_id=session_id,
+ models=turn.router,
+ tools=(),
+ hooks=(),
+ store=self.store,
+ jobs=suite.jobs,
+ cwd=cwd,
+ env=environment,
+ reasoning_effort=request.subagent_reasoning_effort or request.vibe_agent_reasoning_effort,
+ )
+ # Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.
+ tools = tuple(suite.create_tools(agent.jobs, self.media.image_sink(session_id)))
+ agent.set_tools(tools)
+ agent.system = system_prompt([tool.spec.name for tool in tools], sections)
+ turn.agent, turn.cwd = agent, cwd
+
+ async def _on_event(self, run: _Run, event: AgentEvent) -> None:
+ if isinstance(event, MessageCommitted):
+ if event.final:
+ # Delivered at the end of the run, which decides how the Turn settles.
+ run.final_row = event.message_id
+ else:
+ await self._emit_narration(run, event.message_id)
+ elif isinstance(event, ToolStarted):
+ await self._emit_tool_started(run, event)
+ elif isinstance(event, AgentError):
+ run.errors.append((event.kind, event.message))
+ elif isinstance(event, RunEnded):
+ run.reason = event.reason
+
+ async def _settle(self, run: _Run) -> None:
+ """Settle the Turn from the run's outcome (loop-control.md section 6).
+
+ A committed final row is the Turn's outcome and result text, and it always
+ settles through the result path, which writes that row's display and type as
+ for the other backends; there is no separate failure notice for it. The row's
+ own outcome is ``final_outcome`` (the rule its type was committed by); the live
+ run adds only the failures it alone can observe after the commit. A Stop that
+ arrives after the final row committed loses the race, as it does for the Codex
+ backend.
+ """
+ run.settled = True
+ request, context = run.request, run.request.context
+ reason = run.reason or "error"
+ kind, diagnostic = run.errors[0] if run.errors else (None, reason)
+ final = run.responses.get(run.final_row) if run.final_row else None
+ if final is not None:
+ if run.stop_requested and reason == "aborted":
+ reason = "completed"
+ run_failed_after_commit = reason not in _COMPLETED
+ failed = final_outcome(final) == "failed" or run_failed_after_commit
+ body = self._display_source(final, final=True)
+ if failed and not body.strip():
+ # A silent final whose run failed after the commit: like a final without text
+ # of its own (``_display_source``), its row carries the explanation.
+ body = error_text(kind or "empty_response", self._language(), reason=reason)
+ if failed:
+ await self.record_model_hub_native_failure(context, diagnostic or (kind or "failed final"))
+ if body.strip():
+ # The same result path as the other backends; the row is already the message.
+ await self.emit_result_message(
+ context,
+ body,
+ subtype="error" if failed else "success",
+ started_at=request.started_at,
+ request=request,
+ output=replace(terminal_output_for(request), persisted_row_id=run.final_row),
+ )
+ else:
+ # A reply the model chose to keep silent.
+ await self.controller.emit_agent_message(
+ context, "result", "", level="silent", output=terminal_output_for(request)
+ )
+ return
+ if run.stop_requested and reason == "aborted":
+ # The stop receipt IM shows, as for the other backends.
+ await self._remove_ack_reaction(request, terminal_emoji=STOPPED_REACTION_EMOJI)
+ await self.controller.emit_agent_message(
+ context, "result", "", level="silent", output=stop_output_for(request)
+ )
+ return
+ if reason in _COMPLETED and kind is None:
+ # The run ended without a final reply by design (a terminating tool, a hook end).
+ await self.controller.emit_agent_message(
+ context, "result", "", level="silent", output=terminal_output_for(request)
+ )
+ return
+ await self._fail(request, kind, diagnostic, reason=reason, refusal=run.refusal)
+
+ async def _continuing_input(self, run: _Run) -> Optional[AgentInput]:
+ """The input that continues a Turn whose run ended by design with inputs it accepted.
+
+ An accepted steer belongs to the Turn that accepted it. A run that a terminating
+ tool or a hook ``end`` closed before draining its queue therefore runs again for
+ them: the earlier ones enter the context, the last starts the next run. A
+ stopped or failed run continues nothing (``_admit_returned_inputs``).
+ """
+ if run.stop_requested or run.reason not in _COMPLETED:
+ return None
+ pending = await run.agent.take_pending_inputs()
+ if not pending:
+ return None
+ for item in pending[:-1]:
+ await self.store.consume_input(run.session_id, item.message_id, item.message)
+ run.reason = None
+ return pending[-1]
+
+ async def _admit_returned_inputs(self, run: _Run) -> None:
+ """Inputs a stopped or failed run accepted but did not consume enter the context (T3).
+
+ They belong to the Turn that accepted them and share its outcome, as a message
+ merged into another backend's stopped or failed turn does; the next Turn
+ answers them with the full context.
+ """
+ if run.agent is None:
+ return
+ try:
+ for item in await run.agent.take_pending_inputs():
+ await self.store.consume_input(run.session_id, item.message_id, item.message)
+ except Exception:
+ # The rows stay accepted and unconsumed: the recovery owner admits them (T3)
+ # without waiting for the Session's next message.
+ logger.exception("Avibe Agent could not admit returned inputs for Session %s", run.session_id)
+ self._schedule_recovery()
+
+ # --- resume (recovery.md T2, T3) -------------------------------------------
+
+ async def _resume(self, runtime: _SessionRuntime) -> None:
+ session_id = runtime.session_id
+ # T2 before every run: idempotent, and a Turn that waited behind an aborted one
+ # finds the call that abort left open on the same, still-held runtime.
+ await self._settle_open_calls(runtime)
+ if not runtime.cwd:
+ runtime.cwd = await asyncio.to_thread(self._session_workdir, session_id)
+ for message_id, text_value, files, delivery in await asyncio.to_thread(self._unconsumed_inputs, session_id):
+ message = await self._render_input(session_id, text_value, files, await self._input_metadata(delivery))
+ await self.store.consume_input(session_id, message_id, message)
+
+ async def _input_metadata(self, delivery: dict[str, Any]) -> Optional[AgentInputMetadata]:
+ """A recovered input's sender facts, from the owner the live steer path uses (T3).
+
+ ``SessionTurnManager`` rebuilds the Delivery's context, including a scheduled
+ or agent-authored input's provenance, and asks the message handler, so the
+ input renders after a restart exactly as it would have live.
+ """
+ owner = getattr(getattr(self.controller, "session_turns", None), "_steer_input_metadata", None)
+ if not callable(owner):
+ return None
+ try:
+ return await owner([delivery])
+ except Exception:
+ # The input is admitted regardless (T3 never drops one): a recovered input whose
+ # sender facts cannot be rebuilt must not stop every later Turn of the Session.
+ logger.exception("Avibe Agent could not rebuild sender facts for input %s", delivery.get("id"))
+ return None
+
+ async def _settle_open_calls(self, runtime: _SessionRuntime) -> None:
+ """T2: one committed result for every open tool call, chosen from its job's state."""
+ session_id = runtime.session_id
+ open_calls = open_tool_calls(await self.store.load(session_id))
+ if not open_calls:
+ return
+ suite = self._tools()
+
+ def evidence() -> tuple[list[ContextEntry], dict[tuple[str, str], str]]:
+ # A call is its instance, the owning response plus its id (providers reuse ids).
+ # A call this Session inherited open takes the result its owner committed, matched
+ # in context order. Only a job file falls back to the clock: its job started after
+ # the owning response committed (one rule with J5).
+ committed = self._committed_at([owner.row_id for owner, _ in open_calls])
+ inherited, found = [], {}
+ with self._engine.connect() as conn:
+ for owner, call in open_calls:
+ if owner.session_id != session_id:
+ result = source_tool_result(conn, owner.session_id, owner.context_seq, call.id)
+ if result is not None:
+ inherited.append(result)
+ continue
+ since = committed.get(owner.row_id)
+ job_id = suite.find_job(owner.session_id, call.id, created_since=since)
+ if job_id is not None:
+ found[(owner.session_id, call.id)] = job_id
+ return inherited, found
+
+ # Each job lookup lists the jobs directory: one pass, off the event loop.
+ inherited, job_ids = await asyncio.to_thread(evidence)
+ # A tool result is the Agent's that made the call: its owning response's author, not
+ # the Turn writing it now (or none, at startup) or the Session's current selection.
+ # Only the last response can hold open calls, so they share one owner.
+ owner_agent = await asyncio.to_thread(self._author_of, open_calls[0][0].row_id)
+ with self.store.writing_as(session_id, owner_agent):
+ for result in inherited:
+ await self.store.append_tool_result(
+ session_id, result.message, details=dict(result.payload.get("details") or {})
+ )
+ await settle_open_calls(
+ session_id=session_id,
+ store=self.store,
+ jobs=suite.jobs,
+ job_ids=job_ids,
+ render_result=suite.render_recovered,
+ )
+
+ def _author_of(self, row_id: str) -> Optional[str]:
+ with self._engine.connect() as conn:
+ return conn.execute(select(messages.c.author_name).where(messages.c.id == row_id)).scalar()
+
+ def _job_route(self, meta: Mapping[str, Any]) -> dict[str, Any]:
+ """A job Watch's Agent and authorization, from the job's owning Turn (fail closed).
+
+ The same rule for every hand-over, in a Turn or at startup: the owning response
+ is the latest one carrying the job's call, committed at or before the job's
+ creation; its Turn is the one whose input the response answers, and that Turn's
+ initial input row carries the principal and its persisted resource snapshot.
+ A remote Turn without a usable snapshot, or a job whose Turn cannot be found, is
+ handed over as unverifiable: owned, but never followed up.
+ """
+ from core.caller_context import caller_context_from_platform_payload
+ from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ ResourceAccessError,
+ resource_user_context_from_metadata,
+ )
+
+ session_id, call_id = str(meta.get("session_id") or ""), str(meta.get("tool_call_id") or "")
+ created = instant(meta.get("created_at"))
+ with self._engine.connect() as conn:
+ owner = self._owning_response(conn, session_id, call_id, created)
+ origin = self._turn_initial_input(conn, session_id, owner["context_seq"]) if owner else None
+ if owner is None or origin is None:
+ return {"unverifiable_remote": True}
+ route: dict[str, Any] = {"agent_name": owner["author_name"]} if owner["author_name"] else {}
+ metadata = _json_object(origin["metadata_json"])
+ caller = caller_context_from_platform_payload(
+ {"agent_session_id": session_id, "platform": origin["platform"], "message_metadata": metadata},
+ message=SimpleNamespace(
+ platform=origin["platform"], user_id=origin["author_id"] or "", channel_id=None,
+ message_id=None, thread_id=None,
+ ),
+ )
+ if caller is None or not caller.is_remote:
+ return route
+ try:
+ context = (
+ resource_user_context_from_metadata({RESOURCE_USER_CONTEXT_METADATA_KEY: caller.resource_user_context})
+ if caller.resource_user_context
+ else None
+ )
+ except ResourceAccessError:
+ context = None
+ if context is None:
+ return {**route, "unverifiable_remote": True}
+ return {**route, "user_context": context}
+
+ @staticmethod
+ def _owning_response(conn: Any, session_id: str, call_id: str, created: Optional[datetime]) -> Optional[dict]:
+ from sqlalchemy import text as sql_text
+
+ rows = conn.execute(
+ sql_text(
+ "SELECT m.context_seq, m.author_name, m.created_at FROM messages AS m, "
+ "json_each(json_extract(m.content_json, '$.model.message.content')) AS block "
+ "WHERE m.session_id = :session_id AND m.context_seq IS NOT NULL "
+ "AND json_extract(block.value, '$.type') = 'tool_call' AND json_extract(block.value, '$.id') = :call_id "
+ "ORDER BY m.context_seq DESC"
+ ),
+ {"session_id": session_id, "call_id": call_id},
+ ).mappings()
+ for row in rows:
+ committed = instant(row["created_at"])
+ if created is None or committed is None or committed <= created:
+ return dict(row)
+ return None
+
+ @staticmethod
+ def _turn_initial_input(conn: Any, session_id: str, before_seq: int) -> Optional[dict]:
+ """The initial input row of the Turn whose input precedes ``before_seq``."""
+ latest = conn.execute(
+ select(messages.c.id)
+ .where(
+ messages.c.session_id == session_id,
+ messages.c.context_seq.is_not(None),
+ messages.c.context_seq < before_seq,
+ messages.c.type.in_(INPUT_TYPES),
+ )
+ .order_by(messages.c.context_seq.desc())
+ .limit(1)
+ ).scalar()
+ if latest is None:
+ return None
+ # The Turn that wrote it, in any state: the hand-over may come after that Turn settled
+ # (T2 at a later resume, or a retried recovery pass after T4).
+ turn_id = conn.execute(
+ select(message_deliveries.c.turn_id)
+ .where(message_deliveries.c.message_id == latest, message_deliveries.c.turn_id.is_not(None))
+ .limit(1)
+ ).scalar()
+ initial_id = latest
+ if turn_id is not None:
+ initial_id = conn.execute(
+ select(message_deliveries.c.message_id)
+ .select_from(
+ session_turns.join(message_deliveries, message_deliveries.c.id == session_turns.c.initial_delivery_id)
+ )
+ .where(session_turns.c.id == turn_id)
+ ).scalar() or latest
+ row = conn.execute(
+ select(messages.c.platform, messages.c.author_id, messages.c.metadata_json).where(messages.c.id == initial_id)
+ ).mappings().first()
+ return dict(row) if row is not None else None
+
+ def _committed_at(self, row_ids: Sequence[str]) -> dict[str, datetime]:
+ with self._engine.connect() as conn:
+ rows = conn.execute(select(messages.c.id, messages.c.created_at).where(messages.c.id.in_(set(row_ids))))
+ return {row_id: moment for row_id, created in rows if (moment := instant(created)) is not None}
+
+ def _unconsumed_inputs(self, session_id: str) -> list[tuple[str, str, list[FileAttachment], dict[str, Any]]]:
+ """Inputs accepted into an ``avibe`` Turn but never consumed, in acceptance order.
+
+ Only Turns this backend ran count, so history from an earlier backend of the
+ same Session never enters the context.
+ """
+ from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
+
+ with self._engine.connect() as conn:
+ rows = conn.execute(
+ select(
+ messages.c.id,
+ messages.c.content_text,
+ messages.c.content_json,
+ message_deliveries.c.id.label("delivery_id"),
+ message_deliveries.c.turn_role,
+ session_turns.c.dispatch_text.label("turn_dispatch_text"),
+ )
+ .select_from(
+ messages.join(message_deliveries, message_deliveries.c.message_id == messages.c.id).join(
+ session_turns, session_turns.c.id == message_deliveries.c.turn_id
+ )
+ )
+ .where(
+ and_(
+ messages.c.session_id == session_id,
+ messages.c.context_seq.is_(None),
+ messages.c.type.in_(INPUT_TYPES),
+ message_deliveries.c.state == "accepted",
+ session_turns.c.backend == BACKEND,
+ )
+ )
+ .order_by(message_deliveries.c.materialized_at, message_deliveries.c.turn_position, messages.c.id)
+ ).mappings().all()
+ inputs = []
+ seen: set[str] = set()
+ for row in rows:
+ if row["id"] in seen:
+ continue
+ seen.add(row["id"])
+ content = _json_object(row["content_json"])
+ specs = resolve_attachment_specs(
+ conn, session_id=session_id, attachments=list(content.get("attachments") or [])
+ )
+ delivery = delivery_store.get_delivery(conn, row["delivery_id"])
+ # A Turn's initial input is sent as the Turn's dispatch text, which the Turn owner
+ # derived from its Delivery batch (attachment notes, merged scheduled inputs) and
+ # keeps after acceptance; the row's display text omits that.
+ text_value = (
+ row["turn_dispatch_text"]
+ if row["turn_role"] == "initial" and row["turn_dispatch_text"]
+ else row["content_text"] or ""
+ )
+ inputs.append((row["id"], text_value, list(file_attachments_from_specs(specs) or ()), delivery))
+ return inputs
+
+ # --- rendering ---------------------------------------------------------------
+
+ async def _render_input(
+ self,
+ session_id: str,
+ message: str,
+ files: Optional[Sequence[FileAttachment]],
+ metadata: Optional[AgentInputMetadata],
+ ) -> UserMessage:
+ """The input as the model sees it: identity and time prefix, attachments, images.
+
+ Images become context images through immutable snapshots; other files are
+ listed by path, as the native backends list them. The environment block is
+ added when the loop consumes the input (``AdapterTranscriptStore``).
+ """
+ images = []
+ listed = []
+ for attachment in files or ():
+ if not attachment.local_path:
+ continue
+ mime = (attachment.mimetype or "").split(";", 1)[0].strip().lower()
+ if mime in IMAGE_MIME_TYPES:
+ try:
+ images.append(
+ await self.media.snapshot_file(
+ attachment.local_path, mime, session_id=session_id, name=attachment.name or None
+ )
+ )
+ continue
+ except OSError:
+ # Unreadable now: listed by path, as the native backends pass every attachment.
+ logger.warning("Avibe Agent lists an image it could not snapshot: %s", attachment.local_path)
+ size = f", {attachment.size} bytes" if attachment.size else ""
+ listed.append(f"- File: {attachment.local_path} ({attachment.mimetype}{size})")
+ body = message or ""
+ if listed:
+ body = "\n".join([body, "", "[User Attachments]", *listed]) if body.strip() else "\n".join(
+ ["[User Attachments]", *listed]
+ )
+ rendered = self.render_input(body, metadata)
+ content = ([text_block(rendered)] if rendered or not images else []) + images
+ return UserMessage(content=tuple(content))
+
+ def _display_source(self, message: AssistantMessage, *, final: bool) -> str:
+ """The text a surface renders a response from: its text blocks without silent blocks.
+
+ Also the row's commit-time display (the store's renderer). A final without
+ text of its own (``final_outcome`` failed) is explained by localized copy:
+ the refusal or safety explanation, else the empty-reply one, so the row
+ never shows nothing for a failed Turn (loop-control.md section 2).
+ """
+ value = render_text(message)
+ if final and not value.strip():
+ kind = message.stop_reason if message.stop_reason in _EXPLAINED_STOPS else "empty_response"
+ return error_text(kind, self._language())
+ return strip_silent_blocks(value)
+
+ async def _avibe_sections(self, request: AgentRequest, cwd: str) -> tuple[str, Optional[dict]]:
+ """Avibe's injected prompt sections and the skill catalog they offered.
+
+ Built off the event loop as the other backends build them: skill resolution
+ scans the filesystem and may run ``claude plugin list``.
+ """
+ from core.managed_skills import managed_skill_claude_cli_path, managed_skill_project_base
+ from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
+
+ context = request.context
+ skill_catalog_sink: list[dict] = []
+
+ def build() -> str:
+ # Every lookup runs here, off the loop: the enabled-Agent list reads SQLite.
+ return build_system_prompt_injection(
+ agent_instructions=request.vibe_agent_system_prompt or "",
+ backend=BACKEND,
+ include_quick_replies=getattr(self.config, "reply_enhancements", True)
+ and context.platform != "wechat",
+ context=context,
+ fallback_platform=context.platform,
+ enabled_agents=get_enabled_agents_for_prompt(self.controller),
+ skills_cwd=cwd or None,
+ skills_project_base=managed_skill_project_base(context),
+ skills_claude_cli_path=managed_skill_claude_cli_path(self.config),
+ skill_catalog_sink=skill_catalog_sink,
+ )
+
+ sections = await asyncio.to_thread(build)
+ return sections, (skill_catalog_sink[0] if skill_catalog_sink else None)
+
+ def _turn_environment(self, request: AgentRequest, cwd: str) -> dict[str, str]:
+ """The environment a Turn's commands run in, from the owners the other backends' shells use.
+
+ The service's environment without its own caller provenance, then this Turn's
+ caller context (``AVIBE_SESSION_ID``, ``AVIBE_CALLER_*``, so a ``vibe`` call in a
+ command records where it came from), the managed-skill bindings, and verified
+ Git on ``PATH``, composed as the Codex backend composes its shell environment.
+ The Model Hub gateway token stays in the adapter.
+ """
+ from core.caller_context import caller_env_for_platform_payload, environment_without_caller_context
+ from core.git_runtime import prepend_vendored_git_to_path
+ from core.managed_skills import (
+ managed_skill_claude_cli_path,
+ managed_skill_environment,
+ managed_skill_project_base,
+ )
+
+ context = request.context
+ environment = environment_without_caller_context()
+ environment.update(
+ caller_env_for_platform_payload(
+ getattr(context, "platform_specific", None),
+ message=context,
+ fallback_platform=getattr(self.config, "platform", None),
+ )
+ )
+ environment.update(
+ managed_skill_environment(
+ cwd or None,
+ project_base=managed_skill_project_base(context),
+ claude_cli_path=managed_skill_claude_cli_path(self.config),
+ )
+ )
+ prepend_vendored_git_to_path(environment, base_env=environment, working_dir=cwd or None)
+ return environment
+
+ def _environment(self, session_id: str) -> dict[str, str]:
+ runtime = self._runtimes.get(session_id)
+ cwd = ((runtime.run.cwd if runtime.run is not None else "") or runtime.cwd) if runtime is not None else ""
+ return current_environment(
+ cwd, self._watch_lines(session_id), include_time=getattr(self.config, "include_time_info", True)
+ )
+
+ def _watch_lines(self, session_id: str) -> list[str]:
+ service = getattr(self.controller, "watch_service", None)
+ store = getattr(service, "store", None)
+ list_watches = getattr(store, "list_watches", None)
+ if not callable(list_watches):
+ return []
+ try:
+ watches = list_watches()
+ except Exception:
+ logger.debug("Avibe Agent could not list Watches", exc_info=True)
+ return []
+ lines = []
+ for watch in watches:
+ if getattr(watch, "session_id", None) != session_id or not getattr(watch, "enabled", False):
+ continue
+ # Model context: a Watch's id, name and kind only. Its command can carry a
+ # credential, and the block is persisted and sent to the provider.
+ kind = "job" if getattr(watch, "job_target", None) else "command"
+ name = " ".join(str(getattr(watch, "name", None) or "").split())
+ lines.append(f'{watch.id} "{name}" {kind} running' if name else f"{watch.id} {kind} running")
+ return lines
+
+ # --- output helpers ------------------------------------------------------
+
+ async def _emit_narration(self, run: _Run, row_id: str) -> None:
+ """A non-final response through the same process path as the other backends' narration."""
+ message = run.responses.get(row_id)
+ body = self._display_source(message, final=False) if message is not None else ""
+ if not body.strip():
+ return
+ try:
+ await self.controller.emit_agent_message(
+ run.request.context,
+ "assistant",
+ body,
+ output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id=row_id),
+ )
+ except Exception:
+ logger.exception("Avibe Agent could not show narration %s", row_id)
+
+ async def _emit_tool_started(self, run: _Run, event: ToolStarted) -> None:
+ call = run.tool_calls.get(event.tool_call_id)
+ arguments = dict(call.arguments) if call is not None else {}
+ formatter = self._get_formatter(run.request.context)
+ relative = _relative_to(run.cwd)
+ try:
+ await self.controller.emit_agent_message(
+ run.request.context,
+ "toolcall",
+ formatter.format_toolcall(event.name, arguments, get_relative_path=relative),
+ status_label=formatter.format_toolcall_label(event.name, arguments, get_relative_path=relative),
+ )
+ except Exception:
+ logger.exception("Avibe Agent could not show tool %s", event.name)
+
+ def _on_response(self, session_id: str, row_id: str, message: AssistantMessage) -> None:
+ """A response committed for the Session's run: keep what its delivery and tool events need."""
+ run = self._run_for(session_id, None)
+ if run is None:
+ return
+ run.responses[row_id] = message
+ run.tool_calls.update({call.id: call for call in message.tool_calls})
+ self._note_tokens(run, message)
+
+ def _note_tokens(self, run: _Run, message: AssistantMessage) -> None:
+ usage = message.usage
+ note = getattr(self.controller, "note_session_tokens", None)
+ if usage is None or not callable(note):
+ return
+ total = usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens
+ try:
+ note(run.request.context, total=total)
+ except Exception:
+ logger.debug("Avibe Agent token note failed", exc_info=True)
+
+ async def _fail(
+ self,
+ request: AgentRequest,
+ kind: Optional[str],
+ diagnostic: str,
+ *,
+ reason: Optional[str] = None,
+ cause: Optional[BaseException] = None,
+ refusal: Optional[str] = None,
+ ) -> None:
+ """A failed Turn's notice; a Model Hub ``refusal`` copy takes precedence, as at preflight."""
+ # A failure after Model Hub served the route replaces that served attempt, as for the other backends.
+ await self.record_model_hub_native_failure(request.context, diagnostic or (kind or "error"))
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ BACKEND,
+ diagnostic or (kind or "error"),
+ display_text=f"❌ {refusal or error_text(kind, self._language(), reason=reason)}",
+ request=request,
+ cause=cause,
+ )
+
+ async def _fail_preflight(self, request: AgentRequest, error: BaseException) -> None:
+ from modules.agents.model_hub import launch_refusal_copy
+
+ logger.warning("Avibe Agent could not resolve its model route: %s", error)
+ refusal = launch_refusal_copy(self.controller, error)
+ # Recorded on every start failure, as the other backends do: a no-op unless a launch is bound.
+ await self.record_model_hub_native_failure(request.context, str(error))
+ display = f"❌ {refusal}" if refusal is not None else f"❌ {error_text('generic', self._language())}"
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ BACKEND,
+ str(error),
+ display_text=display,
+ request=request,
+ cause=error,
+ )
+
+ # --- lookups ---------------------------------------------------------------
+
+ def _tools(self) -> ToolSuite:
+ if self._tool_suite is None:
+ # Jobs live in Watch's agent_jobs_dir(), where vibe stop and the job-Watch sweep look;
+ # a job's Watch takes its Agent and authorization from the job's owning Turn.
+ self._tool_suite = local_tool_suite(route=self._job_route)
+ return self._tool_suite
+
+ @asynccontextmanager
+ async def _held(
+ self, session_id: str, *, wait: bool = True, run: Optional[_Run] = None
+ ) -> AsyncIterator[Optional[_SessionRuntime]]:
+ """Hold the Session's writer lock; the last holder retires its in-memory state.
+
+ With ``wait=False`` a Session someone already holds yields ``None`` instead of
+ waiting: startup recovery never blocks behind a run, which does the same work
+ at its own resume. A Turn's ``run`` is published before the lock is awaited,
+ so a Stop is honored even while the Turn waits for it.
+ """
+ runtime = self._runtimes.get(session_id)
+ if runtime is None:
+ runtime = self._runtimes[session_id] = _SessionRuntime(session_id)
+ if not wait and runtime.lock.locked():
+ yield None
+ return
+ runtime.holders += 1
+ if run is not None:
+ runtime.run = run
+ try:
+ async with runtime.lock:
+ yield runtime
+ finally:
+ if run is not None and runtime.run is run:
+ runtime.run = None
+ runtime.holders -= 1
+ if runtime.holders == 0 and runtime.run is None and self._runtimes.get(session_id) is runtime:
+ del self._runtimes[session_id]
+ self.store.forget(session_id)
+
+ def _run_for(self, session_id: Optional[str], turn_id: Optional[str]) -> Optional[_Run]:
+ runtime = self._runtimes.get(session_id or "")
+ run = runtime.run if runtime is not None else None
+ if run is None or (turn_id is not None and run.turn_id != turn_id):
+ return None
+ return run
+
+ @staticmethod
+ def _session_id(context: Any) -> Optional[str]:
+ return BaseAgent._reserved_agent_session_id(context) or BaseAgent._session_id_from_context(context)
+
+ def _language(self) -> str:
+ return str(getattr(self.config, "language", "en") or "en")
+
+ def _attempt_leader_id(self, attempt_id: str) -> Optional[str]:
+ """The ``messages.id`` a steer attempt materializes as: its first Delivery."""
+ if not attempt_id:
+ return None
+ with self._engine.connect() as conn:
+ rows = delivery_store.attempt_deliveries(conn, attempt_id)
+ return str(rows[0]["id"]) if rows else None
+
+ def _consumed(self, message_id: str) -> bool:
+ with self._engine.connect() as conn:
+ seq = conn.execute(select(messages.c.context_seq).where(messages.c.id == message_id)).scalar()
+ return seq is not None
+
+ def _sessions_with_open_tail(self) -> list[str]:
+ """Sessions whose context can hold an open tool call: startup T2's candidates.
+
+ Every run settles earlier open calls before its next model call, so only a
+ Session's last response can have one: it has tool calls and fewer results after
+ it. Candidates come from Avibe context rows (only this backend writes
+ ``context_seq``), whatever Agent the Session is routed to now: a Session switched
+ away mid-run still owns its jobs.
+ """
+ from sqlalchemy import func
+
+ with self._engine.connect() as conn:
+ last_response = (
+ select(messages.c.session_id, func.max(messages.c.context_seq).label("seq"))
+ .where(
+ messages.c.session_id.is_not(None),
+ messages.c.context_seq.is_not(None),
+ messages.c.type.in_(RESPONSE_TYPES),
+ )
+ .group_by(messages.c.session_id)
+ .subquery()
+ )
+ responses = conn.execute(
+ select(messages.c.session_id, messages.c.context_seq, messages.c.content_json).join(
+ last_response,
+ and_(
+ messages.c.session_id == last_response.c.session_id,
+ messages.c.context_seq == last_response.c.seq,
+ ),
+ )
+ ).all()
+ candidates = []
+ for session_id, seq, raw in responses:
+ message = (_json_object(raw).get("model") or {}).get("message") or {}
+ calls = [block for block in message.get("content") or () if isinstance(block, dict)
+ and block.get("type") == "tool_call"]
+ if not calls:
+ continue
+ settled = conn.execute(
+ select(func.count()).select_from(agent_events).where(
+ agent_events.c.session_id == session_id,
+ agent_events.c.event_type == "tool_result",
+ agent_events.c.context_seq > seq,
+ )
+ ).scalar()
+ if settled < len(calls):
+ candidates.append(session_id)
+ return sorted(candidates)
+
+ def _sessions_with_unconsumed_inputs(self) -> list[str]:
+ """Sessions with inputs accepted into an ``avibe`` Turn that no run consumed (T3)."""
+ with self._engine.connect() as conn:
+ return sorted(
+ conn.execute(
+ select(messages.c.session_id)
+ .select_from(
+ messages.join(message_deliveries, message_deliveries.c.message_id == messages.c.id).join(
+ session_turns, session_turns.c.id == message_deliveries.c.turn_id
+ )
+ )
+ .where(
+ messages.c.session_id.is_not(None),
+ messages.c.context_seq.is_(None),
+ messages.c.type.in_(INPUT_TYPES),
+ message_deliveries.c.state == "accepted",
+ session_turns.c.backend == BACKEND,
+ )
+ .distinct()
+ ).scalars()
+ )
+
+ def _session_workdir(self, session_id: str) -> str:
+ with self._engine.connect() as conn:
+ workdir = conn.execute(
+ select(agent_sessions.c.workdir).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ return str(workdir or "")
+
+
+def _json_object(raw: Any) -> dict[str, Any]:
+ import json
+
+ try:
+ value = json.loads(raw or "{}")
+ except (TypeError, ValueError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
diff --git a/modules/agents/avibe/errors.py b/modules/agents/avibe/errors.py
new file mode 100644
index 000000000..3b6f81c19
--- /dev/null
+++ b/modules/agents/avibe/errors.py
@@ -0,0 +1,49 @@
+"""User-facing copy for Avibe Agent failures.
+
+``AgentError.kind`` is the engine's stable discriminator (loop-control.md section 6);
+``AgentError.message`` is diagnostic detail and is never shown as display copy.
+Every kind maps to one ``vibe/i18n`` key under ``avibeAgent.error``.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from vibe.i18n import t as i18n_t
+
+# Engine and provider kinds (C-2 error classification, C-3 run outcomes) with their own copy.
+_KIND_KEYS: dict[str, str] = {
+ "refusal": "refusal",
+ "safety": "safety",
+ "empty_response": "emptyResponse",
+ "dependency_cancelled": "interrupted",
+ "aborted": "interrupted",
+ "overflow": "contextExhausted",
+ "context_exhausted": "contextExhausted",
+ "rate_limit": "rateLimit",
+ "overloaded": "overloaded",
+ "network": "network",
+ "server": "server",
+ "auth": "auth",
+ "invalid_request": "invalidRequest",
+ "error": "modelError",
+ # The loop refuses a route that declares no tool support before any request.
+ "UnsupportedModelRoute": "toolsUnsupported",
+ # A provider answer the canonical transcript cannot hold.
+ "ProviderProtocolViolation": "providerProtocol",
+}
+# Run reasons that carry their own copy when no error event names a kind.
+_REASON_KEYS: dict[str, str] = {
+ "context_exhausted": "contextExhausted",
+ "aborted": "interrupted",
+}
+
+
+def error_key(kind: Optional[str], *, reason: Optional[str] = None) -> str:
+ """The i18n key for an error kind, falling back to the run reason, then to generic copy."""
+ name = _KIND_KEYS.get(kind or "") or _REASON_KEYS.get(reason or "") or "generic"
+ return f"avibeAgent.error.{name}"
+
+
+def error_text(kind: Optional[str], lang: str, *, reason: Optional[str] = None) -> str:
+ return i18n_t(error_key(kind, reason=reason), lang)
diff --git a/modules/agents/avibe/media.py b/modules/agents/avibe/media.py
new file mode 100644
index 000000000..b8eaa946b
--- /dev/null
+++ b/modules/agents/avibe/media.py
@@ -0,0 +1,106 @@
+"""Images in the Avibe Agent's context: immutable snapshots over ``media_objects``.
+
+An ``ImageBlock`` names a ``media_objects`` token whose bytes never change for a
+committed block (C-1, C-2 ``MediaLoader``). Every image the agent puts into its
+context - an input attachment or a file ``read`` attaches - is first copied to a
+content-addressed file ``<state>/agent_core/media/<sha256>.<ext>`` and registered
+there, so a later edit or deletion of the original file cannot change what a
+transcript replays. Loading re-checks the digest.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import os
+import secrets
+from pathlib import Path
+from typing import Optional
+
+from sqlalchemy import select
+from sqlalchemy.engine import Engine
+
+from core.agent_core.messages import IMAGE_MIME_TYPES, ImageBlock
+from storage import media_service
+from storage.models import agent_sessions
+
+MEDIA_SOURCE = "agent_context"
+_EXTENSIONS = {"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp"}
+
+
+class MediaUnavailable(RuntimeError):
+ """A context image's snapshot is missing, revoked, or no longer matches its digest."""
+
+
+class MediaSnapshots:
+ """``MediaLoader`` for the provider adapters plus the snapshot writer."""
+
+ def __init__(self, engine: Engine, root: Path) -> None:
+ self._engine = engine
+ self._root = Path(root)
+
+ # --- MediaLoader ---------------------------------------------------------
+
+ async def load(self, media_token: str) -> tuple[bytes, str]:
+ return await asyncio.to_thread(self._load, media_token)
+
+ def _load(self, media_token: str) -> tuple[bytes, str]:
+ with self._engine.connect() as conn:
+ row = media_service.get_by_token(conn, media_token)
+ if row is None or row.get("revoked_at"):
+ raise MediaUnavailable(f"media {media_token} is not available")
+ path = Path(row["local_path"])
+ try:
+ data = path.read_bytes()
+ except OSError as exc:
+ raise MediaUnavailable(f"media {media_token} cannot be read") from exc
+ if path.parent == self._root and path.stem != hashlib.sha256(data).hexdigest():
+ raise MediaUnavailable(f"media {media_token} no longer matches its snapshot")
+ return data, str(row.get("content_type") or "")
+
+ # --- snapshots -----------------------------------------------------------
+
+ async def snapshot(self, data: bytes, mime_type: str, *, session_id: str, name: Optional[str] = None) -> str:
+ """Store ``data`` immutably and return its token for ``session_id``."""
+ return await asyncio.to_thread(self._snapshot, data, mime_type, session_id, name)
+
+ async def snapshot_file(
+ self, path: str, mime_type: str, *, session_id: str, name: Optional[str] = None
+ ) -> ImageBlock:
+ data = await asyncio.to_thread(Path(path).read_bytes)
+ token = await self.snapshot(data, mime_type, session_id=session_id, name=name or Path(path).name)
+ return ImageBlock(mime_type=mime_type, media_token=token, name=name or Path(path).name)
+
+ def image_sink(self, session_id: str):
+ """The ``read`` tool's sink: ``(bytes, mime_type, name) -> media token``."""
+
+ async def sink(data: bytes, mime_type: str, name: str) -> str:
+ return await self.snapshot(data, mime_type, session_id=session_id, name=name)
+
+ return sink
+
+ def _snapshot(self, data: bytes, mime_type: str, session_id: str, name: Optional[str]) -> str:
+ if mime_type not in IMAGE_MIME_TYPES:
+ raise ValueError(f"unsupported image type: {mime_type}")
+ digest = hashlib.sha256(data).hexdigest()
+ path = self._root / f"{digest}.{_EXTENSIONS[mime_type]}"
+ if not path.is_file():
+ self._root.mkdir(parents=True, exist_ok=True)
+ tmp = self._root / f".{digest}.{secrets.token_hex(4)}.tmp"
+ tmp.write_bytes(data)
+ os.chmod(tmp, 0o444)
+ os.replace(tmp, path)
+ with self._engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ return media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind="image",
+ source=MEDIA_SOURCE,
+ local_path=str(path),
+ file_name=name or path.name,
+ content_type=mime_type,
+ )
diff --git a/modules/agents/avibe/models.py b/modules/agents/avibe/models.py
new file mode 100644
index 000000000..3c3a100be
--- /dev/null
+++ b/modules/agents/avibe/models.py
@@ -0,0 +1,155 @@
+"""Model routing for the Avibe Agent over Model Hub hop resolution (C-2, C-6).
+
+Model Hub answers "how should the ``avibe`` backend call model M now" with a
+``HopResolution`` (``ModelHubRuntimeRouter.resolve_hop``). ``selection_from_hop``
+turns it into the loop's ``ModelEndpoint`` and ``ModelCapabilities`` and keeps
+unknown capabilities ``None``; the loop applies the conservative defaults.
+Transport is the provider adapter registered for the endpoint's protocol.
+
+A ``google`` hop is called over Chat Completions at the same gateway: Model Hub
+serves every source on its OpenAI-compatible ``/v1`` surface and converts, so
+the agent needs no Gemini transport. The served origin still comes from
+``x-avibe-served-hop``.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Awaitable, Callable, Mapping, Optional
+
+from core.agent_core.agent.models import ModelSelection
+from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ProviderAdapter
+from core.agent_core.messages import PROTOCOLS, ProtocolName
+
+logger = logging.getLogger(__name__)
+
+SelectionResolver = Callable[[], Awaitable[ModelSelection]]
+ProviderFactory = Callable[[ProtocolName], ProviderAdapter]
+
+
+class HopResolutionError(ValueError):
+ """Model Hub returned a hop the agent cannot call."""
+
+
+def _optional(value: Any, kind: type, what: str) -> Any:
+ if value is None:
+ return None
+ if not isinstance(value, kind) or (isinstance(value, bool) and kind is not bool):
+ raise HopResolutionError(f"hop capability {what} must be {kind.__name__} or null")
+ return value
+
+
+def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[str] = None) -> ModelSelection:
+ """Build the loop's selection from one ``HopResolution`` (hop-resolution.schema.json).
+
+ ``gateway_base_url`` is the Model Hub gateway prefix the hop's ``base_url`` was
+ built from; a ``google`` hop needs it, because its ``base_url`` is the
+ ``/v1beta`` Gemini surface and the agent speaks Chat to ``/v1``.
+ """
+ if hop.get("backend") != "avibe":
+ raise HopResolutionError(f"hop resolved for backend {hop.get('backend')!r}, not avibe")
+ protocol = hop.get("protocol")
+ if protocol not in PROTOCOLS:
+ raise HopResolutionError(f"hop protocol {protocol!r} is not supported")
+ for name in ("base_url", "token", "runtime_model", "provider"):
+ if not isinstance(hop.get(name), str) or not hop[name]:
+ raise HopResolutionError(f"hop has no {name}")
+ headers = hop.get("request_headers")
+ if not isinstance(headers, Mapping) or not all(
+ isinstance(key, str) and isinstance(value, str) for key, value in headers.items()
+ ):
+ raise HopResolutionError("hop request_headers must map strings to strings")
+ raw = hop.get("capabilities")
+ if not isinstance(raw, Mapping):
+ raise HopResolutionError("hop has no capabilities")
+ efforts = raw.get("reasoning_efforts") or []
+ if not isinstance(efforts, (list, tuple)) or not all(isinstance(item, str) for item in efforts):
+ raise HopResolutionError("hop capability reasoning_efforts must be a list of strings")
+ capabilities = ModelCapabilities(
+ context_window=_optional(raw.get("context_window"), int, "context_window"),
+ input_limit=_optional(raw.get("input_limit"), int, "input_limit"),
+ max_output_tokens=_optional(raw.get("max_output_tokens"), int, "max_output_tokens"),
+ supports_tools=_optional(raw.get("supports_tools"), bool, "supports_tools"),
+ supports_images=_optional(raw.get("supports_images"), bool, "supports_images"),
+ supports_reasoning=_optional(raw.get("supports_reasoning"), bool, "supports_reasoning"),
+ reasoning_efforts=tuple(efforts),
+ )
+ base_url = hop["base_url"]
+ if protocol == "google":
+ if not gateway_base_url:
+ raise HopResolutionError("a google hop needs the gateway prefix to call Chat Completions")
+ protocol, base_url = "openai_chat", f"{gateway_base_url.rstrip('/')}/v1"
+ endpoint = ModelEndpoint(
+ protocol=protocol,
+ base_url=base_url,
+ model_id=hop["runtime_model"],
+ token=hop["token"],
+ request_headers=dict(headers),
+ provider=hop["provider"],
+ )
+ return ModelSelection(endpoint=endpoint, capabilities=capabilities)
+
+
+class HubModelRouter:
+ """``ModelRouter`` for one run: a fresh hop for every model attempt (C-6 item 3).
+
+ ``first`` is the selection the adapter already resolved during preflight; the
+ loop's first attempt reuses it, so a run resolves once and again only after a
+ retryable error.
+ """
+
+ def __init__(
+ self,
+ resolve: SelectionResolver,
+ providers: ProviderFactory,
+ *,
+ first: Optional[ModelSelection] = None,
+ ) -> None:
+ self._resolve = resolve
+ self._providers = providers
+ self._first = first
+ self._adapters: dict[str, ProviderAdapter] = {}
+
+ async def resolve(self) -> ModelSelection:
+ if self._first is not None:
+ selection, self._first = self._first, None
+ return selection
+ return await self._resolve()
+
+ def provider_for(self, protocol: ProtocolName) -> ProviderAdapter:
+ adapter = self._adapters.get(protocol)
+ if adapter is None:
+ adapter = self._adapters[protocol] = self._providers(protocol)
+ return adapter
+
+ async def aclose(self) -> None:
+ """Close every adapter, best effort: run cleanup never changes the Turn's outcome."""
+ adapters, self._adapters = list(self._adapters.items()), {}
+ for protocol, adapter in adapters:
+ close = getattr(adapter, "aclose", None)
+ if close is None:
+ continue
+ try:
+ await close()
+ except Exception:
+ logger.warning("Avibe Agent could not close its %s provider adapter", protocol, exc_info=True)
+
+
+def registry_providers(*, media_loader: Any, client: Any = None) -> ProviderFactory:
+ """Provider adapters from the ``ai`` registry, speaking to the Model Hub gateway.
+
+ In gateway mode each adapter reads the served origin from ``x-avibe-served-hop``
+ with the engine's own resolver, the one owner of that C-6 rule.
+ """
+
+ def create(protocol: ProtocolName) -> ProviderAdapter:
+ from core.agent_core.ai.registry import create_adapter
+
+ return create_adapter(
+ protocol,
+ client=client,
+ media_loader=media_loader,
+ gateway=True,
+ )
+
+ return create
diff --git a/modules/agents/avibe/prompt.py b/modules/agents/avibe/prompt.py
new file mode 100644
index 000000000..4f653ce73
--- /dev/null
+++ b/modules/agents/avibe/prompt.py
@@ -0,0 +1,158 @@
+"""The Avibe Agent's system prompt and the environment block of each consumed input.
+
+The system prompt is stable so providers can cache it: Pi's coding-agent framing
+and tool snippets, then Avibe's injected sections. Facts that change (cwd, date,
+live Watches) travel in an ``<environment>`` block rendered into each consumed
+input instead (C-7 tools.md section 8), so the stored transcript is what the
+model saw.
+
+Preamble, tool snippets, and rules ported from Pi (MIT, Copyright (c) 2025 Mario
+Zechner), ``packages/coding-agent/src/core/system-prompt.ts`` and
+``packages/coding-agent/src/core/tools/{read,write,edit,bash}.ts`` at ``7fbbd5f``;
+Pi-specific lines (its docs, ``PI_*`` variables) are left out.
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import platform
+import re
+import time
+from datetime import datetime
+from pathlib import Path
+from typing import Iterable, Mapping, Optional, Sequence
+
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.messages import TextBlock, UserMessage
+
+PREAMBLE = (
+ "You are an expert coding assistant operating inside Avibe, a local-first agent runtime. You help users by "
+ "reading files, executing commands, editing code, and writing new files."
+)
+TOOL_SNIPPETS: dict[str, str] = {
+ "read": "Read file contents",
+ "bash": "Execute bash commands (ls, grep, find, etc.)",
+ "edit": "Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
+ "write": "Create or overwrite files",
+}
+TOOL_GUIDELINES: dict[str, tuple[str, ...]] = {
+ "read": ("Use read to examine files instead of cat or sed.",),
+ "edit": (
+ "Use edit for precise changes (edits[].oldText must match exactly)",
+ "When changing multiple separate locations in one file, use one edit call with multiple entries in "
+ "edits[] instead of multiple edit calls",
+ "Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not "
+ "emit overlapping or nested edits. Merge nearby changes into one edit.",
+ "Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large "
+ "unchanged regions.",
+ ),
+ "write": ("Use write only for new files or complete rewrites.",),
+}
+TOOL_ORDER = ("read", "bash", "edit", "write")
+
+
+def coding_prompt(tool_names: Iterable[str]) -> str:
+ """Pi's preamble, tool list, and rules for the tools actually offered."""
+ offered = set(tool_names)
+ names = [name for name in TOOL_ORDER if name in offered]
+ tools = "\n".join(f"- {name}: {TOOL_SNIPPETS[name]}" for name in names) or "(none)"
+ rules: list[str] = []
+ if "bash" in names:
+ rules.append("Use bash for file operations like ls, rg, find")
+ for name in names:
+ rules.extend(TOOL_GUIDELINES.get(name, ()))
+ rules += ["Be concise in your responses", "Show file paths clearly when working with files"]
+ return "\n\n".join(
+ (
+ PREAMBLE,
+ f"Available tools:\n{tools}",
+ "Guidelines:\n" + "\n".join(f"- {rule}" for rule in rules),
+ )
+ )
+
+
+def system_prompt(tool_names: Iterable[str], avibe_sections: str) -> str:
+ return "\n\n".join(part for part in (coding_prompt(tool_names), avibe_sections.strip()) if part)
+
+
+# --- environment block ---------------------------------------------------------
+
+ENVIRONMENT_FIELDS = ("cwd", "os", "shell", "date", "timezone", "watches")
+_BLOCK = re.compile(r"\A<environment>\n(?P<body>(?:[a-z]+: [^\n]*\n)*)</environment>\Z")
+
+
[email protected]_cache(maxsize=1)
+def operating_system() -> str:
+ machine = platform.machine() or "unknown"
+ if platform.system() == "Darwin":
+ release = platform.mac_ver()[0] or platform.release()
+ return f"macOS {release} ({machine})"
+ return f"{platform.system() or 'unknown'} {platform.release()} ({machine})".strip()
+
+
+def local_timezone() -> str:
+ zone = os.environ.get("TZ", "").lstrip(":")
+ if zone:
+ return zone
+ try:
+ target = os.path.realpath("/etc/localtime")
+ if "zoneinfo/" in target:
+ return target.split("zoneinfo/", 1)[1]
+ except OSError:
+ pass
+ return time.tzname[0] if time.tzname else "UTC"
+
+
+def current_environment(
+ cwd: str, watches: Sequence[str], *, include_time: bool = True, now: Optional[datetime] = None
+) -> dict[str, str]:
+ """The environment fields; the clock ones follow ``include_time_info``, as every input prefix does."""
+ fields = {
+ "cwd": str(Path(cwd).resolve()) if cwd else "",
+ "os": operating_system(),
+ "shell": os.environ.get("SHELL") or "/bin/sh",
+ }
+ if include_time:
+ fields.update(date=(now or datetime.now()).date().isoformat(), timezone=local_timezone())
+ fields["watches"] = "; ".join(watches) if watches else "none"
+ # One line per field: a value never carries the block's own line structure.
+ return {name: " ".join(value.split()) if "\n" in value else value for name, value in fields.items()}
+
+
+def render_environment(fields: Mapping[str, str]) -> str:
+ lines = [f"{name}: {fields[name]}" for name in ENVIRONMENT_FIELDS if name in fields]
+ return "<environment>\n" + "".join(f"{line}\n" for line in lines) + "</environment>"
+
+
+def parse_environment(text: str) -> Optional[dict[str, str]]:
+ match = _BLOCK.match(text or "")
+ if match is None:
+ return None
+ fields = dict(line.split(": ", 1) for line in match.group("body").splitlines())
+ return {name: value for name, value in fields.items() if name in ENVIRONMENT_FIELDS}
+
+
+def environment_state(entries: Sequence[ContextEntry]) -> dict[str, str]:
+ """The environment the model was last told, replaying each input's block in context order."""
+ state: dict[str, str] = {}
+ for entry in entries:
+ if entry.kind != "input" or not isinstance(entry.message, UserMessage):
+ continue
+ first = entry.message.content[0]
+ if isinstance(first, TextBlock) and first.text is not None:
+ delta = parse_environment(first.text)
+ if delta is not None:
+ state.update(delta)
+ return state
+
+
+def environment_delta(previous: Mapping[str, str], current: Mapping[str, str]) -> dict[str, str]:
+ """Fields that changed since the model last saw them; every field on the first input."""
+ return {name: value for name, value in current.items() if previous.get(name) != value}
+
+
+def with_environment(message: UserMessage, delta: Mapping[str, str]) -> UserMessage:
+ if not delta:
+ return message
+ return UserMessage(content=(TextBlock(text=render_environment(delta)), *message.content))
diff --git a/modules/agents/avibe/recovery.py b/modules/agents/avibe/recovery.py
new file mode 100644
index 000000000..a1822c76c
--- /dev/null
+++ b/modules/agents/avibe/recovery.py
@@ -0,0 +1,105 @@
+"""The single owner of the Avibe Agent's settlement outside a Turn.
+
+Settlement outside a Turn is T2 (open tool calls), T3 admission (accepted inputs
+no run consumed), and J5 (pruning settled jobs). The controller holds one
+``AvibeRecovery`` and so at most one recovery task: two adapters settling the
+same Session would each take their own locks and could both append a
+``tool_result``.
+
+A pass runs on the registered adapter, or, while ``agents.avibe`` is disabled,
+on one unregistered adapter it keeps for as long as it needs one: recovery
+needs only the transcript store, the job host, and the Watch hand-over. Every
+pass re-derives its candidates from the rows, so the unsettled set carries over
+to whichever adapter runs the next pass.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import itertools
+import logging
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+# A pass that left Sessions unsettled is retried after 5 s, 30 s, 2 min, then every 10 min.
+RETRY_DELAYS_S = (5.0, 30.0, 120.0)
+RETRY_PERIOD_S = 600.0
+
+
+class AvibeRecovery:
+ def __init__(self, controller: Any) -> None:
+ self._controller = controller
+ self._task: Optional[asyncio.Task] = None
+ self._transient: Any = None
+ # Serializes every pass, immediate or retried, and the scheduling around it, so
+ # two passes never run at once (a start racing a registration, or a retry).
+ self._lock = asyncio.Lock()
+
+ @property
+ def retrying(self) -> bool:
+ """Whether some Session is still unsettled and a retry is pending."""
+ return self._task is not None and not self._task.done()
+
+ async def start(self) -> list[str]:
+ """Retire any pending retry, run one pass now, and keep retrying while Sessions stay unsettled.
+
+ The entry point for startup and for live registration of the backend. Under
+ the lock a pending retry is only ever sleeping or waiting for the lock, never
+ mid-pass, so it is retired without interrupting a write and there are never
+ two passes at once. Returns the Sessions this pass left unsettled.
+ """
+ async with self._lock:
+ await self.stop()
+ unsettled = await self._pass()
+ if unsettled and not self.retrying:
+ self._task = asyncio.create_task(self._retry(), name="avibe-agent-recovery")
+ return unsettled
+
+ def ensure(self) -> None:
+ """A Turn could not settle something (a returned input it failed to admit): retry it."""
+ if not self.retrying:
+ self._task = asyncio.create_task(self._retry(), name="avibe-agent-recovery")
+
+ async def stop(self) -> None:
+ """Stop retrying (service stop, or a new owner taking over); the next start recovers again."""
+ task, self._task = self._task, None
+ if task is not None and not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ async def _retry(self) -> None:
+ # No kill fail-safe: a transient DB or Watch failure must not kill a user's command,
+ # whose own wrapper deadline still bounds it.
+ for attempt in itertools.count():
+ await asyncio.sleep(RETRY_DELAYS_S[attempt] if attempt < len(RETRY_DELAYS_S) else RETRY_PERIOD_S)
+ async with self._lock:
+ unsettled = await self._pass()
+ if not unsettled:
+ logger.info("Avibe Agent recovery settled every Session")
+ return
+ logger.error("Avibe Agent recovery could not settle Sessions %s; retrying", ", ".join(unsettled))
+
+ async def _pass(self) -> list[str]:
+ agent = self._agent()
+ try:
+ unsettled = await agent.recover_runtime_state()
+ except Exception:
+ logger.exception("Avibe Agent recovery pass failed")
+ return ["*"]
+ if not unsettled:
+ self._transient = None
+ return unsettled
+
+ def _agent(self) -> Any:
+ registered = getattr(getattr(self._controller, "agent_service", None), "agents", {}).get("avibe")
+ if registered is not None:
+ self._transient = None
+ return registered
+ if self._transient is None:
+ from modules.agents.avibe.agent import AvibeAgent
+
+ self._transient = AvibeAgent(self._controller)
+ return self._transient
diff --git a/modules/agents/avibe/store.py b/modules/agents/avibe/store.py
new file mode 100644
index 000000000..dbffa9eaa
--- /dev/null
+++ b/modules/agents/avibe/store.py
@@ -0,0 +1,137 @@
+"""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, from the environment the context last recorded, so what
+ ``consume_input`` stores is exactly what the model is sent;
+* 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, for the run that
+owns it; nothing here keeps responses after that.
+"""
+
+from __future__ import annotations
+
+import asyncio
+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.store import ContextEntry
+from core.agent_core.messages import AssistantMessage, ToolResultMessage, UserMessage
+from modules.agents.avibe.prompt import environment_delta, environment_state, with_environment
+from storage.agent_transcript import SQLiteTranscriptStore
+from storage.models import messages
+
+EnvironmentSource = Callable[[str], Mapping[str, str]]
+ResponseObserver = Callable[[str, str, AssistantMessage], None]
+
+#: 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,
+ 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._input_row_timeout_s = input_row_timeout_s
+ # Per Session, the environment the context last recorded; evicted by ``forget``
+ # when the adapter retires the Session's runtime.
+ 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] = {}
+
+ def bind_agent(self, session_id: str, agent_name: Optional[str]) -> 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)
+
+ @contextmanager
+ def writing_as(self, session_id: str, agent_name: Optional[str]) -> Iterator[None]:
+ """Attribute the Session's writes inside the block to ``agent_name``; restore after."""
+ previous = self._agents.get(session_id)
+ self.bind_agent(session_id, agent_name or previous)
+ try:
+ yield
+ finally:
+ self.bind_agent(session_id, previous)
+
+ 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._store.forget(session_id)
+
+ # --- TranscriptStore -----------------------------------------------------
+
+ async def load(self, session_id: str) -> Sequence[ContextEntry]:
+ return await self._store.load(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:
+ previous = environment_state(await self._store.load(session_id))
+ current = dict(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, **current}
+ return entry
+
+ async def append_response(self, session_id: str, message: AssistantMessage, *, final: bool) -> ContextEntry:
+ entry = await self._store.append_response(
+ session_id, message, final=final, agent_name=self._agents.get(session_id)
+ )
+ self._on_response(session_id, entry.row_id, message)
+ return entry
+
+ async def append_tool_result(
+ self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]
+ ) -> ContextEntry:
+ return await self._store.append_tool_result(
+ session_id, message, details=details, agent_name=self._agents.get(session_id)
+ )
+
+ async def append_payload(
+ self, session_id: str, kind: Literal["compaction", "context_edit", "agent_state"], payload: Mapping[str, Any]
+ ) -> ContextEntry:
+ return await self._store.append_payload(session_id, kind, payload, agent_name=self._agents.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 _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
diff --git a/modules/agents/avibe/tools.py b/modules/agents/avibe/tools.py
new file mode 100644
index 000000000..df029ab72
--- /dev/null
+++ b/modules/agents/avibe/tools.py
@@ -0,0 +1,88 @@
+"""The Avibe Agent's tools: Pi's coding tools over a Watch-backed job host (C-7).
+
+``ToolSuite`` is the adapter's whole dependency on ``core.agent_core.tools``:
+the job host, the tools built over the loop's tracking wrapper (``Agent.jobs``,
+so an abort kills foreground commands), the bash renderer recovery uses for open
+calls (``recovery.md`` T2), the lookup from a tool call to its job, and job
+pruning.
+
+The job host lives in Watch's ``agent_jobs_dir()``, where ``vibe stop`` and the
+job-Watch sweep look, and hands a job over through Watch's own
+``hand_over_job``: adopt-or-create the once Watch with target kind ``job``,
+keyed by ``job_id`` (J6). Raising means no Watch owns the job; ``bash`` then
+keeps the command in the foreground.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from typing import Any, Awaitable, Callable, Mapping, Optional, Sequence
+
+from core.agent_core.agent.recovery import RecoveryRenderer
+from core.agent_core.tools.base import JobHost, Tool
+
+ImageSink = Callable[[bytes, str, str], Awaitable[str]]
+#: Whether a job's tool call has a durable ``tool_result`` (the adapter's half of J5).
+CallSettled = Callable[[Mapping[str, Any]], bool]
+
+
+@dataclass(frozen=True)
+class ToolSuite:
+ jobs: JobHost
+ create_tools: Callable[[JobHost, Optional[ImageSink]], Sequence[Tool]]
+ render_recovered: RecoveryRenderer
+ # ``find_job(session_id, tool_call_id, *, created_since)``: the newest job the call started.
+ find_job: Callable[..., Optional[str]]
+ prune: Optional[Callable[[CallSettled], list[str]]] = None
+
+
+#: The hand-over route for a job (``hand_over_job``'s keywords), from its owning Turn.
+HandOverRoute = Callable[[Mapping[str, Any]], Mapping[str, Any]]
+
+
+def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOverRoute] = None) -> ToolSuite:
+ """Pi's ``read``, ``write``, ``edit``, and ``bash`` over the ``pipe`` job host.
+
+ Every path that creates a job Watch (``watch=true``, the foreground-window hand-over,
+ and T2 recovery) goes through the host's ``on_hand_over``, which takes the Watch's
+ Agent and authorization from ``route``: the job's owning Turn.
+ """
+ from core.agent_core.tools.bash import final_result, handover_result
+ from core.agent_core.tools.coding import create_coding_tools
+ from core.agent_core.tools.jobs import LocalJobHost
+ from core.agent_core.tools.output import JobOutput
+ from core.watches import ManagedWatchStore, agent_jobs_dir
+
+ async def hand_over(meta: Mapping[str, Any]) -> str:
+ import core.watches as watches
+ from core.vibe_agents import VibeAgentAccessError
+ from storage.resource_access_service import ResourceAccessError
+
+ owner = dict(await asyncio.to_thread(route, meta)) if route is not None else {}
+ try:
+ return await watches.hand_over_job(meta, **owner)
+ except (ResourceAccessError, VibeAgentAccessError, ValueError):
+ # The Turn's principal may not create this Watch (no Harness edit right, or
+ # no access to the Agent): the Watch still owns the job, and its follow-up
+ # stays denied.
+ fallback = {key: value for key, value in owner.items() if key != "user_context"}
+ return await watches.hand_over_job(meta, **fallback, unverifiable_remote=True)
+
+ host = LocalJobHost(str(jobs_dir or agent_jobs_dir()), on_hand_over=hand_over)
+
+ def create_tools(jobs: JobHost, image_sink: Optional[ImageSink]) -> Sequence[Tool]:
+ return create_coding_tools(jobs, image_sink=image_sink)
+
+ async def render(call: Any, job_id: str, status: Any, watch_id: Optional[str]) -> Any:
+ output = JobOutput(host, job_id)
+ return await handover_result(output, watch_id) if watch_id else await final_result(output, status)
+
+ def prune(call_settled: CallSettled) -> list[str]:
+ # J5: a job's files stay until its call has a durable result and no Watch still manages it.
+ watches = ManagedWatchStore()
+ return host.prune(lambda meta: call_settled(meta) and watches.job_watch_settled(str(meta.get("job_id"))))
+
+ return ToolSuite(
+ jobs=host, create_tools=create_tools, render_recovered=render, find_job=host.find_job, prune=prune
+ )
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index 645a3e201..35faeceec 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -291,7 +291,9 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
else "ignore"
)
elif activity_role == "activity":
- kind = "activity"
+ # A row with no text (a response that only called tools, or a hidden silent
+ # final) shows nothing; other backends never persist one.
+ kind = "activity" if str(msg.get("text") or "").strip() else "ignore"
elif activity_role == "boundary":
kind = "boundary"
else:
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 9de94a563..af8d6280e 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -7,9 +7,8 @@ context exactly when its ``context_seq`` is non-null:
* inputs are existing ``messages`` rows (``user``, ``harness``,
``agent_initiated``, ``annotation``); consuming one sets its ``context_seq``
and ``content_json.model`` once;
-* responses are new ``assistant`` / ``result`` rows with ``content_json.model``,
- a rendered ``content_text``, and the output outbox state
- ``metadata_json.delivery``;
+* responses are new ``assistant`` / ``result`` / ``error`` rows with
+ ``content_json.model`` and a rendered ``content_text``;
* tool results, checkpoints, context edits, and hook state are new
``agent_events`` rows with ``visibility='context'``.
@@ -24,7 +23,8 @@ Delivery, and that Turn's initial Delivery names the input row. That is the
channel the Turn answers, where ``persist_agent_message`` attributes the same
output, and a steer from another surface does not re-home the reply. An input
without a Delivery link stands for itself. ``agent_events.turn_id`` is that
-Turn.
+Turn. A fork that settles the calls it inherited open before its first input
+attributes those rows to its own scope, with no Turn.
Fork. A child inherits its source's context rows up to ``anchor_seq``, read
from the top-level Session metadata ``fork_source_session_id`` and
@@ -35,11 +35,13 @@ never move into or out of the prefix. A fork without that key (a released fork,
or one from another backend) inherits nothing. The child's own rows continue
from ``anchor_seq + 1``.
-Outbox. A response row commits with ``delivery = {"state": "pending",
-"parts": []}``. The adapter records a receipt for each part a surface splits it
-into; the row becomes ``delivered`` only when every part has one
-(``recovery.md`` D1). A response whose display text is blank (only thinking or
-tool calls) has no part on any surface and commits ``delivered``.
+Display. A response row commits with the display text its renderer gives it.
+Its display columns (``content_text``, the display keys of ``content_json``,
+type ``result`` or ``error``) are written again when the dispatcher delivers
+it, exactly as for the other backends' rows (``persist_agent_message`` with
+``existing_row_id``). The transcript payload, ``content_json.model``, never
+changes after commit. A final whose ``final_outcome`` failed commits as
+``error``.
Cancellation. A worker thread cannot be interrupted, so a cancelled write keeps
the Session's lock until its transaction settles and only then raises: when a
@@ -54,7 +56,7 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Callable, Literal, Mapping, Optional, Sequence, TypeVar
-from sqlalchemy import and_, func, or_, select
+from sqlalchemy import and_, func, or_, select, text
from sqlalchemy.engine import Connection, Engine
from core.agent_core.harness.store import ContextEntry, EntryKind
@@ -69,11 +71,19 @@ from core.agent_core.messages import (
)
from storage import agent_events_service, messages_service
from storage.agent_session_rows import reserve_write_lock
-from storage.models import agent_events, agent_sessions, message_deliveries, messages, session_turns
+from storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns
INPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")
-RESPONSE_TYPES = ("assistant", "result")
+# A final response is ``result``, or ``error`` when ``final_outcome`` says it failed:
+# the row carries its outcome, as the other backends' terminal rows do. A final with
+# nothing to show (a silent reply) is the hidden response type ``assistant``: context,
+# but no transcript row, inbox reply, or unread result, as the other backends persist
+# nothing visible for it.
+FINAL_TYPES = ("result", "error")
+RESPONSE_TYPES = ("assistant", *FINAL_TYPES)
CONTEXT_VISIBILITY = "context"
+# Only the Avibe Agent writes context rows; the Session's routed backend may change mid-Turn.
+CONTEXT_WRITER = "avibe"
PAYLOAD_VERSION = 1
PayloadKind = Literal["compaction", "context_edit", "agent_state"]
@@ -85,11 +95,34 @@ _EVENT_TYPE_BY_KIND: dict[str, str] = {
}
_KIND_BY_EVENT_TYPE = {event_type: kind for kind, event_type in _EVENT_TYPE_BY_KIND.items()}
-DisplayRenderer = Callable[[AssistantMessage], str]
+# ``render(message, final=...)``: a response row's commit-time display text.
+DisplayRenderer = Callable[..., str]
_T = TypeVar("_T")
+FinalOutcome = Literal["completed", "failed"]
-def render_text(message: AssistantMessage) -> str:
+def final_outcome(message: AssistantMessage) -> FinalOutcome:
+ """The Turn outcome a committed final response determines by itself.
+
+ The one rule, shared by the row's type at commit and live settlement: a final
+ reply without text of its own (an unexplained refusal or safety stop, or an
+ empty answer) failed; any other final completed. It is the loop's own
+ empty-reply test (loop-control.md section 2). Failures only a live run can
+ observe after the commit are applied by the live caller.
+ """
+ has_text = any(isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content)
+ return "completed" if has_text else "failed"
+
+
+def _response_type(message: AssistantMessage, *, final: bool, display_text: str) -> str:
+ if not final:
+ return "assistant"
+ if final_outcome(message) == "failed":
+ return "error"
+ return "result" if display_text.strip() else "assistant"
+
+
+def render_text(message: AssistantMessage, *, final: bool = False) -> str:
"""Default display copy of a response: its text blocks, verbatim, in order."""
return "\n\n".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
@@ -98,20 +131,6 @@ class TranscriptError(RuntimeError):
"""A write the context rules refuse, or rows that cannot form a context."""
-@dataclass(frozen=True)
-class PendingDelivery:
- """A committed response whose surface delivery has not been recorded."""
-
- session_id: str
- context_seq: int
- row_id: str
- final: bool
- text: str
- message: AssistantMessage
- parts: tuple[Optional[Mapping[str, Any]], ...] = ()
- """Receipts by part index from an earlier attempt; ``None`` marks a part still to send."""
-
-
@dataclass(frozen=True)
class _TurnOrigin:
platform: str
@@ -122,10 +141,11 @@ class _TurnOrigin:
class SQLiteTranscriptStore:
- """``TranscriptStore`` over Avibe's tables, plus the output outbox helpers.
+ """``TranscriptStore`` over Avibe's tables.
- ``render`` produces a response row's ``content_text``; the adapter supplies
- its display rendering, the default keeps the text blocks.
+ ``render(message, final=...)`` produces a response row's commit-time
+ ``content_text``; the adapter supplies its display rendering, the default keeps
+ the text blocks.
"""
def __init__(self, engine: Engine, *, render: DisplayRenderer = render_text) -> None:
@@ -133,6 +153,12 @@ class SQLiteTranscriptStore:
self._render = render
self._locks: dict[str, asyncio.Lock] = {}
+ def forget(self, session_id: str) -> None:
+ """Drop an idle Session's write lock; the next write creates it again."""
+ lock = self._locks.get(session_id)
+ if lock is not None and not lock.locked():
+ del self._locks[session_id]
+
# --- TranscriptStore ----------------------------------------------------
async def load(self, session_id: str) -> Sequence[ContextEntry]:
@@ -171,14 +197,16 @@ class SQLiteTranscriptStore:
return await self._write(session_id, work)
- async def append_response(self, session_id: str, message: AssistantMessage, *, final: bool) -> ContextEntry:
+ async def append_response(
+ self, session_id: str, message: AssistantMessage, *, final: bool, agent_name: Optional[str] = None
+ ) -> ContextEntry:
if not isinstance(message, AssistantMessage):
raise TypeError("append_response takes an AssistantMessage")
model = _canonical({"version": PAYLOAD_VERSION, "message": message_to_dict(message)}, "response")
- display_text = self._render(message)
+ display_text = self._render(message, final=final)
def work(conn: Connection) -> ContextEntry:
- origin = _turn_origin(conn, session_id)
+ origin = _turn_origin(conn, session_id, agent_name)
seq = _next_context_seq(conn, session_id)
row = messages_service.append(
conn,
@@ -188,10 +216,9 @@ class SQLiteTranscriptStore:
author="agent",
source="agent",
author_name=origin.agent_name,
- message_type="result" if final else "assistant",
+ message_type=_response_type(message, final=final, display_text=display_text),
text=display_text,
content={"model": model},
- metadata={"delivery": {"state": "pending" if display_text.strip() else "delivered", "parts": []}},
)
conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
return ContextEntry(session_id, seq, "response", row["id"], message=message, payload=model)
@@ -199,7 +226,12 @@ class SQLiteTranscriptStore:
return await self._write(session_id, work)
async def append_tool_result(
- self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]
+ self,
+ session_id: str,
+ message: ToolResultMessage,
+ *,
+ details: Mapping[str, Any],
+ agent_name: Optional[str] = None,
) -> ContextEntry:
if not isinstance(message, ToolResultMessage):
raise TypeError("append_tool_result takes a ToolResultMessage")
@@ -207,41 +239,29 @@ class SQLiteTranscriptStore:
if details:
payload["details"] = dict(details)
payload = _canonical(payload, "tool result")
- return await self._write(
- session_id, lambda conn: self._append_event(conn, session_id, "tool_result", payload, message)
- )
- async def append_payload(self, session_id: str, kind: PayloadKind, payload: Mapping[str, Any]) -> ContextEntry:
+ def work(conn: Connection) -> ContextEntry:
+ # A call instance is settled once, whoever writes (a run, T2 at resume, a
+ # recovery pass): checked under the writer lock, so a racing second writer
+ # gets the first result back instead of a duplicate.
+ settled = _settled_result(conn, session_id, message.tool_call_id)
+ if settled is not None:
+ return settled
+ return self._append_event(conn, session_id, "tool_result", payload, message, agent_name)
+
+ return await self._write(session_id, work)
+
+ async def append_payload(
+ self, session_id: str, kind: PayloadKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None
+ ) -> ContextEntry:
if kind not in ("compaction", "context_edit", "agent_state"):
raise ValueError(f"not a payload entry kind: {kind!r}")
data = _canonical(dict(payload), f"{kind} payload")
if not _is_current_version(data):
raise ValueError(f"a {kind} payload needs version {PAYLOAD_VERSION}")
- return await self._write(session_id, lambda conn: self._append_event(conn, session_id, kind, data, None))
-
- # --- output outbox --------------------------------------------------------
-
- async def pending_deliveries(self, session_id: str) -> list[PendingDelivery]:
- """The Session's committed responses not yet delivered, in ``context_seq`` order."""
- return await asyncio.to_thread(self._pending_deliveries, session_id)
-
- async def record_delivery_part(
- self,
- session_id: str,
- row_id: str,
- *,
- index: int,
- count: int,
- native_message_id: Optional[str] = None,
- ) -> bool:
- """Record the receipt of part ``index`` of ``count``; True once every part has one.
-
- A part that already has a receipt keeps its first one, so a retried send is
- recorded once.
- """
- if not 0 <= index < count:
- raise ValueError(f"part {index} is outside a delivery of {count} part(s)")
- return await asyncio.to_thread(self._record_delivery_part, session_id, row_id, index, count, native_message_id)
+ return await self._write(
+ session_id, lambda conn: self._append_event(conn, session_id, kind, data, None, agent_name)
+ )
# --- implementation -------------------------------------------------------
@@ -267,8 +287,9 @@ class SQLiteTranscriptStore:
kind: EntryKind,
payload: dict[str, Any],
message: Optional[ToolResultMessage],
+ agent_name: Optional[str] = None,
) -> ContextEntry:
- origin = _turn_origin(conn, session_id)
+ origin = _turn_origin(conn, session_id, agent_name)
seq = _next_context_seq(conn, session_id)
row = agent_events_service.append(
conn,
@@ -302,82 +323,6 @@ class SQLiteTranscriptStore:
)
return entries
- def _pending_deliveries(self, session_id: str) -> list[PendingDelivery]:
- with self._engine.connect() as conn:
- rows = conn.execute(
- select(
- messages.c.id,
- messages.c.type,
- messages.c.context_seq,
- messages.c.content_text,
- messages.c.content_json,
- messages.c.metadata_json,
- )
- .where(
- messages.c.session_id == session_id,
- messages.c.context_seq.is_not(None),
- messages.c.type.in_(RESPONSE_TYPES),
- func.json_extract(messages.c.metadata_json, "$.delivery.state") == "pending",
- )
- .order_by(messages.c.context_seq)
- ).mappings().all()
- deliveries = []
- for row in rows:
- entry = _message_entry(session_id, row)
- assert isinstance(entry.message, AssistantMessage)
- deliveries.append(
- PendingDelivery(
- session_id=session_id,
- context_seq=entry.context_seq,
- row_id=entry.row_id,
- final=row["type"] == "result",
- text=row["content_text"] or "",
- message=entry.message,
- parts=tuple(_delivery(row["metadata_json"], entry.row_id)["parts"]),
- )
- )
- return deliveries
-
- def _record_delivery_part(
- self, session_id: str, row_id: str, index: int, count: int, native_message_id: Optional[str]
- ) -> bool:
- with self._engine.begin() as conn:
- reserve_write_lock(conn)
- raw = conn.execute(
- select(messages.c.metadata_json).where(
- messages.c.id == row_id,
- messages.c.session_id == session_id,
- messages.c.context_seq.is_not(None),
- messages.c.type.in_(RESPONSE_TYPES),
- )
- ).scalar_one_or_none()
- if raw is None:
- raise TranscriptError(f"{row_id} is not a response of Session {session_id}")
- metadata = _json_object(raw, row_id)
- delivery = _delivery(raw, row_id)
- if delivery["state"] == "delivered":
- return True
- parts = delivery["parts"] or [None] * count
- if len(parts) != count:
- raise TranscriptError(f"{row_id} was split into {len(parts)} part(s), not {count}")
- if parts[index] is None:
- now = _utc_now()
- receipt: dict[str, Any] = {"delivered_at": now}
- if native_message_id:
- receipt["native_message_id"] = native_message_id
- parts[index] = receipt
- state = "delivered" if all(part is not None for part in parts) else "pending"
- conn.execute(
- messages.update()
- .where(messages.c.id == row_id)
- .values(
- metadata_json=json.dumps({**metadata, "delivery": {"state": state, "parts": parts}}),
- updated_at=now,
- )
- )
- return all(part is not None for part in parts)
-
-
async def _settle(task: asyncio.Future[Any]) -> None:
"""Wait for ``task`` to finish, whatever cancellations arrive meanwhile."""
while not task.done():
@@ -414,9 +359,15 @@ def _next_context_seq(conn: Connection, session_id: str) -> int:
return top + 1
-def _turn_origin(conn: Connection, session_id: str) -> _TurnOrigin:
+def _turn_origin(conn: Connection, session_id: str, agent_name: Optional[str] = None) -> _TurnOrigin:
+ """Where an inserted row belongs, and the Agent that wrote it.
+
+ ``agent_name`` is the running Turn's Agent (its request snapshot): the Session's
+ selected Agent may change mid-Turn, so the Session row is only the fallback for a
+ write outside a Turn (startup recovery).
+ """
session = conn.execute(
- select(agent_sessions.c.agent_name, agent_sessions.c.agent_backend).where(agent_sessions.c.id == session_id)
+ select(agent_sessions.c.agent_name).where(agent_sessions.c.id == session_id)
).first()
if session is None:
raise TranscriptError(f"Session {session_id} does not exist")
@@ -431,7 +382,20 @@ def _turn_origin(conn: Connection, session_id: str) -> _TurnOrigin:
.limit(1)
).first()
if latest is None:
- raise TranscriptError(f"Session {session_id} has consumed no input; a context row answers a Turn")
+ # A fork settles the calls it inherited open (T2) before it consumes its first
+ # input: those rows belong to the Session's own scope, outside any Turn.
+ home = (
+ conn.execute(
+ select(scopes.c.id, scopes.c.platform)
+ .select_from(agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id))
+ .where(agent_sessions.c.id == session_id)
+ ).first()
+ if _fork_link(conn, session_id) is not None
+ else None
+ )
+ if home is None:
+ raise TranscriptError(f"Session {session_id} has consumed no input; a context row answers a Turn")
+ return _TurnOrigin(home.platform, home.id, None, agent_name or session.agent_name, CONTEXT_WRITER)
platform, scope_id = latest.platform, latest.scope_id
turn_id = conn.execute(
select(message_deliveries.c.turn_id)
@@ -454,12 +418,22 @@ def _turn_origin(conn: Connection, session_id: str) -> _TurnOrigin:
).first()
if initial is not None:
platform, scope_id = initial.platform, initial.scope_id
- return _TurnOrigin(platform, scope_id, turn_id, session.agent_name, session.agent_backend)
+ return _TurnOrigin(platform, scope_id, turn_id, agent_name or session.agent_name, CONTEXT_WRITER)
# --- fork ancestry -------------------------------------------------------------
+def context_bound(conn: Connection, session_id: str) -> int:
+ """The last ``context_seq`` of a Session's context, including the prefix it inherited.
+
+ A fork of a Session with no running Turn inherits all of it: a Turn that ended
+ silently or was stopped shows no row a message anchor could name.
+ """
+ link = _fork_link(conn, session_id)
+ return max(value for value in (_own_bound(conn, session_id), link[1] if link else 0) if value is not None)
+
+
def resolve_fork_anchor_seq(conn: Connection, source_session_id: str, anchor_message_id: Optional[str]) -> int:
"""``anchor_seq`` for a fork of ``source_session_id`` at ``anchor_message_id`` (C-5 §4).
@@ -496,6 +470,104 @@ def resolve_fork_anchor_seq(conn: Connection, source_session_id: str, anchor_mes
return max(value for value in (inherited, own_messages, own_events) if value is not None)
+def _settled_result(conn: Connection, session_id: str, tool_call_id: str) -> Optional[ContextEntry]:
+ """The result already committed for the latest call instance with this id in the Session's context.
+
+ The call instance is the last response in the context (own rows and the inherited
+ prefix) that carries a tool call with this id; its result is the first
+ ``tool_result`` for the id after that response, in context order.
+ """
+ chain = _ancestry(conn, session_id)
+ owner_seq: Optional[int] = None
+ for member, bound in chain:
+ query = (
+ "SELECT MAX(m.context_seq) FROM messages AS m, "
+ "json_each(json_extract(m.content_json, '$.model.message.content')) AS block "
+ "WHERE m.session_id = :member AND m.context_seq IS NOT NULL "
+ "AND json_extract(block.value, '$.type') = 'tool_call' "
+ "AND json_extract(block.value, '$.id') = :call_id"
+ + (" AND m.context_seq <= :bound" if bound is not None else "")
+ )
+ seq = conn.execute(
+ text(query), {"member": member, "call_id": tool_call_id, "bound": bound}
+ ).scalar()
+ if seq is not None and (owner_seq is None or seq > owner_seq):
+ owner_seq = seq
+ if owner_seq is None:
+ return None
+ first = None
+ for member, bound in chain:
+ conditions = [
+ agent_events.c.session_id == member,
+ agent_events.c.event_type == _EVENT_TYPE_BY_KIND["tool_result"],
+ agent_events.c.visibility == CONTEXT_VISIBILITY,
+ agent_events.c.context_seq > owner_seq,
+ func.json_extract(agent_events.c.content_json, "$.message.tool_call_id") == tool_call_id,
+ ]
+ if bound is not None:
+ conditions.append(agent_events.c.context_seq <= bound)
+ row = (
+ conn.execute(
+ select(
+ agent_events.c.id,
+ agent_events.c.session_id,
+ agent_events.c.context_seq,
+ agent_events.c.content_json,
+ agent_events.c.event_type,
+ agent_events.c.visibility,
+ )
+ .where(*conditions)
+ .order_by(agent_events.c.context_seq)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is not None and (first is None or row["context_seq"] < first["context_seq"]):
+ first = row
+ return _event_entry(first["session_id"], first) if first is not None else None
+
+
+def source_tool_result(
+ conn: Connection, owner_session_id: str, response_seq: int, tool_call_id: str
+) -> Optional[ContextEntry]:
+ """The result its owner committed for a call instance a fork inherited open.
+
+ A fork anchored between a response and its tool results inherits those calls
+ open. A call's identity is its instance: the response that carries it
+ (``owner_session_id`` at ``response_seq``) plus its id, because providers may
+ reuse ids. Its result is the first ``tool_result`` for that id after the
+ response in the owner's own rows, in context order: every call is settled
+ before the next model call, so a later reuse of the id comes after it. The
+ child settles with that result instead of re-deriving it from job state that
+ J5 may since have pruned.
+ """
+ row = (
+ conn.execute(
+ select(
+ agent_events.c.id,
+ agent_events.c.session_id,
+ agent_events.c.context_seq,
+ agent_events.c.content_json,
+ agent_events.c.event_type,
+ agent_events.c.visibility,
+ )
+ .where(
+ agent_events.c.session_id == owner_session_id,
+ agent_events.c.event_type == _EVENT_TYPE_BY_KIND["tool_result"],
+ agent_events.c.visibility == CONTEXT_VISIBILITY,
+ agent_events.c.context_seq > response_seq,
+ func.json_extract(agent_events.c.content_json, "$.message.tool_call_id") == tool_call_id,
+ )
+ .order_by(agent_events.c.context_seq)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ return _event_entry(row["session_id"], row) if row is not None else None
+
+
def _fork_link(conn: Connection, session_id: str) -> Optional[tuple[str, int]]:
"""``(source_session_id, anchor_seq)`` when the Session inherits a context."""
raw = conn.execute(
@@ -596,19 +668,6 @@ def _is_current_version(payload: Mapping[str, Any]) -> bool:
return isinstance(version, int) and not isinstance(version, bool) and version == PAYLOAD_VERSION
-def _delivery(raw_metadata: Any, row_id: str) -> dict[str, Any]:
- delivery = _json_object(raw_metadata, row_id).get("delivery")
- parts = delivery.get("parts") if isinstance(delivery, dict) else None
- if (
- not isinstance(delivery, dict)
- or delivery.get("state") not in ("pending", "delivered")
- or not isinstance(parts, list)
- or any(part is not None and not isinstance(part, dict) for part in parts)
- ):
- raise TranscriptError(f"response {row_id} has no readable delivery state")
- return {"state": delivery["state"], "parts": list(parts)}
-
-
def _json_object(raw: Any, row_id: str) -> dict[str, Any]:
try:
value = json.loads(raw or "{}")
diff --git a/storage/messages_service.py b/storage/messages_service.py
index c80c6588c..f3d343db5 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -99,6 +99,10 @@ def _row_to_payload(
content = json.loads(row.get("content_json") or "{}")
except json.JSONDecodeError:
content = {}
+ if isinstance(content, dict):
+ # A transcript row's model payload (the Avibe Agent's context) is not display:
+ # no reader of a message payload uses it, and it can be large or private.
+ content.pop("model", None)
link = content.get("failure_retry") if isinstance(content, dict) else None
if conn is not None and isinstance(link, dict):
from storage.message_deliveries import failure_retry_state, get_delivery
diff --git a/tests/agent_core/agent/test_recovery.py b/tests/agent_core/agent/test_recovery.py
index debf90bed..efa90f042 100644
--- a/tests/agent_core/agent/test_recovery.py
+++ b/tests/agent_core/agent/test_recovery.py
@@ -26,8 +26,12 @@ from tests.agent_core.fakes import (
)
+async def _never_rendered(*_args):
+ pytest.fail("missing/gone jobs must not invoke the renderer")
+
+
def renderer(jobs):
- def render(call, job_id, status, watch_id):
+ async def render(call, job_id, status, watch_id):
output, _ = jobs.output(job_id)
content = (
f"still running, now Watch {watch_id}"
@@ -77,7 +81,7 @@ async def test_resume_settles_each_job_state_once_and_projection_never_rechecks_
render_result=(
renderer(jobs)
if state in {"running", "exited"}
- else lambda *args: pytest.fail("missing/gone jobs must not invoke the renderer")
+ else _never_rendered
),
)
assert len(committed) == 1
@@ -140,10 +144,10 @@ async def test_settlement_resume_after_partial_commit_skips_done_calls_and_keeps
jobs.outputs[name] = name.encode()
ids = {("session", name): name for name in ("a", "b")}
- def render(call, job_id, status, watch_id):
+ async def render(call, job_id, status, watch_id):
if failure == "unsupported_result" and store.fail and call.id == "b":
return ToolResult((TextBlock(ref=LargeRef("sha256:" + "a" * 64, 1)),))
- return renderer(jobs)(call, job_id, status, watch_id)
+ return await renderer(jobs)(call, job_id, status, watch_id)
error_type, error_message = (
(OSError, "second result") if failure == "store_write" else (ProjectionError, "large-content references")
diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.py
index 8bca4f39a..1e8c144b5 100644
--- a/tests/agent_core/tools/test_jobs.py
+++ b/tests/agent_core/tools/test_jobs.py
@@ -147,6 +147,36 @@ async def test_a_wrapper_left_without_a_decision_abandons_and_a_late_host_cannot
assert _counter(tmp_path) == 0
+async def test_find_job_tells_apart_jobs_a_reused_call_started_within_one_millisecond(tmp_path, monkeypatch):
+ import secrets
+
+ # The earlier call's job, the later response's commit, and the later call's job, all inside one
+ # millisecond; the earlier job's id sorts first, so a tie would pick it.
+ moments = iter([
+ datetime(2026, 10, 4, 4, 30, 0, 123100, tzinfo=timezone.utc),
+ datetime(2026, 10, 4, 4, 30, 0, 123700, tzinfo=timezone.utc),
+ ])
+ real_datetime, token_hex = jobs_module.datetime, secrets.token_hex
+
+ class _Clock(real_datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return next(moments)
+
+ job_ids = iter(["0" * 16, "f" * 16])
+ monkeypatch.setattr(jobs_module, "datetime", _Clock)
+ monkeypatch.setattr(jobs_module.secrets, "token_hex", lambda n=None: next(job_ids) if n == 8 else token_hex(n))
+ host = LocalJobHost(str(tmp_path / "jobs"))
+ earlier = await _start(host, tmp_path, "true", tool_call_id="call_0")
+ later = await _start(host, tmp_path, "true", tool_call_id="call_0")
+ monkeypatch.undo()
+ response_committed = datetime(2026, 10, 4, 4, 30, 0, 123400, tzinfo=timezone.utc)
+
+ assert host.find_job("ses_test", "call_0", created_since=response_committed) == later
+ assert host.find_job("ses_test", "call_0") == later
+ assert _wait_until(lambda: all(host.status(job).state != "running" for job in (earlier, later)))
+
+
async def test_recovery_reads_exited_running_and_gone(tmp_path):
jobs_dir = str(tmp_path / "jobs")
host = LocalJobHost(jobs_dir)
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index f5fb801bd..833f37efb 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -151,6 +151,8 @@ def test_done_failed_interrupted_and_trailing_groups(isolated_state):
# Turn 1 — done: user, assistant, tool_call, result.
_msg(conn, scope, sid, mid="m_u1", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q1", source="user")
_msg(conn, scope, sid, mid="m_a1", mtype="assistant", author="agent", created_at="2026-06-01T10:00:01.000000+00:00", text="thinking")
+ # A response that only called tools persists no text (the Avibe Agent's transcript row): not a step.
+ _msg(conn, scope, sid, mid="m_a1b", mtype="assistant", author="agent", created_at="2026-06-01T10:00:01.500000+00:00", text="")
_evt(conn, scope, sid, eid="e_t1", created_at="2026-06-01T10:00:02Z", text="🔧 `Bash` `{\"command\":\"ls\"}`")
_msg(conn, scope, sid, mid="m_r1", mtype="result", author="agent", created_at="2026-06-01T10:00:03.000000+00:00", text="answer 1")
# Turn 2 — no activity: user + result only → no group.
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index 1e9dbeb9f..e5b45142d 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -20,6 +20,7 @@ from core.agent_core.messages import (
AssistantMessage,
ImageBlock,
Origin,
+ TextBlock,
ThinkingBlock,
ToolCallBlock,
ToolResultMessage,
@@ -233,7 +234,6 @@ async def test_every_kind_round_trips_in_one_order_attributed_to_the_turn(engine
for entry, row_type, display in ((written[1], "assistant", "Listing."), (written[7], "result", "两个文件。")):
row = rows[entry.row_id]
assert (row["type"], row["content_text"], row["author"]) == (row_type, display, "agent")
- assert json.loads(row["metadata_json"])["delivery"] == {"state": "pending", "parts": []}
# Every inserted row answers the Turn's initial input, not the steer's surface.
inserted = [rows[written[1].row_id], rows[written[7].row_id], *events]
assert {(row["platform"], row["scope_id"]) for row in inserted} == {("slack", home)}
@@ -362,51 +362,6 @@ async def test_fork_chain_reads_the_ancestry_up_to_each_anchor(engine) -> None:
assert early.context_seq == 2
-async def test_outbox_replays_pending_responses_until_every_part_is_confirmed(engine) -> None:
- with engine.begin() as conn:
- home = _scope(conn, "C-home")
- _session(conn, "ses_main", home)
- consumed = _row(conn, "ses_main", home, "go")
- store = SQLiteTranscriptStore(engine)
- await store.consume_input("ses_main", consumed, _user("go"))
- narration = await store.append_response("ses_main", _assistant("step", call_id="call_1"), final=False)
- await store.append_tool_result("ses_main", _tool_result("call_1", "ok"), details={})
- # A response with nothing to display has no part on any surface.
- silent = AssistantMessage(content=(ToolCallBlock(id="call_2", name="bash"),), origin=ORIGIN, stop_reason="tool_use")
- await store.append_response("ses_main", silent, final=False)
- await store.append_tool_result("ses_main", _tool_result("call_2", "ok"), details={})
- reply = await store.append_response("ses_main", _assistant("answer"), final=True)
-
- pending = await store.pending_deliveries("ses_main")
- assert [(item.row_id, item.context_seq, item.final, item.text, item.parts) for item in pending] == [
- (narration.row_id, 2, False, "step", ()),
- (reply.row_id, 6, True, "answer", ()),
- ]
- assert pending[1].message == reply.message
-
- assert await store.record_delivery_part("ses_main", narration.row_id, index=0, count=1) is True
- # A reply split in two stays pending until both parts are confirmed, and a
- # retried part keeps its first receipt.
- assert await store.record_delivery_part("ses_main", reply.row_id, index=1, count=2, native_message_id="b") is False
- assert await store.record_delivery_part("ses_main", reply.row_id, index=1, count=2, native_message_id="x") is False
- [still_pending] = await store.pending_deliveries("ses_main")
- assert still_pending.row_id == reply.row_id
- assert [part and part["native_message_id"] for part in still_pending.parts] == [None, "b"]
- with pytest.raises(TranscriptError):
- await store.record_delivery_part("ses_main", reply.row_id, index=0, count=3)
- assert await store.record_delivery_part("ses_main", reply.row_id, index=0, count=2, native_message_id="a") is True
-
- assert await store.pending_deliveries("ses_main") == []
- with engine.connect() as conn:
- delivery = json.loads(
- conn.execute(select(messages.c.metadata_json).where(messages.c.id == reply.row_id)).scalar_one()
- )["delivery"]
- assert delivery["state"] == "delivered"
- assert [part["native_message_id"] for part in delivery["parts"]] == ["a", "b"]
- with pytest.raises(TranscriptError):
- await store.record_delivery_part("ses_main", consumed, index=0, count=1)
-
-
async def test_a_cancelled_write_raises_only_after_its_commit_settled(engine) -> None:
with engine.begin() as conn:
home = _scope(conn, "C-home")
@@ -450,3 +405,57 @@ async def test_payloads_that_would_not_read_back_unchanged_are_refused(engine, v
with pytest.raises(ValueError):
await store.append_tool_result("ses_main", _tool_result("call_1", "ok"), details={"value": value})
assert list(await store.load("ses_main")) == [entry]
+
+
+async def test_the_display_copy_commits_with_its_row_and_never_reaches_the_context(engine) -> None:
+ with engine.begin() as conn:
+ home = _scope(conn, "C-home")
+ _session(conn, "ses_main", home)
+ consumed = _row(conn, "ses_main", home, "go")
+
+ def render(message, *, final):
+ body = "\n".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
+ return f"{body} (shown)" if final else body.upper()
+
+ store = SQLiteTranscriptStore(engine, render=render)
+ await store.consume_input("ses_main", consumed, _user("go"))
+ narration = await store.append_response("ses_main", _assistant("step", call_id="call_1"), final=False)
+ await store.append_tool_result("ses_main", _tool_result("call_1", "ok"), details={})
+ reply = await store.append_response("ses_main", _assistant("答案"), final=True)
+
+ with engine.connect() as conn:
+ shown = dict(
+ conn.execute(
+ select(messages.c.id, messages.c.content_text).where(
+ messages.c.id.in_([narration.row_id, reply.row_id])
+ )
+ ).all()
+ )
+ assert shown == {narration.row_id: "STEP", reply.row_id: "答案 (shown)"}
+ # The model copy is the response verbatim; the display copy is not context.
+ assert [entry.message for entry in await store.load("ses_main") if entry.kind == "response"] == [
+ narration.message,
+ reply.message,
+ ]
+
+
+async def test_a_call_instance_is_settled_once_whoever_writes(engine) -> None:
+ with engine.begin() as conn:
+ home = _scope(conn, "C-home")
+ _session(conn, "ses_main", home)
+ consumed = _row(conn, "ses_main", home, "go")
+ store = SQLiteTranscriptStore(engine)
+ await store.consume_input("ses_main", consumed, _user("go"))
+ await store.append_response("ses_main", _assistant("step", call_id="call_1"), final=False)
+
+ # Two writers settle the same open call (a run and a recovery pass): one result row.
+ first = await store.append_tool_result("ses_main", _tool_result("call_1", "ok"), details={})
+ second = await store.append_tool_result("ses_main", _tool_result("call_1", "again"), details={})
+
+ assert second.row_id == first.row_id and second.message == first.message
+ results = [entry for entry in await store.load("ses_main") if entry.kind == "tool_result"]
+ assert [entry.row_id for entry in results] == [first.row_id]
+ # A later response that reuses the id is a new call instance, settled on its own.
+ await store.append_response("ses_main", _assistant("again", call_id="call_1"), final=False)
+ later = await store.append_tool_result("ses_main", _tool_result("call_1", "second call"), details={})
+ assert later.row_id != first.row_id
diff --git a/tests/test_avibe_agent.py b/tests/test_avibe_agent.py
new file mode 100644
index 000000000..47d219f01
--- /dev/null
+++ b/tests/test_avibe_agent.py
@@ -0,0 +1,2554 @@
+"""Avibe Agent backend adapter (``modules/agents/avibe``) over Avibe's real rows.
+
+Properties, each through the adapter's real boundaries (the transcript store on
+a temporary SQLite database, the Delivery rows, and the shared outbound
+dispatcher), with a scripted provider and test-owned tools:
+
+* a Workbench Turn and an IM Turn commit the same context rows and show the
+ same reply once, and every request equals the context rebuilt from the
+ tables (A10);
+* a P1 steer enters the running loop after the tool batch, even when its row
+ appears after the steer was accepted;
+* Stop aborts the run and settles the Turn as stopped;
+* a committed row is delivered through the shared dispatcher, which writes its
+ display into that row instead of persisting a second one;
+* resume settles open tool calls and admits accepted, unconsumed inputs before
+ the next model call, never running the model on its own (T2, T3, T4);
+* failures show localized copy in English and Chinese.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, Optional
+
+import pytest
+from sqlalchemy import select, update
+
+from core.agent_core.agent.recovery import UNRECORDED_EFFECT
+from core.agent_core.ai.provider import Done
+from core.agent_core.harness.projection import project
+from core.agent_core.messages import AssistantMessage, TextBlock, ToolCallBlock, ToolResultMessage, UserMessage, text
+from core.agent_core.tools.base import JobStatus, ToolResult
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
+from modules.agents.avibe import AvibeAgent
+from modules.agents.avibe.errors import _KIND_KEYS, error_key
+from modules.agents.avibe.tools import ToolSuite, local_tool_suite
+from modules.agents.base import AgentRequest
+from modules.agents.model_hub import ModelHubLaunch
+from modules.im import MessageContext
+from storage import message_deliveries
+from storage.agent_transcript import resolve_fork_anchor_seq
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_events, agent_sessions, messages, session_turns
+from storage.settings_service import upsert_scope
+from tests.agent_core.fakes import ORIGIN, FakeJobHost, FakeTool, ScriptedProvider, assistant
+from vibe.i18n import t as i18n_t
+
+NOW = "2026-10-02T00:00:00.000000Z"
+SESSION = "ses_avibe"
+
+
+def engine():
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ yield engine
+ engine.dispose()
+
+
+def published(monkeypatch) -> list[tuple[str, dict]]:
+ from core.inbox_events import bus
+
+ events: list[tuple[str, dict]] = []
+ monkeypatch.setattr(bus, "publish", lambda name, payload: events.append((name, payload)))
+ return events
+
+
+class _Formatter:
+ def format_toolcall(self, name: str, arguments: Optional[dict] = None, get_relative_path=None) -> str:
+ return f"🔧 {name} {json.dumps(arguments or {}, sort_keys=True)}"
+
+ def format_toolcall_label(self, name: str, arguments: Optional[dict] = None, get_relative_path=None) -> str:
+ return f"🔧 {name}"
+
+ def format_result_footer(self, subtype: str, *_args: Any, **_kwargs: Any) -> str:
+ return "❌ failed" if subtype == "error" else "✅ done"
+
+
+class _IMClient:
+ """Records every send; ``fail_sends`` names 1-based send attempts the platform rejects.
+
+ ``routes`` records ``(channel, route, text)``: ``reply`` for the result path
+ (native Markdown sender), ``message`` for a plain send such as the process log.
+ """
+
+ def __init__(self) -> None:
+ self.formatter = _Formatter()
+ self.sent: list[str] = []
+ self.routes: list[tuple[str, str, str]] = []
+ self.uploads: list[str] = []
+ self.attempts = 0
+ self.fail_sends: set[int] = set()
+ self.fail_uploads = 0
+ # 1-based attempts whose send "succeeds" without evidence, and uploads that return this.
+ self.send_results: dict[int, Any] = {}
+ self.upload_results: list[Any] = []
+
+ def should_use_thread_for_reply(self) -> bool:
+ return False
+
+ def supports_message_editing(self, context=None) -> bool:
+ return context is not None and context.platform != "wechat"
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None, subtext=None, *, _route="message"):
+ self.attempts += 1
+ if self.attempts in self.fail_sends:
+ raise RuntimeError("the platform rejected this part")
+ if self.attempts in self.send_results:
+ return self.send_results[self.attempts]
+ self.sent.append(text)
+ self.routes.append((context.channel_id, _route, text))
+ return f"im-{self.attempts}"
+
+ async def send_markdown_message(self, context, text, keyboard=None, subtext=None):
+ return await self.send_message(context, text, subtext=subtext, _route="reply")
+
+ async def upload_file_from_path(self, context, file_path, title=None):
+ if self.fail_uploads:
+ self.fail_uploads -= 1
+ raise RuntimeError("the platform rejected the upload")
+ if self.upload_results:
+ return self.upload_results.pop(0)
+ self.uploads.append(file_path)
+ return f"file-{len(self.uploads)}"
+
+ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None, subtext=None):
+ return await self.send_message(context, text, parse_mode=parse_mode)
+
+ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None, subtext=None):
+ return True
+
+
+class _SettingsManager:
+ def __init__(self) -> None:
+ self.hidden: set[str] = set()
+
+ def _canonicalize_message_type(self, message_type: str) -> str:
+ return message_type
+
+ def is_message_type_hidden(self, settings_key: str, canonical_type: str) -> bool:
+ return canonical_type in self.hidden
+
+
+class _Controller:
+ """The controller surface the adapter and the shared dispatcher use, over real rows."""
+
+ def __init__(self, engine, platform: str, *, language: str = "en") -> None:
+ self.engine = engine
+ self.platform = platform
+ self.config = SimpleNamespace(
+ platform=platform,
+ language=language,
+ reply_enhancements=True,
+ show_duration=False,
+ include_time_info=False,
+ include_user_info=False,
+ )
+ self.im_client = _IMClient()
+ self.settings_manager = _SettingsManager()
+ self.sessions = SimpleNamespace(bind_agent_session_by_id=lambda session_id, *_args, **_kwargs: session_id)
+ self.session_handler = SimpleNamespace(finalize_scheduled_delivery=lambda *_args: None)
+ self.terminals: list[dict] = []
+ self.terminal_texts: list[Optional[str]] = []
+ self.released: list[str] = []
+ self.started: list[Optional[str]] = []
+ self.hub_calls: list[str] = []
+ self.hub_protocol = "anthropic"
+ self.agent: Optional[AvibeAgent] = None
+ self.agent_service = SimpleNamespace(
+ mark_runtime_turn_started=self._native_start,
+ release_runtime_turn=lambda context, **_kw: self.released.append(_turn(context)),
+ )
+ self.session_turns = SimpleNamespace(
+ on_terminal_result=self._terminal,
+ on_terminal_delivery_complete=lambda _context: None,
+ model_hub_turn_id_for_task=lambda: None,
+ _build_context=lambda session_id: _context(platform, session_id, turn_id="redelivery", delivery_id=""),
+ )
+ self.model_hub_runtime = SimpleNamespace(resolve=self._resolve)
+ self.message_dispatcher = ConsolidatedMessageDispatcher(self)
+
+ # --- controller ---------------------------------------------------------
+
+ def get_settings_manager_for_context(self, context):
+ return self.settings_manager
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+ def _get_settings_key(self, context):
+ return context.channel_id
+
+ def _get_session_key(self, context):
+ return f"{context.platform}::{context.channel_id}"
+
+ async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", **kwargs):
+ return await self.message_dispatcher.emit_agent_message(context, message_type, text, parse_mode, **kwargs)
+
+ # --- collaborators --------------------------------------------------------
+
+ def _terminal(self, context, *, is_error, settled_by, terminal_evidence) -> None:
+ self.terminals.append({"turn": _turn(context), "is_error": is_error, "settled_by": settled_by})
+ self.terminal_texts.append(terminal_evidence.get("result_text"))
+
+ async def _resolve(self, backend, requested_model, *, process_scope=None, turn_id=None) -> ModelHubLaunch:
+ self.hub_calls.append(requested_model)
+ return ModelHubLaunch(
+ backend=backend,
+ channel="hub",
+ requested_model=requested_model,
+ target_model=requested_model,
+ runtime_model=requested_model,
+ source_id="src_test",
+ gateway_base_url="http://hub.invalid/avibe",
+ gateway_token="hub-token",
+ context_window=32000,
+ max_output_tokens=4096,
+ supports_tools=True,
+ protocol=self.hub_protocol,
+ provider="test-provider",
+ supports_images=True,
+ )
+
+ def _native_start(self, context, *, activation_identity=None) -> None:
+ """The Turn owner's native start: bind the steer identity, materialize the input row."""
+ turn_id = _turn(context)
+ target = ActiveSteerTarget("runtime", turn_id, context, None, self.agent)
+ # Outside a run (a crash simulation), the identity a previous process's adapter bound.
+ native = self.agent.steering_native_turn_id(target) or f"avibe:previous-process:{turn_id}"
+ self.started.append(native)
+ with self.engine.begin() as conn:
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key="runtime",
+ runtime_turn_id=turn_id,
+ native_turn_id=native,
+ )
+ assert message_deliveries.materialize_start_acceptance(conn, turn_id=turn_id, evidence={"kind": "test"})
+
+
+def _turn(context) -> str:
+ return str((context.platform_specific or {}).get("turn_token") or "")
+
+
+def _context(platform: str, session_id: str, *, turn_id: str, delivery_id: str) -> MessageContext:
+ return MessageContext(
+ user_id="u1",
+ channel_id=session_id if platform == "avibe" else "C1",
+ platform=platform,
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"id": session_id, "agent_backend": "avibe"},
+ "workbench_session_id": session_id if platform == "avibe" else None,
+ "platform": platform,
+ "turn_token": turn_id,
+ "delivery_id": delivery_id,
+ },
+ )
+
+
+async def _unused_renderer(*_args) -> ToolResult:
+ return ToolResult((text("unused"),))
+
+
+class _Harness:
+ def __init__(
+ self, engine, tmp_path: Path, platform: str, scripts, *, tools=None, suite=None, language="en", session_id=SESSION,
+ providers=None,
+ ):
+ self.session_id = session_id
+ self.engine = engine
+ self.platform = platform
+ self.tmp_path = tmp_path
+ self.controller = _Controller(engine, platform, language=language)
+ self.provider = ScriptedProvider(scripts)
+ self.providers = providers or (lambda protocol: self.provider)
+ self.jobs = FakeJobHost()
+ self.tools = list(tools or [FakeTool("echo")])
+ self.suite = suite or ToolSuite(
+ jobs=self.jobs,
+ create_tools=lambda jobs, sink: list(self.tools),
+ render_recovered=_unused_renderer,
+ find_job=lambda session_id, call_id, **_: None,
+ )
+ self.agent = self.new_agent()
+ self._turns = 0
+
+ def new_agent(self) -> AvibeAgent:
+ """A fresh adapter over the same rows: what a restarted process starts with."""
+ agent = AvibeAgent(
+ self.controller,
+ engine=self.engine,
+ providers=self.providers,
+ tool_suite=self.suite,
+ state_dir=self.tmp_path / "agent_core",
+ )
+ self.controller.agent = agent
+ self.agent = agent
+ return agent
+
+ def scope(self) -> str:
+ with self.engine.connect() as conn:
+ return conn.execute(
+ select(messages.c.scope_id).where(messages.c.session_id == self.session_id).limit(1)
+ ).scalar() or _SCOPES[self.platform]
+
+ def request(self, body: str) -> AgentRequest:
+ """An input admitted through the real Delivery path, claimed for a new Turn."""
+ self._turns += 1
+ turn_id = f"turn_{self._turns}_{id(self)}"
+ delivery_id = f"dlv_{turn_id}"
+ with self.engine.begin() as conn:
+ # The Turn owner settles the previous Turn before it claims the next one.
+ conn.execute(
+ update(session_turns)
+ .where(session_turns.c.session_id == self.session_id, session_turns.c.state != "terminal")
+ .values(state="terminal", terminal_outcome="completed", terminal_at=NOW)
+ )
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=self.session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=_SCOPES[self.platform],
+ session_id=self.session_id,
+ platform=self.platform,
+ author="user",
+ source="user",
+ message_type="user",
+ text=body,
+ ),
+ dispatch_text=body,
+ now=NOW,
+ )
+ message_deliveries.claim_start_batch(
+ conn, turn_id=turn_id, session_id=self.session_id, backend="avibe", deliveries=[delivery], dispatch_text=body
+ )
+ context = _context(self.platform, self.session_id, turn_id=turn_id, delivery_id=delivery_id)
+ return AgentRequest(
+ context=context,
+ message=body,
+ user_message=body,
+ working_path=str(self.tmp_path),
+ base_session_id=self.session_id,
+ composite_session_id=self.session_id,
+ session_key=f"{self.platform}::{context.channel_id}",
+ vibe_agent_model="test-model",
+ )
+
+ def open_steer(self, body: str, turn_id: str, native_turn_id: str) -> tuple[str, str]:
+ delivery_id = f"dlv_steer_{body[:8].replace(' ', '_')}"
+ attempt_id = f"att_{delivery_id}"
+ with self.engine.begin() as conn:
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=self.session_id,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=_SCOPES[self.platform],
+ session_id=self.session_id,
+ platform=self.platform,
+ author="user",
+ source="user",
+ message_type="user",
+ text=body,
+ ),
+ dispatch_text=body,
+ now=NOW,
+ )
+ assert message_deliveries.open_steer_attempt(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_turn_id,
+ )
+ return delivery_id, attempt_id
+
+ def accept_steer(self, delivery_id: str, attempt_id: str, turn_id: str) -> None:
+ """What ``SessionTurnManager._finish_steer`` commits after an ACCEPTED receipt."""
+ with self.engine.begin() as conn:
+ assert message_deliveries.materialize_steer_acceptance(
+ conn, leader_delivery_id=delivery_id, expected_attempt_id=attempt_id, turn_id=turn_id, evidence={}
+ )
+
+ def rows(self, message_type: str) -> list[dict]:
+ with self.engine.connect() as conn:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(messages).where(messages.c.session_id == self.session_id, messages.c.type == message_type)
+ ).mappings()
+ ]
+
+ async def context_rows(self):
+ return list(await self.agent.store.load(self.session_id))
+
+
+_SCOPES: dict[str, str] = {}
+
+
+def session(engine):
+ """One Avibe Agent Session, with a Workbench project scope and an IM channel scope."""
+ with engine.begin() as conn:
+ _SCOPES["avibe"] = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_1", now=NOW)
+ for platform in ("telegram", "wechat"):
+ _SCOPES[platform] = upsert_scope(conn, platform=platform, scope_type="channel", native_id="C1", now=NOW)
+ _insert_session(conn, SESSION, _SCOPES["avibe"])
+ return SESSION
+
+
+def _insert_session(conn, session_id: str, scope_id: str, metadata: Optional[dict] = None) -> None:
+ conn.exec_driver_sql(
+ "insert into agent_sessions (id, scope_id, agent_name, agent_backend, agent_variant, session_anchor, "
+ "workdir, native_session_id, status, visibility, pinned, agent_status, metadata_json, created_at, "
+ "updated_at, last_active_at) values (?, ?, 'avibe', 'avibe', 'avibe', ?, '/tmp', ?, 'active', "
+ "'foreground', 0, 'idle', ?, ?, ?, ?)",
+ (session_id, scope_id, session_id, session_id, json.dumps(metadata or {}), NOW, NOW, NOW),
+ )
+
+
+def _tool_turn() -> list:
+ call = ToolCallBlock(id="call_1", name="echo", arguments={"path": "src"})
+ return [[Done(assistant("Listing.", calls=(call,)))], [Done(assistant("两个文件。"))]]
+
+
+def _shape(entries) -> list[tuple]:
+ """Context rows without their row ids, which differ per Session."""
+ return [(entry.context_seq, entry.kind, entry.message) for entry in entries]
+
+
[email protected]("platform", ["avibe", "telegram"])
+async def test_a_turn_commits_its_context_once_and_shows_the_reply_once(
+ engine, session, tmp_path, published, platform
+) -> None:
+ harness = _Harness(engine, tmp_path, platform, _tool_turn())
+ request = harness.request("看一下目录")
+
+ await harness.agent.handle_message(request)
+
+ rows = await harness.context_rows()
+ assert [entry.kind for entry in rows] == ["input", "response", "tool_result", "response"]
+ environment, typed = rows[0].message.content
+ assert environment.text.startswith("<environment>\ncwd: ") and typed == TextBlock(text="看一下目录")
+ # The clock fields follow include_time_info (off here), as every input prefix does.
+ assert "date:" not in environment.text and "timezone:" not in environment.text
+ # The steer identity existed when the Turn owner bound the native start.
+ [native] = harness.controller.started
+ assert native.startswith("avibe:") and native.endswith(f":{_turn(request.context)}")
+ # A10: every request is the context rebuilt from the tables at that point.
+ assert [request_.messages for request_ in harness.provider.requests] == [
+ project(rows[:1]).messages,
+ project(rows[:3]).messages,
+ ]
+ assert harness.provider.requests[0].endpoint.base_url == "http://hub.invalid/avibe/v1"
+ # One row per response: the dispatcher wrote its display into the committed rows, never a copy.
+ [result] = harness.rows("result")
+ [narration] = harness.rows("assistant")
+ assert result["id"] == rows[3].row_id and result["content_text"] == "两个文件。"
+ assert narration["id"] == rows[1].row_id
+ assert harness.controller.terminals == [
+ {"turn": _turn(request.context), "is_error": False, "settled_by": "terminal_result"}
+ ]
+ if platform == "avibe":
+ announced = [payload["id"] for name, payload in published if name == "message.new"]
+ assert announced.count(result["id"]) == 1
+ # The model payload is context, never part of a message a client receives.
+ assert not any("model" in (payload.get("content") or {}) for name, payload in published if name == "message.new")
+ else:
+ assert harness.controller.im_client.sent.count("两个文件。") == 1
+ assert harness.controller.im_client.sent[0] == "Listing."
+
+
+async def test_a_stop_before_dispatch_settles_the_turn_as_stopped(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("an answer nobody wants"))]])
+ resolving, release = asyncio.Event(), asyncio.Event()
+ resolve = harness.controller._resolve
+
+ async def slow_route(*args, **kwargs):
+ resolving.set()
+ await release.wait()
+ return await resolve(*args, **kwargs)
+
+ # Stop arrives while Model Hub is still resolving the route, before anything is dispatched.
+ harness.controller.model_hub_runtime = SimpleNamespace(resolve=slow_route)
+ request = harness.request("long question")
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await resolving.wait()
+
+ assert await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"})) is True
+ release.set()
+ await running
+
+ assert harness.controller.started == [] and harness.provider.requests == []
+ assert harness.controller.terminals == [
+ {"turn": _turn(request.context), "is_error": False, "settled_by": "stopped"}
+ ]
+
+
+async def test_a_setup_failure_after_the_route_resolved_fails_the_hub_attempt(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ import core.system_prompt_injection as injection
+
+ reported: list[str] = []
+
+ async def record_native_failure(context, diagnostic) -> bool:
+ reported.append(diagnostic)
+ return False
+
+ def broken(**_kwargs):
+ raise RuntimeError("the skills directory could not be read")
+
+ monkeypatch.setattr(injection, "build_system_prompt_injection", broken)
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("unreachable"))]])
+ harness.controller.model_hub_runtime.record_native_failure = record_native_failure
+
+ await harness.agent.handle_message(harness.request("hello"))
+
+ # Through the same Hub-aware failure path as any other run failure, before any dispatch.
+ assert len(reported) == 1 and harness.controller.started == []
+ assert harness.controller.terminals[-1]["is_error"] is True
+
+
+async def test_committed_rows_keep_the_agent_that_ran_the_turn(engine, session, tmp_path, published) -> None:
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def slow(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("a.py"),))
+
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), tools=[FakeTool("echo", execute=slow)])
+ request = harness.request("list files")
+ request.vibe_agent_name = "avibe"
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ with engine.begin() as conn:
+ # The user picks another Agent while this Turn runs.
+ conn.execute(
+ update(agent_sessions).where(agent_sessions.c.id == SESSION).values(agent_name="reviewer", agent_backend="codex")
+ )
+ release.set()
+ await running
+
+ with engine.connect() as conn:
+ names = {
+ row.author_name
+ for row in conn.execute(
+ select(messages.c.author_name).where(
+ messages.c.session_id == SESSION, messages.c.author == "agent", messages.c.context_seq.is_not(None)
+ )
+ )
+ } | {
+ row.agent_name
+ for row in conn.execute(
+ select(agent_events.c.agent_name).where(
+ agent_events.c.session_id == SESSION, agent_events.c.context_seq.is_not(None)
+ )
+ )
+ }
+ assert names == {"avibe"}
+ with engine.connect() as conn:
+ backends = set(conn.execute(
+ select(agent_events.c.backend).where(agent_events.c.session_id == SESSION, agent_events.c.context_seq.is_not(None))
+ ).scalars())
+ assert backends == {"avibe"}
+
+
+async def test_the_environment_names_watches_without_their_commands(engine, session, tmp_path, published) -> None:
+ from core.watches import ManagedWatch
+
+ secret = "curl -H 'Authorization: Bearer sk-live-secret' https://api.example"
+ watches = [
+ ManagedWatch(id="wch_named", name="nightly sync", session_key="k", session_id=SESSION, shell_command=secret),
+ ManagedWatch(
+ id="wch_job", name=None, session_key="k", session_id=SESSION, shell_command=secret,
+ metadata={"watch_target": {"kind": "job", "job_id": "job_1", "command": secret}},
+ ),
+ ]
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("ok"))]])
+ harness.controller.watch_service = SimpleNamespace(store=SimpleNamespace(list_watches=lambda: watches))
+
+ await harness.agent.handle_message(harness.request("status?"))
+
+ # The block is model context: a Watch is named by its id, name, and kind, never its command.
+ block = (await harness.context_rows())[0].message.content[0].text
+ assert "sk-live-secret" not in block and "curl" not in block
+ assert 'wch_named "nightly sync" command' in block and "wch_job job" in block
+
+
+async def test_a_steer_enters_after_the_tool_batch_even_when_its_row_arrives_late(
+ engine, session, tmp_path, published
+) -> None:
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def slow(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("a.py"),))
+
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), tools=[FakeTool("echo", execute=slow)])
+ request = harness.request("list files")
+ turn_id = _turn(request.context)
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+
+ native = harness.controller.started[0]
+ delivery_id, attempt_id = harness.open_steer("also check tests", turn_id, native)
+ receipt = await harness.agent.steer_active_turn(
+ SteerRequest(SESSION, turn_id, native, "also check tests", attempt_id=attempt_id),
+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),
+ )
+ assert receipt.outcome is SteerOutcome.ACCEPTED
+ release.set()
+ # The Turn owner materializes the steer's row only after the receipt.
+ await asyncio.sleep(0.05)
+ harness.accept_steer(delivery_id, attempt_id, turn_id)
+ await running
+
+ rows = await harness.context_rows()
+ assert [(entry.kind, entry.row_id) for entry in rows[2:4]] == [
+ ("tool_result", rows[2].row_id),
+ ("input", delivery_id),
+ ]
+ assert rows[3].message == UserMessage((text("also check tests"),))
+ assert harness.provider.requests[1].messages == project(rows[:4]).messages
+ # After the run, a steer for the settled Turn is refused and falls back to the queue.
+ late = await harness.agent.steer_active_turn(
+ SteerRequest(SESSION, turn_id, native, "too late", attempt_id="att_none"),
+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),
+ )
+ assert late.outcome is SteerOutcome.NOT_ACTIVE
+
+
+async def test_reconcile_reports_a_steer_attempt_only_from_evidence(engine, session, tmp_path, published) -> None:
+ from core.services.agent_steering import SteerReconcileRequest
+ from modules.im.base import FileAttachment
+
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def slow(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("a.py"),))
+
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), tools=[FakeTool("echo", execute=slow)])
+ request = harness.request("list files")
+ turn_id = _turn(request.context)
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ native = harness.controller.started[0]
+ _delivery_id, attempt_id = harness.open_steer("look at this", turn_id, native)
+ preparing, fail = asyncio.Event(), asyncio.Event()
+
+ async def vanished(*_args, **_kwargs):
+ preparing.set()
+ await fail.wait()
+ raise RuntimeError("the snapshot store refused the image")
+
+ # The steer's image is still being snapshotted when the Turn owner reconciles the attempt.
+ harness.agent.media.snapshot_file = vanished
+ attachment = FileAttachment(name="shot.png", mimetype="image/png", local_path=str(tmp_path / "shot.png"))
+ steering = asyncio.create_task(
+ harness.agent.steer_active_turn(
+ SteerRequest(SESSION, turn_id, native, "look at this", attempt_id=attempt_id, files=(attachment,)),
+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),
+ )
+ )
+ await preparing.wait()
+ reconcile = SteerReconcileRequest(SESSION, turn_id, native, attempt_id)
+
+ async def outcome() -> SteerOutcome:
+ return (await harness.agent.reconcile_steer_attempt(reconcile, None)).outcome
+
+ try:
+ # No evidence the run has the steer, and its live call is in flight: neither accepted nor a negative.
+ assert await outcome() is SteerOutcome.UNKNOWN
+ fail.set()
+ assert (await steering).outcome is SteerOutcome.REFUSED
+ # The live call returned (its receipt may have been lost) while the run goes on in a long tool:
+ # nothing here can settle the attempt any more, so it is not held until the run ends.
+ assert await outcome() is SteerOutcome.NOT_ACTIVE
+ finally:
+ fail.set()
+ release.set()
+ await running
+ assert await outcome() is SteerOutcome.NOT_ACTIVE
+
+
+async def test_reconcile_settles_an_attempt_another_adapter_instance_opened(engine, session, tmp_path, published) -> None:
+ from core.services.agent_steering import SteerReconcileRequest
+
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ request = harness.request("long task")
+ turn_id = _turn(request.context)
+ harness.controller._native_start(request.context)
+ [native] = harness.controller.started
+ _delivery_id, attempt_id = harness.open_steer("and this", turn_id, native)
+ # A retired adapter (the backend disabled and enabled again, even within one second) or a
+ # previous process: the native turn id names the instance that ran the Turn, so no clock
+ # is needed to tell that no call of this adapter can settle the attempt.
+ harness.new_agent()
+
+ receipt = await harness.agent.reconcile_steer_attempt(SteerReconcileRequest(SESSION, turn_id, native, attempt_id), None)
+
+ assert receipt.outcome is SteerOutcome.NOT_ACTIVE
+
+
+async def test_a_run_ended_by_design_still_answers_the_steer_its_turn_accepted(
+ engine, session, tmp_path, published
+) -> None:
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def finish(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("handed off"),), terminate=True)
+
+ call = ToolCallBlock(id="call_1", name="finish", arguments={})
+ harness = _Harness(
+ engine, tmp_path, "telegram",
+ [[Done(assistant("", calls=(call,)))], [Done(assistant("Docs checked too."))]],
+ tools=[FakeTool("finish", execute=finish)],
+ )
+ request = harness.request("wrap up")
+ turn_id = _turn(request.context)
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ native = harness.controller.started[0]
+ delivery_id, attempt_id = harness.open_steer("also check the docs", turn_id, native)
+ receipt = await harness.agent.steer_active_turn(
+ SteerRequest(SESSION, turn_id, native, "also check the docs", attempt_id=attempt_id),
+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),
+ )
+ assert receipt.outcome is SteerOutcome.ACCEPTED
+ release.set()
+ harness.accept_steer(delivery_id, attempt_id, turn_id)
+ await running
+
+ # The terminating tool ended the run before its queue drained; the Turn answers the steer.
+ rows = await harness.context_rows()
+ assert [(entry.kind, entry.row_id) for entry in rows[2:]] == [
+ ("tool_result", rows[2].row_id),
+ ("input", delivery_id),
+ ("response", rows[4].row_id),
+ ]
+ assert harness.provider.requests[1].messages == project(rows[:4]).messages
+ assert harness.controller.im_client.sent.count("Docs checked too.") == 1
+ assert harness.controller.terminals == [
+ {"turn": turn_id, "is_error": False, "settled_by": "terminal_result"}
+ ]
+
+
+async def test_stop_aborts_the_running_tool_and_settles_the_turn_as_stopped(
+ engine, session, tmp_path, published
+) -> None:
+ started = asyncio.Event()
+ observed: list[bool] = []
+
+ async def wait_for_cancel(arguments, ctx):
+ started.set()
+ await ctx.cancel.wait()
+ observed.append(ctx.cancel.cancelled)
+ return ToolResult((text("Command aborted"),), is_error=True)
+
+ harness = _Harness(engine, tmp_path, "telegram", _tool_turn(), tools=[FakeTool("echo", execute=wait_for_cancel)])
+ receipts: list[Optional[str]] = []
+
+ async def finish(_request, *, terminal_emoji=None) -> None:
+ receipts.append(terminal_emoji)
+
+ async def delete_ack_message(_request, **_kwargs) -> None:
+ receipts.append("ack deleted")
+
+ harness.controller.processing_indicator = SimpleNamespace(finish=finish, delete_ack_message=delete_ack_message)
+ request = harness.request("run it")
+ stop = AgentRequest(**{**request.__dict__, "message": "stop"})
+ assert await harness.agent.handle_stop(stop) is False
+ assert stop.stop_failure_reason == "not_active"
+
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ assert await harness.agent.handle_stop(stop) is True
+ await running
+
+ assert observed == [True]
+ assert len(harness.provider.requests) == 1
+ # The ack message goes at native start, and Stop leaves IM's ⏹️ receipt, as for the other backends.
+ assert receipts[:2] == ["ack deleted", "⏹️"]
+ assert harness.controller.terminals == [
+ {"turn": _turn(request.context), "is_error": False, "settled_by": "stopped"}
+ ]
+ assert not any("❌" in sent for sent in harness.controller.im_client.sent)
+
+
+async def test_resume_settles_open_calls_and_admits_unconsumed_inputs_before_the_next_call(
+ engine, session, tmp_path, published
+) -> None:
+ jobs = FakeJobHost()
+ rendered: list[tuple] = []
+
+ async def render(call, job_id, status, watch_id):
+ rendered.append((call.id, job_id, status.state, watch_id))
+ return ToolResult((text(f"Command is still running and is now Watch {watch_id}."),))
+
+ suite = ToolSuite(
+ jobs=jobs,
+ create_tools=lambda jobs_, sink: [FakeTool("bash"), FakeTool("edit")],
+ render_recovered=render,
+ find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ )
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("resumed"))]], suite=suite)
+ # The crashed process: a Turn whose response opened two calls, one with a running job,
+ # and a steer it accepted but never consumed.
+ first = harness.request("fix the test")
+ harness.controller._native_start(first.context)
+ await harness.agent.store.consume_input(
+ SESSION, first.context.platform_specific["delivery_id"], UserMessage((text("fix the test"),))
+ )
+ calls = (
+ ToolCallBlock(id="call_bash", name="bash", arguments={"command": "pytest -q"}),
+ ToolCallBlock(id="call_edit", name="edit", arguments={"path": "a.py", "edits": []}),
+ )
+ await harness.agent.store.append_response(SESSION, assistant("Running.", calls=calls), final=False)
+ jobs.states["job_1"] = JobStatus("running")
+ steer_id, attempt = harness.open_steer("and the docs", _turn(first.context), harness.controller.started[-1])
+ harness.accept_steer(steer_id, attempt, _turn(first.context))
+
+ harness.new_agent()
+ second = harness.request("continue")
+ await harness.agent.handle_message(second)
+
+ rows = await harness.context_rows()
+ assert [(entry.kind, entry.row_id) for entry in rows[2:5]] == [
+ ("tool_result", rows[2].row_id),
+ ("tool_result", rows[3].row_id),
+ ("input", steer_id),
+ ]
+ assert rendered == [("call_bash", "job_1", "running", "watch_job_1")]
+ assert rows[3].message.content == (text(UNRECORDED_EFFECT),)
+ assert rows[5].row_id == second.context.platform_specific["delivery_id"]
+ # The model ran once, for the new input, with everything that was settled before it.
+ [only] = harness.provider.requests
+ assert only.messages == project(rows[:6]).messages
+
+
+async def test_resume_renders_a_recovered_steer_as_the_live_path_would(engine, session, tmp_path, published) -> None:
+ from types import MethodType
+
+ from core.handlers.message_handler import MessageHandler
+ from core.session_turns import SessionTurnManager
+
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]])
+ # The live steer path's owner of sender facts: the Turn owner and the message handler.
+ owner = SessionTurnManager(
+ harness.controller, build_context=lambda sid: _context("avibe", sid, turn_id="", delivery_id="")
+ )
+ owner._engine = engine
+ harness.controller.session_turns._steer_input_metadata = owner._steer_input_metadata
+ handler = SimpleNamespace(_source_session_id=MessageHandler._source_session_id)
+ harness.controller.message_handler = SimpleNamespace(
+ prepare_input_metadata=MethodType(MessageHandler.prepare_input_metadata, handler)
+ )
+ first = harness.request("watch the deploy")
+ turn_id = _turn(first.context)
+ harness.controller._native_start(first.context)
+ await harness.agent.store.consume_input(
+ SESSION, first.context.platform_specific["delivery_id"], UserMessage((text("watch the deploy"),))
+ )
+ with engine.begin() as conn:
+ # Another Session's agent steers this Turn; the process exits before the loop consumes it.
+ steer = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="dlv_agent_steer",
+ session_id=SESSION,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=_SCOPES["avibe"], session_id=SESSION, platform="avibe", author="harness",
+ source="harness", message_type="harness", text="the deploy finished",
+ metadata={"scheduled_provenance": {
+ "task_execution_id": "run_1",
+ "platform_specific": {"task_trigger_kind": "agent_run", "source_session_id": "ses_source"},
+ }},
+ ),
+ dispatch_text="the deploy finished",
+ now=NOW,
+ )
+ assert message_deliveries.open_steer_attempt(
+ conn, steer["id"], expected_version=int(steer["version"]), turn_id=turn_id,
+ attempt_id="att_agent_steer", expected_native_turn_id=harness.controller.started[-1],
+ )
+ assert message_deliveries.materialize_steer_acceptance(
+ conn, leader_delivery_id=steer["id"], expected_attempt_id="att_agent_steer", turn_id=turn_id, evidence={}
+ )
+
+ harness.new_agent()
+ await harness.agent.handle_message(harness.request("anything new?"))
+
+ [recovered] = [entry for entry in await harness.context_rows() if entry.row_id == "dlv_agent_steer"]
+ assert "From: #ses_source" in recovered.message.content[-1].text
+
+
+async def test_a_fork_from_an_earlier_message_continues_only_the_inherited_prefix(
+ engine, session, tmp_path, published
+) -> None:
+ source = _Harness(engine, tmp_path, "avibe", [[Done(assistant("first answer"))], [Done(assistant("later"))]])
+ await source.agent.handle_message(source.request("first question"))
+ [anchor] = source.rows("result")
+ with engine.begin() as conn:
+ # What fork reservation records (core/services/session_fork.py, C-5 section 4).
+ _insert_session(
+ conn,
+ "ses_child",
+ _SCOPES["avibe"],
+ {
+ "created_via": "session_fork",
+ "fork_source_session_id": SESSION,
+ "fork_source_message_id": anchor["id"],
+ "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, anchor["id"]),
+ },
+ )
+ # The source moves on after the fork; none of it may reach the child.
+ await source.agent.handle_message(source.request("source continues"))
+
+ child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("child answer"))]], session_id="ses_child")
+ await child.agent.handle_message(child.request("child question"))
+
+ inherited = [entry for entry in await source.context_rows() if entry.context_seq <= 2]
+ rows = await child.context_rows()
+ assert rows[:2] == inherited
+ assert [(entry.session_id, entry.context_seq, entry.kind) for entry in rows[2:]] == [
+ ("ses_child", 3, "input"),
+ ("ses_child", 4, "response"),
+ ]
+ [request] = child.provider.requests
+ assert request.messages == project(rows[:3]).messages
+ assert "source continues" not in json.dumps([str(message) for message in request.messages], ensure_ascii=False)
+
+
+async def test_a_fork_settles_a_call_it_inherited_open_with_the_sources_result(
+ engine, session, tmp_path, published
+) -> None:
+ # The source's job is gone (J5 pruned it once the source's call settled).
+ suite = ToolSuite(
+ jobs=FakeJobHost(),
+ create_tools=lambda jobs_, sink: [FakeTool("bash")],
+ render_recovered=_unused_renderer,
+ find_job=lambda *_args, **_kwargs: None,
+ )
+ call = ToolCallBlock(id="call_1", name="bash", arguments={"command": "make release"})
+ source = _Harness(
+ engine, tmp_path, "avibe", [[Done(assistant("Releasing.", calls=(call,)))], [Done(assistant("Released."))]],
+ tools=[FakeTool("bash", result=ToolResult((text("release 1.2.0 published"),)))],
+ )
+ await source.agent.handle_message(source.request("ship it"))
+ narration = (await source.context_rows())[1]
+ with engine.begin() as conn:
+ # A fork from the narration message: its anchor precedes the call's result.
+ _insert_session(
+ conn,
+ "ses_child",
+ _SCOPES["avibe"],
+ {
+ "created_via": "session_fork",
+ "fork_source_session_id": SESSION,
+ "fork_source_message_id": narration.row_id,
+ "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, narration.row_id),
+ },
+ )
+ child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]], suite=suite, session_id="ses_child")
+
+ await child.agent.handle_message(child.request("what happened?"))
+
+ rows = await child.context_rows()
+ assert [(entry.session_id, entry.kind) for entry in rows[:3]] == [
+ (SESSION, "input"), (SESSION, "response"), ("ses_child", "tool_result")
+ ]
+ # The child settles with what the source recorded, not with an uncertain effect.
+ assert rows[2].message.content == (text("release 1.2.0 published"),)
+ assert child.provider.requests[0].messages == project(rows[:4]).messages
+
+
+async def test_a_nested_fork_takes_the_result_of_its_own_call_instance(engine, session, tmp_path, published) -> None:
+ # Grandparent SESSION -> parent ses_parent -> child ses_child; providers reuse the call id.
+ reused = ToolCallBlock(id="call_1", name="bash", arguments={})
+ grandparent = _Harness(
+ engine, tmp_path, "avibe",
+ [[Done(assistant("hello"))], [Done(assistant("", calls=(reused,)))], [Done(assistant("checked"))]],
+ tools=[FakeTool("bash", result=ToolResult((text("the grandparent's own check"),)))],
+ )
+ await grandparent.agent.handle_message(grandparent.request("hi"))
+ [anchor] = grandparent.rows("result")
+ with engine.begin() as conn:
+ _insert_session(conn, "ses_parent", _SCOPES["avibe"], {
+ "created_via": "session_fork",
+ "fork_source_session_id": SESSION,
+ "fork_source_message_id": anchor["id"],
+ "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, anchor["id"]),
+ })
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def release_build(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("release 1.2.0 published"),))
+
+ parent = _Harness(
+ engine, tmp_path, "avibe",
+ [[Done(assistant("Releasing.", calls=(reused,)))], [Done(assistant("Released."))]],
+ tools=[FakeTool("bash", execute=release_build)], session_id="ses_parent",
+ )
+ running = asyncio.create_task(parent.agent.handle_message(parent.request("ship it")))
+ await started.wait()
+ # The grandparent continues on its own and settles its own call_1 first.
+ await grandparent.agent.handle_message(grandparent.request("check something"))
+ release.set()
+ await running
+ narration = next(entry for entry in await parent.context_rows() if entry.session_id == "ses_parent"
+ and entry.kind == "response")
+ with engine.begin() as conn:
+ _insert_session(conn, "ses_child", _SCOPES["avibe"], {
+ "created_via": "session_fork",
+ "fork_source_session_id": "ses_parent",
+ "fork_source_message_id": narration.row_id,
+ "fork_source_context_seq": resolve_fork_anchor_seq(conn, "ses_parent", narration.row_id),
+ })
+ suite = ToolSuite(
+ jobs=FakeJobHost(), create_tools=lambda jobs_, sink: [FakeTool("bash")],
+ render_recovered=_unused_renderer, find_job=lambda *_args, **_kwargs: None,
+ )
+ child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]], suite=suite, session_id="ses_child")
+
+ await child.agent.handle_message(child.request("what happened?"))
+
+ [settled] = [entry for entry in await child.context_rows()
+ if entry.session_id == "ses_child" and entry.kind == "tool_result"]
+ assert settled.message.content == (text("release 1.2.0 published"),)
+
+
+async def test_a_google_hop_is_called_over_chat_at_the_gateway_prefix(engine, session, tmp_path, published) -> None:
+ asked: list[str] = []
+ harness = _Harness(
+ engine, tmp_path, "avibe", [[Done(assistant("hi"))]],
+ providers=lambda protocol: asked.append(protocol) or harness.provider,
+ )
+ harness.controller.hub_protocol = "google"
+
+ await harness.agent.handle_message(harness.request("hello"))
+
+ # Model Hub's google hop is its /v1beta Gemini surface; the agent speaks Chat to /v1.
+ [request] = harness.provider.requests
+ assert asked == ["openai_chat"]
+ assert (request.endpoint.protocol, request.endpoint.base_url, request.endpoint.provider) == (
+ "openai_chat", "http://hub.invalid/avibe/v1", "test-provider"
+ )
+ assert harness.controller.terminals[-1]["is_error"] is False
+
+
[email protected]("kind", sorted({*_KIND_KEYS, "unknown", "context_exhausted"}))
+def test_every_error_kind_has_english_and_chinese_copy(kind: str) -> None:
+ key = error_key(kind)
+ english, chinese = i18n_t(key, "en"), i18n_t(key, "zh")
+ assert english != key and chinese != key and english != chinese
+
+
[email protected]("language", ["en", "zh"])
+async def test_a_failed_run_shows_localized_copy_and_a_refusal_shows_its_explanation_once(
+ engine, session, tmp_path, published, language
+) -> None:
+ refusal = AssistantMessage((), ORIGIN, "refusal")
+ harness = _Harness(
+ engine, tmp_path, "telegram", [[Done(assistant(""))], [Done(refusal)]], language=language
+ )
+ reported: list[str] = []
+
+ async def record_native_failure(context, diagnostic) -> bool:
+ reported.append(diagnostic)
+ return False
+
+ harness.controller.model_hub_runtime.record_native_failure = record_native_failure
+
+ await harness.agent.handle_message(harness.request("say nothing"))
+ await harness.agent.handle_message(harness.request("say something unsafe"))
+
+ sent = harness.controller.im_client.sent
+ empty_copy = i18n_t("avibeAgent.error.emptyResponse", language)
+ refusal_copy = i18n_t("avibeAgent.error.refusal", language)
+ # Each failed final carries its own explanation in its row.
+ assert sent == [empty_copy, refusal_copy]
+ assert sorted(row["content_text"] for row in harness.rows("error")) == sorted([empty_copy, refusal_copy])
+ assert [terminal["is_error"] for terminal in harness.controller.terminals] == [True, True]
+ # A final that failed by itself is a failed Turn for Model Hub too.
+ assert len(reported) == 2
+
+
+async def test_a_run_failure_is_reported_to_model_hub_like_the_other_backends(engine, session, tmp_path, published) -> None:
+ from core.agent_core.ai.provider import ProviderError
+
+ reported: list[str] = []
+
+ async def record_native_failure(context, diagnostic) -> bool:
+ reported.append(diagnostic)
+ return False
+
+ harness = _Harness(
+ engine, tmp_path, "telegram", [[ProviderError("invalid_request", "the served response broke its protocol", False)]]
+ )
+ harness.controller.model_hub_runtime.record_native_failure = record_native_failure
+
+ await harness.agent.handle_message(harness.request("hello"))
+
+ # The served attempt is replaced by the backend's terminal failure, so the Hub's copy can apply.
+ assert len(reported) == 1 and harness.controller.terminals[-1]["is_error"] is True
+
+
+async def test_an_unreadable_image_is_listed_by_path_and_the_turn_runs(engine, session, tmp_path, published) -> None:
+ from modules.im.base import FileAttachment
+
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("seen"))], [Done(assistant("still here"))]])
+ request = harness.request("look")
+ gone = str(tmp_path / "deleted.png")
+ request.files = [FileAttachment(name="deleted.png", mimetype="image/png", local_path=gone)]
+
+ await harness.agent.handle_message(request)
+ await harness.agent.handle_message(harness.request("and now?"))
+
+ # Listed by path as the native backends pass it; the Session is not stuck on it.
+ first = (await harness.context_rows())[0]
+ assert f"- File: {gone} (image/png)" in first.message.content[-1].text
+ assert harness.controller.im_client.sent == ["seen", "still here"]
+
+
+async def test_resume_sends_a_recovered_initial_input_as_its_turns_dispatch_text(
+ engine, session, tmp_path, published
+) -> None:
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]])
+ first = harness.request("deploy it")
+ turn_id = _turn(first.context)
+ with engine.begin() as conn:
+ # What the Turn owner dispatches carries notes the displayed row does not.
+ conn.execute(
+ update(session_turns).where(session_turns.c.id == turn_id).values(
+ dispatch_text="deploy it\n\n[Attachment download errors]\n- notes.pdf: timed out"
+ )
+ )
+ # The process exits after native acceptance, before the loop consumed the input.
+ harness.controller._native_start(first.context)
+
+ harness.new_agent()
+ await harness.agent.handle_message(harness.request("well?"))
+
+ recovered = (await harness.context_rows())[0]
+ assert recovered.row_id == first.context.platform_specific["delivery_id"]
+ assert "[Attachment download errors]" in recovered.message.content[-1].text
+
+
+async def test_a_session_is_titled_from_its_first_prompt(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("done"))]])
+
+ await harness.agent.handle_message(harness.request("Refactor the parser"))
+
+ def title() -> Optional[str]:
+ with engine.connect() as conn:
+ return conn.execute(select(agent_sessions.c.title).where(agent_sessions.c.id == SESSION)).scalar()
+
+ # As the native backends title a session without metadata: derived from the first prompt.
+ await _until(lambda: bool(title()), "the Session was never titled")
+ assert title().startswith("Refactor")
+
+
+async def test_a_route_model_hub_refuses_mid_run_shows_the_hubs_copy(engine, session, tmp_path, published) -> None:
+ from core.handlers.model_hub.service import ModelHubError
+ from modules.agents.model_hub import launch_refusal_copy
+
+ from core.handlers.model_hub.service import produce_turn_outcome
+
+ refused = ModelHubError("engine_down", status=503, turn_outcome=produce_turn_outcome("turn.engine_down"))
+ harness = _Harness(engine, tmp_path, "telegram", _tool_turn())
+ resolve, calls = harness.controller._resolve, []
+
+ async def route(*args, **kwargs):
+ calls.append(1)
+ if len(calls) > 1:
+ raise refused
+ return await resolve(*args, **kwargs)
+
+ # Every model call resolves again; the second one (after the tool batch) is refused.
+ harness.controller.model_hub_runtime = SimpleNamespace(resolve=route)
+
+ await harness.agent.handle_message(harness.request("look"))
+
+ copy = launch_refusal_copy(harness.controller, refused)
+ assert copy and harness.controller.im_client.sent[-1] == f"❌ {copy}"
+
+
+async def test_an_im_stop_finds_the_turn_by_its_runtime_key(engine, session, tmp_path, published) -> None:
+ started = asyncio.Event()
+
+ async def wait_for_cancel(arguments, ctx):
+ started.set()
+ await ctx.cancel.wait()
+ return ToolResult((text("Command aborted"),), is_error=True)
+
+ harness = _Harness(engine, tmp_path, "telegram", _tool_turn(), tools=[FakeTool("echo", execute=wait_for_cancel)])
+ request = harness.request("run it")
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ # IM /stop: the raw channel context names no Session, only the runtime identity.
+ raw = MessageContext(user_id="u1", channel_id="C1", platform="telegram", platform_specific={})
+ stop = AgentRequest(
+ context=raw, message="stop", user_message="", working_path=str(tmp_path),
+ base_session_id=request.base_session_id, composite_session_id=request.composite_session_id,
+ session_key=request.session_key,
+ )
+
+ assert await harness.agent.handle_stop(stop) is True
+ await running
+ assert harness.controller.terminals[-1]["settled_by"] == "stopped"
+
+
+async def test_a_turn_queued_behind_a_stopped_one_settles_the_call_it_left_open(
+ engine, session, tmp_path, published
+) -> None:
+ started, closing, close = asyncio.Event(), asyncio.Event(), asyncio.Event()
+
+ async def wait_for_cancel(arguments, ctx):
+ started.set()
+ await ctx.cancel.wait()
+ raise asyncio.CancelledError()
+
+ class _SlowClose(ScriptedProvider):
+ async def aclose(self) -> None:
+ closing.set()
+ await close.wait()
+
+ provider = _SlowClose([[Done(assistant("", calls=(ToolCallBlock(id="call_1", name="echo", arguments={}),)))],
+ [Done(assistant("next answer"))]])
+ harness = _Harness(engine, tmp_path, "telegram", [], tools=[FakeTool("echo", execute=wait_for_cancel)],
+ providers=lambda protocol: provider)
+ first = harness.request("run it")
+ stopped = asyncio.create_task(harness.agent.handle_message(first))
+ await started.wait()
+ await harness.agent.handle_stop(AgentRequest(**{**first.__dict__, "message": "stop"}))
+ await closing.wait()
+ # The next Turn arrives while the stopped one is still closing its provider.
+ second = asyncio.create_task(harness.agent.handle_message(harness.request("and now?")))
+ await asyncio.sleep(0.05)
+ close.set()
+ await stopped
+ await second
+
+ rows = await harness.context_rows()
+ results = [entry for entry in rows if entry.kind == "tool_result"]
+ assert [entry.message.tool_call_id for entry in results] == ["call_1"]
+ assert results[0].context_seq < next(entry.context_seq for entry in rows if entry.row_id.startswith("dlv_turn_2"))
+
+
[email protected]("phase", ["terminal_result", "preflight_failure"])
+async def test_a_failure_while_settling_reaches_the_shared_owner(engine, session, tmp_path, published, phase) -> None:
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("the answer"))]])
+ if phase == "preflight_failure":
+ async def refuse(*_args, **_kwargs):
+ raise RuntimeError("no source serves this model")
+
+ harness.controller.model_hub_runtime = SimpleNamespace(resolve=refuse)
+ emit = harness.controller.emit_agent_message
+
+ async def broken_terminal(context, message_type, text, *args, **kwargs):
+ if message_type in ("result", "error", "notify"):
+ raise RuntimeError("the settings lookup failed")
+ return await emit(context, message_type, text, *args, **kwargs)
+
+ harness.controller.emit_agent_message = broken_terminal
+
+ # AgentService's fallback releases the runtime gate only if the failure reaches it.
+ with pytest.raises(RuntimeError, match="settings lookup"):
+ await harness.agent.handle_message(harness.request("hello"))
+
+
+async def test_a_refused_model_route_fails_before_the_input_is_written(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "telegram", [])
+
+ async def refuse(*_args, **_kwargs):
+ raise RuntimeError("no source serves this model")
+
+ harness.controller.model_hub_runtime = SimpleNamespace(resolve=refuse)
+ request = harness.request("hello")
+ await harness.agent.handle_message(request)
+
+ assert harness.controller.started == []
+ assert await harness.context_rows() == []
+ assert harness.provider.requests == []
+ assert harness.controller.im_client.sent == [f"❌ {i18n_t('avibeAgent.error.generic', 'en')}"]
+ assert [terminal["is_error"] for terminal in harness.controller.terminals] == [True]
+
+
+# --- settlement and run shape -----------------------------------------------------------
+
+
+async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_path, published) -> None:
+ class _LeakyJobs(FakeJobHost):
+ async def kill(self, job_id, *, reason="killed") -> None:
+ raise RuntimeError("the job's process group cannot be signalled")
+
+ jobs = _LeakyJobs()
+
+ def tools(tracking, sink):
+ async def start_and_leave(arguments, ctx):
+ await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, session_id=ctx.session_id,
+ tool_call_id=ctx.tool_call_id)
+ return ToolResult((text("started"),))
+
+ return [FakeTool("echo", execute=start_and_leave)]
+
+ suite = ToolSuite(jobs=jobs, create_tools=tools, render_recovered=_unused_renderer, find_job=lambda *a: None)
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), suite=suite)
+ harness.controller.config.show_duration = True
+
+ await harness.agent.handle_message(harness.request("start it"))
+
+ # The reply committed before cleanup failed, so only settlement knows the run failed: the
+ # dispatcher writes the failed outcome into that row, as for any failed terminal result.
+ [result] = harness.rows("error")
+ assert result["content_text"] == "两个文件。"
+ assert json.loads(result["content_json"])["result_footer"] == "❌ failed"
+ assert (await harness.context_rows())[-1].row_id == result["id"]
+ assert harness.controller.terminals[-1]["is_error"] is True
+
+
[email protected]("platform", ["avibe", "telegram"])
+async def test_a_silent_final_shows_nothing_and_completes(engine, session, tmp_path, published, platform) -> None:
+ harness = _Harness(engine, tmp_path, platform, [[Done(assistant("<silent>nothing to add</silent>"))]])
+
+ await harness.agent.handle_message(harness.request("fyi"))
+
+ # The reply stays in the context as a hidden response: no transcript row, inbox reply, or
+ # unread result, as the other backends persist nothing visible for a silent reply.
+ final = (await harness.context_rows())[-1]
+ assert final.message.content[0] == text("<silent>nothing to add</silent>")
+ assert harness.rows("result") == [] and harness.rows("error") == []
+ [hidden] = [row for row in harness.rows("assistant") if row["id"] == final.row_id]
+ assert hidden["content_text"] == ""
+ assert harness.controller.im_client.sent == []
+ assert harness.controller.terminals[-1]["is_error"] is False
+
+
+async def test_a_silent_final_whose_run_failed_after_its_commit_is_typed_by_its_row(
+ engine, session, tmp_path, published
+) -> None:
+ class _LeakyJobs(FakeJobHost):
+ async def kill(self, job_id, *, reason="killed") -> None:
+ raise RuntimeError("the job's process group cannot be signalled")
+
+ def tools(tracking, sink):
+ async def start_and_leave(arguments, ctx):
+ await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, session_id=ctx.session_id,
+ tool_call_id=ctx.tool_call_id)
+ return ToolResult((text("started"),))
+
+ return [FakeTool("echo", execute=start_and_leave)]
+
+ call = ToolCallBlock(id="call_1", name="echo", arguments={})
+ suite = ToolSuite(jobs=_LeakyJobs(), create_tools=tools, render_recovered=_unused_renderer, find_job=lambda *a: None)
+ harness = _Harness(
+ engine, tmp_path, "avibe",
+ [[Done(assistant("", calls=(call,)))], [Done(assistant("<silent>nothing to add</silent>"))]], suite=suite,
+ )
+
+ await harness.agent.handle_message(harness.request("start it"))
+
+ # The failure settles through the committed final itself, never a second notice beside it.
+ final = (await harness.context_rows())[-1]
+ assert harness.rows("result") == []
+ [row] = harness.rows("error")
+ assert row["id"] == final.row_id and row["content_text"].strip()
+ assert harness.controller.terminals[-1]["is_error"] is True
+
+
+async def test_a_relative_tool_path_is_shown_under_the_runs_cwd(engine, session, tmp_path, published) -> None:
+ from modules.agents.avibe.agent import _relative_to
+
+ project = tmp_path / "project"
+ shown = _relative_to(str(project))
+ # The tool reads src/app.py under the run's cwd; the line shows it as such, not under the controller's cwd.
+ assert shown("src/app.py") == "src/app.py"
+ assert shown(str(project / "core" / "foo.py")) == "core/foo.py"
+ assert shown("/etc/hosts") == "/etc/hosts"
+
+
+async def test_the_system_prompt_lists_every_tool_the_run_offers(engine, session, tmp_path, published) -> None:
+ harness = _Harness(
+ engine, tmp_path, "avibe", [[Done(assistant("ok"))]],
+ tools=[FakeTool(name) for name in ("read", "bash", "edit", "write")],
+ )
+
+ await harness.agent.handle_message(harness.request("hi"))
+
+ system = harness.provider.requests[0].system
+ assert all(f"- {name}: " in system for name in ("read", "bash", "edit", "write"))
+ assert "Use edit for precise changes" in system
+
+
+async def test_an_idle_session_holds_no_adapter_state(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn() + [[Done(assistant("again"))]])
+
+ await harness.agent.handle_message(harness.request("first"))
+ await harness.agent.handle_message(harness.request("second"))
+
+ assert harness.agent._runtimes == {}
+ assert harness.agent.store._env_state == {} and harness.agent.store._store._locks == {}
+ assert not getattr(harness.agent.store, "_responses", {})
+
+
+async def test_a_background_final_settles_with_its_committed_text(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("the nightly summary"))]])
+ request = harness.request("summarize the night")
+ request.context.platform_specific["suppress_delivery"] = True
+
+ await harness.agent.handle_message(request)
+
+ assert harness.controller.im_client.sent == []
+ assert harness.controller.terminal_texts == ["the nightly summary"]
+ assert harness.controller.terminals[-1]["is_error"] is False
+
+
+async def test_a_stop_while_the_input_is_prepared_starts_no_run(engine, session, tmp_path, published) -> None:
+ from modules.im.base import FileAttachment
+
+ image = tmp_path / "shot.png"
+ image.write_bytes(b"\x89PNG\r\n\x1a\n")
+ harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("an answer nobody wants"))]])
+ preparing, release = asyncio.Event(), asyncio.Event()
+ snapshot = harness.agent.media.snapshot
+
+ async def slow_snapshot(*args, **kwargs):
+ preparing.set()
+ await release.wait()
+ return await snapshot(*args, **kwargs)
+
+ harness.agent.media.snapshot = slow_snapshot
+ request = harness.request("look at this")
+ request.files = [FileAttachment(name="shot.png", mimetype="image/png", local_path=str(image))]
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await preparing.wait()
+
+ assert await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"})) is True
+ release.set()
+ await running
+
+ # The acknowledged Stop holds: no model call, nothing sent, the Turn settles as stopped.
+ assert harness.provider.requests == []
+ assert harness.controller.im_client.sent == []
+ assert harness.controller.terminals == [
+ {"turn": _turn(request.context), "is_error": False, "settled_by": "stopped"}
+ ]
+
+
+async def test_a_stop_after_the_final_reply_committed_loses_the_race(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ import modules.agents.avibe.agent as agent_module
+ from core.agent_core.agent.events import MessageCommitted, RunEnded
+ from core.agent_core.agent.loop import Agent
+
+ stopped = asyncio.Event()
+
+ class _FinalThenStop(Agent):
+ """The loop's event order when Stop lands after the final commit but before the run ends."""
+
+ async def run(self, input, *, turn_id):
+ await self.store.consume_input(self.session_id, input.message_id, input.message)
+ row = await self.store.append_response(self.session_id, assistant("the answer"), final=True)
+ yield MessageCommitted(turn_id, 0, row.row_id, row.context_seq, True)
+ await stopped.wait()
+ yield RunEnded(turn_id, 1, "aborted")
+
+ def abort(self, reason: str = "aborted") -> None:
+ stopped.set()
+
+ async def take_pending_inputs(self):
+ return ()
+
+ monkeypatch.setattr(agent_module, "Agent", _FinalThenStop)
+ harness = _Harness(engine, tmp_path, "telegram", [])
+ request = harness.request("answer me")
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ while not harness.rows("result"):
+ await asyncio.sleep(0.01)
+
+ assert await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"})) is True
+ await running
+
+ assert harness.controller.im_client.sent.count("the answer") == 1
+ assert harness.controller.terminals[-1] == {
+ "turn": _turn(request.context), "is_error": False, "settled_by": "terminal_result"
+ }
+
+
+async def test_the_config_refresh_registers_and_retires_the_backend(engine, monkeypatch) -> None:
+ from config.v2_compat import to_app_config
+ from config.v2_config import V2Config
+ from core.agent_auth_service import AgentAuthService
+
+ agents: dict[str, Any] = {}
+ recovered: list[AvibeAgent] = []
+
+ async def recover(agent) -> list[str]:
+ recovered.append(agent)
+ return []
+
+ # A backend enabled after startup missed the startup recovery (T2, J5); it runs on registration.
+ monkeypatch.setattr(AvibeAgent, "recover_runtime_state", recover)
+
+ async def refresh_runtime_config(name, runtime_config) -> bool:
+ return False
+
+ service = SimpleNamespace(
+ agents=agents,
+ register=lambda agent: agents.__setitem__(agent.name, agent),
+ refresh_runtime_config=refresh_runtime_config,
+ runtime_turn_tokens_for_backend=lambda _backend: {},
+ release_runtime_turn_tokens=lambda _tokens: None,
+ )
+ config = V2Config.default()
+ from modules.agents.avibe.recovery import AvibeRecovery
+
+ controller = SimpleNamespace(
+ agent_service=service, im_client=_IMClient(), settings_manager=_SettingsManager(), config=None
+ )
+ controller.avibe_recovery = AvibeRecovery(controller)
+ owner = AgentAuthService(controller)
+ for enabled in (True, False, True):
+ config.agents.avibe.enabled = enabled
+ config.save()
+ controller.config = to_app_config(config)
+ await owner._apply_backend_runtime_refresh("avibe")
+ assert isinstance(agents.get("avibe"), AvibeAgent) is enabled
+ assert len(recovered) == 2 and recovered[-1] is agents["avibe"]
+
+
+async def test_startup_hands_an_orphaned_foreground_job_to_its_watch(engine, session, tmp_path, published) -> None:
+ jobs = FakeJobHost()
+ rendered: list[tuple] = []
+
+ async def render(call, job_id, status, watch_id):
+ rendered.append((call.id, job_id, watch_id))
+ return ToolResult((text(f"Command is still running and is now Watch {watch_id}."),))
+
+ suite = ToolSuite(
+ jobs=jobs,
+ create_tools=lambda jobs_, sink: [FakeTool("bash")],
+ render_recovered=render,
+ find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ )
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ # The crashed process left a running foreground command, and no Turn will resume this
+ # Session: startup itself must settle the open call.
+ request = harness.request("run the slow suite")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run the slow suite"),))
+ )
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "pytest -q"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ jobs.states["job_1"] = JobStatus("running")
+
+ # A pass that failed before it settled anything runs again in full.
+ harness.new_agent()
+ scan = harness.agent._sessions_with_open_tail
+
+ def unavailable():
+ raise RuntimeError("database is locked")
+
+ harness.agent._sessions_with_open_tail = unavailable
+ with pytest.raises(RuntimeError):
+ await harness.agent.recover_runtime_state()
+ harness.agent._sessions_with_open_tail = scan
+ assert await harness.agent.recover_runtime_state() == []
+ rows = await harness.context_rows()
+ assert rows[-1].kind == "tool_result" and "now Watch watch_job_1" in rows[-1].message.content[0].text
+ # Another process start settles nothing twice.
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ assert await harness.context_rows() == rows
+ assert rendered == [("call_bash", "job_1", "watch_job_1")] and jobs.watches == {"job_1": "watch_job_1"}
+ assert harness.provider.requests == []
+
+
+async def test_startup_recovers_a_session_routed_to_another_agent_since(engine, session, tmp_path, published) -> None:
+ jobs = FakeJobHost()
+
+ async def render(call, job_id, status, watch_id):
+ return ToolResult((text(f"Command is still running and is now Watch {watch_id}."),))
+
+ suite = ToolSuite(
+ jobs=jobs,
+ create_tools=lambda jobs_, sink: [FakeTool("bash")],
+ render_recovered=render,
+ find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ )
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ request = harness.request("run the slow suite")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run the slow suite"),))
+ )
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "pytest -q"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ jobs.states["job_1"] = JobStatus("running")
+ with engine.begin() as conn:
+ # The user switched this Session to another Agent while the command ran; then the process died.
+ conn.execute(
+ update(agent_sessions).where(agent_sessions.c.id == SESSION).values(agent_name="codex", agent_backend="codex")
+ )
+
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ assert jobs.watches == {"job_1": "watch_job_1"}
+ assert (await harness.context_rows())[-1].kind == "tool_result"
+
+
+async def test_recovered_tool_results_keep_the_agent_that_made_the_call(engine, session, tmp_path, published) -> None:
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ request = harness.request("run the slow suite")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run the slow suite"),))
+ )
+ harness.agent.store.bind_agent(SESSION, "builder")
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "pytest -q"})
+ owner = await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ harness.agent.store.bind_agent(SESSION, None)
+ with engine.begin() as conn:
+ # The Session is switched to another Agent; then the process restarts with the call open.
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == SESSION).values(agent_name="reviewer"))
+
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ # Startup T2 writes outside any Turn: the result takes the Agent of the response that made the call.
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.author_name).where(messages.c.id == owner.row_id)).scalar() == "builder"
+ [recovered] = conn.execute(
+ select(agent_events.c.agent_name).where(
+ agent_events.c.session_id == SESSION, agent_events.c.event_type == "tool_result"
+ )
+ ).scalars().all()
+ assert recovered == "builder"
+
+
+async def test_a_provider_that_fails_to_close_does_not_fail_a_delivered_turn(
+ engine, session, tmp_path, published
+) -> None:
+ closed: list[str] = []
+
+ class _Provider(ScriptedProvider):
+ def __init__(self, scripts, name: str, *, fails: bool) -> None:
+ super().__init__(scripts)
+ self.name, self.fails = name, fails
+
+ async def aclose(self) -> None:
+ closed.append(self.name)
+ if self.fails:
+ raise RuntimeError("the connection pool would not close")
+
+ provider = _Provider([[Done(assistant("done"))]], "anthropic", fails=True)
+ harness = _Harness(engine, tmp_path, "telegram", [], providers=lambda protocol: provider)
+
+ await harness.agent.handle_message(harness.request("hi"))
+
+ assert harness.controller.im_client.sent == ["done"]
+ assert harness.controller.terminals[-1]["is_error"] is False
+ assert closed == ["anthropic"]
+ # Every adapter is closed even when an earlier one fails to close.
+ from modules.agents.avibe.models import HubModelRouter
+
+ adapters = {"anthropic": _Provider([], "anthropic", fails=True), "google": _Provider([], "google", fails=False)}
+ router = HubModelRouter(lambda: None, lambda protocol: adapters[protocol])
+ router.provider_for("anthropic"), router.provider_for("google")
+ closed.clear()
+ await router.aclose()
+ assert closed == ["anthropic", "google"]
+
+
+async def test_startup_recovery_never_waits_for_a_running_session(engine, session, tmp_path, published) -> None:
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def slow(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("ok"),))
+
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), tools=[FakeTool("echo", execute=slow)])
+ running = asyncio.create_task(harness.agent.handle_message(harness.request("work")))
+ await started.wait()
+ try:
+ # The running Session's own resume already did T2 and T3; startup recovery must not block on it.
+ await asyncio.wait_for(harness.agent.recover_runtime_state(), timeout=2)
+ finally:
+ release.set()
+ await running
+
+
+# --- narration is live best-effort output; failed finals carry error semantics -------------
+
+
+async def test_im_narration_is_live_best_effort_output(engine, session, tmp_path, published) -> None:
+ call = ToolCallBlock(id="call_1", name="echo", arguments={})
+ shown = _Harness(engine, tmp_path, "telegram", [[Done(assistant("First look.", calls=(call,)))], [Done(assistant("done"))]])
+ await shown.agent.handle_message(shown.request("go"))
+ # Shown live through the process log, like the other backends.
+ assert shown.controller.im_client.routes[0] == ("C1", "message", "First look.")
+
+ failing = _Harness(engine, tmp_path, "telegram", [[Done(assistant("Second look.", calls=(call,)))], [Done(assistant("ok"))]])
+ failing.controller.im_client.fail_sends = {1}
+ await failing.agent.handle_message(failing.request("again"))
+ failing.new_agent()
+ await failing.agent.recover_runtime_state()
+ # Best effort: a failed narration send is not retried; the final reply was delivered.
+ assert "Second look." not in failing.controller.im_client.sent
+ assert failing.controller.im_client.sent.count("ok") == 1
+
+ hidden = _Harness(engine, tmp_path, "telegram", [[Done(assistant("Third look.", calls=(call,)))], [Done(assistant("fine"))]])
+ hidden.controller.settings_manager.hidden = {"assistant"}
+ await hidden.agent.handle_message(hidden.request("once more"))
+ assert "Third look." not in hidden.controller.im_client.sent
+
+
[email protected]("final, row_type", [("answer", "result"), ("empty", "error"), ("refusal", "error")])
+async def test_a_final_is_stored_with_its_outcome_semantics(
+ engine, session, tmp_path, published, final, row_type
+) -> None:
+ message = {
+ "answer": assistant("here it is"),
+ "empty": assistant(""),
+ "refusal": AssistantMessage((), ORIGIN, "refusal"),
+ }[final]
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(message)]])
+
+ await harness.agent.handle_message(harness.request("answer me"))
+
+ [row] = harness.rows(row_type)
+ assert json.loads(row["content_json"])["kind"] == row_type
+ # The row is still the Turn's final response in the context and in delivery.
+ entries = await harness.context_rows()
+ assert entries[-1].kind == "response" and entries[-1].row_id == row["id"]
+ assert [name for name, payload in published if name == "message.new" and payload.get("id") == row["id"]] == [
+ "message.new"
+ ]
+
+
+# --- the dispatcher writes a committed row's display instead of a second row ---------------
+
+_SHIP = "Shipped.\n\n---\n[✅ Merge] | [👀 Review]"
+
+
+ "platform, suppressed, site",
+ [
+ ("avibe", False, "result"),
+ ("telegram", False, "result"),
+ ("avibe", True, "result"),
+ ("telegram", True, "result"),
+ ("avibe", False, "assistant"),
+ ("telegram", True, "assistant"),
+ ],
+)
+async def test_every_persist_site_writes_the_committed_row_instead_of_a_second_one(
+ engine, session, tmp_path, published, platform, suppressed, site
+) -> None:
+ call = ToolCallBlock(id="call_1", name="echo", arguments={})
+ narration, final = (_SHIP, "ok") if site == "assistant" else ("Looking.", _SHIP)
+ harness = _Harness(
+ engine, tmp_path, platform, [[Done(assistant(narration, calls=(call,)))], [Done(assistant(final))]]
+ )
+ request = harness.request("ship it")
+ request.context.platform_specific["suppress_delivery"] = suppressed
+
+ await harness.agent.handle_message(request)
+
+ responses = {entry.row_id: entry.message for entry in await harness.context_rows() if entry.kind == "response"}
+ agent_rows = harness.rows("assistant") + harness.rows("result") + harness.rows("error")
+ # Every row the dispatcher persisted for the agent is a committed response, once.
+ assert sorted(row["id"] for row in agent_rows) == sorted(responses)
+ [row] = [row for row in agent_rows if row["type"] == site]
+ body = json.loads(row["content_json"])
+ assert body["kind"] == site and body["text"] == row["content_text"]
+ # The model payload is untouched: the context still reads the raw reply.
+ assert responses[row["id"]].content[0] == text(_SHIP)
+ assert json.loads(row["metadata_json"]).get("delivery_suppressed", False) is suppressed
+ if site == "result":
+ # The dispatcher's display copy, as for any backend: the quick replies left the text.
+ assert row["content_text"].startswith("Shipped.") and "[✅ Merge]" not in row["content_text"]
+ if platform == "avibe":
+ assert body["quick_replies"] == ["✅ Merge", "👀 Review"]
+
+
+async def _committed_final(harness: _Harness, body: str):
+ """A final response the store committed, before anything delivered it."""
+ request = harness.request("summarize")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("summarize"),))
+ )
+ return request, await harness.agent.store.append_response(SESSION, assistant(body), final=True)
+
+
+def _announced(published, row_id: str) -> int:
+ return sum(1 for name, payload in published if name == "message.new" and payload.get("id") == row_id)
+
+
[email protected]("platform", ["avibe", "telegram"])
+async def test_a_retried_output_is_recognized_by_the_committed_row_it_wrote(
+ engine, session, tmp_path, published, platform
+) -> None:
+ from core.message_output import MessageOutput
+
+ harness = _Harness(engine, tmp_path, platform, [])
+ request, final = await _committed_final(harness, "the summary")
+ output = MessageOutput(idempotency_key="reply", persisted_row_id=final.row_id)
+
+ for _ in range(2):
+ await harness.controller.emit_agent_message(request.context, "result", "the summary", output=output)
+
+ # The committed row carries the output's identity, so the retry is a duplicate.
+ [row] = harness.rows("result")
+ assert row["id"] == final.row_id and row["native_message_id"] == output.native_message_id(request.context)
+ if platform == "avibe":
+ assert _announced(published, final.row_id) == 1
+ else:
+ assert harness.controller.im_client.sent == ["the summary"]
+
+
+async def test_a_committed_row_never_takes_a_native_id_another_row_holds(engine, session, tmp_path, published) -> None:
+ from core.message_mirror import persist_agent_message
+
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ request, first = await _committed_final(harness, "first")
+ later = await harness.agent.store.append_response(SESSION, assistant("later"), final=True)
+ persist_agent_message(request.context, "result", "first", native_message_id="out_1", existing_row_id=first.row_id)
+
+ # A concurrent duplicate of the same output, written into a different committed row.
+ persist_agent_message(request.context, "result", "later", native_message_id="out_1", existing_row_id=later.row_id)
+
+ rows = {row["id"]: row for row in harness.rows("result")}
+ assert rows[first.row_id]["native_message_id"] == "out_1"
+ assert rows[later.row_id]["native_message_id"] is None
+ assert json.loads(rows[later.row_id]["content_json"])["kind"] == "result"
+
+
+async def test_a_suppressed_committed_row_becomes_a_receipt_when_its_output_is_sent(
+ engine, session, tmp_path, published
+) -> None:
+ from core.message_output import MessageOutput
+
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ request, final = await _committed_final(harness, "the nightly summary")
+ output = MessageOutput(idempotency_key="reply", persisted_row_id=final.row_id)
+ background = MessageContext(
+ **{**request.context.__dict__, "platform_specific": {**request.context.platform_specific, "suppress_delivery": True}}
+ )
+
+ await harness.controller.emit_agent_message(background, "result", "the nightly summary", output=output)
+ [local] = harness.rows("result")
+ assert json.loads(local["metadata_json"])["delivery_suppressed"] is True
+ assert _announced(published, final.row_id) == 0
+
+ await harness.controller.emit_agent_message(request.context, "result", "the nightly summary", output=output)
+ [shown] = harness.rows("result")
+ assert shown["id"] == final.row_id and shown["native_message_id"] == local["native_message_id"]
+ assert "delivery_suppressed" not in json.loads(shown["metadata_json"])
+ assert _announced(published, final.row_id) == 1
+
+
+# --- real wiring: the merged tools, job host and Watch hand-over ---------------------------
+
+
+async def _real_job(suite, command: str, *, call_id: str, cwd: Path) -> str:
+ return await suite.jobs.start(
+ command,
+ cwd=str(cwd),
+ env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
+ timeout_s=None,
+ session_id=SESSION,
+ tool_call_id=call_id,
+ )
+
+
+async def _until(predicate, what: str, timeout: float = 10.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while not predicate():
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError(what)
+ await asyncio.sleep(0.05)
+
+
+_TEXT_STREAMS = {
+ "anthropic": (
+ "/avibe/v1/messages",
+ 'data: {"type":"message_start","message":{"usage":{}}}\n\n'
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}\n\n'
+ 'data: {"type":"content_block_stop","index":0}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n',
+ ),
+ "openai_responses": (
+ "/avibe/v1/responses",
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"hi"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":null}}\n\n',
+ ),
+ "openai_chat": (
+ "/avibe/v1/chat/completions",
+ 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n",
+ ),
+}
+
+
[email protected]("hub_protocol", ["anthropic", "openai_responses", "openai_chat", "google"])
+async def test_a_turn_runs_through_the_real_provider_registry(engine, session, tmp_path, published, hub_protocol) -> None:
+ import httpx
+
+ from modules.agents.avibe.models import registry_providers
+
+ wire = "openai_chat" if hub_protocol == "google" else hub_protocol
+ path, body = _TEXT_STREAMS[wire]
+ served = json.dumps({"provider": "upstream", "api": wire, "model": "served-model"}, separators=(",", ":"))
+ seen: list[str] = []
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ seen.append(request.url.path)
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=body
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(
+ engine, tmp_path, "telegram", [], providers=registry_providers(media_loader=None, client=client)
+ )
+ harness.controller.hub_protocol = hub_protocol
+ await harness.agent.handle_message(harness.request("hello"))
+
+ # Each protocol's adapter from the real registry speaks to its gateway path; a google hop is
+ # called over Chat at the gateway prefix; the served origin comes from x-avibe-served-hop.
+ assert seen == [path]
+ final = (await harness.context_rows())[-1].message
+ assert final.content == (TextBlock(text="hi"),)
+ assert (final.origin.provider, final.origin.api, final.origin.model) == ("upstream", wire, "served-model")
+ assert harness.controller.im_client.sent == ["hi"]
+
+
+async def test_a_turn_runs_bash_through_the_real_job_host(engine, session, tmp_path, published) -> None:
+ command = "printf 'hi from bash'"
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})
+ harness = _Harness(
+ engine,
+ tmp_path,
+ "avibe",
+ [[Done(assistant("", calls=(call,)))], [Done(assistant("done"))]],
+ suite=local_tool_suite(str(tmp_path / "jobs")),
+ )
+
+ await harness.agent.handle_message(harness.request("say hi"))
+
+ rows = await harness.context_rows()
+ assert [entry.kind for entry in rows] == ["input", "response", "tool_result", "response"]
+ assert "hi from bash" in rows[2].message.content[0].text and not rows[2].message.is_error
+ assert "hi from bash" in str(harness.provider.requests[1].messages[-1])
+
+
+async def test_bash_runs_with_the_turns_caller_environment(engine, session, tmp_path, published) -> None:
+ from core.caller_context import AVIBE_CALLER_BACKEND_ENV, AVIBE_SESSION_ID_ENV, CALLER_CONTEXT_ENV_NAMES
+
+ # Resolved through PATH, as ordinary project commands and the vibe CLI are.
+ command = "env | sort"
+ call = ToolCallBlock(id="call_env", name="bash", arguments={"command": command})
+ harness = _Harness(
+ engine, tmp_path, "telegram",
+ [[Done(assistant("", calls=(call,)))], [Done(assistant("done"))]],
+ suite=local_tool_suite(str(tmp_path / "jobs")),
+ )
+ request = harness.request("show the environment")
+
+ await harness.agent.handle_message(request)
+
+ output = (await harness.context_rows())[2].message.content[0].text
+ assert not (await harness.context_rows())[2].message.is_error
+ seen = dict(line.split("=", 1) for line in output.splitlines() if "=" in line and line.split("=", 1)[0].isupper())
+ # The service's environment: PATH and HOME, so the command resolved at all.
+ assert seen.get("PATH") and seen.get("HOME")
+ # The Turn's caller provenance, as the other backends give their shells.
+ assert seen[AVIBE_SESSION_ID_ENV] == SESSION
+ assert seen[AVIBE_CALLER_BACKEND_ENV] == "avibe"
+ assert {key for key in seen if key in CALLER_CONTEXT_ENV_NAMES} >= {AVIBE_SESSION_ID_ENV, AVIBE_CALLER_BACKEND_ENV}
+ # The Model Hub gateway token stays in the adapter: never in a command's environment.
+ assert "hub-token" not in output
+
+
[email protected]("state", ["exited", "running"])
+async def test_resume_settles_a_real_bash_job_through_the_real_renderer(
+ engine, session, tmp_path, published, state
+) -> None:
+ from core.watches import ManagedWatchStore
+
+ suite = local_tool_suite(str(tmp_path / "jobs"))
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ request = harness.request("run it")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
+ )
+ command = "printf done" if state == "exited" else "sleep 30"
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ # The crashed process had started the command; nothing committed its result.
+ job_id = await _real_job(suite, command, call_id="call_bash", cwd=tmp_path)
+ try:
+ if state == "exited":
+ await _until(lambda: suite.jobs.status(job_id).state == "exited", "the command never exited")
+
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ result = (await harness.context_rows())[-1]
+ assert result.kind == "tool_result"
+ body = result.message.content[0].text
+ if state == "exited":
+ assert "done" in body and not result.message.is_error
+ else:
+ watch_id = ManagedWatchStore().find_job_watch(job_id)
+ assert watch_id and f"now Watch {watch_id}" in body
+ assert suite.jobs.status(job_id).state == "running"
+ finally:
+ if suite.jobs.status(job_id).state == "running":
+ await suite.jobs.kill(job_id)
+
+
+async def test_resume_settles_a_reused_call_id_from_the_job_its_own_call_started(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ import secrets
+
+ import core.agent_core.tools.jobs as jobs_module
+ from core.watches import ManagedWatchStore
+
+ # The earlier call's job id sorts first, so a lookup by (session, call id) alone finds it.
+ job_ids, token_hex = iter(["0" * 16, "f" * 16]), secrets.token_hex
+ monkeypatch.setattr(jobs_module.secrets, "token_hex", lambda n=None: next(job_ids) if n == 8 else token_hex(n))
+ suite = local_tool_suite(str(tmp_path / "jobs"))
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ first = harness.request("print it")
+ harness.controller._native_start(first.context)
+ await harness.agent.store.consume_input(
+ SESSION, first.context.platform_specific["delivery_id"], UserMessage((text("print it"),))
+ )
+ reused = ToolCallBlock(id="call_0", name="bash", arguments={"command": "printf old"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(reused,)), final=False)
+ old = await _real_job(suite, "printf old", call_id="call_0", cwd=tmp_path)
+ await _until(lambda: suite.jobs.status(old).state == "exited", "the first command never exited")
+ await harness.agent.store.append_tool_result(
+ SESSION, ToolResultMessage("call_0", "bash", (text("old"),)), details={"job_id": old}
+ )
+ await harness.agent.store.append_response(SESSION, assistant("printed"), final=True)
+ # The next Turn's provider reuses call_0; the crash leaves its command running.
+ second = harness.request("wait for it")
+ harness.controller._native_start(second.context)
+ await harness.agent.store.consume_input(
+ SESSION, second.context.platform_specific["delivery_id"], UserMessage((text("wait for it"),))
+ )
+ again = ToolCallBlock(id="call_0", name="bash", arguments={"command": "sleep 30"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(again,)), final=False)
+ current = await _real_job(suite, "sleep 30", call_id="call_0", cwd=tmp_path)
+ try:
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ result = (await harness.context_rows())[-1]
+ watch_id = ManagedWatchStore().find_job_watch(current)
+ assert result.kind == "tool_result" and watch_id and f"now Watch {watch_id}" in result.message.content[0].text
+ assert ManagedWatchStore().find_job_watch(old) is None
+ finally:
+ await suite.jobs.kill(current)
+
+
+def _disabled_controller() -> SimpleNamespace:
+ """A controller with ``agents.avibe`` disabled: no registered adapter, and its single recovery owner."""
+ from modules.agents.avibe.recovery import AvibeRecovery
+
+ controller = SimpleNamespace(
+ agent_service=SimpleNamespace(agents={}),
+ config=SimpleNamespace(avibe=None, platform="avibe", language="en"),
+ im_client=None,
+ settings_manager=SimpleNamespace(),
+ )
+ controller.avibe_recovery = AvibeRecovery(controller)
+ return controller
+
+
+async def test_startup_hands_a_foreground_job_to_its_watch_with_the_backend_disabled(
+ engine, session, tmp_path, published
+) -> None:
+ from core.controller import Controller
+ from core.watches import ManagedWatchStore
+
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=local_tool_suite())
+ request = harness.request("run it")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
+ )
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "sleep 30"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ suite = harness.suite
+ job_id = await _real_job(suite, "sleep 30", call_id="call_bash", cwd=tmp_path)
+ # The process restarts with agents.avibe disabled: no adapter is registered.
+ controller = _disabled_controller()
+ try:
+ await Controller._recover_avibe_agent_runtime_state(controller)
+
+ watch_id = ManagedWatchStore().find_job_watch(job_id)
+ assert watch_id is not None and not controller.avibe_recovery.retrying
+ result = (await harness.context_rows())[-1]
+ assert result.kind == "tool_result" and f"now Watch {watch_id}" in result.message.content[0].text
+ finally:
+ if suite.jobs.status(job_id).state == "running":
+ await suite.jobs.kill(job_id)
+
+
+async def _two_sessions_with_open_calls(engine, tmp_path, suite) -> tuple[_Harness, str, str]:
+ """SESSION's open call has a running job; ses_b's has one that exited."""
+ with engine.begin() as conn:
+ _insert_session(conn, "ses_b", _SCOPES["avibe"])
+ jobs = {}
+ for session_id, command in ((SESSION, "sleep 30"), ("ses_b", "printf done")):
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite, session_id=session_id)
+ request = harness.request("run it")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ session_id, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
+ )
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})
+ await harness.agent.store.append_response(session_id, assistant("", calls=(call,)), final=False)
+ jobs[session_id] = await suite.jobs.start(
+ command, cwd=str(tmp_path), env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
+ timeout_s=None, session_id=session_id, tool_call_id="call_bash",
+ )
+ await _until(lambda: suite.jobs.status(jobs["ses_b"]).state == "exited", "ses_b's job never exited")
+ return harness, jobs[SESSION], jobs["ses_b"]
+
+
+def _hand_over_failing_once(monkeypatch) -> list[str]:
+ """Watch hand-over raises on its first call, as a transient DB or Watch failure would."""
+ import core.watches as watches_module
+ import modules.agents.avibe.recovery as recovery_module
+
+ calls: list[str] = []
+ real = watches_module.hand_over_job
+
+ async def flaky(meta, **kwargs):
+ calls.append(str(meta.get("job_id")))
+ if len(calls) == 1:
+ raise RuntimeError("the Watch store is locked")
+ return await real(meta, **kwargs)
+
+ monkeypatch.setattr(watches_module, "hand_over_job", flaky)
+ monkeypatch.setattr(recovery_module, "RETRY_DELAYS_S", (0.05, 0.05))
+ monkeypatch.setattr(recovery_module, "RETRY_PERIOD_S", 0.05)
+ return calls
+
+
+async def _results(engine, session_id: str) -> list[str]:
+ with engine.connect() as conn:
+ return list(conn.execute(
+ select(agent_events.c.content_text).where(
+ agent_events.c.session_id == session_id, agent_events.c.event_type == "tool_result"
+ )
+ ).scalars())
+
+
[email protected]("registered", [True, False])
+async def test_recovery_retries_a_session_it_could_not_settle(
+ engine, session, tmp_path, published, monkeypatch, registered
+) -> None:
+ from core.watches import ManagedWatchStore
+
+ _hand_over_failing_once(monkeypatch)
+ harness, running, _exited = await _two_sessions_with_open_calls(engine, tmp_path, local_tool_suite())
+ controller = _disabled_controller()
+ if registered:
+ controller.agent_service.agents["avibe"] = harness.new_agent()
+ recovery = controller.avibe_recovery
+ try:
+ # The first pass settles ses_b and reports SESSION, never success over a failure.
+ assert await recovery.start() == [SESSION]
+ assert recovery.retrying and len(await _results(engine, "ses_b")) == 1
+ # Without any Turn, the single owner's retry hands SESSION's running job to its Watch.
+ await _until(lambda: ManagedWatchStore().find_job_watch(running) is not None, "the retry never handed over")
+ await _until(lambda: not recovery.retrying, "the retry never finished")
+ assert len(await _results(engine, SESSION)) == 1 and len(await _results(engine, "ses_b")) == 1
+ finally:
+ await recovery.stop()
+ await harness.suite.jobs.kill(running)
+
+
+async def test_two_recovery_passes_racing_on_one_open_call_settle_it_once(engine, session, tmp_path, published) -> None:
+ jobs = FakeJobHost()
+ both_rendering, renders = asyncio.Event(), []
+
+ async def render(call, job_id, status, watch_id):
+ # Both passes have loaded the open call before either commits its result.
+ renders.append(job_id)
+ if len(renders) == 2:
+ both_rendering.set()
+ await both_rendering.wait()
+ return ToolResult((text("done"),))
+
+ suite = ToolSuite(
+ jobs=jobs, create_tools=lambda jobs_, sink: [FakeTool("bash")], render_recovered=render,
+ find_job=lambda session_id, call_id, **_: "job_1",
+ )
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ request = harness.request("run it")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
+ )
+ call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "make"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ jobs.states["job_1"] = JobStatus("exited", exit_code=0)
+ # Two adapters (two owners' worth of locks) recover the same Session at once.
+ first, second = harness.new_agent(), harness.new_agent()
+
+ await asyncio.gather(first.recover_runtime_state(), second.recover_runtime_state())
+
+ results = [entry for entry in await harness.context_rows() if entry.kind == "tool_result"]
+ assert len(renders) == 2 and len(results) == 1
+
+
+async def test_enabling_the_backend_hands_recovery_to_the_registered_adapter(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ import modules.agents.avibe.recovery as recovery_module
+ from core.agent_auth_service import AgentAuthService
+ from core.controller import Controller
+ from core.watches import ManagedWatchStore
+
+ calls = _hand_over_failing_once(monkeypatch)
+ # The detached retry would wait long; live registration must not leave it beside the new owner.
+ monkeypatch.setattr(recovery_module, "RETRY_DELAYS_S", (60.0,))
+ harness, running, _exited = await _two_sessions_with_open_calls(engine, tmp_path, local_tool_suite())
+ controller = _disabled_controller()
+ try:
+ # Startup with agents.avibe disabled: SESSION's hand-over fails and a retry is pending.
+ await Controller._recover_avibe_agent_runtime_state(controller)
+ # agents.avibe is enabled: the config refresh registers an adapter and recovers on it.
+ controller.agent_service.agents["avibe"] = harness.new_agent()
+ await AgentAuthService._recover_after_live_registration(SimpleNamespace(controller=controller), "avibe")
+
+ # One owner: the registered adapter settled everything, and no detached retry remains.
+ pending = [task for task in asyncio.all_tasks() if task.get_name().startswith("avibe-agent-recovery")]
+ assert [task for task in pending if not task.done()] == []
+ assert ManagedWatchStore().find_job_watch(running) is not None
+ assert len(await _results(engine, SESSION)) == 1 and calls.count(running) == 2
+ finally:
+ await controller.avibe_recovery.stop()
+ for task in asyncio.all_tasks():
+ if task.get_name().startswith("avibe-agent-recovery"):
+ task.cancel()
+ await harness.suite.jobs.kill(running)
+
+
+async def test_recovery_admits_a_returned_input_whose_admission_failed(engine, session, tmp_path, published) -> None:
+ from modules.agents.avibe.recovery import AvibeRecovery
+
+ started = asyncio.Event()
+
+ async def wait_for_cancel(arguments, ctx):
+ started.set()
+ await ctx.cancel.wait()
+ return ToolResult((text("Command aborted"),), is_error=True)
+
+ harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), tools=[FakeTool("echo", execute=wait_for_cancel)])
+ harness.controller.avibe_recovery = AvibeRecovery(harness.controller)
+ harness.controller.agent_service.agents = {"avibe": harness.agent}
+ request = harness.request("run it")
+ turn_id = _turn(request.context)
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await started.wait()
+ native = harness.controller.started[-1]
+ delivery_id, attempt_id = harness.open_steer("and the docs", turn_id, native)
+ receipt = await harness.agent.steer_active_turn(
+ SteerRequest(SESSION, turn_id, native, "and the docs", attempt_id=attempt_id),
+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),
+ )
+ assert receipt.outcome is SteerOutcome.ACCEPTED
+ harness.accept_steer(delivery_id, attempt_id, turn_id)
+ store, consume, failures = harness.agent.store, harness.agent.store.consume_input, []
+
+ async def locked_once(session_id, message_id, message):
+ if message_id == delivery_id and not failures:
+ failures.append(message_id)
+ raise RuntimeError("database is locked")
+ return await consume(session_id, message_id, message)
+
+ store.consume_input = locked_once
+ # Stop returns the accepted steer; admitting it fails once.
+ await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"}))
+ await running
+ assert failures == [delivery_id] and harness.controller.avibe_recovery.retrying
+ harness.controller.avibe_recovery._task.cancel()
+
+ # The owner's next pass admits it, without any Turn, exactly once.
+ assert await harness.controller.avibe_recovery.start() == []
+ admitted = [entry for entry in await harness.context_rows() if entry.row_id == delivery_id]
+ assert len(admitted) == 1
+
+
+_REMOTE_SNAPSHOT = {
+ "sub": "remote-user-1",
+ "email": "[email protected]",
+ "vibe_instance_role": "owner",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org_1",
+ "vibe_organization_role": "member",
+}
+
+
+async def _remote_turn_with_open_call(
+ harness: _Harness, tmp_path: Path, *, snapshot: Optional[dict], author_id: str = "remote:remote-user-1"
+) -> str:
+ """A Workbench Turn (by a remote principal unless ``author_id`` says otherwise) whose response opened a bash call; returns its job id."""
+ from core.vibe_agents import VibeAgentStore
+
+ VibeAgentStore().ensure_builtin_default_agent(backend="avibe")
+ turn_id, delivery_id = f"turn_remote_{id(harness)}", f"dlv_remote_{id(harness)}"
+ metadata = {"resource_user_context": dict(snapshot)} if snapshot is not None else {}
+ with harness.engine.begin() as conn:
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=SESSION,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=_SCOPES["avibe"], session_id=SESSION, platform="avibe", author="user", source="user",
+ message_type="user", text="run the release", metadata=metadata, author_id=author_id,
+ ),
+ dispatch_text="run the release",
+ now=NOW,
+ )
+ message_deliveries.claim_start_batch(
+ conn, turn_id=turn_id, session_id=SESSION, backend="avibe", deliveries=[delivery],
+ dispatch_text="run the release",
+ )
+ context = _context("avibe", SESSION, turn_id=turn_id, delivery_id=delivery_id)
+ harness.controller._native_start(context)
+ await harness.agent.store.consume_input(SESSION, delivery_id, UserMessage((text("run the release"),)))
+ harness.agent.store.bind_agent(SESSION, "avibe")
+ call = ToolCallBlock(id="call_release", name="bash", arguments={"command": "sleep 30"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ harness.agent.store.bind_agent(SESSION, None)
+ return await harness.agent._tools().jobs.start(
+ "sleep 30", cwd=str(tmp_path), env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
+ timeout_s=None, session_id=SESSION, tool_call_id="call_release",
+ )
+
+
+def _job_watch(job_id: str):
+ from core.watches import ManagedWatchStore
+
+ store = ManagedWatchStore()
+ watch_id = store.find_job_watch(job_id)
+ store.load()
+ return store.get_watch(watch_id) if watch_id else None
+
+
+async def test_a_remote_turns_job_watch_carries_its_authorization(engine, session, tmp_path, published, monkeypatch) -> None:
+ import storage.resource_access_service as access
+
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ harness.agent._tool_suite = None # the adapter's own job host and hand-over
+ job_id = await _remote_turn_with_open_call(harness, tmp_path, snapshot=_REMOTE_SNAPSHOT)
+ try:
+ # The same hand-over bash's watch=true and its foreground window use.
+ await harness.agent._tools().jobs.hand_over(job_id)
+
+ watch = _job_watch(job_id)
+ assert watch.agent_name == "avibe"
+ assert watch.metadata["resource_user_context"]["sub"] == "remote-user-1"
+ from core.watches import watch_allows_runtime
+
+ assert watch_allows_runtime(watch)
+
+ # Revoked access fails the recheck the Watch runs before following up.
+ def revoked(metadata, **_kwargs):
+ raise access.ResourceAccessError(access.HARNESS_ACCESS_FORBIDDEN_CODE)
+
+ monkeypatch.setattr(access, "resource_user_context_from_metadata", revoked)
+ assert not watch_allows_runtime(watch)
+
+ # An update re-authors the Watch to its updater, explicitly: a local rename makes it local.
+ from core.watches import ManagedWatchStore
+ from tests.test_watch_job_target import _update_fields
+
+ ManagedWatchStore().update_watch(watch.id, **{**_update_fields(watch), "name": "release"})
+ renamed = _job_watch(job_id)
+ assert "resource_user_context" not in renamed.metadata
+ assert watch_allows_runtime(renamed)
+ finally:
+ await harness.agent._tools().jobs.kill(job_id)
+
+
+ ("author_id", "snapshot", "authority", "allowed"),
+ [
+ ("remote:remote-user-1", _REMOTE_SNAPSHOT, {"resource_user_context": {"sub": "remote-user-1"}}, True),
+ # A remote Turn with no snapshot: owned, but never followed up.
+ ("remote:remote-user-1", None, {"resource_user_context": {"unverifiable": True}}, False),
+ ("owner", None, {"job_watch_authorization": "local"}, True),
+ ],
+ ids=["remote", "remote-without-snapshot", "local"],
+)
+async def test_startup_recovery_hands_a_job_over_with_its_turns_authorization(
+ engine, session, tmp_path, published, author_id, snapshot, authority, allowed
+) -> None:
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ harness.agent._tool_suite = None
+ job_id = await _remote_turn_with_open_call(harness, tmp_path, snapshot=snapshot, author_id=author_id)
+ suite = harness.agent._tool_suite
+ try:
+ # The process restarted: no live request, only the Turn's durable rows.
+ agent = harness.new_agent()
+ agent._tool_suite = None
+ assert await agent.recover_runtime_state() == []
+
+ watch = _job_watch(job_id)
+ assert watch is not None and watch.agent_name == "avibe"
+ for key, expected in authority.items():
+ recorded = watch.metadata.get(key)
+ assert {k: recorded[k] for k in expected} == expected if isinstance(expected, dict) else recorded == expected
+ assert ("resource_user_context" in watch.metadata) is author_id.startswith("remote:")
+ from core.watches import watch_allows_runtime
+
+ assert watch_allows_runtime(watch) is allowed
+ finally:
+ await suite.jobs.kill(job_id)
+
+
+async def test_the_default_job_host_lives_in_the_watch_jobs_dir(engine, session, tmp_path) -> None:
+ from core.watches import agent_jobs_dir
+
+ controller = _Controller(engine, "avibe")
+ suite = AvibeAgent(controller, engine=engine)._tools()
+ job_id = await _real_job(suite, "true", call_id="call_true", cwd=tmp_path)
+ try:
+ # vibe stop's stop_all_jobs and the job-Watch sweep both look in this one directory.
+ assert Path(suite.jobs.output_path(job_id)).is_relative_to(Path(os.path.realpath(agent_jobs_dir())))
+ finally:
+ await _until(lambda: suite.jobs.status(job_id).state != "running", "the job never ended")
+
+
+async def test_startup_prunes_only_jobs_whose_call_and_watch_have_settled(engine, session, tmp_path, published) -> None:
+ from core.watches import ManagedWatchStore
+
+ suite = local_tool_suite(str(tmp_path / "jobs"))
+ harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ request = harness.request("run them")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run them"),))
+ )
+ calls = tuple(ToolCallBlock(id=f"call_{name}", name="bash", arguments={"command": "printf out"}) for name in "abc")
+ await harness.agent.store.append_response(SESSION, assistant("", calls=calls), final=False)
+ # d's call is in no committed response, so nothing can ever settle it.
+ jobs = {name: await _real_job(suite, "printf out", call_id=f"call_{name}", cwd=tmp_path) for name in "abcd"}
+ for job_id in jobs.values():
+ await _until(lambda job_id=job_id: suite.jobs.status(job_id).state == "exited", "a job never exited")
+ # a and b have durable results and b's Watch still owns it; c's call is still open.
+ for name in "ab":
+ await harness.agent.store.append_tool_result(
+ SESSION, ToolResultMessage(f"call_{name}", "bash", (text("ok"),)), details={"job_id": jobs[name]}
+ )
+ # e reuses a's call id after a's result committed (a model call apart): a's result does not settle it.
+ await asyncio.sleep(0.01)
+ jobs["e"] = await _real_job(suite, "printf out", call_id="call_a", cwd=tmp_path)
+ await _until(lambda: suite.jobs.status(jobs["e"]).state == "exited", "a job never exited")
+ await suite.jobs.hand_over(jobs["b"])
+ assert ManagedWatchStore().job_watch_settled(jobs["b"]) is False
+ week_ago = time.time() - 8 * 24 * 3600
+ for job_id in jobs.values():
+ for entry in Path(suite.jobs.output_path(job_id)).parent.iterdir():
+ os.utime(entry, (week_ago, week_ago))
+
+ harness.new_agent()
+ await harness.agent.recover_runtime_state()
+
+ # Startup settles c's open call from its job's output (T2) before any file goes.
+ [c_result] = [entry for entry in await harness.context_rows() if entry.kind == "tool_result"][-1:]
+ assert c_result.message.tool_call_id == "call_c" and "out" in c_result.message.content[0].text
+ present = {name: Path(suite.jobs.output_path(job_id)).parent.exists() for name, job_id in jobs.items()}
+ # J5: a job is removed only once its call has a durable result and no Watch still manages it.
+ assert present == {"a": False, "b": True, "c": False, "d": True, "e": True}
+
+
+
+async def test_a_running_service_prunes_settled_jobs_after_its_runs(engine, session, tmp_path, published) -> None:
+ suite = local_tool_suite(str(tmp_path / "jobs"))
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("done"))]], suite=suite)
+ request = harness.request("run it")
+ harness.controller._native_start(request.context)
+ await harness.agent.store.consume_input(
+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
+ )
+ call = ToolCallBlock(id="call_old", name="bash", arguments={"command": "printf out"})
+ await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ job_id = await _real_job(suite, "printf out", call_id="call_old", cwd=tmp_path)
+ await _until(lambda: suite.jobs.status(job_id).state == "exited", "the job never exited")
+ await harness.agent.store.append_tool_result(
+ SESSION, ToolResultMessage("call_old", "bash", (text("out"),)), details={"job_id": job_id}
+ )
+ await harness.agent.store.append_response(SESSION, assistant("finished"), final=True)
+ job_dir = Path(suite.jobs.output_path(job_id)).parent
+ week_ago = time.time() - 8 * 24 * 3600
+ for entry in job_dir.iterdir():
+ os.utime(entry, (week_ago, week_ago))
+
+ # No restart: the service has been up since the job ran, and the next Turn ends.
+ await harness.agent.handle_message(harness.request("anything else?"))
+
+ await _until(lambda: not job_dir.exists(), "a settled job outlived its retention while the service ran")
diff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.py
index 5599f7d4c..7bc2f1860 100644
--- a/tests/test_backend_registration_contract.py
+++ b/tests/test_backend_registration_contract.py
@@ -53,7 +53,7 @@ PYTHON_DECLARATIONS = {
("core/handlers/model_hub/service.py", "Tuple", frozenset({"claude", "codex"})): (3, "native_subset", "Backends with bundled model lists."),
("core/services/session_fork.py", "Set", frozenset({"codex", "opencode"})): (1, "native_subset", "Native forks that can trim a running turn."),
("core/services/skills.py", "Dict", NATIVE): (1, "native", "askill native CLI ids."),
- ("core/session_turns.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Runtimes whose running turns cannot restore."),
+ ("core/session_turns.py", "Set", frozenset({"claude", "codex", "avibe"})): (1, "agent_subset", "Runtimes whose accepted turns cannot survive a service restart (process-bound, including Avibe's in-process loop)."),
("core/vibe_agents.py", "Dict", NATIVE): (1, "native", "Native recommendations; Avibe uses its configured Hub catalog."),
("modules/im/telegram.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Native subagent routing controls."),
("scripts/incus_tenant.py", "Dict", AGENTS): (1, "agent", "Bootstrap config with backend-specific fields."),
@@ -146,6 +146,8 @@ def test_backend_universes_are_catalog_owned_and_literals_are_classified():
assert members == AGENTS
elif relation == "native":
assert members == NATIVE
+ elif relation == "agent_subset":
+ assert members < AGENTS
else:
assert relation == "native_subset" and members < NATIVE
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 664bcf5cd..68c0cc60e 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -4200,9 +4200,16 @@ def test_start_write_ambiguity_replays_once_after_restart(managers) -> None:
assert turns[1]["state"] == "starting"
-def test_accepted_codex_turn_without_runtime_settles_and_releases_queue(managers) -> None:
[email protected]("backend", ["codex", "avibe"])
+def test_accepted_turn_of_a_process_bound_backend_without_runtime_settles_and_releases_queue(
+ managers, backend: str
+) -> None:
+ # The Avibe Agent's loop runs inside the controller process, so after a
+ # restart its accepted Turn can only be settled as interrupted (recovery.md T4).
first, restarted, engine, _engine_b, starts = managers
turn_id, _context_value = asyncio.run(_activate(first, text="accepted before restart"))
+ with engine.begin() as conn:
+ conn.execute(update(session_turns).where(session_turns.c.id == turn_id).values(backend=backend))
queued = asyncio.run(
first.deliver(
DeliveryRequest(
@@ -4234,6 +4241,50 @@ def test_accepted_codex_turn_without_runtime_settles_and_releases_queue(managers
assert [text for _started_turn, text in starts] == ["continue after restart"]
+def test_a_late_negative_steer_receipt_never_moves_a_delivery_its_attempt_no_longer_owns(managers) -> None:
+ # A refusal re-queued the steer and the queue claimed it into a new Turn; a second, late
+ # negative receipt for the same attempt must not pull it back out of that Turn.
+ manager, _restarted, engine, _engine_b, starts = managers
+ turn_id, _context_value = asyncio.run(_activate(manager))
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id="dlv_late_negative",
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None, session_id="ses_fsm", platform="avibe", author="user",
+ source="user", message_type="user", text="also this",
+ ),
+ dispatch_text="also this",
+ now="2026-10-04T00:00:00.000000Z",
+ )
+ assert delivery_store.open_steer_attempt(
+ conn, delivery["id"], expected_version=int(delivery["version"]), turn_id=turn_id,
+ attempt_id="att_late_negative", expected_native_turn_id=f"native-{turn_id}",
+ )
+ conn.execute(
+ update(session_turns).where(session_turns.c.id == turn_id).values(
+ state="terminal", terminal_outcome="completed", terminal_at="2026-10-04T00:00:01.000000Z"
+ )
+ )
+ asyncio.run(manager._finish_steer(
+ "dlv_late_negative", steer_result(SteerOutcome.REFUSED, reason="run_closed"), context=None
+ ))
+ with engine.connect() as conn:
+ claimed = delivery_store.get_delivery(conn, "dlv_late_negative")
+ assert claimed["state"] == "claimed" and claimed["turn_id"]
+
+ asyncio.run(manager._finish_steer(
+ "dlv_late_negative", steer_result(SteerOutcome.NOT_ACTIVE, reason="not_active"), context=None
+ ))
+
+ with engine.connect() as conn:
+ after = delivery_store.get_delivery(conn, "dlv_late_negative")
+ assert (after["state"], after["turn_id"]) == ("claimed", claimed["turn_id"])
+
+
def _capture_lost_turn_report(manager: SessionTurnManager) -> tuple[list, list]:
"""Record what a lost turn reports outward, without a real IM client."""
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index cfc7e9440..52ca04665 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -201,6 +201,43 @@ def test_reserve_forked_session_copies_row_and_applies_overrides(tmp_path: Path)
assert metadata["fork_trim_latest_running_turn"] is False
+def test_reserve_forked_avibe_session_records_its_context_anchor(tmp_path: Path) -> None:
+ # The Avibe Agent's context is the source's rows up to the anchor (C-5 section 4):
+ # resolved once at reservation, so rows the source commits later never enter the prefix.
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="avibe")
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).scalar_one()
+ turns = (("user", "user", "first question"), ("agent", "result", "first answer"),
+ ("user", "user", "fyi"), ("agent", "assistant", ""))
+ # The last Turn ended silently: its final is a hidden row no message anchor names.
+ for seq, (author, mtype, text) in enumerate(turns, start=1):
+ row = messages_service.append(
+ conn, scope_id=scope_id, session_id=source_id, platform="avibe", author=author,
+ source=author, message_type=mtype, text=text,
+ )
+ conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == result.session_id)).mappings().one()
+ finally:
+ engine.dispose()
+ metadata = json.loads(row["metadata_json"])
+ assert result.fork.source_backend == "avibe"
+ # With no running Turn the child inherits the whole settled context, as a native fork does.
+ assert metadata["fork_source_context_seq"] == 4
+
+
def test_reserve_forked_codex_running_fork_marks_trim(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
source_id = _seed_source_session(db_path, tmp_path)
@@ -559,9 +596,12 @@ def test_reserve_forked_opencode_running_first_turn_records_user_boundary(
assert "fork_opencode_fork_empty_history" not in metadata
-def test_reserve_forked_session_clears_stale_opencode_active_run_boundary(
+def test_reserve_forked_session_clears_stale_fork_boundaries(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ # A source that is itself a fork carries its own boundaries; the child must
+ # never inherit them as its own (OpenCode's native point, the Avibe Agent's
+ # ``fork_source_context_seq`` context anchor).
db_path = tmp_path / "vibe.sqlite"
xdg_home = tmp_path / "xdg"
monkeypatch.setenv("XDG_DATA_HOME", str(xdg_home))
@@ -583,6 +623,7 @@ def test_reserve_forked_session_clears_stale_opencode_active_run_boundary(
"fork_opencode_message_id": "stale-oc-msg",
"fork_opencode_fork_empty_history": True,
"fork_opencode_boundary_from_active_run": True,
+ "fork_source_context_seq": 7,
}
),
)
@@ -605,6 +646,7 @@ def test_reserve_forked_session_clears_stale_opencode_active_run_boundary(
assert "fork_opencode_message_id" not in metadata
assert "fork_opencode_fork_empty_history" not in metadata
assert "fork_opencode_boundary_from_active_run" not in metadata
+ assert "fork_source_context_seq" not in metadata
def test_reserve_forked_opencode_missing_boundary_preserves_trim_intent(
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 72352b3e8..cc307f910 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1525,5 +1525,24 @@
"busy": "Another retention run is active; try again later.",
"cancelled": "Retention stopped at a batch boundary; no completion was recorded."
}
+ },
+ "avibeAgent": {
+ "error": {
+ "refusal": "The model declined to answer this request.",
+ "safety": "The model stopped this reply for safety reasons.",
+ "emptyResponse": "The model returned an empty reply. Try again or rephrase the request.",
+ "interrupted": "The Avibe Agent run was interrupted before it finished.",
+ "contextExhausted": "This conversation no longer fits in the model's context window. Start a new session, or fork from an earlier message.",
+ "rateLimit": "The model provider is rate-limiting requests. Try again in a moment.",
+ "overloaded": "The model provider is overloaded. Try again in a moment.",
+ "network": "The model provider could not be reached. Check the network and the Model Hub source.",
+ "server": "The model provider returned a server error. Try again in a moment.",
+ "auth": "The model provider rejected the credentials of this route. Check the Model Hub source.",
+ "invalidRequest": "The model provider rejected the request.",
+ "modelError": "The model stopped with an error.",
+ "toolsUnsupported": "The selected model does not support tools, which the Avibe Agent needs. Choose another model.",
+ "providerProtocol": "The model provider sent a reply the Avibe Agent cannot use.",
+ "generic": "The Avibe Agent run failed."
+ }
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 050bf7deb..ddd2806a5 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1525,5 +1525,24 @@
"busy": "另一个保留清理正在运行,请稍后重试。",
"cancelled": "保留清理已在批次边界停止;未记录完成状态。"
}
+ },
+ "avibeAgent": {
+ "error": {
+ "refusal": "模型拒绝回答这个请求。",
+ "safety": "模型出于安全原因停止了这次回复。",
+ "emptyResponse": "模型返回了空回复。请重试,或换一种说法。",
+ "interrupted": "Avibe Agent 的运行在完成前被中断。",
+ "contextExhausted": "这段对话已超出模型的上下文窗口。请新建会话,或从更早的消息分叉。",
+ "rateLimit": "模型服务商正在限流,请稍后重试。",
+ "overloaded": "模型服务商当前过载,请稍后重试。",
+ "network": "无法连接模型服务商。请检查网络和 Model Hub 来源。",
+ "server": "模型服务商返回了服务器错误,请稍后重试。",
+ "auth": "模型服务商拒绝了此路由的凭据。请检查 Model Hub 来源。",
+ "invalidRequest": "模型服务商拒绝了这个请求。",
+ "modelError": "模型因错误而停止。",
+ "toolsUnsupported": "所选模型不支持工具,而 Avibe Agent 需要工具。请换一个模型。",
+ "providerProtocol": "模型服务商返回的回复 Avibe Agent 无法使用。",
+ "generic": "Avibe Agent 运行失败。"
+ }
}
}