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.

feat(vibey): Gemini runs Google Search as its native web_search (#3038)

Call Whited13fd4cd5350
diff --git a/core/agent_core/ai/google.py b/core/agent_core/ai/google.py
index 1dbb2355a..9ed9dff17 100644
--- a/core/agent_core/ai/google.py
+++ b/core/agent_core/ai/google.py
@@ -7,14 +7,22 @@ assembler; ``agent-core-contracts/conversion-tables.md`` ("Google Gemini") is th
from __future__ import annotations
+import copy
import json
import re
from collections.abc import AsyncIterator, Mapping
+from dataclasses import replace
from typing import Any
from urllib.parse import quote
import httpx
+from core.agent_core.ai.hosted import (
+ GOOGLE_SEARCH_TOOL_TYPE,
+ google_grounding_sources,
+ google_hosted_block,
+ google_search_count,
+)
from core.agent_core.ai.image_limits import LoadedImage
from core.agent_core.ai._common import (
PinUnavailable,
@@ -29,6 +37,7 @@ from core.agent_core.ai._common import (
hosted_pin,
join_endpoint_url,
json_object,
+ native_hosted_tools,
pin_refusal,
prepare_messages,
request_credential_values,
@@ -39,6 +48,7 @@ from core.agent_core.ai.provider import Done, MediaLoader, ModelRequest, Provide
from core.agent_core.cancel import CancelToken
from core.agent_core.messages import (
AssistantMessage,
+ HostedToolBlock,
ImageBlock,
TextBlock,
ThinkingBlock,
@@ -47,6 +57,9 @@ from core.agent_core.messages import (
UserMessage,
)
+#: The generateContent tool each overlay declaration type names (``vibey-gemini-native.md`` §4): the overlay spells
+#: Google Search as Google's typed tools do, and this API takes it as a keyed tool object.
+_NATIVE_TOOLS = {"google_search": {"googleSearch": {}}}
#: Google's documented stand-in for the signature of a function call Gemini did not produce ("Thought signatures",
#: FAQ 1): another origin's call in the current turn, which Gemini 3 and later validate.
DUMMY_THOUGHT_SIGNATURE = "skip_thought_signature_validator"
@@ -79,6 +92,10 @@ _GOOGLE_PART_FIELDS = (
Mapping,
children=(WireField("name", str), WireField("id", str), WireField("args", Mapping)),
),
+ WireField("toolCall", Mapping, children=(WireField("toolType", str), WireField("id", str), WireField("args", Mapping))),
+ WireField(
+ "toolResponse", Mapping, children=(WireField("toolType", str), WireField("id", str), WireField("response", Mapping)),
+ ),
)
_GOOGLE_WIRE_SHAPES = {
"chunk": (
@@ -91,6 +108,11 @@ _GOOGLE_WIRE_SHAPES = {
item_children=(
WireField("finishReason", str),
WireField("finishMessage", str),
+ WireField(
+ "groundingMetadata",
+ Mapping,
+ children=(WireField("webSearchQueries", list), WireField("groundingChunks", list)),
+ ),
WireField(
"content",
Mapping,
@@ -163,7 +185,7 @@ class GoogleAdapter(ProviderAdapter):
if terminal is not None:
yield terminal
return
- stream = _GoogleStream(assembler)
+ stream = _GoogleStream(assembler, frozenset(native_hosted_tools(request)))
try:
wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)
@@ -227,8 +249,13 @@ class _GoogleStream:
stream), and the request builder puts it back on that text part.
"""
- def __init__(self, assembler: StreamAssembler) -> None:
+ def __init__(self, assembler: StreamAssembler, hosted: frozenset[str] = frozenset()) -> None:
self.assembler = assembler
+ # The tools this request declared natively: a server-side call of any other stays out of the transcript.
+ self.hosted = hosted
+ # Each Google Search by its call id: its slot and its toolCall part, until its toolResponse arrives.
+ self._searches: dict[str, tuple[tuple[str, str], dict[str, Any]]] = {}
+ self._grounding: Mapping[str, Any] | None = None
self.ended = False
self._finish: str | None = None
self._finish_message: str | None = None
@@ -286,6 +313,8 @@ class _GoogleStream:
content = candidate.get("content")
for part in (content.get("parts") or []) if isinstance(content, Mapping) else []:
events.extend(self._part(part))
+ if isinstance(candidate.get("groundingMetadata"), Mapping):
+ self._grounding = candidate["groundingMetadata"]
if candidate.get("finishReason"):
self._finish = candidate["finishReason"]
self._finish_message = candidate.get("finishMessage")
@@ -294,6 +323,9 @@ class _GoogleStream:
def _part(self, part: Mapping[str, Any]) -> list[Any]:
events: list[Any] = []
signature = part.get("thoughtSignature") or None
+ if isinstance(part.get("toolCall"), Mapping) or isinstance(part.get("toolResponse"), Mapping):
+ self._server_part(part)
+ return events
call = part.get("functionCall")
if isinstance(call, Mapping):
name = call.get("name")
@@ -333,11 +365,61 @@ class _GoogleStream:
# Parts of a kind this adapter does not declare (inline data, code execution) carry nothing to the loop.
return events
+ def _server_part(self, part: Mapping[str, Any]) -> None:
+ """A Google Search Gemini ran inside the response: one hosted call, its two parts kept verbatim (§4)."""
+
+ source_id = self.assembler.source_id
+ call = part.get("toolCall")
+ response = part.get("toolResponse")
+ item = call if isinstance(call, Mapping) else response
+ if (
+ "web_search" not in self.hosted or source_id is None or not isinstance(item, Mapping)
+ or item.get("toolType") != GOOGLE_SEARCH_TOOL_TYPE
+ ):
+ return
+ self._end_block()
+ if isinstance(call, Mapping):
+ call_id = call.get("id") or f"google_search_{len(self._searches) + 1}"
+ key = ("hosted", call_id)
+ self._searches[call_id] = (key, dict(part))
+ self.assembler.hosted_block(key, google_hosted_block(part, None, source_id=source_id, call_id=call_id))
+ return
+ # A response names its call; one that names none answers the latest call still waiting.
+ call_id = response.get("id") or next(
+ (pending for pending, (key, _) in reversed(self._searches.items())
+ if (block := self.assembler.hosted_block_at(key)) is not None and block.record.status == "pending"),
+ None,
+ )
+ if call_id not in self._searches:
+ return
+ key, call_part = self._searches[call_id]
+ self.assembler.hosted_block(
+ key, google_hosted_block(call_part, part, source_id=source_id, call_id=call_id),
+ )
+
+ def _ground(self) -> None:
+ """Gemini reports a response's searches and sources once: they count its calls and fill its last record."""
+
+ if not self._searches or self._grounding is None:
+ return
+ searches = google_search_count(self._grounding)
+ if searches:
+ self.assembler.set_hosted_facts(counts={"web_search_requests": searches})
+ sources = google_grounding_sources(self._grounding)
+ completed = [
+ (key, block) for key, _ in self._searches.values()
+ if (block := self.assembler.hosted_block_at(key)) is not None and block.record.status == "completed"
+ ]
+ if sources and completed:
+ key, block = completed[-1]
+ self.assembler.hosted_block(key, replace(block, record=replace(block.record, sources=sources)))
+
def finish(self) -> list[Any]:
if self._finish is None and self._blocked is None:
terminal = self.assembler.terminal(self.assembler.incomplete())
return [terminal] if terminal is not None else []
self._end_block()
+ self._ground()
events: list[Any] = list(self.assembler.block_end_events())
if self._finish is None:
final = self.assembler.finalize("safety", error_message=f"Gemini blocked the prompt: {self._blocked}")
@@ -360,13 +442,24 @@ def build_google_payload(
payload: dict[str, Any] = {"contents": _contents(messages, model, request.supports_images, loaded_images)}
if request.system:
payload["systemInstruction"] = {"parts": [{"text": request.system}]}
- if request.tools:
- payload["tools"] = [{
- "functionDeclarations": [
- {"name": tool.name, "description": tool.description, "parametersJsonSchema": dict(tool.input_schema)}
- for tool in request.tools
- ],
- }]
+ # A hosted tool this hop runs natively is sent as Gemini's own tool in its spec's place (§4.1), and Gemini runs a
+ # server-side tool next to functions only when the request says it will circulate their calls.
+ native = native_hosted_tools(request)
+ functions = [
+ {"name": tool.name, "description": tool.description, "parametersJsonSchema": dict(tool.input_schema)}
+ for tool in request.tools
+ if tool.name not in native
+ ]
+ tools: list[dict[str, Any]] = [{"functionDeclarations": functions}] if functions else []
+ for route in native.values():
+ kind = (route.declaration or {}).get("type")
+ if kind not in _NATIVE_TOOLS:
+ raise ValueError(f"unsupported Gemini hosted declaration: {kind!r}")
+ tools.append(copy.deepcopy(_NATIVE_TOOLS[kind]))
+ if tools:
+ payload["tools"] = tools
+ if native:
+ payload["toolConfig"] = {"includeServerSideToolInvocations": True}
generation: dict[str, Any] = {"maxOutputTokens": request.max_tokens}
thinking = _thinking_config(model, _effort(request.reasoning_effort or ""))
if thinking is not None:
@@ -485,6 +578,10 @@ def _model_parts(message: AssistantMessage, *, current_turn: bool) -> list[dict[
call["thoughtSignature"] = signature
first_call = False
parts.append(call)
+ elif isinstance(block, HostedToolBlock):
+ # Its toolCall and toolResponse parts, verbatim with their signatures (transform allowed it for this
+ # Source); Gemini circulates them as its own.
+ parts.extend(copy.deepcopy(list(block.native.payload)))
return parts
diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.py
index 1877298fa..1041e5db8 100644
--- a/core/agent_core/ai/hosted.py
+++ b/core/agent_core/ai/hosted.py
@@ -243,6 +243,58 @@ def anthropic_hosted_block(
)
+#: Gemini's server-side tool type for a Google Search it ran.
+GOOGLE_SEARCH_TOOL_TYPE = "GOOGLE_SEARCH_WEB"
+
+
+def google_hosted_block(
+ call: Mapping[str, Any],
+ response: Optional[Mapping[str, Any]],
+ *,
+ source_id: str,
+ call_id: str,
+ sources: tuple[HostedSource, ...] = (),
+) -> HostedToolBlock:
+ """A Gemini Google Search: its ``toolCall`` part and, once one arrived, its ``toolResponse`` part, both verbatim
+ with their signatures. ``sources`` are the response's grounding chunks, which Gemini reports once per response."""
+
+ tool_call = call.get("toolCall") if isinstance(call.get("toolCall"), Mapping) else {}
+ arguments = tool_call.get("args") if isinstance(tool_call.get("args"), Mapping) else {}
+ raw_queries = arguments.get("queries")
+ queries = tuple(query for query in raw_queries if _text(query)) if isinstance(raw_queries, list) else ()
+ action = HostedAction("search", queries=queries) if queries else HostedAction("other", name="google_search")
+ record = HostedRecord(status="pending") if response is None else HostedRecord(status="completed", sources=sources)
+ return HostedToolBlock(
+ id=_text(tool_call.get("id")) or call_id,
+ tool="web_search",
+ action=action,
+ record=record,
+ native=HostedNative(source_id=source_id, payload=_payload(call) if response is None else _payload(call, response)),
+ )
+
+
+def google_grounding_sources(metadata: Any) -> tuple[HostedSource, ...]:
+ """The web sources a Gemini response's ``groundingMetadata`` lists, in its order, each once."""
+
+ chunks = metadata.get("groundingChunks") if isinstance(metadata, Mapping) else None
+ sources: dict[str, HostedSource] = {}
+ for chunk in chunks if isinstance(chunks, list) else ():
+ web = chunk.get("web") if isinstance(chunk, Mapping) else None
+ url = _text(web.get("uri")) if isinstance(web, Mapping) else None
+ if url is not None and url not in sources:
+ sources[url] = HostedSource(url=url, title=_text(web.get("title")))
+ return tuple(sources.values())
+
+
+def google_search_count(metadata: Any) -> int:
+ """The searches Google bills a Gemini response for: its distinct, non-empty ``webSearchQueries``."""
+
+ queries = metadata.get("webSearchQueries") if isinstance(metadata, Mapping) else None
+ return len({query.strip() for query in queries if isinstance(query, str) and query.strip()}) if isinstance(
+ queries, list
+ ) else 0
+
+
def citation(raw: Mapping[str, Any], *, offset: int = 0) -> Optional[Citation]:
"""A provider citation on assistant text: an OpenAI/xAI ``url_citation`` with its range, shifted by ``offset``
into the block's text, or an Anthropic ``web_search_result_location``, which covers its whole text block."""
diff --git a/core/agent_core/ai/transform.py b/core/agent_core/ai/transform.py
index 1038fc317..cffa5c930 100644
--- a/core/agent_core/ai/transform.py
+++ b/core/agent_core/ai/transform.py
@@ -363,7 +363,7 @@ def native_replay(
# A native payload is opaque provider content too: it goes back only to the account that issued it.
if not _opaque_admitted(message, endpoint, "hosted"):
return False
- if protocol not in ("anthropic", "openai_responses"):
+ if protocol not in ("anthropic", "openai_responses", "google"):
return False
if {block.native.source_id for block in blocks} != {endpoint.source_id}:
return False
diff --git a/core/handlers/model_hub/hosted_admission.py b/core/handlers/model_hub/hosted_admission.py
index bd1c9da12..9874d272d 100644
--- a/core/handlers/model_hub/hosted_admission.py
+++ b/core/handlers/model_hub/hosted_admission.py
@@ -29,6 +29,7 @@ from vibe.backend_model_catalog import HostedToolSpec, bundled_provider_overlay
from .capability_evidence import HOSTED_TOOL_ASPECTS
from .hosted_items import responses_item_tool
from .hosted_tools import HostedEvidence, hosted_tool_facts
+from .request import declared_tool_types
PIN_SOURCE_HEADER: Final = "x-avibe-pin-source"
# The served-hop model a continuation was rendered for; without it a pin is the launch's primary hop.
@@ -47,6 +48,8 @@ _RESPONSES_MODEL_OUTPUTS: Final = frozenset({
# Output items identified by the tool they name; one without a textual name is malformed.
_RESPONSES_NAMED_CALLS: Final = frozenset({"function_call", "custom_tool_call", "mcp_call"})
_ANTHROPIC_SERVER_RESULTS: Final = {"web_search_tool_result": "web_search"}
+# Gemini's server-side tool parts, by the catalog tool their ``toolType`` ran.
+_GOOGLE_SERVER_TOOLS: Final = {"GOOGLE_SEARCH_WEB": "web_search"}
SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]
@@ -90,16 +93,13 @@ def hosted_content(request: Mapping[str, Any], protocol: str, *, pinned: bool) -
"""The hosted declarations and replayed native items in a request body, by tool."""
declared = _declaration_tools().get(protocol, {})
- tools = request.get("tools")
- calls = frozenset(
- (declared[tool["type"]], tool["type"])
- for tool in (tools if isinstance(tools, list) else ())
- if isinstance(tool, Mapping) and isinstance(tool.get("type"), str) and tool["type"] in declared
- )
+ calls = frozenset((declared[kind], kind) for kind in declared_tool_types(request) if kind in declared)
if protocol == "openai_responses":
replays, in_flight = _responses_replays(request.get("input"), pinned=pinned)
elif protocol == "anthropic":
replays, in_flight = _anthropic_replays(request.get("messages"), pinned=pinned)
+ elif protocol == "google":
+ replays, in_flight = _google_replays(request.get("contents"), pinned=pinned)
else:
replays, in_flight = frozenset(), frozenset()
return HostedContent(calls, replays, in_flight)
@@ -197,6 +197,49 @@ def _anthropic_replays(messages: Any, *, pinned: bool) -> tuple[frozenset[str],
return frozenset(tools), frozenset(carried)
+def _google_server_tool(part: Any) -> str | None:
+ for key in ("toolCall", "toolResponse"):
+ item = part.get(key) if isinstance(part, Mapping) else None
+ if isinstance(item, Mapping):
+ return _GOOGLE_SERVER_TOOLS.get(item.get("toolType"))
+ return None
+
+
+def _only_function_responses(content: Any) -> bool:
+ parts = content.get("parts") if isinstance(content, Mapping) else None
+ return (
+ content.get("role") == "user" and isinstance(parts, list) and bool(parts)
+ and all(isinstance(part, Mapping) and "functionResponse" in part for part in parts)
+ )
+
+
+def _google_replays(contents: Any, *, pinned: bool) -> tuple[frozenset[str], frozenset[str]]:
+ """The tools of Gemini server-side parts to replay, and of those in the in-flight response.
+
+ The in-flight response is the last ``model`` content when only the client's function responses follow it.
+ """
+
+ if not isinstance(contents, list):
+ return frozenset(), frozenset()
+ in_flight: int | None = None
+ if pinned:
+ index = len(contents)
+ while index and _only_function_responses(contents[index - 1]):
+ index -= 1
+ if index and isinstance(contents[index - 1], Mapping) and contents[index - 1].get("role") == "model":
+ in_flight = index - 1
+ tools: set[str] = set()
+ carried: set[str] = set()
+ for index, content in enumerate(contents):
+ if not isinstance(content, Mapping) or content.get("role") != "model":
+ continue
+ parts = content.get("parts")
+ for part in parts if isinstance(parts, list) else ():
+ if (tool := _google_server_tool(part)) is not None:
+ (carried if index == in_flight else tools).add(tool)
+ return frozenset(tools), frozenset(carried)
+
+
def admits(
content: HostedContent,
*,
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index f219e013f..ac93d2af8 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -71,7 +71,7 @@ SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]
# The engine release when the engine manifest cannot be read. It names no release, so a refusal learned under it
# never matches a real one.
UNKNOWN_ENGINE_RELEASE = "unknown-engine"
-NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})
+NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses", "google"})
# S2b-2 activates the read and chain together; release with S6 disclosure. Not a user toggle.
SEARCH_SERVICES_ACTIVE: Final = True
diff --git a/core/handlers/model_hub/request.py b/core/handlers/model_hub/request.py
index 94277ab9c..d0e756f57 100644
--- a/core/handlers/model_hub/request.py
+++ b/core/handlers/model_hub/request.py
@@ -127,14 +127,22 @@ def without_opaque_history(request: Mapping[str, Any]) -> Mapping[str, Any]:
return payload
+# Gemini's generateContent declares a server-side tool as a keyed object (``{"googleSearch": {}}``); the overlay
+# names it by the type Google's typed tools give it (``vibey-gemini-native.md`` §4).
+GOOGLE_NATIVE_TOOL_TYPES: Final[Mapping[str, str]] = {"googleSearch": "google_search"}
+
+
def declared_tool_types(request: Mapping[str, Any]) -> frozenset[str]:
- """The ``type`` of every tool the request declares."""
+ """The ``type`` of every tool the request declares, a Gemini keyed tool by its overlay type."""
tools = request.get("tools")
if not isinstance(tools, list):
return frozenset()
return frozenset(
kind for tool in tools if isinstance(tool, Mapping) and isinstance(kind := tool.get("type"), str)
+ ) | frozenset(
+ kind for tool in tools if isinstance(tool, Mapping)
+ for key, kind in GOOGLE_NATIVE_TOOL_TYPES.items() if key in tool
)
diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.md
index ef7170781..74b54c813 100644
--- a/docs/plans/agent-core-contracts/conversion-tables.md
+++ b/docs/plans/agent-core-contracts/conversion-tables.md
@@ -29,7 +29,7 @@ rules on top of those mappings.
| Partial and abort | The shared `partial_message` policy is used by all three adapters. Usage captured before the first visible delta is retained, and errors/abort carry an assembled `AssistantMessage` whenever visible content or usage exists; empty placeholder slots alone do not count as streamed output, while non-empty terminal snapshots do. Consumer/task cancellation is preserved even if response cleanup fails. |
| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. It admits at most one `after_thinking` retry per request; that attempt's thinking partial is never context, like any retried attempt's. A retry-admitted usage-only partial is never context: the retry resends the original request, and the attempt's usage is one non-context `ModelAttempt` audit row, in every mode (C-9 `context.md` §10, invariant 4), so per-attempt usage is kept without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_keeps_a_usage_only_partial_out_of_the_context` are the loop proofs. |
| Tool-call stop normalization | `StreamAssembler.finalize` changes only `stop` with one or more tool calls to canonical `tool_use`, following Pi. The loop admits execution only for `stop_reason="tool_use"`; calls attached to `length`, `safety`, `refusal`, or `error` are settled as `is_error` results explaining the stop reason. |
-| Parallel tool calls | No request turns them off, so a response may carry several calls: Anthropic Messages sends no `tool_choice`, so `disable_parallel_tool_use` keeps its default `false`; Chat Completions and Responses send no `parallel_tool_calls`, which defaults to `true`; a Gemini request sends no `toolConfig`, and Gemini has no switch for it. No Chat request may send `parallel_tool_calls: false`: a Chat relay serving Gemini has no switch to map it to, and the gateway's engine (CLIProxyAPI `c404af96`, `internal/translator/gemini/openai/chat-completions/gemini_openai_request.go`) then turns every tool off. The loop runs neighbouring concurrent calls at the same time and every `edit` or `write` alone (C-3 `loop-control.md` §2), a deviation from Pi, which runs a response's calls at once and serializes mutations only per file path. |
+| Parallel tool calls | No request turns them off, so a response may carry several calls: Anthropic Messages sends no `tool_choice`, so `disable_parallel_tool_use` keeps its default `false`; Chat Completions and Responses send no `parallel_tool_calls`, which defaults to `true`; a Gemini request sends no `toolConfig` beyond the one Google Search needs (`includeServerSideToolInvocations`), and Gemini has no switch for it. No Chat request may send `parallel_tool_calls: false`: a Chat relay serving Gemini has no switch to map it to, and the gateway's engine (CLIProxyAPI `c404af96`, `internal/translator/gemini/openai/chat-completions/gemini_openai_request.go`) then turns every tool off. The loop runs neighbouring concurrent calls at the same time and every `edit` or `write` alone (C-3 `loop-control.md` §2), a deviation from Pi, which runs a response's calls at once and serializes mutations only per file path. |
## Shared stream assembler and dispatch ledger
@@ -661,7 +661,7 @@ gateway's Gemini surface, which serves it to a Gemini Source untranslated.
| Thinking | Same origin: a signed or unsigned thought is `{text, thought: true}` with its `thoughtSignature`. An empty block that holds only a signature goes back on the text part right before it (an answer's signature, which `TextBlock` cannot hold), else as `{text: "", thoughtSignature}`. A signature that is not well-formed base64 (a Chat reasoning marker an older transcript holds) is not sent. |
| Tool call | `functionCall {name, args, id}` with the call's `thoughtSignature`. In the current turn (after the last user message), the first call of a step that carries no valid signature gets Google's documented stand-in `skip_thought_signature_validator`, so another origin's calls are accepted; earlier turns are not validated and get none. |
| Tool result | `functionResponse {name, id, response: {output}}`, or `{error}` for an error result; image-only text is `(see attached image)`, empty text `(no tool output)`. A step's results share one `role="user"` content in call order. Images ride in `functionResponse.parts` on Gemini 3 and later and on non-Gemini ids, else in one user content after `Tool result image:` that follows the whole step's results. |
-| Tools | One `functionDeclarations` list with `name`, `description`, and the JSON Schema as `parametersJsonSchema`. |
+| Tools | One `functionDeclarations` list with `name`, `description`, and the JSON Schema as `parametersJsonSchema`; a natively declared `web_search` is `{"googleSearch": {}}` after it instead, with `toolConfig.includeServerSideToolInvocations: true` (Hosted tools, below). |
| Reasoning effort | Gemini 3 and later and the `-latest` aliases get `thinkingConfig.thinkingLevel` (`xhigh`/`max` → `high`; `none` → `minimal`; `minimal` → `low` outside the Flash family, which alone takes it); Gemini 2.5 gets `thinkingBudget` (`minimal`/`low` 1024, `medium` 8192, `high` and above 24576, `none` 0 without thoughts). `includeThoughts` is set on every thinking model; other models get no `thinkingConfig`. The effort token (`registry.sent_effort`, the key Model Hub holds effort evidence under, and what its gateway reads back from the request) is the thinking level sent, or the effort a budget stands for (`0` none, `1024` low, `8192` medium, `24576` high). |
| Output bound | `generationConfig.maxOutputTokens`. |
@@ -672,7 +672,9 @@ Gemini stream events (each `data:` frame is a `GenerateContentResponse` whose pa
| `candidates[0].content.parts[].text` with `thought: true` | delta | `ThinkingDelta`; consecutive thought parts extend one block, and its `thoughtSignature` is the block's signature. |
| `…parts[].text` | delta | `TextDelta`; consecutive text parts extend one block. A `thoughtSignature` on any of them, or on an empty part right after them, becomes an empty signed `ThinkingBlock` after that text once the text ends. |
| `…parts[].functionCall` | delta | `ToolCallStart` and one `ToolCallDelta` of the JSON `args`; `id` is the native id, `thoughtSignature` the call's signature. An empty name is terminal `invalid_request`. |
-| any other part | ignored | Parts of a kind the request did not declare (inline data, code execution). |
+| `…parts[].toolCall` / `toolResponse` with `toolType: GOOGLE_SEARCH_WEB` | state | One `web_search` `HostedToolBlock` per call `id` (Hosted tools, below), only when the request declared it natively. |
+| any other part | ignored | Parts of a kind the request did not declare (inline data, code execution, another server-side tool). |
+| `candidates[0].groundingMetadata` | state | `webSearchQueries` and `groundingChunks` of the response, read at its finish (Hosted tools, below). |
| `candidates[0].finishReason` | state | Stop reason (below). |
| `usageMetadata` | state | `input = promptTokenCount - cachedContentTokenCount`; `output = candidatesTokenCount + thoughtsTokenCount`; `cache_read = cachedContentTokenCount`; `reasoning = thoughtsTokenCount`. The last frame's counts win. |
| `promptFeedback.blockReason` without a finish | Done | `safety`, with the block reason as `error_message`. |
@@ -711,7 +713,7 @@ These rows describe the wire mapping the `ai` lane implements.
that call from its result.
- **Native replay and pins.** A response's hosted calls go back verbatim, their `native.payload` in place, only to
the hop the request goes to, and only when that hop's Source served them on the same origin. The protocol must be
- Anthropic or Responses, and the hop must still declare each tool they called natively. Such a request is pinned to
+ Anthropic, Responses or Gemini, and the hop must still declare each tool they called natively. Such a request is pinned to
the hop's Source.
- The response a request continues within its turn needs no replay evidence, and its request also names the
model that served it (`x-avibe-pin-model`, when that id is ASCII). That response is the request's last assistant
@@ -741,6 +743,19 @@ These rows describe the wire mapping the `ai` lane implements.
An Anthropic citation covers its whole text block, so it carries no range.
+Gemini (`google`, plan `../vibey-gemini-native.md` §4) runs `web_search` as Google Search:
+
+| Concern | Gemini `generateContent` |
+| --- | --- |
+| Native declaration | `{"googleSearch": {}}` after the `functionDeclarations`, for the overlay's `{"type": "google_search"}`, plus `toolConfig.includeServerSideToolInvocations: true` |
+| Proxy declaration | a `functionDeclarations` entry with the canonical schema |
+| Native result → `HostedToolBlock` | a `toolCall` part (`toolType: GOOGLE_SEARCH_WEB`, `args.queries`) opens one `search` block by its `id`, `pending`; the `toolResponse` part with the same `id` completes it. Both parts, signatures included, are its `native.payload`. The `search_suggestions` markup in the response is never kept. |
+| Response-level facts | at the finish, the distinct `groundingMetadata.webSearchQueries` are `counts.web_search_requests`, and the `groundingChunks` (`web.uri`, `web.title`, each URL once) are the sources of the response's last completed search |
+| Citations | none yet: `groundingSupports` is not read |
+| Same-Source replay | `native.payload` parts verbatim, in place in the `model` content |
+| Other-origin replay | the portable synthetic call and result, as for the other protocols |
+| Pinning, in-flight replay | as for the other protocols; the in-flight response is the last `model` content followed only by function responses |
+
| Concern | Anthropic Messages | OpenAI Responses (OpenAI, xAI) | OpenAI Chat Completions |
| --- | --- | --- | --- |
| Native declaration (mode from `HopResolution.hosted_tools`) | `{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}` | `{"type": "web_search"}`; xAI also `{"type": "x_search"}`; plus the overlay entry's `include` values (OpenAI web search: `web_search_call.action.sources`) | none |
diff --git a/docs/plans/vibey-gemini-native.md b/docs/plans/vibey-gemini-native.md
index 5418dbca5..d8d292f9f 100644
--- a/docs/plans/vibey-gemini-native.md
+++ b/docs/plans/vibey-gemini-native.md
@@ -109,15 +109,26 @@ included (owner, 2026-10-27: "统一都走原生").
## 4. Google Search as Gemini's native `web_search` (PR 3)
-- The overlay's `gemini` provider row declares `web_search` on `google` as `{"googleSearch": {}}` with the per-query
- price; the adapter adds `toolConfig.includeServerSideToolInvocations` when it declares one.
-- A response's `toolCall`/`toolResponse` pair becomes one `HostedToolBlock` (`action: search` with the queries;
- the record's sources from `groundingChunks`; the answer's citations from `groundingSupports`), with the parts
- verbatim as its native payload for same-Source replay; any other target gets the synthetic call and result
- (`vibey-hosted-tools.md` §5). The raw `search_suggestions` markup is not kept in the record.
-- Evidence (`evidence_rules.py`): a served response with a `GOOGLE_SEARCH_WEB` `toolCall` is positive; an error
- naming the tool before output is the narrow negative rule. Cost: queries × list price, from
- `groundingMetadata.webSearchQueries`.
+- The overlay's `gemini` provider rows (prefixes `gemini-3`, `gemini-4`; ids `gemini-flash-latest`,
+ `gemini-flash-lite-latest`, `gemini-pro-latest`) declare `web_search` on `google` as `{"type": "google_search"}`
+ with the per-query price ($14 per 1,000, as of 2026-10-27). Gemini 2.5 is not declared: it refuses a server-side
+ tool next to functions (measured). A Source keeps Google's `models/<id>` names, so the overlay matches the id
+ without that prefix.
+- The adapter sends that declaration as `{"googleSearch": {}}` after the `functionDeclarations`, with
+ `toolConfig.includeServerSideToolInvocations: true`, which Gemini requires to run it next to functions (measured).
+- A response's `toolCall`/`toolResponse` pair (`toolType: GOOGLE_SEARCH_WEB`) becomes one `HostedToolBlock`
+ (`action: search` with the call's `queries`; the record's sources are the response's `groundingChunks`, each
+ once), with both parts verbatim, signatures included, as its native payload. Same-Source replay sends them back
+ in place; any other target gets the synthetic call and result (`vibey-hosted-tools.md` §5). The
+ `search_suggestions` markup is never kept (§0). A server-side part of a tool the request did not declare stays
+ out of the transcript.
+- Gateway: `hosted_admission` reads the keyed declaration through `request.declared_tool_types` and Gemini's
+ server-side parts as replays (the in-flight response is the last `model` content followed only by function
+ responses). Gemini's refusal "Tool call context circulation is not enabled" before output is the narrow negative
+ rule for `web_search` `call`, so the hop falls back to the executor chain. Cost: the response's distinct `groundingMetadata.webSearchQueries` × list price, as
+ `hosted_summary.counts.web_search_requests`.
+- Not in this step: a positive evidence rule (the Tools tab shows no "最近一次 … 正常" for Google Search) and
+ answer citations from `groundingSupports` (the record lists the sources; the text carries no links).
- Public docs (`avibe-docs`, en and zh): Gemini searches with Google, queries go to Google, and the price.
## 5. Delivery
@@ -135,5 +146,9 @@ of each other once PR 1 is merged.
- A Gemini subscription (Antigravity) is served by the engine over Chat only; it keeps Exa/Tavily search.
- Source links in Google's grounding are redirect URLs; the card shows the domain as title.
+- Google Search has no positive evidence yet and Gemini answers carry no inline citations (§4).
+- Gemini is not a search executor for other hops: the executor speaks Anthropic and Responses only, so Gemini runs
+ Google Search on its own hop and names no `executor_models` (a follow-up would add a `google` executor request
+ and result).
- The OpenAI-compatible Chat path keeps no dummy for another origin's current-turn call: after PR 2 no official
Gemini Source uses it, and a Chat relay that serves Gemini is the relay's to translate.
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index c32244d91..e34eee72b 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -164,14 +164,16 @@ The evidence store, its record and its owner are the capability model's §3. v2
current while file writes are throttled, and a Source that changes identity hands the line to the newest other
success rather than to an older file copy. There is no separate per-tool projection to drift from the records.
- Positive evidence never changes routing. It feeds the "最近一次 … 正常" lines (§8) and nothing else.
- - A `google` hop has no native hosted tools yet; Vibey speaks Gemini natively there (amended 2026-10-27,
- `vibey-gemini-native.md`), and Google Search joins as Gemini's native `web_search` in its §4.
+ - On a `google` hop Vibey speaks Gemini natively, and Google Search is Gemini's native `web_search` (amended
+ 2026-10-27, `vibey-gemini-native.md` §4). It has no positive rule yet, so it shows no "最近一次 … 正常" line.
- **Negative (`unsupported`) is routing state.** When the file write fails, the narrow rule still updates the
in-memory store and logs the loss, so the re-resolve that follows (§3.5) cannot declare the refused tool natively
again. The narrow rules of #2551 fire on a real error before output, unchanged in form:
- `Unsupported tool type: <type>` for a declared type → hosted tool `call`;
- `Invalid encrypted_content in search_result block` while the request replays a web-search result → `web_search`
`replay`;
+ - Gemini's `Tool call context circulation is not enabled` while the request declares Google Search →
+ `web_search` `call` (amended 2026-10-27, `vibey-gemini-native.md` §4);
- **new:** an upstream image endpoint that refuses the model or the endpoint before producing anything →
`image_generate` `call`. A 400 or 404 whose machine code names the model (`model_not_found`, `unknown_model`) is
written for that (Source, model); any other 404 is a refusal of the endpoint itself (the path is not served, as a
@@ -374,7 +376,7 @@ failover, and is refused unpinned (C-6 item 7). What changes is what happens aft
| `openai_responses` (OpenAI, xAI) | `{"type": "web_search"}`, `{"type": "x_search"}`, plus the overlay entry's `include` values. OpenAI's web search requires `include: ["web_search_call.action.sources"]`, merged with Vibey's existing `reasoning.encrypted_content`. | `{"type": "function", "name": <tool>, "parameters": <canonical>}` |
| `anthropic` | `{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}` | `{"name": <tool>, "input_schema": <canonical>}` |
| `openai_chat` | none | `{"type": "function", "function": {"name": <tool>, "parameters": <canonical>}}` |
-| `google` | none yet (`vibey-gemini-native.md` §4) | a `functionDeclarations` entry with the canonical schema as `parametersJsonSchema`; Vibey speaks Gemini natively (amended 2026-10-27) |
+| `google` (Gemini 3 and later, `-latest`) | `{"googleSearch": {}}` for the overlay's `{"type": "google_search"}`, with `toolConfig.includeServerSideToolInvocations: true` (amended 2026-10-27, `vibey-gemini-native.md` §4) | a `functionDeclarations` entry with the canonical schema as `parametersJsonSchema` |
- Vibey declares a search tool natively exactly when it is enabled and `native` is `assumed`; otherwise it declares
the same-named function. It never declares a hosted image tool.
diff --git a/tests/agent_core/ai/test_google_adapter.py b/tests/agent_core/ai/test_google_adapter.py
index e26e085b9..e78baf939 100644
--- a/tests/agent_core/ai/test_google_adapter.py
+++ b/tests/agent_core/ai/test_google_adapter.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import base64
import json
+from dataclasses import replace
from typing import Any
import httpx
@@ -11,10 +12,12 @@ import pytest
from core.agent_core.ai.google import DUMMY_THOUGHT_SIGNATURE, GoogleAdapter
from core.agent_core.ai.registry import sent_effort
-from core.agent_core.ai.provider import Done, ModelEndpoint, ModelRequest, ProviderError
+from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError
from core.agent_core.cancel import CancelToken
from core.agent_core.messages import (
AssistantMessage,
+ HostedSource,
+ HostedToolBlock,
ImageBlock,
Origin,
TextBlock,
@@ -313,3 +316,103 @@ async def test_an_error_frame_is_classified_from_its_google_status() -> None:
error = (await _stream({"error": {"code": 429, "message": "Resource exhausted", "status": "RESOURCE_EXHAUSTED"}}))[-1]
assert isinstance(error, ProviderError)
assert error.kind == "rate_limit" and error.retryable
+
+
+# --- Google Search, Gemini's native web_search (vibey-gemini-native.md §4) ----------------------------------------
+
+SOURCE = "src_gemini0001"
+SEARCH = ToolSpec("web_search", "Search the web", {"type": "object", "properties": {"query": {"type": "string"}}})
+NATIVE_SEARCH = HostedToolRoute(mode="native", replay=True, declaration={"type": "google_search"})
+SERVED = json.dumps({"provider": "google", "api": "google", "model": MODEL, "source": SOURCE}, separators=(",", ":"))
+CALL_PART = {
+ "toolCall": {"toolType": "GOOGLE_SEARCH_WEB", "args": {"queries": ["btc price today", "btc close"]}, "id": "srch_1"},
+ "thoughtSignature": SIG_A,
+}
+RESPONSE_PART = {
+ "toolResponse": {"toolType": "GOOGLE_SEARCH_WEB", "response": {"search_suggestions": "<div>chips</div>"}, "id": "srch_1"},
+ "thoughtSignature": SIG_B,
+}
+GROUNDING = {
+ "webSearchQueries": ["btc price today", "btc close", "btc price today"],
+ "groundingChunks": [
+ {"web": {"uri": "https://grounding.invalid/a", "title": "coindesk.com"}},
+ {"web": {"uri": "https://grounding.invalid/b", "title": "coinbase.com"}},
+ {"web": {"uri": "https://grounding.invalid/a", "title": "coindesk.com"}},
+ ],
+}
+
+
+def _searching(*messages: Any) -> ModelRequest:
+ request = _request(*messages, base_url="http://hub.invalid/vibey/v1beta", tools=(BASH, SEARCH))
+ return replace(request, endpoint=replace(
+ request.endpoint, source_id=SOURCE, source_identity="sha256:gemini", hosted_tools={"web_search": NATIVE_SEARCH},
+ ))
+
+
+async def test_a_native_search_is_googles_own_tool_with_server_side_calls_enabled() -> None:
+ wire = await build_wire_request(_searching(_user("btc?")), gateway=True)
+
+ # Gemini runs Google Search next to functions only when the request says it will circulate their calls.
+ assert wire.body["tools"] == [
+ {"functionDeclarations": [
+ {"name": "bash", "description": "Run a command", "parametersJsonSchema": dict(BASH.input_schema)},
+ ]},
+ {"googleSearch": {}},
+ ]
+ assert wire.body["toolConfig"] == {"includeServerSideToolInvocations": True}
+ # A native declaration only ever goes to the hop's own Source.
+ assert wire.headers["x-avibe-pin-source"] == SOURCE
+
+
+async def test_a_google_search_is_one_hosted_call_whose_parts_go_back_verbatim() -> None:
+ chunks = (
+ _parts(CALL_PART),
+ _parts(RESPONSE_PART),
+ _parts({"text": "BTC closed at $79,6xx."}),
+ # Gemini reports the response's searches and sources once, with its finish.
+ {"candidates": [{"content": {"role": "model", "parts": [{"text": "", "thoughtSignature": SIG_A}]},
+ "finishReason": "STOP", "groundingMetadata": GROUNDING}]},
+ )
+
+ def gateway(sent: httpx.Request) -> httpx.Response:
+ body = "".join(f"data: {json.dumps(chunk)}\r\n\r\n" for chunk in chunks)
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": SERVED}, text=body,
+ )
+
+ request = _searching(_user("btc?"))
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ events = [event async for event in GoogleAdapter(client, gateway=True).stream(request, CancelToken())]
+ message = _final(events)
+
+ [search] = [block for block in message.content if isinstance(block, HostedToolBlock)]
+ assert (search.id, search.tool, search.action.type, search.action.queries) == (
+ "srch_1", "web_search", "search", ("btc price today", "btc close"),
+ )
+ assert search.record.status == "completed"
+ # The grounding chunks, each once; Google's Search Suggestions markup is not part of the record.
+ assert search.record.sources == (
+ HostedSource(url="https://grounding.invalid/a", title="coindesk.com"),
+ HostedSource(url="https://grounding.invalid/b", title="coinbase.com"),
+ )
+ assert search.native.source_id == SOURCE and search.native.payload == (CALL_PART, RESPONSE_PART)
+ # Google bills each distinct query the model ran.
+ assert message.hosted_summary is not None and message.hosted_summary.counts == {"web_search_requests": 2}
+
+ # Back to the same Source, the call's parts go verbatim, signatures included, before the answer.
+ body = await _body(_searching(_user("btc?"), message, _user("and eth?")), gateway=True)
+ assert body["contents"][1]["parts"] == [
+ CALL_PART, RESPONSE_PART, {"text": "BTC closed at $79,6xx.", "thoughtSignature": SIG_A},
+ ]
+
+ # Any other Source gets the portable form: a synthetic web_search call and result, no Google parts.
+ other = _searching(_user("btc?"), message, _user("and eth?"))
+ other = replace(other, endpoint=replace(other.endpoint, source_id="src_other0001"))
+ wire = json.dumps((await _body(other, gateway=True))["contents"])
+ assert "toolCall" not in wire and "toolResponse" not in wire and SIG_B not in wire
+ assert '"name": "web_search"' in wire
+
+
+async def test_a_server_side_call_the_request_did_not_declare_stays_out_of_the_transcript() -> None:
+ message = _final(await _stream(_parts(CALL_PART), _parts(RESPONSE_PART), _parts({"text": "ok"}, finish="STOP")))
+ assert message.content == (TextBlock(text="ok"),) and message.hosted_summary is None
diff --git a/tests/test_model_hub_evidence_rules.py b/tests/test_model_hub_evidence_rules.py
index ad9cd3ccb..8bfc619c2 100644
--- a/tests/test_model_hub_evidence_rules.py
+++ b/tests/test_model_hub_evidence_rules.py
@@ -29,6 +29,11 @@ ULTRA_REFUSED = {
}
}
TOOL_REFUSED = {"error": {"message": "Unsupported tool type: web_search", "type": "invalid_request_error"}}
+# Measured on gemini-2.5-flash, 2026-10-27.
+GOOGLE_SEARCH_REFUSED = {"error": {
+ "code": 400, "status": "INVALID_ARGUMENT",
+ "message": "Tool call context circulation is not enabled for models/gemini-2.5-flash",
+}}
REPLAY_REFUSED = {
"type": "error",
"error": {"type": "invalid_request_error", "message": "Invalid encrypted_content in search_result block"},
@@ -73,15 +78,23 @@ CASES = [
{"max_tokens": 64, "messages": [{"role": "user", "content": "hi"}]}, 400, REPLAY_REFUSED, None, None),
("server-error-names-the-effort", "codex", "openai", "openai_responses",
{"input": "hi", "reasoning": {"effort": "ultra"}}, 500, ULTRA_REFUSED, None, None),
+ # Gemini refuses Google Search next to functions on a model that cannot circulate server-side calls.
+ (
+ "gemini-search-refused", "codex", "custom", "google",
+ {"contents": [{"role": "user", "parts": [{"text": "hi"}]}], "tools": [{"googleSearch": {}}]}, 400,
+ GOOGLE_SEARCH_REFUSED, EvidenceFeature.hosted("web_search", "call"), "400 invalid_request_error",
+ ),
+ ("gemini-search-not-declared", "codex", "custom", "google",
+ {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]}, 400, GOOGLE_SEARCH_REFUSED, None, None),
]
def _web_search_only(vendor, protocol, model_id, tool):
if tool != "web_search":
return None
- declaration = {"anthropic": {"type": "web_search_20250305", "name": "web_search"}}.get(
- protocol, {"type": "web_search"}
- )
+ declaration = {
+ "anthropic": {"type": "web_search_20250305", "name": "web_search"}, "google": {"type": "google_search"},
+ }.get(protocol, {"type": "web_search"})
return HostedToolSpec(declaration_json=json.dumps(declaration), price=None, include=())
@@ -97,6 +110,8 @@ async def test_an_upstream_400_teaches_only_the_feature_it_names(
"""MH-HOSTED-006: a narrow rule learns exactly the named feature; anything else learns nothing."""
monkeypatch.setattr(service_module, "hosted_tool_spec", _web_search_only)
source = _source("src_evidence1", "Relay 中转", vendor=vendor, protocol=protocol)
+ if protocol == "google":
+ source.base_url = "https://gemini.invalid" # a Google Source names its root
service, _clock, models = configured_service(tmp_path, sources=[source])
async def respond(_request):
diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.py
index 899298bdd..437ab90f4 100644
--- a/tests/test_model_hub_hosted_pinning.py
+++ b/tests/test_model_hub_hosted_pinning.py
@@ -533,6 +533,14 @@ def _tool_result(call_id):
return {"role": "user", "content": [{"type": "tool_result", "tool_use_id": call_id, "content": "ok"}]}
+GEMINI_USER = {"role": "user", "parts": [{"text": "search"}]}
+GEMINI_SEARCH_CALL = {"toolCall": {"toolType": "GOOGLE_SEARCH_WEB", "args": {"queries": ["q"]}, "id": "s1"},
+ "thoughtSignature": "sig"}
+GEMINI_SEARCH_RESULT = {"toolResponse": {"toolType": "GOOGLE_SEARCH_WEB", "response": {}, "id": "s1"},
+ "thoughtSignature": "sig"}
+GEMINI_CALL = {"functionCall": {"name": "shell", "args": {}, "id": "f1"}}
+GEMINI_RESULT = {"role": "user", "parts": [{"functionResponse": {"name": "shell", "id": "f1", "response": {}}}]}
+
IN_FLIGHT_CASES = [
("responses_cross_turn", "openai_responses", [USER, WEB_CALL, ASSISTANT_TEXT, USER], True, {"web_search"}),
("responses_in_flight", "openai_responses", [USER, WEB_CALL, X_CALL, LOCAL_CALL, LOCAL_OUTPUT], True, set()),
@@ -584,6 +592,20 @@ IN_FLIGHT_CASES = [
[USER, WEB_CALL, LOCAL_CALL, {"type": ["function_call_output"], "call_id": "fc_1"}], True, {"web_search"}),
("anthropic_server_tool_name_not_text", "anthropic",
[USER, {"role": "assistant", "content": [{**SERVER_USE, "name": ["web_search"]}]}, USER], True, set()),
+ # Gemini: the in-flight response is the last model content, followed only by function responses.
+ ("google_in_flight", "google",
+ [GEMINI_USER, {"role": "model", "parts": [GEMINI_SEARCH_CALL, GEMINI_SEARCH_RESULT, GEMINI_CALL]},
+ GEMINI_RESULT], True, set()),
+ ("google_cross_turn", "google",
+ [GEMINI_USER, {"role": "model", "parts": [GEMINI_SEARCH_CALL, GEMINI_SEARCH_RESULT]}, GEMINI_USER], True,
+ {"web_search"}),
+ ("google_unpinned", "google",
+ [GEMINI_USER, {"role": "model", "parts": [GEMINI_SEARCH_CALL, GEMINI_SEARCH_RESULT, GEMINI_CALL]},
+ GEMINI_RESULT], False, {"web_search"}),
+ # A server-side tool Gemini ran for anything but a search is not a hosted call of the catalog's.
+ ("google_other_server_tool", "google",
+ [GEMINI_USER, {"role": "model", "parts": [{"toolCall": {"toolType": "URL_CONTEXT", "id": "u1"}}]}, GEMINI_USER],
+ True, set()),
]
@@ -592,7 +614,7 @@ IN_FLIGHT_CASES = [
def test_only_items_outside_the_in_flight_response_need_replay_evidence(protocol, history, pinned, replays):
"""MH-HOSTED-GATEWAY-003: the structural in-flight rule agreed with the Vibey request builder."""
- field = "input" if protocol == "openai_responses" else "messages"
+ field = {"openai_responses": "input", "google": "contents"}.get(protocol, "messages")
content = hosted_content({field: history, "tools": [SHELL]}, protocol, pinned=pinned)
assert content.replays == frozenset(replays)
assert content.calls == frozenset()
@@ -658,3 +680,8 @@ def test_declarations_are_recognized_by_every_vendors_type():
{("web_search", "web_search_20250305")}
)
assert not hosted_content({"tools": tools}, "openai_chat", pinned=True)
+ # Gemini declares Google Search as a keyed tool object, named by the overlay's type.
+ gemini_tools = [{"functionDeclarations": [{"name": "web_search"}]}, {"googleSearch": {}}]
+ assert hosted_content({"tools": gemini_tools}, "google", pinned=True).calls == frozenset(
+ {("web_search", "google_search")}
+ )
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index e41f01514..2492cf52f 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -172,9 +172,9 @@ def _evidence(tmp_path, *refused) -> HostedEvidence:
(OPENAI, "x_search", (), "unsupported", "unsupported", False),
(OPENAI, "x_search", ((OPENAI, "gpt-6-astra", "x_search", "call"),), "unsupported", "unsupported", False),
(CLAUDE_SUB, "web_search", (), "unsupported", "unsupported", False),
- # Vibey speaks Gemini on a google hop (vibey-gemini-native.md), so the overlay's declaration runs there too;
- # its native payload is not replayed until Gemini's hosted replay is (§4).
- (GEMINI, "web_search", (), "assumed", "unsupported", False),
+ # Vibey speaks Gemini on a google hop (vibey-gemini-native.md), so the overlay's declaration runs there, and
+ # Gemini's server-side parts go back to it verbatim (§4).
+ (GEMINI, "web_search", (), "assumed", "assumed", False),
],
ids=[
"assumed", "replay-refused", "call-refused", "not-offered", "not-offered-refused",
diff --git a/tests/test_provider_overlay.py b/tests/test_provider_overlay.py
index 8b0e03707..9b15dfd4f 100644
--- a/tests/test_provider_overlay.py
+++ b/tests/test_provider_overlay.py
@@ -301,14 +301,22 @@ def test_an_image_model_entry_is_read_in_a_stable_form(monkeypatch, tmp_path):
assert catalog.provider_image_models("anthropic") == ()
+EXECUTOR_PROTOCOLS = {"anthropic", "openai_responses"}
+
+
@pytest.mark.parametrize("vendor", sorted(BUNDLED["providers"]))
def test_each_vendors_executor_models_run_every_search_tool_the_vendor_offers(vendor):
"""MH-HOSTED-005: an executor model the overlay does not declare a tool on would silently drop the vendor from
- that tool's executor chain on every Source that lists it first."""
+ that tool's executor chain on every Source that lists it first.
+
+ The executor speaks Anthropic and Responses (``hosted_executor.executor_request``); Gemini runs Google Search
+ natively on its own hop only (``vibey-gemini-native.md`` §6), so a tool offered on another protocol needs none.
+ """
offered = {
(protocol, tool)
for family in catalog.bundled_provider_overlay()[vendor]
for protocol, tools in family.hosted_tools.items()
+ if protocol in EXECUTOR_PROTOCOLS
for tool in tools
}
executors = catalog.provider_executor_models(vendor)
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index 7c440167b..f3567cd7a 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -843,11 +843,15 @@ def bundled_provider_vendors() -> Mapping[str, ProviderVendorOverlay]:
def provider_overlay_entry(vendor: str, model_id: str) -> ProviderModelOverlay | None:
- """Return the first model family of ``vendor`` that matches ``model_id``."""
+ """Return the first model family of ``vendor`` that matches ``model_id``.
+
+ Google names a model inside its ``models/`` collection (``models/gemini-4-argon``), the name a Gemini Source keeps;
+ a family matches the model's own id.
+ """
from core.handlers.model_hub.identifiers import normalized_model_id
- model = normalized_model_id(model_id)
+ model = normalized_model_id(model_id).removeprefix("models/")
vendor_entry = bundled_provider_vendors().get(vendor.strip().lower())
for entry in vendor_entry.models if vendor_entry is not None else ():
if (entry.match_kind == "id" and model == entry.match_value) or (
diff --git a/vibe/data/backend_models.json b/vibe/data/backend_models.json
index 130fc9669..f2a3f6241 100644
--- a/vibe/data/backend_models.json
+++ b/vibe/data/backend_models.json
@@ -94,7 +94,93 @@
]
},
"gemini": {
- "models": [],
+ "models": [
+ {
+ "match": { "prefix": "gemini-3" },
+ "wire_efforts": null,
+ "hosted_tools": {
+ "google": {
+ "web_search": {
+ "declaration": { "type": "google_search" },
+ "price": {
+ "unit": "search",
+ "usd_per_1k": 14,
+ "as_of": "2026-10-27",
+ "url": "https://ai.google.dev/gemini-api/docs/google-search#pricing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "match": { "prefix": "gemini-4" },
+ "wire_efforts": null,
+ "hosted_tools": {
+ "google": {
+ "web_search": {
+ "declaration": { "type": "google_search" },
+ "price": {
+ "unit": "search",
+ "usd_per_1k": 14,
+ "as_of": "2026-10-27",
+ "url": "https://ai.google.dev/gemini-api/docs/google-search#pricing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "match": { "id": "gemini-flash-latest" },
+ "wire_efforts": null,
+ "hosted_tools": {
+ "google": {
+ "web_search": {
+ "declaration": { "type": "google_search" },
+ "price": {
+ "unit": "search",
+ "usd_per_1k": 14,
+ "as_of": "2026-10-27",
+ "url": "https://ai.google.dev/gemini-api/docs/google-search#pricing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "match": { "id": "gemini-flash-lite-latest" },
+ "wire_efforts": null,
+ "hosted_tools": {
+ "google": {
+ "web_search": {
+ "declaration": { "type": "google_search" },
+ "price": {
+ "unit": "search",
+ "usd_per_1k": 14,
+ "as_of": "2026-10-27",
+ "url": "https://ai.google.dev/gemini-api/docs/google-search#pricing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "match": { "id": "gemini-pro-latest" },
+ "wire_efforts": null,
+ "hosted_tools": {
+ "google": {
+ "web_search": {
+ "declaration": { "type": "google_search" },
+ "price": {
+ "unit": "search",
+ "usd_per_1k": 14,
+ "as_of": "2026-10-27",
+ "url": "https://ai.google.dev/gemini-api/docs/google-search#pricing"
+ }
+ }
+ }
+ }
+ }
+ ],
"image_models": [
{
"id": "gemini-2.5-flash-image",
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index d0282ddd3..a3d1ab193 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -2281,6 +2281,10 @@ _REJECTION_MESSAGE_SCAN_CHARS = 2000
_INVALID_VALUE_MESSAGE = re.compile(r"Invalid value: '([A-Za-z0-9_.-]{1,64})'")
_UNSUPPORTED_TOOL_TYPE_MESSAGE = re.compile(r"Unsupported tool type: ([A-Za-z0-9_.-]{1,64})")
_INVALID_ENCRYPTED_CONTENT_MESSAGE = re.compile(r"Invalid encrypted_content in ([a-z_]{1,64}) block")
+# Gemini's refusal of Google Search on a model that cannot run it next to functions (measured 2026-10-27 on
+# gemini-2.5-flash and gemini-3-pro-image-preview: "Tool call context circulation is not enabled for models/…"),
+# named by the overlay's declaration type.
+_GOOGLE_SEARCH_REFUSAL_MESSAGE = re.compile(r"Tool call context circulation is not enabled")
def _upstream_rejection(
@@ -2333,7 +2337,9 @@ def _upstream_rejection(
error_type=token(error_type),
param=token(fields.get("param")),
invalid_value=named(_INVALID_VALUE_MESSAGE),
- unsupported_tool_type=named(_UNSUPPORTED_TOOL_TYPE_MESSAGE),
+ unsupported_tool_type=named(_UNSUPPORTED_TOOL_TYPE_MESSAGE) or (
+ "google_search" if _GOOGLE_SEARCH_REFUSAL_MESSAGE.search(text) else None
+ ),
invalid_encrypted_content_block=named(_INVALID_ENCRYPTED_CONTENT_MESSAGE),
)