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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Route tool calls to agent events (#504)
Call Whitee8a2bb7bf65d
diff --git a/core/message_mirror.py b/core/message_mirror.pyindex a2e28be52..6ed4c9076 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -12,9 +12,9 @@ Hooks live in two places:* ``core/handlers/message_handler.py`` calls :func:`mirror_inbound` onceper human-originated turn, after session resolution.* ``core/message_dispatcher.py`` calls :func:`persist_agent_message` once per- agent ``emit_agent_message`` — for every type (result / assistant /- tool_call / notify), on every platform incl. avibe, BEFORE the IM mute- filter so hidden messages still land.+ agent ``emit_agent_message`` — for every type, on every platform incl. avibe,+ BEFORE the IM mute filter. Chat outputs land in ``messages``; tool-call trace+ events land in ``agent_events``.Failures are swallowed and logged. A bad mirror write must never breakthe live IM reply path.@@ -29,7 +29,7 @@ from typing import Optionalfrom sqlalchemy.exc import IntegrityErrorfrom modules.im.base import MessageContext-from storage import messages_service, settings_service+from storage import agent_events_service, messages_service, settings_servicefrom storage.db import create_sqlite_enginelogger = logging.getLogger(__name__)@@ -100,17 +100,27 @@ def _publish_session_message(row: Optional[dict]) -> None:logger.debug("message_mirror: message.new publish failed", exc_info=True)-def _scope_id_for_session(conn, session_id: str) -> Optional[str]:- """Resolve a message's scope from its agent session (works for avibe +- IM once the session has been reserved)."""+def _session_row(conn, session_id: str) -> Optional[dict]:+ """Resolve scope/provenance from an agent session."""from sqlalchemy import selectfrom storage.models import agent_sessionsrow = conn.execute(- select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)- ).first()- return row[0] if row else None+ select(+ agent_sessions.c.scope_id,+ agent_sessions.c.agent_name,+ agent_sessions.c.agent_backend,+ ).where(agent_sessions.c.id == session_id)+ ).mappings().first()+ return dict(row) if row else None+++def _scope_id_for_session(conn, session_id: str) -> Optional[str]:+ """Resolve a message's scope from its agent session (works for avibe ++ IM once the session has been reserved)."""+ row = _session_row(conn, session_id)+ return row["scope_id"] if row else None# Maps the dispatcher's canonical message type to the persisted ``messages.type``.@@ -127,12 +137,33 @@ _AGENT_TYPE_BY_CANONICAL = {"error": "error","notify": "notify","assistant": "assistant",- "toolcall": "tool_call",- "tool_call": "tool_call","system": "assistant",}+def _is_tool_call_type(canonical_type: str | None) -> bool:+ return (canonical_type or "") in {"toolcall", "tool_call"}+++def _agent_provenance_from_context(context: MessageContext, session_row: Optional[dict] = None) -> tuple[Optional[str], Optional[str]]:+ spec = context.platform_specific or {}+ target = spec.get("agent_session_target") or {}+ agent_name = spec.get("vibe_agent_name") or target.get("agent_name") or (session_row or {}).get("agent_name")+ backend = spec.get("vibe_agent_backend") or target.get("agent_backend") or (session_row or {}).get("agent_backend")+ return agent_name, backend+++def _trace_ids_from_context(context: MessageContext) -> tuple[Optional[str], Optional[str]]:+ spec = context.platform_specific or {}+ trigger_kind = str(spec.get("task_trigger_kind") or "").strip()+ run_id = str(spec.get("task_execution_id") or "").strip() or None+ turn_token = str(spec.get("turn_token") or "").strip()+ turn_id = turn_token or None+ if trigger_kind == "agent_run" and run_id and not turn_id:+ turn_id = run_id+ return turn_id, run_id++def persist_agent_message(context: MessageContext,canonical_type: str,@@ -143,8 +174,8 @@ def persist_agent_message("""Persist one agent output into the workbench ``messages`` store.Unified across **all** platforms (including avibe, which has no IM mirror)- and called BEFORE any IM delivery/mute decision, so assistant / tool_call- messages land even when a channel hides them. Each ``emit_agent_message``+ 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``call is a distinct logical message — the consolidated IM "log" message onlymerges them for display — so one row per emit is correct, not fragments.@@ -165,7 +196,6 @@ def persist_agent_message(# would only be noise in history) (user request).if (canonical_type or "") == "system":return- message_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")session_id = (context.platform_specific or {}).get("agent_session_id")try:engine = create_sqlite_engine()@@ -176,13 +206,15 @@ def persist_agent_message(# Inbox groups by the avibe session's project scope; never invent# a 'channel' scope for avibe (projects are pre-created via# /api/projects). Skip if the session row isn't visible yet.- scope_id = _scope_id_for_session(conn, session_id) if session_id else None+ session_row = _session_row(conn, session_id) if session_id else None+ scope_id = session_row["scope_id"] if session_row else Nonerow_session_id = session_idelse:# IM: attribute the row to the delivery channel (this ``context``# is the routed target), matching where the reply was sent. The# cross-platform history is scope-keyed, not session-keyed, so the# row carries no session_id — same shape as ``mirror_inbound``.+ session_row = Nonescope_id = _resolve_scope_id(conn, context)row_session_id = Noneif scope_id is None:@@ -190,14 +222,32 @@ def persist_agent_message(# Provenance: every agent reply is source='agent'; name = the# session's agent (from the dispatch context). source_id (author_id)# is left to the agent-id wiring later; the session already carries it.- spec = context.platform_specific or {}- agent_name = spec.get("vibe_agent_name") or (spec.get("agent_session_target") or {}).get("agent_name")+ agent_name, backend = _agent_provenance_from_context(context, session_row)+ if _is_tool_call_type(canonical_type):+ turn_id, run_id = _trace_ids_from_context(context)+ agent_events_service.append(+ conn,+ scope_id=scope_id,+ session_id=row_session_id,+ platform=context.platform,+ event_type="tool_call",+ visibility="trace",+ text=text,+ content={"kind": canonical_type or "tool_call"},+ metadata={"canonical_type": canonical_type or "tool_call"},+ agent_name=agent_name,+ backend=backend,+ turn_id=turn_id,+ run_id=run_id,+ )+ return+ message_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")# Workbench Chat only: rewrite ``file://`` links in the persisted copy# to same-origin media-proxy URLs so the browser renders agent images# inline + files as download cards. IM rows keep the raw ``file://``# (the dispatcher uploads those to the platform separately). Scoped to# the user-visible result/notify rows so we don't mint tokens for the- # hidden intermediate assistant/tool_call stream.+ # hidden intermediate assistant stream.if context.platform == "avibe" and message_type in ("result", "notify", "error") and row_session_id:try:from core.workbench_media import rewrite_agent_mediadiff --git a/docs/plans/tool-call-agent-events-cutover.md b/docs/plans/tool-call-agent-events-cutover.mdnew file mode 100644index 000000000..41d555035--- /dev/null+++ b/docs/plans/tool-call-agent-events-cutover.md@@ -0,0 +1,201 @@+# Tool Call Agent Events Cutover Plan++## Status++- Scope: move new `tool_call` persistence out of `messages` and into an+ execution-trace table.+- Product decision: historical `messages.type = 'tool_call'` rows are+ disposable trace data. They do not require lossless backfill before deletion.+- Non-goal: redesign all assistant/intermediate events in this pass. This plan+ intentionally starts with `tool_call` only.++## Background++The local SQLite `messages` table currently stores both user-visible transcript+rows and backend execution trace rows. The current observed distribution is+dominated by `tool_call` rows, which are execution details and should not be+part of the canonical chat transcript.++`messages` should represent user-facing conversation facts. `tool_call` rows+should instead be stored as agent trace events that can be retained, displayed,+or deleted independently from the transcript.++## Target Boundary++Long-term, `messages` should converge on the canonical transcript:++- `user`+- `result`+- `notify`+- `error`+- user-visible `assistant` text++PR 1 only moves `tool_call`. Existing intermediate `assistant` process-log rows+remain in `messages` for now so this change does not bundle a broader event+taxonomy decision into the first cleanup.++`agent_events` owns execution trace:++- first supported event type: `tool_call`+- future event types may include `tool_result`, `thinking`, `sdk_error`,+ `intermediate_assistant`, and backend raw events++The first implementation should only move new `tool_call` writes. Broader event+taxonomy can be added later without blocking this cleanup.++## Proposed Table++Create a new `agent_events` table:++```sql+create table agent_events (+ id varchar primary key,+ scope_id varchar not null,+ session_id varchar,+ turn_id varchar,+ run_id varchar,+ platform varchar not null,+ agent_name varchar,+ backend varchar,+ event_type varchar not null,+ visibility varchar not null default 'trace',+ sequence integer,+ content_text text,+ content_json text not null,+ metadata_json text not null,+ source varchar,+ created_at varchar not null,+ updated_at varchar not null,+ foreign key(scope_id) references scopes(id) on delete cascade,+ foreign key(session_id) references agent_sessions(id) on delete set null+);+```++Initial indexes:++```sql+create index ix_agent_events_session_created_id+ on agent_events (session_id, created_at, id);++create index ix_agent_events_session_type_created_id+ on agent_events (session_id, event_type, created_at, id);++create index ix_agent_events_scope_created_id+ on agent_events (scope_id, created_at, id);++create index ix_agent_events_turn_sequence_id+ on agent_events (turn_id, sequence, id);+```++Notes:++- `turn_id` is nullable because current write paths may not consistently expose+ a stable turn identifier yet. The schema should reserve the boundary now.+- `visibility = 'trace'` should be the default for `tool_call`.+- `content_json` should preserve the structured payload currently mirrored into+ `messages.content_json`.+- `metadata_json` should carry backend, formatter, model, tool name, duration,+ and any source details that are not query dimensions.++## Phase 1: New Writes Only++Goal: stop new `tool_call` rows from entering `messages`.++Implementation tasks:++1. Add the `agent_events` migration and model/store helpers.+2. Add a shared persistence API, for example `persist_agent_event(...)`.+3. Route outbound `tool_call` persistence through `agent_events`.+4. Keep transport/UI behavior stable: IM adapters may still send visible+ tool-call previews if configured, but durable transcript persistence should+ not write `messages.type = 'tool_call'`.+5. Add focused tests:+ - emitting a `tool_call` creates an `agent_events` row;+ - emitting a `tool_call` does not create a `messages` row;+ - normal `user`, `result`, `notify`, `error`, and visible `assistant`+ messages still persist to `messages`.++Read-path checks before merging:++- Workbench chat transcript should not require `messages.tool_call`.+- Inbox/session list queries should not count `tool_call` as transcript+ activity unless explicitly intended.+- Export/debug paths that previously read `messages.tool_call` should either+ accept the loss or be changed to read `agent_events`.++## Phase 2: Historical Cleanup++Goal: remove historical `tool_call` rows from `messages`.++Product decision:++- Lossless backfill is not required.+- Historical `tool_call` data may be deleted because it is disposable trace, not+ user-visible transcript.++Preferred cleanup:++```sql+delete from messages+where type = 'tool_call';+```++For the current local scale, one transaction is acceptable. If this later ships+to much larger databases, use batched deletion.++Validation:++```sql+select count(*) from messages where type = 'tool_call';+select type, count(*) from messages group by type order by count desc;+```++Expected outcome:++- `messages.type = 'tool_call'` count is `0`.+- Total `messages` count drops by approximately the previous `tool_call` count.+- Workbench chat and inbox views still behave normally.++## Phase 3: Optional Trace UI++This is intentionally separate from the cutover.++Potential future UI/API work:++- session/turn execution details panel reading `agent_events`;+- event pagination by `(session_id, created_at, id)`;+- trace retention or compaction policy;+- optional deletion of trace events independent of transcript messages.++## Risks++- Hidden read dependency: some debug/export path may treat `messages` as a full+ execution stream. Phase 1 should search and test those paths before changing+ persistence.+- Naming drift: code may use both `toolcall` and `tool_call`. The migration+ should pick one canonical event type, with `tool_call` preferred for database+ consistency.+- Turn association: without a stable `turn_id`, early trace grouping will rely+ on `session_id` and timestamps. This is acceptable for the first cutover but+ should not become the long-term model.++## Suggested PR Split++### PR 1: `agent_events` table and new `tool_call` write path++- Add schema and store helper.+- Cut new `tool_call` persistence from `messages` to `agent_events`.+- Add unit coverage around the persistence split.+- Do not delete historical data.++### PR 2: Delete historical `messages.tool_call`++- Run/delete historical `messages.type = 'tool_call'` rows.+- Add or update a migration/maintenance command depending on the chosen+ deployment policy.+- Validate count is zero and transcript views still work.++### Later PR: richer event model++- Add `tool_result`, `thinking`, `sdk_error`, and intermediate assistant events+ only after the `tool_call` boundary has proven stable.diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex a885dccd6..1cd3fcbd8 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -461,6 +461,10 @@ class ClaudeAgent(BaseAgent):if assistant_text:self._last_assistant_text[composite_key] = assistant_text+ pending_requests = self._pending_requests.get(composite_key) or []+ pending_request = pending_requests[0] if pending_requests else None+ self._adopt_pending_turn_token(context, pending_request)+pending = self._pending_assistant_message.pop(composite_key, None)if pending:await self.controller.emit_agent_message(diff --git a/storage/agent_events_service.py b/storage/agent_events_service.pynew file mode 100644index 000000000..34559069b--- /dev/null+++ b/storage/agent_events_service.py@@ -0,0 +1,106 @@+"""Append-only trace events emitted by agent runtimes.++``agent_events`` is intentionally separate from ``messages``: rows here are+debug/trace material, not transcript content. The first writer is tool-call+output from backend SDK streams, which should be retained for diagnosis without+ever becoming a chat/inbox message.+"""++from __future__ import annotations++import json+import time+import uuid+from datetime import datetime, timezone+from typing import Any, Optional++from sqlalchemy.engine import Connection++from storage.models import agent_events+++def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _new_event_id() -> str:+ return f"evt_{int(time.time() * 1_000_000):015x}{uuid.uuid4().hex[:8]}"+++def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:+ try:+ content = json.loads(row.get("content_json") or "{}")+ except json.JSONDecodeError:+ content = {}+ try:+ metadata = json.loads(row.get("metadata_json") or "{}")+ except json.JSONDecodeError:+ metadata = {}+ return {+ "id": row["id"],+ "scope_id": row.get("scope_id"),+ "session_id": row.get("session_id"),+ "turn_id": row.get("turn_id"),+ "run_id": row.get("run_id"),+ "platform": row.get("platform"),+ "agent_name": row.get("agent_name"),+ "backend": row.get("backend"),+ "event_type": row.get("event_type"),+ "visibility": row.get("visibility"),+ "sequence": row.get("sequence"),+ "text": row.get("content_text") or content.get("text") or "",+ "content": content,+ "metadata": metadata,+ "source": row.get("source"),+ "created_at": row.get("created_at"),+ "updated_at": row.get("updated_at"),+ }+++def append(+ conn: Connection,+ *,+ scope_id: str,+ session_id: Optional[str],+ platform: str,+ event_type: str,+ text: Optional[str] = None,+ content: Optional[dict[str, Any]] = None,+ metadata: Optional[dict[str, Any]] = None,+ agent_name: Optional[str] = None,+ backend: Optional[str] = None,+ turn_id: Optional[str] = None,+ run_id: Optional[str] = None,+ visibility: str = "trace",+ source: Optional[str] = "agent",+ sequence: Optional[int] = None,+) -> dict[str, Any]:+ body: dict[str, Any] = {}+ if content:+ body.update(content)+ if text is not None:+ body.setdefault("text", text)+ plain = text if text is not None else body.get("text") or None++ now = _utc_now_iso()+ payload = {+ "id": _new_event_id(),+ "scope_id": scope_id,+ "session_id": session_id,+ "turn_id": turn_id,+ "run_id": run_id,+ "platform": platform,+ "agent_name": agent_name,+ "backend": backend,+ "event_type": event_type,+ "visibility": visibility,+ "sequence": sequence,+ "content_text": plain,+ "content_json": json.dumps(body),+ "metadata_json": json.dumps(metadata or {}),+ "source": source,+ "created_at": now,+ "updated_at": now,+ }+ conn.execute(agent_events.insert().values(**payload))+ return _row_to_payload(payload)diff --git a/storage/alembic/versions/20260608_0020_agent_events.py b/storage/alembic/versions/20260608_0020_agent_events.pynew file mode 100644index 000000000..0557a104c--- /dev/null+++ b/storage/alembic/versions/20260608_0020_agent_events.py@@ -0,0 +1,77 @@+"""add agent events trace table++Revision ID: 20260608_0020+Revises: 20260606_0019+Create Date: 2026-06-08+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260608_0020"+down_revision = "20260606_0019"+branch_labels = None+depends_on = None+++def _tables() -> set[str]:+ bind = op.get_bind()+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}+++def upgrade() -> None:+ if "agent_events" not in _tables():+ op.create_table(+ "agent_events",+ sa.Column("id", sa.String(), primary_key=True),+ sa.Column("scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),+ sa.Column("session_id", sa.String(), sa.ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),+ sa.Column("turn_id", sa.String(), nullable=True),+ sa.Column("run_id", sa.String(), nullable=True),+ sa.Column("platform", sa.String(), nullable=False),+ sa.Column("agent_name", sa.String(), nullable=True),+ sa.Column("backend", sa.String(), nullable=True),+ sa.Column("event_type", sa.String(), nullable=False),+ sa.Column("visibility", sa.String(), nullable=False, server_default="trace"),+ sa.Column("sequence", sa.Integer(), nullable=True),+ sa.Column("content_text", sa.Text(), nullable=True),+ sa.Column("content_json", sa.Text(), nullable=False),+ sa.Column("metadata_json", sa.Text(), nullable=False),+ sa.Column("source", sa.String(), nullable=True),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.Column("updated_at", sa.String(), nullable=False),+ )+ op.create_index(+ "ix_agent_events_session_created_id",+ "agent_events",+ ["session_id", "created_at", "id"],+ if_not_exists=True,+ )+ op.create_index(+ "ix_agent_events_session_type_created_id",+ "agent_events",+ ["session_id", "event_type", "created_at", "id"],+ if_not_exists=True,+ )+ op.create_index(+ "ix_agent_events_scope_created_id",+ "agent_events",+ ["scope_id", "created_at", "id"],+ if_not_exists=True,+ )+ op.create_index(+ "ix_agent_events_turn_sequence_id",+ "agent_events",+ ["turn_id", "sequence", "id"],+ if_not_exists=True,+ )+++def downgrade() -> None:+ op.drop_index("ix_agent_events_turn_sequence_id", table_name="agent_events")+ op.drop_index("ix_agent_events_scope_created_id", table_name="agent_events")+ op.drop_index("ix_agent_events_session_type_created_id", table_name="agent_events")+ op.drop_index("ix_agent_events_session_created_id", table_name="agent_events")+ op.drop_table("agent_events")diff --git a/storage/migrations.py b/storage/migrations.pyindex ca138b326..33c686dbb 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -12,7 +12,7 @@ from config import pathsfrom storage.db import create_sqlite_engine, sqlite_urlINITIAL_REVISION = "20260501_0001"-LATEST_SCHEMA_REVISION = "20260606_0019"+LATEST_SCHEMA_REVISION = "20260608_0020"REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"INITIAL_TABLES = {"state_meta",@@ -28,6 +28,7 @@ HEAD_TABLES = INITIAL_TABLES | {"agent_runs","show_pages","messages",+ "agent_events","show_session_events","media_objects","web_push_subscriptions",@@ -512,10 +513,32 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -)+def _ensure_agent_events_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:+ if "agent_events" not in tables:+ return+ conn.execute(+ "create index if not exists ix_agent_events_session_created_id "+ "on agent_events (session_id, created_at, id)"+ )+ conn.execute(+ "create index if not exists ix_agent_events_session_type_created_id "+ "on agent_events (session_id, event_type, created_at, id)"+ )+ conn.execute(+ "create index if not exists ix_agent_events_scope_created_id "+ "on agent_events (scope_id, created_at, id)"+ )+ conn.execute(+ "create index if not exists ix_agent_events_turn_sequence_id "+ "on agent_events (turn_id, sequence, id)"+ )++def _ensure_head_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:if {"run_definitions", "agent_runs"}.issubset(tables):_ensure_new_background_indexes(conn)_ensure_messages_query_indexes(conn, tables)+ _ensure_agent_events_indexes(conn, tables)def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:diff --git a/storage/models.py b/storage/models.pyindex 3d1abddec..ee48aac95 100644--- a/storage/models.py+++ b/storage/models.py@@ -279,6 +279,35 @@ show_session_events = Table(Index("ix_show_session_events_type_created", "event_type", "created_at"),)+# Append-only agent trace log. Rows here are backend/process events, not chat+# messages. They can be inspected later without polluting the transcript,+# unread counters, or Inbox activity.+agent_events = Table(+ "agent_events",+ metadata,+ Column("id", String, primary_key=True),+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),+ Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),+ Column("turn_id", String, nullable=True),+ Column("run_id", String, nullable=True),+ Column("platform", String, nullable=False),+ Column("agent_name", String, nullable=True),+ Column("backend", String, nullable=True),+ Column("event_type", String, nullable=False),+ Column("visibility", String, nullable=False, server_default="trace"),+ Column("sequence", Integer, nullable=True),+ Column("content_text", Text, nullable=True),+ Column("content_json", Text, nullable=False),+ Column("metadata_json", Text, nullable=False),+ Column("source", String, nullable=True),+ Column("created_at", String, nullable=False),+ Column("updated_at", String, nullable=False),+ Index("ix_agent_events_session_created_id", "session_id", "created_at", "id"),+ Index("ix_agent_events_session_type_created_id", "session_id", "event_type", "created_at", "id"),+ Index("ix_agent_events_scope_created_id", "scope_id", "created_at", "id"),+ Index("ix_agent_events_turn_sequence_id", "turn_id", "sequence", "id"),+)+# Platform-agnostic chat message store. Every IM adapter (Slack, Discord,# Telegram, Lark, WeChat, Avibe/Web UI) writes user+agent turns here so the# workbench Inbox and per-session history can read from a single ORM@@ -427,6 +456,7 @@ imported_state_tables = [runtime_records,scopes,messages,+ agent_events,show_session_events,web_push_subscriptions,]diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 32f4c5b3d..c051adab3 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -115,6 +115,56 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])self.assertTrue(controller.session_manager.session.session_active[composite_key])+ async def test_toolcall_emit_adopts_current_pending_turn_token(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock()+ agent = ClaudeAgent(controller)+ composite_key = "session-1:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "T2"}))+ agent._pending_requests[composite_key] = [pending_request]++ class FakeToolUseBlock:+ name = "Bash"+ input = {"command": "pwd"}++ class AssistantMessage:+ content = [FakeToolUseBlock()]++ class _Formatter:+ @staticmethod+ def format_toolcall(*_args, **_kwargs):+ return "Bash(pwd)"++ @staticmethod+ def format_assistant_message(parts):+ return "\n\n".join(parts)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield AssistantMessage()++ return _iterate()++ with patch("modules.agents.claude_agent.ToolUseBlock", FakeToolUseBlock):+ agent._get_formatter = lambda _context: _Formatter()+ await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)++ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "toolcall",+ "Bash(pwd)",+ parse_mode="markdown",+ )+ self.assertEqual(context.platform_specific["turn_token"], "T2")+ self.assertEqual(agent._pending_requests[composite_key], [pending_request])+async def test_handle_message_uses_runtime_session_key_for_claude_tracking(self):controller = _StubController()controller.emit_agent_message = AsyncMock()diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex fb1865d71..3f38db120 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -29,7 +29,7 @@ from core.message_mirror import mirror_harness_inbound, mirror_inbound, persist_from modules.im import MessageContextfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_sessions, messages, scopes+from storage.models import agent_events, agent_sessions, messages, scopesfrom storage.settings_service import upsert_scope@@ -93,7 +93,7 @@ def test_persist_agent_writes_typed_agent_row_on_same_scope(isolated_state):assert agent_row["scope_id"] == user_row["scope_id"]-def test_persist_agent_maps_canonical_type(isolated_state):+def test_persist_agent_toolcall_writes_event_not_message(isolated_state):ctx = _slack_ctx()mirror_inbound(ctx, "ping")persist_agent_message(ctx, "toolcall", "ran a tool")@@ -103,8 +103,13 @@ def test_persist_agent_maps_canonical_type(isolated_state):agent_row = conn.execute(select(messages).where(messages.c.author == "agent")).mappings().first()- # canonical 'toolcall' persists as the 'tool_call' type.- assert agent_row["type"] == "tool_call"+ event_row = conn.execute(select(agent_events)).mappings().first()+ assert agent_row is None+ assert event_row["event_type"] == "tool_call"+ assert event_row["visibility"] == "trace"+ assert event_row["platform"] == "slack"+ assert event_row["session_id"] is None+ assert event_row["content_text"] == "ran a tool"def test_persist_agent_im_uses_delivery_scope_not_session(isolated_state):@@ -310,6 +315,65 @@ def test_persist_agent_intermediate_persisted_but_not_streamed(isolated_state):assert [m["type"] for m in every["messages"]] == ["assistant"]+def test_persist_agent_toolcall_avibe_writes_event_without_streaming(isolated_state):+ """A tool-call stream item is trace data only: it is saved to agent_events,+ not messages, and does not publish chat/inbox updates."""+ from core import inbox_events++ engine = create_sqlite_engine()+ now = "2026-05-30T12:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_tool", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_tool",+ scope_id=scope_id,+ agent_name="Atlas",+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_ses_tool",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ ctx = MessageContext(+ user_id="workbench",+ channel_id="ses_tool",+ platform="avibe",+ platform_specific={+ "agent_session_id": "ses_tool",+ "turn_token": "turn_123",+ "task_execution_id": "run_123",+ },+ )++ async def scenario():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ persist_agent_message(ctx, "tool_call", "Tool input failed to parse")+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(queue.get(), timeout=0.1)+ finally:+ inbox_events.bus.unsubscribe(sub_id)++ asyncio.run(scenario())+ with engine.connect() as conn:+ message_row = conn.execute(select(messages).where(messages.c.session_id == "ses_tool")).first()+ event_row = conn.execute(select(agent_events).where(agent_events.c.session_id == "ses_tool")).mappings().one()+ assert message_row is None+ assert event_row["scope_id"] == scope_id+ assert event_row["agent_name"] == "Atlas"+ assert event_row["backend"] == "claude"+ assert event_row["turn_id"] == "turn_123"+ assert event_row["run_id"] == "run_123"+ assert event_row["content_text"] == "Tool input failed to parse"++def test_persist_system_message_is_not_persisted(isolated_state):"""A canonical ``system`` message (init banner / status line — generated byus, not the agent) is NOT persisted at all and publishes nothing (userdiff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex e3a3dd333..c1058ed0e 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260606_0019"+HEAD_REVISION = "20260608_0020"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:@@ -40,8 +40,19 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert "agent_runs" in tablesassert "show_pages" in tablesassert "show_session_events" in tables+ assert "agent_events" in tablesassert "media_objects" in tablesassert "web_push_subscriptions" in tables+ agent_event_indexes = {+ row[1]+ for row in conn.execute(+ "select seq, name from pragma_index_list('agent_events')",+ )+ }+ assert "ix_agent_events_session_created_id" in agent_event_indexes+ assert "ix_agent_events_session_type_created_id" in agent_event_indexes+ assert "ix_agent_events_scope_created_id" in agent_event_indexes+ assert "ix_agent_events_turn_sequence_id" in agent_event_indexesmessage_indexes = {row[1]for row in conn.execute(@@ -167,6 +178,33 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Pathassert "ix_agent_sessions_scope_status_activity" in agent_session_indexes+def test_run_migrations_adds_agent_events_from_previous_head(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"++ run_migrations(db_path, revision="20260606_0019")+ with sqlite3.connect(db_path) as conn:+ assert conn.execute("select name from sqlite_master where name = 'agent_events'").fetchone() is None+ version = conn.execute("select version_num from alembic_version").fetchone()+ assert version == ("20260606_0019",)++ run_migrations(db_path)+ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ version = conn.execute("select version_num from alembic_version").fetchone()+ agent_event_indexes = {+ row[1]+ for row in conn.execute(+ "select seq, name from pragma_index_list('agent_events')",+ )+ }+ assert version == (HEAD_REVISION,)+ assert "ix_agent_events_session_created_id" in agent_event_indexes+ assert "ix_agent_events_session_type_created_id" in agent_event_indexes+ assert "ix_agent_events_scope_created_id" in agent_event_indexes+ assert "ix_agent_events_turn_sequence_id" in agent_event_indexes++def test_run_migrations_runs_legacy_default_cleanup_when_stamping_existing_head_schema(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"engine = create_sqlite_engine(db_path)