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(turns): one admission entry and policy for every input source (#2879)
Call White2ec81ca9df01
diff --git a/core/backend_failure_retry.py b/core/backend_failure_retry.pyindex 52c859471..c9759757b 100644--- a/core/backend_failure_retry.py+++ b/core/backend_failure_retry.py@@ -7,11 +7,13 @@ All writers call these helpers while holding the SQLite writer reservation.from __future__ import annotationsimport json+from dataclasses import replacefrom typing import Anyfrom sqlalchemy import select, updatefrom sqlalchemy.engine import Connection+from core.input_admission import InputEnvelope, admit_inputfrom storage import message_deliveries as deliveries, messages_servicefrom storage.delivery_states import policy_forfrom storage.message_deliveries import (@@ -129,9 +131,13 @@ def reserve_retry(*,session_id: str,notice_id: str,- snapshot: dict[str, Any],+ envelope: InputEnvelope,) -> dict[str, Any]:- """Resolve duplicate clicks or reserve one canonical, draft-independent input."""+ """Resolve duplicate clicks or reserve one canonical, draft-independent input.++ Retained inputs keep the admission they already recorded; a new retry input+ is admitted through the input admission entry with its binding as the event.+ """notice = _notice(conn, session_id, notice_id)link = notice["content"].get("failure_retry") or {}existing = deliveries.get_delivery(conn, str(link.get("delivery_id") or ""))@@ -181,21 +187,11 @@ def reserve_retry(if saved is None:raise RuntimeError("retry retained input claim lost")else:- retry_snapshot = dict(snapshot)- dispatch_text = "continue"+ retry_input = replace(envelope, dispatch_text="continue")if vibey_resume:# Vibey resumes its committed transcript. Keep the Delivery as the# durable ownership record, but do not create a visible user input.- retry_snapshot.update(- {- "author": "harness",- "source": "harness",- "type": "agent_initiated",- "content_text": None,- "content_json": "{}",- }- )- metadata = json.loads(str(retry_snapshot.get("metadata_json") or "{}"))+ metadata = json.loads(str(envelope.snapshot().get("metadata_json") or "{}"))if not isinstance(metadata, dict):metadata = {}metadata.update(@@ -205,20 +201,17 @@ def reserve_retry(deliveries.VIBEY_SOURCE_TURN_METADATA_KEY: turn["id"],})- retry_snapshot["metadata_json"] = json.dumps(- metadata, ensure_ascii=False, sort_keys=True, separators=(",", ":")+ retry_input = replace(+ envelope,+ sender=replace(envelope.sender, kind="harness"),+ kind="agent_initiated",+ provenance=replace(envelope.provenance, origin="harness"),+ dispatch_text="",+ text=None,+ content=None,+ metadata=metadata,)- dispatch_text = ""- deliveries.insert_delivery(- conn,- delivery_id=delivery_id,- session_id=session_id,- priority="p3",- state="reserved",- snapshot=retry_snapshot,- dispatch_text=dispatch_text,- history_event=binding,- )+ admit_input(conn, retry_input, delivery_id=delivery_id, history=binding)content = dict(notice["content"])content["failure_retry"] = {"delivery_id": delivery_id}conn.execute(diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex a88103520..76870510c 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -621,19 +621,13 @@ class MessageHandler(BaseHandler):spec["routing_subagent"] = routing_agentcontext.platform_specific = spec- from core.message_priority import delivery_intent_for_trigger-- delivery_intent = delivery_intent_for_trigger("im")- if (- restored_route is None- and agent_name == "opencode"- and subagent_name- and subagent_message is not None- ):- # OpenCode subagents share the main Session anchor. They need a- # fresh Turn so the persisted route can select the requested- # native subagent instead of text-steering the active main Turn.- delivery_intent = "queue"+ # The subagent an explicit prefix named; the admission policy decides+ # what it means for this input's priority.+ explicit_subagent = (+ subagent_name+ if restored_route is None and subagent_message is not None+ else None+ )if agent_name in {"claude", "codex"} and subagent_name:spec = dict(context.platform_specific or {})@@ -691,7 +685,7 @@ class MessageHandler(BaseHandler):session_anchor=base_session_id,working_path=working_path,vibe_agent=vibe_agent,- delivery_intent=delivery_intent,+ explicit_subagent=explicit_subagent,downloaded_attachment_paths=downloaded_attachment_paths,attachment_lease=attachment_lease,admission_context={@@ -949,7 +943,7 @@ class MessageHandler(BaseHandler):session_anchor: str,working_path: str,vibe_agent: Any,- delivery_intent: str,+ explicit_subagent: Optional[str],downloaded_attachment_paths: List[str],admission_context: dict[str, Any],attachment_lease: Any = None,@@ -968,13 +962,17 @@ class MessageHandler(BaseHandler):if not session_id:raise RuntimeError("Could not reserve the Agent Session before delivery")- from core.message_priority import priority_for_delivery_intent+ from core.input_admission import (+ InputEnvelope,+ InputProvenance,+ InputSender,+ admit_input,+ )from core.session_turns import SCRIPT_CONFIRM_ANSWER_REASON, DeliveryRequestfrom storage import message_deliveries, media_service, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.db import get_cached_sqlite_engine- priority = priority_for_delivery_intent(delivery_intent)author_name = await self._input_user_name(context)scope_id = Nonerequest = None@@ -1045,38 +1043,74 @@ class MessageHandler(BaseHandler):content = {"text": display_text}if attachment_refs:content["attachments"] = attachment_refs- request = DeliveryRequest(+ envelope = InputEnvelope(session_id=session_id,- priority=priority,- content=dispatch_text,- has_content=True,- delivery_id=message_deliveries.new_delivery_id(),scope_id=scope_id,- platform=platform,- source="user",- author="user",- message_type="user",- author_id=str(context.user_id or "").strip() or None,- author_name=author_name,- display_text=display_text,- content_json=content,- admission_context=admission_context,- native_message_id=native_message_id or None,- parent_native_message_id=(- str(context.thread_id or "").strip() or None+ sender=InputSender(+ "user",+ str(context.user_id or "").strip() or None,+ author_name,+ ),+ kind="user",+ provenance=InputProvenance(+ source="im",+ platform=platform,+ native_message_id=native_message_id or None,+ parent_native_message_id=(+ str(context.thread_id or "").strip() or None+ ),),+ dispatch_text=dispatch_text,+ text=display_text,+ content=content,message_kind=("original"if context.is_original_human_text is Trueor context.is_original_human_attachment is Trueelse context.message_kind),+ backend=agent_name,+ subagent=explicit_subagent,)- reserved = manager.reserve_delivery(conn, request)- if str(reserved["id"]) != request.delivery_id:+ delivery_id = message_deliveries.new_delivery_id()+ admitted = admit_input(+ conn,+ envelope,+ delivery_id=delivery_id,+ dedupe_key=message_deliveries.native_dedupe_key(+ platform,+ envelope.provenance.native_message_id,+ scope_id=scope_id,+ ),+ admission_context=admission_context,+ reuse_existing=True,+ )+ if str(admitted.delivery["id"]) != delivery_id:raise RuntimeError("native Delivery appeared after writer reservation")+ request = DeliveryRequest(+ session_id=session_id,+ priority=admitted.decision.priority,+ content=dispatch_text,+ has_content=True,+ delivery_id=delivery_id,+ scope_id=scope_id,+ platform=platform,+ source=envelope.provenance.origin,+ author=envelope.sender.kind,+ message_type=envelope.kind,+ author_id=envelope.sender.id,+ author_name=envelope.sender.name,+ display_text=display_text,+ content_json=content,+ admission_context=admission_context,+ native_message_id=envelope.provenance.native_message_id,+ parent_native_message_id=(+ envelope.provenance.parent_native_message_id+ ),+ message_kind=envelope.message_kind,+ )except Exception:if attachment_lease is not None:attachment_lease.release()diff --git a/core/input_admission.py b/core/input_admission.pynew file mode 100644index 000000000..1bb0b693f--- /dev/null+++ b/core/input_admission.py@@ -0,0 +1,320 @@+"""One admission entry for every input that reaches an Avibe Session.++Every input source (the Web composer, IM, Harness triggers, Show annotations, a+failure retry, and an agent-initiated Turn) normalizes its input into one+``InputEnvelope`` and admits it here. The entry asks the admission policy for+the input's priority, records which policy decided and why on the Delivery's+admission history event, and persists the reserved Delivery.++Everything after that is unchanged and owned elsewhere: P0/P1/P3 admission in+``SessionTurnManager.deliver``, steering, the FIFO, segment merging, and the+dedupe identity each source supplies.++The policy is the seam for an agent-owned input firewall and a mailbox. Only the+default policy exists; it holds each source's released priority. Another policy+replaces it by implementing ``AdmissionPolicy``, or composes with it by+delegating to it.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal, Mapping, Protocol++from sqlalchemy.engine import Connection++from core.message_priority import (+ DeliveryIntent,+ DeliveryPriority,+ delivery_intent_for_trigger,+ normalize_delivery_intent,+ priority_for_delivery_intent,+)+from storage import message_deliveries+++InputSource = Literal[+ "web_composer",+ "im",+ "harness",+ "show_annotation",+ "failure_retry",+ "agent_initiated",+]+++@dataclass(frozen=True)+class InputSender:+ """Who sent the input.++ ``kind`` is the transcript author (``user`` or ``harness``); ``id`` and+ ``name`` are the identity the transcript shows for it.+ """++ kind: str+ id: str | None = None+ name: str | None = None+++@dataclass(frozen=True)+class InputProvenance:+ """Where the input came from."""++ source: InputSource+ platform: str = "avibe"+ #: The transcript ``source`` column (``user`` or ``harness``).+ origin: str = "user"+ native_message_id: str | None = None+ parent_native_message_id: str | None = None+ #: The Harness trigger kind (``scheduled``, ``watch``, ``agent_run``, ...).+ trigger: str | None = None+++@dataclass(frozen=True)+class InputEnvelope:+ """One input, normalized, before any admission decision."""++ session_id: str+ scope_id: str | None+ sender: InputSender+ #: The Message type the input is recorded as (``user``, ``harness``,+ #: ``annotation``, ``agent_initiated``).+ kind: str+ provenance: InputProvenance+ #: The prompt the agent receives.+ dispatch_text: str = ""+ #: The text the transcript shows.+ text: str | None = None+ #: The Message content, attachments included.+ content: dict[str, Any] | None = None+ metadata: dict[str, Any] | None = None+ #: How a person produced it (``original``, ``quick_reply``, ...).+ message_kind: str | None = None+ #: An explicit request from the sender (``queue``, ``steer``, legacy+ #: ``send_now``), or ``None`` to take the source's default.+ requested_intent: str | None = None+ #: The backend the input is routed to, and the native subagent an IM input+ #: named with an explicit prefix.+ backend: str | None = None+ subagent: str | None = None++ @property+ def attachments(self) -> list[dict[str, Any]]:+ return list((self.content or {}).get("attachments") or [])++ def snapshot(self) -> dict[str, Any]:+ """The immutable Message candidate the Delivery holds."""++ return message_deliveries.message_snapshot(+ scope_id=self.scope_id,+ session_id=self.session_id,+ platform=self.provenance.platform,+ author=self.sender.kind,+ source=self.provenance.origin,+ message_type=self.kind,+ text=self.text,+ content=self.content,+ metadata=self.metadata,+ author_id=self.sender.id,+ author_name=self.sender.name,+ native_message_id=self.provenance.native_message_id,+ parent_native_message_id=self.provenance.parent_native_message_id,+ message_kind=self.message_kind,+ )+++@dataclass(frozen=True)+class AdmissionDecision:+ intent: DeliveryIntent+ policy: str+ reason: str++ @property+ def priority(self) -> DeliveryPriority:+ return priority_for_delivery_intent(self.intent)++ def record(self) -> dict[str, str]:+ """Who decided and why, as recorded in the Delivery history."""++ return {"id": self.policy, "reason": self.reason}+++class AdmissionPolicy(Protocol):+ def decide(self, envelope: InputEnvelope) -> AdmissionDecision: ...+++class DefaultAdmissionPolicy:+ """Each source's released priority."""++ id = "default"++ def decide(self, envelope: InputEnvelope) -> AdmissionDecision:+ source = envelope.provenance.source+ if source == "harness":+ return self._decide_harness(envelope)+ if source == "im":+ if envelope.backend == "opencode" and envelope.subagent:+ # OpenCode subagents share the main Session anchor. They need a+ # fresh Turn so the persisted route can select the requested+ # native subagent instead of text-steering the active main Turn.+ return self._decision("queue", "opencode_subagent")+ return self._decision(delivery_intent_for_trigger("im"), "source:im")+ if source == "show_annotation":+ return self._decision(+ delivery_intent_for_trigger("show_annotation"),+ "source:show_annotation",+ )+ if source in {"web_composer", "failure_retry", "agent_initiated"}:+ return self._decision("queue", f"source:{source}")+ raise ValueError(f"unsupported input source: {source}")++ def _decide_harness(self, envelope: InputEnvelope) -> AdmissionDecision:+ requested = envelope.requested_intent+ if requested is not None:+ return self._decision(+ normalize_delivery_intent(requested),+ f"requested:{requested.strip().lower()}",+ )+ trigger = str(envelope.provenance.trigger or "").strip()+ if trigger:+ return self._decision(delivery_intent_for_trigger(trigger), f"trigger:{trigger}")+ return self._decision("steer", "harness_default")++ def _decision(self, intent: DeliveryIntent, reason: str) -> AdmissionDecision:+ return AdmissionDecision(intent=intent, policy=self.id, reason=reason)+++DEFAULT_ADMISSION_POLICY: AdmissionPolicy = DefaultAdmissionPolicy()+++@dataclass(frozen=True)+class AdmittedInput:+ delivery: dict[str, Any]+ decision: AdmissionDecision+++def existing_delivery(+ conn: Connection,+ *,+ session_id: str,+ delivery_id: str,+ platform: str,+ native_message_id: str | None,+ scope_id: str | None,+) -> dict[str, Any] | None:+ """The Delivery an input already has: its own id, then its native identity.++ A Delivery that belongs to another Session is refused, never reused.+ """++ existing = message_deliveries.get_delivery(conn, delivery_id)+ if existing is not None:+ if existing["session_id"] != session_id:+ raise ValueError("Delivery does not belong to the target Session")+ return existing+ if not message_deliveries.native_dedupe_key(+ platform, native_message_id, scope_id=scope_id+ ):+ return None+ existing = message_deliveries.get_delivery_by_native_identity(+ conn,+ platform=platform,+ native_message_id=str(native_message_id or ""),+ scope_id=scope_id,+ session_id=session_id,+ normalize_legacy=True,+ )+ if existing is not None and existing["session_id"] != session_id:+ raise ValueError("Delivery dedupe identity belongs to another Session")+ return existing+++def decide_admission(+ envelope: InputEnvelope,+ *,+ policy: AdmissionPolicy = DEFAULT_ADMISSION_POLICY,+) -> AdmissionDecision:+ return policy.decide(envelope)+++def reserve_input(+ conn: Connection,+ envelope: InputEnvelope,+ decision: AdmissionDecision,+ *,+ delivery_id: str,+ dedupe_key: str | None = None,+ admission_context: Mapping[str, Any] | None = None,+ history: Mapping[str, Any] | None = None,+) -> dict[str, Any]:+ """Persist the reserved Delivery for a decided input in the caller's transaction.++ ``history`` replaces the admission event for a source that records its own+ (a failure retry's binding, an agent-initiated Turn's start); the decision's+ record is added to whichever event admits the Delivery.+ """++ event = (+ dict(history)+ if history is not None+ else {+ "kind": "admission",+ "priority": decision.priority,+ "state": "reserved",+ **({"context": dict(admission_context)} if admission_context else {}),+ }+ )+ event["policy"] = decision.record()+ return message_deliveries.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id=envelope.session_id,+ priority=decision.priority,+ state="reserved",+ snapshot=envelope.snapshot(),+ dispatch_text=envelope.dispatch_text,+ dedupe_key=dedupe_key,+ history_event=event,+ )+++def admit_input(+ conn: Connection,+ envelope: InputEnvelope,+ *,+ delivery_id: str,+ dedupe_key: str | None = None,+ admission_context: Mapping[str, Any] | None = None,+ history: Mapping[str, Any] | None = None,+ reuse_existing: bool = False,+ policy: AdmissionPolicy = DEFAULT_ADMISSION_POLICY,+) -> AdmittedInput:+ """Decide one input's priority and reserve its Delivery.++ With ``reuse_existing`` an input that already has a Delivery, by id or by+ its native identity (``existing_delivery``), gets that Delivery back and+ nothing is written.+ """++ decision = decide_admission(envelope, policy=policy)+ if reuse_existing:+ existing = existing_delivery(+ conn,+ session_id=envelope.session_id,+ delivery_id=delivery_id,+ platform=envelope.provenance.platform,+ native_message_id=envelope.provenance.native_message_id,+ scope_id=envelope.scope_id,+ )+ if existing is not None:+ return AdmittedInput(delivery=existing, decision=decision)+ delivery = reserve_input(+ conn,+ envelope,+ decision,+ delivery_id=delivery_id,+ dedupe_key=dedupe_key,+ admission_context=admission_context,+ history=history,+ )+ return AdmittedInput(delivery=delivery, decision=decision)diff --git a/core/internal_server.py b/core/internal_server.pyindex b442d51c6..983160b5d 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -281,11 +281,13 @@ def create_app(context: MessageContext,text: str,*,- delivery_intent: str = "steer",+ delivery_intent: str | None = None,) -> Any:"""Run a Harness input through the same durable owner as interactive Chat.- The explicit source intent decides whether this content queues or steers.+ The admission policy decides whether this content queues or steers, from+ the sender's explicit ``delivery_intent`` when it made one and otherwise+ from the context's trigger kind (``core.input_admission``).Content-bearing P1 targets this Delivery; content-free P1 promotion isexposed separately through ``SessionTurnManager.send_now``.The submission remains a Delivery until exact native acceptance materializes@@ -295,8 +297,16 @@ def create_app(submission = await manager.submit(None, context, text, source=SOURCE_SCHEDULED)return submission.route+ from dataclasses import replace++ from core.input_admission import (+ InputEnvelope,+ InputProvenance,+ InputSender,+ decide_admission,+ reserve_input,+ )from core.message_mirror import _scope_id_for_session- from core.message_priority import normalize_delivery_intentfrom core.runtime_work import answer_caught_cancellation, step_failedfrom core.session_turns import (DeliveryRequest,@@ -326,8 +336,29 @@ def create_app(delivery_owner_transferred = Falsetarget_was_busy = Falselegacy_send_now = str(delivery_intent or "").strip().lower() == "send_now"- delivery_intent = normalize_delivery_intent(delivery_intent)- effective_delivery_intent = delivery_intent+ # The scope is resolved inside the admission transaction below.+ envelope = InputEnvelope(+ session_id=session_id,+ scope_id=None,+ sender=InputSender("harness", author_id, author_name),+ kind="harness",+ provenance=InputProvenance(+ source="harness",+ platform=submission_platform,+ origin="harness",+ native_message_id=native_message_id or None,+ trigger=author_name,+ ),+ dispatch_text=text,+ text=text,+ metadata={+ **dict(submission_spec.get("message_metadata") or {}),+ SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context),+ },+ requested_intent=delivery_intent,+ )+ decision = decide_admission(envelope)+ effective_delivery_intent = decision.intentexecution_id = str((context.platform_specific or {}).get("task_execution_id") or "").strip()@@ -420,10 +451,14 @@ def create_app(str(existing["id"]),expected_version=int(existing["version"]),expected_states=("queued",),- values={"priority": "p1", "state": "reserved"},+ values={+ "priority": decision.priority,+ "state": "reserved",+ },history_event={"kind": "legacy_send_now_re_admission","from_priority": "p3",+ "policy": decision.record(),},)if existing is None:@@ -481,42 +516,13 @@ def create_app(persisted_spec.get("task_execution_id") or execution_id).strip()else:- from core.message_priority import priority_for_delivery_intent-delivery_id = message_deliveries.new_delivery_id()- admitted_state = "reserved"- priority = priority_for_delivery_intent(delivery_intent)- message_deliveries.insert_delivery(+ reserve_input(conn,+ replace(envelope, scope_id=scope_id),+ decision,delivery_id=delivery_id,- session_id=session_id,- priority=priority,- state=admitted_state,- snapshot=message_deliveries.message_snapshot(- scope_id=scope_id,- session_id=session_id,- platform=submission_platform,- author="harness",- author_id=author_id,- author_name=author_name,- source="harness",- message_type="harness",- text=text,- metadata={- **dict(submission_spec.get("message_metadata") or {}),- SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(- context- )- },- native_message_id=native_message_id or None,- ),- dispatch_text=text,dedupe_key=dedupe_key,- history_event={- "kind": "admission",- "priority": priority,- "state": admitted_state,- },)if execution_id and not delivery_owner_transferred:if not attach_agent_run_delivery_in_connection(@@ -559,11 +565,9 @@ def create_app(raise asyncio.CancelledErrorif delivery_request is None:- from core.message_priority import priority_for_delivery_intent-delivery_request = DeliveryRequest(session_id=session_id,- priority=priority_for_delivery_intent(delivery_intent),+ priority=decision.priority,content=text,delivery_id=delivery_id,scope_id=scope_id,diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex ea9c31956..59256c8f7 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -8646,7 +8646,8 @@ class ScheduledTaskService:prompt=request.prompt,execution_id=request.id,task_id=task_id,- # ``delivery_intent_for_trigger`` has a CLOSED vocabulary, and an+ # The admission policy's trigger vocabulary+ # (``delivery_intent_for_trigger``) is CLOSED, and an# escalation IS a hook send -- an out-of-band turn a definition# queued -- so it takes the hook intent rather than a new one no# mapping knows. Provenance is not lost: the run row still carries@@ -11154,22 +11155,17 @@ class ScheduledTaskService:# ``_build_context``). No dot bookkeeping here.## Route every persisted Session target through the durable owner. The- # source policy decides whether this input queues or steers; the platform- # only controls native routing and outward delivery.+ # admission policy decides from the context's trigger kind whether this+ # input queues or steers; the platform only controls native routing and+ # outward delivery.# Returning ``None`` keeps ``ok = not error`` true (the run's own outcome# surfaces via the outbound terminal result + sidebar dot, exactly as the# interactive Chat turn does).gate = getattr(self.controller, "session_turn_gate", None)if session_id and gate is not None:- from core.message_priority import delivery_intent_for_triggerfrom core.session_turns import TurnSubmissionResult- submission = await gate.submit_scheduled(- session_id,- context,- prompt,- delivery_intent=delivery_intent_for_trigger(trigger_kind),- )+ submission = await gate.submit_scheduled(session_id, context, prompt)if isinstance(submission, TurnSubmissionResult):result = TaskDispatchResult(error=None,diff --git a/core/session_turns.py b/core/session_turns.pyindex a3709b969..7d81afa47 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -2714,30 +2714,24 @@ class SessionTurnManager:priority: str,state: str,) -> dict[str, Any]:+ from core.input_admission import existing_delivery+delivery_id = request.delivery_id or delivery_store.new_delivery_id()- existing = delivery_store.get_delivery(conn, delivery_id)+ existing = existing_delivery(+ conn,+ session_id=request.session_id,+ delivery_id=delivery_id,+ platform=request.platform,+ native_message_id=request.native_message_id,+ scope_id=request.scope_id,+ )if existing is not None:- if existing["session_id"] != request.session_id:- raise ValueError("Delivery does not belong to the target Session")return existingdedupe_key = delivery_store.native_dedupe_key(request.platform,request.native_message_id,scope_id=request.scope_id,)- if dedupe_key:- existing = delivery_store.get_delivery_by_native_identity(- conn,- platform=request.platform,- native_message_id=str(request.native_message_id or ""),- scope_id=request.scope_id,- session_id=request.session_id,- normalize_legacy=True,- )- if existing is not None:- if existing["session_id"] != request.session_id:- raise ValueError("Delivery dedupe identity belongs to another Session")- return existingreturn delivery_store.insert_delivery(conn,delivery_id=delivery_id,@@ -2759,24 +2753,6 @@ class SessionTurnManager:},)- @staticmethod- def reserve_delivery(- conn: Connection,- request: DeliveryRequest,- ) -> dict[str, Any]:- """Persist a producer-owned content reservation in the caller's transaction."""-- if request.content is None:- raise ValueError("content Delivery requires a Message snapshot")- if request.priority not in {"p1", "p3"}:- raise ValueError("content reservation requires P1 or P3 priority")- return SessionTurnManager._insert_delivery(- conn,- request,- priority=request.priority,- state="reserved",- )-def _active_identity(self,backend: str,@@ -9727,41 +9703,45 @@ class SessionTurnManager:).mappings().one()if session_row["status"] != "active":return False+ from core.input_admission import (+ InputEnvelope,+ InputProvenance,+ InputSender,+ admit_input,+ )+delivery_id = delivery_store.new_delivery_id()language = self._controller_language()trigger_text = str(payload.get("agent_initiated_trigger_text")or i18n_t("harness.agentInitiatedContinuation", language))- delivery = delivery_store.insert_delivery(+ delivery = admit_input(conn,- delivery_id=delivery_id,- session_id=session_id,- priority="p3",- state="reserved",- snapshot=delivery_store.message_snapshot(- scope_id=session_row["scope_id"],+ InputEnvelope(session_id=session_id,- platform="avibe",- author="harness",- source="harness",+ scope_id=session_row["scope_id"],+ sender=InputSender("harness"),# This durable row owns the backend-started Turn for# Stop/FSM/history, but it is not a user instruction# and must not render as a chat bubble.- message_type="agent_initiated",+ kind="agent_initiated",+ provenance=InputProvenance(+ source="agent_initiated", origin="harness"+ ),text=trigger_text,metadata={"source": "agent_initiated","runtime_key": payload.get("agent_runtime_turn_key"),},),- dispatch_text="",- history_event={+ delivery_id=delivery_id,+ history={"kind": "admission","turn_id": turn_token,"outcome": "backend_initiated",},- )+ ).deliveryclaimed = self._claim_start_batch(conn,owner=start_owner,diff --git a/core/show_session_events.py b/core/show_session_events.pyindex c0dd9a99d..99b3c5dfb 100644--- a/core/show_session_events.py+++ b/core/show_session_events.py@@ -370,48 +370,45 @@ class ShowSessionEventStore:# leaves the metadata byte-identical to before.metadata = metadata_with_resource_user_context(metadata, access_context)if requests_dispatch:- from core.message_priority import (- delivery_intent_for_trigger,- priority_for_delivery_intent,+ from core.input_admission import (+ InputEnvelope,+ InputProvenance,+ InputSender,+ admit_input,)- priority = priority_for_delivery_intent(- delivery_intent_for_trigger("show_annotation")- )delivery_id = message_deliveries.new_delivery_id()- delivery_row = message_deliveries.insert_delivery(+ admitted = admit_input(conn,- delivery_id=delivery_id,- session_id=session_id,- priority=priority,- state="reserved",- snapshot=message_deliveries.message_snapshot(- scope_id=session["scope_id"],+ InputEnvelope(session_id=session_id,- platform="avibe",- author=messages_service.HARNESS_TYPE,- source=messages_service.HARNESS_TYPE,- message_type=(+ scope_id=session["scope_id"],+ sender=InputSender(+ messages_service.HARNESS_TYPE,+ event_id,+ SHOW_TRIGGER_KIND[event_type],+ ),+ kind=(messages_service.ANNOTATION_TYPEif writes_annotationelse messages_service.HARNESS_TYPE),+ provenance=InputProvenance(+ source="show_annotation",+ origin=messages_service.HARNESS_TYPE,+ native_message_id=f"show:{event_id}",+ ),+ dispatch_text=dispatch_text,text=transcript_text,content=content,metadata=metadata,- author_name=SHOW_TRIGGER_KIND[event_type],- author_id=event_id,- native_message_id=f"show:{event_id}",),- dispatch_text=dispatch_text,+ delivery_id=delivery_id,dedupe_key=f"show:{event_id}",- history_event={- "kind": "admission",- "priority": priority,- "state": "reserved",- },)- delivery = message_deliveries.public_delivery_payload(delivery_row)+ delivery = message_deliveries.public_delivery_payload(+ admitted.delivery+ )conn.execute(update(show_session_events).where(show_session_events.c.id == event_id)diff --git a/tests/backend_failure_retry_helpers.py b/tests/backend_failure_retry_helpers.pyindex 1099697ec..8f23fb0eb 100644--- a/tests/backend_failure_retry_helpers.py+++ b/tests/backend_failure_retry_helpers.py@@ -95,17 +95,19 @@ def seed_failed_notice(def reserve_failure_retry(conn, notice):from core.backend_failure_retry import reserve_retry+ from core.input_admission import InputEnvelope, InputProvenance, InputSenderreturn reserve_retry(conn,session_id=notice["session_id"],notice_id=notice["id"],- snapshot=deliveries.message_snapshot(- scope_id=notice["scope_id"],+ envelope=InputEnvelope(session_id=notice["session_id"],- platform="avibe",- author="user",- source="user",+ scope_id=notice["scope_id"],+ sender=InputSender("user"),+ kind="user",+ provenance=InputProvenance(source="failure_retry"),+ dispatch_text="continue",text="continue",message_kind="quick_reply",),diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex a57c743c8..179e9808a 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -522,5 +522,15 @@ scenarios:- 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_receipt+ - id: MESSAGE-DELIVERY-338+ name: Every input source (Web composer, IM, Harness, Show annotation, failure retry, agent-initiated) is normalized into one envelope and admitted through one entry; one default admission policy holds each source's released priority (the OpenCode subagent exception, an Agent Run's --queue and legacy send_now, the scheduled P3 included) and the admitting history event records which policy decided and why+ status: covered+ kind: contract+ layer: contract+ test:+ - tests/test_input_admission.py::test_each_source_is_admitted_with_its_released_priority_and_records_the_decision+ - tests/test_input_admission.py::test_a_source_owned_admission_event_carries_the_decision+ - tests/test_input_admission.py::test_an_input_that_already_has_a_delivery_gets_it_back+ - tests/test_input_admission.py::test_the_record_names_whichever_policy_decidednext_priority:- - MESSAGE-DELIVERY-337+ - MESSAGE-DELIVERY-339diff --git a/tests/test_input_admission.py b/tests/test_input_admission.pynew file mode 100644index 000000000..847e88cb7--- /dev/null+++ b/tests/test_input_admission.py@@ -0,0 +1,259 @@+"""MESSAGE-DELIVERY-338: one admission entry for every input source."""++from __future__ import annotations++import json+from dataclasses import replace++import pytest+from sqlalchemy import func, select++from core.input_admission import (+ DEFAULT_ADMISSION_POLICY,+ AdmissionDecision,+ InputEnvelope,+ InputProvenance,+ InputSender,+ admit_input,+)+from storage import message_deliveries+from storage.db import create_sqlite_engine+from storage.models import agent_sessions, metadata+from storage.models import message_deliveries as message_deliveries_table+++SESSION_ID = "ses_admission"+++def _envelope(source: str, **fields) -> InputEnvelope:+ provenance = {+ key: fields.pop(key) for key in ("trigger", "platform") if key in fields+ }+ harness = source in {"harness", "show_annotation", "agent_initiated"}+ return InputEnvelope(+ session_id=SESSION_ID,+ scope_id=None,+ sender=InputSender("harness" if harness else "user", "sender-id", "Sender"),+ kind="harness" if harness else "user",+ provenance=InputProvenance(+ source=source,+ origin="harness" if harness else "user",+ **provenance,+ ),+ dispatch_text="input",+ text="input",+ **fields,+ )+++HARNESS_TRIGGERS = [+ ("scheduled", "p3"),+ ("task_run", "p3"),+ ("watch", "p1"),+ ("hook", "p1"),+ ("webhook", "p1"),+ ("agent_run", "p1"),+ ("callback", "p1"),+]++CASES = [+ ("web composer", _envelope("web_composer"), "p3", "source:web_composer"),+ ("im", _envelope("im", platform="slack", backend="codex"), "p1", "source:im"),+ (+ "im claude subagent prefix",+ _envelope("im", platform="slack", backend="claude", subagent="reviewer"),+ "p1",+ "source:im",+ ),+ (+ "im opencode",+ _envelope("im", platform="slack", backend="opencode"),+ "p1",+ "source:im",+ ),+ (+ "im opencode subagent prefix",+ _envelope("im", platform="slack", backend="opencode", subagent="reviewer"),+ "p3",+ "opencode_subagent",+ ),+ *[+ (f"harness {trigger}", _envelope("harness", trigger=trigger), priority, f"trigger:{trigger}")+ for trigger, priority in HARNESS_TRIGGERS+ ],+ (+ "agent run --queue",+ _envelope("harness", trigger="agent_run", requested_intent="queue"),+ "p3",+ "requested:queue",+ ),+ (+ "agent run steer",+ _envelope("harness", trigger="agent_run", requested_intent="steer"),+ "p1",+ "requested:steer",+ ),+ (+ "agent run legacy send_now",+ _envelope("harness", trigger="agent_run", requested_intent="send_now"),+ "p1",+ "requested:send_now",+ ),+ (+ "requested intent wins over the trigger",+ _envelope("harness", trigger="watch", requested_intent="queue"),+ "p3",+ "requested:queue",+ ),+ ("harness without trigger", _envelope("harness"), "p1", "harness_default"),+ ("show annotation", _envelope("show_annotation"), "p1", "source:show_annotation"),+ ("failure retry", _envelope("failure_retry"), "p3", "source:failure_retry"),+ ("agent initiated", _envelope("agent_initiated"), "p3", "source:agent_initiated"),+]+++def engine(tmp_path):+ engine = create_sqlite_engine(tmp_path / "state.sqlite")+ metadata.create_all(engine)+ now = "2026-10-20T00:00:00+00:00"+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id=SESSION_ID,+ agent_backend="codex",+ agent_variant="default",+ session_anchor=SESSION_ID,+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ yield engine+ engine.dispose()+++def _admit(engine, envelope, **kwargs):+ with engine.begin() as conn:+ admitted = admit_input(+ conn,+ envelope,+ delivery_id=message_deliveries.new_delivery_id(),+ **kwargs,+ )+ row = message_deliveries.get_delivery(conn, admitted.delivery["id"])+ return admitted, row+++ ("envelope", "priority", "reason"),+ [case[1:] for case in CASES],+ ids=[case[0] for case in CASES],+)+def test_each_source_is_admitted_with_its_released_priority_and_records_the_decision(+ engine, envelope, priority, reason+) -> None:+ """MESSAGE-DELIVERY-338: one policy holds every source's released priority."""++ admitted, row = _admit(engine, envelope)++ assert (row["priority"], row["state"]) == (priority, "reserved")+ assert admitted.decision.priority == priority+ assert json.loads(row["delivery_history_json"])["events"] == [+ {+ "at": row["submitted_at"],+ "kind": "admission",+ "priority": priority,+ "state": "reserved",+ "policy": {"id": "default", "reason": reason},+ }+ ]+ assert row["snapshot_json"] == json.dumps(+ envelope.snapshot(), ensure_ascii=False, sort_keys=True, separators=(",", ":")+ )+++def test_a_source_owned_admission_event_carries_the_decision(engine) -> None:+ """MESSAGE-DELIVERY-338: a failure retry and an agent-initiated Turn keep their own event."""++ binding = {"kind": "backend_failure_retry", "notice_id": "msg_notice"}+ _admitted, row = _admit(+ engine,+ _envelope("failure_retry"),+ history=binding,+ admission_context={"ignored": "the source event wins"},+ )++ (event,) = json.loads(row["delivery_history_json"])["events"]+ assert event == {+ "at": row["submitted_at"],+ **binding,+ "policy": {"id": "default", "reason": "source:failure_retry"},+ }+++def test_an_input_that_already_has_a_delivery_gets_it_back(engine) -> None:+ """MESSAGE-DELIVERY-338: a duplicate native id reuses its Delivery, never a second one."""++ envelope = replace(+ _envelope("im", platform="slack", backend="codex"),+ provenance=InputProvenance(source="im", platform="slack", native_message_id="171.1"),+ )+ dedupe_key = message_deliveries.native_dedupe_key("slack", "171.1")+ first, _ = _admit(engine, envelope, dedupe_key=dedupe_key, reuse_existing=True)+ again, _ = _admit(engine, envelope, dedupe_key=dedupe_key, reuse_existing=True)++ assert again.delivery["id"] == first.delivery["id"]+ with engine.connect() as conn:+ assert conn.execute(+ select(func.count()).select_from(message_deliveries_table)+ ).scalar_one() == 1+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id="ses_other",+ agent_backend="codex",+ agent_variant="default",+ session_anchor="ses_other",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at="2026-10-20T00:00:00+00:00",+ updated_at="2026-10-20T00:00:00+00:00",+ last_active_at="2026-10-20T00:00:00+00:00",+ )+ )+ other = replace(envelope, session_id="ses_other")+ with pytest.raises(ValueError, match="belongs to another Session"):+ _admit(engine, other, dedupe_key=dedupe_key, reuse_existing=True)+++def test_the_record_names_whichever_policy_decided(engine) -> None:+ """MESSAGE-DELIVERY-338: a policy that replaces or wraps the default is what gets recorded."""++ class QueueEverything:+ def decide(self, envelope):+ default = DEFAULT_ADMISSION_POLICY.decide(envelope)+ return AdmissionDecision("queue", "test-firewall", f"over:{default.reason}")++ admitted, row = _admit(+ engine,+ _envelope("im", platform="slack", backend="codex"),+ admission_context={"processing_indicator_message_id": "echo-1"},+ policy=QueueEverything(),+ )++ assert row["priority"] == "p3"+ (event,) = json.loads(row["delivery_history_json"])["events"]+ assert event["context"] == {"processing_indicator_message_id": "echo-1"}+ assert event["policy"] == {"id": "test-firewall", "reason": "over:source:im"}+++def test_an_unknown_harness_trigger_is_refused_rather_than_guessed() -> None:+ """The trigger vocabulary stays closed now that the policy, not the scheduler, maps it."""++ with pytest.raises(ValueError, match="unsupported delivery trigger"):+ DEFAULT_ADMISSION_POLICY.decide(_envelope("harness", trigger="task_escalation"))diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex aa0552fd2..0238022da 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -3978,7 +3978,6 @@ def test_hfr_482_create_per_run_delivery_adopts_reserved_session(monkeypatch, tmsession_id,ctx,"fresh session prompt",- delivery_intent="queue",)await asyncio.wait_for(started.wait(), timeout=3)return resultdiff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex b10a3255f..4c03b9d09 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -407,7 +407,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await handler.handle_user_message(context, "reviewer: check this")call = handler._admit_human_delivery.await_args.kwargs- self.assertEqual(call["delivery_intent"], "queue")+ self.assertEqual(call["explicit_subagent"], "reviewer")self.assertEqual(call["admission_context"]["message_handler_route"]["subagent_name"],"reviewer",diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex ed1a8048e..ce427c2da 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -12862,8 +12862,16 @@ def test_execute_request_avibe_routes_through_gate(monkeypatch, tmp_path) -> Nonsubmitted: list[tuple] = []handler_calls: list = []- async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):- submitted.append((sid, text, getattr(ctx, "platform", None), delivery_intent))+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent=None):+ submitted.append(+ (+ sid,+ text,+ getattr(ctx, "platform", None),+ ctx.platform_specific["task_trigger_kind"],+ delivery_intent,+ )+ )async def _handle_scheduled_message(context, message, parsed_session_key=None):handler_calls.append(message)@@ -12888,8 +12896,9 @@ def test_execute_request_avibe_routes_through_gate(monkeypatch, tmp_path) -> Non)assert error is None, "dispatched-success returns None so ok=not error stays true"+ # The admission policy decides from the trigger (scheduled queues).assert submitted == [- (session_id, "run the digest", "avibe", "queue")+ (session_id, "run the digest", "avibe", "scheduled", None)], "routed through the turn gate"assert handler_calls == [], "the direct handle_scheduled_message path is bypassed for avibe"@@ -12909,8 +12918,10 @@ def test_execute_request_im_watch_steers_through_delivery_owner(submitted: list = []handler_calls: list = []- async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):- submitted.append((sid, text, delivery_intent))+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent=None):+ submitted.append(+ (sid, text, ctx.platform_specific["task_trigger_kind"], delivery_intent)+ )async def _handle_scheduled_message(context, message, parsed_session_key=None):handler_calls.append((message, context.platform))@@ -12944,7 +12955,8 @@ def test_execute_request_im_watch_steers_through_delivery_owner()assert error is None- assert submitted == [(session_id, "send digest", "steer")]+ # The admission policy decides from the trigger (a Watch steers).+ assert submitted == [(session_id, "send digest", "watch", None)]assert handler_calls == []diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 1262552c8..67f493498 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -5900,7 +5900,7 @@ async def test_concurrent_im_attachment_retry_keeps_one_reserved_owner(session_anchor="base-session",working_path="/tmp",vibe_agent=None,- delivery_intent="steer",+ explicit_subagent=None,downloaded_attachment_paths=[str(path)],admission_context={},)@@ -6004,11 +6004,12 @@ async def test_im_reply_answers_only_the_approvers_pending_script_confirm(display_text=answer,processed_files=[],session_key="slack::C1",- agent_name="codex",+ # An explicit OpenCode subagent is the IM input the policy queues.+ agent_name="opencode",session_anchor="base-session",working_path="/tmp",vibe_agent=None,- delivery_intent="queue",+ explicit_subagent="reviewer",downloaded_attachment_paths=[],admission_context={},)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ab7f7c30d..797cfa43d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -12111,6 +12111,7 @@ async def sessions_messages_create(session_id: str):def _persist_user_row() -> dict | None:"""Atomically persist one unaccepted submission as a Delivery."""+ from core.input_admission import InputEnvelope, InputProvenance, InputSender, admit_inputfrom storage import message_deliveriesfrom storage.agent_session_rows import reserve_write_lock@@ -12131,17 +12132,18 @@ async def sessions_messages_create(session_id: str):message_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = [web_push_authorization_context]- snapshot = message_deliveries.message_snapshot(- scope_id=session["scope_id"],+ envelope = InputEnvelope(session_id=session_id,- platform="avibe",- author="user",- source="user",+ scope_id=session["scope_id"],+ sender=InputSender("user", workbench_author_id, payload.get("author_name")),+ kind="user",+ provenance=InputProvenance(+ source="failure_retry" if retry_for else "web_composer",+ ),+ dispatch_text=dispatch_text,text=text if isinstance(text, str) else None,content=content if isinstance(content, dict) else None,metadata=message_metadata,- author_id=workbench_author_id,- author_name=payload.get("author_name"),message_kind=message_kind,)if retry_for:@@ -12151,19 +12153,10 @@ async def sessions_messages_create(session_id: str):conn,session_id=session_id,notice_id=retry_for,- snapshot=snapshot,+ envelope=envelope,)else:- row = message_deliveries.insert_delivery(- conn,- delivery_id=delivery_id,- session_id=session_id,- priority="p3",- state="reserved",- snapshot=snapshot,- dispatch_text=dispatch_text,- history_event={"kind": "admission", "priority": "p3", "state": "reserved"},- )+ row = admit_input(conn, envelope, delivery_id=delivery_id).deliveryif not quick_reply_for and not retry_for:message_deliveries.set_draft(conn, session_id, None)draft = message_deliveries.get_draft_state(conn, session_id)