refactor(agent/retry_utils,runtime_cwd,ssl_*): inline single-use helpers, reuse is_truthy_value, compact docs

This commit is contained in:
Teknium
2026-09-02 18:36:16 -07:00
parent bfb7ba20d2
commit 0e1e86bef4
4 changed files with 43 additions and 81 deletions
+17 -27
View File
@@ -16,24 +16,21 @@ from typing import Any, Optional
_jitter_counter = 0
_jitter_lock = threading.Lock()
# Z.AI Coding Plan's GLM-5.2 endpoint often returns 429 code 1305 ("service
# may be temporarily overloaded"). Short retries hammer the same window, so
# after a few normal retries the wait widens progressively. Cap stays
# interactive-friendly: a TUI message should fail visibly in minutes.
# Z.AI Coding Plan's GLM-5.2 endpoint often returns 429 code 1305 ("service may be
# temporarily overloaded"). Short retries hammer the same window, so after
# ``_ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS`` normal retries the wait widens progressively;
# the cap stays interactive-friendly (a TUI message should fail visibly in minutes).
# The short count is shared by ``adaptive_rate_limit_backoff`` and
# ``zai_coding_overload_retry_ceiling`` so the two cannot silently desync.
_ZAI_CODING_OVERLOAD_LONG_BACKOFF = (30.0, 60.0, 90.0, 120.0)
# Short retries before the long tier. Shared by ``adaptive_rate_limit_backoff``
# (walks the long table from attempt ``short_attempts + 1``) and
# ``zai_coding_overload_retry_ceiling`` (sizes the loop so every long entry is
# reachable) so the two cannot silently desync.
_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 / number) or a headers
mapping into seconds. Both casings are tried for plain dicts (real header
containers are already case-insensitive). Float clamped at 0.0, or None
when absent / unparseable.
"""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.
"""
raw = value_or_headers
if raw is not None and not isinstance(raw, (str, int, float)):
@@ -119,28 +116,21 @@ def adaptive_rate_limit_backoff(
) -> 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. ``attempt`` is 1-based like the loop's log.
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.
"""
if not is_zai_coding_overload_error(base_url=base_url, model=model, error=error):
return default_wait, None
if attempt <= short_attempts:
return default_wait, "zai_coding_overload_short"
idx = min(attempt - short_attempts - 1, len(_ZAI_CODING_OVERLOAD_LONG_BACKOFF) - 1)
base_delay = _ZAI_CODING_OVERLOAD_LONG_BACKOFF[idx]
# Smaller jitter keeps long waits readable while still de-synchronizing.
wait = jittered_backoff(1, base_delay=base_delay, max_delay=base_delay, jitter_ratio=0.2)
return wait, "zai_coding_overload_long"
return jittered_backoff(1, base_delay=base_delay, max_delay=base_delay, jitter_ratio=0.2), "zai_coding_overload_long"
def zai_coding_overload_retry_ceiling(short_attempts: int = _ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS) -> int:
"""Retry-loop ceiling for the full Z.AI overload schedule.
The loop gives up when ``retry_count >= ceiling`` *before* computing the
attempt's backoff, so the ceiling must sit one past the last long entry
or the long tier never runs (the default ``api_max_retries`` of 3 equals
``short_attempts``).
"""
"""Retry-loop ceiling for the full Z.AI overload schedule: one past the last long entry,
because the loop gives up when ``retry_count >= ceiling`` BEFORE computing the attempt's
backoff (the default ``api_max_retries`` of 3 equals ``short_attempts``)."""
return short_attempts + len(_ZAI_CODING_OVERLOAD_LONG_BACKOFF) + 1
+19 -36
View File
@@ -1,10 +1,10 @@
"""Single source of truth for the agent working directory.
`TERMINAL_CWD` is the runtime carrier for the configured working directory
(`terminal.cwd` is bridged to it once at gateway/cron startup; the local CLI
leaves it unset and relies on the launch dir). Reading it in one place keeps the
system prompt, tool surfaces, and context-file discovery agreeing on where the
agent lives. Multi-session gateways can pin a logical cwd via `_SESSION_CWD`.
`TERMINAL_CWD` is the runtime carrier for the configured working directory (`terminal.cwd`
is bridged to it once at gateway/cron startup; the local CLI leaves it unset and relies on
the launch dir). Reading it in one place keeps the system prompt, tool surfaces, and
context-file discovery agreeing on where the agent lives. Multi-session gateways can pin a
logical cwd via `_SESSION_CWD`.
"""
import logging
@@ -19,9 +19,9 @@ _UNSET: Any = object()
_SESSION_CWD: ContextVar = ContextVar("HERMES_SESSION_CWD", default=_UNSET)
# The package/source root (<root>/agent/runtime_cwd.py). A backend launched from
# or self-spawned into this tree (desktop default) must never let an os.getcwd()
# fallback inject this repo's contributor AGENTS.md as project context.
# The package/source root (<root>/agent/runtime_cwd.py). A backend launched from or
# self-spawned into this tree (desktop default) must never let an os.getcwd() fallback
# inject this repo's contributor AGENTS.md as project context.
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent
@@ -44,20 +44,12 @@ def clear_session_cwd() -> None:
_SESSION_CWD.set("")
def _session_cwd_override() -> str:
value = _SESSION_CWD.get()
if value is _UNSET:
return ""
return str(value).strip()
def scope_terminal_cwd() -> str:
"""Scope-aware TERMINAL_CWD value (may be empty) — every cwd consumer reads through this.
def _terminal_cwd_env() -> str:
"""Scope-aware TERMINAL_CWD read (tools.terminal_scope.terminal_env).
Under gateway multiplexing the per-turn terminal scope carries the active
profile's cwd; the process-global env var may hold another profile's. Only
an ImportError falls back: an active refusal scope must raise, not silently
resolve the launch profile's cwd.
Under gateway multiplexing the per-turn terminal scope carries the active profile's cwd;
the process-global env var may hold another profile's. Only an ImportError falls back: an
active refusal scope must raise, not silently resolve the launch profile's cwd.
"""
try:
from tools.terminal_scope import terminal_env
@@ -66,22 +58,14 @@ def _terminal_cwd_env() -> str:
return terminal_env("TERMINAL_CWD", "")
def scope_terminal_cwd() -> str:
"""Public wrapper — the scope-aware TERMINAL_CWD value (may be empty).
Shared by agent_init / skill_utils / code_execution_tool so every cwd consumer
reads through the per-turn terminal scope under gateway multiplexing.
"""
return _terminal_cwd_env()
def _resolve_configured_cwd(*, override_is_final: bool) -> Path | None:
"""Session override, then TERMINAL_CWD; each validated as a real directory.
``override_is_final``: a set-but-missing session override yields None
instead of falling through to TERMINAL_CWD.
"""
override = _session_cwd_override()
override = _SESSION_CWD.get()
override = "" if override is _UNSET else str(override).strip()
if override:
p = Path(override).expanduser()
if p.is_dir():
@@ -89,7 +73,7 @@ def _resolve_configured_cwd(*, override_is_final: bool) -> Path | None:
logger.warning("configured working directory does not exist: %s", override)
if override_is_final:
return None
raw = _terminal_cwd_env().strip()
raw = scope_terminal_cwd().strip()
if raw:
p = Path(raw).expanduser()
if p.is_dir():
@@ -108,10 +92,9 @@ def resolve_agent_cwd() -> Path:
def resolve_context_cwd() -> Path | None:
"""Configured cwd for context-file discovery, or None for "no configured cwd".
None makes build_context_files_prompt fall back to the launch dir (correct
for a local CLI launched inside a real project). A configured path is
validated here; an existing one is honored verbatim — including the Hermes
source tree itself, a legitimate workspace when developing Hermes
None makes build_context_files_prompt fall back to the launch dir (correct for a local CLI
launched inside a real project). An existing configured path is honored verbatim —
including the Hermes source tree itself, a legitimate workspace when developing Hermes
(fallback-directory policy lives in build_context_files_prompt).
"""
return _resolve_configured_cwd(override_is_final=True)
+2 -6
View File
@@ -9,11 +9,11 @@ import ssl
from pathlib import Path
from agent.errors import SSLConfigurationError
from utils import is_truthy_value
logger = logging.getLogger(__name__)
_CA_BUNDLE_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE")
_SKIP_VALUES = {"1", "true", "yes", "on"}
_REPAIR_HINT = (
"Repair: run `hermes doctor --fix` (auto-reinstalls certifi), or "
"manually: python -m pip install --force-reinstall certifi openai httpx\n"
@@ -22,10 +22,6 @@ _REPAIR_HINT = (
)
def _skip_ssl_guard_enabled() -> bool:
return os.getenv("HERMES_SKIP_SSL_GUARD", "").strip().lower() in _SKIP_VALUES
def _ssl_err(message: str) -> SSLConfigurationError:
"""Create a consistent, user-actionable SSL configuration error."""
return SSLConfigurationError(f"{message}\n{_REPAIR_HINT}")
@@ -58,7 +54,7 @@ def verify_ca_bundle() -> None:
Raises SSLConfigurationError when an explicit CA-bundle env var points at a
bad path or certifi's bundled ``cacert.pem`` is missing/corrupt.
"""
if _skip_ssl_guard_enabled():
if is_truthy_value(os.getenv("HERMES_SKIP_SSL_GUARD", "")):
logger.debug("SSL CA bundle guard skipped via HERMES_SKIP_SSL_GUARD")
return
for env_var in _CA_BUNDLE_ENV_VARS:
+5 -12
View File
@@ -11,12 +11,7 @@ from typing import Any, Optional
logger = logging.getLogger(__name__)
_CA_BUNDLE_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE")
def _coerce_insecure(ssl_verify: Any) -> bool:
if ssl_verify is False:
return True
return isinstance(ssl_verify, str) and ssl_verify.strip().lower() in {"false", "0", "no", "off"}
_INSECURE_STRINGS = {"false", "0", "no", "off"}
def resolve_httpx_verify(
@@ -27,7 +22,7 @@ def resolve_httpx_verify(
) -> bool | ssl.SSLContext:
"""Resolve httpx ``verify``: ``ssl_verify: false`` > explicit ``ca_bundle`` >
CA-bundle env vars > ``True`` (certifi default). ``base_url`` only feeds the warning."""
if _coerce_insecure(ssl_verify):
if ssl_verify is False or (isinstance(ssl_verify, str) and ssl_verify.strip().lower() in _INSECURE_STRINGS):
logger.warning(
"TLS certificate verification DISABLED (ssl_verify: false) for %s — "
"this is intended for local development only and is unsafe on any "
@@ -36,11 +31,9 @@ def resolve_httpx_verify(
)
return False
effective_ca = (ca_bundle or "").strip()
for env_var in _CA_BUNDLE_ENV_VARS:
if effective_ca:
break
effective_ca = os.getenv(env_var, "").strip()
effective_ca = (ca_bundle or "").strip() or next(
(v for v in (os.getenv(var, "").strip() for var in _CA_BUNDLE_ENV_VARS) if v), "",
)
if effective_ca:
ca_path = str(Path(effective_ca).expanduser())
if os.path.isfile(ca_path):