Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): switch a repeatedly interrupted native search to the proxied route (#3078)

Call Whitec9e94aa762c2
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index ecd8d3fa4..c58a17677 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -466,6 +466,16 @@ class Agent:
self._outcome.primary("aborted")
self._ctx.cancel.cancel(reason)
+ @property
+ def last_attempt_response(self) -> Optional[AssistantMessage]:
+ """The latest conversation attempt's committed response, not an earlier attempt's.
+
+ An output-free failure returns None, even when an earlier attempt in this
+ run committed a partial. Adapters use this fact to qualify continuation.
+ """
+ attempt = next((item for item in reversed(self._attempts) if item.purpose == "conversation"), None)
+ return deepcopy(attempt.message) if attempt is not None and attempt.committed else None
+
def snapshot(self) -> Snapshot:
"""A committed cut, including only state that can be restored there."""
seq = self._rows[-1].context_seq if self._rows else 0
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.py
index af9d1b604..c5e4b48c8 100644
--- a/core/agent_core/ai/_common.py
+++ b/core/agent_core/ai/_common.py
@@ -2364,8 +2364,12 @@ PARTIAL_ERROR_MESSAGE_CHARS = 1000
def _partial_with_error(error: ProviderError) -> ProviderError:
"""The provider's error text on the partial it leaves; a Stop's partial needs none."""
partial = error.partial
- if partial is None or partial.error_message is not None or error.kind == "aborted" or not error.message:
+ if partial is None or error.kind == "aborted":
return error
+ if partial.error_kind != error.kind:
+ partial = replace(partial, error_kind=error.kind)
+ if partial.error_message is not None or not error.message:
+ return replace(error, partial=partial)
return replace(error, partial=replace(partial, error_message=error.message))
diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.py
index 37f14006c..0a960fb5c 100644
--- a/core/agent_core/ai/provider.py
+++ b/core/agent_core/ai/provider.py
@@ -55,12 +55,18 @@ class HostedToolRoute:
declaration: Optional[Mapping[str, Any]] = None
include: tuple[str, ...] = ()
refused: bool = False
+ #: Internal reason this request selected a recovery proxy, never refusal/capability evidence.
+ route_switch: Optional[str] = None
def __post_init__(self) -> None:
if self.mode not in ("native", "proxy"):
raise ValueError(f"unknown hosted tool mode: {self.mode!r}")
if not isinstance(self.replay, bool) or not isinstance(self.refused, bool):
raise ValueError("hosted replay and refused must be booleans")
+ if self.route_switch is not None and self.route_switch != "native_interrupted":
+ raise ValueError(f"unknown hosted route switch: {self.route_switch}")
+ if self.route_switch is not None and self.mode != "proxy":
+ raise ValueError("a route switch must use a proxy hosted tool")
if self.refused and self.mode != "proxy":
raise ValueError("a tool its Source refused runs as its function")
if self.mode == "proxy":
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
index bf9fde373..844d55be5 100644
--- a/core/agent_core/messages.py
+++ b/core/agent_core/messages.py
@@ -745,6 +745,9 @@ class HostedResult:
#: A search call that ran as its function only because the turn's own Source refused it natively; absent when it
#: ran where it was declared, or where the vendor never offers the tool natively.
fallback_from: Optional[HostedFallback] = None
+ #: A presentation-only reason for a proxied call selected after repeated native interruptions. This is not refusal
+ #: evidence. Carried in process; persisted in tool-result details, never the canonical message wire.
+ route_switch: Optional[str] = field(default=None, compare=False, repr=False)
def __post_init__(self) -> None:
if not isinstance(self.record, (HostedRecord, WebFetchRecord)):
@@ -752,6 +755,9 @@ class HostedResult:
_require(self.execution, ProxyExecution, "proxy execution", optional=True)
_require(self.action, HostedAction, "hosted result action", optional=True)
_require(self.fallback_from, HostedFallback, "hosted fallback", optional=True)
+ _require(self.route_switch, str, "hosted route switch", optional=True)
+ if self.route_switch is not None and self.route_switch != "native_interrupted":
+ raise ValueError(f"unknown hosted route switch: {self.route_switch}")
if self.execution is None and self.record.status != "failed":
raise ValueError("a hosted result without an execution is a failed record")
@@ -839,6 +845,9 @@ class AssistantMessage:
#: credential generation), when known: its opaque payloads go back only to a hop of that identity, since an account
#: refuses another's ciphertext (``cross-provider.md``). Credential-free.
source_identity: Optional[str] = None
+ #: Provider classification carried to the store as response-row metadata, not a canonical message field.
+ #: A later hop can distinguish transient cut-offs without interpreting provider wording as capability evidence.
+ error_kind: Optional[str] = field(default=None, compare=False, repr=False)
def __post_init__(self) -> None:
_require_blocks(self.content, (TextBlock, ThinkingBlock, ToolCallBlock, HostedToolBlock), "assistant message")
@@ -848,6 +857,7 @@ class AssistantMessage:
_require(self.error_message, str, "error_message", optional=True)
_require(self.hosted_summary, HostedSummary, "hosted_summary", optional=True)
_require_text(self.source_identity, "source_identity", optional=True)
+ _require(self.error_kind, str, "error_kind", optional=True)
hosted = any(isinstance(block, HostedToolBlock) for block in self.content)
if hosted != (self.hosted_summary is not None):
raise ValueError("a hosted summary is present exactly when the message has hosted tool blocks")
diff --git a/core/hosted_activity.py b/core/hosted_activity.py
index 14e44d6ca..1083aedb8 100644
--- a/core/hosted_activity.py
+++ b/core/hosted_activity.py
@@ -184,6 +184,8 @@ class HostedActivity:
executor_kind: Optional[Literal["service", "model", "local"]] = None
fetch: Optional[WebFetchRecord] = None
switch: Optional[HostedSwitch] = None
+ # Presentation-only explanation for a proxy hop selected after repeated native interruptions.
+ route_switch: Optional[Literal["native_interrupted"]] = None
# Policy refusal: the service ids already sent this URL; empty means no forwarding.
policy_sources: Optional[tuple[str, ...]] = None
# Display-only category of the owning model response's failure, never provider text.
@@ -228,6 +230,7 @@ class HostedActivity:
"response_id": self.response_id,
"executor_kind": self.executor_kind,
"interruption": self.interruption,
+ "route_switch": self.route_switch,
}
payload.update({key: value for key, value in optional.items() if value is not None})
if self.policy_sources is not None:
@@ -598,6 +601,7 @@ def proxy_activity(
fallback_source_name=(
source_names(result.fallback_from.source_id) if result.fallback_from is not None else None
),
+ route_switch=result.route_switch,
cost_at_least=at_least,
attempts=attempts,
executor_kind=kind,
@@ -687,6 +691,12 @@ def _ran(activity: HostedActivity, lang: str, escape: Callable[[str], str]) -> l
more = _count(activity, lang) if len(activity.images) > 1 else None
return [_untrusted(activity.model, escape) if activity.model else None, size, more]
vendor = _runner_label(activity, lang, escape)
+ if vendor and activity.mode == "proxy" and activity.route_switch == "native_interrupted":
+ return [
+ i18n_t("hostedTools.mode.nativeInterrupted", lang, provider=vendor),
+ _switch_text(activity, lang, escape) if activity.switch is not None else None,
+ _count(activity, lang),
+ ]
if vendor and activity.mode == "proxy" and activity.fallback_source_id is not None:
# Why it ran by proxy: the turn's own Source refused the native tool (§8.3, mockup 06).
refused_by = _untrusted(activity.fallback_source_name or activity.fallback_source_id, escape)
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index bb23114da..cf072390e 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -376,6 +376,66 @@ failover, and is refused unpinned (C-6 item 7). What changes is what happens aft
never swaps declarations or converts history. C-6 item 6's opaque thinking strip still applies to unpinned
requests only.
+### 3.6 Repeated native-search interruptions (owner decision 2026-10-30)
+
+When a native `web_search` (and `x_search` where the frozen Turn has a proxy
+executor) is repeatedly cut off by the upstream, Vibey retries the native route
+first. The decision is per tool and Turn-scoped:
+
+- Count committed responses in this Turn whose `stop_reason` is `error`, whose
+ persisted upstream class is transient (`overloaded`, `server`, `network`,
+ `stalled` or `interrupted`), and whose native call for that tool is still
+ pending. Counts for another tool do not contribute.
+- The first three qualifying failures keep the native declaration. On the
+ fourth, later hops of this Turn declare the same-named function tool and use
+ the frozen proxy executor order. If the existing recovery budget makes the
+ next hop the last permitted retry before its deadline or attempt cap, the
+ switch happens on that last permitted retry instead of spending it natively.
+ A tool with no frozen proxy candidate keeps its existing retry/failure path.
+- This is not a refusal: it writes no negative capability/refusal evidence, does
+ not change the native preference or Tools-tab refusal state, and a new Turn
+ starts native again. The provider error class travels with the partial in
+ process and commits as response-row metadata (not a new canonical message
+ field); older rows use only explicitly classifiable error wording. New response
+ metadata projects the qualifying interrupted tools and the request's actual
+ recovery-proxy routes. This immutable per-response route fact is necessary:
+ after an early switch below four, a successful response resets the episode
+ budget but must not restore native search within the same Turn, including after
+ restart. Before a response commits, the router's existing current hop retains
+ the switch through in-place retries and re-resolution. Hop resolution reads
+ small response facts, not the Turn's tool outputs;
+ only legacy response bodies need decoding. The display explanation uses the
+ existing tool-result `details` map. No frozen contract, settings, or mutable
+ Turn-level switch flag is added.
+- Two existing recovery budgets are distinct. Model Hub has a 120-second
+ recovery window, 30/60/120-second server-error delays (with jitter), and a
+ one-second admission margin. It cannot retry a stream already committed to
+ the client; those cut-offs are recovered by Vibey's transcript continuations.
+ Vibey normally allows five continuations, with 0.5/1/2/4/8-second backoff and a
+ 120-second window starting at the first continuable failure. This budget belongs
+ to a **failure episode**: any successfully committed model response ends it and
+ resets both elapsed time and attempt count; consecutive failures share it.
+ Request duration and recovery work spend the window; `Retry-After` remains a
+ floor and Stop owns the wait. The last admitted continuation switches early
+ only for a tool still pending in the **just-failed response**, with a proxy
+ candidate. Older interruptions never grant extra retries for unrelated errors.
+ A long streamed request can itself overrun the window, or the first native
+ interruption can occur on the last normal attempt. The one explicit exception
+ to both normal limits is **at most one proxied reserve request per episode**,
+ qualified by that same just-failed native call and candidate. It consumes the
+ episode's final slot, never renews either budget, and a failed reserve cannot
+ obtain another one, even for a different tool. The Turn-wide count is used only
+ for the ordinary four-failure threshold. Model Hub's per-request budget is
+ unchanged.
+- Earlier completed native items stay in context. Because the current route is
+ now function-only, the existing cross-mode replay transform downgrades those
+ items to portable ordinary call/result content; it does not invent refusal
+ evidence. OpenAI Responses and Anthropic adapters follow the same rule.
+
+The Web card and IM line name the proxy without claiming a failure count (for
+example, “Native search was interrupted; switched to Exa (free).” /
+“自带搜索中断,已改用 Exa(免费)。”).
+
## 4. Vibey responsibilities
### 4.1 Request building
diff --git a/docs/plans/web-search-services.md b/docs/plans/web-search-services.md
index 2b759922d..c71179ec7 100644
--- a/docs/plans/web-search-services.md
+++ b/docs/plans/web-search-services.md
@@ -1,8 +1,10 @@
# Web search services
Status: **design**, 2026-10-19. Direction and the six product decisions in §0 are owner-approved (2026-10-19 15:38).
-- Scope: Vibey's `web_search` through Model Hub. `x_search`, `image_generate`, Claude Code, Codex and OpenCode are
- unchanged.
+- Scope: Vibey's `web_search` through Model Hub; the shared native-interruption recovery rule in hosted tools §3.6 also
+ applies to `x_search` when a proxied candidate is available. Other `image_generate`, Claude Code, Codex and OpenCode
+ behavior is unchanged.
+- Repeated native-search cut-offs are Turn-scoped and never capability/refusal evidence; see [`vibey-hosted-tools.md`](vibey-hosted-tools.md) §3.6.
- Extends [`vibey-hosted-tools.md`](vibey-hosted-tools.md) (design v2). Every rule there holds unless this document
says otherwise; section references like "hosted tools §6" point into it. Phase-2 page reading is specified in
[`web-fetch.md`](web-fetch.md), which reuses these conventions and governs `web_fetch` wherever it is more
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 9d93de331..831a95e44 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -1165,6 +1165,22 @@ class ModelHubRuntimeRouter:
terminal_turn_id=terminal_turn_id,
)
+ def has_proxied_hosted_candidate(self, turn_id: Optional[str], tool: str) -> bool:
+ """Whether this Turn froze at least one enabled proxy executor for ``tool``.
+
+ The executor order is a Turn fact held by the gateway correlation, not a
+ mutable route flag. Native-search recovery consults this read-only view
+ before switching a hop; a tool with no proxy candidate keeps its existing
+ retry/failure behavior.
+ """
+
+ if self.turn_gateway is None:
+ return False
+ frozen = self.turn_gateway.correlation.turn_hosted_tools(turn_id)
+ if frozen is None:
+ return False
+ return any(slot.enabled for slot in frozen.executors.get(tool, ()))
+
def snapshot(self) -> ModelHubConfig:
"""Load the configuration one turn resolves and launches against.
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index f2921b6a2..f0b9e56e2 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -57,7 +57,7 @@ from core.agent_core.agent.events import (
)
from core.agent_core.agent.hooks import AgentInput
from core.agent_core.agent.loop import Agent
-from core.agent_core.agent.models import ModelSelection
+from core.agent_core.agent.models import ModelSelection, RetryPolicy
from core.agent_core.agent.recovery import settle_open_calls
from core.agent_core.harness.context import ContextConfig
from core.agent_core.harness.projection import open_tool_calls
@@ -106,6 +106,9 @@ from modules.agents.vibey.errors import error_text
from modules.agents.vibey.instructions import load_instruction_files, project_context
from modules.agents.vibey.media import MediaSnapshots
from modules.agents.vibey.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hop
+from modules.agents.vibey.native_search_recovery import (
+ SEARCH_TOOLS, interrupted_native_searches, response_recovery_metadata, should_switch, turn_recovery_facts,
+)
from modules.agents.vibey.prompt import EnvironmentValue, current_environment, system_prompt
from modules.agents.vibey.store import AdapterTranscriptStore
from modules.agents.vibey.tools import ToolSuite, hosted_tools, local_tool_suite
@@ -215,10 +218,10 @@ class _Run:
committed_display: Optional[str] = None
# Steer attempts ``Agent.steer`` accepted into this run: reconcile's in-process evidence.
accepted_steers: set[str] = field(default_factory=set)
- # Automatic transcript-only continuations already spent by this Turn. The
- # initial model call is not counted; the limit is five additional attempts.
+ # Automatic continuations in this failure episode. Success resets both fields;
+ # the initial call is not counted. One proxy reserve may spend the final slot
+ # beyond the normal cap, but never reopens the native window.
continuations: int = 0
- # One elapsed window from the first continuable failure, shared by every outer continuation.
continuation_started_at: Optional[float] = None
stop_requested: bool = False
stop_event: asyncio.Event = field(default_factory=asyncio.Event)
@@ -269,6 +272,7 @@ class VibeyAgent(BaseAgent):
self._engine,
environment=self._environment,
on_response=self._on_response,
+ response_metadata=self._response_metadata,
)
self._providers = providers or registry_providers(media_loader=self.media)
# The client of the Turn's other gateway calls (the hosted-tool executor); None opens one per call.
@@ -434,7 +438,9 @@ class VibeyAgent(BaseAgent):
resume_turn_inputs = None
async for event in stream:
await self._on_event(turn, event)
- if self._can_auto_continue(turn) and turn.continuations < _MAX_AUTO_CONTINUATIONS:
+ if self._can_auto_continue(turn) and (
+ turn.continuations < _MAX_AUTO_CONTINUATIONS or await self._native_search_switch_available(turn)
+ ):
if turn.continuation_started_at is None:
turn.continuation_started_at = time.monotonic()
# Finish T2 before asking the same Agent to build its next request.
@@ -556,10 +562,11 @@ class VibeyAgent(BaseAgent):
)
async def _wait_auto_continue(self, run: _Run) -> bool:
- """Honor the provider's delay floor and one elapsed budget, with Stop owning the wait.
+ """Honor Retry-After and one failure episode's budget, with Stop owning the wait.
- The initial run is not in this window. Subsequent runs and recovery work spend it, not just backoff.
- Expiry prevents another continuation, but never interrupts a run already doing useful work.
+ Success ends the episode. Consecutive failures spend one window, including
+ request duration and recovery work, not just backoff. Expiry never interrupts
+ a running request; a qualifying cut-off may spend one final proxy reserve.
"""
if run.stop_requested:
run.reason = "aborted"
@@ -571,7 +578,11 @@ class VibeyAgent(BaseAgent):
backoff = min(policy.max_delay_s, policy.initial_delay_s * 2**run.continuations)
delay = max(backoff, run.cause.retry_after_s or 0.0)
if elapsed + delay >= policy.max_elapsed_s:
- return False
+ # A streamed native request can itself consume the remaining window. Reserve one final
+ # proxy attempt rather than ending before the alternate path was tried; its normal delay
+ # (including Retry-After) still holds, and a proxy failure gets no renewed window.
+ if not await self._native_search_switch_available(run):
+ return False
try:
await asyncio.wait_for(run.stop_event.wait(), timeout=delay)
except asyncio.TimeoutError:
@@ -579,7 +590,13 @@ class VibeyAgent(BaseAgent):
if run.stop_requested:
run.reason = "aborted"
return False
- return time.monotonic() - run.continuation_started_at < policy.max_elapsed_s
+ if time.monotonic() - run.continuation_started_at >= policy.max_elapsed_s:
+ if not await self._native_search_switch_available(run):
+ return False
+ # Spend the episode's final reserve slot, even if time expired before
+ # the ordinary attempt cap. A second tool cannot obtain another reserve.
+ run.continuations = _MAX_AUTO_CONTINUATIONS
+ return True
def _accept_native_start(self, request: AgentRequest, session_id: str) -> None:
# The native start records the request this Turn runs with, which a restart rerun keeps.
@@ -835,10 +852,86 @@ class VibeyAgent(BaseAgent):
raise
bind_launch(context, launch)
# Every resolved hop, the first and each retry's, carries the output the Agent asks for on it.
- return budgeted(selection_from_hop(launch.to_hop_resolution()))
+ selection = budgeted(selection_from_hop(launch.to_hop_resolution()))
+ return await self._native_search_recovery_route(turn, selection)
return HubModelRouter(resolve, self._providers, first=await resolve())
+ async def _native_search_recovery_route(self, turn: _Run, selection: ModelSelection) -> ModelSelection:
+ """Derive a per-tool route from this Turn's immutable committed response facts."""
+ native = {
+ tool for tool, route in selection.endpoint.hosted_tools.items()
+ if tool in SEARCH_TOOLS and route.mode == "native"
+ }
+ runtime = getattr(self.controller, "model_hub_runtime", None)
+ candidate = getattr(runtime, "has_proxied_hosted_candidate", None)
+ if not native or not callable(candidate):
+ return selection
+ rows = await self.store.load_turn_response_metadata(turn.session_id, turn.turn_id)
+ counts, previously_proxied = turn_recovery_facts(rows)
+ # The current immutable hop also covers retries before a response commits
+ # (503/no output, pin re-resolution, overflow relief). Do not lose an early
+ # switch when the loop replaces its latest attempt with an uncommitted one.
+ current = getattr(turn.router, "current", None)
+ previously_proxied.update(
+ tool for tool, route in getattr(getattr(current, "endpoint", None), "hosted_tools", {}).items()
+ if route.mode == "proxy" and route.route_switch == "native_interrupted"
+ )
+ just_interrupted = interrupted_native_searches(getattr(turn.agent, "last_attempt_response", None))
+ last_retry = self._last_permitted_auto_retry(turn)
+ switched = {
+ tool for tool in native
+ if candidate(turn.turn_id, tool) and (
+ tool in previously_proxied
+ or should_switch(counts[tool], last_permitted_retry=last_retry and tool in just_interrupted)
+ )
+ }
+ return self._with_native_search_proxy_routes(selection, switched) if switched else selection
+
+ async def _native_search_switch_available(self, turn: _Run) -> bool:
+ """A reserve is for this just-failed native call, at most once per episode."""
+ if turn.continuations > _MAX_AUTO_CONTINUATIONS:
+ return False
+ just_interrupted = interrupted_native_searches(getattr(turn.agent, "last_attempt_response", None))
+ if not just_interrupted:
+ return False
+ runtime = getattr(self.controller, "model_hub_runtime", None)
+ candidate = getattr(runtime, "has_proxied_hosted_candidate", None)
+ current = getattr(getattr(turn, "router", None), "current", None)
+ routes = getattr(getattr(current, "endpoint", None), "hosted_tools", {})
+ return bool(callable(candidate) and any(
+ tool in routes and routes[tool].mode == "native" and candidate(turn.turn_id, tool)
+ for tool in just_interrupted
+ ))
+
+ @staticmethod
+ def _with_native_search_proxy_routes(selection: ModelSelection, switched: set[str]) -> ModelSelection:
+ hosted = {
+ tool: replace(
+ route,
+ mode="proxy",
+ replay=False,
+ declaration=None,
+ include=(),
+ route_switch="native_interrupted",
+ ) if tool in switched else route
+ for tool, route in selection.endpoint.hosted_tools.items()
+ }
+ return replace(selection, endpoint=replace(selection.endpoint, hosted_tools=hosted))
+
+ @staticmethod
+ def _last_permitted_auto_retry(turn: _Run) -> bool:
+ """Whether this continuation is the last retry the existing budget admits."""
+
+ if turn.continuation_started_at is None:
+ return False
+ policy = turn.agent.retry if turn.agent is not None else RetryPolicy()
+ if turn.continuations >= _MAX_AUTO_CONTINUATIONS:
+ return True
+ elapsed = time.monotonic() - turn.continuation_started_at
+ backoff = min(policy.max_delay_s, policy.initial_delay_s * 2**turn.continuations)
+ return elapsed + backoff >= policy.max_elapsed_s
+
def _start_agent(
self,
turn: _Run,
@@ -1793,7 +1886,12 @@ class VibeyAgent(BaseAgent):
raw = conn.execute(select(agent_events.c.content_json).where(agent_events.c.id == event_id)).scalar()
if not raw:
return None
- message = message_from_dict((json.loads(raw) or {}).get("message") or {})
+ payload = json.loads(raw) or {}
+ message = message_from_dict(payload.get("message") or {})
+ if isinstance(message, ToolResultMessage) and message.hosted is not None:
+ details = payload.get("details")
+ if isinstance(details, Mapping) and details.get("hosted_route_switch") == "native_interrupted":
+ message = replace(message, hosted=replace(message.hosted, route_switch="native_interrupted"))
return message if isinstance(message, ToolResultMessage) else None
async def _emit_tool_started(self, run: _Run, event: ToolStarted) -> None:
@@ -1818,6 +1916,15 @@ class VibeyAgent(BaseAgent):
except Exception:
logger.exception("Vibey could not show tool %s", name)
+ def _response_metadata(self, session_id: str, message: AssistantMessage) -> dict[str, Any]:
+ run = self._run_for(session_id, None)
+ current = getattr(getattr(run, "router", None), "current", None)
+ routes = getattr(getattr(current, "endpoint", None), "hosted_tools", {})
+ return response_recovery_metadata(message, (
+ tool for tool, route in routes.items()
+ if route.mode == "proxy" and route.route_switch == "native_interrupted"
+ ))
+
def _on_response(
self,
session_id: str,
@@ -1831,6 +1938,9 @@ class VibeyAgent(BaseAgent):
if run is None:
return
run.responses[row_id] = message
+ if message.stop_reason not in {"error", "aborted"}:
+ run.continuations = 0
+ run.continuation_started_at = None
if replied is not None:
run.replied[row_id] = replied
if images:
diff --git a/modules/agents/vibey/native_search_recovery.py b/modules/agents/vibey/native_search_recovery.py
new file mode 100644
index 000000000..20f2744bb
--- /dev/null
+++ b/modules/agents/vibey/native_search_recovery.py
@@ -0,0 +1,75 @@
+"""Turn-scoped, immutable response facts for interrupted native hosted searches.
+
+Neither the count nor a selected proxy route is capability/refusal evidence.
+Early switches below four survive a successful response's episode-budget reset
+because each committed response records the routes its request actually used.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from typing import Any, Iterable, Mapping, Optional
+
+from core.agent_core.ai.errors import classify_error
+from core.agent_core.messages import AssistantMessage, HostedToolBlock
+
+NATIVE_SEARCH_SWITCH_THRESHOLD = 4
+SEARCH_TOOLS = frozenset({"web_search", "x_search"})
+TRANSIENT_NATIVE_SEARCH_ERROR_KINDS = frozenset({
+ "overloaded", "server", "network", "stalled", "interrupted",
+})
+
+
+def _transient_error(message: AssistantMessage) -> bool:
+ if message.stop_reason != "error":
+ return False
+ if message.error_kind is not None:
+ return message.error_kind in TRANSIENT_NATIVE_SEARCH_ERROR_KINDS
+ if not message.error_message:
+ return False
+ classified = classify_error(body=message.error_message)
+ if classified.kind in TRANSIENT_NATIVE_SEARCH_ERROR_KINDS:
+ return True
+ lowered = message.error_message.lower()
+ return classified.kind == "unknown" and any(
+ phrase in lowered for phrase in ("stream disconnected", "stream ended", "connection reset")
+ )
+
+
+def interrupted_native_searches(message: Optional[AssistantMessage]) -> set[str]:
+ """One qualifying response counts at most once for each pending native tool."""
+ if not isinstance(message, AssistantMessage) or not _transient_error(message):
+ return set()
+ return {
+ block.tool for block in message.content
+ if isinstance(block, HostedToolBlock) and block.record.status == "pending" and block.tool in SEARCH_TOOLS
+ }
+
+
+def response_recovery_metadata(message: AssistantMessage, proxied: Iterable[str] = ()) -> dict[str, Any]:
+ """Small projection beside the response, outside the frozen canonical payload."""
+ return {"native_search_recovery": {
+ "error_kind": message.error_kind,
+ "interrupted": sorted(interrupted_native_searches(message)),
+ "proxied": sorted(SEARCH_TOOLS.intersection(proxied)),
+ }}
+
+
+def turn_recovery_facts(
+ rows: Iterable[tuple[Mapping[str, Any], Optional[AssistantMessage]]],
+) -> tuple[Counter[str], set[str]]:
+ """Read metadata-only new rows and original response bodies for older rows."""
+ counts: Counter[str] = Counter()
+ proxied: set[str] = set()
+ for metadata, legacy in rows:
+ facts = metadata.get("native_search_recovery")
+ if isinstance(facts, Mapping):
+ counts.update(SEARCH_TOOLS.intersection(facts.get("interrupted", ())))
+ proxied.update(SEARCH_TOOLS.intersection(facts.get("proxied", ())))
+ else:
+ counts.update(interrupted_native_searches(legacy))
+ return counts, proxied
+
+
+def should_switch(count: int, *, last_permitted_retry: bool = False) -> bool:
+ return count >= NATIVE_SEARCH_SWITCH_THRESHOLD or (count > 0 and last_permitted_retry)
diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.py
index eb3d07f6b..e03c54824 100644
--- a/modules/agents/vibey/store.py
+++ b/modules/agents/vibey/store.py
@@ -45,6 +45,7 @@ from storage.models import agent_sessions, messages
EnvironmentSource = Callable[[str], Mapping[str, EnvironmentValue]]
ResponseObserver = Callable[[str, str, AssistantMessage, Optional[bool], tuple[HostedImage, ...]], None]
+ResponseMetadata = Callable[[str, AssistantMessage], Mapping[str, Any]]
#: How long consumption waits for an accepted steer's row before failing the run.
INPUT_ROW_TIMEOUT_S = 10.0
@@ -62,12 +63,14 @@ class AdapterTranscriptStore:
*,
environment: EnvironmentSource,
on_response: ResponseObserver,
+ response_metadata: Optional[ResponseMetadata] = None,
input_row_timeout_s: float = INPUT_ROW_TIMEOUT_S,
) -> None:
self._store = store
self._engine = engine
self._environment = environment
self._on_response = on_response
+ self._response_metadata = response_metadata
self._input_row_timeout_s = input_row_timeout_s
# Per Session, the environment the projected context shows; evicted by ``forget`` when
# the adapter retires the Session's runtime, and when a checkpoint commits.
@@ -116,6 +119,12 @@ class AdapterTranscriptStore:
async def load_turn(self, session_id: str, turn_id: str) -> Sequence[ContextEntry]:
return await self._store.load_turn(session_id, turn_id)
+ async def load_turn_response_metadata(
+ self, session_id: str, turn_id: str
+ ) -> Sequence[tuple[Mapping[str, Any], Optional[AssistantMessage]]]:
+ """Small response facts; only legacy rows need their canonical body decoded."""
+ return await self._store.load_turn_response_metadata(session_id, turn_id)
+
async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:
await self._await_input_row(session_id, message_id)
previous = self._env_state.get(session_id)
@@ -153,6 +162,7 @@ class AdapterTranscriptStore:
replied=replied,
images=images,
superseded=superseded,
+ metadata=self._response_metadata(session_id, message) if self._response_metadata else None,
agent_name=self._agents.get(session_id),
turn_id=self._turns.get(session_id),
)
diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.py
index 36d27b79b..e717ef5f0 100644
--- a/modules/agents/vibey/tools.py
+++ b/modules/agents/vibey/tools.py
@@ -158,6 +158,8 @@ class HostedTool:
# The hop's own Source would run the tool but refused it, so this call is a fallback from it (C-6
# ``refused``): the card and the IM line say so.
hosted = replace(hosted, fallback_from=HostedFallback(endpoint.source_id))
+ elif route is not None and route.route_switch is not None:
+ hosted = replace(hosted, route_switch=route.route_switch)
query = arguments.get("query")
return _result(self.spec.name, hosted, query=query if isinstance(query, str) else None)
@@ -364,7 +366,8 @@ def _result(tool: str, hosted: HostedResult, *, query: Optional[str], notes: Seq
text = record_text(tool, hosted.record, query=query, notes=notes)
failed = hosted.record.status in ("failed", "incomplete")
- return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted)
+ details = {"hosted_route_switch": hosted.route_switch} if hosted.route_switch is not None else {}
+ return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted, details=details)
async def _gateway_call(
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 4d0c80f97..186ff5d3c 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -234,6 +234,39 @@ class SQLiteTranscriptStore:
"""Load one durable Turn's own context, excluding older history and fork ancestry."""
return await asyncio.to_thread(self._load, session_id, turn_id=turn_id)
+ async def load_turn_response_metadata(
+ self, session_id: str, turn_id: str
+ ) -> Sequence[tuple[Mapping[str, Any], Optional[AssistantMessage]]]:
+ """Read response recovery facts through the Turn index, never tool outputs.
+
+ Newly written rows need only their small metadata. Older rows have no
+ recovery projection, so decode their original immutable response instead.
+ """
+ def work() -> list[tuple[Mapping[str, Any], Optional[AssistantMessage]]]:
+ query = text(
+ "SELECT id, metadata_json, "
+ "CASE WHEN json_type(metadata_json, '$.native_search_recovery') IS NULL "
+ "THEN content_json END AS legacy_content "
+ "FROM messages INDEXED BY ix_messages_turn_id "
+ f"WHERE session_id = :session_id AND ({MESSAGE_TURN_ID_SQL}) = :turn_id "
+ "AND context_seq IS NOT NULL AND type IN :response_types ORDER BY context_seq"
+ ).bindparams(bindparam("response_types", expanding=True))
+ result = []
+ with self._engine.connect() as conn:
+ rows = conn.execute(query, {
+ "session_id": session_id, "turn_id": turn_id, "response_types": RESPONSE_TYPES,
+ }).mappings()
+ for row in rows:
+ metadata = _json_object(row["metadata_json"], row["id"])
+ message = None
+ if row["legacy_content"] is not None:
+ model = _versioned(_json_object(row["legacy_content"], row["id"]).get("model"), row["id"])
+ message = _message(model.get("message"), AssistantMessage, row["id"])
+ result.append((metadata, message))
+ return result
+
+ return await asyncio.to_thread(work)
+
async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:
if not isinstance(message, UserMessage):
raise TypeError("consume_input takes a UserMessage")
@@ -283,6 +316,7 @@ class SQLiteTranscriptStore:
replied: Optional[bool] = None,
images: Sequence[HostedImage] = (),
superseded: bool = False,
+ metadata: Optional[Mapping[str, Any]] = None,
agent_name: Optional[str] = None,
turn_id: Optional[str] = None,
) -> ContextEntry:
@@ -299,6 +333,9 @@ class SQLiteTranscriptStore:
def work(conn: Connection) -> ContextEntry:
origin = _turn_origin(conn, session_id, agent_name, turn_id)
seq = _next_context_seq(conn, session_id)
+ row_metadata = dict(metadata or {})
+ if origin.turn_id:
+ row_metadata["turn_id"] = origin.turn_id
row = messages_service.append(
conn,
scope_id=origin.scope_id,
@@ -312,7 +349,7 @@ class SQLiteTranscriptStore:
),
text=display_text,
content={"model": model},
- metadata={"turn_id": origin.turn_id} if origin.turn_id else None,
+ metadata=row_metadata or None,
)
conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
_register_images(conn, origin.scope_id, session_id, message)
diff --git a/tests/agent_core/ai/test_hosted_replay.py b/tests/agent_core/ai/test_hosted_replay.py
index b8fc78017..f70f83d23 100644
--- a/tests/agent_core/ai/test_hosted_replay.py
+++ b/tests/agent_core/ai/test_hosted_replay.py
@@ -222,6 +222,71 @@ async def test_a_continuation_of_a_model_whose_id_is_no_header_value_is_pinned_t
httpx.Request("POST", wire.url, headers=wire.headers, json=wire.body)
[email protected]("protocol", ["openai_responses", "anthropic"])
+async def test_transient_switch_preserves_completed_native_history_as_portable_content(protocol):
+ from modules.agents.vibey.agent import VibeyAgent
+
+ selection = ModelSelection(_endpoint(protocol, replay=True), ModelCapabilities())
+ switched = VibeyAgent._with_native_search_proxy_routes(selection, {"web_search"})
+ request = _request(switched.endpoint, _searched(protocol))
+ wire = await build_wire_request(request, gateway=True)
+
+ assert not _verbatim(protocol, wire.body)
+ assert PIN_SOURCE_HEADER not in wire.headers
+ assert "https://avibe.bot/r" in json.dumps(wire.body)
+ declaration, = wire.body["tools"]
+ assert declaration["name"] == "web_search"
+ assert declaration.get("type") != "web_search"
+ assert not switched.endpoint.hosted_tools["web_search"].refused
+
+ # Both real adapters parse a continuation on this request without a server-tool declaration.
+ def gateway(incoming):
+ body = json.loads(incoming.content)
+ assert not _verbatim(protocol, body)
+ return httpx.Response(200, headers={"content-type": "text/event-stream"},
+ text="".join("data: " + json.dumps(event) + "\n\n" for event in _ANSWERED[protocol]))
+
+ from core.agent_core.ai.provider import Done
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ events = [event async for event in create_adapter(protocol, client=client, gateway=True).stream(request, CancelToken())]
+ assert isinstance(events[-1], Done)
+
+
[email protected]("protocol", ["openai_responses", "anthropic"])
+async def test_pending_native_cutoff_retains_upstream_class_without_new_wire_fields(protocol):
+ from core.agent_core.messages import message_to_dict
+
+ if protocol == "openai_responses":
+ prefix = [
+ {"type": "response.created", "response": {"status": "in_progress"}},
+ {"type": "response.output_item.added", "output_index": 0,
+ "item": {"id": "ws_1", "type": "web_search_call", "status": "in_progress"}},
+ ]
+ error = {"type": "response.failed", "response": {"status": "failed", "error": {
+ "type": "server_error", "message": "Our servers are currently overloaded"}}}
+ else:
+ prefix = [
+ {"type": "message_start", "message": {"usage": {"input_tokens": 1}}},
+ {"type": "content_block_start", "index": 0, "content_block": USE},
+ ]
+ error = {"type": "error", "error": {"type": "overloaded_error", "message": "upstream busy"}}
+ body = "".join("data: " + json.dumps(event) + "\n\n" for event in [*prefix, error])
+ headers = {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps({
+ "provider": MODELS[protocol][0], "api": protocol, "model": MODELS[protocol][1], "source": SOURCE,
+ })}
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body, headers=headers))) as client:
+ events = [event async for event in create_adapter(protocol, client=client, gateway=True).stream(
+ _request(_endpoint(protocol, replay=True)), CancelToken()
+ )]
+ terminal = events[-1]
+ assert isinstance(terminal, ProviderError)
+ assert terminal.partial is not None
+ assert terminal.partial.error_kind == terminal.kind
+ assert terminal.kind in {"overloaded", "server"}
+ assert any(isinstance(block, HostedToolBlock) and block.record.status == "pending" for block in terminal.partial.content)
+ assert "error_kind" not in message_to_dict(terminal.partial)
+
+
_PIN_UNAVAILABLE = {"type": "error", "error": {"type": "model_hub_pin_unavailable", "code": "pin_unavailable"}}
_ANSWERED = {
"openai_responses": (
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index dbdb39c99..18749280e 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -19,8 +19,15 @@ from sqlalchemy import select
from core.agent_core.messages import (
AssistantMessage,
+ HostedAction,
+ HostedNative,
+ HostedRecord,
+ HostedResult,
+ HostedSummary,
+ HostedToolBlock,
ImageBlock,
Origin,
+ ProxyExecution,
TextBlock,
ThinkingBlock,
ToolCallBlock,
@@ -259,6 +266,48 @@ async def test_every_kind_round_trips_in_one_order_attributed_to_the_turn(engine
]
[email protected]("legacy", [False, True])
+async def test_recovery_facts_survive_without_changing_message_contract(engine, legacy) -> None:
+ with engine.begin() as conn:
+ home = _scope(conn, "C-native-recovery")
+ _session(conn, "ses_native_recovery", home)
+ first = _accepted_turn(conn, "ses_native_recovery", home, "search", "turn_native_recovery")
+ block = HostedToolBlock(
+ id="ws_recovery",
+ tool="web_search",
+ action=HostedAction(type="search", queries=("Avibe",)),
+ record=HostedRecord(status="pending"),
+ native=HostedNative("src_recovery1", ({"type": "web_search_call", "id": "ws_recovery"},)),
+ )
+ message = AssistantMessage(
+ content=(block,),
+ origin=ORIGIN,
+ stop_reason="error",
+ error_message="Our servers are currently overloaded",
+ hosted_summary=HostedSummary(),
+ error_kind="overloaded",
+ )
+ store = SQLiteTranscriptStore(engine)
+ await store.consume_input("ses_native_recovery", first, _user("search"))
+ metadata = None if legacy else {"native_search_recovery": {
+ "error_kind": "overloaded", "interrupted": ["web_search"], "proxied": [],
+ }}
+ written = await store.append_response("ses_native_recovery", message, final=False, metadata=metadata)
+ facts = await store.load_turn_response_metadata("ses_native_recovery", "turn_native_recovery")
+ assert len(facts) == 1
+ recorded, original = facts[0]
+ if legacy:
+ assert original == message
+ else:
+ assert original is None # no canonical body needed for new rows
+ assert recorded["native_search_recovery"] == metadata["native_search_recovery"]
+ with 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 "error_kind" not in model
+ assert "native_search_recovery" not in model
+
+
async def test_a_stored_unknown_native_hosted_row_loads_through_the_transcript_owner(engine):
with engine.begin() as conn:
home = _scope(conn, "C-hosted-history")
diff --git a/tests/test_hosted_activity.py b/tests/test_hosted_activity.py
index 2d67a30e0..816ba5d5b 100644
--- a/tests/test_hosted_activity.py
+++ b/tests/test_hosted_activity.py
@@ -206,6 +206,22 @@ def proxy_fallback():
)
+def test_repeated_native_interruptions_are_explained_on_the_proxy_card_and_line():
+ activity = proxy_activity(
+ ToolCallBlock(id="call_switch", name="web_search", arguments={"query": "Avibe release"}),
+ HostedResult(
+ record=HostedRecord(status="completed", sources=POSTS[:1]),
+ execution=XAI,
+ route_switch="native_interrupted",
+ ),
+ source_names=NAMES,
+ )
+
+ assert activity.to_payload()["route_switch"] == "native_interrupted"
+ assert "Native search was interrupted; switched to xAI." in hosted_line(activity, "en")
+ assert "自带搜索中断,已改用 xAI。" in hosted_line(activity, "zh")
+
+
@pytest.mark.parametrize(
"build",
[native_web_search, proxy_x_search, direct_image, proxy_failed, proxy_unreachable, proxy_retried, proxy_fallback],
diff --git a/tests/test_native_search_recovery.py b/tests/test_native_search_recovery.py
new file mode 100644
index 000000000..7b5dc1b36
--- /dev/null
+++ b/tests/test_native_search_recovery.py
@@ -0,0 +1,313 @@
+"""Transient native search cut-offs change one Turn's route, never capability evidence."""
+import json
+from dataclasses import replace
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import httpx
+import pytest
+
+from core.agent_core.agent.models import ModelSelection, RetryPolicy
+from core.agent_core.ai.provider import Done, HostedToolRoute, ModelCapabilities, ModelEndpoint, ProviderError
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.messages import (
+ AssistantMessage, HostedAction, HostedNative, HostedRecord, HostedSummary,
+ HostedToolBlock, Origin, ToolCallBlock,
+)
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from modules.agents.vibey.agent import VibeyAgent, _Run
+from modules.agents.vibey.native_search_recovery import should_switch, turn_recovery_facts
+from tests.agent_core.fakes import assistant
+from tests.test_vibey_agent import ( # noqa: F401 -- shared real-store/Delivery harness and fixtures
+ SESSION, _Harness, _NATIVE_SEARCH, continuation_policy, engine, published, session,
+)
+
+
+def _response(*, tool="web_search", error_kind="overloaded", pending=True, stop_reason="error", index=0):
+ action = HostedAction("search", queries=("q",)) if tool == "web_search" else HostedAction("x_search", variant="keyword", query="q")
+ block = HostedToolBlock(
+ f"native-{index}", tool, action, HostedRecord("pending" if pending else "completed"),
+ HostedNative("src_served00001", ({"type": "web_search_call"},)),
+ )
+ return AssistantMessage(
+ (block,), Origin("openai", "openai_responses", "model"), stop_reason,
+ error_message="Our servers are currently overloaded", hosted_summary=HostedSummary(), error_kind=error_kind,
+ )
+
+
+def _entry(message, seq=1):
+ return ContextEntry("session", seq, "response", f"row-{seq}", message=message)
+
+
+def _interruptions(entries):
+ return turn_recovery_facts(({}, entry.message) for entry in entries)[0]
+
+
+def test_counts_responses_not_calls_and_only_pending_native_calls_of_each_tool():
+ repeated = _response()
+ entries = [
+ _entry(replace(repeated, content=(*repeated.content, replace(repeated.content[0], id="other")))),
+ _entry(_response(tool="x_search"), 2),
+ _entry(_response(error_kind="invalid_request"), 3),
+ _entry(_response(pending=False), 4),
+ _entry(_response(stop_reason="stop"), 5),
+ ]
+ assert _interruptions(entries) == {"web_search": 1, "x_search": 1}
+
+
[email protected]("kind", ["overloaded", "server", "network", "stalled", "interrupted"])
+def test_counts_transient_class_even_when_error_text_names_no_class(kind):
+ message = replace(_response(error_kind=kind), error_message="upstream failed")
+ assert _interruptions([_entry(message)]) == {"web_search": 1}
+
+
[email protected]("kind", ["auth", "invalid_request", "rate_limit", "unknown", "aborted", "overflow"])
+def test_nontransient_class_wins_over_provider_wording(kind):
+ assert not _interruptions([_entry(_response(error_kind=kind))])
+
+
+def test_released_explicit_overload_rows_still_count_but_ambiguous_errors_do_not():
+ assert _interruptions([_entry(_response(error_kind=None))]) == {"web_search": 1}
+ assert not _interruptions([_entry(replace(_response(error_kind=None), error_message="failed"))])
+
+
+def test_switch_threshold_and_last_retry_override():
+ assert [should_switch(count) for count in range(1, 5)] == [False, False, False, True]
+ assert all(should_switch(count, last_permitted_retry=True) for count in range(1, 5))
+ assert not should_switch(0, last_permitted_retry=True)
+
+
+def _selection():
+ return ModelSelection(ModelEndpoint(
+ "openai_responses", "http://hub.invalid", "model", "test-token", provider="openai",
+ hosted_tools={tool: HostedToolRoute("native", True, {"type": tool}) for tool in ("web_search", "x_search")},
+ ), ModelCapabilities())
+
+
[email protected]("count", [1, 2, 3, 4, 5])
[email protected]("tool", ["web_search", "x_search"])
+async def test_hop_resolution_is_tool_and_turn_scoped_without_refusal_writes(count, tool):
+ selection = _selection()
+ store = SimpleNamespace(load_turn_response_metadata=AsyncMock(side_effect=lambda sid, tid: (
+ [({}, _response(tool=tool)) for _ in range(count)] if tid == "old" else []
+ )))
+ agent = object.__new__(VibeyAgent)
+ agent.store = store
+ candidate = Mock(return_value=True)
+ agent.controller = SimpleNamespace(model_hub_runtime=SimpleNamespace(has_proxied_hosted_candidate=candidate))
+ turn = _Run(None, "session", "old", "test")
+ resolved = await agent._native_search_recovery_route(turn, selection)
+ assert resolved.endpoint.hosted_tools[tool].mode == ("proxy" if count >= 4 else "native")
+ assert resolved.endpoint.hosted_tools["x_search" if tool == "web_search" else "web_search"].mode == "native"
+ assert not any(route.refused for route in resolved.endpoint.hosted_tools.values())
+ assert all(route.mode == "native" for route in selection.endpoint.hosted_tools.values())
+ turn.turn_id = "new"
+ assert await agent._native_search_recovery_route(turn, selection) is selection
+
+
[email protected]("available", [False, True])
+async def test_last_permitted_hop_switches_only_with_a_frozen_proxy_candidate(available):
+ agent = object.__new__(VibeyAgent)
+ agent.store = SimpleNamespace(load_turn_response_metadata=AsyncMock(return_value=[({}, _response())]))
+ agent.controller = SimpleNamespace(model_hub_runtime=SimpleNamespace(has_proxied_hosted_candidate=lambda *_: available))
+ turn = _Run(None, "session", "turn", "test", continuations=5, continuation_started_at=0,
+ agent=SimpleNamespace(last_attempt_response=_response(), retry=RetryPolicy()))
+ route = (await agent._native_search_recovery_route(turn, _selection())).endpoint.hosted_tools["web_search"]
+ assert route.mode == ("proxy" if available else "native")
+ assert route.refused is False
+
+
[email protected]("enabled", [False, True])
+def test_proxy_candidate_read_uses_the_turns_frozen_enabled_executor_list(enabled):
+ runtime = object.__new__(ModelHubRuntimeRouter)
+ frozen = SimpleNamespace(executors={"web_search": (SimpleNamespace(enabled=enabled),)})
+ runtime.turn_gateway = SimpleNamespace(correlation=SimpleNamespace(turn_hosted_tools=lambda _: frozen))
+ assert runtime.has_proxied_hosted_candidate("turn", "web_search") is enabled
+ assert not runtime.has_proxied_hosted_candidate("turn", "x_search")
+
+
[email protected]("platform,language", [("avibe", "en"), ("telegram", "zh")])
[email protected]("budget,failures", [("normal", 4), ("elapsed", 3), ("long-call", 2), ("cap", 1)])
+async def test_actual_continuations_switch_keep_proxy_for_later_hops_and_reset_next_turn(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, budget, failures, platform, language,
+):
+ """Real loop, persisted response metadata, fresh hops, gateway function and committed card/IM line."""
+ continuation_policy(initial_delay_s=0)
+ clock = [0.0]
+ monkeypatch.setattr("modules.agents.vibey.agent.time", SimpleNamespace(monotonic=lambda: clock[0]))
+ if budget == "cap":
+ monkeypatch.setattr("modules.agents.vibey.agent._MAX_AUTO_CONTINUATIONS", 1)
+ scripts = []
+ for index in range(failures):
+ async def fail(request, cancel, index=index):
+ clock[0] += 67 if budget == "elapsed" else (121 if budget == "long-call" else 0)
+ yield ProviderError("overloaded", "Our servers are currently overloaded", False,
+ partial=_response(index=index), continuable=True)
+ scripts.append(fail)
+ scripts += [
+ [Done(assistant(calls=(ToolCallBlock("proxy-call", "web_search", {"query": "q"}),)))],
+ [Done(assistant("recovered"))], [Done(assistant("next turn"))],
+ ]
+ answer = {"record": {"status": "completed", "sources": []}, "execution": {
+ "mode": "proxy", "executor_origin": {"provider": "exa", "api": "search_api", "model": "exa-search"},
+ "executor_source_id": "src_exakeyless", "executor_billing": "metered",
+ }}
+ proxy_requests = []
+
+ def gateway(request):
+ proxy_requests.append(request)
+ return httpx.Response(200, json=answer)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(engine, tmp_path, platform, scripts, language=language, gateway_client=client)
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: True
+ request = harness.request("search")
+ await harness.agent.handle_message(request)
+ assert not harness.controller.terminals[-1]["is_error"]
+ restarted = harness.new_agent()
+ resumed = _Run(None, SESSION, request.context.platform_specific["turn_token"], "restart")
+ # A restarted adapter has no live episode budget. It reads only response
+ # metadata, not canonical bodies or tool results, to retain an early switch.
+ with monkeypatch.context() as patch:
+ patch.setattr("storage.agent_transcript._message", Mock(side_effect=AssertionError("body decoded")))
+ recovered = await restarted._native_search_recovery_route(resumed, _selection())
+ assert recovered.endpoint.hosted_tools["web_search"].mode == "proxy"
+ await restarted.handle_message(harness.request("next"))
+
+ routes = [request.endpoint.hosted_tools["web_search"] for request in harness.provider.requests]
+ assert [route.mode for route in routes] == ["native"] * failures + ["proxy", "proxy", "native"]
+ assert not any(route.refused for route in routes)
+ assert len(proxy_requests) == 1
+ assert proxy_requests[0].url.path.endswith("/hosted-tools/web_search")
+ assert all(entry.kind != "replay_refusal" for entry in await harness.context_rows())
+ from sqlalchemy import select
+ from storage.models import agent_events
+ with engine.connect() as conn:
+ events = list(conn.execute(
+ select(agent_events.c.content_json, agent_events.c.content_text).where(agent_events.c.event_type == "tool_call")
+ ))
+ cards = [json.loads(row.content_json)["hosted"] for row in events]
+ proxy = next(card for card in cards if card["mode"] == "proxy")
+ assert proxy["status"] == "completed"
+ assert proxy["route_switch"] == "native_interrupted" and "fallback_from" not in proxy
+ expected = ("Native search was interrupted; switched to Exa (free)." if language == "en"
+ else "自带搜索中断,已改用 Exa(免费)。")
+ assert any(expected in row.content_text for row in events)
+
+
[email protected]("proxy_available", [False, True])
+async def test_exhausted_budget_does_not_reopen_after_a_proxy_failure(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, proxy_available,
+):
+ continuation_policy(initial_delay_s=0)
+ monkeypatch.setattr("modules.agents.vibey.agent._MAX_AUTO_CONTINUATIONS", 1)
+ native = ProviderError("overloaded", "overloaded", False, partial=_response(), continuable=True)
+ generic = ProviderError("server", "failed again", False, continuable=True)
+ harness = _Harness(engine, tmp_path, "avibe", [[native], [generic]])
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: proxy_available
+ await harness.agent.handle_message(harness.request("search"))
+ assert len(harness.provider.requests) == 2
+ assert harness.controller.terminals[-1]["is_error"]
+
+
[email protected]("native", [False, True])
+async def test_success_ends_failure_episode_before_a_later_overload(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, native,
+):
+ continuation_policy(initial_delay_s=0)
+ monkeypatch.setattr("modules.agents.vibey.agent._MAX_AUTO_CONTINUATIONS", 2)
+ clock = [0.0]
+ monkeypatch.setattr("modules.agents.vibey.agent.time", SimpleNamespace(monotonic=lambda: clock[0]))
+ first = ProviderError("overloaded", "overloaded", False,
+ partial=_response() if native else None, continuable=True)
+
+ async def later(request, cancel):
+ clock[0] += 130
+ yield ProviderError("overloaded", "overloaded", False,
+ partial=_response(index=2) if native else None, continuable=True)
+
+ harness = _Harness(engine, tmp_path, "avibe", [
+ [first], [Done(assistant(calls=(ToolCallBlock("echo-1", "echo", {}),)))],
+ later, [Done(assistant("recovered"))],
+ ])
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: True
+ await harness.agent.handle_message(harness.request("work"))
+ assert not harness.controller.terminals[-1]["is_error"]
+ assert [r.endpoint.hosted_tools["web_search"].mode for r in harness.provider.requests] == ["native"] * 4
+
+
[email protected]("partial", [False, True])
+async def test_an_unrelated_latest_failure_gets_no_search_reserve(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, partial,
+):
+ continuation_policy(initial_delay_s=0)
+ clock = [0.0]
+ monkeypatch.setattr("modules.agents.vibey.agent.time", SimpleNamespace(monotonic=lambda: clock[0]))
+
+ async def unrelated(request, cancel):
+ clock[0] += 130
+ yield ProviderError("server", "server error", False, continuable=True,
+ partial=replace(assistant("partial"), stop_reason="error", error_kind="server") if partial else None)
+
+ harness = _Harness(engine, tmp_path, "avibe", [
+ [ProviderError("overloaded", "overloaded", False, partial=_response(), continuable=True)], unrelated,
+ ])
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: True
+ await harness.agent.handle_message(harness.request("work"))
+ assert harness.controller.terminals[-1]["is_error"]
+ assert len(harness.provider.requests) == 2
+ assert all(r.endpoint.hosted_tools["web_search"].mode == "native" for r in harness.provider.requests)
+
+
[email protected]("budget", ["cap", "elapsed"])
+async def test_only_one_reserve_per_episode_even_if_a_different_native_tool_then_fails(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, budget,
+):
+ continuation_policy(initial_delay_s=0)
+ if budget == "cap":
+ monkeypatch.setattr("modules.agents.vibey.agent._MAX_AUTO_CONTINUATIONS", 1)
+ clock = [0.0]
+ monkeypatch.setattr("modules.agents.vibey.agent.time", SimpleNamespace(monotonic=lambda: clock[0]))
+
+ async def native_failure(request, cancel):
+ clock[0] += 130 if budget == "elapsed" else 0
+ yield ProviderError("overloaded", "overloaded", False, partial=_response(), continuable=True)
+
+ harness = _Harness(engine, tmp_path, "avibe", [
+ [ProviderError("server", "server error", False, continuable=True)], native_failure,
+ [ProviderError("overloaded", "overloaded", False, partial=_response(tool="x_search"), continuable=True)],
+ ])
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH, "x_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: True
+ await harness.agent.handle_message(harness.request("work"))
+ assert harness.controller.terminals[-1]["is_error"]
+ assert len(harness.provider.requests) == 3
+ assert [r.endpoint.hosted_tools["web_search"].mode for r in harness.provider.requests] == ["native", "native", "proxy"]
+ assert all(r.endpoint.hosted_tools["x_search"].mode == "native" for r in harness.provider.requests)
+
+
[email protected]("reserve", [False, True])
+async def test_in_place_retry_cannot_restore_native_after_an_early_switch(
+ engine, session, tmp_path, published, continuation_policy, monkeypatch, reserve,
+):
+ continuation_policy(initial_delay_s=0)
+ monkeypatch.setattr("modules.agents.vibey.agent._MAX_AUTO_CONTINUATIONS", 1)
+ native = ProviderError("overloaded", "overloaded", False, partial=_response(), continuable=True)
+ scripts = [[ProviderError("server", "server error", False, continuable=True)]] if reserve else []
+ scripts += [
+ [native], [ProviderError("server", "503 before output", True)],
+ [Done(assistant(calls=(ToolCallBlock("echo-after-retry", "echo", {}),)))],
+ [Done(assistant("recovered"))],
+ ]
+ harness = _Harness(engine, tmp_path, "avibe", scripts)
+ harness.controller.hub_hosted_tools = {"web_search": _NATIVE_SEARCH}
+ harness.controller.model_hub_runtime.has_proxied_hosted_candidate = lambda *_: True
+ await harness.agent.handle_message(harness.request("work"))
+ assert not harness.controller.terminals[-1]["is_error"]
+ assert [r.endpoint.hosted_tools["web_search"].mode for r in harness.provider.requests] == (
+ ["native"] * (2 if reserve else 1) + ["proxy"] * 3
+ )
diff --git a/ui/src/components/workbench/HostedToolRow.test.tsx b/ui/src/components/workbench/HostedToolRow.test.tsx
index 3591c92f3..dde3f6d86 100644
--- a/ui/src/components/workbench/HostedToolRow.test.tsx
+++ b/ui/src/components/workbench/HostedToolRow.test.tsx
@@ -53,6 +53,22 @@ const row = (callId: string) => document.querySelector(`[data-hosted-call="${cal
afterEach(() => cleanup());
describe('hosted tool cards', () => {
+ it.each(['en', 'zh'] as const)('explains the transient native-to-Exa switch without a refusal in %s', (lng) => {
+ const payload = {
+ ...fixture.proxy_x_search, tool: 'web_search', call_id: 'switched-search',
+ source_id: 'src_exakeyless', provider: 'exa', source_name: 'Exa', executor_kind: 'service',
+ model: undefined, route_switch: 'native_interrupted',
+ };
+ for (const record of [payload, JSON.parse(JSON.stringify(payload))]) {
+ renderGroup([record], lng);
+ const card = row('switched-search');
+ within(card).getByText(lng === 'en'
+ ? 'Native search was interrupted; switched to Exa (free).'
+ : '自带搜索中断,已改用 Exa(免费)。');
+ expect(card.textContent).not.toMatch(/doesn't support|不支持/);
+ cleanup();
+ }
+ });
it.each(['en', 'zh'] as const)('explains interrupted responses without inventing a subject in %s, live and reloaded', (lng) => {
for (const [interruption, reason] of [
['overloaded', lng === 'en' ? 'upstream overloaded' : '上游服务过载'],
diff --git a/ui/src/components/workbench/HostedToolRow.tsx b/ui/src/components/workbench/HostedToolRow.tsx
index 1c9ff989d..2e3bd20d6 100644
--- a/ui/src/components/workbench/HostedToolRow.tsx
+++ b/ui/src/components/workbench/HostedToolRow.tsx
@@ -429,6 +429,12 @@ export const HostedToolRow: React.FC<{ card: HostedActivity }> = ({ card }) => {
{card.retried && <span>{t('chat.agentActivity.hosted.interruption.retriedLabel')}</span>}
</p>
)}
+ {hostedCompleted(card) && card.route_switch === 'native_interrupted' && runnerLabel(card, t) && (
+ <p className="mx-1.5 mb-1 mt-0.5 flex items-center gap-1.5 rounded-md border border-gold/40 bg-gold/10 px-2.5 py-1.5 text-[11px] text-foreground" data-hosted-route-switch={card.call_id}>
+ <TriangleAlert className="size-3 shrink-0 text-gold-ink" aria-hidden="true" />
+ {t('chat.agentActivity.hosted.nativeInterrupted', { provider: runnerLabel(card, t) })}
+ </p>
+ )}
<HostedAttemptNotes card={card} />
<FallbackNote card={card} />
{open && <HostedDetail card={card} />}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d1fc006f7..b5fa29eda 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5390,6 +5390,7 @@
"listSeparator": ", ",
"itemSeparator": "; ",
"switch": "{{failed}}; switched to {{provider}}",
+ "nativeInterrupted": "Native search was interrupted; switched to {{provider}}.",
"interruption": {
"message": "Model response interrupted: {{reason}}",
"overloaded": "upstream overloaded",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 24278cd75..678d6ed00 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5390,6 +5390,7 @@
"listSeparator": "、",
"itemSeparator": ";",
"switch": "{{failed}},已改用 {{provider}}",
+ "nativeInterrupted": "自带搜索中断,已改用 {{provider}}。",
"interruption": {
"message": "模型回复中断:{{reason}}",
"overloaded": "上游服务过载",
diff --git a/ui/src/lib/hostedActivity.ts b/ui/src/lib/hostedActivity.ts
index 498f977e7..39765a0d0 100644
--- a/ui/src/lib/hostedActivity.ts
+++ b/ui/src/lib/hostedActivity.ts
@@ -103,6 +103,8 @@ export type HostedActivity = {
duration_ms?: number;
/** The Source that refused to run this search natively, so it ran by proxy instead; absent otherwise. */
fallback_from?: { source_id: string; source_name?: string };
+ /** Why this proxy route was chosen for the current Turn, not a refusal or capability fact. */
+ route_switch?: 'native_interrupted';
/** Every candidate a search chain reached; absent for a record that has none, as a model-only chain's. */
attempts?: HostedActivityAttempt[];
policy_sources?: string[];
@@ -169,6 +171,7 @@ export const hostedActivityFrom = (raw: unknown): HostedActivity | undefined =>
subject: nativeSubject(card),
interruption: card.mode === 'native' && card.status === 'pending' && ['overloaded', 'disconnected', 'upstream'].includes(card.interruption as string)
? card.interruption as HostedActivity['interruption'] : undefined,
+ route_switch: card.route_switch === 'native_interrupted' ? ('native_interrupted' as const) : undefined,
retried: card.retried === true,
sources: Array.isArray(card.sources) ? (card.sources as HostedActivitySource[]).filter((s) => typeof s?.url === 'string' || typeof s?.title === 'string') : [],
images: Array.isArray(card.images) ? (card.images as HostedActivityImage[]).filter((i) => typeof i?.path === 'string') : [],
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 56440418f..7e72f12f1 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1697,6 +1697,7 @@
"proxy": "via {provider} proxy",
"proxyModel": "via {provider} proxy ({model})",
"fallback": "{source} doesn't support it, now using {provider}",
+ "nativeInterrupted": "Native search was interrupted; switched to {provider}.",
"direct": "direct ({provider})"
},
"count": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 7dae1fbee..2a79be6e6 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1697,6 +1697,7 @@
"proxy": "由 {provider} 代理",
"proxyModel": "由 {provider} 代理({model})",
"fallback": "{source} 不支持,已改用 {provider}",
+ "nativeInterrupted": "自带搜索中断,已改用 {provider}。",
"direct": "{provider} 直连"
},
"count": {