The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: ruff UP037 fixes
Maciej Lisiewski2ff58849f4c4
diff --git a/agent/account_usage_cache.py b/agent/account_usage_cache.pyindex 0358fd5c58b..695361b8d89 100644--- a/agent/account_usage_cache.py+++ b/agent/account_usage_cache.py@@ -32,7 +32,7 @@ SNAPSHOT_STALE_AFTER_S = 15 * 60.0_lock = threading.Lock()# slot key (home, provider, identity_id, base_url) → snapshot-_snapshots: dict[tuple[str, str, str, str], "AccountUsageSnapshot"] = {}+_snapshots: dict[tuple[str, str, str, str], AccountUsageSnapshot] = {}# slot key → monotonic time the stored snapshot's fetch STARTED (late-fetch guard)_started: dict[tuple[str, str, str, str], float] = {}# slot key → monotonic time of the last refresh try (success or failure)@@ -87,7 +87,7 @@ def _identity_id_for(provider: str, entry: Any) -> str:def remember_account_usage(- provider: Optional[str], snapshot: Optional["AccountUsageSnapshot"],+ provider: Optional[str], snapshot: Optional[AccountUsageSnapshot],*, identity_id: Optional[str] = None, base_url: Optional[str] = None,started_monotonic: Optional[float] = None,) -> None:@@ -127,12 +127,12 @@ def remember_account_usage(def cached_account_usage(provider: str, *, identity_id: Optional[str] = None, base_url: Optional[str] = None,-) -> Optional["AccountUsageSnapshot"]:+) -> Optional[AccountUsageSnapshot]:with _lock:return _snapshots.get(_key(provider, identity_id, base_url))-def snapshot_is_stale(snapshot: Optional["AccountUsageSnapshot"]) -> bool:+def snapshot_is_stale(snapshot: Optional[AccountUsageSnapshot]) -> bool:"""True when the snapshot is too old to render as a live gauge (the picker shows state``unknown`` instead of trusting its percentages)."""from agent.account_usage import AccountUsageSnapshot as _Snapshotdiff --git a/agent/activity_tracking.py b/agent/activity_tracking.pyindex 55da3b59077..984b6d8fbe1 100644--- a/agent/activity_tracking.py+++ b/agent/activity_tracking.py@@ -16,7 +16,7 @@ from agent.session_activity import ActivityProvenancelogger = logging.getLogger("run_agent")-def _activity_lock(obj) -> "threading.Lock":+def _activity_lock(obj) -> threading.Lock:"""Lazy per-instance ``_turn_liveness_activity_lock`` (so ``__new__``/SimpleNamespace doubles work)."""_lock = getattr(obj, "_turn_liveness_activity_lock", None)if _lock is None:@@ -28,7 +28,7 @@ def _activity_lock(obj) -> "threading.Lock":class ActivityTrackingMixin:"""Liveness timestamps/labels and rate-limited session activity persistence."""- def _liveness_activity_lock(self) -> "threading.Lock":+ def _liveness_activity_lock(self) -> threading.Lock:"""Shared lock for the activity clock and its generation counter.``_touch_activity`` stamps under it and the liveness watchdog samples/commits under it, so a stalldiff --git a/agent/agent_init.py b/agent/agent_init.pyindex c51c857c0c2..52eb03305c5 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -2388,7 +2388,7 @@ def init_agent(gateway_session_key: str | None = None, skip_context_files: bool = False,load_soul_identity: bool = False, skip_memory: bool = False,skip_background_review: bool = False, session_db=None, parent_session_id: str | None = None,- iteration_budget: "IterationBudget" = None, run_budget_seconds: Optional[float] = None,+ iteration_budget: IterationBudget = None, run_budget_seconds: Optional[float] = None,fallback_model: dict[str, Any] | None = None, credential_pool=None, checkpoints_enabled: bool = False,checkpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.pyindex 4f8d1477b4b..e3ba2f9c09a 100644--- a/agent/anthropic_credentials.py+++ b/agent/anthropic_credentials.py@@ -132,7 +132,7 @@ _SPENT_ROTATION_LOCK = threading.Lock()# Fingerprints of Claude Code refresh tokens the endpoint rejected terminally: the WARNING fires once per token# per process and later attempts skip the POST (a re-login rotates the token, so a new one is tried normally)._DEAD_REFRESH_TOKEN_FINGERPRINTS: set = set()-_SPENT_ROTATION_FINGERPRINTS: "OrderedDict[str, None]" = OrderedDict()+_SPENT_ROTATION_FINGERPRINTS: OrderedDict[str, None] = OrderedDict()_SPENT_ROTATION_MAX_TRACKED = 64_SPENT_ROTATION_SIDECAR_COMMENT = ("Non-secret one-way fingerprints of Anthropic OAuth credentials whose rotation was "@@ -238,7 +238,7 @@ def _claude_oauth_record(data: Any, source: str) -> Optional[dict[str, Any]]:_KEYCHAIN_ATTR = r'(?:0x(?P<hex>[0-9A-Fa-f]+)\b.*|"(?P<text>.*)")'-def _decode_keychain_attr(match: Optional["re.Match[str]"]) -> str:+def _decode_keychain_attr(match: Optional[re.Match[str]]) -> str:"""``security`` prints an attribute as ``"text"`` when it is plain printable ASCII and as``0x<HEX> "<octal-escaped echo>"`` otherwise; the quoted form is NOT escaped (an embedded``"`` appears raw), so the text group must run to the last quote on the line."""diff --git a/agent/async_utils.py b/agent/async_utils.pyindex 2bc558fad21..def2bd23a82 100644--- a/agent/async_utils.py+++ b/agent/async_utils.py@@ -40,7 +40,7 @@ def safe_schedule_threadsafe(return None-def consume_detached_task_result(task: "asyncio.Future[Any]") -> None:+def consume_detached_task_result(task: asyncio.Future[Any]) -> None:"""``add_done_callback`` for cancelled-and-detached tasks: observe the exception so theloop does not log "exception was never retrieved"; cancellation and terminal errorsare swallowed because the task's owner already gave up on it."""diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 7c5471a3ddd..10a5b1814eb 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -655,7 +655,7 @@ def remember_temperature_rejection(def _fixed_temperature_for_model(model: Optional[str], base_url: Optional[str] = None, provider: Optional[str] = None,-) -> "Optional[float] | object":+) -> Optional[float] | object:"""``OMIT_TEMPERATURE`` (drop the key; Kimi/Moonshot, OpenAI reasoning families, routes thatalready rejected it), a fixed ``float``, or ``None``."""if _is_kimi_model(model):@@ -7016,7 +7016,7 @@ def _client_streams_internally(client: Any) -> bool:_MANAGED_LOCAL_STATE_TTL_S = 15.0-_managed_local_cache: "tuple[float, str]" = (0.0, "")+_managed_local_cache: tuple[float, str] = (0.0, "")def _managed_local_netloc() -> str:@@ -7123,7 +7123,7 @@ def _create_with_progress(return _create_with_progress_once(client, retry_kwargs, task, force_stream=force_stream)-def _stream_request_plan(kwargs: dict[str, Any]) -> "tuple[dict[str, Any], str, float]":+def _stream_request_plan(kwargs: dict[str, Any]) -> tuple[dict[str, Any], str, float]:"""(stream kwargs, model name, total ceiling) for a streamed re-aggregation."""stream_kwargs = dict(kwargs)stream_kwargs["stream"] = True@@ -7190,7 +7190,7 @@ def _create_with_progress_once(def _aggregate_chat_stream(chunks: Any, *, model: str = "", total_ceiling: Optional[float] = None,- no_progress: "Optional[tuple[float, Optional[float]]]" = None,+ no_progress: Optional[tuple[float, Optional[float]]] = None,) -> Any:"""Consume a chunk stream into a complete response; TimeoutError (phrased "timed out" so``_is_timeout_error`` matches) past *total_ceiling* or the *no_progress* windows (#100501)."""@@ -7576,7 +7576,7 @@ _FALLBACK_REASONS: tuple[tuple[Callable[[Exception], bool], str], ...] = ()-def _rung(step: "_LadderStep", accept: Callable[[Exception], bool]):+def _rung(step: _LadderStep, accept: Callable[[Exception], bool]):"""One ladder rung: perform ``step``; yields ``(response, None)`` on success,``(None, exc)`` when ``accept(exc)`` lets the next rung handle it, else re-raises."""try:diff --git a/agent/auxiliary_stream_watchdog.py b/agent/auxiliary_stream_watchdog.pyindex bc25a1e1e77..f3a6c5abfd6 100644--- a/agent/auxiliary_stream_watchdog.py+++ b/agent/auxiliary_stream_watchdog.py@@ -132,7 +132,7 @@ class ChatStreamWatchdog:f"({elapsed:.1f}s elapsed, timed out)")-def chat_stream_windows(client: Any, kwargs: dict, task: Optional[str]) -> "tuple[float, Optional[float]]":+def chat_stream_windows(client: Any, kwargs: dict, task: Optional[str]) -> tuple[float, Optional[float]]:"""(inter-chunk window, first-token window) for a streamed chat-completions attempt. Betweenchunks: the Codex guard's window (``auxiliary.<task>.no_progress_timeout``, 60s default). Beforethe first token: the main loop's cloud stale patience for the routed provider (its explicit@@ -156,7 +156,7 @@ def chat_stream_windows(client: Any, kwargs: dict, task: Optional[str]) -> "tuplreturn window, first-def consume_chat_stream(chunks: Any, acc: Any, no_progress: "Optional[tuple[float, Optional[float]]]") -> None:+def consume_chat_stream(chunks: Any, acc: Any, no_progress: Optional[tuple[float, Optional[float]]]) -> None:"""Feed *chunks* into the accumulator *acc*. Under a ``(window, first_token_window)`` watchdog asilent stream raises TimeoutError, except after the terminal chunk: with finish_reason (and anyusage) in hand a stall is teardown, so the completed response and its billed usage are kept."""diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.pyindex 443d1d0a641..a75b41e7896 100644--- a/agent/azure_identity_adapter.py+++ b/agent/azure_identity_adapter.py@@ -89,7 +89,7 @@ class EntraIdentityConfig:return {"scope": self.scope, "exclude_interactive_browser": self.exclude_interactive_browser}@classmethod- def from_dict(cls, data: Optional[dict[str, Any]], *, default_scope: Optional[str] = None) -> "EntraIdentityConfig":+ def from_dict(cls, data: Optional[dict[str, Any]], *, default_scope: Optional[str] = None) -> EntraIdentityConfig:data = data or {}return cls(scope=str(data.get("scope") or "").strip() or default_scope or SCOPE_AI_AZURE_DEFAULT,@@ -318,7 +318,7 @@ def build_bearer_http_client(token_provider: Callable[[], str], **httpx_kwargs:raise ValueError("build_bearer_http_client requires a zero-arg callable token provider")import httpx- def _inject_bearer(request: "httpx.Request") -> None:+ def _inject_bearer(request: httpx.Request) -> None:try:token = materialize_bearer_for_http(token_provider)except ValueError as exc:diff --git a/agent/backend_identity.py b/agent/backend_identity.pyindex 011a58f1602..aba64f62c0e 100644--- a/agent/backend_identity.py+++ b/agent/backend_identity.py@@ -51,7 +51,7 @@ class BackendIdentity:def build(cls, provider: Optional[str] = None, model: Optional[str] = None,base_url: Optional[str] = None,- ) -> "BackendIdentity":+ ) -> BackendIdentity:return cls(provider=_norm(provider), model=_norm(model),base_url=normalize_route_base_url(base_url),diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex ae234f95d65..2a31db654a5 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -486,7 +486,7 @@ def _provider_preferences_for_agent(agent) -> dict[str, Any]:return {key: value for key, value in merged.items() if value}-def _prompt_cache_scope_for_agent(agent) -> "str | None":+def _prompt_cache_scope_for_agent(agent) -> str | None:"""Rotation-stable logical cache scope for *agent*, or None (transports thenfall back to the physical session_id, so a failure never blocks the build)."""try:@@ -618,7 +618,7 @@ def _check_stale_giveup(agent) -> None:)-def _stream_env_stale_base() -> "tuple[float, bool]":+def _stream_env_stale_base() -> tuple[float, bool]:"""(HERMES_STREAM_STALE_TIMEOUT or the implicit 180s, explicit) — like``AIAgent._resolved_api_call_stale_timeout_base``; an explicit env value is theuser's deadline, so it is never capped to the run budget."""@@ -700,7 +700,7 @@ def _cloud_stale_timeout_for(agent, api_kwargs: dict) -> float:return timeout if explicit_env else cap_to_run_budget(agent, timeout)-def _bedrock_reasoning_stale_floor(model_id: object) -> "float | None":+def _bedrock_reasoning_stale_floor(model_id: object) -> float | None:"""Map a Bedrock inference-profile id to its reasoning stale-timeout floor.``us.anthropic.claude-opus-4-6-v1:0`` -> strip the region prefix, then try the@@ -831,7 +831,7 @@ def should_use_direct_api_call(agent) -> bool:_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS = 15.0-def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":+def _managed_local_load_notice(agent, api_kwargs: dict) -> Optional[str]:"""Live phase notice ("⏳ loading <model> into memory — N%" / "⚙ processingprompt — P%") while the managed local server works before the first token;None when neither applies. Otherwise a cold load reads as a generic stall."""@@ -1824,7 +1824,7 @@ _FALLBACK_REASON_LABELS = {}-def _fallback_reason_text(reason: "FailoverReason | None") -> str:+def _fallback_reason_text(reason: FailoverReason | None) -> str:"""Return a concise operator-facing explanation for a fallback switch."""label = _FALLBACK_REASON_LABELS.get(reason)return label or str(getattr(reason, "value", None) or reason or "provider failure").replace("_", " ")@@ -1930,7 +1930,7 @@ def _log_fallback_activated(agent, reason, old_model, old_provider, fb_model, fb)-def _fallback_chain_exhausted(agent, reason: "FailoverReason | None") -> bool:+def _fallback_chain_exhausted(agent, reason: FailoverReason | None) -> bool:"""Chain exhausted (always False). A non-empty chain walked on a non-rate-limit failure arms ashort cooldown so next turn's restore_primary_runtime stays gated instead of replaying the wholecontext across every provider again."""@@ -2069,7 +2069,7 @@ def _buffer_fallback_notice(agent, notice: str) -> None:agent._pending_fallback_notice = [str(pending), notice] if pending else [notice]-def try_activate_fallback(agent, reason: "FailoverReason | None" = None, reset_at=None) -> bool:+def try_activate_fallback(agent, reason: FailoverReason | None = None, reset_at=None) -> bool:"""Switch to the next fallback model/provider in the chain; False when exhausted. Swaps client,model slug and provider in place so the retry loop continues on the new backend; clientconstruction goes through resolve_provider_client (no duplicated provider→key mappings)."""diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 191b4e9f359..dce3fc77889 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -1055,7 +1055,7 @@ Spend up to ~{_LEAN_SESSION_LOG_BUDGET_TOKENS} tokens here — this section is t# (SHAs, ids, error strings) cannot be paraphrased away; also a session_search map._LEAN_ANCHOR_HEADING = "## Anchor Index (mechanically extracted, exact)"_LEAN_ANCHOR_BUDGET_CHARS = 7_000-_ANCHOR_PATTERNS: "list[tuple[str, re.Pattern[str], int]]" = [+_ANCHOR_PATTERNS: list[tuple[str, re.Pattern[str], int]] = [("PRs/issues", re.compile(r"#\d{3,6}\b"), 120),("commits", re.compile(r"\b[0-9a-f]{9,40}\b"), 40),("branches", re.compile(r"\b(?:fix|feat|docs|refactor|chore|salvage|ent)/[A-Za-z0-9._/-]{3,60}"), 40),@@ -1352,17 +1352,17 @@ def _estimate_msg_budget_tokens(msg: dict, charge_stale_thinking: bool = True) -return tokens-def _last_index_with_role(messages: "list[dict[str, Any]]", role: str) -> int:+def _last_index_with_role(messages: list[dict[str, Any]], role: str) -> int:"""Index of the newest dict message with ``role``, or -1."""return max((i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == role), default=-1)-def _last_assistant_index(messages: "list[dict[str, Any]]") -> int:+def _last_assistant_index(messages: list[dict[str, Any]]) -> int:"""Newest assistant message index, or -1 (the one turn whose thinking may replay; see ``_NEWEST_TURN_ONLY_BUDGET_KEYS``)."""return _last_index_with_role(messages, "assistant")-def _pending_tool_round(messages: "list[dict[str, Any]]") -> range:+def _pending_tool_round(messages: list[dict[str, Any]]) -> range:"""Indices of the tool results the transcript ends with — a round the model has not answered yet; empty whenthe transcript ends in any other row. /steer rows after the round do not answer it: a steer is deliveredafter the newest tool result before the next API call, and two can land in one iteration (one when the tool@@ -2011,7 +2011,7 @@ def _json_dict(text: Any) -> dict:return parsed if isinstance(parsed, dict) else {}-def _summarize_refused_tool_result(tool_name: str, args: dict, content: str) -> "str | None":+def _summarize_refused_tool_result(tool_name: str, args: dict, content: str) -> str | None:"""Summary for a call an approval or write guard refused (``BLOCKED: ...`` / ``status````blocked``/``pending_approval``), else None. The per-tool summarizers describe the call as done("ran ...", "wrote to ..."), which would turn a user's denial into a record of the action and@@ -2050,7 +2050,7 @@ def _summarize_tool_result_unguarded(tool_name: str, tool_args: str, tool_contenreturn f"[{tool_name}]{first_arg} ({content_len:,} chars result)" + _result_failure_suffix(content)-def _model_threshold_key_rank(key: str, model: str, provider: str) -> "tuple[int, int] | None":+def _model_threshold_key_rank(key: str, model: str, provider: str) -> tuple[int, int] | None:"""Match rank for one ``model_thresholds`` key, or None when it does not apply.``"<provider>:<substr>"`` keys apply only on that provider; bare keys apply on every route.The same slug means different windows on different routes (Codex caps Astra at 272K; OpenRouter@@ -2934,7 +2934,7 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMi# Dedup key for the over-threshold "reclamation no-oped" warning# (#101889) so a tool loop riding above the threshold warns once per# distinct reason + rearm snapshot instead of every iteration.- self._last_reclaim_block_warn: "tuple[str, int] | None" = None+ self._last_reclaim_block_warn: tuple[str, int] | None = Noneself.min_tail_user_messages = min_tail_user_messagesself.summary_target_ratio = max(0.10, min(summary_target_ratio, 0.80))self.quiet_mode = quiet_mode@@ -3090,7 +3090,7 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMi"""True when compression should run now (anti-thrash included; see :meth:`should_compress_info` for the reason)."""return self.should_compress_info(prompt_tokens)[0]- def should_compress_info(self, prompt_tokens: int | None = None) -> "tuple[bool, str | None]":+ def should_compress_info(self, prompt_tokens: int | None = None) -> tuple[bool, str | None]:"""Return ``(should_compress, reason)``.``reason`` is None unless compression is needed but blocked: ``"cooldown:<seconds>"`` or``"ineffective"``. Callers should surface a warning when it is non-None."""@@ -3101,7 +3101,7 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMireturn False, self._compression_block_reason() or "blocked"return True, None- def _compression_block_reason(self) -> "str | None":+ def _compression_block_reason(self) -> str | None:"""Block reason: ``"cooldown:<s>"``, ``"structural_backoff:<s>"``, ``"ineffective"``, or None."""for label, until in (("cooldown", self._summary_failure_cooldown_until), ("structural_backoff", self._structural_no_op_backoff_until),@@ -3421,7 +3421,7 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMiself._proactive_prune_rearm_tokens = 0self._last_reclaim_block_warn = None- def _billed_basis_over_threshold(self, current_tokens: "int | None") -> bool:+ def _billed_basis_over_threshold(self, current_tokens: int | None) -> bool:"""Whether a provider-billed reading says the session is over threshold.``current_tokens`` is the provider's ``prompt_tokens`` (or the@@ -3440,8 +3440,8 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMidef _warn_reclamation_no_op(self,reason: str,- current_tokens: "int | None",- before: "int | None" = None,+ current_tokens: int | None,+ before: int | None = None,) -> None:"""Warn when an over-threshold session's reclamation path no-ops.@@ -5298,7 +5298,7 @@ Write only the summary body. Do not include any preamble or prefix."""def _scan_window_handoffs(self, messages: list[dict[str, Any]], compress_start: int, compress_end: int,turns_to_summarize: list[dict[str, Any]],- ) -> "_HandoffScan":+ ) -> _HandoffScan:"""Rehydrate ``_previous_summary`` / user-turn provenance from in-transcript handoffs.Handoff rows are removed from the summarizer window (merged handoffs unwrap to their prior-tailcontent) and ``tail_start`` advances past a handoff beyond the window. The pre-scan state is@@ -5736,7 +5736,7 @@ Write only the summary body. Do not include any preamble or prefix."""return self._finalize_compressed(compressed, canonical_messages, n_messages, spare_pending_images)def _assemble_compressed(- self, messages: list[dict[str, Any]], compress_start: int, compress_end: int, scan: "_HandoffScan", summary: str,+ self, messages: list[dict[str, Any]], compress_start: int, compress_end: int, scan: _HandoffScan, summary: str,) -> list[dict[str, Any]]:"""Head + summary + tail from the pruned copy: its tool-result demotions are what let an oversizedhead/tail compress at all (#61932); tool-call arguments are never rewritten by pruning."""diff --git a/agent/context_compressor_summary.py b/agent/context_compressor_summary.pyindex decf4aeab09..eb52028b936 100644--- a/agent/context_compressor_summary.py+++ b/agent/context_compressor_summary.py@@ -58,7 +58,7 @@ class SummaryDispatchMixin:call_kwargs[key] = valuedef _summarize_window(- self, messages: list[dict[str, Any]], turns_to_summarize: list[dict[str, Any]], scan: "_HandoffScan",+ self, messages: list[dict[str, Any]], turns_to_summarize: list[dict[str, Any]], scan: _HandoffScan,focus_topic: Optional[str], memory_context: str, bypass_cooldown: bool,) -> Optional[str]:"""Run the summary LLM; a cancellation rolls back the handoff scan's self-heal mutation first.diff --git a/agent/context_engine.py b/agent/context_engine.pyindex c9bc6d33001..25feb67ef35 100644--- a/agent/context_engine.py+++ b/agent/context_engine.py@@ -85,7 +85,7 @@ class ContextEngine(ABC):def should_compress(self, prompt_tokens: int | None = None) -> bool:"""Return True if compaction should fire this turn."""- def should_compress_info(self, prompt_tokens: int | None = None) -> "tuple[bool, str | None]":+ def should_compress_info(self, prompt_tokens: int | None = None) -> tuple[bool, str | None]:"""Return ``(should_compress, reason)``.Engines with block reasons (summary-LLM cooldown, anti-thrashing guard) override@@ -223,7 +223,7 @@ class ContextEngine(ABC):"compression_count": self.compression_count,}- def clone_for_agent(self) -> "ContextEngine":+ def clone_for_agent(self) -> ContextEngine:"""Per-agent instance of a plugin-registered engine (the plugin system holds ONE sharedinstance; every AIAgent gets its own so a child's update_model() cannot mutate the parent's).Override when the engine holds uncopyable state (locks, DB connections): return a freshdiff --git a/agent/context_file_sources.py b/agent/context_file_sources.pyindex db0c77e5f59..0c77190364a 100644--- a/agent/context_file_sources.py+++ b/agent/context_file_sources.py@@ -59,7 +59,7 @@ def _loaded_status(content: str, rendered_len: int, max_chars: int, user_authoredef list_context_file_sources(cwd: Optional[str] = None, context_length: Optional[int] = None, allow_install_tree_fallback: bool = False,- home_override: "Path | None" = None, skip_soul: bool = False,+ home_override: Path | None = None, skip_soul: bool = False,) -> list[dict[str, Any]]:"""One dict per context file Hermes considered, in the builder's priority order.diff --git a/agent/context_references.py b/agent/context_references.pyindex 88cacf39f0d..fa1c455800b 100644--- a/agent/context_references.py+++ b/agent/context_references.py@@ -27,7 +27,7 @@ from hermes_cli.sizefmt import format_bytes# provider API (Issue #26193) ---------------------------------------------------------------------------BUILTIN_PREFIXES = frozenset({"diff", "staged", "file", "folder", "git", "url"})-_context_reference_providers: dict[str, "ContextReferenceProvider"] = {}+_context_reference_providers: dict[str, ContextReferenceProvider] = {}class ContextCompletionItem:diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 092961c8f85..4d06784952d 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -1787,7 +1787,7 @@ class _CompressionActivityHeartbeat:self._stop = threading.Event()self._thread = threading.Thread(target=self._run, name="compression-activity-heartbeat", daemon=True)- def start(self) -> "_CompressionActivityHeartbeat":+ def start(self) -> _CompressionActivityHeartbeat:# A new compression episode always republishes agent.compression even# if a prior timeout/cooldown stamp is still on the agent.self._suppressed = False@@ -1905,7 +1905,7 @@ class _CompressionLockLeaseRefresher:self._stop = threading.Event()self._thread = threading.Thread(target=self._run, name="compression-lock-refresh", daemon=True)- def start(self) -> "_CompressionLockLeaseRefresher":+ def start(self) -> _CompressionLockLeaseRefresher:self._thread.start()return selfdiff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex e1e7d734340..9682aedcf62 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -251,7 +251,7 @@ class PooledCredential:raise AttributeError(f"'{type(self).__name__}' object has no attribute {name!r}")@classmethod- def from_dict(cls, provider: str, payload: dict[str, Any]) -> "PooledCredential":+ def from_dict(cls, provider: str, payload: dict[str, Any]) -> PooledCredential:field_names = {f.name for f in fields(cls) if f.name != "provider"}data = {k: payload.get(k) for k in field_names if k in payload}# Rehydrated last_status_at may be an ISO string from to_dict() — normalize to float epoch@@ -425,7 +425,7 @@ def _parse_absolute_timestamp(value: Any) -> Optional[float]:return None-def _singleton_predates_entry(state: Any, entry: "PooledCredential") -> bool:+def _singleton_predates_entry(state: Any, entry: PooledCredential) -> bool:"""True only when the auth.json singleton is PROVABLY older than *entry*.Both sides stamp ``last_refresh`` on every successful rotation. When@@ -819,7 +819,7 @@ def _write_through_provider_state_to_global_root(logger.debug("%s pool refresh: write-through to global root failed: %s", provider_id, exc)-def _singleton_target_for_entry(pool: "CredentialPool", entry: "PooledCredential") -> Optional[Path]:+def _singleton_target_for_entry(pool: CredentialPool, entry: PooledCredential) -> Optional[Path]:"""Root ``.anthropic_oauth.json`` when *entry* is a borrowed hermes_pkce row, else None."""if entry.source != "hermes_pkce" or entry.id not in getattr(pool, "_borrowed_root_ids", ()):return None@@ -999,7 +999,7 @@ _RESYNC_SOURCE = {class _RefreshDone(Exception):"""Raised inside a provider refresher to short-circuit ``_refresh_entry_impl`` with ``result``."""- def __init__(self, result: Optional["PooledCredential"]):+ def __init__(self, result: Optional[PooledCredential]):super().__init__()self.result = resultdiff --git a/agent/credential_pool_model_cooldowns.py b/agent/credential_pool_model_cooldowns.pyindex 941799a8109..4e267cf9acb 100644--- a/agent/credential_pool_model_cooldowns.py+++ b/agent/credential_pool_model_cooldowns.py@@ -19,7 +19,7 @@ if TYPE_CHECKING:MODEL_ENTITLEMENT_BENCH_SECONDS = 365 * 24 * 60 * 60-def model_cooldown_until(entry: "PooledCredential", model: Optional[str]) -> Optional[float]:+def model_cooldown_until(entry: PooledCredential, model: Optional[str]) -> Optional[float]:"""Active cooldown blocking *entry* for *model*, or ``None``.Callers that do not know the model stay conservative: any active model@@ -75,7 +75,7 @@ class CredentialPoolModelCooldownMixin:)def _cool_down_model(- self, entry: "PooledCredential", model: str, error_context: Optional[dict[str, Any]],+ self, entry: PooledCredential, model: str, error_context: Optional[dict[str, Any]],failure_reason: Optional[str] = None,) -> None:"""Record a cooldown for *model* on *entry* and every sibling sharing its key.diff --git a/agent/credential_pool_plugin.py b/agent/credential_pool_plugin.pyindex e103f45af90..99dcb978a5e 100644--- a/agent/credential_pool_plugin.py+++ b/agent/credential_pool_plugin.py@@ -36,7 +36,7 @@ logger = logging.getLogger(__name__)_EXPIRY_SKEW_MS = 120_000-def plugin_row_is_expiring(entry: "PooledCredential") -> bool:+def plugin_row_is_expiring(entry: PooledCredential) -> bool:"""An expiry-stamped OAuth row (a plugin's, or Anthropic's) is due within the skew of ``expires_at_ms``.The token endpoint's ``expires_in`` is the only clock: many providers issue opaque bearers (Google's@@ -45,7 +45,7 @@ def plugin_row_is_expiring(entry: "PooledCredential") -> bool:return entry.expires_at_ms is not None and int(entry.expires_at_ms) <= int(time.time() * 1000) + _EXPIRY_SKEW_MS-def apply_plugin_refresh_result(entry: "PooledCredential", result: Any) -> "PooledCredential":+def apply_plugin_refresh_result(entry: PooledCredential, result: Any) -> PooledCredential:"""Merge a ``refresh_credential`` return value into *entry*.Field names go through ``dataclasses.replace``; everything else is merged into ``extra``@@ -78,8 +78,8 @@ def is_terminal_plugin_refresh_error(exc: BaseException) -> bool:def recover_failed_plugin_refresh(- pool: "CredentialPool", entry: "PooledCredential", exc: Exception,-) -> tuple[bool, Optional["PooledCredential"]]:+ pool: CredentialPool, entry: PooledCredential, exc: Exception,+) -> tuple[bool, Optional[PooledCredential]]:"""Recovery for a plugin hook that raised: adopt a peer's rotation, or quarantine a dead grant.Returns ``(handled, result)``; ``handled=False`` means the caller should bench the row as adiff --git a/agent/deadline.py b/agent/deadline.pyindex 34ead7cb14a..82025d98198 100644--- a/agent/deadline.py+++ b/agent/deadline.py@@ -195,7 +195,7 @@ def resolve_timeout(key: str, *, default: Optional[float], env_var: Optional[str# timer dumps all thread stacks when the loop provably failed to process the expiry — the one piece of# information loop-blocked hangs otherwise never surface.# ----------------------------------------------------------------------------def _consume_abandoned(task: "asyncio.Future[Any]") -> None:+def _consume_abandoned(task: asyncio.Future[Any]) -> None:"""Observe an abandoned task's outcome so it never logs 'never retrieved'."""try:if not task.cancelled():@@ -204,7 +204,7 @@ def _consume_abandoned(task: "asyncio.Future[Any]") -> None:pass-def _abandon(task: "asyncio.Future[Any]") -> None:+def _abandon(task: asyncio.Future[Any]) -> None:"""Cancel ``task`` and never await it; its outcome is consumed so it stays unobserved-safe."""task.cancel()task.add_done_callback(_consume_abandoned)@@ -253,7 +253,7 @@ async def run_bounded_async(task = asyncio.ensure_future(awaitable)loop = asyncio.get_running_loop()- deadline: "asyncio.Future[None]" = loop.create_future()+ deadline: asyncio.Future[None] = loop.create_future()loop_processed_expiry = threading.Event()def _mark_expired() -> None:diff --git a/agent/delegation_context.py b/agent/delegation_context.pyindex 9528cbd2f35..ef2a465856d 100644--- a/agent/delegation_context.py+++ b/agent/delegation_context.py@@ -138,7 +138,7 @@ def scrub_kanban_env(env: Mapping[str, str] | MutableMapping[str, str]) -> dict[return cleaned-def kanban_path_is_fenced(path: "os.PathLike[str] | str") -> bool:+def kanban_path_is_fenced(path: os.PathLike[str] | str) -> bool:"""Whether Kanban mutations at *path* (a board DB or board-metadata root) are denied for thisprocess: always for an in-process delegate child (the parent's own board); for a spawneddescendant only when *path* is the dispatcher-pinned ``HERMES_KANBAN_DB`` or lies under thediff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex 7c44299b6bb..8b53887eb80 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -1301,7 +1301,7 @@ _CODEX_MASKED_REPLAY_MESSAGE = "request blocked."_CODEX_UNSUPPORTED_CONTENT_DETAIL = "unsupported content type"-def _is_codex_masked_replay_rejection(c: "_Ctx") -> bool:+def _is_codex_masked_replay_rejection(c: _Ctx) -> bool:"""HTTP 400 / status-less ``{code: invalid_prompt, message: "Request blocked."}`` from``openai-codex`` — as an SDK error body, a Responses ``error`` SSE frame, or the``response.failed`` text ``"invalid_prompt: Request blocked."`` — or the barediff --git a/agent/fallback_cooldown.py b/agent/fallback_cooldown.pyindex 769a5fbf5cb..a42d7a2302e 100644--- a/agent/fallback_cooldown.py+++ b/agent/fallback_cooldown.py@@ -21,7 +21,7 @@ def _provider_reset_delay(reset_at) -> float | None:return None-def switch_deferred_by_reset(agent, reason: "FailoverReason | None", reset_at) -> bool:+def switch_deferred_by_reset(agent, reason: FailoverReason | None, reset_at) -> bool:"""Opt-in ``fallback.min_switch_reset_seconds`` (default 0 = off, #117484): when the primary'srate limit reopens sooner than N seconds, switching model mid-task costs more than waiting, sothe fallback walk is skipped and the retry loop's own backoff rides out the window. Only for@@ -43,7 +43,7 @@ def switch_deferred_by_reset(agent, reason: "FailoverReason | None", reset_at) -def _arm_rate_limit_cooldown(- agent, reason: "FailoverReason | None", reset_at=None,+ agent, reason: FailoverReason | None, reset_at=None,) -> int | None:"""Arm the primary cooldown until the provider reset, or use exponential backoff.diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex bf4a5681355..eeb22a45bdf 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -850,7 +850,7 @@ class GeminiNativeClient:return {"Content-Type": "application/json", "Accept": "application/json", **self._auth_headers(),"User-Agent": f"{_API_CLIENT} (gemini-native)", "X-Goog-Api-Client": _API_CLIENT, **self._default_headers}- def _http_error(self, response: httpx.Response, body_text: Optional[str] = None) -> "GeminiAPIError":+ def _http_error(self, response: httpx.Response, body_text: Optional[str] = None) -> GeminiAPIError:return gemini_http_error(response, body_text=body_text, api_key=self.api_key, base_url=self.base_url)@staticmethoddiff --git a/agent/interrupt_scope.py b/agent/interrupt_scope.pyindex 26f664c81aa..80d263f7354 100644--- a/agent/interrupt_scope.py+++ b/agent/interrupt_scope.py@@ -18,7 +18,7 @@ from typing import Any, Iterator, Optionalfrom agent.interrupt_compat import request_hard_interrupt-_ACTIVE_SCOPE: ContextVar[Optional["InterruptScope"]] = ContextVar("hermes_interrupt_scope", default=None)+_ACTIVE_SCOPE: ContextVar[Optional[InterruptScope]] = ContextVar("hermes_interrupt_scope", default=None)_TOOL_REASON_HOST_CANCELLED = "host cancelled the command"diff --git a/agent/lsp/manager.py b/agent/lsp/manager.pyindex 7550aeef7fd..75bf0604838 100644--- a/agent/lsp/manager.py+++ b/agent/lsp/manager.py@@ -189,7 +189,7 @@ class LSPService:self._loop.run(self._start_idle_reaper(), timeout=2.0)@classmethod- def create_from_config(cls) -> Optional["LSPService"]:+ def create_from_config(cls) -> Optional[LSPService]:"""Build a service from ``hermes_cli.config``; ``None`` if config can't load."""try:from hermes_cli.config import load_config_readonlydiff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 17c4969f60c..310a59f8395 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -665,7 +665,7 @@ def matches_reasoning_echo_family(family: str, provider: Any, model: Any, base_u)-def reasoning_echo_family(provider: Any, model: Any, base_url: Any) -> "str | None":+def reasoning_echo_family(provider: Any, model: Any, base_url: Any) -> str | None:"""``"kimi"`` / ``"deepseek"`` / ``"mimo"`` (first match in table order) when theendpoint enforces reasoning_content echo-back, else ``None`` (strip side)."""families = (rule[0] for rule in _REASONING_ECHO_RULES)diff --git a/agent/micro_compaction.py b/agent/micro_compaction.pyindex 1d729cd08f1..d0401fd61d5 100644--- a/agent/micro_compaction.py+++ b/agent/micro_compaction.py@@ -371,7 +371,7 @@ class MicroCompactionMixin:except Exception as exc:logger.debug("failed to emit micro-compaction telemetry: %s", exc)- def _micro_start_watermark(self, held: list[dict[str, Any]]) -> "tuple[Optional[str], Optional[int]]":+ def _micro_start_watermark(self, held: list[dict[str, Any]]) -> tuple[Optional[str], Optional[int]]:"""``(skip_outcome, watermark)`` taken before a pass's slow step; *skip_outcome* is the telemetrylabel of a pass that must not run, or None.diff --git a/agent/monitoring/emitter.py b/agent/monitoring/emitter.pyindex 87cc10fa622..52e5b8c7e3f 100644--- a/agent/monitoring/emitter.py+++ b/agent/monitoring/emitter.py@@ -26,7 +26,7 @@ class MonitoringEmitter:def __init__(self, *, enabled: bool = True) -> None:self._enabled = enabled- self._q: "queue.Queue[dict[str, Any]]" = queue.Queue(maxsize=_MAX_QUEUE)+ self._q: queue.Queue[dict[str, Any]] = queue.Queue(maxsize=_MAX_QUEUE)self._dropped = 0self._dispatched = 0self._stop = threading.Event()diff --git a/agent/outbound_webhooks.py b/agent/outbound_webhooks.pyindex f3b152ad5dd..df6c07ea833 100644--- a/agent/outbound_webhooks.py+++ b/agent/outbound_webhooks.py@@ -46,7 +46,7 @@ QUEUE_MAX_SIZE = 256_registered: set[tuple[str, str, str]] = set()_registered_lock = threading.Lock()-_delivery_queue: "queue.Queue[Optional[dict[str, Any]]]" = queue.Queue(maxsize=QUEUE_MAX_SIZE)+_delivery_queue: queue.Queue[Optional[dict[str, Any]]] = queue.Queue(maxsize=QUEUE_MAX_SIZE)_worker_lock = threading.Lock()_worker: Optional[threading.Thread] = Nonediff --git a/agent/periodic_scheduler.py b/agent/periodic_scheduler.pyindex c3355876f81..421f93055f7 100644--- a/agent/periodic_scheduler.py+++ b/agent/periodic_scheduler.py@@ -40,7 +40,7 @@ class ScheduledHandle:__slots__ = ("_cancelled", "_context", "_fn", "_interval", "_runner", "_scheduler")- def __init__(self, scheduler: "PeriodicScheduler", fn: Callable[[], object], interval: float):+ def __init__(self, scheduler: PeriodicScheduler, fn: Callable[[], object], interval: float):self._scheduler = schedulerself._fn = fnself._interval = intervaldiff --git a/agent/pet/constants.py b/agent/pet/constants.pyindex 1167966984c..8eacf7cdb0f 100644--- a/agent/pet/constants.py+++ b/agent/pet/constants.py@@ -80,7 +80,7 @@ STATE_ALIASES: dict[str, tuple[str, ...]] = {}-def state_aliases_for(state: "PetState | str") -> tuple[str, ...]:+def state_aliases_for(state: PetState | str) -> tuple[str, ...]:"""Return accepted row-name aliases for *state* (always non-empty)."""value = state.value if isinstance(state, PetState) else str(state)return STATE_ALIASES.get(value) or (value,)@@ -95,7 +95,7 @@ def state_rows_for_grid(row_count: int | None) -> list[str]:return CODEX_STATE_ROWS if rows >= len(CODEX_STATE_ROWS) else LEGACY_STATE_ROWS-def state_row_index(state: "PetState | str", row_count: int | None = None) -> int:+def state_row_index(state: PetState | str, row_count: int | None = None) -> int:"""Return the spritesheet row index for *state* (clamped, never raises)."""rows = state_rows_for_grid(row_count)return next((rows.index(name) for name in state_aliases_for(state) if name in rows), 0) # 0 = idle rowdiff --git a/agent/pet/manifest.py b/agent/pet/manifest.pyindex e54372fa580..18f17cb1aff 100644--- a/agent/pet/manifest.py+++ b/agent/pet/manifest.py@@ -78,7 +78,7 @@ class ManifestEntry:zip_url: str@classmethod- def from_dict(cls, data: dict) -> "ManifestEntry":+ def from_dict(cls, data: dict) -> ManifestEntry:return cls(slug=str(data.get("slug", "")).strip(),display_name=str(data.get("displayName", "") or data.get("slug", "")),diff --git a/agent/plugin_stream_hooks.py b/agent/plugin_stream_hooks.pyindex 87aec9d3018..daa9281e096 100644--- a/agent/plugin_stream_hooks.py+++ b/agent/plugin_stream_hooks.py@@ -27,7 +27,7 @@ _STOP = object()class _ConsumerDispatcher:hook_name: strcallback: Callable[..., Any]- events: "queue.Queue[tuple[contextvars.Context, dict[str, Any]] | object]"+ events: queue.Queue[tuple[contextvars.Context, dict[str, Any]] | object]thread: threading.Thread | None = None@@ -39,7 +39,7 @@ def _callback_name(callback: Callable[..., Any]) -> str:return getattr(callback, "__name__", repr(callback))-def _put_drop_oldest(events: "queue.Queue[Any]", item: Any) -> bool:+def _put_drop_oldest(events: queue.Queue[Any], item: Any) -> bool:"""put_nowait; on a full queue evict the oldest pending event and retry once."""try:events.put_nowait(item)diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex ac42f82409e..293694213e1 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -61,7 +61,7 @@ def _read_text_with_timeout("""if timeout is None:timeout = _get_context_file_read_timeout()- result: "queue.Queue[tuple[bool, object]]" = queue.Queue(maxsize=1)+ result: queue.Queue[tuple[bool, object]] = queue.Queue(maxsize=1)def _reader() -> None:try:@@ -620,8 +620,8 @@ STEER_CHANNEL_NOTE = ()-def hud_surface_note(valid_tool_names: "set[str] | None" = None,- deferred_tool_names: "frozenset[str] | set[str]" = frozenset()) -> str:+def hud_surface_note(valid_tool_names: set[str] | None = None,+ deferred_tool_names: frozenset[str] | set[str] = frozenset()) -> str:"""Per-turn note for a message typed into the desktop's floating HUD ("this"/"here" = the app behind it).A per-turn fact, not a platform (one session alternates between app window and HUD), so it rides the@@ -1062,7 +1062,7 @@ def _local_host_hints() -> list[str]:return ["\n".join(host_lines), _WINDOWS_BASH_SHELL_HINT]-def bot_screen_note(running: bool, display: "str | None", holder: str) -> str:+def bot_screen_note(running: bool, display: str | None, holder: str) -> str:"""The one-line Bot Screen status the model sees — the prompt's ``_bot_screen_hint`` body,parameterised so the display watcher can stage the same sentence as a per-turn note when ascreen starts or stops mid-session (#125830; the byte-stable prompt only converges at@@ -1184,7 +1184,7 @@ def _get_context_file_max_chars(context_length: Optional[int] = None) -> int:# Truncation warnings for run_agent to surface. A ContextVar so concurrent gateway prompt builds cannot# drain each other's.-_truncation_warnings: "contextvars.ContextVar[Optional[list]]" = contextvars.ContextVar(+_truncation_warnings: contextvars.ContextVar[Optional[list]] = contextvars.ContextVar("context_file_truncation_warnings", default=None)@@ -1294,8 +1294,8 @@ def _parse_skill_file(skill_file: Path) -> tuple[bool, dict, str]:def _skill_should_show(- conditions: dict, available_tools: "set[str] | None", available_toolsets: "set[str] | None",- session_platform: "str | None" = None,+ conditions: dict, available_tools: set[str] | None, available_toolsets: set[str] | None,+ session_platform: str | None = None,) -> bool:"""False if the skill's conditional activation rules exclude it."""# Gateway-channel gate runs regardless of tool info; fails open when the platform is unknown.@@ -1315,16 +1315,16 @@ def _skill_should_show(def _plugin_skill_prompt_rows(- disabled: "set[str]", available_tools: "set[str] | None", available_toolsets: "set[str] | None",- session_platform: "str | None",-) -> "list[tuple[str, str]]":+ disabled: set[str], available_tools: set[str] | None, available_toolsets: set[str] | None,+ session_platform: str | None,+) -> list[tuple[str, str]]:"""``(qualified_name, description)`` for every skill registered by an ENABLED plugin(``ctx.register_skill``), filtered through the same offer-time gates as on-disk skills.Plugin skills live in the plugin-manager registry — never under the profile skills tree —so the disk scans above cannot see them; this is their one path into ``<available_skills>``.The qualified ``plugin:skill`` name is exactly what ``skill_view`` resolves, and disablingor unloading a plugin removes its registry entries, so enablement gating is inherent."""- rows: "list[tuple[str, str]]" = []+ rows: list[tuple[str, str]] = []try:from hermes_cli.plugins import discover_plugins, get_plugin_managerdiscover_plugins() # idempotent; joins an in-flight discovery (same call skills_list makes)@@ -1359,8 +1359,8 @@ def _current_session_platform_hint() -> str:def build_skills_system_prompt(- available_tools: "set[str] | None" = None, available_toolsets: "set[str] | None" = None,- compact_categories: "frozenset[str] | None" = None, skills_dir_override: "Path | None" = None,+ available_tools: set[str] | None = None, available_toolsets: set[str] | None = None,+ compact_categories: frozenset[str] | None = None, skills_dir_override: Path | None = None,) -> str:"""Compact skill index for the system prompt.@@ -1432,7 +1432,7 @@ def _label_visible_entries(visible_entries: list[dict], skills_by_category: dictdef _render_skills_index(skills_by_category: dict[str, list[tuple[str, str]]], category_descriptions: dict[str, str],- compact_categories: "frozenset[str] | None", available_tools: "set[str] | None", unloadable: "list[str]" = (),+ compact_categories: frozenset[str] | None, available_tools: set[str] | None, unloadable: list[str] = (),) -> str:"""Render the ## Skills block; "" when there is nothing to list. *unloadable* names (different skillssharing a name AND relative path within one tier — one root or several) get a rename note instead of a row skill_view would refuse."""@@ -1501,8 +1501,8 @@ def _oneshot_prompt_variant() -> bool:def _build_skills_system_prompt_inner(- skills_dir: "Path", extra_roots: "list[tuple[int, Path]]", available_tools: "set[str] | None",- available_toolsets: "set[str] | None", compact_categories: "frozenset[str] | None",+ skills_dir: Path, extra_roots: list[tuple[int, Path]], available_tools: set[str] | None,+ available_toolsets: set[str] | None, compact_categories: frozenset[str] | None,) -> str:# The resolved platform is part of the key: per-platform disabled-skill lists need distinct cache entries._platform_hint = _current_session_platform_hint()@@ -1644,7 +1644,7 @@ def _omitted_headings(content: str, start: int, end: int, limit: int = 15) -> lireturn headings[:limit] + (["..."] if len(headings) > limit else [])-def load_soul_md(context_length: Optional[int] = None, home_override: "Path | None" = None) -> Optional[str]:+def load_soul_md(context_length: Optional[int] = None, home_override: Path | None = None) -> Optional[str]:"""SOUL.md from HERMES_HOME (identity slot #1), or None.Callers must pass ``skip_soul=True`` to ``build_context_files_prompt`` so it isn't injected twice.@@ -1850,7 +1850,7 @@ def _load_cursorrules(cwd_path: Path, context_length: Optional[int] = None) -> sdef build_context_files_prompt(cwd: Optional[str] = None, skip_soul: bool = False, context_length: Optional[int] = None,- allow_install_tree_fallback: bool = False, home_override: "Path | None" = None,+ allow_install_tree_fallback: bool = False, home_override: Path | None = None,) -> str:"""Discover and load context files for the system prompt (each capped, see ``_get_context_file_max_chars``).diff --git a/agent/prompt_cache_boundary.py b/agent/prompt_cache_boundary.pyindex 6d0fa76f54e..54b1be0dbd7 100644--- a/agent/prompt_cache_boundary.py+++ b/agent/prompt_cache_boundary.py@@ -20,7 +20,7 @@ _MAX_ENTRIES = 32_MAX_CHARS = 4 * 1024 * 1024_lock = threading.Lock()-_prefixes: "OrderedDict[str, None]" = OrderedDict()+_prefixes: OrderedDict[str, None] = OrderedDict()def register_stable_prefix(prefix: str) -> None:diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.pyindex b39704d8531..aa45bc90e91 100644--- a/agent/proxy_sources/iron_proxy.py+++ b/agent/proxy_sources/iron_proxy.py@@ -215,7 +215,7 @@ def allowlisted_env() -> dict[str, str]:return {n: os.environ[n] for n in _PROXY_SUBPROCESS_ENV_ALLOWLIST if n in os.environ}-def _run(argv: list[str], *, timeout: int, text: bool = False, **kwargs) -> "subprocess.CompletedProcess":+def _run(argv: list[str], *, timeout: int, text: bool = False, **kwargs) -> subprocess.CompletedProcess:if text:kwargs.update(text=True, encoding="utf-8", errors="replace")return subprocess.run(argv, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL, **kwargs)@@ -719,7 +719,7 @@ def _interrupt_guard(handler):signal.signal(sig, old)-def _spawn_daemon(bin_path: Path, cfg: Path, env: dict[str, str], log_path: Path) -> "subprocess.Popen":+def _spawn_daemon(bin_path: Path, cfg: Path, env: dict[str, str], log_path: Path) -> subprocess.Popen:"""Popen with stdout/stderr appended to ``log_path`` (0o600 from the first byte, O_NOFOLLOW so a plantedsymlink e.g. to authorized_keys can't receive output, owner-checked). Our log fd closes after Popen — the child has its dup."""try:@@ -743,7 +743,7 @@ def _spawn_daemon(bin_path: Path, cfg: Path, env: dict[str, str], log_path: Pathos.close(log_fd)-def _await_listening(proc: "subprocess.Popen", host: str, port: int, *, on_exit) -> bool:+def _await_listening(proc: subprocess.Popen, host: str, port: int, *, on_exit) -> bool:"""Poll until ``host:port`` accepts or the grace window lapses (do-while: >=1 check even at 0s); raises ``on_exit()`` if the child dies."""deadline = time.time() + _STARTUP_GRACE_SECONDSwhile True:@@ -784,7 +784,7 @@ def _write_pidfile_safely(pidfile: Path, pid: int) -> None:_write_private_file(pidfile.with_suffix(".nonce"), _proxy_nonce.encode("utf-8"))-def _kill_and_wait(proc: "subprocess.Popen", *, grace_seconds: int = 2) -> None:+def _kill_and_wait(proc: subprocess.Popen, *, grace_seconds: int = 2) -> None:try:proc.terminate()except OSError:diff --git a/agent/reasoning_params.py b/agent/reasoning_params.pyindex 3749faa67e4..8baa685a323 100644--- a/agent/reasoning_params.py+++ b/agent/reasoning_params.py@@ -210,7 +210,7 @@ class ReasoningParamsMixin:_reapply_reasoning_echo_for_provider = _forward("agent.agent_runtime_helpers", "reapply_reasoning_echo_for_provider")@staticmethod- def _sanitize_tool_calls_for_strict_api(api_msg: dict, model: "str | None" = None) -> dict:+ def _sanitize_tool_calls_for_strict_api(api_msg: dict, model: str | None = None) -> dict:"""Strip Codex Responses fields from tool_calls for strict Chat Completions APIs (Mistral, Fireworks400/422 on unknown fields). ``extra_content`` (Gemini thought_signature) is kept only for Gemini-familymodels. Builds new dicts so the internal history keeps the Codex fields for a later fallback."""diff --git a/agent/redact.py b/agent/redact.pyindex ab30c887336..e76499be9db 100644--- a/agent/redact.py+++ b/agent/redact.py@@ -363,7 +363,7 @@ def _is_word_end(s: str, j: int, *, allow_plural: bool = True) -> bool:return allow_plural and cur in "sS" and _is_word_end(s, j + 1, allow_plural=False)-def _has_word_bounded_keyword(key: str, keyword_re: "re.Pattern[str]") -> bool:+def _has_word_bounded_keyword(key: str, keyword_re: re.Pattern[str]) -> bool:"""True if ``keyword_re`` matches ``key`` at a word boundary (see _KEY_KEYWORD_RE)."""return any(_is_word_start(key, m.start()) and _is_word_end(key, m.end()) for m in keyword_re.finditer(key))@@ -580,7 +580,7 @@ _CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f\u200b-\u200f\u2028-\u202f\u2060\_TOKEN_BODY_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.")-def _compile_prefix_matcher(patterns: list) -> "re.Pattern[str]":+def _compile_prefix_matcher(patterns: list) -> re.Pattern[str]:return re.compile(r"(?<![A-Za-z0-9_-])(" + "|".join(patterns) + r")(?![A-Za-z0-9_-])")diff --git a/agent/relay_llm.py b/agent/relay_llm.pyindex 270cbc9a66f..e52f0b89176 100644--- a/agent/relay_llm.py+++ b/agent/relay_llm.py@@ -59,7 +59,7 @@ class _ManagedAttempt:def resolve(cls, session_id: str | None, request: dict[str, Any], metadata: dict[str, Any] | None,*, name: str, model_name: str,- ) -> "_ManagedAttempt | None":+ ) -> _ManagedAttempt | None:"""Return the managed attempt for ``session_id`` (None: the inherited turn's), or None to run unmanaged."""if session_id is None:session_id = _current_session_id()@@ -429,7 +429,7 @@ class ManagedLlmStream(Iterator[Any]):self._release_runtime_lease()raise- def __iter__(self) -> "ManagedLlmStream":+ def __iter__(self) -> ManagedLlmStream:return selfdef _prime_completed_response(self) -> None:diff --git a/agent/relay_runtime.py b/agent/relay_runtime.pyindex 5b3befef959..b0831f2a4dc 100644--- a/agent/relay_runtime.py+++ b/agent/relay_runtime.py@@ -270,7 +270,7 @@ _reset_segments_config_for_tests = _SEGMENTS_CONFIG.resetclass RelayOperationLease:"""Keep process-wide Relay plugins alive across a deferred operation."""- def __init__(self, runtime: "RelayRuntime") -> None:+ def __init__(self, runtime: RelayRuntime) -> None:self._lock, self._runtime = threading.Lock(), runtimedef run_in_session(self, session: RelaySession, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:diff --git a/agent/retry_utils.py b/agent/retry_utils.pyindex 1d35ccdb9e2..fc1d702f263 100644--- a/agent/retry_utils.py+++ b/agent/retry_utils.py@@ -79,12 +79,12 @@ _RETRY_AFTER_SECONDS_RE = re.compile(r"retry\s+(?:after\s+)?(\d+(?:\.\d+)?)\s*(?_RESETS_IN_SECONDS_FIELD_RE = re.compile(r"resets_in_seconds\W{1,4}(\d+(?:\.\d+)?)", re.IGNORECASE)-def _quota_reset_seconds(m: "re.Match[str]") -> float:+def _quota_reset_seconds(m: re.Match[str]) -> float:value = float(m.group(1))return value / 1000.0 if m.group(2).lower() == "ms" else value-def _resets_in_seconds(m: "re.Match[str]") -> Optional[float]:+def _resets_in_seconds(m: re.Match[str]) -> Optional[float]:if not any(m.groups()): # "resets in" with no unit-bearing number: not this grammarreturn Nonereturn float(m.group(1) or 0) * 3600 + float(m.group(2) or 0) * 60 + float(m.group(3) or 0)diff --git a/agent/secret_scope.py b/agent/secret_scope.pyindex 6175563e08a..dfe185a2882 100644--- a/agent/secret_scope.py+++ b/agent/secret_scope.py@@ -307,7 +307,7 @@ def _parse_env_value(raw_value: str) -> str:# symlink repointed mid-read can't file one file's contents under another's identity.# ``invalidate_env_file_cache()`` is the explicit knob; ``hermes_cli.config.invalidate_env_cache()``# calls it for Hermes's own .env writers.-_ENV_FILE_CACHE: "OrderedDict[str, tuple[tuple, dict[str, str]]]" = OrderedDict()+_ENV_FILE_CACHE: OrderedDict[str, tuple[tuple, dict[str, str]]] = OrderedDict()_ENV_FILE_CACHE_LOCK = threading.Lock()_ENV_FILE_CACHE_MAX = 64 # one entry per profile home in practicediff --git a/agent/secret_sources/base.py b/agent/secret_sources/base.pyindex c95e6aae648..eba98b6eeb7 100644--- a/agent/secret_sources/base.py+++ b/agent/secret_sources/base.py@@ -118,7 +118,7 @@ class FetchResult:def ok(self) -> bool:return self.error is None- def fail(self, error: str, kind: ErrorKind) -> "FetchResult":+ def fail(self, error: str, kind: ErrorKind) -> FetchResult:self.error, self.error_kind = error, kindreturn self@@ -191,7 +191,7 @@ class SecretSource(ABC):"""Informational ``{key: {"description": str, "default": Any}}`` for setup UIs."""return {}- def remediation(self, kind: Optional["ErrorKind"], cfg: dict) -> str:+ def remediation(self, kind: Optional[ErrorKind], cfg: dict) -> str:"""One-line actionable next step for a failed fetch (pure); "" suppresses the hint."""if kind is None:return ""diff --git a/agent/subagent_lifecycle.py b/agent/subagent_lifecycle.pyindex 82d6fa0dbb2..3aca72ee77b 100644--- a/agent/subagent_lifecycle.py+++ b/agent/subagent_lifecycle.py@@ -77,7 +77,7 @@ class SubagentHandle:return dataclasses.asdict(self)@classmethod- def from_dict(cls, value: Mapping[str, Any]) -> "SubagentHandle":+ def from_dict(cls, value: Mapping[str, Any]) -> SubagentHandle:try:return cls(**dict(value))except (TypeError, ValueError) as exc:diff --git a/agent/thread_scoped_output.py b/agent/thread_scoped_output.pyindex 02b7e273d0d..2363c73cab8 100644--- a/agent/thread_scoped_output.py+++ b/agent/thread_scoped_output.py@@ -19,11 +19,11 @@ __all__ = ["thread_scoped_silence"]_install_lock = threading.Lock()# Proxy installed per attribute ("stdout"/"stderr"): never double-wrap.-_installed: dict[str, "_ThreadRoutingStream"] = {}+_installed: dict[str, _ThreadRoutingStream] = {}# One process-lifetime sink per stream: global redirects that displace and# restore a proxy must not leak a new /dev/null descriptor each time._sinks: dict[str, TextIO] = {}-_routing_states: dict[str, "_RoutingState"] = {}+_routing_states: dict[str, _RoutingState] = {}class _RoutingState:@@ -87,7 +87,7 @@ class _ThreadRoutingStream:return getattr(self._target(), name)-def _ensure_installed(attr: str, passthrough: TextIO) -> "_ThreadRoutingStream":+def _ensure_installed(attr: str, passthrough: TextIO) -> _ThreadRoutingStream:"""Install (idempotently) a routing proxy as ``sys.<attr>`` and return it."""with _install_lock:proxy = _installed.get(attr)diff --git a/agent/title_generator.py b/agent/title_generator.pyindex 558e06bdf1d..fa14b71d406 100644--- a/agent/title_generator.py+++ b/agent/title_generator.py@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)# In-flight stage-2 upgrade threads. They bill their aux usage to the session from a daemon thread,# so a process that reads the ledger right before exit (``-z --usage-file``) must be able to join# them (bounded) instead of racing the write (#112848).-_UPGRADE_THREADS: "weakref.WeakSet[threading.Thread]" = weakref.WeakSet()+_UPGRADE_THREADS: weakref.WeakSet[threading.Thread] = weakref.WeakSet()def wait_for_title_upgrades(timeout: float = 10.0) -> None:diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.pyindex 50601f87dd0..258ca3ab929 100644--- a/agent/tool_guardrails.py+++ b/agent/tool_guardrails.py@@ -106,7 +106,7 @@ class LoopCapConfig:max_subagents: int = _DEFAULT_MAX_SUBAGENTS_PER_TURN@classmethod- def from_mapping(cls, data: Mapping[str, Any] | None) -> "LoopCapConfig":+ def from_mapping(cls, data: Mapping[str, Any] | None) -> LoopCapConfig:"""Build config from the ``tool_loop_guardrails.loop_caps`` section."""if not isinstance(data, Mapping):return cls()@@ -134,7 +134,7 @@ class ToolCallGuardrailConfig:@classmethoddef from_mapping(cls, data: Mapping[str, Any] | None, *, platform: str | None = None,- ) -> "ToolCallGuardrailConfig":+ ) -> ToolCallGuardrailConfig:"""Build config from `tool_loop_guardrails`; nested ``warn_after`` / ``hard_stop_after`` win over flat legacy keys."""if not isinstance(data, Mapping):data = {}@@ -170,7 +170,7 @@ class ToolCallSignature:args_hash: str@classmethod- def from_call(cls, tool_name: str, args: Mapping[str, Any] | None) -> "ToolCallSignature":+ def from_call(cls, tool_name: str, args: Mapping[str, Any] | None) -> ToolCallSignature:return cls(tool_name=tool_name, args_hash=_sha256(canonical_tool_args(args or {})))def to_metadata(self) -> dict[str, str]:diff --git a/agent/transcription_provider.py b/agent/transcription_provider.pyindex 48428d1d93e..2935b19fc0e 100644--- a/agent/transcription_provider.py+++ b/agent/transcription_provider.py@@ -43,7 +43,7 @@ class TranscriptionProvider(CatalogProviderBase):def open_stream_session(self, *, language: Optional[str] = None, prompt: Optional[str] = None,- ) -> "TranscriptionStreamSession":+ ) -> TranscriptionStreamSession:"""A single-use live session for one utterance (streaming-capable providers only)."""raise NotImplementedError(f"{self.name} does not support live streaming transcription")diff --git a/agent/transports/codex_app_server.py b/agent/transports/codex_app_server.pyindex da3b777441f..a64cec40d2a 100644--- a/agent/transports/codex_app_server.py+++ b/agent/transports/codex_app_server.py@@ -219,7 +219,7 @@ class CodexAppServerClient:for _rid, pending in pending_items:pending.put_nowait(synthetic)- def __enter__(self) -> "CodexAppServerClient":+ def __enter__(self) -> CodexAppServerClient:return selfdef __exit__(self, *exc: object) -> None:diff --git a/agent/usage_pricing.py b/agent/usage_pricing.pyindex 154df0d8151..91fdfa908d2 100644--- a/agent/usage_pricing.py+++ b/agent/usage_pricing.py@@ -80,7 +80,7 @@ class CanonicalUsage:def total_tokens(self) -> int:return self.prompt_tokens + self.output_tokens- def __add__(self, other: "CanonicalUsage") -> "CanonicalUsage":+ def __add__(self, other: CanonicalUsage) -> CanonicalUsage:"""Sum two usage buckets. ``raw_usage`` (single-response detail) isdropped; ``request_count`` adds so callers see how many API calls acombined figure covers."""diff --git a/agent/vault_backends/base.py b/agent/vault_backends/base.pyindex 636f8f481db..6795a2ba754 100644--- a/agent/vault_backends/base.py+++ b/agent/vault_backends/base.py@@ -20,7 +20,7 @@ from agent.vault_store import VaultItemMetaclass UnlockRequired(Exception):"""The backend is locked for this session; the surface must prompt for the master password."""- def __init__(self, backend: "LoginBackend"):+ def __init__(self, backend: LoginBackend):super().__init__(f"{backend.display_name} is locked")self.backend = backenddiff --git a/agent/vault_login_classifier.py b/agent/vault_login_classifier.pyindex 8fe521a6159..470ba80af6f 100644--- a/agent/vault_login_classifier.py+++ b/agent/vault_login_classifier.py@@ -76,7 +76,7 @@ class LoginControl:max_length: Optional[int] = None@classmethod- def from_dict(cls, raw: dict[str, Any]) -> "LoginControl":+ def from_dict(cls, raw: dict[str, Any]) -> LoginControl:form_index = raw.get("formIndex", raw.get("form_index"))max_length = raw.get("maxLength", raw.get("max_length"))return cls(diff --git a/agent/verify/recipes.py b/agent/verify/recipes.pyindex 8ec5a1c41b2..02dc573fd21 100644--- a/agent/verify/recipes.py+++ b/agent/verify/recipes.py@@ -47,7 +47,7 @@ class Recipe:}@classmethod- def from_dict(cls, raw: Any) -> "Recipe | None":+ def from_dict(cls, raw: Any) -> Recipe | None:"""Tolerant loader mirroring grok's ``normalizeVerifyRecipe``; acceptsboth this module's field names and grok's camelCase aliases."""if not isinstance(raw, dict):diff --git a/cli.py b/cli.pyindex 78ff9357c58..3c720665737 100644--- a/cli.py+++ b/cli.py@@ -896,7 +896,7 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,# Seeded -q first message (see _should_seed_interactive); run() re-creates# _pending_input, so it is enqueued only after the fresh queue exists.- _seeded_first_message: Optional["_SeededQueryMessage"] = None+ _seeded_first_message: Optional[_SeededQueryMessage] = None# Inspection surfaces (banner, /tools, status line) read this on partially built instances too.disabled_toolsets: Optional[list[str]] = Nonediff --git a/cron/jobs.py b/cron/jobs.pyindex 7d165965189..4a6264ad61a 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -121,7 +121,7 @@ class _CronStorePaths:output_dir: Path@classmethod- def for_dir(cls, cron_dir: Path) -> "_CronStorePaths":+ def for_dir(cls, cron_dir: Path) -> _CronStorePaths:return cls(cron_dir, cron_dir / "jobs.json", cron_dir / "output")diff --git a/cron/scheduler.py b/cron/scheduler.pyindex bd715ff3083..eb2abf1cd07 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -659,7 +659,7 @@ class _CombinedCancelEvent:``lost_ownership`` + per-transport events). Workers only call is_set()/set(), so no pump thread."""- def __init__(self, *events: Optional["_CancelEventLike"]) -> None:+ def __init__(self, *events: Optional[_CancelEventLike]) -> None:self._events = [event for event in events if event is not None]def is_set(self) -> bool:@@ -670,7 +670,7 @@ class _CombinedCancelEvent:event.set()-def get_running_job_ids() -> "frozenset[str]":+def get_running_job_ids() -> frozenset[str]:"""Thread-safe snapshot of executing job IDs (dispatch until ``_process_job`` returns). Read bythe gateway shutdown drain, otherwise blind to cron work (runs outside ``_running_agents``).@@ -697,7 +697,7 @@ def get_running_job_details() -> list[dict]:]-def get_wedged_job_ids() -> "frozenset[str]":+def get_wedged_job_ids() -> frozenset[str]:"""In-flight job IDs older than their stale-inflight allowance (``max(2 * interval,cron.inflight_max_minutes)``) — the scheduler's own definition of a claim that can no longer bemaking progress. ``sweep_stale_inflight`` cannot release these while the worker thread is still@@ -707,7 +707,7 @@ def get_wedged_job_ids() -> "frozenset[str]":return frozenset(key[1] for key in _wedged_inflight_keys())-def _wedged_inflight_keys() -> "frozenset[tuple]":+def _wedged_inflight_keys() -> frozenset[tuple]:"""In-flight keys behind :func:`get_wedged_job_ids`, before the projection to bare job IDs."""now = time.time()with _running_lock:@@ -3243,7 +3243,7 @@ def _deliver_crash_failure(-def _install_fire_secret_scope() -> "tuple[contextvars.Token, Optional[contextvars.Token]]":+def _install_fire_secret_scope() -> tuple[contextvars.Token, Optional[contextvars.Token]]:"""Install the firing profile's secret scope for the span ``_run_one_job_body`` runs, deliveryincluded, and return the tokens ``_reset_fire_secret_scope`` needs.@@ -3270,7 +3270,7 @@ def _install_fire_secret_scope() -> "tuple[contextvars.Token, Optional[contextvareturn scope_token, context_token-def _reset_fire_secret_scope(tokens: "tuple[contextvars.Token, Optional[contextvars.Token]]") -> None:+def _reset_fire_secret_scope(tokens: tuple[contextvars.Token, Optional[contextvars.Token]]) -> None:"""Undo ``_install_fire_secret_scope`` — the context first, so multiplex semantics neveroutlive the scope they depend on."""from agent.secret_scope import reset_multiplex_context, reset_secret_scope@@ -3291,7 +3291,7 @@ def _fire_secret_scope():_reset_fire_secret_scope(tokens)-def _start_owned_run(job: dict, execution_id: str) -> "Optional[contextvars.Token]":+def _start_owned_run(job: dict, execution_id: str) -> Optional[contextvars.Token]:"""Win the run's ``claimed`` → ``running`` CAS and bind its cron identity; ``None`` when the runlost ownership first. A restart-safe worker already won it by adopting the row."""if os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id:diff --git a/cron/scheduler_detached_worker.py b/cron/scheduler_detached_worker.pyindex 66cbbccf47a..a51a308cd26 100644--- a/cron/scheduler_detached_worker.py+++ b/cron/scheduler_detached_worker.py@@ -15,7 +15,7 @@ import threadingfrom typing import Optional-def _close_late_session_db_result(future: "concurrent.futures.Future") -> None:+def _close_late_session_db_result(future: concurrent.futures.Future) -> None:"""Done-callback: close a SessionDB whose constructor finished after run_job's init timeout(worker abandoned via ``shutdown(wait=False)``), else its .db/WAL/SHM handles leak to EMFILE.diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex 8cc78116026..f753b0a7fa2 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -291,7 +291,7 @@ def _misfire_grace_minutes() -> float:def fire_overdue_jobs(- provider: "CronScheduler", *, adapters: Any = None, loop: Any = None, now: Any = None,+ provider: CronScheduler, *, adapters: Any = None, loop: Any = None, now: Any = None,) -> int:"""Misfire backstop (gateway housekeeping loop): fire jobs whose external HTTP fire neverarrived, else ``next_run_at`` stays parked in the past forever. No-op for the built-in (its tick@@ -384,7 +384,7 @@ def fire_overdue_jobs(return fired-def resolve_cron_scheduler() -> "CronScheduler":+def resolve_cron_scheduler() -> CronScheduler:"""Resolve ``cron.provider``; missing/failing/unavailable providers fall back to the built-inwith a warning — cron must never be left without a trigger."""name = ""@@ -414,8 +414,8 @@ def resolve_cron_scheduler() -> "CronScheduler":def scheduler_for_profile_mode(- provider: "CronScheduler", *, multiplex_profiles: bool-) -> "CronScheduler":+ provider: CronScheduler, *, multiplex_profiles: bool+) -> CronScheduler:"""External providers own one unscoped remote registry and cannot reconcile several profilestores: fail closed to the built-in multiplex ticker until the API carries profile identity."""if not multiplex_profiles or isinstance(provider, InProcessCronScheduler):diff --git a/evals/postmortem/forensics/common.py b/evals/postmortem/forensics/common.pyindex a8f7a6efbce..76fe6978772 100644--- a/evals/postmortem/forensics/common.py+++ b/evals/postmortem/forensics/common.py@@ -67,12 +67,12 @@ class Run:return ap@classmethod- def from_args(cls, argv: Optional[list[str]] = None, description: str = "") -> "Run":+ def from_args(cls, argv: Optional[list[str]] = None, description: str = "") -> Run:a = cls.parser(description).parse_args(argv)return cls.open(a.db, root=a.root, out=a.out)@classmethod- def open(cls, db: str, *, root: Optional[str] = None, out: str = "postmortem_out") -> "Run":+ def open(cls, db: str, *, root: Optional[str] = None, out: str = "postmortem_out") -> Run:conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)conn.row_factory = sqlite3.Rowsessions = {r["id"]: dict(r) for r in conn.execute("SELECT * FROM sessions")}diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.pyindex ad407168eac..97fc1c37a28 100644--- a/gateway/authz_mixin.py+++ b/gateway/authz_mixin.py@@ -448,7 +448,7 @@ class GatewayAuthorizationMixin:return bool(sender_allow.strip())return isinstance(sender_allow, (list, tuple, set)) and any(str(item).strip() for item in sender_allow)- def _pairing_store_for(self, source: "SessionSource"):+ def _pairing_store_for(self, source: SessionSource):"""Per-profile PairingStore for a source, else the global ``self.pairing_store``."""per_profile = getattr(self, "pairing_stores", None) or {}profile = getattr(source, "profile", None)diff --git a/gateway/browser_control_broker.py b/gateway/browser_control_broker.pyindex 5286437d609..67673517235 100644--- a/gateway/browser_control_broker.py+++ b/gateway/browser_control_broker.py@@ -201,7 +201,7 @@ class BrowserControlBroker:else:self._artifact_stores[profile_id] = store- def _artifact_store_for_scope(self, scope: "ControllerScope") -> Any:+ def _artifact_store_for_scope(self, scope: ControllerScope) -> Any:store = self._artifact_stores.get(getattr(scope, "profile_id", None) or None)return store if store is not None else self._artifact_stores.get(None)diff --git a/gateway/config.py b/gateway/config.pyindex 79654878e38..8564642c811 100644--- a/gateway/config.py+++ b/gateway/config.py@@ -43,7 +43,7 @@ def _coerce_bool(value: Any, default: bool = True) -> bool:return is_truthy_value(value, default=default)-def _env_multiplex_profiles_override() -> "bool | None":+def _env_multiplex_profiles_override() -> bool | None:"""GATEWAY_MULTIPLEX_PROFILES operator override: True/False for a recognized token.``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml@@ -68,7 +68,7 @@ def _env_multiplex_profiles_override() -> "bool | None":ON_ALL_ADAPTERS_DOWN_POLICIES = ("exit", "stay_alive")-def _env_on_all_adapters_down_override() -> "str | None":+def _env_on_all_adapters_down_override() -> str | None:"""GATEWAY_ON_ALL_ADAPTERS_DOWN operator override: 'exit'/'stay_alive' for a recognized token.``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml value@@ -267,7 +267,7 @@ class Platform(Enum):return cls._add_pseudo_member(value) if registered else None@classmethod- def _add_pseudo_member(cls, value: str) -> "Platform":+ def _add_pseudo_member(cls, value: str) -> Platform:pseudo = object.__new__(cls)pseudo._value_ = valuepseudo._name_ = value.upper().replace("-", "_").replace(" ", "_")@@ -276,7 +276,7 @@ class Platform(Enum):return pseudo@classmethod- def _scan_bundled_plugin_platforms(cls) -> "tuple[set, dict]":+ def _scan_bundled_plugin_platforms(cls) -> tuple[set, dict]:"""Directory names of bundled platform plugins under ``plugins/platforms/``, plus a map ofmanifest ``name:`` keys that differ from their directory (alias -> directory name). Aliasesnever shadow a directory name, so the directory stays the canonical platform value."""@@ -359,7 +359,7 @@ class HomeChannel:return {"platform": self.platform.value, "chat_id": self.chat_id, "name": self.name, **optional}@classmethod- def from_dict(cls, data: dict[str, Any]) -> "HomeChannel":+ def from_dict(cls, data: dict[str, Any]) -> HomeChannel:optional = {k: str(data[k]) if data.get(k) else None for k in ("thread_id", "user_id", "scope_id")}return cls(platform=Platform(data["platform"]), chat_id=str(data["chat_id"]), name=data.get("name", "Home"), **optional)@@ -386,7 +386,7 @@ class ChannelOverride:return {k: v for k, v in asdict(self).items() if v is not None}@classmethod- def from_dict(cls, data: dict[str, Any]) -> "ChannelOverride":+ def from_dict(cls, data: dict[str, Any]) -> ChannelOverride:return cls(**{f.name: data.get(f.name) for f in fields(cls)}) if data else cls()@@ -395,7 +395,7 @@ class ChannelOverride:# authenticate another way and must never be skipped for a missing token.# Platforms absent from this map authenticate some other way (session files, port-bound webhooks,# api_key-only) and must never be skipped for a missing token. See #64674.-PLATFORM_TOKEN_ENV_NAMES: dict["Platform", str] = {+PLATFORM_TOKEN_ENV_NAMES: dict[Platform, str] = {Platform.TELEGRAM: "TELEGRAM_BOT_TOKEN",Platform.DISCORD: "DISCORD_BOT_TOKEN",Platform.SLACK: "SLACK_BOT_TOKEN",@@ -442,7 +442,7 @@ class PlatformConfig:})@classmethod- def from_dict(cls, data: dict[str, Any]) -> "PlatformConfig":+ def from_dict(cls, data: dict[str, Any]) -> PlatformConfig:data = _coerce_dict(data)home = data.get("home_channel")# Adapters read their settings from ``extra`` (``config.extra.get("port")``), but users@@ -518,7 +518,7 @@ class StreamingConfig:return asdict(self)@classmethod- def from_dict(cls, data: dict[str, Any]) -> "StreamingConfig":+ def from_dict(cls, data: dict[str, Any]) -> StreamingConfig:if not isinstance(data, dict) or not data:return cls()@@ -721,7 +721,7 @@ class GatewayConfig:}@classmethod- def from_dict(cls, data: dict[str, Any]) -> "GatewayConfig":+ def from_dict(cls, data: dict[str, Any]) -> GatewayConfig:data = _coerce_dict(data)nested_gateway = _coerce_dict(data.get("gateway"))@@ -865,7 +865,7 @@ def load_gateway_config() -> GatewayConfig:return config-def _validate_gateway_config(config: "GatewayConfig") -> None:+def _validate_gateway_config(config: GatewayConfig) -> None:"""Validate and sanitize a loaded GatewayConfig in place (after all sources are merged)."""try:# Reject known-weak placeholder tokens. Ported from openclaw/openclaw#64586: users who copydiff --git a/gateway/delivery.py b/gateway/delivery.pyindex b38dfb1433c..edcae16f5b1 100644--- a/gateway/delivery.py+++ b/gateway/delivery.py@@ -121,7 +121,7 @@ class DeliveryTarget:unknown_platform: Optional[str] = None@classmethod- def parse(cls, target: str, origin: Optional[SessionSource] = None) -> "DeliveryTarget":+ def parse(cls, target: str, origin: Optional[SessionSource] = None) -> DeliveryTarget:"""Parse "origin" | "local" | "<platform>" | "<platform>:<chat_id>[:<thread_id>]"."""target = target.strip()if target.lower() == "origin":diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.pyindex cf2db2bf285..ee1f8c2dd2a 100644--- a/gateway/host_rendezvous.py+++ b/gateway/host_rendezvous.py@@ -120,7 +120,7 @@ class HostRecord:}@classmethod- def from_json(cls, payload: Any) -> Optional["HostRecord"]:+ def from_json(cls, payload: Any) -> Optional[HostRecord]:if not isinstance(payload, dict):return Nonepid = payload.get("pid")diff --git a/gateway/hosted_room_execution_policy.py b/gateway/hosted_room_execution_policy.pyindex 07e012eef47..f75a82a0c68 100644--- a/gateway/hosted_room_execution_policy.py+++ b/gateway/hosted_room_execution_policy.py@@ -38,7 +38,7 @@ class RoomExecutionPolicy:policy_digest: str@classmethod- def from_mapping(cls, value: Mapping[str, Any]) -> "RoomExecutionPolicy":+ def from_mapping(cls, value: Mapping[str, Any]) -> RoomExecutionPolicy:if not isinstance(value, Mapping) or set(value) != _POLICY_FIELDS:raise RoomExecutionPolicyError("execution policy fields are invalid")if value["version"] != POLICY_VERSION:diff --git a/gateway/hosted_room_links.py b/gateway/hosted_room_links.pyindex 000986b20c0..9d55894824f 100644--- a/gateway/hosted_room_links.py+++ b/gateway/hosted_room_links.py@@ -50,7 +50,7 @@ class StoredRoomLink:updated_at: float@classmethod- def from_mapping(cls, value: Mapping[str, Any]) -> "StoredRoomLink":+ def from_mapping(cls, value: Mapping[str, Any]) -> StoredRoomLink:_link_fields(value)room_id = _short_string(value["room_id"], "room_id")member_id = _short_string(value["member_id"], "member_id")@@ -76,7 +76,7 @@ class StoredRoomLink:status=status, updated_at=updated_at)@classmethod- def from_record(cls, value: Mapping[str, Any]) -> "StoredRoomLink":+ def from_record(cls, value: Mapping[str, Any]) -> StoredRoomLink:try:catalog = json.loads(str(value["catalog_json"]))except Exception as exc:diff --git a/gateway/hosted_room_peer.py b/gateway/hosted_room_peer.pyindex eb1493d53e9..e39f4d679d2 100644--- a/gateway/hosted_room_peer.py+++ b/gateway/hosted_room_peer.py@@ -206,7 +206,7 @@ class GatewayRoomCatalog:transport_security: TransportSecurity | None = None@classmethod- def from_mapping(cls, value: Mapping[str, Any]) -> "GatewayRoomCatalog":+ def from_mapping(cls, value: Mapping[str, Any]) -> GatewayRoomCatalog:_exact_fields(value, required=_CATALOG_FIELDS, optional={"endpoint"}, label="capability catalog")installation_id = _identifier(value["installation_id"], field="installation_id")versions = tuple(_protocol_versions(_non_empty_list(value["protocol_versions"], field="protocol_versions")))@@ -379,7 +379,7 @@ class HostedMemberDispatch:return asdict(self)@classmethod- def from_mapping(cls, value: Mapping[str, Any]) -> "HostedMemberDispatch":+ def from_mapping(cls, value: Mapping[str, Any]) -> HostedMemberDispatch:_exact_fields(value, required=set(_DISPATCH_FIELDS) | {"prompt", "prompt_digest"}, label="dispatch")if not isinstance(prompt := value["prompt"], str) or not prompt.strip():raise HostedRoomPeerError("prompt must be a non-empty string")diff --git a/gateway/kanban_watchers_common.py b/gateway/kanban_watchers_common.pyindex eb0bca88a41..4be46ea4c4b 100644--- a/gateway/kanban_watchers_common.py+++ b/gateway/kanban_watchers_common.py@@ -63,7 +63,7 @@ def _positive_int_setting(kanban_cfg: dict, key: str) -> Optional[int]:return value-def _resolve_auto_decompose_settings(load_config: Callable[[], Any]) -> "tuple[bool, int]":+def _resolve_auto_decompose_settings(load_config: Callable[[], Any]) -> tuple[bool, int]:"""Live (enabled, per_tick) auto-decompose settings, re-read every dispatcher tick.Fails safe: a config read error returns ``(False, 3)`` rather than@@ -110,7 +110,7 @@ def _kanban_dispatch_allowed() -> bool:return not check_paused("kanban", logger)-def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":+def _acquire_singleton_lock(lock_path) -> tuple[Optional[object], str]:"""Take the exclusive, non-blocking advisory lock for the sole dispatcher.Only one gateway machine-wide may run the embedded dispatcher: concurrentdiff --git a/gateway/kanban_watchers_notifier.py b/gateway/kanban_watchers_notifier.pyindex b19ebb01200..d94be2b853f 100644--- a/gateway/kanban_watchers_notifier.py+++ b/gateway/kanban_watchers_notifier.py@@ -470,7 +470,7 @@ def _fmt_timed_out(ev, n) -> tuple:# archived / unblocked are claimed (so the cursor advances past them) but# intentionally silent (no formatter), and excluded from _WAKE_KINDS so they# never wake the creator.-_EVENT_FORMATTERS: dict[str, Callable[[Any, "_KanbanNotification"], tuple]] = {+_EVENT_FORMATTERS: dict[str, Callable[[Any, _KanbanNotification], tuple]] = {"completed": _fmt_completed,"blocked": lambda ev, n: (t("gateway.kanban.ping.blocked", head=n.head, reason=_clip(ev, "reason", "gateway.kanban.ping.reason_suffix", 160)),diff --git a/gateway/platforms/_http_client_limits.py b/gateway/platforms/_http_client_limits.pyindex d24f5321294..1e4d3d90cf6 100644--- a/gateway/platforms/_http_client_limits.py+++ b/gateway/platforms/_http_client_limits.py@@ -34,7 +34,7 @@ def _positive_env(name: str, default, cast):return val if val > 0 else default-def platform_httpx_limits() -> "httpx.Limits | None":+def platform_httpx_limits() -> httpx.Limits | None:"""``httpx.Limits`` tuned for persistent platform-adapter clients; ``None`` without httpx."""if httpx is None:return Nonediff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 7db0bdd156e..f28b6bf4f0f 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -558,7 +558,7 @@ def _content_has_visible_payload(content: Any) -> bool:return False-def _multimodal_validation_error(exc: ValueError, *, param: str) -> "web.Response":+def _multimodal_validation_error(exc: ValueError, *, param: str) -> web.Response:"""Translate a ``_normalize_multimodal_content`` ValueError into a 400 response."""raw = str(exc)code, _, message = raw.partition(":")@@ -633,7 +633,7 @@ def _clear_turn_process_ownership(agent: Any) -> None:agent._gateway_turn_process_epoch = None-def _session_chat_user_message(body: dict[str, Any], *, param: str = "message") -> tuple[Any, Optional["web.Response"]]:+def _session_chat_user_message(body: dict[str, Any], *, param: str = "message") -> tuple[Any, Optional[web.Response]]:"""Parse and normalize session chat ``message`` / ``input`` like chat completions."""user_message = body.get("message") or body.get("input")if not _content_has_visible_payload(user_message):@@ -884,7 +884,7 @@ def _resolve_media_to_data_urls(text: str) -> str:return Nonereturn f""- def _repl(m: "re.Match[str]") -> str:+ def _repl(m: re.Match[str]) -> str:return _to_data_url(m.group("path")) or m.group(0)try:# A leaked terminal <|eos|> glued to the last tag is not a path terminator (#111046):@@ -912,12 +912,12 @@ def _openai_error(message: str, err_type: str = "invalid_request_error", param:def _error_response(message: str, status: int, *, err_type: str = "invalid_request_error",param: str | None = None, code: str | None = None, headers: Optional[dict[str, str]] = None,-) -> "web.Response":+) -> web.Response:"""``web.json_response(_openai_error(...), status=...)`` in one call."""return web.json_response(_openai_error(message, err_type, param, code), status=status, headers=headers)-def _invalid_request(message: str) -> "web.Response":+def _invalid_request(message: str) -> web.Response:"""400 with the bare ``{message, type}`` envelope the OpenAI-compatible validators use."""return web.json_response({"error": {"message": message, "type": "invalid_request_error"}}, status=400)@@ -988,7 +988,7 @@ class _IdempotencyCache:def __init__(self, max_items: int = 1000, ttl_seconds: int = 300):from collections import OrderedDictself._store = OrderedDict()- self._inflight: dict[tuple[str, str], "asyncio.Task[Any]"] = {}+ self._inflight: dict[tuple[str, str], asyncio.Task[Any]] = {}self._ttl = ttl_secondsself._max = max_items@@ -1016,7 +1016,7 @@ class _IdempotencyCache:task = asyncio.create_task(_compute_and_store())self._inflight[inflight_key] = task- def _clear_inflight(done_task: "asyncio.Task[Any]") -> None:+ def _clear_inflight(done_task: asyncio.Task[Any]) -> None:if self._inflight.get(inflight_key) is done_task:self._inflight.pop(inflight_key, None)task.add_done_callback(_clear_inflight)@@ -1124,7 +1124,7 @@ class _SessionEventQueue:def __init__(self, session_id: str, run_id: str):self.loop = asyncio.get_running_loop()- self.queue: "asyncio.Queue[Optional[tuple[str, dict[str, Any]]]]" = asyncio.Queue()+ self.queue: asyncio.Queue[Optional[tuple[str, dict[str, Any]]]] = asyncio.Queue()self.session_id = session_idself.run_id = run_idself.seq = 0@@ -1153,7 +1153,7 @@ class _SessionEventQueue:def _room_grant_delegate(name: str):"""Adapter method forwarding to ``api_server_room_grants.<name>`` (looked up at call time sotest patches on that module take effect) with this module's error/profile bindings."""- async def _handler(self, request: "web.Request") -> "web.Response":+ async def _handler(self, request: web.Request) -> web.Response:return await getattr(_room_grants, name)(self, request, _openai_error=_openai_error, _api_request_profile=_api_request_profile)_handler.__name__ = name@@ -1163,7 +1163,7 @@ def _room_grant_delegate(name: str):def _run_route_delegate(name: str):"""Adapter method forwarding to ``api_server_runs.<name>`` (call-time lookup) with thismodule's namespace as ``_api_server``."""- async def _handler(self, request: "web.Request") -> "web.StreamResponse":+ async def _handler(self, request: web.Request) -> web.StreamResponse:return await getattr(_api_runs, name)(self, request, _api_server=sys.modules[__name__])_handler.__name__ = namereturn _handler@@ -1214,9 +1214,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# clients that choke on named events (#12020). Default on.self._tool_progress_events: bool = _coerce_request_bool(extra.get("tool_progress_events"), default=True)- self._app: Optional["web.Application"] = None- self._runner: Optional["web.AppRunner"] = None- self._site: Optional["web.TCPSite"] = None+ self._app: Optional[web.Application] = None+ self._runner: Optional[web.AppRunner] = None+ self._site: Optional[web.TCPSite] = Nonefrom hermes_constants import get_hermes_homeself._response_store = ResponseStore() # this home's; a /p/<profile>/ route gets its ownself._response_store_home = str(get_hermes_home())@@ -1310,7 +1310,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except Exception:return False- def _draining_response(self) -> Optional["web.Response"]:+ def _draining_response(self) -> Optional[web.Response]:"""Return a retryable response while the gateway drains existing work."""if not self._gateway_is_draining():return None@@ -1478,7 +1478,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return {**_CORS_HEADERS, "Access-Control-Allow-Origin": origin, "Vary": "Origin","Access-Control-Max-Age": "600"}- def _sse_headers(self, request: "web.Request", extra: Optional[dict[str, str]] = None) -> dict[str, str]:+ def _sse_headers(self, request: web.Request, extra: Optional[dict[str, str]] = None) -> dict[str, str]:"""Headers for an SSE StreamResponse prepared inside a handler: the CORS middleware onlytouches the response after the handler returns, by which point ``prepare()`` has alreadyflushed the head, so CORS must be resolved up front (#72892, #6358)."""@@ -1500,7 +1500,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):text = str(value).replace("\r", " ").replace("\n", " ").strip()return text[:max_len]- def _request_audit_context(self, request: "web.Request") -> dict[str, str]:+ def _request_audit_context(self, request: web.Request) -> dict[str, str]:"""Return non-secret source metadata for security/audit warnings."""peer_ip = ""with suppress(Exception):@@ -1516,12 +1516,12 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"path": self._clean_log_value(request.path_qs, max_len=500),"user_agent": self._clean_log_value(request.headers.get("User-Agent", ""), max_len=300)}- def _request_audit_log_suffix(self, request: "web.Request") -> str:+ def _request_audit_log_suffix(self, request: web.Request) -> str:ctx = self._request_audit_context(request)fields = [f"{key}={value!r}" for key, value in ctx.items() if value]return " ".join(fields) if fields else "source='unknown'"- def _cron_origin_from_request(self, request: "web.Request") -> dict[str, str]:+ def _cron_origin_from_request(self, request: web.Request) -> dict[str, str]:"""Persist safe API source metadata on cron jobs created over HTTP."""ctx = self._request_audit_context(request)origin = {"platform": "api_server", "chat_id": "api"}@@ -1550,13 +1550,13 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return ""@staticmethod- def _auth_failed_response() -> "web.Response":+ def _auth_failed_response() -> web.Response:return web.json_response({"error": {"message": "Invalid gateway API key (API_SERVER_KEY)", "type": "gateway_auth_error","code": "gateway_auth_failed"}},status=401)- def _check_auth(self, request: "web.Request") -> Optional["web.Response"]:+ def _check_auth(self, request: web.Request) -> Optional[web.Response]:"""Validate the Bearer token; None when OK, else a 401. The no-key branch (connect()refuses to start without API_SERVER_KEY) exists for tests/manual wiring on the defaultlistener only; named profiles fail closed rather than inherit the owner's key."""@@ -1586,7 +1586,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return normalized if re.fullmatch(r"[a-z0-9_]+", normalized) else ""def _get_platform_callback_adapter(- self, request: "web.Request", platform_name: str) -> Optional[Any]:+ self, request: web.Request, platform_name: str) -> Optional[Any]:injected = request.app.get("platform_event_adapters")adapter = injected.get(platform_name) if isinstance(injected, dict) else Noneif adapter is None:@@ -1605,7 +1605,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return Nonereturn runner._authorization_adapter(platform, _api_request_profile.get())- async def _handle_platform_event_callback(self, request: "web.Request") -> "web.Response":+ async def _handle_platform_event_callback(self, request: web.Request) -> web.Response:platform_name = self._normalize_callback_platform(request.match_info.get("platform", ""))if not platform_name:return _error_response("Invalid platform name", 400, code="invalid_platform")@@ -1644,7 +1644,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# -- Multi-profile multiplexing (/p/<profile>/...) --------------------------------- def _resolve_request_profile(self, request: "web.Request"):+ def _resolve_request_profile(self, request: web.Request):"""Resolve + validate the /p/<profile>/ prefix: ``None`` (no prefix, or multiplexingoff and the prefix names this gateway's own profile), the served profile name, or``_PROFILE_REJECTED`` (-> 404). Fail closed: a foreign prefix must never be ignored."""@@ -1682,7 +1682,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):from hermes_cli.profiles import get_profile_dirreturn _profile_runtime_scope(get_profile_dir(profile))- async def _handle_profile_ingress(self, request: "web.Request") -> "web.StreamResponse":+ async def _handle_profile_ingress(self, request: web.Request) -> web.StreamResponse:"""``/p/<profile>/<tail>`` → the served profile's shared-listener adapter (already scoped by theprefix middleware); a profile with no adapter for the path is a 404, never the default's."""from gateway.platforms.shared_ingress import dispatch_profile_ingress@@ -1694,7 +1694,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"""Reject unknown /p/<profile>/ prefixes and scope the request home."""@web.middleware- async def profile_prefix_middleware(request: "web.Request", handler):+ async def profile_prefix_middleware(request: web.Request, handler):profile = self._resolve_request_profile(request)if profile is _PROFILE_REJECTED:return web.json_response({"error": "Unknown or unconfigured profile"}, status=404)@@ -1823,7 +1823,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"[%s] declared-conversation bind failed for %s", self.name, sid, exc_info=True)def _parse_session_key_header(- self, request: "web.Request") -> tuple[Optional[str], Optional["web.Response"]]:+ self, request: web.Request) -> tuple[Optional[str], Optional[web.Response]]:"""Validate ``X-Hermes-Session-Key`` (per-channel memory scope) -> ``(key_or_None, None)``or ``(None, error)``. Requires API-key auth so a client can't guess another scope."""raw = request.headers.get("X-Hermes-Session-Key", "").strip()@@ -1845,7 +1845,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# -- Responses state ----------------------------------------------------------------- def _current_response_store(self) -> "ResponseStore":+ def _current_response_store(self) -> ResponseStore:"""Responses state of the routed profile's home. Conversation names are client-chosen, so oneshared store let any profile's key read, chain onto and overwrite another's (#84253)."""from hermes_constants import get_hermes_home@@ -2049,7 +2049,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return (cls._clean_runtime_id(requested.get("model")),cls._clean_runtime_id(requested.get("provider"), max_len=80))- def _runtime_lock_error(self, runtime_request: dict[str, Any]) -> Optional["web.Response"]:+ def _runtime_lock_error(self, runtime_request: dict[str, Any]) -> Optional[web.Response]:if not runtime_request.get("require_model_lock"):return Nonemodel, provider = self._requested_ids(runtime_request.get("requested"))@@ -2422,12 +2422,12 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# -- HTTP handlers ----------------------------------------------------------------- async def _handle_health(self, request: "web.Request") -> "web.Response":+ async def _handle_health(self, request: web.Request) -> web.Response:"""GET /health — simple health check."""return web.json_response({"status": "ok", "platform": "hermes-agent", "version": _hermes_version()})@_require_auth- async def _handle_health_detailed(self, request: "web.Request") -> "web.Response":+ async def _handle_health_detailed(self, request: web.Request) -> web.Response:"""GET /health/detailed — gateway state, platforms, PID for dashboard probing (Bearer auth)."""from gateway.status import (derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents,@@ -2472,7 +2472,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"updated_at": normalize_updated_at(runtime.get("updated_at")), "pid": os.getpid()})@_require_auth- async def _handle_models(self, request: "web.Request") -> "web.Response":+ async def _handle_models(self, request: web.Request) -> web.Response:"""GET /v1/models — hermes-agent plus configured model_routes aliases (alias + resolvedmodel only, never credentials). Under /p/<profile>/ the primary id follows that profile."""now = int(time.time())@@ -2489,7 +2489,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "list", "data": models})@_require_auth- async def _handle_model_options(self, request: "web.Request") -> "web.Response":+ async def _handle_model_options(self, request: web.Request) -> web.Response:"""GET /api/model/options — the dashboard/TUI model-picker inventory, so external clientscan sync to the configured provider catalog instead of scraping /v1/models."""refresh = _coerce_request_bool(request.query.get("refresh"), default=False)@@ -2509,7 +2509,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return _error_response("Failed to list model options.", 500, code="model_options_failed")@_require_auth- async def _handle_capabilities(self, request: "web.Request") -> "web.Response":+ async def _handle_capabilities(self, request: web.Request) -> web.Response:"""GET /v1/capabilities — the stable, machine-readable API surface for external UIs."""return web.json_response({"object": "hermes.api_server.capabilities", "platform": "hermes-agent",@@ -2551,7 +2551,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# -- Browser-extension control (authenticated local/VPS API) ----------------------- async def _handle_browser_control_register(self, request: "web.Request") -> "web.Response":+ async def _handle_browser_control_register(self, request: web.Request) -> web.Response:"""POST /v1/browser-control/register — mint a short-lived single-use controller ticket.Identity is NOT taken from the body: the principal is a server-derived digest of the@@ -2630,7 +2630,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"capabilities": sorted(scope.capabilities)}},status=201)- async def _handle_browser_control_ws(self, request: "web.Request") -> "web.WebSocketResponse":+ async def _handle_browser_control_ws(self, request: web.Request) -> web.WebSocketResponse:"""GET /v1/browser-control/ws — controller WebSocket (one-shot ticket).The ticket rides in ``Sec-WebSocket-Protocol`` (never the query string: targets land in@@ -2686,7 +2686,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return wsdef _handle_browser_control_frame(- self, scope: "ControllerScope", frame: dict, *, owner: Any = None) -> Optional[dict]:+ self, scope: ControllerScope, frame: dict, *, owner: Any = None) -> Optional[dict]:"""Apply one controller->broker frame with exact-scope checks."""method = frame.get("method")params = frame.get("params")@@ -2729,7 +2729,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):digest = hashlib.sha256(f"{profile}\x00{key}".encode()).hexdigest()return f"principal:{profile}:{digest[:32]}"- def _browser_control_transport_family(self, request: "web.Request") -> str:+ def _browser_control_transport_family(self, request: web.Request) -> str:"""``local-api`` for a loopback peer, else ``remote-api``; the broker treats the family aspart of exact identity, so a remote controller never satisfies a local-only dispatch."""host = None@@ -2830,7 +2830,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if limiter is not None:self._browser_control_artifact_limiter = limiter- def _artifact_route_prelude(self, request: "web.Request", action: str, *, check_enabled: bool = True) -> tuple:+ def _artifact_route_prelude(self, request: web.Request, action: str, *, check_enabled: bool = True) -> tuple:"""Shared upload/download gate (feature flag -> API key -> Bearer -> per-principal ratelimit) -> ``((profile, principal), None)`` or ``(None, error_response)``."""if check_enabled and not self._browser_control_enabled():@@ -2851,7 +2851,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):code="rate_limit_exceeded", headers={"Retry-After": "1"})return (profile, principal), None- async def _handle_artifact_upload(self, request: "web.Request") -> "web.Response":+ async def _handle_artifact_upload(self, request: web.Request) -> web.Response:"""POST /v1/artifacts/upload — one-shot bounded raw upload; ``Content-Type`` must be anallowed MIME type, ``X-Artifact-Filename`` is display-only. Returns a provenance receipt(never a filesystem path). Ladder: 404 disabled, 403 no API key, 401 bad Bearer, 429@@ -2895,7 +2895,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response(receipt.to_dict(download_path=f"/v1/artifacts/download/{receipt.artifact_id}"), status=201)- async def _handle_artifact_download(self, request: "web.Request") -> "web.Response":+ async def _handle_artifact_download(self, request: web.Request) -> web.Response:"""GET /v1/artifacts/download/{artifact_id} — one-shot download (a second one 404s) with``X-Artifact-Sha256``. Ladder: 404 disabled/unknown, 403 no API key, 401 bad Bearer, 429rate limited, 410 expired, 400 invalid id/scope mismatch, 200."""@@ -2924,7 +2924,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"Content-Disposition": f'attachment; filename="{receipt.filename}"'})@_require_auth- async def _handle_skills(self, request: "web.Request") -> "web.Response":+ async def _handle_skills(self, request: web.Request) -> web.Response:"""GET /v1/skills — deterministic JSON listing of installed skills (name, description,category), the same set ``/skills list`` shows."""try:@@ -2940,7 +2940,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "list", "data": skills})@_require_auth- async def _handle_toolsets(self, request: "web.Request") -> "web.Response":+ async def _handle_toolsets(self, request: web.Request) -> web.Response:"""GET /v1/toolsets — each toolset the api_server agent exposes: enabled/configured stateplus the concrete tool names it expands to."""try:@@ -2979,7 +2979,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return default if parsed < 0 else min(parsed, maximum)@staticmethod- def _session_db_unavailable() -> "web.Response":+ def _session_db_unavailable() -> web.Response:return _error_response("Session database unavailable", 503, code="session_db_unavailable")@staticmethod@@ -3026,7 +3026,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"display_kind")return {key: message.get(key) for key in safe_keys if key in message}- async def _read_json_body(self, request: "web.Request") -> tuple[dict[str, Any], Optional["web.Response"]]:+ async def _read_json_body(self, request: web.Request) -> tuple[dict[str, Any], Optional[web.Response]]:try:body = await request.json()except Exception:@@ -3035,7 +3035,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return {}, _error_response("Request body must be a JSON object", 400)return body, None- async def _get_existing_session_or_404(self, session_id: str) -> tuple[Optional[dict[str, Any]], Optional["web.Response"]]:+ async def _get_existing_session_or_404(self, session_id: str) -> tuple[Optional[dict[str, Any]], Optional[web.Response]]:db = await self._ensure_session_db_async()if db is None:return None, self._session_db_unavailable()@@ -3063,7 +3063,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):notification_category=notification_category, _api_server=sys.modules[__name__])@_require_auth- async def _handle_list_sessions(self, request: "web.Request") -> "web.Response":+ async def _handle_list_sessions(self, request: web.Request) -> web.Response:"""GET /api/sessions — list persisted Hermes sessions."""db = await self._ensure_session_db_async()if db is None:@@ -3118,7 +3118,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"limit": limit, "offset": offset, "has_more": windowed >= limit})@_require_auth- async def _handle_create_session(self, request: "web.Request") -> "web.Response":+ async def _handle_create_session(self, request: web.Request) -> web.Response:"""POST /api/sessions -- create an empty Hermes session row. Existence check, insert andtitle handling run as ONE off-loop write so concurrent same-id creates can't both 201."""body, err = await self._read_json_body(request)@@ -3186,7 +3186,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "hermes.session", "session": self._session_response(session)}, status=201)@_require_auth- async def _handle_get_session(self, request: "web.Request") -> "web.Response":+ async def _handle_get_session(self, request: web.Request) -> web.Response:"""GET /api/sessions/{session_id}."""session, err = await self._get_existing_session_or_404(request.match_info["session_id"])if err:@@ -3194,7 +3194,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "hermes.session", "session": self._session_response(session)})@_require_auth- async def _handle_patch_session(self, request: "web.Request") -> "web.Response":+ async def _handle_patch_session(self, request: web.Request) -> web.Response:"""PATCH /api/sessions/{session_id} — update client-safe session metadata."""session_id = request.match_info["session_id"]session, err = await self._get_existing_session_or_404(session_id)@@ -3234,7 +3234,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "hermes.session", "session": self._session_response(session)})@_require_auth- async def _handle_delete_session(self, request: "web.Request") -> "web.Response":+ async def _handle_delete_session(self, request: web.Request) -> web.Response:"""DELETE /api/sessions/{session_id}."""session_id = request.match_info["session_id"]_session, err = await self._get_existing_session_or_404(session_id)@@ -3267,7 +3267,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"object": "hermes.session.deleted", "id": session_id, "deleted": bool(deleted)})@_require_auth- async def _handle_session_messages(self, request: "web.Request") -> "web.Response":+ async def _handle_session_messages(self, request: web.Request) -> web.Response:"""GET /api/sessions/{session_id}/messages."""session_id = request.match_info["session_id"]_, err = await self._get_existing_session_or_404(session_id)@@ -3303,7 +3303,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"returned": len(messages)}})@_require_auth- async def _handle_fork_session(self, request: "web.Request") -> "web.Response":+ async def _handle_fork_session(self, request: web.Request) -> web.Response:"""POST /api/sessions/{session_id}/fork — branch via current SessionDB primitives."""source_id = request.match_info["session_id"]source, err = await self._get_existing_session_or_404(source_id)@@ -3344,7 +3344,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):fork = await asyncio.to_thread(db.get_session, fork_id) or {"id": fork_id, "parent_session_id": source_id}return web.json_response({"object": "hermes.session", "session": self._session_response(fork)}, status=201)- async def _prepare_session_chat(self, request: "web.Request") -> tuple:+ async def _prepare_session_chat(self, request: web.Request) -> tuple:"""Shared prelude for /api/sessions/{id}/chat[/stream]: header/body validation, thenruntime selection — a Browser model lock (body ``require_model_lock`` or a confirmedpersisted lock) wins; else the session-persisted model routes via model_routes when an@@ -3481,7 +3481,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):record = await asyncio.to_thread(_admit)return None if record is None else (home, record)- async def _answer_through_live_bot_chat(self, ctx: dict[str, Any]) -> Optional["web.Response"]:+ async def _answer_through_live_bot_chat(self, ctx: dict[str, Any]) -> Optional[web.Response]:"""Hand a turn aimed at a canonical Bot Chat that a Desktop holds live to that owner.This is the ``hermes peer dm`` transport. Running the turn here would make this process a@@ -3528,7 +3528,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):await keepalive()return record- async def _stream_through_live_bot_chat(self, request: "web.Request", ctx: dict[str, Any]) -> Optional["web.StreamResponse"]:+ async def _stream_through_live_bot_chat(self, request: web.Request, ctx: dict[str, Any]) -> Optional[web.StreamResponse]:"""``_answer_through_live_bot_chat`` for the SSE sibling route: the owner's settled receipt isthe run's single ``assistant.completed`` event; a receipt still open at the budget is a``run.queued`` event (the 202 shape), a failed one an ``error`` event carrying the reason."""@@ -3567,7 +3567,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return response@_admit_api_agent_request- async def _handle_session_chat(self, request: "web.Request") -> "web.Response":+ async def _handle_session_chat(self, request: web.Request) -> web.Response:"""POST /api/sessions/{session_id}/chat — one synchronous agent turn (plus the delivery lanes'one bounded re-run of a transient failure; ``hermes peer dm`` is the client)."""from tools.bot_failure_reasons import RETRY_NONE, result_retry_action@@ -3612,7 +3612,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):headers=headers)@_admit_api_agent_request- async def _handle_session_chat_stream(self, request: "web.Request") -> "web.StreamResponse":+ async def _handle_session_chat_stream(self, request: web.Request) -> web.StreamResponse:"""POST /api/sessions/{session_id}/chat/stream — SSE wrapper over _run_agent."""limited = self._concurrency_limited_response()if limited is not None:@@ -3740,7 +3740,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):logger.debug("[api_server] session SSE stream error: %s", exc)return response- def _register_session_stream_approval(self, run_id: str, events: "_SessionEventQueue", message_id: str):+ def _register_session_stream_approval(self, run_id: str, events: _SessionEventQueue, message_id: str):"""Route a session-stream turn's dangerous-command approvals to its SSE queue and to``POST /v1/runs/{run_id}/approval`` (#58856). Keyed by the run id (never the sharedsession key) so concurrent turns on one session can't cross-resolve."""@@ -3753,7 +3753,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return _approval_notifyasync def _drain_session_stream_task_on_disconnect(- self, run_id: str, task: "asyncio.Task", *, interrupt_message: str, shield_wait: bool+ self, run_id: str, task: asyncio.Task, *, interrupt_message: str, shield_wait: bool) -> None:"""Preserve live run control refs until the executor-backed turn actually exits."""agent = self._active_run_agents.get(run_id)@@ -3770,7 +3770,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):await (asyncio.shield(task) if shield_wait else task)@_require_auth- async def _handle_session_model_lock(self, request: "web.Request") -> "web.Response":+ async def _handle_session_model_lock(self, request: web.Request) -> web.Response:"""POST /api/sessions/{session_id}/model — backend-ack a Browser model lock."""session_id = request.match_info["session_id"]_, err = await self._get_existing_session_or_404(session_id)@@ -3809,7 +3809,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):_MAX_PROMPT_LENGTH = 5000def _cron_request_guard(- self, request: "web.Request", *, need_job_id: bool = False, check_draining: bool = False,+ self, request: web.Request, *, need_job_id: bool = False, check_draining: bool = False,) -> tuple:"""Shared /api/jobs prelude: auth → (drain) → cron available → (job_id). Returns (job_id, err)."""auth_err = self._check_auth(request)@@ -3831,10 +3831,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return job_id, None@staticmethod- def _cron_error_response(exc: BaseException) -> "web.Response":+ def _cron_error_response(exc: BaseException) -> web.Response:return web.json_response({"error": _redact_api_error_text(exc)}, status=500)- def _validate_cron_prompt(self, prompt: str) -> Optional["web.Response"]:+ def _validate_cron_prompt(self, prompt: str) -> Optional[web.Response]:"""Length cap + injection scan shared by create/update/run."""if len(prompt) > self._MAX_PROMPT_LENGTH:return web.json_response({"error": f"Prompt must be ≤ {self._MAX_PROMPT_LENGTH} characters"}, status=400)@@ -3844,7 +3844,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return web.json_response({"error": scan_error}, status=400)return None- def _job_response(self, fn, job_id: str, *, notify: bool) -> "web.Response":+ def _job_response(self, fn, job_id: str, *, notify: bool) -> web.Response:"""Run ``fn(job_id)``: 404 when falsy, else ``{"job": ...}``; exceptions -> 500."""try:job = fn(job_id)@@ -3856,11 +3856,11 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except Exception as e:return self._cron_error_response(e)- async def _job_lookup_or_mutate(self, request: "web.Request", fn, *, notify: bool) -> "web.Response":+ async def _job_lookup_or_mutate(self, request: web.Request, fn, *, notify: bool) -> web.Response:job_id, err = self._cron_request_guard(request, need_job_id=True)return err if err else self._job_response(fn, job_id, notify=notify)- async def _handle_list_jobs(self, request: "web.Request") -> "web.Response":+ async def _handle_list_jobs(self, request: web.Request) -> web.Response:"""GET /api/jobs — list all cron jobs."""_, err = self._cron_request_guard(request)if err:@@ -3871,7 +3871,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except Exception as e:return self._cron_error_response(e)- async def _handle_create_job(self, request: "web.Request") -> "web.Response":+ async def _handle_create_job(self, request: web.Request) -> web.Response:"""POST /api/jobs — create a new cron job."""_, err = self._cron_request_guard(request)if err:@@ -3913,11 +3913,11 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except Exception as e:return self._cron_error_response(e)- async def _handle_get_job(self, request: "web.Request") -> "web.Response":+ async def _handle_get_job(self, request: web.Request) -> web.Response:"""GET /api/jobs/{job_id} — get a single cron job."""return await self._job_lookup_or_mutate(request, _cron_get, notify=False)- async def _handle_update_job(self, request: "web.Request") -> "web.Response":+ async def _handle_update_job(self, request: web.Request) -> web.Response:"""PATCH /api/jobs/{job_id} — update a cron job."""job_id, err = self._cron_request_guard(request, need_job_id=True)if err:@@ -3938,7 +3938,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return self._cron_error_response(e)return self._job_response(lambda jid: _cron_update(jid, sanitized), job_id, notify=True)- async def _handle_delete_job(self, request: "web.Request") -> "web.Response":+ async def _handle_delete_job(self, request: web.Request) -> web.Response:"""DELETE /api/jobs/{job_id} — delete a cron job."""job_id, err = self._cron_request_guard(request, need_job_id=True)if err:@@ -3951,15 +3951,15 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except Exception as e:return self._cron_error_response(e)- async def _handle_pause_job(self, request: "web.Request") -> "web.Response":+ async def _handle_pause_job(self, request: web.Request) -> web.Response:"""POST /api/jobs/{job_id}/pause — pause a cron job."""return await self._job_lookup_or_mutate(request, _cron_pause, notify=True)- async def _handle_resume_job(self, request: "web.Request") -> "web.Response":+ async def _handle_resume_job(self, request: web.Request) -> web.Response:"""POST /api/jobs/{job_id}/resume — resume a paused cron job."""return await self._job_lookup_or_mutate(request, _cron_resume, notify=True)- async def _handle_run_job(self, request: "web.Request") -> "web.Response":+ async def _handle_run_job(self, request: web.Request) -> web.Response:"""POST /api/jobs/{job_id}/run — trigger immediate execution."""job_id, err = self._cron_request_guard(request, need_job_id=True, check_draining=True)if err:@@ -3980,7 +3980,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return self._job_response(lambda jid: _cron_trigger(jid, extra_prompt=extra_prompt), job_id, notify=False)- async def _handle_cron_fire(self, request: "web.Request") -> "web.Response":+ async def _handle_cron_fire(self, request: web.Request) -> web.Response:"""POST /api/cron/fire — Chronos fire webhook (NAS -> agent), authenticated by aNAS-minted JWT via the pluggable verifier, NOT API_SERVER_KEY. 202 + background run soa long turn never trips NAS's timeout; the store CAS claim guards double-fire on retry."""@@ -4038,7 +4038,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if refusal is not None:return refusal- def _detach_fire(fire_fn, *fire_args) -> "web.Response":+ def _detach_fire(fire_fn, *fire_args) -> web.Response:# The done callback owns the reservation once the task is detached.task = asyncio.create_task(asyncio.to_thread(fire_fn, *fire_args, adapters=adapters, loop=loop))reservation["detached"] = True@@ -4077,7 +4077,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if hasattr(task, "add_done_callback"):task.add_done_callback(self._background_tasks.discard)- def _concurrency_limited_response(self) -> Optional["web.Response"]:+ def _concurrency_limited_response(self) -> Optional[web.Response]:"""429 when the concurrent-run cap is reached (0 disables), else None. Uses the sameadapter-owned work count as shutdown draining (admitted requests included)."""limit = self._max_concurrent_runs@@ -4361,29 +4361,29 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):def _set_run_status(self, run_id: str, status: str, **fields: Any) -> dict[str, Any]:return _api_runs._set_run_status(self, run_id, status, **fields)- def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoop"):+ def _make_run_event_callback(self, run_id: str, loop: asyncio.AbstractEventLoop):return _api_runs._make_run_event_callback(self, run_id, loop, _api_server=sys.modules[__name__])- def _run_idempotency_scope(self, request: "web.Request") -> str:+ def _run_idempotency_scope(self, request: web.Request) -> str:return _api_runs._run_idempotency_scope(self, request, _api_server=sys.modules[__name__])@staticmethod- def _room_grant_token(request: "web.Request") -> str:+ def _room_grant_token(request: web.Request) -> str:return _room_grants._room_grant_token(request)def _room_grant_secret(self) -> bytes:return _room_grants._room_grant_secret(self)- def _room_grant_claims(self, request: "web.Request", *, permission: str) -> dict[str, Any]:+ def _room_grant_claims(self, request: web.Request, *, permission: str) -> dict[str, Any]:return _room_grants._room_grant_claims(self, request, permission=permission)- def _check_run_auth(self, request: "web.Request", *, permission: str) -> "web.Response | None":+ def _check_run_auth(self, request: web.Request, *, permission: str) -> web.Response | None:return _api_runs._check_run_auth(self, request, permission=permission, _api_server=sys.modules[__name__])async def _ensure_hosted_member_session(self, dispatch: Any) -> str:return await _room_dispatch._ensure_hosted_member_session(self, dispatch)- async def _normalize_room_dispatch(self, request: "web.Request", body: Any) -> tuple[Any, "web.Response | None"]:+ async def _normalize_room_dispatch(self, request: web.Request, body: Any) -> tuple[Any, web.Response | None]:return await _room_dispatch._normalize_room_dispatch(self, request, body, _api_server=sys.modules[__name__])_handle_room_member_invitation = _room_grant_delegate("_handle_room_member_invitation")@@ -4391,14 +4391,14 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):_handle_room_member_grant_refresh = _room_grant_delegate("_handle_room_member_grant_refresh")_handle_room_member_grant_revoke = _room_grant_delegate("_handle_room_member_grant_revoke")- def _durable_run_status(self, request: "web.Request", run_id: str) -> dict[str, Any] | None:+ def _durable_run_status(self, request: web.Request, run_id: str) -> dict[str, Any] | None:return _api_runs._durable_run_status(self, request, run_id)@_admit_api_agent_request- async def _handle_runs(self, request: "web.Request") -> "web.Response":+ async def _handle_runs(self, request: web.Request) -> web.Response:return await _api_runs._handle_runs(self, request, _api_server=sys.modules[__name__])- def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:+ def _request_owns_run(self, request: web.Request, run_id: str) -> bool:return _api_runs._request_owns_run(self, request, run_id)def _release_run_owner_if_forgotten(self, run_id: str) -> None:diff --git a/gateway/platforms/api_server_fire_startup.py b/gateway/platforms/api_server_fire_startup.pyindex 50d5693e441..84f84f60486 100644--- a/gateway/platforms/api_server_fire_startup.py+++ b/gateway/platforms/api_server_fire_startup.py@@ -27,7 +27,7 @@ def runner_is_draining(runner: Any) -> bool:return bool(getattr(runner, "_draining", False) or getattr(runner, "_external_drain_active", False))-async def refuse_until_started(runner: Any, job_id: str, *, received_at: float) -> Optional["web.Response"]:+async def refuse_until_started(runner: Any, job_id: str, *, received_at: float) -> Optional[web.Response]:"""None once ``runner`` has finished starting (``_running``: every platform connect attempted and itsadapters published), or when there is no runner to ask (a self-hosted api_server, a test double).Otherwise the retryable 503, worded like the dashboard's own "gateway unreachable" so NAS classifies@@ -53,8 +53,8 @@ async def refuse_until_started(runner: Any, job_id: str, *, received_at: float)async def live_adapters_once_started(- api_adapter: Any, request: "web.Request", job_id: str, *, received_at: float,-) -> tuple[Optional["web.Response"], Any]:+ api_adapter: Any, request: web.Request, job_id: str, *, received_at: float,+) -> tuple[Optional[web.Response], Any]:"""``(refusal, adapters)`` for a fire: the startup gate's retryable 503, else the gateway's LIVE adapters(parity with the built-in ticker: E2EE / relay-fronted platforms have no native credential, so withoutthem delivery fails). ``None`` adapters when there is no runner (a self-hosted api_server)."""diff --git a/gateway/platforms/api_server_memory_sessions.py b/gateway/platforms/api_server_memory_sessions.pyindex 0d3b8c469c3..7dcf75e6591 100644--- a/gateway/platforms/api_server_memory_sessions.py+++ b/gateway/platforms/api_server_memory_sessions.py@@ -32,7 +32,7 @@ class ApiServerMemorySessions:"""Session-keyed ``MemoryManager`` registry with exclusive check-out/check-in."""def __init__(self, *, max_size: Optional[int] = None, idle_ttl_secs: Optional[float] = None) -> None:- self._entries: "OrderedDict[tuple[str, str], tuple[Any, Optional[Path], float]]" = OrderedDict()+ self._entries: OrderedDict[tuple[str, str], tuple[Any, Optional[Path], float]] = OrderedDict()self._lock = threading.Lock()self._max_size = max_sizeself._idle_ttl_secs = idle_ttl_secsdiff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 6d8b43adf46..0c3a134381c 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -633,7 +633,7 @@ class OpenAICompatRoutesMixin:agent_task.add_done_callback(_done)return agent_task, agent_ref- async def _handle_chat_completions(self, request: "web.Request") -> "web.Response":+ async def _handle_chat_completions(self, request: web.Request) -> web.Response:"""POST /v1/chat/completions — OpenAI Chat Completions format."""from gateway.platforms.api_server import (ThreadSafeAsyncQueue, _api_request_profile, _chat_usage_payload, _coerce_request_bool,@@ -841,7 +841,7 @@ class OpenAICompatRoutesMixin:return web.json_response(response_data, headers=response_headers)async def _run_idempotent(- self, request: "web.Request", body: dict[str, Any], compute, *,+ self, request: web.Request, body: dict[str, Any], compute, *,log_label: str, fingerprint_keys: list[str], route: str) -> tuple:"""Run ``compute()`` once per (principal scope, logical route, Idempotency-Key) + body fingerprint-> ``((result, usage), None)`` or ``(None, 500 response)``.@@ -870,8 +870,8 @@ class OpenAICompatRoutesMixin:return None, _error_response(message, 500, err_type="server_error")async def _prepare_sse_response(- self, request: "web.Request", session_id: Optional[str], gateway_session_key: Optional[str],- ) -> "web.StreamResponse":+ self, request: web.Request, session_id: Optional[str], gateway_session_key: Optional[str],+ ) -> web.StreamResponse:"""Open a prepared SSE StreamResponse with CORS + session headers (the CORS middlewarecan't inject headers after ``prepare()`` flushes them, so they are resolved here)."""sse_headers = self._sse_headers(request)@@ -884,9 +884,9 @@ class OpenAICompatRoutesMixin:return responseasync def _write_sse_chat_completion(- self, request: "web.Request", completion_id: str, model: str,+ self, request: web.Request, completion_id: str, model: str,created: int, stream_q, agent_task, agent_ref=None, session_id: str | None = None,- gateway_session_key: str | None = None) -> "web.StreamResponse":+ gateway_session_key: str | None = None) -> web.StreamResponse:"""Stream ``chat.completion.chunk`` frames from the agent's delta queue. On clientdisconnect the agent is interrupted (stops LLM calls), then its task wrapper cancelled."""from gateway.platforms.api_server import (@@ -975,10 +975,10 @@ class OpenAICompatRoutesMixin:return responseasync def _write_sse_responses(- self, request: "web.Request", response_id: str, model: str, created_at: int, stream_q,+ self, request: web.Request, response_id: str, model: str, created_at: int, stream_q,agent_task, agent_ref, conversation_history: list[dict[str, str]], user_message: str,instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str,- gateway_session_key: Optional[str] = None) -> "web.StreamResponse":+ gateway_session_key: Optional[str] = None) -> web.StreamResponse:"""Write the SSE stream for POST /v1/responses.Events: ``response.created`` -> ``output_text.delta/done`` + ``output_item.added/done``@@ -1031,7 +1031,7 @@ class OpenAICompatRoutesMixin:logger.error("Agent crashed mid-stream for %s: %s", response_id, str(st.agent_error)[:300])return response- async def _handle_responses(self, request: "web.Request") -> "web.Response":+ async def _handle_responses(self, request: web.Request) -> web.Response:"""POST /v1/responses — OpenAI Responses API format."""from gateway.platforms.api_server import (ThreadSafeAsyncQueue, _auto_truncate_response_history, _coerce_request_bool,@@ -1213,7 +1213,7 @@ class OpenAICompatRoutesMixin:response_headers["X-Hermes-Session-Key"] = gateway_session_keyreturn web.json_response(response_data, headers=response_headers)- async def _handle_get_response(self, request: "web.Request") -> "web.Response":+ async def _handle_get_response(self, request: web.Request) -> web.Response:"""GET /v1/responses/{response_id} — retrieve a stored response."""from gateway.platforms.api_server import _error_responseauth_err = self._check_auth(request)@@ -1225,7 +1225,7 @@ class OpenAICompatRoutesMixin:return _error_response(f"Response not found: {response_id}", 404)return web.json_response(stored["response"])- async def _handle_delete_response(self, request: "web.Request") -> "web.Response":+ async def _handle_delete_response(self, request: web.Request) -> web.Response:"""DELETE /v1/responses/{response_id} — delete a stored response."""from gateway.platforms.api_server import _error_responseauth_err = self._check_auth(request)diff --git a/gateway/platforms/api_server_room_dispatch.py b/gateway/platforms/api_server_room_dispatch.pyindex 44f6ed940ce..dc4061f5f6f 100644--- a/gateway/platforms/api_server_room_dispatch.py+++ b/gateway/platforms/api_server_room_dispatch.py@@ -48,7 +48,7 @@ async def _ensure_hosted_member_session(self, dispatch: Any) -> str:return await asyncio.to_thread(db._execute_write, atomic)-def _room_dispatch_error(exc: Exception, *, _openai_error) -> "web.Response":+def _room_dispatch_error(exc: Exception, *, _openai_error) -> web.Response:message, code = str(exc), "invalid_room_dispatch"lowered = message.lower()if "execution policy" in lowered or "remote room execution requires" in lowered:@@ -61,7 +61,7 @@ def _room_dispatch_error(exc: Exception, *, _openai_error) -> "web.Response":async def _normalize_room_dispatch(- self, request: "web.Request", body: Any, *, _api_server) -> tuple[Any, "web.Response | None"]:+ self, request: web.Request, body: Any, *, _api_server) -> tuple[Any, web.Response | None]:"""Validate and normalize a scoped RoomLink dispatch request."""_openai_error, room_token = _api_server._openai_error, self._room_grant_token(request)if not room_token:diff --git a/gateway/platforms/api_server_room_grants.py b/gateway/platforms/api_server_room_grants.pyindex 1c2eab3e347..a32500ba6f6 100644--- a/gateway/platforms/api_server_room_grants.py+++ b/gateway/platforms/api_server_room_grants.py@@ -14,7 +14,7 @@ class RoomGrantReauthorizationRequired(ValueError):"""A validly signed room grant was revoked or superseded."""-def _json_error(_openai_error, message: str, *, status: int, **error_kwargs) -> "web.Response":+def _json_error(_openai_error, message: str, *, status: int, **error_kwargs) -> web.Response:"""JSON error response built with the injected ``_openai_error`` envelope builder."""return web.json_response(_openai_error(message, **error_kwargs), status=status)@@ -25,7 +25,7 @@ def _require_unchanged_execution_policy(claims: dict[str, Any], execution_policyraise RoomGrantReauthorizationRequired("room execution policy changed")-def _room_grant_error_response(exc: Optional[Exception] = None, *, _openai_error) -> "web.Response":+def _room_grant_error_response(exc: Optional[Exception] = None, *, _openai_error) -> web.Response:"""401 invalid grant, or 403 reauthorization-required for a revoked/superseded grant."""if isinstance(exc, RoomGrantReauthorizationRequired):message, code, status = "Room authorization needs to be renewed.", "room_reauthorization_required", 403@@ -78,7 +78,7 @@ def _http_routes(self) -> list[tuple[str, str, Any]]:("POST", "/v1/room-members/grants/revoke", self._handle_room_member_grant_revoke)]-def _room_grant_token(request: "web.Request") -> str:+def _room_grant_token(request: web.Request) -> str:scheme, separator, token = str(request.headers.get("Authorization") or "").partition(" ")return token.strip() if separator and scheme.lower() == "hermesroom" else ""@@ -88,7 +88,7 @@ def _room_grant_secret(self) -> bytes:return gateway_room_grant_secret()-def _decode_request_grant(self, request: "web.Request", *, permission: str) -> dict[str, Any]:+def _decode_request_grant(self, request: web.Request, *, permission: str) -> dict[str, Any]:"""Signature/scope/horizon check only (no revocation lookup)."""from gateway.hosted_room_peer import decode_room_granttoken = self._room_grant_token(request)@@ -97,7 +97,7 @@ def _decode_request_grant(self, request: "web.Request", *, permission: str) -> dreturn decode_room_grant(self._room_grant_secret(), token, permission=permission)-def _room_grant_claims(self, request: "web.Request", *, permission: str) -> dict[str, Any]:+def _room_grant_claims(self, request: web.Request, *, permission: str) -> dict[str, Any]:claims = _decode_request_grant(self, request, permission=permission)from gateway import hosted_roomsdb_path = hosted_rooms.default_db_path()@@ -109,7 +109,7 @@ def _room_grant_claims(self, request: "web.Request", *, permission: str) -> dictasync def _handle_room_member_invitation(- self, request: "web.Request", *, _openai_error, _api_request_profile) -> "web.Response":+ self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:"""Mint a short-lived room/profile grant for a trusted home gateway."""auth_err = self._check_auth(request)if auth_err:@@ -153,7 +153,7 @@ async def _handle_room_member_invitation(async def _handle_room_member_capabilities(- self, request: "web.Request", *, _openai_error, _api_request_profile) -> "web.Response":+ self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:"""Verify a scoped grant and return this target's live room catalog."""try:claims = self._room_grant_claims(request, permission="status")@@ -167,7 +167,7 @@ async def _handle_room_member_capabilities(async def _handle_room_member_grant_refresh(- self, request: "web.Request", *, _openai_error, _api_request_profile) -> "web.Response":+ self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:"""Refresh dispatch access without a Desktop or broad gateway key."""body, error = await self._read_json_body(request)if error:@@ -206,7 +206,7 @@ async def _handle_room_member_grant_refresh(async def _handle_room_member_grant_revoke(- self, request: "web.Request", *, _openai_error, _api_request_profile) -> "web.Response":+ self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:"""Revoke exactly the scoped grant authenticating this request."""body, error = await self._read_json_body(request)if error:diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex a3498355274..bfb5b4dbee3 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -157,7 +157,7 @@ class _RunStream:self.subscribers.discard(queue)-def _remember_room_retention(request: "web.Request", claims: dict[str, Any]) -> None:+def _remember_room_retention(request: web.Request, claims: dict[str, Any]) -> None:value = float(claims.get("status_expires_at") or claims.get("expires_at") or 0)try:request[_ROOM_RETENTION_REQUEST_KEY] = value@@ -165,7 +165,7 @@ def _remember_room_retention(request: "web.Request", claims: dict[str, Any]) ->request._hermes_room_run_retention_until = value-def _room_retention_until(request: "web.Request") -> float:+def _room_retention_until(request: web.Request) -> float:try:value = request.get(_ROOM_RETENTION_REQUEST_KEY, 0)except AttributeError:@@ -200,11 +200,11 @@ def terminal_run_status(result: dict[str, Any]) -> tuple[str, dict[str, Any]]:return status, fields-def _run_not_found(_openai_error, run_id: str) -> "web.Response":+def _run_not_found(_openai_error, run_id: str) -> web.Response:return _json_error(_openai_error, f"Run not found: {run_id}", code="run_not_found", status=404)-def _uses_room_run_auth(self, request: "web.Request") -> bool:+def _uses_room_run_auth(self, request: web.Request) -> bool:return request.path.endswith("/v1/runs") and bool(self._room_grant_token(request))@@ -312,7 +312,7 @@ def _mark_shutdown_requested(self) -> int:return marked-def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoop", *, _api_server):+def _make_run_event_callback(self, run_id: str, loop: asyncio.AbstractEventLoop, *, _api_server):"""Return a callback that pushes structured events to the run SSE queue."""redact_sensitive_text = _api_server.redact_sensitive_text@@ -349,7 +349,7 @@ def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoopreturn _callback-def _room_permission_for(request: "web.Request") -> str:+def _room_permission_for(request: web.Request) -> str:if request.path.endswith("/stop"):return "stop"if request.path.endswith("/approval"):@@ -357,7 +357,7 @@ def _room_permission_for(request: "web.Request") -> str:return "status" if request.method == "GET" else "dispatch"-def _run_idempotency_scope(self, request: "web.Request", *, _api_server) -> str:+def _run_idempotency_scope(self, request: web.Request, *, _api_server) -> str:"""Opaque auth/profile namespace; never persist bearer credentials."""if self._room_grant_token(request):claims = self._room_grant_claims(request, permission=_room_permission_for(request))@@ -371,7 +371,7 @@ def _run_idempotency_scope(self, request: "web.Request", *, _api_server) -> str:return hashlib.sha256("\0".join(map(str, parts)).encode()).hexdigest()-def _check_run_auth(self, request: "web.Request", *, permission: str, _api_server) -> "web.Response | None":+def _check_run_auth(self, request: web.Request, *, permission: str, _api_server) -> web.Response | None:if not self._room_grant_token(request):return self._check_auth(request)try:@@ -392,7 +392,7 @@ def _owner_alive(owner_pid: int, owner_started: int) -> bool:return False-def _durable_run_status(self, request: "web.Request", run_id: str) -> dict[str, Any] | None:+def _durable_run_status(self, request: web.Request, run_id: str) -> dict[str, Any] | None:"""Hydrate a scoped run status and fail stale owners closed."""status = self._run_statuses.get(run_id)if status is not None:@@ -420,7 +420,7 @@ def _durable_run_status(self, request: "web.Request", run_id: str) -> dict[str,def _resolve_conversation_history(self, body: dict, raw_input: Any, *, _openai_error-) -> "tuple[list[dict[str, str]], Any, Any, web.Response | None]":+) -> tuple[list[dict[str, str]], Any, Any, web.Response | None]:"""Return ``(history, instructions, stored_session_id, error)``; precedence:``conversation_history`` > ``previous_response_id`` chain > all-but-last ``input`` messages."""instructions = body.get("instructions")@@ -458,7 +458,7 @@ def _resolve_conversation_history(return conversation_history, instructions, stored_session_id, None-def _accepted_response(run_id: str, status: str, gateway_session_key, *, replayed: bool) -> "web.Response":+def _accepted_response(run_id: str, status: str, gateway_session_key, *, replayed: bool) -> web.Response:"""202 admission response; replays are flagged via ``Idempotency-Replayed``."""headers = {"Idempotency-Replayed": "true"} if replayed else {}if gateway_session_key:@@ -467,7 +467,7 @@ def _accepted_response(run_id: str, status: str, gateway_session_key, *, replaye{"run_id": run_id, "status": status, "replayed": replayed}, status=202, headers=headers)-def _replay_or_conflict(self, request, outcome, record, gateway_session_key, _openai_error) -> "web.Response":+def _replay_or_conflict(self, request, outcome, record, gateway_session_key, _openai_error) -> web.Response:"""409 for a fingerprint conflict, else a 202 replay of the already-admitted run."""if outcome == "conflict":return _json_error(@@ -617,7 +617,7 @@ async def run_internal_session_turn(self, *, session_id: str, text: str, profile_api_server._api_request_profile.reset(token)-async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Response":+async def _handle_runs(self, request: web.Request, *, _api_server) -> web.Response:"""POST /v1/runs — start an agent run, return run_id immediately."""_openai_error = _api_server._openai_error# Long-term memory scope header (see chat_completions for details).@@ -1020,7 +1020,7 @@ def _release_run_owner_if_forgotten(self, run_id: str) -> None:self._run_owners.pop(run_id, None)-def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:+def _request_owns_run(self, request: web.Request, run_id: str) -> bool:scope = self._run_idempotency_scope(request)owner = self._run_owners.get(run_id)if owner is not None:@@ -1054,14 +1054,14 @@ def _load_owned_run(self, request, *, _api_server, permission: Optional[str], acreturn run_id, status, agent, task, None-async def _handle_get_run(self, request: "web.Request", *, _api_server) -> "web.Response":+async def _handle_get_run(self, request: web.Request, *, _api_server) -> web.Response:"""GET /v1/runs/{run_id} — return pollable run status for external UIs."""_, status, _, _, err = _load_owned_run(self, request, _api_server=_api_server, permission="status", active_fallback=True)return err or web.json_response(status)-async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "web.StreamResponse":+async def _handle_run_events(self, request: web.Request, *, _api_server) -> web.StreamResponse:"""GET /v1/runs/{run_id}/events — stream structured agent lifecycle events."""auth_err = self._check_auth(request)if auth_err:@@ -1165,7 +1165,7 @@ def _mark_run_event(self, run_id: str, name: str, **fields: Any) -> None:_APPROVAL_CHOICE_ALIASES = {"approve": "once", "approved": "once", "allow": "once"}-async def _handle_run_approval(self, request: "web.Request", *, _api_server) -> "web.Response":+async def _handle_run_approval(self, request: web.Request, *, _api_server) -> web.Response:"""POST /v1/runs/{run_id}/approval — resolve a pending run approval."""_openai_error = _api_server._openai_errorrun_id, _, _, _, err = _load_owned_run(@@ -1216,7 +1216,7 @@ async def _handle_run_approval(self, request: "web.Request", *, _api_server) ->"resolved": resolved})-async def _handle_steer_run(self, request: "web.Request", *, _api_server) -> "web.Response":+async def _handle_steer_run(self, request: web.Request, *, _api_server) -> web.Response:"""POST /v1/runs/{run_id}/steer — inject guidance into a running agent."""_openai_error = _api_server._openai_errorrun_id, status, agent, _, err = _load_owned_run(@@ -1250,7 +1250,7 @@ async def _handle_steer_run(self, request: "web.Request", *, _api_server) -> "wereturn web.json_response({"object": "hermes.run.steer", "run_id": run_id, "accepted": True})-async def _handle_stop_run(self, request: "web.Request", *, _api_server) -> "web.Response":+async def _handle_stop_run(self, request: web.Request, *, _api_server) -> web.Response:"""POST /v1/runs/{run_id}/stop — interrupt a running agent."""_openai_error = _api_server._openai_errorrun_id, status, agent, task, err = _load_owned_run(diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 770f96267e8..0257a9b5d46 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -28,7 +28,7 @@ from agent.proxy_bypass import first_proxy_env_value, should_bypass_proxy as _shlogger = logging.getLogger(__name__)-def _consume_detached_handler_exception(task: "asyncio.Task") -> None:+def _consume_detached_handler_exception(task: asyncio.Task) -> None:"""Done-callback for a detached fatal-error handler task (carrier cancelled in``_notify_fatal_error``): retrieve its exception so asyncio never logs "never retrieved"."""if task.cancelled():@@ -53,7 +53,7 @@ _TELEGRAM_VOICE_EXTS = frozenset({'.ogg', '.opus'})def transcode_to_ogg_opus(path: str, *, bitrate: str = "32k", timeout: int = 60,- output_path: "str | None" = None) -> "str | None":+ output_path: str | None = None) -> str | None:"""Best-effort ffmpeg transcode to Ogg/Opus (voip-tuned) for native voice bubbles: the written``.ogg`` path (a NEW temp file unless ``output_path`` is given; caller cleans up), or None whenffmpeg is missing/fails. ``output_path`` may equal ``path`` (in-place container repair) — the@@ -182,7 +182,7 @@ def _reply_anchor_for_event(event) -> str | None:_MEDIA_KIND_KEYS = frozenset({"audio", "video", "file", "image"})-def _media_failure_text(kind: str, file_name: "str | None" = None) -> str:+def _media_failure_text(kind: str, file_name: str | None = None) -> str:"""User-facing "couldn't deliver" notice; ``file_name`` is the only name ever shown."""kind_label = t(f"gateway.notify.media_kind.{kind}") if kind in _MEDIA_KIND_KEYS else kindif file_name:@@ -273,7 +273,7 @@ def is_network_accessible(host: str) -> bool:# goes out on a stale answer fails and is retried, which is the same outcome as any transient proxy error.# No lock: a race costs one extra fork and both answers are equally current._MACOS_PROXY_TTL_SECONDS = 60.0-_macos_proxy_cache: "tuple[float, str | None] | None" = None+_macos_proxy_cache: tuple[float, str | None] | None = Nonedef _detect_macos_system_proxy() -> str | None:@@ -1362,7 +1362,7 @@ MEDIA_EXTENSIONLESS_TAG_RE = re.compile(re.IGNORECASE)-def _match_extensionless_path(scan_text: str, match: "re.Match") -> Optional[tuple[str, int]]:+def _match_extensionless_path(scan_text: str, match: re.Match) -> Optional[tuple[str, int]]:"""Extensionless MEDIA tag match -> validated on-disk ``(safe_path, end_offset)`` or None: thecaptured path first, then extended across single spaces (max 8 tokens, never past a newlineor the next ``MEDIA:``).@@ -1634,7 +1634,7 @@ class TextDebounceState:first_ts: floatlast_ts: float- def cancel_timer(self, *, unless: "asyncio.Task | None" = None) -> None:+ def cancel_timer(self, *, unless: asyncio.Task | None = None) -> None:"""Cancel the pending flush timer (if live and not ``unless``)."""if self.task is not None and self.task is not unless and not self.task.done():self.task.cancel()@@ -1662,7 +1662,7 @@ _PLAINTEXT_GATEWAY_RESTART_PATTERNS: tuple[re.Pattern[str], ...] = (re.compile(r"^(?:please\s+)?restart\s+hermes[.!?\s]*$", re.IGNORECASE))-def coerce_plaintext_gateway_command(event: "MessageEvent") -> None:+def coerce_plaintext_gateway_command(event: MessageEvent) -> None:"""Rewrite a tiny set of DM plaintext admin phrases (exact matches only) into slash commands so``restart gateway`` never reaches the LLM/tool path (a self-restart from inside the runningagent leaves the gateway stuck in ``draining`` waiting on that agent)."""@@ -1976,7 +1976,7 @@ class BasePlatformAdapter(ABC):self._running, self._fatal_error_retryable = False, Trueself._fatal_error_code: Optional[str] = Noneself._fatal_error_message: Optional[str] = None- self._fatal_error_handler: Optional[Callable[["BasePlatformAdapter"], Awaitable[None] | None]] = None+ self._fatal_error_handler: Optional[Callable[[BasePlatformAdapter], Awaitable[None] | None]] = None# Strong refs to shielded fatal-error handler tasks that outlive their carrier task# (asyncio keeps only weak refs); without them the loop can GC the detached handler# mid-flight — the "handler killed mid-flight" class (#81335).@@ -2135,7 +2135,7 @@ class BasePlatformAdapter(ABC):return t("gateway.progress.tool_preview", emoji=emoji, tool=tool, preview=self.format_tool_preview(prepared))- def format_tool_preview(self, preview: "ToolPreview") -> str:+ def format_tool_preview(self, preview: ToolPreview) -> str:"""Platform-native formatting of a compact tool preview; rich-text adapters may usethe preview's metadata (e.g. a URL shortened for display)."""return preview.text@@ -2155,7 +2155,7 @@ class BasePlatformAdapter(ABC):return chat_id in self._auto_tts_enabled_chats or (chat_id not in self._auto_tts_disabled_chats and bool(self._auto_tts_default))- def set_fatal_error_handler(self, handler: Callable[["BasePlatformAdapter"], Awaitable[None] | None]) -> None:+ def set_fatal_error_handler(self, handler: Callable[[BasePlatformAdapter], Awaitable[None] | None]) -> None:self._fatal_error_handler = handler#: Published when an adapter is installed and running but its receive@@ -2451,7 +2451,7 @@ class BasePlatformAdapter(ABC):owner = getattr(self, "_owner_profile", None)return owner if isinstance(owner, str) and owner.strip() else None- def _canonicalize(self, source: Optional["SessionSource"]):+ def _canonicalize(self, source: Optional[SessionSource]):"""Pin the source's :class:`RoutingIdentity` before anything derives a key from it. Everyingress path (fresh event, batch merge, busy path, control command, callback) calls thisFIRST. Returns the identity, or ``None`` when it cannot be resolved (a rejected route under@@ -2475,7 +2475,7 @@ class BasePlatformAdapter(ABC):logger.debug("[%s] identity resolution failed; using legacy key readers", self.name, exc_info=True)return None- def _drop_unresolved(self, event: "MessageEvent") -> bool:+ def _drop_unresolved(self, event: MessageEvent) -> bool:"""True when *event* must be dropped: its identity could not be resolved because the routetargets an unserved profile. Same disposition as the runner's ingress gate — one WARNING,never a fall-through to ``agent:main``."""@@ -2554,11 +2554,11 @@ class BasePlatformAdapter(ABC):"text_batch_split_delay_seconds", self._TEXT_BATCH_DEFAULT_SPLIT_DELAY_S,min_value=self._text_batch_delay_seconds, max_value=self._TEXT_BATCH_MAX_SPLIT_DELAY_S)- def _event_session_key(self, event: "MessageEvent") -> str:+ def _event_session_key(self, event: MessageEvent) -> str:"""Adapter-level session key for ``event``, profile-namespaced like the agent run."""return self._source_session_key(event.source)- def _source_session_key(self, source: "SessionSource") -> str:+ def _source_session_key(self, source: SessionSource) -> str:self._canonicalize(source) # identity FIRST; no key derivation before itextra = self.config.extrareturn build_session_key(@@ -2566,11 +2566,11 @@ class BasePlatformAdapter(ABC):thread_sessions_per_user=extra.get("thread_sessions_per_user", False),profile=self._session_key_profile(source))- def _text_batch_key(self, event: "MessageEvent") -> str:+ def _text_batch_key(self, event: MessageEvent) -> str:"""Session-scoped key for text batching (subclasses may override)."""return self._event_session_key(event)- def _enqueue_text_event(self, event: "MessageEvent") -> None:+ def _enqueue_text_event(self, event: MessageEvent) -> None:"""Buffer a text event (merging into a pending one) and restart the flush timer."""if self._drop_unresolved(event):return@@ -2591,16 +2591,16 @@ class BasePlatformAdapter(ABC):prior_task.cancel()self._pending_text_batch_tasks[key] = asyncio.create_task(self._flush_text_batch(key))- def _text_batch_delay_for(self, pending: Optional["MessageEvent"]) -> float:+ def _text_batch_delay_for(self, pending: Optional[MessageEvent]) -> float:"""Quiet period before ``pending`` is dispatched; near-split chunks wait longer."""last_len = getattr(pending, "_last_chunk_len", 0) if pending is not None else 0return self._text_batch_split_delay_seconds if last_len >= self._SPLIT_THRESHOLD else self._text_batch_delay_seconds- def _pop_text_batch(self, key: str) -> Optional["MessageEvent"]:+ def _pop_text_batch(self, key: str) -> Optional[MessageEvent]:"""Remove and return the pending batch for ``key`` (adapters with side tables override)."""return self._pending_text_batches.pop(key, None)- async def _dispatch_text_batch(self, event: "MessageEvent") -> None:+ async def _dispatch_text_batch(self, event: MessageEvent) -> None:"""Hand a flushed batch to the pipeline (adapters with per-chat guards override)."""await self.handle_message(event)@@ -2909,12 +2909,12 @@ class BasePlatformAdapter(ABC):allow_permanent=allow_permanent, allow_session=allow_session, smart_denied=smart_denied))return await self._send_exec_approval_prompt(prompt)- async def _send_exec_approval_prompt(self, prompt: "ExecApprovalPrompt") -> SendResult:+ async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:"""Render ``prompt`` with the platform's native buttons; the default has none."""return SendResult(success=False, error="Not supported")@staticmethod- def _format_choice_page(options: list, page: int, per_page: int) -> "tuple[list, dict[str, Any]]":+ def _format_choice_page(options: list, page: int, per_page: int) -> tuple[list, dict[str, Any]]:"""Shared picker pagination: clamp ``page``, slice ``options`` -> ``(page_options, meta)``with ``page``/``total_pages``/``start``/``end``/``total``/``page_info`` (`` (N–M of T)``,empty for one page)."""@@ -3628,7 +3628,7 @@ class BasePlatformAdapter(ABC):logger.debug("[%s] Failed to resolve media delivery scope", self.name, exc_info=True)return contextlib.nullcontext()- def _final_delivery_adapter(self, source: Optional[SessionSource]) -> "BasePlatformAdapter":+ def _final_delivery_adapter(self, source: Optional[SessionSource]) -> BasePlatformAdapter:"""The runner's CURRENT adapter for a new final-response send: a reconnect can swap theregistry adapter mid-task; an unsent final response belongs on the replacement transport,while message IDs, edits and deletes stay owned by the old one (nothing is migrated)."""@@ -3647,13 +3647,13 @@ class BasePlatformAdapter(ABC):@records_deliveryasync def _send_with_retry(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Any = None,- max_retries: int = 2, base_delay: float = 2.0) -> "SendResult":+ max_retries: int = 2, base_delay: float = 2.0) -> SendResult:"""Send with exponential-backoff retry on transient network errors; permanentfailures fall back to a plain-text send, exhausted retries notify the user."""- async def _send(text: str) -> "SendResult":+ async def _send(text: str) -> SendResult:return await self.send(chat_id=chat_id, content=text, reply_to=reply_to, metadata=metadata)- async def _send_again(previous: "SendResult") -> "Optional[SendResult]":+ async def _send_again(previous: SendResult) -> Optional[SendResult]:"""Retry: the whole payload normally; only the undelivered remainder after a partial splitdelivery (``raw_response["partial_overflow"]``). ``None`` when the adapter cannot resume — thecaller then keeps the partial failure rather than re-sending the already-visible head."""@@ -3767,13 +3767,13 @@ class BasePlatformAdapter(ABC):logger.error("[%s] Fallback send also failed: %s", self.name, fallback_result.error)return fallback_result- def _send_retry_is_final(self, result: "SendResult") -> bool:+ def _send_retry_is_final(self, result: SendResult) -> bool:"""True when a failed send must be returned as-is: neither a retry nor the plain-textfallback can fix it (a structured auth/target refusal). Default: never."""return False@staticmethod- def _is_partial_delivery(result: "SendResult") -> bool:+ def _is_partial_delivery(result: SendResult) -> bool:"""True when a split payload was PARTLY delivered (``raw_response["partial_overflow"]``, thecontract Telegram's send/edit-overflow paths set and the stream consumer reads): the visiblehead must never be sent again."""@@ -3781,14 +3781,14 @@ class BasePlatformAdapter(ABC):return isinstance(raw, dict) and bool(raw.get("partial_overflow"))async def _resume_partial_send(- self, chat_id: str, result: "SendResult", *, reply_to: Optional[str], metadata: Any) -> "Optional[SendResult]":+ self, chat_id: str, result: SendResult, *, reply_to: Optional[str], metadata: Any) -> Optional[SendResult]:"""Deliver only the remainder of a partially delivered split payload. ``None`` (the default) meansthis adapter cannot resume; ``_send_with_retry`` then returns the partial failure instead ofre-sending the whole payload. Override only where non-delivery of the remainder is CERTAIN."""return Noneasync def _send_plain_fallback(- self, chat_id: str, content: str, *, reply_to: Optional[str], metadata: Any) -> "SendResult":+ self, chat_id: str, content: str, *, reply_to: Optional[str], metadata: Any) -> SendResult:"""Last-resort send after a non-transient failure; platforms whose markup is not thelikely culprit override it (Photon drops rich links instead of adding the banner)."""return await self.send(@@ -4244,7 +4244,7 @@ class BasePlatformAdapter(ABC):async def _record_delivery_obligation(self, event: MessageEvent, session_key: str, text_content: str,- delivery_adapter: "BasePlatformAdapter", is_ephemeral_response: bool) -> Optional[str]:+ delivery_adapter: BasePlatformAdapter, is_ephemeral_response: bool) -> Optional[str]:"""Ledger the final response BEFORE the send so a crash before platform ACK redelivers onnext boot; best-effort, skips slash-command and ephemeral replies. Returns the obligation idor None."""@@ -4278,7 +4278,7 @@ class BasePlatformAdapter(ABC):async def _finalize_delivery_obligation(self, obligation_id: str, result: Any, event: MessageEvent,- delivery_adapter: "BasePlatformAdapter") -> None:+ delivery_adapter: BasePlatformAdapter) -> None:"""Mark the ledger row delivered/failed (best-effort). On ``send_path_degraded`` with areplacement adapter live, trigger another redelivery sweep (the watcher's may have runbefore this failure landed; atomic claiming keeps it idempotent). On any other rejection arm@@ -4378,7 +4378,7 @@ class BasePlatformAdapter(ABC):async def send_final_ledgered(self, event: MessageEvent, session_key: str, text_content: str, metadata: dict[str, Any], *,reply_to: Optional[str], is_ephemeral_response: bool = False,- ) -> "tuple[SendResult, BasePlatformAdapter]":+ ) -> tuple[SendResult, BasePlatformAdapter]:"""The delivery-ledger bracket every final text goes through, on the CURRENT transport(a reconnect may have replaced this adapter): record the obligation before the send,send with retry, finalize from the result — so a refused final (flood control, a dead@@ -4440,7 +4440,7 @@ class BasePlatformAdapter(ABC):"[%s] Failed to send error notification to user: %s", self.name, notify_err, exc_info=True)return _thread_metadata- async def _deliver_attachments(self, event: MessageEvent, extracted: "_ExtractedResponse",+ async def _deliver_attachments(self, event: MessageEvent, extracted: _ExtractedResponse,metadata: dict[str, Any], *, anything_sent: bool,record_delivery: Callable) -> None:"""Send extracted image URLs, MEDIA files and bare local files (human-paced),@@ -4474,7 +4474,7 @@ class BasePlatformAdapter(ABC):return asyncio.create_task(self._keep_typing(event.source.chat_id, **kwargs))async def _extract_response_content(self, response: str, event: MessageEvent, session_key: str,- *, is_ephemeral_response: bool) -> "_ExtractedResponse":+ *, is_ephemeral_response: bool) -> _ExtractedResponse:"""Split a handler response into deliverable text + attachments. Order matters: MEDIA tags →image URLs → residual directives → bare local paths (skipped for ephemeral notices so configpaths stay text; unknown-extension MEDIA tags survive for the bare-path detector). History@@ -4859,7 +4859,7 @@ class BasePlatformAdapter(ABC):"""Get information about a chat/channel; dict with at least ``name``and ``type`` ("dm", "group", "channel")."""- def toolsets_for_source(self, source: "SessionSource") -> Optional[list[str]]:+ def toolsets_for_source(self, source: SessionSource) -> Optional[list[str]]:"""Per-source toolset override REPLACING ``platform_toolsets.<platform>``, or None(default); validated via ``_get_platform_tools`` (webhook adapter pins per-route)."""return None@@ -4871,7 +4871,7 @@ class BasePlatformAdapter(ABC):@staticmethoddef truncate_message(content: str, max_length: int = 4096,- len_fn: Optional["Callable[[str], int]"] = None) -> list[str]:+ len_fn: Optional[Callable[[str], int]] = None) -> list[str]:"""Split a long message into chunks preserving code blocks: a split inside a fence closes itat the chunk end and reopens it (same language tag) in the next; multi-chunk output gets``(1/3)`` indicators. ``len_fn`` overrides ``len`` (``utf16_len`` for Telegram)."""diff --git a/gateway/platforms/event.py b/gateway/platforms/event.pyindex 54ecff5519e..2ddd39b1bdb 100644--- a/gateway/platforms/event.py+++ b/gateway/platforms/event.py@@ -107,7 +107,7 @@ class MessageEvent:# Run-owned final presentation snapshot; never deserialized from ingress metadata._notification_reply_muted: Optional[bool] = field(default=None, init=False, repr=False, compare=False)- def absorb_reply_expected(self, other: "MessageEvent") -> None:+ def absorb_reply_expected(self, other: MessageEvent) -> None:"""One turn now answers *other* too: an addressed message wins, then an unknown one."""if self.reply_expected is not True and other.reply_expected is not False:self.reply_expected = other.reply_expecteddiff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.pyindex 8a2a8245185..1e27210786e 100644--- a/gateway/platforms/helpers.py+++ b/gateway/platforms/helpers.py@@ -60,7 +60,7 @@ class MessageDeduplicator:def clear(self):self._seen.clear()- def absorb(self, other: "MessageDeduplicator") -> None:+ def absorb(self, other: MessageDeduplicator) -> None:"""Adopt *other*'s still-live IDs (at their original seen times) into this cache."""cutoff = time.time() - self._ttlself._seen.update({k: v for k, v in other._seen.items() if v > cutoff and k not in self._seen})@@ -135,7 +135,7 @@ _HTTP_TARGET_RE = re.compile(r"https?://", re.IGNORECASE)_NEWLINE_SQUEEZE_RE = re.compile(r"\n{3,}")-def _keep_link_target(match: "re.Match[str]") -> str:+def _keep_link_target(match: re.Match[str]) -> str:r"""``[label](https://url)`` -> ``label\nurl``.The bare URL is the only thing a platform with its own data detection@@ -345,8 +345,8 @@ def convert_table_to_bullets(text: str) -> str:def compile_mention_patterns(raw, *, log_prefix: str, platform_label: str | None = None,- display_label: str | None = None, defaults: 'list[str] | None' = None,- logger_: 'logging.Logger | None' = None) -> 'list[re.Pattern]':+ display_label: str | None = None, defaults: list[str] | None = None,+ logger_: logging.Logger | None = None) -> list[re.Pattern]:"""Compile regex wake-word/mention patterns from config or env values.* **Config-style** (dingtalk, telegram): pass ``platform_label``. ``raw`` must be a@@ -459,11 +459,11 @@ def split_at_paragraph_boundary(text, max_chars, len_fn=None):return text[:cut], text[cut:]-def split_markdown_atoms(text: str) -> "list[str]":+def split_markdown_atoms(text: str) -> list[str]:"""Split markdown into indivisible atoms: fenced code blocks, tables(consecutive ``|...|`` lines) and paragraphs. Blank lines belong to no atom."""- atoms: "list[str]" = []- current_lines: "list[str]" = []+ atoms: list[str] = []+ current_lines: list[str] = []in_fence = Falsedef _flush_current() -> None:@@ -505,10 +505,10 @@ def infer_block_separator(prev_chunk: str, next_chunk: str) -> str:return '\n\n'-def merge_streaming_fences(chunks: "list[str]") -> "list[str]":+def merge_streaming_fences(chunks: list[str]) -> list[str]:"""Rejoin chunks truncated mid-fence: while chunk *i* has an unclosed fenceand a successor exists, merge the successor in via :func:`infer_block_separator`."""- result: "list[str]" = []+ result: list[str] = []i = 0while i < len(chunks):current = chunks[i]@@ -520,12 +520,12 @@ def merge_streaming_fences(chunks: "list[str]") -> "list[str]":return result-def balance_fences_across_chunks(chunks: "list[str]") -> "list[str]":+def balance_fences_across_chunks(chunks: list[str]) -> list[str]:"""Close orphaned ``` fences at each chunk boundary and reopen (with theoriginal language tag) on the next, so every chunk is fence-balanced alone."""if len(chunks) <= 1:return chunks- out: "list[str]" = []+ out: list[str] = []carry_lang = Nonefor chunk in chunks:body = f"```{carry_lang}\n{chunk}" if carry_lang is not None else chunk@@ -535,7 +535,7 @@ def balance_fences_across_chunks(chunks: "list[str]") -> "list[str]":return out-def fence_state_after(text: str, in_code: bool = False, lang: str = "") -> "tuple[bool, str]":+def fence_state_after(text: str, in_code: bool = False, lang: str = "") -> tuple[bool, str]:"""Walk ``text`` line by line toggling on ``` lines; return the final (in_code, lang)."""for line in text.split("\n"):stripped = line.strip()@@ -549,7 +549,7 @@ def greedy_pack_blocks(blocks, max_length, len_fn=None, sep="\n\n", overflow=Non"""Greedily pack *blocks* (joined with *sep*) into chunks of at most *max_length*; anoversized block goes through *overflow(block)* (-> list of chunks) if given, else as-is."""_len = len_fn or len- packed: "list[str]" = []+ packed: list[str] = []current = ""for block in blocks:candidate = block if not current else f"{current}{sep}{block}"@@ -596,9 +596,9 @@ def _chunk_markdown_paragraphs(text, max_chars, len_fn=None):if _len(text) <= max_chars:return [text]# Phase 2: greedy merge; oversized fence/table atoms stay indivisible.- chunks: "list[str]" = []- indivisible_set: "set[int]" = set()- current_parts: "list[str]" = []+ chunks: list[str] = []+ indivisible_set: set[int] = set()+ current_parts: list[str] = []current_len = 0for atom in split_markdown_atoms(text):atom_len = _len(atom)@@ -616,7 +616,7 @@ def _chunk_markdown_paragraphs(text, max_chars, len_fn=None):if current_parts:chunks.append('\n\n'.join(current_parts))# Phase 3: split still-oversized divisible chunks at paragraph boundaries.- result: "list[str]" = []+ result: list[str] = []for idx, chunk in enumerate(chunks):if _len(chunk) <= max_chars or idx in indivisible_set or text_has_unclosed_fence(chunk):result.append(chunk)@@ -631,7 +631,7 @@ def _chunk_markdown_paragraphs(text, max_chars, len_fn=None):if remaining:result.append(remaining)# Phase 4: merge small chunks with neighbours.- merged: "list[str]" = result[:1]+ merged: list[str] = result[:1]for chunk in result[1:]:combined = merged[-1] + '\n\n' + chunkif _len(combined) <= max_chars:@@ -647,7 +647,7 @@ def _chunk_newline_preferred(text, limit, len_fn):return [text]# Reserve headroom for fence markers a balancing pass may add.split_limit = max(limit - 16, limit // 2, 1) if "```" in text else limit- chunks: "list[str]" = []+ chunks: list[str] = []remaining = textwhile len_fn(remaining) > split_limit:budget = _cp_budget(remaining, split_limit, len_fn)diff --git a/gateway/platforms/msgraph_webhook.py b/gateway/platforms/msgraph_webhook.pyindex a10d32139d7..540a8a26fe7 100644--- a/gateway/platforms/msgraph_webhook.py+++ b/gateway/platforms/msgraph_webhook.py@@ -167,14 +167,14 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):async def get_chat_info(self, chat_id: str) -> dict[str, Any]:return {"name": chat_id, "type": "webhook"}- async def _handle_health(self, request: "web.Request") -> "web.Response":+ async def _handle_health(self, request: web.Request) -> web.Response:if not self._source_ip_allowed(request):return web.Response(status=403)return web.json_response({"status": "ok", "platform": self.platform.value, "webhook_path": self._webhook_path,"accepted": self._accepted_count, "duplicates": self._duplicate_count})- async def _handle_validation(self, request: "web.Request") -> "web.Response":+ async def _handle_validation(self, request: web.Request) -> web.Response:"""Graph subscription validation handshake: echo ``validationToken`` verbatim as text/plain. Bare GETsare rejected so the endpoint can't be enumerated."""if not self._source_ip_allowed(request):@@ -203,7 +203,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):self._schedule_notification(notification, self._build_message_event(notification, receipt_key))return "accepted"- async def _handle_notification(self, request: "web.Request") -> "web.Response":+ async def _handle_notification(self, request: web.Request) -> web.Response:if not self._source_ip_allowed(request):return web.Response(status=403)# Graph never sends validationToken on POST, but tolerate clients replaying it in-band.@@ -224,7 +224,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):return web.Response(status=403)return web.Response(status=400)- async def _read_notifications(self, request: "web.Request") -> tuple[int, list]:+ async def _read_notifications(self, request: web.Request) -> tuple[int, list]:"""Read and validate the POST body; returns (error_status, []) or (0, notifications)."""try:content_length = request.content_length@@ -245,7 +245,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):notifications = body.get("value") if isinstance(body, dict) else Nonereturn (0, notifications) if isinstance(notifications, list) else (400, [])- def _source_ip_allowed(self, request: "web.Request") -> bool:+ def _source_ip_allowed(self, request: web.Request) -> bool:"""Loopback-only binds may omit ``allowed_source_cidrs`` (local proxies, dev tunnels);network-accessible binds fail closed without one."""if self._source_allowlist_required_but_missing():diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.pyindex 0c5b74542c9..ab4093d93a3 100644--- a/gateway/platforms/qqbot/adapter.py+++ b/gateway/platforms/qqbot/adapter.py@@ -1285,7 +1285,7 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):# ── Outbound messaging — REST API ──- def _require_http_client(self) -> "httpx.AsyncClient":+ def _require_http_client(self) -> httpx.AsyncClient:if not self._http_client:raise RuntimeError("HTTP client not initialized — not connected?")return self._http_clientdiff --git a/gateway/platforms/shared_ingress.py b/gateway/platforms/shared_ingress.pyindex 8018ce1290f..5c883734d06 100644--- a/gateway/platforms/shared_ingress.py+++ b/gateway/platforms/shared_ingress.py@@ -55,9 +55,9 @@ def shared_listener_base(runner: Any) -> Optional[str]:async def bind_listener(- adapter: Any, app: "web.Application", host: Optional[str], port: int, ingress_path: str, *,+ adapter: Any, app: web.Application, host: Optional[str], port: int, ingress_path: str, *,reuse_address: Optional[bool] = None, access_log: Any = ...,-) -> Optional["web.AppRunner"]:+) -> Optional[web.AppRunner]:"""Start *app* on ``host:port`` and return its ``AppRunner`` — or, in shared-listener mode,publish *app* for ``/p/<profile>/`` forwarding and return None (nothing bound). ``ingress_path``is the adapter's primary callback path, used for the log line and runtime status."""@@ -77,7 +77,7 @@ async def bind_listener(return runner-def publish_shared_ingress(adapter: Any, app: "web.Application", ingress_path: str) -> None:+def publish_shared_ingress(adapter: Any, app: web.Application, ingress_path: str) -> None:"""Freeze *app* and expose it to the default listener; records the ``/p/<profile>/`` URL."""profile = shared_ingress_profile(adapter)app.freeze()@@ -104,7 +104,7 @@ def publish_shared_ingress(adapter: Any, app: "web.Application", ingress_path: swrite("shared_ingress", ingress_url=adapter._shared_ingress_url)-def shared_ingress_apps(runner: Any, profile: Optional[str]) -> list[tuple[Any, "web.Application"]]:+def shared_ingress_apps(runner: Any, profile: Optional[str]) -> list[tuple[Any, web.Application]]:"""``(adapter, app)`` for every shared-listener adapter of a NAMED served profile. ``default`` andunknown profiles yield nothing: the default's port-binders own their own ports, and a profilewithout a live adapter must never fall back to another profile's."""@@ -118,8 +118,8 @@ def shared_ingress_apps(runner: Any, profile: Optional[str]) -> list[tuple[Any,async def dispatch_profile_ingress(- runner: Any, profile: Optional[str], tail: str, request: "web.Request", *, scoped: bool = False,-) -> "web.StreamResponse":+ runner: Any, profile: Optional[str], tail: str, request: web.Request, *, scoped: bool = False,+) -> web.StreamResponse:"""Forward ``/p/<profile>/<tail>`` to the served profile's adapter app that routes ``/<tail>``,under that profile's runtime scope (``scoped=True`` when the caller already entered it). 404 whenno adapter of *profile* serves the path."""diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.pyindex c1d7f0f6718..2430ae2814d 100644--- a/gateway/platforms/signal.py+++ b/gateway/platforms/signal.py@@ -209,12 +209,12 @@ class SignalAdapter(BasePlatformAdapter):self._account_normalized = self.account.strip()# Recently sent timestamps filter echo-backs (Note to Self / linked-device sync-sents); LRU + TTL# so a pending echo in a chatty group isn't evicted by many outbounds.- self._recent_sent_timestamps: "OrderedDict[int, float]" = OrderedDict()+ self._recent_sent_timestamps: OrderedDict[int, float] = OrderedDict()self._max_recent_timestamps = 512self._recent_sent_ttl_seconds = 300.0# Separate FIFO of outbound timestamps: Signal quote.id is the quoted message's timestamp, so# replies to this bot are recognised after the echo was consumed.- self._sent_message_timestamps: "OrderedDict[str, None]" = OrderedDict()+ self._sent_message_timestamps: OrderedDict[str, None] = OrderedDict()self._max_sent_message_timestamps = 500# Best-effort number↔ACI/PNI UUID mapping so sends can upgrade a number to the UUID signal-cli prefers.self._recipient_uuid_by_number: dict[str, str] = {}@@ -950,7 +950,7 @@ class SignalAdapter(BasePlatformAdapter):ok = isinstance(raw, dict) and raw.get("sender") and raw.get("timestamp_ms")return (raw["sender"], raw["timestamp_ms"]) if ok else None- def _reactions_enabled(self, event: "MessageEvent" = None) -> bool:+ def _reactions_enabled(self, event: MessageEvent = None) -> bool:"""SIGNAL_REACTIONS env gate, then the DM allowlist: reactions fire before run.py's auth gate,so an unauthorized contact's 👀 would otherwise reveal a listening bot."""if str(_sig_secret("SIGNAL_REACTIONS", "true")).lower() in {"false", "0", "no"}:@@ -963,7 +963,7 @@ class SignalAdapter(BasePlatformAdapter):if self._reactions_enabled(event) and (target := self._extract_reaction_target(event)):await self.send_reaction(event.source.chat_id, "👀", *target)- async def on_processing_complete(self, event: MessageEvent, outcome: "ProcessingOutcome") -> None:+ async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None:"""Swap 👀 for ✅/❌; on CANCELLED the 👀 stays to keep reflecting "in progress" (matches Telegram)."""if outcome == ProcessingOutcome.CANCELLED or not self._reactions_enabled(event):returndiff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex 934bb2f0dbc..786aa499756 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -80,7 +80,7 @@ class _WebhookDeliveryIdentity:delivery_id: str@classmethod- def from_parts(cls, profile: Optional[str], route: str, delivery_id: str) -> "_WebhookDeliveryIdentity":+ def from_parts(cls, profile: Optional[str], route: str, delivery_id: str) -> _WebhookDeliveryIdentity:return cls(profile=profile or "default", route=route, delivery_id=delivery_id)@property@@ -142,7 +142,7 @@ def _is_known_platform(name: str) -> bool:return False-def _json_error(message: str, status: int) -> "web.Response":+def _json_error(message: str, status: int) -> web.Response:return web.json_response({"error": message}, status=status)@@ -385,7 +385,7 @@ class WebhookAdapter(BasePlatformAdapter):# --- HTTP handlers ---- async def _handle_health(self, request: "web.Request") -> "web.Response":+ async def _handle_health(self, request: web.Request) -> web.Response:"""GET /health — simple health check."""return web.json_response({"status": "ok", "platform": "webhook"})@@ -454,7 +454,7 @@ class WebhookAdapter(BasePlatformAdapter):except Exception as e:logger.error("[webhook] Failed to reload dynamic routes: %s", e)- async def _handle_profile_ingress(self, request: "web.Request") -> "web.StreamResponse":+ async def _handle_profile_ingress(self, request: web.Request) -> web.StreamResponse:profile = self._resolve_request_profile(request)if profile is _PROFILE_REJECTED or profile is None:return _json_error("Unknown or unconfigured profile", 404)@@ -462,7 +462,7 @@ class WebhookAdapter(BasePlatformAdapter):return await dispatch_profile_ingress(self.gateway_runner, profile, request.match_info.get("tail", ""), request)- def _resolve_request_profile(self, request: "web.Request"):+ def _resolve_request_profile(self, request: web.Request):"""Resolve + validate the /p/<profile>/ URL prefix: None (no prefix, or multiplexing off and theprefix names this gateway's own profile), the profile name (served under multiplexing), or``_PROFILE_REJECTED`` (unknown / not served → 404)."""@@ -502,8 +502,8 @@ class WebhookAdapter(BasePlatformAdapter):from hermes_cli.profiles import get_profile_dirreturn _profile_runtime_scope(get_profile_dir(profile))- async def _read_authenticated_body(self, request: "web.Request", route_name: str,- route_config: dict) -> "tuple[Optional[bytes], Optional[web.Response]]":+ async def _read_authenticated_body(self, request: web.Request, route_name: str,+ route_config: dict) -> tuple[Optional[bytes], Optional[web.Response]]:"""Auth-before-body: size-cap, read, then HMAC-validate. Returns ``(body, None)`` or ``(None, response)``."""if (request.content_length or 0) > self._max_body_bytes:return None, _json_error("Payload too large", 413)@@ -541,7 +541,7 @@ class WebhookAdapter(BasePlatformAdapter):return _UNPARSEABLEasync def _handle_deliver_only(self, prompt: str, payload: Any, route_config: dict, route_name: str,- event_type: str, delivery_id: str, profile: Optional[str] = None) -> "web.Response":+ event_type: str, delivery_id: str, profile: Optional[str] = None) -> web.Response:"""deliver_only: the rendered prompt IS the message — skip the agent, reuse the sameauth/rate-limit/idempotency/template pipeline."""delivery = {"deliver": route_config.get("deliver", "log"), "payload": payload, "profile": profile,@@ -565,7 +565,7 @@ class WebhookAdapter(BasePlatformAdapter):return web.json_response(failed, status=502)def _handle_cron_trigger(self, prompt: str, route_config: dict, route_name: str, event_type: str,- delivery_id: str, profile: Optional[str] = None) -> "web.Response":+ delivery_id: str, profile: Optional[str] = None) -> web.Response:"""cron_job: fire an EXISTING cron job on this event instead of starting a webhook agent session.The rendered prompt is transient per-run context (same rail as ``cronjob(action='run', prompt=...)``);the job's own prompt, skills, model and delivery apply. Same auth/rate-limit/filter/script/idempotency@@ -596,7 +596,7 @@ class WebhookAdapter(BasePlatformAdapter):return web.json_response({"status": "accepted", "route": route_name, "cron_job": job_ref, "event": event_type,"delivery_id": delivery_id}, status=202)- def _resolve_route(self, request: "web.Request") -> "tuple[str, Optional[dict], Any, Optional[web.Response]]":+ def _resolve_route(self, request: web.Request) -> tuple[str, Optional[dict], Any, Optional[web.Response]]:"""Route + profile lookup for a POST; ``(route_name, route_config, profile, error_response)``."""self._reload_dynamic_routes() # hot-reload dynamic subscriptions (stat-gated, lock-free)route_name = request.match_info.get("route_name", "")@@ -635,7 +635,7 @@ class WebhookAdapter(BasePlatformAdapter):logger.warning("[webhook] Skill loading failed: %s", e)return prompt- async def _handle_webhook(self, request: "web.Request") -> "web.Response":+ async def _handle_webhook(self, request: web.Request) -> web.Response:"""POST /webhooks/{route_name} — receive and process a webhook event."""route_name, route_config, profile, error_response = self._resolve_route(request)if error_response is None:@@ -699,7 +699,7 @@ class WebhookAdapter(BasePlatformAdapter):delivery_id, now)def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,- event_type: str, delivery_id: str, now: float) -> "web.Response":+ event_type: str, delivery_id: str, now: float) -> web.Response:"""Spawn the agent run for one POST and return 202 immediately."""logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,len(prompt), delivery_id)@@ -709,7 +709,7 @@ class WebhookAdapter(BasePlatformAdapter):"delivery_id": delivery_id}, status=202)def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,- route_name: str, profile, event_type: str) -> "asyncio.Task":+ route_name: str, profile, event_type: str) -> asyncio.Task:"""Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)session_chat_id = identity.session_chat_id@@ -736,13 +736,13 @@ class WebhookAdapter(BasePlatformAdapter):task.add_done_callback(self._background_tasks.discard)return task- async def on_processing_complete(self, event: "MessageEvent", outcome: Any) -> None:+ async def on_processing_complete(self, event: MessageEvent, outcome: Any) -> None:"""Close the one-shot per-delivery session: ``prune_sessions`` only reaps rows with ``ended_at`` set, sounclosed webhook sessions leak unbounded. Fires at the true end of the run; ``end_session()`` isfirst-reason-wins."""await self._end_webhook_session(event, event.source.chat_id)- async def _end_webhook_session(self, event: "MessageEvent", session_chat_id: str) -> None:+ async def _end_webhook_session(self, event: MessageEvent, session_chat_id: str) -> None:"""Mark the per-delivery session ended via ``SessionDB.end_session`` (never a hand-written UPDATE),resolving session_id from the SAME source the run was keyed on."""runner = self.gateway_runner@@ -766,7 +766,7 @@ class WebhookAdapter(BasePlatformAdapter):# --- Signature validation ---- def _validate_signature(self, request: "web.Request", body: bytes, secret: str) -> bool:+ def _validate_signature(self, request: web.Request, body: bytes, secret: str) -> bool:"""Validate webhook signature (GitHub, GitLab, Svix, Standard Webhooks, Linear, generic HMAC-SHA256)."""headers = request.headersdiff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex 6a89f40daec..59710ed248d 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -66,7 +66,7 @@ _TABLE_RULE_RE = re.compile(r"^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?\s*_FENCE_RE = re.compile(r"^```([^\n`]*)\s*$")-def _is_stale_session_ret(ret: "Optional[int]", errcode: "Optional[int]", errmsg: "Optional[str]") -> bool:+def _is_stale_session_ret(ret: Optional[int], errcode: Optional[int], errmsg: Optional[str]) -> bool:"""Recognize stale-session variants of iLink's ``-2`` response, not real rate limits."""return (ret == RATE_LIMIT_ERRCODE or errcode == RATE_LIMIT_ERRCODE) and (errmsg or "").lower() in {"unknown error",@@ -88,7 +88,7 @@ def _session_not_ready_error(ret: Any, errcode: Any, errmsg: Any) -> RuntimeErro" — the user must send the bot a message first (or re-pair)")-def _make_ssl_connector() -> Optional["aiohttp.TCPConnector"]:+def _make_ssl_connector() -> Optional[aiohttp.TCPConnector]:"""TCPConnector with certifi's CA bundle (``ilinkai.weixin.qq.com`` fails some system stores, e.g. HomebrewOpenSSL); None without certifi so aiohttp's default (honors ``SSL_CERT_FILE`` under trust_env) applies.``keepalive_timeout=2`` + ``enable_cleanup_closed`` drain idle CLOSE_WAIT sockets behind proxies like Warp.@@ -108,7 +108,7 @@ def _make_ssl_connector() -> Optional["aiohttp.TCPConnector"]:return aiohttp.TCPConnector(ssl=ssl.create_default_context(cafile=certifi.where()), keepalive_timeout=2, enable_cleanup_closed=True)-def _new_session(**kwargs: Any) -> "aiohttp.ClientSession":+def _new_session(**kwargs: Any) -> aiohttp.ClientSession:return aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector(), **kwargs)@@ -264,7 +264,7 @@ def _guess_chat_type(message: dict[str, Any], account_id: str) -> tuple[str, str# HTTP helpers enforce timeouts via asyncio.wait_for(), not aiohttp ClientTimeout, which raises# "Timeout context manager should be used inside a task" under run_coroutine_threadsafe() from cron.async def _api_request(- session: "aiohttp.ClientSession", method: str, *, base_url: str, endpoint: str, headers: dict[str, str], timeout_ms: int, body: Optional[str] = None,+ session: aiohttp.ClientSession, method: str, *, base_url: str, endpoint: str, headers: dict[str, str], timeout_ms: int, body: Optional[str] = None,) -> dict[str, Any]:async def _do() -> dict[str, Any]:kwargs = {"data": body} if body is not None else {}@@ -277,18 +277,18 @@ async def _api_request(async def _api_post(- session: "aiohttp.ClientSession", *, base_url: str, endpoint: str, payload: dict[str, Any], token: Optional[str], timeout_ms: int,+ session: aiohttp.ClientSession, *, base_url: str, endpoint: str, payload: dict[str, Any], token: Optional[str], timeout_ms: int,) -> dict[str, Any]:body = json.dumps({**payload, "base_info": {"channel_version": CHANNEL_VERSION}}, ensure_ascii=False, separators=(",", ":"))return await _api_request(session, "POST", base_url=base_url, endpoint=endpoint, headers=_headers(token, body), timeout_ms=timeout_ms, body=body)-async def _api_get(session: "aiohttp.ClientSession", *, base_url: str, endpoint: str, timeout_ms: int) -> dict[str, Any]:+async def _api_get(session: aiohttp.ClientSession, *, base_url: str, endpoint: str, timeout_ms: int) -> dict[str, Any]:headers = {"iLink-App-Id": ILINK_APP_ID, "iLink-App-ClientVersion": str(ILINK_APP_CLIENT_VERSION)}return await _api_request(session, "GET", base_url=base_url, endpoint=endpoint, headers=headers, timeout_ms=timeout_ms)-async def _get_updates(session: "aiohttp.ClientSession", *, base_url: str, token: str, sync_buf: str, timeout_ms: int) -> dict[str, Any]:+async def _get_updates(session: aiohttp.ClientSession, *, base_url: str, token: str, sync_buf: str, timeout_ms: int) -> dict[str, Any]:try:return await _api_post(session, base_url=base_url, endpoint=EP_GET_UPDATES, payload={"get_updates_buf": sync_buf}, token=token, timeout_ms=timeout_ms)except TimeoutError:@@ -296,7 +296,7 @@ async def _get_updates(session: "aiohttp.ClientSession", *, base_url: str, tokenasync def _send_items(- session: "aiohttp.ClientSession", *, base_url: str, token: str, to: str, item_list: list[dict[str, Any]], context_token: Optional[str], client_id: str,+ session: aiohttp.ClientSession, *, base_url: str, token: str, to: str, item_list: list[dict[str, Any]], context_token: Optional[str], client_id: str,) -> dict[str, Any]:message: dict[str, Any] = {"from_user_id": "", "to_user_id": to, "client_id": client_id, "message_type": MSG_TYPE_BOT, "message_state": MSG_STATE_FINISH,@@ -307,7 +307,7 @@ async def _send_items(async def _send_message(- session: "aiohttp.ClientSession", *, base_url: str, token: str, to: str, text: str, context_token: Optional[str], client_id: str,+ session: aiohttp.ClientSession, *, base_url: str, token: str, to: str, text: str, context_token: Optional[str], client_id: str,) -> dict[str, Any]:if not text or not text.strip():raise ValueError("_send_message: text must not be empty")@@ -315,7 +315,7 @@ async def _send_message(return await _send_items(session, base_url=base_url, token=token, to=to, item_list=item_list, context_token=context_token, client_id=client_id)-async def _get_config(session: "aiohttp.ClientSession", *, base_url: str, token: str, user_id: str, context_token: Optional[str]) -> dict[str, Any]:+async def _get_config(session: aiohttp.ClientSession, *, base_url: str, token: str, user_id: str, context_token: Optional[str]) -> dict[str, Any]:payload: dict[str, Any] = {"ilink_user_id": user_id}if context_token:payload["context_token"] = context_token@@ -323,7 +323,7 @@ async def _get_config(session: "aiohttp.ClientSession", *, base_url: str, token:async def _get_upload_url(- session: "aiohttp.ClientSession", *, base_url: str, token: str, to_user_id: str, media_type: int, filekey: str, rawsize: int,+ session: aiohttp.ClientSession, *, base_url: str, token: str, to_user_id: str, media_type: int, filekey: str, rawsize: int,rawfilemd5: str, filesize: int, aeskey_hex: str,) -> dict[str, Any]:payload = {@@ -332,7 +332,7 @@ async def _get_upload_url(return await _api_post(session, base_url=base_url, endpoint=EP_GET_UPLOAD_URL, payload=payload, token=token, timeout_ms=API_TIMEOUT_MS)-async def _upload_ciphertext(session: "aiohttp.ClientSession", *, ciphertext: bytes, upload_url: str) -> str:+async def _upload_ciphertext(session: aiohttp.ClientSession, *, ciphertext: bytes, upload_url: str) -> str:async def _do() -> str:async with session.post(upload_url, data=ciphertext, headers={"Content-Type": "application/octet-stream"}) as response:encrypted_param = response.headers.get("x-encrypted-param") if response.status == 200 else None@@ -344,7 +344,7 @@ async def _upload_ciphertext(session: "aiohttp.ClientSession", *, ciphertext: byreturn await asyncio.wait_for(_do(), timeout=120)-async def _download_bytes(session: "aiohttp.ClientSession", *, url: str, timeout_seconds: float = 60.0) -> bytes:+async def _download_bytes(session: aiohttp.ClientSession, *, url: str, timeout_seconds: float = 60.0) -> bytes:async def _do() -> bytes:async with session.get(url) as response:response.raise_for_status()@@ -369,7 +369,7 @@ def _assert_weixin_cdn_url(url: str) -> None:async def _download_and_decrypt_media(- session: "aiohttp.ClientSession", *, cdn_base_url: str, encrypted_query_param: Optional[str], aes_key_b64: Optional[str],+ session: aiohttp.ClientSession, *, cdn_base_url: str, encrypted_query_param: Optional[str], aes_key_b64: Optional[str],full_url: Optional[str], timeout_seconds: float,) -> bytes:if encrypted_query_param:@@ -571,7 +571,7 @@ def _save_sync_buf(hermes_home: str, account_id: str, sync_buf: str) -> None:atomic_json_write(_account_dir(hermes_home) / f"{account_id}.sync.json", {"get_updates_buf": sync_buf})-async def _fetch_qr(session: "aiohttp.ClientSession", bot_type: str) -> tuple[str, str]:+async def _fetch_qr(session: aiohttp.ClientSession, bot_type: str) -> tuple[str, str]:qr_resp = await _api_get(session, base_url=ILINK_BASE_URL, endpoint=f"{EP_GET_BOT_QR}?bot_type={bot_type}", timeout_ms=QR_TIMEOUT_MS)return str(qr_resp.get("qrcode") or ""), str(qr_resp.get("qrcode_img_content") or "")diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex 6c3eeafc141..030349dc4d9 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -205,18 +205,18 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._group_allow_from: set[str] = self._normalize_allow_ids(self._coerce_allow_list(raw_groups))self._mention_patterns = self._compile_mention_patterns()# Webhook dedup state (in-memory, FIFO-evicted) and counters.- self._seen_wamids: "OrderedDict[str, bool]" = OrderedDict()+ self._seen_wamids: OrderedDict[str, bool] = OrderedDict()self._duplicate_count = self._accepted_count = self._rejected_signature_count = 0self._warned_no_ffmpeg: bool = False# Latest inbound wamid per chat: Meta's typing/read-receipt API needs a# message_id to attach to, and the base send_typing contract has none.- self._last_inbound_wamid_by_chat: "OrderedDict[str, str]" = OrderedDict()+ self._last_inbound_wamid_by_chat: OrderedDict[str, str] = OrderedDict()# Interactive-button state: short id (in the button payload) → session_key for# the gateway resolver. Popped on tap; FIFO-capped via bounded_put so ignored# prompts don't accumulate (an evicted tap degrades to text fallback).- self._clarify_state: "OrderedDict[str, str]" = OrderedDict()- self._exec_approval_state: "OrderedDict[str, str]" = OrderedDict()- self._slash_confirm_state: "OrderedDict[str, str]" = OrderedDict()+ self._clarify_state: OrderedDict[str, str] = OrderedDict()+ self._exec_approval_state: OrderedDict[str, str] = OrderedDict()+ self._slash_confirm_state: OrderedDict[str, str] = OrderedDict()self._runner = self._http_client = None# ------------------------------------------------------------------ helpers@@ -417,7 +417,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# ------------------------------------------------------------------ interactive messagesasync def _send_interactive(self, chat_id: str, interactive: dict[str, Any], metadata: Optional[dict[str, Any]],- state: "OrderedDict[str, str]", state_id: str, session_key: str,+ state: OrderedDict[str, str], state_id: str, session_key: str,) -> SendResult:"""POST an ``interactive`` message (caller supplies ``type``/``body``/``action``) and, onsuccess, remember ``state_id → session_key`` for the tap. Free-form interactives need no@@ -692,7 +692,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return str(out_path), mime or None# ------------------------------------------------------------------ inbound- async def _handle_health(self, request: "web.Request") -> "web.Response":+ async def _handle_health(self, request: web.Request) -> web.Response:return web.json_response({"status": "ok", "platform": self.platform.value, "phone_number_id": self._phone_number_id,"webhook_path": self._webhook_path, "verify_token_configured": bool(self._verify_token),@@ -701,7 +701,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):"rejected_signature": self._rejected_signature_count,})- async def _handle_verify(self, request: "web.Request") -> "web.Response":+ async def _handle_verify(self, request: web.Request) -> web.Response:"""Meta subscription handshake: echo ``hub.challenge`` iff mode is``subscribe`` and ``hub.verify_token`` matches (constant-time)."""if not self._verify_token:@@ -717,7 +717,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return web.Response(status=400, text="missing challenge")return web.Response(text=q["hub.challenge"], content_type="text/plain")- async def _handle_webhook(self, request: "web.Request") -> "web.Response":+ async def _handle_webhook(self, request: web.Request) -> web.Response:"""Inbound webhook POST: raw bytes → HMAC verify → JSON → dispatch. Signature is overthe raw body, so JSON parsing must come after verification. Always 200 once a validrequest is ack'd — Meta retries non-200 for up to 7 days and would multiply agent work."""@@ -855,7 +855,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):@staticmethoddef _pop_tap_state(- state: "OrderedDict[str, str]", key: str, stale_log: str, choice: str = "", valid: tuple = (),+ state: OrderedDict[str, str], key: str, stale_log: str, choice: str = "", valid: tuple = (),) -> Optional[str]:"""Pop the session_key for a tapped prompt. None (info-logged) when nothing is live — likelya stale tap; an unrecognised ``choice`` keeps the prompt live and also yields None."""diff --git a/gateway/platforms/yuanbao.py b/gateway/platforms/yuanbao.pyindex c7559d2a6da..fa0008a318d 100644--- a/gateway/platforms/yuanbao.py+++ b/gateway/platforms/yuanbao.py@@ -337,24 +337,24 @@ class InboundPipeline:return name_or_mw.name, name_or_mwreturn name_or_mw, handler- def use(self, name_or_mw, handler=None, when=None) -> "InboundPipeline":+ def use(self, name_or_mw, handler=None, when=None) -> InboundPipeline:"""Append ``pipeline.use(SomeMiddleware())`` or ``pipeline.use("name", fn)``."""return self._insert_relative(None, 0, name_or_mw, handler, when)- def _insert_relative(self, target: Optional[str], offset: int, name_or_mw, handler, when) -> "InboundPipeline":+ def _insert_relative(self, target: Optional[str], offset: int, name_or_mw, handler, when) -> InboundPipeline:"""Insert at index(target)+offset; appends when *target* is None or not registered."""name, h = self._normalize(name_or_mw, handler)idx = next((i for i, (n, _, _) in enumerate(self._middlewares) if n == target), None)self._middlewares.insert(len(self._middlewares) if idx is None else idx + offset, (name, h, when))return self- def use_before(self, target: str, name_or_mw, handler=None, when=None) -> "InboundPipeline":+ def use_before(self, target: str, name_or_mw, handler=None, when=None) -> InboundPipeline:return self._insert_relative(target, 0, name_or_mw, handler, when)- def use_after(self, target: str, name_or_mw, handler=None, when=None) -> "InboundPipeline":+ def use_after(self, target: str, name_or_mw, handler=None, when=None) -> InboundPipeline:return self._insert_relative(target, 1, name_or_mw, handler, when)- def remove(self, name: str) -> "InboundPipeline":+ def remove(self, name: str) -> InboundPipeline:self._middlewares = [(n, h, w) for n, h, w in self._middlewares if n != name]return self@@ -1721,7 +1721,7 @@ class DispatchMiddleware(InboundMiddleware):task.add_done_callback(adapter._inbound_tasks.discard)@staticmethod- async def _consume_group_queue(adapter: "YuanbaoAdapter", session_key: str) -> None:+ async def _consume_group_queue(adapter: YuanbaoAdapter, session_key: str) -> None:"""Drain the group queue one dispatch at a time, waiting for each to finish; exits after 2s idle."""queue = adapter._group_queues.get(session_key)if not queue:@@ -1766,7 +1766,7 @@ class ConnectionManager:_DEBOUNCE_WINDOW: float = 1.5 # seconds to wait for companion frames of a multi-part message_LOOPS = (("_heartbeat_task", "_heartbeat_loop", "heartbeat"), ("_recv_task", "_receive_loop", "recv"))- def __init__(self, adapter: "YuanbaoAdapter") -> None:+ def __init__(self, adapter: YuanbaoAdapter) -> None:self._adapter = adapterself._ws = None # websockets connectionself._connect_id: Optional[str] = None@@ -2173,15 +2173,15 @@ class MediaSendHandler(ABC):return True@abstractmethod- async def acquire_file(self, adapter: "YuanbaoAdapter", **kwargs: Any) -> tuple[bytes, str, str]:+ async def acquire_file(self, adapter: YuanbaoAdapter, **kwargs: Any) -> tuple[bytes, str, str]:"""(file_bytes, filename, content_type); raise ValueError when unobtainable."""@abstractmethoddef build_msg_body(self, upload_result: dict, **kwargs: Any) -> list:"""Platform-specific MsgBody list from the COS upload result."""- async def handle(self, adapter: "YuanbaoAdapter", chat_id: str, reply_to: Optional[str] = None,- caption: Optional[str] = None, **kwargs: Any) -> "SendResult":+ async def handle(self, adapter: YuanbaoAdapter, chat_id: str, reply_to: Optional[str] = None,+ caption: Optional[str] = None, **kwargs: Any) -> SendResult:if adapter._connection.ws is None:return SendResult(success=False, error="Not connected", retryable=True)adapter._outbound.slow_notifier.cancel(chat_id)@@ -2277,7 +2277,7 @@ class StickerHandler(MediaSendHandler):class HeartbeatManager:"""Reply heartbeat lifecycle: RUNNING every 2s, auto-FINISH after 30s idle, explicit stop."""- def __init__(self, adapter: "YuanbaoAdapter") -> None:+ def __init__(self, adapter: YuanbaoAdapter) -> None:self._adapter = adapterself._reply_heartbeat_tasks: dict[str, asyncio.Task] = {}self._reply_hb_last_active: dict[str, float] = {}@@ -2347,7 +2347,7 @@ class HeartbeatManager:class SlowResponseNotifier:"""Per-chat timer that sends a courtesy 'please wait' after SLOW_RESPONSE_TIMEOUT_S without a reply."""- def __init__(self, adapter: "YuanbaoAdapter", sender: "MessageSender") -> None:+ def __init__(self, adapter: YuanbaoAdapter, sender: MessageSender) -> None:self._adapter = adapterself._sender = senderself._tasks: dict[str, asyncio.Task] = {}@@ -2383,7 +2383,7 @@ class MessageSender:# @nickname bounded by whitespace / line edges_AT_USER_RE = re.compile(r'(?:(?<=\s)|(?<=^))@(\S+?)(?=\s|$)', re.MULTILINE)- def __init__(self, adapter: "YuanbaoAdapter") -> None:+ def __init__(self, adapter: YuanbaoAdapter) -> None:self._adapter = adapterself._chat_locks: collections.OrderedDict[str, asyncio.Lock] = collections.OrderedDict()self._media_handlers: dict[str, MediaSendHandler] = {@@ -2400,7 +2400,7 @@ class MessageSender:self._chat_locks[chat_id] = asyncio.Lock()return self._chat_locks[chat_id]- async def send_text(self, chat_id: str, content: str, reply_to: Optional[str] = None, group_code: str = "") -> "SendResult":+ async def send_text(self, chat_id: str, content: str, reply_to: Optional[str] = None, group_code: str = "") -> SendResult:"""Send text with auto-chunking and per-chat-id ordering guarantee."""adapter = self._adapterif adapter._connection.ws is None:@@ -2420,7 +2420,7 @@ class MessageSender:return SendResult(success=True)async def send_media(self, chat_id: str, handler_name: str, reply_to: Optional[str] = None,- caption: Optional[str] = None, **kwargs: Any) -> "SendResult":+ caption: Optional[str] = None, **kwargs: Any) -> SendResult:handler = self._media_handlers.get(handler_name)if handler is None:return SendResult(success=False, error=f"Unknown media handler: {handler_name!r}")@@ -2429,7 +2429,7 @@ class MessageSender:async def send_direct(self, chat_id: str, message: str, media_files: Optional[list[tuple[str, bool]]] = None) -> dict[str, Any]:"""send_message tool entry: text first, then each media file by extension, on the running adapter."""adapter = self._adapter- last_result: Optional["SendResult"] = None+ last_result: Optional[SendResult] = Noneif message.strip():last_result = await adapter.send(chat_id, message)if not last_result.success:@@ -2443,19 +2443,19 @@ class MessageSender:return {"error": "No deliverable text or media remained after processing"}return {"success": True, "platform": "yuanbao", "chat_id": chat_id, "message_id": last_result.message_id}- async def dispatch_msg_body(self, chat_id: str, msg_body: list, reply_to: Optional[str] = None, group_code: str = "") -> "SendResult":+ async def dispatch_msg_body(self, chat_id: str, msg_body: list, reply_to: Optional[str] = None, group_code: str = "") -> SendResult:"""Lock + dispatch an arbitrary MsgBody to C2C or group."""async with self.get_chat_lock(chat_id):result = await self._send_msg_body(chat_id, msg_body, reply_to, group_code)return self._to_send_result(result)@staticmethod- def _to_send_result(raw: dict) -> "SendResult":+ def _to_send_result(raw: dict) -> SendResult:if raw.get("success"):return SendResult(success=True, message_id=raw.get("msg_key"))return SendResult(success=False, error=raw.get("error", "Unknown error"))- async def send_text_chunk(self, chat_id: str, text: str, reply_to: Optional[str] = None, retry: int = 3, group_code: str = "") -> "SendResult":+ async def send_text_chunk(self, chat_id: str, text: str, reply_to: Optional[str] = None, retry: int = 3, group_code: str = "") -> SendResult:"""Send a single text chunk with retry (exponential backoff: 1s, 2s, 4s)."""adapter = self._adapterlast_error: str = "Unknown error"@@ -2532,7 +2532,7 @@ class MessageSender:), req_id)@staticmethod- async def _dispatch_encoded(adapter: "YuanbaoAdapter", encoded: bytes, req_id: str) -> dict:+ async def _dispatch_encoded(adapter: YuanbaoAdapter, encoded: bytes, req_id: str) -> dict:"""Send pre-encoded bytes via WS → ``{"success", "msg_key" | "error"}``."""try:response = await adapter._connection.send_biz_request(encoded, req_id=req_id)@@ -2579,7 +2579,7 @@ class MessageSender:class OutboundManager:"""Composes MessageSender, HeartbeatManager and SlowResponseNotifier (sender cancels the notifierbefore a send and emits the FINISH heartbeat after)."""- def __init__(self, adapter: "YuanbaoAdapter") -> None:+ def __init__(self, adapter: YuanbaoAdapter) -> None:self._adapter = adapterself.sender: MessageSender = MessageSender(adapter)self.heartbeat: HeartbeatManager = HeartbeatManager(adapter)@@ -2598,16 +2598,16 @@ class YuanbaoAdapter(BasePlatformAdapter):splits_long_messages = True # send() auto-chunks via truncate_message(MAX_TEXT_CHUNK)MEDIA_MAX_SIZE_MB: int = 50DM_MAX_CHARS = 10000- _active_instance: ClassVar[Optional["YuanbaoAdapter"]] = None+ _active_instance: ClassVar[Optional[YuanbaoAdapter]] = None# Per Hermes home: a multiplexed gateway runs one Yuanbao adapter per profile, and the tools /# send_message read "the" adapter from inside a profile-scoped turn, so last-wins would route# profile B's sends through profile A's bot. Registration and lookup both key on the ambient# override (connect/reconnect tasks inherit the profile's Context); the slot above serves the# unscoped path.- _active_instances: ClassVar[dict[str, "YuanbaoAdapter"]] = {}+ _active_instances: ClassVar[dict[str, YuanbaoAdapter]] = {}@classmethod- def get_active(cls) -> Optional["YuanbaoAdapter"]:+ def get_active(cls) -> Optional[YuanbaoAdapter]:from hermes_constants import get_hermes_home_override, hermes_home_keyif get_hermes_home_override() is None:@@ -2615,7 +2615,7 @@ class YuanbaoAdapter(BasePlatformAdapter):return cls._active_instances.get(hermes_home_key())@classmethod- def set_active(cls, adapter: Optional["YuanbaoAdapter"]) -> None:+ def set_active(cls, adapter: Optional[YuanbaoAdapter]) -> None:from hermes_constants import get_hermes_home_override, hermes_home_keyif get_hermes_home_override() is None:diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 3424756c30a..7219932d93c 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -179,7 +179,7 @@ class RelayAdapter(BasePlatformAdapter):self._revocation_monitor: Optional[asyncio.Task[None]] = None# Lazily built client for the connector's /relay/media routes; None when# dial URL or creds are absent (media lanes degrade to text fallbacks).- self._media_client: Optional["RelayMediaClient"] = None+ self._media_client: Optional[RelayMediaClient] = None# prompt_id -> pending-prompt state for the interactive `prompt` op; the# user's pick comes back as a prompt_response naming this id and resolves the# waiting primitive like native button callbacks. Expire lazily (_pop_prompt).@@ -193,7 +193,7 @@ class RelayAdapter(BasePlatformAdapter):self._prompt_owner_nonce: str = secrets.token_hex(3)# Prompt ids this process already resolved, newest last (repeat answers are# consumed silently instead of treated as stale).- self._resolved_prompts: "OrderedDict[str, float]" = OrderedDict()+ self._resolved_prompts: OrderedDict[str, float] = OrderedDict()# ── capability surface (from descriptor) ─────────────────────────────@propertydiff --git a/gateway/relay/descriptor.py b/gateway/relay/descriptor.pyindex 5385576df3d..eb29e7b61c5 100644--- a/gateway/relay/descriptor.py+++ b/gateway/relay/descriptor.py@@ -67,7 +67,7 @@ class CapabilityDescriptor:return json.dumps(asdict(self), sort_keys=True, ensure_ascii=False)@classmethod- def from_json(cls, data: str) -> "CapabilityDescriptor":+ def from_json(cls, data: str) -> CapabilityDescriptor:"""Deserialize a handshake JSON string; unknown keys ignored, missing keys default.Trust-boundary normalization (malformed input never breaks the handshake):diff --git a/gateway/relay/transport.py b/gateway/relay/transport.pyindex 45d320ea941..7c93179bbe7 100644--- a/gateway/relay/transport.py+++ b/gateway/relay/transport.py@@ -42,7 +42,7 @@ class RelayTransport(Protocol):def set_inbound_handler(self, handler: InboundHandler) -> None:...- def set_passthrough_handler(self, handler: "PassthroughHandler") -> None:+ def set_passthrough_handler(self, handler: PassthroughHandler) -> None:"""Register the callback for each forwarded passthrough request (§5.1).The connector answers the provider's edge ACK itself, then forwards the realdiff --git a/gateway/restart.py b/gateway/restart.pyindex 3d19d3d74c1..64bd1fc398b 100644--- a/gateway/restart.py+++ b/gateway/restart.py@@ -125,7 +125,7 @@ def read_launchd_exit_timeout_s(*,environ: Mapping[str, str] | None = None,uid: int | None = None,- run: Callable[..., "subprocess.CompletedProcess[str]"] = subprocess.run,+ run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,platform: str = sys.platform,) -> float | None:"""Live ``ExitTimeOut`` (seconds) launchd enforces for this gateway's job.diff --git a/gateway/run.py b/gateway/run.pyindex 02d93260666..f75b987a58a 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -542,7 +542,7 @@ def _is_transient_network_error(exc: BaseException) -> bool:def _gateway_loop_exception_handler(- loop: "asyncio.AbstractEventLoop", context: dict[str, Any]) -> None:+ loop: asyncio.AbstractEventLoop, context: dict[str, Any]) -> None:"""Loop-level safety net for transient network errors (installed once by ``start_gateway``).Logs WARNING with traceback; non-transient errors go to the default handler so real bugs surface.@@ -574,7 +574,7 @@ def _redact_gateway_user_facing_secrets(text: str) -> str:return redact_for_egress(text)-def _redact_approval_command(cmd: "str | None") -> str:+def _redact_approval_command(cmd: str | None) -> str:"""Redact credentials from a command before it goes into an approval prompt.The gateway approval prompt is built from the raw command string, so a credential-shaped value would@@ -1587,7 +1587,7 @@ def _reload_runtime_env_preserving_config_authority() -> None:_bridge_max_turns_from_config(_hermes_home)-def _bridge_max_turns_from_config(home: "Path") -> None:+def _bridge_max_turns_from_config(home: Path) -> None:"""Re-bridge agent.max_turns (+ sessions.*) per turn; managed overlay applies or it reverts.Skipped inside a served secondary's scope: the env slots are the launch profile's andhermes_state reads the routed profile's ``sessions.*`` from its own config under scope."""@@ -1638,13 +1638,13 @@ class HygieneTurnHoldExceeded(Exception):must NOT take the idle-timeout path (AGENT_COMPRESSION_TIMEOUT, "no output", failure cooldown)."""-def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:+def _multiplex_profile_homes(config: object) -> list[tuple[str, Path]]:"""Return the authoritative profile set for one multiplex gateway config."""from hermes_cli.profiles import profiles_to_servereturn list(profiles_to_serve(multiplex=True))-def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:+def _cron_tick_profile_homes(config: object) -> list[tuple[str, Path]]:"""Profile homes the in-process ticker visits: the served set PLUS the process-activeprofile: ``profiles_to_serve`` lists default + every live named profile, but a ``--profile<name>`` gateway's own profile may sit outside ``profiles/`` (custom HERMES_HOME). One host@@ -1662,7 +1662,7 @@ def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:return homes-def _cron_profile_gate(name: str, home: "Path") -> bool:+def _cron_profile_gate(name: str, home: Path) -> bool:"""Tick ``home`` this cycle unless ANOTHER gateway process owns it.Same stand-down the serve/Desktop ticker applies (``hermes_cli/web_server.py``): a host that@@ -1769,7 +1769,7 @@ def _terminal_scope_cwd(default: str = "") -> str:return _ts_env("TERMINAL_CWD", default)-def _load_profile_secret_scope(profile_home: "Path") -> dict:+def _load_profile_secret_scope(profile_home: Path) -> dict:"""Hydrate and load one profile's secrets under its home override."""from hermes_constants import set_hermes_home_override, reset_hermes_home_override# Caller already hydrated external sources off-loop (#99519).@@ -1786,7 +1786,7 @@ def _load_profile_secret_scope(profile_home: "Path") -> dict:@_contextmanagerdef _profile_runtime_scope(- profile_home: "Path", prepared_secret_scope: Optional[dict] = None, *,+ profile_home: Path, prepared_secret_scope: Optional[dict] = None, *,hydrate_secrets: bool = True):"""Scope config/skills/memory AND credentials to a profile for one turn (multiplexed path only).``set_hermes_home_override`` is a contextvar (reaches the agent worker via ``copy_context()``);@@ -1821,14 +1821,14 @@ def _profile_runtime_scope(@_asynccontextmanager-async def _async_profile_runtime_scope(profile_home: "Path"):+async def _async_profile_runtime_scope(profile_home: Path):"""Enter a profile scope without loading secret files on the event loop."""secrets = await asyncio.to_thread(_load_profile_secret_scope, Path(profile_home))with _profile_runtime_scope(Path(profile_home), secrets):yield-def load_gateway_config_for_runner() -> "GatewayConfig":+def load_gateway_config_for_runner() -> GatewayConfig:"""Load gateway config for the process-level GatewayRunner. An UNSET ``multiplex_profiles`` issettled first by ``resolve_multiplex_mode`` (the default is on; the boot guard keeps a fleet thatstill runs per-profile gateways standalone). Multiplexed: set multiplex-active, then reload@@ -1898,7 +1898,7 @@ async def _discover_gateway_mcp_tools(config: object) -> None:logger.warning("MCP tool discovery failed for profile '%s'", profile_name, exc_info=True)-def _platform_has_bot_credential(platform: "Platform", platform_config: "PlatformConfig") -> bool:+def _platform_has_bot_credential(platform: Platform, platform_config: PlatformConfig) -> bool:"""Return True when a token-authenticated platform has a usable bot credential; platforms not using``PlatformConfig.token`` (Signal session paths, port-binding HTTP adapters) always return True."""from gateway.config import PLATFORM_TOKEN_ENV_NAMES, Platform@@ -2846,7 +2846,7 @@ def _check_unavailable_skill(command_name: str) -> str | None:return None-def _platform_config_key(platform: "Platform") -> str:+def _platform_config_key(platform: Platform) -> str:"""Map a Platform enum to its config.yaml key (LOCAL→"cli", rest→enum value)."""return "cli" if platform == Platform.LOCAL else platform.value@@ -2863,7 +2863,7 @@ def _gateway_config_home() -> Path:return Path(override) if override else _hermes_home-def _load_gateway_config(config_path: "Path | None" = None) -> dict:+def _load_gateway_config(config_path: Path | None = None) -> dict:"""The effective user config.yaml (managed overlay, ``${VAR}`` expansion, model-key canon; noDEFAULT_CONFIG merge) — ``{}`` on any error (fail-open). Defaults to the active gateway home(``_hermes_home`` monkeypatches apply); multiplexers pass a path.@@ -2953,7 +2953,7 @@ def _resolve_hermes_bin() -> Optional[list[str]]:_PROFILE_ID_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")-def _parse_session_key(session_key: str) -> "dict | None":+def _parse_session_key(session_key: str) -> dict | None:"""Parse a session key (``agent:{ns}:{platform}:{chat_type}:{chat_id}[:{extra}...]``).``{ns}`` is ``main`` for the default profile, ``main~`` for a profile literally named ``main``@@ -3020,7 +3020,7 @@ def _format_concise_process_notification(return text-def _format_gateway_process_notification(evt: dict) -> "str | None":+def _format_gateway_process_notification(evt: dict) -> str | None:"""Format a watch pattern event from completion_queue into a [IMPORTANT:] message."""evt_type = evt.get("type", "completion")_sid = evt.get("session_id", "unknown")@@ -3050,7 +3050,7 @@ def _format_gateway_process_notification(evt: dict) -> "str | None":return None-def _drain_gateway_watch_events(completion_queue) -> "list[dict]":+def _drain_gateway_watch_events(completion_queue) -> list[dict]:"""Drain gateway-owned watch events without spinning on requeued events.Foreign events requeued inside ``while not queue.empty()`` never terminate: detach, then requeue."""watch_events: list[dict] = []@@ -3205,7 +3205,7 @@ def _preserve_queued_followup_history_offset(return {**followup_result, "history_offset": current_offset}-async def _dispose_unused_adapter(adapter: "BasePlatformAdapter | None") -> None:+async def _dispose_unused_adapter(adapter: BasePlatformAdapter | None) -> None:"""Best-effort dispose for an adapter that never made it onto ``self.adapters`` (may be ``None``).Nothing else calls ``disconnect()`` on it, so ``__init__`` resources (e.g. SQLite fds) would leakuntil GC (not prompt for asyncio-bound objects) and exhaust the fd ulimit over a long retry loop.@@ -3403,7 +3403,7 @@ class GatewayRunner(_pending_approvals = legacy_dict_property("_pending_approvals")_update_prompt_pending = legacy_dict_property("_update_prompt_pending")- def _sessions_map(self) -> dict[str, "SessionState"]:+ def _sessions_map(self) -> dict[str, SessionState]:"""Per-session state map; lazily created so bare ``object.__new__`` test runners work."""sessions = self.__dict__.get("_sessions")if sessions is None:@@ -3411,7 +3411,7 @@ class GatewayRunner(self.__dict__["_sessions"] = sessionsreturn sessions- def _session_state(self, session_key: str) -> "SessionState":+ def _session_state(self, session_key: str) -> SessionState:"""Get-or-create the :class:`SessionState` for ``session_key``."""sessions = self._sessions_map()state = sessions.get(session_key)@@ -3420,7 +3420,7 @@ class GatewayRunner(sessions[session_key] = statereturn state- def _peek_session_state(self, session_key: str) -> Optional["SessionState"]:+ def _peek_session_state(self, session_key: str) -> Optional[SessionState]:"""Return the SessionState for ``session_key`` without creating one."""sessions = self.__dict__.get("_sessions")return sessions.get(session_key) if sessions else None@@ -3437,13 +3437,13 @@ class GatewayRunner(# Loop-liveness / watchdog handles; class-level defaults so partially constructed test runners work.# Class-level defaults so partial construction in tests doesn't blow up on access; the real values are# set in __init__ / start() / stop(). See #66892, #69089.- _loop_heartbeat_task: Optional["asyncio.Task"] = None+ _loop_heartbeat_task: Optional[asyncio.Task] = None_loop_floor_timer_handle: Optional[Any] = None_loop_liveness_watchdog: Optional[Any] = None_gateway_started_at: float = 0.0- _shutdown_watchdog_done: Optional["threading.Event"] = None+ _shutdown_watchdog_done: Optional[threading.Event] = None_platform_lock_takeover_on_start: bool = False- _reconnect_watcher_task: Optional["asyncio.Task"] = None+ _reconnect_watcher_task: Optional[asyncio.Task] = Nonedef __init__(self, config: Optional[GatewayConfig] = None):global _gateway_runner_ref@@ -3591,13 +3591,13 @@ class GatewayRunner(self._platform_lock_takeover_on_start = False# Capped LRU of live SessionSources for fallback routing (shutdown notices, synthetic events) when# the persisted origin is missing and _parse_session_key can't recover thread_id.- self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()+ self._session_sources: OrderedDict[str, SessionSource] = OrderedDict()self._session_sources_max = 512# Lifecycle-scoped completion dedup: closes queue/watcher races inside one gateway without claiming# exactly-once across a crash; durable replay state stays owned by tools.async_delegation.self._completion_delivery_lock = threading.Lock()self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()- self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()+ self._completion_deliveries_delivered: OrderedDict[tuple[str, str, object], None] = OrderedDict()self._completion_delivery_retention = 2048# Agent-triggered terminal completions from one conversation often land in the same scheduler# tick; hold them briefly so the agent gets one synthetic turn instead of one per process.@@ -3612,7 +3612,7 @@ class GatewayRunner("""Agent cache, profile identity, Teams runtime, failed-platform tracking, slash-confirm counter."""# AIAgent per session preserves prompt caching (fresh agent per message ~10x cost on Anthropic).# Value: (AIAgent, config_signature); LRU cap in _enforce_agent_cache_cap, TTL in expiry watcher.- self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()+ self._agent_cache: OrderedDict[str, tuple] = OrderedDict()self._agent_cache_lock = threading.Lock()# Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``# compares against this rather than the per-turn ``_active_profile_name()``. A multiplex@@ -3685,7 +3685,7 @@ class GatewayRunner(from gateway.pairing import PairingStorefrom gateway.hooks import ProfileHookRegistriesself.pairing_store = PairingStore()- self.pairing_stores: dict[str, "PairingStore"] = {}+ self.pairing_stores: dict[str, PairingStore] = {}# One HookRegistry per served profile home, resolved from the active scope at emit time.self.hooks = ProfileHookRegistries()# Per-chat voice reply mode: "off" | "voice_only" | "all"@@ -4432,7 +4432,7 @@ class GatewayRunner(getattr(source, "thread_id", None), getattr(source, "parent_chat_id", None))return None- def _resolve_profile_home_for_source(self, source: SessionSource) -> "Path":+ def _resolve_profile_home_for_source(self, source: SessionSource) -> Path:"""Resolve which profile's HERMES_HOME serves this source: the pinned identity's runtimehome, else ``source.profile``, then ``_profile_name_for_source`` (sources bypassing``build_source``), then the active profile."""diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 2afc4b47f7c..4e19825717c 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -71,7 +71,7 @@ class GatewayAdapterLifecycleMixin:"""Adapter lifecycle: connect/teardown, fatal recovery, reconnect watcher, multiplex profiles."""@staticmethod- async def _wait_or_detach(task: "asyncio.Future", timeout: float) -> bool:+ async def _wait_or_detach(task: asyncio.Future, timeout: float) -> bool:"""Wait up to ``timeout`` for ``task``; on deadline (or our own cancellation) detach it. Not``asyncio.wait_for``: that WAITS for the cancelled child, so a connect()/close() swallowing``CancelledError`` blocks recovery forever. True if it finished in time."""@@ -427,7 +427,7 @@ class GatewayAdapterLifecycleMixin:"retry in background.", len(self._failed_platforms),)- def _retain_background_task(self, task: "asyncio.Task") -> "asyncio.Task":+ def _retain_background_task(self, task: asyncio.Task) -> asyncio.Task:"""Register ``task`` in ``_background_tasks`` (created lazily for bare test runners)."""tasks = getattr(self, "_background_tasks", None)if not isinstance(tasks, set):@@ -437,7 +437,7 @@ class GatewayAdapterLifecycleMixin:return task@staticmethod- def _track_task_in(tasks: set, task: "asyncio.Task") -> "asyncio.Task":+ def _track_task_in(tasks: set, task: asyncio.Task) -> asyncio.Task:"""Register ``task`` in an arbitrary lifecycle set with self-removal on completion."""tasks.add(task)task.add_done_callback(tasks.discard)@@ -541,7 +541,7 @@ class GatewayAdapterLifecycleMixin:except Exception:_process_takes_profile = False# In-flight dispatches by session id: a handoff is a FULL agent turn, so never process inline.- inflight: dict[str, "asyncio.Task"] = {}+ inflight: dict[str, asyncio.Task] = {}async def _dispatch(row, session_id, session_db, profile_name) -> None:"""Run one claimed handoff to a terminal state, off the poll path."""@@ -1061,7 +1061,7 @@ class GatewayAdapterLifecycleMixin:from hermes_constants import get_hermes_homepublish_record(ROLE_GATEWAY, profiles=tuple(served), home=str(get_hermes_home()))- async def _load_secondary_profile_config(self, profile_name: str, profile_home: "Path"):+ async def _load_secondary_profile_config(self, profile_name: str, profile_home: Path):"""Hydrate + enter ``profile_home``'s scope once; return its gateway config. Raises``MultiplexConfigError`` (open dm/group policy). Port-binding platforms are NOT refused: thedefault profile owns the single shared listener and a secondary's port-binders are built in@@ -1247,7 +1247,7 @@ class GatewayAdapterLifecycleMixin:return linesasync def _start_one_profile_adapters(- self, profile_name: str, profile_home: "Path", claimed: dict[tuple, str]+ self, profile_name: str, profile_home: Path, claimed: dict[tuple, str]) -> int:"""Create+connect one profile's adapters under its runtime scope."""from gateway.run import _platform_has_bot_credential, _profile_runtime_scopediff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 4dc6b099927..e4e1b5d2f7d 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -102,7 +102,7 @@ class GatewayBusySessionMixin:state = self._peek_session_state(session_key)return state.conversation.queued_events if state else None- def _enqueue_fifo(self, session_key: str, queued_event: "MessageEvent", adapter: Any) -> None:+ def _enqueue_fifo(self, session_key: str, queued_event: MessageEvent, adapter: Any) -> None:"""Append a /queue event to the FIFO chain for a session."""pending_slot = getattr(adapter, "_pending_messages", None) if adapter is not None else Noneif pending_slot is None:@@ -114,8 +114,8 @@ class GatewayBusySessionMixin:queued_event._gateway_accepted = Truedef _promote_queued_event(- self, session_key: str, adapter: Any, pending_event: Optional["MessageEvent"]- ) -> Optional["MessageEvent"]:+ self, session_key: str, adapter: Any, pending_event: Optional[MessageEvent]+ ) -> Optional[MessageEvent]:"""Promote the next overflow item after the slot drained.``pending_event`` None → the overflow head becomes the pending event; otherwise the head is@@ -138,7 +138,7 @@ class GatewayBusySessionMixin:depth += 1return depth- def _rescue_orphaned_overflow(self, session_key: str, adapter: Any) -> Optional["MessageEvent"]:+ def _rescue_orphaned_overflow(self, session_key: str, adapter: Any) -> Optional[MessageEvent]:"""Pop the oldest orphaned FIFO overflow event for an idle session (None if nothing to rescue).``queued_events`` drains only at the post-turn promotion site; a busy window ending without@@ -582,7 +582,7 @@ class GatewayBusySessionMixin:async def _resolve_busy_steer_or_redirect(self, event: MessageEvent, session_key: str, effective_mode: str, running_agent: Any- ) -> "GatewayRunner._BusySteerOutcome":+ ) -> GatewayRunner._BusySteerOutcome:"""Apply interrupt->queue demotions, then attempt steer (steer mode) or redirect (interrupt mode)."""from gateway.run import _AGENT_PENDING_SENTINEL# Steer injects mid-run via running_agent.steer(), falling back to queue (nothing lost) when@@ -1287,7 +1287,7 @@ class GatewayBusySessionMixin:async def _maybe_confirm_destructive_slash(self, *, event: MessageEvent, command: str, title: str, detail: str, execute- ) -> str | "EphemeralReply" | None:+ ) -> str | EphemeralReply | None:"""Gate a destructive session slash command (/new, /reset, /undo).``execute()`` (async → str | EphemeralReply) runs immediately whendiff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex 64519f2c4b7..7d262716a08 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -56,7 +56,7 @@ class GatewayGoalsMixin:except Exception as exc:logger.warning("%s: session DB warm-up failed: %s", label, exc)- async def _session_entry_for_manager(self, event: "MessageEvent", label: str):+ async def _session_entry_for_manager(self, event: MessageEvent, label: str):"""Session entry for a /goal or /heartbeat manager, or None when lookup fails. Warms theSessionDB cache first (a cold cache drops the first write while the reply claims it wasset). Internal events never touch activity (idle/daily reset clock)."""@@ -70,7 +70,7 @@ class GatewayGoalsMixin:return Nonereturn session_entry if getattr(session_entry, "session_id", None) else None- async def _manager_for_event(self, event: "MessageEvent", kind: str, load):+ async def _manager_for_event(self, event: MessageEvent, kind: str, load):"""``(manager, session_entry)`` for *kind* ("goal"/"heartbeat"), or ``(None, None)``.``load()`` imports the manager class and returns a ``session_id -> manager`` factory."""try:@@ -83,7 +83,7 @@ class GatewayGoalsMixin:return None, Nonereturn factory(session_entry.session_id), session_entry- async def _get_goal_manager_for_event(self, event: "MessageEvent"):+ async def _get_goal_manager_for_event(self, event: MessageEvent):"""Return ``(GoalManager, session_entry)`` for this event, or ``(None, None)``."""def _load():from hermes_cli.goals import GoalManager@@ -91,7 +91,7 @@ class GatewayGoalsMixin:return lambda sid: GoalManager(session_id=sid, default_max_turns=max_turns)return await self._manager_for_event(event, "goal", _load)- async def _get_heartbeat_manager_for_event(self, event: "MessageEvent"):+ async def _get_heartbeat_manager_for_event(self, event: MessageEvent):"""Return ``(HeartbeatManager, session_entry)`` for this event, or ``(None, None)``."""def _load():from hermes_cli.heartbeat import HeartbeatManagerdiff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 65ba2b9b2d0..888d40e2bb3 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -71,8 +71,8 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):"""Inbound message pipeline (_handle_message, text/media preparation, durable-turn markers, plugin injection) for GatewayRunner."""async def _hm_pre_gateway_dispatch_hook(- self, event: "MessageEvent", source: SessionSource- ) -> Optional["MessageEvent"]:+ self, event: MessageEvent, source: SessionSource+ ) -> Optional[MessageEvent]:"""Run the ``pre_gateway_dispatch`` plugin hook; None = drop, else the (maybe rewritten) event.Results: ``{"action": "skip"}`` → drop; ``{"action": "rewrite", "text"}`` → replace ``event.text``;``allow``/None → normal dispatch. Runs BEFORE auth so plugins can handle unauthorized senders."""@@ -165,8 +165,8 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):await notifier.notify(self, source, hint)async def _hm_admit_event(- self, event: "MessageEvent"- ) -> Optional[tuple["MessageEvent", SessionSource, bool]]:+ self, event: MessageEvent+ ) -> Optional[tuple[MessageEvent, SessionSource, bool]]:"""Ingress gates for ``_handle_message``; None when dropped, else ``(event, source, is_internal)``(the ``pre_gateway_dispatch`` hook may have rewritten ``event``)."""from gateway.run import _is_slack_ignored_channel@@ -260,7 +260,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return Nonereturn event, source, False- def _hm_estop_turn_allowed(self, event: "MessageEvent", source: SessionSource) -> bool:+ def _hm_estop_turn_allowed(self, event: MessageEvent, source: SessionSource) -> bool:"""Whether a turn may bypass the global emergency stop: pause blocks NEW agent turns, neverrunning work or control traffic — recognized slash commands (incl. /pause off, the in-bandresume) and replies owned by in-flight work (pending update prompt, running session,@@ -288,7 +288,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return Falsedef _hm_estop_gate(- self, event: "MessageEvent", source: SessionSource, is_internal: bool+ self, event: MessageEvent, source: SessionSource, is_internal: bool) -> Optional[str]:"""Global emergency-stop (`hermes pause`) notice when this turn must be blocked, else None.Placed after auth so unauthorized senders can't probe pause state. A synthetic heartbeat that@@ -327,7 +327,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return str(e)return None- def _hm_update_prompt_reply(self, event: "MessageEvent", _quick_key: str) -> Optional[str]:+ def _hm_update_prompt_reply(self, event: MessageEvent, _quick_key: str) -> Optional[str]:"""Consume a reply to a pending ``/update`` prompt (routed to the detached update process via``.update_response``); None when nothing was consumed. Recognized slash commands must bypassthis or /new, /help etc. get silently consumed as update answers."""@@ -373,7 +373,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return Noneasync def _hm_clarify_reply(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> Optional[str]:"""Intercept a reply to a pending clarify prompt; None when the message falls through.Free text answers open-ended/"Other" prompts; "2" answers a multi-choice one. Resolved/retained@@ -468,7 +468,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):choices.setdefault(word, choice)return choices- async def _hm_slash_confirm_reply(self, event: "MessageEvent", _quick_key: str) -> Optional[str]:+ async def _hm_slash_confirm_reply(self, event: MessageEvent, _quick_key: str) -> Optional[str]:"""Resolve a reply (/approve, /always, /cancel + aliases) to a pending slash-confirm prompt;None when it falls through — a stale pending confirm does NOT block other commands. A pendingdangerous-command approval takes precedence: /approve there unblocks the waiting tool thread."""@@ -581,7 +581,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):self._drop_turn_slot(_quick_key, run_generation=_generation_at_interrupt)def _hm_merge_pending_for_source(- self, source: SessionSource, _quick_key: str, event: "MessageEvent", *, merge_text: bool = False+ self, source: SessionSource, _quick_key: str, event: MessageEvent, *, merge_text: bool = False) -> None:"""Merge *event* into the source adapter's pending slot (no-op without an adapter)."""from gateway.platforms.base import merge_pending_message_event@@ -590,7 +590,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):merge_pending_message_event(adapter._pending_messages, _quick_key, event, merge_text=merge_text)async def _hm_busy_slash_or_photo(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> tuple[bool, Optional[str]]:"""Slash-command / photo-burst handling on the busy fast-path → ``(handled, result)``. Eachcommand's mid-run behavior is declared on its CommandDef (busy_policy / busy_handler)."""@@ -622,7 +622,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return False, Nonedef _hm_busy_telegram_grace_queue(- self, event: "MessageEvent", source: SessionSource, _quick_key: str, effective_busy_input_mode: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str, effective_busy_input_mode: str) -> bool:"""Queue a Telegram text follow-up that lands within the post-start grace window."""_grace = float(os.getenv("HERMES_TELEGRAM_FOLLOWUP_GRACE_SECONDS", "3.0"))@@ -646,10 +646,10 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return True@staticmethod- def _hm_text_only(event: "MessageEvent") -> bool:+ def _hm_text_only(event: MessageEvent) -> bool:return event.message_type == MessageType.TEXT and not event.media_urls and not event.media_types- def _hm_busy_steer(self, event: "MessageEvent", running_agent: Any, _quick_key: str) -> None:+ def _hm_busy_steer(self, event: MessageEvent, running_agent: Any, _quick_key: str) -> None:"""Steer mode: inject text mid-run via ``agent.steer()``, else fall back to queue semantics."""steer_text = (event.text or "").strip()steered = False@@ -666,7 +666,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):self._queue_or_replace_pending_event(_quick_key, event)async def _hm_busy_interrupt(- self, event: "MessageEvent", source: SessionSource, running_agent: Any, _quick_key: str+ self, event: MessageEvent, source: SessionSource, running_agent: Any, _quick_key: str) -> None:"""Interrupt path: redirect text-only corrections when supported, else ``agent.interrupt()``."""from gateway.run import _build_media_placeholder@@ -691,7 +691,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):running_agent.interrupt(_interrupt_text)async def _hm_handle_running_session_message(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> Optional[str]:"""Fast-path while this session's agent is running: interrupt by default (minimal latency);busy_input_mode queue/steer, subagent and compression protection demote to queue."""@@ -751,7 +751,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return qc if isinstance(qc, dict) else {}@staticmethod- def _hm_expand_alias_quick_command(event: "MessageEvent", qcmd: dict) -> Optional[str]:+ def _hm_expand_alias_quick_command(event: MessageEvent, qcmd: dict) -> Optional[str]:"""Rewrite ``event.text`` to an alias quick command's target; returns the new command name."""target = (qcmd.get("target") or "").strip()if not target:@@ -762,7 +762,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return target_command.split()[0] if target_command else target_commandasync def _hm_command_hooks(- self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str, canonical: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str, command: str, canonical: str) -> tuple[bool, Optional[str], Optional[str]]:"""Fire ``pre_command`` (observer) and ``command:<canonical>`` (interceptor) hooks →``(handled, result, new_command)`` (``new_command`` set when a handler rewrote the command).@@ -809,7 +809,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return False, None, Noneasync def _hm_resolve_command(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:"""Resolve the slash command (aliases, access gate, hooks) → ``(handled, result, command,canonical)``; when ``handled`` the caller returns ``result`` as-is (may be None)."""@@ -1008,7 +1008,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):})async def _hm_dispatch_canonical_command(- self, event: "MessageEvent", source: SessionSource, _quick_key: str,+ self, event: MessageEvent, source: SessionSource, _quick_key: str,canonical: Optional[str],) -> tuple[bool, Optional[str]]:"""Dispatch built-in idle-path commands → ``(handled, result)``; prompt-rewriting commands@@ -1045,7 +1045,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return t("gateway.quick_command.error", error=e)async def _hm_dispatch_quick_and_plugin_commands(- self, event: "MessageEvent", source: SessionSource, command: Optional[str]+ self, event: MessageEvent, source: SessionSource, command: Optional[str]) -> tuple[bool, Optional[str], Optional[str]]:"""Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →``(handled, result, command)``; an alias quick command rewrites ``command``."""@@ -1105,7 +1105,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return False, None, commanddef _hm_bundle_slash_rewrite(- self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str, command: str) -> bool:"""Rewrite ``/<bundle>`` to the bundle invocation message; True when handled.Skill bundles take precedence over individual skill commands (mirrors CLI dispatch)."""@@ -1156,7 +1156,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return t("gateway.unknown_command", command=command)def _hm_skill_slash_rewrite(- self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: Optional[str]+ self, event: MessageEvent, source: SessionSource, _quick_key: str, command: Optional[str]) -> Optional[str]:"""Rewrite ``/<bundle>`` / ``/<skill>`` invocations into the skill prompt on ``event.text``;returns a reply string when the command is disabled/unknown/failed, else None.@@ -1217,7 +1217,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return Noneasync def _hm_pending_reply_intercepts(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> Optional[str]:"""Replies owned by in-flight work: pending /update prompt, clarify, slash-confirm.Only events that may control the gateway (``allow_gateway_control``) can answer them."""@@ -1231,7 +1231,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return _replyasync def _hm_dispatch_idle_commands(- self, event: "MessageEvent", source: SessionSource, _quick_key: str+ self, event: MessageEvent, source: SessionSource, _quick_key: str) -> tuple[bool, Optional[str]]:"""Idle path: resolve + dispatch slash commands; rewriting commands fall through to the agent."""_handled, _result, command, canonical = await self._hm_resolve_command(event, source, _quick_key)@@ -1250,8 +1250,8 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):return _handled, _resultdef _hm_rescue_orphaned_fifo(- self, event: "MessageEvent", source: SessionSource, is_internal: bool, _quick_key: str- ) -> tuple["MessageEvent", SessionSource, bool]:+ self, event: MessageEvent, source: SessionSource, is_internal: bool, _quick_key: str+ ) -> tuple[MessageEvent, SessionSource, bool]:"""FIFO orphan rescue: a session that went idle with a populated overflow (post-turn drainnever promoted, e.g. a compression-demoted follow-up) silently orphaned those events. Theoldest orphan runs as THIS turn and the incoming event is parked behind the chain. Skipped@@ -1765,7 +1765,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):state.persistent.native_image_paths = []return paths- async def _mark_durable_active_turn(self, event: "MessageEvent", session_key: str) -> bool:+ async def _mark_durable_active_turn(self, event: MessageEvent, session_key: str) -> bool:"""Persist the exact resolved routing key for this running turn."""try:token = await self.async_session_store.mark_turn_active(session_key)@@ -1780,7 +1780,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):event._gateway_active_turn_token = tokenreturn True- async def _clear_durable_active_turn(self, event: "MessageEvent") -> bool:+ async def _clear_durable_active_turn(self, event: MessageEvent) -> bool:"""Best-effort CAS clear of the marker owned by *event* (3 attempts; never blocks agent/leaserelease — a stale marker is bounded by the agent timeout and clean-start discard)."""session_key = getattr(event, "_gateway_active_turn_session_key", None)diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 177d000049b..bf0a9b949a9 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -519,7 +519,7 @@ class GatewayNotificationsMixin:logger.debug("Skipping update notification watcher: no running event loop")@classmethod- def _update_paths(cls) -> "GatewayNotificationsMixin._UpdatePaths":+ def _update_paths(cls) -> GatewayNotificationsMixin._UpdatePaths:from gateway.run import _hermes_homereturn cls._UpdatePaths(pending=_hermes_home / ".update_pending.json",@@ -560,7 +560,7 @@ class GatewayNotificationsMixin:now = datetime.now(stamped.tzinfo) if stamped.tzinfo else datetime.now()return (now - stamped).total_seconds()- def _resolve_update_target(self, paths: "_UpdatePaths") -> Optional["_UpdateTarget"]:+ def _resolve_update_target(self, paths: _UpdatePaths) -> Optional[_UpdateTarget]:"""Resolve adapter/chat/session for update watcher messages from the pending marker."""for path in (paths.claimed, paths.pending):if not path.exists():@@ -592,7 +592,7 @@ class GatewayNotificationsMixin:reply_to_message_id=data.get("message_id"), adapter=adapter,)- async def _watch_update_completion_only(self, paths: "_UpdatePaths", deadline: float, poll_interval: float) -> None:+ async def _watch_update_completion_only(self, paths: _UpdatePaths, deadline: float, poll_interval: float) -> None:"""Fallback when no adapter/chat can be resolved: wait for the exit code, then notify."""logger.warning("Update watcher: cannot resolve adapter/chat_id, falling back to completion-only")# Poll until _send_update_notification delivers (it returns False while the platform reconnects).@@ -606,7 +606,7 @@ class GatewayNotificationsMixin:await self._send_update_notification()@staticmethod- def _update_exit_code(paths: "_UpdatePaths") -> int:+ def _update_exit_code(paths: _UpdatePaths) -> int:return int(paths.exit_code.read_text(encoding="utf-8-sig").strip() or "1")@staticmethod@@ -620,7 +620,7 @@ class GatewayNotificationsMixin:return "", len(data)return data[offset:].decode("utf-8", errors="replace"), len(data)- async def _send_update_output(self, target: "_UpdateTarget", text: str) -> None:+ async def _send_update_output(self, target: _UpdateTarget, text: str) -> None:"""Send buffered update output as fenced chunks that fit message limits (Telegram: 4096)."""from tools.ansi_strip import strip_ansiclean = strip_ansi(text).strip()@@ -631,7 +631,7 @@ class GatewayNotificationsMixin:with _log_suppressed(logging.DEBUG, "Update stream send failed: %s"):await target.send(f"```\n{clean[i:i + max_chunk]}\n```")- async def _forward_update_prompt(self, target: "_UpdateTarget", prompt_text: str, default: str) -> None:+ async def _forward_update_prompt(self, target: _UpdateTarget, prompt_text: str, default: str) -> None:"""Forward an update prompt: platform-native buttons first (Discord, Telegram), else text."""sent_buttons = Falseadapter = target.adapter@@ -650,7 +650,7 @@ class GatewayNotificationsMixin:self._session_state(target.session_key).persistent.update_prompt_pending = Truelogger.info("Forwarded update prompt to %s: %s", target.session_key, prompt_text[:80])- def _clear_update_markers(self, paths: "_UpdatePaths", session_key: Optional[str]) -> None:+ def _clear_update_markers(self, paths: _UpdatePaths, session_key: Optional[str]) -> None:paths.unlink_all()state = self._peek_session_state(session_key)if state is not None:@@ -1480,7 +1480,7 @@ class GatewayNotificationsMixin:return Falsereturn True- async def _preflight_completion_delivery(self, evt: dict) -> "_CompletionClaim":+ async def _preflight_completion_delivery(self, evt: dict) -> _CompletionClaim:"""Claim the durable row (async delegations) and verify the target before adapter acceptance.Adapter acceptance is not proof of delivery: the inner resolver can still fail closed insidediff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex 66fa0df87a3..c22e839725f 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -34,7 +34,7 @@ _PROFILE_SIGNATURE_FILES = ("config.yaml", ".env")_OWN_GATEWAY_PROBE_TIMEOUT_SECS = 5.0-def profile_serve_signature(home: "Path") -> tuple:+def profile_serve_signature(home: Path) -> tuple:"""Cheap change detector for a served profile's credentials/config: file signature per file."""sig = []for name in _PROFILE_SIGNATURE_FILES:@@ -49,7 +49,7 @@ def profile_serve_signature(home: "Path") -> tuple:class GatewayProfileReconcileMixin:"""Runtime reconciliation of the multiplexed served-profile set (hot add / unroute / credential-add)."""- _served_profile_homes: Optional[dict[str, "Path"]] = None+ _served_profile_homes: Optional[dict[str, Path]] = None_served_profile_signatures: Optional[dict[str, tuple]] = None_profile_reconcile_lock: Optional[asyncio.Lock] = None_profile_own_gateway_warned: Optional[set[str]] = None@@ -239,7 +239,7 @@ class GatewayProfileReconcileMixin:except Exception:logger.warning("MCP tool discovery failed for profile '%s'", profile_name, exc_info=True)- async def _unserve_profile(self, name: str, home: "Path") -> None:+ async def _unserve_profile(self, name: str, home: Path) -> None:"""Stop and unroute one profile: cancel its reconnects, tear down its adapters, drop itsbookkeeping and release this process's handles into its home so the deleter's rmtree succeeds.The releasing process is not always the deleter (#130244): under multiplexing THIS gatewaydiff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex e04dfc23ab0..7c04fc4dd1b 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1837,7 +1837,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):GatewayShutdownMixin._stop_kill_tool_subprocesses, phase)- async def _stop_begin_teardown(self, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_begin_teardown(self, ctx: GatewayShutdownMixin._StopContext) -> None:"""Flag teardown, stop room worker/watchdog, notify sessions."""logger.info("Stopping gateway%s...", " for restart" if self._restart_requested else "")ctx.started_at = time.monotonic()@@ -1866,7 +1866,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):await self._notify_active_sessions_of_shutdown()logger.info("Shutdown phase: notify_active_sessions done at +%.2fs", ctx.elapsed())- async def _stop_drain_active_work(self, timeout: float, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_drain_active_work(self, timeout: float, ctx: GatewayShutdownMixin._StopContext) -> None:"""Pre-mark resume_pending, drain agents/cron/API work into ``ctx``."""from gateway.run import GatewayRunner# Pre-mark resume_pending BEFORE the drain so a mid-drain SIGKILL still leaves a durable marker.@@ -1915,7 +1915,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):except Exception as _e:logger.debug("clear_resume_pending after drain failed for %s: %s", _sk, _e)- async def _stop_interrupt_remaining_work(self, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_interrupt_remaining_work(self, ctx: GatewayShutdownMixin._StopContext) -> None:"""Drain timed out: mark resume_pending, interrupt, settle, kill tool subprocesses, notify cron."""from gateway.run import GatewayRunnerlogger.warning(@@ -1957,7 +1957,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):await self._notify_interrupted_cron_jobs(_interrupted_cron_jobs)logger.info("Shutdown phase: cron interrupt notices done at +%.2fs", ctx.elapsed())- async def _stop_finalize_agents_and_adapters(self, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_finalize_agents_and_adapters(self, ctx: GatewayShutdownMixin._StopContext) -> None:"""Detached restart launch, agent finalization, idle-cache cleanup, adapter teardown."""if self._restart_requested and self._restart_detached:with _log_suppressed(logging.ERROR, "Failed to launch detached gateway restart: %s"):@@ -1991,7 +1991,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):_profile_adapters.clear()logger.info("Shutdown phase: all adapters disconnected at +%.2fs", ctx.elapsed())- async def _stop_release_runtime_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_release_runtime_state(self, ctx: GatewayShutdownMixin._StopContext) -> None:"""Cancel background tasks, flush pending messages, clear per-session state, final tool kill."""from gateway.run import GatewayRunnerfor _task in list(self._background_tasks):@@ -2043,7 +2043,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):GatewayShutdownMixin._quiet_step("shutdown_cached_clients error", _reap_aux_clients)- def _stop_quiesce_and_close_session_dbs(self, timeout: float, ctx: "GatewayShutdownMixin._StopContext") -> None:+ def _stop_quiesce_and_close_session_dbs(self, timeout: float, ctx: GatewayShutdownMixin._StopContext) -> None:"""Quiesce the executor, then close SessionDB handles only if no worker is still live."""from gateway.run import GatewayRunner, _EXECUTOR_QUIESCE_TIMEOUT# Quiesce the thread pool BEFORE closing session DBs: a late executor write after@@ -2122,7 +2122,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):_step("Shared SessionDB close error", _close_shared)logger.info("Shutdown phase: SessionDB close done at +%.2fs", ctx.elapsed())- async def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:+ async def _stop_persist_exit_state(self, ctx: GatewayShutdownMixin._StopContext) -> None:"""PID/lock release, clean-shutdown marker, restart markers, terminal runtime status."""from gateway.run import _hermes_home, _planned_restart_notification_path, _shutdown_gateway_health_exportfrom utils import atomic_json_write@@ -2185,7 +2185,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):_shutdown_gateway_health_export(self)logger.info("Gateway stopped (total teardown %.2fs)", ctx.elapsed())- def _shutdown_watchdog_snapshot(self, ctx: "GatewayShutdownMixin._StopContext") -> dict:+ def _shutdown_watchdog_snapshot(self, ctx: GatewayShutdownMixin._StopContext) -> dict:"""State dumped by the thread-based shutdown watchdog when teardown hangs."""return {"restart_requested": bool(self._restart_requested),diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 622a22f1791..071330e0ab2 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -273,7 +273,7 @@ class GatewayStartupMixin:"""Done-callback for boot-path tasks that outlive the startup-restore gate: surface a latefailure otherwise swallowed once the task leaves ``_background_tasks``. Cancellation isexpected (shutdown), not an error."""- def _report(task: "asyncio.Task") -> None:+ def _report(task: asyncio.Task) -> None:if task.cancelled():returnexc = task.exception()@@ -1715,7 +1715,7 @@ class GatewayStartupMixin:async def _handoff_resolve_destination(self, row: dict[str, Any], profile_name: Optional[str]- ) -> "GatewayStartupMixin._HandoffDestination":+ ) -> GatewayStartupMixin._HandoffDestination:"""Resolve platform, transport, home channel, thread and destination source for a row."""from gateway.delivery import resolve_delivery_transportcli_session_id = row["id"]diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 593078cafe4..bcfd8e18fc4 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -2374,7 +2374,7 @@ class GatewayTurnMixin:return "\n".join(lines)async def _run_background_task(- self, prompt: str, source: "SessionSource", task_id: str,+ self, prompt: str, source: SessionSource, task_id: str,event_message_id: Optional[str] = None, media_urls: Optional[list[str]] = None,media_types: Optional[list[str]] = None,) -> None:@@ -2385,7 +2385,7 @@ class GatewayTurnMixin:)def _resolve_enabled_toolsets_for_source(- self, user_config: dict, source: "SessionSource", platform_key: str,+ self, user_config: dict, source: SessionSource, platform_key: str,) -> list:"""Enabled toolsets for an agent run, honoring an adapter ``toolsets_for_source()`` overridevalidated through the SAME ``_get_platform_tools`` path (unknown / platform-restricted@@ -2402,7 +2402,7 @@ class GatewayTurnMixin:user_config = {**user_config, "platform_toolsets": pts}return sorted(_get_platform_tools(user_config, platform_key))- def _resolve_turn_toolsets(self, user_config: dict, source: "SessionSource", platform_key: str):+ def _resolve_turn_toolsets(self, user_config: dict, source: SessionSource, platform_key: str):"""``(enabled_toolsets, disabled_toolsets)`` for an agent run on ``source``."""from agent.skill_utils import parse_config_string_listenabled = self._resolve_enabled_toolsets_for_source(user_config, source, platform_key)@@ -2410,7 +2410,7 @@ class GatewayTurnMixin:return enabled, disabledasync def _run_background_task_inner(- self, prompt: str, source: "SessionSource", task_id: str,+ self, prompt: str, source: SessionSource, task_id: str,event_message_id: Optional[str] = None, media_urls: Optional[list[str]] = None,media_types: Optional[list[str]] = None,) -> None:@@ -2668,8 +2668,8 @@ class GatewayTurnMixin:return url.rstrip("/") if url else Nonedef _build_stream_consumer_config(- self, source: "SessionSource", scfg: Any, adapter: Any, *, on_missing_cursor: str,- ) -> "tuple[Any, Optional[Callable[[], None]]]":+ self, source: SessionSource, scfg: Any, adapter: Any, *, on_missing_cursor: str,+ ) -> tuple[Any, Optional[Callable[[], None]]]:"""Build the shared ``StreamConsumerConfig`` and optional Telegram pause-typing closure.For non-editing adapters ``on_missing_cursor="fallback"`` streams with an empty cursor;``"raise"`` raises ``RuntimeError`` so the caller skips streaming entirely."""@@ -2716,7 +2716,7 @@ class GatewayTurnMixin:def _proxy_error_result(text: str) -> dict[str, Any]:return {"final_response": text, "messages": [], "api_calls": 0, "tools": []}- def _proxy_stream_consumer(self, source: "SessionSource", event_message_id, _thread_metadata, _run_still_current):+ def _proxy_stream_consumer(self, source: SessionSource, event_message_id, _thread_metadata, _run_still_current):"""Platform stream consumer for the proxy path when streaming is enabled, else ``None``."""from gateway.run import _load_gateway_config, _platform_config_key_scfg = getattr(getattr(self, "config", None), "streaming", None)@@ -2752,7 +2752,7 @@ class GatewayTurnMixin:async def _run_agent_via_proxy(self, message: str, context_prompt: str, history: list[dict[str, Any]],- source: "SessionSource", session_id: str, session_key: str | None = None,+ source: SessionSource, session_id: str, session_key: str | None = None,run_generation: Optional[int] = None, event_message_id: Optional[str] = None,scheduled_heartbeat: bool = False,) -> dict[str, Any]:@@ -2934,7 +2934,7 @@ class GatewayTurnMixin:with self._profile_scope_for_source(source):return await self._run_agent_inner(message, context_prompt, history, source, session_id, **turn_kwargs)- def _run_agent_display_settings(self, source: SessionSource) -> "GatewayRunner._RunAgentDisplay":+ def _run_agent_display_settings(self, source: SessionSource) -> GatewayRunner._RunAgentDisplay:"""Resolve per-platform display, progress, status and streaming-surface settings for a turn."""from gateway.run import (_gateway_platform_value, _has_platform_display_override, _load_gateway_config,@@ -3059,7 +3059,7 @@ class GatewayTurnMixin:)def _run_agent_build_turn_context(- self, disp: "GatewayRunner._RunAgentDisplay", AIAgent: Any, *, message: str, source: SessionSource,+ self, disp: GatewayRunner._RunAgentDisplay, AIAgent: Any, *, message: str, source: SessionSource,session_key: Optional[str], run_generation: Optional[int], **turn_params,) -> tuple[TurnContext, TurnRunner, Any]:"""Build the ``TurnContext`` and its ``TurnRunner``; ``turn_params`` (history, context_prompt,@@ -3296,7 +3296,7 @@ class GatewayTurnMixin:async def _run_agent_fire_pending_interrupt(self, adapter: Any, agent: Any, source: SessionSource, session_key: str,- _interrupt_detected: "asyncio.Event", streaming_tts_consumer_holder: list, *,+ _interrupt_detected: asyncio.Event, streaming_tts_consumer_holder: list, *,log_context: str, log: Callable[[], None],) -> None:"""Peek the adapter's pending event, transcribe voice, then signal the agent + abort streaming TTS.@@ -3332,7 +3332,7 @@ class GatewayTurnMixin:if _stts is not None:_stts.abort("barge-in")- async def _run_agent_monitor_for_interrupt(self, turn_ctx: TurnContext, _interrupt_detected: "asyncio.Event") -> None:+ async def _run_agent_monitor_for_interrupt(self, turn_ctx: TurnContext, _interrupt_detected: asyncio.Event) -> None:"""Poll the adapter for interrupts (new messages) every 200ms and signal the agent.Level 1 (base.py) catches regular text before _handle_message(); the inactivity poll loop@@ -3363,7 +3363,7 @@ class GatewayTurnMixin:logger.debug("monitor_for_interrupt error (will retry): %s", _mon_err)async def _run_agent_backup_interrupt_check(- self, turn_ctx: TurnContext, _interrupt_detected: "asyncio.Event", interrupt_monitor: "asyncio.Task",+ self, turn_ctx: TurnContext, _interrupt_detected: asyncio.Event, interrupt_monitor: asyncio.Task,) -> None:"""Backup interrupt check: if the monitor task died or missed the interrupt, catch it here."""source, session_key = turn_ctx.source, turn_ctx.session_key@@ -3413,7 +3413,7 @@ class GatewayTurnMixin:return Falsereturn False- def _run_agent_start_turn_worker(self, turn_ctx: TurnContext, run_sync: Callable[[], Any]) -> "GatewayRunner._RunAgentWorker":+ def _run_agent_start_turn_worker(self, turn_ctx: TurnContext, run_sync: Callable[[], Any]) -> GatewayRunner._RunAgentWorker:"""Schedule ``run_sync`` on the executor plus the inactivity watchdog thread.*Inactivity* timeout (agent.gateway_timeout / HERMES_AGENT_TIMEOUT, env wins; 0 = unlimited),@@ -3481,7 +3481,7 @@ class GatewayTurnMixin:return worker@staticmethod- def _reaper_kwargs(worker: "GatewayRunner._RunAgentWorker") -> dict:+ def _reaper_kwargs(worker: GatewayRunner._RunAgentWorker) -> dict:"""Shared kwargs of the watchdog + timeout-reaper threads."""return {**{k: getattr(worker, k) for k in ("task_id", "process_baseline", "worker_done", "timeout_fired", "cleanup_lock")},@@ -3556,8 +3556,8 @@ class GatewayTurnMixin:}async def _run_agent_await_turn_worker(- self, worker: "GatewayRunner._RunAgentWorker", turn_ctx: TurnContext,- _interrupt_detected: "asyncio.Event", interrupt_monitor: "asyncio.Task",+ self, worker: GatewayRunner._RunAgentWorker, turn_ctx: TurnContext,+ _interrupt_detected: asyncio.Event, interrupt_monitor: asyncio.Task,) -> Any:"""Poll the executor future (inactivity timeout + backup interrupt checks); return its result,or a synthetic failed run dict on inactivity timeout. Polls even with an unlimited timeout@@ -3977,8 +3977,8 @@ class GatewayTurnMixin:return mergedasync def _run_agent_cleanup_turn_tasks(- self, turn_ctx: TurnContext, *, progress_task: Any, log_task: Any, interrupt_monitor: "asyncio.Task",- _notify_task: "asyncio.Task", tracking_task: "asyncio.Task", stream_task: Any,+ self, turn_ctx: TurnContext, *, progress_task: Any, log_task: Any, interrupt_monitor: asyncio.Task,+ _notify_task: asyncio.Task, tracking_task: asyncio.Task, stream_task: Any,) -> None:"""``finally`` half of a turn: cancel background tasks, flush stream, release the session slot."""stream_consumer_holder, session_key = turn_ctx.stream_consumer_holder, turn_ctx.session_key@@ -4188,7 +4188,7 @@ class GatewayTurnMixin:return _status_thread_metadataasync def _run_agent_notify_long_running(- self, disp: "GatewayRunner._RunAgentDisplay", turn_ctx: TurnContext, _executor_task_holder: list,+ self, disp: GatewayRunner._RunAgentDisplay, turn_ctx: TurnContext, _executor_task_holder: list,) -> None:"""Periodic "still working" heartbeat, edited in place where supported. Stops once this runno longer owns the session slot or the executor finished. ``_executor_task_holder[0]`` isdiff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex c822f988455..7e29a4cdf8c 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -78,7 +78,7 @@ class _ExecApprovalDeclined(RuntimeError):class TurnRunner:"""Per-turn collaborator carrying ``GatewayRunner._run_agent_inner``'s tool-progress callbacks."""- def __init__(self, runner: "GatewayRunner", ctx: TurnContext) -> None:+ def __init__(self, runner: GatewayRunner, ctx: TurnContext) -> None:self._runner = runnerself._ctx = ctx@@ -546,7 +546,7 @@ class TurnRunner:_PROGRESS_TEXT_LIMIT: int_edit_accepts_metadata: bool- def _progress_edit_state(self, adapter) -> "TurnRunner._ProgressEditState":+ def _progress_edit_state(self, adapter) -> TurnRunner._ProgressEditState:ctx = self._ctxlen_fn = adapter.message_len_fn if isinstance(adapter, BasePlatformAdapter) else lentry:diff --git a/gateway/session.py b/gateway/session.pyindex 3c016b53271..eb77ed128f1 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -147,7 +147,7 @@ class SessionSource:return d@classmethod- def from_dict(cls, data: dict[str, Any]) -> "SessionSource":+ def from_dict(cls, data: dict[str, Any]) -> SessionSource:plain = {name: data.get(name)for name in cls._ALWAYS_FIELDS[1:] + cls._OPTIONAL_PRE_SCOPE + cls._OPTIONAL_POST_SCOPE + cls._OPTIONAL_TAIL@@ -580,7 +580,7 @@ class SessionEntry:return result@classmethod- def from_dict(cls, data: dict[str, Any]) -> "SessionEntry":+ def from_dict(cls, data: dict[str, Any]) -> SessionEntry:origin = data.get("origin")origin = SessionSource.from_dict(origin) if isinstance(origin, dict) else Noneplatform = None@@ -621,7 +621,7 @@ class SessionEntry:)-def build_channel_continuity_note(entry: "SessionEntry", source: SessionSource) -> Optional[str]:+def build_channel_continuity_note(entry: SessionEntry, source: SessionSource) -> Optional[str]:"""One-line continuity hint for long-lived Slack/Discord channels/threads.After an auto-reset the agent could bind a new request to an unrelated recent session; this@@ -729,7 +729,7 @@ def build_session_key(class _SessionFlight:def __init__(self) -> None:self.event = threading.Event()- self.result: Optional["SessionEntry"] = None+ self.result: Optional[SessionEntry] = Noneself.error: Optional[BaseException] = None@@ -745,7 +745,7 @@ class _RouteChecks:@dataclassclass _RouteDecision:"""What the locked apply-phase decided for one routing transition."""- entry: Optional["SessionEntry"] = None+ entry: Optional[SessionEntry] = Noneneeds_save: bool = False# Healthy-path saves take the single-row UPSERT fast path; structural# transitions (recover/create) keep the full rewrite.@@ -757,7 +757,7 @@ class _RouteDecision:reset_had_activity: bool = Falseprev_session_id: Optional[str] = None- def schedule_reset(self, reason: str, ended: "SessionEntry", had_activity: bool) -> None:+ def schedule_reset(self, reason: str, ended: SessionEntry, had_activity: bool) -> None:"""Record that *ended* is auto-reset for *reason* (ends its row, seeds the successor)."""self.reset_reason = reasonself.reset_had_activity = had_activity@@ -767,7 +767,7 @@ class _RouteDecision:class AsyncSessionStore:"""Async boundary for the synchronous, thread-safe SessionStore."""- def __init__(self, store: "SessionStore") -> None:+ def __init__(self, store: SessionStore) -> None:self._store = storedef __getattr__(self, name: str):diff --git a/gateway/session_identity.py b/gateway/session_identity.pyindex aba8789b506..7285aa2aa66 100644--- a/gateway/session_identity.py+++ b/gateway/session_identity.py@@ -111,7 +111,7 @@ def transport_profile_of(source: Any) -> Optional[str]:return identity.transport_profile if identity is not None and identity.multiplexed else None-def replace_source(source: "SessionSource", **changes: Any) -> "SessionSource":+def replace_source(source: SessionSource, **changes: Any) -> SessionSource:""":func:`dataclasses.replace` that keeps the wire-invisible provenance (transport ref,authorization home, identity). A plain ``replace`` silently produces a source the runnercan only route through heuristics."""@@ -129,7 +129,7 @@ def _name(value: Any) -> Optional[str]:def canonical_identity(- source: "SessionSource", *, runner: Any, adapter: Any = None,+ source: SessionSource, *, runner: Any, adapter: Any = None,transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,) -> Optional[RoutingIdentity]:"""The identity already pinned on *source*, else :func:`resolve_identity` — the one call every@@ -149,7 +149,7 @@ def canonical_identity(def restore_identity(- source: "SessionSource", *, runner: Any, transport_profile: Optional[str],+ source: SessionSource, *, runner: Any, transport_profile: Optional[str],) -> Optional[RoutingIdentity]:"""Pin the identity of a source rebuilt from durable state (``SessionEntry.origin``, a``sessions`` row, a cached copy) — no live adapter, so ``transport=None``: the restored row of the@@ -189,7 +189,7 @@ def restore_identity(def resolve_identity(- source: "SessionSource", *, runner: Any, adapter: Any = None,+ source: SessionSource, *, runner: Any, adapter: Any = None,transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,) -> RoutingIdentity:"""Resolve and pin the :class:`RoutingIdentity` of an inbound *source*.diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex 52199d02d29..efdf599d8fe 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -120,7 +120,7 @@ class SessionTranscriptMixin:return session_iddef _heal_compression_tip_locked(- self, entry: "SessionEntry", original_session_id: Optional[str],+ self, entry: SessionEntry, original_session_id: Optional[str],canonical_session_id: Optional[str]) -> bool:"""Rewrite *entry* to the compression continuation if stale. Lock held."""if not original_session_id or not canonical_session_id:diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 061f3f3ba75..67c451b186b 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -150,7 +150,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi# Wall-clock timestamp (time.monotonic) when ``_message_id`` was first assigned from a successful# first-send. Used by the fresh-final logic to detect long-lived previews whose edit timestamps# would be stale by completion time. Ported from openclaw/openclaw#72038.- self._preview_message_ids: "set[str]" = set()+ self._preview_message_ids: set[str] = set()self._already_sent = Falseself._edit_supported = True # False once progressive edits stop workingself._last_edit_time = 0.0@@ -200,7 +200,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiself._fallback_prefix = ""# Fallback sends only the missing tail after a partial overflow delivery.self._fallback_preserve_partial_messages = False- self._segment_preview_message_ids: "set[str]" = set()+ self._segment_preview_message_ids: set[str] = set()# Tool-progress overlay (native only): shown in the bubble until text arrives.self._tool_progress_lines: list[str] = []self._tool_progress_active: bool = False@@ -618,7 +618,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi# ── run() collaborators ─────────────────────────────────────────────- def _resolve_length_budget(self) -> "tuple[Callable[[str], int], int]":+ def _resolve_length_budget(self) -> tuple[Callable[[str], int], int]:"""Per-chat length function (relay adapters differ per chat, e.g. utf16) + budget.isinstance gate: MagicMock auto-attributes aren't callables; test doubles use len."""# Shares the guarded ladder with the fallback path: a git pull while the gateway@@ -650,7 +650,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThilogger.debug("Stream consumer using native-draft transport (chat=%s draft_id=%s)",self.chat_id, self._draft_id)- def _drain_queue(self) -> "_Tick":+ def _drain_queue(self) -> _Tick:"""Drain everything queued so far into one tick. Control sentinels stop the drain(they take effect this tick); _FINAL_TEXT / _TOOL_PROGRESS / text deltas fold intostate so simultaneous items batch."""@@ -726,7 +726,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi# Degrade to a single buffered send(), like the approval path.self._degrade_native_to_buffered_send()- def _should_edit(self, tick: "_Tick") -> bool:+ def _should_edit(self, tick: _Tick) -> bool:"""Decide whether this tick flushes an edit/frame."""if not tick.is_interim:return True@@ -749,7 +749,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThireturn should_edit and not _is_partial_silence_marker(self._clean_for_display(self._accumulated))- async def _split_first_send(self, tick: "_Tick") -> bool:+ async def _split_first_send(self, tick: _Tick) -> bool:"""No message to edit yet and the buffer overflows: seal only the head chunks; thetail stays in _accumulated as the active preview later deltas edit in place.True when the turn finished here (the run loop returns)."""@@ -821,7 +821,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiself._last_sent_text = ""self._turn_split_delivery = True- async def _push_update(self, tick: "_Tick") -> None:+ async def _push_update(self, tick: _Tick) -> None:"""Send/edit this tick's visible text (cursor-suffixed unless finalizing)."""display_text = self._accumulatedif tick.is_interim:@@ -846,7 +846,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi# Lines stay in _tool_progress_lines for the next compose.self._tool_progress_active = False- async def _finalize_turn(self, tick: "_Tick") -> None:+ async def _finalize_turn(self, tick: _Tick) -> None:"""got_done: final edit without cursor, or one continuation send if edits failed."""if self._accumulated or self._message_id is not None or self._already_sent:await self._notify_before_finalize()@@ -872,7 +872,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThielif self._accumulated:await self._finalize_edit_path(tick)- async def _finalize_edit_path(self, tick: "_Tick") -> None:+ async def _finalize_edit_path(self, tick: _Tick) -> None:"""Edit-transport finalize (the non-native got_done branches, in priority order)."""if self._fallback_final_send:await self._send_fallback_final(self._accumulated)@@ -919,7 +919,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiif not cumulative:self._reset_segment_state()- async def _end_segment(self, tick: "_Tick") -> None:+ async def _end_segment(self, tick: _Tick) -> None:"""Tool boundary: edit-based transports reset so the next chunk is a fresh message.Cumulative transports must NOT reset — clearing _accumulated makes the next frame anon-prefix snapshot and the connector re-appends the whole answer. preserve_no_edit:diff --git a/gateway/stream_consumer_fallback.py b/gateway/stream_consumer_fallback.pyindex 135915d8572..f6c571747c6 100644--- a/gateway/stream_consumer_fallback.py+++ b/gateway/stream_consumer_fallback.py@@ -71,14 +71,14 @@ class StreamFallbackMixin:return final_text@staticmethod- def _split_text_chunks(text: str, limit: int, len_fn: "Callable[[str], int]" = len,+ def _split_text_chunks(text: str, limit: int, len_fn: Callable[[str], int] = len,) -> list[str]:"""Split text for fallback sends: newline-preferred, fence-balanced across chunks."""from gateway.platforms.helpers import split_text_fence_awarereturn split_text_fence_aware(text, limit, len_fn, prefer_paragraphs=False,balance_fences=True)- def _truncate_for_stream(self, text: str, limit: int, len_fn: "Callable[[str], int]",+ def _truncate_for_stream(self, text: str, limit: int, len_fn: Callable[[str], int],) -> list[str]:"""Split via the adapter's canonical truncate_message (platform-specific rules);non-base test doubles / legacy adapters keep the two-argument call shape."""@@ -208,10 +208,10 @@ class StreamFallbackMixin:self._mark_final_delivered(record=final_text)return None- def _fallback_len_budget(self) -> "tuple[Callable[[str], int], int]":+ def _fallback_len_budget(self) -> tuple[Callable[[str], int], int]:"""(len_fn, raw_limit) for fallback chunking — per-chat cap/unit on base adapters."""raw_limit = getattr(self.adapter, "MAX_MESSAGE_LENGTH", 4096)- _len_fn: "Callable[[str], int]" = len+ _len_fn: Callable[[str], int] = lenif isinstance(self.adapter, _BasePlatformAdapter):_len_fn = self.adapter.message_len_fntry: # per-chat cap/unit (relay adapter fronting N platforms)diff --git a/gateway/stream_consumer_think.py b/gateway/stream_consumer_think.pyindex e458312a452..61db1323090 100644--- a/gateway/stream_consumer_think.py+++ b/gateway/stream_consumer_think.py@@ -35,7 +35,7 @@ class StreamThinkFilterMixin:return acc_boundary and preceding.strip() == ""return preceding[last_nl + 1:].strip() == ""- def _earliest_open_tag(self, buf: str, lower_buf: str) -> "tuple[int, int]":+ def _earliest_open_tag(self, buf: str, lower_buf: str) -> tuple[int, int]:"""(index, length) of the earliest block-boundary opening tag, or (-1, 0)."""best_idx, best_len = -1, 0for tag in self._OPEN_THINK_TAGS:diff --git a/gateway/streaming_tts_consumer.py b/gateway/streaming_tts_consumer.pyindex 418e38b09d5..d6f7a357f50 100644--- a/gateway/streaming_tts_consumer.py+++ b/gateway/streaming_tts_consumer.py@@ -43,7 +43,7 @@ class StreamingTTSConsumer:# since an OpenAI-compatible endpoint reports its real rate only in the response (#76466).self._audio_format = audio_format or AudioFormat() if self._streamer is None else self._streamer_format()# Thread-safe queue of completed clauses plus the _DONE/_ABORT sentinels.- self._queue: "queue.Queue[Any]" = queue.Queue(maxsize=256)+ self._queue: queue.Queue[Any] = queue.Queue(maxsize=256)self._handle: Optional[StreamingTTSHandle] = Noneself._task: Optional[asyncio.Task] = None # drain task, created once by start()self._completed = self._partial = self._aborted = Falsediff --git a/gateway/turn_lease.py b/gateway/turn_lease.pyindex 2046f1b198d..812b08cdaf2 100644--- a/gateway/turn_lease.py+++ b/gateway/turn_lease.py@@ -25,7 +25,7 @@ DEFAULT_MAX_LEASES = 512DEFAULT_LEASE_WAIT = 5.0-def _holder_desc(holder: Optional["TurnLeaseToken"]) -> tuple:+def _holder_desc(holder: Optional[TurnLeaseToken]) -> tuple:return (holder.owner_key, holder.generation) if holder else ("?", "?")@@ -45,7 +45,7 @@ class TurnLeaseToken:__slots__ = ("generation", "lease", "owner_key", "released", "session_id")- def __init__(self, session_id: str, owner_key: str, generation: int, lease: "_SessionLease") -> None:+ def __init__(self, session_id: str, owner_key: str, generation: int, lease: _SessionLease) -> None:self.session_id, self.owner_key, self.generation = session_id, owner_key, generationself.released = False# The concrete lease, so release resolves by identity even after a rotation re-aliasesdiff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.pyindex 4d0a9a08ffd..53455472e5d 100644--- a/hermes_cli/_subprocess_compat.py+++ b/hermes_cli/_subprocess_compat.py@@ -303,7 +303,7 @@ _GIT_CONFIG_OVERRIDES = {}-def _safe_directory_cache_key(env: "Mapping[str, str]") -> tuple:+def _safe_directory_cache_key(env: Mapping[str, str]) -> tuple:"""Everything that decides which files ``git config --system/--global`` reads, plus theglobal candidates' mtimes so an edit to ``~/.gitconfig`` is picked up without a restart."""home = env.get("HOME", "")@@ -328,7 +328,7 @@ def _safe_directory_cache_key(env: "Mapping[str, str]") -> tuple:_safe_directory_cache: dict[tuple, list[str]] = {}-def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:+def _user_safe_directories(base_env: Mapping[str, str]) -> list[str]:"""The user's configured ``safe.directory`` values, in git's own effective order.Read with ``git config -z --get-all`` under *base_env* (the caller's untouched environment) so@@ -426,7 +426,7 @@ def expose_pm_git(project_root: Path) -> None:os.environ["PATH"] = path-def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, str]:+def noninteractive_git_env(base: Mapping[str, str] | None = None) -> dict[str, str]:"""Environment for *internal* git invocations that must never prompt.Copy of ``base`` (default ``os.environ``) with ``GIT_TERMINAL_PROMPT=0`` (fail instead of@@ -510,9 +510,9 @@ FILTER_DISCOVERY_FAILED = "git filter discovery failed"def noninteractive_repo_git_env(- cwd: "str | os.PathLike[str]",- base: "Mapping[str, str] | None" = None,-) -> "dict[str, str] | None":+ cwd: str | os.PathLike[str],+ base: Mapping[str, str] | None = None,+) -> dict[str, str] | None:"""Harden internal git for one repository, including named clean/smudge/process filters.The static environment can pin fixed config keys such as core.fsmonitor and@@ -536,7 +536,7 @@ def noninteractive_repo_git_env(return Nonenames: list[str] = []targets: set[Path] = set()- toplevel: "Path | None" = None+ toplevel: Path | None = Nonefields = proc.stdout.split("\0")for origin, entry in zip(fields[0::2], fields[1::2]):key, _, value = entry.partition("\n")@@ -734,7 +734,7 @@ def pid_is_hermes(pid: int, *, expected_start_time: int | None = None) -> bool:return False-def kill_process_tree(proc: "subprocess.Popen") -> None:+def kill_process_tree(proc: subprocess.Popen) -> None:"""Best-effort terminate *proc* and its descendants on both platforms; never raises.``proc.kill()`` alone only terminates the direct child. This is cleanup on an already-failing@@ -766,7 +766,7 @@ def kill_process_tree(proc: "subprocess.Popen") -> None:pass-def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:+def _legacy_kill_process_tree(proc: subprocess.Popen) -> None:"""Local tree-kill fallback when agent.deadline is unavailable (partial install, cycle)."""if not IS_WINDOWS:# Verify the child leads its own process group before signalling, never a shared group.@@ -796,9 +796,9 @@ def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:def bounded_probe_run(argv: Sequence[str], *, timeout: float, errors: str = "replace",- env: "Mapping[str, str] | None" = None, cwd: "str | os.PathLike[str] | None" = None,- raise_on_spawn_failure: bool = False, input: "str | None" = None,-) -> "subprocess.CompletedProcess[str] | None":+ env: Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None,+ raise_on_spawn_failure: bool = False, input: str | None = None,+) -> subprocess.CompletedProcess[str] | None:"""Deadlock-safe ``subprocess.run(argv, capture_output=True, timeout=…)`` for fail-open probes.``input`` is written to the child's stdin (closed afterwards); without it stdin is ``DEVNULL``.@@ -846,7 +846,7 @@ def bounded_probe_run(return subprocess.CompletedProcess(list(argv), proc.returncode, stdout, stderr)-def kill_and_drain(proc: "subprocess.Popen", seconds: float) -> "tuple | None":+def kill_and_drain(proc: subprocess.Popen, seconds: float) -> tuple | None:"""Tree-kill *proc* (:func:`kill_process_tree`), then read what its pipes still hold for atmost *seconds*: ``(stdout, stderr)``, or ``None`` when a descendant the kill missed stillholds them. Those pipes are left to ``communicate()``'s reader threads, never closed@@ -868,7 +868,7 @@ def _close_job(job) -> None:pass-def bounded_git_probe(argv: Sequence[str], *, timeout: float, env: "Mapping[str, str] | None" = None) -> str:+def bounded_git_probe(argv: Sequence[str], *, timeout: float, env: Mapping[str, str] | None = None) -> str:"""Run a short ``git`` probe and return stripped stdout, or ``""`` on ANY failure.On Windows ``run()``'s post-timeout cleanup calls an unbounded ``communicate()``; a suspendeddiff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.pyindex bda16edff11..7a279f97379 100644--- a/hermes_cli/active_sessions.py+++ b/hermes_cli/active_sessions.py@@ -122,7 +122,7 @@ class ActiveSessionRefusal(str):reason: str- def __new__(cls, message: str, reason: str) -> "ActiveSessionRefusal":+ def __new__(cls, message: str, reason: str) -> ActiveSessionRefusal:obj = super().__new__(cls, message)obj.reason = reasonreturn obj@@ -181,7 +181,7 @@ def _lock_path(registry_home: str | Path | None = None) -> Path:def _lease_paths(- lease: Optional["ActiveSessionLease"] = None, registry_home: str | Path | None = None+ lease: Optional[ActiveSessionLease] = None, registry_home: str | Path | None = None) -> tuple[Path, Path]:if lease is not None and lease.state_path is not None and lease.lock_path is not None:return lease.state_path, lease.lock_pathdiff --git a/hermes_cli/approval_transport.py b/hermes_cli/approval_transport.pyindex bf141d0b9f4..3d6b8757362 100644--- a/hermes_cli/approval_transport.py+++ b/hermes_cli/approval_transport.py@@ -57,7 +57,7 @@ class ApprovalRequest:cls, *, command: str, description: str, pattern_key: str, pattern_keys: tuple[str, ...],session_key: str, surface: str, allow_session: bool, allow_permanent: bool,timeout_seconds: float = 300,- ) -> "ApprovalRequest":+ ) -> ApprovalRequest:choices: list[ApprovalChoice] = ["once"]if allow_session:choices.append("session")diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex d1dec24769e..e296bbb6235 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -1753,7 +1753,7 @@ def _tls_state_from_verify(verify: Any) -> dict[str, Any]:def _last_auth_error_marker(- provider: str, error: "AuthError", *, reason: str, default_code: Optional[str] = None,+ provider: str, error: AuthError, *, reason: str, default_code: Optional[str] = None,) -> dict[str, Any]:"""The ``last_auth_error`` record persisted when dead OAuth material is quarantined."""return {@@ -1765,7 +1765,7 @@ def _last_auth_error_marker(_FLAT_OAUTH_TOKEN_KEYS = ("access_token", "refresh_token", "expires_at", "expires_in", "obtained_at")-def _quarantine_flat_oauth_state(state: dict[str, Any], provider: str, exc: "AuthError") -> None:+def _quarantine_flat_oauth_state(state: dict[str, Any], provider: str, exc: AuthError) -> None:"""Strip dead tokens from a flat OAuth state after a terminal runtime refresh failure sosubsequent calls fail fast without a network retry (mirrors the Nous / xAI / Codex pattern)."""for _k in _FLAT_OAUTH_TOKEN_KEYS:@@ -1798,7 +1798,7 @@ _NOUS_PORTAL_ALLOWED_HOSTS: frozenset[str] = frozenset({# per-turn HERMES_HOME override a multiplex gateway sets), so a single slot would hand profile A's# Portal bearer to profile B for up to the TTL._RESOLVE_TOKEN_CACHE_LOCK = threading.Lock()-_RESOLVE_TOKEN_CACHE: "dict[str, tuple[float, str]]" = {}+_RESOLVE_TOKEN_CACHE: dict[str, tuple[float, str]] = {}_RESOLVE_TOKEN_CACHE_TTL_S = 5.0diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 4b9425d4b29..257b43145ca 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -257,7 +257,7 @@ def _recover_codex_tokens_from_cli(def _refresh_payload_access_token(- response: "httpx.Response", *, provider: str, invalid_json: tuple[str, str],+ response: httpx.Response, *, provider: str, invalid_json: tuple[str, str],invalid_response: Optional[tuple[str, str]], missing_access: tuple[str, str],relogin_required: bool = True, invalid_json_relogin: Optional[bool] = None,strict_str: bool = True) -> tuple[dict[str, Any], str]:@@ -335,7 +335,7 @@ def _is_transient_transport_error(exc: BaseException) -> bool:return False-def _codex_login_post(url: str, *, failure: tuple[str, str], **kwargs: Any) -> "httpx.Response":+def _codex_login_post(url: str, *, failure: tuple[str, str], **kwargs: Any) -> httpx.Response:"""One 15s POST for the device-login flow; transport errors become ``_codex_err(*failure)``.A transient transport blip (a dropped connection mid-flow) is retried twice with a small@@ -376,7 +376,7 @@ def _capped_byte_stream_class() -> type:stream subclass rather than a bare generator."""- def __init__(self, response: "httpx.Response") -> None:+ def __init__(self, response: httpx.Response) -> None:self._response, self._raw = response, response.streamdef __iter__(self) -> Iterator[bytes]:@@ -398,7 +398,7 @@ def _capped_byte_stream_class() -> type:return _CappedByteStream-def _cap_codex_response_body(response: "httpx.Response") -> None:+def _cap_codex_response_body(response: httpx.Response) -> None:"""httpx response hook: refuse to buffer an auth body above ``_CODEX_AUTH_BODY_MAX_BYTES``.Runs before ``client.post()`` reads the body, so a hostile or broken endpoint/proxy answering@@ -408,7 +408,7 @@ def _cap_codex_response_body(response: "httpx.Response") -> None:response.stream = _capped_byte_stream_class()(response)-def _codex_http_client(**kwargs: Any) -> "httpx.Client":+def _codex_http_client(**kwargs: Any) -> httpx.Client:"""Build an ``httpx.Client`` for Codex OAuth/probe endpoints with Happy-Eyeballs racing and a1 MiB response-body cap (``_cap_codex_response_body``).@@ -440,7 +440,7 @@ def _codex_quota_exhausted_error(retry_after: Optional[int]) -> AuthError:return _codex_err(message, CODEX_RATE_LIMITED_CODE, relogin=False)-def _codex_refresh_failure_error(response: "httpx.Response") -> AuthError:+def _codex_refresh_failure_error(response: httpx.Response) -> AuthError:"""Decode a non-200 Codex token-refresh response into a shaped AuthError."""from hermes_cli.auth import _nonempty_strcode = "codex_refresh_failed"@@ -981,7 +981,7 @@ def _login_openai_codex(args, pconfig: ProviderConfig, *, force_new_login: bool_print_login_success("openai-codex", config_path, show_auth_state=True)-def _codex_login_rate_limited_error(response: "httpx.Response", *, during: str = "") -> AuthError:+def _codex_login_rate_limited_error(response: httpx.Response, *, during: str = "") -> AuthError:"""AuthError for a 429 from OpenAI's device-auth endpoints (throttle, not credential fault)."""# Upstream rate-limit / usage-quota exhaustion on the token endpoint. The stored refresh token is still# valid here — re-authenticating cannot lift a quota cap. Classify distinctly from auth failures sodiff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.pyindex f2ee8d7f91f..b8ca803f410 100644--- a/hermes_cli/auth_device_flow.py+++ b/hermes_cli/auth_device_flow.py@@ -314,10 +314,10 @@ def _print_device_code_instructions(def _poll_device_token_generic(- post: Callable[[], "httpx.Response"], *, expires_in: int, poll_interval: int,+ post: Callable[[], httpx.Response], *, expires_in: int, poll_interval: int,validate_success: Callable[[dict[str, Any]], None],- on_non_json_error: Callable[["httpx.Response"], Exception],- on_error: Callable[["httpx.Response", dict[str, Any]], Exception],+ on_non_json_error: Callable[[httpx.Response], Exception],+ on_error: Callable[[httpx.Response, dict[str, Any]], Exception],on_timeout: Callable[[], Exception]) -> dict[str, Any]:"""RFC 8628 device-code polling loop shared by the Nous and xAI flows.diff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 790807125e3..84ac31df031 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -685,7 +685,7 @@ def _banner_skill_lines(skills_by_category: dict[str, list[str]], skills_enableddef build_welcome_banner(- console: "Console", model: str, cwd: str, tools: list[dict] | None = None, enabled_toolsets: list[str] | None = None,+ console: Console, model: str, cwd: str, tools: list[dict] | None = None, enabled_toolsets: list[str] | None = None,session_id: str | None = None, get_toolset_for_tool=None, context_length: int | None = None, provider: str | None = None,availability: dict[str, Any] | None = None, skills_by_category: dict[str, list[str]] | None = None,context_pinned: bool = False,diff --git a/hermes_cli/cli_single_query.py b/hermes_cli/cli_single_query.pyindex 647e0a29d7e..ddb719d5449 100644--- a/hermes_cli/cli_single_query.py+++ b/hermes_cli/cli_single_query.py@@ -50,7 +50,7 @@ def _interrupt_agent_for_signal(agent, signum) -> None:pass # never block signal handling-def _run_kanban_goal_loop_q(cli: "HermesCLI", first_response: str, run_turn=None, log=None) -> None:+def _run_kanban_goal_loop_q(cli: HermesCLI, first_response: str, run_turn=None, log=None) -> None:"""Drive a kanban goal_mode worker through ``goals.run_kanban_goal_loop`` after its first turn.``run_turn`` defaults to the bare ``-Q`` turn (final answer only). The ``-q`` worker path@@ -94,7 +94,7 @@ def _run_kanban_goal_loop_q(cli: "HermesCLI", first_response: str, run_turn=None"failure_reason": result.get("failure_reason") if isinstance(result, dict) else None,}- def _task_status() -> "str | None":+ def _task_status() -> str | None:with _kbc.connect_closing() as c:return _kb.goal_run_status(c, task_id, worker_run_id)@@ -110,7 +110,7 @@ def _run_kanban_goal_loop_q(cli: "HermesCLI", first_response: str, run_turn=None)-def _run_kanban_goal_loop_chat(cli: "HermesCLI", first_response: str) -> None:+def _run_kanban_goal_loop_chat(cli: HermesCLI, first_response: str) -> None:"""``-q`` worker variant: follow-up turns go through ``cli.chat`` (tool feed stays on stdout,which is the Kanban worker log) and judge verdicts are printed there too, so a goal_mode card'slog reads like any other worker's instead of staying blank until the final answer."""diff --git a/hermes_cli/cli_status_bar_mixin.py b/hermes_cli/cli_status_bar_mixin.pyindex 959d60f18f0..67aac0e1261 100644--- a/hermes_cli/cli_status_bar_mixin.py+++ b/hermes_cli/cli_status_bar_mixin.py@@ -52,7 +52,7 @@ class CLIStatusBarMixin:return "class:status-bar-bad"return _threshold_style(percent_used, ((50, "warn"),), "good")- def _cache_hit_rate(self, snapshot: dict, precision: int = 1) -> "tuple[float, str] | None":+ def _cache_hit_rate(self, snapshot: dict, precision: int = 1) -> tuple[float, str] | None:"""Return (cache_pct, label) or None without cache data. Prefers the baseline-delta pctfrom ``_get_status_bar_snapshot`` (resets on model switch / compression, so it reflectsthe *current* cache regime); falls back to the session-lifetime ratio."""@@ -455,7 +455,7 @@ class CLIStatusBarMixin:return "".join(out).rstrip() + "..."@classmethod- def _status_title_badge(cls, title: str, width: int) -> "tuple[str, int] | None":+ def _status_title_badge(cls, title: str, width: int) -> tuple[str, int] | None:"""(badge, left_width) for the far-right session-title badge, or None when itdoesn't fit (no title / bar narrower than 24 cells)."""title = str(title or "").strip()@@ -829,7 +829,7 @@ class CLIStatusBarMixin:except (OSError, ValueError):pass- def _pet_view(self) -> "tuple[str, bool] | None":+ def _pet_view(self) -> tuple[str, bool] | None:"""(state, is_kitty) for the current frame, or None when no pet shows."""with self._pet_lock:if not self._pet_enabled or self._pet_renderer is None:diff --git a/hermes_cli/cli_terminal_input.py b/hermes_cli/cli_terminal_input.pyindex 76f7527ee34..604d848a5da 100644--- a/hermes_cli/cli_terminal_input.py+++ b/hermes_cli/cli_terminal_input.py@@ -142,7 +142,7 @@ def _file_drop_result(path: Path, remainder: str) -> dict:return {"path": path, "is_image": path.suffix.lower() in _IMAGE_EXTENSIONS, "remainder": remainder}-def _detect_file_drop(user_input: str) -> "dict | None":+def _detect_file_drop(user_input: str) -> dict | None:"""Detect a dragged/pasted file path at the start of *user_input* -> ``{path, is_image, remainder}`` or None."""from cli import _file_drop_result, _resolve_attachment_path, _split_path_inputif not isinstance(user_input, str):diff --git a/hermes_cli/commands_platforms.py b/hermes_cli/commands_platforms.pyindex e001bdad651..bf7a8c8bc57 100644--- a/hermes_cli/commands_platforms.py+++ b/hermes_cli/commands_platforms.py@@ -232,7 +232,7 @@ def _iter_gateway_skills(platform: str):def _collect_gateway_skill_entries(platform: str, max_slots: int | None, reserved_names: set[str], desc_limit: int = 100,- sanitize_name: "Callable[[str], str] | None" = None,+ sanitize_name: Callable[[str], str] | None = None,) -> tuple[list[tuple[str, str, str, str]], int]:"""Collect plugin + skill entries for a gateway platform.diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 576562b4715..54b863b13c8 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -987,12 +987,12 @@ class ConfigIssue:hint: str-def _issue(issues: list["ConfigIssue"], severity: str, message: str, hint: str) -> None:+def _issue(issues: list[ConfigIssue], severity: str, message: str, hint: str) -> None:issues.append(ConfigIssue(severity, message, hint))def _require_fields(- issues: list["ConfigIssue"], entry: dict[str, Any], label: str,+ issues: list[ConfigIssue], entry: dict[str, Any], label: str,fields: tuple[tuple[str, str], ...], suffix: str = "") -> None:"""Append a warning for every falsy ``field`` of *entry* (message: ``<label> is missing '<f>' field``)."""for field, hint in fields:@@ -1174,7 +1174,7 @@ def _validate_quoted_containers(config: dict[str, Any], issues: list[ConfigIssue"or remove the quotes in config.yaml")-def validate_config_structure(config: Optional[dict[str, Any]] = None) -> list["ConfigIssue"]:+def validate_config_structure(config: Optional[dict[str, Any]] = None) -> list[ConfigIssue]:"""Validate config.yaml structure and return detected issues (accepts a pre-loaded dict).Catches common YAML mistakes that otherwise surface as confusing runtime errors."""if config is None:@@ -4100,7 +4100,7 @@ def platform_manifest_stamp(home: Optional[Path] = None) -> tuple:def _platform_plugin_manifests(home: Optional[Path] = None, source: PlatformManifestSource = "all", *,- strict: bool = False, skipped: "list | None" = None):+ strict: bool = False, skipped: list | None = None):"""Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest (see:func:`_platform_manifest_paths`). ``strict`` raises when a manifest cannot be read instead ofskipping it: the child-env scrub must not lose a declared secret to an I/O error. Only a@@ -4173,7 +4173,7 @@ def platform_manifest_secret_envs(home: Optional[Path] = None, source: PlatformMreturn _manifest_secret_envs(_platform_plugin_manifests(home, source, strict=strict))-def platform_manifest_secret_scan(home: Optional[Path] = None) -> "tuple[frozenset[str], bool]":+def platform_manifest_secret_scan(home: Optional[Path] = None) -> tuple[frozenset[str], bool]:"""``home``'s user-installed platform plugin secrets, strictly read, and whether the scan wascomplete: False when a plugin dir or flat manifest could not be read or parsed, so the callerkeeps the denials it already knew instead of releasing them on a failed discovery."""@@ -4182,14 +4182,14 @@ def platform_manifest_secret_scan(home: Optional[Path] = None) -> "tuple[frozensreturn names, not skipped-def _inject_platform_plugin_env_vars() -> "frozenset[str] | None":+def _inject_platform_plugin_env_vars() -> frozenset[str] | None:"""Populate OPTIONAL_ENV_VARS from platform plugin manifests (bundled AND user-installed) soTeams / IRC / Google Chat and third-party platforms are configurable in the ``hermes config`` /Desktop Gateway form without the core knowing they exist. Failures are swallowed so amalformed plugin.yaml can't break CLI import. Returns the bundled manifests' secret names, orNone when a bundled manifest could not be read (the policy then re-reads strictly)."""- bundled: "list | None" = []+ bundled: list | None = []try:bundled = list(_platform_plugin_manifests(source="bundled", strict=True))except OSError:@@ -4218,4 +4218,4 @@ def _inject_platform_plugin_env_vars() -> "frozenset[str] | None":# one: the config form keeps the core entry, and the child-env scrub keeps a plugin that lists# OPENAI_API_KEY from turning a provider key into an adapter secret.CORE_DECLARED_ENV_NAMES: frozenset[str] = frozenset(OPTIONAL_ENV_VARS)-BUNDLED_PLATFORM_SECRET_ENVS: "frozenset[str] | None" = _inject_platform_plugin_env_vars()+BUNDLED_PLATFORM_SECRET_ENVS: frozenset[str] | None = _inject_platform_plugin_env_vars()diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.pyindex 3773321568c..a891dac1693 100644--- a/hermes_cli/console_engine.py+++ b/hermes_cli/console_engine.py@@ -39,7 +39,7 @@ class ConsoleCommand:path: tuple[str, ...]usage: strsummary: str- handler: Callable[["HermesConsoleEngine", list[str]], str]+ handler: Callable[[HermesConsoleEngine, list[str]], str]mutating: bool = Falseconfirmation: str = ""@@ -334,7 +334,7 @@ _SEND_SURFACE = _CliSurface("adder", "hermes_cli.send_cmd", "register_send_subpadef _register_command_family(- engine: "HermesConsoleEngine", root: str, surface: _CliSurface, paths: str) -> None:+ engine: HermesConsoleEngine, root: str, surface: _CliSurface, paths: str) -> None:summaries = _surface_summaries(surface, root)namespace_update = _apply_confirmed_defaults if surface.kind in _CONFIRMED_KINDS else Nonefor child_path, mutating in _paths(paths):@@ -440,7 +440,7 @@ class HermesConsoleEngine:def register(self, path: Iterable[str], usage: str, summary: str,- handler: Callable[["HermesConsoleEngine", list[str]], str], *,+ handler: Callable[[HermesConsoleEngine, list[str]], str], *,mutating: bool = False, confirmation: str = "") -> None:key = tuple(path)self.commands[key] = ConsoleCommand(key, usage, summary, handler, mutating, confirmation)diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 681d555d331..aee52f065cd 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -128,7 +128,7 @@ class DashboardAuthProvider(ABC):@abstractmethoddef revoke_session(self, *, refresh_token: str) -> None: ...- def complete_password_login(self, *, username: str, password: str) -> "Session":+ def complete_password_login(self, *, username: str, password: str) -> Session:"""Verify a username/password pair and mint a :class:`Session` (only called when``supports_password``). Raise ``InvalidCredentialsError`` on rejection (SHOULD be constanttime for unknown users — no timing oracle) and ``ProviderError`` when the store is@@ -137,7 +137,7 @@ class DashboardAuthProvider(ABC):f"{type(self).__name__} does not support password login ""(set supports_password = True and override complete_password_login)")- def verify_token(self, *, token: str) -> "Optional[TokenPrincipal]":+ def verify_token(self, *, token: str) -> Optional[TokenPrincipal]:"""Verify a non-interactive bearer token; return its principal. Mirrors ``verify_session``:return ``None`` (never raise) for an unrecognised token so the seam falls through; raise``ProviderError`` ONLY for a genuine backing-store outage. Shared secrets MUST be compareddiff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex 1202e615fac..80b3bfcf47e 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -386,7 +386,7 @@ async def auth_callback(_PW_RATE_MAX_ATTEMPTS = 10_PW_RATE_WINDOW_SEC = 60.0_PW_RATE_MAX_BUCKETS = 4096-_pw_attempts: "OrderedDict[str, deque[float]]" = OrderedDict()+_pw_attempts: OrderedDict[str, deque[float]] = OrderedDict()_pw_attempts_lock = threading.Lock()diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 0a439ff51d5..d1c89ad8bea 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -588,7 +588,7 @@ def _kill_pids_posix(pids: list[int], killed: list[int], failed: list[tuple[int,def _kill_stale_dashboard_processes(reason: str = "the running backend no longer matches the updated frontend", *,- restart_managed: bool = False, already_restarted_units: "set[str] | None" = None,+ restart_managed: bool = False, already_restarted_units: set[str] | None = None,scope_home: str | None = None,) -> dict[str, list]:"""Kill running ``hermes dashboard`` / ``hermes serve`` processes (update end, ``--stop``).diff --git a/hermes_cli/desktop_build_lock.py b/hermes_cli/desktop_build_lock.pyindex de5de957151..214d276ddde 100644--- a/hermes_cli/desktop_build_lock.py+++ b/hermes_cli/desktop_build_lock.py@@ -147,7 +147,7 @@ class DesktopBuildLock:finally:self._release_checkout() # the narrower lock first: the order is checkout, build- def __enter__(self) -> "DesktopBuildLock":+ def __enter__(self) -> DesktopBuildLock:if not self.acquire():raise RuntimeError("desktop build lock is already held")return selfdiff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex 530d7fe4f95..bba9eb19efe 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -221,7 +221,7 @@ def _report_host_gateway_slot(mgr, issues: list[str]) -> None:"hermes --profile default gateway migrate --multiplex")-def check_certificates(should_fix: bool = False, issues: "list | None" = None) -> None:+def check_certificates(should_fix: bool = False, issues: list | None = None) -> None:"""Verify the actual TLS policy is usable before the first HTTPS call tracebacks.The policy is ``agent.ssl_verify``: the platform verifier (truststore) is@@ -405,7 +405,7 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:check_warn(f"{h.package}=={h.installed_version} still installed (advisory {h.advisory.id} acknowledged)")-def _staged_venv_dir() -> "Path | None":+def _staged_venv_dir() -> Path | None:"""pm's provisioned runtime venv, or None when nothing is staged.``pm.packages.Venv().venv_dir()`` is pm's public authority for wherediff --git a/hermes_cli/doctor_report.py b/hermes_cli/doctor_report.pyindex fc258dd4f9c..aa3c961dc99 100644--- a/hermes_cli/doctor_report.py+++ b/hermes_cli/doctor_report.py@@ -59,7 +59,7 @@ class Finding:manual_issues: list = field(default_factory=list)fixed: int = 0- def merge(self, other: "Finding") -> None:+ def merge(self, other: Finding) -> None:self.issues.extend(other.issues)self.manual_issues.extend(other.manual_issues)self.fixed += other.fixeddiff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.pyindex ec0483fc180..1997530c148 100644--- a/hermes_cli/gitlock.py+++ b/hermes_cli/gitlock.py@@ -196,7 +196,7 @@ def _killed_update_owns(lock: Path) -> bool:return last.get("outcome") in ("running", "interrupted") and not update_receipt._owner_alive(last)-def _windows_git_in_checkout(root: Path) -> "bool | None":+def _windows_git_in_checkout(root: Path) -> bool | None:"""Whether any git (``git.exe``, a dashed ``git-<sub>.exe``) works in ``root``; None when unknowable.Works in: its cwd, a path argument or a ``GIT_DIR``-style variable is inside the checkout or@@ -462,7 +462,7 @@ class _ShallowLock:self._path = shallow_pathself._lock_path = shallow_path.with_name(shallow_path.name + ".lock")- def __enter__(self) -> "_ShallowLock":+ def __enter__(self) -> _ShallowLock:try:fd = os.open(self._lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)except FileExistsError:@@ -623,7 +623,7 @@ def prune_stale_shallow_grafts(repo_root: Path) -> int:return 0-def _partial_clone_filter(repo_root: Path, **run_kwargs) -> "str | None":+def _partial_clone_filter(repo_root: Path, **run_kwargs) -> str | None:"""The checkout's own ``remote.origin.partialclonefilter``, or None for a non-partial clone."""result = run_git(["git"], ["config", "--get", "remote.origin.promisor"],diff --git a/hermes_cli/goals.py b/hermes_cli/goals.pyindex 11ee00ff8aa..a9e1341d414 100644--- a/hermes_cli/goals.py+++ b/hermes_cli/goals.py@@ -299,7 +299,7 @@ class GoalContract:return {f: getattr(self, f) for f in _CONTRACT_FIELDS}@classmethod- def from_dict(cls, data: Optional[dict[str, Any]]) -> "GoalContract":+ def from_dict(cls, data: Optional[dict[str, Any]]) -> GoalContract:if not isinstance(data, dict):return cls()return cls(**{f: str(data.get(f) or "").strip() for f in _CONTRACT_FIELDS})@@ -358,7 +358,7 @@ class GoalGate:return asdict(self)@classmethod- def from_dict(cls, data: Optional[dict[str, Any]]) -> "GoalGate":+ def from_dict(cls, data: Optional[dict[str, Any]]) -> GoalGate:if not isinstance(data, dict):return cls(command="")return cls(@@ -455,7 +455,7 @@ class GoalState:return json.dumps(asdict(self), ensure_ascii=False)@classmethod- def from_json(cls, raw: str) -> "GoalState":+ def from_json(cls, raw: str) -> GoalState:data = json.loads(raw)raw_subgoals = data.get("subgoals") or []ints = {k: int(data.get(k) or 0) for k in ("turns_used", "consecutive_parse_failures", "consecutive_transport_failures", "waiting_on_delegations")}diff --git a/hermes_cli/gui_uninstall.py b/hermes_cli/gui_uninstall.pyindex 660cb8b6e83..52112316b13 100644--- a/hermes_cli/gui_uninstall.py+++ b/hermes_cli/gui_uninstall.py@@ -34,7 +34,7 @@ def desktop_userdata_dir() -> Path:return _env_dir("XDG_CONFIG_HOME", home / ".config") / "Hermes"-def source_built_gui_artifacts(hermes_home: Path) -> "list[Path]":+def source_built_gui_artifacts(hermes_home: Path) -> list[Path]:"""GUI build artifacts produced by ``hermes desktop`` inside the checkout (same ``hermes-agent/`` layoutinstall.sh uses). The workspace-root node_modules is shared with the TUI, dashboard and otherworkspaces, so only the desktop workspace's own dependencies belong to GUI removal."""@@ -52,7 +52,7 @@ def desktop_install_record() -> Path:return get_default_hermes_root() / "desktop-installed-apps.json"-def packaged_gui_app_paths() -> "list[Path]":+def packaged_gui_app_paths() -> list[Path]:"""Standard install locations of the packaged desktop distributable for the current OS. Every candidateis returned; the caller filters to those that exist. Never globs system-wide — only the well-knownelectron-builder output locations for the "Hermes" product."""@@ -93,7 +93,7 @@ def gui_is_installed(hermes_home: Path) -> bool:))-def gui_install_summary(hermes_home: "Path | None" = None) -> dict:+def gui_install_summary(hermes_home: Path | None = None) -> dict:"""JSON-serializable snapshot of what's installed, for the desktop UI to render via IPC."""home: Path = hermes_home if hermes_home is not None else get_hermes_home()userdata = desktop_userdata_dir()@@ -133,7 +133,7 @@ def _remove_path(path: Path) -> bool:return False-def uninstall_gui(hermes_home: "Path | None" = None, *, remove_userdata: bool = True) -> "list[Path]":+def uninstall_gui(hermes_home: Path | None = None, *, remove_userdata: bool = True) -> list[Path]:"""Remove the desktop GUI's artifacts, leaving the agent + user data intact."""home: Path = hermes_home if hermes_home is not None else get_hermes_home()removed: list[Path] = []diff --git a/hermes_cli/heartbeat.py b/hermes_cli/heartbeat.pyindex 02f1963df1e..b10a5846fbf 100644--- a/hermes_cli/heartbeat.py+++ b/hermes_cli/heartbeat.py@@ -76,7 +76,7 @@ class HeartbeatState:return json.dumps(asdict(self), ensure_ascii=False)@classmethod- def from_json(cls, raw: str) -> "HeartbeatState":+ def from_json(cls, raw: str) -> HeartbeatState:data = json.loads(raw)return cls(**{name: coerce(data.get(name) or default) for name, (coerce, default) in _STATE_FIELDS.items()})diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex e4a6011f0b7..b6933231724 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -28,7 +28,7 @@ class ConfigContext:def with_overrides(self, *, current_provider: Optional[str] = None, current_model: Optional[str] = None,current_base_url: Optional[str] = None,- ) -> "ConfigContext":+ ) -> ConfigContext:"""Copy with TRUTHY overrides applied: the TUI reads agent attributes that may be empty stringsbefore an agent is spawned — empties must not clobber the disk-config values."""overrides = (("current_provider", current_provider), ("current_model", current_model),@@ -956,7 +956,7 @@ def _apply_pricing(rows: list[dict], *, force_fresh_nous_tier: bool = False, cacrow["unavailable_models"] = []-def _local_runtime_row(ctx: "ConfigContext") -> dict | None:+def _local_runtime_row(ctx: ConfigContext) -> dict | None:"""The ``llamacpp`` row from staged GGUFs (``None`` when none) — downloaded models must be selectablebefore the server runs (selection starts it via the runtime_provider seam). The row's id comes fromthe provider registry's own definition, never a local literal: a row the resolver can't resolve isdiff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 24e1fb78156..69d948e179b 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -135,7 +135,7 @@ _IS_WINDOWS = sys.platform == "win32"KANBAN_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024 # one cap for dashboard, tools and CLI-def _assert_not_delegated_child_mutation(path: "str | Path | None" = None) -> None:+def _assert_not_delegated_child_mutation(path: str | Path | None = None) -> None:"""Reject Kanban mutations from ``delegate_task`` child contexts.The tool/CLI fast-fail guards are UX, not a trust boundary (a child can shell@@ -162,7 +162,7 @@ def _fire_kanban_lifecycle_hook(event: str, task_id: str, **fields: Any) -> None_log.debug("kanban lifecycle hook %s failed: %s", event, exc)-def _fire_task_hook(event: str, task: Optional["Task"], task_id: str, run_id: Optional[int], **fields: Any) -> None:+def _fire_task_hook(event: str, task: Optional[Task], task_id: str, run_id: Optional[int], **fields: Any) -> None:"""Lifecycle hook for a task transition; ``assignee`` from the (possibly missing) row."""_fire_kanban_lifecycle_hook(event, task_id, board=get_current_board(),@@ -192,7 +192,7 @@ def _kanban_observer_consumed(event: str) -> bool:def _fire_worker_spawned_hook(- conn: sqlite3.Connection, task: "Task", workspace_path: str, pid: Optional[int], *,+ conn: sqlite3.Connection, task: Task, workspace_path: str, pid: Optional[int], *,board: Optional[str] = None,) -> None:"""``on_kanban_worker_spawned`` AFTER the PID is durably persisted; best-effort."""@@ -240,7 +240,7 @@ _TICK_ACTIVITY_FIELDS = (def _fire_dispatch_tick_hook(- result: "DispatchResult", *, board: Optional[str] = None, dry_run: bool = False,+ result: DispatchResult, *, board: Optional[str] = None, dry_run: bool = False,) -> None:"""``on_kanban_dispatch_tick`` — strictly AFTER ``_dispatch_tick_lock`` isreleased so a slow subscriber cannot stall a sibling dispatcher.@@ -667,7 +667,7 @@ class Task:completion_contract: Optional[str] = None@classmethod- def from_row(cls, row: sqlite3.Row) -> "Task":+ def from_row(cls, row: sqlite3.Row) -> Task:g = lambda col, default=None: _lossy_text(_row_get(row, col, default))parsed = _json_or(g("skills"))skills_value = [str(s) for s in parsed if s] if isinstance(parsed, list) else None@@ -725,7 +725,7 @@ class Run:error: Optional[str]@classmethod- def from_row(cls, row: sqlite3.Row) -> "Run":+ def from_row(cls, row: sqlite3.Row) -> Run:return cls(**{col: _lossy_text(row[col]) for col in (@@ -749,7 +749,7 @@ class Comment:created_at: int@classmethod- def from_row(cls, r: sqlite3.Row) -> "Comment":+ def from_row(cls, r: sqlite3.Row) -> Comment:return cls(id=r["id"], task_id=r["task_id"], author=_lossy_text(r["author"]),body=_lossy_text(r["body"]), created_at=r["created_at"],@@ -770,7 +770,7 @@ class Attachment:created_at: int@classmethod- def from_row(cls, r: sqlite3.Row) -> "Attachment":+ def from_row(cls, r: sqlite3.Row) -> Attachment:return cls(id=r["id"], task_id=r["task_id"], filename=r["filename"],stored_path=r["stored_path"], content_type=r["content_type"],@@ -788,7 +788,7 @@ class Event:run_id: Optional[int] = None@classmethod- def from_row(cls, row: sqlite3.Row) -> "Event":+ def from_row(cls, row: sqlite3.Row) -> Event:run_id = _row_get(row, "run_id")return cls(id=row["id"], task_id=row["task_id"], kind=_lossy_text(row["kind"]),diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex a770af8e710..1bb3044bfa7 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -154,7 +154,7 @@ class DispatchResult:Reclaim/promotion bookkeeping still ran; deferred tasks stay queued."""-def describe_suppression(results: Iterable[Optional["DispatchResult"]]) -> str:+def describe_suppression(results: Iterable[Optional[DispatchResult]]) -> str:"""One line naming why the tick(s) held ready work back, or ``""``.``active_pr=1, recent_success=2, rate_limited=1, skipped_locked=1,@@ -193,12 +193,12 @@ def describe_suppression(results: Iterable[Optional["DispatchResult"]]) -> str:# leaves in its own log (``KANBAN_WORKER_EXIT_TRAILER``)._RECENT_WORKER_EXIT_TTL_SECONDS = 600_RECENT_WORKER_EXITS_MAX = 4096-_recent_worker_exits: "dict[int, tuple[int, float]]" = {}+_recent_worker_exits: dict[int, tuple[int, float]] = {}# Windows has no ``waitpid(-1)``: a child's exit code is only recoverable# through a live handle, so ``_default_spawn`` parks each worker's ``Popen``# here (Windows only) and ``reap_worker_zombies`` polls it. Entry: ``pid -> Popen``.-_live_worker_procs: "dict[int, subprocess.Popen]" = {}+_live_worker_procs: dict[int, subprocess.Popen] = {}def _wait_status_from_returncode(returncode: int) -> int:@@ -223,7 +223,7 @@ def _record_worker_exit(pid: int, raw_status: int) -> None:_recent_worker_exits.pop(_pid, None)-def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":+def _classify_worker_exit(pid: int) -> tuple[str, Optional[int]]:"""``(kind, code)`` for a reaped worker PID: ``clean_exit`` (rc 0 whilestill ``running`` = protocol violation), ``rate_limited``(``KANBAN_RATE_LIMIT_EXIT_CODE``, never counts as a failure),@@ -246,7 +246,7 @@ def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":return ("unknown", None)-def _exit_code_kind(code: int) -> "tuple[str, int]":+def _exit_code_kind(code: int) -> tuple[str, int]:"""``(kind, code)`` for a worker's exit code, however it was observed."""if code == 0:return ("clean_exit", 0)@@ -278,12 +278,12 @@ def _worker_log_exit_code(task_id: str, board: Optional[str] = None) -> Optionalreturn int(matches[-1]) if matches else None-def reap_worker_zombies() -> "list[int]":+def reap_worker_zombies() -> list[int]:"""Reap exited workers without blocking; returns reaped PIDs. POSIX reapsevery child via ``waitpid(-1)``; Windows polls the ``Popen`` handlesparked by ``_default_spawn`` (the only way to learn a child's exit codethere), so the rate-limit sentinel exit is classified on both hosts."""- reaped: "list[int]" = []+ reaped: list[int] = []if _kb._IS_WINDOWS:for pid, proc in list(_live_worker_procs.items()):returncode = proc.poll()@@ -2026,7 +2026,7 @@ def _dispatch_lane_task(conn: sqlite3.Connection,row: sqlite3.Row,assignee: str,- result: "DispatchResult",+ result: DispatchResult,*,lane: str,dry_run: bool,diff --git a/hermes_cli/linux_desktop_entry.py b/hermes_cli/linux_desktop_entry.pyindex 62d3fa7d657..c6bcc03001a 100644--- a/hermes_cli/linux_desktop_entry.py+++ b/hermes_cli/linux_desktop_entry.py@@ -81,7 +81,7 @@ def _running_interpreter() -> str:return str(path.resolve())-_probe_cache: "dict[str, bool]" = {}+_probe_cache: dict[str, bool] = {}def _can_import_hermes_cli(interpreter: Path) -> bool:@@ -328,7 +328,7 @@ def _resolve_hermes_bin_for_desktop_entry(return None-def _shebang_tokens(shebang: str) -> "list[str]":+def _shebang_tokens(shebang: str) -> list[str]:return shebang[2:].strip().split()@@ -599,7 +599,7 @@ def _render_legacy_alias_entry(exec_command: str, icon: str) -> str:return render_desktop_entry(exec_command, icon) + "NoDisplay=true\n"-def refresh_desktop_databases(applications_dir: Path) -> "list[str]":+def refresh_desktop_databases(applications_dir: Path) -> list[str]:"""Reindex the menu caches. Run each tool only when it exists."""ran: list[str] = []@@ -618,7 +618,7 @@ def refresh_desktop_databases(applications_dir: Path) -> "list[str]":return ran-def _run_quiet(cmd: "list[str]", *, timeout: int = 60, on_error: Optional[bool] = False, **kwargs) -> Optional[bool]:+def _run_quiet(cmd: list[str], *, timeout: int = 60, on_error: Optional[bool] = False, **kwargs) -> Optional[bool]:"""Exit-status success of a silenced subprocess; ``on_error`` when it could not be run at all."""try:result = subprocess.run(diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex 0098514986f..e553fee980d 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -68,7 +68,7 @@ def assets_dir() -> Path:return models_dir() / "assets"-def staged_in(models_dir: Path, *, require_complete: bool = True) -> "list[Path]":+def staged_in(models_dir: Path, *, require_complete: bool = True) -> list[Path]:"""Servable GGUFs in a directory: single files, plus split GGUFs once by their first part.With ``require_complete`` a split counts only when EVERY part is on disk — a mid-download splitis not servable and must not surface anywhere as a model."""@@ -89,7 +89,7 @@ def staged_in(models_dir: Path, *, require_complete: bool = True) -> "list[Path]return out-def adopt_legacy_models() -> "list[Path]":+def adopt_legacy_models() -> list[Path]:"""Move GGUFs left in the old per-profile ``<profile home>/models`` layout (and its assets/)into the machine-scoped dirs, so everything downstream keeps reading one directory.@@ -133,12 +133,12 @@ def adopt_legacy_models() -> "list[Path]":return moved-def staged_models() -> "list[Path]":+def staged_models() -> list[Path]:"""Servable staged models (continuation parts, incomplete splits and assets/ never count)."""return staged_in(models_dir())-def staged_model_ids() -> "list[str]":+def staged_model_ids() -> list[str]:return [model_id_from_stem(p.stem) for p in staged_models()]@@ -399,7 +399,7 @@ def _cross_process_boot_lock(timeout_s: float = 130.0):os.close(fd)-def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":+def ensure_local_runtime(config: dict, force: bool = False) -> object | None:"""Idempotent boot of the managed runtime. Returns the supervisor (or None whendisabled/unavailable). Never raises into a session start — failures log and return None; chatfalls back to configured providers."""diff --git a/hermes_cli/local_runtime/capabilities.py b/hermes_cli/local_runtime/capabilities.pyindex f85a8b3253f..3c69a2ff1ec 100644--- a/hermes_cli/local_runtime/capabilities.py+++ b/hermes_cli/local_runtime/capabilities.py@@ -37,7 +37,7 @@ def is_managed_provider(provider: str, base_url: str = "") -> bool:return False-def _props_modalities(model_id: str) -> "bool | None":+def _props_modalities(model_id: str) -> bool | None:"""Ask the running server whether this loaded child sees images. None when the server is down,the model isn't loaded, or the build doesn't report modalities."""with suppress(Exception):@@ -52,7 +52,7 @@ def _props_modalities(model_id: str) -> "bool | None":return None-def managed_model_supports_vision(model_id: str) -> "bool | None":+def managed_model_supports_vision(model_id: str) -> bool | None:"""Ground-truth vision capability for a staged model, or None when the model isn't ours /nothing is known (caller keeps falling through)."""if not model_id:diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex e84b35a5b9d..7d9884237bc 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -101,11 +101,11 @@ class CatalogEntry:# GGUF general.architecture; prices architecture-specific buffers (estimator._WINDOW_COMPUTE_BYTES)# before the file is on disk.architecture: str = ""- mmproj: "AssetFile | None" = None # vision projector, downloads with model- draft: "AssetFile | None" = None # spec-decode draft model (e.g. DSpark)+ mmproj: AssetFile | None = None # vision projector, downloads with model+ draft: AssetFile | None = None # spec-decode draft model (e.g. DSpark)# MTP head shipped as its own file (the model carries none): the engine loads it as the# draft for MTP spec decode. Downloads with the model.- mtp_head: "AssetFile | None" = None+ mtp_head: AssetFile | None = Nonesampling: dict = field(default_factory=dict) # INI long-form launch defaults# Oldest llama.cpp release tag that can load this model (day-0 architectures need the release# where their support landed). Empty means any installed engine.@@ -220,7 +220,7 @@ _PRODUCT_DEFAULTS = {}-def _hardware_key(budget: HardwareBudget, backend: str) -> "tuple[str, str, str]":+def _hardware_key(budget: HardwareBudget, backend: str) -> tuple[str, str, str]:"""(platform, backend, reference GPU name) for the shipped tables; the name is empty when theGPU is not recognized."""# Drivers may append a parenthesized description to the stable device name.@@ -246,8 +246,8 @@ def predicted_decode_tok_s(entry: CatalogEntry, variant: QuantVariant, budget: Hdef recommended_entry(budget: HardwareBudget,- entries: "tuple[CatalogEntry, ...] | None" = None, *, backend: str = "auto"- ) -> "tuple[CatalogEntry, str] | None":+ entries: tuple[CatalogEntry, ...] | None = None, *, backend: str = "auto"+ ) -> tuple[CatalogEntry, str] | None:"""The catalog's default pick for THIS machine, with its reason key.Callers pass pre-filtered entries when some are ineligible for reasons the catalog can't know@@ -296,7 +296,7 @@ _refresh_lock = threading.Lock()_last_refresh_attempt = 0.0-def _asset_from(d: "dict | None") -> "AssetFile | None":+def _asset_from(d: dict | None) -> AssetFile | None:if not d:return Nonereturn AssetFile(path=d["path"], size_bytes=int(d["size_bytes"]), local=d.get("local"),@@ -314,7 +314,7 @@ _SCALAR_FIELDS = {}-def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":+def _load_catalog(doc: dict) -> tuple[CatalogEntry, ...]:"""Parse a catalog document. Unknown fields are ignored (newer catalogs stay readable by olderapps); a major schema bump is the signal that they wouldn't be, and the caller skips it."""if int(doc.get("schema_version", 0)) != _SCHEMA_VERSION:@@ -337,14 +337,14 @@ def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":return tuple(entries)-def _packaged_catalog() -> "tuple[CatalogEntry, ...]":+def _packaged_catalog() -> tuple[CatalogEntry, ...]:from importlib.resources import filesraw = files("hermes_cli.local_runtime").joinpath("catalog.json").read_text(encoding="utf-8-sig")return _load_catalog(json.loads(raw))-CATALOG: "tuple[CatalogEntry, ...]" = _packaged_catalog()+CATALOG: tuple[CatalogEntry, ...] = _packaged_catalog()def refresh_catalog(force: bool = False) -> bool:@@ -383,7 +383,7 @@ def catalog_by_id() -> dict[str, CatalogEntry]:return {entry.id: entry for entry in CATALOG}-def find_entry_for_model(model_id: str) -> "tuple[CatalogEntry, QuantVariant] | None":+def find_entry_for_model(model_id: str) -> tuple[CatalogEntry, QuantVariant] | None:"""Locate the entry + variant that owns a staged model id."""for entry in CATALOG:for variant in entry.variants:@@ -392,6 +392,6 @@ def find_entry_for_model(model_id: str) -> "tuple[CatalogEntry, QuantVariant] |return None-def entry_for_model(model_id: str) -> "CatalogEntry | None":+def entry_for_model(model_id: str) -> CatalogEntry | None:hit = find_entry_for_model(model_id)return hit[0] if hit is not None else Nonediff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex 506b6f4b7a2..4e5d3542fbf 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -52,7 +52,7 @@ def _state_endpoint() -> dict | None:return {"base_url": base_url, "api_key": state.get("api_key", "")}-def managed_root() -> "tuple[str, str] | None":+def managed_root() -> tuple[str, str] | None:"""(base_root, api_key) of the managed router, or None. Resolved through theownership-guarded reader, not a raw state-file read: on the shared stable port a foreigninstall's server answers /health for anyone, and a raw read would attach callers to someonediff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex 01cdaf2b5ad..3b7a31441bd 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -205,7 +205,7 @@ class GGUFHeader:return self.head_dim_k-def split_parts(path: Path) -> "list[Path] | None":+def split_parts(path: Path) -> list[Path] | None:"""Every on-disk part of the split ``path`` belongs to, first part first; None when ``path`` isnot a split member or no other part is present.diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 49c7cfe2034..27ed7468602 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -58,7 +58,7 @@ _GPU_ENGINE_BACKENDS = ("vulkan", "hip")# One probe per process once a device answers (silicon doesn't change); a miss retries after this# long so a runtime installed mid-session gets picked up by the engine fallback._POOL_NEGATIVE_TTL_S = 60.0-_pool_probe_cache: tuple[float, "tuple[int, bool | None] | None"] | None = None+_pool_probe_cache: tuple[float, tuple[int, bool | None] | None] | None = None# ' CUDA0: NVIDIA Example Device (1234-core Example GPU) (46464 MiB, 46284 MiB free)'# — greedy .* pins the LAST parenthesized group, so device names with parentheses parse.@@ -174,7 +174,7 @@ def _ram_bytes() -> tuple[int, int]:# nvidia-smi lives at a fixed path under the driver install; PATH presence varies by session type# (services and gateways often run minimal environments) and by driver generation (the legacy# NVSMI dir was never on PATH). Cached: the driver doesn't move mid-process.-_smi_path_cache: "tuple[str | None] | None" = None+_smi_path_cache: tuple[str | None] | None = Nonedef _nvidia_smi_path() -> str | None:@@ -212,7 +212,7 @@ def _nvidia_vram() -> tuple[int, int, str, int | None] | None:return query["total_bytes"], query["free_bytes"], query["gpu_name"], query.get("gpu_pci_id")-_gpu_query_cache: "tuple[float, dict | None] | None" = None+_gpu_query_cache: tuple[float, dict | None] | None = None# The statusbar polls /api/local-models/hardware every 5s and the endpoint needs# name/util/vram; the budget probe needs total/free. One shared query (with a TTL# shorter than the poll) serves both, so one poll = one nvidia-smi spawn (#120262)@@ -221,7 +221,7 @@ _gpu_query_cache: "tuple[float, dict | None] | None" = None_GPU_QUERY_TTL_S = 4.0-def _cached_nvidia_gpu_query(ttl_s: float = _GPU_QUERY_TTL_S) -> "dict | None":+def _cached_nvidia_gpu_query(ttl_s: float = _GPU_QUERY_TTL_S) -> dict | None:"""One nvidia-smi read shared by the budget probe and the hardware endpoint.Returns ``dict(gpu_name=, total_bytes=, free_bytes=, used_bytes=, gpu_util_percent=,@@ -267,7 +267,7 @@ def _cached_nvidia_gpu_query(ttl_s: float = _GPU_QUERY_TTL_S) -> "dict | None":return None-def _cuda_driver_pool() -> "tuple[int, bool | None] | None":+def _cuda_driver_pool() -> tuple[int, bool | None] | None:"""(allocator_total_bytes, integrated_or_None) from the CUDA driver API via ctypes against thedriver's own DLL/SO — no toolkit, no subprocess, ~ms. INTEGRATED is the vendor's ownunified-memory declaration; total is the pool the allocator will actually hand out (on@@ -315,7 +315,7 @@ def _configured_engine():return installed_engine(section.get("backend") or "auto")-def _engine_device_pool() -> "tuple[int, bool | None] | None":+def _engine_device_pool() -> tuple[int, bool | None] | None:"""(engine_total_bytes, None) from the installed runtime's own --list-devices, or None. Thefallback when the driver API is unreachable: asks the exact binary that will do theallocating. Carries no integrated verdict — callers must gate it."""@@ -335,7 +335,7 @@ def _engine_device_pool() -> "tuple[int, bool | None] | None":return None-def _device_pool_view() -> "tuple[int, bool | None] | None":+def _device_pool_view() -> tuple[int, bool | None] | None:"""Best available allocator-side view, cached: a hit is permanent for the process, a missretries after a short TTL (the engine binary can appear mid-session via a pane install)."""global _pool_probe_cache@@ -349,10 +349,10 @@ def _device_pool_view() -> "tuple[int, bool | None] | None":return view-_accelerator_cache: "dict[str, tuple[float, dict | None]]" = {}+_accelerator_cache: dict[str, tuple[float, dict | None]] = {}-def _accelerator_device(*, fresh: bool = False) -> "dict | None":+def _accelerator_device(*, fresh: bool = False) -> dict | None:"""The device a Vulkan/HIP engine will place layers on, or None (no such engine, probe miss).Mirrors llama.cpp's own placement: discrete devices whenever one exists, an integrated one onlydiff --git a/hermes_cli/local_runtime/load_progress.py b/hermes_cli/local_runtime/load_progress.pyindex 737c32065bc..96bb1ca0b2a 100644--- a/hermes_cli/local_runtime/load_progress.py+++ b/hermes_cli/local_runtime/load_progress.py@@ -46,7 +46,7 @@ def _composite_percent(stages: list[str], current: str, value: float) -> int:return _pct(value)-def _endpoint() -> "tuple[str, str] | None":+def _endpoint() -> tuple[str, str] | None:"""(base_root, api_key) of the managed router via the ownership-guarded reader, or None."""from hermes_cli.local_runtime.endpoint import managed_root@@ -130,7 +130,7 @@ def get_loading_progress() -> dict[str, dict]:for m, e in _snapshot.items() if now - e["ts"] < _STALE_ENTRY_TTL_S}-def get_prefill_progress(model: str) -> "dict | None":+def get_prefill_progress(model: str) -> dict | None:"""{"processed": tokens} while the managed server is prompt-processing for ``model``, or None(idle, decoding, unreachable, or foreign server).diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex 8cafec173b9..7a57a7bd5a7 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -47,7 +47,7 @@ def _args_to_keys(args: list[str]) -> dict[str, str]:return keys-def _asset_path(asset) -> "Path | None":+def _asset_path(asset) -> Path | None:"""On-disk path of a catalog companion asset, or None when it isn't downloaded."""from hermes_cli.local_runtime.bootstrap import assets_dir@@ -61,8 +61,8 @@ def _asset_path(asset) -> "Path | None":class _Companions:"""The files a catalog entry loads beside its weights, as far as they are on disk."""- mmproj: "Path | None" = None- mtp_head: "Path | None" = None+ mmproj: Path | None = None+ mtp_head: Path | None = Nonenbytes: int = 0diff --git a/hermes_cli/loops.py b/hermes_cli/loops.pyindex de4f4e07ae1..ab93f87785d 100644--- a/hermes_cli/loops.py+++ b/hermes_cli/loops.py@@ -202,7 +202,7 @@ class LoopState:return json.dumps(asdict(self), ensure_ascii=False)@classmethod- def from_json(cls, raw: str) -> "LoopState":+ def from_json(cls, raw: str) -> LoopState:data = json.loads(raw)route = data.get("route")kwargs: dict[str, Any] = {@@ -638,12 +638,12 @@ LOOP_HELP = ()-def _pause_output(mgr: "LoopManager") -> str:+def _pause_output(mgr: LoopManager) -> str:state = mgr.pause(reason="user-paused")return "No loop set." if state is None else f"⏸ Loop paused: {state.prompt}\nUse /loop resume to continue."-def _resume_output(mgr: "LoopManager") -> str:+def _resume_output(mgr: LoopManager) -> str:state = mgr.resume()return "No loop to resume." if state is None else f"▶ Loop resumed ({state.cadence_label()}): {state.prompt}"@@ -659,7 +659,7 @@ _CONTROL_COMMANDS = {def dispatch_loop_command(- mgr: "LoopManager",+ mgr: LoopManager,args: str,*,route: Optional[dict[str, str]] = None,diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 0af769a0778..0289e2df5be 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -185,7 +185,7 @@ def _run_and_exit_oneshot(_exit_after_oneshot(rc)-def _warn_if_unsupervised_pid1(pid: "int | None" = None) -> None:+def _warn_if_unsupervised_pid1(pid: int | None = None) -> None:"""Warn when this process is PID 1 with nothing above it to reap orphans.The official image's ENTRYPOINT (``docker/entrypoint-dispatch.sh`` -> s6-overlay's@@ -244,7 +244,7 @@ def _set_process_title() -> None:# in: mouse-residue suppression reads this BEFORE `_apply_profile_override()`# sets HERMES_HOME, and a cache keyed on nothing pinned every later caller to# the default home's interface for the whole run (#116902).-_EARLY_INTERFACE_CACHE: "tuple[str, str] | None" = None+_EARLY_INTERFACE_CACHE: tuple[str, str] | None = Nonedef _early_interface_config_path() -> str:@@ -280,7 +280,7 @@ def _config_default_interface_early() -> str:return value-def _wants_tui_early(argv: "list[str] | None" = None) -> bool:+def _wants_tui_early(argv: list[str] | None = None) -> bool:"""Earliest TUI decision, usable before argparse/config imports.Precedence: ``--cli`` wins, then ``--tui``/``HERMES_TUI=1``, then adiff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex 2fedc9ec199..805f7b1ab29 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -315,7 +315,7 @@ def _loaded_launchd_backend_jobs(def _launchd_job_owning_backend(pid: int, cmdline: list[str] | None, jobs: list[tuple[str, str, list[str], int | None]],- ancestors: "list[int] | tuple[int, ...]" = (),+ ancestors: list[int] | tuple[int, ...] = (),) -> tuple[str, str, int | None] | None:"""``(domain, label, live_pid)`` of the loaded launchd job that owns *pid*: launchd reports *pid*(or one of its *ancestors* — a plist may wrap the backend in ``/bin/sh -c …`` without ``exec``)@@ -406,7 +406,7 @@ def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:"""from hermes_constants import get_hermes_homerespawned: list[list[str]] = []- spawned: list[tuple[list[str], list[str], "subprocess.Popen"]] = []+ spawned: list[tuple[list[str], list[str], subprocess.Popen]] = []failed: list[tuple[list[str], list[str], str]] = []log_path = get_hermes_home() / "logs" / "dashboard-restart.log"with contextlib.suppress(OSError):diff --git a/hermes_cli/main_dep_hints.py b/hermes_cli/main_dep_hints.pyindex e2f5134468a..c3808bd3f05 100644--- a/hermes_cli/main_dep_hints.py+++ b/hermes_cli/main_dep_hints.py@@ -9,7 +9,7 @@ def missing_optional_deps_message(surface: str, what: str, extra: str) -> str:)-def smart_app_control_block_message(error: BaseException) -> "str | None":+def smart_app_control_block_message(error: BaseException) -> str | None:"""Guidance for Windows Smart App Control / Application Control blocking the embeddedPython runtime's ``_ssl`` module, or ``None`` when *error* is not that case.diff --git a/hermes_cli/mcp_startup.py b/hermes_cli/mcp_startup.pyindex 09e052a12e5..80ff0cfb46b 100644--- a/hermes_cli/mcp_startup.py+++ b/hermes_cli/mcp_startup.py@@ -151,7 +151,7 @@ def start_background_mcp_discovery(*, logger, thread_name: str) -> None:thread.start()-def _resolve_discovery_timeout(explicit: "float | None", *, single_query: bool = False) -> float:+def _resolve_discovery_timeout(explicit: float | None, *, single_query: bool = False) -> float:"""Resolve the MCP discovery wait bound: explicit arg > config.yaml > ``DEFAULT_CONFIG``.Lazy and fail-safe: a missing/invalid value or broken config falls back to a short bound so@@ -257,7 +257,7 @@ def start_deferred_mcp_discovery_now() -> None:timer.function()-def wait_for_mcp_discovery(timeout: "float | None" = None, *, single_query: bool = False) -> None:+def wait_for_mcp_discovery(timeout: float | None = None, *, single_query: bool = False) -> None:"""Wait for background MCP discovery before the first tool snapshot.``join`` returns the instant discovery completes, so this only blocks for a still-pending@@ -290,7 +290,7 @@ def mcp_discovery_in_flight() -> bool:return thread is not None and thread.is_alive()-def join_mcp_discovery(timeout: "float | None" = None) -> bool:+def join_mcp_discovery(timeout: float | None = None) -> bool:"""Block up to ``timeout`` for THIS module's discovery; True once complete, False if stillrunning. For the off-critical-path late-refresh waiter (accepts a long wait, reports outcome)."""thread = _current_home_thread()@@ -303,7 +303,7 @@ def join_mcp_discovery(timeout: "float | None" = None) -> bool:def ensure_mcp_discovery_before_agent_build(*,logger,- timeout: "float | None" = None,+ timeout: float | None = None,single_query: bool = False,thread_name: str = "cli-mcp-discovery") -> None:"""Give configured MCP tools a bounded chance to register before AIAgent.diff --git a/hermes_cli/model_catalog.py b/hermes_cli/model_catalog.pyindex 4a94b1316b8..a23e3afc203 100644--- a/hermes_cli/model_catalog.py+++ b/hermes_cli/model_catalog.py@@ -324,7 +324,7 @@ def get_default_model_from_cache(provider: str) -> str | None:return _default_model_from_block(_block_of(disk_data, provider)) if disk_data is not None else None-def seed_cache_from_checkout(project_root: "Path | str") -> bool:+def seed_cache_from_checkout(project_root: Path | str) -> bool:"""Overwrite the disk cache with the checkout's ``website/static/api/model-catalog.json``.After ``hermes update`` that file IS the newest catalog, so the picker stays current even whenthe remote fetch is bot-gated. Validated, then written via the same atomic writer."""diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 941ac7a569a..845735954e1 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -718,7 +718,7 @@ class AmbiguousAliasError(Exception):super().__init__(f"alias {alias!r} matches {len(candidates)} models on {provider}")-def _ambiguous_alias_message(err: "AmbiguousAliasError") -> str:+def _ambiguous_alias_message(err: AmbiguousAliasError) -> str:"""User-facing disambiguation list for an ambiguous alias."""shown = err.candidates[:10]lines = "\n".join(f" {i}. {m}" for i, m in enumerate(shown, 1))@@ -981,7 +981,7 @@ def _duplicates_configured_row(if identity == row or (provider_key == row_slug.lower() and identity[1:3] == row[1:3])), None)-def _current_provider_match(st: "_Switch", cfg_matches: dict[str, str]) -> Optional[str]:+def _current_provider_match(st: _Switch, cfg_matches: dict[str, str]) -> Optional[str]:"""The slug in *cfg_matches* the session already runs on: an exact hit, or — for a session onthe compat projection slug (``custom:relay``) of ``providers.relay`` — that row's slug, so asame-provider switch keeps the caller's slug instead of flipping it (#112788)."""@@ -1105,7 +1105,7 @@ def _config_declares_model(return False-def _apply_direct_alias_endpoint(st: "_Switch", da: DirectAlias) -> None:+def _apply_direct_alias_endpoint(st: _Switch, da: DirectAlias) -> None:"""Route a direct alias to its own base_url and decide its credential (mutates ``st``).Credentials were resolved against the DEFAULT provider; carrying that key onto the aliasdiff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.pyindex 413721cf4c9..7a7ad6d665e 100644--- a/hermes_cli/model_switch_providers.py+++ b/hermes_cli/model_switch_providers.py@@ -183,7 +183,7 @@ def _credential_pool_is_usable(provider: str, *, raw_pool_present: bool = False,return raw_pool_present-def prewarm_picker_cache_async() -> Optional["_threading.Thread"]:+def prewarm_picker_cache_async() -> Optional[_threading.Thread]:"""Warm ``provider_models_cache.json`` in a daemon thread by running the picker path once.The first ``/model`` open (or the first after the 1h TTL) otherwise blocks ~1-2s on serialdiff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 704e060c7b7..8bbbb0baace 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -361,7 +361,7 @@ _NOUS_RECOMMENDED_CACHE_TTL: int = 600 # seconds (10 minutes)_nous_recommended_cache: dict[tuple[str, str], tuple[dict[str, Any], float]] = {}-def _nous_recommended_disk_path() -> "Path":+def _nous_recommended_disk_path() -> Path:from hermes_constants import get_hermes_homereturn get_hermes_home() / "cache" / "nous_recommended_cache.json"@@ -2899,7 +2899,7 @@ def _custom_endpoint_fingerprint(def _cache_entry_valid(- entry: Any, fp: str, *, allow_empty: bool = False) -> "TypeGuard[dict[str, Any]]":+ entry: Any, fp: str, *, allow_empty: bool = False) -> TypeGuard[dict[str, Any]]:"""Well-formed cache row for fingerprint *fp*. Requires a numeric ``at`` so corrupt disk statedegrades to a cache miss instead of raising; empty model lists are valid only when the calleropts into an authoritative empty catalog."""diff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.pyindex 6dbcf4a424c..deefb45603e 100644--- a/hermes_cli/models_validate.py+++ b/hermes_cli/models_validate.py@@ -49,7 +49,7 @@ class _Match:exact: bool = Falsesuggestion_text: str = ""- def verdict(self, req: "_Request") -> Optional[dict[str, Any]]:+ def verdict(self, req: _Request) -> Optional[dict[str, Any]]:"""Accept on exact membership, else None so the branch composes its own message."""return _accept() if self.exact else Nonediff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.pyindex 921a4a49d21..068867fece0 100644--- a/hermes_cli/nous_account.py+++ b/hermes_cli/nous_account.py@@ -20,7 +20,7 @@ NousAccountInfoSource = Literal["jwt", "account_api", "inference_key", "none", "TOOL_COVERAGE_CATEGORIES = ("firecrawl", "fal", "fal-video", "openai-audio", "browser-use", "modal")_ACCOUNT_INFO_CACHE_TTL = 60-_account_info_cache: tuple[str, float, "NousPortalAccountInfo"] | None = None+_account_info_cache: tuple[str, float, NousPortalAccountInfo] | None = None_ACCOUNT_INFO_CACHE_LOCK = threading.Lock()@@ -73,7 +73,7 @@ FREE_TIER_NEEDS_ACCOUNT = "This needs a Nous account. Run `hermes auth upgrade`.FREE_TIER_NEEDS_ACCOUNT_CHAT = "This needs a Nous account. Use /login to sign in."-def _is_anonymous_tier(account_info: Optional["NousPortalAccountInfo"]) -> bool:+def _is_anonymous_tier(account_info: Optional[NousPortalAccountInfo]) -> bool:return account_info is not None and account_info.is_anonymous_tierdiff --git a/hermes_cli/nous_billing.py b/hermes_cli/nous_billing.pyindex 71269138230..3cbc0419832 100644--- a/hermes_cli/nous_billing.py+++ b/hermes_cli/nous_billing.py@@ -135,7 +135,7 @@ def invalidate_cached_token() -> None:_token_cache.clear()-def _billing_not_logged_in(exc: Optional[BaseException] = None) -> "BillingAuthError":+def _billing_not_logged_in(exc: Optional[BaseException] = None) -> BillingAuthError:"""Build the canonical 'not logged in' BillingAuthError (single source)."""err = BillingAuthError("Not logged into Nous Portal — run `hermes portal` to log in.", status=401, error="invalid_token")if exc is not None:diff --git a/hermes_cli/platforms.py b/hermes_cli/platforms.pyindex 8fda766d159..f866902a9ef 100644--- a/hermes_cli/platforms.py+++ b/hermes_cli/platforms.py@@ -55,7 +55,7 @@ def platform_label(key: str, default: str = "") -> str:return default-def get_all_platforms() -> "OrderedDict[str, PlatformInfo]":+def get_all_platforms() -> OrderedDict[str, PlatformInfo]:"""PLATFORMS plus plugin-registered platforms (appended after builtins) — use for menus."""merged = OrderedDict(PLATFORMS)try:diff --git a/hermes_cli/plugin_dev.py b/hermes_cli/plugin_dev.pyindex 7151703e763..bee268a5607 100644--- a/hermes_cli/plugin_dev.py+++ b/hermes_cli/plugin_dev.py@@ -273,7 +273,7 @@ def _accepts_var_kwargs(callback: Any) -> bool:return any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters)-def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:+def _check_manifest_v2(report: DoctorReport, manifest: Any) -> None:"""Manifest v2 checks: versions, deps, pip declarations, config schema."""import importlib.metadataimport re as _rediff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.pyindex 6faa9f4b812..b0cd37ee545 100644--- a/hermes_cli/plugin_host.py+++ b/hermes_cli/plugin_host.py@@ -327,19 +327,19 @@ class PluginHost:return self._call("invoke", {"ref": ref, "args": encode(list(args)), "kwargs": encode(kwargs)},generation=generation)- def obj_invoke(self, slot: "_ObjectSlot", method: str, args: tuple, kwargs: dict) -> Any:+ def obj_invoke(self, slot: _ObjectSlot, method: str, args: tuple, kwargs: dict) -> Any:ref, generation = slot.live()return self._call("obj_invoke", {"ref": ref, "method": method, "args": encode(list(args)),"kwargs": encode(kwargs)}, generation=generation)- def obj_getattr(self, slot: "_ObjectSlot", name: str) -> Any:+ def obj_getattr(self, slot: _ObjectSlot, name: str) -> Any:ref, generation = slot.live()value = self._call("obj_getattr", {"ref": ref, "name": name}, generation=generation)if isinstance(value, dict) and set(value) == {"__missing__"}:raise AttributeError(name)return value- def obj_setattr(self, slot: "_ObjectSlot", name: str, value: Any) -> None:+ def obj_setattr(self, slot: _ObjectSlot, name: str, value: Any) -> None:ref, generation = slot.live()self._call("obj_setattr", {"ref": ref, "name": name, "value": encode(value)}, generation=generation)diff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.pyindex 5dd640e98ee..c9aee6a290a 100644--- a/hermes_cli/plugin_host_child.py+++ b/hermes_cli/plugin_host_child.py@@ -41,7 +41,7 @@ _ENTRY_POINTS_GROUP = "hermes_agent.plugins"class RemoteRegistration:"""Child-side twin of ``PluginRegistration``: ``dispose()`` releases the Hermes-side entry."""- def __init__(self, runtime: "HostRuntime", handle_id: int, kind: str, key: str):+ def __init__(self, runtime: HostRuntime, handle_id: int, kind: str, key: str):self._runtime, self._id, self.kind, self.key = runtime, handle_id, kind, keyself._disposed = False@@ -59,7 +59,7 @@ class RemoteRegistration:class RemoteFacade:"""``ctx.state`` / ``ctx.llm`` / ...: every method call runs on the Hermes-side facade."""- def __init__(self, runtime: "HostRuntime", plugin_key: str, name: str):+ def __init__(self, runtime: HostRuntime, plugin_key: str, name: str):self._runtime, self._plugin_key, self._name = runtime, plugin_key, nameself._methods: dict[str, bool] = {} # method name -> is a coroutine function in Hermes@@ -86,7 +86,7 @@ class RemotePluginContext:"""What ``register(ctx)`` receives inside the host. Mirrors ``PluginContext``'s public surface asannounced by Hermes at load, so ``hasattr(ctx, "register_x")`` answers the same as in-process."""- def __init__(self, runtime: "HostRuntime", plugin_key: str, info: dict[str, Any]):+ def __init__(self, runtime: HostRuntime, plugin_key: str, info: dict[str, Any]):self._runtime, self._plugin_key = runtime, plugin_keyself._methods = set(info.get("ctx_methods") or ())self._facades: dict[str, RemoteFacade] = {}diff --git a/hermes_cli/plugin_host_wire.py b/hermes_cli/plugin_host_wire.pyindex 3cab022cdee..ff336a76e9c 100644--- a/hermes_cli/plugin_host_wire.py+++ b/hermes_cli/plugin_host_wire.py@@ -211,7 +211,7 @@ class Channel:self._closed_reason: Optional[str] = Noneself._thread = threading.Thread(target=self._read_loop, name=f"{name}-reader", daemon=True)- def start(self) -> "Channel":+ def start(self) -> Channel:self._thread.start()return selfdiff --git a/hermes_cli/plugin_validate_desktop.py b/hermes_cli/plugin_validate_desktop.pyindex db94523803d..c5915012a46 100644--- a/hermes_cli/plugin_validate_desktop.py+++ b/hermes_cli/plugin_validate_desktop.py@@ -14,7 +14,7 @@ from pathlib import Pathfrom typing import List, Tuple# (rule, regex) applied to comment-stripped source; every hit fails the "desktop surface" check.-_FORBIDDEN: tuple[tuple[str, "re.Pattern[str]"], ...] = (+_FORBIDDEN: tuple[tuple[str, re.Pattern[str]], ...] = (("prototype patching",re.compile(r"\b[A-Za-z_$][\w$]*\.prototype\.[\w$]+\s*=[^=]")),("prototype patching",diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 42150596f8f..a652179cd4a 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -230,7 +230,7 @@ class LoadedPlugin:class PluginContext:"""Facade given to plugins so they can register tools and hooks."""- def __init__(self, manifest: PluginManifest, manager: "PluginManager"):+ def __init__(self, manifest: PluginManifest, manager: PluginManager):self.manifest = manifestself._manager = managerself._llm: Any = None # lazy; tests preseed it (see ``llm``)@@ -415,7 +415,7 @@ class PluginContext:logger.debug("Plugin %s registered on_unload callback", self.manifest.name)return handle- def spawn_task(self, coro, *, name: Optional[str] = None) -> "asyncio.Task":+ def spawn_task(self, coro, *, name: Optional[str] = None) -> asyncio.Task:"""Spawn a supervised asyncio task; unload/force reload cancels it. Needs a running loop."""if not asyncio.iscoroutine(coro):raise TypeError("spawn_task expects a coroutine")@@ -1815,7 +1815,7 @@ def _persist_plugin_toolset_keys() -> None:logger.debug("plugin toolset key persist failed", exc_info=True)-def _nowait_plugin_set(cache_field: str, live: Callable[[PluginManager], "set[str]"]) -> "set[str]":+def _nowait_plugin_set(cache_field: str, live: Callable[[PluginManager], set[str]]) -> set[str]:"""Shared body of the ``*_nowait`` probes: live registry, else last launch's cache, else block."""manager = get_plugin_manager()t = _background_discovery_thread@@ -1832,14 +1832,14 @@ def _nowait_plugin_set(cache_field: str, live: Callable[[PluginManager], "set[streturn live(manager)-def get_plugin_toolset_keys_nowait() -> "set[str]":+def get_plugin_toolset_keys_nowait() -> set[str]:"""Plugin toolset keys without blocking on in-flight discovery: live registry when done, lastlaunch's persisted set while a background scan runs (callers only EXCLUDE these keys, so a staleset is harmless and self-heals), else block via discover_plugins()."""return _nowait_plugin_set("toolset_keys", lambda _m: {ts_key for ts_key, _, _ in get_plugin_toolsets()})-def get_portable_mcp_server_names_nowait() -> "set[str]":+def get_portable_mcp_server_names_nowait() -> set[str]:"""Portable MCP server names; same contract as :func:`get_plugin_toolset_keys_nowait`."""return _nowait_plugin_set("portable_mcp", lambda m: set(m.get_portable_mcp_servers()))@@ -2049,7 +2049,7 @@ def resolve_pre_tool_block(def _resolve_block_from_details(- details: "_PreToolCallDirective", tool_name: str, *, turn_id: str = "", tool_call_id: str = "",+ details: _PreToolCallDirective, tool_name: str, *, turn_id: str = "", tool_call_id: str = "",session_id: str = "",) -> Optional[str]:"""The ONE place for the fail-closed approval logic: ``block`` blocks with its message; andiff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 75a4f500f50..517521e1c64 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -885,7 +885,7 @@ def _category_active_names() -> set:def _plugin_status(name: str, enabled: set, disabled: set, key: str = "", *, source: str = "",- dir_path=None, active: "frozenset | set" = frozenset()) -> str:+ dir_path=None, active: frozenset | set = frozenset()) -> str:"""User-facing activation state for a plugin name or key. Mirrors ``gate_manifest``: an explicitdisable wins, then the allow-list, then the activations that need no list entry — bundledbackends/platforms and model providers from any source (*source* + *dir_path*) and category-selected providersdiff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.pyindex 3f06aced8ff..29088a55529 100644--- a/hermes_cli/plugins_cmd_install.py+++ b/hermes_cli/plugins_cmd_install.py@@ -60,7 +60,7 @@ class _ConsentRefusal(str):"""A refusal reason (user-facing text) carrying its closed extension-install ``failure_class``,so publication classifies the refusal without matching the copy."""- def __new__(cls, text: str, failure_class: str) -> "_ConsentRefusal":+ def __new__(cls, text: str, failure_class: str) -> _ConsentRefusal:refusal = super().__new__(cls, text)refusal.failure_class = failure_classreturn refusaldiff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.pyindex c76badc8f1e..ff4547a32f8 100644--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@ -69,7 +69,7 @@ def _select_entry_point_group(entry_points: Any, group: str) -> list:return [ep for ep in entry_points if ep.group == group]-def discover_entrypoint_manifests() -> list["PluginManifest"]:+def discover_entrypoint_manifests() -> list[PluginManifest]:"""Return metadata-only manifests for installed entry-point plugins. Kind comes from an import-free sourcescan (memory/model providers route to their own discovery). Capabilities come from the companion``hermes_agent.plugin_capabilities`` group (``<plugin-id>.<capability-id>`` entries pointing at the samediff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.pyindex ca06386262f..5df35196b72 100644--- a/hermes_cli/plugins_ledger.py+++ b/hermes_cli/plugins_ledger.py@@ -40,7 +40,7 @@ class PluginRegistration:# See #91701.persistent: bool = False_disposed: bool = field(default=False, init=False, repr=False)- _on_dispose: Optional[Callable[["PluginRegistration"], None]] = field(default=None, init=False, repr=False)+ _on_dispose: Optional[Callable[[PluginRegistration], None]] = field(default=None, init=False, repr=False)@propertydef active(self) -> bool:diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 1b5c1b950ab..4d4505659ce 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -48,7 +48,7 @@ _LOADER_THREAD_PREFIX = "plugin-load:" # names each deadline-bounded load worke_ABANDONED_LOADERS: list[threading.Thread] = []_ABANDONED_LOADERS_LOCK = threading.Lock()# PluginContexts of the outermost deadline-bounded load; set only inside its worker.-_IN_PLUGIN_LOAD: contextvars.ContextVar[Optional[list["PluginContext"]]] = contextvars.ContextVar(+_IN_PLUGIN_LOAD: contextvars.ContextVar[Optional[list[PluginContext]]] = contextvars.ContextVar("hermes_plugin_load_scope", default=None,)@@ -101,7 +101,7 @@ def _reserve_abandoned_loader_slot() -> None:)-def run_with_load_deadline(plugin_key: str, ctx: "PluginContext", fn: Callable[[], Any]) -> Any:+def run_with_load_deadline(plugin_key: str, ctx: PluginContext, fn: Callable[[], Any]) -> Any:"""Run ``fn`` (a plugin's import + ``register()``) under the per-plugin deadline.The worker inherits the caller's context (the Hermes-home override is a ContextVar). On timeout thediff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex 493e3a61728..ec09ac3987e 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -216,7 +216,7 @@ def validate_config_schema(plugin_id: str, schema: Mapping, settings: Mapping) -return warnings-def resolve_plugin_load_order(manifests: Mapping[str, "PluginManifest"]) -> list[str]:+def resolve_plugin_load_order(manifests: Mapping[str, PluginManifest]) -> list[str]:"""Return plugin keys in dependency order: B before A when A requires B; alphabetical ties. A cycle warnsand falls back to alphabetical order for all; a missing dependency warns once but never removes thedependent plugin (loads never hard-fail on advisory deps).@@ -333,7 +333,7 @@ def _resolve_module_source(module_name: str, limit: int = 8192) -> str:return _read_source_from_origin(resolve_module_origin(module_name), limit)-def manifest_key(manifest: "PluginManifest") -> str:+def manifest_key(manifest: PluginManifest) -> str:"""Registry id of a manifest: the path-derived ``key`` when set, else the bare ``name``."""return manifest.key or manifest.name@@ -475,7 +475,7 @@ def version_satisfies(spec: str, current: str) -> bool:return True-def requires_hermes_error(manifest: "PluginManifest") -> Optional[str]:+def requires_hermes_error(manifest: PluginManifest) -> Optional[str]:"""Load-blocking reason when the manifest's ``requires_hermes`` rejects the running version."""spec = manifest.get("requires_hermes", "") if isinstance(manifest, Mapping) else manifest.requires_hermesif not spec:diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.pyindex 181a4d63336..53cd959fbf8 100644--- a/hermes_cli/profile_distribution.py+++ b/hermes_cli/profile_distribution.py@@ -80,7 +80,7 @@ class EnvRequirement:default: Optional[str] = None@classmethod- def from_dict(cls, data: Any) -> "EnvRequirement":+ def from_dict(cls, data: Any) -> EnvRequirement:if not isinstance(data, dict):raise DistributionError(f"env_requires entry must be a mapping, got {type(data).__name__}")name = _str(data, "name").strip()@@ -116,7 +116,7 @@ class DistributionManifest:installed_at: str = ""@classmethod- def from_dict(cls, data: Any) -> "DistributionManifest":+ def from_dict(cls, data: Any) -> DistributionManifest:if not isinstance(data, dict):raise DistributionError(f"{MANIFEST_FILENAME} must be a mapping, got {type(data).__name__}")name = _str(data, "name").strip()diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex d3c18e8cf5d..f741c724574 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -450,7 +450,7 @@ def profile_exists(name: str) -> bool:return named_profile_is_live(profile_dir)-def profile_matches_home(name: str, home: "Path | None" = None) -> bool:+def profile_matches_home(name: str, home: Path | None = None) -> bool:"""True when *name* refers to the profile served from *home* (default: current home).Lets single-profile gateways decide whether a ``/p/<profile>/`` URL prefix isdiff --git a/hermes_cli/proxy/server.py b/hermes_cli/proxy/server.pyindex 9617dcd3198..49575154482 100644--- a/hermes_cli/proxy/server.py+++ b/hermes_cli/proxy/server.py@@ -49,7 +49,7 @@ def _require_aiohttp() -> None:raise RuntimeError("aiohttp is required for `hermes proxy`. Run `hermes setup` to install it.")-def _json_error(status: int, message: str, code: str = "proxy_error") -> "web.Response":+def _json_error(status: int, message: str, code: str = "proxy_error") -> web.Response:"""OpenAI-style error JSON response."""body = {"error": {"message": message, "type": code, "code": code}}return web.json_response(body, status=status)@@ -126,7 +126,7 @@ def _filter_headers(headers, drop: frozenset = _HOP_BY_HOP_HEADERS) -> dict:return {key: value for key, value in headers.items() if key.lower() not in drop}-async def _open_upstream(request: "web.Request", rel_path: str, body: bytes, cred: UpstreamCredential):+async def _open_upstream(request: web.Request, rel_path: str, body: bytes, cred: UpstreamCredential):"""Send the request upstream with ``cred``; returns ``(session, response)`` or``(error_response, None)``."""upstream_url = f"{cred.base_url.rstrip('/')}{rel_path}"@@ -159,7 +159,7 @@ async def _open_upstream(request: "web.Request", rel_path: str, body: bytes, crereturn session, upstream_resp-async def _stream_back(request: "web.Request", session, upstream_resp) -> "web.StreamResponse":+async def _stream_back(request: web.Request, session, upstream_resp) -> web.StreamResponse:"""Relay status + filtered headers, then the body chunk-by-chunk, appending a missing SSE``[DONE]`` only after a clean EOF."""resp = web.StreamResponse(@@ -191,7 +191,7 @@ async def _stream_back(request: "web.Request", session, upstream_resp) -> "web.Sreturn resp-def create_app(adapter: UpstreamAdapter, bound_host: str = DEFAULT_HOST) -> "web.Application":+def create_app(adapter: UpstreamAdapter, bound_host: str = DEFAULT_HOST) -> web.Application:"""Build the aiohttp application bound to a specific upstream adapter.Every adapter method is synchronous and blocking (the Nous adapter takes the 15s cross-process@@ -206,7 +206,7 @@ def create_app(adapter: UpstreamAdapter, bound_host: str = DEFAULT_HOST) -> "weballowed_hosts = _LOOPBACK_HOSTS | {bound}@web.middleware- async def local_only(request: "web.Request", handler):+ async def local_only(request: web.Request, handler):refusal = _local_request_error(request.headers.get("Host", ""),request.headers.get("Origin"),@@ -226,11 +226,11 @@ def create_app(adapter: UpstreamAdapter, bound_host: str = DEFAULT_HOST) -> "web# AppKey: forward-compat with aiohttp versions that strip bare-string keys.app[web.AppKey("adapter", UpstreamAdapter)] = adapter- async def handle_health(request: "web.Request") -> "web.Response":+ async def handle_health(request: web.Request) -> web.Response:authenticated = await asyncio.to_thread(adapter.is_authenticated)return web.json_response({"status": "ok", "upstream": adapter.display_name, "authenticated": authenticated})- async def handle_proxy(request: "web.Request") -> "web.StreamResponse":+ async def handle_proxy(request: web.Request) -> web.StreamResponse:rel_path = "/" + request.match_info.get("tail", "").lstrip("/")if rel_path not in adapter.allowed_paths:allowed = ", ".join(sorted(adapter.allowed_paths))diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.pyindex eebeace42b1..431ff6ea662 100644--- a/hermes_cli/pty_bridge.py+++ b/hermes_cli/pty_bridge.py@@ -108,7 +108,7 @@ class PtyBridge:WebSocket task, never the dashboard event loop."""- def __init__(self, proc: "ptyprocess.PtyProcess"): # type: ignore[name-defined]+ def __init__(self, proc: ptyprocess.PtyProcess): # type: ignore[name-defined]self._proc = procself._fd: int = proc.fdself._closed = False@@ -128,7 +128,7 @@ class PtyBridge:@classmethoddef spawn(cls, argv: Sequence[str], *, cwd: Optional[str] = None, env: Optional[dict] = None, cols: int = 80, rows: int = 24- ) -> "PtyBridge":+ ) -> PtyBridge:"""Spawn ``argv`` behind a new PTY and return a bridge."""if not _PTY_AVAILABLE:if sys.platform.startswith("win"):@@ -374,7 +374,7 @@ class PtyBridge:except Exception:pass- def __enter__(self) -> "PtyBridge":+ def __enter__(self) -> PtyBridge:return selfdef __exit__(self, *_exc) -> None:diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 4eaf43dccc9..a6976023996 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -208,7 +208,7 @@ class RegistryFull(Exception):super().__init__(message)-async def run_reaper(registry: "PtySessionRegistry", *, interval: float = 60.0) -> None:+async def run_reaper(registry: PtySessionRegistry, *, interval: float = 60.0) -> None:"""Periodically reap idle/dead keep-alive sessions. Cancelled on shutdown."""while True:await asyncio.sleep(interval)@@ -352,7 +352,7 @@ class PtySessionRegistry:self._sessions.pop(oldest.key, None)self._close_in_background(oldest)- def _close_in_background(self, session: "PtySession") -> None:+ def _close_in_background(self, session: PtySession) -> None:task = asyncio.create_task(session.close())self._background_closes.add(task)task.add_done_callback(self._background_closes.discard)diff --git a/hermes_cli/route_identity.py b/hermes_cli/route_identity.pyindex 56d3a2e7b33..01be9fa61c5 100644--- a/hermes_cli/route_identity.py+++ b/hermes_cli/route_identity.py@@ -83,7 +83,7 @@ def provider_owns_route(provider: Any, base_url: Any, config: Any = None) -> Optreturn normalize_provider(inferred) == canonical-def drop_stale_model_route(model_cfg: Any, provider: Any, config: Any = None) -> "tuple[dict[str, Any], bool]":+def drop_stale_model_route(model_cfg: Any, provider: Any, config: Any = None) -> tuple[dict[str, Any], bool]:"""Pop the route keys (``base_url``, ``api_mode``) a previous provider left in ``model:``when the block is re-pointed at *provider* without a fresh route (``hermes config setmodel.provider``). Mirrors what a persisted ``/model`` switch writes: the route is synced todiff --git a/hermes_cli/sessions_repair_profiles.py b/hermes_cli/sessions_repair_profiles.pyindex eadb669f4de..83637edd3e1 100644--- a/hermes_cli/sessions_repair_profiles.py+++ b/hermes_cli/sessions_repair_profiles.py@@ -61,7 +61,7 @@ class Finding:detail: straction: Optional[str] = None # what --apply does; None = report onlyreason: Optional[str] = None # why it is report only- _fix: Optional[Callable[["_Session"], dict[str, int]]] = field(default=None, repr=False, compare=False)+ _fix: Optional[Callable[[_Session], dict[str, int]]] = field(default=None, repr=False, compare=False)@propertydef repairable(self) -> bool:@@ -167,7 +167,7 @@ class RepairPlan:self.legacy_main = legacy_mainself.multiplexes = _gateway_multiplexes(self.routing_store.home) if self.routing_store else Falseself.findings: list[Finding] = []- self._moves: dict[tuple[Path, Path], "_MoveBatch"] = {}+ self._moves: dict[tuple[Path, Path], _MoveBatch] = {}# -- helpers --def _add(self, finding: Finding) -> None:@@ -178,7 +178,7 @@ class RepairPlan:return [f for f in self.findings if f.repairable]# -- scan --- def scan(self, session: _Session) -> "RepairPlan":+ def scan(self, session: _Session) -> RepairPlan:for store in self.stores:self._scan_sessions(session, store)self._scan_topics(session, store)@@ -249,7 +249,7 @@ class RepairPlan:reason="either a standalone gateway's own history (--legacy-main rekey) or a default ""chat that leaked in (--legacy-main move); the row cannot say which"))- def _move_batch(self, src: Store, dst: Store) -> "_MoveBatch":+ def _move_batch(self, src: Store, dst: Store) -> _MoveBatch:return self._moves.setdefault((src.db_path, dst.db_path), _MoveBatch(src, dst))def _scan_topics(self, session: _Session, store: Store) -> None:diff --git a/hermes_cli/ssh_workspace_fs.py b/hermes_cli/ssh_workspace_fs.pyindex 7814309235c..dff054088e7 100644--- a/hermes_cli/ssh_workspace_fs.py+++ b/hermes_cli/ssh_workspace_fs.py@@ -35,7 +35,7 @@ class _SshFsConfig:_CACHE_LOCK = threading.RLock()-_BACKENDS: dict[str, tuple[_SshFsConfig, "SshWorkspaceFs"]] = {}+_BACKENDS: dict[str, tuple[_SshFsConfig, SshWorkspaceFs]] = {}class SshWorkspaceFs:diff --git a/hermes_cli/steward.py b/hermes_cli/steward.pyindex 96e7423c4dc..135091e1770 100644--- a/hermes_cli/steward.py+++ b/hermes_cli/steward.py@@ -165,7 +165,7 @@ def steward_update_message(steward: str) -> str:return _STEWARD_UPDATE_FALLBACK.format(steward=steward)-def steward_uninstall_message(steward: str, platform: "str | None" = None) -> str:+def steward_uninstall_message(steward: str, platform: str | None = None) -> str:"""The uninstall refusal text for a sealed tree."""if steward == STEWARD_DESKTOP:key = platform if platform is not None else sys.platform@@ -223,7 +223,7 @@ def sealed_steward(project_root: Path) -> Optional[str]:return distribution if isinstance(distribution, str) and distribution else "unknown"-def classify_install(project_root: Path) -> "tuple[str, bool]":+def classify_install(project_root: Path) -> tuple[str, bool]:"""(steward, code_removal_allowed) for the tree at ``project_root``.A git checkout reports ``("git", True)``; a sealed tree reports itsdiff --git a/hermes_cli/stream_json.py b/hermes_cli/stream_json.pyindex d134f3eff25..6c3b19bf754 100644--- a/hermes_cli/stream_json.py+++ b/hermes_cli/stream_json.py@@ -43,7 +43,7 @@ class StreamJsonEmitter:self._tool_started: dict[str, float] = {}self._emit({"type": "system", "subtype": "init", "model": model, "session_id": session_id})- def attach(self, agent) -> "StreamJsonEmitter":+ def attach(self, agent) -> StreamJsonEmitter:"""Route the agent's streaming/tool callbacks into this emitter (``init`` was already written atconstruction, before credentials/agent init, so a failed start still yields init + result)."""agent.stream_delta_callback = self.on_text_deltadiff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.pyindex 6ec507d9266..6288dd9ff90 100644--- a/hermes_cli/uninstall.py+++ b/hermes_cli/uninstall.py@@ -67,7 +67,7 @@ def get_project_root() -> Path:return Path(__file__).parent.parent.resolve()-def code_removal_refusal() -> "str | None":+def code_removal_refusal() -> str | None:"""Why the uninstaller must not remove this tree's code, or ``None``.A git checkout (the install.sh / install.ps1 / `hermes desktop` layout)@@ -188,7 +188,7 @@ def remove_wrapper_script():return removed-def _node_symlink_candidate_dirs() -> "list[Path]":+def _node_symlink_candidate_dirs() -> list[Path]:"""Directories where the installer may have placed node/npm/npx symlinks."""dirs: list[Path] = [Path.home() / ".local" / "bin"]if sys.platform == "linux": # root FHS installs put links in /usr/local/bin@@ -304,7 +304,7 @@ _LAUNCHD_GATEWAY_PLIST_PATTERNS = ()-def _launchd_gateway_plists() -> "list[Path]":+def _launchd_gateway_plists() -> list[Path]:"""Every gateway LaunchAgent plist on disk, under the real account home."""from hermes_cli.gateway import get_launchd_plist_path@@ -437,7 +437,7 @@ def remove_portable_tooling_windows(hermes_home: Path) -> list[Path]:return _remove_each((t for t in targets if t.exists()), lambda t: shutil.rmtree(t) or True)-def _xdg_leftover_paths(full_uninstall: bool) -> "tuple[list[Path], list[Path]]":+def _xdg_leftover_paths(full_uninstall: bool) -> tuple[list[Path], list[Path]]:"""The XDG cache/data dirs an install scatters outside HERMES_HOME.Returns (removable, data_preserved): the cache dir is always removable;@@ -915,7 +915,7 @@ def _rmtree_step(path: Path, *, indent: str = "", fully: bool = True) -> None:log_info("You may need to manually remove it")-def _macos_cache_leftover_dirs() -> "list[Path]":+def _macos_cache_leftover_dirs() -> list[Path]:"""Cache dirs Electron/Chromium and the setup binary write OUTSIDE HERMES_HOME onmacOS. Chromium splits the desktop app's HTTP/script caches under ``~/Library/Caches``keyed by both the product name and the app id, and the Tauri setup binary does the@@ -938,7 +938,7 @@ def _rmtree_if_exists(path: Path) -> bool:return True-def remove_dashboard_launchd_jobs() -> "list[Path]":+def remove_dashboard_launchd_jobs() -> list[Path]:"""macOS: boot out and delete every launchd job whose ``ProgramArguments`` runs a``hermes dashboard`` / ``hermes serve`` backend, returning the removed plist paths.@@ -960,7 +960,7 @@ def remove_dashboard_launchd_jobs() -> "list[Path]":from hermes_cli.main_dashboard import _launchd_plist_dirs, _parse_dashboard_runtimeuid = os.getuid() # windows-footgun: ok — darwin-only branch- removed: "list[Path]" = []+ removed: list[Path] = []for kind, plist_dir in _launchd_plist_dirs():try:plists = sorted(plist_dir.glob("*.plist"))diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.pyindex 0950e3e917c..58ac7a0ffc3 100644--- a/hermes_cli/update_abort_recovery.py+++ b/hermes_cli/update_abort_recovery.py@@ -91,7 +91,7 @@ def _qualified_serve_skips(skip_units) -> list[dict]:def _run_fresh_recovery_process(profiles, candidates, *, gateway_mode: bool, recover_serve: bool, skip_units-) -> "subprocess.CompletedProcess | None":+) -> subprocess.CompletedProcess | None:"""Spawn ``hermes_cli.update_restart_recovery --stdin`` detached from this process; None when itcould not run (no systemd-run in gateway mode, OSError, timeout) — the caller fails closed."""command = [sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"]diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex c43e7eb590f..7b8223900f7 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1319,12 +1319,12 @@ def _missing_branch_stop(git_cmd, branch) -> str:class _CheckoutPlan:"""What the pre-pull checkout phase decided (see ``_prepare_checkout_for_update``)."""- auto_stash_ref: "str | None"+ auto_stash_ref: str | Nonecommit_count: intin_place_update: boolparked_branch_switched: boolprompt_for_restore: bool- switch_block_reason: "str | None"+ switch_block_reason: str | Noneupstream_checked: boolpre_sync_sha: str | None = Nonerollback_branch: str | None = None@@ -1334,7 +1334,7 @@ class _CheckoutPlan:def _apply_parked_branch_guard(git_cmd, branch, current_branch, *, switch_branch, _windows_gateway_resume-) -> tuple[bool, bool, "str | None"]:+) -> tuple[bool, bool, str | None]:"""Decide how a checkout parked on another branch is brought to *branch* (stash-switch-pull-switch-back used to "update" main while the running code stayed behind).diff --git a/hermes_cli/update_cmd_common.py b/hermes_cli/update_cmd_common.pyindex 677ae5226e3..319b9d5a5ff 100644--- a/hermes_cli/update_cmd_common.py+++ b/hermes_cli/update_cmd_common.py@@ -8,7 +8,7 @@ from contextlib import contextmanagerlogger = logging.getLogger("hermes_cli.update_cmd")-def _record_stop(reason: str, *, without_receipt: "str | None" = None) -> None:+def _record_stop(reason: str, *, without_receipt: str | None = None) -> None:"""Name the exit about to stop this update as one closed token (see update_receipt.record_stop_reason).``without_receipt`` (``refused``/``failed``) is for an exit that fires before the receiptdiff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex d376fa43ab3..52eb380cca6 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -1442,7 +1442,7 @@ class _GatewayRestartOutcome:incomplete: boolphase_errors: list- pre_restart_gateway_pids: "list | None"+ pre_restart_gateway_pids: list | Nonerestarted_services: listfailed_or_stale_units: listrelaunched_profiles: listdiff --git a/hermes_cli/update_cmd_fleet_verify.py b/hermes_cli/update_cmd_fleet_verify.pyindex 6097bce476d..4ee3b2185db 100644--- a/hermes_cli/update_cmd_fleet_verify.py+++ b/hermes_cli/update_cmd_fleet_verify.py@@ -216,7 +216,7 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re# pre-update sys.modules graph — and its cron ticker keeps firing agent jobs that ImportError on every# symbol added in the pulled range. The rows also feed the plan-vs-execution reconciliation below, so a# survivor is escalated (an owed gateway_restart follow-up) instead of merely printed.- _stale_serve_rows: "list | None" = None+ _stale_serve_rows: list | None = Nonewith _best_effort('Failed to check for surviving serve runtimes: %s'):_stale_serve_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)if _stale_serve_rows:diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 5861770c001..40fab12bbf8 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -261,7 +261,7 @@ def _reload_process_scan_modules() -> None:def _finish_dashboard_update_cleanup(- node_failures: list[str], already_restarted_units: "set[str] | None" = None+ node_failures: list[str], already_restarted_units: set[str] | None = None) -> None:"""Historical updater hook; do not continue a pre-PM update after the swap."""from hermes_cli._old_updater import stop_for_relaunchdiff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex fac8b12a26c..4a772082b3a 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -48,7 +48,7 @@ class UpdatePlan:return asdict(self) # recursive: RuntimeRecord entries become dicts@classmethod- def from_dict(cls, data: dict[str, Any]) -> "UpdatePlan":+ def from_dict(cls, data: dict[str, Any]) -> UpdatePlan:"""Inverse of :meth:`to_dict` (the plan crosses the post-swap hand-off as JSON)."""fields_ = {f.name for f in dataclass_fields(cls)}plan = cls(**{k: v for k, v in data.items() if k in fields_ and k != "runtimes"})@@ -237,7 +237,7 @@ def _loaded_backend_launchd_jobs() -> list:return []-def _launchd_owner_for_ledger_entry(entry: dict, pid: int, jobs: list) -> "tuple[str, str, int | None] | None":+def _launchd_owner_for_ledger_entry(entry: dict, pid: int, jobs: list) -> tuple[str, str, int | None] | None:"""``(domain, label, live_pid)`` of the loaded launchd job owning this ledger row, if any.A KeepAlive LaunchAgent backend's recorded spawner (the bootstrap shell) is long dead, so the@@ -385,11 +385,11 @@ def _gateway_named_in(r: RuntimeRecord, names: set) -> bool:def match_runtime_outcomes(- plan: "UpdatePlan", *, restarted_services: list, relaunched_profiles: list,+ plan: UpdatePlan, *, restarted_services: list, relaunched_profiles: list,externally_supervised_profiles: list, killed_pids: set, failed_units: list,- stale_serve_pids: "set | None" = None, failed_respawn_pids: "set | None" = None,- external_gateway_pids: "set | None" = None,- live_gateway_pids: "dict[str, set[int]] | None" = None,+ stale_serve_pids: set | None = None, failed_respawn_pids: set | None = None,+ external_gateway_pids: set | None = None,+ live_gateway_pids: dict[str, set[int]] | None = None,) -> list[dict[str, Any]]:"""Reconcile the plan's runtimes against what the restart phase DID.diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex cfc438e73c7..578b421654c 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -1575,7 +1575,7 @@ class UpdateLock:self.acquired = self._claimed = Falseself._drop_checkout()- def __enter__(self) -> "UpdateLock":+ def __enter__(self) -> UpdateLock:self.acquire()return selfdiff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 68ea05a9437..85c33104175 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -56,7 +56,7 @@ COMMAND_BOUNDARY_STOP_REASON = "completed at command boundary"# the outer one, and the boundary finalize must see exactly its own# process's receipt. Same pattern as pm.receipt's ContextVars — no# manager object.-_current: contextvars.ContextVar[Optional["UpdateReceipt"]] = contextvars.ContextVar(+_current: contextvars.ContextVar[Optional[UpdateReceipt]] = contextvars.ContextVar("update_receipt_current", default=None)#: The terminal outcome of the run the enclosing command scope finalized or adopted (from adiff --git a/hermes_cli/voice.py b/hermes_cli/voice.pyindex d716e41c429..cd424cc496b 100644--- a/hermes_cli/voice.py+++ b/hermes_cli/voice.py@@ -580,7 +580,7 @@ def _speak_streaming(text: str, stop_event: Optional[threading.Event]) -> bool:if resolve_streaming_provider(_load_tts_config()) is None:return False- text_queue: "queue.Queue" = queue.Queue()+ text_queue: queue.Queue = queue.Queue()text_queue.put(text)text_queue.put(None) # end-of-text sentineldone_event = threading.Event()diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 127947f0c93..4dea1d2a7ba 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -444,7 +444,7 @@ class ProfileCreate(BaseModel):provider: Optional[str] = Nonemodel: Optional[str] = None# Profile-builder additions, applied best-effort AFTER the profile dir exists (a hiccup never 500s).- mcp_servers: list["MCPServerCreate"] = []+ mcp_servers: list[MCPServerCreate] = []keep_skills: list[str] = [] # skills to KEEP: non-empty = replace semantics (unlisted seeded ones disabled)# Installed async via `hermes -p <name> skills install` (skills_hub.SKILLS_DIR is import-time-bound,# so HERMES_HOME can't redirect it); PIDs go back for the UI to poll.diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex 411fd8cb48a..3c048cba225 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -513,7 +513,7 @@ async def stt_lease(payload: STTLeaseRequest, profile: Optional[str] = None):@router.websocket("/api/audio/transcribe-stream")-async def transcribe_stream_ws(ws: "WebSocket") -> None:+async def transcribe_stream_ws(ws: WebSocket) -> None:"""Live STT for Desktop dictation: mic PCM in while the user speaks, partial + final text out.Protocol:@@ -590,7 +590,7 @@ async def transcribe_stream_ws(ws: "WebSocket") -> None:@router.websocket("/api/audio/speak-stream")-async def speak_stream_ws(ws: "WebSocket") -> None:+async def speak_stream_ws(ws: WebSocket) -> None:"""Streaming TTS for the desktop: text in, raw int16 PCM frames out.The socket is a per-reply speech *session*: the client feeds textdiff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex d203a0a1ca4..2e88ab4984e 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -39,7 +39,7 @@ _ws_host_origin_reason = late("_ws_host_origin_reason", "hermes_cli.web_server_c_DASHBOARD_EMBEDDED_CHAT_ENABLED = LateState("_DASHBOARD_EMBEDDED_CHAT_ENABLED")-def _get_event_state(app: "FastAPI"):+def _get_event_state(app: FastAPI):"""(event_channels, event_lock) from app.state, lazily initialised when thelifespan hasn't run (TestClient without a ``with`` block). The lifespan pathis preferred because it creates the Lock on the correct event loop."""@@ -62,7 +62,7 @@ def _unlink_active_session_file(path: Optional[Path]) -> None:pass-def _discard_active_session_file(app: "FastAPI", channel: Optional[str], path: Optional[Path]) -> None:+def _discard_active_session_file(app: FastAPI, channel: Optional[str], path: Optional[Path]) -> None:_unlink_active_session_file(path)if not channel or path is None:return@@ -479,7 +479,7 @@ def _lease_holder_pid(session_id: Optional[str], *, registry_home: Optional[str]return None-async def _pump_keepalive_input(ws: "WebSocket", session: Any) -> None:+async def _pump_keepalive_input(ws: WebSocket, session: Any) -> None:"""Writer loop for a keep-alive /api/pty socket: forward client input to thesession's bridge, consuming resize escapes locally. On child EOF the draintask closes the attached socket with 4410, which unparks ws.receive()."""diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 252bc0b1671..44ad06134ab 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -143,8 +143,8 @@ def _job(kind: str, target: str, model_id: str | None = None) -> dict[str, Any]:return job-def _rate_and_eta(samples: "collections.deque[tuple[float, int]]", done: int,- total: int | None) -> "tuple[float | None, int | None]":+def _rate_and_eta(samples: collections.deque[tuple[float, int]], done: int,+ total: int | None) -> tuple[float | None, int | None]:"""Transfer rate and remaining seconds from a trailing sample window.The rate is the slope across the window, not the last two ticks, so a@@ -406,7 +406,7 @@ def _model_id_for(gguf: Path) -> str:return re.sub(_SPLIT_PART_RE + "$", "", gguf.stem)-def _variant_files_on_disk(model_id: str) -> "list[Path]":+def _variant_files_on_disk(model_id: str) -> list[Path]:"""Every local file of a staged model: all split parts plus catalog-declared assets (mmproj/draft/MTP head) when present."""files = [p for p in bootstrap.models_dir().glob("*.gguf") if _model_id_for(p) == model_id]hit = catalog.find_entry_for_model(model_id)@@ -446,7 +446,7 @@ def _download_job(job: dict[str, Any], plan) -> None:dl.run(progress=_download_progress_hook(job))-def _loaded_models(running: dict[str, Any]) -> "tuple[dict[str, str], dict[str, Any]]":+def _loaded_models(running: dict[str, Any]) -> tuple[dict[str, str], dict[str, Any]]:"""Resident models right now, plus how each is placed (granted window from the child, spill facts fromthe preset decision) — the difference between 'fast' and 'why is my CPU busy', so it must be inspectable.'loading' is its own state (a 20-GB load in flight is the most important thing the pane can show)."""diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.pyindex 62afa0283e2..df6b0840087 100644--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@ -419,7 +419,7 @@ def _memory_provider_payload(name: str, provider: Any) -> dict[str, Any]:}-def _coerce_schema_number(field: dict[str, Any], raw: Any) -> "int | float":+def _coerce_schema_number(field: dict[str, Any], raw: Any) -> int | float:value = raw if raw is not None and raw != "" else _field_default(field)try:if isinstance(value, bool) or not math.isfinite(result := float(value)):diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex 02143a915bc..e58e429a063 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -185,7 +185,7 @@ def _is_profile_platform_status_key(key: object) -> bool:return isinstance(key, str) and bool(_PROFILE_PLATFORM_STATUS_KEY_RE.fullmatch(key))-def _status_platform_key_allowed(key: object, configured: "set[str] | None") -> bool:+def _status_platform_key_allowed(key: object, configured: set[str] | None) -> bool:"""Whether a runtime-status platform key may appear publicly: namespaced``<profile>:<platform>`` keys are validated against the grammar *unconditionally* (afailed config-set load must not fail open into projecting arbitrary keys from a@@ -261,7 +261,7 @@ def _bounded_health_probe():return False, None-def _project_gateway_platforms(gateway_platforms: dict, configured: "set[str] | None",+def _project_gateway_platforms(gateway_platforms: dict, configured: set[str] | None,gateway_running: bool, gateway_state) -> dict:"""Public projection of a runtime's platform map (see ``_status_platform_key_allowed``for the key rules). A cleanly stopped gateway's platform states are stale noise and arediff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 31680606f0a..b314f74391b 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -87,7 +87,7 @@ def _gateway_owns_cron(name: str, home) -> bool:name != "default" and _served_by_running_multiplexer(name))-def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60) -> None:+def _start_desktop_cron_ticker(stop_event: threading.Event, interval: int = 60) -> None:"""Tick the cron scheduler from inside the desktop dashboard backend.The desktop spawns a ``hermes dashboard`` backend, not a gateway, so without@@ -177,7 +177,7 @@ _DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0@asynccontextmanager-async def _lifespan(app: "FastAPI"):+async def _lifespan(app: FastAPI):app.state.event_channels = {} # dict[str, set]app.state.event_lock = asyncio.Lock()app.state.pty_active_session_files = {} # dict[str, Path]@@ -246,8 +246,8 @@ async def _lifespan(app: "FastAPI"):# Desktop-spawned backends fire cron jobs themselves, since the app has no# gateway running the scheduler. Server `hermes dashboard` is unaffected —# it relies on its own gateway.- cron_stop: "threading.Event | None" = None- cron_thread: "threading.Thread | None" = None+ cron_stop: threading.Event | None = None+ cron_thread: threading.Thread | None = Nonedesktop_owned = is_desktop_owned_backend()if desktop_owned:# Reap an orphaned gateway from an abnormal previous exit (reparented to@@ -341,7 +341,7 @@ async def _lifespan(app: "FastAPI"):eager_reconcile_thread.join()-def _app_state_default(app: "FastAPI", name: str, factory):+def _app_state_default(app: FastAPI, name: str, factory):"""Return ``app.state.<name>``, lazily creating it for non-``with`` TestClient usages.The lifespan normally initialises these on the running event loop (an@@ -355,11 +355,11 @@ def _app_state_default(app: "FastAPI", name: str, factory):return value-def _get_chat_argv_lock(app: "FastAPI") -> asyncio.Lock:+def _get_chat_argv_lock(app: FastAPI) -> asyncio.Lock:return _app_state_default(app, "chat_argv_lock", asyncio.Lock)-def _get_pty_active_session_files(app: "FastAPI") -> dict[str, Path]:+def _get_pty_active_session_files(app: FastAPI) -> dict[str, Path]:return _app_state_default(app, "pty_active_session_files", dict)@@ -744,7 +744,7 @@ class DashboardHealth:def __init__(self, window_seconds: float = _DASHBOARD_HEALTH_WINDOW_SECONDS) -> None:self.window_seconds = window_seconds- self._error_times: "deque[float]" = deque(maxlen=256)+ self._error_times: deque[float] = deque(maxlen=256)self.last_error_type: Optional[str] = Noneself.last_error_path: Optional[str] = None # internal-only, never serializedself.last_error_at: Optional[float] = Nonediff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 6ee5974e68b..3ec2fe41834 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -51,7 +51,7 @@ PTY_REGISTRY = PtySessionRegistry(ttl=30 * 60, max_sessions=16, buffer_cap=1 * 1024 * 1024, read_timeout=_PTY_READ_CHUNK_TIMEOUT)-async def _close_stalled_pty_input(ws: "WebSocket", *, path: str) -> None:+async def _close_stalled_pty_input(ws: WebSocket, *, path: str) -> None:"""Close only the terminal socket when its child stops accepting input."""_log.warning("pty input stalled path=%s; recycling terminal session", path)try:@@ -60,7 +60,7 @@ async def _close_stalled_pty_input(ws: "WebSocket", *, path: str) -> None:pass-async def _legacy_pump(ws: "WebSocket", bridge) -> None:+async def _legacy_pump(ws: WebSocket, bridge) -> None:"""Original 1:1 socket<->PTY pump: stream until disconnect, then close thebridge. Used when no ``?attach=`` token is supplied (keep-alive opt-in).@@ -136,7 +136,7 @@ async def _legacy_pump(ws: "WebSocket", bridge) -> None:_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost", "testclient"})-def _ws_client_reason(ws: "WebSocket") -> Optional[str]:+def _ws_client_reason(ws: WebSocket) -> Optional[str]:"""Return a rejection reason token for the peer IP, or None when allowed.Loopback bind: only loopback peers (the legacy ``?token=`` is the only auth,@@ -159,12 +159,12 @@ def _ws_client_reason(ws: "WebSocket") -> Optional[str]:return f"peer_not_loopback peer={client_host} bound={bound_host or '?'}"-def _ws_client_is_allowed(ws: "WebSocket") -> bool:+def _ws_client_is_allowed(ws: WebSocket) -> bool:"""True when the peer IP passes :func:`_ws_client_reason`."""return _ws_client_reason(ws) is None-def _ws_host_origin_reason(ws: "WebSocket") -> Optional[str]:+def _ws_host_origin_reason(ws: WebSocket) -> Optional[str]:"""Return ``host_mismatch …`` / ``origin_mismatch …``, or None when allowed.HTTP middleware does not run for WebSocket routes, so the DNS-rebinding@@ -194,12 +194,12 @@ def _ws_host_origin_reason(ws: "WebSocket") -> Optional[str]:return None-def _ws_host_origin_is_allowed(ws: "WebSocket") -> bool:+def _ws_host_origin_is_allowed(ws: WebSocket) -> bool:"""True when the upgrade passes the dashboard Host/Origin guard."""return _ws_host_origin_reason(ws) is None-def _ws_request_is_allowed(ws: "WebSocket") -> bool:+def _ws_request_is_allowed(ws: WebSocket) -> bool:"""Return True when the WebSocket upgrade matches dashboard boundaries."""return _ws_host_origin_is_allowed(ws) and _ws_client_is_allowed(ws)@@ -208,7 +208,7 @@ _GATEWAY_WS_PROTOCOL = "hermes-gateway-v1"_GATEWAY_WS_TICKET_PROTOCOL_PREFIX = "hermes-gateway-ticket."-def _gateway_ws_ticket_from_subprotocol(ws: "WebSocket") -> tuple[str, str]:+def _gateway_ws_ticket_from_subprotocol(ws: WebSocket) -> tuple[str, str]:"""Return ``(ticket, reason)`` from an unambiguous gateway protocol set."""raw = str(ws.headers.get("sec-websocket-protocol", "") or "")protocols = [value.strip() for value in raw.split(",") if value.strip()]@@ -222,7 +222,7 @@ def _gateway_ws_ticket_from_subprotocol(ws: "WebSocket") -> tuple[str, str]:return (ticket, "ok") if ticket else ("", "invalid")-def _ws_request_view(ws: "WebSocket") -> "Request":+def _ws_request_view(ws: WebSocket) -> Request:"""A ``Request`` facade over a ``WebSocket`` for the auth helpers.``_verify_access_token`` only touches ``request.headers`` (X-Forwarded-For@@ -247,7 +247,7 @@ def _ws_request_view(ws: "WebSocket") -> "Request":})-def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:+def _ws_auth_reason(ws: WebSocket) -> tuple[Optional[str], str]:"""Validate WS-upgrade auth; return ``(reason, credential)``.``reason`` is None when accepted, else a short token (``no_credential``,@@ -374,7 +374,7 @@ def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:return "token_mismatch", "token"-def _ws_auth_ok(ws: "WebSocket") -> bool:+def _ws_auth_ok(ws: WebSocket) -> bool:"""True when the WS-upgrade credential is accepted. See _ws_auth_reason."""return _ws_auth_reason(ws)[0] is None@@ -538,7 +538,7 @@ async def _resolve_chat_argv_async(return await asyncio.to_thread(_resolve_chat_argv, **kwargs)-def _active_session_file_for_channel(app: "FastAPI", channel: str) -> Path:+def _active_session_file_for_channel(app: FastAPI, channel: str) -> Path:"""Return the per-channel file where a dashboard TUI writes its active sid."""from hermes_cli.web_server import _get_pty_active_session_filesfiles = _get_pty_active_session_files(app)diff --git a/hermes_cli/web_server_config.py b/hermes_cli/web_server_config.pyindex 460152a8448..7fb3dec6e8c 100644--- a/hermes_cli/web_server_config.py+++ b/hermes_cli/web_server_config.py@@ -477,7 +477,7 @@ def _normalize_main_model_assignment(provider: str, model: str) -> tuple[str, stdef _validated_main_model_selection(cfg: dict, provider: str, model: str, base_url: str = "", api_key: str = ""-) -> "ModelSwitchResult":+) -> ModelSwitchResult:"""Route a dashboard main-slot pick through ``switch_model`` (catalog/alias/credentialvalidation) seeded with the configured route, exactly like a ``/model <model> --provider<provider> --global``. A bare ``custom`` target carries the submitted endpoint as the current@@ -510,7 +510,7 @@ def _validated_main_model_selection(return result-def _apply_main_model_assignment(model_cfg: "Any", result: "ModelSwitchResult", api_key: str = "") -> dict:+def _apply_main_model_assignment(model_cfg: Any, result: ModelSwitchResult, api_key: str = "") -> dict:"""Apply a main-slot selection to a ``model`` config dict via the canonical /model shape(``hermes_cli.model_switch.apply_model_selection``). An explicit key for a custom endpoint isthe one inline credential the runtime reads (``model.api_key``); the legacy ``api`` alias is@@ -739,7 +739,7 @@ def _provider_entry(cfg: dict, provider: str) -> Any:return providers_cfg.get(provider) if isinstance(providers_cfg, dict) else None-def _prepare_main_assignment(cfg: dict, provider: str, model: str, base_url: str, api_key: str) -> "tuple[str, ModelSwitchResult]":+def _prepare_main_assignment(cfg: dict, provider: str, model: str, base_url: str, api_key: str) -> tuple[str, ModelSwitchResult]:"""Validation half of a main-slot assignment: ``(effective base_url, switch result)``.``switch_model`` fetches catalogs / probes endpoints, so callers run this BEFORE taking``_CONFIG_MUTATION_LOCK``; it writes nothing."""@@ -753,7 +753,7 @@ def _prepare_main_assignment(cfg: dict, provider: str, model: str, base_url: strdef _apply_main_assignment_sync(cfg: dict, provider: str, model: str, base_url: str, api_key: str,- prepared: "Optional[tuple[str, ModelSwitchResult]]" = None) -> dict:+ prepared: Optional[tuple[str, ModelSwitchResult]] = None) -> dict:from hermes_cli.config import save_configfrom hermes_cli.free_tier_bootstrap import reconcile_recordbase_url, result = prepared or _prepare_main_assignment(cfg, provider, model, base_url, api_key)@@ -888,7 +888,7 @@ def _apply_aux_assignment_sync(cfg: dict, provider: str, model: str, task: str,def _apply_model_assignment_sync(scope: str, provider: str, model: str, task: str, base_url: str, api_key: str = "",- reasoning_effort: Optional[str] = _UNSET, prepared: "Optional[tuple[str, ModelSwitchResult]]" = None,+ reasoning_effort: Optional[str] = _UNSET, prepared: Optional[tuple[str, ModelSwitchResult]] = None,):"""Synchronous body of POST /api/model/set.diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex 8de136550ca..95997036645 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -194,7 +194,7 @@ def _eager_reconcile_own_session_db() -> None:)-def _read_bound_port(server: "uvicorn.Server", fallback: int) -> int:+def _read_bound_port(server: uvicorn.Server, fallback: int) -> int:"""Read the OS-assigned port from the live uvicorn socket (ephemeral port-0 discovery)."""if server.servers and server.servers[0].sockets:return server.servers[0].sockets[0].getsockname()[1]diff --git a/hermes_cli/web_server_mcp.py b/hermes_cli/web_server_mcp.pyindex 36ef416ca8d..4626ae639bf 100644--- a/hermes_cli/web_server_mcp.py+++ b/hermes_cli/web_server_mcp.py@@ -105,7 +105,7 @@ def _mcp_server_summary(name: str, cfg: dict[str, Any], plugin: str | None = Non}-_mcp_oauth_flows: dict[str, "DashboardOAuthFlow"] = {}+_mcp_oauth_flows: dict[str, DashboardOAuthFlow] = {}_mcp_oauth_transactions: dict[tuple[str, str], threading.Lock] = {}_mcp_oauth_transactions_lock = threading.Lock()diff --git a/hermes_cli/web_server_profiles.py b/hermes_cli/web_server_profiles.pyindex 8ae1b7727db..21002f21bbc 100644--- a/hermes_cli/web_server_profiles.py+++ b/hermes_cli/web_server_profiles.py@@ -106,7 +106,7 @@ def _broadcast_gateway_session_info() -> None:_MODEL_ENTRY_METADATA = ("canonical_model", "reasoning_effort")-def _parse_model_entries(resp: "Any") -> list[dict[str, str]]:+def _parse_model_entries(resp: Any) -> list[dict[str, str]]:"""Model rows from an OpenAI-compatible ``/v1/models`` response as ``{"id": ..}`` dicts,keeping the alias metadata a gateway may advertise (``canonical_model``,``reasoning_effort``). Flattening to bare ids lost that, so Desktop stored a reasoning@@ -137,7 +137,7 @@ def _parse_model_entries(resp: "Any") -> list[dict[str, str]]:return entries-def _parse_model_ids(resp: "Any") -> list[str]:+def _parse_model_ids(resp: Any) -> list[str]:"""Bare model ids from a ``/v1/models`` response (see :func:`_parse_model_entries`)."""return [entry["id"] for entry in _parse_model_entries(resp)]@@ -199,7 +199,7 @@ def _resolve_profile_dir(name: str) -> Path:return profiles_mod.get_profile_dir(name)-def _write_profile_mcp_servers(profile_dir: Path, servers: list["MCPServerCreate"]) -> int:+def _write_profile_mcp_servers(profile_dir: Path, servers: list[MCPServerCreate]) -> int:"""Write MCP server entries into ``profile_dir``'s config.yaml (HERMES_HOME-scoped).Mirrors the per-server shape ``POST /api/mcp/servers`` builds, batched so the wholediff --git a/hermes_cli/win_pty_bridge.py b/hermes_cli/win_pty_bridge.pyindex b87143809fb..ffb2dd931fc 100644--- a/hermes_cli/win_pty_bridge.py+++ b/hermes_cli/win_pty_bridge.py@@ -45,7 +45,7 @@ class WinPtyBridge:``run_in_executor``; ConPTY has no selectable fd, so reads poll and writes run in a workerthread to keep the same non-blocking event-loop contract as the POSIX bridge."""- def __init__(self, proc: "PtyProcess") -> None: # type: ignore[name-defined]+ def __init__(self, proc: PtyProcess) -> None: # type: ignore[name-defined]self._proc = procself._closed = False@@ -56,7 +56,7 @@ class WinPtyBridge:@classmethoddef spawn(cls, argv: Sequence[str], *, cwd: Optional[str] = None, env: Optional[dict] = None,- cols: int = 80, rows: int = 24) -> "WinPtyBridge":+ cols: int = 80, rows: int = 24) -> WinPtyBridge:if not _PTY_AVAILABLE:if PtyProcess is None:raise PtyUnavailableError("pywinpty is not installed. Run hermes pm repair, then restart Hermes.")@@ -187,7 +187,7 @@ class WinPtyBridge:except Exception:pass- def __enter__(self) -> "WinPtyBridge":+ def __enter__(self) -> WinPtyBridge:return selfdef __exit__(self, *_exc) -> None:diff --git a/hermes_cli/xai_retirement.py b/hermes_cli/xai_retirement.pyindex cf8d5e2a3aa..91c861a6f5a 100644--- a/hermes_cli/xai_retirement.py+++ b/hermes_cli/xai_retirement.py@@ -111,7 +111,7 @@ class ApplyResult:config_changed: bool-def _walk_to_parent(yaml_doc: Any, dotted_path: str) -> "tuple[Any, str]":+def _walk_to_parent(yaml_doc: Any, dotted_path: str) -> tuple[Any, str]:"""Resolve a dotted slot path to (parent_mapping, leaf_key)."""*parents, leaf = dotted_path.split(".")if not parents:diff --git a/hermes_constants.py b/hermes_constants.pyindex ced1e33e8bd..ceef4a291ea 100644--- a/hermes_constants.py+++ b/hermes_constants.py@@ -210,7 +210,7 @@ LOCAL_RUNTIME_ROOT_DIRS: frozenset[str] = frozenset({"models", "runtimes", "node# get_default_hermes_root() memo keyed on (native home, expanded HERMES_HOME) so it stays# fresh when a test or plugin mutates either input; saves ~80us/call at 31+ sites.-_default_hermes_root_memo: "tuple[str, str, Path] | None" = None+_default_hermes_root_memo: tuple[str, str, Path] | None = Nonedef get_default_hermes_root(*, home: str | Path | None = None) -> Path:diff --git a/hermes_logging.py b/hermes_logging.pyindex d11c392f641..6e9e6b20be0 100644--- a/hermes_logging.py+++ b/hermes_logging.py@@ -581,7 +581,7 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):def _new_file_handler(path: Path, *, level: int, max_bytes: int, backup_count: int, formatter-) -> "_ManagedRotatingFileHandler":+) -> _ManagedRotatingFileHandler:"""Create the ``logs/`` directory and a configured ``_ManagedRotatingFileHandler``."""mkdir_under_hermes_home(path.parent)if _WINDOWS_CLH_FALLBACK:@@ -722,7 +722,7 @@ class _ProfileRoutingFileHandler(logging.Handler):# drops WebSocket clients. Every file handler is therefore driven by a single# QueueListener thread; loggers only do a non-blocking enqueue.-_log_queue: "Optional[queue.SimpleQueue]" = None+_log_queue: Optional[queue.SimpleQueue] = None_queue_listener: Optional[QueueListener] = None_queued_file_handlers: list = []_queue_atexit_registered = Falsediff --git a/hermes_platform/resolver/core.py b/hermes_platform/resolver/core.pyindex 8b27e84a549..40cab4023b0 100644--- a/hermes_platform/resolver/core.py+++ b/hermes_platform/resolver/core.py@@ -43,7 +43,7 @@ class Observation(Generic[T]):detail: str = ""@classmethod- def not_checked(cls) -> "Observation[T]":+ def not_checked(cls) -> Observation[T]:return cls(CheckState.NOT_CHECKED)diff --git a/hermes_startup_watchdog.py b/hermes_startup_watchdog.pyindex f5ab0e9f052..43d09a25922 100644--- a/hermes_startup_watchdog.py+++ b/hermes_startup_watchdog.py@@ -94,7 +94,7 @@ _FIRING = "firing"# gateway.run.main / cli.py --gateway) and the disarm site (GatewayRunner)# share no object, and only one gateway startup ever runs per process._handle_lock = threading.Lock()-_handle: Optional["StartupWatchdogHandle"] = None+_handle: Optional[StartupWatchdogHandle] = Nonedef _process_hermes_home() -> Path:diff --git a/hermes_state.py b/hermes_state.pyindex 79db7a4d164..cda968f5b0b 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -428,7 +428,7 @@ def _close_time_checkpoint_configurable() -> bool:and hasattr(sqlite3.Connection, "setconfig"))-def divert_session_transcript_jsonl(session_id: str, messages) -> "Optional[Path]":+def divert_session_transcript_jsonl(session_id: str, messages) -> Optional[Path]:"""Append pending messages to HERMES_HOME/sessions/<id>.jsonl (state.db was replaced under alive process). Returns the path, or None if nothing to write."""sid = str(session_id or "").strip()@@ -597,7 +597,7 @@ class SessionDB(# Read-path split (WAL only): reads borrow from a BOUNDED read-only pool so they# never queue behind writer flushes on self._lock (see _read_ctx); unbounded# per-thread connections pinned fds for the process lifetime and hit EMFILE.- self._read_pool: "queue.LifoQueue[sqlite3.Connection]" = queue.LifoQueue(maxsize=_READ_POOL_MAX)+ self._read_pool: queue.LifoQueue[sqlite3.Connection] = queue.LifoQueue(maxsize=_READ_POOL_MAX)# Permits bound PEAK descriptors (the pool bounds only the idle set), shared per# DATABASE PATH; acquired non-blocking so a permitless reader degrades to the writer lock.# One permit per live read connection, held from before the open in _get_read_conn() until after the@@ -1325,7 +1325,7 @@ class SessionDB(and classify_persistence_error(exc) == "corrupt")- def _corrupt_error(self, prefix: str = "") -> "StateDbCorruptError":+ def _corrupt_error(self, prefix: str = "") -> StateDbCorruptError:"""Build the quarantine error for this handle (message assembled once)."""return StateDbCorruptError(f"{prefix}{_STATE_DB_CORRUPT_MSG} (cause: {self._db_corrupt_reason})")@@ -1488,7 +1488,7 @@ class SessionDB(except Exception as exc:logger.warning("WAL checkpoint (PASSIVE) failed: %s", exc)- def __enter__(self) -> "SessionDB":+ def __enter__(self) -> SessionDB:"""``with SessionDB(path) as db:`` closes on exit; owners must release deterministically.Ownership of a SessionDB should be released explicitly. Historically an instance with a started@@ -1707,7 +1707,7 @@ class AsyncSessionDB:"""Async door onto SessionDB: every call runs via asyncio.to_thread so a blocking SQLite callnever freezes the event loop (no method returns a live cursor)."""- def __init__(self, db: "SessionDB") -> None:+ def __init__(self, db: SessionDB) -> None:self._db = dbdef __getattr__(self, name: str):diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 33a35606368..5a37d49eba3 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -329,7 +329,7 @@ _FTS_OLD_INDEXED_CONTENT_SQL = _fts_indexed_content_sql("old")MAX_FTS5_QUERY_CHARS = 2_048-def stat_db_file_identity(path) -> "tuple[int, int] | None":+def stat_db_file_identity(path) -> tuple[int, int] | None:"""``(st_dev, st_ino)`` for *path*, or None. st_ino=0 (Windows, some network FS) would false-positiveevery replaced-file check, so it counts as unknown."""try:diff --git a/hermes_state_dbfile.py b/hermes_state_dbfile.pyindex b3cc755571a..5d19aba9bee 100644--- a/hermes_state_dbfile.py+++ b/hermes_state_dbfile.py@@ -69,12 +69,12 @@ def _prepare_connection_retirement():# at a new inode (the very replacement this probe detects) the stale fd is RETIRED, never closed# — closing it would cancel the live connection's locks. Replacements are rare and halt writes._HEADER_PROBE_LOCK = threading.Lock()-_HEADER_PROBE_FDS: "dict[str, tuple[int, int, int]]" = {} # key -> (fd, dev, ino)-_RETIRED_HEADER_PROBE_FDS: "list[int]" = [] # intentionally never closed+_HEADER_PROBE_FDS: dict[str, tuple[int, int, int]] = {} # key -> (fd, dev, ino)+_RETIRED_HEADER_PROBE_FDS: list[int] = [] # intentionally never closed_FTS_TABLE_NAMES = ("messages_fts", "messages_fts_trigram", "messages_fts_cjk")-def _pread_db_range(db_path: Path, offset: int, length: int) -> "Optional[bytes]":+def _pread_db_range(db_path: Path, offset: int, length: int) -> Optional[bytes]:"""Lock-safe raw read of a possibly-live SQLite database: POSIX preads from a cached,never-closed fd (rebound when the path names a new inode); Windows reads plainly, sinceadvisory-lock cancellation is a POSIX-only hazard."""@@ -111,12 +111,12 @@ def _pread_db_range(db_path: Path, offset: int, length: int) -> "Optional[bytes]return None-def _pread_db_header(db_path: Path, length: int) -> "Optional[bytes]":+def _pread_db_header(db_path: Path, length: int) -> Optional[bytes]:"""Lock-safe raw header read of a possibly-live SQLite database (see :func:`_pread_db_range`)."""return _pread_db_range(db_path, 0, length)-def _read_sqlite_application_id(db_path: Path) -> "Optional[int]":+def _read_sqlite_application_id(db_path: Path) -> Optional[int]:"""application_id from the SQLite header, via the lock-safe :func:`_pread_db_header`."""from hermes_state_errors import _STATE_DB_APPLICATION_ID_OFFSETend = _STATE_DB_APPLICATION_ID_OFFSET + 4@@ -156,7 +156,7 @@ def _watched_sqlite_sidecar_paths(db_path) -> dict[str, str]:return watched-def _identity_is_truly_unlinked(identity: "tuple[int, int]", watched_path: str) -> bool:+def _identity_is_truly_unlinked(identity: tuple[int, int], watched_path: str) -> bool:"""The shared verdict: does ``(st_dev, st_ino)`` name a generation the watched path no longerholds? See :func:`_fd_is_truly_unlinked` for why the test is identity and never link count."""try:@@ -432,7 +432,7 @@ def _fsync_path(path: Path) -> None:os.close(fd)-def _own_descriptor_for_identity(identity) -> "Optional[int]":+def _own_descriptor_for_identity(identity) -> Optional[int]:"""This process's open descriptor for the inode ``(st_dev, st_ino)``, or None.Exact-generation qualified: pathnames are never consulted. The descriptor stays owned bydiff --git a/hermes_state_errors.py b/hermes_state_errors.pyindex ec098af359d..8ee7a76885e 100644--- a/hermes_state_errors.py+++ b/hermes_state_errors.py@@ -40,7 +40,7 @@ _TRANSIENT_SQLITE_MARKERS = (_SQLITE_LOCK_CODES = (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED)-def _sqlite_primary_code(exc_or_str) -> "int | None":+def _sqlite_primary_code(exc_or_str) -> int | None:"""Primary result code (extended codes keep it in the low byte); None when unknown."""code = getattr(exc_or_str, "sqlite_errorcode", None)return code & 0xFF if isinstance(code, int) else Nonediff --git a/hermes_state_guard.py b/hermes_state_guard.pyindex 2f0444df57e..916d7a5861b 100644--- a/hermes_state_guard.py+++ b/hermes_state_guard.py@@ -138,7 +138,7 @@ def _is_production_state_db(resolved: Path, root: Path) -> bool:# Population is gated on the isolation marker (exported by tests/conftest.py# before any test module imports). Production processes never populate it;# do not "simplify" the gate away. WeakSet membership never pins an instance.-_test_instance_registry: "weakref.WeakSet[Any]" = weakref.WeakSet()+_test_instance_registry: weakref.WeakSet[Any] = weakref.WeakSet()def _register_test_instance(db: Any) -> None:diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 64ada03a77f..f8c80ee6153 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -110,7 +110,7 @@ def _not_pinned_sql(alias: str = "s") -> str:class SessionMaintenanceMixin:"""Retention pruning, stale-session archiving and VACUUM policy for SessionDB."""- def prune_empty_ghost_sessions(self, sessions_dir: "Optional[Path]" = None) -> int:+ def prune_empty_ghost_sessions(self, sessions_dir: Optional[Path] = None) -> int:"""Remove empty TUI ghost sessions (no messages, no title, >24hr old)."""cutoff = time.time() - 86400def _do(conn):diff --git a/hermes_state_readpool.py b/hermes_state_readpool.pyindex d392aacb142..e918df2c6ba 100644--- a/hermes_state_readpool.py+++ b/hermes_state_readpool.py@@ -66,10 +66,10 @@ _process_read_permits = threading.BoundedSemaphore(_READ_POOL_PROCESS_MAX)_read_open_denied_fd_headroom = 0_fd_usage_lock = threading.Lock()-_fd_usage_cache: "tuple[float, Optional[int]]" = (0.0, None)+_fd_usage_cache: tuple[float, Optional[int]] = (0.0, None)-def _proc_fd_targets(pid: int) -> "Iterator[tuple[str, str]]":+def _proc_fd_targets(pid: int) -> Iterator[tuple[str, str]]:"""Yield ``(readlink target, fd path)`` for every entry in /proc/<pid>/fd (unreadablelinks skipped). Raises OSError when the fd directory itself cannot be listed."""fd_dir = f"/proc/{pid}/fd"@@ -154,10 +154,10 @@ class _PathReadBudget:self.permits = threading.BoundedSemaphore(_READ_POOL_MAX)self._lock = threading.Lock()# Weak: a SessionDB dropped without close() must not pin peers' budget.- self._members: "weakref.WeakSet[SessionDB]" = weakref.WeakSet()+ self._members: weakref.WeakSet[SessionDB] = weakref.WeakSet()self._duplicate_handles_warned = False- def register(self, db: "SessionDB") -> None:+ def register(self, db: SessionDB) -> None:with self._lock:self._members.add(db)# Only writable handles carry the cost the warning names (writer connection, write@@ -190,12 +190,12 @@ class _PathReadBudget:handles, db.db_path, _READ_POOL_MAX, creation_sites,)- def unregister(self, db: "SessionDB") -> None:+ def unregister(self, db: SessionDB) -> None:"""Remove a closed writer from duplicate-handle diagnostics immediately."""with self._lock:self._members.discard(db)- def acquire(self, requester: "SessionDB") -> bool:+ def acquire(self, requester: SessionDB) -> bool:"""Take a permit for a new read connection, or refuse (caller degrades to thelocked writer connection). Gates, broadest first: fd headroom, processceiling, this file's ceiling."""@@ -222,12 +222,12 @@ class _PathReadBudget:_reclaim_idle_read_conn_anywhere() and _process_read_permits.acquire(blocking=False))- def _acquire_path_permit(self, requester: "SessionDB") -> bool:+ def _acquire_path_permit(self, requester: SessionDB) -> bool:return self.permits.acquire(blocking=False) or (self.reclaim_idle(exclude=requester) and self.permits.acquire(blocking=False))- def reclaim_idle(self, exclude: "Optional[SessionDB]" = None) -> bool:+ def reclaim_idle(self, exclude: Optional[SessionDB] = None) -> bool:"""Close one idle pooled connection held by a member; True if one went.Its release() returns both permits, so both ceilings reclaim through here."""with self._lock:@@ -237,7 +237,7 @@ class _PathReadBudget:# canonical db path -> permits for that file. Weak values: the budget lives only# while some SessionDB on the path holds it, so tmp_path churn can't grow this.-_read_budgets: "weakref.WeakValueDictionary[str, _PathReadBudget]" = (weakref.WeakValueDictionary())+_read_budgets: weakref.WeakValueDictionary[str, _PathReadBudget] = (weakref.WeakValueDictionary())_read_budgets_lock = threading.Lock()diff --git a/hermes_state_registry.py b/hermes_state_registry.pyindex 5152723424f..9f567852e0c 100644--- a/hermes_state_registry.py+++ b/hermes_state_registry.py@@ -69,7 +69,7 @@ class _Generation:__slots__ = ("db", "identity", "path", "refcount", "retired")- def __init__(self, path: Path, db: "SessionDB", identity: Optional[tuple[int, int]]) -> None:+ def __init__(self, path: Path, db: SessionDB, identity: Optional[tuple[int, int]]) -> None:self.path = pathself.db = dbself.refcount = 1@@ -98,21 +98,21 @@ _tearing_down: dict[Path, _TeardownBarrier] = {}_path_lifecycle_locks: dict[Path, threading.Lock] = {}-def _open_session_db(path: Path) -> "SessionDB":+def _open_session_db(path: Path) -> SessionDB:"""Construct the SessionDB for *path* (call-time import avoids cycles; tests patch this)."""from hermes_state import SessionDBreturn SessionDB(db_path=path)-def _teardown(db: "SessionDB") -> None:+def _teardown(db: SessionDB) -> None:"""Close a shared instance, clearing its registry-owned flag first."""with contextlib.suppress(Exception):db._shared_registry_owned = False_close_quietly(db, "Error closing shared SessionDB")-def _close_quietly(db: "SessionDB", debug_message: str) -> None:+def _close_quietly(db: SessionDB, debug_message: str) -> None:"""close() that never propagates. A lost WAL generation whose capture failed is data at risk,not teardown noise: the handle stays open and the operator has to act, so that one surfaces."""try:@@ -161,7 +161,7 @@ def _finish_teardown(path: Path, barrier: _TeardownBarrier) -> None:def _teardown_generation(path: Path,- db: "SessionDB",+ db: SessionDB,*,barrier: Optional[_TeardownBarrier] = None,) -> None:@@ -176,7 +176,7 @@ def _teardown_generation(_finish_teardown(path, barrier)-def _db_path_of(db: "SessionDB") -> Optional[Path]:+def _db_path_of(db: SessionDB) -> Optional[Path]:"""``Path(db.db_path)`` or None when absent/unconvertible."""path = getattr(db, "db_path", None)try:@@ -192,7 +192,7 @@ def _finish_opening(path: Path, opening: threading.Event) -> None:opening.set()-def acquire(db_path: Optional[Path] = None) -> "SessionDB":+def acquire(db_path: Optional[Path] = None) -> SessionDB:"""Return the shared SessionDB for *db_path*, incrementing its refcount. If the file wasreplaced (different inode) since the generation opened, that generation is RETIREDbut stays alive for its holders, and a fresh one is opened in its place. Raises@@ -273,7 +273,7 @@ def acquire(db_path: Optional[Path] = None) -> "SessionDB":return winner-def release(db: "SessionDB") -> bool:+def release(db: SessionDB) -> bool:"""Decrement the refcount of a shared SessionDB. ``True`` if *db* was shared; ``False``if it is not registry-managed (caller owns close()). The final release tears thegeneration down OUTSIDE the registry lock. Lookup is object-keyed, so holders of an@@ -399,7 +399,7 @@ def close_all_under(directory: str | Path) -> int:def other_generations_for_path(- db_path: Path, *, exclude: Optional["SessionDB"] = None+ db_path: Path, *, exclude: Optional[SessionDB] = None) -> list[str]:"""Describe every other LIVE SessionDB generation THIS process holds for *db_path*.@@ -430,7 +430,7 @@ def other_generations_for_path(]-def live_shared_session_dbs() -> list["SessionDB"]:+def live_shared_session_dbs() -> list[SessionDB]:"""Snapshot of every live (non-retired) shared SessionDB (refcounts untouched), forin-process maintenance. A concurrent final release may close an instance, in whichcase the callee sees ``_conn is None``."""@@ -439,7 +439,7 @@ def live_shared_session_dbs() -> list["SessionDB"]:@contextlib.contextmanager-def borrow_live_shared_session_dbs() -> Iterator[list["SessionDB"]]:+def borrow_live_shared_session_dbs() -> Iterator[list[SessionDB]]:"""Borrow live handles with registry references pinned for the whole block.Maintenance must not operate on the unowned snapshot returned by@@ -471,7 +471,7 @@ def stats() -> dict[str, int]:}-def release_or_close(db: "SessionDB") -> None:+def release_or_close(db: SessionDB) -> None:"""Release a shared instance, or close it when it is not registry-managed. Drop-in for aplain ``db.close()``: read-only opens, CLI one-shots and test fakes fall back."""if not release(db):diff --git a/hermes_state_repair.py b/hermes_state_repair.pyindex 0bc23786647..c4f09f68f55 100644--- a/hermes_state_repair.py+++ b/hermes_state_repair.py@@ -249,7 +249,7 @@ def _repair_backup_headroom_bytes(total_bytes: int) -> int:return max(_REPAIR_BACKUP_MIN_FREE_BYTES, int(total_bytes * _REPAIR_BACKUP_FREE_FRACTION))-def _disk_budget(db_path: Path, refusal: str) -> "tuple[Optional[str], int, int, int]":+def _disk_budget(db_path: Path, refusal: str) -> tuple[Optional[str], int, int, int]:"""``(error, bundle_bytes, free_bytes, headroom_bytes)`` for *db_path*'s volume (main file plus every PRESENTsidecar); *error* is set (and the sizes zero) on stat()/disk_usage() failure. Fails CLOSED: the nearly-fullvolume these guards exist for is exactly where they are most likely to fail."""@@ -319,7 +319,7 @@ def _repair_ledger_path(db_path: Path) -> Path:return db_path.with_name(db_path.name + ".repair-attempts.json")-def _db_fingerprint(db_path: Path) -> "Optional[str]":+def _db_fingerprint(db_path: Path) -> Optional[str]:"""Cheap identity for a damaged DB file: size + a bounded content sample.EXCLUDES mtime: a malformed-schema DB still accepts writes, so live writers, checkpoints and the@@ -340,7 +340,7 @@ def _db_fingerprint(db_path: Path) -> "Optional[str]":return _read_offline(db_path, "fingerprint", _sample)-def _backup_content_identity(db_path: Path) -> "Optional[str]":+def _backup_content_identity(db_path: Path) -> Optional[str]:"""Recovery-image identity for forensic-backup dedupe: whole file + sidecars.A DIFFERENT relation from :func:`_db_fingerprint` (never conflate them): the fingerprint answers "same@@ -366,7 +366,7 @@ def _backup_content_identity(db_path: Path) -> "Optional[str]":return _read_offline(db_path, "backup-identity", _digest)-def _read_repair_ledger(db_path: Path) -> "dict[str, Any]":+def _read_repair_ledger(db_path: Path) -> dict[str, Any]:with contextlib.suppress(OSError, ValueError):raw = json.loads(_repair_ledger_path(db_path).read_text(encoding="utf-8"))return raw if isinstance(raw, dict) else {}@@ -405,7 +405,7 @@ def _persistent_repair_exhausted_error(db_path: Path) -> str:f"Delete {_repair_ledger_path(db_path).name} to force another automatic attempt.")-def _record_repair_outcome(db_path: Path, *, repaired: bool, fingerprint: "Optional[str]" = None) -> None:+def _record_repair_outcome(db_path: Path, *, repaired: bool, fingerprint: Optional[str] = None) -> None:"""Update the persistent attempt ledger after a repair pass. Never raises.Keys on the post-attempt fingerprint (what the NEXT exhaustion probe sees). If a live connection makes it@@ -432,7 +432,7 @@ def _record_repair_outcome(db_path: Path, *, repaired: bool, fingerprint: "Optiologger.warning("Could not update state.db repair ledger: %s", exc)-def _existing_malformed_backups(db_path: Path) -> "list[Path]":+def _existing_malformed_backups(db_path: Path) -> list[Path]:"""Timestamped forensic backups of *db_path*, newest first."""prefix = f"{db_path.name}.malformed-backup-"try:@@ -461,7 +461,7 @@ def _publish_backup_bundle(db_path: Path, staging: Path, backup_path: Path) -> Nmain = (db_path, staging, backup_path)sidecars = [(sidecar, staging.with_name(staging.name + suffix), backup_path.with_name(backup_path.name + suffix))for suffix, sidecar in zip(_DB_SIDECAR_SUFFIXES, _sidecars(db_path)) if sidecar.exists()]- published: "list[Path]" = []+ published: list[Path] = []try:for src, staged, _dst in (main, *sidecars):shutil.copy2(src, staged)@@ -475,7 +475,7 @@ def _publish_backup_bundle(db_path: Path, staging: Path, backup_path: Path) -> Nraise-def _backup_db_file(db_path: Path) -> "tuple[Optional[Path], Optional[str]]":+def _backup_db_file(db_path: Path) -> tuple[Optional[Path], Optional[str]]:"""Raw-copy a (possibly malformed) DB plus sidecars to a timestamped backup.Raw bytes on purpose: the DB won't open cleanly, so preserve them exactly for forensics. Returns ``(backup_path,diff --git a/hermes_state_search.py b/hermes_state_search.pyindex ae7660325b5..95caec48254 100644--- a/hermes_state_search.py+++ b/hermes_state_search.py@@ -826,7 +826,7 @@ class SessionSearchMixin:# left-to-right without backtracking); a leftover unmatched quote becomes whitespace._quoted_parts: list = []- def _hold(m: "re.Match[str]") -> str:+ def _hold(m: re.Match[str]) -> str:_quoted_parts.append(m.group(0))return f"\x00Q{len(_quoted_parts) - 1}\x00"diff --git a/mcp_serve.py b/mcp_serve.pyindex c5b26e73d54..e64c1c85add 100644--- a/mcp_serve.py+++ b/mcp_serve.py@@ -689,7 +689,7 @@ _TOOL_NAMES = ()-def create_mcp_server(event_bridge: Optional[EventBridge] = None) -> "MCPServer":+def create_mcp_server(event_bridge: Optional[EventBridge] = None) -> MCPServer:"""Create and return the Hermes MCP server with all tools registered."""if not _MCP_SERVER_AVAILABLE:raise ImportError(f"MCP server requires the 'mcp' package. Install with: {sys.executable} -m pip install 'mcp'")diff --git a/optional-skills/devops/watchers/scripts/_watermark.py b/optional-skills/devops/watchers/scripts/_watermark.pyindex e888139f2f2..7dfbd7e5154 100755--- a/optional-skills/devops/watchers/scripts/_watermark.py+++ b/optional-skills/devops/watchers/scripts/_watermark.py@@ -51,7 +51,7 @@ class Watermark:self._data: dict[str, Any] = {"seen_ids": [], "first_run": True}@classmethod- def load(cls, name: str, *, max_seen: int = 500) -> "Watermark":+ def load(cls, name: str, *, max_seen: int = 500) -> Watermark:wm = cls(name, max_seen=max_seen)if wm._path.exists():try:diff --git a/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py b/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.pyindex f9045011bbd..9f15bdd4dcd 100644--- a/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py+++ b/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py@@ -534,7 +534,7 @@ def _case_preserving_replacement(replacement: str):``~/.hermes/config.yaml`` (the real Hermes home) instead of the broken``~/.Hermes/config.yaml``."""- def _sub(match: "re.Match[str]") -> str:+ def _sub(match: re.Match[str]) -> str:matched = match.group(0)if matched and matched.islower():return replacement.lower()diff --git a/plugins/computer_use/__init__.py b/plugins/computer_use/__init__.pyindex e6f14c2fea2..15e21bd2069 100644--- a/plugins/computer_use/__init__.py+++ b/plugins/computer_use/__init__.py@@ -53,7 +53,7 @@ def find_provider_dir(name: str) -> Optional[Path]:return next((path for found, path in _iter_provider_dirs() if found == name), None)-def load_computer_use_provider(name: str) -> Optional["ComputerUseProvider"]:+def load_computer_use_provider(name: str) -> Optional[ComputerUseProvider]:"""Import the named provider and return its ComputerUseProvider; None if not found or it fails to load."""provider_dir = find_provider_dir(name)if provider_dir is None:@@ -62,7 +62,7 @@ def load_computer_use_provider(name: str) -> Optional["ComputerUseProvider"]:noun="provider", logger=logger)-def _load_provider_from_dir(provider_dir: Path) -> Optional["ComputerUseProvider"]:+def _load_provider_from_dir(provider_dir: Path) -> Optional[ComputerUseProvider]:# Providers hand back live driver sessions, so they load in-process only: load_plugin_module refuses user# code under ``plugins.isolation: host`` (warning + None), which surfaces as "could not be loaded".from tools.computer_use.backend import ComputerUseProvider@@ -95,7 +95,7 @@ def configured_backend_name() -> str:return raw.strip() if isinstance(raw, str) and raw.strip() else DEFAULT_BACKEND-def get_active_provider() -> "ComputerUseProvider":+def get_active_provider() -> ComputerUseProvider:"""The one provider ``computer_use.backend`` selects; ``LookupError`` naming the available ones otherwise."""name = configured_backend_name()provider = load_computer_use_provider(name)diff --git a/plugins/context_engine/__init__.py b/plugins/context_engine/__init__.pyindex 62d28b113f9..dd36c9bb144 100644--- a/plugins/context_engine/__init__.py+++ b/plugins/context_engine/__init__.py@@ -57,7 +57,7 @@ def find_engine_dir(name: str) -> Optional[Path]:return user if user and user.is_dir() and _is_context_engine_dir(user) else None-def load_context_engine(name: str) -> Optional["ContextEngine"]:+def load_context_engine(name: str) -> Optional[ContextEngine]:"""Load a ContextEngine instance by name; None if not found or it fails to load."""engine_dir = find_engine_dir(name)if engine_dir is None:@@ -68,7 +68,7 @@ def load_context_engine(name: str) -> Optional["ContextEngine"]:)-def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]:+def _load_engine_from_dir(engine_dir: Path) -> Optional[ContextEngine]:"""Import an engine module and extract its ContextEngine (register(ctx) or subclass)."""from agent.context_engine import ContextEnginename = engine_dir.namediff --git a/plugins/cron_providers/__init__.py b/plugins/cron_providers/__init__.pyindex 5e81c56d117..8651836d506 100644--- a/plugins/cron_providers/__init__.py+++ b/plugins/cron_providers/__init__.py@@ -61,7 +61,7 @@ def discover_cron_schedulers() -> list[tuple[str, str, bool]]:for name, child in _iter_provider_dirs()]-def load_cron_scheduler(name: str) -> Optional["CronScheduler"]:+def load_cron_scheduler(name: str) -> Optional[CronScheduler]:"""Load a CronScheduler instance by name; None if not found or it fails to load."""provider_dir = find_provider_dir(name)if not provider_dir:@@ -72,7 +72,7 @@ def load_cron_scheduler(name: str) -> Optional["CronScheduler"]:kind="Cron provider", noun="provider", logger=logger)-def _load_provider_from_dir(provider_dir: Path) -> Optional["CronScheduler"]:+def _load_provider_from_dir(provider_dir: Path) -> Optional[CronScheduler]:"""Import a provider module and extract its CronScheduler (register(ctx) or subclass)."""from cron.scheduler_provider import CronSchedulername = provider_dir.namediff --git a/plugins/google_meet/meet_bot.py b/plugins/google_meet/meet_bot.pyindex 10358bb61f1..277c1eaf391 100644--- a/plugins/google_meet/meet_bot.py+++ b/plugins/google_meet/meet_bot.py@@ -218,7 +218,7 @@ def _pcm_tail_loop(proc, pcm_path: Path, stop_flag: dict, poll_interval: float =_quiet(proc.stdin.close)-def _start_pcm_pump(rt: dict, bridge_info: dict, pcm_path: Path, state: "_BotState",+def _start_pcm_pump(rt: dict, bridge_info: dict, pcm_path: Path, state: _BotState,stop_flag: dict) -> None:"""Stream the growing ``speaker.pcm`` (24kHz s16le mono) into the device Chrome's fake mic reads.The pump reads raw PCM from stdin (``-``) so audio appended after start-up is still played —@@ -257,7 +257,7 @@ def _start_pcm_pump(rt: dict, bridge_info: dict, pcm_path: Path, state: "_BotStart["pcm_tail_thread"].start()-def _start_realtime_speaker(rt: dict, cfg: "_BotConfig", stop_flag: dict, state: "_BotState") -> None:+def _start_realtime_speaker(rt: dict, cfg: _BotConfig, stop_flag: dict, state: _BotState) -> None:"""Wire up the OpenAI Realtime session, the say-queue speaker thread and the PCM pump."""pcm_path, queue_path = cfg.out_dir / "speaker.pcm", cfg.out_dir / "say_queue.jsonl"pcm_path.write_bytes(b"") # clean sink file per sessiondiff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.pyindex 18edac30786..2ec5ea0c570 100644--- a/plugins/kanban/dashboard/plugin_api.py+++ b/plugins/kanban/dashboard/plugin_api.py@@ -47,7 +47,7 @@ _BOARD_Q = Query(None, description="Kanban board slug (omit for current)")# --- Connection / board helpers ----------------------------------------------def _ws_upgrade_authorized(ws: "WebSocket") -> bool:+def _ws_upgrade_authorized(ws: WebSocket) -> bool:"""Authorize a WS upgrade via the dashboard's canonical gate (``web_server_chat._ws_auth_ok``:``?token=`` / ``?ticket=`` / ``?internal=``) so this endpoint can never drift from coreauth; accepts when the dashboard isn't importable (bare-FastAPI test harness)."""diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 6c1c3d13cac..8a645f6f2b6 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -212,7 +212,7 @@ def discover_memory_providers() -> list[tuple[str, str, bool]]:return results-def load_memory_provider(name: str, *, register_skills: Optional[bool] = None) -> Optional["MemoryProvider"]:+def load_memory_provider(name: str, *, register_skills: Optional[bool] = None) -> Optional[MemoryProvider]:"""Load a MemoryProvider by name (bundled, user, project, then pip entry point);None if not found or failing to load. Skills register only for the configuredactive provider unless ``register_skills`` is explicit, so inspecting inactive@@ -310,7 +310,7 @@ def import_provider_module(name: str, submodule: Optional[str] = None):return importlib.import_module(f"{package.__name__}.{submodule}") if submodule else package-def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:+def _instantiate_subclass(namespace) -> Optional[MemoryProvider]:"""First instantiable ``MemoryProvider`` subclass found among *namespace*'s attributes."""from agent.memory_provider import MemoryProvider@@ -324,7 +324,7 @@ def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:return None-def _load_provider_from_entry_point(entry_point, *, register_skills: bool = True) -> Optional["MemoryProvider"]:+def _load_provider_from_entry_point(entry_point, *, register_skills: bool = True) -> Optional[MemoryProvider]:"""Import a provider entry point and extract the MemoryProvider instance: aninstance, a subclass, a module with ``register(ctx)``, a factory / ``register``callable, or a namespace holding a subclass — in that order."""@@ -360,7 +360,7 @@ def _load_provider_from_entry_point(entry_point, *, register_skills: bool = Truereturn provider-def _load_provider_from_dir(provider_dir: Path, *, register_skills: bool = True) -> Optional["MemoryProvider"]:+def _load_provider_from_dir(provider_dir: Path, *, register_skills: bool = True) -> Optional[MemoryProvider]:"""Import a provider module; ``register(ctx)`` first, else a top-level subclass."""name = provider_dir.namefrom hermes_cli.plugin_isolation import user_plugin_hostdiff --git a/plugins/memory/holographic/holographic.py b/plugins/memory/holographic/holographic.pyindex f3fd0ede670..05b6ee35b66 100644--- a/plugins/memory/holographic/holographic.py+++ b/plugins/memory/holographic/holographic.py@@ -29,7 +29,7 @@ def _require_numpy() -> None:raise RuntimeError("numpy is required for holographic operations")-def encode_atom(word: str, dim: int = 1024) -> "np.ndarray":+def encode_atom(word: str, dim: int = 1024) -> np.ndarray:"""Deterministic phase vector: SHA-256 counter blocks of f"{word}:{i}" -> uint16 -> [0, 2π).hashlib rather than numpy RNG so atoms are reproducible across platforms."""_require_numpy()@@ -38,38 +38,38 @@ def encode_atom(word: str, dim: int = 1024) -> "np.ndarray":return np.array(uint16_values[:dim], dtype=np.float64) * (_TWO_PI / 65536.0)-def bind(a: "np.ndarray", b: "np.ndarray") -> "np.ndarray":+def bind(a: np.ndarray, b: np.ndarray) -> np.ndarray:"""Circular convolution = phase addition; result is quasi-orthogonal to both inputs."""_require_numpy()return (a + b) % _TWO_PI-def unbind(memory: "np.ndarray", key: "np.ndarray") -> "np.ndarray":+def unbind(memory: np.ndarray, key: np.ndarray) -> np.ndarray:"""Circular correlation = phase subtraction; unbind(bind(a, b), a) ≈ b."""_require_numpy()return (memory - key) % _TWO_PI-def bundle(*vectors: "np.ndarray") -> "np.ndarray":+def bundle(*vectors: np.ndarray) -> np.ndarray:"""Superposition via circular mean; holds O(sqrt(dim)) items before similarity degrades."""_require_numpy()return np.angle(np.sum([np.exp(1j * v) for v in vectors], axis=0)) % _TWO_PI-def similarity(a: "np.ndarray", b: "np.ndarray") -> float:+def similarity(a: np.ndarray, b: np.ndarray) -> float:"""Phase cosine similarity in [-1, 1]; ~0 for unrelated vectors."""_require_numpy()return float(np.mean(np.cos(a - b)))-def encode_text(text: str, dim: int = 1024) -> "np.ndarray":+def encode_text(text: str, dim: int = 1024) -> np.ndarray:"""Bag-of-words bundle of token atoms; empty text -> encode_atom("__hrr_empty__")."""_require_numpy()tokens = [t for t in (tok.strip(".,!?;:\"'()[]{}") for tok in text.lower().split()) if t]return bundle(*[encode_atom(token, dim) for token in tokens]) if tokens else encode_atom("__hrr_empty__", dim)-def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarray":+def encode_fact(content: str, entities: list[str], dim: int = 1024) -> np.ndarray:"""bundle(bind(text, ROLE_CONTENT), bind(entity_i, ROLE_ENTITY)...), sounbind(fact, bind(entity, ROLE_ENTITY)) ≈ content_vector."""_require_numpy()@@ -78,7 +78,7 @@ def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarr*[bind(encode_atom(entity.lower(), dim), role_entity) for entity in entities])-def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:+def phases_to_bytes(phases: np.ndarray, dim: int | None = None) -> bytes:"""Serialize as prefixed float32 (half the size of legacy float64 blobs). At dim=1 the prefixed float32 bloband a raw float64 blob are both 8 bytes, so write legacy float64 there to keep ``bytes_to_phases`` unambiguous."""_require_numpy()@@ -88,7 +88,7 @@ def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:return _FLOAT32_BLOB_PREFIX + np.asarray(phases, dtype=np.float32).tobytes()-def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":+def bytes_to_phases(data: bytes, dim: int | None = None) -> np.ndarray:"""Deserialize prefixed float32 or legacy raw float64 blobs (always returns float64). With ``dim`` given, aprefixed blob whose size equals the float64 size (dim=1) is read as legacy float64: ``phases_to_bytes`` neverwrites a prefixed blob at that size."""diff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.pyindex a913cf2d394..bf40b780994 100644--- a/plugins/memory/holographic/store.py+++ b/plugins/memory/holographic/store.py@@ -97,7 +97,7 @@ class MemoryStore:_shared: dict = {}_shared_guard = threading.Lock()- def __init__(self, db_path: "str | Path | None" = None, default_trust: float = 0.5, hrr_dim: int = 1024) -> None:+ def __init__(self, db_path: str | Path | None = None, default_trust: float = 0.5, hrr_dim: int = 1024) -> None:if db_path is None:from hermes_constants import get_hermes_homedb_path = str(get_hermes_home() / "memory_store.db")@@ -262,7 +262,7 @@ class MemoryStore:"updated_at = excluded.updated_at", (bank_name, hrr.phases_to_bytes(bank_vector), self.hrr_dim, len(rows)))@classmethod- def release_all_under(cls, directory: "str | Path") -> int:+ def release_all_under(cls, directory: str | Path) -> int:"""Force-close every shared connection whose database lives under ``directory``; returns the count.close() is refcount-driven, so a live holder (e.g. an agent's provider) keeps a profile's SQLite handleopen, which on Windows makes rmtree of the profile fail. The directory is going away, so later use by a@@ -302,7 +302,7 @@ class MemoryStore:MemoryStore._shared.pop(self._key, None)self._entry = None- def __enter__(self) -> "MemoryStore":+ def __enter__(self) -> MemoryStore:return selfdef __exit__(self, *_: object) -> None:diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.pyindex 6918a44d16f..36ac5d60be0 100644--- a/plugins/platforms/a2a/adapter.py+++ b/plugins/platforms/a2a/adapter.py@@ -155,7 +155,7 @@ class A2ARequestHandler(BaseHTTPRequestHandler):"""HTTP handler for the A2A JSON-RPC surface; all state lives on ``self.server.adapter``."""@property- def adapter(self) -> "A2AAdapter":+ def adapter(self) -> A2AAdapter:return self.server.adapter # type: ignore[attr-defined]def log_message(self, format, *args):diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.pyindex 907ab4904a7..b5206d245b6 100644--- a/plugins/platforms/a2a/protocol.py+++ b/plugins/platforms/a2a/protocol.py@@ -79,7 +79,7 @@ def build_agent_card(*, name: str, url: str, description: str, skills: Optional[return card-def skills_from_toolsets(toolsets: "list[str] | dict[str, list[str]] | None") -> list[dict]:+def skills_from_toolsets(toolsets: list[str] | dict[str, list[str]] | None) -> list[dict]:"""A2A skill descriptors from toolset names or a toolset -> tool-names mapping (tool namesbecome tags, max 10)."""if not isinstance(toolsets, dict):@@ -296,7 +296,7 @@ class TaskStore:_MAX_TERMINAL = 500def __init__(self) -> None:- self._tasks: "OrderedDict[str, dict[str, Any]]" = OrderedDict()+ self._tasks: OrderedDict[str, dict[str, Any]] = OrderedDict()self._watchers: dict[str, list[Future]] = {}self._lock = threading.Lock()diff --git a/plugins/platforms/a2a/security.py b/plugins/platforms/a2a/security.pyindex e6215021d40..31871cf403a 100644--- a/plugins/platforms/a2a/security.py+++ b/plugins/platforms/a2a/security.py@@ -64,7 +64,7 @@ class A2ASecurityContext:push_secret: str@classmethod- def capture(cls) -> "A2ASecurityContext":+ def capture(cls) -> A2ASecurityContext:bearer_token = _startup_env("A2A_BEARER_TOKEN")return cls(bearer_token=bearer_token, peer_tokens=tuple(_parse_peer_tokens(_startup_env("A2A_PEER_TOKENS")).items()),trusted_peers=_configured_trusted_peers(),diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex a93bd718425..739368dec9f 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -570,7 +570,7 @@ class BuzzAdapter(BasePlatformAdapter):self._member_cache: dict[str, tuple[float, list[str]]] = {} # (monotonic, pubkeys)self._profile_name_cache: dict[str, tuple[float, str]] = {}# inbound event_id -> thread root (None when top-level), so send() joins the user's thread instead of nesting.- self._thread_roots: "OrderedDict[str, Optional[str]]" = OrderedDict()+ self._thread_roots: OrderedDict[str, Optional[str]] = OrderedDict()@propertydef name(self) -> str:diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex fb62e53ea99..f595a58d94e 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -410,7 +410,7 @@ class DingTalkAdapter(BasePlatformAdapter):def _message_matches_mention_patterns(self, text: str) -> bool:return bool(text and self._mention_patterns) and any(p.search(text) for p in self._mention_patterns)- def _should_process_message(self, message: "ChatbotMessage", text: str, is_group: bool, chat_id: str) -> bool:+ def _should_process_message(self, message: ChatbotMessage, text: str, is_group: bool, chat_id: str) -> bool:"""Group trigger rules (DMs always pass; ``allowed_users`` is enforced earlier): ``allowed_chats`` is a hardgate, then any of free_response_chats / require_mention off / @mentioned (SDK ``is_in_at_list``) / wake-word."""if not is_group:@@ -455,7 +455,7 @@ class DingTalkAdapter(BasePlatformAdapter):await self._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.done"), recall=False)self._spawn_bg(_swap())- async def _on_message(self, message: "ChatbotMessage") -> None:+ async def _on_message(self, message: ChatbotMessage) -> None:"""Process an incoming DingTalk chatbot message."""msg_id = getattr(message, "message_id", None) or uuid.uuid4().hexif self._dedup.is_duplicate(msg_id):@@ -496,7 +496,7 @@ class DingTalkAdapter(BasePlatformAdapter):_extract_text = staticmethod(extract_text)- def _extract_media(self, message: "ChatbotMessage"):+ def _extract_media(self, message: ChatbotMessage):return extract_media(message)async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None) -> SendResult:@@ -664,7 +664,7 @@ class DingTalkAdapter(BasePlatformAdapter):except Exception:logger.debug("[%s] _send_emotion %s failed", self.name, action, exc_info=True)- async def _resolve_media_codes(self, message: "ChatbotMessage") -> None:+ async def _resolve_media_codes(self, message: ChatbotMessage) -> None:"""Resolve download codes in the message to real URLs (in place, in parallel)."""token = await self._get_access_token()if not token:@@ -719,7 +719,7 @@ class _IncomingHandler(dingtalk_stream.ChatbotHandler if DINGTALK_STREAM_AVAILAB"""No-op hook the SDK calls on every handler before opening the WebSocket (missing → AttributeError)."""return- async def process(self, message: "CallbackMessage"):+ async def process(self, message: CallbackMessage):"""Convert to ChatbotMessage, dispatch as a background task, ACK immediately (blocking would stall SDK heartbeats)."""try:data = json.loads(message.data) if isinstance(message.data, str) else message.data@@ -739,7 +739,7 @@ class _IncomingHandler(dingtalk_stream.ChatbotHandler if DINGTALK_STREAM_AVAILABreturn AckMessage.STATUS_SYSTEM_EXCEPTION, "error"return AckMessage.STATUS_OK, "OK"- async def _safe_on_message(self, chatbot_msg: "ChatbotMessage") -> None:+ async def _safe_on_message(self, chatbot_msg: ChatbotMessage) -> None:try:await self._adapter._on_message(chatbot_msg)except Exception:diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 519f51cab6e..5aa00806ea9 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -3250,7 +3250,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInawait self._add_reaction(message, "❌")@staticmethod- def _message_reference_from_ids(message_id, channel) -> "discord.MessageReference":+ def _message_reference_from_ids(message_id, channel) -> discord.MessageReference:"""ids-built reply reference — no fetch_message round trip. fail_if_not_exists=Falsekeeps sends to deleted targets degrading to the send-side 10008 retry."""return discord.MessageReference(@@ -4243,7 +4243,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn)async def _check_slash_authorization(- self, interaction: "discord.Interaction", command_text: str,+ self, interaction: discord.Interaction, command_text: str,) -> bool:"""Mirror on_message's gates onto a slash invocation.Returns False only *after* sending the ephemeral rejection, so the caller just stops."""@@ -4253,7 +4253,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInreturn await self._reject_slash(interaction, command_text, reason=reason or "unauthorized")async def _reject_slash(- self, interaction: "discord.Interaction", command_text: str, *, reason: str,+ self, interaction: discord.Interaction, command_text: str, *, reason: str,) -> bool:"""Send ephemeral reject + log + schedule admin alert; returns False.Tolerates a missing ``interaction.user`` (fail-closed branch routes malformed payloads here)."""@@ -4750,7 +4750,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInif not self._skill_entries:return- async def _autocomplete_name(interaction: "discord.Interaction", current: str) -> list:+ async def _autocomplete_name(interaction: discord.Interaction, current: str) -> list:"""Filter skills by typed prefix against name and description (Discord caps at 25).Unauthorized users get ``[]``: no catalog leak, no per-keystroke ephemeral rejections."""try:@@ -4778,7 +4778,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInargs=_t_discord("platform.discord.command.skill.arg_args", _DISCORD_APP_COMMAND_TEXT_LIMIT),)@discord.app_commands.autocomplete(name=_autocomplete_name)- async def _skill_handler(interaction: "discord.Interaction", name: str, args: str = ""):+ async def _skill_handler(interaction: discord.Interaction, name: str, args: str = ""):# Authorize BEFORE lookup so unknown/known names reject identically (no catalog probing).if not await self._check_slash_authorization(interaction, "/skill"):return@@ -5267,7 +5267,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInreturn 50async def _fetch_channel_context(- self, channel: Any, before: "DiscordMessage", reply_target: Optional[Any] = None,+ self, channel: Any, before: DiscordMessage, reply_target: Optional[Any] = None,) -> str:"""Fetch recent channel messages; returns a ``[Recent channel messages]`` block or "".Scans back from *before* to the bot's own message or ``history_backfill_limit``; with@@ -5525,7 +5525,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInpassreturn thread- async def _auto_create_thread(self, message: 'DiscordMessage') -> Optional[Any]:+ async def _auto_create_thread(self, message: DiscordMessage) -> Optional[Any]:"""Create an auto-thread from a user message; returns the thread or ``None``.Primary path and seed-message fallback each retry once after a short backoff (transient errors).@@ -6940,11 +6940,11 @@ def _define_discord_view_classes() -> None:return f"{prefix}{truncated.rstrip() + _DISCORD_ELLIPSIS}"def _make_choice_callback(self, index: int, choice: str):- async def _callback(interaction: "discord.Interaction"):+ async def _callback(interaction: discord.Interaction):await self._resolve_choice(interaction, index, choice)return _callback- async def _finish(self, interaction: "discord.Interaction", color, footer: str, *, log_edit_failure: bool) -> None:+ async def _finish(self, interaction: discord.Interaction, color, footer: str, *, log_edit_failure: bool) -> None:"""Disable the buttons and stamp the embed; fall back to a bare defer."""self.resolved = Trueself._disable_all()@@ -6962,7 +6962,7 @@ def _define_discord_view_classes() -> None:except Exception:pass- async def _resolve_choice(self, interaction: "discord.Interaction", index: int, choice: str) -> None:+ async def _resolve_choice(self, interaction: discord.Interaction, index: int, choice: str) -> None:"""Resolve the clarify with a chosen option."""if not await self._gate(interaction, resolved_msg=t("platform.discord.prompt.clarify_already_answered"),@@ -6995,7 +6995,7 @@ def _define_discord_view_classes() -> None:except Exception as exc:logger.error("Discord clarify resolve_gateway_clarify failed (id=%s): %s", self.clarify_id, exc)- async def _on_other(self, interaction: "discord.Interaction") -> None:+ async def _on_other(self, interaction: discord.Interaction) -> None:"""Flip the clarify entry into text-capture mode."""if not await self._gate(interaction, resolved_msg=t("platform.discord.prompt.clarify_already_answered"),diff --git a/plugins/platforms/discord/adapter_slash_auth.py b/plugins/platforms/discord/adapter_slash_auth.pyindex 0404a6844fe..ebb80b5cde6 100644--- a/plugins/platforms/discord/adapter_slash_auth.py+++ b/plugins/platforms/discord/adapter_slash_auth.py@@ -21,7 +21,7 @@ class DiscordSlashAuthMixin:# fail closed unless allow-all; DISCORD_ALLOWED_CHANNELS alone authorizes per validated channel.def _evaluate_slash_authorization(- self, interaction: "discord.Interaction",+ self, interaction: discord.Interaction,) -> tuple[bool, Optional[str]]:"""Evaluate slash authorization without responding; returns ``(allowed, reason)``.Shared with side-effect-free callers (``/skill`` autocomplete returns [] per keystroke).@@ -83,7 +83,7 @@ class DiscordSlashAuthMixin:return (False, "user not in DISCORD_ALLOWED_USERS / DISCORD_ALLOWED_ROLES")return (True, None)- def _slash_role_grant(self, interaction: "discord.Interaction") -> bool:+ def _slash_role_grant(self, interaction: discord.Interaction) -> bool:"""``role_authorized`` for an event built from ``interaction``, with the message path'smeaning (_discord_message_admission): a role allowlist exists and THIS actor passes the gate.Re-evaluated for the interaction instead of trusted from call order, so a builder can neverdiff --git a/plugins/platforms/discord/voice_mixer.py b/plugins/platforms/discord/voice_mixer.pyindex ecfce50d423..b1753bb879b 100644--- a/plugins/platforms/discord/voice_mixer.py+++ b/plugins/platforms/discord/voice_mixer.py@@ -50,7 +50,7 @@ class MixerChild:self.fade_frames = max(0, fade_in_ms // FRAME_LENGTH_MS)self._finished = False- def read_frame(self) -> "Optional[np.ndarray]":+ def read_frame(self) -> Optional[np.ndarray]:"""Next 20 ms frame as a float32 ndarray, or None when done."""if self._finished:return None@@ -140,7 +140,7 @@ class VoiceMixer(discord.AudioSource):if self._closed:return SILENCE_FRAMEnp = _require_numpy()- acc: "Optional[np.ndarray]" = None+ acc: Optional[np.ndarray] = None# Speech children (drop exhausted ones; release duck when last ends)if self._speech:still_live: list[MixerChild] = []diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex 8f3d0b59e0c..d983fd81c79 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -117,7 +117,7 @@ def _tls_context(verify: bool, host: str) -> ssl.SSLContext:return ssl._create_unverified_context()-def _close_imap(imap: "imaplib.IMAP4") -> None:+def _close_imap(imap: imaplib.IMAP4) -> None:"""Teardown that guarantees the socket closes: ``logout()`` only guards ``OSError``, so ``IMAP4.abort`` on abroken connection skipped ``shutdown()`` and leaked one fd per failed poll (fatal on macOS's 256 soft limit).@@ -175,7 +175,7 @@ def _open_smtp(host: str, port: int, security: str, ctx: ssl.SSLContext, smtp_clreturn smtp-def _send_imap_id(imap: "imaplib.IMAP4") -> None:+def _send_imap_id(imap: imaplib.IMAP4) -> None:"""Send RFC 2971 IMAP ID: 163/NetEase require it after LOGIN (else every UID commandreturns ``BYE Unsafe Login``); other servers may reject it, so failures are swallowed.@@ -226,7 +226,7 @@ def check_email_requirements() -> bool:return all(_get_secret(name, "").strip() for name in ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"))-def _safe_decode(payload: bytes, charset: "Optional[str]") -> str:+def _safe_decode(payload: bytes, charset: Optional[str]) -> str:"""Decode without ever raising: ``errors="replace"`` does not guard a missing codec (``LookupError``), so fall back alias → UTF-8 → latin-1.Unknown or malformed charset labels (``unknown-8bit``, misspelled names, attacker-controlled garbage)@@ -665,7 +665,7 @@ class EmailAdapter(BasePlatformAdapter):self._set_fatal_error("email_imap_fetch_failed", self._last_fetch_error or "IMAP fetch failed", retryable=True)await self._notify_fatal_error()- def _mark_uid_consumed(self, imap: "imaplib.IMAP4", uid: Any) -> None:+ def _mark_uid_consumed(self, imap: imaplib.IMAP4, uid: Any) -> None:"""Remember a rejected UID and mark it seen without fetching its MIME body."""self._seen_uids.add(uid)self._trim_seen_uids()@@ -744,11 +744,11 @@ class EmailAdapter(BasePlatformAdapter):"message_id": msg.get("Message-ID", ""), "in_reply_to": msg.get("In-Reply-To", ""),"date": msg.get("Date", ""), "sender_authenticated": sender_authenticated, "auth_reason": auth_reason}- def _parse_fetched_headers(self, uid: bytes, raw_headers: "bytes | bytearray") -> Optional[dict[str, Any]]:+ def _parse_fetched_headers(self, uid: bytes, raw_headers: bytes | bytearray) -> Optional[dict[str, Any]]:"""Parse the bounded IMAP header preflight without constructing a MIME tree."""return self._message_metadata(uid, BytesHeaderParser().parsebytes(bytes(raw_headers)))- def _parse_fetched_message(self, uid: bytes, raw_email: "bytes | bytearray") -> Optional[dict[str, Any]]:+ def _parse_fetched_message(self, uid: bytes, raw_email: bytes | bytearray) -> Optional[dict[str, Any]]:"""Parse an authorized RFC822 payload into a dispatchable dict."""msg = email_lib.message_from_bytes(raw_email)if (metadata := self._message_metadata(uid, msg)) is None:diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex ca46d82bf1c..a62f39d340e 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -892,7 +892,7 @@ def _first_text_field(payload: dict[str, Any], *keys: str, deep: tuple[str, ...]# --- General text utilities ---def _normalize_feishu_text(text: str, mentions_map: Optional[dict[str, FeishuMentionRef]] = None) -> str:- def _sub(match: "re.Match[str]") -> str:+ def _sub(match: re.Match[str]) -> str:ref = (mentions_map or {}).get(match.group(0))return " " if ref is None else f"@{ref.name or ref.open_id or 'user'}"@@ -1326,9 +1326,9 @@ class FeishuAdapter(BasePlatformAdapter):self._pending_inbound_lock = threading.Lock()self._pending_drain_scheduled = Falseself._pending_inbound_max_depth = 1000 # cap queue; drop oldest beyond- self._chat_locks: "collections.OrderedDict[str, asyncio.Lock]" = collections.OrderedDict() # chat_id → lock (per-chat serial processing, LRU-bounded)+ self._chat_locks: collections.OrderedDict[str, asyncio.Lock] = collections.OrderedDict() # chat_id → lock (per-chat serial processing, LRU-bounded)self._chat_info_cache: dict[str, dict[str, Any]] = {}- self._message_text_cache: "OrderedDict[str, Optional[str]]" = OrderedDict()+ self._message_text_cache: OrderedDict[str, Optional[str]] = OrderedDict()self._app_lock_identity: Optional[str] = Noneself._text_batch_state = FeishuBatchState()self._pending_text_batches = self._text_batch_state.events@@ -1343,7 +1343,7 @@ class FeishuAdapter(BasePlatformAdapter):self._update_prompt_state: dict[int, dict[str, str]] = {}self._update_prompt_counter = itertools.count(1)# Reaction deletion needs the opaque reaction_id from create, cached per message_id.- self._pending_processing_reactions: "OrderedDict[str, str]" = OrderedDict()+ self._pending_processing_reactions: OrderedDict[str, str] = OrderedDict()self._load_seen_message_ids()@staticmethoddiff --git a/plugins/platforms/ntfy/adapter.py b/plugins/platforms/ntfy/adapter.pyindex 01937b8343a..c5747db9c54 100644--- a/plugins/platforms/ntfy/adapter.py+++ b/plugins/platforms/ntfy/adapter.py@@ -127,7 +127,7 @@ class NtfyAdapter(BasePlatformAdapter):self._publish_topic: str = _extra_or_secret(extra, "publish_topic", "NTFY_PUBLISH_TOPIC") or self._topicself._token: str = _extra_or_secret(extra, "token", "NTFY_TOKEN")self._stream_task: Optional[asyncio.Task] = None- self._http_client: Optional["httpx.AsyncClient"] = None+ self._http_client: Optional[httpx.AsyncClient] = Noneself._dedup = MessageDeduplicator(max_size=DEDUP_MAX_SIZE, ttl_seconds=DEDUP_WINDOW_SECONDS)# -- Connection lifecycle -----------------------------------------------diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex 25546d3d685..c55cc12848c 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -592,7 +592,7 @@ class PhotonAdapter(BasePlatformAdapter):# markdown path renders a fence as inline Unicode monospace, not a block.self.supports_code_blocks = Falseself._sidecar_proc: Optional[subprocess.Popen] = None- self._http_client: Optional["httpx.AsyncClient"] = None+ self._http_client: Optional[httpx.AsyncClient] = Noneself._respawn_lock: Optional[asyncio.Lock] = Noneself._sidecar_supervisor_task = self._inbound_task = self._sidecar_health_task = Noneself._watchdog_task: Optional[asyncio.Task] = None@@ -618,7 +618,7 @@ class PhotonAdapter(BasePlatformAdapter):# -- Group-mention gating (parity with BlueBubbles) ----------------------------@staticmethod- def _compile_mention_patterns(raw: Any) -> "list[re.Pattern]":+ def _compile_mention_patterns(raw: Any) -> list[re.Pattern]:"""``raw``: list, string (JSON list or comma/newline-separated) or None (defaults)."""return compile_mention_patterns(raw, log_prefix="photon", defaults=_DEFAULT_MENTION_PATTERNS, logger_=logger)diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.pyindex 7162694a447..b2fca6840ca 100644--- a/plugins/platforms/photon/auth.py+++ b/plugins/platforms/photon/auth.py@@ -456,7 +456,7 @@ def _validated_dashboard_token(candidates: list) -> str:def login_device_flow(*, client_id: str = DEFAULT_CLIENT_ID, open_browser: bool = True,- on_user_code: Optional[Callable[["DeviceCode"], None]] = None) -> str:+ on_user_code: Optional[Callable[[DeviceCode], None]] = None) -> str:"""Run the full device-code login flow, validate the token against the dashboard APIbefore persisting it, and return it. ``on_user_code`` receives the :class:`DeviceCode`."""code = request_device_code(client_id=client_id)diff --git a/plugins/platforms/raft/adapter.py b/plugins/platforms/raft/adapter.pyindex 29ac8c66e88..415eac8606f 100644--- a/plugins/platforms/raft/adapter.py+++ b/plugins/platforms/raft/adapter.py@@ -65,7 +65,7 @@ _MAX_SCALAR_LENGTH = 120_ACTIVITY_ALLOWED_FIELDS = set("schema eventId sessionId hookEventName status occurredAt toolName toolInput toolOutput ""toolInputTruncated toolOutputTruncated truncated errorClass durationMs".split())-_ACTIVE_ADAPTERS: "weakref.WeakSet[RaftAdapter]" = weakref.WeakSet()+_ACTIVE_ADAPTERS: weakref.WeakSet[RaftAdapter] = weakref.WeakSet()_ACTIVE_ADAPTERS_LOCK = threading.Lock()_RAFT_CONTEXT_LOCK = threading.Lock()_RAFT_SESSION_IDS: set[str] = set()@@ -299,7 +299,7 @@ def _on_session_finalize(**kwargs: Any) -> None:_forget_raft_context(kwargs.get("session_id"), kwargs.get("turn_id"), forget_session=True)-def _error_response(error: str, status: int) -> "web.Response":+def _error_response(error: str, status: int) -> web.Response:return web.json_response({"ok": False, "error": error}, status=status)@@ -408,17 +408,17 @@ class RaftAdapter(BasePlatformAdapter):async def get_chat_info(self, chat_id: str) -> dict[str, Any]:return {"name": f"raft/{chat_id}", "type": "raft"}- async def _handle_health(self, request: "web.Request") -> "web.Response":+ async def _handle_health(self, request: web.Request) -> web.Response:activity = {"queueSize": self._activity_queue.size, "endpoint": "/activity", "drainEndpoint": "/activity/drain"}return web.json_response({"status": "ok", "platform": "raft", "runtimeSession": self._runtime_session, "activity": activity})- def _authorized(self, request: "web.Request") -> bool:+ def _authorized(self, request: web.Request) -> bool:token = request.headers.get(BRIDGE_TOKEN_HEADER, "")# Compare as bytes: compare_digest raises TypeError on a non-ASCII str header.return bool(self._bridge_token and token) and hmac.compare_digest(token.encode(), self._bridge_token.encode())- async def _read_bridge_body(self, request: "web.Request", *, text: bool) -> tuple[Any, Optional["web.Response"]]:+ async def _read_bridge_body(self, request: web.Request, *, text: bool) -> tuple[Any, Optional[web.Response]]:"""Auth + size-capped body read for wake/activity -> ``(body, None)`` or ``(None, error)``.``text=True``: ``request.text()``, utf-8 length check, exception text in the 400 body; else raw bytes."""if not self._authorized(request):@@ -437,7 +437,7 @@ class RaftAdapter(BasePlatformAdapter):return None, _error_response("payload_too_large", 413)return body, None- async def _handle_wake(self, request: "web.Request") -> "web.Response":+ async def _handle_wake(self, request: web.Request) -> web.Response:raw_body, error = await self._read_bridge_body(request, text=False)if error is not None:return error@@ -468,7 +468,7 @@ class RaftAdapter(BasePlatformAdapter):return web.json_response(not_ready, status=503)return web.json_response({"ok": True, "runtimeSession": self._runtime_session}, status=202)- async def _handle_activity(self, request: "web.Request") -> "web.Response":+ async def _handle_activity(self, request: web.Request) -> web.Response:raw_text, error = await self._read_bridge_body(request, text=True)if error is not None:return error@@ -480,7 +480,7 @@ class RaftAdapter(BasePlatformAdapter):return _error_response(str(exc), 400)return web.json_response({"ok": True}, status=202)- async def _handle_activity_drain(self, request: "web.Request") -> "web.Response":+ async def _handle_activity_drain(self, request: web.Request) -> web.Response:if not self._authorized(request):return _error_response("unauthorized", 401)max_events = coerce_port(request.query.get("max", "200"), 200) # int-or-defaultdiff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 447447425a8..5fd44180e85 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -1484,7 +1484,7 @@ class SlackAdapter(BasePlatformAdapter):formatted = self.format_message(content)return self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH) or [formatted]- async def _send_slash_ephemeral(self, ctx: dict[str, Any], content: str) -> "SendResult":+ async def _send_slash_ephemeral(self, ctx: dict[str, Any], content: str) -> SendResult:"""Replace the ephemeral ack via ``response_url`` (``replace_original`` valid 30 min). Firstchunk replaces the ack, the rest post as new ephemerals; Slack caps a response_url at 5POSTs so overflow gets a truncation notice. ``success=False`` lets ``send()`` fall back.@@ -1525,7 +1525,7 @@ class SlackAdapter(BasePlatformAdapter):return SendResult(success=False, error=str(e))async def _post_ephemeral_fallback(- self, chat_id: str, ctx: dict[str, Any], content: str) -> "SendResult":+ self, chat_id: str, ctx: dict[str, Any], content: str) -> SendResult:"""Deliver a slash reply via ``chat.postEphemeral`` when ``response_url`` fails.Keeps the reply private (a public channel post must never happen for an ephemeral reply).Cannot ``replace_original``, so the ack stays; no 5-POST cap applies here.@@ -2127,7 +2127,7 @@ class SlackAdapter(BasePlatformAdapter):@staticmethodasync def _start_native_task_card_stream(- client, stream: "_NativeTaskCardStream", metadata: Optional[dict[str, Any]]+ client, stream: _NativeTaskCardStream, metadata: Optional[dict[str, Any]]) -> None:"""chat.startStream a plan-mode card in ``stream``'s thread; sets ``stream.stream_ts``."""start_payload: dict[str, Any] = {@@ -6445,7 +6445,7 @@ class SlackAdapter(BasePlatformAdapter):_slack_ignored_channels = _extra_or_env_channel_set_getter("ignored_channels", "SLACK_IGNORED_CHANNELS", coerce_scalar=True)- def _slack_mention_patterns(self) -> list["re.Pattern"]:+ def _slack_mention_patterns(self) -> list[re.Pattern]:"""Compile (cached) wake-word regexes from ``slack.mention_patterns`` (list/str) or``SLACK_MENTION_PATTERNS`` (JSON list or newline/comma-separated)."""cached = getattr(self, "_compiled_mention_patterns", None)@@ -6462,7 +6462,7 @@ class SlackAdapter(BasePlatformAdapter):patterns = [p.strip() for p in raw.replace("\n", ",").split(",") if p.strip()]if isinstance(patterns, str):patterns = [patterns]- compiled: list["re.Pattern"] = []+ compiled: list[re.Pattern] = []if isinstance(patterns, list):for pat in patterns:if not isinstance(pat, str) or not pat.strip():diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.pyindex 458b26c4a43..5aad56ecc54 100644--- a/plugins/platforms/teams/adapter.py+++ b/plugins/platforms/teams/adapter.py@@ -119,12 +119,12 @@ class _AiohttpBridgeAdapter:"""HttpServerAdapter bridging SDK route registrations into our aiohttp app; without it``App()`` unconditionally imports fastapi/uvicorn and allocates a ``FastAPI()``."""- def __init__(self, aiohttp_app: "web.Application"):+ def __init__(self, aiohttp_app: web.Application):self._aiohttp_app = aiohttp_app- def register_route(self, method: "HttpMethod", path: str, handler: "HttpRouteHandler") -> None:- async def _aiohttp_handler(request: "web.Request") -> "web.Response":- result: "HttpResponse" = await handler(HttpRequest(body=await request.json(), headers=dict(request.headers)))+ def register_route(self, method: HttpMethod, path: str, handler: HttpRouteHandler) -> None:+ async def _aiohttp_handler(request: web.Request) -> web.Response:+ result: HttpResponse = await handler(HttpRequest(body=await request.json(), headers=dict(request.headers)))status = result.get("status", 200)resp_body = result.get("body")if resp_body is not None:@@ -366,8 +366,8 @@ class TeamsAdapter(BasePlatformAdapter):self._port = coerce_port(self._extra.get("port") or _get_scoped_secret("TEAMS_PORT", str(_DEFAULT_PORT)), _DEFAULT_PORT)_raw_host = self._extra.get("host") or _get_scoped_secret("TEAMS_HOST", "") or _DEFAULT_HOST # falsy → dual-stack Noneself._host: Optional[str] = str(_raw_host) if _raw_host else None- self._app: Optional["App"] = None- self._runner: Optional["web.AppRunner"] = None+ self._app: Optional[App] = None+ self._runner: Optional[web.AppRunner] = Noneself._dedup = MessageDeduplicator(max_size=1000)# chat_id → ConversationReference so proactive cards use the right conversation type.self._conv_refs: dict[str, Any] = {}@@ -600,7 +600,7 @@ class TeamsAdapter(BasePlatformAdapter):logger.warning("[teams] Failed to cache attachment '%s' (%s): %s", att_name or content_url, content_type, e)return None- async def _send_card(self, chat_id: str, card: "AdaptiveCard") -> "Any":+ async def _send_card(self, chat_id: str, card: AdaptiveCard) -> Any:"""Send an AdaptiveCard, using a stored ConversationReference when available."""from microsoft_teams.api import MessageActivityInputif not self._app:@@ -624,17 +624,17 @@ class TeamsAdapter(BasePlatformAdapter):self._sent_ids.append(sent_id)@staticmethod- def _invoke_message(text: str) -> "InvokeResponse[AdaptiveCardActionMessageResponse]":+ def _invoke_message(text: str) -> InvokeResponse[AdaptiveCardActionMessageResponse]:return InvokeResponse(status=200, body=AdaptiveCardActionMessageResponse(value=text))@staticmethod- def _invoke_card(body: list) -> "InvokeResponse[AdaptiveCardActionMessageResponse]":+ def _invoke_card(body: list) -> InvokeResponse[AdaptiveCardActionMessageResponse]:card = AdaptiveCard().with_version("1.4").with_body(body)return InvokeResponse(status=200, body=AdaptiveCardActionCardResponse(value=card))async def _on_card_action(- self, ctx: "ActivityContext[AdaptiveCardInvokeActivity]"- ) -> "InvokeResponse[AdaptiveCardActionMessageResponse]":+ self, ctx: ActivityContext[AdaptiveCardInvokeActivity]+ ) -> InvokeResponse[AdaptiveCardActionMessageResponse]:from tools.approval import resolve_gateway_approval, has_blocking_approvaldata = ctx.activity.value.action.data or {}diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex bdcea5d45f1..9a7e9129a2e 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -74,7 +74,7 @@ async def _await_with_thread_deadline(return result.value-def _iter_exception_graph(error: BaseException) -> "Iterator[BaseException]":+def _iter_exception_graph(error: BaseException) -> Iterator[BaseException]:"""Yield ``error`` and every ``__cause__``/``__context__`` ancestor (DFS, cycle-safe) —PTB wraps httpx errors, so classifiers must inspect the whole graph."""seen: set[int] = set()@@ -203,7 +203,7 @@ _FLOOD_INLINE_WAIT_CAP_SECS = 5.0_TELEGRAM_CHAT_OUTBOUND_BUDGET_SECS = 1.0-def _flood_cap_result(wait: float) -> "SendResult":+def _flood_cap_result(wait: float) -> SendResult:"""The shared fail-closed SendResult for an over-cap flood wait."""return SendResult(success=False, error=f"flood_control:{wait}", retry_after=float(wait))@@ -751,7 +751,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):return Falsereturn not bool(getattr(self, "_fatal_error_retryable", True))- def _replacement_telegram_adapter(self) -> Optional["TelegramAdapter"]:+ def _replacement_telegram_adapter(self) -> Optional[TelegramAdapter]:"""Live adapter if the reconnect watcher replaced us in ``runner.adapters`` (an in-flight``send()`` still holds the old instance whose ``_bot`` stays None)."""runner = getattr(self, "gateway_runner", None)@@ -4371,7 +4371,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):_MODEL_PAGE_SIZE = 8@staticmethod- def _provider_button(p: dict) -> "InlineKeyboardButton":+ def _provider_button(p: dict) -> InlineKeyboardButton:count = p.get("total_models", len(p.get("models", [])))label = f"{p['name']} ({count})"if p.get("is_current"):@@ -4615,7 +4615,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):with contextlib.suppress(Exception):await query.edit_message_text(text=self.format_message(text_md), parse_mode=ParseMode.MARKDOWN_V2, reply_markup=None)- async def _handle_inline_query(self, update: "Update", context: "ContextTypes.DEFAULT_TYPE") -> None:+ async def _handle_inline_query(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:"""Answer ``@botname <query>`` with a searchable command/skill picker (the ``/`` menu is capped at60 slots). Results are computed per keystroke, 50 per page; tapping sends ``/cmd`` text as theuser, so dispatch flows through the normal command path. Inline queries arrive from ANY chat, so@@ -4680,7 +4680,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):await query.answer(text=denial_text)return False- async def _handle_callback_query(self, update: "Update", context: "ContextTypes.DEFAULT_TYPE") -> None:+ async def _handle_callback_query(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:"""Dispatch inline keyboard button clicks on the callback_data prefix."""query = update.callback_queryif not query or not query.data:@@ -6851,7 +6851,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):await self._flush_buffered(self._media_group_events, self._media_group_tasks, media_group_id, self.MEDIA_GROUP_WAIT_SECONDS, "media-group")- async def _handle_sticker(self, msg: Message, event: "MessageEvent") -> None:+ async def _handle_sticker(self, msg: Message, event: MessageEvent) -> None:"""Describe a sticker via vision, cached by file_unique_id; animated/video stickers get an emoji placeholder."""from gateway.sticker_cache import (get_cached_description, cache_sticker_description_async, build_sticker_injection,diff --git a/plugins/platforms/telegram/telegram_context.py b/plugins/platforms/telegram/telegram_context.pyindex b02f9ca3134..44d45aae8a7 100644--- a/plugins/platforms/telegram/telegram_context.py+++ b/plugins/platforms/telegram/telegram_context.py@@ -11,7 +11,7 @@ if TYPE_CHECKING:from plugins.platforms.telegram.adapter import TelegramAdapter-def mentions_other_participants(adapter: "TelegramAdapter", message: "Message") -> bool:+def mentions_other_participants(adapter: TelegramAdapter, message: Message) -> bool:"""True when a ``mention``/``text_mention`` entity names someone other than this bot."""own = adapter._current_bot_username()bot_id = getattr(adapter._bot, "id", None) if adapter._bot else None@@ -29,7 +29,7 @@ def mentions_other_participants(adapter: "TelegramAdapter", message: "Message")return False-def group_trigger_text(adapter: "TelegramAdapter", message: "Message", text: Optional[str]) -> Optional[str]:+def group_trigger_text(adapter: TelegramAdapter, message: Message, text: Optional[str]) -> Optional[str]:"""Strip our own handle only when we are the sole addressee. With other participants named,``@research_bot , @ops_bot are you both listening?`` must not reach us as ``, @ops_bot …``."""if adapter._is_group_chat(message) and mentions_other_participants(adapter, message):@@ -38,7 +38,7 @@ def group_trigger_text(adapter: "TelegramAdapter", message: "Message", text: Optdef group_identity_prompt(- adapter: "TelegramAdapter", message: "Message", channel_prompt: Optional[str],+ adapter: TelegramAdapter, message: Message, channel_prompt: Optional[str],) -> Optional[str]:"""Session-stable identity line so the model can read retained @mentions as itself or not."""if not adapter._is_group_chat(message) or not getattr(adapter, "_bot", None):diff --git a/plugins/platforms/telegram/telegram_held_inbound.py b/plugins/platforms/telegram/telegram_held_inbound.pyindex e9819bc3173..1d5a7105801 100644--- a/plugins/platforms/telegram/telegram_held_inbound.py+++ b/plugins/platforms/telegram/telegram_held_inbound.py@@ -72,7 +72,7 @@ class TelegramHeldInboundMixin:if schedule and not self._should_drop_delayed_delivery():self._schedule_held_inbound_redispatch()- def adopt_held_inbound(self, predecessor: "TelegramHeldInboundMixin") -> None:+ def adopt_held_inbound(self, predecessor: TelegramHeldInboundMixin) -> None:"""Take over the hold queue of the instance the runner just replaced with us (#132829): it onlydrains on its own ``_mark_connected``, which never comes; later holds there forward here."""self._held_inbound_successor = None # we own the queue again: a reverse link would forward in a cyclediff --git a/plugins/teams_pipeline/models.py b/plugins/teams_pipeline/models.pyindex 0ce903d4e21..bfbd787e835 100644--- a/plugins/teams_pipeline/models.py+++ b/plugins/teams_pipeline/models.py@@ -180,7 +180,7 @@ class TeamsMeetingSummaryPayload(_Model):_DATETIMES = ("start_time", "end_time")@classmethod- def from_dict(cls, payload: dict[str, Any]) -> "TeamsMeetingSummaryPayload":+ def from_dict(cls, payload: dict[str, Any]) -> TeamsMeetingSummaryPayload:# meeting_ref is mandatory: a missing key raises KeyError rather than building a half-empty payload.return super().from_dict({**payload, "meeting_ref": payload["meeting_ref"]})diff --git a/plugins/teams_pipeline/pipeline.py b/plugins/teams_pipeline/pipeline.pyindex b7d2eac0bee..e18d89b56e2 100644--- a/plugins/teams_pipeline/pipeline.py+++ b/plugins/teams_pipeline/pipeline.py@@ -67,7 +67,7 @@ class TeamsPipelineConfig:teams_delivery: dict[str, Any] | None = None@classmethod- def from_dict(cls, payload: Optional[dict[str, Any]]) -> "TeamsPipelineConfig":+ def from_dict(cls, payload: Optional[dict[str, Any]]) -> TeamsPipelineConfig:data = dict(payload or {})tmp_dir = data.get("tmp_dir") or data.get("tmpDir")flags = {"transcript_preferred": True, "transcript_required": False, "transcription_fallback": True, "ffmpeg_extract_audio": True}diff --git a/pm/downloader.py b/pm/downloader.pyindex 82e2788263c..5c5c51a904d 100644--- a/pm/downloader.py+++ b/pm/downloader.py@@ -217,7 +217,7 @@ def replace_when_released(tmp: Path, dest: Path, *, timeout: float = _RELEASE_WAdelay = min(delay * 2, 2.0)-def _existing_dest_ok(source: "Source") -> bool:+def _existing_dest_ok(source: Source) -> bool:"""Pinned destinations are rehashed; unpinned model files are accepted as-is.Catalog policy does not supply their expected hash or stable length.diff --git a/pm/package.py b/pm/package.pyindex da459d963f6..5b4dbed2c6d 100644--- a/pm/package.py+++ b/pm/package.py@@ -140,7 +140,7 @@ class Package:extract(archive, staged)- def stage(self, store: "Store", staged: Path, version: str, target: str) -> None:+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:"""Post-unpack fixups inside the scratch dir. Default: nothing."""def binary(self, entry: Path, target: str) -> Optional[Path]:@@ -363,7 +363,7 @@ def _missing_reason(binary: Path, entry: Path) -> str:return f"{rel} missing under {native(entry)}; {_entry_listing(entry)}"-def _probe_reason(binary: Path, proc: "subprocess.CompletedProcess") -> str:+def _probe_reason(binary: Path, proc: subprocess.CompletedProcess) -> str:"""Why a --version probe failed: the exit code plus output tail."""out = (proc.stdout or b"") + (proc.stderr or b"")tail = out.decode(errors="replace").strip()[-300:]diff --git a/providers/__init__.py b/providers/__init__.pyindex 694086e8e58..8fe3f466c85 100644--- a/providers/__init__.py+++ b/providers/__init__.py@@ -168,7 +168,7 @@ _NAMED_CUSTOM_MEMO_SIG: dict[str, Any] = {}_NAMED_CUSTOM_MEMO_NO_SIG = object()-def _has_named_custom_provider(name: str, home: "Path | None", hkey: str) -> bool:+def _has_named_custom_provider(name: str, home: Path | None, hkey: str) -> bool:"""``has_named_custom_provider`` memoized on the home's config file signature."""from utils import file_signaturediff --git a/registration_lifecycle.py b/registration_lifecycle.pyindex 6724cc2fe9f..24811cdcb0b 100644--- a/registration_lifecycle.py+++ b/registration_lifecycle.py@@ -24,13 +24,13 @@ def same_registration(left: Any, right: Any) -> bool:class ReplacementLease:"""One ownership generation in a replaceable registry slot."""- coordinator: "ReplacementCoordinator"+ coordinator: ReplacementCoordinatorslot: Hashablecurrent: Anyprevious: Anyrestore: Callable[[Any], bool]finalize: Callable[[], None] | None = None- predecessor: "ReplacementLease | None" = None+ predecessor: ReplacementLease | None = Noneactive: bool = field(default=True, init=False)def dispose(self) -> None:diff --git a/ruff.strict.toml b/ruff.strict.tomlindex 7cdb36ab7d6..070c9c4661d 100644--- a/ruff.strict.toml+++ b/ruff.strict.toml@@ -384,7 +384,7 @@ select = ["UP034",# "UP035","UP036",- # "UP037",+ "UP037","UP039","UP040","UP041",diff --git a/run_agent.py b/run_agent.pyindex 12e4ecc5398..e47a649f784 100644--- a/run_agent.py+++ b/run_agent.py@@ -54,7 +54,7 @@ def _launch_cwd_for_session(source: str) -> Optional[str]:return None-def _gateway_origin_json(agent: "AIAgent") -> Optional[str]:+def _gateway_origin_json(agent: AIAgent) -> Optional[str]:"""Gateway routing ``origin_json`` for a session row; None when the agent carries no gateway identity.Mirrors ``SessionSource.to_dict()`` so state.db consumers see the same fields ``record_gateway_session_peer`` writes.@@ -268,7 +268,7 @@ class AIAgent(skip_context_files: bool = False, load_soul_identity: bool = False,skip_memory: bool = False, skip_background_review: bool = False,session_db=None, parent_session_id: str | None = None,- iteration_budget: "IterationBudget" = None, run_budget_seconds: Optional[float] = None,+ iteration_budget: IterationBudget = None, run_budget_seconds: Optional[float] = None,fallback_model: dict[str, Any] | None = None, credential_pool=None,checkpoints_enabled: bool = False, checkpoint_max_snapshots: int = 20,checkpoint_max_total_size_mb: int = 500, checkpoint_max_file_size_mb: int = 10,@@ -1452,7 +1452,7 @@ def _parse_toolset_arg(raw: Optional[str], label: str) -> Optional[list[str]]:return names-def _save_sample_trajectory(agent: "AIAgent", result: dict, user_query: str, model: str) -> None:+def _save_sample_trajectory(agent: AIAgent, result: dict, user_query: str, model: str) -> None:"""``--save_sample``: write one trajectory (same format as batch_runner) to a UUID-named JSON file."""sample_filename = f"sample_{str(uuid.uuid4())[:8]}.json"entry = {diff --git a/scripts/check-windows-footguns.py b/scripts/check-windows-footguns.pyindex 6fd918ce364..90ee769e0b8 100644--- a/scripts/check-windows-footguns.py+++ b/scripts/check-windows-footguns.py@@ -137,7 +137,7 @@ class Footgun:# if the match is a REAL footgun (not a false positive). Use this when# the regex can't fully distinguish (e.g. open() where mode may contain# "b" for binary, or the line may have `encoding=` elsewhere).- post_filter: "Callable[..., Any] | None" = None+ post_filter: Callable[..., Any] | None = NoneFOOTGUNS: list[Footgun] = [@@ -646,7 +646,7 @@ def _call_closes_on_line(line: str, open_paren_end: int) -> bool:return False-def _looks_like_string_literal(line: str, match: "re.Match") -> bool:+def _looks_like_string_literal(line: str, match: re.Match) -> bool:"""Heuristic: is the ``text=True`` match inside a string literal?Catches the common case of docstrings/comments that mention ``text=True``diff --git a/scripts/iso-certify.py b/scripts/iso-certify.pyindex 01fa8de5a37..0b69dae4247 100755--- a/scripts/iso-certify.py+++ b/scripts/iso-certify.py@@ -163,7 +163,7 @@ class ScratchDashboard:self.actual_port = int(m.group(1))self._ready.set()- def __enter__(self) -> "ScratchDashboard":+ def __enter__(self) -> ScratchDashboard:venv_py = REPO_ROOT / "venv" / "bin" / "python"python = str(venv_py) if venv_py.exists() else sys.executableenv = dict(os.environ)diff --git a/scripts/releases/authors.py b/scripts/releases/authors.pyindex 09735a23f79..aa696f10458 100644--- a/scripts/releases/authors.py+++ b/scripts/releases/authors.py@@ -19,7 +19,7 @@ REPO_ROOT = Path(__file__).resolve().parents[2]CONTRIBUTORS_EMAILS_DIR = REPO_ROOT / "contributors" / "emails"-def _load_contributor_dir(directory: "Path | None" = None) -> dict:+def _load_contributor_dir(directory: Path | None = None) -> dict:"""Load one-file-per-email mappings from contributors/emails/.Filename = commit-author email, first non-comment line = GitHub login.diff --git a/scripts/run_tests_parallel.py b/scripts/run_tests_parallel.pyindex e4a88615b02..047ead06d36 100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.py@@ -402,7 +402,7 @@ def _discover_files(roots: list[Path]) -> list[Path]:return sorted(out)-def _kill_tree(proc: "subprocess.Popen", pgid: int | None = None) -> None:+def _kill_tree(proc: subprocess.Popen, pgid: int | None = None) -> None:"""Kill the pytest subprocess and every descendant it spawned.A test run can spin up uvicorn servers, async runtimes, or other@@ -1410,7 +1410,7 @@ def main() -> int:files_crashed = 0lock = threading.Lock()- def _on_done(file: Path, started_at: float, fut: "Future[tuple[Path, int, str, dict[str, int], float]]") -> None:+ def _on_done(file: Path, started_at: float, fut: Future[tuple[Path, int, str, dict[str, int], float]]) -> None:nonlocal files_done, tests_done, pass_count, fail_count, tests_passed, tests_failed, tests_skippednonlocal tests_collected, files_crashedn_tests = test_counts.get(file, 0)diff --git a/skills/research/grounded-citations/scripts/sources.py b/skills/research/grounded-citations/scripts/sources.pyindex fb7633abe71..e824ef56bb7 100644--- a/skills/research/grounded-citations/scripts/sources.py+++ b/skills/research/grounded-citations/scripts/sources.py@@ -118,7 +118,7 @@ class _LedgerLock:self.timeout = timeoutself.fd: int | None = None- def __enter__(self) -> "_LedgerLock":+ def __enter__(self) -> _LedgerLock:self.lock_path.parent.mkdir(parents=True, exist_ok=True)deadline = time.monotonic() + self.timeoutwhile True:diff --git a/tests/agent/test_codex_app_server_thread_resume.py b/tests/agent/test_codex_app_server_thread_resume.pyindex 17dd60015a9..9b4c1347453 100644--- a/tests/agent/test_codex_app_server_thread_resume.py+++ b/tests/agent/test_codex_app_server_thread_resume.py@@ -22,7 +22,7 @@ class _WireClient:id (or refuses ids in ``dead``), and records every JSON-RPC method it saw."""dead: set[str] = set()- instances: list["_WireClient"] = []+ instances: list[_WireClient] = []counter = 0def __init__(self, **kwargs):diff --git a/tests/conformance/persistence/_harness.py b/tests/conformance/persistence/_harness.pyindex 40236bc632d..ee1cd4f70d7 100644--- a/tests/conformance/persistence/_harness.py+++ b/tests/conformance/persistence/_harness.py@@ -59,7 +59,7 @@ def wait_for(*,deadline: float = CHILD_DEADLINE,what: str = "condition",- child: "subprocess.Popen | None" = None,+ child: subprocess.Popen | None = None,) -> None:"""Poll ``predicate`` until true or fail loudly at the deadline.diff --git a/tests/e2e/core/chaos/_tui_rpc.py b/tests/e2e/core/chaos/_tui_rpc.pyindex 2bed226040a..a291823bc0f 100644--- a/tests/e2e/core/chaos/_tui_rpc.py+++ b/tests/e2e/core/chaos/_tui_rpc.py@@ -198,7 +198,7 @@ class Heartbeat:self._inflight_since = Noneself._stop.wait(self.interval)- def __enter__(self) -> "Heartbeat":+ def __enter__(self) -> Heartbeat:self._inflight_since: float | None = Noneself._thread.start()return selfdiff --git a/tests/e2e/core/chaos/test_agent_turn_liveness.py b/tests/e2e/core/chaos/test_agent_turn_liveness.pyindex ef722e64c30..04f06897e8f 100644--- a/tests/e2e/core/chaos/test_agent_turn_liveness.py+++ b/tests/e2e/core/chaos/test_agent_turn_liveness.py@@ -141,7 +141,7 @@ class Scenario:call_bound: int = MAX_PROVIDER_CALLS_PER_FAILED_TURNexact_calls: int | None = None# Poll condition (run, ctx-free) that, once true, sends ``interrupt`` to the driver.- interrupt_when: Callable[["Run"], bool] | None = None+ interrupt_when: Callable[[Run], bool] | None = Nonetool_tokens: bool = False # parallel batch: each result must carry its own token# "answer": the PROBE gets the scripted reply; "breaker": the stale breaker refuses it# immediately with a surfaced error and no provider call.@@ -248,7 +248,7 @@ class Run:self.tag = new_tag()self.nonce = uuid.uuid4().hex[:10]self.session_id = f"chaos-{self.nonce}"- self.events: "queue.Queue[tuple[float, dict[str, Any]]]" = queue.Queue()+ self.events: queue.Queue[tuple[float, dict[str, Any]]] = queue.Queue()self.seen: list[tuple[float, dict[str, Any]]] = []self.srv = FakeLLMServer(self._respond)self.fault_msg = f"[[chaos:{sc.id}]] please help ({self.nonce})"diff --git a/tests/e2e/core/delivery/_cron_clock.py b/tests/e2e/core/delivery/_cron_clock.pyindex 73cb953f7b3..cd4a80e3870 100644--- a/tests/e2e/core/delivery/_cron_clock.py+++ b/tests/e2e/core/delivery/_cron_clock.py@@ -106,7 +106,7 @@ class Control:self.replica = self.root / "replica"self.claims = self.root / "claims.jsonl"- def ensure(self) -> "Control":+ def ensure(self) -> Control:for d in (self.root, self.gates, self.child, self.replica):d.mkdir(parents=True, exist_ok=True)if not self.behaviors.exists():diff --git a/tests/e2e/core/delivery/_fake_platform.py b/tests/e2e/core/delivery/_fake_platform.pyindex a00d6fc06fd..734d8131529 100644--- a/tests/e2e/core/delivery/_fake_platform.py+++ b/tests/e2e/core/delivery/_fake_platform.py@@ -218,7 +218,7 @@ def _adapter_class():splits_long_messages = True- def __init__(self, config, *, name: str, profile: str, world: "ChildWorld"):+ def __init__(self, config, *, name: str, profile: str, world: ChildWorld):super().__init__(config, Platform(name))self.pname = nameself.world = world@@ -529,7 +529,7 @@ class GatewayProcess:})return env- def start(self) -> "GatewayProcess":+ def start(self) -> GatewayProcess:assert self.proc is Noneself.boots += 1ready_before = len(read_jsonl(self.spool / "ready.jsonl"))diff --git a/tests/e2e/core/history/_helpers.py b/tests/e2e/core/history/_helpers.pyindex e0d0057c7ea..155a0c1f49a 100644--- a/tests/e2e/core/history/_helpers.py+++ b/tests/e2e/core/history/_helpers.py@@ -395,7 +395,7 @@ class TuiGateway:self._wlock = threading.Lock()self.stored: dict[str, str] = {}- def __enter__(self) -> "TuiGateway":+ def __enter__(self) -> TuiGateway:self.proc = self.spawned.add(subprocess.Popen([sys.executable, "-m", "tui_gateway.entry"], cwd=self.cwd, env={**self.env, "PWD": self.cwd},stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,diff --git a/tests/e2e/core/live/_helpers.py b/tests/e2e/core/live/_helpers.pyindex 1aeafc7829c..e884cabb6d4 100644--- a/tests/e2e/core/live/_helpers.py+++ b/tests/e2e/core/live/_helpers.py@@ -185,12 +185,12 @@ def install_wire_recorder(monkeypatch: pytest.MonkeyPatch, secret: str) -> WireLlog = WireLog(secret=secret)- def _carries(request: "httpx.Request") -> bool:+ def _carries(request: httpx.Request) -> bool:if secret in str(request.url):return Truereturn any(secret in v for v in request.headers.values())- def _body(request: "httpx.Request") -> Any:+ def _body(request: httpx.Request) -> Any:if request.method != "POST":return Nonetry:@@ -198,11 +198,11 @@ def install_wire_recorder(monkeypatch: pytest.MonkeyPatch, secret: str) -> WireLexcept Exception:return None- def _record(request: "httpx.Request", status: int, body: Any, error: str = "") -> None:+ def _record(request: httpx.Request, status: int, body: Any, error: str = "") -> None:log.records.append(WireRecord(request.method, request.url.host, request.url.path, status,_carries(request), body, error.replace(secret, "<redacted>")[:400]))- def _error_text(resp: "httpx.Response") -> str:+ def _error_text(resp: httpx.Response) -> str:# Error bodies are small and read eagerly by every SDK anyway; cache them on# the response so the caller still sees the same content.if resp.status_code < 400:diff --git a/tests/e2e/core/mcp_plugins/_helpers.py b/tests/e2e/core/mcp_plugins/_helpers.pyindex 84413fdb1b6..f168270ec93 100644--- a/tests/e2e/core/mcp_plugins/_helpers.py+++ b/tests/e2e/core/mcp_plugins/_helpers.py@@ -193,7 +193,7 @@ class HttpMcpServer:def url(self) -> str:return f"http://127.0.0.1:{self.port}/mcp"- def start(self) -> "HttpMcpServer":+ def start(self) -> HttpMcpServer:with contextlib.suppress(FileNotFoundError):self.port_file.unlink()env = {k: v for k, v in os.environ.items() if k in _PASSTHROUGH_ENV}diff --git a/tests/e2e/core/parity/_drive_gateway.py b/tests/e2e/core/parity/_drive_gateway.pyindex 7ae6991f5d8..3ef6e64b70d 100644--- a/tests/e2e/core/parity/_drive_gateway.py+++ b/tests/e2e/core/parity/_drive_gateway.py@@ -68,7 +68,7 @@ def _spawn(ph: ParityHome, argv: list[str], log_name: str, extra_env: dict[str,return proc-def _stdout_pump(proc: subprocess.Popen) -> "queue.Queue[str | None]":+def _stdout_pump(proc: subprocess.Popen) -> queue.Queue[str | None]:lines: queue.Queue[str | None] = queue.Queue()def pump() -> None:diff --git a/tests/e2e/core/parity/_drive_rpc.py b/tests/e2e/core/parity/_drive_rpc.pyindex 2dcc71c16d2..f9cd720ea3e 100644--- a/tests/e2e/core/parity/_drive_rpc.py+++ b/tests/e2e/core/parity/_drive_rpc.py@@ -40,7 +40,7 @@ READY_TIMEOUT = 120.0class RpcClient:"""Minimal JSON-RPC 2.0 client over a line/frame transport (``send`` + ``recv`` callables)."""- def __init__(self, send: Callable[[str], None], frames: "queue.Queue[str | None]") -> None:+ def __init__(self, send: Callable[[str], None], frames: queue.Queue[str | None]) -> None:self._send = sendself._frames = framesself._next_id = 0@@ -110,11 +110,11 @@ def run_turn(rpc: RpcClient, prompt: str, create_params: dict[str, Any]) -> str:class StreamCapture:"""Every stdout line (in order) plus the stderr text of a child, pumped on threads."""- stdout_lines: "queue.Queue[str | None]" = field(default_factory=queue.Queue)+ stdout_lines: queue.Queue[str | None] = field(default_factory=queue.Queue)stdout_seen: list[str] = field(default_factory=list)stderr_chunks: list[str] = field(default_factory=list)- def start(self, proc: subprocess.Popen) -> "StreamCapture":+ def start(self, proc: subprocess.Popen) -> StreamCapture:def out() -> None:assert proc.stdout is not Nonefor line in proc.stdout:diff --git a/tests/e2e/core/platforms/_helpers.py b/tests/e2e/core/platforms/_helpers.pyindex e5e8fb05a0a..a3a7c0784f9 100644--- a/tests/e2e/core/platforms/_helpers.py+++ b/tests/e2e/core/platforms/_helpers.py@@ -125,7 +125,7 @@ class GatewayUnderTest:def db_path(self) -> Path:return self.hermes_home / "state.db"- def start(self, timeout: float = 60.0) -> "GatewayUnderTest":+ def start(self, timeout: float = 60.0) -> GatewayUnderTest:assert self.proc is None or self.proc.poll() is not Nonelog = open(self.log_path, "a", encoding="utf-8")self.proc = subprocess.Popen(diff --git a/tests/e2e/core/providers/_openai_helpers.py b/tests/e2e/core/providers/_openai_helpers.pyindex c8f73dc483c..f928ea7291b 100644--- a/tests/e2e/core/providers/_openai_helpers.py+++ b/tests/e2e/core/providers/_openai_helpers.py@@ -137,7 +137,7 @@ class Home:return envdef write(self, config: dict[str, Any], dotenv: dict[str, str] | None = None,- auth: dict[str, Any] | None = None) -> "Home":+ auth: dict[str, Any] | None = None) -> Home:self.hermes_home.mkdir(parents=True, exist_ok=True)self.project.mkdir(parents=True, exist_ok=True)base = {"updates": {"check": False}, "agent": {"api_max_retries": 2},diff --git a/tests/e2e/core/providers/test_native_copilot_acp_streaming.py b/tests/e2e/core/providers/test_native_copilot_acp_streaming.pyindex a0dbd57ff12..5d595154f06 100644--- a/tests/e2e/core/providers/test_native_copilot_acp_streaming.py+++ b/tests/e2e/core/providers/test_native_copilot_acp_streaming.py@@ -73,7 +73,7 @@ class Observed:stderr: str = ""-def _pump(proc: subprocess.Popen, sink: "queue.Queue[tuple[float, dict[str, Any]] | None]") -> None:+def _pump(proc: subprocess.Popen, sink: queue.Queue[tuple[float, dict[str, Any]] | None]) -> None:for line in proc.stdout: # type: ignore[union-attr]try:sink.put((time.time(), json.loads(line)))diff --git a/tests/e2e/core/providers/test_openai_codex_pool.py b/tests/e2e/core/providers/test_openai_codex_pool.pyindex ec257e19086..a149010ed2c 100644--- a/tests/e2e/core/providers/test_openai_codex_pool.py+++ b/tests/e2e/core/providers/test_openai_codex_pool.py@@ -88,7 +88,7 @@ class FakeTokenServer:self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)- def __enter__(self) -> "FakeTokenServer":+ def __enter__(self) -> FakeTokenServer:self._thread.start()return selfdiff --git a/tests/e2e/core/providers/test_openai_pricing.py b/tests/e2e/core/providers/test_openai_pricing.pyindex abe0540b735..6561d7e13bb 100644--- a/tests/e2e/core/providers/test_openai_pricing.py+++ b/tests/e2e/core/providers/test_openai_pricing.py@@ -100,7 +100,7 @@ class FakeCatalog:self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)- def __enter__(self) -> "FakeCatalog":+ def __enter__(self) -> FakeCatalog:self._thread.start()return selfdiff --git a/tests/e2e/core/security/_redact.py b/tests/e2e/core/security/_redact.pyindex af4bac5f275..37227aaf020 100644--- a/tests/e2e/core/security/_redact.py+++ b/tests/e2e/core/security/_redact.py@@ -73,7 +73,7 @@ SINK_IDS = {LOGS: "logs", STORE: "store", EXPORT: "export", EXPORT_REDACTED: "exclass Scenario:name: strsecrets: Callable[[Secrets], list[str]]- script: Callable[["Ctx"], list[Response]]+ script: Callable[[Ctx], list[Response]]sinks: tuple[str, ...]prompt: str = "please run the task"followup: bool = False # a second user turn, so the NEXT request after the answer exists@@ -89,7 +89,7 @@ class Ctx:port: int = 0-def _tee(c: Ctx, name: str, src: "str | Path") -> str:+def _tee(c: Ctx, name: str, src: str | Path) -> str:return f"cat {src} | tee {c.ws / name}"@@ -292,7 +292,7 @@ class LoggingGateway(GatewayProcess):"""The delivery suite's real GatewayRunner child, with the gateway's file logging installed the way``start_gateway`` does (agent.log / errors.log / gateway.log under the child's HERMES_HOME)."""- def start(self) -> "LoggingGateway":+ def start(self) -> LoggingGateway:assert self.proc is Noneself.boots += 1ready_before = len(read_jsonl(self.spool / "ready.jsonl"))diff --git a/tests/e2e/core/tenancy/_routing_helpers.py b/tests/e2e/core/tenancy/_routing_helpers.pyindex cb100d99de5..16e41d43fed 100644--- a/tests/e2e/core/tenancy/_routing_helpers.py+++ b/tests/e2e/core/tenancy/_routing_helpers.py@@ -128,7 +128,7 @@ class Fleet:def url(self, role: str) -> str:return self.servers[role].base_url- def start(self) -> "Fleet":+ def start(self) -> Fleet:for srv in self.servers.values():srv.start()return selfdiff --git a/tests/e2e/core/terminal/_gateway_client.py b/tests/e2e/core/terminal/_gateway_client.pyindex a36289154e3..f10e495d7e0 100644--- a/tests/e2e/core/terminal/_gateway_client.py+++ b/tests/e2e/core/terminal/_gateway_client.py@@ -103,7 +103,7 @@ class Backend:self.port: int | None = Noneself.clients: list[WSClient] = []- def start(self, *, timeout: float = 90.0) -> "Backend":+ def start(self, *, timeout: float = 90.0) -> Backend:operator_root = (Path(_operator_home()) / ".hermes").resolve()assert operator_root not in (self.hermes_home.resolve(), *self.hermes_home.resolve().parents), (f"sandbox {self.hermes_home} sits inside the operator's Hermes home {operator_root}")@@ -136,7 +136,7 @@ class Backend:def ws_url(self) -> str:return f"ws://127.0.0.1:{self.port}/api/ws?token={self.token}"- def connect(self, name: str) -> "WSClient":+ def connect(self, name: str) -> WSClient:client = WSClient(self.ws_url, name)self.clients.append(client)return clientdiff --git a/tests/e2e/core/upgrade/handoff/_handoff.py b/tests/e2e/core/upgrade/handoff/_handoff.pyindex a64dbee8445..e8bc60dfcfc 100644--- a/tests/e2e/core/upgrade/handoff/_handoff.py+++ b/tests/e2e/core/upgrade/handoff/_handoff.py@@ -492,7 +492,7 @@ class FileWatch:last = curself._stop.wait(self.interval)- def __enter__(self) -> "FileWatch":+ def __enter__(self) -> FileWatch:self._thread = threading.Thread(target=self._run, daemon=True)self._thread.start()return selfdiff --git a/tests/e2e/core/upgrade/handoff/_scenario.py b/tests/e2e/core/upgrade/handoff/_scenario.pyindex e6c1e210cf0..79f02355d8f 100644--- a/tests/e2e/core/upgrade/handoff/_scenario.py+++ b/tests/e2e/core/upgrade/handoff/_scenario.py@@ -250,7 +250,7 @@ class WorkerSampler:passself._stop.wait(self.interval)- def __enter__(self) -> "WorkerSampler":+ def __enter__(self) -> WorkerSampler:self._thread = threading.Thread(target=self._run, daemon=True)self._thread.start()return selfdiff --git a/tests/e2e/core/upgrade/network/_seed.py b/tests/e2e/core/upgrade/network/_seed.pyindex 650d42bf4ab..da42335b525 100644--- a/tests/e2e/core/upgrade/network/_seed.py+++ b/tests/e2e/core/upgrade/network/_seed.py@@ -46,7 +46,7 @@ PUBLIC_INDEXES = ("pypi.org", "files.pythonhosted.org", "registry.npmjs.org")class Result:cp: subprocess.CompletedProcesssecs: float- edge: "Edge | None"+ edge: Edge | None@propertydef rc(self) -> int:@@ -56,7 +56,7 @@ class Result:def out(self) -> str:return (self.cp.stdout or "") + (self.cp.stderr or "")- def report(self, inst: "Installed", *extra: str) -> str:+ def report(self, inst: Installed, *extra: str) -> str:parts = [f"exit={self.rc} after {self.secs:.1f}s", I.describe(self.cp)]if self.edge is not None:parts.append("--- network edge log ---\n" + self.edge.transcript())@@ -70,7 +70,7 @@ class Result:class Edge:"""The namespace's only egress: a TLS-inspecting proxy plus optional plain-HTTP mirrors."""- inst: "Installed"+ inst: Installedproxy: N.EdgeProxysites: list[N.HttpSite] = field(default_factory=list)use_auth: bool = Falsediff --git a/tests/e2e/core/windows/_rpc.py b/tests/e2e/core/windows/_rpc.pyindex c8164092474..929e971fd2b 100644--- a/tests/e2e/core/windows/_rpc.py+++ b/tests/e2e/core/windows/_rpc.py@@ -24,7 +24,7 @@ class StdioGateway:[sys.executable, "-m", "tui_gateway.entry"], cwd=home.project, env=home.env(),stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)- self._frames: "queue.Queue[bytes | None]" = queue.Queue()+ self._frames: queue.Queue[bytes | None] = queue.Queue()self._stderr: list[bytes] = []self.events: list[dict[str, Any]] = []self._responses: dict[str, dict[str, Any]] = {}diff --git a/tests/e2e/core/windows/test_boot_lifecycle.py b/tests/e2e/core/windows/test_boot_lifecycle.pyindex 9f88acc0fec..20737df72b3 100644--- a/tests/e2e/core/windows/test_boot_lifecycle.py+++ b/tests/e2e/core/windows/test_boot_lifecycle.py@@ -103,7 +103,7 @@ def _serve_ready(home: WinHome) -> tuple[subprocess.Popen, int]:"""Spawn serve and wait for its READY port. A daemon pump keeps draining stdout afterREADY, as the Desktop does, so a full pipe can never stall the backend."""proc = _spawn_serve(home)- found: "queue.Queue[int | None]" = queue.Queue()+ found: queue.Queue[int | None] = queue.Queue()seen: list[str] = []def pump() -> None:diff --git a/tests/fakes/fake_llm_provider.py b/tests/fakes/fake_llm_provider.pyindex e2483f83508..be30380515e 100644--- a/tests/fakes/fake_llm_provider.py+++ b/tests/fakes/fake_llm_provider.py@@ -153,7 +153,7 @@ class FakeLLMServer:self._tool_seq = 0# lifecycle- def __enter__(self) -> "FakeLLMServer":+ def __enter__(self) -> FakeLLMServer:self.start()return selfdiff --git a/tests/fakes/platforms/_standin.py b/tests/fakes/platforms/_standin.pyindex 683bd6b79a2..85690227824 100644--- a/tests/fakes/platforms/_standin.py+++ b/tests/fakes/platforms/_standin.py@@ -97,7 +97,7 @@ class StandinServer:def build_app(self) -> web.Application: # pragma: no cover - abstractraise NotImplementedError- def start(self) -> "StandinServer":+ def start(self) -> StandinServer:self._thread = threading.Thread(target=self._serve, name=type(self).__name__, daemon=True)self._thread.start()if not self._ready.wait(30):@@ -139,7 +139,7 @@ class StandinServer:async def on_shutdown(self) -> None:"""Subclasses close long-lived sockets here."""- def __enter__(self) -> "StandinServer":+ def __enter__(self) -> StandinServer:return self.start()def __exit__(self, *_exc: object) -> None:diff --git a/tests/fakes/providers/anthropic_messages.py b/tests/fakes/providers/anthropic_messages.pyindex 44fbfcebfe1..d48fd7450db 100644--- a/tests/fakes/providers/anthropic_messages.py+++ b/tests/fakes/providers/anthropic_messages.py@@ -313,13 +313,13 @@ class AnthropicMessagesServer:self._httpd: ThreadingHTTPServer | None = Noneself._tool_seq = 0- def __enter__(self) -> "AnthropicMessagesServer":+ def __enter__(self) -> AnthropicMessagesServer:return self.start()def __exit__(self, *_exc: object) -> None:self.stop()- def start(self) -> "AnthropicMessagesServer":+ def start(self) -> AnthropicMessagesServer:self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))self._httpd.daemon_threads = Truethreading.Thread(target=self._httpd.serve_forever, kwargs={"poll_interval": 0.05},diff --git a/tests/fakes/providers/bedrock_converse.py b/tests/fakes/providers/bedrock_converse.pyindex 6ec066eba02..49277b4cc13 100644--- a/tests/fakes/providers/bedrock_converse.py+++ b/tests/fakes/providers/bedrock_converse.py@@ -302,7 +302,7 @@ class FakeBedrock:_ids: int = 0_httpd: ThreadingHTTPServer | None = None- def __enter__(self) -> "FakeBedrock":+ def __enter__(self) -> FakeBedrock:self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))self._httpd.daemon_threads = Truethreading.Thread(target=self._httpd.serve_forever, daemon=True).start()diff --git a/tests/fakes/providers/catalog_fake.py b/tests/fakes/providers/catalog_fake.pyindex ee9cef9c3e3..27654dbb4e7 100644--- a/tests/fakes/providers/catalog_fake.py+++ b/tests/fakes/providers/catalog_fake.py@@ -85,7 +85,7 @@ class CatalogFake:self._stop = threading.Event()self._server: ThreadingHTTPServer | None = None- def __enter__(self) -> "CatalogFake":+ def __enter__(self) -> CatalogFake:server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))server.daemon_threads = Trueself._server = serverdiff --git a/tests/fakes/providers/catalog_oauth.py b/tests/fakes/providers/catalog_oauth.pyindex 7d2d1b97dcd..9460a71cfc6 100644--- a/tests/fakes/providers/catalog_oauth.py+++ b/tests/fakes/providers/catalog_oauth.py@@ -73,7 +73,7 @@ class OAuthFake:self._lock = threading.Lock()self._server: ThreadingHTTPServer | None = None- def __enter__(self) -> "OAuthFake":+ def __enter__(self) -> OAuthFake:server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))server.daemon_threads = Trueself._server = serverdiff --git a/tests/fakes/providers/chat_variants.py b/tests/fakes/providers/chat_variants.pyindex 20a298f37e4..5ad070d4f3a 100644--- a/tests/fakes/providers/chat_variants.py+++ b/tests/fakes/providers/chat_variants.py@@ -137,7 +137,7 @@ class FakeChatVariantServer:self._seq = 0self._server: ThreadingHTTPServer | None = None- def __enter__(self) -> "FakeChatVariantServer":+ def __enter__(self) -> FakeChatVariantServer:self._server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))self._server.daemon_threads = Truethreading.Thread(target=self._server.serve_forever, name="fake-chat-variant", daemon=True).start()diff --git a/tests/fakes/providers/gemini_native.py b/tests/fakes/providers/gemini_native.pyindex c4e0f770f90..8026945817e 100644--- a/tests/fakes/providers/gemini_native.py+++ b/tests/fakes/providers/gemini_native.py@@ -459,7 +459,7 @@ class GeminiFake:self._thread = threading.Thread(target=self._server.serve_forever, name="gemini-fake", daemon=True)# lifecycle ---------------------------------------------------------------------------------- def __enter__(self) -> "GeminiFake":+ def __enter__(self) -> GeminiFake:self._thread.start()return selfdiff --git a/tests/fakes/providers/oauth_token_server.py b/tests/fakes/providers/oauth_token_server.pyindex dbd7b4623be..e32207d535e 100644--- a/tests/fakes/providers/oauth_token_server.py+++ b/tests/fakes/providers/oauth_token_server.py@@ -208,7 +208,7 @@ class OAuthTokenServer:# ---- lifecycle -------------------------------------------------------- def start(self) -> "OAuthTokenServer":+ def start(self) -> OAuthTokenServer:self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _make_handler(self))self._httpd.daemon_threads = Trueself._thread = threading.Thread(target=self._httpd.serve_forever, kwargs={"poll_interval": 0.05},@@ -234,7 +234,7 @@ class OAuthTokenServer:def handler_class(self) -> type[BaseHTTPRequestHandler]:return _make_handler(self)- def __enter__(self) -> "OAuthTokenServer":+ def __enter__(self) -> OAuthTokenServer:return self.start()def __exit__(self, *exc: object) -> None:@@ -362,7 +362,7 @@ class TLSInterceptProxy:assert self._sock is not None, "proxy not started"return f"http://127.0.0.1:{self._sock.getsockname()[1]}"- def start(self) -> "TLSInterceptProxy":+ def start(self) -> TLSInterceptProxy:self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self._sock.bind(("127.0.0.1", 0))self._sock.listen(64)@@ -416,7 +416,7 @@ class TLSInterceptProxy:except OSError:pass- def __enter__(self) -> "TLSInterceptProxy":+ def __enter__(self) -> TLSInterceptProxy:return self.start()def __exit__(self, *exc: object) -> None:diff --git a/tests/fakes/providers/openai_responses.py b/tests/fakes/providers/openai_responses.pyindex 06485b555a3..8472187c6b2 100644--- a/tests/fakes/providers/openai_responses.py+++ b/tests/fakes/providers/openai_responses.py@@ -299,7 +299,7 @@ class FakeResponsesServer:self._lock = threading.Lock()self._server: ThreadingHTTPServer | None = None- def __enter__(self) -> "FakeResponsesServer":+ def __enter__(self) -> FakeResponsesServer:server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))server.daemon_threads = Trueself._server = serverdiff --git a/tests/fakes/providers/vertex.py b/tests/fakes/providers/vertex.pyindex 839b50323ba..a9d9f76c309 100644--- a/tests/fakes/providers/vertex.py+++ b/tests/fakes/providers/vertex.py@@ -389,7 +389,7 @@ class FakeVertex:self._tls: ssl.SSLContext | None = None# lifecycle- def __enter__(self) -> "FakeVertex":+ def __enter__(self) -> FakeVertex:self.start()return selfdiff --git a/tests/gateway/test_discord_model_picker_partition.py b/tests/gateway/test_discord_model_picker_partition.pyindex 53b0a527386..8ffdb1b50e7 100644--- a/tests/gateway/test_discord_model_picker_partition.py+++ b/tests/gateway/test_discord_model_picker_partition.py@@ -15,7 +15,7 @@ from gateway.platforms.base import utf16_lenfrom plugins.platforms.discord.adapter import ModelPickerView-def _all_options(view: "ModelPickerView"):+def _all_options(view: ModelPickerView):"""Flatten every model select menu's options into (label, value).Detect selects by their ``model_model_select*`` custom_id (and presence ofdiff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.pyindex dea0e56fcaf..077bec67f00 100644--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@ -1137,7 +1137,7 @@ class TestAdapterBehavior(unittest.TestCase):def __init__(self, *_a: object, **_k: object) -> None:pass- async def __aenter__(self) -> "_FakeAsyncClient":+ async def __aenter__(self) -> _FakeAsyncClient:events.append("client_enter")return self@@ -1497,7 +1497,7 @@ class TestPendingInboundQueue(unittest.TestCase):class TestWebhookSecurity(unittest.TestCase):"""Tests for webhook signature verification, rate limiting, and body size limits."""- def _make_adapter(self, encrypt_key: str = "") -> "FeishuAdapter":+ def _make_adapter(self, encrypt_key: str = "") -> FeishuAdapter:from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapterdiff --git a/tests/gateway/test_profile_resolution.py b/tests/gateway/test_profile_resolution.pyindex 51b2c436fab..68af85012c1 100644--- a/tests/gateway/test_profile_resolution.py+++ b/tests/gateway/test_profile_resolution.py@@ -301,7 +301,7 @@ class _StubAdapter(BasePlatformAdapter):_StubAdapter.__abstractmethods__ = frozenset() # type: ignore[attr-defined]-def _stub_adapter(platform: Platform, runner) -> "_StubAdapter":+def _stub_adapter(platform: Platform, runner) -> _StubAdapter:a = _StubAdapter.__new__(_StubAdapter)a.platform = platforma.gateway_runner = runnerdiff --git a/tests/gateway/test_systemd_watchdog_lifecycle.py b/tests/gateway/test_systemd_watchdog_lifecycle.pyindex 13ef36ed8a2..7fd8fc6ea25 100644--- a/tests/gateway/test_systemd_watchdog_lifecycle.py+++ b/tests/gateway/test_systemd_watchdog_lifecycle.py@@ -9,7 +9,7 @@ from gateway.run import GatewayRunnerclass _FakeWatchdog:- instances: list["_FakeWatchdog"] = []+ instances: list[_FakeWatchdog] = []def __init__(self, *, config_enabled: bool = True):self.config_enabled = config_enableddiff --git a/tests/hermes_cli/test_deferred_platform_client_tools.py b/tests/hermes_cli/test_deferred_platform_client_tools.pyindex 7cc257ecfd7..026e4f2b5e4 100644--- a/tests/hermes_cli/test_deferred_platform_client_tools.py+++ b/tests/hermes_cli/test_deferred_platform_client_tools.py@@ -42,8 +42,8 @@ def _write_platform_plugin(platform: str,*,with_tools_module: bool,- declares_provides_tools: "bool | None" = None,-) -> "object":+ declares_provides_tools: bool | None = None,+) -> object:"""Create a bundled-style platform plugin and return its manifest.The adapter import is the expensive thing we must NOT trigger: it isdiff --git a/tests/hermes_cli/test_global_auth_store_memo.py b/tests/hermes_cli/test_global_auth_store_memo.pyindex ffe33ff1e27..288213ad667 100644--- a/tests/hermes_cli/test_global_auth_store_memo.py+++ b/tests/hermes_cli/test_global_auth_store_memo.py@@ -33,7 +33,7 @@ def _reset_cache(monkeypatch):)-def _make_global_store(tmp_path) -> "os.PathLike[str]":+def _make_global_store(tmp_path) -> os.PathLike[str]:"""Write a realistic global auth.json and return its path."""path = tmp_path / "global-hermes" / "auth.json"path.parent.mkdir(parents=True)diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.pyindex bad70da88c3..5480c3d7b10 100644--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@ -859,7 +859,7 @@ def test_install_is_a_noop_on_windows(tmp_path):# ----------------------------------------------------------------------------def _stub_tools(monkeypatch, available: "set[str]") -> "list[list[str]]":+def _stub_tools(monkeypatch, available: set[str]) -> list[list[str]]:ran: list[list[str]] = []monkeypatch.setattr(lde.shutil,diff --git a/tests/hermes_cli/test_proxy.py b/tests/hermes_cli/test_proxy.pyindex 6e9bce2bdd4..dbd4285d23c 100644--- a/tests/hermes_cli/test_proxy.py+++ b/tests/hermes_cli/test_proxy.py@@ -295,7 +295,7 @@ class FakeAdapter(UpstreamAdapter):)-async def _start_runner(app: "web.Application"):+async def _start_runner(app: web.Application):"""Spin up an aiohttp app on an ephemeral localhost port. Returns (runner, base_url)."""runner = web.AppRunner(app, access_log=None)await runner.setup()@@ -306,7 +306,7 @@ async def _start_runner(app: "web.Application"):return runner, f"http://127.0.0.1:{port}"-def _build_fake_upstream(captured: dict[str, Any]) -> "web.Application":+def _build_fake_upstream(captured: dict[str, Any]) -> web.Application:async def echo(request):body = await request.read()captured["requests"].append({@@ -334,7 +334,7 @@ def _build_fake_upstream(captured: dict[str, Any]) -> "web.Application":return app-def _build_retrying_fake_upstream(captured: dict[str, Any]) -> "web.Application":+def _build_retrying_fake_upstream(captured: dict[str, Any]) -> web.Application:async def maybe_unauthorized(request):body = await request.read()auth = request.headers.get("Authorization")@@ -433,7 +433,7 @@ def _build_sse_upstream(frames: list[bytes],*,path: str = "/v1/chat/completions",-) -> "web.Application":+) -> web.Application:async def sse(request):_ = await request.read()resp = web.StreamResponse(diff --git a/tests/hermes_cli/test_proxy_off_loop.py b/tests/hermes_cli/test_proxy_off_loop.pyindex 7fe9edd80f1..03ee4422f90 100644--- a/tests/hermes_cli/test_proxy_off_loop.py+++ b/tests/hermes_cli/test_proxy_off_loop.py@@ -149,7 +149,7 @@ class _RecordingAdapter(UpstreamAdapter):)-async def _start_runner(app: "web.Application"):+async def _start_runner(app: web.Application):"""Spin up an aiohttp app on an ephemeral localhost port. Returns (runner, base_url)."""runner = web.AppRunner(app, access_log=None)await runner.setup()@@ -160,7 +160,7 @@ async def _start_runner(app: "web.Application"):return runner, f"http://127.0.0.1:{port}"-def _build_fake_upstream(captured: dict[str, Any]) -> "web.Application":+def _build_fake_upstream(captured: dict[str, Any]) -> web.Application:async def echo(request):body = await request.read()captured["requests"].append(@@ -175,7 +175,7 @@ def _build_fake_upstream(captured: dict[str, Any]) -> "web.Application":def _build_rejecting_upstream(captured: dict[str, Any], *, reject_status: int, accept_bearer: str-) -> "web.Application":+) -> web.Application:"""Upstream that rejects every bearer except ``accept_bearer``.Drives ``handle_proxy``'s ``status in {401, 429}`` branch: the first forwarddiff --git a/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.pyindex 02c3341d6ac..3ae9114c6bc 100644--- a/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py+++ b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py@@ -244,7 +244,7 @@ class TestEmittedCommandsSatisfyCliContract:"""@staticmethod- def _namespace(source: Path, **overrides) -> "argparse.Namespace":+ def _namespace(source: Path, **overrides) -> argparse.Namespace:"""The namespace hermes main() produces for `sessions recover`.Mirrors the registrations in hermes_cli/main.py (sessions_recoverdiff --git a/tests/hermes_cli/test_tag_fetch_partial_clone.py b/tests/hermes_cli/test_tag_fetch_partial_clone.pyindex 9c55cb66091..8f478484da5 100644--- a/tests/hermes_cli/test_tag_fetch_partial_clone.py+++ b/tests/hermes_cli/test_tag_fetch_partial_clone.py@@ -41,7 +41,7 @@ def _git(root: Path, *args: str) -> str:text=True, encoding="utf-8").stdout.strip()-def _config_values(root: Path, key: str) -> "list[str]":+def _config_values(root: Path, key: str) -> list[str]:proc = subprocess.run(["git", "config", "--get-all", key], cwd=root,capture_output=True, text=True, encoding="utf-8")return [line.strip() for line in proc.stdout.splitlines() if line.strip()]diff --git a/tests/hermes_cli/test_uninstall_install_kind.py b/tests/hermes_cli/test_uninstall_install_kind.pyindex 8056e3d8ef9..8d4259fd156 100644--- a/tests/hermes_cli/test_uninstall_install_kind.py+++ b/tests/hermes_cli/test_uninstall_install_kind.py@@ -62,7 +62,7 @@ def test_all_refusals_point_at_the_data_mode():# ----------------------------------------------------------------------------def _fake_project_root(monkeypatch, tmp_path: Path, *, git: bool, distribution: "str | None" = None) -> Path:+def _fake_project_root(monkeypatch, tmp_path: Path, *, git: bool, distribution: str | None = None) -> Path:root = tmp_path / "hermes-agent"root.mkdir()if git:diff --git a/tests/hermes_cli/test_update_external_profile_reconciliation.py b/tests/hermes_cli/test_update_external_profile_reconciliation.pyindex 32439847d8e..4514ee46f44 100644--- a/tests/hermes_cli/test_update_external_profile_reconciliation.py+++ b/tests/hermes_cli/test_update_external_profile_reconciliation.py@@ -69,7 +69,7 @@ def external_profile_host(tmp_path, monkeypatch):return SimpleNamespace(other_checkout=other_checkout)-def _restart_outcome() -> "fleet._GatewayRestartOutcome":+def _restart_outcome() -> fleet._GatewayRestartOutcome:# The root's own LaunchAgent was restarted; the other install's gateway was left alone.return fleet._GatewayRestartOutcome(False, [], [1111, 4242], ["ai.hermes.gateway"], [], [], [], set(),diff --git a/tests/hermes_cli/test_web_server_asset_mime.py b/tests/hermes_cli/test_web_server_asset_mime.pyindex 19c157aaeed..4b0b18f8eab 100644--- a/tests/hermes_cli/test_web_server_asset_mime.py+++ b/tests/hermes_cli/test_web_server_asset_mime.py@@ -22,7 +22,7 @@ def _essence(content_type: str) -> str:return content_type.split(";", 1)[0].strip().lower()-def _is_javascript(content_type: "str | None") -> bool:+def _is_javascript(content_type: str | None) -> bool:if not content_type:return Falsereturn _essence(content_type) in JAVASCRIPT_MIME_ESSENCESdiff --git a/tests/hermes_state/_wal_generation_harness.py b/tests/hermes_state/_wal_generation_harness.pyindex 2dec12d9c19..dba5037dae1 100644--- a/tests/hermes_state/_wal_generation_harness.py+++ b/tests/hermes_state/_wal_generation_harness.py@@ -171,7 +171,7 @@ class GatewayWriter:self._proc = procself.path = pathself._stderr_path = stderr_path- self._events: "queue.Queue[str | None]" = queue.Queue()+ self._events: queue.Queue[str | None] = queue.Queue()self._reader = threading.Thread(target=self._read_events, daemon=True)self._reader.start()diff --git a/tests/hermes_state/test_no_locked_readers_gate.py b/tests/hermes_state/test_no_locked_readers_gate.pyindex efb73d62f2d..7349113d989 100644--- a/tests/hermes_state/test_no_locked_readers_gate.py+++ b/tests/hermes_state/test_no_locked_readers_gate.py@@ -143,7 +143,7 @@ def _is_self_lock_with(item: ast.withitem) -> bool:def _scan_locked_readers(- state_py: "Path | None" = None, class_name: str = "SessionDB"+ state_py: Path | None = None, class_name: str = "SessionDB") -> list[str]:target = state_py if state_py is not None else _STATE_PYtree = ast.parse(target.read_text(encoding="utf-8"))diff --git a/tests/hermes_state/test_state_db_maintenance_conformance.py b/tests/hermes_state/test_state_db_maintenance_conformance.pyindex fa326e8eab6..cfdb15151b6 100644--- a/tests/hermes_state/test_state_db_maintenance_conformance.py+++ b/tests/hermes_state/test_state_db_maintenance_conformance.py@@ -113,7 +113,7 @@ class _LiveWriter:if conn is not None:conn.close()- def __enter__(self) -> "_LiveWriter":+ def __enter__(self) -> _LiveWriter:self.thread.start()assert self.ready.wait(timeout=30), "live writer never acquired lock"if self.error is not None:diff --git a/tests/hermes_state/test_state_db_repair_non_destructive.py b/tests/hermes_state/test_state_db_repair_non_destructive.pyindex 1e192da3153..64478ae79bc 100644--- a/tests/hermes_state/test_state_db_repair_non_destructive.py+++ b/tests/hermes_state/test_state_db_repair_non_destructive.py@@ -74,9 +74,9 @@ PAGE_SIZE = 4096def _writer_after_stage(db_path: str,- ready: "multiprocessing.synchronize.Event",- start: "multiprocessing.synchronize.Event",- result: "multiprocessing.queues.Queue",+ ready: multiprocessing.synchronize.Event,+ start: multiprocessing.synchronize.Event,+ result: multiprocessing.queues.Queue,) -> None:"""Try one real cross-process write after staging has begun.diff --git a/tests/install/e2e-assets/launch-capture/sitecustomize.py b/tests/install/e2e-assets/launch-capture/sitecustomize.pyindex efbee190559..38a18169a9d 100644--- a/tests/install/e2e-assets/launch-capture/sitecustomize.py+++ b/tests/install/e2e-assets/launch-capture/sitecustomize.py@@ -58,7 +58,7 @@ if _SPEC_PATH:base = base[: -len(ext)]return base.lower()- def _match_shape(argv: "list[str]") -> str:+ def _match_shape(argv: list[str]) -> str:"""Return the launch shape for argv, or '' when it is not a launch."""if not argv:return ""@@ -79,14 +79,14 @@ if _SPEC_PATH:return "packaged"return ""- def _launch_shape(args, kwargs) -> "tuple[list[str], str]":+ def _launch_shape(args, kwargs) -> tuple[list[str], str]:argv = args[0] if args else kwargs.get("args")if not isinstance(argv, (list, tuple)):return [], ""tokens = [str(t) for t in argv]return tokens, _match_shape(tokens)- def _capture(tokens: "list[str]", kwargs: dict, shape: str) -> None:+ def _capture(tokens: list[str], kwargs: dict, shape: str) -> None:env = kwargs.get("env")spec = {"argv": tokens,diff --git a/tests/plugins/platforms/photon/test_auth.py b/tests/plugins/platforms/photon/test_auth.pyindex f7dd5e7402f..ab6d1cf30b6 100644--- a/tests/plugins/platforms/photon/test_auth.py+++ b/tests/plugins/platforms/photon/test_auth.py@@ -198,7 +198,7 @@ def test_request_device_code_uses_photon_cli(monkeypatch: pytest.MonkeyPatch) ->assert captured["body"]["scope"] == "openid profile email"-def _device_code() -> "photon_auth.DeviceCode":+def _device_code() -> photon_auth.DeviceCode:return photon_auth.DeviceCode(device_code="d", user_code="u",verification_uri="https://x", verification_uri_complete=None,diff --git a/tests/plugins/platforms/photon/test_overflow_recovery.py b/tests/plugins/platforms/photon/test_overflow_recovery.pyindex 0284a6901b4..4726d14c072 100644--- a/tests/plugins/platforms/photon/test_overflow_recovery.py+++ b/tests/plugins/platforms/photon/test_overflow_recovery.py@@ -503,7 +503,7 @@ async def test_standalone_send_classifies_target_not_allowed(def __init__(self, *a: Any, **k: Any) -> None:pass- async def __aenter__(self) -> "_FakeClient":+ async def __aenter__(self) -> _FakeClient:return selfasync def __aexit__(self, *a: object) -> bool:diff --git a/tests/plugins/platforms/photon/test_runtime_record.py b/tests/plugins/platforms/photon/test_runtime_record.pyindex 566f6ed82ac..4d404229342 100644--- a/tests/plugins/platforms/photon/test_runtime_record.py+++ b/tests/plugins/platforms/photon/test_runtime_record.py@@ -85,7 +85,7 @@ class _HealthzClient:def __init__(self, *a: Any, **k: Any) -> None:pass- async def __aenter__(self) -> "_HealthzClient":+ async def __aenter__(self) -> _HealthzClient:return selfasync def __aexit__(self, *a: object) -> bool:@@ -193,7 +193,7 @@ class _SendClient:def __init__(self, *a: Any, **k: Any) -> None:pass- async def __aenter__(self) -> "_SendClient":+ async def __aenter__(self) -> _SendClient:return selfasync def __aexit__(self, *a: object) -> bool:diff --git a/tests/plugins/platforms/photon/test_sidecar_lifecycle.py b/tests/plugins/platforms/photon/test_sidecar_lifecycle.pyindex 09edecdd583..b601d2c471c 100644--- a/tests/plugins/platforms/photon/test_sidecar_lifecycle.py+++ b/tests/plugins/platforms/photon/test_sidecar_lifecycle.py@@ -36,7 +36,7 @@ class _ProbeClient:def __init__(self, *a: Any, **k: Any) -> None:pass- async def __aenter__(self) -> "_ProbeClient":+ async def __aenter__(self) -> _ProbeClient:return selfasync def __aexit__(self, *a: object) -> bool:diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.pyindex dc513062662..178464f1a49 100644--- a/tests/plugins/test_langfuse_plugin.py+++ b/tests/plugins/test_langfuse_plugin.py@@ -376,7 +376,7 @@ class _FakeLangfuse:can fire. Patching ``plugin.Langfuse`` with this class lets theplaceholder validator exercise its full code path."""- instances: list["_FakeLangfuse"] = []+ instances: list[_FakeLangfuse] = []def __init__(self, **kwargs):self.kwargs = kwargsdiff --git a/tests/providers/fake_pkce_idp.py b/tests/providers/fake_pkce_idp.pyindex b35aca5bc03..8a887e9735b 100644--- a/tests/providers/fake_pkce_idp.py+++ b/tests/providers/fake_pkce_idp.py@@ -77,7 +77,7 @@ class FakeIdP:self.base = f"http://127.0.0.1:{self.server.server_address[1]}"self._thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)- def start(self) -> "FakeIdP":+ def start(self) -> FakeIdP:self._thread.start()return selfdiff --git a/tests/test_agent_close_lifecycle.py b/tests/test_agent_close_lifecycle.pyindex c19a028bd11..dc31f275434 100644--- a/tests/test_agent_close_lifecycle.py+++ b/tests/test_agent_close_lifecycle.py@@ -33,7 +33,7 @@ import hermes_bootstrapclass RecordingAgent:"""Minimal AIAgent stand-in: records close() and optional run failure."""- instances: list["RecordingAgent"] = []+ instances: list[RecordingAgent] = []def __init__(self, *args, **kwargs):self.closed = Falsediff --git a/tests/tools/test_mcp_preflight_content_type.py b/tests/tools/test_mcp_preflight_content_type.pyindex 950771cccbc..1b6a8273ddf 100644--- a/tests/tools/test_mcp_preflight_content_type.py+++ b/tests/tools/test_mcp_preflight_content_type.py@@ -57,11 +57,11 @@ def _serve(handler_cls):def _handler(status: int = 200,- content_type: "str | None" = "text/html; charset=utf-8",+ content_type: str | None = "text/html; charset=utf-8",body: bytes = b"<html>x</html>", head_status=None, record=None,- post_content_type: "str | None" = None,+ post_content_type: str | None = None,post_body: bytes = b"",- post_status: "int | None" = None):+ post_status: int | None = None):"""Build a BaseHTTPRequestHandler that replies with the given shape.``head_status`` lets HEAD return a different status than GET (to exercisediff --git a/tests/tools/test_process_heartbeat.py b/tests/tools/test_process_heartbeat.pyindex bbed60791af..c199fe53234 100644--- a/tests/tools/test_process_heartbeat.py+++ b/tests/tools/test_process_heartbeat.py@@ -15,7 +15,7 @@ import tools.process_registry as prfrom tools.process_registry import ProcessRegistry-def _drain(q: "queue.Queue") -> list:+def _drain(q: queue.Queue) -> list:out = []while True:try:diff --git a/tools/approval_context.py b/tools/approval_context.pyindex b28b820c9a4..977ba44449b 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -15,7 +15,7 @@ from utils import env_var_enabled, is_truthy_valuelogger = logging.getLogger("tools.approval")-def _ctx(name: str, default: "str | None" = "") -> contextvars.ContextVar:+def _ctx(name: str, default: str | None = "") -> contextvars.ContextVar:return contextvars.ContextVar(name, default=default)diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex f376a65d08b..8107e5cc9fb 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -541,7 +541,7 @@ def is_running() -> bool:return bool(published_env().get("DISPLAY"))-def open_rfb_stream() -> "subprocess.Popen":+def open_rfb_stream() -> subprocess.Popen:"""Popen whose stdin/stdout carry RFB bytes for a sandbox-hosted screen (``in_sandbox()`` only)."""from tools.bot_desktop import sandbox_hostenv = _sandbox_env(create=False)diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 80a44c70b93..23dc00eb24e 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -474,12 +474,12 @@ def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, streturn proc.returncode-def _live_intent_file(dm_file: "str | os.PathLike") -> str:+def _live_intent_file(dm_file: str | os.PathLike) -> str:"""The pinned live-delivery intent beside a DM file (the cache sweep globs ``*.live.json``)."""return f"{os.fspath(dm_file)}.live.json"-def _dm_delivery_id(dm_file: "str | os.PathLike") -> str:+def _dm_delivery_id(dm_file: str | os.PathLike) -> str:"""One delivery id per DM file: the dispatch ack, the live-owner intent and every retryof the runner derive it the same way, so the sender can correlate all of them."""return hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest()@@ -520,7 +520,7 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dicreturn record-def _wait_live_dm(home: str, delivery_id: str, *, dm_file: "str | os.PathLike | None" = None) -> int:+def _wait_live_dm(home: str, delivery_id: str, *, dm_file: str | os.PathLike | None = None) -> int:from tools.bot_failure_reasons import RUNTIME_OFFLINEfrom tools.bot_live_delivery import await_delivery, cancel_queued_delivery, owner_holds_deliverydiff --git a/tools/bot_relay.py b/tools/bot_relay.pyindex 0688a8a0748..f6b2b92c823 100644--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@ -211,7 +211,7 @@ def _title_slug(row: dict) -> str:return slug if slug in alias_forms(title) else ""-def remote_target_forms(roster: list[dict], local_taken: "set[str] | frozenset[str]" = frozenset()) -> list[str]:+def remote_target_forms(roster: list[dict], local_taken: set[str] | frozenset[str] = frozenset()) -> list[str]:"""One unambiguous target string per row, shortest first: the bare handle when no other remoterow and no LOCAL profile (``local_taken``: this gateway's handles and friendly-name slugs) answersto it; else the title slug under the same test (a remote ``default`` titled "CoS Bot" is@@ -241,7 +241,7 @@ _SENDER_STAMP_RE = re.compile(r"^(Message from 🤖 .+? \(@)([A-Za-z0-9_-]+)(\):def qualify_sender_stamp(message: str, from_handle: Any, from_connection: Any, roster: list[dict],- local_taken: "set[str] | frozenset[str]" = frozenset()) -> str:+ local_taken: set[str] | frozenset[str] = frozenset()) -> str:"""Rewrite a relayed DM's ``Message from 🤖 <name> (@<handle>):`` stamp so the handle is theform THIS gateway can reply to: the sender's row in the local relay roster as``remote_target_forms`` renders it, else ``handle@connection``. A relayed ``@hermes`` is another@@ -553,7 +553,7 @@ def delivery_turn_author(from_profile: Any, from_handle: Any, from_connection: A"is_bot": True}-def _delivery_child_session_env_names() -> "tuple[str, ...]":+def _delivery_child_session_env_names() -> tuple[str, ...]:"""Session-bound env names to strip from a delivery child, from ``gateway.session_context``.Synced with the session binding surface as vars are added; deliberately NOT a@@ -577,7 +577,7 @@ def relaying_principal_author(principal: str) -> dict:return {"id": bot_author_id("relay", str(principal or "").strip()), "name": "relayed teammate", "is_bot": True}-def delivery_env(author: Optional[dict], profile_home: "str | Path | None" = None) -> dict[str, str]:+def delivery_env(author: Optional[dict], profile_home: str | Path | None = None) -> dict[str, str]:"""Environment for one delivery turn's ``hermes -p <profile>`` child. The dispatcher's ownHERMES_TURN_AUTHOR is dropped first so a delivery without an author never inherits the author of the turnthat sent it. Dispatcher session identity (the canonical ``gateway.session_context`` session env names) isdiff --git a/tools/browser_lightpanda.py b/tools/browser_lightpanda.pyindex 44990476f4b..55ca0e8bea1 100644--- a/tools/browser_lightpanda.py+++ b/tools/browser_lightpanda.py@@ -28,7 +28,7 @@ _READY_TIMEOUT_S = 10.0_POLL_INTERVAL_S = 0.1_STDERR_TAIL_LIMIT = 2000-_servers: dict[str, "LightpandaServer"] = {}+_servers: dict[str, LightpandaServer] = {}_servers_lock = threading.Lock()diff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.pyindex d8945455e76..243eac97174 100644--- a/tools/browser_supervisor.py+++ b/tools/browser_supervisor.py@@ -513,7 +513,7 @@ class _SupervisorRegistry:with self._lock:return self._by_task.pop(task_id, None)- def capture(self, task_id: str, *, timeout: float = 10.0) -> "CapturedCDP":+ def capture(self, task_id: str, *, timeout: float = 10.0) -> CapturedCDP:"""Public CDP seam for trusted in-process plugins: a handle pinned to this task'scurrent connection and default page session (``tools.browser_supervisor_capture``)."""from tools.browser_supervisor_capture import capturediff --git a/tools/browser_tool_lifecycle.py b/tools/browser_tool_lifecycle.pyindex a530ea30e47..8ac65a5aad7 100644--- a/tools/browser_tool_lifecycle.py+++ b/tools/browser_tool_lifecycle.py@@ -477,7 +477,7 @@ def _update_session_activity(task_id: str):_bt._session_owner_homes.setdefault(task_id, str(get_hermes_home()))-def _kill_process_tree(proc: "subprocess.Popen") -> None:+def _kill_process_tree(proc: subprocess.Popen) -> None:"""Best-effort kill of *proc* and every descendant; never raises.``Popen.kill()`` only signals the direct child; npm/npx helpers and the detached@@ -504,7 +504,7 @@ def _kill_process_tree(proc: "subprocess.Popen") -> None:_legacy_kill_process_tree(proc)-def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:+def _legacy_kill_process_tree(proc: subprocess.Popen) -> None:"""Local tree-kill (fallback when agent.deadline is unavailable; tests pinthe signal sequence). A child leading its own group gets SIGTERM thenSIGKILL via killpg; a shared-group child can never be killpg'd (that is OURdiff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 9e66bdbd049..8472668cf08 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -132,7 +132,7 @@ def _agent_browser_argv(browser_cmd: str) -> list:return [browser_cmd]-def _shim_safe_args(argv0: str, command: str, args: list[str]) -> "tuple[str, list[str], Optional[bytes]]":+def _shim_safe_args(argv0: str, command: str, args: list[str]) -> tuple[str, list[str], Optional[bytes]]:"""``(spawn_command, spawn_args, stdin_payload)`` for one CLI command. Arguments that reach a``.cmd``/``.bat`` shim (``npx.cmd``, npm's ``agent-browser.cmd`` on Windows) go through cmd.exe,which re-parses the child command line: a newline ends the argument and ``%VAR%`` expands even@@ -228,7 +228,7 @@ def _ensure_screen_for_headed_chromium() -> None:def _popen_agent_browser(argv: list[str], env: dict[str, str], socket_dir: str, tag: str,- stdin_payload: Optional[bytes] = None) -> "subprocess.Popen":+ stdin_payload: Optional[bytes] = None) -> subprocess.Popen:"""Spawn agent-browser with stdout/stderr redirected to ``socket_dir/_std{out,err}_<tag>``;``stdin_payload`` (a ``batch`` JSON body) is served from ``_stdin_<tag>`` the same way.@@ -567,7 +567,7 @@ def _sandbox_socket_dir(env) -> str:return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/agent-browser"-def sandbox_screenshot_path(host_path: "Path") -> Optional[str]:+def sandbox_screenshot_path(host_path: Path) -> Optional[str]:"""Where the sandboxed CLI should write a screenshot (its own tmp), or None on a gateway-hosted browser."""if not _browser_in_sandbox():return None@@ -578,7 +578,7 @@ def sandbox_screenshot_path(host_path: "Path") -> Optional[str]:return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/shots/{host_path.name}"-def fetch_sandbox_file(remote_path: str, local_dest: "Path", *, max_bytes: int = 16 * 1024 * 1024) -> bool:+def fetch_sandbox_file(remote_path: str, local_dest: Path, *, max_bytes: int = 16 * 1024 * 1024) -> bool:"""Copy a file the sandboxed browser wrote (a screenshot) to the host; False when not in sandbox mode."""if not _browser_in_sandbox():return False@@ -660,7 +660,7 @@ def _browser_in_sandbox() -> bool:return placement.resolve().where == placement.TERMINAL-def _sandbox_wrap(cmd_parts: list[str], browser_env: dict[str, str], task_socket_dir: str) -> "tuple[list[str], dict[str, str]]":+def _sandbox_wrap(cmd_parts: list[str], browser_env: dict[str, str], task_socket_dir: str) -> tuple[list[str], dict[str, str]]:"""Rewrite one agent-browser invocation to run inside the sandbox: exec prefix + the CLI by name, with thebrowser-relevant variables exported there (the daemon's socket dir mirrors the host path so the host-sideliveness probes keep their shape) and a screen-published DISPLAY. Identity on a gateway-hosted screen."""@@ -810,7 +810,7 @@ def run_fenced(session_info: dict[str, Any], fn: Callable[[], dict[str, Any]]) -return result-def run_fenced_pair(session_info: dict[str, Any], fn: Callable[[], "tuple[str, dict[str, Any]]"]) -> "tuple[str, dict[str, Any]]":+def run_fenced_pair(session_info: dict[str, Any], fn: Callable[[], tuple[str, dict[str, Any]]]) -> tuple[str, dict[str, Any]]:"""``run_fenced`` for the dispatch shape ``(engine, result)``; a refusal carries no engine (never ran)."""engine_box: list = []@@ -846,7 +846,7 @@ def _bot_desktop_attach_port(session_info: dict[str, Any]) -> Optional[int]:def _dispatch_browser_command(task_id: str, session_info: dict[str, Any], browser_cmd: str, command: str, args: list[str],timeout: int, _engine_override: Optional[str],-) -> "tuple[str, dict[str, Any]]":+) -> tuple[str, dict[str, Any]]:"""Build the agent-browser argv for ``session_info`` and run it once → ``(engine, result)``."""# Cleanup stops the supervisor before closing the backend; keep it stopped.if command != "close" and session_info.get("cdp_url"):diff --git a/tools/code_kernel.py b/tools/code_kernel.pyindex 0aa0ef40fe4..64c32569e62 100644--- a/tools/code_kernel.py+++ b/tools/code_kernel.py@@ -322,7 +322,7 @@ class SessionKernel:self.attached: int = 0# Owned by a live delegate_task child: exempt from LRU eviction (the child's teardown disposes it).self.pinned: bool = False- self.response_q: "queue.Queue[dict]" = queue.Queue()+ self.response_q: queue.Queue[dict] = queue.Queue()self.raw, self.stderr = _BoundedBuffer(), _BoundedBuffer()self.execution_count, self.last_used = 0, time.monotonic()self.cell_authority: Optional[CellAuthority] = Nonediff --git a/tools/code_kernel_remote.py b/tools/code_kernel_remote.pyindex 3d443c71041..e0e23651b45 100644--- a/tools/code_kernel_remote.py+++ b/tools/code_kernel_remote.py@@ -178,7 +178,7 @@ def shutdown_remote_kernels_where(owner_matches: Callable[[str], bool]) -> None:_REGISTRY.shutdown(owner_matches=owner_matches)-def _reap_unlocked(idle_timeout: int) -> list["RemoteKernel"]:+def _reap_unlocked(idle_timeout: int) -> list[RemoteKernel]:"""Pop idle-expired, unattached remote kernels; caller tears them down outside the lock. Therunner self-exits after the same idle window, so this clears the HOST-side entry — without itthe map grew one entry per never-revisited (owner, env_type, task_env_id) for the gateway's life."""@@ -188,7 +188,7 @@ def _reap_unlocked(idle_timeout: int) -> list["RemoteKernel"]:return [_REMOTE_KERNELS.pop(key) for key in doomed]-def _evict_over_cap_unlocked(keep: tuple) -> list["RemoteKernel"]:+def _evict_over_cap_unlocked(keep: tuple) -> list[RemoteKernel]:"""Pop least-recently-used unattached remote kernels beyond the process-wide cap (the same``max_session_kernels`` bound as local kernels, applied independently to this map)."""from tools.code_kernel import _lifecycle_limitsdiff --git a/tools/computer_use/cua_backend_capture.py b/tools/computer_use/cua_backend_capture.pyindex 31a1c45fa3a..0e93f1c5b4d 100644--- a/tools/computer_use/cua_backend_capture.py+++ b/tools/computer_use/cua_backend_capture.py@@ -211,7 +211,7 @@ class _CaptureMixin:return next((matched for matched in tiers if matched), [])def _resolve_capture_windows(self, mode: str, app: Optional[str], pid: Optional[int],- window_id: Optional[int]) -> "list[dict[str, Any]] | CaptureResult":+ window_id: Optional[int]) -> list[dict[str, Any]] | CaptureResult:"""Candidate windows for capture(), or a failed CaptureResult."""if pid is not None or window_id is not None:# An exact pid/window pair is both the stable capture_after target and the escape hatch whendiff --git a/tools/connectors/gateway/config.py b/tools/connectors/gateway/config.pyindex 5a936e95cc2..c3237992243 100644--- a/tools/connectors/gateway/config.py+++ b/tools/connectors/gateway/config.py@@ -30,7 +30,7 @@ class ConnectorConfig:enabled: bool = True@classmethod- def from_raw(cls, raw: Any) -> "ConnectorConfig":+ def from_raw(cls, raw: Any) -> ConnectorConfig:"""Malformed configuration falls back to the enabled default."""if isinstance(raw, bool):return cls(enabled=raw)diff --git a/tools/connectors/mcp_oauth.py b/tools/connectors/mcp_oauth.pyindex a98bb0510ef..66790aba73f 100644--- a/tools/connectors/mcp_oauth.py+++ b/tools/connectors/mcp_oauth.py@@ -216,7 +216,7 @@ def _validate_client_redirect_uri(uri: str) -> str:return f"http://{'[' + host + ']' if ':' in host else host}:{parsed.port}{parsed.path or '/callback'}"-def _start_loopback_receiver(flow) -> "http.server.HTTPServer":+def _start_loopback_receiver(flow) -> http.server.HTTPServer:"""Bind the single backend-hosted one-shot receiver and feed its callback into ``flow``."""from tools.mcp_oauth import _parse_redirect_querydiff --git a/tools/connectors/operation.py b/tools/connectors/operation.pyindex 45c452a725e..3cd35b0ca21 100644--- a/tools/connectors/operation.py+++ b/tools/connectors/operation.py@@ -71,7 +71,7 @@ class Target:class ConnectionOperation:# The gateway installs its ``connection.update`` emitter here once; pure data otherwise.on_change: ClassVar[- Optional[Callable[["ConnectionOperation", Optional[dict[str, Any]], dict[str, Any]], None]]+ Optional[Callable[[ConnectionOperation, Optional[dict[str, Any]], dict[str, Any]], None]]] = Nonetargets: list[Target]diff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 4f775f1e3dd..dc3b7af1446 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -154,7 +154,7 @@ def _apply_child_cache_ttl(child) -> None:_CHILD_CAP_MIN = 16_000 # below this a child compresses on every call; treat as a config error-def _child_compression_cap_tokens(raw) -> "int | None":+def _child_compression_cap_tokens(raw) -> int | None:"""Validated ``delegation.compression_threshold_tokens``: an int >= 16000, or None for "no cap".Unset / ``0`` / ``false`` / ``null`` mean no subagent-specific cap: the child compacts at thediff --git a/tools/environments/base.py b/tools/environments/base.pyindex 00182c691ee..c6810afba94 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -56,7 +56,7 @@ _activity_callback_local = threading.local()# Foreground commands in flight in THIS process, across every environment. Each runs in its# own session/process group, so a host that exits mid-command (TUI client gone, SIGTERM) would# orphan the whole tree; the process-exit funnel ``cleanup_all_environments`` kills them.-_live_foreground: dict[int, tuple["BaseEnvironment", "ProcessHandle"]] = {}+_live_foreground: dict[int, tuple[BaseEnvironment, ProcessHandle]] = {}# Reentrant, and the hard-exit path only ever takes it with a timeout: a signal handler can run# on a thread that already holds it._live_foreground_cond = threading.Condition(threading.RLock())@@ -74,7 +74,7 @@ def _enter_foreground_spawn() -> bool:return True-def _leave_foreground_spawn(env: "BaseEnvironment", spawned) -> bool:+def _leave_foreground_spawn(env: BaseEnvironment, spawned) -> bool:"""Publish ``spawned`` (None: the spawn failed); True when the exit fence went up meanwhile."""global _spawns_in_flightwith _live_foreground_cond:diff --git a/tools/environments/base_output.py b/tools/environments/base_output.pyindex c0175a926f1..050e5833c85 100644--- a/tools/environments/base_output.py+++ b/tools/environments/base_output.py@@ -34,7 +34,7 @@ class _BoundedOutputCollector:# Hard ceiling on spill file size; protects disk from runaway output._SPILL_CAP_CHARS = 5_000_000- def __init__(self, max_chars: int, spill_path: "Path | None" = None):+ def __init__(self, max_chars: int, spill_path: Path | None = None):self.max_chars = max(1, int(max_chars))self._head_limit = int(self.max_chars * 0.4)self._tail_limit = self.max_chars - self._head_limit@@ -76,7 +76,7 @@ class _BoundedOutputCollector:# Disk trouble must never break command execution.self._spill_capped = True- def close_spill(self) -> "str | None":+ def close_spill(self) -> str | None:"""Close the spill file and return its path if it was used."""with self._lock:if self._spill_fh is None:@@ -339,7 +339,7 @@ class _ThreadedProcessHandle:# --- Stdout drain thread ----def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: "threading.Event | None" = None) -> None:+def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: threading.Event | None = None) -> None:"""Drain ``proc.stdout`` into *output* until EOF or shortly after exit.``for line in proc.stdout`` would block on ``readline()`` until EOF, and a backgroundedgrandchild (``cmd &``, ``setsid cmd & disown``) inherits the pipe's write end — so the@@ -471,7 +471,7 @@ def _drain_fd_windows(proc, fd: int, output: _BoundedOutputCollector, decoder, sdef _start_drain_thread(- proc: ProcessHandle, output: _BoundedOutputCollector, stop: "threading.Event | None" = None,+ proc: ProcessHandle, output: _BoundedOutputCollector, stop: threading.Event | None = None,) -> threading.Thread:"""Start the daemon thread running :func:`_drain_stdout`; *stop* ends it early."""thread = threading.Thread(target=_drain_stdout, args=(proc, output, stop), daemon=True)diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 7eaa5b7d868..41a7c16229c 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -48,7 +48,7 @@ _terminal_temp_pruned_once = False_BG_GROUP_RE = re.compile(r"^(hermes_bg_[A-Za-z0-9_-]+)\.(log|pid|exit)$")-def _default_terminal_temp_dir() -> "Path | None":+def _default_terminal_temp_dir() -> Path | None:"""Return HERMES_HOME/cache/terminal, or None if unresolvable."""try:from hermes_constants import get_hermes_home@@ -348,8 +348,8 @@ def _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:def build_subprocess_env(- base: "Mapping[str, str] | None" = None, *, inherit_profile_home: bool = True,- scrub_secrets: bool = True, extra: "Mapping[str, str] | None" = None,+ base: Mapping[str, str] | None = None, *, inherit_profile_home: bool = True,+ scrub_secrets: bool = True, extra: Mapping[str, str] | None = None,strip_launch_profile: bool = False) -> dict[str, str]:"""Single factory for child-process envs. ``base=None`` snapshots ``os.environ``.``scrub_secrets=True`` -> :func:`_sanitize_subprocess_env` (profile home inherent,@@ -384,7 +384,7 @@ def build_subprocess_env(def served_profile_child_env(- base: "Mapping[str, str] | None" = None, *, target_home: "str | Path | None" = None,+ base: Mapping[str, str] | None = None, *, target_home: str | Path | None = None,inherit_credentials: bool = False,) -> dict[str, str]:"""Child env for a process that acts FOR the active (possibly served) profile: ``hermes -p X``@@ -428,7 +428,7 @@ def served_profile_child_env(def host_gateway_child_env(- base: "Mapping[str, str] | None" = None,+ base: Mapping[str, str] | None = None,) -> dict[str, str]:"""Child env for the host gateway: the default profile's secrets, never the launcher's.@@ -442,7 +442,7 @@ def host_gateway_child_env()-def _is_routed_home(target_home: "str | Path") -> bool:+def _is_routed_home(target_home: str | Path) -> bool:"""True when ``target_home`` is not the process's own (launch) home.Same launch-home identity as ``agent.secret_scope.serves_routed_profile()``: under a host that@@ -455,7 +455,7 @@ def _is_routed_home(target_home: "str | Path") -> bool:return True-def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None) -> dict:+def strip_launch_profile_env(env: dict, target_home: str | Path | None = None) -> dict:"""Drop the LAUNCH profile's residue from a child env built for another served profile.``os.environ`` holds the default profile's ``.env`` and its bridged ``TERMINAL_*`` settings;the secret scrub removes credentials but not settings (``HERMES_MODEL``, ``TERMINAL_ENV``,@@ -527,7 +527,7 @@ def _find_bash() -> str:)-_git_bash_bin_dirs_cache: "list[str] | None" = None+_git_bash_bin_dirs_cache: list[str] | None = Nonedef _git_bash_bin_dirs() -> list[str]:@@ -595,7 +595,7 @@ _SANE_PATH = ("/opt/homebrew/bin:/opt/homebrew/sbin:"# Cached directory containing the ``hermes`` console-script.# ``_SENTINEL`` distinguishes "not resolved yet" from a resolved ``None``._SENTINEL = object()-_HERMES_BIN_DIR: "str | None | object" = _SENTINEL+_HERMES_BIN_DIR: str | None | object = _SENTINEL# True when the cached dir is a sealed payload's own launcher dir (see below)._HERMES_BIN_DIR_IS_PAYLOAD = Falsediff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.pyindex d8cf7128bce..04b7f3eae9d 100644--- a/tools/environments/local_env_policy.py+++ b/tools/environments/local_env_policy.py@@ -170,7 +170,7 @@ def _registered_adapter_secret_env() -> frozenset:return _registry_adapter_secret_env() | _home_adapter_secret_env()-def _is_provider_env_blocklisted(name: str, _registered: "frozenset | None" = None) -> bool:+def _is_provider_env_blocklisted(name: str, _registered: frozenset | None = None) -> bool:"""``name`` is a blocklisted provider/tool credential or adapter secret, matched the way theplatform's environment resolves names: exact plus case-folded. On Windows the environmentblock is case-insensitive, so ``openai_api_key`` IS ``OPENAI_API_KEY``; consistent withdiff --git a/tools/environments/streams.py b/tools/environments/streams.pyindex 41ace989d56..f4dc87f0450 100644--- a/tools/environments/streams.py+++ b/tools/environments/streams.py@@ -129,7 +129,7 @@ _TCP_RELAY = (" os.write(1,d)\n")-_forwards: dict[tuple[int, str, int], "PortForward"] = {}+_forwards: dict[tuple[int, str, int], PortForward] = {}_forwards_lock = threading.Lock()diff --git a/tools/file_operations.py b/tools/file_operations.pyindex d5a1519190e..26220c563cf 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -283,7 +283,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):result = self._exec(f"python -c {self._escape_shell_arg(snippet)}")return result- def _fenced_read(self, body: str, *more: str) -> "tuple[Optional[list[str]], Optional[int], ExecuteResult]":+ def _fenced_read(self, body: str, *more: str) -> tuple[Optional[list[str]], Optional[int], ExecuteResult]:"""Run BODY, then each of MORE, each in its own sentinel-delimited segment; return (thosesegments, BODY's exit status, reply).@@ -337,7 +337,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):return Nonereturn self._decode_base64_sample(segments[0])- def _read_exact_bytes(self, path: str) -> "tuple[Optional[bytes], Optional[ExecuteResult]]":+ def _read_exact_bytes(self, path: str) -> tuple[Optional[bytes], Optional[ExecuteResult]]:"""The file's bytes exactly, for the edit paths that write back every line they did not touch.The text transport cannot carry them: it decodes with errors="replace", so a byte UTF-8 cannot@@ -395,7 +395,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):return ExecuteResult(stdout=_strip_terminal_fence_leaks(payload).strip() or f"{path}: exit {read_rc}",exit_code=read_rc)- def _read_exact_bytes_hex(self, path: str) -> "tuple[Optional[bytes], Optional[ExecuteResult]]":+ def _read_exact_bytes_hex(self, path: str) -> tuple[Optional[bytes], Optional[ExecuteResult]]:"""``od`` fallback for a backend without ``base64``, fenced the same way.``read_file_raw`` is the edit paths' source read AND, through ``_apply_add``, their@@ -564,7 +564,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):arg = _msys_to_windows_path(arg).replace("\\", "/")return "'" + arg.replace("'", "'\"'\"'") + "'"- def _atomic_write(self, path: str, content: str) -> "ExecuteResult":+ def _atomic_write(self, path: str, content: str) -> ExecuteResult:"""Write ``content`` atomically: stdin → temp file in the SAME directory →``mv -f`` (same-FS rename; cross-device ``mv`` is copy+unlink, NOT atomic).``mkdir -p`` folded in. Exit 0 = swap happened; non-zero = original intact.@@ -731,7 +731,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):)def _try_read_utf16(self, path: str, offset: int, limit: int,- file_size: int) -> "Optional[ReadResult]":+ file_size: int) -> Optional[ReadResult]:"""Read ``path`` as UTF-16 transcoded to UTF-8, or None (caller falls backto the binary-file error). Skips known-binary extensions and files over10 MiB. ``path`` must already be expanded."""diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex e19d2e83ce3..194d221adb2 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -74,11 +74,11 @@ class RefreshFenceTimeout(RuntimeError):_FENCE_CONTENTION_ERRNOS = frozenset({errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES, errno.EDEADLK})-def _refresh_lock_path(path: "Path") -> "Path":+def _refresh_lock_path(path: Path) -> Path:return path.with_suffix(path.suffix + ".refresh.lock")-async def acquire_refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int:+async def acquire_refresh_fence(path: Path, *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int:"""Take the fence that owns one refresh generation across read -> POST -> persist.Token files are written atomically (``_write_json``), so a reader never@@ -243,7 +243,7 @@ def _safe_filename(name: str) -> str:# Holding the socket from port-selection time until _wait_for_callback adopts it closes the TOCTOU window# where another process could grab the port between _find_free_port() closing its probe socket and# HTTPServer binding minutes later (#22161).-_reserved_sockets: "dict[int, socket.socket]" = {}+_reserved_sockets: dict[int, socket.socket] = {}_MAX_RESERVED_SOCKETS = 8@@ -275,7 +275,7 @@ def _reserve_callback_port() -> int:return _bind_reserved(0) # type: ignore[return-value] # port 0 never returns None-def _cached_client_info(storage: "HermesTokenStorage | None") -> dict | None:+def _cached_client_info(storage: HermesTokenStorage | None) -> dict | None:"""The on-disk client registration for *storage*, or None."""try:info = _read_json(storage._client_info_path()) if storage is not None else None@@ -286,7 +286,7 @@ def _cached_client_info(storage: "HermesTokenStorage | None") -> dict | None:return info if isinstance(info, dict) else None-def _cached_redirect(storage: "HermesTokenStorage | None") -> "tuple[str | None, int | None]":+def _cached_redirect(storage: HermesTokenStorage | None) -> tuple[str | None, int | None]:"""``(https proxy URI, loopback callback port)`` from the cached client registration (None whenabsent): a DCR ``client_id`` is bound to its registered redirect URI, so a new random port underit gets ``redirect_uri does not match any registered URIs``."""@@ -483,11 +483,11 @@ class HermesTokenStorage:self.loaded_issuer = data.pop("hermes_issuer", None)self._rebase_expires_in(data)- async def get_tokens(self) -> "OAuthToken | None":+ async def get_tokens(self) -> OAuthToken | None:self.loaded_issuer = Nonereturn self._load_model(self._tokens_path(), "OAuthToken", "tokens", self._fixup_loaded_tokens)- async def set_tokens(self, tokens: "OAuthToken") -> None:+ async def set_tokens(self, tokens: OAuthToken) -> None:payload = _model_json(tokens)# Absolute ``expires_at``: see _rebase_expires_in.if payload.get("expires_in") is not None:@@ -545,7 +545,7 @@ class HermesTokenStorage:return Truereturn False- async def get_client_info(self) -> "OAuthClientInformationFull | None":+ async def get_client_info(self) -> OAuthClientInformationFull | None:coerced: list[bool] = []info = self._load_model(self._client_info_path(), "OAuthClientInformationFull", "client info",@@ -554,19 +554,19 @@ class HermesTokenStorage:_write_json(self._client_info_path(), _model_json(info)) # persist so later flows skip the coercionreturn info- async def set_client_info(self, client_info: "OAuthClientInformationFull") -> None:+ async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:data = _model_json(client_info)self._coerce_secret_auth_method(data)_write_json(self._client_info_path(), data)logger.debug("OAuth client info saved for %s", self._server_name)- def save_oauth_metadata(self, metadata: "OAuthMetadata") -> None:+ def save_oauth_metadata(self, metadata: OAuthMetadata) -> None:"""Persist server metadata so a restarted process can refresh without re-discovery;otherwise the SDK guesses ``{server_url}/token`` (404) and forces re-auth."""_write_json(self._meta_path(), _model_json(metadata))logger.debug("OAuth metadata saved for %s", self._server_name)- def load_oauth_metadata(self) -> "OAuthMetadata | None":+ def load_oauth_metadata(self) -> OAuthMetadata | None:return self._load_model(self._meta_path(), "OAuthMetadata", "OAuth metadata")def mark_cimd_rejected(self) -> None:@@ -650,7 +650,7 @@ class HermesTokenStorage:# Callback capture: the HTTP listener and the stdin paste reader share one result dict.-def _authorization_code_result(code: str, state: "str | None", iss: "str | None" = None):+def _authorization_code_result(code: str, state: str | None, iss: str | None = None):"""Redirect parameters in the shape the installed SDK expects: mcp 2.0's ``callback_handler``returns an ``AuthorizationCodeResult`` (the SDK reads ``.state``/``.iss`` off it); older SDKs take a tuple."""try:@@ -950,7 +950,7 @@ def _is_valid_cimd_url(url: str) -> bool:# lifetime), including ports restored from a cached registration.# Includes a port restored from a cached client registration, so a sibling server is never handed a port# another one is already registered on (#34260).-_assigned_cimd_ports: "list[int]" = []+_assigned_cimd_ports: list[int] = []def _pick_cimd_port() -> int | None:@@ -970,7 +970,7 @@ def _pick_cimd_port() -> int | None:return _assigned_cimd_ports[0] if _assigned_cimd_ports else None-def _server_declined_cimd(storage: "HermesTokenStorage | None") -> bool:+def _server_declined_cimd(storage: HermesTokenStorage | None) -> bool:"""True when cached metadata shows this server doesn't advertise CIMD. The SDK decides CIMD vs DCRin its 401 branch — after Hermes must fix the redirect URI — so cached metadata closes the gap;only a genuinely unknown server pays the optimistic pin."""@@ -981,7 +981,7 @@ def _server_declined_cimd(storage: "HermesTokenStorage | None") -> bool:return metadata is not None and getattr(metadata, "client_id_metadata_document_supported", None) is not True-def _maybe_use_cimd(cfg: dict, storage: "HermesTokenStorage | None" = None) -> "tuple[str, int] | None":+def _maybe_use_cimd(cfg: dict, storage: HermesTokenStorage | None = None) -> tuple[str, int] | None:"""``(client_id URL, pinned callback port)``, or None to use DCR. Each ineligibility case means theredirect URI is not one the document declares, the client identity is already settled, or theserver is known not to want a document — a metadata URL would be rejected."""@@ -1035,7 +1035,7 @@ def login_connect_timeout(config: dict) -> float:_seconds(oauth_cfg.get("timeout"), 300.0) + 15.0)-def _configure_callback_port(cfg: dict, storage: "HermesTokenStorage | None" = None) -> int:+def _configure_callback_port(cfg: dict, storage: HermesTokenStorage | None = None) -> int:"""Resolve the callback port into ``cfg['_resolved_port']`` (0 = non-loopback URI). Precedence:dashboard flow / cached https redirect URI → CIMD pinned port (sets ``cfg['_cimd_url']``) →``oauth.redirect_port`` → cached registration port → fresh ephemeral port (the only parked one).@@ -1119,7 +1119,7 @@ def apply_oauth_provider_defaults(cfg: dict, *, server_name: str = "", server_urreturn cfg-def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata":+def _build_client_metadata(cfg: dict) -> OAuthClientMetadata:"""Build OAuthClientMetadata; requires ``_configure_callback_port`` first."""port = cfg.get("_resolved_port")if port is None:@@ -1146,7 +1146,7 @@ def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata":def _invalidate_tokens_on_client_change(- storage: "HermesTokenStorage", new_client_id: str, new_client_secret: str | None) -> None:+ storage: HermesTokenStorage, new_client_id: str, new_client_secret: str | None) -> None:"""Drop cached tokens when the configured client identity changes: tokens minted under the old``client_id`` fail refresh with ``invalid_client``, and pre-registered clients are exempt fromauto-poison, so stale tokens would wedge every request until a manual wipe. Compares on-disk@@ -1175,7 +1175,7 @@ def _invalidate_tokens_on_client_change(storage._server_name, old_client_id, new_client_id, storage._server_name)-def _maybe_preregister_client(storage: "HermesTokenStorage", cfg: dict, client_metadata: "OAuthClientMetadata") -> None:+def _maybe_preregister_client(storage: HermesTokenStorage, cfg: dict, client_metadata: OAuthClientMetadata) -> None:"""If cfg has a pre-registered client_id, persist it to storage."""client_id = cfg.get("client_id")if not client_id:@@ -1231,7 +1231,7 @@ def humanize_oauth_registration_error("API-key / local server instead.")-def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | None = None) -> "OAuthClientProvider | None":+def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | None = None) -> OAuthClientProvider | None:"""``httpx.Auth`` OAuth handler for an MCP server; None if the SDK lacks OAuth. Legacy API — new codeuses :func:`tools.mcp_oauth_manager.get_manager` so state is shared across config-time, runtime and reconnect paths."""global HermesOAuthClientProviderdiff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.pyindex 3c4f38704a7..3399d06c216 100644--- a/tools/mcp_oauth_manager.py+++ b/tools/mcp_oauth_manager.py@@ -38,7 +38,7 @@ class _ProviderEntry:provider: Optional[Any] = Nonelast_mtime_ns: int = 0lock: asyncio.Lock = field(default_factory=asyncio.Lock)- pending_401: dict[str, "asyncio.Future[bool]"] = field(default_factory=dict)+ pending_401: dict[str, asyncio.Future[bool]] = field(default_factory=dict)class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.pyindex 8b3ff790f99..545c5b071d2 100644--- a/tools/mcp_oauth_provider.py+++ b/tools/mcp_oauth_provider.py@@ -603,7 +603,7 @@ def enforce_refresh_token_issuer(context: Any) -> None:tokens.refresh_token = None-def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, "HermesTokenStorage"]:+def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, HermesTokenStorage]:"""Copy the ``oauth:`` block, apply provider defaults, open its token storage. The copymatters: later steps record ``_resolved_port`` / ``_cimd_url`` in the dict, which mustnever leak back into the caller's config."""@@ -613,7 +613,7 @@ def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict |return cfg, mo.HermesTokenStorage(server_name)-def build_provider_kwargs(cfg: dict, storage: "HermesTokenStorage", *, ssh_proxy_hint: bool) -> dict[str, Any]:+def build_provider_kwargs(cfg: dict, storage: HermesTokenStorage, *, ssh_proxy_hint: bool) -> dict[str, Any]:"""Resolve the callback port and return the shared provider constructor kwargs. Ordermatters: metadata needs the resolved port, pre-registration needs the metadata.``ssh_proxy_hint`` lets the redirect handler tailor its remote-session hint to a configureddiff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.pyindex b79e08f3fad..0d48a0c941c 100644--- a/tools/mcp_tool_errors.py+++ b/tools/mcp_tool_errors.py@@ -284,7 +284,7 @@ def _apply_identity_header(server_name: str, config: dict, headers: dict) -> dicdef _make_redirect_header_stripper(httpx_mod, original_url, *, strict: bool = False,- configured_header_names: "set[str] | frozenset[str]" = frozenset()):+ configured_header_names: set[str] | frozenset[str] = frozenset()):"""Client factory enforcing the redirect credential boundary: on a cross-origin redirectfollow-up it strips ``Authorization``; with *strict* (Agent Plugins v1 ``strict_redirect_headers``)every configured header (lowercase names in *configured_header_names*) is stripped too — v1 forbidsdiff --git a/tools/mcp_tool_loop.py b/tools/mcp_tool_loop.pyindex 831ea81bb6d..ebe6730cf5b 100644--- a/tools/mcp_tool_loop.py+++ b/tools/mcp_tool_loop.py@@ -100,7 +100,7 @@ def _mcp_loop_exception_handler(loop, context):loop.default_exception_handler(context)-def _wrap_with_home_override(coro: "Coroutine") -> "Coroutine":+def _wrap_with_home_override(coro: Coroutine) -> Coroutine:"""Carry the caller's context-local HERMES_HOME override into ``coro`` (task-local on the MCPloop, so concurrent scopes don't interfere)."""try:diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.pyindex 4aa495d63ea..38ba2b7db79 100644--- a/tools/mcp_tool_registration.py+++ b/tools/mcp_tool_registration.py@@ -153,7 +153,7 @@ def _remove_server_scope(key, scope: str) -> None:_restore_server_toolset_alias(key)-def _select_utility_schemas(server_name: str, server: "MCPServerTask", config: dict) -> list[dict]:+def _select_utility_schemas(server_name: str, server: MCPServerTask, config: dict) -> list[dict]:"""Utility schemas allowed by config (``tools.resources``/``tools.prompts``) and advertisedcapabilities. ``initialize_result.capabilities`` is the truth (sub-object non-None iff thefamily is served); without it fall back to the legacy session-method check, which never@@ -367,7 +367,7 @@ def _register_candidates(name: str, candidates: list[_Candidate], *, check_fn: Creturn registered-def _write_schema_cache(name: str, server: "MCPServerTask", config: dict, should_register) -> None:+def _write_schema_cache(name: str, server: MCPServerTask, config: dict, should_register) -> None:"""Write-through: persist the manifest so the next startup registers this server lazily (no spawn). Never raises."""try:# Write-through (#56832): refresh the on-disk schema cache after a live connect so the next startup@@ -397,7 +397,7 @@ def _write_schema_cache(name: str, server: "MCPServerTask", config: dict, shouldlogger.debug("MCP schema cache write failed for '%s': %s", name, exc)-def _register_server_tools(name: str, server: "MCPServerTask", config: dict) -> list[str]:+def _register_server_tools(name: str, server: MCPServerTask, config: dict) -> list[str]:"""Register a connected server's tools plus utilities (initial discovery and list_changedrefresh); returns the names. Toolset aliases derive from the live registry, not``toolsets.TOOLSETS``; lossy normalization collisions (``read-file``/``read_file``) fail closed."""diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 9e74bd9da50..7fff1ccf41b 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -374,7 +374,7 @@ class MCPServerRunMixin:# Stale PIDs must never fast-fail the NEXT transport's calls.self._stdio_child_pids = set()- async def _on_clean_return(self, lifecycle_reason: str, budget: "_RetryBudget") -> bool:+ async def _on_clean_return(self, lifecycle_reason: str, budget: _RetryBudget) -> bool:"""Clean transport return: shutdown, stdio recycle, or a requested rebuild (not a failurefor the retry counters)."""if self._shutdown_event.is_set():@@ -415,7 +415,7 @@ class MCPServerRunMixin:self.session = Nonereturn True- async def _park_and_rearm(self, revival_reason: str, budget: "_RetryBudget") -> bool:+ async def _park_and_rearm(self, revival_reason: str, budget: _RetryBudget) -> bool:"""Park; on revival leave ONE probe per wake so a still-dead server re-parks instead ofburning 5 rapid retries. False on shutdown."""if await self._park(revival_reason):@@ -423,7 +423,7 @@ class MCPServerRunMixin:self._reconnect_retries, budget.backoff = _core._MAX_RECONNECT_RETRIES, 1.0return True- async def _park_initial_failure(self, exc: Exception, revival_reason: str, budget: "_RetryBudget") -> bool:+ async def _park_initial_failure(self, exc: Exception, revival_reason: str, budget: _RetryBudget) -> bool:"""Publish ``exc`` to ``start()``, park, and on revival reset every counter. False on shutdown."""self._publish_error(exc)if await self._park(revival_reason):@@ -434,11 +434,11 @@ class MCPServerRunMixin:self._ready.clear()return True- async def _backoff_sleep(self, budget: "_RetryBudget") -> None:+ async def _backoff_sleep(self, budget: _RetryBudget) -> None:await asyncio.sleep(_jittered(budget.backoff))budget.backoff = min(budget.backoff * 2, _core._MAX_BACKOFF_SECONDS)- async def _on_transport_error(self, exc: Exception, budget: "_RetryBudget") -> bool:+ async def _on_transport_error(self, exc: Exception, budget: _RetryBudget) -> bool:"""Transport raised: classify, then run the initial-connect or reconnect ladder. False = exit."""# Unwrap anyio TaskGroup wrappers: the group's str() hides the root cause.root = _errors._unwrap_exception_group(exc)@@ -477,7 +477,7 @@ class MCPServerRunMixin:return not self._shutdown_event.is_set()async def _on_initial_connect_error(self, exc: Exception, root: BaseException,- failure_class: str, budget: "_RetryBudget") -> bool:+ failure_class: str, budget: _RetryBudget) -> bool:if failure_class == "permanent":# Deterministic failure (bad command, non-MCP URL, 401/403): park at once; auth# failures park (not return) so the task can pick up fresh tokens later.@@ -503,7 +503,7 @@ class MCPServerRunMixin:self._publish_error(exc)return not self._shutdown_event.is_set()- async def _on_permanent_error(self, root: BaseException, budget: "_RetryBudget") -> bool:+ async def _on_permanent_error(self, root: BaseException, budget: _RetryBudget) -> bool:# Auth failure on a PROVEN session is often a raced-teardown OAuth lock, not revoked# credentials: grant ONE suspect+reconnect cycle first.if _errors._is_auth_error(root) and self._session_proven and not self._permanent_grace_used:diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex b0e4254f15e..a6e8a72258d 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -44,7 +44,7 @@ from tools.memory_tool_store import (ENTRY_DELIMITER, FAILURE_CLASS, MEMORY_BLOCK_HEADERS, MemoryStore, _scan_memory_content)-def load_on_disk_store() -> "MemoryStore":+def load_on_disk_store() -> MemoryStore:"""Fresh on-disk MemoryStore with configured limits/flags for contexts with no liveagent (gateway, Desktop, ``/memory``) so approvals enforce the SAME caps as``agent_init``. Falls back to defaults if config can't load; never raises."""@@ -61,7 +61,7 @@ def load_on_disk_store() -> "MemoryStore":return store-def _pin_matched_entries(store: "MemoryStore", payload: dict[str, Any]) -> Optional[str]:+def _pin_matched_entries(store: MemoryStore, payload: dict[str, Any]) -> Optional[str]:"""Record on each staged replace/remove the FULL entry its old_text selects now. Approvalthen applies to exactly the entry the approver reviewed and refuses if it changed:re-running the old_text search at approve time could hit a newer entry that still@@ -81,7 +81,7 @@ def _pin_matched_entries(store: "MemoryStore", payload: dict[str, Any]) -> Optioreturn None if result.get("success") else json.dumps(result, ensure_ascii=False)-def _gate_or_stage(store: "MemoryStore", summary: str, detail: str, payload: dict[str, Any]) -> Optional[str]:+def _gate_or_stage(store: MemoryStore, summary: str, detail: str, payload: dict[str, Any]) -> Optional[str]:"""JSON tool-result string when the write must NOT proceed (blocked or stagedfor approval), None to proceed. Fails open if the gate module can't load."""try:@@ -123,7 +123,7 @@ def _batch_op_line(op: dict[str, Any]) -> str:else f"- {act}: {content}")-def _apply_write_gate(store: "MemoryStore", action: str, target: str, content: Optional[str],+def _apply_write_gate(store: MemoryStore, action: str, target: str, content: Optional[str],old_text: Optional[str], operations: Optional[list[dict[str, Any]]] = None) -> Optional[str]:"""Gate one mutating op, or (``operations`` set) a whole batch as a single unit."""label = "user profile" if target == "user" else "memory"@@ -309,7 +309,7 @@ def check_memory_requirements() -> bool:return flags[0] or flags[1]-def _memory_target_error(store: "MemoryStore", target: str) -> Optional[dict[str, Any]]:+def _memory_target_error(store: MemoryStore, target: str) -> Optional[dict[str, Any]]:"""Return a shared validation error for an invalid or disabled target."""if target not in {"memory", "user"}:from tools.registry import _bound_error_text@@ -323,7 +323,7 @@ def _memory_target_error(store: "MemoryStore", target: str) -> Optional[dict[strreturn {"success": False, "error": f"Built-in {label} writes are disabled in memory config.", "target": target}-def apply_memory_pending(payload: dict[str, Any], store: "MemoryStore") -> dict[str, Any]:+def apply_memory_pending(payload: dict[str, Any], store: MemoryStore) -> dict[str, Any]:"""Replay a staged write against the store, bypassing the gate (/memory approve). Areplace/remove applies to exactly its pinned ``matched_entry`` or is refused; a recordstaged before pinning has no verifiable target, so it is refused rather than replayed bydiff --git a/tools/microsoft_graph_auth.py b/tools/microsoft_graph_auth.pyindex 538597dcf45..0acfbfd55b9 100644--- a/tools/microsoft_graph_auth.py+++ b/tools/microsoft_graph_auth.py@@ -56,7 +56,7 @@ class GraphCredentials:return f"{self.authority_url.rstrip('/')}/{self.tenant_id.strip().strip('/')}/oauth2/v2.0/token"@classmethod- def from_env(cls, environ: dict[str, str] | None = None, *, required: bool = True) -> "GraphCredentials | None":+ def from_env(cls, environ: dict[str, str] | None = None, *, required: bool = True) -> GraphCredentials | None:env = environ if environ is not None else os.environvalues = [(env.get(name) or "").strip() for name in _REQUIRED_ENV]missing = [name for name, value in zip(_REQUIRED_ENV, values) if not value]@@ -96,7 +96,7 @@ class MicrosoftGraphTokenProvider:self._lock = asyncio.Lock()@classmethod- def from_env(cls, environ: dict[str, str] | None = None, **kwargs: Any) -> "MicrosoftGraphTokenProvider":+ def from_env(cls, environ: dict[str, str] | None = None, **kwargs: Any) -> MicrosoftGraphTokenProvider:return cls(GraphCredentials.from_env(environ), **kwargs)def clear_cache(self) -> None:diff --git a/tools/plugin_guard_context.py b/tools/plugin_guard_context.pyindex 54ff6fba390..50872818a52 100644--- a/tools/plugin_guard_context.py+++ b/tools/plugin_guard_context.py@@ -259,7 +259,7 @@ def is_regex_alternation_token(finding: Finding, line: str) -> bool:spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]hits = list(token.finditer(line))- def inert(h: "re.Match[str]") -> bool:+ def inert(h: re.Match[str]) -> bool:if " " in h.group(0):return Falsespan = next(((a, b) for a, b in spans if a <= h.start() and h.end() <= b), None)@@ -320,7 +320,7 @@ def is_pip_install_in_prose_literal(finding: Finding, line: str) -> bool:spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]hits = list(_PIP_INSTALL_TOKEN.finditer(line))- def prose(h: "re.Match[str]") -> bool:+ def prose(h: re.Match[str]) -> bool:span = next(((a, b) for a, b in spans if a <= h.start() and h.end() <= b), None)if span is None:return False@@ -416,7 +416,7 @@ def is_json_prose_value(finding: Finding, rel_path: str, line: str) -> bool:if key is not None and not re.search(r"\s", key) and _JSON_COMMAND_KEY.search(key):return False- def prose(h: "re.Match[str]") -> bool:+ def prose(h: re.Match[str]) -> bool:part = next((g for g in ("k", "v") if m.start(g) <= h.start() and h.end() <= m.end(g)), None)return part is not None and _COMMAND_POSITION.search(line[m.start(part):h.start()]) is Nonediff --git a/tools/process_registry.py b/tools/process_registry.pyindex 285984fd472..2014d9fc47a 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -516,14 +516,14 @@ def _not_found(session_id: str) -> dict:return {"status": "not_found", "error": f"No process with ID {session_id}"}-def _output_tail(session: "ProcessSession", n: int) -> str:+def _output_tail(session: ProcessSession, n: int) -> str:"""Last *n* chars of the session output with ANSI sequences stripped."""from tools.ansi_strip import strip_ansireturn strip_ansi(session.output_buffer[-n:])-def _completion_output(session: "ProcessSession") -> dict:+def _completion_output(session: ProcessSession) -> dict:"""``output`` sized by the session's ``completion_output_chars`` plus ``output_cut`` when trimmed.Shared by the completion notification AND the wait/poll/kill snapshots: a bot in an api_server@@ -1857,7 +1857,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):def drain_notifications(self, session_key: str = "", owns_event=None, *, skip_poll_observed: bool = True,- ) -> "list[tuple[dict, str]]":+ ) -> list[tuple[dict, str]]:"""Pop all pending events and return ``(raw_event, formatted_text)`` pairs.Skips completions per ``_drain_should_skip`` (gateway/TUI pass``skip_poll_observed=False``). Routing (``_owns_event``): async-delegation events@@ -1867,11 +1867,11 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):equality; non-owned events are re-queued for their owner. No filter consumeseverything (legacy single-session) except restored delegation payloads (fail-closed)."""self.restore_completions()- results: "list[tuple[dict, str]]" = []- requeue: "list[dict]" = []+ results: list[tuple[dict, str]] = []+ requeue: list[dict] = []# delegation.surface_child_process_notifications, read at most once per drain# and only when an sa- event shows up.- surface_child: "bool | None" = None+ surface_child: bool | None = Nonewhile not self.completion_queue.empty():try:evt = self.completion_queue.get_nowait()@@ -1942,7 +1942,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):})return next(iter(matches.values())) if len(matches) == 1 else None- def _reconcile_local_exit(self, session: "ProcessSession") -> None:+ def _reconcile_local_exit(self, session: ProcessSession) -> None:"""Reconcile ``session.exited`` against the real child state.The reader flips ``exited`` only at EOF; when the direct child has exited but adescendant (e.g. a daemon from ``hermes update``) holds the pipe open, poll()diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex 4df4eee2897..c6274ecb4e6 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -67,7 +67,7 @@ def _format_age(seconds: float) -> str:return f"{h}h" + (f"{m}m" if m else "")-def _model_not_found_patterns() -> "list[str]":+def _model_not_found_patterns() -> list[str]:"""Model-not-found phrases from ``agent.error_classifier`` (the failover path'sown list, so nothing drifts); a minimal built-in set if the import fails.@@ -103,7 +103,7 @@ def _delegation_model_not_found(results, config) -> bool:return any(model in text and any(p in text for p in patterns) for text in texts)-def _delegation_model_not_found_notice(results) -> "list[str] | None":+def _delegation_model_not_found_notice(results) -> list[str] | None:"""Config-level model_not_found notice lines, or None (fail-open) — once per batch."""config = _delegation_config()if not _delegation_model_not_found(results, config):@@ -133,13 +133,13 @@ def _is_truncated(entry: dict) -> bool:return bool(entry.get("truncated") or entry.get("exit_reason") == "max_iterations")-def _notice_lines(results) -> "list[str]":+def _notice_lines(results) -> list[str]:"""Blank + model_not_found notice block, or [] when the notice does not apply."""notice = _delegation_model_not_found_notice(results)return ["", *notice] if notice else []-def _preamble(evt: dict, title: str, intro: str, completed_at: float, *, with_goal: bool) -> "list[str]":+def _preamble(evt: dict, title: str, intro: str, completed_at: float, *, with_goal: bool) -> list[str]:"""Shared preamble: title, intro, blank, dispatch time, [goal], context/toolsets, role+model."""lines = [title, intro, ""]dispatched_at = evt.get("dispatched_at")@@ -175,7 +175,7 @@ def _format_task_failure_notice(evt: dict, deleg_id: str) -> str:return "\n".join(line for line in lines if line)-def _recovery_lines(evt: dict) -> "list[str]":+def _recovery_lines(evt: dict) -> list[str]:"""Owner-died recovery diagnostics (``recover_abandoned_delegations``): last persistedstatus, per-task transcript paths, their verbatim tails and the owner's git state."""if not evt.get("last_known_status"):@@ -375,13 +375,13 @@ class TimelineNotification(str):return instance@classmethod- def for_delegation(cls, text: str, event: dict) -> "TimelineNotification":+ def for_delegation(cls, text: str, event: dict) -> TimelineNotification:from agent.notification_presentation import diagnostic_process_eventreturn cls(text, async_delegation_display_text(event), "async_delegation_complete","diagnostic" if diagnostic_process_event(event) else "result")-def _delegation_attribution_line(evt: dict) -> "str | None":+def _delegation_attribution_line(evt: dict) -> str | None:"""One-line provenance for a subagent-owned process event, else None. Such a processoutlives the child and lands in the PARENT conversation, which would otherwise see ananonymous output wall. Keyed on ``owner_task_id`` — ``task_id`` may be the session key."""@@ -408,7 +408,7 @@ def _completion_status(evt: dict) -> str:return _REASON_STATUS.get(reason) or ("completed normally" if evt.get("exit_code", "?") == 0 else "exited")-def format_process_notification(evt: dict) -> "str | None":+def format_process_notification(evt: dict) -> str | None:"""Format a completion_queue event into an ``[IMPORTANT: ...]`` message."""evt_type = evt.get("type", "completion")# watch_disabled and overflow events carry their own human-readable `message`;diff --git a/tools/process_registry_termination.py b/tools/process_registry_termination.pyindex 1778d8727c1..7f3ad385cdb 100644--- a/tools/process_registry_termination.py+++ b/tools/process_registry_termination.py@@ -146,7 +146,7 @@ class ProcessTerminationMixin:# escalated kill as incomplete._KILL_SETTLE_SECONDS = 1.0- def _post_kill_survivors(self, session: "ProcessSession") -> list[int]:+ def _post_kill_survivors(self, session: ProcessSession) -> list[int]:"""Host PIDs still alive once the kill signals have had time to land (#115490).Fail-closed: anything unverifiable counts as a survivor, so a kill@@ -160,7 +160,7 @@ class ProcessTerminationMixin:return survivorstime.sleep(0.05)- def _probe_survivors(self, session: "ProcessSession") -> list[int]:+ def _probe_survivors(self, session: ProcessSession) -> list[int]:survivors: list[int] = []proc = getattr(session, "process", None)if proc is not None:diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.pyindex a7b58892636..7b3c8283381 100644--- a/tools/skill_manager_guards.py+++ b/tools/skill_manager_guards.py@@ -48,7 +48,7 @@ class _BackgroundReviewReadMarks:return path in self._paths-_background_review_read_paths: "_ctxvars.ContextVar[Optional[_BackgroundReviewReadMarks]]" = (+_background_review_read_paths: _ctxvars.ContextVar[Optional[_BackgroundReviewReadMarks]] = (_ctxvars.ContextVar("background_review_read_paths", default=None))diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex eee8c452e46..8d4d4ef375c 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -647,7 +647,7 @@ def _remove_file(name: str, file_path: str) -> dict[str, Any]:# --- Main entry point ---------------------------------------------------------# Set while replaying an approved staged skill write so skill_manage() does not re-gate it.-_skill_gate_bypass: "_ctxvars.ContextVar[bool]" = _ctxvars.ContextVar(+_skill_gate_bypass: _ctxvars.ContextVar[bool] = _ctxvars.ContextVar("skill_gate_bypass", default=False)diff --git a/tools/skills_sync.py b/tools/skills_sync.pyindex 396d8898747..fef59d04a48 100644--- a/tools/skills_sync.py+++ b/tools/skills_sync.py@@ -222,7 +222,7 @@ def _copy_dir(src: Path, dest: Path) -> None:shutil.copytree(src, dest, ignore=_ignore_runtime_cache)-def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Optional[str]:+def _recover_renamed_skill(st: _SyncState, skill_name: str, dest: Path) -> Optional[str]:"""Move a bundled skill's stale copy to its new canonical path after an upstream RENAME /RECATEGORIZATION (else it is misread as user-deleted and stranded forever). Only a copybyte-identical to the origin hash — proof *we* placed it — moves. Returns rel source path."""diff --git a/tools/terminal_scope.py b/tools/terminal_scope.pyindex 9b80ac3bdde..6b5b707ad45 100644--- a/tools/terminal_scope.py+++ b/tools/terminal_scope.py@@ -87,7 +87,7 @@ def terminal_env(name: str, default: str = "") -> str:def build_profile_terminal_scope(- hermes_home: "Any", *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:+ hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <- *env_overlay*@@ -194,7 +194,7 @@ def _resolve_scope_cwd_placeholder(scope: dict[str, str]) -> None:def install_profile_terminal_scope(- hermes_home: "Any", *, env_overlay: Optional[dict[str, str]] = None) -> Token:+ hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> Token:"""Build AND install a profile's policy; on failure install the refusal scope. Never raises."""try:return set_terminal_scope(build_profile_terminal_scope(hermes_home, env_overlay=env_overlay))@@ -204,7 +204,7 @@ def install_profile_terminal_scope(@contextmanager-def install_and_reset_profile_terminal_scope(hermes_home: "Any") -> Iterator[None]:+def install_and_reset_profile_terminal_scope(hermes_home: Any) -> Iterator[None]:"""Install the profile's terminal policy for a bounded turn/fire. Never raises."""token = install_profile_terminal_scope(hermes_home)try:diff --git a/tools/tool_search.py b/tools/tool_search.pyindex 3c52c3ae342..ba594578f8c 100644--- a/tools/tool_search.py+++ b/tools/tool_search.py@@ -57,7 +57,7 @@ class ToolSearchConfig:return _DEFAULT_DEFERRED_TOOLS if self.defer_tools is None else self.defer_tools@classmethod- def from_raw(cls, raw: Any) -> "ToolSearchConfig":+ def from_raw(cls, raw: Any) -> ToolSearchConfig:"""Build from a raw dict / legacy bool / None; every field is clamped and unknownvalues fall back to safe defaults — a config typo must not break the agent."""if not isinstance(raw, dict): # legacy bool / Nonediff --git a/tools/transcription_common.py b/tools/transcription_common.pyindex f78cfac6e18..b5e96c74a80 100644--- a/tools/transcription_common.py+++ b/tools/transcription_common.py@@ -108,7 +108,7 @@ def _lazy_ensure_quietly(extra: str) -> None:pass-def _process_error_detail(exc: "subprocess.CalledProcessError") -> str:+def _process_error_detail(exc: subprocess.CalledProcessError) -> str:"""stderr > stdout > str(exc) for a failed helper binary."""for output in (exc.stderr, exc.stdout):if isinstance(output, bytes):diff --git a/tools/transcription_streaming.py b/tools/transcription_streaming.pyindex c25fddf3666..e29e9c567ef 100644--- a/tools/transcription_streaming.py+++ b/tools/transcription_streaming.py@@ -91,7 +91,7 @@ class StreamingSession:def __init__(self, on_partial: Optional[PartialCallback] = None) -> None:self._on_partial = on_partial- self._audio: "queue.Queue[Optional[bytes]]" = queue.Queue()+ self._audio: queue.Queue[Optional[bytes]] = queue.Queue()self._done = threading.Event()self._cancelled = threading.Event()self._result: dict[str, Any] = {}@@ -116,7 +116,7 @@ class StreamingSession:return chunk# ── caller API ──- def start(self) -> "StreamingSession":+ def start(self) -> StreamingSession:# copy_context: a plugin session reads secrets from the opener's profile scope.ctx = contextvars.copy_context()self._worker = threading.Thread(target=ctx.run, args=(self._run,), name=f"stt-stream-{self.provider}",diff --git a/tools/tts_command_provider.py b/tools/tts_command_provider.pyindex 56bb2f9089f..ea85f381d81 100644--- a/tools/tts_command_provider.py+++ b/tools/tts_command_provider.py@@ -180,7 +180,7 @@ def run_command_provider(proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,text=True, encoding="utf-8", errors="replace", env=delegated_child_subprocess_env(scrubbed),stdin=subprocess.DEVNULL, **group)- output_queue: "queue.Queue[tuple[str, Optional[str]]]" = queue.Queue()+ output_queue: queue.Queue[tuple[str, Optional[str]]] = queue.Queue()chunks: dict[str, list[str]] = {"stdout": [], "stderr": []}open_streams = {"stdout", "stderr"}diff --git a/tools/tts_streaming.py b/tools/tts_streaming.pyindex 396d3612395..af9ccf7b846 100644--- a/tools/tts_streaming.py+++ b/tools/tts_streaming.py@@ -82,7 +82,7 @@ class SentenceChunker:self.buf = ""@classmethod- def from_config(cls, tts_config: dict) -> "SentenceChunker":+ def from_config(cls, tts_config: dict) -> SentenceChunker:"""Chunker honouring ``tts.streaming.min_len``. 20 suits English; a CJK opener of 5–7characters is a whole clause, so voice setups lower it to speak the first sentencealone instead of buffering it behind the second. Floor 1: 0 would emit every boundary."""@@ -446,7 +446,7 @@ class XAIStreamer(StreamingTTSProvider):import threadingfrom contextvars import copy_context- q: "queue.Queue[object]" = queue.Queue(maxsize=_XAI_QUEUE_MAX)+ q: queue.Queue[object] = queue.Queue(maxsize=_XAI_QUEUE_MAX)done = object()stop = threading.Event()diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex 355e114371c..2c058e54996 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -69,7 +69,7 @@ def _play_via_tempfile(audio_iter: Iterable[bytes], stop_evt: threading.Event, s_unlink_quietly(tmp_path)-def _drain_chunks(chunk_queue: "queue.Queue[Optional[bytes]]") -> list[bytes]:+def _drain_chunks(chunk_queue: queue.Queue[Optional[bytes]]) -> list[bytes]:"""Collect one sentence's PCM chunks up to the ``None`` sentinel."""return list(iter(chunk_queue.get, None))@@ -107,7 +107,7 @@ class _SyncSentencePipeline:def __init__(self, stop_event: threading.Event, *, lookahead: int = 2):self._stop = stop_event- self._queue: "queue.Queue[Optional[tuple[str, Future]]]" = queue.Queue(maxsize=max(1, lookahead))+ self._queue: queue.Queue[Optional[tuple[str, Future]]] = queue.Queue(maxsize=max(1, lookahead))self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="tts-sync-synth")self._player = threading.Thread(target=self._drain, name="tts-sync-play", daemon=True)self._player.start()@@ -172,7 +172,7 @@ class _StreamerPlayback:# ``streamer.sample_rate`` is only trustworthy after the request answered (#76466).self.output_stream = Noneself._use_device = self._device_usable()- self._audio_queue: "queue.Queue[Optional[queue.Queue[Optional[bytes]]]]" = queue.Queue()+ self._audio_queue: queue.Queue[Optional[queue.Queue[Optional[bytes]]]] = queue.Queue()self._prefetch_threads: list[threading.Thread] = []self._prefetch_sem = threading.Semaphore(3)self._worker = threading.Thread(target=self._playback_worker, daemon=True)@@ -230,13 +230,13 @@ class _StreamerPlayback:logger.warning("Streaming TTS synthesis failed: %s", exc)returnself._prefetch_sem.acquire()- chunk_queue: "queue.Queue[Optional[bytes]]" = queue.Queue(maxsize=self._CHUNK_QUEUE_MAX)+ chunk_queue: queue.Queue[Optional[bytes]] = queue.Queue(maxsize=self._CHUNK_QUEUE_MAX)self._audio_queue.put(chunk_queue)self._prefetch_threads.append(threading.Thread(target=self._consume_to_queue, args=(audio_iter, chunk_queue), daemon=True))self._prefetch_threads[-1].start()- def _consume_to_queue(self, audio_iter: Iterator[bytes], chunk_queue: "queue.Queue[Optional[bytes]]") -> None:+ def _consume_to_queue(self, audio_iter: Iterator[bytes], chunk_queue: queue.Queue[Optional[bytes]]) -> None:try:for chunk in audio_iter:if self.stop_event.is_set():diff --git a/tools/voice_mode.py b/tools/voice_mode.pyindex 8940d031c16..d1d6323aacb 100644--- a/tools/voice_mode.py+++ b/tools/voice_mode.py@@ -448,7 +448,7 @@ def thinking_sound_enabled() -> bool:return True-def _synth_thinking_blip(np, frequency: float) -> "Any":+def _synth_thinking_blip(np, frequency: float) -> Any:"""One soft 'blub': short sine with a downward glide and a click-free envelope."""duration = 0.16n = int(SAMPLE_RATE * duration)@@ -1187,7 +1187,7 @@ def listen_for_speech(# from the opening TTS passage, but later louder passages exceed the# stale floor and false-trigger. The rolling window keeps the floor# current so only genuinely louder-than-playback speech trips the VAD.- floor_window: "deque[float]" = deque(maxlen=max(calib_blocks, 100)) # ~3s rolling+ floor_window: deque[float] = deque(maxlen=max(calib_blocks, 100)) # ~3s rollingpre_roll: deque = deque(maxlen=max(1, pre_roll_ms // 30))consecutive = 0min_floor = 0.0 # baseline from initial calibration; floor never drops below thisdiff --git a/tools/wake_word.py b/tools/wake_word.pyindex dd2a0efd379..4db2cf658fd 100644--- a/tools/wake_word.py+++ b/tools/wake_word.py@@ -496,7 +496,7 @@ class WakeWordDetector:once and kept across pause/resume — only the stream + reader thread cycle, so mic toggles are cheap."""def __init__(self, engine: _Engine, on_wake: Callable[[], None], cooldown: float = _FIRE_COOLDOWN_SECONDS,- on_failure: Optional[Callable[["WakeWordDetector"], None]] = None,+ on_failure: Optional[Callable[[WakeWordDetector], None]] = None,input_device: int | str | None = None, external_audio: bool = False):self.engine, self.on_wake, self.cooldown, self.on_failure = engine, on_wake, cooldown, on_failureself.input_device, self.external_audio = input_device, bool(external_audio)@@ -510,7 +510,7 @@ class WakeWordDetector:self._stop, self._callback_inflight = threading.Event(), threading.Event()self._lock, self._last_fire = threading.Lock(), 0.0# Client-capture PCM queue (int16 mono frames). Local mode ignores this.- self._audio_q: "queue.Queue[Any]" = queue.Queue(maxsize=64)+ self._audio_q: queue.Queue[Any] = queue.Queue(maxsize=64)# True when the stream is open but every frame is (near-)silence, so status# surfaces can tell "armed" from "deaf".self.audio_silent, self._silent_frames = False, 0diff --git a/tools/web_tools_truncate.py b/tools/web_tools_truncate.pyindex cc456814a3e..d3596ba659b 100644--- a/tools/web_tools_truncate.py+++ b/tools/web_tools_truncate.py@@ -48,7 +48,7 @@ def convert_base64_images_to_links(text: str) -> str:"""Replace inline base64 image blobs (token bombs) with ``[IMAGE: alt]`` placeholders: markdown images(alt kept), parenthesised blobs, and bare ``data:image/...;base64,`` payloads. Real http(s) markdownimage links are left untouched so the agent can ``web_extract`` / ``vision_analyze`` them."""- def _md_repl(m: "re.Match[str]") -> str:+ def _md_repl(m: re.Match[str]) -> str:return f"[IMAGE: {alt}]" if (alt := (m.group("alt") or "").strip()) else "[IMAGE]"out = re.sub(r"!\[(?P<alt>[^\]]*)\]\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)", _md_repl, text)diff --git a/trajectory_compressor.py b/trajectory_compressor.pyindex 9675aa82590..41741f2544c 100644--- a/trajectory_compressor.py+++ b/trajectory_compressor.py@@ -134,7 +134,7 @@ class CompressionConfig:metrics_output_file: str = "compression_metrics.json"@classmethod- def from_yaml(cls, yaml_path: str) -> "CompressionConfig":+ def from_yaml(cls, yaml_path: str) -> CompressionConfig:"""Load configuration from YAML file (missing keys keep the defaults)."""with open(yaml_path, 'r', encoding="utf-8") as f:data = yaml.safe_load(f) or {}diff --git a/tui_gateway/entry.py b/tui_gateway/entry.pyindex b09f0acb3e0..6f7c2d23e99 100644--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@ -175,7 +175,7 @@ def _log_exit(reason: str) -> None:print(f"[gateway-exit] {reason}", file=sys.stderr, flush=True)-def wait_for_mcp_discovery(timeout: "float | None" = None) -> None:+def wait_for_mcp_discovery(timeout: float | None = None) -> None:"""Block until background MCP discovery finishes, up to the resolved bound (config``mcp_discovery_timeout``; ``timeout`` overrides). The agent snapshots its tool list ONCEat build time, so this bounded join lets already-spawning servers land."""diff --git a/tui_gateway/event_replay.py b/tui_gateway/event_replay.pyindex c5dac701896..f0b6aa0f8ce 100644--- a/tui_gateway/event_replay.py+++ b/tui_gateway/event_replay.py@@ -38,7 +38,7 @@ _replay_lock = threading.Lock()# sid -> deque of (seq, frozen params JSON bytes without the server-owned seq, retained bytes).# Bytes detach the replay ring from the live event object: later caller mutation cannot grow or# rewrite an already-accounted cache entry.-_replay_buffers: "OrderedDict[str, deque]" = OrderedDict()+_replay_buffers: OrderedDict[str, deque] = OrderedDict()_replay_buffer_bytes: dict[str, int] = {}_replay_evicted_through: dict[str, int] = {}_replay_total_bytes = 0diff --git a/tui_gateway/launch_profile_policy.py b/tui_gateway/launch_profile_policy.pyindex 3b2fb06b3c4..59e9cd26fab 100644--- a/tui_gateway/launch_profile_policy.py+++ b/tui_gateway/launch_profile_policy.py@@ -126,7 +126,7 @@ def launch_terminal_env() -> dict[str, str]:return {k: v for k, v in capture_launch_env().items() if k.startswith("TERMINAL_")}-def launch_secret_scope(launch_home: "str | Path") -> dict[str, str]:+def launch_secret_scope(launch_home: str | Path) -> dict[str, str]:"""The launch profile's secret mapping: its ``.env`` + external sources over the launch env(systemd / ``op run`` injection survives the fail-closed flip; a secondary never sees it becauseits scope is built from its own files only). Bound for EVERY launch-profile body, multiplexing or@@ -149,7 +149,7 @@ def launch_secret_scope(launch_home: "str | Path") -> dict[str, str]:@contextlib.contextmanager-def launch_profile_runtime_scope(launch_home: "str | Path") -> Iterator[None]:+def launch_profile_runtime_scope(launch_home: str | Path) -> Iterator[None]:"""Bind the launch profile's own runtime scope for one body: HERMES_HOME override naming thelaunch home, ``launch_secret_scope``, and its terminal policy over the frozen launch``TERMINAL_*`` overlay. For hosts whose launch-profile bodies are not RPC sessions (thediff --git a/tui_gateway/mcp_oauth_sessions.py b/tui_gateway/mcp_oauth_sessions.pyindex 9cf0c103b49..a479880f19b 100644--- a/tui_gateway/mcp_oauth_sessions.py+++ b/tui_gateway/mcp_oauth_sessions.py@@ -114,7 +114,7 @@ def start_flow(def _lookup(session_id: str, server_name: str, hermes_home: Optional[str] = None,-) -> "tuple[dict[str, Any] | None, str | None]":+) -> tuple[dict[str, Any] | None, str | None]:"""Find a session belonging to the caller's resolved profile."""from hermes_constants import hermes_home_keywith _sessions_lock:diff --git a/tui_gateway/methods_display.py b/tui_gateway/methods_display.pyindex 9b7c780fb06..7cca148ee32 100644--- a/tui_gateway/methods_display.py+++ b/tui_gateway/methods_display.py@@ -111,7 +111,7 @@ def _(rid, params: dict) -> dict:# viewer ids minted per connection (keyed by the transport that asked), so a reconnecting pane can# keep its identity — and its lease — while nobody can claim an id minted for another connection.-_minted_viewer_ids: "weakref.WeakKeyDictionary[object, set[str]]" = weakref.WeakKeyDictionary()+_minted_viewer_ids: weakref.WeakKeyDictionary[object, set[str]] = weakref.WeakKeyDictionary()# Transports that cannot be weakly referenced (stdio, slotted, or none bound at all) are one# connection per process — the TUI's own pipe — so their minted ids share one process-wide set._unweakable_minted_ids: set[str] = set()diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex ab4009eb051..c6ad4348ba1 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -199,7 +199,7 @@ def _capture_run_kwargs(timeout: int) -> dict:def _captured_exec(rid, cmd, timeout: int, *, on_result, timeout_err: tuple, fail_code: int,- shell: bool = False, env: "dict | None" = None) -> dict:+ shell: bool = False, env: dict | None = None) -> dict:"""Run ``cmd`` captured (see ``_capture_run_kwargs``) and hand the CompletedProcess to``on_result``; TimeoutExpired → ``timeout_err`` (code, message), other errors → ``fail_code``."""try:diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.pyindex 28a7d28afa8..49803cdb5b1 100644--- a/tui_gateway/methods_voice.py+++ b/tui_gateway/methods_voice.py@@ -18,7 +18,7 @@ method = _registry.method_voice_sid_lock = threading.Lock()_voice_event_sid: str = ""-_voice_wake_owner: "Optional[Transport]" = None+_voice_wake_owner: Optional[Transport] = Nonedef _caller_transport():@@ -142,7 +142,7 @@ def _tts_stream_stop(user_barge: bool = True) -> None:_fd_listener_lock = threading.Lock()_fd_listener_active = False-_fd_speak_pipelines: "set[tuple[threading.Event, threading.Event]]" = set()+_fd_speak_pipelines: set[tuple[threading.Event, threading.Event]] = set()def _arm_full_duplex_listener() -> None:@@ -311,7 +311,7 @@ def _voice_status_payload(**extra) -> dict:# wake.detected and the client opens a session + its own capture. The detector yields the mic# to voice.record (pause/resume) and to the desktop's browser mic (wake.pause/resume RPCs)._wake_lock = threading.Lock()-_wake_owner_transport: "Optional[Transport]" = None+_wake_owner_transport: Optional[Transport] = None_wake_owner_surface = ""@@ -320,7 +320,7 @@ def _wake_owner_snapshot():return _wake_owner_transport, _wake_owner_surface-def _release_wake_for_transport(transport: "Transport") -> bool:+def _release_wake_for_transport(transport: Transport) -> bool:"""Release the wake lease iff ``transport`` is the current gateway owner."""global _wake_owner_transport, _wake_owner_surfacewith _wake_lock:@@ -344,7 +344,7 @@ _wake_resume_retry_lock = threading.Lock()_wake_resume_retry_active = False-def _wake_resume_if_owner(owner: "Transport", *, retry_seconds: float = 15.0,+def _wake_resume_if_owner(owner: Transport, *, retry_seconds: float = 15.0,retry_interval: float = 1.0) -> bool:"""Resume the wake detector for ``owner``, self-healing a busy microphone: reopening right aftera voice turn can fail while the device is still being released (browser WebRTC tracks releasediff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.pyindex e521e7450c7..bf76f39e051 100644--- a/tui_gateway/model_switch.py+++ b/tui_gateway/model_switch.py@@ -51,7 +51,7 @@ def _restore_agent_model_runtime(agent, snapshot: dict | None) -> None:agent.reasoning_config = snapshot["reasoning_config"]-def _profile_runtime_scope_tokens(profile_home, *, hydrate_secrets: bool = True) -> "_TurnScopes":+def _profile_runtime_scope_tokens(profile_home, *, hydrate_secrets: bool = True) -> _TurnScopes:"""Bind HERMES_HOME + secret + terminal scope for ``profile_home`` (None = launch profile) andreturn the reset tokens. The launch profile's SECRET scope is always bound — its ``.env`` overthe launch env (live while single-profile, frozen at activation afterwards; never live@@ -109,7 +109,7 @@ def _profile_runtime_scope_tokens(profile_home, *, hydrate_secrets: bool = True)raise-def _release_profile_runtime_scope_tokens(scopes: "_TurnScopes | None") -> None:+def _release_profile_runtime_scope_tokens(scopes: _TurnScopes | None) -> None:"""Release terminal → secret → home. Each reset is independent: a failing terminal reset mustnot leave the previous profile's secrets / HERMES_HOME installed for the next body in thiscontext (a fail-open scope leak on the teardown path). The first failure is re-raised afterdiff --git a/tui_gateway/profile_roster_cache.py b/tui_gateway/profile_roster_cache.pyindex ccdfe2c8e2e..557867487b5 100644--- a/tui_gateway/profile_roster_cache.py+++ b/tui_gateway/profile_roster_cache.py@@ -62,7 +62,7 @@ def _cached(cache: dict, key: str, signature: Optional[tuple], compute: Callablereturn fields-def store_signature(profile_path: "str | Path") -> Optional[tuple]:+def store_signature(profile_path: str | Path) -> Optional[tuple]:"""``(name, mtime_ns, size)`` per session-store file, or None when the profile has no store.The pair the change watcher already trusts for ``sessions.changed``.@@ -74,17 +74,17 @@ def store_signature(profile_path: "str | Path") -> Optional[tuple]:return tuple(p for p in parts if not (p[0].endswith("-wal") and p[2] == 0)) or None-def profile_yaml_signature(profile_dir: "str | Path") -> Optional[tuple]:+def profile_yaml_signature(profile_dir: str | Path) -> Optional[tuple]:"""``(name, mtime_ns, size, inode)`` of the profile's ``profile.yaml``, or None when absent."""return _file_parts(Path(profile_dir) / "profile.yaml", with_inode=True)-def cached_session_fields(profile_path: "str | Path", compute: Callable[[], dict]) -> dict[str, Any]:+def cached_session_fields(profile_path: str | Path, compute: Callable[[], dict]) -> dict[str, Any]:"""``compute()``'s fields, reused while the profile's session store has not moved."""return _cached(_SESSION_CACHE, str(profile_path), store_signature(profile_path), compute, dict)-def cached_ui_meta_fields(profile_dir: "str | Path", compute: Callable[[], dict]) -> dict[str, Any]:+def cached_ui_meta_fields(profile_dir: str | Path, compute: Callable[[], dict]) -> dict[str, Any]:"""``compute()``'s fields, reused while the profile's ``profile.yaml`` has not changed.Copied deeply: ``ui_meta`` is a nested mapping the caller hands to a client.@@ -93,7 +93,7 @@ def cached_ui_meta_fields(profile_dir: "str | Path", compute: Callable[[], dict]compute, copy.deepcopy)-def invalidate(profile_path: "str | Path | None" = None) -> None:+def invalidate(profile_path: str | Path | None = None) -> None:"""Drop one profile's memos, or all of them. For tests and for a caller that knows better."""for cache in (_SESSION_CACHE, _UI_META_CACHE):if profile_path is None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 84c15554c4c..b196ab1e54e 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1002,7 +1002,7 @@ def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:return _err(rid, 5032, err) if (err := session.get("agent_error")) else None-def _bind_build_profile_scopes(profile_home: "str | None") -> "_TurnScopes | None":+def _bind_build_profile_scopes(profile_home: str | None) -> _TurnScopes | None:"""Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. ``None`` is thelaunch profile: its own launch-env secret scope (live env while single-profile, frozen oncemultiplexing is active — a hosted-room turn for a default member otherwise died at build with@@ -1020,7 +1020,7 @@ def _bind_build_profile_scopes(profile_home: "str | None") -> "_TurnScopes | Nonreturn scopes-def _release_build_profile_scopes(scopes: "_TurnScopes | None") -> None:+def _release_build_profile_scopes(scopes: _TurnScopes | None) -> None:with contextlib.suppress(Exception):_release_profile_runtime_scope_tokens(scopes)diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.pyindex 781f6cf0bef..a4624d2d885 100644--- a/tui_gateway/slash_worker.py+++ b/tui_gateway/slash_worker.py@@ -112,7 +112,7 @@ def _refuse_skill_slash(command: str) -> None:raise SkillSlashRefused(base)-def _run(cli: "HermesCLI", command: str) -> str:+def _run(cli: HermesCLI, command: str) -> str:"""Run one command; return its captured, ANSI-stripped output.A command like /prompt or /blueprint parks the composed text on the one-shotdiff --git a/tui_gateway/transport.py b/tui_gateway/transport.pyindex 5216b4dbdf7..8e9a54946fe 100644--- a/tui_gateway/transport.py+++ b/tui_gateway/transport.py@@ -290,7 +290,7 @@ class TeeTransport:__slots__ = ("_primary", "_secondaries")- def __init__(self, primary: "Transport", *secondaries: "Transport") -> None:+ def __init__(self, primary: Transport, *secondaries: Transport) -> None:self._primary = primaryself._secondaries = secondariesdiff --git a/utils.py b/utils.pyindex 10c090ef91e..840def42736 100644--- a/utils.py+++ b/utils.py@@ -37,7 +37,7 @@ def env_var_enabled(name: str, default: str = "") -> bool:return is_truthy_value(os.getenv(name, default), default=False)-def file_signature(st: os.stat_result) -> "tuple[int, int, int, int]":+def file_signature(st: os.stat_result) -> tuple[int, int, int, int]:"""Change-detection key for a stat result: ``(st_mtime_ns, st_size, st_ino, st_ctime_ns)``.mtime + size alone miss a replacement that preserves both (``cp -p``, ``rsync -t``, a tar@@ -49,7 +49,7 @@ def file_signature(st: os.stat_result) -> "tuple[int, int, int, int]":return (st.st_mtime_ns, st.st_size, st.st_ino, st.st_ctime_ns)-def _preserve_file_mode(path: Path) -> "int | None":+def _preserve_file_mode(path: Path) -> int | None:"""Permission bits of *path* if it exists, else ``None``."""try:return stat.S_IMODE(path.stat().st_mode) if path.exists() else None@@ -57,7 +57,7 @@ def _preserve_file_mode(path: Path) -> "int | None":return None-def _preserve_file_owner(path: Path) -> "tuple[int, int] | None":+def _preserve_file_owner(path: Path) -> tuple[int, int] | None:"""Owning ``(uid, gid)`` of *path* on POSIX, else ``None``."""try:st = path.stat() if os.name == "posix" else None@@ -66,7 +66,7 @@ def _preserve_file_owner(path: Path) -> "tuple[int, int] | None":return (st.st_uid, st.st_gid) if st else None-def _restore_file_metadata(path: Path, owner: "tuple[int, int] | None", mode: "int | None") -> None:+def _restore_file_metadata(path: Path, owner: tuple[int, int] | None, mode: int | None) -> None:"""Best-effort re-apply of uid/gid and permission bits after an atomic replace.Docker/NAS installs often run some commands as root on a volume owned by the runtime user;@@ -82,7 +82,7 @@ def _restore_file_metadata(path: Path, owner: "tuple[int, int] | None", mode: "ios.chmod(path, mode)-def default_new_file_mode() -> "int | None":+def default_new_file_mode() -> int | None:"""The mode ``open(path, "w")`` gives a file it has to create (``0o666 & ~umask``); ``None``when the umask cannot be read or on non-POSIX hosts (Windows mode bits are synthesized).@@ -101,11 +101,11 @@ def default_new_file_mode() -> "int | None":return 0o666 & ~current-def _restore_file_owner(path: Path, owner: "tuple[int, int] | None") -> None:+def _restore_file_owner(path: Path, owner: tuple[int, int] | None) -> None:_restore_file_metadata(path, owner, None)-def _restore_file_mode(path: Path, mode: "int | None") -> None:+def _restore_file_mode(path: Path, mode: int | None) -> None:_restore_file_metadata(path, None, mode)@@ -287,7 +287,7 @@ def rmtree_readonly(path: str | Path, *, ignore_errors: bool = False) -> None:raise-def _atomic_write(path: Path, write, *, prefix: str, encoding: str = "utf-8", mode: "int | None" = None,+def _atomic_write(path: Path, write, *, prefix: str, encoding: str = "utf-8", mode: int | None = None,preserve_owner: bool = True, binary: bool = False, fsync_dir: bool = False) -> None:"""Temp file + fsync + :func:`atomic_replace`, then re-apply owner/mode.@@ -330,14 +330,14 @@ def _atomic_write(path: Path, write, *, prefix: str, encoding: str = "utf-8", moraise-def _mode_for_write(path: Path, create_mode: "int | None", preserve: bool = True) -> "int | None":+def _mode_for_write(path: Path, create_mode: int | None, preserve: bool = True) -> int | None:"""Existing permission bits of *path* (when *preserve*), else *create_mode* for a new file."""mode = _preserve_file_mode(path) if preserve else Nonereturn mode if mode is not None or path.exists() else create_modedef atomic_write_text(path: str | Path, content: str, *, encoding: str = "utf-8", tmp_prefix: str = ".tmp_",- preserve_mode: bool = False, create_mode: "int | None" = None, mode: "int | None" = None,+ preserve_mode: bool = False, create_mode: int | None = None, mode: int | None = None,fsync_dir: bool = False) -> None:"""Write *content* to *path* via temp file + fsync + atomic rename.@@ -353,14 +353,14 @@ def atomic_write_text(path: str | Path, content: str, *, encoding: str = "utf-8"def atomic_write_bytes(path: str | Path, content: bytes, *, tmp_prefix: str = ".tmp_",- mode: "int | None" = None, fsync_dir: bool = False) -> None:+ mode: int | None = None, fsync_dir: bool = False) -> None:"""Bytes variant of :func:`atomic_write_text` (encrypted blobs, key material)."""path = Path(path)_atomic_write(path, lambda f: f.write(content), prefix=tmp_prefix, binary=True, preserve_owner=False,mode=mode if mode is not None else _preserve_file_mode(path), fsync_dir=fsync_dir)-def _dump_json(data: Any, f, *, indent: "int | None", ensure_ascii: bool, dump_kwargs: dict) -> None:+def _dump_json(data: Any, f, *, indent: int | None, ensure_ascii: bool, dump_kwargs: dict) -> None:"""``json.dump`` that survives surrogate-escaped strings.``os.fsdecode`` of a non-UTF-8 filename/argv yields lone surrogates (``'\\udcff'``); a utf-8@@ -427,7 +427,7 @@ def warn_if_credential_file_broadly_readable(path: str | Path, *, label: str = "def atomic_yaml_write(path: str | Path, data: Any, *, default_flow_style: bool = False, sort_keys: bool = False,- extra_content: str | None = None, create_mode: "int | None" = None) -> None:+ extra_content: str | None = None, create_mode: int | None = None) -> None:"""Write YAML to *path* atomically (temp file + fsync + replace)."""path = Path(path)@@ -449,7 +449,7 @@ def _roundtrip_load(path: Path):return yaml_rt, data if isinstance(data, CommentedMap) else CommentedMap(data or {})-def _roundtrip_dump(path: Path, yaml_rt, config, *, extra_content: "str | None" = None) -> None:+def _roundtrip_dump(path: Path, yaml_rt, config, *, extra_content: str | None = None) -> None:def _write(f) -> None:yaml_rt.dump(config, f)if extra_content:@@ -527,7 +527,7 @@ def _rt_value(value: Any) -> Any:def atomic_roundtrip_yaml_save(path: str | Path, new_state: dict, *,- extra_content_on_create: "str | None" = None) -> None:+ extra_content_on_create: str | None = None) -> None:"""Persist a full config-state dict while preserving comments and ordering.THE on-disk primitive for ``config.yaml`` (production callers reach it through