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
refactor(agents): one typed output event set and a delivery receipt for every backend (#2872)
Call White7b380c0fdd34
diff --git a/core/agent_output.py b/core/agent_output.pynew file mode 100644index 000000000..ac3054eea--- /dev/null+++ b/core/agent_output.py@@ -0,0 +1,216 @@+"""One typed output event set for every agent backend (docs/plans/reply-and-turn-end.md).++A backend says what an output is, never how the dispatcher should treat it:++* ``Reply``: a complete answer that does not end the current Turn, or the answer of+ detached work (an Activity) that settles its own Runs;+* ``Narration``: text beside the work, Activity-only (long narration also gets the+ Web's muted ``interim`` copy);+* ``ToolActivity``: one tool call;+* ``TurnEnd``: the Turn's end, with its ``TurnOutcome`` and, when the final reply+ coincides with the end, that reply's text;+* ``AgentError``: a backend failure the user is told about;+* ``Notice``: any other visible notice from a backend (``notify``).++``emit_output`` is the single entry. ``dispatch_call`` is the one place an event+becomes the dispatcher's message type, lifecycle and options: a ``Reply`` never ends+the Turn, a ``TurnEnd`` always does and its outcome supplies the stop, teardown and+failure semantics. A backend passes a ``MessageOutput`` only as provenance and Run+lineage (identity, committed row, Activity or Run routing). Every emit answers with a+``DeliveryReceipt``, so delivery evidence is a type rather than a convention.+"""++from __future__ import annotations++from dataclasses import dataclass, replace+from enum import Enum+from typing import Any, Optional, Union++from core.citations import CitationBundle+from core.delivery_evidence import DeliveryEvidence+from core.message_output import MessageOutput, terminal_turn_output+from core.run_settlement import SETTLED_BY_BACKEND_REFRESH, SETTLED_BY_STOPPED+++class TurnOutcome(str, Enum):+ """How a Turn ended."""++ #: It finished; its reply, if any, is its answer.+ DONE = "done"+ #: The backend failed it.+ FAILED = "failed"+ #: The user stopped it: it releases the Turn and leaves its Runs to the stop's owner.+ STOPPED = "stopped"+ #: The service retired the backend runtime under it (``backend_refresh``).+ TEARDOWN = "teardown"+++@dataclass(frozen=True)+class Reply:+ """A complete answer that does not end the current Turn.++ It is a ``result`` (an ``error`` row when ``failed``) whatever follows it. Empty+ text is the content-free end of detached work whose ``output`` settles its own+ Runs (an Activity with nothing to show).+ """++ text: str+ parse_mode: Optional[str] = "markdown"+ citations: Optional[CitationBundle] = None+ footer: Optional[str] = None+ failed: bool = False+ output: Optional[MessageOutput] = None+++@dataclass(frozen=True)+class Narration:+ """Text beside the work; ``process_only`` keeps it out of the Web's ``interim`` copy."""++ text: str+ parse_mode: Optional[str] = "markdown"+ process_only: bool = False+ citations: Optional[CitationBundle] = None+ status_label: Optional[str] = None+ output: Optional[MessageOutput] = None+++@dataclass(frozen=True)+class ToolActivity:+ """One tool call: its line, its concise status label, its hosted-tool card."""++ text: str+ parse_mode: Optional[str] = "markdown"+ status_label: Optional[str] = None+ hosted: Optional[dict] = None+ citations: Optional[CitationBundle] = None+++@dataclass(frozen=True)+class TurnEnd:+ """The Turn's end.++ ``text`` is the final reply when it coincides with the end, empty for a+ content-free end; ``silent`` settles without a bubble even when there is text.+ ``output`` is the Turn's output policy and Run lineage (``request.output``).+ """++ outcome: TurnOutcome = TurnOutcome.DONE+ text: str = ""+ parse_mode: Optional[str] = "markdown"+ citations: Optional[CitationBundle] = None+ footer: Optional[str] = None+ silent: bool = False+ terminal_error: Optional[str] = None+ output: Optional[MessageOutput] = None+++@dataclass(frozen=True)+class AgentError:+ """A backend failure the user is told about; ``delivery`` records what the send proved."""++ text: str+ parse_mode: Optional[str] = "markdown"+ output: Optional[MessageOutput] = None+ delivery: Optional[DeliveryEvidence] = None+++@dataclass(frozen=True)+class Notice:+ """Any other visible notice from a backend: neither a reply nor a failure."""++ text: str+ parse_mode: Optional[str] = "markdown"+++AgentOutputEvent = Union[Reply, Narration, ToolActivity, TurnEnd, AgentError, Notice]+++@dataclass(frozen=True)+class DeliveryReceipt:+ """What an emit proved: the delivered message's id, None when nothing was delivered.++ On the Web and in a background Session the receipt is the persisted row; on IM the+ message the platform accepted.+ """++ message_id: Optional[Any] = None++ @property+ def delivered(self) -> bool:+ return self.message_id is not None+++def _turn_end_output(event: TurnEnd) -> MessageOutput:+ base = event.output or terminal_turn_output()+ if event.outcome is TurnOutcome.STOPPED:+ return replace(base, completes_turn=True, completes_run=False, settled_by=SETTLED_BY_STOPPED)+ if event.outcome is TurnOutcome.TEARDOWN:+ return replace(base, completes_turn=True, completes_run=False, settled_by=SETTLED_BY_BACKEND_REFRESH)+ if not base.completes_turn:+ raise ValueError("a TurnEnd's output must end the Turn; detached work answers with a Reply")+ return base+++def dispatch_call(event: AgentOutputEvent) -> tuple[str, str, dict[str, Any]]:+ """The dispatcher's ``(message_type, text, options)`` for one event.++ Options a dispatcher stand-in may not accept (citations, status labels, hosted+ cards, footers, failure details, delivery evidence) are passed only when set, as+ every caller passed them before.+ """++ def optional(**values: Any) -> dict[str, Any]:+ return {key: value for key, value in values.items() if value}++ if isinstance(event, Reply):+ output = event.output or MessageOutput(completes_turn=False, completes_run=False)+ if output.completes_turn:+ raise ValueError("a Reply never ends the Turn; its end is a TurnEnd")+ return "result", event.text, {+ "parse_mode": event.parse_mode,+ "output": output,+ **optional(is_error=event.failed, result_footer=event.footer, citations=event.citations),+ }+ if isinstance(event, Narration):+ return "assistant", event.text, {+ "parse_mode": event.parse_mode,+ **optional(+ level="process" if event.process_only else None,+ status_label=event.status_label,+ output=event.output,+ citations=event.citations,+ ),+ }+ if isinstance(event, ToolActivity):+ return "toolcall", event.text, {+ "parse_mode": event.parse_mode,+ **optional(status_label=event.status_label, hosted=event.hosted, citations=event.citations),+ }+ if isinstance(event, TurnEnd):+ return "result", event.text, {+ "parse_mode": event.parse_mode,+ "output": _turn_end_output(event),+ **optional(+ is_error=event.outcome in (TurnOutcome.FAILED, TurnOutcome.TEARDOWN),+ level="silent" if event.silent else None,+ result_footer=event.footer,+ terminal_error=event.terminal_error,+ citations=event.citations,+ ),+ }+ if isinstance(event, AgentError):+ return "notify", event.text, {+ "parse_mode": event.parse_mode,+ **optional(output=event.output, delivery=event.delivery),+ }+ if isinstance(event, Notice):+ return "notify", event.text, {"parse_mode": event.parse_mode}+ raise TypeError(f"not an agent output event: {event!r}")+++async def emit_output(controller: Any, context: Any, event: AgentOutputEvent) -> DeliveryReceipt:+ """Emit one backend output through the dispatcher; the single entry every backend uses."""++ message_type, text, options = dispatch_call(event)+ message_id = await controller.emit_agent_message(context, message_type, text, **options)+ return DeliveryReceipt(message_id)diff --git a/core/backend_failure.py b/core/backend_failure.pyindex 1589a3acd..1c9c81317 100644--- a/core/backend_failure.py+++ b/core/backend_failure.py@@ -7,6 +7,7 @@ from dataclasses import replacefrom inspect import Parameter, signaturefrom typing import Any+from core.agent_output import AgentError, TurnEnd, TurnOutcome, emit_outputfrom core.delivery_evidence import (ACK_EVIDENCE_DELIVERY_ONLY,ACK_EVIDENCE_RECEIPT,@@ -347,15 +348,7 @@ async def emit_replayed_backend_failure()# ``delivery`` is passed ONLY when a caller asked for it: controller-like objects# that implement ``emit_agent_message`` without the keyword must keep working.- notify_kwargs: dict[str, Any] = {"output": notification}- if delivery is not None:- notify_kwargs["delivery"] = delivery- await controller.emit_agent_message(- context,- "notify",- visible,- **notify_kwargs,- )+ await emit_output(controller, context, AgentError(visible, output=notification, delivery=delivery))async def emit_backend_failure(@@ -449,14 +442,10 @@ async def emit_backend_failure(failure_id=notification_identity,delivery=live_delivery,)- await controller.emit_agent_message(+ await emit_output(+ controller,context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output,- terminal_error=error,+ TurnEnd(outcome=TurnOutcome.FAILED, silent=True, terminal_error=error, output=terminal_output),)# Auth recovery is unconditional for non-Harness live callers, and there is no@@ -495,7 +484,7 @@ async def emit_backend_failure(# ``delivery`` is passed only when the emitter supports it. Durable Turn and# Harness contexts create the object automatically, but controller-like test# and integration doubles with the legacy signature must keep working.- notify_kwargs: dict[str, Any] = {"output": notification}+ accepts_delivery = Falseif live_delivery is not None:emit = controller.emit_agent_messagetry:@@ -506,22 +495,19 @@ async def emit_backend_failure()except (TypeError, ValueError):accepts_delivery = False- if accepts_delivery:- notify_kwargs["delivery"] = live_deliverytry:- delivered_id = await controller.emit_agent_message(+ receipt = await emit_output(+ controller,context,- "notify",- visible,- **notify_kwargs,+ AgentError(visible, output=notification, delivery=live_delivery if accepts_delivery else None),)if (live_delivery is not Noneand live_delivery.delivered_id is None- and delivered_id is not None+ and receipt.deliveredand not bool((context.platform_specific or {}).get("suppress_delivery"))):- live_delivery.delivered_id = str(delivered_id)+ live_delivery.delivered_id = str(receipt.message_id)live_delivery.send_returned = Truefinally:await settle_terminal_failure()diff --git a/docs/plans/reply-and-turn-end.md b/docs/plans/reply-and-turn-end.mdindex df173f68c..c4521e53f 100644--- a/docs/plans/reply-and-turn-end.md+++ b/docs/plans/reply-and-turn-end.md@@ -1,9 +1,9 @@# A reply is not the end of a TurnStatus: approved by the owner (cyhhao), 2026-10-19. PR 1 (merged): shared-contract, Vibey, and Claude's pre-steer phase typed as a reply. PR 2a: Codex and-OpenCode on the reply rule, and rule 5 owned by the dispatcher. PR 2b and later:-see Next steps.+contract, Vibey, and Claude's pre-steer phase typed as a reply. PR 2a (merged):+Codex and OpenCode on the reply rule, and rule 5 owned by the dispatcher. PR 2b:+typed output events. Later: see Next steps.## Background@@ -295,7 +295,9 @@ Scenarios `MESSAGE-DELIVERY-334` (PR 1) and `MESSAGE-DELIVERY-335` (PR 2a)- Activity grouping, fork completion, and the UI message-role helpers keep theirrendering for single-reply Turns and treat a mid-Turn reply as a phaseboundary.-- PR 2b: one primary regression per backend at its owning boundary.+- PR 2b: the event-to-dispatcher mapping is table-tested (`MESSAGE-DELIVERY-336`);+ every existing suite passes with only mechanical updates (canonical options on+ asserted calls, receipts instead of raw ids).## Next steps@@ -314,8 +316,10 @@ Approved by the owner, in this order:included. A footer-only end is content-free.- PR 2b (structural only, no behavior change, branched from master after2a merges): every backend, Vibey included, reports output through one- typed event set: reply, narration, tool activity, turn end (outcome), and- error. This replaces type strings plus `MessageOutput` flags, so the+ typed event set (`core/agent_output.py`): reply, narration, tool activity,+ turn end (outcome), error, and notice for the rest of a backend's visible+ notices. Vibey's generated-images fallback keeps its released `output` type+ on the legacy entry until the presentation decision point (PR 3). This replaces type strings plus `MessageOutput` flags, so thedispatcher no longer infers semantics. Vibey's agent-event schema is thestarting point, and rule 5 moves onto the typed Turn-end event. Emitsreturn a typed delivery receipt (delivered, with its receipt row or thediff --git a/modules/agents/base.py b/modules/agents/base.pyindex dedbcdfde..7aa3bc503 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -13,6 +13,7 @@ from modules.im import MessageContextfrom modules.im.base import FileAttachmentfrom core.agent_input import AgentInputMetadatafrom core.agent_session_context import resolve_context_agent_session_target+from core.agent_output import DeliveryReceipt, Reply, TurnEnd, TurnOutcome, emit_outputfrom core.citations import CitationBundlefrom core.message_output import MessageOutput, terminal_turn_outputfrom core.reply_enhancer import strip_silent_blocks@@ -607,8 +608,10 @@ class BaseAgent(ABC):request: Optional[AgentRequest] = None,output: MessageOutput | None = None,citations: Optional[CitationBundle] = None,- ) -> Optional[str]:- """Emit a terminal result.+ ) -> DeliveryReceipt:+ """Emit a backend's result: the Turn's end, or detached work's reply.++ Returns the emit's ``DeliveryReceipt``.``citations`` is the registered source bundle for the answer body (see``core.citations``): the body carries an opaque token where each cited@@ -637,59 +640,29 @@ class BaseAgent(ABC):visible_result = strip_silent_blocks(raw_result)visible_suffix = strip_silent_blocks(raw_suffix) if raw_suffix else Nonehas_silent_directive = "<silent" in raw_result.lower() or "<silent" in raw_suffix.lower()- message_id: Optional[str] = Noneif has_silent_directive and not visible_result.strip() and not (visible_suffix or "").strip():- message_id = await self.controller.emit_agent_message(+ receipt = await emit_output(+ self.controller,context,- "result",- "",- parse_mode=parse_mode,- is_error=is_error,- output=output,+ self._result_event("", parse_mode=parse_mode, failed=is_error, output=output),)if request and settles_request:await self._remove_ack_reaction(request)- return message_id+ return receipt- # When show_duration is disabled, skip the entire result line- # unless there is actual result_text or suffix to deliver.+ result_footer: Optional[str] = Noneif not show_duration:+ # When show_duration is disabled, skip the entire result line unless+ # there is actual result_text or suffix to deliver. No visible text is+ # still a TERMINAL turn: its empty end settles it through the outbound+ # status chokepoint (dot idle / failed, the web-Chat stream released).parts = []if raw_result and raw_result.strip():parts.append(raw_result)if raw_suffix:parts.append(raw_suffix)- if parts:- formatted = "\n".join(parts)- message_id = await self.controller.emit_agent_message(- context,- "result",- formatted,- parse_mode=parse_mode,- is_error=is_error,- output=output,- # Forwarded ONLY when there is a sidecar to carry, for the- # reason ``controller.emit_agent_message`` gives when it- # forwards the same value: the controller is a substitutable- # collaborator, and an always-present keyword would change the- # required signature of every stand-in that has none.- **({"citations": citations} if citations else {}),- )- else:- # No visible text (show_duration off + empty result/suffix) is still- # a TERMINAL turn: settle it through the OUTBOUND status chokepoint- # (empty result → dot idle / failed AND releases the web-Chat stream- # waiter), mirroring the silent-directive path above — otherwise the- # dot stays green and the stream hangs until the 600s timeout (Codex P2).- message_id = await self.controller.emit_agent_message(- context,- "result",- "",- parse_mode=parse_mode,- is_error=is_error,- output=output,- )+ body = "\n".join(parts)else:token_field = ""get_token_field = getattr(self.controller, "session_token_field", None)@@ -713,27 +686,59 @@ class BaseAgent(ABC):parts.append(raw_result)if raw_suffix:parts.append(raw_suffix)- body = "\n".join(parts)# A footer is never a reply: with no visible result or suffix this is the# Turn's content-free end, and the footer rides only as ``result_footer``# (the concise status bubble still shows its done line). The dispatcher# settles the Turn's Runs with its last reply, if any# (docs/plans/reply-and-turn-end.md).- message_id = await self.controller.emit_agent_message(- context,- "result",+ body = "\n".join(parts)+ receipt = await emit_output(+ self.controller,+ context,+ self._result_event(body,parse_mode=parse_mode,- is_error=is_error,- result_footer=result_footer,+ failed=is_error,output=output,- **({"citations": citations} if citations else {}),- )+ footer=result_footer,+ # The sidecar rides only with a body to carry it.+ citations=citations if body else None,+ ),+ )# Remove ack reaction after result is sentif request and settles_request:await self._remove_ack_reaction(request)- return message_id+ return receipt++ @staticmethod+ def _result_event(+ text: str,+ *,+ parse_mode: Optional[str],+ failed: bool,+ output: MessageOutput,+ footer: Optional[str] = None,+ citations: Optional[CitationBundle] = None,+ ) -> Reply | TurnEnd:+ """A result's event: the Turn's end when its output ends the Turn, else a reply.++ Detached work (an Activity) answers through this path with an output that+ does not end the current Turn; its answer is a reply that settles its own Runs.+ """++ if output.completes_turn:+ return TurnEnd(+ outcome=TurnOutcome.FAILED if failed else TurnOutcome.DONE,+ text=text,+ parse_mode=parse_mode,+ citations=citations,+ footer=footer,+ output=output,+ )+ return Reply(+ text=text, parse_mode=parse_mode, citations=citations, footer=footer, failed=failed, output=output+ )@abstractmethodasync def handle_message(self, request: AgentRequest) -> None:diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex b40ba46f8..2a925d414 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -14,12 +14,20 @@ from core.handlers.session_handler import (ClaudeInputNotSentError,ClaudeSessionNotFoundError,)+from core.agent_output import (+ DeliveryReceipt,+ Narration,+ Notice,+ Reply,+ ToolActivity,+ TurnEnd,+ TurnOutcome,+ emit_output,+)from core.message_dispatcher import ActivityOutputDeliveryErrorfrom core.message_output import (HARNESS_RUN_ID_TRIGGER_KINDS,MessageOutput,- contained_teardown_output_for,- stop_output_for,terminal_output_for,terminal_turn_output,)@@ -912,18 +920,15 @@ class ClaudeAgent(BaseAgent):machine-readable cause; the footer only has to stop claiming success."""- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,context,- "result",- "",- is_error=True,- level="silent",- output=(- contained_teardown_output_for(request)- if contained- else terminal_output_for(request)+ TurnEnd(+ outcome=TurnOutcome.TEARDOWN if contained else TurnOutcome.FAILED,+ silent=True,+ terminal_error=None if contained else diagnostic,+ output=terminal_output_for(request),),- terminal_error=None if contained else diagnostic,)def _release_service_runtime_turn(self, context: MessageContext) -> None:@@ -965,10 +970,13 @@ class ClaudeAgent(BaseAgent):AskUserQuestion programmatically. See: https://github.com/anthropics/claude-code/issues/10168"""# AskUserQuestion support disabled- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,request.context,- "notify",- "AskUserQuestion support is currently disabled. Claude Code SDK does not support programmatic responses to this tool.",+ Notice(+ "AskUserQuestion support is currently disabled. Claude Code SDK does not support programmatic"+ " responses to this tool."+ ),)return@@ -1422,13 +1430,10 @@ class ClaudeAgent(BaseAgent):if context is not None:try:- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output_for(pending_request),+ TurnEnd(outcome=TurnOutcome.FAILED, silent=True, output=terminal_output_for(pending_request)),)except Exception:logger.debug(@@ -1936,10 +1941,8 @@ class ClaudeAgent(BaseAgent):client = self.claude_sessions[composite_key]if not hasattr(client, "interrupt"):request.stop_failure_reason = "unsupported"- await self.controller.emit_agent_message(- request.context,- "notify",- "⚠️ This Claude session cannot be interrupted; consider /new.",+ await emit_output(+ self.controller, request.context, Notice("⚠️ This Claude session cannot be interrupted; consider /new."))return False@@ -1974,10 +1977,8 @@ class ClaudeAgent(BaseAgent):except Exception as err:request.stop_failure_reason = "interrupt_failed"logger.error(f"Failed to interrupt Claude session {composite_key}: {err}")- await self.controller.emit_agent_message(- request.context,- "notify",- "⚠️ Failed to interrupt Claude session. Please try /new.",+ await emit_output(+ self.controller, request.context, Notice("⚠️ Failed to interrupt Claude session. Please try /new."))return False@@ -2030,12 +2031,10 @@ class ClaudeAgent(BaseAgent):# disconnecting. ``stop_output_for`` (not the terminal-turn default) keeps# this empty body out of the run's terminal state so the stop settles it# ``canceled`` instead of ``succeeded`` — see its docstring.- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,request.context,- "result",- "",- level="silent",- output=stop_output_for(request),+ TurnEnd(outcome=TurnOutcome.STOPPED, silent=True, output=terminal_output_for(request)),)except Exception as err:logger.error("Failed to emit Claude stop result for session %s: %s", composite_key, err, exc_info=True)@@ -2449,23 +2448,16 @@ class ClaudeAgent(BaseAgent):pending = self._pending_assistant_message.pop(composite_key, None)if pending:- await self.controller.emit_agent_message(- context,- "assistant",- pending,- parse_mode="markdown",- )+ await emit_output(self.controller, context, Narration(pending))for toolcall_text, toolcall_label in toolcalls:# Persisted/verbose text stays the original# ``format_toolcall`` output; ``status_label`` carries# the clean claude-pipe label for the concise bubble only.- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,context,- "toolcall",- toolcall_text,- parse_mode="markdown",- status_label=toolcall_label,+ ToolActivity(toolcall_text, status_label=toolcall_label),)if text_parts:@@ -4008,12 +4000,14 @@ class ClaudeAgent(BaseAgent):settled = asyncio.Event()self._synthetic_owner_settlements[composite_key] = settledtry:- await self.controller.emit_agent_message(+ # Releases the Turn only: another owner settles its Runs.+ await emit_output(+ self.controller,owner_context,- "result",- "",- is_error=is_error,- output=MessageOutput(completes_turn=True, completes_run=False),+ TurnEnd(+ outcome=TurnOutcome.FAILED if is_error else TurnOutcome.DONE,+ output=MessageOutput(completes_turn=True, completes_run=False),+ ),)except BaseException as exc:# No backend result will ever arrive for this Turn again and its@@ -4812,19 +4806,12 @@ class ClaudeAgent(BaseAgent):)previous = self._pending_assistant_message.pop(composite_key, None)if previous:- await self.controller.emit_agent_message(- context,- "assistant",- previous,- parse_mode="markdown",- )+ await emit_output(self.controller, context, Narration(previous))for toolcall_text, toolcall_label in toolcalls:- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,context,- "toolcall",- toolcall_text,- parse_mode="markdown",- status_label=toolcall_label,+ ToolActivity(toolcall_text, status_label=toolcall_label),)if assistant_text:self._pending_assistant_message[composite_key] = assistant_text@@ -4894,17 +4881,11 @@ class ClaudeAgent(BaseAgent):)# A completed phase is a reply like any other: a ``result`` that does not end# the Turn (docs/plans/reply-and-turn-end.md).- message_id = await self.controller.emit_agent_message(- context,- "result",- emitted_text,- parse_mode="markdown",- output=output,- )+ receipt = await emit_output(self.controller, context, Reply(emitted_text, output=output))if activity is None:returnif strip_silent_blocks(emitted_text).strip():- self._require_activity_delivery(activity, message_id)+ self._require_activity_delivery(activity, receipt)self._clear_request_activities(request)if request is not None:request.output = terminal_turn_output()@@ -5371,9 +5352,9 @@ class ClaudeAgent(BaseAgent):@staticmethoddef _require_activity_delivery(activity: SessionActivity,- message_id: str | None,+ receipt: DeliveryReceipt,) -> None:- if message_id is None:+ if not receipt.delivered:raise ActivityOutputDeliveryError(f"Claude Activity output {activity.id} was not persisted or delivered",delivered=False,@@ -5386,12 +5367,10 @@ class ClaudeAgent(BaseAgent):"""Close the origin Turn if delivery failed before its terminal chokepoint."""try:- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,context,- "result",- "",- level="silent",- output=MessageOutput(completes_turn=True, completes_run=False),+ TurnEnd(silent=True, output=MessageOutput(completes_turn=True, completes_run=False)),)except Exception:logger.debug(@@ -5429,15 +5408,14 @@ class ClaudeAgent(BaseAgent):)visible_text = str(text or "")if not strip_silent_blocks(visible_text).strip():- await self.controller.emit_agent_message(+ # The Turn's content-free end, or detached work's content-free answer.+ await emit_output(+ self.controller,context,- "result",- "",- is_error=(subtype or "").startswith("error"),- output=output,+ self._result_event("", parse_mode="markdown", failed=(subtype or "").startswith("error"), output=output),)return- message_id = await self.emit_result_message(+ receipt = await self.emit_result_message(context,visible_text,subtype=subtype,@@ -5446,7 +5424,7 @@ class ClaudeAgent(BaseAgent):request=request,output=output,)- self._require_activity_delivery(activity, message_id)+ self._require_activity_delivery(activity, receipt)@staticmethoddef _unsolicited_message_output(@@ -5591,14 +5569,14 @@ class ClaudeAgent(BaseAgent):activities=record.activities, output=output,)elif record.text:- message_id = await self.emit_result_message(+ receipt = await self.emit_result_message(record.context or context, record.text,subtype=record.subtype, duration_ms=record.duration_ms,parse_mode="markdown", output=record.output,)# A silent-only reply settles without a Message, so it has no# receipt; retrying it would block every later record.- if message_id is None and strip_silent_blocks(record.text).strip():+ if not receipt.delivered and strip_silent_blocks(record.text).strip():raise ActivityOutputDeliveryError("Claude detached output was not accepted", delivered=False,)@@ -6398,12 +6376,7 @@ class ClaudeAgent(BaseAgent):original_model or "<unknown>",fallback_model or "<unknown>",)- await self.controller.emit_agent_message(- context,- "notify",- text,- parse_mode="markdown",- )+ await emit_output(self.controller, context, Notice(text))async def _handle_auth_failure_result(self,diff --git a/modules/agents/claude_question_handler.py b/modules/agents/claude_question_handler.pyindex ce00aa071..9699b295e 100644--- a/modules/agents/claude_question_handler.py+++ b/modules/agents/claude_question_handler.py@@ -13,6 +13,7 @@ import jsonimport loggingfrom typing import Any, Dict, List, Optional, TYPE_CHECKING+from core.agent_output import Notice, emit_outputfrom modules.agents.base import AgentRequestfrom modules.agents.question_ui import (Question,@@ -181,21 +182,15 @@ class ClaudeQuestionHandler:client is not None,composite_session_id,)- await self._controller.emit_agent_message(- request.context,- "notify",- "Claude question context is missing. Please retry your request.",+ await emit_output(+ self._controller, request.context, Notice("Claude question context is missing. Please retry your request."))return False# Parse answer from callback dataanswers_payload = self._parse_answer(request.message, pending)if answers_payload is None:- await self._controller.emit_agent_message(- request.context,- "notify",- "Please provide an answer.",- )+ await emit_output(self._controller, request.context, Notice("Please provide an answer."))return False# Update UI to show selection@@ -209,10 +204,8 @@ class ClaudeQuestionHandler:await self._submit_tool_result(client, composite_session_id, tool_use_id, answer_text)except Exception as err:logger.error(f"Failed to submit answer to Claude: {err}", exc_info=True)- await self._controller.emit_agent_message(- request.context,- "notify",- f"Failed to submit answer to Claude: {err}. Please retry.",+ await emit_output(+ self._controller, request.context, Notice(f"Failed to submit answer to Claude: {err}. Please retry."))return Falsediff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 60cb494d7..4040d928f 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -26,7 +26,8 @@ from config.v2_config import (from core.backend_failure import emit_backend_failurefrom core.agent_input import AgentInputMetadatafrom core.caller_context import caller_env_for_platform_payload-from core.message_output import stop_output_for, terminal_output_for+from core.agent_output import TurnEnd, TurnOutcome, emit_output+from core.message_output import terminal_output_forfrom core.managed_skills import (managed_skill_environment,managed_skill_project_base,@@ -1315,15 +1316,13 @@ class CodexAgent(BaseAgent):# bubble. The user already knows they stopped it (avibe shows the dot go# idle; IM shows the ⏹️ receipt stamped above). ``level="silent"`` is# the explicit visibility grade rather than faking it via empty text.- # ``stop_output_for`` (not the terminal-turn default) keeps this empty body+ # A ``STOPPED`` end (not the terminal-turn default) keeps this empty body# out of the run's terminal state so the stop settles it ``canceled``- # instead of ``succeeded`` — see its docstring.- await self.controller.emit_agent_message(+ # instead of ``succeeded`` (``stop_output_for`` explains why).+ await emit_output(+ self.controller,request.context,- "result",- "",- level="silent",- output=stop_output_for(request),+ TurnEnd(outcome=TurnOutcome.STOPPED, silent=True, output=terminal_output_for(request)),)logger.info("Codex turn %s interrupted via /stop", turn_id)return Truediff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex 514110b53..5859ee9ef 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Collection, Mappingfrom vibe.i18n import t as i18n_t+from core.agent_output import Narration, Reply, ToolActivity, emit_outputfrom core.backend_failure import emit_backend_failurefrom core.message_output import MessageOutputfrom core.citations import (@@ -631,28 +632,26 @@ class CodexEventHandler:level: str = "normal",output_key: str | None = None,) -> None:- await self._agent.controller.emit_agent_message(- request.context,- role,- text,- parse_mode=parse_mode or "markdown",+ event: Reply | Narration | ToolActivity+ if role == _REPLY_ROLE:# A reply that does not end the Turn, identified by its item id so two- # replies with the same text stay two; narration keeps the call it had.- **(- {- "output": MessageOutput(- completes_turn=False, completes_run=False, idempotency_key=output_key- )- }- if role == _REPLY_ROLE- else {}- ),- # Forwarded only when non-default, like ``citations`` below.- **({"level": level} if level != "normal" else {}),- # Forwarded only when there is a sidecar, so a message without- # citations keeps the call it always had.- **({"citations": citations} if citations else {}),- )+ # replies with the same text stay two.+ event = Reply(+ text or "",+ parse_mode=parse_mode or "markdown",+ citations=citations,+ output=MessageOutput(completes_turn=False, completes_run=False, idempotency_key=output_key),+ )+ elif role == "toolcall":+ event = ToolActivity(text or "", parse_mode=parse_mode or "markdown", citations=citations)+ else:+ event = Narration(+ text or "",+ parse_mode=parse_mode or "markdown",+ process_only=level == "process",+ citations=citations,+ )+ await emit_output(self._agent.controller, request.context, event)async def _drain_narration(self, turn_state: CodexTurnState | None, *, force: bool = Falsediff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex f888f9686..fe02b9ac4 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -29,7 +29,8 @@ from core.caller_context import (caller_env_for_platform_payload,validated_caller_env_snapshot,)-from core.message_output import stop_output_for+from core.agent_output import TurnEnd, TurnOutcome, emit_output+from core.message_output import terminal_output_forfrom core.managed_skills import (BUILTIN_SKILLS_ROOT_ENV,managed_skill_environment,@@ -2604,15 +2605,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# user-facing message: a single SILENT result settles the dot to idle +# releases the SSE waiter through the outbound chokepoint without a bubble# (``level="silent"`` makes that explicit rather than faking it via empty text).- # ``stop_output_for`` (not the terminal-turn default) keeps this empty body out+ # A ``STOPPED`` end (not the terminal-turn default) keeps this empty body out# of the run's terminal state so the stop settles it ``canceled`` instead of- # ``succeeded`` — see its docstring.- await self.controller.emit_agent_message(+ # ``succeeded`` (``stop_output_for`` explains why).+ await emit_output(+ self.controller,request.context,- "result",- "",- level="silent",- output=stop_output_for(request),+ TurnEnd(outcome=TurnOutcome.STOPPED, silent=True, output=terminal_output_for(request)),)logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")return Truediff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 7324c667c..48796292d 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -16,6 +16,7 @@ from config.v2_config import (from core.backend_failure import emit_backend_failurefrom core.handlers.model_hub.retry import RECOVERY_EXHAUSTED_CODEfrom core.message_context import build_context_session_key+from core.agent_output import Narration, Notice, Reply, ToolActivity, TurnEnd, TurnOutcome, emit_outputfrom core.message_output import MessageOutput, terminal_output_for, terminal_turn_outputfrom core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.reply_enhancer import strip_silent_blocks@@ -555,18 +556,19 @@ class OpenCodePollLoop:message_id,settlement_id,)- delivered = await self._agent.controller.emit_agent_message(+ receipt = await emit_output(+ self._agent.controller,context,- "result",- text,- parse_mode="markdown",# OpenCode's message id: two replies with the same text stay two# deliveries, and a restored poll's replay of one stays one.- output=MessageOutput(- completes_turn=False, completes_run=False, idempotency_key=str(message_id)+ Reply(+ text,+ output=MessageOutput(+ completes_turn=False, completes_run=False, idempotency_key=str(message_id)+ ),),)- if not delivered:+ if not receipt.delivered:logger.warning("OpenCode reply %s was not delivered; it stays unrecorded as emitted",message_id,@@ -727,12 +729,10 @@ class OpenCodePollLoop:logger.warning("Aborting OpenCode session %s after disabled question tool call", session_id)# Terminal abort → error RESULT so the outbound chokepoint# turns the dot red (not a bare notify that never settles it).- await self._agent.controller.emit_agent_message(+ await emit_output(+ self._agent.controller,request.context,- "result",- message,- is_error=True,- output=terminal_output_for(request),+ TurnEnd(outcome=TurnOutcome.FAILED, text=message, output=terminal_output_for(request)),)try:await server.abort_session(session_id, request.working_path)@@ -745,12 +745,7 @@ class OpenCodePollLoop:tool_input,get_relative_path=_relative_path,)- await self._agent.controller.emit_agent_message(- request.context,- "toolcall",- toolcall,- parse_mode="markdown",- )+ await emit_output(self._agent.controller, request.context, ToolActivity(toolcall))seen_tool_calls.add(call_key)if (@@ -760,12 +755,7 @@ class OpenCodePollLoop:):text = self._agent._extract_response_text(message)if text:- await self._agent.controller.emit_agent_message(- request.context,- "assistant",- text,- parse_mode="markdown",- )+ await emit_output(self._agent.controller, request.context, Narration(text))emitted_assistant_messages.add(message_id)self._persist_emitted_assistant_messages(session_id, emitted_assistant_messages@@ -929,10 +919,8 @@ class OpenCodePollLoop:)bind_persisted_launch(context, processing_snapshot.get("model_hub_launch"))- await self._agent.controller.emit_agent_message(- context,- "notify",- "Resuming interrupted OpenCode session after restart...",+ await emit_output(+ self._agent.controller, context, Notice("Resuming interrupted OpenCode session after restart..."))baseline_message_ids = set(poll_info.baseline_message_ids)@@ -1065,12 +1053,10 @@ class OpenCodePollLoop:session_id,)# Terminal abort → error RESULT (settles the dot red).- await self._agent.controller.emit_agent_message(+ await emit_output(+ self._agent.controller,context,- "result",- message,- is_error=True,- output=terminal_turn_output(),+ TurnEnd(outcome=TurnOutcome.FAILED, text=message, output=terminal_turn_output()),)try:await server.abort_session(session_id, poll_info.working_path)@@ -1105,7 +1091,7 @@ class OpenCodePollLoop:if path:tool_summary = f"`{tool_name}`: `{_relative_path(path)}`"- await self._agent.controller.emit_agent_message(context, "tool_call", tool_summary)+ await emit_output(self._agent.controller, context, ToolActivity(tool_summary))if (info.get("time", {}).get("completed")@@ -1114,12 +1100,7 @@ class OpenCodePollLoop:):text = self._agent._extract_response_text(message)if text:- await self._agent.controller.emit_agent_message(- context,- "assistant",- text,- parse_mode="markdown",- )+ await emit_output(self._agent.controller, context, Narration(text))emitted_assistant_messages.add(message_id)poll_info.emitted_assistant_messages = sorted(emitted_assistant_messages)self._persist_emitted_assistant_messages(diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 832249f42..3c2e63ade 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -87,9 +87,10 @@ from core.services.agent_steering import (result as steer_result,)from core.backend_failure import emit_backend_failure+from core.agent_output import Narration, Reply, ToolActivity, TurnEnd, TurnOutcome, emit_outputfrom core.citations import CitationBundle, register_text_citationsfrom core.hosted_activity import HostedActivity, hosted_line, native_activities, proxy_activity-from core.message_output import MessageOutput, stop_output_for, terminal_output_for+from core.message_output import MessageOutput, terminal_output_forfrom core.native_dispatch_phase import mark_backend_dispatch_attemptedfrom core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.reply_enhancer import strip_silent_blocks@@ -961,9 +962,7 @@ class VibeyAgent(BaseAgent):else:# A reply the model chose to keep silent: the Turn's end with no reply of# its own; any earlier reply in the Turn was already delivered as one.- await self.controller.emit_agent_message(- context, "result", "", output=terminal_output_for(request)- )+ await emit_output(self.controller, context, TurnEnd(output=terminal_output_for(request)))return# Generated images are paid for and already announced: they reach the user# whether or not a final reply follows.@@ -971,15 +970,15 @@ class VibeyAgent(BaseAgent):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)+ await emit_output(+ self.controller,+ context,+ TurnEnd(outcome=TurnOutcome.STOPPED, silent=True, output=terminal_output_for(request)),)returnif 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)- )+ await emit_output(self.controller, context, TurnEnd(silent=True, output=terminal_output_for(request)))returnself._log_failure(run, reason, kind, origin, diagnostic)await self._fail(request, kind, diagnostic, reason=reason, refusal=run.refusal, source=source)@@ -1524,7 +1523,7 @@ class VibeyAgent(BaseAgent):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."""- await self._emit_non_final(run, row_id, "assistant")+ await self._emit_non_final(run, row_id, reply=False)async def _emit_reply(self, run: _Run, row_id: str) -> None:"""A completed reply later input took the final word from: a ``result`` that does not end the Turn.@@ -1533,28 +1532,32 @@ class VibeyAgent(BaseAgent):it is green, notifies, and counts as unread like the final, whatever itslength; the steered input's answer is the Turn's next reply."""- await self._emit_non_final(run, row_id, "result")+ await self._emit_non_final(run, row_id, reply=True)- async def _emit_non_final(self, run: _Run, row_id: str, message_type: str) -> None:+ async def _emit_non_final(self, run: _Run, row_id: str, *, reply: bool) -> None:message = run.responses.get(row_id)body, citations = self._display_with_citations(message, final=False) if message is not None else ("", None)if not body.strip():return- try:- await self.controller.emit_agent_message(- run.request.context,- message_type,+ event: Reply | Narration+ if reply:+ # A reply is identified by its committed row: two replies with the same+ # text stay two, and a replay of one stays one.+ event = Reply(body,+ citations=citations,output=MessageOutput(- completes_turn=False,- completes_run=False,- persisted_row_id=row_id,- # A reply is identified by its committed row: two replies with the- # same text stay two, and a replay of one stays one.- idempotency_key=row_id if message_type == "result" else None,+ completes_turn=False, completes_run=False, persisted_row_id=row_id, idempotency_key=row_id),+ )+ else:+ event = Narration(+ body,citations=citations,+ output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id=row_id),)+ try:+ await emit_output(self.controller, run.request.context, event)except Exception:logger.exception("Vibey could not show response %s", row_id)@@ -1619,6 +1622,8 @@ class VibeyAgent(BaseAgent):if not links:returntry:+ # The released ``output`` type stays until the presentation decision point+ # (docs/plans/reply-and-turn-end.md, PR 3): not a reply, not a notice.await self.controller.emit_agent_message(run.request.context,"output",@@ -1657,8 +1662,10 @@ class VibeyAgent(BaseAgent):formatter = self._get_formatter(run.request.context)line = hosted_line(activity, self._language(), escape=formatter.escape_special_chars)try:- await self.controller.emit_agent_message(- run.request.context, "toolcall", line, status_label=line, hosted=activity.to_payload()+ await emit_output(+ self.controller,+ run.request.context,+ ToolActivity(line, status_label=line, hosted=activity.to_payload()),)except Exception:logger.exception("Vibey could not show hosted call %s", activity.call_id)@@ -1711,11 +1718,13 @@ class VibeyAgent(BaseAgent):formatter = self._get_formatter(run.request.context)relative = _relative_to(run.cwd)try:- await self.controller.emit_agent_message(+ await emit_output(+ self.controller,run.request.context,- "toolcall",- formatter.format_toolcall(name, arguments, get_relative_path=relative),- status_label=formatter.format_toolcall_label(name, arguments, get_relative_path=relative),+ ToolActivity(+ formatter.format_toolcall(name, arguments, get_relative_path=relative),+ status_label=formatter.format_toolcall_label(name, arguments, get_relative_path=relative),+ ),)except Exception:logger.exception("Vibey could not show tool %s", name)diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 9643da906..a57c743c8 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -513,5 +513,14 @@ scenarios:- tests/test_vibey_agent.py::test_a_reply_a_steer_superseded_is_a_result_and_the_turn_ends_once_after_both- tests/test_vibey_agent.py::test_a_restart_rerun_ends_with_the_final_its_cut_run_committed- tests/test_agent_silent_result.py::AgentSilentResultTests::test_a_footer_only_end_is_content_free+ - id: MESSAGE-DELIVERY-336+ name: Every backend reports output through one typed event set (Reply, Narration, ToolActivity, TurnEnd with its outcome, AgentError, Notice) through one entry; one pure mapping names each event's message type and lifecycle (a Reply never ends the Turn, a TurnEnd always does, its outcome supplies stop, teardown and failure semantics) and reproduces the call each backend made before, and every emit answers with a typed delivery receipt+ status: covered+ kind: contract+ layer: contract+ test:+ - tests/test_agent_output.py::test_each_event_maps_to_one_dispatch_call+ - tests/test_agent_output.py::test_an_event_cannot_contradict_its_lifecycle+ - tests/test_agent_output.py::test_an_emit_answers_with_its_delivery_receiptnext_priority:- - MESSAGE-DELIVERY-336+ - MESSAGE-DELIVERY-337diff --git a/tests/test_agent_output.py b/tests/test_agent_output.pynew file mode 100644index 000000000..deb530b20--- /dev/null+++ b/tests/test_agent_output.py@@ -0,0 +1,216 @@+"""The typed output events and their one mapping onto the dispatcher (MESSAGE-DELIVERY-336).++Every backend says what an output is (``core.agent_output``); ``dispatch_call`` is the one+place it becomes the dispatcher's message type, lifecycle, and options. The mapping must+reproduce exactly the call each backend made before the events existed, so moving the+backends onto events changes no behavior.+"""++from __future__ import annotations++import pytest++from core.agent_output import (+ AgentError,+ DeliveryReceipt,+ Narration,+ Notice,+ Reply,+ ToolActivity,+ TurnEnd,+ TurnOutcome,+ dispatch_call,+ emit_output,+)+from core.citations import CitationBundle+from core.delivery_evidence import DeliveryEvidence+from core.message_output import MessageOutput++LINEAGE = MessageOutput(completes_turn=True, completes_run=True, run_id="run_1", idempotency_key="final")+TURN_ONLY = MessageOutput(completes_turn=True, completes_run=False)+ACTIVITY = MessageOutput(completes_turn=False, completes_run=True, detached=True, activity_id="act_1")+CITATIONS = CitationBundle(citations=(), markers=(), sources=())+EVIDENCE = DeliveryEvidence()+HOSTED = {"tool": "web_search"}+++ ("event", "expected"),+ [+ pytest.param(+ Reply("4."),+ ("result", "4.", {"parse_mode": "markdown", "output": MessageOutput(completes_turn=False, completes_run=False)}),+ id="reply",+ ),+ pytest.param(+ Reply(+ "4.",+ citations=CITATIONS,+ footer="⏱ 2s",+ failed=True,+ output=MessageOutput(completes_turn=False, completes_run=False, idempotency_key="msg_2"),+ ),+ (+ "result",+ "4.",+ {+ "parse_mode": "markdown",+ "output": MessageOutput(completes_turn=False, completes_run=False, idempotency_key="msg_2"),+ "is_error": True,+ "result_footer": "⏱ 2s",+ "citations": CITATIONS,+ },+ ),+ id="reply-identified-failed-detached-shape",+ ),+ pytest.param(+ Reply("", output=ACTIVITY),+ ("result", "", {"parse_mode": "markdown", "output": ACTIVITY}),+ id="detached-work-content-free-answer",+ ),+ pytest.param(+ Narration("Looking."),+ ("assistant", "Looking.", {"parse_mode": "markdown"}),+ id="narration-keeps-no-output",+ ),+ pytest.param(+ Narration(+ "_🧠 weighing_",+ process_only=True,+ citations=CITATIONS,+ status_label="thinking",+ output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id="row_1"),+ ),+ (+ "assistant",+ "_🧠 weighing_",+ {+ "parse_mode": "markdown",+ "level": "process",+ "status_label": "thinking",+ "output": MessageOutput(completes_turn=False, completes_run=False, persisted_row_id="row_1"),+ "citations": CITATIONS,+ },+ ),+ id="narration-process-only-committed-row",+ ),+ pytest.param(+ ToolActivity("🔧 `rg lock`", status_label="rg lock", hosted=HOSTED),+ ("toolcall", "🔧 `rg lock`", {"parse_mode": "markdown", "status_label": "rg lock", "hosted": HOSTED}),+ id="tool-activity",+ ),+ pytest.param(+ TurnEnd(),+ ("result", "", {"parse_mode": "markdown", "output": MessageOutput(completes_turn=True, completes_run=True)}),+ id="content-free-end",+ ),+ pytest.param(+ TurnEnd(text="Done.", footer="⏱ 2s", citations=CITATIONS, output=LINEAGE),+ (+ "result",+ "Done.",+ {"parse_mode": "markdown", "output": LINEAGE, "result_footer": "⏱ 2s", "citations": CITATIONS},+ ),+ id="end-with-its-reply",+ ),+ pytest.param(+ TurnEnd(outcome=TurnOutcome.FAILED, silent=True, terminal_error="boom", output=LINEAGE),+ (+ "result",+ "",+ {"parse_mode": "markdown", "output": LINEAGE, "is_error": True, "level": "silent", "terminal_error": "boom"},+ ),+ id="failed-end",+ ),+ pytest.param(+ TurnEnd(outcome=TurnOutcome.STOPPED, silent=True, output=LINEAGE),+ (+ "result",+ "",+ {+ "parse_mode": "markdown",+ "output": MessageOutput(+ completes_turn=True,+ completes_run=False,+ run_id="run_1",+ idempotency_key="final",+ settled_by="stopped",+ ),+ "level": "silent",+ },+ ),+ id="stopped-end-leaves-its-runs-to-the-stop",+ ),+ pytest.param(+ TurnEnd(outcome=TurnOutcome.TEARDOWN, silent=True),+ (+ "result",+ "",+ {+ "parse_mode": "markdown",+ "output": MessageOutput(completes_turn=True, completes_run=False, settled_by="backend_refresh"),+ "is_error": True,+ "level": "silent",+ },+ ),+ id="teardown-end",+ ),+ pytest.param(+ TurnEnd(output=TURN_ONLY),+ ("result", "", {"parse_mode": "markdown", "output": TURN_ONLY}),+ id="turn-only-release",+ ),+ pytest.param(+ AgentError("❌ Codex turn failed", output=TURN_ONLY, delivery=EVIDENCE),+ ("notify", "❌ Codex turn failed", {"parse_mode": "markdown", "output": TURN_ONLY, "delivery": EVIDENCE}),+ id="agent-error",+ ),+ pytest.param(+ Notice("Resuming interrupted OpenCode session after restart..."),+ ("notify", "Resuming interrupted OpenCode session after restart...", {"parse_mode": "markdown"}),+ id="notice",+ ),+ ],+)+def test_each_event_maps_to_one_dispatch_call(event, expected):+ """MESSAGE-DELIVERY-336: the mapping names the type and the lifecycle; an option a+ dispatcher stand-in may not accept is passed only when the event sets it."""+ assert dispatch_call(event) == expected+++ "event",+ [+ pytest.param(Reply("4.", output=MessageOutput(completes_turn=True)), id="a-reply-that-ends-the-turn"),+ pytest.param(TurnEnd(output=ACTIVITY), id="a-turn-end-that-does-not-end-it"),+ ],+)+def test_an_event_cannot_contradict_its_lifecycle(event):+ """MESSAGE-DELIVERY-336: a Reply never ends the Turn and a TurnEnd always does; an+ output that says otherwise is a programming error, not a silent re-typing."""+ with pytest.raises(ValueError):+ dispatch_call(event)+++async def test_an_emit_answers_with_its_delivery_receipt():+ """MESSAGE-DELIVERY-336: the single entry hands the dispatcher the mapped call and+ returns what it proved as a receipt: the delivered id, or nothing delivered."""+ calls = []++ class _Controller:+ def __init__(self, answer):+ self.answer = answer++ async def emit_agent_message(self, context, message_type, text, **options):+ calls.append((context, message_type, text, options))+ return self.answer++ delivered = await emit_output(_Controller("msg_1"), "ctx", Narration("Looking."))+ missed = await emit_output(_Controller(None), "ctx", Notice("Resuming."))++ assert calls == [+ ("ctx", "assistant", "Looking.", {"parse_mode": "markdown"}),+ ("ctx", "notify", "Resuming.", {"parse_mode": "markdown"}),+ ]+ assert (delivered, delivered.delivered) == (DeliveryReceipt("msg_1"), True)+ assert (missed, missed.delivered) == (DeliveryReceipt(None), False)diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.pyindex 854de6158..251a3851c 100644--- a/tests/test_agent_silent_result.py+++ b/tests/test_agent_silent_result.py@@ -7,6 +7,7 @@ from types import SimpleNamespacesys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from core.agent_output import DeliveryReceiptfrom core.citations import CitationSource, register_citationsfrom modules.agents.base import AgentRequest, BaseAgentfrom modules.im import MessageContext@@ -63,7 +64,7 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(controller.messages, [("result", "", "markdown")])- self.assertEqual(message_id, "message-id")+ self.assertEqual(message_id, DeliveryReceipt("message-id"))async def test_no_visible_result_with_duration_hidden_settles_via_outbound(self):# show_duration off + empty result/suffix is still a TERMINAL turn: it is@@ -109,7 +110,7 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):controller.config.show_duration = show_durationmessage_id = await agent.emit_result_message(context, "Plain answer.")- self.assertEqual(message_id, "message-id")+ self.assertEqual(message_id, DeliveryReceipt("message-id"))self.assertEqual([m[0] for m in controller.messages], ["result", "result"])async def test_a_cited_result_forwards_its_sidecar(self):diff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.pyindex f8de4a915..c80bfc5d8 100644--- a/tests/test_backend_failure.py+++ b/tests/test_backend_failure.py@@ -413,6 +413,7 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):request.context,"notify","Codex failed: provider unavailable",+ parse_mode="markdown",output=ANY,delivery=ANY,),@@ -436,6 +437,7 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):request.context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.pyindex 1000188a1..c5c188292 100644--- a/tests/test_claude_agent_initiated_turn.py+++ b/tests/test_claude_agent_initiated_turn.py@@ -32,6 +32,7 @@ from modules.claude_sdk_compat import (TextBlock,ToolUseBlock,)+from core.agent_output import DeliveryReceiptfrom core.controller import Controllerfrom core.message_context import resolve_turn_sink_keyfrom core.message_output import MessageOutput, terminal_output_for@@ -366,7 +367,7 @@ def _dispatcher_owned_emit(service: AgentService, *, message_id="message-id"):output,accepted_message_exists=True,)- return message_id+ return DeliveryReceipt(message_id)return AsyncMock(side_effect=emit)@@ -803,7 +804,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):accepted_message_exists=True,)service.release_runtime_turn(ctx)- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=_emit_result)await agent._receive_messages(@@ -1161,7 +1162,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):))retry_succeeded.set()- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -1228,7 +1229,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):)retained = agent._detached_phase(composite_key)agent._classify_output_record(retained, context, text="retained payload")- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))assistant_seen = asyncio.Event()release_result = asyncio.Event()@@ -1314,7 +1315,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):attempts.append((text, kwargs["output"]))if not accept.is_set():raise RuntimeError("transport temporarily unavailable")- return "accepted"+ return DeliveryReceipt("accepted")agent.emit_result_message = AsyncMock(side_effect=emit)@@ -1704,7 +1705,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):async def _emit_result(context, _text, *, request=None, output=None, **_kwargs):semantics = output or terminal_output_for(request)emitted_provenance.append(semantics.provenance(context))- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=_emit_result)composite_key = "session-foreground-bash:/tmp/work"@@ -1829,7 +1830,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):output,accepted_message_exists=True,)- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -1934,7 +1935,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):if attempts == 1:raise RuntimeError("temporary delivery failure")retry_succeeded.set()- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -2106,12 +2107,12 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):output = kwargs["output"]attempts.append((text, output))if not allow_success.is_set():- return None+ return DeliveryReceipt(None)service.activities.settle_completed_output_batch(output,accepted_message_exists=True,)- return f"message-{len(attempts)}"+ return DeliveryReceipt(f"message-{len(attempts)}")agent.emit_result_message = AsyncMock(side_effect=emit_result)class _Client:@@ -2207,12 +2208,12 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):async def emit_result(_context, text, **kwargs):attempts.append(text)if not allow_success.is_set():- return None+ return DeliveryReceipt(None)service.activities.settle_completed_output_batch(kwargs["output"],accepted_message_exists=True,)- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -2314,7 +2315,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):kwargs["output"],accepted_message_exists=True,)- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -2420,7 +2421,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):return _iterate()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))receiver = asyncio.create_task(agent._receive_messages(_Client(),@@ -3560,7 +3561,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):record = agent._retain_activity_output_record(composite_key, [activity], text="Full background result",)- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))should_retry = await agent._flush_detached_activity_output(composite_key, context)@@ -3749,7 +3750,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):metadata={"summary": f"{activity_id} finished"},expects_output=True,)- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))should_retry = await agent._flush_completed_activity_outputs(composite_key,@@ -3834,7 +3835,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):metadata={"summary": "Background verification finished"},expects_output=True,)- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))should_retry = await agent._flush_completed_activity_outputs(composite_key,@@ -3891,14 +3892,14 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):nonlocal emit_attemptsemit_attempts += 1if emit_attempts == 1:- return None+ return DeliveryReceipt(None)self.assertTrue(service.activities.settle_completed_output_batch(kwargs["output"],accepted_message_exists=True,))- return "delivered-message-id"+ return DeliveryReceipt("delivered-message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)agent._remove_result_pending_reaction = AsyncMock()@@ -4560,7 +4561,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):)# A real turn is in flight: one pending request already enqueued.agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))await agent._receive_messages(_one_result_client(),diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 7a905844a..a0e4e4208 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -525,6 +525,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,@@ -2907,7 +2908,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):# Suppressing the DIAGNOSTIC is what separates this from a real failure —# the dispatcher reads the pair as an intentional silent end (``stopped``)# rather than a fault, and the settlement carries the machine-readable cause.- self.assertIsNone(call.kwargs["terminal_error"])+ self.assertIsNone(call.kwargs.get("terminal_error"))def assert_uncontained_settlement(self, emitter, diagnostic_fragment):"""An ordinary backend failure still settles as one."""@@ -3339,6 +3340,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,@@ -3388,6 +3390,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,@@ -3854,6 +3857,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,@@ -3964,6 +3968,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):pending_context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,@@ -4038,6 +4043,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"result","",+ parse_mode="markdown",is_error=True,level="silent",output=ANY,diff --git a/tests/test_claude_output_recovery_ledger.py b/tests/test_claude_output_recovery_ledger.pyindex ce5a6819e..50cecd762 100644--- a/tests/test_claude_output_recovery_ledger.py+++ b/tests/test_claude_output_recovery_ledger.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, patchimport pytest+from core.agent_output import DeliveryReceiptfrom core.runtime_activation import RuntimeActivationRegistryfrom core.session_activities import SessionActivityRegistry, activity_completion_outputfrom modules.agents.base import AgentRequest@@ -59,7 +60,7 @@ async def test_generation_end_preserves_terminal_recovery_owner_and_gate(ending)attempts.append((text, kwargs["output"]))if not allow_delivery.is_set():raise RuntimeError("outbound unavailable")- return "durably-accepted"+ return DeliveryReceipt("durably-accepted")async def controller_emit(ctx, _kind, _text, **kwargs):if kwargs["output"].completes_turn:@@ -173,7 +174,7 @@ async def test_human_phase_and_successor_cannot_overwrite_or_be_released_by_old_else:human_emits.append(text)service.release_runtime_turn(ctx)- return "accepted"+ return DeliveryReceipt("accepted")agent.emit_result_message = AsyncMock(side_effect=emit)@@ -273,7 +274,7 @@ async def test_failure_replay_revalidates_after_steering_wait(ending, replace_wh))if kwargs["output"].completes_turn:service.release_runtime_turn(ctx)- return "accepted"+ return DeliveryReceipt("accepted")agent.controller.emit_agent_message = AsyncMock(side_effect=emit)@@ -430,7 +431,7 @@ async def test_unowned_terminal_text_survives_claim_failure(return "accepted-output"async def emit_result(ctx, text, **kwargs):- return await accepted(ctx, "result", text, **kwargs)+ return DeliveryReceipt(await accepted(ctx, "result", text, **kwargs))agent.emit_result_message = AsyncMock(side_effect=emit_result)agent.controller.emit_agent_message = AsyncMock(side_effect=accepted)@@ -1263,7 +1264,7 @@ async def test_result_arriving_during_managed_retry_keeps_worker_responsibility(retry_entered.set()await release_retry.wait()delivered.append(text)- return "accepted"+ return DeliveryReceipt("accepted")agent.emit_result_message = AsyncMock(side_effect=emit)@@ -1424,7 +1425,7 @@ async def test_replaced_receiver_late_result_and_eof_cannot_consume_new_request(old = OldClient()agent.claude_sessions[key] = old- agent.emit_result_message = AsyncMock(return_value="delivered")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("delivered"))receiver = asyncio.create_task(agent._receive_messages(old, "recovery-replaced", "/tmp/work", context_for(key), composite_key=key))@@ -1499,10 +1500,10 @@ async def test_stop_interrupt_claim_precedes_every_late_result_route(origin):async def emit(ctx, _kind, _text, **kwargs):if kwargs["output"].completes_turn:service.release_runtime_turn(ctx)- return "settled"+ return DeliveryReceipt("settled")agent.controller.emit_agent_message = AsyncMock(side_effect=emit)- agent.emit_result_message = AsyncMock(return_value="must-not-deliver")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("must-not-deliver"))client = Client()agent.claude_sessions[key] = clientreceiver = asyncio.create_task(diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.pyindex 6bd2f3b24..469a439e8 100644--- a/tests/test_claude_receiver_result_settle.py+++ b/tests/test_claude_receiver_result_settle.py@@ -22,6 +22,7 @@ from unittest.mock import ANY, AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from core.agent_output import DeliveryReceiptfrom core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequestfrom modules.agents.claude_agent import ClaudeAgentfrom modules.agents.service import AgentService@@ -210,7 +211,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-interrupt-unknown:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))agent.controller.emit_agent_message = AsyncMock(return_value=None)result_ready = asyncio.Event()result_processed = asyncio.Event()@@ -280,7 +281,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-steer:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))query_started = asyncio.Event()release_query = asyncio.Event()first_result_ready = asyncio.Event()@@ -369,7 +370,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-buffered-result:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))query_started = asyncio.Event()release_query = asyncio.Event()consume_buffered_result = asyncio.Event()@@ -464,7 +465,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-ambiguous:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))query_started = asyncio.Event()release_query = asyncio.Event()first_result_ready = asyncio.Event()@@ -552,7 +553,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-ambiguous-undelivered:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))result_ready = asyncio.Event()input_ended = asyncio.Event()@@ -624,7 +625,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-ambiguous-consumed:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))receipt = agent._register_native_input(composite_key,"ambiguous input",@@ -674,7 +675,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-ambiguous-close-failed:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))query_started = asyncio.Event()release_query = asyncio.Event()result_ready = asyncio.Event()@@ -762,7 +763,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-activity-steer:/tmp/work"primary_request = SimpleNamespace(context=context, output_activities=[])agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))query_started = asyncio.Event()release_query = asyncio.Event()@@ -897,7 +898,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):))agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))agent.controller.emit_agent_message = AsyncMock(return_value=None)agent._cleanup_runtime_session = AsyncMock()agent._release_service_runtime_turn = Mock()@@ -1146,7 +1147,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):ack_reaction_emoji=None,)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))agent.controller.emit_agent_message = AsyncMock(return_value=None)agent._cleanup_runtime_session = AsyncMock()agent._remove_specific_pending_reaction = AsyncMock()@@ -1302,7 +1303,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-assistant-failure:/tmp/work"primary_request = SimpleNamespace(context=context)agent._pending_requests[composite_key] = [primary_request]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))agent._detect_message_type = lambda message: ("assistant"if isinstance(message, _AssistantFailureMessage)@@ -1497,7 +1498,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):composite_key = "session-2:/tmp/work"agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]- agent.emit_result_message = AsyncMock(return_value=None)+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt(None))await agent._receive_messages(_one_result_client(), "session-2", "/tmp/work", context, composite_key=composite_keydiff --git a/tests/test_claude_result_provenance.py b/tests/test_claude_result_provenance.pyindex 64a06f859..4b258f5e7 100644--- a/tests/test_claude_result_provenance.py+++ b/tests/test_claude_result_provenance.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, Mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from core.agent_output import DeliveryReceiptfrom core.handlers.session_handler import ClaudeInputNotSentErrorfrom core.native_dispatch_phase import (DISPATCH_PHASE_PREWRITE,@@ -186,7 +187,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))await agent._receive_messages(_client(messages),"sess-provenance",@@ -292,7 +293,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))class _Formatter:@staticmethod@@ -436,7 +437,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):key = "session-proven-human-turn:/tmp/work"agent, service = _build_agent()context = _context(key)- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))agent._get_formatter = lambda _context: _Formatter()def visible():@@ -526,7 +527,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))service.activities.start(backend="claude",runtime_key=key,@@ -575,7 +576,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):request = _pending_request(key)agent._pending_requests[key] = [request]agent._get_formatter = lambda _context: _ToolcallFormatter()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))before_result = {}class _Client:@@ -641,7 +642,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):request = _pending_request(key)agent._pending_requests[key] = [request]agent._get_formatter = lambda _context: _ToolcallFormatter()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))before_result = {}tool_name = tool_block.name@@ -717,7 +718,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):request = _pending_request(key)agent._pending_requests[key] = [request]agent._get_formatter = lambda _context: _ToolcallFormatter()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))_start_competing_activity(service, key)receipt = agent._register_native_input(key, "steered prompt", kind="steer"@@ -793,7 +794,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):request = _pending_request(key)agent._pending_requests[key] = [request]agent._get_formatter = lambda _context: _ToolcallFormatter()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))_start_competing_activity(service, key)receipt = agent._register_native_input(key, "steered prompt", kind="steer")receipt.state = "accepted"@@ -931,7 +932,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))class _Formatter:format_assistant_message = Mock(side_effect=RuntimeError("replay failed"))@@ -1006,7 +1007,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):activity = service.activities.claim_completed_output("claude", key)self.assertIsNotNone(activity)agent._retain_activity_output_record(key, [activity])- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))assistant = AssistantMessage(_block(TextBlock, text="detached progress"),@@ -1065,7 +1066,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))terminal = TaskNotificationMessage("task-no-output", "not user text")terminal.status = status@@ -1127,7 +1128,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):service.controller.scheduled_task_service = SimpleNamespace(settle_activity_runs=settle_activity,)- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))# Competing output keeps this task provisional until the human# Result classifies its phase._start_competing_activity(service, key)@@ -1204,7 +1205,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):format_toolcall=lambda *_args, **_kwargs: "fixture tool",format_toolcall_label=lambda *_args, **_kwargs: "fixture tool",)- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))service.activities.start(backend="claude",runtime_key=key,@@ -1401,7 +1402,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):request = _pending_request(key)agent._pending_requests[key] = [request]agent._get_formatter = lambda _context: None- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))failure_seen = asyncio.Event()release_result = asyncio.Event()@@ -1452,7 +1453,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))agent._steering_closing_keys().add(key)await agent._receive_messages(@@ -2035,7 +2036,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):agent, _service = _build_agent()request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))cleanup_entered = asyncio.Event()release_cleanup = asyncio.Event()@@ -2193,7 +2194,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):context = _context(key)request = _pending_request(key)agent._pending_requests[key] = [request]- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))service.activities.classify_provisional_provenance = Mock(side_effect=RuntimeError("activity store unavailable"))@@ -2319,7 +2320,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):attempts.append(kwargs["output"])if len(attempts) == 1:raise RuntimeError("temporary delivery failure")- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_with_one_transient_failure)@@ -2388,7 +2389,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):attempts.append(text)if not allow_retry.is_set():raise RuntimeError("detached delivery unavailable")- return "message-id"+ return DeliveryReceipt("message-id")agent.emit_result_message = AsyncMock(side_effect=emit_result)@@ -2451,7 +2452,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):return "fixture tool"agent._get_formatter = lambda _context: _Formatter()- agent.emit_result_message = AsyncMock(return_value="message-id")+ agent.emit_result_message = AsyncMock(return_value=DeliveryReceipt("message-id"))snapshots = []class _Client: