From ad9d2d8c83876137b37e95f1d03c60f35edde986 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 19:49:34 -0700 Subject: [PATCH] refactor(agent/credits,gemini): derive header names from field table; contextlib.suppress --- agent/credits_tracker.py | 46 ++++++++++++++++------------------ agent/gemini_native_adapter.py | 24 +++++++----------- 2 files changed, 30 insertions(+), 40 deletions(-) diff --git a/agent/credits_tracker.py b/agent/credits_tracker.py index b575df965b..063de81a92 100644 --- a/agent/credits_tracker.py +++ b/agent/credits_tracker.py @@ -12,6 +12,7 @@ import re import threading import time from dataclasses import dataclass +from decimal import Decimal from typing import Any, Mapping, Optional from utils import is_truthy_value @@ -96,8 +97,7 @@ GRANT_UNSPENT_MIN_MICROS = 10_000 def new_credits_latch() -> dict: - """Fresh notice latch for :func:`evaluate_credits_notices`. Every producer must - build it here so a new gate key lands everywhere at once.""" + """Fresh notice latch for :func:`evaluate_credits_notices`; every producer builds it here so a new gate key lands everywhere.""" return {"active": set(), "seen_below_90": False, "usage_band": None, "seen_grant_unspent": False} @@ -224,33 +224,33 @@ def evaluate_credits_notices( return (to_show, to_clear) -# Header contract: (field, header, kind[, default]). micros: required int >= 0 ("signed": may be -# negative); usd: the server's formatted string, ^-?\d+\.\d{2}$; bool: optional "true"/"false" STRING. -# Handled inline below: subscription-limit-* (PAIRED/optional), tool-pool-micros (optional), +# Header contract: (field, kind[, default-when-absent]); a field is REQUIRED unless it has a default. +# Header name = ``x-nous-credits-`` (``x-nous-`` for tool_pool_*), underscores → dashes. +# micros: int >= 0 ("signed": may be negative); usd: the server's formatted string ^-?\d+\.\d{2}$ +# (never re-parsed); bool: "true"/"false" STRING. Handled inline: subscription-limit-* (PAIRED/optional), # denominator-kind ("subscription_cap" | "none"), disabled-reason (omitted when null). _HEADER_FIELDS: tuple[tuple, ...] = ( - ("remaining_micros", "x-nous-credits-remaining-micros", "micros"), - ("subscription_micros", "x-nous-credits-subscription-micros", "signed"), - ("rollover_micros", "x-nous-credits-rollover-micros", "micros"), - ("purchased_micros", "x-nous-credits-purchased-micros", "micros"), - ("as_of_ms", "x-nous-credits-as-of-ms", "micros"), - ("remaining_usd", "x-nous-credits-remaining-usd", "usd"), - ("subscription_usd", "x-nous-credits-subscription-usd", "usd"), - ("purchased_usd", "x-nous-credits-purchased-usd", "usd"), - ("paid_access", "x-nous-credits-paid-access", "bool", True), # absent → fail-open (assume access) - ("tool_pool_gated_off", "x-nous-tool-pool-gated-off", "bool", False), + ("remaining_micros", "micros"), ("subscription_micros", "signed"), ("rollover_micros", "micros"), + ("purchased_micros", "micros"), ("as_of_ms", "micros"), ("tool_pool_micros", "micros", 0), + ("remaining_usd", "usd"), ("subscription_usd", "usd"), ("purchased_usd", "usd"), + ("paid_access", "bool", True), # absent → fail-open (assume access) + ("tool_pool_gated_off", "bool", False), ) -def _parse_field(kind: str, raw: Optional[str], default: Any = None) -> Any: - """One header value → field value, or ``_SENTINEL`` on a contract violation.""" +def _header_name(field: str) -> str: + return "x-nous-" + ("" if field.startswith("tool_pool_") else "credits-") + field.replace("_", "-") + + +def _parse_field(kind: str, raw: Optional[str], default: Any = _SENTINEL) -> Any: + """One header value → field value; ``default`` when absent, ``_SENTINEL`` on a contract violation.""" + if raw is None: + return default if kind in ("micros", "signed"): val = _safe_int(raw) return _SENTINEL if val is _SENTINEL or (kind == "micros" and val < 0) else val if kind == "usd": - return raw if raw is not None and _USD_RE.match(raw) else _SENTINEL - if raw is None: - return default + return raw if _USD_RE.match(raw) else _SENTINEL flag = raw.strip().lower() return _SENTINEL if flag not in ("true", "false") else flag == "true" @@ -277,11 +277,8 @@ def parse_credits_headers(headers: Mapping[str, str], provider: str = "") -> Opt logger.warning("credits header version %d unsupported, ignoring — update Hermes", version_val) return None fields: dict[str, Any] = { - name: _parse_field(kind, lowered.get(key), *default) for name, key, kind, *default in _HEADER_FIELDS + name: _parse_field(kind, lowered.get(_header_name(name)), *default) for name, kind, *default in _HEADER_FIELDS } - # tool_pool_micros is OPTIONAL: absent → 0; present-but-invalid → miss. - tp_raw = lowered.get("x-nous-tool-pool-micros") - fields["tool_pool_micros"] = 0 if tp_raw is None else _parse_field("micros", tp_raw) lim_micros_raw = lowered.get("x-nous-credits-subscription-limit-micros") lim_usd_raw = lowered.get("x-nous-credits-subscription-limit-usd") if lim_micros_raw is not None and lim_usd_raw is not None: @@ -308,7 +305,6 @@ def parse_credits_headers(headers: Mapping[str, str], provider: str = "") -> Opt def _fixture(remaining: str, subscription: str, limit: Optional[str] = None, purchased: Optional[str] = None, *, paid: bool = True, reason: Optional[str] = None) -> dict: """Fixture spec from *_usd strings; micros derived exactly (Decimal).""" - from decimal import Decimal d: dict = {} for field, usd in (("remaining", remaining), ("subscription", subscription), ("subscription_limit", limit), ("purchased", purchased)): diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py index e8df963bcc..ea6e9b05ba 100644 --- a/agent/gemini_native_adapter.py +++ b/agent/gemini_native_adapter.py @@ -8,6 +8,7 @@ from __future__ import annotations import asyncio import base64 +import contextlib import json import logging import re @@ -97,8 +98,7 @@ def probe_gemini_tier( if not key: return "unknown" base = str(base_url or DEFAULT_GEMINI_BASE_URL).strip().rstrip("/") or DEFAULT_GEMINI_BASE_URL - if base.lower().endswith("/openai"): - base = base[: -len("/openai")] + base = re.sub(r"/openai\Z", "", base, flags=re.IGNORECASE) try: with httpx.Client(timeout=timeout) as client: resp = client.post( @@ -222,11 +222,10 @@ def _translate_tool_call_to_gemini(tool_call: Dict[str, Any], include_ids: bool def _looks_like_json_schema(node: Any) -> bool: - """True if a parsed value contains a JSON-Schema ``$ref`` pointer (``#/...``): Gemini 3 - resolves ``$ref``/``$defs`` inside functionResponse.response 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. False positives only - lose the structured shape, never the content.""" + """True if a parsed value contains a JSON-Schema ``$ref`` pointer (``#/...``): Gemini 3 resolves + ``$ref``/``$defs`` inside functionResponse.response and rejects unknown pointers with HTTP 400, so a + tool result that is itself a JSON Schema (e.g. ``tool_describe`` output) is forwarded as opaque text. + False positives only lose the structured shape, never the content.""" if isinstance(node, dict): return any( (key == "$ref" and isinstance(value, str) and value.startswith("#/")) or _looks_like_json_schema(value) @@ -299,9 +298,7 @@ def _build_gemini_contents( system_text_parts.append(_coerce_content_to_text(msg.get("content"))) continue if role in {"tool", "function"}: - 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 - ) + part = _translate_tool_result_to_gemini(msg, tool_name_by_call_id, include_tool_call_ids, is_gemini3=is_gemini3) contents.append({"role": "user", "parts": [part]}) continue parts = _extract_multimodal_parts(msg.get("content")) @@ -586,8 +583,7 @@ def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = No status = response.status_code body_text = (_response_text(response) if body_text is None else body_text) or "" err_obj = _error_object(body_text) - err_status = str(err_obj.get("status") or "").strip() - err_message = str(err_obj.get("message") or "").strip() + err_status, err_message = (str(err_obj.get(k) or "").strip() for k in ("status", "message")) reason, metadata = _error_info(err_obj) try: retry_after: Optional[float] = float(response.headers.get("Retry-After") or response.headers.get("retry-after")) @@ -635,10 +631,8 @@ class GeminiNativeClient: def close(self) -> None: self.is_closed = True - try: + with contextlib.suppress(Exception): self._http.close() - except Exception: - pass def _headers(self) -> Dict[str, str]: return {"Content-Type": "application/json", "Accept": "application/json", "x-goog-api-key": self.api_key,