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 rejected search history without replaying client tools (#3070)
Call White8434bb9fb041
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex c9c275275..ecd8d3fa4 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -71,7 +71,7 @@ from core.agent_core.agent.lifecycle import RunAborted as _Aborted, RunScopefrom core.agent_core.agent.models import ModelRouter, ModelSelection, RetryPolicyfrom core.agent_core.agent.outcome import OutcomeOwnerfrom core.agent_core.agent.state import HookStateError, state_representation-from core.agent_core.ai._common import endpoint_origin, native_hosted_tools, portable_endpoint+from core.agent_core.ai._common import endpoint_origin, native_hosted_tools, portable_endpoint, search_history_endpointfrom core.agent_core.ai.provider import (Done,ModelEndpoint,@@ -238,8 +238,10 @@ MAX_REFUSAL_RESOLVES = 2@dataclassclass _Refusals:- """A run's refusals before any output, and how the requests after them render (``vibey-hosted-tools.md`` §3.5).+ """A run's refusals and changed-request recovery (``vibey-hosted-tools.md`` §3.5).+ Generic pin/opaque refusals require no output. Corroborated Anthropic search refusals may also replace an+ uncommitted partial: no client tool from that failed attempt has run, and its usage stays in the audit.A refusal is answered by a fresh hop, rendered normally: at most once per (Source, tool, aspect) a narrow hostedrule names, and at most ``MAX_REFUSAL_RESOLVES`` times in the run. Past a bound, or when a gateway hand-back'sfresh hop is the refused one again, the request goes portable instead.@@ -253,15 +255,25 @@ class _Refusals:rules: set[tuple[Optional[str], str, Optional[str]]] = field(default_factory=set)opaque: set[tuple[Optional[str], str]] = field(default_factory=set)unsaved: dict[Optional[str], list[str]] = field(default_factory=dict)+ # A guarded compatibility trial is not permanent capability evidence. Keep it within this run, not in a new+ # on-disk payload vocabulary that older releases cannot load after a rollback.+ search_history: set[Optional[str]] = field(default_factory=set)- def answer(self, refusal: Refusal) -> Optional[Literal["resolve", "portable"]]:+ def answer(self, refusal: Refusal) -> Optional[Literal["resolve", "portable", "same"]]:"""How the next attempt answers ``refusal``, counted; None when the refusal stands as the error."""+ if refusal.kind == "search_history":+ if refusal.source_identity in self.search_history:+ return None+ self.search_history.add(refusal.source_identity)+ return "same"if refusal.kind == "opaque_refused":fresh = [kind for kind in refusal.payloads if (refusal.source_identity, kind) not in self.opaque]if not fresh:return Noneself.opaque.update((refusal.source_identity, kind) for kind in fresh)self.unsaved.setdefault(refusal.source_identity, []).extend(fresh)+ if refusal.tool == "web_search":+ return "same"rule = (refusal.source_id, refusal.tool, refusal.aspect) if refusal.tool is not None else Noneif self.resolves >= MAX_REFUSAL_RESOLVES or rule in self.rules:return "portable"@@ -276,6 +288,8 @@ class _Refusals:endpoint = selection.endpointif self.opaque:endpoint = replace(endpoint, opaque_refused=frozenset(self.opaque))+ if endpoint.source_identity in self.search_history:+ endpoint = search_history_endpoint(endpoint)if portable:endpoint = portable_endpoint(endpoint)return selection if endpoint is selection.endpoint else replace(selection, endpoint=endpoint)@@ -910,8 +924,8 @@ class Agent:# A response that dropped after thinking alone is retried once per request (C-2 ``provider.md``): some# prompts drop at the same point every time.thinking_retried = False- # A refusal before any output is answered by rendering the request again (§3.5, ``_Refusals``): the hop a- # gateway hand-back refused, and whether the next request goes portable.+ # A refusal is answered by a changed rendering (§3.5, ``_Refusals``): the hop a gateway hand-back refused,+ # and whether the next request goes portable. Search-history trials keep the same hop.refused: Optional[ModelEndpoint] = Noneportable = Falsewhile True:@@ -976,14 +990,28 @@ class Agent:and not streamedand (terminal.partial is None or not terminal.partial.content))+ search_recovery = (+ isinstance(terminal, ProviderError)+ and terminal.refusal is not None+ and (+ terminal.refusal.kind == "search_history"+ or (terminal.refusal.kind == "opaque_refused" and terminal.refusal.tool == "web_search")+ )+ )rerender = (self._refusals.answer(terminal.refusal)if isinstance(terminal, ProviderError)and terminal.refusal is not None- and not streamed- and (terminal.partial is None or not terminal.partial.content)+ and (+ search_recovery+ or (not streamed and (terminal.partial is None or not terminal.partial.content))+ )else None)+ # Search-history repair owns one changed-request trial even after deltas. No client tool from+ # this attempt has run: _loop executes only a committed, successful tool-use response. Failed+ # deltas stay speculative (Vibey displays committed rows); audit usage rather than publishing a+ # failed narration and consuming a separate transcript-continuation budget.delay = (self.retry.delay(terminal, retries=retries, streamed=streamed, elapsed_s=time.monotonic() - started)if isinstance(terminal, ProviderError) and not relieve and rerender is None@@ -1012,6 +1040,9 @@ class Agent:terminal = replace(terminal, partial=None)if rerender is not None:await self._save_refusals()+ if rerender == "same":+ selected = route+ continueif rerender == "portable":selected, portable = route, Truecontinuediff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex dad004e65..af9d1b604 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -1737,6 +1737,14 @@ def pin_refusal(assembler: StreamAssembler, endpoint: ModelEndpoint, handed_backreturn replace(error, retryable=False, continuable=False, after_thinking=False, refusal=refusal)+def search_history_endpoint(endpoint: ModelEndpoint) -> ModelEndpoint:+ """Keep native execution and in-flight exchanges; only completed historical web searches become portable."""+ route = endpoint.hosted_tools.get("web_search")+ if route is None or not route.replay:+ return endpoint+ return replace(endpoint, hosted_tools={**endpoint.hosted_tools, "web_search": replace(route, replay=False)})++def portable_endpoint(endpoint: ModelEndpoint) -> ModelEndpoint:"""``endpoint`` in portable form (§3.5): never pinned, and every hosted tool as its function, so a request carriesno native declaration and replays no native payload. The hop's Source and identity stay for attribution: a responsediff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex 97a903e1a..3dffb2ccb 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -55,6 +55,7 @@ from core.agent_core.ai.provider import (ProviderError,MediaLoader,)+from core.agent_core.ai.search_recovery import search_replay_refusalfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.hosted_continuations import pending_hostedfrom core.agent_core.ai.transform import in_flight_position, native_replay@@ -895,6 +896,14 @@ class AnthropicAdapter(ProviderAdapter):if event is REFUSED:rejected = Truebreak+ if isinstance(event, ProviderError):+ repair = search_replay_refusal(event, sending, wire.body)+ if repair != event.refusal:+ event = replace(event, refusal=repair)+ if repair is not None:+ # The Agent owns bounds and retries of uncommitted output. The adapter only+ # identifies a changed request, equally for HTTP refusals and streamed errors.+ event = replace(event, retryable=False, continuable=False, after_thinking=False)yield eventfinally:await driver.aclose()diff --git a/core/agent_core/ai/errors.py b/core/agent_core/ai/errors.pyindex 919d3a806..50edb2850 100644--- a/core/agent_core/ai/errors.py+++ b/core/agent_core/ai/errors.py@@ -338,6 +338,10 @@ def _classify_kind(return "overflow"if is_overflow_message(message, status=status):return "overflow"+ if normalized_code in {"invalid_request_error", "upstream_request_invalid"}:+ # An SSE error has no HTTP 400 status. Its explicit request-rejection type is still permanent, not an+ # unknown/thinking-drop failure. Narrow compatibility recoveries are admitted separately by the adapter.+ return "invalid_request"if exc is not None:# A stall is not a connection failure: the provider was reached and# then stopped sending.diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex 4eaf60684..37f14006c 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -237,8 +237,8 @@ class ProviderError:#: The response streamed thinking and nothing else before this error (``THINKING_DROP_RETRY_KINDS``): it is#: ``retryable``, and the loop retries it at most once per request (``provider.md``).after_thinking: bool = False- #: A refusal before any output, which the loop answers by rendering the request again (``vibey-hosted-tools.md``- #: §3.5), never by the generic retry.+ #: A provider refusal which can change how history is rendered (``vibey-hosted-tools.md`` §3.5).+ #: Most require no output. Corroborated search refusals also permit repair of an uncommitted partial.refusal: Optional["Refusal"] = None#: Permission to continue from the committed transcript, not replay this request. False by default:#: only a classified transient failure grants it, even when streaming makes ``retryable`` false.@@ -251,17 +251,19 @@ class ProviderError:@dataclass(frozen=True)class Refusal:- """Why a request was refused before any output, so the next attempt renders it differently (§3.5).+ """Why a refused request can be rendered differently on the next attempt (§3.5).``pin_unavailable``: the gateway handed a pinned request back; ``tool`` and ``aspect`` name the narrow hosted rulethat fired, when one did. ``opaque_refused``: the provider refused an opaque payload a response of this Sourceidentity minted, replayed under an account that cannot read it (a key change, or a relay serving from anotheraccount); ``payloads`` says which kind (``OPAQUE_PAYLOADS``): Anthropic names it, xAI's "Could not decrypt theprovided encrypted_content" does not, so it is both. ``source_id`` and ``source_identity`` are the refused- request's hop.+ request's hop. ``search_history`` is a narrower Anthropic compatibility recovery: only completed historical+ web searches become portable; in-flight content and native tool declarations stay intact. It is a run-local+ replay decision, not a claim that the Source cannot execute searches or that a relay account changed."""- kind: Literal["pin_unavailable", "opaque_refused"]+ kind: Literal["pin_unavailable", "opaque_refused", "search_history"]source_id: Optional[str] = Nonesource_identity: Optional[str] = Nonetool: Optional[str] = Nonediff --git a/core/agent_core/ai/search_recovery.py b/core/agent_core/ai/search_recovery.pynew file mode 100644index 000000000..4e73332c7--- /dev/null+++ b/core/agent_core/ai/search_recovery.py@@ -0,0 +1,129 @@+"""Narrow Anthropic search-history refusal admission, corroborated by the submitted wire.++A prefill error is not a search diagnosis. Its one recovery trial needs a valid mixed+continuation and actual completed search history which the existing compiler can demote+without changing the in-flight exchange. No capability evidence is written here.+"""++from collections.abc import Mapping+import re+from typing import Any++from core.agent_core.ai._common import endpoint_origin, search_history_endpoint+from core.agent_core.ai.provider import ModelRequest, ProviderError, Refusal+from core.agent_core.ai.transform import transform_messages+from core.agent_core.messages import AssistantMessage, HostedToolBlock, ToolResultMessage++_SEARCH_ERROR = re.compile(+ r"invalid `?encrypted_content`? in `?search_result`? block|invalid `?encrypted_index`? in (?:a )?(?:`?web_search_result_location`? )?citation",+ re.IGNORECASE,+)+_PREFILL_ERROR = re.compile(+ r"This model does not support assistant message prefill\.\s*The conversation must end with a user message\.",+ re.IGNORECASE,+)+_BLOCK_PATH = re.compile(r"messages\.(\d+)\.content\.(\d+)")+++def _blocks(message: Any) -> list[Mapping[str, Any]]:+ content = message.get("content") if isinstance(message, Mapping) else None+ return [block for block in content if isinstance(block, Mapping)] if isinstance(content, list) else []+++def _search_id(block: Mapping[str, Any]) -> str | None:+ if block.get("type") == "server_tool_use" and block.get("name") == "web_search":+ value = block.get("id")+ elif block.get("type") == "web_search_tool_result":+ value = block.get("tool_use_id")+ else:+ return None+ return value if isinstance(value, str) and value else None+++def _mixed_continuation(messages: list[Any]) -> bool:+ """A tool-result-only user tail answers every client call beside a still-pending server search."""+ if len(messages) < 2 or any(not isinstance(message, Mapping) for message in messages[-2:]):+ return False+ before, tail = messages[-2:]+ blocks, results = _blocks(before), _blocks(tail)+ if (before.get("role") != "assistant" or tail.get("role") != "user" or not results+ or len(results) != len(tail.get("content", ())) or any(b.get("type") != "tool_result" for b in results)):+ return False+ calls = [b.get("id") for b in blocks if b.get("type") == "tool_use"]+ answered = [b.get("tool_use_id") for b in results]+ if not calls or any(not isinstance(value, str) or not value for value in (*calls, *answered)):+ return False+ if len(set(calls)) != len(calls) or sorted(calls) != sorted(answered):+ return False+ pending = {_search_id(b) for b in blocks if b.get("type") == "server_tool_use"} - {None}+ done = {_search_id(b) for b in blocks if b.get("type") == "web_search_tool_result"}+ return bool(pending - done)+++def search_replay_refusal(error: ProviderError, request: ModelRequest, body: Mapping[str, Any]) -> Refusal | None:+ """Admit a search repair only for ciphertext the request actually carries; preserve other refusal kinds.++ Called for HTTP rejection and upstream SSE error after normalization. Never inspect echoed input or arbitrary+ response fields for keywords. The history-only compiler identifies exchanges that can be demoted without changing+ the current continuation. Explicit rejection of remaining in-flight ciphertext retains the opaque fallback.+ """+ endpoint = request.endpoint+ if error.kind != "invalid_request" or error.status not in (None, 400):+ return error.refusal+ explicit = _SEARCH_ERROR.search(error.message) is not None+ prefill = _PREFILL_ERROR.search(error.message) is not None+ if not explicit and not prefill:+ return error.refusal+ if not endpoint.source_id or not endpoint.source_identity:+ return None+ messages = body.get("messages")+ if not isinstance(messages, list):+ return None+ if not explicit and not (+ request.messages and isinstance(request.messages[-1], ToolResultMessage) and _mixed_continuation(messages)+ ):+ return None+ uses, completed = set(), set()+ for message in messages:+ if not isinstance(message, Mapping) or message.get("role") != "assistant":+ continue+ for block in _blocks(message):+ call_id = _search_id(block)+ if call_id is None:+ continue+ if block.get("type") == "server_tool_use":+ uses.add(call_id)+ elif isinstance(block.get("content"), list) and any(+ isinstance(item, Mapping) and item.get("type") == "web_search_result"+ and isinstance(item.get("encrypted_content"), str) and item["encrypted_content"]+ for item in block["content"]+ ):+ completed.add(call_id)+ candidates = uses & completed+ if not candidates:+ return None+ if explicit and (path := _BLOCK_PATH.search(error.message)) is not None:+ try:+ named = messages[int(path[1])]["content"][int(path[2])]+ except (IndexError, KeyError, TypeError):+ named = None+ # Intermediaries can change message/block indices. A resolvable path narrows the explicit rejection,+ # but a stale path must not erase recovery for search ciphertext that this request really carries.+ named_id = _search_id(named) if isinstance(named, Mapping) else None+ if named_id in candidates:+ candidates = {named_id}+ compiled = transform_messages(+ request.messages, target=endpoint_origin(endpoint), protocol="anthropic",+ supports_images=request.supports_images, endpoint=search_history_endpoint(endpoint),+ )+ kept = {+ _search_id(item) for message in compiled.messages if isinstance(message, AssistantMessage)+ for block in message.content if isinstance(block, HostedToolBlock) for item in block.native.payload+ }+ if candidates - kept:+ return Refusal("search_history", endpoint.source_id, endpoint.source_identity, "web_search", "replay")+ if explicit:+ # History-only demotion cannot repair an explicitly rejected in-flight ciphertext. Keep the existing+ # portable opaque fallback available, including after a history trial; never permanently wedge a Session.+ return Refusal("opaque_refused", endpoint.source_id, endpoint.source_identity, "web_search", "replay", ("hosted",))+ return Nonediff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 704fdef22..64c1edf7e 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -145,6 +145,10 @@ HTTP `401/403` always map to `auth`, `413` to `overflow`, `429` tothat says so), otherwise `server`.Transport errors map to `network`, and the silence bound to `stalled`. Every classification is non-retryable oncethe assembler has emitted text or a tool-call event; after thinking alone, see the Retry boundary row.+`invalid_request_error` and `upstream_request_invalid` remain `invalid_request` even in an SSE error without an HTTP+400 status, unless the earlier overflow rule applies. The corroborated Anthropic search recovery in C-2 `provider.md`+is a separate changed-request repair: it keeps `retryable=false`, can discard an uncommitted partial, and does not+relax generic replay or grant transcript-continuation permission.## Endpoint identity and redaction ledgerdiff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex 13250b5eb..1a9c83395 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -72,7 +72,8 @@ History follows the same Source rule. A response's hosted calls go back verbatimwhen that hop's Source served them on the same origin (`conversion-tables.md`, Hosted tools): within their turn as acontinuation, later with the hop's current `replay`, and pinned to that Source either way.-**Refusals before any output** (`vibey-hosted-tools.md` §3.5). The gateway answers a pinned request it cannot serve+**Refusals and changed-request recovery** (`vibey-hosted-tools.md` §3.5). Except for the corroborated Anthropic+search recovery below, refusals require no output. The gateway answers a pinned request it cannot servefrom that Source with `409 pin_unavailable`, matched on its `type` and `code`, and names the narrow hosted rule thatfired in `error.reason` when one did. A provider refuses an opaque payload replayed under an account that cannot readit (a key change, or a relay serving a later turn from another pooled account, which no Source identity can see) with@@ -96,6 +97,26 @@ for xAI's). The loop answers it by rendering the request again, never by the genA `pause_turn` continuation's `pin_unavailable` comes after output, so it is no refusal (`conversion-tables.md`).+**Anthropic search replay compatibility** (`search-history-recovery.md`). An `invalid_request` from HTTP 400 or+SSE may carry the run-local `search_history` refusal when its precise search ciphertext/citation error corresponds+to native call/result pairs actually sent. A resolvable `messages.N.content.M` path narrows the match; a path that+does not name such a pair is only a hint, since intermediary indices may differ. The exact+assistant-prefill rejection is weaker evidence: it permits a trial only when canonical context ends in a real client+result, the wire ends in a tool-result-only user message answering all preceding client calls beside a pending native+search, and the compiler can demote completed search history. It is not a search diagnosis by itself.++The loop tries once per Source identity per run, on the same hop with only web-search `replay=False`. The existing+compiler preserves in-flight native content, declarations, saved client results, and signatures, while rendering+completed history portably. The decision is not persisted or learned as permanent capability evidence. If an explicit+search error instead names ciphertext remaining in the current exchange, the existing `opaque_refused(hosted)`+fallback remains available once, including after a history trial, and persists only the released `hosted` payload kind.+Absent ciphertext and already-demoted history do not authorize an unchanged retry.++Both search paths may replace an uncommitted partial: audit the failed attempt's usage and recompile before committing+any response. Failed client calls never execute, completed client results are not replayed, and Vibey publishes no+failed narration or duplicate search card. `retryable` and `continuable` stay false: this is a bounded changed-request+repair, not generic replay or an outer transcript continuation. Other refusal kinds retain their no-output boundary.+The loop's `ModelRouter` returns the `ModelEndpoint` together with its `ModelCapabilities`. Every capability has adefined effect, including when it is unknown:@@ -143,7 +164,7 @@ own bounded continuation policy (`loop-control.md`).| --- | --- | --- || `overflow` | the request exceeded the model's context (Pi's overflow patterns and Anthropic's refusal of input plus `max_tokens` over the window, HTTP 413, `context_length_exceeded`) | overflow recovery (plan §5.2) || `rate_limit`, `overloaded`, `network`, `stalled`, `server`, `interrupted` | transient (`network`: the provider could not be reached; `stalled`: a connected provider sent nothing for the silence bound; `interrupted`: the provider's stream ended after output without a terminal, as Model Hub reports with its own `modelHub.errors.stream_interrupted` frame) | retry with backoff, honoring `retry_after_s`, only when nothing was streamed (no deltas, no `partial`), at most 3 retries within 120 s; then the run ends with that error. After streamed text or a tool call the error is terminal for the request, matching Model Hub's first-byte rule; after thinking alone it is retried once (below) |-| `auth`, `invalid_request` | not retryable | end the run with the error. The one narrow exception is a strict final tool-argument parse failure: the adapter keeps a safe partial with every call, marks malformed call identities in `malformed_tool_calls`, and grants only Vibey's transcript-only recovery permission; no malformed call is executed. |+| `auth`, `invalid_request` | not retryable | end the run with the error, except for the corroborated search changed-request repair above and strict final tool-argument recovery below. Neither permits generic replay or execution of malformed calls. || `aborted` | cancelled by the caller | end the run as aborted || `unknown` | anything else | end the run with the error; after thinking alone, retry once (below) |@@ -161,7 +182,8 @@ A `ProviderError` whose `partial` is committed (a response that failed after outpartial's `error_message`, redacted like the error itself and bounded to 1,000 characters, so the transcript row sayswhy the response ended. A Stop's partial carries none.-A strict final tool-argument parse failure is the only `invalid_request` that carries recovery metadata. Its `partial`+A strict final tool-argument parse failure is the only `invalid_request` that grants transcript-continuation+permission (distinct from the search changed-request repair above). Its `partial`keeps text, thinking, and all canonical tool calls, replacing every malformed argument payload with `{}`. The`malformed_tool_calls` identities tell the loop which calls are unsafe: it commits the assistant row, records onemodel-visible error `tool_result` for each such call, executes valid sibling calls once, and then returns a boundeddiff --git a/docs/plans/search-history-recovery.md b/docs/plans/search-history-recovery.mdnew file mode 100644index 000000000..f75cc319a--- /dev/null+++ b/docs/plans/search-history-recovery.md@@ -0,0 +1,46 @@+# Search-history compatibility recovery++## Change contract++Implement an Avibe-only recovery for Anthropic native web-search history rejected by an upstream or pooled relay. Do not change relay routing, credentials, or production services, or retry the affected conversation as part of implementation.++The failure shape contains completed historical native searches, a later mixed server/client tool call, and a user message containing saved client tool results. A prefill rejection of that shape is a recovery candidate, not proof of a search defect. Synthetic regression coverage validates recovery behavior, not the original production cause.++### Admission and request changes++- Read only normalized provider rejection details, on `invalid_request` with HTTP 400 or an SSE error without HTTP status. Other errors retain their existing policy.+- Match explicit invalid search `encrypted_content` / citation `encrypted_index` errors against the submitted request's native search call/result pairs containing ciphertext. A `messages.N.content.M` path narrows the match when it resolves to such a pair; otherwise it is only a hint, since an intermediary's indices need not match this wire. Do not answer an error about absent ciphertext with an unchanged request.+- The exact assistant-prefill rejection permits one compatibility trial only if canonical context ends in a real client result, the wire ends in a tool-result-only user message answering every preceding client call, that assistant also has a pending native search, and there is completed native search history that can be demoted. Genuine assistant prefill, unrelated 400s, and malformed continuations are not search diagnoses.+- Reuse `transform_messages` with the web-search route's `replay=False`. Its existing deferred-exchange ownership identifies historical versus in-flight content. Historical exchanges become portable observations; current native exchanges, declarations, client call/result identities, and unrelated thinking signatures stay intact. Canonical history is never changed.+- An explicit refusal of ciphertext still in the current exchange retains the existing `opaque_refused(hosted)` fallback, including after a history trial. This converts that identity's hosted payloads to their portable form, with completed observations readable in place and a pending search carrying no invented result. It does not remove thinking signatures.++### Ownership, bounds, and compatibility++- Both a no-output rejection and a rejection after partial text/thinking/tool/search output are handled in the existing `_model` changed-request loop. Discard the failed, uncommitted attempt, audit its usage, and recompile from committed context on the same hop. No failed narration/search card is committed or republished. Vibey displays committed rows, not speculative deltas.+- No client call from a failed attempt executes. Previously completed client tool results remain context and are not run again. This is neither generic same-request replay nor an outer `Agent.resume` continuation.+- Allow one history-only trial per Source identity per run. An explicit current-ciphertext fallback is bounded by the existing one-per-(identity, payload kind) refusal handling. Already-portable requests and a repeated refusal cannot obtain another unchanged retry. RunScope still owns cancellation and normal tool/steer admission.+- Keep history-only decisions in memory, not as a new persisted `replay_refusal.payloads` value. A later turn may probe native history again; a guarded prefill error is not a permanent capability verdict. Existing explicit opaque refusals still use the released `hosted` / `signature` format, readable on rollback and by forks. No projection/schema migration is needed.+- No Model Hub evidence rule is broadened. History-replay compatibility and the ability to execute native searches remain separate.++## Validation++`tests/agent_core/ai/test_search_history_recovery.py` exercises the real adapter/compiler/Agent boundary with a deterministic mock upstream:++- direct/wrapped HTTP rejection and SSE rejection after partial output;+- initial native search, later mixed continuation, and a single corrected historical request;+- preserved current native calls, signatures, declarations, saved client results, and one client execution;+- repeated failures terminate; an explicit current ciphertext refusal still recovers after the historical trial, including after partial output;+- a steer accepted during rejection stays out of the pending native exchange; Stop prevents another request without losing the saved client result;+- genuine assistant prefill, missing history, invalid result pairing, unrelated/signature errors, and already-portable history do not gain history recovery; stale diagnostic indices do not remove recovery when ciphertext is present, while a resolvable path selects its own exchange.++`tests/test_vibey_agent.py` covers the distinct SQLite/delivery boundary: partial text, thinking, incomplete and completed client arguments, and a completed deferred search result, each with prefill or explicit search rejection, followed by either recovery or another refusal. The tests verify unchanged original rows, no failed partial/narration/search-card duplication, no repeated client execution, no new persisted refusal vocabulary, audited attempt usage, and the final success/error notice.++Run focused pytest and changed-file Ruff locally, independent read-only review, then exact-head Codex review and CI through the PR delivery loop. No live affected-session retry or deployment is part of validation.++## Known-by-design++- Portable history retains already-readable queries, sources, and citations, not decrypted page bodies.+- A retried provider attempt can repeat provider-owned read-only searches. The client cannot guarantee exactly-once upstream work; recovery must not repeat previously executed client tools.+- A successful compatibility trial does not establish the production root cause or prove that a hidden relay account changed.+- History-only trials are run-local. This intentionally avoids a permanent capability assertion and a rollback-incompatible on-disk marker.+- Generic retry, transcript-continuation budgets, gateway evidence, routing policy, and other protocols are unchanged except that explicit invalid-request SSE codes are classified as permanent errors rather than unknown failures.diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 95d46b191..bb23114da 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -359,6 +359,14 @@ failover, and is refused unpinned (C-6 item 7). What changes is what happens aft**every** opaque payload of that Source identity dropped for the rest of the turn: signatures, encrypted reasoningand native hosted payloads, since the refusal does not say which one failed. Once per (turn, identity); noevidence is written (§3.2).+- **Anthropic search compatibility is request-scoped** (C-2 `provider.md`, `search-history-recovery.md`). A precise+ ciphertext/citation rejection must correspond to native search ciphertext actually sent. The exact prefill error+ allows only a guarded trial on a valid mixed server/client continuation with completed native search history; it+ is not a permanent capability diagnosis. Once per identity per run, render that history with `replay=False` on the+ same hop, preserving native execution and the in-flight exchange. An explicit refusal of remaining current+ ciphertext can still use the existing hosted-opaque fallback. Both paths may replace an uncommitted failed partial+ in the model-request loop: audit usage, do not publish duplicate narration/search cards or rerun completed client+ tools. The history-only decision stays in memory; no new persisted refusal payload or gateway evidence rule is added.- **The cost is one cold prompt prefix.** Dropping a native declaration changes the tools block, so the resend andthe next turns start a new cache prefix: once per (Source, model, tool), since evidence is per model (anothermodel of the same Source may run the tool), when the refusal is first learned, and again onlydiff --git a/tests/agent_core/ai/test_hosted_replay.py b/tests/agent_core/ai/test_hosted_replay.pyindex 40adcabc3..b8fc78017 100644--- a/tests/agent_core/ai/test_hosted_replay.py+++ b/tests/agent_core/ai/test_hosted_replay.py@@ -348,13 +348,16 @@ async def test_an_opaque_payload_refusal_ends_the_send_as_a_refusal_of_its_sourcthe send with an opaque refusal of the request's Source identity and the kinds the provider named, pinned or not(§3.5). Any other 400 is the ordinary error."""- request = _request(_endpoint(protocol, replay=True, native=native))+ history = (_searched(protocol), UserMessage((TextBlock("next turn"),))) if protocol == "anthropic" and payloads == ("hosted",) else ()+ request = _request(_endpoint(protocol, replay=True, native=native), *history)sent, events = await _send(request, lambda _: httpx.Response(400, text=body))(error,) = eventsassert len(sent) == 1 and isinstance(error, ProviderError) and error.status == 400 and not error.retryableexpected = Refusal("opaque_refused", SOURCE, IDENTITY, payloads=payloads) if payloads else None+ if history:+ expected = Refusal("search_history", SOURCE, IDENTITY, "web_search", "replay") if native else Noneassert error.refusal == expected@@ -625,14 +628,14 @@ async def _session([(_SEARCH_REFUSAL, '"opaque"', "sig-account-a"), (_SIGNATURE_REFUSAL, "sig-account-a", '"opaque"')],ids=["search-result", "thinking-signature"],)-async def test_an_opaque_payload_another_account_refuses_is_sent_portably_from_then_on_in_the_session(+async def test_a_refused_payload_is_demoted_without_disabling_unrelated_native_content(refusal, demoted, kept, via_gateway):"""A relay can serve a later turn from another upstream account, which cannot read the search results or thinkingsignatures the first minted; Anthropic then refuses the request before any output, naming what it refused. The- Session's native search replays verbatim while that is accepted; once refused, the turn is sent again once without- that kind of payload from that Source identity, in its portable form, and succeeds. The Session keeps the- refusal: its next turn is portable from its first request, with no failed attempt. Only the kind refused goes."""+ Session's native search replays verbatim while accepted; once refused, the turn is sent again once without the+ refused history, and succeeds. Signature restrictions persist; history-only search trials remain run-local.+ Only the kind refused goes."""def answer(turn: int, attempt: int) -> httpx.Response:if turn == 1:@@ -653,8 +656,10 @@ async def test_an_opaque_payload_another_account_refuses_is_sent_portably_from_tif demoted == '"opaque"':# The search in its portable form: the query and the source, readable, with no encrypted data.assert "avibe release" in bodies[2][1] and "https://avibe.bot/r" in bodies[2][1]- # The next turn: portable from its first request.- assert len(bodies[3]) == 1 and demoted not in bodies[3][0] and kept in bodies[3][0]+ # Signature rejection keeps its existing Session-wide restriction. History-only search repair is run-local;+ # the gateway may learn replay evidence separately, but this fake gateway does not, so a new turn probes again.+ assert len(bodies[3]) == 1 and kept in bodies[3][0]+ assert (demoted not in bodies[3][0]) is (refusal == _SIGNATURE_REFUSAL)async def test_a_refusal_of_what_the_session_already_demoted_stands_as_the_error():diff --git a/tests/agent_core/ai/test_search_history_recovery.py b/tests/agent_core/ai/test_search_history_recovery.pynew file mode 100644index 000000000..07d658fb9--- /dev/null+++ b/tests/agent_core/ai/test_search_history_recovery.py@@ -0,0 +1,304 @@+"""Search-history repair, not a blanket invalid-request retry. Scenario MH-HOSTED-VIBEY-005.++Existing opaque tests omit deferred native calls and reject only before output. These+regressions exercise the real wire compiler and adapter with that missing shape.+"""++from dataclasses import replace+import json++import httpx+import pytest++from core.agent_core.agent.loop import Agent+from core.agent_core.ai.provider import ProviderError, Refusal+from core.agent_core.messages import (+ AssistantMessage, HostedAction, HostedNative, HostedRecord, HostedSummary,+ HostedToolBlock, TextBlock, ThinkingBlock, ToolCallBlock, ToolResultMessage, UserMessage,+)+from tests.agent_core.ai import test_hosted_replay as replay+from tests.agent_core.fakes import FakeJobHost, FakeTool, InMemoryTranscriptStore, input_row++PREFILL = "This model does not support assistant message prefill. The conversation must end with a user message."+SEARCH_ERROR = "Invalid encrypted_content in search_result block"+LIVE_USE = {+ "type": "server_tool_use", "id": "srvtoolu_live", "name": "web_search", "input": {"query": "next release"},+}+LIVE_RESULT = {+ "type": "web_search_tool_result", "tool_use_id": "srvtoolu_live",+ "content": [{"type": "web_search_result", "title": "Next", "url": "https://avibe.bot/next", "encrypted_content": "new-opaque"}],+}+++def mixed_request(*, history=True):+ endpoint = replay._endpoint("anthropic", replay=True)+ old = replay._searched("anthropic")+ pending = HostedToolBlock(+ "srvtoolu_live", "web_search", HostedAction("search", queries=("next release",)),+ HostedRecord(status="pending"), HostedNative(source_id=replay.SOURCE, payload=(LIVE_USE,)),+ )+ live = AssistantMessage(+ (ThinkingBlock(text="read first", signature="live-signature"), pending,+ ToolCallBlock("toolu_read", "read", {"path": "a"})),+ old.origin, "tool_use", hosted_summary=HostedSummary(), source_identity=replay.IDENTITY,+ )+ earlier = (old, UserMessage((TextBlock("next"),))) if history else ()+ request = replay._request(+ endpoint, *earlier, live, ToolResultMessage("toolu_read", "read", (TextBlock("saved result"),)),+ )+ return replace(request, tools=(replay.WEB, FakeTool("read").spec))+++def failed_stream(detail, output="text"):+ events = [{"type": "message_start", "message": {"usage": {"input_tokens": 7}}}]+ if output == "text":+ events += [+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "partial answer"}},+ {"type": "content_block_stop", "index": 0},+ ]+ elif output == "thinking":+ events += [+ {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "partial thought"}},+ ]+ elif output == "search":+ events += [+ {"type": "content_block_start", "index": 0, "content_block": LIVE_RESULT},+ {"type": "content_block_stop", "index": 0},+ ]+ elif output in {"tool", "complete-tool"}:+ events += [+ {"type": "content_block_start", "index": 0,+ "content_block": {"type": "tool_use", "id": "toolu_unfinished", "name": "read", "input": {}}},+ {"type": "content_block_delta", "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": '{"path": "a"}' if output == "complete-tool" else '{"path":'}},+ ]+ if output == "complete-tool":+ events.append({"type": "content_block_stop", "index": 0})+ events.append({"type": "error", "error": {"type": "invalid_request_error", "message": detail}})+ return replay._sse("anthropic", tuple(events))++[email protected]("detail", [SEARCH_ERROR, "Invalid encrypted_index in citation", PREFILL])[email protected]("transport", ["http", "wrapped", "stream-text", "stream-thinking", "stream-tool"])+async def test_search_recovery_is_identified_on_the_actual_wire_even_after_output(detail, transport):+ request = mixed_request()+ if transport.startswith("stream-"):+ response = httpx.Response(200, headers=replay._served("anthropic"), text=failed_stream(detail, transport[7:]))+ else:+ response = httpx.Response(400, json=replay._anthropic_refusal(detail, via_gateway=transport == "wrapped"))++ sent, events = await replay._send(request, lambda _: response)++ assert len(sent) == 1 # Classification only; the Agent owns recovery.+ error = events[-1]+ assert isinstance(error, ProviderError)+ assert error.refusal == Refusal(+ "search_history", replay.SOURCE, replay.IDENTITY, "web_search", "replay",+ )+ assert not error.retryable and not error.continuable+ assert (error.partial is not None) == transport.startswith("stream-")++[email protected]("transport", ["http", "thinking"])[email protected]("case", ["assistant-tail", "no-history", "wrong-result", "extra-user-text", "unrelated", "signature", "portable"])+async def test_prefill_is_not_an_unconditional_search_refusal(case, transport):+ request = mixed_request(history=case != "no-history")+ detail = PREFILL+ if case == "assistant-tail":+ request = replace(request, messages=request.messages[:-1])+ elif case == "wrong-result":+ request = replace(request, messages=(*request.messages[:-1], replace(request.messages[-1], tool_call_id="unrelated")))+ elif case == "extra-user-text":+ request = replace(request, messages=(*request.messages, UserMessage((TextBlock("continue"),))))+ elif case == "unrelated":+ detail = "invalid max_tokens"+ elif case == "signature":+ detail = "Invalid signature in thinking block"+ elif case == "portable":+ route = replace(request.endpoint.hosted_tools["web_search"], replay=False)+ request = replace(request, endpoint=replace(request.endpoint, hosted_tools={"web_search": route}))++ response = (+ httpx.Response(200, headers=replay._served("anthropic"), text=failed_stream(detail, "thinking"))+ if transport == "thinking"+ else httpx.Response(400, json=replay._anthropic_refusal(detail, via_gateway=False))+ )+ _, events = await replay._send(request, lambda _: response)++ error = events[-1]+ assert isinstance(error, ProviderError)+ assert error.kind == "invalid_request" and not error.retryable and not error.continuable+ assert error.refusal is None or error.refusal.kind != "search_history"+++def mixed_stream(*, completed=False):+ events = (+ {"type": "message_start", "message": {"usage": {"input_tokens": 5}}},+ {"type": "content_block_start", "index": 0,+ "content_block": {"type": "thinking", "thinking": "read first", "signature": "live-signature"}},+ {"type": "content_block_stop", "index": 0},+ {"type": "content_block_start", "index": 1, "content_block": LIVE_USE},+ {"type": "content_block_stop", "index": 1},+ {"type": "content_block_start", "index": 2,+ "content_block": {"type": "tool_use", "id": "toolu_read", "name": "read", "input": {"path": "a"}}},+ {"type": "content_block_stop", "index": 2},+ {"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 3}},+ {"type": "message_stop"},+ )+ if completed:+ # The current search already finished before the client tool; its ciphertext can independently be refused.+ tail = tuple({**event, "index": 3} if "index" in event else event for event in events[5:])+ events = (*events[:5],+ {"type": "content_block_start", "index": 2, "content_block": LIVE_RESULT},+ {"type": "content_block_stop", "index": 2}, *tail)+ return replay._sse("anthropic", events)+++def completed_stream():+ events = (+ {"type": "message_start", "message": {"usage": {"input_tokens": 5}}},+ {"type": "content_block_start", "index": 0, "content_block": LIVE_RESULT},+ {"type": "content_block_stop", "index": 0},+ *replay._ANSWERED["anthropic"][1:],+ )+ # The final text has its own index after the result.+ events = tuple({**event, "index": 1} if event.get("index") == 0 and i > 2 else event for i, event in enumerate(events))+ return replay._sse("anthropic", events)++[email protected]("detail", [PREFILL, SEARCH_ERROR])[email protected]("again", [False, True])+async def test_only_completed_history_is_demoted_and_the_client_tool_is_not_rerun(monkeypatch, detail, again):+ read = FakeTool("read")+ monkeypatch.setattr(replay, "READ", read)++ def answer(turn, attempt):+ if turn == 1:+ return httpx.Response(200, headers=replay._served("anthropic"), text=replay._searched_and_answered())+ if turn == 2:+ if attempt == 1:+ return httpx.Response(200, headers=replay._served("anthropic"), text=mixed_stream())+ if attempt == 2 or again:+ return httpx.Response(400, json=replay._anthropic_refusal(detail, via_gateway=True))+ return httpx.Response(200, headers=replay._served("anthropic"), text=completed_stream())+ return httpx.Response(200, headers=replay._served("anthropic"), text=replay._sse("anthropic", replay._ANSWERED["anthropic"]))++ sent, ended = await replay._session(answer, replay._endpoint("anthropic", replay=True), turns=2 if again else 3)++ assert len(read.calls) == 1+ assert len(sent[1]) == 3 # The failed continuation has exactly one repair attempt.+ assert ended[1].reason == ("error" if again else "completed")+ before, after = [json.loads(wire.content) for wire in sent[1][1:]]+ before_blocks, after_blocks = (replay._history_items("anthropic", body) for body in (before, after))+ assert replay.RESULT in before_blocks and replay.RESULT not in after_blocks+ assert LIVE_USE in after_blocks+ assert before["messages"][-2:] == after["messages"][-2:] # Preserve signed thinking and the saved result.+ assert before["tools"] == after["tools"]+ assert "avibe release" in json.dumps(after) and "https://avibe.bot/r" in json.dumps(after)+ if not again:+ assert len(sent[2]) == 1 and ended[2].reason == "completed"+ # A guarded trial does not teach permanent capability evidence or extend the persisted payload vocabulary.+ assert '"opaque"' in sent[2][0].content.decode()++[email protected]("partial", [False, True])[email protected]("again", [False, True])+async def test_an_explicit_in_flight_ciphertext_refusal_still_recovers_after_the_history_trial(monkeypatch, partial, again):+ """Demoting history must not wedge a Session when the next rejection names current ciphertext."""+ read = FakeTool("read")+ monkeypatch.setattr(replay, "READ", read)++ def answer(turn, attempt):+ if turn == 1:+ return httpx.Response(200, headers=replay._served("anthropic"), text=replay._searched_and_answered())+ if attempt == 1:+ return httpx.Response(200, headers=replay._served("anthropic"), text=mixed_stream(completed=True))+ if partial and attempt == 3:+ return httpx.Response(200, headers=replay._served("anthropic"), text=failed_stream(SEARCH_ERROR))+ if attempt in (2, 3) or again:+ return httpx.Response(400, json=replay._anthropic_refusal(SEARCH_ERROR, via_gateway=True))+ return httpx.Response(200, headers=replay._served("anthropic"), text=replay._sse("anthropic", replay._ANSWERED["anthropic"]))++ sent, ended = await replay._session(answer, replay._endpoint("anthropic", replay=True), turns=2)++ assert ended[1].reason == ("error" if again else "completed") and len(sent[1]) == 4 and len(read.calls) == 1+ history_repaired = json.loads(sent[1][2].content)+ fully_repaired = json.loads(sent[1][3].content)+ assert '"opaque"' not in json.dumps(history_repaired) and '"new-opaque"' in json.dumps(history_repaired)+ assert "encrypted_content" not in json.dumps(fully_repaired)+ assert "live-signature" in json.dumps(fully_repaired)+ assert "https://avibe.bot/next" in json.dumps(fully_repaired)+ assert history_repaired["messages"][-1] == fully_repaired["messages"][-1]++[email protected]("path", ["messages.1.content.1", "messages.3.content.1", "messages.9.content.0", "messages.90.content.1"])[email protected]("history", [False, True])+async def test_a_search_error_path_is_a_hint_but_actual_request_ciphertext_is_required(path, history):+ request = mixed_request(history=history)+ _, events = await replay._send(request, lambda _: httpx.Response(+ 400, json=replay._anthropic_refusal(f"{path}: {SEARCH_ERROR}", via_gateway=False),+ ))+ error = events[-1]+ assert isinstance(error, ProviderError)+ assert (error.refusal.kind if error.refusal else None) == ("search_history" if history else None)+++async def test_a_resolvable_path_selects_the_current_ciphertext_instead_of_unrelated_history():+ request = mixed_request()+ live = request.messages[-2]+ current = live.content[1]+ finished = replace(current, record=HostedRecord(status="completed"), native=replace(current.native, payload=(LIVE_USE, LIVE_RESULT)))+ request = replace(request, messages=(*request.messages[:-2], replace(live, content=(live.content[0], finished, live.content[2])), request.messages[-1]))+ _, events = await replay._send(request, lambda _: httpx.Response(+ 400, json=replay._anthropic_refusal(f"messages.3.content.2: {SEARCH_ERROR}", via_gateway=False),+ ))+ assert isinstance(events[-1], ProviderError)+ assert events[-1].refusal == Refusal("opaque_refused", replay.SOURCE, replay.IDENTITY, "web_search", "replay", ("hosted",))++[email protected]("action", ["steer", "stop"])+async def test_control_input_during_a_search_refusal_does_not_break_the_saved_tool_continuation(action):+ """A recompile after failed deltas must not admit a steer early or bypass Stop.++ Existing deferred-steer tests have no rejected request or changed-request loop between the result and completion.+ """+ seen, read, store = [], FakeTool("read"), InMemoryTranscriptStore()++ async def gateway(wire):+ seen.append(json.loads(wire.content))+ if len(seen) == 1:+ body = replay._searched_and_answered()+ elif len(seen) == 2:+ body = mixed_stream()+ elif len(seen) == 3:+ if action == "steer":+ assert await agent.steer(input_row("steer", "extra user input"))+ else:+ agent.abort("user stop")+ body = failed_stream(PREFILL)+ elif len(seen) == 4:+ body = completed_stream()+ else:+ body = replay._sse("anthropic", replay._ANSWERED["anthropic"])+ return httpx.Response(200, headers=replay._served("anthropic"), text=body)++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ for turn in (1, 2):+ agent = Agent(+ session_id="session", models=replay._Hops(client, (replay._endpoint("anthropic", replay=True),)),+ tools=(replay._hosted_tool("web_search"), read), hooks=(), store=store, jobs=FakeJobHost(), cwd="/test-owned",+ )+ events = [event async for event in agent.run(input_row(f"input-{turn}", "search"), turn_id=f"turn-{turn}")]++ assert len(read.calls) == 1+ assert events[-1].reason == ("completed" if action == "steer" else "aborted")+ assert len(seen) == (5 if action == "steer" else 3)+ rows = await store.load("session")+ assert sum(row.kind == "tool_result" and row.message.tool_call_id == "toolu_read" for row in rows) == 1+ if action == "steer":+ assert seen[2]["messages"][-2:] == seen[3]["messages"][-2:]+ assert "extra user input" not in json.dumps(seen[3])+ assert "extra user input" in json.dumps(seen[4])+ assert sum(row.kind == "input" and row.row_id == "steer" for row in rows) == 1diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 31933ae42..ad846e6bf 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -439,7 +439,9 @@ scenarios:- tests/agent_core/ai/test_hosted_replay.py::test_pin_unavailable_ends_the_pinned_send_as_a_refusal_with_no_output- tests/agent_core/ai/test_hosted_replay.py::test_refusals_are_answered_within_their_bounds_and_portable_rendering_is_the_last_resort- tests/agent_core/ai/test_hosted_replay.py::test_an_opaque_payload_refusal_ends_the_send_as_a_refusal_of_its_source_identity- - tests/agent_core/ai/test_hosted_replay.py::test_an_opaque_payload_another_account_refuses_is_sent_portably_from_then_on_in_the_session+ - tests/agent_core/ai/test_hosted_replay.py::test_a_refused_payload_is_demoted_without_disabling_unrelated_native_content+ - tests/agent_core/ai/test_search_history_recovery.py::test_only_completed_history_is_demoted_and_the_client_tool_is_not_rerun+ - tests/test_vibey_agent.py::test_search_history_repair_after_partial_output_does_not_republish_or_reexecute- tests/agent_core/ai/test_hosted_replay.py::test_a_refusal_of_what_the_session_already_demoted_stands_as_the_error- tests/agent_core/ai/test_hosted_replay.py::test_anthropic_thinking_fallback_is_scoped_to_manual_claude_tool_loops- tests/agent_core/ai/test_hosted_replay.py::test_a_session_whose_signatures_were_refused_still_finishes_tool_loops_with_thinking_ondiff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 09e2a6584..df890b0b3 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -1310,6 +1310,86 @@ async def test_a_transient_failure_continues_from_the_same_transcript_without_a_assert harness.controller.terminals[-1]["is_error"] is False[email protected]("output", ["text", "thinking", "tool", "complete-tool", "search"])[email protected]("refusal", ["prefill", "encrypted"])[email protected]("again", [False, True])+async def test_search_history_repair_after_partial_output_does_not_republish_or_reexecute(+ engine, session, tmp_path, published, continuation_policy, output, refusal, again, monkeypatch+):+ """The real parser/loop/SQLite/delivery path preserves executed client results after a streamed refusal.++ Failed deltas were never a completed response. Repair the request before committing one, rather than publishing+ a failed narration/search card and then redoing it through an outer transcript continuation.+ """+ import httpx+ from modules.agents.vibey.models import registry_providers+ from tests.agent_core.ai import test_hosted_replay as replay+ from tests.agent_core.ai.test_search_history_recovery import (+ PREFILL, SEARCH_ERROR, LIVE_USE, completed_stream, failed_stream, mixed_stream,+ )++ continuation_policy(initial_delay_s=0)+ monkeypatch.setattr("core.message_mirror._activity_streaming_enabled", lambda: True)+ seen = []+ detail = PREFILL if refusal == "prefill" else SEARCH_ERROR+ served = {"provider": "test-provider", "api": "anthropic", "model": "test-model", "source": replay.SOURCE}+ headers = {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(served)}++ def gateway(request):+ seen.append(json.loads(request.content))+ if len(seen) == 1:+ body = replay._searched_and_answered()+ elif len(seen) == 2:+ body = mixed_stream()+ elif len(seen) == 3:+ body = failed_stream(detail, output)+ elif len(seen) == 4 and not again:+ body = completed_stream()+ else:+ return httpx.Response(400, json=replay._anthropic_refusal(detail, via_gateway=True))+ return httpx.Response(200, headers=headers, text=body)++ read = FakeTool("read")+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(+ engine, tmp_path, "telegram", [], tools=[read],+ providers=registry_providers(media_loader=None, client=client),+ )+ harness.controller.hub_source_id = replay.SOURCE+ harness.controller.im_client.supports_message_editing = lambda context=None: False+ harness.controller.hub_hosted_tools = {"web_search": {+ "native": "assumed", "declaration": {"type": "web_search_20250305", "name": "web_search"},+ "include": [], "replay": "assumed",+ }}+ await harness.agent.handle_message(harness.request("search"))+ original = tuple(await harness.context_rows())+ await harness.agent.handle_message(harness.request("read and search"))++ assert len(seen) == 4+ assert len(read.calls) == 1 # The interrupted tool parameters never execute; the completed tool never reruns.+ assert seen[2]["messages"][-2:] == seen[3]["messages"][-2:]+ blocks = replay._history_items("anthropic", seen[3])+ assert LIVE_USE in blocks and replay.RESULT not in blocks+ assert seen[2]["tools"] == seen[3]["tools"]+ rows = await harness.context_rows()+ assert tuple(rows[:len(original)]) == original+ partials = [row.message for row in rows if row.kind == "response" and row.message.stop_reason == "error"]+ assert partials == []+ assert not any(row.kind == "replay_refusal" for row in rows) # No new persisted shape; rollback remains readable.+ assert not any("partial answer" in line for line in harness.controller.im_client.sent)+ assert sum("next release" in line for line in harness.controller.im_client.sent) == (0 if again else 1)+ with engine.connect() as conn:+ assert conn.execute(select(agent_events.c.id).where(+ agent_events.c.session_id == SESSION, agent_events.c.event_type == "model_attempt"+ )).first() is not None # The discarded attempt's usage still has an owner.+ assert harness.controller.terminals[-1]["is_error"] is again+ if not again:+ assert harness.rows("notify") == []+ assert harness.controller.im_client.sent[-1] == "ok"+ if output in {"tool", "complete-tool"}:+ assert not any(row.kind == "tool_result" and row.message.tool_call_id == "toolu_unfinished" for row in rows)++async def test_a_silent_stop_resumes_the_same_transcript_without_a_notice(engine, session, tmp_path, published, continuation_policy) -> None: