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
fix(vibey): recover legacy hosted refusal tails (#3108)
Call Whiteb83caaf6730b
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex d787ab4e5..2da44d57b 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -39,6 +39,8 @@ from core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import (AssistantContent,AssistantMessage,+ HOSTED_RENDER_EPOCH,+ HOSTED_RENDER_RULE,Citation,HostedCost,HostedSource,@@ -226,6 +228,8 @@ class StreamAssembler:#: The Source that served the response (the served-hop report): the ``native.source_id`` of its hosted calls.self.source_id: str | None = Noneself.source_identity: str | None = None+ # Evidence from this stream's first prepared request; pause continuations must preserve its wire prefix.+ self.hosted_render_omitted: tuple[str, ...] = ()self._citations: dict[int, list[Citation]] = {}self._hosted_inputs: dict[Hashable, io.StringIO] = {}self._hosted_counts: dict[str, int] = {}@@ -1148,11 +1152,11 @@ class StreamAssembler:kind="invalid_request",message=message,retryable=False,- partial=partial,+ partial=self._rendered_response(partial),continuable=True,malformed_tool_calls=tuple(malformed),)- return assistant_message(+ return self._rendered_response(assistant_message(final,origin=self.origin,stop_reason=stop_reason,@@ -1161,6 +1165,14 @@ class StreamAssembler:verified_origin=self.verified_origin,hosted_summary=self._hosted_summary(final),source_identity=self.source_identity,+ ))++ def _rendered_response(self, message: AssistantMessage) -> AssistantMessage:+ if not self.hosted_render_omitted:+ return message+ return replace(+ message, hosted_render_epoch=HOSTED_RENDER_EPOCH, hosted_render_rule=HOSTED_RENDER_RULE,+ hosted_render_omitted=self.hosted_render_omitted,)def pause(self) -> AssistantMessage | ProviderError:@@ -1177,7 +1189,7 @@ class StreamAssembler:content = list(self.content)if not self._emitted_output:content = []- return partial_message(+ return self._rendered_response(partial_message(content,origin=self.origin,usage=self.usage,@@ -1185,7 +1197,7 @@ class StreamAssembler:stop_reason=stop_reason,hosted_summary=self._hosted_summary(content),source_identity=self.source_identity,- )+ ))def error(self,@@ -2260,6 +2272,15 @@ async def read_response_body(return b"".join(chunks).decode("utf-8", errors="replace")+@dataclass(frozen=True)+class PreparedMessages:+ """The compiled history, its immutable media snapshots, and the legacy rows this exact render omitted."""++ messages: tuple[Any, ...]+ loaded_images: dict[str, LoadedImage]+ hosted_render_omitted: tuple[str, ...]++async def prepare_messages(messages: tuple[Any, ...],*,@@ -2269,7 +2290,7 @@ async def prepare_messages(media_loader: MediaLoader | None,cancel: CancelToken,endpoint: ModelEndpoint | None = None,-) -> tuple[tuple[Any, ...], dict[str, LoadedImage]] | ProviderError:+) -> PreparedMessages | ProviderError:"""Transform history and resolve immutable media snapshots as one safe boundary."""try:@@ -2296,7 +2317,7 @@ async def prepare_messages(retryable=False,continuable=False,)- return transformed.messages, loaded_images+ return PreparedMessages(transformed.messages, loaded_images, transformed.hosted_render_omitted)class _suppress_cancelled:diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex 68ab0d787..f439f0295 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -262,7 +262,8 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared+ transformed_messages, loaded_images = prepared.messages, prepared.loaded_images+ assembler.hosted_render_omitted = prepared.hosted_render_omittedif cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))if terminal is not None:@@ -979,7 +980,7 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared+ transformed_messages, loaded_images = prepared.messages, prepared.loaded_imagesif first_sent is not None and _binding_prefix(sending, transformed_messages, loaded_images) != _binding_prefix(request, (*first_sent[0], so_far), first_sent[1]):diff --git a/core/agent_core/ai/google.py b/core/agent_core/ai/google.pyindex 41700aa3c..cb07c0c17 100644--- a/core/agent_core/ai/google.py+++ b/core/agent_core/ai/google.py@@ -184,7 +184,7 @@ class GoogleAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared+ transformed_messages, loaded_images = prepared.messages, prepared.loaded_imagesif cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))if terminal is not None:diff --git a/core/agent_core/ai/openai_chat.py b/core/agent_core/ai/openai_chat.pyindex 7660e515f..bb02476d6 100644--- a/core/agent_core/ai/openai_chat.py+++ b/core/agent_core/ai/openai_chat.py@@ -206,7 +206,7 @@ class OpenAIChatAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared+ transformed_messages, loaded_images = prepared.messages, prepared.loaded_imagesif cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))if terminal is not None:diff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.pyindex cfeaac1ac..7273e22b6 100644--- a/core/agent_core/ai/openai_responses.py+++ b/core/agent_core/ai/openai_responses.py@@ -331,7 +331,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared+ transformed_messages, loaded_images = prepared.messages, prepared.loaded_imagesif cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))if terminal is not None:diff --git a/core/agent_core/ai/preview.py b/core/agent_core/ai/preview.pyindex ea7e83230..45dfe24b1 100644--- a/core/agent_core/ai/preview.py+++ b/core/agent_core/ai/preview.py@@ -50,8 +50,7 @@ async def preview_wire_request()if isinstance(prepared, ProviderError):return prepared- messages, images = prepared- wire = builder(request, messages, gateway=gateway, loaded_images=images)+ wire = builder(request, prepared.messages, gateway=gateway, loaded_images=prepared.loaded_images)# AsyncClient.build_request delegates JSON serialization to Request, too.# No client construction (or environment/proxy/credential lookup) is needed.body = httpx.Request("POST", wire.url, headers=wire.headers, json=wire.body).contentdiff --git a/core/agent_core/ai/transform.py b/core/agent_core/ai/transform.pyindex 4b50f778a..d7b32fd5e 100644--- a/core/agent_core/ai/transform.py+++ b/core/agent_core/ai/transform.py@@ -19,6 +19,7 @@ from core.agent_core.messages import (AssistantMessage,AssistantContent,HOSTED_RENDER_EPOCH,+ HOSTED_RENDER_RULE,HostedToolBlock,ImageBlock,Message,@@ -40,6 +41,8 @@ class TransformResult:messages: tuple[Message, ...]tool_call_id_map: Mapping[str, str]+ #: Store row ids whose legacy pending tails were actually omitted in this compilation.+ hosted_render_omitted: tuple[str, ...] = ()@propertydef id_map(self) -> Mapping[str, str]:@@ -103,6 +106,7 @@ def transform_messages(pending_tool_ids: dict[str, list[str]] = {}suppressed_tool_result_ids: set[str] = set()transformed: list[Message] = []+ omitted_rows: list[str] = []for position, message in enumerate(messages):if isinstance(message, UserMessage):@@ -152,7 +156,9 @@ def transform_messages(in_flight=in_flight,interrupted=SYNTHETIC_TOOL_RESULT,parallel_group=position in parallel_groups,- omit_pending=_omit_refused_pending(message, position, messages, endpoint, target_protocol),+ omit_pending=_omit_refused_pending(+ message, position, messages, endpoint, target_protocol, parallel_group=position in parallel_groups+ ),)# The synthetic results of the current run of hosted calls, and the assistant parts they split off.results: list[ToolResultMessage] = []@@ -236,6 +242,11 @@ def transform_messages(if message.stop_reason in {"aborted", "error"}:suppressed_tool_result_ids.update(turn_tool_ids)continue+ if (+ message.hosted_render_epoch is None and message.transcript_row_id is not None+ and any(portable.kind == "omit" for portable in hosted.values())+ ):+ omitted_rows.append(message.transcript_row_id)for source_id, wire_ids in turn_tool_ids.items():pending_tool_ids.setdefault(source_id, []).extend(wire_ids)split()@@ -248,7 +259,9 @@ def transform_messages(transformed.extend(results)transformed = _insert_synthetic_results(transformed)- return TransformResult(messages=tuple(transformed), tool_call_id_map=dict(id_map))+ return TransformResult(+ messages=tuple(transformed), tool_call_id_map=dict(id_map), hosted_render_omitted=tuple(omitted_rows),+ )def _complete_hosted_history(@@ -349,24 +362,56 @@ def _omit_refused_pending(messages: tuple[Message, ...],endpoint: ModelEndpoint | None,protocol: str,+ *,+ parallel_group: bool = False,) -> bool:- """Select B after an explicit hosted-payload refusal without changing old signed history back and forth.+ """Keep rc8's marked history stable; migrate only an unbound legacy mixed tail.- A response's own marker says that the new renderer was available when it was committed, but it does not say how- that response rendered its predecessors. Later signed responses are the binding evidence: if any later one is an- old unmarked response, this response retains the released X* rendering; otherwise B is stable for this suffix.+ The first signed successor commits the renderer that bound this prefix. Rule 3 must name this predecessor's+ store row as actually omitted: neither the running version nor a provider call id is binding evidence.+ No historical metadata is changed. Prefix-only compaction keeps a predecessor with its first successor."""if protocol != "anthropic" or endpoint is None or message.source_identity is None:return Falseif (message.source_identity, "hosted") not in endpoint.opaque_refused:return False- if message.hosted_render_epoch != HOSTED_RENDER_EPOCH:+ later_messages = messages[position + 1 :]+ if message.hosted_render_epoch == HOSTED_RENDER_EPOCH:+ # This is the released rc8 predicate, including its treatment of partials. Do not apply the new guard or+ # successor filtering to marked rows: existing signed history may already bind precisely that rendering.+ return all(+ not _has_signed_thinking(later) or later.hosted_render_epoch == HOSTED_RENDER_EPOCH+ for later in later_messages+ if isinstance(later, AssistantMessage)+ )+ if (+ parallel_group or message.hosted_render_epoch is not None or message.hosted_render_rule is not None+ or message.transcript_row_id is None+ ):+ return False # No migration without a stable row identity; unknown versions and grouped results stay intact.++ client_seen = pending_seen = False+ for block in message.content:+ if isinstance(block, ToolCallBlock):+ client_seen = True+ elif isinstance(block, HostedToolBlock) and block.record.status == "pending":+ if not client_seen:+ return False # Only remove existing trailing in-place text, never a synthetic call/result pair.+ pending_seen = True+ elif pending_seen and isinstance(block, ThinkingBlock) and block.signature is not None:+ return False # This includes redacted thinking: its opaque data is held in signature.+ if not pending_seen:return False- return all(- not _has_signed_thinking(later) or later.hosted_render_epoch == HOSTED_RENDER_EPOCH- for later in messages[position + 1 :]- if isinstance(later, AssistantMessage)++ successor = next(+ (later for later in later_messages if isinstance(later, AssistantMessage)+ and later.stop_reason not in {"error", "aborted"} and _has_signed_thinking(later)),+ None,+ )+ return successor is None or (+ successor.hosted_render_epoch == HOSTED_RENDER_EPOCH and successor.hosted_render_rule == HOSTED_RENDER_RULE+ and message.transcript_row_id in successor.hosted_render_omitted)diff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex e82ddfe4d..0fd9ec76a 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -27,6 +27,9 @@ STOP_REASONS: tuple[str, ...] = ("stop", "length", "tool_use", "refusal", "safet#: the canonical message payload: older releases ignore the row metadata, while this build uses it to keep a#: response's historical rendering stable across later requests.HOSTED_RENDER_EPOCH = 2+#: The successor-binding rule used when this response was generated. Keep epoch 2 for released readers; rule 3+#: plus explicit predecessor row ids proves which legacy tails the actual request omitted.+HOSTED_RENDER_RULE = 3IMAGE_MIME_TYPES: tuple[str, ...] = ("image/png", "image/jpeg", "image/gif", "image/webp")@@ -856,6 +859,13 @@ class AssistantMessage:#: The response-row metadata epoch used by the hosted-refusal renderer. This transient fact is loaded from the#: response metadata and is intentionally omitted from ``message_to_dict`` / the canonical transcript payload.hosted_render_epoch: Optional[int] = field(default=None, compare=False, repr=False)+ #: Like the epoch, this is response-row metadata, not canonical content. A signed successor commits the rule+ #: that compiled its predecessors without modifying any historical row (including shared fork ancestry).+ hosted_render_rule: Optional[int] = field(default=None, compare=False, repr=False)+ #: The old response rows actually migrated by the request producing this response, not provider call ids.+ hosted_render_omitted: tuple[str, ...] = field(default=(), compare=False, repr=False)+ #: Store-owned identity, stable across reload and shared fork ancestry; never serialized as canonical content.+ transcript_row_id: Optional[str] = field(default=None, compare=False, repr=False)def __post_init__(self) -> None:_require_blocks(self.content, (TextBlock, ThinkingBlock, ToolCallBlock, HostedToolBlock), "assistant message")diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex a61648f84..a67262c8a 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -373,7 +373,13 @@ failover, and is refused unpinned (C-6 item 7). What changes is what happens aftmodel of the same Source may run the tool), when the refusal is first learned, and again onlyafter the record is cleared (by the user or a stamp change) and the tool is tried natively once more. The upstream is not called twicefor nothing: a refusal before output costs no output tokens.-- **Hosted-refusal rendering is versioned.** When an Anthropic hop has explicit `opaque_refused(hosted)` evidence and the refused hosted call is still pending (so Vibey did not execute it), a response written with `hosted_render_epoch=2` omits that call from the portable assistant wire instead of inventing an Avibe `no result` text. This applies only to that refusal state; completed, failed, incomplete, other protocols and ordinary portable fallbacks keep their existing rendering. The epoch lives in response-row metadata, never in the canonical message payload. A later signed-thinking response without the new epoch keeps the suffix on the old renderer, so upgrading cannot rewrite an already-signed history halfway through a Session; once all later signed responses carry epoch 2, new responses use the omission renderer consistently.+- **Hosted-refusal rendering is versioned.** When an Anthropic hop has explicit `opaque_refused(hosted)` evidence, B omits unexecuted pending hosted calls instead of inventing Avibe `no result` text. Completed, failed, incomplete, other protocols and ordinary portable fallbacks keep their existing rendering. `hosted_render_epoch=2`, `hosted_render_rule=3`, and `hosted_render_omitted` live only in response-row metadata, never in the canonical message payload; old or malformed optional metadata cannot prevent loading history.+ - A response already marked epoch 2 keeps the exact released rc8 rule: B only when every later signed-thinking response also has epoch 2. This includes rc8's existing treatment of error/aborted responses; the legacy-tail rules below must not change an already-marked response's wire.+ - An unmarked legacy response can migrate only when all its pending hosted calls follow a client call (already rendered as trailing in-place text), with no signed or redacted thinking after the first omitted block inside the response. Unknown metadata versions do not authorize migration. The store supplies its stable `transcript_row_id` on load and append; without that identity it stays X*. This identity is transient, not canonical content, and does not rely on provider call ids being unique.+ - Its first later signed-thinking response that is actually replayed (excluding error/aborted responses) fixes the rendering. No such successor means the tail is unbound and uses B. A successor carrying epoch 2, rule 3, and this predecessor's row id in `hosted_render_omitted` proves its request actually omitted that tail. Version alone, another row's evidence, or a refusal learned later cannot authorize a change. Older or unevidenced bindings keep X*. Signature refusals do not erase canonical binding evidence.+ - The compiler collects only legacy rows it actually omits. `PreparedMessages` carries that evidence into the Anthropic stream assembler, whose final, partial, and paused messages retain the first send's set; the existing continuation prefix guard rejects any altered continuation. Fresh attempts get fresh assemblers, never a union of failed attempts. The response writer retains epoch 2 for released readers and writes rule 3 only with nonempty compiler evidence. No historical row is rewritten, including shared fork ancestry. Preview and retry use the same pure compiler; failed attempts need no migration write. Prefix-only compaction cannot remove the first binding successor while retaining its predecessor.+ - **Downgrade limit:** rolling back to rc8 renders a migrated, unmarked legacy tail as X* again, invalidating any later signature generated against B. Continuing after that downgrade can create conflicting old/new signature prefixes that a later upgrade cannot preserve simultaneously. Avoid downgrading such Sessions; this is not a promise of transparent signature recovery. New epoch-2 responses retain rc8 behavior.+ - **Acceptance:** an unbound legacy mixed tail must change in the production wire compiler, not just new-response fixtures. Repeated previews are deterministic; unsigned/new-rule successors preserve the prior request prefix; rc8/older bindings remain byte-identical. Existing thinking prefixes and client tool/result objects must not change, and no tool executes during reconstruction. These are structural guarantees, not proof that an upstream prefill rejection has only this cause.- **The gateway never rewrites hosted content.** Vibey renders every request from its canonical records; the gatewaynever swaps declarations or converts history. C-6 item 6's opaque thinking strip still applies to unpinnedrequests only.diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 232f774e9..6db6dd5b4 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -69,6 +69,7 @@ from core.agent_core.tools.base import CallInstancefrom core.agent_core.tools.jobs import call_instancefrom core.agent_core.messages import (HOSTED_RENDER_EPOCH,+ HOSTED_RENDER_RULE,HOSTED_RESULT_TOOLS,HostedImage,IMAGE_MIME_TYPES,@@ -1979,6 +1980,10 @@ class VibeyAgent(BaseAgent):if route.mode == "proxy" and route.route_switch == "native_interrupted")),"hosted_render_epoch": HOSTED_RENDER_EPOCH,+ **({+ "hosted_render_rule": HOSTED_RENDER_RULE,+ "hosted_render_omitted": list(message.hosted_render_omitted),+ } if message.hosted_render_rule == HOSTED_RENDER_RULE and message.hosted_render_omitted else {}),}def _on_response(diff --git a/storage/agent_transcript.py b/storage/agent_transcript.pyindex d1861860f..5d48afe1e 100644--- a/storage/agent_transcript.py+++ b/storage/agent_transcript.py@@ -323,10 +323,7 @@ class SQLiteTranscriptStore:if not isinstance(message, AssistantMessage):raise TypeError("append_response takes an AssistantMessage")row_metadata = dict(metadata or {})- stored_message = message- epoch = row_metadata.get("hosted_render_epoch")- if isinstance(epoch, int) and not isinstance(epoch, bool):- stored_message = replace(message, hosted_render_epoch=epoch)+ stored_message = _with_render_metadata(message, row_metadata)response: dict[str, Any] = {"version": PAYLOAD_VERSION, "message": message_to_dict(stored_message)}if request is not None:response["request"] = dict(request) # C-9 ``ModelResponse.request``: the anchor's request facts@@ -359,7 +356,8 @@ class SQLiteTranscriptStore:conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))_register_images(conn, origin.scope_id, session_id, stored_message)return ContextEntry(- session_id, seq, "response", row["id"], message=stored_message, payload=model, created_at=_epoch(row["created_at"])+ session_id, seq, "response", row["id"], message=replace(stored_message, transcript_row_id=row["id"]),+ payload=model, created_at=_epoch(row["created_at"]),)return await self._write(session_id, work)@@ -1032,6 +1030,19 @@ def _turn_context_entries(conn: Connection, session_id: str, turn_id: str) -> lireturn sorted(entries, key=lambda row: row.context_seq)+def _with_render_metadata(message: AssistantMessage, metadata: Mapping[str, Any]) -> AssistantMessage:+ """Optional renderer facts never make an otherwise valid historical row unreadable."""+ changes: dict[str, Any] = {}+ for key in ("hosted_render_epoch", "hosted_render_rule"):+ value = metadata.get(key)+ if type(value) is int:+ changes[key] = value+ omitted = metadata.get("hosted_render_omitted")+ if isinstance(omitted, list) and all(isinstance(row, str) and row for row in omitted):+ changes["hosted_render_omitted"] = tuple(omitted)+ return replace(message, **changes)++def _message_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:row_id = row["id"]if row["type"] in INPUT_TYPES:@@ -1048,9 +1059,7 @@ def _message_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:metadata = _json_object(row.get("metadata_json"), row_id)except TranscriptError:metadata = {}- epoch = metadata.get("hosted_render_epoch")- if isinstance(epoch, int) and not isinstance(epoch, bool):- message = replace(message, hosted_render_epoch=epoch)+ message = replace(_with_render_metadata(message, metadata), transcript_row_id=row_id)return ContextEntry(session_id, row["context_seq"], kind, row_id, message=message, payload=payload, created_at=_epoch(row["created_at"]))diff --git a/tests/agent_core/agent/test_compaction.py b/tests/agent_core/agent/test_compaction.pyindex c2c907d7d..ba7fc5ffa 100644--- a/tests/agent_core/agent/test_compaction.py+++ b/tests/agent_core/agent/test_compaction.py@@ -362,7 +362,7 @@ async def _wire(request):media_loader=None,cancel=CancelToken(),)- messages, images = prepared+ messages, images = prepared.messages, prepared.loaded_imagesbuild = {"anthropic": build_messages_payload,"openai_chat": build_chat_payload,diff --git a/tests/agent_core/ai/_wire.py b/tests/agent_core/ai/_wire.pyindex 61de2bb8f..7c70ee97c 100644--- a/tests/agent_core/ai/_wire.py+++ b/tests/agent_core/ai/_wire.py@@ -38,5 +38,4 @@ async def build_wire_request()if isinstance(prepared, ProviderError):raise ValueError(prepared.message)- messages, loaded_images = prepared- return _WIRE_REQUESTS[protocol](request, messages, gateway=gateway, loaded_images=loaded_images)+ return _WIRE_REQUESTS[protocol](request, prepared.messages, gateway=gateway, loaded_images=prepared.loaded_images)diff --git a/tests/agent_core/ai/test_hosted_transform.py b/tests/agent_core/ai/test_hosted_transform.pyindex 31c964a89..25e1b7c4a 100644--- a/tests/agent_core/ai/test_hosted_transform.py+++ b/tests/agent_core/ai/test_hosted_transform.py@@ -9,6 +9,7 @@ are never sent.from __future__ import annotationsimport itertools+from dataclasses import replaceimport pytest@@ -52,6 +53,17 @@ def _hosted(call_id: str, tool: str, action: HostedAction, record: HostedRecord))+def _deferred_hosted(call_id: str, *, completed: bool) -> HostedToolBlock:+ action = HostedAction("search", queries=(f"q-{call_id}",))+ if completed:+ record = HostedRecord(status="completed")+ native = HostedNative(source_id=SOURCE, payload=({"type": "web_search_tool_result", "tool_use_id": call_id},))+ else:+ record = HostedRecord(status="pending")+ native = HostedNative(source_id=SOURCE, payload=({"type": "server_tool_use", "id": call_id},))+ return HostedToolBlock(id=call_id, tool="web_search", action=action, record=record, native=native)++SEARCH = _hosted("ws_1","web_search",@@ -256,6 +268,189 @@ def test_legacy_refused_pending_response_stays_legacy_after_new_epoch_history():assert any(isinstance(block, ToolCallBlock) for block in sent.content)+async def test_legacy_refused_tail_recovers_in_the_real_wire_without_changing_client_results():+ """MH-HOSTED-VIBEY-003: an already-failed, unmarked mixed tail must benefit from the upgrade."""+ target = Origin("anthropic", "anthropic", "claude-opus-5-5")+ thinking = ThinkingBlock(text="kept", signature="signed-prefix")+ calls = (ToolCallBlock("client_1", "x_search", {}), ToolCallBlock("client_2", "web_fetch", {}))+ pending = tuple(+ _hosted(f"pending_{i}", "web_search", HostedAction("search", queries=("q",)), HostedRecord(status="pending"))+ for i in range(2)+ )+ first = AssistantMessage(+ (thinking, calls[0], pending[0]), target, "tool_use", hosted_summary=HostedSummary(), source_identity="identity",+ transcript_row_id="legacy-first",+ )+ second = AssistantMessage(+ (calls[1], pending[1]), target, "tool_use", hosted_summary=HostedSummary(), source_identity="identity",+ transcript_row_id="legacy-second",+ )+ results = tuple(ToolResultMessage(call.id, call.name, (TextBlock("settled"),)) for call in calls)+ endpoint = ModelEndpoint(+ "anthropic", "http://hub.invalid/vibey/v1", target.model, "hub-token", provider="anthropic",+ source_id=SOURCE, source_identity="identity", opaque_refused=frozenset({("identity", "hosted")}),+ )+ request = ModelRequest(+ endpoint=endpoint, system="unchanged", tools=(), max_tokens=256, cache="none",+ messages=(UserMessage((TextBlock("go"),)), first, results[0], second, results[1]),+ )++ wire = await build_wire_request(request, gateway=True)+ again = await build_wire_request(request, gateway=True)++ assert wire.body == again.body+ sent = wire.body["messages"]+ assert len(sent) == 5+ assert [block["type"] for block in sent[1]["content"]] == ["thinking", "tool_use"]+ assert sent[1]["content"][0] == {"type": "thinking", "thinking": "kept", "signature": "signed-prefix"}+ assert [block["type"] for block in sent[3]["content"]] == ["tool_use"]+ assert [sent[i]["content"][0]["tool_use_id"] for i in (2, 4)] == [call.id for call in calls]+ assert all(sent[i]["content"][0]["content"] == [{"type": "text", "text": "settled"}] for i in (2, 4))+ assert first.content == (thinking, calls[0], pending[0]) and second.content == (calls[1], pending[1])+ unidentified = await build_wire_request(replace(+ request, messages=tuple(replace(m, transcript_row_id=None) if isinstance(m, AssistantMessage) else m+ for m in request.messages),+ ), gateway=True)+ assert all(unidentified.body["messages"][i]["content"][-1]["text"].endswith("(no result)") for i in (1, 3))+++async def test_parallel_deferred_group_keeps_unfinished_pending_call_as_synthetic_wire_pair():+ """A paired deferred call makes the whole mixed response parallel; legacy migration must not drop its sibling."""+ target = Origin("anthropic", "anthropic", "claude-opus-5-5")+ client = ToolCallBlock("client", "read", {})+ pending_a = _deferred_hosted("pending_a", completed=False)+ completed = _deferred_hosted("pending_a", completed=True)+ unfinished = _deferred_hosted("pending_b", completed=False)+ first = AssistantMessage(+ (client, pending_a, unfinished),+ target,+ "tool_use",+ hosted_summary=HostedSummary(),+ source_identity="identity",+ transcript_row_id="legacy-parallel",+ )+ continuation = AssistantMessage(+ (completed,), target, "stop", hosted_summary=HostedSummary(), source_identity="identity"+ )+ endpoint = ModelEndpoint(+ "anthropic", "http://hub.invalid/vibey/v1", target.model, "hub-token", provider="anthropic",+ source_id=SOURCE, source_identity="identity", opaque_refused=frozenset({("identity", "hosted")}),+ )+ request = ModelRequest(+ endpoint=endpoint, system="same", tools=(), max_tokens=256, cache="none",+ messages=(UserMessage((TextBlock("go"),)), first, ToolResultMessage("client", "read", (TextBlock("done"),)), continuation),+ )++ wire = await build_wire_request(request, gateway=True)++ assistant = wire.body["messages"][1]+ assert [block["type"] for block in assistant["content"]] == ["tool_use", "tool_use", "tool_use"]+ assert {block["id"] for block in assistant["content"]} == {"client", "pending_a", "pending_b"}+ result_ids = [block["tool_use_id"] for block in wire.body["messages"][2]["content"]]+ assert result_ids == ["pending_a", "pending_b", "client"]+ unfinished_result = next(+ block for block in wire.body["messages"][2]["content"] if block["tool_use_id"] == "pending_b"+ )+ assert unfinished_result["content"] == [{"type": "text", "text": SYNTHETIC_TOOL_RESULT}]+++ ("epoch", "inline_binding", "successors", "omitted"),+ [+ (None, False, (), True),+ (None, False, ((2, 3, "stop", False),), True),+ (None, False, ((None, None, "stop", False),), False),+ (None, False, ((2, None, "stop", False),), False),+ (None, False, ((2, 4, "stop", False),), False),+ (None, False, ((None, 3, "stop", False),), False),+ (None, False, ((None, None, "stop", False), (2, 3, "stop", False)), False),+ (None, False, ((2, 3, "stop", True),), True),+ (None, False, ((None, None, "stop", True),), False),+ (None, False, ((None, None, "error", False),), True),+ (None, False, ((None, None, "aborted", True),), True),+ (None, True, (), False),+ (2, True, (), True), # The released rc8 branch is not retroactively guarded.+ (2, False, ((2, None, "stop", False), (None, None, "stop", False)), False),+ (2, False, ((None, None, "error", False),), False), # rc8 counted this partial.+ (2, False, ((2, 3, "stop", False),), True),+ (42, False, (), False),+ ],+)+async def test_refused_legacy_tail_uses_first_binding_successor_but_preserves_rc8(+ epoch, inline_binding, successors, omitted,+):+ target = Origin("anthropic", "anthropic", "claude-opus-5-5")+ client = ToolCallBlock("client", "read", {})+ pending = _hosted("pending", "web_search", HostedAction("search", queries=("q",)), HostedRecord(status="pending"))+ thinking = ThinkingBlock(text="", signature="opaque", redacted=True)+ content = (client, pending, thinking) if inline_binding else (thinking, client, pending)+ response = AssistantMessage(+ content, target, "tool_use", hosted_summary=HostedSummary(), source_identity="identity", hosted_render_epoch=epoch,+ transcript_row_id="legacy",+ )+ later = tuple(+ AssistantMessage(+ (ThinkingBlock(text="", signature=f"signed-{i}", redacted=redacted), TextBlock("next")),+ target, stop, source_identity="identity", hosted_render_epoch=marker, hosted_render_rule=rule,+ hosted_render_omitted=("legacy",) if rule == 3 else (),+ )+ for i, (marker, rule, stop, redacted) in enumerate(successors)+ )+ endpoint = ModelEndpoint(+ "anthropic", "http://hub.invalid/vibey/v1", target.model, "hub-token", provider="anthropic",+ source_id=SOURCE, source_identity="identity", opaque_refused=frozenset({("identity", "hosted")}),+ )+ request = ModelRequest(+ endpoint=endpoint, system="same", tools=(), max_tokens=256, cache="none",+ messages=(UserMessage((TextBlock("go"),)), response, ToolResultMessage("client", "read", (TextBlock("done"),)), *later),+ )+ wire = await build_wire_request(request, gateway=True)+ blocks = wire.body["messages"][1]["content"]+ assert any(block.get("text") == '[web_search: "q"] (no result)' for block in blocks) is not omitted+ assert [block for block in blocks if block["type"] == "redacted_thinking"] == [+ {"type": "redacted_thinking", "data": "opaque"}+ ]+ assert len([block for block in blocks if block["type"] == "tool_use"]) == 1+++async def test_legacy_tail_render_stays_an_exact_prefix_after_unsigned_and_rule3_responses():+ target = Origin("anthropic", "anthropic", "claude-opus-5-5")+ pending = _hosted("pending", "web_search", HostedAction("search", queries=("q",)), HostedRecord(status="pending"))+ response = AssistantMessage(+ (ThinkingBlock(text="kept", signature="original"), ToolCallBlock("client", "read", {}), pending),+ target, "tool_use", hosted_summary=HostedSummary(), source_identity="identity", transcript_row_id="legacy",+ )+ endpoint = ModelEndpoint(+ "anthropic", "http://hub.invalid/vibey/v1", target.model, "hub-token", provider="anthropic",+ source_id=SOURCE, source_identity="identity", opaque_refused=frozenset({("identity", "hosted")}),+ )+ request = ModelRequest(+ endpoint=endpoint, system="same", tools=(), max_tokens=256, cache="none",+ messages=(UserMessage((TextBlock("go"),)), response, ToolResultMessage("client", "read", (TextBlock("done"),))),+ )+ initial = await build_wire_request(request, gateway=True)+ assert initial.body["messages"][1]["content"][-1]["type"] == "tool_use"+ for signed in (False, True, True):+ successor = AssistantMessage(+ ((ThinkingBlock(text="later", signature="next-signature"),) if signed else ()) + (TextBlock("next"),),+ target, "stop", source_identity="identity", hosted_render_epoch=2, hosted_render_rule=3,+ hosted_render_omitted=("legacy",),+ )+ request = replace(request, messages=(*request.messages, successor))+ continued = await build_wire_request(request, gateway=True)+ assert continued.body["messages"][:len(initial.body["messages"])] == initial.body["messages"]+ initial = continued+ assert response.hosted_render_epoch is None and response.hosted_render_rule is None+ for evidence in ((), ("another-row",)):+ unproven = await build_wire_request(replace(+ request, messages=tuple(+ replace(m, hosted_render_omitted=evidence) if isinstance(m, AssistantMessage) and m.hosted_render_rule == 3+ else m for m in request.messages+ ),+ ), gateway=True)+ assert unproven.body["messages"][1]["content"][-1]["text"] == '[web_search: "q"] (no result)'++def test_refused_pending_hosted_b_does_not_change_non_anthropic_targets():target = Origin("google", "openai_chat", "gemini-3-pro")pending = _hosted("ws_pending", "web_search", HostedAction("search", queries=("q",)), HostedRecord(status="pending"))diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.pyindex 098ec1eec..f37a4ea65 100644--- a/tests/test_agent_transcript.py+++ b/tests/test_agent_transcript.py@@ -20,6 +20,7 @@ from sqlalchemy import selectfrom core.agent_core.messages import (AssistantMessage,HOSTED_RENDER_EPOCH,+ HOSTED_RENDER_RULE,HostedAction,HostedNative,HostedRecord,@@ -315,15 +316,16 @@ async def test_hosted_render_epoch_is_response_metadata_not_canonical_message_cohome = _scope(conn, "C-hosted-render-epoch")_session(conn, "ses_hosted_render_epoch", home)consumed = _row(conn, "ses_hosted_render_epoch", home, "go")+ from modules.agents.vibey.agent import VibeyAgent++ agent = object.__new__(VibeyAgent)+ agent._run_for = lambda *_: Nonestore = AdapterTranscriptStore(SQLiteTranscriptStore(engine),engine,environment=lambda _: {},on_response=lambda *_: None,- response_metadata=lambda *_: {- "hosted_render_epoch": HOSTED_RENDER_EPOCH,- "future_metadata": "ignored by the model payload",- },+ response_metadata=agent._response_metadata,)await store.consume_input("ses_hosted_render_epoch", consumed, _user("go"))written = await store.append_response("ses_hosted_render_epoch", _assistant("stored"), final=True)@@ -332,11 +334,149 @@ async def test_hosted_render_epoch_is_response_metadata_not_canonical_message_corestored = loaded[1].messageassert isinstance(restored, AssistantMessage)assert restored.hosted_render_epoch == HOSTED_RENDER_EPOCH+ assert restored.hosted_render_rule is None # The running version alone is not evidence of a migration.+ assert written.message.hosted_render_rule is None+ assert restored.hosted_render_omitted == ()+ assert restored.transcript_row_id == written.message.transcript_row_id == written.row_idwith engine.connect() as conn:row = conn.execute(select(messages).where(messages.c.id == written.row_id)).mappings().one()model = json.loads(row["content_json"])["model"]["message"]assert "hosted_render_epoch" not in model- assert "future_metadata" not in model+ assert "hosted_render_rule" not in model+ assert "hosted_render_omitted" not in model+ assert "transcript_row_id" not in model++[email protected]("initial_refused", [(), ("old-a",), ("old-a", "old-b")])[email protected]("paused", [False, True])+async def test_legacy_binding_records_actual_wire_before_later_refusals(engine, initial_refused, paused):+ """MH-HOSTED-VIBEY-003: a later refusal cannot rewrite the prefix of an already signed response.++ Version-only fixtures missed this: use the real adapter and metadata writer, including a request which+ migrates one legacy tail but not its sibling (even with reused provider ids), and a signed pause inside+ the same response.+ """+ from dataclasses import replace++ import httpx++ from core.agent_core.ai.provider import Done+ from modules.agents.vibey.agent import VibeyAgent+ from tests.agent_core.ai._wire import build_wire_request+ from tests.agent_core.ai.test_hosted_pause_turn import _request, _response, _served, _stream, _text, _thinking++ sid = "ses_actual_render_binding"+ with engine.begin() as conn:+ home = _scope(conn, "C-actual-render-binding")+ _session(conn, sid, home)+ consumed = _row(conn, sid, home, "go")+ raw_store = SQLiteTranscriptStore(engine)+ await raw_store.consume_input(sid, consumed, _user("go"))+ for i, identity in enumerate(("old-a", "old-b")):+ legacy = AssistantMessage(+ (+ ToolCallBlock(f"client-{i}", "read", {"path": "a"}),+ HostedToolBlock(+ id="reused-hosted-id", tool="web_search", action=HostedAction("search", queries=(f"q-{i}",)),+ record=HostedRecord(status="pending"),+ native=HostedNative(source_id="src_served00001", payload=({+ "type": "server_tool_use", "id": "reused-hosted-id", "name": "web_search", "input": {},+ },)),+ ),+ ),+ ORIGIN, "tool_use", hosted_summary=HostedSummary(), source_identity=identity,+ )+ await raw_store.append_response(sid, legacy, final=False)+ await raw_store.append_tool_result(+ sid, ToolResultMessage(f"client-{i}", "read", (TextBlock("settled"),)), details={},+ )+ initial_entries = list(await raw_store.load(sid))+ request = _request()+ request = replace(+ request, messages=tuple(entry.message for entry in initial_entries),+ endpoint=replace(request.endpoint, source_identity="current",+ opaque_refused=frozenset((identity, "hosted") for identity in initial_refused)),+ )++ def answer(number):+ return httpx.Response(200, headers=_served(), text=_response(+ *([_thinking()] if number == 1 else []), _text("next"),+ stop_reason="pause_turn" if paused and number == 1 else "end_turn", input_tokens=100, output_tokens=10,+ ))++ sent, events = await _stream(answer, request)+ assert isinstance(events[-1], Done), events[-1]+ assert len(sent) == (2 if paused else 1)+ initial = json.loads(sent[0].content)+ for i, identity in enumerate(("old-a", "old-b")):+ blocks = initial["messages"][1 + 2 * i]["content"]+ assert any(block.get("text", "").endswith("(no result)") for block in blocks) == (identity not in initial_refused)+ if paused:+ assert json.loads(sent[1].content)["messages"][:-1] == initial["messages"]++ agent = object.__new__(VibeyAgent)+ agent._run_for = lambda *_: None+ store = AdapterTranscriptStore(raw_store, engine, environment=lambda _: {}, on_response=lambda *_: None,+ response_metadata=agent._response_metadata)+ await store.append_response(sid, events[-1].message, final=True)+ restored = list(await store.load(sid))+ assert restored[:-1] == initial_entries # The migration never rewrites old rows.+ evidence = tuple(entry.row_id for entry in initial_entries if isinstance(entry.message, AssistantMessage)+ and entry.message.source_identity in initial_refused)+ assert restored[-1].message.hosted_render_omitted == evidence+ assert restored[-1].message.hosted_render_rule == (HOSTED_RENDER_RULE if evidence else None)+ with engine.connect() as conn:+ row = conn.execute(select(messages).where(messages.c.id == restored[-1].row_id)).mappings().one()+ canonical = json.loads(row["content_json"])["model"]["message"]+ assert not {"hosted_render_omitted", "hosted_render_rule", "transcript_row_id"} & canonical.keys()+ # The Session learns both refusals only after the signed successor was generated and committed.+ replay = await build_wire_request(replace(+ request, messages=tuple(entry.message for entry in restored),+ endpoint=replace(request.endpoint, opaque_refused=frozenset({("old-a", "hosted"), ("old-b", "hosted")})),+ ), gateway=True)+ assert replay.body["messages"][:len(initial["messages"])] == initial["messages"]++[email protected](("value", "expected"), [(None, None), (True, None), ("3", None), ({}, None), (3, 3), (4, 4)])+async def test_optional_hosted_render_rule_metadata_does_not_break_historical_load(engine, value, expected):+ with engine.begin() as conn:+ home = _scope(conn, "C-render-rule")+ _session(conn, "ses_render_rule", home)+ consumed = _row(conn, "ses_render_rule", home, "go")+ store = SQLiteTranscriptStore(engine)+ await store.consume_input("ses_render_rule", consumed, _user("go"))+ written = await store.append_response("ses_render_rule", _assistant("stored"), final=True)+ with engine.begin() as conn:+ conn.execute(messages.update().where(messages.c.id == written.row_id).values(+ metadata_json=json.dumps({"hosted_render_epoch": 2, "hosted_render_rule": value}),+ ))+ loaded = list(await store.load("ses_render_rule"))+ assert loaded[1].message.hosted_render_epoch == 2+ assert loaded[1].message.hosted_render_rule == expected+ assert loaded[1].payload == written.payload+++ ("value", "expected"),+ [(None, ()), (True, ()), ("row", ()), ({}, ()), ([1], ()), (["row", None], ()), ([""], ()),+ ([], ()), (["row"], ("row",))],+)+async def test_optional_hosted_render_evidence_loads_fail_closed(engine, value, expected):+ with engine.begin() as conn:+ home = _scope(conn, "C-render-evidence")+ _session(conn, "ses_render_evidence", home)+ consumed = _row(conn, "ses_render_evidence", home, "go")+ store = SQLiteTranscriptStore(engine)+ await store.consume_input("ses_render_evidence", consumed, _user("go"))+ written = await store.append_response("ses_render_evidence", _assistant("stored"), final=True)+ with engine.begin() as conn:+ conn.execute(messages.update().where(messages.c.id == written.row_id).values(+ metadata_json=json.dumps({"hosted_render_epoch": 2, "hosted_render_rule": 3, "hosted_render_omitted": value}),+ ))+ loaded = list(await store.load("ses_render_evidence"))+ assert loaded[1].message.hosted_render_omitted == expected+ assert loaded[1].message.hosted_render_rule == 3+ assert loaded[1].payload == written.payloadasync def test_a_stored_unknown_native_hosted_row_loads_through_the_transcript_owner(engine):