The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/adapters): simplify gemini, vertex, moonshot adapters (-607 LOC)
Teknium1db2452272c5
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 821ae6b6ce3..31871509c75 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -1,17 +1,11 @@"""OpenAI-compatible facade over Google AI Studio's native Gemini API.Hermes keeps ``api_mode='chat_completions'`` for the ``gemini`` provider so the-main agent loop can keep using its existing OpenAI-shaped message flow.-This adapter is the transport shim that converts those OpenAI-style-``messages[]`` / ``tools[]`` requests into Gemini's native-``models/{model}:generateContent`` schema and converts the responses back.--Why this exists-----------------Google's OpenAI-compatible endpoint has been brittle for Hermes's multi-turn-agent/tool loop (auth churn, tool-call replay quirks, thought-signature-requirements). The native Gemini API is the canonical path and avoids the-OpenAI-compat layer entirely.+agent loop keeps its OpenAI-shaped message flow; this shim converts those+``messages[]`` / ``tools[]`` requests into ``models/{model}:generateContent``+payloads and converts the responses back. Google's OpenAI-compat endpoint has+been brittle for the multi-turn tool loop (auth churn, tool-call replay quirks,+thought-signature requirements); the native API is the canonical path."""from __future__ import annotations@@ -42,11 +36,9 @@ except Exception:DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"-# Published max output-token ceiling shared by every current Gemini text model-# (2.5 + 3.x: flash, flash-lite, pro). Used as the default when the caller-# passes max_tokens=None, because Gemini's native API otherwise applies a low-# internal default and truncates output (unlike OpenAI-compat endpoints where-# an omitted limit means full budget).+# Published max output-token ceiling shared by every current Gemini text model.+# Used when the caller passes max_tokens=None: unlike OpenAI-compat endpoints,+# Gemini's native API applies a low internal default and truncates output.GEMINI_DEFAULT_MAX_OUTPUT_TOKENS = 65535@@ -62,24 +54,16 @@ def bare_gemini_model_id(model: str) -> str:def _gemini_major_version(model: str) -> Optional[int]:"""Extract the major version from a Gemini model id (``gemini-3.6-flash`` → 3)."""- name = bare_gemini_model_id(model).lower()- match = re.match(r"gemini-(\d+)", name)- if not match:- return None- try:- return int(match.group(1))- except ValueError:- return None+ match = re.match(r"gemini-(\d+)", bare_gemini_model_id(model).lower())+ return int(match.group(1)) if match else Nonedef gemini_requires_tool_call_ids(model: str) -> bool:"""Whether functionCall/functionResponse parts must carry explicit ids.- Gemini 3+ models require explicit tool call IDs in replayed history —- without them, multi-tool turns can be rejected or mismatched. Older- Gemini models (2.x) reject unexpected ``id`` fields, so this is gated on- the major version. Mirrors earendil-works/pi#7494 (their fix for the same- class of bug in the google-shared converter).+ Gemini 3+ needs explicit ids so replayed parallel tool calls pair with+ their responses; Gemini 2.x rejects unexpected ``id`` fields, so gate on+ the major version."""version = _gemini_major_version(model)return version is not None and version >= 3@@ -88,140 +72,85 @@ def gemini_requires_tool_call_ids(model: str) -> bool:def is_native_gemini_base_url(base_url: str) -> bool:"""Return True when the endpoint speaks Gemini's native REST API."""normalized = str(base_url or "").strip().rstrip("/").lower()- if not normalized:- return False- if "generativelanguage.googleapis.com" not in normalized:- return False- return not normalized.endswith("/openai")+ return "generativelanguage.googleapis.com" in normalized and not normalized.endswith("/openai")def probe_gemini_tier(- api_key: str,- base_url: str = DEFAULT_GEMINI_BASE_URL,- *,- model: str = "gemini-3.7-flash",- timeout: float = 10.0,+ api_key: str, base_url: str = DEFAULT_GEMINI_BASE_URL, *, model: str = "gemini-3.7-flash", timeout: float = 10.0) -> str:- """Probe a Google AI Studio API key and return its tier.-- Returns one of:-- - ``"free"`` -- key is on the free tier (unusable with Hermes)- - ``"paid"`` -- key is on a paid tier- - ``"unknown"`` -- probe failed; callers should proceed without blocking.- """+ """Probe a Google AI Studio API key; return ``"free"``, ``"paid"`` or+ ``"unknown"`` (probe failed — callers should proceed without blocking)."""key = (api_key or "").strip()if not key:return "unknown"- normalized_base = str(base_url or DEFAULT_GEMINI_BASE_URL).strip().rstrip("/")- if not normalized_base:- normalized_base = DEFAULT_GEMINI_BASE_URL+ normalized_base = str(base_url or DEFAULT_GEMINI_BASE_URL).strip().rstrip("/") or DEFAULT_GEMINI_BASE_URLif normalized_base.lower().endswith("/openai"):normalized_base = normalized_base[: -len("/openai")]- url = f"{normalized_base}/models/{model}:generateContent"- payload = {- "contents": [{"role": "user", "parts": [{"text": "hi"}]}],- "generationConfig": {"maxOutputTokens": 1},- }-+ payload = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}], "generationConfig": {"maxOutputTokens": 1}}try:with httpx.Client(timeout=timeout) as client:resp = client.post(- url,+ f"{normalized_base}/models/{model}:generateContent",params={"key": key},json=payload,- headers={- "Content-Type": "application/json",- "X-Goog-Api-Client": f"hermes-agent/{_HERMES_VERSION}",- },+ headers={"Content-Type": "application/json", "X-Goog-Api-Client": f"hermes-agent/{_HERMES_VERSION}"},)except Exception as exc:logger.debug("probe_gemini_tier: network error: %s", exc)return "unknown"- headers_lower = {k.lower(): v for k, v in resp.headers.items()}- rpd_header = headers_lower.get("x-ratelimit-limit-requests-per-day")+ rpd_header = {k.lower(): v for k, v in resp.headers.items()}.get("x-ratelimit-limit-requests-per-day")if rpd_header:+ # Free-tier daily caps top out at 1000 (flash-lite); Tier 1 starts ~1500+.try:- rpd_val = int(rpd_header)+ return "free" if int(rpd_header) <= 1000 else "paid"except (TypeError, ValueError):- rpd_val = None- # Published free-tier daily caps (Dec 2025):- # gemini-2.5-pro: 100, gemini-2.5-flash: 250, flash-lite: 1000- # Tier 1 starts at ~1500+ for Flash. We treat <= 1000 as free.- if rpd_val is not None and rpd_val <= 1000:- return "free"- if rpd_val is not None and rpd_val > 1000:- return "paid"+ passif resp.status_code == 429:- body_text = ""try:body_text = resp.text or ""except Exception:body_text = ""- if "free_tier" in body_text.lower():- return "free"- return "paid"-- if 200 <= resp.status_code < 300:- return "paid"-- return "unknown"+ return "free" if "free_tier" in body_text.lower() else "paid"+ return "paid" if 200 <= resp.status_code < 300 else "unknown"def is_free_tier_quota_error(error_message: str) -> bool:"""Return True when a Gemini 429 message indicates free-tier exhaustion."""- if not error_message:- return False- return "free_tier" in error_message.lower()+ return bool(error_message) and "free_tier" in error_message.lower()_FREE_TIER_GUIDANCE = (- "\n\nYour Google API key is on the free tier (a few hundred requests/day "- "for Gemini Flash models). Hermes typically makes 3-10 API calls per user turn, "- "so the free tier is exhausted in a handful of messages and cannot sustain "- "an agent session. Enable billing on your Google Cloud project and "- "regenerate the key in a billing-enabled project: "- "https://aistudio.google.com/apikey"+ "\n\nYour Google API key is on the free tier (a few hundred requests/day for Gemini Flash models). "+ "Hermes typically makes 3-10 API calls per user turn, so the free tier is exhausted in a handful of "+ "messages and cannot sustain an agent session. Enable billing on your Google Cloud project and "+ "regenerate the key in a billing-enabled project: https://aistudio.google.com/apikey")-def is_standard_key_auth_error(- status: int, error_message: str, reason: str = ""-) -> bool:+def is_standard_key_auth_error(status: int, error_message: str, reason: str = "") -> bool:"""Return True when a Gemini 401 indicates Google rejected the key TYPE.- Google began rejecting unrestricted legacy "Standard" Google Cloud API- keys on the Gemini API on June 19, 2026, and ALL Standard keys stop- working in September 2026. The rejection surfaces as a misleading 401- telling the user to supply an OAuth 2 access token ("Request had invalid- authentication credentials. Expected OAuth 2 access token, login cookie- or other valid authentication credential."), optionally carrying- ``google.rpc.ErrorInfo`` reason ``ACCESS_TOKEN_TYPE_UNSUPPORTED``.-- Scoped narrowly so a plain bad key (reason ``API_KEY_INVALID``,- "API key not valid") keeps its existing message.+ Google rejects legacy "Standard" Google Cloud API keys with a misleading+ 401 asking for an OAuth 2 access token, optionally carrying ErrorInfo+ reason ``ACCESS_TOKEN_TYPE_UNSUPPORTED``. Scoped narrowly so a plain bad+ key (``API_KEY_INVALID``) keeps its existing message."""if status != 401:return False- if reason == "ACCESS_TOKEN_TYPE_UNSUPPORTED":- return True- return "expected oauth 2 access token" in (error_message or "").lower()+ return reason == "ACCESS_TOKEN_TYPE_UNSUPPORTED" or "expected oauth 2 access token" in (error_message or "").lower()_STANDARD_KEY_GUIDANCE = (- "\n\nGoogle Gemini rejected this API key's type — you do NOT need OAuth. "- "Google began rejecting legacy 'Standard' Google Cloud keys for the "- "Gemini API on June 19, 2026, and all Standard keys stop working in "- "September 2026. Open https://aistudio.google.com/api-keys, check the "- "key's type and status, and create a replacement Gemini API key (or, as "- "a temporary bridge, restrict the Standard key to "- "generativelanguage.googleapis.com). Then update GEMINI_API_KEY / "- "GOOGLE_API_KEY in ~/.hermes/.env and restart your session. "- "Details: https://ai.google.dev/gemini-api/docs/api-key"+ "\n\nGoogle Gemini rejected this API key's type — you do NOT need OAuth. Google began rejecting legacy "+ "'Standard' Google Cloud keys for the Gemini API on June 19, 2026, and all Standard keys stop working in "+ "September 2026. Open https://aistudio.google.com/api-keys, check the key's type and status, and create a "+ "replacement Gemini API key (or, as a temporary bridge, restrict the Standard key to "+ "generativelanguage.googleapis.com). Then update GEMINI_API_KEY / GOOGLE_API_KEY in ~/.hermes/.env and "+ "restart your session. Details: https://ai.google.dev/gemini-api/docs/api-key")@@ -229,13 +158,8 @@ class GeminiAPIError(Exception):"""Error shape compatible with Hermes retry/error classification."""def __init__(- self,- message: str,- *,- code: str = "gemini_api_error",- status_code: Optional[int] = None,- response: Optional[httpx.Response] = None,- retry_after: Optional[float] = None,+ self, message: str, *, code: str = "gemini_api_error", status_code: Optional[int] = None,+ response: Optional[httpx.Response] = None, retry_after: Optional[float] = None,details: Optional[Dict[str, Any]] = None,) -> None:super().__init__(message)@@ -256,10 +180,8 @@ def _coerce_content_to_text(content: Any) -> str:for part in content:if isinstance(part, str):pieces.append(part)- elif isinstance(part, dict) and part.get("type") == "text":- text = part.get("text")- if isinstance(text, str):- pieces.append(text)+ elif isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str):+ pieces.append(part["text"])return "\n".join(pieces)return str(content)@@ -291,14 +213,7 @@ def _extract_multimodal_parts(content: Any) -> List[Dict[str, Any]]:raw = base64.b64decode(encoded)except Exception:continue- parts.append(- {- "inlineData": {- "mimeType": mime,- "data": base64.b64encode(raw).decode("ascii"),- }- }- )+ parts.append({"inlineData": {"mimeType": mime, "data": base64.b64encode(raw).decode("ascii")}})return parts@@ -307,28 +222,22 @@ def _tool_call_extra_signature(tool_call: Dict[str, Any]) -> Optional[str]:if not isinstance(extra, dict):return Nonegoogle = extra.get("google") or extra.get("thought_signature")- if isinstance(google, dict):- sig = google.get("thought_signature") or google.get("thoughtSignature")- return str(sig) if isinstance(sig, str) and sig else None- if isinstance(google, str) and google:- return google- return None+ sig = (google.get("thought_signature") or google.get("thoughtSignature")) if isinstance(google, dict) else google+ return sig if isinstance(sig, str) and sig else None# Stands in for a model turn that never arrived (stream failure / interrupt /# quota fallback) when history leaves a human user text turn directly after a-# tool-result turn. Interposed between the two user contents so the request-# stays alternation-valid while the user's message remains a turn of its own.-# Mirrors gemini-cli's INTERRUPTED_RESPONSE_PLACEHOLDER (gemini-cli#28700).-_INTERRUPTED_RESPONSE_PLACEHOLDER = (- "[The previous response was interrupted before it completed.]"-)+# tool-result turn, keeping the request alternation-valid while the user's+# message remains a turn of its own (mirrors gemini-cli's placeholder repair).+_INTERRUPTED_RESPONSE_PLACEHOLDER = "[The previous response was interrupted before it completed.]"-def _translate_tool_call_to_gemini(- tool_call: Dict[str, Any],- include_ids: bool = False,-) -> Dict[str, Any]:+def _tool_call_id(tool_call: Dict[str, Any]) -> str:+ return str(tool_call.get("id") or tool_call.get("call_id") or "")+++def _translate_tool_call_to_gemini(tool_call: Dict[str, Any], include_ids: bool = False) -> Dict[str, Any]:fn = tool_call.get("function") or {}args_raw = fn.get("arguments", "")try:@@ -338,116 +247,68 @@ def _translate_tool_call_to_gemini(if not isinstance(args, dict):args = {"_value": args}- part: Dict[str, Any] = {- "functionCall": {- "name": str(fn.get("name") or ""),- "args": args,- }- }- if include_ids:- # Gemini 3+ requires explicit tool call IDs so replayed parallel tool- # calls pair with their functionResponses (earendil-works/pi#7494).- tool_call_id = str(tool_call.get("id") or tool_call.get("call_id") or "")- if tool_call_id:- part["functionCall"]["id"] = tool_call_id- thought_signature = _tool_call_extra_signature(tool_call)- # Fallback sentinel for cross-provider tool_calls (e.g. fallback from- # xAI/Anthropic to Gemini, where the original tool_call carries no- # Gemini thoughtSignature). Mirrors gemini_cloudcode_adapter.py:106.- # Without this, Gemini 3 thinking models reject replayed history with- # 400 INVALID_ARGUMENT on the missing thoughtSignature.- part["thoughtSignature"] = thought_signature or "skip_thought_signature_validator"+ part: Dict[str, Any] = {"functionCall": {"name": str(fn.get("name") or ""), "args": args}}+ if include_ids and _tool_call_id(tool_call):+ part["functionCall"]["id"] = _tool_call_id(tool_call)+ # Cross-provider tool_calls (e.g. fallback from xAI/Anthropic) carry no+ # Gemini thoughtSignature; without the sentinel, Gemini 3 thinking models+ # reject replayed history with 400 INVALID_ARGUMENT.+ part["thoughtSignature"] = _tool_call_extra_signature(tool_call) or "skip_thought_signature_validator"return partdef _looks_like_json_schema(node: Any) -> bool:- """True if a parsed value contains a JSON-Schema-style ``$ref`` pointer.-- Gemini 3 resolves ``$ref``/``$defs`` references inside a- functionResponse.response payload and rejects unknown pointers with- HTTP 400 INVALID_ARGUMENT. A tool result that is itself a JSON Schema- (e.g. the output of ``tool_describe`` for an MCP tool) must therefore be- forwarded as opaque text rather than as a structured response.-- Detection is deliberately structural, not semantic: any ``$ref`` value- shaped like a JSON pointer (``#/...``) demotes the whole result. Non-schema- data that happens to carry such a pointer is a false positive, but the raw- content is preserved verbatim either way, so the cost is fidelity-free.- The recursive walk is O(n) over the parsed value; tool-result payloads are- small, so this is negligible per turn.+ """True if a parsed value contains a JSON-Schema-style ``$ref`` pointer (``#/...``).++ Gemini 3 resolves ``$ref``/``$defs`` inside a functionResponse.response+ payload and rejects unknown pointers with HTTP 400, so a tool result that+ is itself a JSON Schema (e.g. ``tool_describe`` output) must be forwarded+ as opaque text. Detection is structural: false positives only lose the+ structured shape, never the content."""if isinstance(node, dict):- for key, value in node.items():- if key == "$ref" and isinstance(value, str) and value.startswith("#/"):- return True- if _looks_like_json_schema(value):- return True- elif isinstance(node, list):- return any(_looks_like_json_schema(item) for item in node)- return False+ return any(+ (key == "$ref" and isinstance(value, str) and value.startswith("#/")) or _looks_like_json_schema(value)+ for key, value in node.items()+ )+ return isinstance(node, list) and any(_looks_like_json_schema(item) for item in node)def _translate_tool_result_to_gemini(- message: Dict[str, Any],- tool_name_by_call_id: Optional[Dict[str, str]] = None,- include_ids: bool = False,- *,- is_gemini3: bool = False,+ message: Dict[str, Any], tool_name_by_call_id: Optional[Dict[str, str]] = None, include_ids: bool = False,+ *, is_gemini3: bool = False,) -> Dict[str, Any]:tool_name_by_call_id = tool_name_by_call_id or {}tool_call_id = str(message.get("tool_call_id") or "")- # A tool result can carry the unwrapped internal tool name (for example,- # an MCP tool invoked through the `tool_call` bridge). Gemini requires- # functionResponse.name to echo the matching functionCall.name, so the- # call-id mapping must take precedence over the internal result name.- name = str(- tool_name_by_call_id.get(tool_call_id)- or message.get("name")- or tool_call_id- or "tool"- )+ # Gemini requires functionResponse.name to echo the matching+ # functionCall.name, so the call-id mapping beats the result's own name+ # (which may be an unwrapped internal name, e.g. an MCP tool via `tool_call`).+ name = str(tool_name_by_call_id.get(tool_call_id) or message.get("name") or tool_call_id or "tool")raw_content = message.get("content")content = _coerce_content_to_text(raw_content)try:parsed = json.loads(content) if content.strip().startswith(("{", "[")) else Noneexcept json.JSONDecodeError:parsed = None- # Gemini 3 resolves JSON-Schema ``$ref`` pointers inside a- # functionResponse.response payload and rejects unknown references with- # HTTP 400 INVALID_ARGUMENT ("referenced name '#/$defs/...' does not match- # a display_name"; see vercel/ai#14369). A tool result that is itself a- # JSON Schema (e.g. tool_describe output for an MCP tool) must therefore- # be forwarded as opaque text, not as a structured response.- if isinstance(parsed, dict) and _looks_like_json_schema(parsed):- parsed = None- response = parsed if isinstance(parsed, dict) else {"output": content}- function_response: Dict[str, Any] = {- "name": name,- "response": response,- }+ response = parsed if isinstance(parsed, dict) and not _looks_like_json_schema(parsed) else {"output": content}+ function_response: Dict[str, Any] = {"name": name, "response": response}if include_ids and tool_call_id:function_response["id"] = tool_call_id- # Gemini 3.x supports embedding images directly inside- # functionResponse.parts (Google's recommended shape for multimodal tool- # results — see "Multimodal function responses" in the Gemini docs).- # Gemini 2.x rejects the field, so only attach inlineData when the target- # model supports it — otherwise the vision tool result is silently- # downgraded to text-only.+ # Gemini 3.x accepts images inside functionResponse.parts; 2.x rejects+ # the field, so older models get the text-only downgrade.if is_gemini3:- image_parts = [- p for p in _extract_multimodal_parts(raw_content)- if "inlineData" in p- ]+ image_parts = [p for p in _extract_multimodal_parts(raw_content) if "inlineData" in p]if image_parts:function_response["parts"] = image_partsreturn {"functionResponse": function_response}+def _has_function_response(content: Dict[str, Any]) -> bool:+ return any(isinstance(part, dict) and "functionResponse" in part for part in content.get("parts", []))++def _build_gemini_contents(- messages: List[Dict[str, Any]],- include_tool_call_ids: bool = False,- *,- is_gemini3: bool = False,+ messages: List[Dict[str, Any]], include_tool_call_ids: bool = False, *, is_gemini3: bool = False) -> tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:system_text_parts: List[str] = []contents: List[Dict[str, Any]] = []@@ -461,99 +322,52 @@ def _build_gemini_contents(if role == "system":system_text_parts.append(_coerce_content_to_text(msg.get("content")))continue-if role in {"tool", "function"}:- contents.append(- {- "role": "user",- "parts": [- _translate_tool_result_to_gemini(- msg,- tool_name_by_call_id=tool_name_by_call_id,- include_ids=include_tool_call_ids,- is_gemini3=is_gemini3,- )- ],- }+ part = _translate_tool_result_to_gemini(+ msg, tool_name_by_call_id=tool_name_by_call_id, include_ids=include_tool_call_ids, is_gemini3=is_gemini3)+ contents.append({"role": "user", "parts": [part]})continue-- gemini_role = "model" if role == "assistant" else "user"- parts: List[Dict[str, Any]] = []-- content_parts = _extract_multimodal_parts(msg.get("content"))- parts.extend(content_parts)-+ parts = _extract_multimodal_parts(msg.get("content"))tool_calls = msg.get("tool_calls") or []- if isinstance(tool_calls, list):- for tool_call in tool_calls:- if isinstance(tool_call, dict):- tool_call_id = str(tool_call.get("id") or tool_call.get("call_id") or "")- tool_name = str(((tool_call.get("function") or {}).get("name") or ""))- if tool_call_id and tool_name:- tool_name_by_call_id[tool_call_id] = tool_name- parts.append(- _translate_tool_call_to_gemini(- tool_call, include_ids=include_tool_call_ids- )- )+ for tool_call in tool_calls if isinstance(tool_calls, list) else []:+ if not isinstance(tool_call, dict):+ continue+ tool_call_id = _tool_call_id(tool_call)+ tool_name = str(((tool_call.get("function") or {}).get("name") or ""))+ if tool_call_id and tool_name:+ tool_name_by_call_id[tool_call_id] = tool_name+ parts.append(_translate_tool_call_to_gemini(tool_call, include_ids=include_tool_call_ids))if parts:- contents.append({"role": gemini_role, "parts": parts})-- # Compatibility contract for native Gemini generateContent:- # 1) Same-role adjacent contents still merge in general (strict user/model- # alternation for ordinary text turns and parallel tool-result grouping;- # consecutive same-role contents are rejected with HTTP 400 "Please- # ensure that multiturn requests alternate between user and model").- # 2) Exception: do NOT fuse a human user text turn into a preceding user- # content that only carries functionResponse parts (or vice versa).- # Gemini 3 accepts that fold with HTTP 200 but then reads the trailing- # text as a continuation of the tool result — it returns an empty- # candidate or "finishes the user's sentence" instead of answering- # (same defect gemini-cli fixed in google-gemini/gemini-cli#28700).- # 3) Because rule 1's HTTP 400 makes two consecutive user contents unsafe- # to emit (#55125 — the reason this merge exists), the split pair is- # kept API-valid by interposing a placeholder model turn between the- # functionResponse content and the human text content, mirroring- # gemini-cli's INTERRUPTED_RESPONSE_PLACEHOLDER repair.- # 4) Parallel tool results (functionResponse + functionResponse) still- # merge into one user content — only mixed functionResponse/text is- # kept apart.+ contents.append({"role": "model" if role == "assistant" else "user", "parts": parts})++ # Alternation contract for generateContent:+ # 1) Adjacent same-role contents merge (consecutive same-role contents are+ # rejected with HTTP 400 "multiturn requests [must] alternate").+ # 2) Exception: never fuse a human user text turn into a preceding user+ # content that only carries functionResponse parts (or vice versa) —+ # Gemini 3 accepts the fold but reads the text as a continuation of the+ # tool result and returns an empty candidate. Parallel tool results+ # (functionResponse + functionResponse) still merge.+ # 3) The split pair is kept API-valid by interposing a placeholder model+ # turn between the functionResponse content and the human text.merged_contents: List[Dict[str, Any]] = []for content in contents:- same_role = bool(- merged_contents and merged_contents[-1]["role"] == content["role"]- )- if same_role and content["role"] == "user":- previous_has_function_response = any(- isinstance(part, dict) and "functionResponse" in part- for part in merged_contents[-1].get("parts", [])- )- current_has_function_response = any(- isinstance(part, dict) and "functionResponse" in part- for part in content.get("parts", [])- )- if previous_has_function_response != current_has_function_response:- same_role = False- merged_contents.append(- {- "role": "model",- "parts": [{"text": _INTERRUPTED_RESPONSE_PLACEHOLDER}],- }- )+ prev = merged_contents[-1] if merged_contents else None+ same_role = prev is not None and prev["role"] == content["role"]+ if same_role and content["role"] == "user" and _has_function_response(prev) != _has_function_response(content):+ same_role = False+ merged_contents.append({"role": "model", "parts": [{"text": _INTERRUPTED_RESPONSE_PLACEHOLDER}]})if same_role:merged_contents[-1]["parts"].extend(content["parts"])else:merged_contents.append(content)- contents = merged_contents- system_instruction = Nonejoined_system = "\n".join(part for part in system_text_parts if part).strip()- if joined_system:- system_instruction = {"role": "system", "parts": [{"text": joined_system}]}- return contents, system_instruction+ system_instruction = {"role": "system", "parts": [{"text": joined_system}]} if joined_system else None+ return merged_contents, system_instructiondef _translate_tools_to_gemini(tools: Any) -> List[Dict[str, Any]]:@@ -561,38 +375,26 @@ def _translate_tools_to_gemini(tools: Any) -> List[Dict[str, Any]]:return []declarations: List[Dict[str, Any]] = []for tool in tools:- if not isinstance(tool, dict):- continue- fn = tool.get("function") or {}- if not isinstance(fn, dict):+ fn = (tool.get("function") or {}) if isinstance(tool, dict) else None+ if not isinstance(fn, dict) or not (isinstance(fn.get("name"), str) and fn["name"]):continue- name = fn.get("name")- if not isinstance(name, str) or not name:- continue- decl: Dict[str, Any] = {"name": name}- description = fn.get("description")- if isinstance(description, str) and description:- decl["description"] = description- parameters = fn.get("parameters")- if isinstance(parameters, dict):- decl["parameters"] = sanitize_gemini_tool_parameters(parameters)+ decl: Dict[str, Any] = {"name": fn["name"]}+ if isinstance(fn.get("description"), str) and fn["description"]:+ decl["description"] = fn["description"]+ if isinstance(fn.get("parameters"), dict):+ decl["parameters"] = sanitize_gemini_tool_parameters(fn["parameters"])declarations.append(decl)return [{"functionDeclarations": declarations}] if declarations else []+_TOOL_CHOICE_MODES = {"auto": "AUTO", "required": "ANY", "none": "NONE"}++def _translate_tool_choice_to_gemini(tool_choice: Any) -> Optional[Dict[str, Any]]:- if tool_choice is None:- return None- if isinstance(tool_choice, str):- if tool_choice == "auto":- return {"functionCallingConfig": {"mode": "AUTO"}}- if tool_choice == "required":- return {"functionCallingConfig": {"mode": "ANY"}}- if tool_choice == "none":- return {"functionCallingConfig": {"mode": "NONE"}}+ if isinstance(tool_choice, str) and tool_choice in _TOOL_CHOICE_MODES:+ return {"functionCallingConfig": {"mode": _TOOL_CHOICE_MODES[tool_choice]}}if isinstance(tool_choice, dict):- fn = tool_choice.get("function") or {}- name = fn.get("name")+ name = (tool_choice.get("function") or {}).get("name")if isinstance(name, str) and name:return {"functionCallingConfig": {"mode": "ANY", "allowedFunctionNames": [name]}}return None@@ -615,13 +417,11 @@ def _normalize_thinking_config(config: Any) -> Optional[Dict[str, Any]]:def _thinking_requests_output_headroom(thinking_config: Any) -> bool:- """Return True when Gemini will spend output tokens on thinking.+ """True when Gemini will spend output tokens on thinking.- Gemini bills thought tokens against ``maxOutputTokens``. A global- Hermes ``max_tokens`` of 4096/16384 is enough for visible text, but- Ultra/high thinking can consume the entire budget and leave- ``finishReason=MAX_TOKENS`` with no complete answer. Continuations- then abort after 4 retries.+ Thought tokens bill against ``maxOutputTokens``; a global 4096/16384+ ``max_tokens`` can be consumed entirely by high thinking, leaving+ ``finishReason=MAX_TOKENS`` with no answer."""normalized = _normalize_thinking_config(thinking_config)if not normalized:@@ -629,27 +429,18 @@ def _thinking_requests_output_headroom(thinking_config: Any) -> bool:if normalized.get("includeThoughts") is False:return "thinkingLevel" in normalized or bool(normalized.get("thinkingBudget"))budget = normalized.get("thinkingBudget")- if isinstance(budget, int) and budget <= 0 and "thinkingLevel" not in normalized:- return False- return True+ return not (isinstance(budget, int) and budget <= 0 and "thinkingLevel" not in normalized)-def _effective_gemini_max_output_tokens(- max_tokens: Optional[int], thinking_config: Any-) -> int:- """Resolve native ``maxOutputTokens``.-- Gemini's generateContent API does not treat an omitted cap as- unlimited — it applies a low internal default and truncates. When- thinking is enabled, also raise a too-small explicit cap to the- published 65,535 ceiling so thought tokens do not starve the answer.- """- if max_tokens is None:- return GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+def _effective_gemini_max_output_tokens(max_tokens: Optional[int], thinking_config: Any) -> int:+ """Resolve native ``maxOutputTokens``: an omitted/invalid cap becomes the+ published ceiling (Gemini truncates on its low internal default), and an+ explicit cap is raised to that ceiling when thinking is enabled so thought+ tokens do not starve the answer."""try:requested = int(max_tokens)except (TypeError, ValueError):- return GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ requested = 0if requested <= 0:return GEMINI_DEFAULT_MAX_OUTPUT_TOKENSif _thinking_requests_output_headroom(thinking_config):@@ -658,106 +449,92 @@ def _effective_gemini_max_output_tokens(def build_gemini_request(- *,- messages: List[Dict[str, Any]],- tools: Any = None,- tool_choice: Any = None,- temperature: Optional[float] = None,- max_tokens: Optional[int] = None,- top_p: Optional[float] = None,- stop: Any = None,- thinking_config: Any = None,+ *, messages: List[Dict[str, Any]], tools: Any = None, tool_choice: Any = None, temperature: Optional[float] = None,+ max_tokens: Optional[int] = None, top_p: Optional[float] = None, stop: Any = None, thinking_config: Any = None,model: str = "",) -> Dict[str, Any]:- version = _gemini_major_version(model)- is_gemini3 = version is not None and version >= 3- contents, system_instruction = _build_gemini_contents(- messages,- include_tool_call_ids=gemini_requires_tool_call_ids(model),- is_gemini3=is_gemini3,- )+ # Gemini 3+ both requires tool-call ids and accepts multimodal functionResponse parts.+ is_gemini3 = gemini_requires_tool_call_ids(model)+ contents, system_instruction = _build_gemini_contents(messages, include_tool_call_ids=is_gemini3, is_gemini3=is_gemini3)request: Dict[str, Any] = {"contents": contents}- if system_instruction:- request["systemInstruction"] = system_instruction-- gemini_tools = _translate_tools_to_gemini(tools)- if gemini_tools:- request["tools"] = gemini_tools-- tool_config = _translate_tool_choice_to_gemini(tool_choice)- if tool_config:- request["toolConfig"] = tool_config+ for key, value in (+ ("systemInstruction", system_instruction),+ ("tools", _translate_tools_to_gemini(tools)),+ ("toolConfig", _translate_tool_choice_to_gemini(tool_choice)),+ ):+ if value:+ request[key] = valuegeneration_config: Dict[str, Any] = {}if temperature is not None:generation_config["temperature"] = temperature- generation_config["maxOutputTokens"] = _effective_gemini_max_output_tokens(- max_tokens, thinking_config- )+ generation_config["maxOutputTokens"] = _effective_gemini_max_output_tokens(max_tokens, thinking_config)if top_p is not None:generation_config["topP"] = top_pif stop:generation_config["stopSequences"] = stop if isinstance(stop, list) else [str(stop)]- normalized_thinking = _normalize_thinking_config(thinking_config)- if normalized_thinking:+ if normalized_thinking := _normalize_thinking_config(thinking_config):generation_config["thinkingConfig"] = normalized_thinking- if generation_config:- request["generationConfig"] = generation_config-+ request["generationConfig"] = generation_configreturn request+_FINISH_REASON_MAP = {+ "STOP": "stop", "MAX_TOKENS": "length", "SAFETY": "content_filter", "RECITATION": "content_filter", "OTHER": "stop",+}++def _map_gemini_finish_reason(reason: str) -> str:- mapping = {- "STOP": "stop",- "MAX_TOKENS": "length",- "SAFETY": "content_filter",- "RECITATION": "content_filter",- "OTHER": "stop",- }- return mapping.get(str(reason or "").upper(), "stop")+ return _FINISH_REASON_MAP.get(str(reason or "").upper(), "stop")def _tool_call_extra_from_part(part: Dict[str, Any]) -> Optional[Dict[str, Any]]:sig = part.get("thoughtSignature")- if isinstance(sig, str) and sig:- return {"google": {"thought_signature": sig}}- return None+ return {"google": {"thought_signature": sig}} if isinstance(sig, str) and sig else None-def _empty_response(model: str) -> SimpleNamespace:- message = SimpleNamespace(- role="assistant",- content="",- tool_calls=None,- reasoning=None,- reasoning_content=None,- reasoning_details=None,+def _new_call_id(fc: Dict[str, Any]) -> str:+ """Echo Gemini's functionCall id when present, else mint an OpenAI-style one."""+ fc_id = fc.get("id")+ return fc_id if isinstance(fc_id, str) and fc_id else f"call_{uuid.uuid4().hex[:12]}"+++def _dump_call_args(fc: Dict[str, Any], **kwargs: Any) -> str:+ try:+ return json.dumps(fc.get("args") or {}, ensure_ascii=False, **kwargs)+ except (TypeError, ValueError):+ return "{}"+++def _usage_from_metadata(usage_meta: Dict[str, Any]) -> SimpleNamespace:+ return SimpleNamespace(+ prompt_tokens=int(usage_meta.get("promptTokenCount") or 0),+ completion_tokens=int(usage_meta.get("candidatesTokenCount") or 0),+ total_tokens=int(usage_meta.get("totalTokenCount") or 0),+ prompt_tokens_details=SimpleNamespace(cached_tokens=int(usage_meta.get("cachedContentTokenCount") or 0)),)- choice = SimpleNamespace(index=0, message=message, finish_reason="stop")- usage = SimpleNamespace(- prompt_tokens=0,- completion_tokens=0,- total_tokens=0,- prompt_tokens_details=SimpleNamespace(cached_tokens=0),+++def _completion(model: str, message: SimpleNamespace, finish_reason: str, usage: SimpleNamespace) -> SimpleNamespace:+ return SimpleNamespace(+ id=f"chatcmpl-{uuid.uuid4().hex[:12]}", object="chat.completion", created=int(time.time()), model=model,+ choices=[SimpleNamespace(index=0, message=message, finish_reason=finish_reason)], usage=usage,)+++def _assistant_message(content: Any, tool_calls: Any, reasoning: Any) -> SimpleNamespace:return SimpleNamespace(- id=f"chatcmpl-{uuid.uuid4().hex[:12]}",- object="chat.completion",- created=int(time.time()),- model=model,- choices=[choice],- usage=usage,+ role="assistant", content=content, tool_calls=tool_calls,+ reasoning=reasoning, reasoning_content=reasoning, reasoning_details=None,)def translate_gemini_response(resp: Dict[str, Any], model: str) -> SimpleNamespace:candidates = resp.get("candidates") or []if not isinstance(candidates, list) or not candidates:- return _empty_response(model)-+ return _completion(model, _assistant_message("", None, None), "stop", _usage_from_metadata({}))cand = candidates[0] if isinstance(candidates[0], dict) else {}- content_obj = cand.get("content") if isinstance(cand, dict) else {}+ content_obj = cand.get("content")parts = content_obj.get("parts") if isinstance(content_obj, dict) else []text_pieces: List[str] = []@@ -775,19 +552,9 @@ def translate_gemini_response(resp: Dict[str, Any], model: str) -> SimpleNamespacontinuefc = part.get("functionCall")if isinstance(fc, dict) and fc.get("name"):- try:- args_str = json.dumps(fc.get("args") or {}, ensure_ascii=False)- except (TypeError, ValueError):- args_str = "{}"tool_call = SimpleNamespace(- id=(- str(fc["id"])- if isinstance(fc.get("id"), str) and fc.get("id")- else f"call_{uuid.uuid4().hex[:12]}"- ),- type="function",- index=index,- function=SimpleNamespace(name=str(fc["name"]), arguments=args_str),+ id=_new_call_id(fc), type="function", index=index,+ function=SimpleNamespace(name=str(fc["name"]), arguments=_dump_call_args(fc)),)extra_content = _tool_call_extra_from_part(part)if extra_content:@@ -795,33 +562,10 @@ def translate_gemini_response(resp: Dict[str, Any], model: str) -> SimpleNamespatool_calls.append(tool_call)finish_reason = "tool_calls" if tool_calls else _map_gemini_finish_reason(str(cand.get("finishReason") or ""))- usage_meta = resp.get("usageMetadata") or {}- usage = SimpleNamespace(- prompt_tokens=int(usage_meta.get("promptTokenCount") or 0),- completion_tokens=int(usage_meta.get("candidatesTokenCount") or 0),- total_tokens=int(usage_meta.get("totalTokenCount") or 0),- prompt_tokens_details=SimpleNamespace(- cached_tokens=int(usage_meta.get("cachedContentTokenCount") or 0),- ),- )- reasoning = "".join(reasoning_pieces) or None- message = SimpleNamespace(- role="assistant",- content="".join(text_pieces) if text_pieces else None,- tool_calls=tool_calls or None,- reasoning=reasoning,- reasoning_content=reasoning,- reasoning_details=None,- )- choice = SimpleNamespace(index=0, message=message, finish_reason=finish_reason)- return SimpleNamespace(- id=f"chatcmpl-{uuid.uuid4().hex[:12]}",- object="chat.completion",- created=int(time.time()),- model=model,- choices=[choice],- usage=usage,+ message = _assistant_message(+ "".join(text_pieces) if text_pieces else None, tool_calls or None, "".join(reasoning_pieces) or None)+ return _completion(model, message, finish_reason, _usage_from_metadata(resp.get("usageMetadata") or {}))class _GeminiStreamChunk(SimpleNamespace):@@ -829,48 +573,28 @@ class _GeminiStreamChunk(SimpleNamespace):def _make_stream_chunk(- *,- model: str,- content: str = "",- tool_call_delta: Optional[Dict[str, Any]] = None,- finish_reason: Optional[str] = None,- reasoning: str = "",+ *, model: str, content: str = "", tool_call_delta: Optional[Dict[str, Any]] = None,+ finish_reason: Optional[str] = None, reasoning: str = "",) -> _GeminiStreamChunk:- delta_kwargs: Dict[str, Any] = {- "role": "assistant",- "content": None,- "tool_calls": None,- "reasoning": None,- "reasoning_content": None,- }- if content:- delta_kwargs["content"] = content+ tool_calls = Noneif tool_call_delta is not None:tool_delta = SimpleNamespace(index=tool_call_delta.get("index", 0),id=tool_call_delta.get("id") or f"call_{uuid.uuid4().hex[:12]}",type="function",- function=SimpleNamespace(- name=tool_call_delta.get("name") or "",- arguments=tool_call_delta.get("arguments") or "",- ),+ function=SimpleNamespace(name=tool_call_delta.get("name") or "", arguments=tool_call_delta.get("arguments") or ""),)extra_content = tool_call_delta.get("extra_content")if isinstance(extra_content, dict):tool_delta.extra_content = extra_content- delta_kwargs["tool_calls"] = [tool_delta]- if reasoning:- delta_kwargs["reasoning"] = reasoning- delta_kwargs["reasoning_content"] = reasoning- delta = SimpleNamespace(**delta_kwargs)- choice = SimpleNamespace(index=0, delta=delta, finish_reason=finish_reason)+ tool_calls = [tool_delta]+ delta = SimpleNamespace(+ role="assistant", content=content or None, tool_calls=tool_calls,+ reasoning=reasoning or None, reasoning_content=reasoning or None,+ )return _GeminiStreamChunk(- id=f"chatcmpl-{uuid.uuid4().hex[:12]}",- object="chat.completion.chunk",- created=int(time.time()),- model=model,- choices=[choice],- usage=None,+ id=f"chatcmpl-{uuid.uuid4().hex[:12]}", object="chat.completion.chunk", created=int(time.time()), model=model,+ choices=[SimpleNamespace(index=0, delta=delta, finish_reason=finish_reason)], usage=None,)@@ -883,8 +607,6 @@ def _iter_sse_events(response: httpx.Response) -> Iterator[Dict[str, Any]]:while "\n" in buffer:line, buffer = buffer.split("\n", 1)line = line.rstrip("\r")- if not line:- continueif not line.startswith("data: "):continuedata = line[6:]@@ -904,7 +626,7 @@ def translate_stream_event(event: Dict[str, Any], model: str, tool_call_indices:if not candidates:return []cand = candidates[0] if isinstance(candidates[0], dict) else {}- parts = ((cand.get("content") or {}).get("parts") or []) if isinstance(cand, dict) else []+ parts = (cand.get("content") or {}).get("parts") or []chunks: List[_GeminiStreamChunk] = []for part_index, part in enumerate(parts):@@ -918,189 +640,108 @@ def translate_stream_event(event: Dict[str, Any], model: str, tool_call_indices:fc = part.get("functionCall")if isinstance(fc, dict) and fc.get("name"):name = str(fc["name"])- try:- args_str = json.dumps(fc.get("args") or {}, ensure_ascii=False, sort_keys=True)- except (TypeError, ValueError):- args_str = "{}"+ args_str = _dump_call_args(fc, sort_keys=True)thought_signature = part.get("thoughtSignature") if isinstance(part.get("thoughtSignature"), str) else ""call_key = json.dumps(- {- "part_index": part_index,- "name": name,- "thought_signature": thought_signature,- },- sort_keys=True,+ {"part_index": part_index, "name": name, "thought_signature": thought_signature}, sort_keys=True)slot = tool_call_indices.get(call_key)if slot is None:- slot = {- "index": len(tool_call_indices),- "id": (- str(fc["id"])- if isinstance(fc.get("id"), str) and fc.get("id")- else f"call_{uuid.uuid4().hex[:12]}"- ),- "last_arguments": "",- }+ slot = {"index": len(tool_call_indices), "id": _new_call_id(fc), "last_arguments": ""}tool_call_indices[call_key] = slot- emitted_arguments = args_str+ # Gemini re-sends the full args each event; emit only the new suffix.last_arguments = str(slot.get("last_arguments") or "")- if last_arguments:- if args_str == last_arguments:- emitted_arguments = ""- elif args_str.startswith(last_arguments):- emitted_arguments = args_str[len(last_arguments):]+ emitted_arguments = args_str[len(last_arguments):] if args_str.startswith(last_arguments) else args_strslot["last_arguments"] = args_str- chunks.append(- _make_stream_chunk(- model=model,- tool_call_delta={- "index": slot["index"],- "id": slot["id"],- "name": name,- "arguments": emitted_arguments,- "extra_content": _tool_call_extra_from_part(part),- },- )- )+ chunks.append(_make_stream_chunk(model=model, tool_call_delta={+ "index": slot["index"], "id": slot["id"], "name": name,+ "arguments": emitted_arguments, "extra_content": _tool_call_extra_from_part(part),+ }))finish_reason_raw = str(cand.get("finishReason") or "")if finish_reason_raw:- mapped = "tool_calls" if tool_call_indices else _map_gemini_finish_reason(finish_reason_raw)- finish_chunk = _make_stream_chunk(model=model, finish_reason=mapped)- # Attach usage from this event's usageMetadata so the streaming- # loop in run_agent.py can record token counts (mirrors the- # non-streaming path in translate_gemini_response).+ finish_chunk = _make_stream_chunk(+ model=model, finish_reason="tool_calls" if tool_call_indices else _map_gemini_finish_reason(finish_reason_raw)+ )+ # Carry usageMetadata on the finish chunk so the streaming loop can+ # record token counts like the non-streaming path does.usage_meta = event.get("usageMetadata") or {}if usage_meta:- finish_chunk.usage = SimpleNamespace(- prompt_tokens=int(usage_meta.get("promptTokenCount") or 0),- completion_tokens=int(usage_meta.get("candidatesTokenCount") or 0),- total_tokens=int(usage_meta.get("totalTokenCount") or 0),- prompt_tokens_details=SimpleNamespace(- cached_tokens=int(usage_meta.get("cachedContentTokenCount") or 0),- ),- )+ finish_chunk.usage = _usage_from_metadata(usage_meta)chunks.append(finish_chunk)return chunks-def gemini_http_error(- response: httpx.Response, *, body_text: Optional[str] = None-) -> GeminiAPIError:+_HTTP_ERROR_CODES = {401: "gemini_unauthorized", 429: "gemini_rate_limited", 404: "gemini_model_not_found"}+++def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = None) -> GeminiAPIError:status = response.status_code- body_json: Dict[str, Any] = {}if body_text is None:try:body_text = response.textexcept Exception:body_text = ""body_text = body_text or ""+ err_obj: Any = Noneif body_text:try:parsed = json.loads(body_text)- if isinstance(parsed, dict):- body_json = parsed+ err_obj = parsed.get("error") if isinstance(parsed, dict) else Noneexcept (ValueError, TypeError):- body_json = {}-- err_obj = body_json.get("error") if isinstance(body_json, dict) else None+ passif not isinstance(err_obj, dict):err_obj = {}err_status = str(err_obj.get("status") or "").strip()err_message = str(err_obj.get("message") or "").strip()- _raw_details = err_obj.get("details")- details_list = _raw_details if isinstance(_raw_details, list) else []+ details_list = err_obj.get("details")reason = ""- retry_after: Optional[float] = Nonemetadata: Dict[str, Any] = {}- for detail in details_list:- if not isinstance(detail, dict):- continue- type_url = str(detail.get("@type") or "")- if not reason and type_url.endswith("/google.rpc.ErrorInfo"):- reason_value = detail.get("reason")+ for detail in details_list if isinstance(details_list, list) else []:+ if isinstance(detail, dict) and not reason and str(detail.get("@type") or "").endswith("/google.rpc.ErrorInfo"):+ reason_value, md = detail.get("reason"), detail.get("metadata")if isinstance(reason_value, str):reason = reason_value- md = detail.get("metadata")if isinstance(md, dict):metadata = md++ retry_after: Optional[float] = Noneheader_retry = response.headers.get("Retry-After") or response.headers.get("retry-after")if header_retry:try:retry_after = float(header_retry)except (TypeError, ValueError):- retry_after = None-- code = f"gemini_http_{status}"- if status == 401:- code = "gemini_unauthorized"- elif status == 429:- code = "gemini_rate_limited"- elif status == 404:- code = "gemini_model_not_found"+ passif err_message:message = f"Gemini HTTP {status} ({err_status or 'error'}): {err_message}"else:message = f"Gemini returned HTTP {status}: {body_text[:500]}"-- # Free-tier quota exhaustion -> append actionable guidance so users who- # bypassed the setup wizard (direct GOOGLE_API_KEY in .env) still learn- # that the free tier cannot sustain an agent session.+ # Users who bypassed the setup wizard (raw GOOGLE_API_KEY in .env) still+ # need to learn that the free tier cannot sustain an agent session.if status == 429 and is_free_tier_quota_error(err_message or body_text):message = message + _FREE_TIER_GUIDANCE-- # Legacy "Standard" Google Cloud key rejection (June 19, 2026 onward) ->- # Google's raw 401 misleadingly tells the user to use OAuth. Append the- # actual fix (mint a new Gemini API key in AI Studio).+ # Legacy "Standard" key rejection: Google's raw 401 misleadingly asks for+ # OAuth; append the actual fix (mint a new Gemini API key in AI Studio).if is_standard_key_auth_error(status, err_message or body_text, reason):message = message + _STANDARD_KEY_GUIDANCEreturn GeminiAPIError(message,- code=code,+ code=_HTTP_ERROR_CODES.get(status, f"gemini_http_{status}"),status_code=status,response=response,retry_after=retry_after,- details={- "status": err_status,- "reason": reason,- "metadata": metadata,- "message": err_message,- },+ details={"status": err_status, "reason": reason, "metadata": metadata, "message": err_message},)-class _GeminiChatCompletions:- def __init__(self, client: "GeminiNativeClient"):- self._client = client-- def create(self, **kwargs: Any) -> Any:- return self._client._create_chat_completion(**kwargs)---class _AsyncGeminiChatCompletions:- def __init__(self, client: "AsyncGeminiNativeClient"):- self._client = client-- async def create(self, **kwargs: Any) -> Any:- return await self._client._create_chat_completion(**kwargs)---class _GeminiChatNamespace:- def __init__(self, client: "GeminiNativeClient"):- self.completions = _GeminiChatCompletions(client)---class _AsyncGeminiChatNamespace:- def __init__(self, client: "AsyncGeminiNativeClient"):- self.completions = _AsyncGeminiChatCompletions(client)--class GeminiNativeClient:- """Minimal OpenAI-SDK-compatible facade over Gemini's native REST API."""+ """Minimal OpenAI-SDK-compatible facade over Gemini's native REST API.++ ``client.chat.completions.create(**kwargs)`` mirrors the OpenAI SDK surface.+ """# Declared for agent/auxiliary_client.py: already a complete client, so it# is never re-dispatched through a wire adapter. (No HERMES_SKIP_ASYNC_WRAP@@ -1108,29 +749,19 @@ class GeminiNativeClient:HERMES_SKIP_TRANSPORT_WRAP = Truedef __init__(- self,- *,- api_key: str,- base_url: Optional[str] = None,- default_headers: Optional[Dict[str, str]] = None,- timeout: Any = None,- http_client: Optional[httpx.Client] = None,- **_: Any,+ self, *, api_key: str, base_url: Optional[str] = None, default_headers: Optional[Dict[str, str]] = None,+ timeout: Any = None, http_client: Optional[httpx.Client] = None, **_: Any,) -> None:if not (api_key or "").strip():raise RuntimeError(- "Gemini native client requires an API key, but none was provided. "- "Set GOOGLE_API_KEY or GEMINI_API_KEY in your environment / ~/.hermes/.env "- "(get one at https://aistudio.google.com/app/apikey), or run `hermes setup` "- "to configure the Google provider."+ "Gemini native client requires an API key, but none was provided. Set GOOGLE_API_KEY or "+ "GEMINI_API_KEY in your environment / ~/.hermes/.env (get one at https://aistudio.google.com/app/apikey), "+ "or run `hermes setup` to configure the Google provider.")self.api_key = api_key- normalized_base = (base_url or DEFAULT_GEMINI_BASE_URL).rstrip("/")- if normalized_base.endswith("/openai"):- normalized_base = normalized_base[: -len("/openai")]- self.base_url = normalized_base+ self.base_url = (base_url or DEFAULT_GEMINI_BASE_URL).rstrip("/").removesuffix("/openai")self._default_headers = dict(default_headers or {})- self.chat = _GeminiChatNamespace(self)+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))self.is_closed = Falseself._http = http_client or httpx.Client(timeout=timeout or httpx.Timeout(connect=15.0, read=600.0, write=30.0, pool=30.0)@@ -1150,18 +781,15 @@ class GeminiNativeClient:self.close()def _headers(self) -> Dict[str, str]:- headers = {+ return {"Content-Type": "application/json","Accept": "application/json","x-goog-api-key": self.api_key,- # Include Hermes client context following Gemini's partner- # integration guidance.- # See https://ai.google.dev/gemini-api/docs/partner-integration+ # Client context per Gemini's partner-integration guidance."User-Agent": f"hermes-agent/{_HERMES_VERSION} (gemini-native)","X-Goog-Api-Client": f"hermes-agent/{_HERMES_VERSION}",+ **self._default_headers,}- headers.update(self._default_headers)- return headers@staticmethoddef _advance_stream_iterator(iterator: Iterator[_GeminiStreamChunk]) -> tuple[bool, Optional[_GeminiStreamChunk]]:@@ -1171,35 +799,17 @@ class GeminiNativeClient:return True, Nonedef _create_chat_completion(- self,- *,- model: str = "gemini-3.7-flash",- messages: Optional[List[Dict[str, Any]]] = None,- stream: bool = False,- tools: Any = None,- tool_choice: Any = None,- temperature: Optional[float] = None,- max_tokens: Optional[int] = None,- top_p: Optional[float] = None,- stop: Any = None,- extra_body: Optional[Dict[str, Any]] = None,- timeout: Any = None,- **_: Any,+ self, *, model: str = "gemini-3.7-flash", messages: Optional[List[Dict[str, Any]]] = None,+ stream: bool = False, tools: Any = None, tool_choice: Any = None, temperature: Optional[float] = None,+ max_tokens: Optional[int] = None, top_p: Optional[float] = None, stop: Any = None,+ extra_body: Optional[Dict[str, Any]] = None, timeout: Any = None, **_: Any,) -> Any:thinking_config = Noneif isinstance(extra_body, dict):thinking_config = extra_body.get("thinking_config") or extra_body.get("thinkingConfig")-request = build_gemini_request(- messages=messages or [],- tools=tools,- tool_choice=tool_choice,- temperature=temperature,- max_tokens=max_tokens,- top_p=top_p,- stop=stop,- thinking_config=thinking_config,- model=model,+ messages=messages or [], tools=tools, tool_choice=tool_choice, temperature=temperature,+ max_tokens=max_tokens, top_p=top_p, stop=stop, thinking_config=thinking_config, model=model,)model = bare_gemini_model_id(model)@@ -1214,33 +824,25 @@ class GeminiNativeClient:payload = response.json()except ValueError as exc:raise GeminiAPIError(- f"Invalid JSON from Gemini native API: {exc}",- code="gemini_invalid_json",- status_code=response.status_code,- response=response,+ f"Invalid JSON from Gemini native API: {exc}", code="gemini_invalid_json",+ status_code=response.status_code, response=response,) from excreturn translate_gemini_response(payload, model=model)def _stream_completion(self, *, model: str, request: Dict[str, Any], timeout: Any = None) -> Iterator[_GeminiStreamChunk]:url = f"{self.base_url}/models/{model}:streamGenerateContent?alt=sse"- stream_headers = dict(self._headers())- stream_headers["Accept"] = "text/event-stream"+ stream_headers = {**self._headers(), "Accept": "text/event-stream"}def _generator() -> Iterator[_GeminiStreamChunk]:try:with self._http.stream("POST", url, json=request, headers=stream_headers, timeout=timeout) as response:if response.status_code != 200:- body_text = read_streaming_error_body(response)- raise gemini_http_error(response, body_text=body_text)+ raise gemini_http_error(response, body_text=read_streaming_error_body(response))tool_call_indices: Dict[str, Dict[str, Any]] = {}for event in _iter_sse_events(response):- for chunk in translate_stream_event(event, model, tool_call_indices):- yield chunk+ yield from translate_stream_event(event, model, tool_call_indices)except httpx.HTTPError as exc:- raise GeminiAPIError(- f"Gemini streaming request failed: {exc}",- code="gemini_stream_error",- ) from exc+ raise GeminiAPIError(f"Gemini streaming request failed: {exc}", code="gemini_stream_error") from excreturn _generator()@@ -1252,12 +854,9 @@ class AsyncGeminiNativeClient:self._sync = sync_clientself.api_key = sync_client.api_keyself.base_url = sync_client.base_url- self.chat = _AsyncGeminiChatNamespace(self)- # Expose the underlying sync client as _real_client so the auxiliary- # cache's eviction-by-leaf-client helper (#23482) can find and drop- # this async entry when the sync GeminiNativeClient is poisoned.- # GeminiNativeClient is itself the leaf (no OpenAI client beneath- # it), so we point at the sync_client directly.+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))+ # The auxiliary cache evicts entries by leaf client; GeminiNativeClient+ # is itself the leaf (no OpenAI client beneath it).self._real_client = sync_clientasync def _create_chat_completion(self, **kwargs: Any) -> Any:diff --git a/agent/gemini_schema.py b/agent/gemini_schema.pyindex 665fd79a37e..748378a9400 100644--- a/agent/gemini_schema.py+++ b/agent/gemini_schema.py@@ -5,45 +5,34 @@ from __future__ import annotationsimport mathfrom typing import Any, Dict-# Gemini's ``FunctionDeclaration.parameters`` field accepts the ``Schema``-# object, which is only a subset of OpenAPI 3.0 / JSON Schema. Strip fields-# outside that subset before sending Hermes tool schemas to Google.+# Gemini's ``FunctionDeclaration.parameters`` accepts the ``Schema`` object,+# only a subset of OpenAPI 3.0 / JSON Schema; everything else is stripped._GEMINI_SCHEMA_ALLOWED_KEYS = {- "type",- "format",- "title",- "description",- "nullable",- "enum",- "maxItems",- "minItems",- "properties",- "required",- "minProperties",- "maxProperties",- "minLength",- "maxLength",- "pattern",- "example",- "anyOf",- "propertyOrdering",- "default",- "items",- "minimum",- "maximum",+ "type", "format", "title", "description", "nullable", "enum",+ "maxItems", "minItems", "properties", "required", "minProperties",+ "maxProperties", "minLength", "maxLength", "pattern", "example",+ "anyOf", "propertyOrdering", "default", "items", "minimum", "maximum",}+def _stringify_enum_value(item: Any) -> Any:+ """Gemini-safe string for a scalar enum entry, or None to drop it."""+ if isinstance(item, str):+ return item+ if isinstance(item, bool):+ return "true" if item else "false"+ if isinstance(item, (int, float)) and math.isfinite(item):+ return str(item)+ return None++def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]:"""Return a Gemini-compatible copy of a tool parameter schema.- Hermes tool schemas are OpenAI-flavored JSON Schema and may contain keys- such as ``$schema`` or ``additionalProperties`` that Google's Gemini- ``Schema`` object rejects. This helper preserves the documented Gemini- subset and recursively sanitizes nested ``properties`` / ``items`` /- ``anyOf`` definitions.+ Keeps only the documented Gemini subset (drops e.g. ``$schema`` /+ ``additionalProperties``) and recursively sanitizes nested+ ``properties`` / ``items`` / ``anyOf`` definitions."""-if not isinstance(schema, dict):return {}@@ -52,77 +41,38 @@ def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]:if key not in _GEMINI_SCHEMA_ALLOWED_KEYS:continueif key == "properties":- if not isinstance(value, dict):- continue- props: Dict[str, Any] = {}- for prop_name, prop_schema in value.items():- if not isinstance(prop_name, str):- continue- props[prop_name] = sanitize_gemini_schema(prop_schema)- cleaned[key] = props- continue- if key == "items":+ if isinstance(value, dict):+ cleaned[key] = {name: sanitize_gemini_schema(sub) for name, sub in value.items() if isinstance(name, str)}+ elif key == "items":cleaned[key] = sanitize_gemini_schema(value)- continue- if key == "anyOf":- if not isinstance(value, list):- continue- cleaned[key] = [- sanitize_gemini_schema(item)- for item in value- if isinstance(item, dict)- ]- continue- cleaned[key] = value+ elif key == "anyOf":+ if isinstance(value, list):+ cleaned[key] = [sanitize_gemini_schema(item) for item in value if isinstance(item, dict)]+ else:+ cleaned[key] = value- # Gemini's Schema validator requires every ``enum`` entry to be a string,- # even when the parent ``type`` is ``integer`` / ``number`` / ``boolean``.- # Preserve those constraints by stringifying scalar values while keeping- # the declared type intact; Gemini uses the strings as schema metadata and+ # Gemini requires every ``enum`` entry to be a string even for+ # integer/number/boolean types; the declared type stays intact and Gemini# still emits typed tool arguments at runtime.enum_val = cleaned.get("enum")- type_val = cleaned.get("type")- if isinstance(enum_val, list) and type_val in {"integer", "number", "boolean"}:- stringified = []- for item in enum_val:- if isinstance(item, str):- value = item- elif isinstance(item, bool):- value = "true" if item else "false"- elif (- isinstance(item, (int, float))- and not isinstance(item, bool)- and math.isfinite(item)- ):- value = str(item)- else:- continue- if value not in stringified:- stringified.append(value)+ if isinstance(enum_val, list) and cleaned.get("type") in {"integer", "number", "boolean"}:+ # dict.fromkeys = order-preserving dedupe.+ stringified = list(dict.fromkeys(v for v in map(_stringify_enum_value, enum_val) if v is not None))if stringified:cleaned["enum"] = stringifiedelse:cleaned.pop("enum", None)# Gemini validates ``required`` strictly against the same node's- # ``properties`` — GenerateContentRequest fails with HTTP 400- # "...items.required[0]: property is not defined" when a required name- # has no matching property in that node. MCP servers routinely emit- # this shape (e.g. the GitHub remote MCP's array item schemas carry- # ``required`` without ``properties``), and one bad tool schema fails- # the ENTIRE request before any model output. Filter ``required`` to- # names that exist in this node's ``properties`` and drop it when- # nothing valid remains. The tool handler still validates required- # fields at execution time, so this only removes what Gemini couldn't- # accept anyway. (Port of Kilo-Org/kilocode#11955.)+ # ``properties`` (HTTP 400 "property is not defined"), and one bad tool+ # schema fails the ENTIRE request. MCP servers routinely emit ``required``+ # without ``properties``, so keep only names that exist here; the tool+ # handler still validates required fields at execution time.required_val = cleaned.get("required")if isinstance(required_val, list):props_val = cleaned.get("properties")prop_names = set(props_val.keys()) if isinstance(props_val, dict) else set()- valid_required = [- name for name in required_val- if isinstance(name, str) and name in prop_names- ]+ valid_required = [name for name in required_val if isinstance(name, str) and name in prop_names]if not valid_required:cleaned.pop("required", None)elif len(valid_required) != len(required_val):@@ -133,8 +83,4 @@ def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]:def sanitize_gemini_tool_parameters(parameters: Any) -> Dict[str, Any]:"""Normalize tool parameters to a valid Gemini object schema."""-- cleaned = sanitize_gemini_schema(parameters)- if not cleaned:- return {"type": "object", "properties": {}}- return cleaned+ return sanitize_gemini_schema(parameters) or {"type": "object", "properties": {}}diff --git a/agent/moonshot_schema.py b/agent/moonshot_schema.pyindex 3f1708ceb0a..ab7319f2cce 100644--- a/agent/moonshot_schema.py+++ b/agent/moonshot_schema.py@@ -1,27 +1,16 @@"""Helpers for translating OpenAI-style tool schemas to Moonshot's schema subset.-Moonshot (Kimi) accepts a stricter subset of JSON Schema than standard OpenAI-tool calling. Requests that violate it fail with HTTP 400:-- tools.function.parameters is not a valid moonshot flavored json schema,- details: <...>--Known rejection modes documented at-https://forum.moonshot.ai/t/tool-calling-specification-violation-on-moonshot-api/102-and MoonshotAI/kimi-cli#1595:--1. Every property schema must carry a ``type``. Standard JSON Schema allows- type to be omitted (the value is then unconstrained); Moonshot refuses.-2. When ``anyOf`` is used, ``type`` must be on the ``anyOf`` children, not- the parent. Presence of both causes "type should be defined in anyOf- items instead of the parent schema".-3. Every object schema must carry a ``required`` array, even an empty one.- Standard JSON Schema allows omitting it; Moonshot 400s with- "required must be an array".--The ``#/definitions/...`` → ``#/$defs/...`` rewrite for draft-07 refs is-handled separately in ``tools/mcp_tool._normalize_mcp_input_schema`` so it-applies at MCP registration time for all providers.+Moonshot (Kimi) accepts a stricter subset of JSON Schema than OpenAI tool+calling; violations fail with HTTP 400 "tools.function.parameters is not a+valid moonshot flavored json schema". Rules applied here:++1. Every property schema must carry a ``type`` (JSON Schema allows omitting it).+2. With ``anyOf``, ``type`` belongs on the children, never the parent.+3. Enum arrays under scalar types may not contain null / empty string.+4. Every object schema must carry a ``required`` array, even an empty one.++The ``#/definitions/...`` → ``#/$defs/...`` rewrite for draft-07 refs lives in+``tools/mcp_tool._normalize_mcp_input_schema`` so it applies to all providers."""from __future__ import annotations@@ -29,111 +18,69 @@ from __future__ import annotationsimport copyfrom typing import Any, Dict, List-# Keys whose values are maps of name → schema (not schemas themselves).-# When we recurse, we walk the values of these maps as schemas, but we do-# NOT apply the missing-type repair to the map itself.+# Values are maps of name → schema: recurse into the values, but the map itself+# is not a schema and gets no repairs._SCHEMA_MAP_KEYS = frozenset({"properties", "patternProperties", "$defs", "definitions"})--# Keys whose values are lists of schemas.+# Values are lists of schemas._SCHEMA_LIST_KEYS = frozenset({"anyOf", "oneOf", "allOf", "prefixItems"})--# Keys whose values are a single nested schema.+# Values are a single nested schema (additionalProperties may also be a bool)._SCHEMA_NODE_KEYS = frozenset({"items", "contains", "not", "additionalProperties", "propertyNames"})-def _repair_schema(node: Any, is_schema: bool = True) -> Any:- """Recursively apply Moonshot repairs to a schema node.+def _empty_object_schema() -> Dict[str, Any]:+ return {"type": "object", "properties": {}, "required": []}- ``is_schema=True`` means this dict is a JSON Schema node and gets the- missing-type + anyOf-parent repairs applied. ``is_schema=False`` means- it's a container map (e.g. the value of ``properties``) and we only- recurse into its values.- """++def _repair_schema(node: Any) -> Any:+ """Recursively apply the Moonshot repairs to a schema node."""if isinstance(node, list):- # Lists only show up under schema-list keys (anyOf/oneOf/allOf), so- # every element is itself a schema.- return [_repair_schema(item, is_schema=True) for item in node]+ return [_repair_schema(item) for item in node]if not isinstance(node, dict):return node- # Walk the dict, deciding per-key whether recursion is into a schema- # node, a container map, or a scalar.repaired: Dict[str, Any] = {}for key, value in node.items():if key in _SCHEMA_MAP_KEYS and isinstance(value, dict):- # Map of name → schema. Don't treat the map itself as a schema- # (it has no type / properties of its own), but each value is.- repaired[key] = {- sub_key: _repair_schema(sub_val, is_schema=True)- for sub_key, sub_val in value.items()- }+ repaired[key] = {sub_key: _repair_schema(sub_val) for sub_key, sub_val in value.items()}elif key in _SCHEMA_LIST_KEYS and isinstance(value, list):- repaired[key] = [_repair_schema(v, is_schema=True) for v in value]- elif key in _SCHEMA_NODE_KEYS:- # items / not / additionalProperties: single nested schema.- # additionalProperties can also be a bool — leave those alone.- if isinstance(value, dict):- repaired[key] = _repair_schema(value, is_schema=True)- else:- repaired[key] = value+ repaired[key] = [_repair_schema(v) for v in value]+ elif key in _SCHEMA_NODE_KEYS and isinstance(value, dict):+ repaired[key] = _repair_schema(value)else:- # Scalars (description, title, format, enum values, etc.) pass through.repaired[key] = value- if not is_schema:- return repaired-- # Rule 2: when anyOf is present, type belongs only on the children.- # Additionally, Moonshot rejects null-type branches inside anyOf- # (enum value (<nil>) does not match any type in [string]).- # Collapse the anyOf to the first non-null branch and infer its type.+ # Rule 2, plus: Moonshot rejects null-type branches inside anyOf. Drop+ # them; a single surviving branch is promoted into this node and falls+ # through to rules 1/3/4, otherwise the pruned anyOf is returned as-is.if "anyOf" in repaired and isinstance(repaired["anyOf"], list):repaired.pop("type", None)- non_null = [b for b in repaired["anyOf"]- if isinstance(b, dict) and b.get("type") != "null"]- if non_null and len(non_null) < len(repaired["anyOf"]):- # Drop the anyOf wrapper — keep only the non-null branch.- # If there's a single non-null branch, promote it and fall- # through to Rules 1/3 so nullable/enum cleanup still applies- # to the merged node.- if len(non_null) == 1:- merge = {k: v for k, v in repaired.items() if k != "anyOf"}- merge.update(non_null[0])- repaired = merge- else:- repaired["anyOf"] = non_null- return repaired- else:- # Nothing to collapse — parent type stripped, children already- # repaired by the recursive walk above.+ non_null = [b for b in repaired["anyOf"] if isinstance(b, dict) and b.get("type") != "null"]+ if not non_null or len(non_null) == len(repaired["anyOf"]):+ return repaired+ if len(non_null) > 1:+ repaired["anyOf"] = non_nullreturn repaired+ merge = {k: v for k, v in repaired.items() if k != "anyOf"}+ merge.update(non_null[0])+ repaired = merge- # Moonshot also rejects non-standard keywords like ``nullable`` on- # parameter schemas — strip it.+ # Moonshot also rejects the non-standard ``nullable`` keyword.repaired.pop("nullable", None)- # Rule 1: property schemas without type need one. $ref nodes are exempt- # — their type comes from the referenced definition.- # Fill missing type BEFORE Rule 3 so enum cleanup can check the type.+ # Rule 1 ($ref nodes take their type from the referenced definition).+ # Runs before rule 3 so enum cleanup can see the type.if "$ref" not in repaired:repaired = _fill_missing_type(repaired)- # Rule 3: Moonshot rejects null/empty-string values inside enum arrays- # when the parent type is a scalar (string, integer, etc.). The error:- # "enum value (<nil>) does not match any type in [string]"- # Strip null and empty-string from enum values, and if the enum becomes- # empty, drop it entirely.- if "enum" in repaired and isinstance(repaired["enum"], list):- node_type = repaired.get("type")- if node_type in {"string", "integer", "number", "boolean"}:- cleaned = [v for v in repaired["enum"]- if v is not None and v != ""]- if cleaned:- repaired["enum"] = cleaned- else:- repaired.pop("enum")-- # Rule 4: object schemas must carry a `required` array, even when empty.+ # Rule 3: drop null/"" enum values under scalar types; drop an emptied enum.+ if isinstance(repaired.get("enum"), list) and repaired.get("type") in {"string", "integer", "number", "boolean"}:+ cleaned = [v for v in repaired["enum"] if v is not None and v != ""]+ if cleaned:+ repaired["enum"] = cleaned+ else:+ repaired.pop("enum")++ # Rule 4.if repaired.get("type") == "object":repaired = _ensure_required_array(repaired)@@ -141,14 +88,9 @@ def _repair_schema(node: Any, is_schema: bool = True) -> Any:def _ensure_required_array(node: Dict[str, Any]) -> Dict[str, Any]:- """Guarantee an object schema carries a ``required`` array (Moonshot rule).-- Standard JSON Schema lets you omit ``required`` when nothing is required;- Moonshot 400s on that ("required must be an array"). Ensure the key is a- list. When ``properties`` is known, prune ``required`` entries that don't- name a real property — defensive against dangling names, which Moonshot- also rejects. Mutates and returns ``node``.- """+ """Guarantee an object schema carries a ``required`` list (Moonshot 400s+ otherwise), pruning names that don't exist in ``properties`` — Moonshot+ also rejects dangling names. Mutates and returns ``node``."""props = node.get("properties")req = node.get("required")if isinstance(req, list):@@ -160,7 +102,13 @@ def _ensure_required_array(node: Dict[str, Any]) -> Dict[str, Any]:def _fill_missing_type(node: Dict[str, Any]) -> Dict[str, Any]:- """Infer a reasonable ``type`` if this schema node has none."""+ """Infer a reasonable ``type`` if this schema node has none.++ A type list collapses to its first concrete member; otherwise+ ``properties``/``required``/``additionalProperties`` → object,+ ``items``/``prefixItems`` → array, ``enum`` → type of its first value,+ else ``string`` (safest scalar).+ """node_type = node.get("type")if isinstance(node_type, list):concrete = next(@@ -171,22 +119,14 @@ def _fill_missing_type(node: Dict[str, Any]) -> Dict[str, Any]:if "type" in node and node_type not in {None, ""}:return node- # Heuristic: presence of ``properties`` → object, ``items`` → array, ``enum``- # → type of first enum value, else fall back to ``string`` (safest scalar).if "properties" in node or "required" in node or "additionalProperties" in node:inferred = "object"elif "items" in node or "prefixItems" in node:inferred = "array"- elif "enum" in node and isinstance(node["enum"], list) and node["enum"]:- sample = node["enum"][0]- if isinstance(sample, bool):- inferred = "boolean"- elif isinstance(sample, int):- inferred = "integer"- elif isinstance(sample, float):- inferred = "number"- else:- inferred = "string"+ elif isinstance(node.get("enum"), list) and node["enum"]:+ sample = node["enum"][0] # bool before int: bool is an int subclass+ scalar_types = ((bool, "boolean"), (int, "integer"), (float, "number"))+ inferred = next((t for cls, t in scalar_types if isinstance(sample, cls)), "string")else:inferred = "string"@@ -194,40 +134,32 @@ def _fill_missing_type(node: Dict[str, Any]) -> Dict[str, Any]:def sanitize_moonshot_tool_parameters(parameters: Any) -> Dict[str, Any]:- """Normalize tool parameters to a Moonshot-compatible object schema.-- Returns a deep-copied schema with the two flavored-JSON-Schema repairs- applied. Input is not mutated.- """+ """Return a deep-copied, Moonshot-compatible object schema; input is not mutated."""if not isinstance(parameters, dict):- return {"type": "object", "properties": {}, "required": []}+ return _empty_object_schema()- repaired = _repair_schema(copy.deepcopy(parameters), is_schema=True)+ repaired = _repair_schema(copy.deepcopy(parameters))if not isinstance(repaired, dict):- return {"type": "object", "properties": {}, "required": []}-- # Top-level must be an object schema- if repaired.get("type") != "object":- repaired["type"] = "object"- if "properties" not in repaired:- repaired["properties"] = {}- _ensure_required_array(repaired)+ return _empty_object_schema()- return repaired+ # Top-level must be an object schema.+ repaired["type"] = "object"+ repaired.setdefault("properties", {})+ return _ensure_required_array(repaired)def sanitize_moonshot_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- """Apply ``sanitize_moonshot_tool_parameters`` to every tool's parameters."""+ """Apply ``sanitize_moonshot_tool_parameters`` to every tool's parameters.++ Returns the input list object itself when nothing needed repairing.+ """if not tools:return toolssanitized: List[Dict[str, Any]] = []any_change = Falsefor tool in tools:- if not isinstance(tool, dict):- sanitized.append(tool)- continue- fn = tool.get("function")+ fn = tool.get("function") if isinstance(tool, dict) else Noneif not isinstance(fn, dict):sanitized.append(tool)continue@@ -235,8 +167,7 @@ def sanitize_moonshot_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]repaired = sanitize_moonshot_tool_parameters(params)if repaired is not params:any_change = True- new_fn = {**fn, "parameters": repaired}- sanitized.append({**tool, "function": new_fn})+ sanitized.append({**tool, "function": {**fn, "parameters": repaired}})else:sanitized.append(tool)@@ -246,24 +177,17 @@ def sanitize_moonshot_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]def is_moonshot_model(model: str | None) -> bool:"""True for any Kimi / Moonshot model slug, regardless of aggregator prefix.- Matches bare names (``kimi-k2.6``, ``moonshotai/Kimi-K2.6``) and aggregator-- prefixed slugs (``nous/moonshotai/kimi-k2.6``, ``openrouter/moonshotai/...``).- Detection by model name covers Nous / OpenRouter / other aggregators that- route to Moonshot's inference, where the base URL is the aggregator's, not- ``api.moonshot.ai``.+ Matches bare names (``kimi-k2.6``, ``moonshotai/Kimi-K2.6``) and+ aggregator-prefixed slugs (``nous/moonshotai/kimi-k2.6``), since aggregators+ route to Moonshot inference under their own base URL."""if not model:return Falsebare = model.strip().lower()- # Last path segment (covers aggregator-prefixed slugs)tail = bare.rsplit("/", 1)[-1]if tail.startswith("kimi-") or tail == "kimi":return True- # Kimi Coding Plan serves K3 under the bare slug ``k3`` (plus dated /- # suffixed variants like ``k3.1`` or ``k3-turbo``).+ # Kimi Coding Plan serves K3 under the bare slug ``k3`` (plus ``k3.1`` / ``k3-turbo``).if tail == "k3" or tail.startswith(("k3.", "k3-")):return True- # Vendor-prefixed forms commonly used on aggregators- if "moonshot" in bare or "/kimi" in bare or bare.startswith("kimi"):- return True- return False+ return "moonshot" in bare or "/kimi" in bare or bare.startswith("kimi")diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.pyindex 582539bc7dc..a2de5f90bc6 100644--- a/agent/vertex_adapter.py+++ b/agent/vertex_adapter.py@@ -1,14 +1,11 @@"""Vertex AI (Google Cloud) adapter for Hermes Agent.-Provides authentication and configuration for Vertex AI's OpenAI-compatible-endpoint. This allows Hermes to use Gemini models via Google Cloud with-enterprise-grade rate limits and quotas.+Authentication and configuration for Vertex AI's OpenAI-compatible endpoint+(Gemini via Google Cloud). Requires ``google-auth`` (lazy-installed).-Requires: pip install google-auth--Environment variables honored (all optional):- GOOGLE_APPLICATION_CREDENTIALS — path to a service account JSON file (secret).- VERTEX_CREDENTIALS_PATH — alias, takes precedence if set (secret).+Environment variables honored (all optional, secrets):+ GOOGLE_APPLICATION_CREDENTIALS — path to a service account JSON file.+ VERTEX_CREDENTIALS_PATH — alias, takes precedence if set.VERTEX_PROJECT_ID — override the project_id embedded in creds.VERTEX_REGION — override default region ("global" unless set).@@ -25,10 +22,8 @@ from typing import Any, Optional, Tuplefrom agent.secret_scope import get_secret as _get_secret, is_multiplex_active-# Ensure google-auth is installed before importing. The [vertex] extra is no-# longer in [all] per the lazy-install policy added 2026-05-12 — lazy_deps-# handles on-demand installation so the Vertex provider still works for users-# who installed plain `hermes-agent` and only later selected a Gemini model.+# The [vertex] extra is not in [all]; lazy_deps installs google-auth on demand+# for users who selected a Gemini model after a plain install.try:from tools.lazy_deps import ensure as _lazy_ensure_lazy_ensure("provider.vertex", prompt=False)@@ -45,17 +40,13 @@ except ImportError:logger = logging.getLogger(__name__)DEFAULT_REGION = "global"+_CLOUD_PLATFORM_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]_creds_cache: dict = {}def _vertex_config() -> dict:- """Return the ``vertex:`` section of config.yaml, or {} on any failure.-- Non-secret routing settings (project_id, region) live in config.yaml per- the .env-secrets-only rule. Env vars still take precedence — they are read- directly at the call sites below, with config.yaml as the fallback.- """+ """Return the ``vertex:`` section of config.yaml, or {} on any failure."""try:from hermes_cli.config import load_config@@ -65,39 +56,31 @@ def _vertex_config() -> dict:return {}+def _env_or_config(env_var: str, config_key: str) -> str:+ """Setting precedence: env/secret > config.yaml; "" when neither is set."""+ env_value = (_get_secret(env_var) or "").strip()+ if env_value:+ return env_value+ return str(_vertex_config().get(config_key) or "").strip()++def _resolve_region(explicit: Optional[str] = None) -> str:"""Region precedence: explicit arg > VERTEX_REGION env > config.yaml > default."""- if explicit:- return explicit- env_region = (_get_secret("VERTEX_REGION") or "").strip()- if env_region:- return env_region- cfg_region = str(_vertex_config().get("region") or "").strip()- return cfg_region or DEFAULT_REGION+ return explicit or _env_or_config("VERTEX_REGION", "region") or DEFAULT_REGIONdef _resolve_project_override() -> Optional[str]:- """Project-ID override precedence: VERTEX_PROJECT_ID env > config.yaml.-- Returns None when neither is set (the credentials' embedded project_id- is used in that case).- """- env_project = (_get_secret("VERTEX_PROJECT_ID") or "").strip()- if env_project:- return env_project- cfg_project = str(_vertex_config().get("project_id") or "").strip()- return cfg_project or None+ """Project-ID override (VERTEX_PROJECT_ID env > config.yaml), or None to use+ the credentials' embedded project_id."""+ return _env_or_config("VERTEX_PROJECT_ID", "project_id") or Nonedef _resolve_credentials_path(explicit: Optional[str]) -> Optional[str]:if explicit and os.path.exists(explicit):return explicit- # Routed through get_secret (not a raw os.environ read): in a multiplex- # gateway serving several profiles from one process, os.environ reflects- # whichever profile's .env happened to be loaded at boot, not the profile- # the current turn belongs to. Reading it directly here would let one- # profile mint Vertex tokens from — and get billed against — a different- # profile's service-account file. See agent/secret_scope.py.+ # get_secret, not os.environ: a multiplex gateway serves several profiles+ # from one process, and os.environ reflects whichever .env loaded at boot.+ # A raw read could mint (and bill) tokens from another profile's SA file.for env_var in ("VERTEX_CREDENTIALS_PATH", "GOOGLE_APPLICATION_CREDENTIALS"):path = _get_secret(env_var)if path and os.path.exists(path):@@ -105,57 +88,70 @@ def _resolve_credentials_path(explicit: Optional[str]) -> Optional[str]:return None-def _refresh_credentials(creds) -> None:- auth_req = google.auth.transport.requests.Request()- creds.refresh(auth_req)---def _read_sa_file(resolved_path: str) -> Tuple[bytes, Tuple[Any, ...]]:- """Read the service-account file once, returning (bytes, cache key).-- The cache key fingerprints the file CONTENT (sha256), not stat- metadata. A (path, mtime_ns, size) signature — the idiom used for- config caches — is not sufficient here: metadata-preserving atomic- replacement (deployment tools that restore mtime; equal-length JSON)- produces a different private key under an identical stat signature,- and this cache guards an identity, not a parse (review finding on- #97701, reproduced: inode/content changed, stat key equal). Reading- the bytes also lets the caller construct credentials from the SAME- snapshot the key was computed from, closing the stat->read TOCTOU.-- The file is a few KB of JSON; one read + sha256 per cache PROBE is- noise next to the OAuth token mint the cache exists to avoid.- """- with open(resolved_path, "rb") as fh:- raw = fh.read()- digest = hashlib.sha256(raw).hexdigest()- return raw, (resolved_path, digest)--def _sa_snapshot(resolved_path: Optional[str]) -> Tuple[Optional[bytes], Tuple[Any, ...]]:"""Resolve (bytes-or-None, cache key) for one credential attempt.- - No path (ADC): (None, ("__adc__",)) — sentinel key, existing- refresh/expiry handling.- - Readable file: (bytes, (path, sha256)) via _read_sa_file — the- caller builds credentials from the SAME bytes the key fingerprints.- - Unreadable file: (None, (path,)) — bare-path key, and the caller- falls back to the SDK's own file read: byte-for-byte the- pre-signature behavior.+ - No path (ADC): (None, ("__adc__",)) sentinel key.+ - Readable file: (bytes, (path, sha256)).+ - Unreadable file: (None, (path,)) — the caller falls back to the SDK's own file read.++ The key fingerprints file CONTENT, not stat metadata: a metadata-preserving+ atomic replacement (equal-length JSON, restored mtime) yields a different+ private key under an identical stat signature, and this cache guards an+ identity. Returning the bytes lets the caller build credentials from the SAME+ snapshot the key was computed from (no stat->read TOCTOU); one read + sha256+ per probe is noise next to the OAuth token mint the cache avoids."""if not resolved_path:return None, ("__adc__",)try:- return _read_sa_file(resolved_path)+ with open(resolved_path, "rb") as fh:+ raw = fh.read()except OSError:return None, (resolved_path,)+ return raw, (resolved_path, hashlib.sha256(raw).hexdigest())+++def _load_credentials(resolved_path: Optional[str], sa_raw: Optional[bytes]) -> Optional[Tuple[Any, Optional[str]]]:+ """Build (credentials, project_id) for a cache miss; None when ADC must be refused."""+ if resolved_path:+ if sa_raw is not None:+ creds = service_account.Credentials.from_service_account_info(json.loads(sa_raw), scopes=_CLOUD_PLATFORM_SCOPES)+ else:+ # Unreadable at key time: let the SDK try the file directly.+ creds = service_account.Credentials.from_service_account_file(resolved_path, scopes=_CLOUD_PLATFORM_SCOPES)+ return creds, creds.project_id+ # google.auth.default() reads GOOGLE_APPLICATION_CREDENTIALS straight from+ # os.environ, which load_dotenv() mutated at boot for whichever profile+ # loaded first. _resolve_credentials_path confirmed *this* profile doesn't+ # define the var, so refuse rather than authenticate under a stranger's identity.+ if is_multiplex_active() and os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):+ logger.warning(+ "Vertex ADC skipped for this profile: GOOGLE_APPLICATION_CREDENTIALS is set in the process environment "+ "(from another profile's .env) but not in this profile's own config. Set VERTEX_CREDENTIALS_PATH in this "+ "profile's .env instead of relying on ADC."+ )+ return None+ return google.auth.default(scopes=_CLOUD_PLATFORM_SCOPES)+++def _needs_refresh(creds) -> bool:+ """No token, expired, or within 5 minutes of expiry."""+ return (+ not getattr(creds, "token", None)+ or getattr(creds, "expired", False)+ or (+ getattr(creds, "expiry", None) is not None+ and (creds.expiry.timestamp() - time.time()) < 300+ )+ )def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:"""Return a (fresh access_token, project_id) pair or (None, None) on failure.- Caches the underlying Credentials object and refreshes it when within- 5 minutes of expiry, so repeated calls don't thrash the token endpoint.+ Caches the Credentials object per file content and refreshes it when+ within 5 minutes of expiry, so repeated calls don't thrash the token endpoint."""if google is None:logger.warning("google-auth package not installed. Cannot use Vertex AI.")@@ -163,88 +159,36 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optiresolved_path = _resolve_credentials_path(credentials_path)# One read serves both the cache key and (on a miss) credential- # construction, so the credentials always match the bytes the key- # fingerprints — no stat/read or read/read TOCTOU.+ # construction, so the credentials always match the fingerprinted bytes.sa_raw, cache_key = _sa_snapshot(resolved_path)try:cached = _creds_cache.get(cache_key)if cached is None:- if resolved_path:- if sa_raw is not None:- creds = service_account.Credentials.from_service_account_info(- json.loads(sa_raw),- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- else:- # Unreadable at key time (bare-path key): let the SDK- # try the file directly — pre-signature behavior.- creds = service_account.Credentials.from_service_account_file(- resolved_path,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- project_id = creds.project_id- else:- # google.auth.default() reads GOOGLE_APPLICATION_CREDENTIALS- # straight from os.environ internally — it has no notion of- # the profile secret scope. _resolve_credentials_path already- # confirmed (via get_secret) that *this* profile doesn't- # define the var, but python-dotenv's load_dotenv() mutates- # os.environ at boot for whichever profile happened to load- # first, so a raw os.environ read here can still pick up a- # different profile's service-account path. Refuse rather- # than silently authenticating under a stranger's identity.- if is_multiplex_active() and os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):- logger.warning(- "Vertex ADC skipped for this profile: "- "GOOGLE_APPLICATION_CREDENTIALS is set in the process "- "environment (from another profile's .env) but not in "- "this profile's own config. Set VERTEX_CREDENTIALS_PATH "- "in this profile's .env instead of relying on ADC."- )- return None, None- creds, project_id = google.auth.default(- scopes=["https://www.googleapis.com/auth/cloud-platform"]- )+ loaded = _load_credentials(resolved_path, sa_raw)+ if loaded is None:+ return None, None+ creds, project_id = loaded_creds_cache[cache_key] = (creds, project_id)- # A rotation leaves the old signature's entry behind; drop any- # other entries for the same path so the cache holds at most one- # Credentials per file (bounded, and stale identities don't- # linger for surprise reuse via an old key).- for k in [- k for k in _creds_cache- if k is not cache_key and k != cache_key and k[0] == cache_key[0]- ]:+ # A rotation leaves the old signature's entry behind; keep at most+ # one Credentials per file so stale identities can't be reused.+ for k in [k for k in _creds_cache if k != cache_key and k[0] == cache_key[0]]:_creds_cache.pop(k, None)else:creds, project_id = cached- needs_refresh = (- not getattr(creds, "token", None)- or getattr(creds, "expired", False)- or (- getattr(creds, "expiry", None) is not None- and (creds.expiry.timestamp() - time.time()) < 300- )- )- if needs_refresh:- _refresh_credentials(creds)+ if _needs_refresh(creds):+ creds.refresh(google.auth.transport.requests.Request())override_project = _resolve_project_override()- if override_project:- project_id = override_project-- return creds.token, project_id+ return creds.token, override_project or project_idexcept Exception as e:logger.error(f"Failed to resolve Vertex AI credentials: {e}")_creds_cache.pop(cache_key, None)- # If ADC failed (e.g. expired refresh token), try the SA file- # before giving up — it may have been added after initial startup.- # Keyed on the RESOLVED PATH being absent (i.e. this attempt was- # ADC), not on the cache-key literal: the signature-keyed cache- # made keys tuples, and a tuple never equals the old "__adc__"- # string (that comparison silently killed this retry path).+ # If ADC failed (e.g. expired refresh token), try the SA file before+ # giving up — it may have been added after startup. Keyed on the+ # resolved path being absent (this attempt was ADC), not on the cache key.if not resolved_path:sa_path = _resolve_credentials_path(credentials_path)if sa_path:@@ -257,10 +201,9 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optidef build_vertex_base_url(project_id: str, region: str = DEFAULT_REGION) -> str:"""Build the OpenAI-compatible base URL for Vertex AI.- The `global` location uses a bare `aiplatform.googleapis.com` hostname,- while regional locations use `{region}-aiplatform.googleapis.com`.- Gemini 3.x preview models are only served via the global endpoint at- the time of writing.+ ``global`` uses the bare ``aiplatform.googleapis.com`` host; regional+ locations use ``{region}-aiplatform.googleapis.com``. Gemini 3.x preview+ models are only served via the global endpoint."""host = "aiplatform.googleapis.com" if region == "global" else f"{region}-aiplatform.googleapis.com"return f"https://{host}/v1beta1/projects/{project_id}/locations/{region}/endpoints/openapi"@@ -274,45 +217,26 @@ def get_vertex_config(token, project_id = get_vertex_credentials(credentials_path)if not token or not project_id:return None, None-- effective_region = _resolve_region(region)- base_url = build_vertex_base_url(project_id, effective_region)- return token, base_url+ return token, build_vertex_base_url(project_id, _resolve_region(region))def has_vertex_credentials() -> bool:- """Fast check for whether Vertex credentials appear configured.-- No network calls and no google-auth import — safe for provider- auto-detection and setup-status display. True when either a service- account JSON path is resolvable, or an explicit project ID is configured- (env or config.yaml, implying ADC is intended).- """- if _resolve_credentials_path(None):- return True- if _resolve_project_override():- return True- return False+ """Fast check (no network, no google-auth import) for configured Vertex+ credentials: a resolvable SA JSON path, or an explicit project ID+ (env or config.yaml, implying ADC is intended)."""+ return bool(_resolve_credentials_path(None) or _resolve_project_override())def has_explicit_vertex_config() -> bool:"""True only when the user deliberately pointed Hermes at Vertex.- Stricter than :func:`has_vertex_credentials`, which also returns True for- an ambient ``GOOGLE_APPLICATION_CREDENTIALS`` path — a var commonly set- globally for unrelated GCP work. That ambient signal must NOT mark Vertex- "explicitly configured" for the model-picker gate, or a user who never set- Hermes up for Vertex would suddenly see it (and could spend against those- credentials). So this checks only Hermes-scoped signals:-- * ``VERTEX_PROJECT_ID`` env or ``vertex.project_id`` in config.yaml- (``_resolve_project_override``), or- * a resolvable ``VERTEX_CREDENTIALS_PATH`` service-account file- (the Hermes-specific path var — NOT ``GOOGLE_APPLICATION_CREDENTIALS``).+ Stricter than :func:`has_vertex_credentials`: an ambient+ ``GOOGLE_APPLICATION_CREDENTIALS`` (often set for unrelated GCP work) must+ NOT mark Vertex "explicitly configured" for the model-picker gate, or a user+ could unknowingly spend against those credentials. Only Hermes-scoped signals+ count: ``VERTEX_PROJECT_ID`` / ``vertex.project_id`` or a readable ``VERTEX_CREDENTIALS_PATH``."""if _resolve_project_override():return Truesa_path = _get_secret("VERTEX_CREDENTIALS_PATH")- if sa_path and os.path.isfile(sa_path) and os.access(sa_path, os.R_OK):- return True- return False+ return bool(sa_path and os.path.isfile(sa_path) and os.access(sa_path, os.R_OK))