Skip to content

The agent that grows with you

refactor(agent/G_small): compact docstrings (keep WHY/invariants), inline constant comments

Teknium922717d538d6
diff --git a/agent/rate_limit_credits.py b/agent/rate_limit_credits.py
index 13b98e19e13..1dcbb3178e4 100644
--- a/agent/rate_limit_credits.py
+++ b/agent/rate_limit_credits.py
@@ -51,11 +51,9 @@ class RateLimitCreditsMixin:
def _capture_credits(self, http_response: Any) -> None:
"""Parse x-nous-credits-* headers, cache CreditsState, fire threshold notices.
- The PARSE is swallowed (miss → keep last-known); the notice EVALUATION is a separate block that WARNS
- on failure so a depletion-notice bug cannot vanish silently.
+ The PARSE is swallowed (miss → keep last-known); notice EVALUATION WARNS on failure so a
+ depletion-notice bug cannot vanish silently. HERMES_DEV_CREDITS_FIXTURE injects a chosen state instead.
"""
- # Dev test fixture (HERMES_DEV_CREDITS_FIXTURE): inject a chosen notice state
- # each turn for repeatable testing, bypassing real headers.
try:
from agent.credits_tracker import dev_fixture_credits_state
fixture = dev_fixture_credits_state()
@@ -110,11 +108,9 @@ class RateLimitCreditsMixin:
self._credits_session_start_micros = state.remaining_micros
def _emit_credits_notices(self) -> None:
- """Run the threshold policy on the current credits state and emit notices.
+ """Run the threshold policy and emit notices (shared by the warm path and the cold-start seed).
- Shared by the warm path and the cold-start seed so an already-depleted session warns immediately. Runs
- only when a notice consumer is bound. WARNS on failure. Emits clears FIRST so depleted lands last
- (latest-wins slot).
+ Runs only when a notice consumer is bound; WARNS on failure; clears FIRST so depleted lands last.
"""
if getattr(self, "notice_callback", None) is None and getattr(self, "notice_clear_callback", None) is None:
return
diff --git a/agent/reasoning_params.py b/agent/reasoning_params.py
index 094c3ac01fe..2660c4dcff8 100644
--- a/agent/reasoning_params.py
+++ b/agent/reasoning_params.py
@@ -27,11 +27,8 @@ class ReasoningParamsMixin:
"""Reasoning-parameter gating and echo policy (see module docstring)."""
def _supports_reasoning_extra_body(self) -> bool:
- """Return True when reasoning extra_body is safe to send for this route/model.
-
- OpenRouter forwards unknown extra_body upstream and some routes 400 on ``reasoning``; gate to known
- reasoning-capable families and direct Nous Portal.
- """
+ """True when reasoning extra_body is safe to send: OpenRouter forwards unknown extra_body upstream and
+ some routes 400 on ``reasoning``, so gate to known reasoning-capable families and direct Nous Portal."""
url = self._base_url_lower
if base_url_host_matches(url, "nousresearch.com") or base_url_host_matches(url, "ai-gateway.vercel.sh"):
return True
@@ -65,10 +62,8 @@ class ReasoningParamsMixin:
return any(model.startswith(prefix) for prefix in _OPENROUTER_REASONING_PREFIXES)
def _cached_probe(self, cache_attr: str, probe, unknown, definitive):
- """Run ``probe(model, base_url, api_key)`` once per (model, base_url) with the module TTL policy.
-
- ``unknown`` is what a raising probe yields; ``definitive(value)`` decides permanent vs 60s TTL.
- """
+ """``probe(model, base_url, api_key)`` once per (model, base_url); ``unknown`` is what a raising probe
+ yields, ``definitive(value)`` decides permanent vs 60s TTL."""
cache = getattr(self, cache_attr, None)
if cache is None:
cache = {}
@@ -132,12 +127,9 @@ class ReasoningParamsMixin:
_build_assistant_message = _forward("agent.chat_completion_helpers", "build_assistant_message")
def _needs_thinking_reasoning_pad(self) -> bool:
- """Return True when the active provider enforces ``reasoning_content`` echo-back on tool-call replays.
-
- DeepSeek thinking, Kimi/Moonshot thinking and Xiaomi MiMo thinking all 400 without it. Cached per
- (provider, model, base_url) and invalidated by ``switch_model()`` / ``_try_activate_fallback()`` —
- the loop calls this ~16× per turn and each miss re-runs several ``urlparse`` host matches.
- """
+ """True when the provider enforces ``reasoning_content`` echo-back on tool-call replays (DeepSeek, Kimi,
+ MiMo thinking all 400 without it). Cached per (provider, model, base_url), invalidated by
+ ``switch_model()`` / ``_try_activate_fallback()`` — called ~16× per turn."""
key = (self.provider, self.model, getattr(self, "_base_url_lower", self.base_url))
cached = getattr(self, "_thinking_pad_cache", None)
if cached is not None and cached[0] == key:
@@ -148,11 +140,8 @@ class ReasoningParamsMixin:
return result
def _reasoning_echo_opt_in(self) -> bool:
- """User opted in to ``reasoning_content`` echo-back for the *current* provider (``model.reasoning_echo``).
-
- Covers custom providers/gateways the host-based echo rules miss. Per-active-provider: fallback
- activation swaps the flag and ``restore_primary_runtime()`` restores it, so a strict fallback still strips.
- """
+ """``model.reasoning_echo`` opt-in for the *current* provider (covers gateways the host rules miss);
+ fallback activation swaps the flag and ``restore_primary_runtime()`` restores it."""
return bool(getattr(self, "_reasoning_echo_flag", False))
@staticmethod
@@ -185,12 +174,9 @@ class ReasoningParamsMixin:
@staticmethod
def _sanitize_tool_calls_for_strict_api(api_msg: dict, model: "str | None" = None) -> dict:
- """Strip Codex Responses fields (call_id, response_item_id, extra_content) from tool_calls.
-
- Strict Chat Completions APIs (Mistral, Fireworks) 400/422 on unknown fields. ``extra_content`` (Gemini
- thought_signature) is kept only when the outgoing model is Gemini-family (it 400s without it). Builds
- new dicts so the internal history retains the Codex fields for a later fallback.
- """
+ """Strip Codex Responses fields from tool_calls for strict Chat Completions APIs (Mistral, Fireworks
+ 400/422 on unknown fields). ``extra_content`` (Gemini thought_signature) is kept only for Gemini-family
+ models. Builds new dicts so the internal history keeps the Codex fields for a later fallback."""
tool_calls = api_msg.get("tool_calls")
if not isinstance(tool_calls, list):
return api_msg
diff --git a/agent/retry_utils.py b/agent/retry_utils.py
index 9fc4852cb31..2e3c88f58aa 100644
--- a/agent/retry_utils.py
+++ b/agent/retry_utils.py
@@ -27,11 +27,8 @@ _ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS = 3
def parse_retry_after_seconds(value_or_headers: Any) -> Optional[float]:
- """Parse a ``Retry-After`` value (numeric / HTTP-date) or a headers mapping into seconds.
-
- Both casings are tried for plain dicts (real header containers are already
- case-insensitive). Clamped at 0.0; None when absent / unparseable.
- """
+ """Parse a ``Retry-After`` value (numeric / HTTP-date) or a headers mapping (both casings tried) into
+ seconds, clamped at 0.0; None when absent / unparseable."""
raw = value_or_headers
if raw is not None and not isinstance(raw, (str, int, float)):
getter = getattr(raw, "get", None)
@@ -104,12 +101,8 @@ def adaptive_rate_limit_backoff(
attempt: int, *, base_url: str | None, model: str | None, error: Any, default_wait: float,
short_attempts: int = _ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS,
) -> tuple[float, str | None]:
- """Provider-aware rate-limit backoff → ``(wait_seconds, reason_label)``.
-
- Most providers get ``default_wait`` unchanged. Z.AI Coding GLM-5.2 overloads keep
- ``short_attempts`` short retries, then 30→60→90→120s (capped) with light jitter so long
- waits stay readable. ``attempt`` is 1-based like the loop's log.
- """
+ """``(wait_seconds, reason_label)``: ``default_wait`` for most providers; Z.AI Coding GLM-5.2 overloads keep
+ ``short_attempts`` short retries, then 30→60→90→120s with light jitter. ``attempt`` is 1-based."""
if not is_zai_coding_overload_error(base_url=base_url, model=model, error=error):
return default_wait, None
if attempt <= short_attempts:
diff --git a/agent/review_engine.py b/agent/review_engine.py
index ca653c178b8..68a00e38976 100644
--- a/agent/review_engine.py
+++ b/agent/review_engine.py
@@ -48,10 +48,8 @@ def _message_text(message: Dict[str, Any]) -> str:
def snapshot_recent_messages(messages: List[Dict[str, Any]], limit: int = DEFAULT_CONTEXT_MESSAGES) -> List[Dict[str, str]]:
- """Last ``limit`` user/assistant messages as {role, text} dicts, oldest first.
-
- System messages, tool results and empty-text messages (pure tool-call stubs) are excluded.
- """
+ """Last ``limit`` user/assistant messages with text as {role, text}, oldest first (system, tool and
+ pure tool-call stubs excluded)."""
out: List[Dict[str, str]] = []
for message in reversed(list(messages or [])):
if not isinstance(message, dict):
@@ -70,13 +68,9 @@ def snapshot_recent_messages(messages: List[Dict[str, Any]], limit: int = DEFAUL
def collect_parent_loaded_skills(parent_agent, messages: List[Dict[str, Any]], limit: int = 8) -> List[str]:
- """Names of skills the parent agent was operating under.
-
- Launch-preloaded skills come from the stable marker in the parent's
- ``ephemeral_system_prompt``; mid-session loads from ``skill_view`` tool calls in the
- history. Preloaded first, then history loads, deduped, capped at ``limit`` (a reviewer
- told to load 30 skills would burn its budget before working).
- """
+ """Skills the parent was operating under: launch-preloaded (marker in ``ephemeral_system_prompt``)
+ first, then ``skill_view`` loads from history, deduped, capped at ``limit`` (a reviewer told to load 30
+ skills would burn its budget before working)."""
names: List[str] = []
prompt = str(getattr(parent_agent, "ephemeral_system_prompt", "") or "")
candidates = [m.group(1) for m in re.finditer(r'with the "([^"]+)" skill\s+preloaded', prompt)]
@@ -137,11 +131,8 @@ def build_review_task(snapshot: List[Dict[str, str]], user_prompt: str = "", loa
def _load_review_credentials_cfg() -> Optional[Dict[str, Any]]:
- """Read ``auxiliary.review`` into a delegation-credentials-shaped dict.
-
- None when nothing is configured (provider=auto/empty and no model/base_url): the
- reviewer then inherits the parent agent's credentials.
- """
+ """``auxiliary.review`` as a delegation-credentials dict, or None when unconfigured (provider auto/empty
+ and no model/base_url) so the reviewer inherits the parent's credentials."""
try:
from hermes_cli.config import load_config_readonly
@@ -160,13 +151,9 @@ def _load_review_credentials_cfg() -> Optional[Dict[str, Any]]:
def start_review(parent_agent, messages: List[Dict[str, Any]], user_prompt: str = "") -> Dict[str, Any]:
- """Dispatch the reviewer subagent in the background.
-
- Returns the parsed ``delegate_task`` dispatch dict (``status: "dispatched"`` with a
- ``delegation_id``, or the synchronous result dict on channels that cannot route async
- completions). Raises ValueError when there is nothing to review or the dispatch is
- rejected/errored.
- """
+ """Dispatch the reviewer subagent; returns the parsed ``delegate_task`` dict (``status: "dispatched"`` +
+ ``delegation_id``, or the synchronous result on channels without async completions). Raises ValueError
+ when there is nothing to review or the dispatch is rejected/errored."""
if parent_agent is None:
raise ValueError("No active agent — send a message first.")
diff --git a/agent/review_idle_queue.py b/agent/review_idle_queue.py
index c59c13cf237..84bf204a9f2 100644
--- a/agent/review_idle_queue.py
+++ b/agent/review_idle_queue.py
@@ -1,20 +1,13 @@
"""Idle deferral for background reviews on the managed local runtime.
-When the review runtime IS the managed llama-server, the post-turn review fork monopolizes
-the GPU the user's next prompt needs, and the next live turn cancels it — an active
-session pays the decode cost AND loses the learning. Only the execution moment moves:
-reviews bound for the managed local endpoint are queued and dispatched when the machine
-is quiet; everything else runs immediately. Policy ``auxiliary.background_review.defer``:
-``auto`` (default) defers exactly when the review runtime targets the managed local
-server; ``never`` is the old behavior. Explicit /refine (focus set) never defers.
-
-Queue semantics: one slot per session, newest snapshot wins (a review replays the whole
-conversation, so coalescing is deduplication, not loss); preempted reviews are requeued by
-the spawn wrapper observing the run token's cancel flag; aged-out events (defer_max_age_s,
-default 30 min) dispatch regardless of idleness — deferral may delay learning, never lose
-it; in-memory best-effort, dropped on process exit like the immediate fork. Idle truth
-comes from the supervisor's /slots (machine-level, sees every client incl. other profiles)
-and must hold for a settle window so a review is not launched between two quick prompts.
+On the managed llama-server the post-turn review fork monopolizes the GPU the next prompt
+needs and the next live turn cancels it (decode cost paid, learning lost). Reviews bound for
+the managed endpoint are therefore queued and dispatched when the machine is quiet
+(``auxiliary.background_review.defer``: ``auto`` = exactly that case, ``never`` = old behavior;
+explicit /refine never defers). One slot per session, newest snapshot wins (a review replays
+the whole conversation, so coalescing is dedup, not loss); aged-out items (defer_max_age_s,
+default 30 min) dispatch regardless of idleness; in-memory best-effort like the immediate
+fork. Idle truth is the supervisor's /slots held for a settle window.
"""
from __future__ import annotations
@@ -29,13 +22,9 @@ from typing import Any, Callable, Dict, Optional
logger = logging.getLogger(__name__)
-# Sustained-quiet window before dispatch: two back-to-back prompts must not look idle,
-# a coffee break must run the queue.
-_IDLE_SETTLE_S = 15.0
-# Poll cadence while the queue is non-empty; the thread parks when empty.
-_POLL_INTERVAL_S = 5.0
-# Age at which a queued review dispatches regardless of idleness.
-_MAX_AGE_DEFAULT_S = 30.0 * 60.0
+_IDLE_SETTLE_S = 15.0 # quiet window: two back-to-back prompts must not look idle, a coffee break must
+_POLL_INTERVAL_S = 5.0 # poll cadence while non-empty; the thread parks when empty
+_MAX_AGE_DEFAULT_S = 30.0 * 60.0 # dispatch regardless of idleness past this age
def defer_mode(task_cfg: Optional[Dict[str, Any]]) -> str:
@@ -53,14 +42,9 @@ def defer_max_age_s(task_cfg: Optional[Dict[str, Any]]) -> float:
def review_targets_managed_local(agent: Any, task_cfg: Optional[Dict[str, Any]]) -> bool:
- """Would this review fork decode on the llama-server WE manage?
-
- Resolves the review runtime as the fork will and exact-matches its netloc against
- the supervisor state file (cannot false-positive on external local servers). Any
- failure reads False: immediate spawn is the safe default. The netloc probe (one
- TTL-cached state-file read) runs FIRST so cloud-only installs return False without
- resolving the runtime on the turn's tail.
- """
+ """Would this review fork decode on the llama-server WE manage? Exact netloc match against the
+ supervisor state file; any failure reads False (immediate spawn is the safe default). The cheap
+ TTL-cached netloc probe runs FIRST so cloud-only installs skip runtime resolution on the turn's tail."""
try:
from agent.auxiliary_client import _is_managed_local_endpoint, _managed_local_netloc
@@ -113,11 +97,8 @@ class ReviewIdleQueue:
# ── queue ────────────────────────────────────────────────────
def enqueue(self, agent: Any, session_key: str, kwargs: Dict[str, Any]) -> None:
- """Add (or replace — newest snapshot wins) a session's pending review.
-
- Keeps the ORIGINAL enqueue time on coalesce so a busy session cannot push its
- review's age-out forever.
- """
+ """Add (or replace — newest snapshot wins) a session's pending review, keeping the ORIGINAL
+ enqueue time on coalesce so a busy session cannot push its age-out forever."""
with self._lock:
existing = self._pending.get(session_key)
enqueued_at = existing.enqueued_at if existing is not None else self._now()
@@ -190,8 +171,7 @@ class ReviewIdleQueue:
@staticmethod
def _still_enabled(item: _PendingReview) -> bool:
- """Re-check the enabled gate at DISPATCH time (minutes may pass in the queue;
- disabling reviews meanwhile must not be resurrected). Fail-open like the gate."""
+ """Re-check the enabled gate at DISPATCH time (disabling reviews while queued must stick). Fail-open."""
try:
from agent.background_review import load_background_review_settings
@@ -201,8 +181,7 @@ class ReviewIdleQueue:
def _managed_server_idle() -> bool:
- """Machine-level idle: no processing slot on any loaded model of the managed router.
- Unreachable/no state file reads idle (nothing to contend with)."""
+ """No processing slot on any loaded model of the managed router; unreachable/no state file reads idle."""
try:
from hermes_cli.local_runtime.supervisor import state_path
from urllib.parse import quote