Skip to content

The agent that grows with you

fix(cron): isolate lazy imports from stale modules

fangliquanflqfd1d8271dbaf
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 7acd0f88ddc..ea2046763eb 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1347,8 +1347,8 @@ def init_agent(
elif base_url_host_matches(effective_base, "portal.qwen.ai"):
client_kwargs["default_headers"] = _ra()._qwen_portal_headers()
elif base_url_host_matches(effective_base, "chatgpt.com"):
- from agent.auxiliary_client import _codex_cloudflare_headers
- client_kwargs["default_headers"] = _codex_cloudflare_headers(
+ from agent.codex_headers import codex_cloudflare_headers
+ client_kwargs["default_headers"] = codex_cloudflare_headers(
api_key, base_url=effective_base,
)
elif base_url_host_matches(effective_base, "x.ai"):
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index c5eb9b34fc6..58cc307fff8 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2842,9 +2842,9 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
# All primary construction and recovery paths must identify Hermes to the
# official Codex endpoint, including snapshots with custom header overrides.
- from agent.auxiliary_client import _apply_required_codex_headers
+ from agent.codex_headers import apply_required_codex_headers
- _apply_required_codex_headers(
+ apply_required_codex_headers(
client_kwargs,
access_token=client_kwargs.get("api_key", ""),
base_url=str(client_kwargs.get("base_url", "")),
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 7ddb60f7c67..645c78c2325 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -62,6 +62,13 @@ from types import SimpleNamespace
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, TYPE_CHECKING
from urllib.parse import urlparse, parse_qs, urlunparse
+from agent.codex_headers import (
+ CODEX_AUX_BASE_URL as _CODEX_AUX_BASE_URL,
+ apply_required_codex_headers as _apply_required_codex_headers,
+ codex_cloudflare_headers as _codex_cloudflare_headers,
+ is_official_codex_base_url as _is_official_codex_base_url,
+)
+
# NOTE: `from openai import OpenAI` is deliberately NOT at module top — the
# openai SDK pulls a large type tree (~240 ms cold, including responses/*,
# graders/*). We expose `OpenAI` here as a thin proxy that imports the SDK on
@@ -1326,89 +1333,10 @@ _NOUS_DEFAULT_BASE_URL = "https://inference-api.nousresearch.com/v1"
_ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com"
_AUTH_JSON_PATH = get_hermes_home() / "auth.json"
-# Codex OAuth endpoint used when a caller explicitly requests
-# provider="openai-codex". There is deliberately no hardcoded default
-# model: the set of models OpenAI accepts on this endpoint for
-# ChatGPT-account auth is an undocumented, shifting allow-list, and
-# pinning one here has drifted silently twice (gpt-5.3-codex → gpt-5.2-codex
-# → gpt-5.4 over 6 weeks in early 2026). Callers must pass the model
-# they want explicitly (from config.yaml model.model, auxiliary.<task>.model,
-# or the user's active Codex model selection).
-_CODEX_AUX_BASE_URL = "https://chatgpt.com/backend-api/codex"
-
-
-def _is_official_codex_base_url(base_url: str) -> bool:
- """Identify OpenAI's Codex endpoint without matching custom proxies."""
- try:
- parsed = urlparse(base_url)
- path = parsed.path.rstrip("/")
- return (
- parsed.scheme == "https"
- and parsed.hostname == "chatgpt.com"
- and parsed.port in (None, 443)
- and (path == "/backend-api/codex" or path.startswith("/backend-api/codex/"))
- )
- except (TypeError, ValueError):
- return False
-
-
-def _codex_cloudflare_headers(
- access_token: str, *, base_url: str = _CODEX_AUX_BASE_URL,
-) -> Dict[str, str]:
- """Identity and account headers for chatgpt.com/backend-api/codex.
-
- OpenAI requires third-party harnesses to identify themselves. Requests to
- the official endpoint always send Hermes' originator and version. Custom
- endpoints retain the existing compatibility identity. In either case,
- preserve ``ChatGPT-Account-ID`` from the OAuth JWT's
- ``chatgpt_account_id`` claim.
-
- Malformed tokens are tolerated — we drop the account-ID header rather than
- raise, so a bad token still surfaces as an auth error (401) instead of a
- crash at client construction.
- """
- headers = {
- "User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)",
- "originator": "codex_cli_rs",
- }
- if _is_official_codex_base_url(base_url):
- from hermes_cli import __version__
-
- headers.update({
- "User-Agent": f"HermesAgent/{__version__}",
- "originator": "hermes-agent",
- })
- if not isinstance(access_token, str) or not access_token.strip():
- return headers
- try:
- import base64
- parts = access_token.split(".")
- if len(parts) < 2:
- return headers
- payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
- claims = json.loads(base64.urlsafe_b64decode(payload_b64))
- acct_id = claims.get("https://api.openai.com/auth", {}).get("chatgpt_account_id")
- if isinstance(acct_id, str) and acct_id:
- headers["ChatGPT-Account-ID"] = acct_id
- except Exception:
- pass
- return headers
-
-
-def _apply_required_codex_headers(
- client_kwargs: Dict[str, Any], *, access_token: str, base_url: str,
-) -> None:
- """Keep required Codex identity after user/provider header overrides."""
- if not _is_official_codex_base_url(base_url):
- return
- required = _codex_cloudflare_headers(access_token, base_url=base_url)
- required_names = {name.lower() for name in required}
- existing = client_kwargs.get("default_headers") or {}
- client_kwargs["default_headers"] = {
- **{name: value for name, value in existing.items()
- if str(name).lower() not in required_names},
- **required,
- }
+# Codex helpers live in a small leaf module so fresh client builders never
+# request newly added exports from a stale, long-lived auxiliary router. The
+# private aliases above preserve the established import surface for plugins and
+# tests while new production consumers import the leaf directly.
# Hosts that expose BOTH an Anthropic-style ``…/anthropic`` path and a sibling
diff --git a/agent/codex_headers.py b/agent/codex_headers.py
new file mode 100644
index 00000000000..607ba4055bc
--- /dev/null
+++ b/agent/codex_headers.py
@@ -0,0 +1,92 @@
+"""Codex request identity helpers shared by agent client builders.
+
+This leaf module intentionally has no dependency on the large auxiliary-client
+router. Long-lived processes can therefore import a newly added client builder
+without resolving a new symbol from an older cached ``auxiliary_client`` module.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+from typing import Any, Dict
+from urllib.parse import urlparse
+
+
+CODEX_AUX_BASE_URL = "https://chatgpt.com/backend-api/codex"
+
+
+def is_official_codex_base_url(base_url: str) -> bool:
+ """Identify OpenAI's Codex endpoint without matching custom proxies."""
+ try:
+ parsed = urlparse(base_url)
+ path = parsed.path.rstrip("/")
+ return (
+ parsed.scheme == "https"
+ and parsed.hostname == "chatgpt.com"
+ and parsed.port in (None, 443)
+ and (path == "/backend-api/codex" or path.startswith("/backend-api/codex/"))
+ )
+ except (TypeError, ValueError):
+ return False
+
+
+def codex_cloudflare_headers(
+ access_token: str, *, base_url: str = CODEX_AUX_BASE_URL,
+) -> Dict[str, str]:
+ """Identity and account headers for chatgpt.com/backend-api/codex.
+
+ OpenAI requires third-party harnesses to identify themselves. Requests to
+ the official endpoint always send Hermes' originator and version. Custom
+ endpoints retain the existing compatibility identity. In either case,
+ preserve ``ChatGPT-Account-ID`` from the OAuth JWT's
+ ``chatgpt_account_id`` claim.
+
+ Malformed tokens are tolerated — we drop the account-ID header rather than
+ raise, so a bad token still surfaces as an auth error (401) instead of a
+ crash at client construction.
+ """
+ headers = {
+ "User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)",
+ "originator": "codex_cli_rs",
+ }
+ if is_official_codex_base_url(base_url):
+ from hermes_cli import __version__
+
+ headers.update({
+ "User-Agent": f"HermesAgent/{__version__}",
+ "originator": "hermes-agent",
+ })
+ if not isinstance(access_token, str) or not access_token.strip():
+ return headers
+ try:
+ parts = access_token.split(".")
+ if len(parts) < 2:
+ return headers
+ payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
+ claims = json.loads(base64.urlsafe_b64decode(payload_b64))
+ acct_id = claims.get("https://api.openai.com/auth", {}).get("chatgpt_account_id")
+ if isinstance(acct_id, str) and acct_id:
+ headers["ChatGPT-Account-ID"] = acct_id
+ except Exception:
+ pass
+ return headers
+
+
+def apply_required_codex_headers(
+ client_kwargs: Dict[str, Any], *, access_token: str, base_url: str,
+) -> None:
+ """Keep required Codex identity after user/provider header overrides."""
+ if not is_official_codex_base_url(base_url):
+ return
+ required = codex_cloudflare_headers(access_token, base_url=base_url)
+ required_names = {name.lower() for name in required}
+ existing = client_kwargs.get("default_headers") or {}
+ client_kwargs["default_headers"] = {
+ **{
+ name: value
+ for name, value in existing.items()
+ if str(name).lower() not in required_names
+ },
+ **required,
+ }
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 22595d0412e..f8dee11cbd1 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -7645,7 +7645,12 @@ def _run_one_job_body(
# anything that isn't a plain Exception. Owner fencing still applies:
# a stale worker must not record over a replacement claim owner.
_err_text = str(e) or type(e).__name__
- logger.error("Error processing job %s: %s", job['id'], _err_text)
+ logger.error(
+ "Error processing job %s: %s",
+ job["id"],
+ _err_text,
+ exc_info=(type(e), e, e.__traceback__),
+ )
delivery_outcome = "suppressed"
# Owner fencing: a stale worker whose fire claim was taken over (or a
# transport-cancelled worker) must not send a failure alert on top of
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index fede9adf49e..3bae3ab645f 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1594,7 +1594,7 @@ def _docker_sandbox_dir_candidates(session_key: str = "") -> List[str]:
"""
candidates: List[str] = []
try:
- from tools.environments.base import sanitize_task_id_for_path
+ from tools.environments.path_utils import sanitize_task_id_for_path
except Exception:
return ["default"]
# Explicit trusted-profiles opt-in: one shared container identity.
diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.py
index 3104aec4719..9823425e946 100644
--- a/plugins/image_gen/openai-codex/__init__.py
+++ b/plugins/image_gen/openai-codex/__init__.py
@@ -469,9 +469,9 @@ def _collect_image_b64(
callers must not treat partial-only as an unconditional success.
"""
import httpx
- from agent.auxiliary_client import _codex_cloudflare_headers
+ from agent.codex_headers import codex_cloudflare_headers
- headers = _codex_cloudflare_headers(token)
+ headers = codex_cloudflare_headers(token)
headers.update({
"Accept": "text/event-stream",
"Authorization": f"Bearer {token}",
diff --git a/run_agent.py b/run_agent.py
index 87e8c941d3a..d056fbd698d 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -6401,8 +6401,8 @@ class AIAgent:
elif base_url_host_matches(base_url, "portal.qwen.ai"):
self._client_kwargs["default_headers"] = _qwen_portal_headers()
elif base_url_host_matches(base_url, "chatgpt.com"):
- from agent.auxiliary_client import _codex_cloudflare_headers
- self._client_kwargs["default_headers"] = _codex_cloudflare_headers(
+ from agent.codex_headers import codex_cloudflare_headers
+ self._client_kwargs["default_headers"] = codex_cloudflare_headers(
self._client_kwargs.get("api_key", ""), base_url=base_url,
)
elif base_url_host_matches(base_url, "x.ai"):
diff --git a/tests/cron/test_stale_module_leaf_imports.py b/tests/cron/test_stale_module_leaf_imports.py
new file mode 100644
index 00000000000..5b706182cd3
--- /dev/null
+++ b/tests/cron/test_stale_module_leaf_imports.py
@@ -0,0 +1,71 @@
+"""Regression tests for lazy consumers importing from stale cached modules.
+
+The scheduled cron lane constructs a fresh agent inside a long-lived gateway.
+These tests model the field failure directly: a foundational module remains in
+``sys.modules`` but lacks a symbol added by newer consumer code on disk.
+"""
+
+from __future__ import annotations
+
+import importlib
+import logging
+import sys
+from types import SimpleNamespace
+
+
+def test_primary_client_ignores_stale_auxiliary_router(monkeypatch):
+ from agent import agent_runtime_helpers, auxiliary_client
+
+ # Model a gateway that cached auxiliary_client before the Codex header
+ # helper was added. The fresh runtime helper must use the leaf module rather
+ # than asking this stale module object for the new export.
+ monkeypatch.delattr(auxiliary_client, "_apply_required_codex_headers")
+
+ captured: dict = {}
+
+ def fake_openai(**kwargs):
+ captured.update(kwargs)
+ return object()
+
+ monkeypatch.setattr(
+ agent_runtime_helpers,
+ "_ra",
+ lambda: SimpleNamespace(OpenAI=fake_openai, logger=logging.getLogger(__name__)),
+ )
+ agent = SimpleNamespace(
+ provider="openai-codex",
+ _build_keepalive_http_client=lambda *_args, **_kwargs: None,
+ _client_log_context=lambda: "test",
+ )
+
+ agent_runtime_helpers.create_openai_client(
+ agent,
+ {
+ "api_key": "token",
+ "base_url": "https://chatgpt.com/backend-api/codex",
+ },
+ reason="test",
+ shared=False,
+ )
+
+ assert captured["default_headers"]["originator"] == "hermes-agent"
+
+
+def test_docker_import_ignores_stale_base_environment(monkeypatch):
+ from tools.environments import base
+ from tools.environments.path_utils import sanitize_task_id_for_path
+
+ # Model base.py cached before the shared sanitizer existed. A Docker module
+ # imported later by tool discovery must get the helper from the leaf module.
+ monkeypatch.delattr(base, "sanitize_task_id_for_path")
+ previous = sys.modules.pop("tools.environments.docker", None)
+ try:
+ docker = importlib.import_module("tools.environments.docker")
+ assert docker._sandbox_dir_name is sanitize_task_id_for_path
+ assert docker._sandbox_dir_name("session:cron:job") == sanitize_task_id_for_path(
+ "session:cron:job"
+ )
+ finally:
+ sys.modules.pop("tools.environments.docker", None)
+ if previous is not None:
+ sys.modules["tools.environments.docker"] = previous
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 1ab32f8a808..46f3d14f531 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -7,7 +7,6 @@ or a temp file (local).
"""
import codecs
-import hashlib
import json
import logging
import os
@@ -26,6 +25,12 @@ from typing import IO, Callable, Iterable, Protocol
from hermes_constants import get_hermes_home
from hermes_cli._subprocess_compat import windows_hide_flags
from tools.interrupt import is_interrupted
+from tools.environments.path_utils import (
+ _SANDBOX_DIR_HASH_LEN,
+ _SANDBOX_DIR_MAX_LEN,
+ _SANDBOX_DIR_UNSAFE_RE,
+ sanitize_task_id_for_path,
+)
logger = logging.getLogger(__name__)
@@ -295,58 +300,6 @@ def get_sandbox_dir() -> Path:
return p
-# A persistent sandbox's host directory is named after task_id, and that name
-# then becomes the source half of a `-v <source>:<target>` spec (Docker) or a
-# writable-overlay directory (Singularity). Docker splits the spec on ':', so
-# a colon-bearing name arrives as extra mount fields and the run is refused
-# outright ("invalid spec ... too many colons" / "invalid mode", exit 125).
-# Path separators would additionally escape the sandbox root, and Windows
-# forbids ':' in path segments entirely.
-_SANDBOX_DIR_UNSAFE_RE = re.compile(r"[^A-Za-z0-9._-]")
-_SANDBOX_DIR_MAX_LEN = 128
-_SANDBOX_DIR_HASH_LEN = 12
-
-
-def sanitize_task_id_for_path(task_id: str) -> str:
- """Return a bind-mountable directory name for *task_id*'s sandbox.
-
- Shared by every environment backend that turns a task id into a host
- filesystem path component (Docker persistent sandboxes, Singularity
- persistent overlays). Names that are already safe are returned verbatim,
- so the shared ``default`` sandbox and RL/benchmark task ids keep resolving
- to the directory they have always used — no installed package or ``/root``
- state moves. Only ids that could never have produced a working bind mount
- are rewritten.
-
- A rewrite also appends a digest of the original id, because the character
- substitution alone is not injective: ``a:b`` and ``a_b`` would otherwise
- share one persistent sandbox and leak one session's ``/root`` into
- another's container. The digest is a pure function of the id, so the same
- session resolves to the same directory in every process — cross-process
- container reuse depends on that.
- """
- value = task_id if isinstance(task_id, str) else ""
- if not value:
- # An empty component collapses the path onto the sandbox root, which
- # would bind-mount every task's state at once.
- return "default"
-
- cleaned = _SANDBOX_DIR_UNSAFE_RE.sub("_", value)
- if (
- cleaned == value
- and len(value) <= _SANDBOX_DIR_MAX_LEN
- and value not in {".", ".."}
- # Windows silently strips trailing dots/spaces, aliasing two ids onto
- # one directory.
- and not value.endswith((".", " "))
- ):
- return value
-
- digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:_SANDBOX_DIR_HASH_LEN]
- stem = cleaned[: _SANDBOX_DIR_MAX_LEN - _SANDBOX_DIR_HASH_LEN - 1].strip("._")
- return f"{stem or 'task'}-{digest}"
-
-
# ---------------------------------------------------------------------------
# Shared constants and utilities
# ---------------------------------------------------------------------------
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index fe8f565568e..0d17249f6f1 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -22,8 +22,8 @@ from tools.environments.base import (
BaseEnvironment,
EnvironmentConnectionError,
_popen_bash,
- sanitize_task_id_for_path,
)
+from tools.environments.path_utils import sanitize_task_id_for_path
from tools.environments.local import (
_HERMES_PROVIDER_ENV_BLOCKLIST,
_is_hermes_internal_secret,
diff --git a/tools/environments/path_utils.py b/tools/environments/path_utils.py
new file mode 100644
index 00000000000..6d5dc1019d3
--- /dev/null
+++ b/tools/environments/path_utils.py
@@ -0,0 +1,44 @@
+"""Path-component helpers shared by execution environment backends.
+
+Kept separate from the base environment class so lazy backend imports do not
+depend on newly added exports from a large module cached earlier in a long-lived
+process.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+
+
+# A persistent sandbox's host directory is named after task_id, and that name
+# then becomes the source half of a Docker bind spec or a writable Singularity
+# overlay directory. Keep every backend on one collision-safe mapping.
+_SANDBOX_DIR_UNSAFE_RE = re.compile(r"[^A-Za-z0-9._-]")
+_SANDBOX_DIR_MAX_LEN = 128
+_SANDBOX_DIR_HASH_LEN = 12
+
+
+def sanitize_task_id_for_path(task_id: str) -> str:
+ """Return a bind-mountable directory name for *task_id*'s sandbox.
+
+ Names that are already safe are returned verbatim, preserving existing
+ sandbox locations. Rewritten names carry a digest because substitution
+ alone is not injective: ``a:b`` and ``a_b`` must not share state.
+ """
+ value = task_id if isinstance(task_id, str) else ""
+ if not value:
+ return "default"
+
+ cleaned = _SANDBOX_DIR_UNSAFE_RE.sub("_", value)
+ if (
+ cleaned == value
+ and len(value) <= _SANDBOX_DIR_MAX_LEN
+ and value not in {".", ".."}
+ and not value.endswith((".", " "))
+ ):
+ return value
+
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:_SANDBOX_DIR_HASH_LEN]
+ stem = cleaned[: _SANDBOX_DIR_MAX_LEN - _SANDBOX_DIR_HASH_LEN - 1].strip("._")
+ return f"{stem or 'task'}-{digest}"
diff --git a/tools/environments/singularity.py b/tools/environments/singularity.py
index 4c2dce53bac..b55043de639 100644
--- a/tools/environments/singularity.py
+++ b/tools/environments/singularity.py
@@ -20,8 +20,8 @@ from tools.environments.base import (
_load_json_store,
_popen_bash,
_save_json_store,
- sanitize_task_id_for_path,
)
+from tools.environments.path_utils import sanitize_task_id_for_path
logger = logging.getLogger(__name__)