The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/credits,gemini): derive header names from field table; contextlib.suppress
Tekniumad9d2d8c8387
diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex b575df965bd..063de81a923 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -12,6 +12,7 @@ import reimport threadingimport timefrom dataclasses import dataclass+from decimal import Decimalfrom typing import Any, Mapping, Optionalfrom utils import is_truthy_value@@ -96,8 +97,7 @@ GRANT_UNSPENT_MIN_MICROS = 10_000def 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-<field>`` (``x-nous-<field>`` 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 defaultif kind in ("micros", "signed"):val = _safe_int(raw)return _SENTINEL if val is _SENTINEL or (kind == "micros" and val < 0) else valif 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 _SENTINELflag = 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 = "") -> Optlogger.warning("credits header version %d unsupported, ignoring — update Hermes", version_val)return Nonefields: 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 = "") -> Optdef _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 Decimald: 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.pyindex e8df963bccc..ea6e9b05ba1 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport asyncioimport base64+import contextlibimport jsonimport loggingimport 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: booldef _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")))continueif 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]})continueparts = _extract_multimodal_parts(msg.get("content"))@@ -586,8 +583,7 @@ def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = Nostatus = response.status_codebody_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:- passdef _headers(self) -> Dict[str, str]:return {"Content-Type": "application/json", "Accept": "application/json", "x-goog-api-key": self.api_key,