The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: resolve the 33 F821 undefined names outside tui_gateway / feishu / godmode
kshitijk4poorc5ff9007616a
diff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.pyindex 32717f83c5a..ae0cb725555 100644--- a/gateway/platforms/helpers.py+++ b/gateway/platforms/helpers.py@@ -2,11 +2,14 @@stripping, thread participation tracking, GFM table → bullets, mention-patterncompilation, and fence-aware markdown chunking."""+from __future__ import annotations+import jsonimport loggingimport reimport timefrom pathlib import Path+from typing import Any, Protocolfrom utils import atomic_json_write@@ -522,6 +525,14 @@ from typing import TYPE_CHECKING # noqa: F401,E402import asyncio # noqa: F401,E402import asyncio # noqa: F401,E402+class BatchableEvent(Protocol):+ """What TextBatchAggregator needs from an inbound event. gateway.platforms.base.MessageEvent+ satisfies it; base imports this module at import time, so the concrete class cannot be named here."""++ text: str+ source: Any++class TextBatchAggregator:"""Aggregates rapid-fire text events into single messages.@@ -554,14 +565,14 @@ class TextBatchAggregator:self._batch_delay = batch_delayself._split_delay = split_delayself._split_threshold = split_threshold- self._pending: Dict[str, "MessageEvent"] = {}+ self._pending: Dict[str, BatchableEvent] = {}self._pending_tasks: Dict[str, asyncio.Task] = {}def is_enabled(self) -> bool:"""Return True if batching is active (delay > 0)."""return self._batch_delay > 0- def enqueue(self, event: "MessageEvent", key: str) -> None:+ def enqueue(self, event: BatchableEvent, key: str) -> None:"""Add *event* to the pending batch for *key*."""chunk_len = len(event.text or "")existing = self._pending.get(key)diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.pyindex bd3c3062804..9442805501c 100644--- a/gateway/platforms/whatsapp_common.py+++ b/gateway/platforms/whatsapp_common.py@@ -15,6 +15,7 @@ import jsonimport loggingimport osimport re+from pathlib import Pathfrom typing import Any, Dict, Optionalfrom gateway.platforms._shared import get_scoped_secret as _get_wsecret@@ -310,9 +311,8 @@ def resolve_whatsapp_bridge_dir() -> Path:"""Bridge directory for CLI and adapter. A read-only install tree (e.g. Docker/opt/hermes) is mirrored to HERMES_HOME so npm install works."""import shutil- from pathlib import Path as _Pathfrom hermes_constants import get_hermes_home- install_bridge = _Path(__file__).resolve().parents[2] / "scripts" / "whatsapp-bridge"+ install_bridge = Path(__file__).resolve().parents[2] / "scripts" / "whatsapp-bridge"hermes_home_bridge = get_hermes_home() / "scripts" / "whatsapp-bridge"try:(install_bridge / ".write_test").touch()diff --git a/gateway/run.py b/gateway/run.pyindex 1ccb18b541d..0e2faabbd0d 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -39,6 +39,7 @@ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIXfrom agent.interrupt_compat import request_hard_interruptfrom agent.turn_context import compression_made_progressfrom hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get+from agent.session_activity import ActivityProvenancefrom hermes_cli.fallback_config import get_fallback_chain# Per-session AIAgent cache bounds (agents are heavy); see _enforce_agent_cache_cap/_session_housekeeping_watcher.@@ -941,7 +942,7 @@ def _float_env(name: str, default: float) -> float:def _stamp_hygiene_compression_provenance(- agent: Any, desc: str, provenance: "ActivityProvenance", debug_label: str) -> None:+ agent: Any, desc: str, provenance: ActivityProvenance, debug_label: str) -> None:"""Best-effort activity provenance stamp for hygiene compression transitions."""try:agent._touch_activity(desc, provenance=provenance)@@ -4189,7 +4190,6 @@ class GatewayRunner(See #15654, #9051."""if interrupt_depth == 0:- from agent.session_activity import ActivityProvenanceagent._last_activity_ts = time.time()agent._last_activity_desc = "starting new turn (cached)"agent._last_activity_provenance = ActivityProvenance.UNKNOWNdiff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex bc7aaabb668..4673315d073 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -27,7 +27,7 @@ from gateway.session_transcript import TranscriptReadErrorfrom gateway.slash_commands_goals import GatewayGoalCommandsMixinfrom gateway.slash_commands_model import GatewayModelCommandsMixinfrom gateway.slash_commands_session import GatewaySessionCommandsMixin-from gateway.slash_commands_status import GatewayStatusCommandsMixin+from gateway.slash_commands_status import HISTORY_UNREADABLE, GatewayStatusCommandsMixinfrom hermes_cli.config import atomic_config_write, cfg_getfrom utils import atomic_json_write, is_truthy_valuediff --git a/plugins/platforms/sms/adapter.py b/plugins/platforms/sms/adapter.pyindex 93fb0b5ea25..c4ef7800848 100644--- a/plugins/platforms/sms/adapter.py+++ b/plugins/platforms/sms/adapter.py@@ -9,6 +9,8 @@ validation — required), SMS_INSECURE_NO_SIGNATURE (true disables validationSMS_ALLOWED_USERS (comma-separated E.164), SMS_ALLOW_ALL_USERS, SMS_HOME_CHANNEL (cron)."""+from __future__ import annotations+import asyncioimport base64import hashlib@@ -20,10 +22,18 @@ import urllib.parsefrom typing import Any, Dict, Optionalfrom gateway.config import Platform, PlatformConfig-from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, MessageEvent, MessageType, SendResult+from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult+from gateway.platforms.event import MessageEvent, MessageTypefrom gateway.platforms.helpers import redact_phone, strip_markdownfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret+try:+ import aiohttp+ from aiohttp import web+except ImportError: # optional ([messaging] extra)+ aiohttp = None # type: ignore[assignment]+ web = None # type: ignore[assignment]+logger = logging.getLogger(__name__)TWILIO_API_BASE = "https://api.twilio.com/2010-04-01/Accounts"@@ -36,8 +46,6 @@ _EMPTY_TWIML = '<?xml version="1.0" encoding="UTF-8"?><Response></Response>'def _twiml_response(status: int = 200):"""Empty TwiML reply — replies go out via the REST API, never inline TwiML."""- from aiohttp import web-return web.Response(text=_EMPTY_TWIML, content_type="application/xml", status=status)@@ -54,8 +62,6 @@ def _messages_endpoint(account_sid: str, auth_token: str) -> tuple:def _twilio_form(from_number: str, to_number: str, body: str):"""Twilio Messages.json form payload (aiohttp FormData)."""- import aiohttp-form_data = aiohttp.FormData()form_data.add_field("From", from_number)form_data.add_field("To", to_number)@@ -64,22 +70,12 @@ def _twilio_form(from_number: str, to_number: str, body: str):def _new_session(**kwargs):- import aiohttp-return aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), **kwargs)-def _aiohttp_available() -> bool:- try:- import aiohttp # noqa: F401- except ImportError:- return False- return True--def check_sms_requirements() -> bool:"""Check if SMS adapter dependencies are available."""- return _aiohttp_available() and bool(+ return aiohttp is not None and bool(_get_scoped_secret("TWILIO_ACCOUNT_SID") and _get_scoped_secret("TWILIO_AUTH_TOKEN"))@@ -97,13 +93,11 @@ class SmsAdapter(BasePlatformAdapter):self._webhook_host: str = os.getenv("SMS_WEBHOOK_HOST", DEFAULT_WEBHOOK_HOST)self._webhook_url: str = os.getenv("SMS_WEBHOOK_URL", "").strip()self._runner = None- self._http_session: Optional["aiohttp.ClientSession"] = None+ self._http_session: Optional[aiohttp.ClientSession] = None# -- Lifecycle -----------------------------------------------------------async def connect(self, *, is_reconnect: bool = False) -> bool:- from aiohttp import web-insecure_no_sig = os.getenv("SMS_INSECURE_NO_SIGNATURE", "").lower() == "true"fatal = Noneif not self._from_number:@@ -228,7 +222,7 @@ class SmsAdapter(BasePlatformAdapter):# -- Inbound webhook ------------------------------------------------------ async def _handle_webhook(self, request) -> "aiohttp.web.Response":+ async def _handle_webhook(self, request: web.Request) -> web.Response:try:content_length = request.content_lengthif content_length is not None and content_length > _TWILIO_WEBHOOK_MAX_BODY_BYTES:@@ -298,7 +292,7 @@ def _strip_markdown_for_sms(message: str) -> str:async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):"""Out-of-process SMS delivery via the Twilio REST API (standalone_sender_fn contract)."""auth_token = getattr(pconfig, "api_key", None) or _get_scoped_secret("TWILIO_AUTH_TOKEN", "")- if not _aiohttp_available():+ if not aiohttp is not None:return {"error": "aiohttp not installed. Run: pip install aiohttp"}account_sid = _get_scoped_secret("TWILIO_ACCOUNT_SID", "")from_number = os.getenv("TWILIO_PHONE_NUMBER", "")diff --git a/plugins/platforms/teams/summary_writer.py b/plugins/platforms/teams/summary_writer.pyindex ae43fe7fa1f..bfeceda460c 100644--- a/plugins/platforms/teams/summary_writer.py+++ b/plugins/platforms/teams/summary_writer.py@@ -1,8 +1,6 @@"""Pipeline-facing Teams outbound delivery (meeting-summary writer).Lives inside the Teams platform plugin so the meeting pipeline reuses one Teams-integration surface. httpx is imported lazily: plugin discovery imports this-module on every CLI start, but only ``incoming_webhook`` delivery needs it."""from __future__ import annotations@@ -15,6 +13,8 @@ from urllib.parse import quotefrom gateway.config import PlatformConfigfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret+import httpx+def _parse_bool(value: Any, *, default: bool = False) -> bool:if isinstance(value, bool):@@ -90,7 +90,6 @@ class TeamsSummaryWriter:return mergedasync def _write_summary_via_incoming_webhook(self, payload: Any, config: dict[str, Any]) -> dict[str, Any]:- import httpx # lazy — see module docstringwebhook_url = str(config.get("incoming_webhook_url") or "").strip()if not webhook_url:raise ValueError("TEAMS_INCOMING_WEBHOOK_URL is required for incoming_webhook mode.")diff --git a/tests/agent/test_credential_pool_anthropic_refresh_race.py b/tests/agent/test_credential_pool_anthropic_refresh_race.pyindex 4953a37fa3b..58534a50024 100644--- a/tests/agent/test_credential_pool_anthropic_refresh_race.py+++ b/tests/agent/test_credential_pool_anthropic_refresh_race.py@@ -30,6 +30,8 @@ Claude Code witness lives in ``test_anthropic_oauth_stress.py``.from __future__ import annotations+from typing import Dict+import threadingimport timefrom dataclasses import replace as dc_replacediff --git a/tests/agent/test_cursor_optimizations_parity.py b/tests/agent/test_cursor_optimizations_parity.pyindex fad6187f3d3..839e566a3f8 100644--- a/tests/agent/test_cursor_optimizations_parity.py+++ b/tests/agent/test_cursor_optimizations_parity.py@@ -231,6 +231,8 @@ def bench():# persist scan: fully-flushed list, old full walk vs bounded skipimport run_agent as ra+ from agent.context_compressor import _DB_PERSISTED_MARKER+ from agent.session_persistence import _is_ephemeral_scaffoldingflushed = copy.deepcopy(msgs)for m in flushed:if isinstance(m, dict):diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.pyindex 682054f8421..f8585878dc4 100644--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@ -12,12 +12,16 @@ No LLM, no real platform connections.import asyncioimport sysimport uuid+from typing import TYPE_CHECKINGfrom datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+if TYPE_CHECKING:+ from gateway.run import GatewayRunner+from gateway.config import GatewayConfig, Platform, PlatformConfigfrom gateway.platforms.base import MessageEvent, SendResultfrom gateway.session import SessionEntry, SessionSource, build_session_keydiff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.pyindex 2d1783e0511..f5f94c2fb78 100644--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@ -10,11 +10,14 @@ import unittestfrom collections import OrderedDictfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Dict+from typing import TYPE_CHECKING, Dictfrom unittest.mock import AsyncMock, Mock, patchfrom gateway.platforms.base import ProcessingOutcome+if TYPE_CHECKING:+ from plugins.platforms.feishu.adapter import FeishuAdapter+try:import lark_oapi_HAS_LARK_OAPI = Truediff --git a/tests/gateway/test_telegram_audio_vs_voice.py b/tests/gateway/test_telegram_audio_vs_voice.pyindex 7f807e3560c..b9e54c59352 100644--- a/tests/gateway/test_telegram_audio_vs_voice.py+++ b/tests/gateway/test_telegram_audio_vs_voice.py@@ -20,6 +20,11 @@ from gateway.config import GatewayConfig, Platformfrom gateway.platforms.base import MessageEvent, MessageTypefrom gateway.session import SessionSource+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from gateway.run import GatewayRunner+def _make_runner(stt_enabled: bool = True) -> "GatewayRunner": # type: ignore[name-defined]from gateway.run import GatewayRunnerdiff --git a/tests/gateway/test_video_context_note.py b/tests/gateway/test_video_context_note.pyindex 19ca1dba8e5..f0cd84575ca 100644--- a/tests/gateway/test_video_context_note.py+++ b/tests/gateway/test_video_context_note.py@@ -8,6 +8,11 @@ from gateway.config import GatewayConfig, Platformfrom gateway.platforms.base import MessageEvent, MessageTypefrom gateway.session import SessionSource+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from gateway.run import GatewayRunner+def _make_runner() -> "GatewayRunner": # type: ignore[name-defined]from gateway.run import GatewayRunnerdiff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 3ed68bba148..a664da184e8 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -1022,6 +1022,27 @@ class TestCustomProviderCompatibility:run_migrations(current_ver, results, quiet=True)return results+ def test_v11_upgrade_moves_custom_providers_into_providers(self, tmp_path):+ config_path = tmp_path / "config.yaml"+ config_path.write_text(+ yaml.safe_dump(+ {+ "_config_version": 11,+ "model": {"default": "openai/gpt-5.4", "provider": "openrouter"},+ "custom_providers": [+ {+ "name": "OpenAI Direct",+ "base_url": "https://api.openai.com/v1",+ "api_key": "test-key",+ "api_mode": "codex_responses",+ "model": "gpt-5-mini",+ }+ ],+ "fallback_providers": [{"provider": "openai-direct", "model": "gpt-5-mini"}],+ }+ ),+ encoding="utf-8",+ )with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):self._run_ladder(11)diff --git a/tests/test_background_review_list_shapes.py b/tests/test_background_review_list_shapes.pyindex ada4c151d99..cc22d2825a4 100644--- a/tests/test_background_review_list_shapes.py+++ b/tests/test_background_review_list_shapes.py@@ -298,9 +298,6 @@ def test_e_call_does_not_unwind_module_callables():def main():runner = TestRunner()- runner.run("a_change_as_list_does_not_crash", test_a_change_as_list_does_not_crash)- runner.run("a_change_as_int_does_not_crash", test_a_change_as_int_does_not_crash)- runner.run("b_operations_as_string_treated_as_empty", test_b_operations_as_string_treated_as_empty)runner.run("b_operations_as_none_treated_as_empty", test_b_operations_as_none_treated_as_empty)runner.run("c_operations_contains_non_dict_entries", test_c_operations_contains_non_dict_entries)runner.run("d_detail_non_dict_replaced_with_empty", test_d_detail_non_dict_replaced_with_empty)diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex 50d20c91ad2..9e39e502e77 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -7,7 +7,7 @@ import jsonimport osimport sysfrom pathlib import Path-from typing import Any, Dict, List, cast+from typing import Any, Dict, List, Optional, castfrom unittest.mock import MagicMock, patchimport pytestdiff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 6e0dece041f..6df52dc48ac 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -2979,7 +2979,7 @@ class TestMCPDiscoveryCrossProcessLock:if sys.platform == "win32":import portalocker- self._lock_exclusive(fh)+ portalocker.lock(fh, portalocker.LOCK_EX | portalocker.LOCK_NB)else:import fcntldiff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.pyindex 2196ac0f02c..fa19a5be77d 100644--- a/tools/mcp_tool_sampling.py+++ b/tools/mcp_tool_sampling.py@@ -1,11 +1,14 @@"""MCP client-side handlers for server-initiated requests: sampling(sampling/createMessage, text and tool-use results) and elicitation."""+from __future__ import annotations+import asyncioimport jsonimport loggingimport time-from typing import Callable, List, Optional+from contextvars import Context+from typing import Callable, List, Optional, Protocolfrom tools.mcp_tool_common import _MISSING, _exc_str, _safe_numeric, _sanitize_error, mcp_field, _corefrom tools.mcp_tool_schema import _normalize_mcp_input_schema@@ -239,6 +242,13 @@ def _format_elicitation_schema_summary(schema: dict, server_name: str) -> str:return "\n".join(lines)+class ElicitationOwner(Protocol):+ """The server task an ElicitationHandler belongs to (tools.mcp_tool.MCPServerTask, which imports this+ module, so it cannot be named here). Only the captured agent contextvars are read."""++ _pending_call_context: Optional[Context]++class ElicitationHandler:"""``elicitation_callback`` for one MCP server. Form-mode routes through Hermes' approval system(CLI, TUI, Telegram, ...); URL-mode is declined. Fail-closed: any timeout, exception or unexpected@@ -250,7 +260,7 @@ class ElicitationHandler:# consent answer -> (ElicitResult action, metric); anything else declines._ANSWER_RESULTS = {"accept": ("accept", "accepted"), "cancel": ("cancel", "errors")}- def __init__(self, server_name: str, config: dict, owner: Optional["MCPServerTask"] = None):+ def __init__(self, server_name: str, config: dict, owner: Optional[ElicitationOwner] = None):self.server_name = server_name# 5 min mirrors the gateway approval default so async surfaces (Telegram, Slack) can respond.self.timeout = _safe_numeric(config.get("timeout", 300), 300, float)diff --git a/tools/patch_parser.py b/tools/patch_parser.pyindex 994e3c1c56d..3c9c1c3f37e 100644--- a/tools/patch_parser.py+++ b/tools/patch_parser.py@@ -11,6 +11,8 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Callable, Dict, List, Optional, Tuple+from tools.file_operations_common import PatchResult+class OperationType(Enum):ADD = "add"@@ -250,11 +252,10 @@ def _unified_diff(path: str, old: str, new: Optional[str]) -> str:fromfile=f"a/{path}", tofile="/dev/null" if new is None else f"b/{path}"))-def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> 'PatchResult':+def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> PatchResult:"""Two-phase: validate everything, then apply (atomic on validation failure). A phase-2failure (validate/apply race) carries a ``git diff`` note since state may be inconsistent.``file_ops`` needs read_file_raw/write_file/delete_file/move_file."""- from tools.file_operations_common import PatchResult # avoid circular importdef _bullets(errs: List[str]) -> str:return "\n".join(f" • {e}" for e in errs)