The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: UP007, UP022, UP028, UP031, UP041 linter fixes
Maciej Lisiewskiaff64c3eebe9
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex edab7a47f52..7c5471a3ddd 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2295,7 +2295,7 @@ def _warn_paid_lane_once(model: str) -> None:)-def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None, model: str | None = None,+def _try_openrouter(explicit_api_key: Optional[str | Callable[[], str]] = None, model: str | None = None,explicit_base_url: Optional[str] = None) -> tuple[Optional[OpenAI], Optional[str]]:free_only, cfg_model = _aux_openrouter_settings()or_model = model or cfg_model@@ -2502,7 +2502,7 @@ def _read_main_model_for_aux() -> str:return model-def _read_main_api_key_if_same_origin(aux_base_url: str) -> Union[str, Callable[[], str]]:+def _read_main_api_key_if_same_origin(aux_base_url: str) -> str | Callable[[], str]:"""Main api_key only when *aux_base_url* has the main base_url's exact origin.Unconditional inheritance would leak the credential to any misconfigured host; mismatch keeps ``no-key-required`` → 401.@@ -3038,7 +3038,7 @@ def _try_azure_foundry(return client, final_model-def _try_anthropic(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None,+def _try_anthropic(explicit_api_key: Optional[str | Callable[[], str]] = None,explicit_base_url: Optional[str] = None) -> tuple[Optional[Any], Optional[str]]:try:from agent.anthropic_adapter import build_anthropic_client@@ -4884,7 +4884,7 @@ class _ResolveRequest(NamedTuple):async_mode: boolraw_codex: boolexplicit_base_url: Optional[str]- explicit_api_key: Optional[Union[str, Callable[[], str]]]+ explicit_api_key: Optional[str | Callable[[], str]]api_mode: Optional[str]main_runtime: Optional[dict[str, Any]]is_vision: bool@@ -4894,7 +4894,7 @@ class _ResolveRequest(NamedTuple):_ResolveResult = tuple[Optional[Any], Optional[str]]-def _normalize_api_key(raw: Any) -> Union[str, Callable[[], str]]:+def _normalize_api_key(raw: Any) -> str | Callable[[], str]:"""A key_cmd/Entra callable passes through uncalled; strings are stripped; anything else is ''."""if callable(raw) and not isinstance(raw, str):return raw@@ -5421,7 +5421,7 @@ _EXPLICIT_PROVIDER_BRANCHES: dict[str, Callable[[_ResolveRequest], _ResolveResuldef resolve_provider_client(provider: str, model: str | None = None, async_mode: bool = False, raw_codex: bool = False,- explicit_base_url: str | None = None, explicit_api_key: Optional[Union[str, Callable[[], str]]] = None,+ explicit_base_url: str | None = None, explicit_api_key: Optional[str | Callable[[], str]] = None,api_mode: str | None = None, main_runtime: Optional[dict[str, Any]] = None, is_vision: bool = False,task: Optional[str] = None,) -> tuple[Optional[Any], Optional[str]]:diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex d6b39c4aa95..fb7bfe4010f 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -401,7 +401,7 @@ class LSPClient:if self.is_running:try:await asyncio.wait_for(self._send_request("shutdown", None), timeout=2.0)- except (asyncio.TimeoutError, LSPRequestError, LSPProtocolError):+ except (TimeoutError, LSPRequestError, LSPProtocolError):passtry:await self._send_notification("exit", None)@@ -657,7 +657,7 @@ class LSPClient:"textDocument/diagnostic", {"textDocument": {"uri": file_uri(abs_path)}},timeout=DIAGNOSTICS_REQUEST_TIMEOUT,)- except (LSPRequestError, LSPProtocolError, asyncio.TimeoutError) as e:+ except (TimeoutError, LSPRequestError, LSPProtocolError) as e:logger.debug("[%s] document diagnostic pull failed: %s", self.server_id, e)returnif not isinstance(result, dict):@@ -711,7 +711,7 @@ class LSPClient:self._push_event.clear()try:await asyncio.wait_for(self._push_event.wait(), timeout=timeout)- except asyncio.TimeoutError:+ except TimeoutError:return Falsereturn Truediff --git a/agent/pet/render.py b/agent/pet/render.pyindex cd36f719450..cf26da34dee 100644--- a/agent/pet/render.py+++ b/agent/pet/render.py@@ -221,18 +221,18 @@ def _encode_sixel(frame) -> str:px = pal.load()alpha = frame.getchannel("A").load()w, h = pal.size- out = ["\x1bP0;1;0q", '"1;1;%d;%d' % (w, h)]+ out = ["\x1bP0;1;0q", f'"1;1;{w:d};{h:d}']used = sorted({px[x, y] for y in range(h) for x in range(w)})for idx in used: # color registers on a 0..100 scaler, g, b = (palette[idx * 3 + c] if idx * 3 + c < len(palette) else 0 for c in range(3))- out.append("#%d;2;%d;%d;%d" % (idx, r * 100 // 255, g * 100 // 255, b * 100 // 255))+ out.append(f'#{idx:d};2;{r * 100 // 255:d};{g * 100 // 255:d};{b * 100 // 255:d}')for band in range(0, h, 6):ys = range(band, min(band + 6, h))for color_idx in used:chars = [chr(63 + sum(1 << (y - band) for y in ys if alpha[x, y] > 32 and px[x, y] == color_idx)) for x in range(w)]runs = ((ch, len(list(group))) for ch, group in groupby(chars)) # run-length: ``!<n><ch>`` for runs longer than 3- out.append("#%d" % color_idx + "".join("!%d%s" % (n, ch) if n > 3 else ch * n for ch, n in runs) + "$") # ``$`` = band CR+ out.append(f'#{color_idx:d}' + "".join(f"!{n:d}{ch}" if n > 3 else ch * n for ch, n in runs) + "$") # ``$`` = band CRout.append("-") # next bandreturn "".join(out) + "\x1b\\"diff --git a/agent/plugin_llm.py b/agent/plugin_llm.pyindex 1d08732a446..16af19cf7c0 100644--- a/agent/plugin_llm.py+++ b/agent/plugin_llm.py@@ -41,7 +41,7 @@ class PluginLlmImageInput:type: str = "image"-PluginLlmInput = Union[PluginLlmTextInput, PluginLlmImageInput, dict[str, Any]]+PluginLlmInput = PluginLlmTextInput | PluginLlmImageInput | dict[str, Any]"""One structured input block: a dataclass above or a plain dict of the same shape."""diff --git a/agent/process_bootstrap.py b/agent/process_bootstrap.pyindex 9d2ede55b47..13f22bcf56f 100644--- a/agent/process_bootstrap.py+++ b/agent/process_bootstrap.py@@ -55,7 +55,7 @@ class _HappyEyeballsSyncBackend:try:sock = _happy_eyeballs_create_connection((host, port), timeout, source_address=source_address,socket_options=socket_options or ())- except socket.timeout as exc:+ except TimeoutError as exc:raise ConnectTimeout(str(exc)) from excexcept OSError as exc:raise ConnectError(str(exc)) from excdiff --git a/agent/rate_limit_credits.py b/agent/rate_limit_credits.pyindex c8cfd50996f..6bcaa7c1e05 100644--- a/agent/rate_limit_credits.py+++ b/agent/rate_limit_credits.py@@ -117,8 +117,8 @@ class RateLimitCreditsMixin:"credits ▸ remaining=%d (%s) · paid=%s · denom=%s · used=%s · Δspent=%s · age=%s%s",state.remaining_micros, state.remaining_usd or "?", state.paid_access, state.denominator_kind,_pct(state.used_fraction), ("%.1f¢" % (spent / 10000)) if spent is not None else "n/a",- ("%.0fs" % state.age_seconds) if state.age_seconds != float("inf") else "n/a",- (" · disabled=%s" % state.disabled_reason) if state.disabled_reason else "")+ (f"{state.age_seconds:.0f}s") if state.age_seconds != float("inf") else "n/a",+ (f" · disabled={state.disabled_reason}") if state.disabled_reason else "")self._emit_credits_notices()def _emit_credits_notices(self) -> None:diff --git a/cron/jobs.py b/cron/jobs.pyindex e207ee1c51c..da16cfcbe0b 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -183,7 +183,7 @@ def _current_cron_store() -> _CronStorePaths:@contextlib.contextmanager-def use_cron_store(home: Union[str, Path]):+def use_cron_store(home: str | Path):"""Route cron storage to ``home`` without mutating process globals."""token = _cron_store_override.set(_CronStorePaths.for_dir(Path(home).expanduser().resolve() / "cron"))@@ -1387,15 +1387,12 @@ def load_jobs() -> list[dict[str, Any]]:# shape; the repair below rewrites it with replace=True.skipped = [k for k, v in jobs.items() if not isinstance(v, dict)]if skipped:- notes.append("Skipping %d non-dict entr%s in id-keyed jobs map: %s" % (- len(skipped), "y" if len(skipped) == 1 else "ies",- ", ".join(map(repr, skipped))))+ notes.append(f"Skipping {len(skipped):d} non-dict entr{('y' if len(skipped) == 1 else 'ies')} in id-keyed jobs map: {', '.join(map(repr, skipped))}")jobs = [{**v, "id": v.get("id") or k} for k, v in jobs.items() if isinstance(v, dict)]repair = "id-keyed jobs map flattened to list"unmergeable = Trueelif not isinstance(jobs, list):- notes.append("Replacing invalid jobs.json 'jobs' field (%s) with an empty list"- % type(jobs).__name__)+ notes.append(f"Replacing invalid jobs.json 'jobs' field ({type(jobs).__name__}) with an empty list")jobs = []repair = "invalid jobs field replaced with list"unmergeable = True@@ -1410,9 +1407,7 @@ def load_jobs() -> list[dict[str, Any]]:# Every reader and the due scan index records as dicts: one junk entry would crash the# whole tick and freeze every healthy sibling job, so skip it like the id-keyed map does.# Types only: the raw values are arbitrary file content and must not reach the logs.- notes.append("Skipping %d non-object entr%s in jobs.json (types: %s)" % (- len(junk), "y" if len(junk) == 1 else "ies",- ", ".join(sorted({type(j).__name__ for j in junk}))))+ notes.append(f"Skipping {len(junk)} non-object entr{'y' if len(junk) == 1 else 'ies'} in jobs.json (types: {', '.join(sorted({type(j).__name__ for j in junk}))})")jobs = [j for j in jobs if isinstance(j, dict)]repair = repair or "non-object entries dropped"for job in jobs:@@ -1828,7 +1823,7 @@ def create_job(provider: Optional[str] = None,base_url: Optional[str] = None,script: Optional[str] = None,- context_from: Optional[Union[str, list[str]]] = None,+ context_from: Optional[str | list[str]] = None,enabled_toolsets: Optional[list[str]] = None,workdir: Optional[str] = None,no_agent: bool = False,@@ -2741,7 +2736,7 @@ def _machine_id() -> str:def claim_job_for_fire(job_id: str, *, claim_ttl_seconds: int = FIRE_CLAIM_TTL_SECONDS, force: bool = False,manual: bool = False, return_job: bool = False,-) -> Union[bool, dict[str, Any]]:+) -> bool | dict[str, Any]:"""Atomically claim a job for one external 'fire' (multi-machine at-most-once); True iff THIScaller won (``CronScheduler.fire_due``: exactly one of N replicas runs a job). Under thefence + file lock: reject missing/terminal/paused jobs unless ``force`` (explicit manualdiff --git a/cron/scheduler.py b/cron/scheduler.pyindex 72b1d0f2858..1eea681c8e1 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -565,7 +565,7 @@ _parallel_pools: dict[str, concurrent.futures.ThreadPoolExecutor] = {}_parallel_pool_max_workers: dict[str, Optional[int]] = {}-def _inflight_key(job_id: str, home: Optional[Union[Path, str]] = None) -> tuple:+def _inflight_key(job_id: str, home: Optional[Path | str] = None) -> tuple:"""``(home key, job id)`` — the identity of one in-flight cron run.ONE gateway process ticks every profile, so a job id alone is not unique: two profiles@@ -771,7 +771,7 @@ def get_restart_wait_cron_counts() -> dict:}-def is_job_running(job_id: str, home: Optional[Union[Path, str]] = None) -> bool:+def is_job_running(job_id: str, home: Optional[Path | str] = None) -> bool:"""True when THIS process has an in-flight run of ``job_id`` FOR ``home`` (default: the activecron scope's home).@@ -834,7 +834,7 @@ def try_register_running_job(job_id: str, *, owner=None, future=_FUTURE_PENDING)def release_running_job(- job_id: str, home: Optional[Union[Path, str]] = None, *, owner=None,+ job_id: str, home: Optional[Path | str] = None, *, owner=None,) -> None:"""Remove the registration unless an explicit ``owner`` has been replaced.diff --git a/cron/scheduler_ownership.py b/cron/scheduler_ownership.pyindex adaa5987c72..2c0c05a234b 100644--- a/cron/scheduler_ownership.py+++ b/cron/scheduler_ownership.py@@ -69,14 +69,14 @@ def ticked_homes() -> dict:return dict(_ticked_homes)-def serves_profile(home: Optional[Union[Path, str]] = None) -> bool:+def serves_profile(home: Optional[Path | str] = None) -> bool:"""True when THIS process's cron ticker owns ``home`` (default: the active cron scope)."""key = hermes_home_key(home if home is not None else get_hermes_home())with _ticked_lock:return key in _ticked_homes-def owns_cron_tick_for(home: Optional[Union[Path, str]] = None) -> bool:+def owns_cron_tick_for(home: Optional[Path | str] = None) -> bool:"""True when this process is the host gateway multiplexer AND ticks ``home``.The runtime lock alone is not enough: it proves only that this process is the host gateway,@@ -92,7 +92,7 @@ def owns_cron_tick_for(home: Optional[Union[Path, str]] = None) -> bool:return serves_profile(home)-def record_serves_profile(record: Any, home: Optional[Union[Path, str]] = None) -> bool:+def record_serves_profile(record: Any, home: Optional[Path | str] = None) -> bool:"""True when a gateway runtime-status ``record``'s served set covers ``home``.The record is read from the holder's own home, so it always proves that home — that is the@@ -120,7 +120,7 @@ def record_serves_profile(record: Any, home: Optional[Union[Path, str]] = None)return label is not None and label in served-def live_gateway_ticking(home: Optional[Union[Path, str]] = None) -> Optional[dict]:+def live_gateway_ticking(home: Optional[Path | str] = None) -> Optional[dict]:"""Runtime-status record of ANOTHER live host gateway that ticks ``home``, else None.``None`` covers every "we cannot prove it" case: this process holds the lock itself, no lockdiff --git a/evals/core_tool_deferral/worker.py b/evals/core_tool_deferral/worker.pyindex 3ebbc5ca4e3..9c8bbe9f38e 100644--- a/evals/core_tool_deferral/worker.py+++ b/evals/core_tool_deferral/worker.py@@ -43,7 +43,7 @@ os.makedirs(hermes_home)os.makedirs(workspace)isolate_host(tmp_root, hermes_home)with open(os.path.join(hermes_home, "config.yaml"), "w", encoding="utf-8") as f:- f.write("model:\n provider: openrouter\n model: %s\n" % MODEL)+ f.write(f"model:\n provider: openrouter\n model: {MODEL}\n")os.environ["HERMES_HOME"] = hermes_homeos.environ["TERMINAL_CWD"] = workspace@@ -157,8 +157,8 @@ def drive_preview_cb(payload):if action in ("snapshot", "read", "links"):return json.dumps({"success": True, "title": PREVIEW_TITLE,"url": "https://example.com/docs/",- "text": ("Page: %s\nLinks: [Docs]->/docs/ [ref=e3]\n"- "Search box: input#docs-search [ref=e12]") % PREVIEW_TITLE})+ "text": (f"Page: {PREVIEW_TITLE}\nLinks: [Docs]->/docs/ [ref=e3]\n"+ "Search box: input#docs-search [ref=e12]")})return json.dumps({"success": True, "action": action, "title": PREVIEW_TITLE})def read_window_below_cb(**kw):@@ -192,8 +192,8 @@ def computer_use_stub(args, **kw):f.write(b"\x89PNG\r\n\x1a\nstub")return json.dumps({"success": True, "action": action, "screenshot": shot,- "analysis": ("Focused window: %s. It shows a note titled 'Shadow feeding "- "schedule' with a table of meal times. No error dialogs visible." % FOCUSED),+ "analysis": (f"Focused window: {FOCUSED}. It shows a note titled 'Shadow feeding "+ "schedule' with a table of meal times. No error dialogs visible."),})def image_generate_stub(args, **kw):@@ -232,7 +232,7 @@ agent = AIAgent()PREAMBLE = ("You are running inside the Hermes desktop app on the user's machine. "- "Your working directory (the workspace) is: %s\n\nTask: " % workspace)+ f"Your working directory (the workspace) is: {workspace}\n\nTask: ")t0 = time.time()error = None@@ -331,14 +331,14 @@ ctx = {"todo_dump": todo_dump,}-score, notes = 0.0, ["run errored: %s" % error] if error else (0.0, [])+score, notes = 0.0, [f"run errored: {error}"] if error else (0.0, [])if not error:try:score, notes = TASK["grade"](ctx)except Exception as ge:score, notes = 0.0, [f"grader crashed: {ge}"]else:- score, notes = 0.0, ["run errored: %s" % error]+ score, notes = 0.0, [f"run errored: {error}"]record = {"arm": ARM, "model": MODEL, "task": TASK_ID, "rep": REP,diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 544e0df32f3..edcfcffde42 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -240,7 +240,7 @@ class GatewayControlServer:None, self.handle_request_line, raw.rstrip(b"\n"))writer.write(response)await writer.drain()- except (asyncio.TimeoutError, ConnectionError, OSError):+ except (TimeoutError, ConnectionError, OSError):passexcept Exception:logger.debug("Control socket connection handler error", exc_info=True)diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex ab9f4d78b48..fa4b8860090 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3720,7 +3720,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):while True:try:item = await asyncio.wait_for(queue.get(), timeout=CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)- except asyncio.TimeoutError:+ except TimeoutError:await response.write(b": keepalive\n\n")continueif item is None:diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 33c9a052fca..6d8b43adf46 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -37,7 +37,7 @@ async def _iter_stream_items(stream_q, agent_task, response):while True:try:item = await asyncio.wait_for(stream_q.get(), timeout=0.5)- except asyncio.TimeoutError:+ except TimeoutError:if agent_task.done():while True:try:diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 9a5b50bb838..a3498355274 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -1133,7 +1133,7 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "wtry:seq, event = await asyncio.wait_for(q.get(), timeout=_api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)- except asyncio.TimeoutError:+ except TimeoutError:await _write(b": keepalive\n\n")continueif event is _RUN_STREAM_SUBSCRIBER_OVERFLOW:diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 4466b5a1ad2..770f96267e8 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2713,7 +2713,7 @@ class BasePlatformAdapter(ABC):return Nonetry:return await asyncio.wait_for(result_future, timeout=_HISTORY_MEDIA_LOOKUP_TIMEOUT_SECONDS)- except asyncio.TimeoutError:+ except TimeoutError:_fail_open("Timed out loading media-delivery history for")return Noneexcept Exception:@@ -3413,7 +3413,7 @@ class BasePlatformAdapter(ABC):try:await asyncio.wait_for(self.send_typing(chat_id, metadata=metadata),timeout=_send_typing_timeout)- except asyncio.TimeoutError:+ except TimeoutError:pass # Slow network — abandon this tick, stay on schedule.except Exception as typing_err:logger.debug("[%s] send_typing error (non-fatal): %s", self.name, typing_err)@@ -3989,7 +3989,7 @@ class BasePlatformAdapter(ABC):await asyncio.wait_for(asyncio.shield(task), timeout=5.0)except asyncio.CancelledError:pass- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Cancelled task for %s did not exit within 5s; ""unblocking dispatch and letting the task unwind in the background",self.name, session_key)@@ -4787,7 +4787,7 @@ class BasePlatformAdapter(ABC):await asyncio.wait_for(asyncio.gather(*(asyncio.shield(t) for t in tasks), return_exceptions=True),timeout=5.0)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] %d background task(s) did not exit within 5s; ""releasing tracking and letting them unwind in the background",self.name, sum(not t.done() for t in tasks))diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.pyindex c4b3479bffa..e15c0611af4 100644--- a/gateway/platforms/qqbot/adapter.py+++ b/gateway/platforms/qqbot/adapter.py@@ -1188,7 +1188,7 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):"[%s] ffmpeg failed for %s: %s",self._log_tag, Path(src_path).name, stderr[:200].decode(errors="replace"))return None- except (asyncio.TimeoutError, FileNotFoundError) as exc:+ except (TimeoutError, FileNotFoundError) as exc:logger.warning("[%s] ffmpeg conversion error: %s", self._log_tag, exc)return Nonediff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex fbb27e0d211..6a89f40daec 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -291,7 +291,7 @@ async def _api_get(session: "aiohttp.ClientSession", *, base_url: str, endpoint: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 asyncio.TimeoutError:+ except TimeoutError:return {"ret": 0, "msgs": [], "get_updates_buf": sync_buf}diff --git a/gateway/platforms/yuanbao.py b/gateway/platforms/yuanbao.pyindex 7fec5444918..1a8459c34ac 100644--- a/gateway/platforms/yuanbao.py+++ b/gateway/platforms/yuanbao.py@@ -1730,7 +1730,7 @@ class DispatchMiddleware(InboundMiddleware):while True:try:dispatch_fn = await asyncio.wait_for(queue.get(), timeout=2.0)- except asyncio.TimeoutError:+ except TimeoutError:breaklogger.debug("[%s] Group queue: dispatching for %s (remaining=%d)", adapter.name, (session_key or "")[:50], queue.qsize())try:@@ -1823,7 +1823,7 @@ class ConnectionManager:self._connected(cancel_existing=False)logger.info("[%s] Connected. connectId=%s botId=%s", adapter.name, self._connect_id, adapter._bot_id)return True- except asyncio.TimeoutError:+ except TimeoutError:logger.error("[%s] Connection timed out", adapter.name)except Exception as exc:logger.error("[%s] connect() failed: %s", adapter.name, exc, exc_info=True)@@ -1915,7 +1915,7 @@ class ConnectionManager:return Falselogger.info("[%s] BIND_ACK received: connectId=%s", adapter.name, self._connect_id)return True- except asyncio.TimeoutError:+ except TimeoutError:logger.error("[%s] AUTH_BIND timeout", adapter.name)except Exception as exc:logger.error("[%s] AUTH_BIND error: %s", adapter.name, exc, exc_info=True)@@ -1959,7 +1959,7 @@ class ConnectionManager:try:await asyncio.wait_for(pong_future, timeout=10.0)self._consecutive_hb_timeouts = 0- except asyncio.TimeoutError:+ except TimeoutError:self._pending_acks.pop(msg_id, None)self._consecutive_hb_timeouts += 1logger.warning("[%s] PONG timeout (%d/%d)", adapter.name, self._consecutive_hb_timeouts, HEARTBEAT_TIMEOUT_THRESHOLD)@@ -2131,7 +2131,7 @@ class ConnectionManager:self._connected(cancel_existing=True)logger.info("[%s] Reconnected on attempt %d. connectId=%s", adapter.name, attempt + 1, self._connect_id)return True- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Reconnect attempt %d timed out", adapter.name, attempt + 1)except Exception as exc:logger.warning("[%s] Reconnect attempt %d failed: %s", adapter.name, attempt + 1, exc)@@ -2146,7 +2146,7 @@ class ConnectionManager:if ws is not None:try:await asyncio.wait_for(ws.close(), timeout=WS_CLOSE_TIMEOUT_S)- except asyncio.TimeoutError:+ except TimeoutError:# No close-frame echo in time; websockets force-closes the transport on cancel.logger.debug("[%s] WS close handshake exceeded %.1fs — dropping connection", self._adapter.name, WS_CLOSE_TIMEOUT_S)except Exception:@@ -2537,7 +2537,7 @@ class MessageSender:try:response = await adapter._connection.send_biz_request(encoded, req_id=req_id)return {"success": True, "msg_key": response.get("msg_id", "")}- except asyncio.TimeoutError:+ except TimeoutError:return {"success": False, "error": f"Request timeout after {DEFAULT_SEND_TIMEOUT}s"}except Exception as exc:return {"success": False, "error": str(exc)}@@ -2767,7 +2767,7 @@ class YuanbaoAdapter(BasePlatformAdapter):return Nonebiz_data = response.get("data", b"") or response.get("body", b"")return decode_rsp(biz_data) if biz_data and isinstance(biz_data, bytes) else empty- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] %s timeout: group=%s", self.name, label, group_code)except Exception as exc:logger.warning("[%s] %s failed: %s", self.name, label, exc)diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 4df932ba1a3..3424756c30a 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -666,7 +666,7 @@ class RelayAdapter(BasePlatformAdapter):async def _card_frame(self, chat_id: str, op: str, reply_to: Optional[str], metadata: dict[str, Any], **fields: Any- ) -> Union[SendResult, dict[str, Any]]:+ ) -> SendResult | dict[str, Any]:"""Emit one task-card op: the connector result dict, or a failed SendResultwhen the lane is unavailable / the transport raised.@@ -1265,7 +1265,7 @@ class RelayAdapter(BasePlatformAdapter):await asyncio.wait_for(self._revocation_monitor, timeout=_RELAY_REVOCATION_MONITOR_TEARDOWN_TIMEOUT_S)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):passself._revocation_monitor = Noneif self._transport is not None:@@ -1511,7 +1511,7 @@ class RelayAdapter(BasePlatformAdapter):self._auto_thread_waiters[key] = waitertry:await asyncio.wait_for(waiter.wait(), timeout)- except asyncio.TimeoutError:+ except TimeoutError:return Nonefinally:# Only the waiter we installed, and only if no later call replaced it; adiff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex ba6aff2362a..581fd699907 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -295,7 +295,7 @@ async def _await_bounded(aw: Awaitable[Any]) -> None:"""Best-effort teardown await: bounded, swallows timeout/cancel/errors."""try:await asyncio.wait_for(aw, timeout=_TEARDOWN_AWAIT_TIMEOUT_S)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):pass@@ -664,7 +664,7 @@ class WebSocketRelayTransport:await self._send(frame)frame_sent = Truereturn await asyncio.wait_for(fut, timeout=self._outbound_timeout_s)- except asyncio.TimeoutError:+ except TimeoutError:# AMBIGUOUS by contract: the frame reached the wire and only the ack is# missing — the connector may have applied it. The fail-fast paths# above never sent anything (definite non-delivery) and stay unmarked.@@ -900,7 +900,7 @@ class WebSocketRelayTransport:await asyncio.wait_for(self._redial_release.wait(), timeout=self._redial_hold_max_s)- except asyncio.TimeoutError:+ except TimeoutError:logger.info("relay: brokered suspend did not land, reconnecting")finally:self._redial_held = Falsediff --git a/gateway/run.py b/gateway/run.pyindex d7dfbb0825b..02d93260666 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -261,7 +261,7 @@ async def run_codex_hygiene_compaction(track_worker(worker_future, agent)try:await asyncio.wait_for(asyncio.shield(worker_future), timeout=max(float(timeout_seconds), 1.0))- except asyncio.TimeoutError:+ except TimeoutError:# Executor thread keeps running (own RPC timeouts); brake retries so a wedged app-server isn't re-hit.if failure_cooldown_seconds >= 0:_record_hygiene_cooldown(diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 4b6d3084aed..4dc6b099927 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -1287,7 +1287,7 @@ class GatewayBusySessionMixin:async def _maybe_confirm_destructive_slash(self, *, event: MessageEvent, command: str, title: str, detail: str, execute- ) -> Union[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_inbound.py b/gateway/run_inbound.pyindex 049a6e58f4d..65ba2b9b2d0 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1039,7 +1039,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):from agent.redact import redact_sensitive_textoutput = redact_sensitive_text(output)return output or t("gateway.quick_command.no_output")- except asyncio.TimeoutError:+ except TimeoutError:return t("gateway.quick_command.timed_out")except Exception as e:return t("gateway.quick_command.error", error=e)diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex 1396dacb17b..66fa0df87a3 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -130,7 +130,7 @@ class GatewayProfileReconcileMixin:pid = await asyncio.wait_for(self._run_housekeeping_in_executor(live_gateway_pid_for_home, current[name]),timeout=_OWN_GATEWAY_PROBE_TIMEOUT_SECS)- except asyncio.TimeoutError:+ except TimeoutError:# Unprovable is not "own gateway running": skip it this cycle without# warning about (or remembering) a gateway that may not exist. Warn once# per stall; a peer that stays wedged repeats at DEBUG every cycle.diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 3b94f09ddcc..e04dfc23ab0 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1253,7 +1253,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):),timeout=self._CLEANUP_TIMEOUT_S,)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Agent resource cleanup%s exceeded %ss; proceeding without blocking the event loop (the worker ""thread is left to finish on its own). (#53175)", ctx_label, self._CLEANUP_TIMEOUT_S,diff --git a/gateway/run_shutdown_session_end.py b/gateway/run_shutdown_session_end.pyindex 63d84a26976..cb268f7564c 100644--- a/gateway/run_shutdown_session_end.py+++ b/gateway/run_shutdown_session_end.py@@ -54,7 +54,7 @@ class GatewaySessionEndMixin:self._run_housekeeping_in_executor(self._run_release_in_profile_scope, _call, (), session_key),timeout=self._FINALIZE_TIMEOUT_S,)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Session finalize hooks (%s, reason=%s) exceeded %ss; proceeding without blocking the event loop ""(the worker thread is left to finish on its own).", session_id, reason, self._FINALIZE_TIMEOUT_S,diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 7cb0842a083..622a22f1791 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -421,7 +421,7 @@ class GatewayStartupMixin:try:await asyncio.wait_for(wake.wait(), timeout=delay)continue # A shorter sibling may now be due first.- except asyncio.TimeoutError:+ except TimeoutError:passif getattr(self, "_running", False):await self._redeliver_failed_obligations_for_platform(target, profile=profile)@@ -429,7 +429,7 @@ class GatewayStartupMixin:pending.pop(key, None)wakes.pop(key, None)- task = asyncio.create_task(_redeliver_after_wait(), name="flood-redelivery:%s:%s" % key)+ task = asyncio.create_task(_redeliver_after_wait(), name="flood-redelivery:{}:{}".format(*key))pending[key] = task# The gateway's ordinary shutdown drain must cancel sleeping timers too.background = getattr(self, "_background_tasks", None)diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex eefee0d87f8..593078cafe4 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -819,7 +819,7 @@ class GatewayTurnMixin:fence = attempt.commit_fencewhile True:if fence.is_cancelled:- raise asyncio.TimeoutError+ raise TimeoutError# Charge the idle budget from the LAST PROGRESS event, else silence can approach 2x timeout._hyg_waited = time.monotonic() - attempt.wait_started_slice = min(@@ -836,7 +836,7 @@ class GatewayTurnMixin:try:_compressed, _ = await asyncio.wait_for(asyncio.shield(attempt.future), timeout=_slice)return _compressed- except asyncio.TimeoutError:+ except TimeoutError:if fence.is_cancelled:raise_hyg_waited = time.monotonic() - attempt.wait_started@@ -1327,7 +1327,7 @@ class GatewayTurnMixin:_compressed = await self._hmwa_hygiene_wait_for_summary(attempt, hs, session_entry)except HygieneTurnHoldExceeded:_compressed = await self._hmwa_hygiene_on_turn_hold(attempt, hs, session_entry, session_key, source)- except asyncio.TimeoutError:+ except TimeoutError:_compressed = await self._hmwa_hygiene_on_timeout(attempt, hs, session_entry, session_key, source)except BaseException:self._hmwa_hygiene_on_unwind(attempt, hs, session_entry, session_key)@@ -2902,7 +2902,7 @@ class GatewayTurnMixin:if stream_task:try:await asyncio.wait_for(stream_task, timeout=5.0)- except (asyncio.TimeoutError, asyncio.CancelledError):+ except (TimeoutError, asyncio.CancelledError):stream_task.cancel()_elapsed = time.time() - _start@@ -3270,7 +3270,7 @@ class GatewayTurnMixin:"""Give the stream consumer task 5s to flush, then cancel it."""try:await asyncio.wait_for(stream_task, timeout=5.0)- except (asyncio.TimeoutError, asyncio.CancelledError):+ except (TimeoutError, asyncio.CancelledError):stream_task.cancel()with suppress(asyncio.CancelledError):await stream_taskdiff --git a/gateway/run_watchers.py b/gateway/run_watchers.pyindex 70dc3a77bc8..05a932550c0 100644--- a/gateway/run_watchers.py+++ b/gateway/run_watchers.py@@ -199,7 +199,7 @@ class GatewaySessionWatchersMixin:# Adapters often return SendResult(success=False) instead of raising.if result is not None and getattr(result, "success", True) is False:raise RuntimeError(getattr(result, "error", "send returned success=False"))- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Session stall notify send timed out after %.0fs for %s; will retry next tick",_STALL_NOTIFY_SEND_TIMEOUT_SECONDS, session_key,diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 4f72f390e7b..0ea4b9e242e 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -417,7 +417,7 @@ class GatewaySlashCommandsMixin(await asyncio.to_thread(_sub)return True- async def _handle_stop_command(self, event: MessageEvent) -> Union[str, EphemeralReply]:+ async def _handle_stop_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /stop command - interrupt a running agent. A truly hung agent (blocked threadnever checking _interrupt_requested) is caught by the early intercept in _handle_message();this handler runs via normal dispatch or as a fallback, and force-cleans the session lock in@@ -526,7 +526,7 @@ class GatewaySlashCommandsMixin(self._resume_paused_platform(platform)return t("gateway.platform.resumed", name=name)- async def _handle_restart_command(self, event: MessageEvent) -> Union[str, EphemeralReply]:+ async def _handle_restart_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /restart command - drain active work, then restart the gateway."""from gateway.run import _hermes_home# Idempotency check: if the previous gateway process recorded this same /restart (platform +@@ -934,7 +934,7 @@ class GatewaySlashCommandsMixin(# system prompt/tool schema (prompt-cache prefix is sacred).return run_approval_mode_command(requested).message- async def _handle_yolo_command(self, event: MessageEvent) -> Union[str, EphemeralReply]:+ async def _handle_yolo_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /yolo — toggle dangerous command approval bypass for this session only. The flag ispersisted on the routing entry so it survives a gateway restart."""from tools.approval_yolo import toggle_session_yolo@@ -975,7 +975,7 @@ class GatewaySlashCommandsMixin(logger.warning("Failed to save tool_progress mode: %s", e)return f"{description}\n" + t("gateway.verbose.save_failed", error=e)- async def _handle_busy_command(self, event: MessageEvent) -> Union[str, EphemeralReply]:+ async def _handle_busy_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /busy — control what happens when messaging while Hermes is working."""arg = event.get_command_args().strip().lower()if not arg or arg == "status":diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex 0b7098bc866..c73d276566c 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -129,7 +129,7 @@ class GatewaySessionCommandsMixin:await asyncio.wait_for(self._run_housekeeping_in_executor(self._cleanup_agent_resources, _old_agent),timeout=_RESET_CLEANUP_TIMEOUT_S)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Agent resource cleanup for session %s exceeded %ss during /new reset; proceeding with ""reset (the worker thread is left to finish on its own). (#35994)",@@ -153,7 +153,7 @@ class GatewaySessionCommandsMixin:await self.hooks.emit("session:end", dict(hook_payload))await self.hooks.emit("session:reset", dict(hook_payload))- async def _handle_reset_command(self, event: MessageEvent) -> Union[str, EphemeralReply]:+ async def _handle_reset_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /new or /reset command."""source = event.sourcesession_key = self._session_key_for_source(source)diff --git a/gateway/stream_events.py b/gateway/stream_events.pyindex 1a1e74c2b80..96e741dcc9a 100644--- a/gateway/stream_events.py+++ b/gateway/stream_events.py@@ -69,10 +69,7 @@ class GatewayNotice:# Explicit union (not a marker base class) so a missing ``case`` in an# exhaustive match is a visible type error rather than a silent fall-through.-StreamEvent = Union[- MessageChunk, MessageStop, Commentary,- ToolCallChunk, ToolCallFinished, LongToolHint, GatewayNotice,-]+StreamEvent = MessageChunk | MessageStop | Commentary | ToolCallChunk | ToolCallFinished | LongToolHint | GatewayNotice__all__ = ["Commentary",diff --git a/gateway/turn_lease.py b/gateway/turn_lease.pyindex 008ecb59f8d..2046f1b198d 100644--- a/gateway/turn_lease.py+++ b/gateway/turn_lease.py@@ -120,7 +120,7 @@ class SessionTurnLeaseRegistry:lease.pending_acquires += 1try:await asyncio.wait_for(lease.lock.acquire(), timeout=wait)- except asyncio.TimeoutError:+ except TimeoutError:logger.error("turn lease wait timed out after %.0fs on session %s (waiter: routing key %s gen ""%s; holder: routing key %s gen %s) — failing closed: refusing to run this turn "diff --git a/gateway/wake.py b/gateway/wake.pyindex 3416ff53326..a0273ede7f1 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -247,7 +247,7 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: strawait resp.read()logger.info("wake self-post delivered for session %s (attempt %d)", session_id, attempt + 1)return- except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc:+ except (TimeoutError, aiohttp.ClientError, OSError) as exc:last_err = exclogger.warning("wake self-post transient failure for session %s (attempt %d/%d): %s",session_id, attempt + 1, attempts, exc)diff --git a/hermes_bootstrap.py b/hermes_bootstrap.pyindex ce469833c3b..619dc5747b4 100644--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@ -99,7 +99,7 @@ def _happy_eyeballs_create_connection(address: tuple[str, int], timeout: float |while pending or active:now = time.monotonic()if deadline is not None and now >= deadline:- raise socket.timeout("timed out")+ raise TimeoutError("timed out")if pending and now >= next_launch:try:winner = start_attempt(pending.pop(0))diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 0db6d9f247f..d84df091448 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1412,7 +1412,7 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):_pr(f" {_t('cron.id', job_id=job['job_id'])}", f" {_t('cron.name', name=job['name'])}",f" {_t('cron.state', state=job.get('state', '?'))}",f" {_t('cron.schedule_repeat', schedule=job['schedule'], repeat=job.get('repeat', '?'))}",- " %s: %s" % _next_run_row(job) if job.get("next_run_at") else f" {_t('cron.next_run_na')}")+ " {}: {}".format(*_next_run_row(job)) if job.get("next_run_at") else f" {_t('cron.next_run_na')}")if job.get("skills"):print(f" {_t('cron.skills', skills=', '.join(job['skills']))}")print(f" {_t('cron.prompt', prompt=job.get('prompt_preview', ''))}")diff --git a/hermes_cli/curses_ui.py b/hermes_cli/curses_ui.pyindex 7b04afa24b9..10045551381 100644--- a/hermes_cli/curses_ui.py+++ b/hermes_cli/curses_ui.py@@ -9,7 +9,7 @@ from typing import Callable, List, Optional, Sequence, Set, Tuple, Unionfrom hermes_cli.colors import Colors, color# Rich radiolist rows: (text, style). style is None | "yellow" | "dim". Plain ``str`` works too.-RadioItem = Union[str, Sequence[tuple[str, Optional[str]]]]+RadioItem = str | Sequence[tuple[str, str | None]]_NO_REPLAY = object()diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 4eacbab780c..0a439ff51d5 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -438,8 +438,8 @@ def _kill_pids_windows(pids: list[int], killed: list[int], failed: list[tuple[infailed.append((pid, "not hermes-owned or process identity changed"))else:result = subprocess.run(- ["taskkill", "/PID", str(pid), "/F"], stdout=subprocess.PIPE,- stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True, encoding="utf-8",+ ["taskkill", "/PID", str(pid), "/F"], capture_output=True,+ stdin=subprocess.DEVNULL, text=True, encoding="utf-8",errors="replace", timeout=10, creationflags=windows_hide_flags())if result.returncode == 0:killed.append(pid)diff --git a/hermes_cli/kanban_pr_acceptance.py b/hermes_cli/kanban_pr_acceptance.pyindex 88f437285ad..7a060c24676 100644--- a/hermes_cli/kanban_pr_acceptance.py+++ b/hermes_cli/kanban_pr_acceptance.py@@ -121,9 +121,7 @@ def collect_acceptance(contract: str, published_pr: str | None,repo, number = match[1], int(match[2])receipt["pr_url"] = urlowner, name = repo.split("/")- query = '''{repository(owner:%s,name:%s){pullRequest(number:%d){headRefOid baseRefName state- baseRef{branchProtectionRule{requiredStatusChecks{context app{databaseId}}}}}}}''' % (- json.dumps(owner), json.dumps(name), number)+ query = f'{{repository(owner:{json.dumps(owner)},name:{json.dumps(name)}){{pullRequest(number:{number:d}){{headRefOid baseRefName state\n baseRef{{branchProtectionRule{{requiredStatusChecks{{context app{{databaseId}}}}}}}}}}}}}}'repository = _api("graphql", query=query, profile_home=profile_home)["data"]["repository"]if repository is None:# A private repo the login cannot read resolves to null, not an error.diff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.pyindex e910e2f875b..41416b766ea 100644--- a/hermes_cli/local_runtime/context_policy.py+++ b/hermes_cli/local_runtime/context_policy.py@@ -286,7 +286,7 @@ def spill_overrides(profile: ModelProfile, spill_bytes: int | None = None) -> lireturn ["-ot", r"blk\.\d+\.ffn_.*_exps\.weight=CPU"]blocks = recurrent_spill_blocks(profile, spill_bytes)if blocks:- return ["-ot", r"blk\.(%s)\.ffn_.*\.weight=CPU" % "|".join(map(str, blocks))]+ return ["-ot", r"blk\.({})\.ffn_.*\.weight=CPU".format("|".join(map(str, blocks)))]return [] # dense: fit's back-to-front layer cut is the only axisdiff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.pyindex d46c259c4c5..abb9cc337e8 100644--- a/hermes_cli/mcp_config.py+++ b/hermes_cli/mcp_config.py@@ -457,7 +457,7 @@ def _probe_single_server(details["initialized"] = Falsetry:server = await asyncio.wait_for(_connect_server(name, config), timeout=connect_timeout)- except asyncio.TimeoutError:+ except TimeoutError:# str(TimeoutError()) is '' — printed verbatim it was a blank "Authentication failed:".raise TimeoutError(f"Connecting to MCP server '{name}' timed out after {float(connect_timeout):.0f}s "diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex b905d335de7..42150596f8f 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -888,7 +888,7 @@ class PluginContext:return countdef register_locale(- self, lang: str, source: Union[str, Path, Mapping[str, Any]], *, endonym: Optional[str] = None,+ self, lang: str, source: str | Path | Mapping[str, Any], *, endonym: Optional[str] = None,rtl: bool = False, surface: str = "core",) -> PluginRegistration:"""Register a language-pack layer for ``lang`` (``pl``, ``pt-br``): ``source`` is a YAML file path or@@ -913,7 +913,7 @@ class PluginContext:return handledef register_locale_dir(- self, path: Union[str, Path], *, metadata: Optional[Mapping[str, Mapping[str, Any]]] = None,+ self, path: str | Path, *, metadata: Optional[Mapping[str, Mapping[str, Any]]] = None,) -> list[PluginRegistration]:"""Register every ``<lang>[.tui|.desktop].yaml`` under ``path`` (a pack's ``locales/`` dir). Theloader calls this for plugins declaring ``provides_locales``; ``metadata`` maps ids to@@ -955,7 +955,7 @@ class PluginContext:return handledef register_system_prompt_section(- self, id: str, content: Union[str, Callable[[Mapping[str, Any]], str]], *,+ self, id: str, content: str | Callable[[Mapping[str, Any]], str], *,position: str = "after_memory", max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,) -> PluginRegistration:"""Register bounded context frozen into each new session prompt. Callables receive adiff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex 0297573b7ec..3ca7e6baa5a 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -112,7 +112,7 @@ class PluginSystemPromptSection:"""A plugin-owned section rendered once for each new session."""id: str- content: Union[str, Callable[[Mapping[str, Any]], str]]+ content: str | Callable[[Mapping[str, Any]], str]position: strmax_chars: intplugin: str@@ -508,7 +508,7 @@ class PluginDispatchMixin:ret = await (asyncio.wait_for(ret, timeout) if use_timeout else ret)if ret is not None:results.append(ret)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Hook '%s' callback %s timed out after %.0fs", hook_name, callback_name, timeout)if fail_closed: # policy hook: fail closed with a block directiveresults.append({"action": "block", "message": _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE})diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.pyindex b8f3ad5d23a..ca06386262f 100644--- a/hermes_cli/plugins_ledger.py+++ b/hermes_cli/plugins_ledger.py@@ -213,18 +213,18 @@ class PluginLedgerMixin:)@staticmethod- def _resolve_plugin_key(plugin: Union[str, PluginManifest, LoadedPlugin]) -> str:+ def _resolve_plugin_key(plugin: str | PluginManifest | LoadedPlugin) -> str:from hermes_cli.plugins import LoadedPluginif isinstance(plugin, LoadedPlugin):return manifest_key(plugin.manifest)return manifest_key(plugin) if isinstance(plugin, PluginManifest) else str(plugin)- def unload(self, plugin: Union[str, PluginManifest, LoadedPlugin, None] = None) -> bool:+ def unload(self, plugin: str | PluginManifest | LoadedPlugin | None = None) -> bool:"""Unload registrations while excluding discovery/deferred loading."""with self._discovery_lock, _plugin_home_scope(self.home_path):return self._unload_scoped(plugin)- def _unload_scoped(self, plugin: Union[str, PluginManifest, LoadedPlugin, None] = None) -> bool:+ def _unload_scoped(self, plugin: str | PluginManifest | LoadedPlugin | None = None) -> bool:"""Unload one plugin (or all when ``plugin=None``, as force rediscovery does). Every ledger registration— including on_unload callbacks and supervised tasks — is disposed in reverse acquisition order withidentity-conditional inverses. Returns ``True`` when anything was found."""diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 36f97b0a728..1b5c1b950ab 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -732,7 +732,7 @@ class PluginLoaderMixin:raisereturn module- def _load_entrypoint_module(self, manifest: PluginManifest) -> Union[types.ModuleType, Callable[..., Any]]:+ def _load_entrypoint_module(self, manifest: PluginManifest) -> types.ModuleType | Callable[..., Any]:"""Load a pip-installed plugin via its entry-point reference: the module for a bare ``module`` target,the referenced attribute (normally ``register``) for the ``module:function`` form."""for ep in _select_entry_point_group(importlib.metadata.entry_points(), ENTRY_POINTS_GROUP):diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex 9e0a6941cb0..493e3a61728 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -346,7 +346,7 @@ class PluginManifest:version: str = ""description: str = ""author: str = ""- requires_env: list[Union[str, dict[str, Any]]] = field(default_factory=list)+ requires_env: list[str | dict[str, Any]] = field(default_factory=list)provides_tools: list[str] = field(default_factory=list)provides_hooks: list[str] = field(default_factory=list)source: str = "" # "bundled", "user", "project", or "entrypoint"diff --git a/hermes_cli/proxy/server.py b/hermes_cli/proxy/server.pyindex e3d9d6b2aa3..9617dcd3198 100644--- a/hermes_cli/proxy/server.py+++ b/hermes_cli/proxy/server.py@@ -150,7 +150,7 @@ async def _open_upstream(request: "web.Request", rel_path: str, body: bytes, creawait session.close()logger.warning("proxy: upstream connection failed: %s", exc)return _json_error(502, f"upstream connection failed: {exc}", code="upstream_unreachable"), None- except asyncio.TimeoutError:+ except TimeoutError:await session.close()return _json_error(504, "upstream request timed out", code="upstream_timeout"), Noneexcept Exception:diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.pyindex f71cfa08a0d..eebeace42b1 100644--- a/hermes_cli/pty_bridge.py+++ b/hermes_cli/pty_bridge.py@@ -202,7 +202,7 @@ class PtyBridge:loop.add_writer(self._fd, _mark_ready)await asyncio.wait_for(ready, timeout=timeout)return not self._closed- except (asyncio.TimeoutError, OSError, ValueError):+ except (TimeoutError, OSError, ValueError):return Falsefinally:try:diff --git a/hermes_cli/update_cmd_validation.py b/hermes_cli/update_cmd_validation.pyindex b521ebf7252..665d10756c3 100644--- a/hermes_cli/update_cmd_validation.py+++ b/hermes_cli/update_cmd_validation.py@@ -30,25 +30,23 @@ def _critical_module_import_failures(# probe only checks importability, so it inherits the updater's own argv contract."sys.argv = ['hermes', 'update']\n""failures = []\n"- "for name in %r:\n"+ f"for name in {_UPDATE_CRITICAL_MODULES!r}:\n"" try:\n"" importlib.import_module(name)\n"" except ModuleNotFoundError as exc:\n"# A missing *third-party* module means deps aren't installed, not a skewed checkout;# only our own packages count. Roots come from hermes_constants so the user hint can't drift." missing = (getattr(exc, 'name', '') or '').split('.')[0]\n"- " if missing in %r or missing.startswith('hermes_') or %r:\n"+ f" if missing in {tuple(sorted(FIRST_PARTY_MODULE_ROOTS))!r} or missing.startswith('hermes_') or {report_runtime_errors!r}:\n"" failures.append((name, type(exc).__name__, str(exc)))\n"" except ImportError as exc:\n"" failures.append((name, type(exc).__name__, str(exc)))\n"" except Exception as exc:\n"- " if %r:\n"+ f" if {report_runtime_errors!r}:\n"" failures.append((name, type(exc).__name__, str(exc)))\n"" except BaseException as exc:\n"" failures.append((name, type(exc).__name__, str(exc)))\n"- "sys.stdout.write('\\n%s' + json.dumps(failures))\n"- % (_UPDATE_CRITICAL_MODULES, tuple(sorted(FIRST_PARTY_MODULE_ROOTS)), report_runtime_errors,- report_runtime_errors, marker))+ f"sys.stdout.write('\\n{marker}' + json.dumps(failures))\n")try:result = subprocess.run(runtime_command(Path(root), code=probe), cwd=str(root), capture_output=True, text=True,diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 45a71904042..127947f0c93 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -318,7 +318,7 @@ class CronJobCreate(BaseModel):# same user-facing strings the CLI accepts ('forever'/'once'/'3'). Normalization and# validation happen in cron.jobs.create_job via normalize_repeat_value — the shared# chokepoint with the CLI and update paths — so an unparseable value 400s there.- repeat: Optional[Union[int, str]] = None+ repeat: Optional[int | str] = Noneskills: Optional[list[str]] = Nonemodel: Optional[str] = Noneprovider: Optional[str] = Nonediff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 947825c57b9..d203a0a1ca4 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -341,7 +341,7 @@ async def console_ws(ws: WebSocket) -> None:except asyncio.CancelledError:await _unwind_console_worker(worker, scope, "cancelled")raise- except asyncio.TimeoutError:+ except TimeoutError:await _unwind_console_worker(worker, scope, "timed out")if command_id == command_generation:pending_confirmation = Nonediff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex ac6c4c6e495..02143a915bc 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -95,7 +95,7 @@ async def _status_active_sessions() -> int:return await asyncio.wait_for(run_in_threadpool(_count_status_active_sessions),timeout=_STATUS_ACTIVE_SESSIONS_TIMEOUT)- except asyncio.TimeoutError:+ except TimeoutError:_log.debug("/api/status active session count exceeded %.2fs; returning 0",_STATUS_ACTIVE_SESSIONS_TIMEOUT)except Exception as exc:diff --git a/hermes_cli/web_server_skew_exit.py b/hermes_cli/web_server_skew_exit.pyindex e1634cdefe6..b74c6b29f52 100644--- a/hermes_cli/web_server_skew_exit.py+++ b/hermes_cli/web_server_skew_exit.py@@ -90,8 +90,8 @@ def start_code_skew_watchdog(server, *, skew_fn: Optional[Callable[[], Skew]] =skew = read_skew()if not (skew and should_retire_for_skew(skew=skew, update_in_progress=update_probe())):return None- return ("SSH-isolated backend loaded %s but the install is now at %s; "- "retiring so its client respawns it on the new code." % skew)+ return ("SSH-isolated backend loaded {} but the install is now at {}; "+ "retiring so its client respawns it on the new code.".format(*skew))return _run_retirement_watchdog(server, observe=_observe, fence=fence, poll_s=poll_s,max_polls=max_polls, thread_name="ssh-isolated-skew-watchdog")diff --git a/hermes_cli/win_pty_bridge.py b/hermes_cli/win_pty_bridge.pyindex aa01d97456d..b87143809fb 100644--- a/hermes_cli/win_pty_bridge.py+++ b/hermes_cli/win_pty_bridge.py@@ -132,7 +132,7 @@ class WinPtyBridge:asyncio.shield(write_future),timeout=max(0.0, timeout),)- except asyncio.TimeoutError:+ except TimeoutError:await self._stop_stalled_write(write_future)return Falseexcept asyncio.CancelledError:@@ -144,7 +144,7 @@ class WinPtyBridge:try:await asyncio.wait_for(asyncio.shield(write_future), timeout=_WRITE_SHUTDOWN_GRACE)return- except asyncio.TimeoutError:+ except TimeoutError:passexcept Exception:return@@ -158,7 +158,7 @@ class WinPtyBridge:asyncio.shield(write_future),timeout=_WRITE_SHUTDOWN_GRACE,)- except asyncio.TimeoutError:+ except TimeoutError:# The worker is still parked inside pywinpty after terminate(); it# now occupies a default-executor thread until the process exits._log.warning(diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 87afa702895..a3435dd5f3d 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -1547,7 +1547,7 @@ class SessionSessionsMixin:return list(reversed(chain)) or [session_id]def search_sessions(- self, source: Union[str, Sequence[str], None] = None, limit: int = 20, offset: int = 0,+ self, source: str | Sequence[str] | None = None, limit: int = 20, offset: int = 0,workspace_key: str | None = None,) -> list[dict[str, Any]]:"""Sessions MRU-first with a computed ``last_active``; ``workspace_key`` scopes to one workspacediff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.pyindex 5146ec3dc17..f65a24ec348 100644--- a/plugins/dashboard_auth/self_hosted/__init__.py+++ b/plugins/dashboard_auth/self_hosted/__init__.py@@ -307,8 +307,7 @@ def _settings() -> dict:"a client_id — either as env vars (HERMES_DASHBOARD_OIDC_ISSUER + ""HERMES_DASHBOARD_OIDC_CLIENT_ID) or under ""dashboard.oauth.self_hosted.{issuer,client_id} in config.yaml — or pass "- "--insecure to skip the OAuth gate entirely. (issuer set: %s; client_id set: %s)"- % (bool(issuer), bool(client_id)))+ f"--insecure to skip the OAuth gate entirely. (issuer set: {bool(issuer)}; client_id set: {bool(client_id)})")return {"issuer": issuer, "client_id": client_id,"scopes": setting("HERMES_DASHBOARD_OIDC_SCOPES", "scopes") or _DEFAULT_SCOPES,diff --git a/plugins/google_meet/meet_bot.py b/plugins/google_meet/meet_bot.pyindex 6807e9bcf28..10358bb61f1 100644--- a/plugins/google_meet/meet_bot.py+++ b/plugins/google_meet/meet_bot.py@@ -438,7 +438,7 @@ def run_bot() -> int:cfg = _config_from_env()if not _is_safe_meet_url(cfg.url):sys.stderr.write("google_meet bot: refusing to launch — HERMES_MEET_URL must be a "- "meet.google.com URL. got: %r\n" % cfg.url)+ f"meet.google.com URL. got: {cfg.url!r}\n")return 2if cfg.out_dir is None:sys.stderr.write("google_meet bot: HERMES_MEET_OUT_DIR is required\n")diff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.pyindex 0fc7859dc9a..18edac30786 100644--- a/plugins/kanban/dashboard/plugin_api.py+++ b/plugins/kanban/dashboard/plugin_api.py@@ -1828,7 +1828,7 @@ async def stream_events(ws: WebSocket):msg = await asyncio.wait_for(ws.receive(), timeout=_EVENT_POLL_SECONDS)if msg["type"] == "websocket.disconnect":return- except asyncio.TimeoutError:+ except TimeoutError:pass # no client message — poll the DBcursor, events = await tail.poll(cursor)if events:diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 4d5145da86b..a93bd718425 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -407,7 +407,7 @@ async def _exec_buzz(try:stdin_bytes = input_text.encode("utf-8") if input_text is not None else Nonestdout, stderr = await asyncio.wait_for(proc.communicate(stdin_bytes), timeout=timeout)- except asyncio.TimeoutError:+ except TimeoutError:proc.kill()await proc.wait()detail = {"error": "timeout", "message": f"buzz {args[0] if args else ''} timed out after {timeout}s"}@@ -989,7 +989,7 @@ class BuzzAdapter(BasePlatformAdapter):try:await asyncio.wait_for(self._ws_ready.wait(), timeout=_WS_AUTH_TIMEOUT + 5)return True- except (asyncio.TimeoutError, TimeoutError):+ except TimeoutError:logger.warning("Buzz: WebSocket did not authenticate in time")await cancel_task(self._ws_task)self._ws_task = Nonediff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex de2cf39bee0..c5454ee2f35 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -357,7 +357,7 @@ class DingTalkAdapter(BasePlatformAdapter):self._stream_task.cancel()try:await asyncio.wait_for(self._stream_task, timeout=5.0)- except (asyncio.CancelledError, asyncio.TimeoutError):+ except (TimeoutError, asyncio.CancelledError):logger.debug("[%s] stream task did not exit cleanly during disconnect", self.name)self._stream_task = Nonefor task in list(self._bg_tasks):diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 5697cba40c2..847267de5a1 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -390,7 +390,7 @@ async def _wait_for_ready_or_bot_exit({ready_task, bot_task}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED,)if not done:- raise asyncio.TimeoutError+ raise TimeoutErrorif bot_task in done:exc = bot_task.exception()if exc is not None:@@ -1658,7 +1658,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn# Plugin-registered native handlers (discord.py Bot — add_listener()/event hooks).self._wire_plugin_handlers(self._client)return True- except asyncio.TimeoutError:+ except TimeoutError:logger.error("[%s] Timeout waiting for connection to Discord", self.name, exc_info=True)# Cancel the bot task so a discarded adapter can't fire on_message (two clients answering).await self._cancel_bot_task()@@ -1799,7 +1799,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInif not self._ready_event.is_set():try:await asyncio.wait_for(self._ready_event.wait(), timeout=30.0)- except asyncio.TimeoutError:+ except TimeoutError:passadmitted, role_authorized = self._discord_message_admission(message, claim=True)if not admitted:@@ -2101,9 +2101,9 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIntry:done, _pending = await asyncio.wait({close_task}, timeout=1.0)if close_task not in done:- raise asyncio.TimeoutError+ raise TimeoutErrorawait close_task- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Timed out closing unhealthy Discord client", self.name)close_task.cancel()close_task.add_done_callback(_consume_background_task_result)@@ -2166,7 +2166,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInasyncio.gather(*pending, return_exceptions=True),timeout=self._text_batch_flush_deadline_seconds(),)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Text-batch flush timed out; cancelling remaining tasks", self.name,)@@ -2443,7 +2443,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInself.name, summary["total"], summary["unchanged"], summary["updated"],summary["recreated"], summary["created"], summary["deleted"],)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Slash command sync timed out — Discord rate-limit bucket ""may be saturated; will retry on next reconnect",@@ -3962,7 +3962,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInvc.play(source, after=_after)try:await asyncio.wait_for(done.wait(), timeout=playback_timeout)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Voice playback timed out after %.1fs", playback_timeout)vc.stop()return Truediff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex caea2a31d85..8f3d0b59e0c 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -86,8 +86,8 @@ _MISSING_AUTHSERV_HINT = (" Set EMAIL_AUTHSERV_ID (or platforms.email.authserv_i# One token of a clause: a property we read (``header.from=x``; the value may be or contain a quoted-string), or# any other whitespace-delimited token consumed whole, so text inside quotes or other values is never read as a prop._QUOTED = r'"(?:[^"\\]|\\.)*"'-_AUTH_PROP_RE = re.compile(r'(header\.from|header\.d|smtp\.mailfrom|smtp\.from|envelope-from)\s*=\s*((?:%s|[^\s";])+)'- r'|(?:%s|[^\s"])+' % (_QUOTED, _QUOTED), re.IGNORECASE)+_AUTH_PROP_RE = re.compile(rf'(header\.from|header\.d|smtp\.mailfrom|smtp\.from|envelope-from)\s*=\s*((?:{_QUOTED}|[^\s";])+)'+ rf'|(?:{_QUOTED}|[^\s"])+', re.IGNORECASE)def _esecret_int(name: str, default: int) -> int:@@ -545,7 +545,7 @@ class EmailAdapter(BasePlatformAdapter):host, port, security, ctx = self._smtp_host, self._smtp_port, self._smtp_security, _tls_context(self._smtp_tls_verify, self._smtp_host)try:return _open_smtp(host, port, security, ctx, smtplib.SMTP, smtplib.SMTP_SSL, timeout=SMTP_CONNECT_TIMEOUT)- except (socket.timeout, TimeoutError, ConnectionError, OSError) as exc:+ except (TimeoutError, ConnectionError, OSError) as exc:if isinstance(exc, ssl.SSLError):raisereturn _open_smtp(host, port, security, ctx, _IPv4SMTP, _IPv4SMTP_SSL, timeout=SMTP_CONNECT_TIMEOUT)diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 4875db3d8b8..ca46d82bf1c 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -1582,7 +1582,7 @@ class FeishuAdapter(BasePlatformAdapter):# A CLOSE frame is one control frame; if 5s isn't enough the link is already wedged.await asyncio.wait_for(asyncio.wrap_future(future), timeout=5.0)logger.debug("[Feishu] Sent WebSocket CLOSE frame to Feishu")- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[Feishu] CLOSE frame not acknowledged within 5s — ""Feishu may briefly route messages to the stale "@@ -1609,7 +1609,7 @@ class FeishuAdapter(BasePlatformAdapter):logger.debug("[Feishu] Waiting for websocket thread to exit (timeout=10s)")await asyncio.wait_for(asyncio.shield(ws_future), timeout=10.0)logger.debug("[Feishu] Websocket thread exited cleanly")- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[Feishu] Websocket thread did not exit within 10s - may be stuck")except asyncio.CancelledError:logger.debug("[Feishu] Websocket thread cancelled during disconnect")@@ -2826,7 +2826,7 @@ class FeishuAdapter(BasePlatformAdapter):except ValueError:logger.warning("[Feishu] Webhook body exceeds limit from %s", remote_ip)return self._webhook_reject(remote_ip, "413", 413, "Request body too large")- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[Feishu] Webhook body read timed out after %ds from %s", _FEISHU_WEBHOOK_BODY_TIMEOUT_SECONDS, remote_ip)return self._webhook_reject(remote_ip, "408", 408, "Request Timeout")except Exception:diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.pyindex 0b13204377c..8ef7ddc507d 100644--- a/plugins/platforms/google_chat/adapter.py+++ b/plugins/platforms/google_chat/adapter.py@@ -1721,7 +1721,7 @@ async def _standalone_send(# Bound the synchronous token refresh so a hung STS endpoint can't stall cron.try:await asyncio.wait_for(asyncio.to_thread(creds.refresh, _GoogleAuthRequest()), timeout=10.0)- except asyncio.TimeoutError:+ except TimeoutError:return _standalone_error("token refresh timed out")except Exception as e:return _standalone_error(f"token refresh failed: {e}")diff --git a/plugins/platforms/irc/adapter.py b/plugins/platforms/irc/adapter.pyindex e2b3416c482..df6970a5456 100644--- a/plugins/platforms/irc/adapter.py+++ b/plugins/platforms/irc/adapter.py@@ -177,7 +177,7 @@ class IRCAdapter(BasePlatformAdapter):self._recv_task = asyncio.create_task(self._receive_loop())try: # wait for registration (001 RPL_WELCOME)await asyncio.wait_for(self._registration_event.wait(), timeout=30.0)- except asyncio.TimeoutError:+ except TimeoutError:logger.error("IRC: registration timed out")await self.disconnect()return self._fail("registration_timeout", "IRC server did not send RPL_WELCOME", retryable=True)@@ -462,7 +462,7 @@ class _StandaloneConn:while (remaining := deadline - self._loop.time()) > 0:try:raw_line = await asyncio.wait_for(self.reader.readuntil(b"\r\n"), timeout=remaining)- except asyncio.TimeoutError:+ except TimeoutError:return Noneexcept asyncio.IncompleteReadError:return _EOFdiff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 9aac259a870..0f288ad1e12 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -2354,7 +2354,7 @@ class MatrixAdapter(BasePlatformAdapter):joined = await asyncio.wait_for(self._join_room_by_id(room_id), timeout=45.0)if joined and is_direct and inviter:await self._record_dm_room(room_id, inviter)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Matrix: timed out joining invite %s", room_id)finally:self._invite_join_tasks.pop(room_id, None)@@ -3137,7 +3137,7 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_ffor payload in _standalone_payloads(message):try:result = await asyncio.wait_for(_do_send(payload), timeout=30)- except asyncio.TimeoutError:+ except TimeoutError:return send_error("Matrix API timeout (30s)")if not result.get("success"):return resultdiff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.pyindex 5e97ebecf0d..3a8be995c44 100644--- a/plugins/platforms/mattermost/adapter.py+++ b/plugins/platforms/mattermost/adapter.py@@ -347,7 +347,7 @@ class MattermostAdapter(BasePlatformAdapter):else:file_data, ct = await resp.read(), resp.content_type or "application/octet-stream"break- except (aiohttp.ClientError, asyncio.TimeoutError) as exc:+ except (TimeoutError, aiohttp.ClientError) as exc:if attempt == 2:logger.warning("Mattermost: failed to download %s after %d attempts: %s", url, attempt + 1, exc)return await fallback()diff --git a/plugins/platforms/simplex/adapter.py b/plugins/platforms/simplex/adapter.pyindex 2805d0fec36..8e0d5f1ac00 100644--- a/plugins/platforms/simplex/adapter.py+++ b/plugins/platforms/simplex/adapter.py@@ -434,7 +434,7 @@ class SimplexAdapter(BasePlatformAdapter):try:await ws.send(json.dumps({"corrId": corr_id, "cmd": command}))return await asyncio.wait_for(fut, timeout=timeout)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("SimpleX: command timed out: %s", command[:50])except Exception as e:logger.warning("SimpleX: command failed: %s — %s", command[:50], e)diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 5b1f016a4b0..40d5904004c 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -70,7 +70,7 @@ async def _await_with_thread_deadline(result = await run_bounded_async(awaitable, timeout, label=label, on_abandon=on_abandon, dump_on_blocked_loop=dump_on_blocked_loop)if result.timed_out:- raise asyncio.TimeoutError(f"timed out after {timeout:.0f}s ({label})")+ raise TimeoutError(f"timed out after {timeout:.0f}s ({label})")return result.value@@ -1911,7 +1911,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):# Losers are NOT cancelled here; the finally below does it.await _await_with_thread_deadline(asyncio.wait({progress_wait, error_wait}, return_when=asyncio.FIRST_COMPLETED), timeout=_INITIAL_POLLING_PROGRESS_TIMEOUT)- except asyncio.TimeoutError as exc:+ except TimeoutError as exc:raise OSError("Telegram getUpdates made no progress within "f"{_INITIAL_POLLING_PROGRESS_TIMEOUT:.0f}s during initial "@@ -2007,7 +2007,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):if app and app.updater and app.updater.running:try:await _await_with_thread_deadline(app.updater.stop(), timeout=_UPDATER_STOP_TIMEOUT)- except asyncio.TimeoutError:+ except TimeoutError:message = (f"Telegram updater.stop() did not finish before the {what} deadline; ""rebuilding the adapter instead of reusing an Updater whose lifecycle lock may still be held.")@@ -2035,8 +2035,8 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):# Not a retry: no counter bump, no backoff, no in-place stop/drain. The supervisor's rebuild# runs disconnect(), which performs the same bounded updater.stop() and app.shutdown().message = (- "Telegram polling stall confirmed (%s); rebuilding the adapter instead of reusing "- "a wedged Updater/dispatcher in place." % _redact_telegram_error_text(error)+ f"Telegram polling stall confirmed ({_redact_telegram_error_text(error)}); rebuilding the adapter instead of reusing "+ "a wedged Updater/dispatcher in place.")await self._go_fatal_network(message, "[%s] %s (rebuilding adapter via supervisor)", self.name, message)return@@ -2048,8 +2048,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):attempt = self._polling_network_error_countif attempt > MAX_NETWORK_RETRIES:message = (- "Telegram polling could not reconnect after %d network error retries. "- "Escalating to gateway recovery." % MAX_NETWORK_RETRIES)+ f'Telegram polling could not reconnect after {MAX_NETWORK_RETRIES:d} network error retries. Escalating to gateway recovery.')await self._go_fatal_network(message, "[%s] %s Last error: %s", self.name, message, _redact_telegram_error_text(error))returndelay = min(BASE_DELAY * (2 ** (attempt - 1)), MAX_DELAY)@@ -2138,7 +2137,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):recovery_task.cancel()self._set_fatal_error("telegram_network_error",- "Telegram reconnect task wedged for %.0fs; forcing gateway reconnect." % stuck_for,+ f"Telegram reconnect task wedged for {stuck_for:.0f}s; forcing gateway reconnect.",retryable=True)await self._handoff_polling_fatal_error()return@@ -2171,7 +2170,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):self._check_ingress_dispatch_stall()except asyncio.CancelledError:return- except (asyncio.TimeoutError, OSError) as probe_err:+ except (TimeoutError, OSError) as probe_err:self._schedule_polling_recovery(probe_err, reason="heartbeat probe")except Exception as probe_err:# Non-connectivity errors (e.g. TelegramError 401) aren't CLOSE-WAIT symptoms.@@ -2228,7 +2227,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):returntry:info = await asyncio.wait_for(get_webhook_info(), probe_timeout) # type: ignore[arg-type]- except (asyncio.TimeoutError, OSError):+ except (TimeoutError, OSError):return # connectivity symptom for the get_me() path, not a stuck-queue signalpending = int(getattr(info, "pending_update_count", 0) or 0)if pending <= 0:@@ -2278,9 +2277,9 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):generation = getattr(self, "_polling_generation", 0)self._schedule_polling_recovery(_PollingStallError(- "ingress healthy but deaf: PTB dispatcher made no progress for %d heartbeats with %d update(s) "- "fetched but not dispatched (%d received, %d dispatched, generation %d)"- % (_INGRESS_DISPATCH_STALL_HEARTBEATS, received - dispatched, received, dispatched, generation)),+ f"ingress healthy but deaf: PTB dispatcher made no progress for {_INGRESS_DISPATCH_STALL_HEARTBEATS} "+ f"heartbeats with {received - dispatched} update(s) fetched but not dispatched "+ f"({received} received, {dispatched} dispatched, generation {generation})"),reason="ingress dispatch stall watchdog")async def _check_polling_stall(self) -> None:@@ -2309,8 +2308,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):# error-level line, so a stall does not announce itself twice.self._schedule_polling_recovery(_PollingStallError(- "getUpdates made no progress for %.0fs (generation %d; polling stall watchdog)"- % (stalled_for, getattr(self, "_polling_generation", 0))),+ f"getUpdates made no progress for {stalled_for:.0f}s (generation {getattr(self, '_polling_generation', 0)}; polling stall watchdog)"),reason="polling stall watchdog")def _verifier_stale(self, generation: int, progress: asyncio.Event) -> bool:@@ -2454,11 +2452,11 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):return# Retries exhausted — fatal so the runner surfaces it and the user knows to act.message = (- "Telegram polling could not recover after %d retries (%ds total wait). "+ f"Telegram polling could not recover after {MAX_CONFLICT_RETRIES} retries "+ f"({sum(10 + i * 10 for i in range(1, MAX_CONFLICT_RETRIES + 1))}s total wait). ""The previous gateway session is still held open on Telegram's servers, ""or another process is using the same bot token. To recover: ensure no other Hermes or OpenClaw instance is running "- "with this token, then restart the gateway with 'hermes gateway restart'."- % (MAX_CONFLICT_RETRIES, sum(10 + i * 10 for i in range(1, MAX_CONFLICT_RETRIES + 1))))+ "with this token, then restart the gateway with 'hermes gateway restart'.")logger.error("[%s] %s Original error: %s", self.name, message, _redact_telegram_error_text(error))# Snapshot whether WE transition to fatal: a concurrent retry task suspended past the entry# guard reaches this branch too. Only the first transition notifies.@@ -2467,7 +2465,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):try:if self._app and self._app.updater:await _await_with_thread_deadline(self._app.updater.stop(), timeout=_UPDATER_STOP_TIMEOUT)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] updater.stop() timed out after exhausting conflict retries (likely CLOSE-WAIT socket); proceeding to fatal notify", self.name)except Exception as stop_error:logger.warning(@@ -3040,7 +3038,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):self._app.initialize(), timeout=_init_timeout, on_abandon=lambda app=self._app: _shutdown_abandoned_app(app),label="telegram-init")break- except asyncio.TimeoutError:+ except TimeoutError:rebuild_app = Trueif _attempt >= _max_connect - 1:raise OSError(@@ -4947,7 +4945,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):label = t("platform.telegram.gmail_triage.failed", verb=verb, detail=last_line[:80])logger.error("[%s] gmail-triage callback failed: verb=%s arg=%s rc=%s stderr=%s", self.name, verb, arg, proc.returncode, stderr_text)- except asyncio.TimeoutError:+ except TimeoutError:label = t("platform.telegram.gmail_triage.timed_out", verb=verb)logger.error("[%s] gmail-triage callback timed out: verb=%s arg=%s", self.name, verb, arg)except Exception as exc:diff --git a/plugins/platforms/telegram/telegram_ids.py b/plugins/platforms/telegram/telegram_ids.pyindex 90f4a715e66..8007e9d1f50 100644--- a/plugins/platforms/telegram/telegram_ids.py+++ b/plugins/platforms/telegram/telegram_ids.py@@ -10,7 +10,7 @@ from typing import Any, Union_TELEGRAM_USERNAME_RE = re.compile(r"@[A-Za-z0-9_]{4,32}")-def normalize_telegram_chat_id(chat_id: Any) -> Union[int, str]:+def normalize_telegram_chat_id(chat_id: Any) -> int | str:"""Bot API-compatible chat_id: numeric values (incl. negative channel IDs) as ``int``, anythingelse (e.g. ``@username``) as a stripped string; never raises."""chat_id_str = str(chat_id).strip()@@ -25,7 +25,7 @@ def looks_like_telegram_username(chat_id: Any) -> bool:return bool(_TELEGRAM_USERNAME_RE.fullmatch(str(chat_id).strip()))-def parse_telegram_username_target(target_ref: Any) -> Union[str, None]:+def parse_telegram_username_target(target_ref: Any) -> str | None:"""Return the value when it is an ``@username`` target, else ``None``."""value = str(target_ref).strip()return value if looks_like_telegram_username(value) else Nonediff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.pyindex a5e1277671f..d893ea38439 100644--- a/plugins/platforms/wecom/adapter.py+++ b/plugins/platforms/wecom/adapter.py@@ -610,7 +610,7 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccif reply_req_id:try:response = await self._send_reply_markdown(reply_req_id, content)- except (asyncio.TimeoutError, RuntimeError) as passive_err:+ except (TimeoutError, RuntimeError) as passive_err:# req_id may be stale after a reconnect — proactive send needs none.logger.warning("[%s] Passive reply failed (%s), falling back to proactive send", self.name, passive_err)response = await self._send_proactive_markdown(chat_id, content)@@ -619,7 +619,7 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccreturn SendResult(success=False, error="No req_id available for group chat (passive reply required)")else:response = await self._send_proactive_markdown(chat_id, content)- except asyncio.TimeoutError:+ except TimeoutError:return SendResult(success=False, error="Timeout sending message to WeCom")except Exception as exc:logger.error("[%s] Send failed: %s", self.name, exc)diff --git a/plugins/platforms/wecom/media.py b/plugins/platforms/wecom/media.pyindex 6d445fa0463..eff23fc3667 100644--- a/plugins/platforms/wecom/media.py+++ b/plugins/platforms/wecom/media.py@@ -323,7 +323,7 @@ class WeComMediaMixin:else:media_response = await self._send_media_message(chat_id, prepared["final_type"], upload_result["media_id"])logger.info("[%s] %s OK: %s", self.name, "send_reply_media" if reply_req_id else "send_media_message", media_response)- except asyncio.TimeoutError:+ except TimeoutError:logger.error("[%s] TIMEOUT in _send_media_source for %s", self.name, media_source)return SendResult(success=False, error="Timeout sending media to WeCom")except Exception as exc:diff --git a/plugins/platforms/wecom/streaming.py b/plugins/platforms/wecom/streaming.pyindex 61d2a9777d4..421c70fd191 100644--- a/plugins/platforms/wecom/streaming.py+++ b/plugins/platforms/wecom/streaming.py@@ -119,7 +119,7 @@ class WeComStreamMixin:return {"errcode": 0, "errmsg": "sent_nonblocking"}try:return await asyncio.wait_for(future, timeout=self._REPLY_ACK_TIMEOUT)- except asyncio.TimeoutError:+ except TimeoutError:# Bytes went out, ack is late — WeCom already rendered it; raising caused duplicates.logger.warning("[%s] Final frame ack timeout (req_id=%s) — treating as delivered (matches official wecom-openclaw-plugin behaviour). No fallback send.", self.name, normalized)return {"errcode": 0, "errmsg": "ack_timeout_assumed_delivered", "ack_pending": True}@@ -133,7 +133,7 @@ class WeComStreamMixin:logger.debug("[%s] _send_reply_queued: final waiting for pending ack drain — req_id=%s pending_stream_id=%s pending_finish=%s pending_sent_at=%.1fs_ago", *pending_desc, _elapsed(pending_frame.sent_at))try:await asyncio.wait_for(asyncio.shield(pending_frame.future), timeout=self._REPLY_ACK_TIMEOUT)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("[%s] Reply ack timeout waiting for pending (req_id=%s) — pending_stream_id=%s pending_finish=%s elapsed=%.1fs. Possible causes: ack cmd filtered, ack req_id mismatch, or WeCom did not ack.",*pending_desc, _elapsed(pending_frame.sent_at),diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex c83c7646acc..75fbdd4d60a 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -406,7 +406,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return False, Nonetry:return True, await resp.json()- except asyncio.TimeoutError:+ except TimeoutError:raise # a body that never arrives is no answer, the same as headers that never arriveexcept Exception:return True, None@@ -485,7 +485,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return Truestale_reason = f"running={running_hash or 'unversioned'}, disk={disk_hash}" if running_hash != disk_hash else "send_read_receipts config changed"print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")- except asyncio.TimeoutError:+ except TimeoutError:self._bridge_probe_timed_out = True # something holds the port but gave no identity; connect() leaves itexcept Exception:pass # Bridge not running, start a new onediff --git a/plugins/web/firecrawl/provider.py b/plugins/web/firecrawl/provider.pyindex 6cebc0fe223..e619ff89fc1 100644--- a/plugins/web/firecrawl/provider.py+++ b/plugins/web/firecrawl/provider.py@@ -296,7 +296,7 @@ async def _scrape_one(url: str, formats: list[str], format: Optional[str]) -> di),timeout=60,)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("Firecrawl scrape timed out for %s", url)return _error_entry(url, _SCRAPE_TIMEOUT_MSG)payload = _extract_scrape_payload(scrape_result)diff --git a/ruff.strict.toml b/ruff.strict.tomlindex 24a8928ed6f..5a7221f726e 100644--- a/ruff.strict.toml+++ b/ruff.strict.toml@@ -358,7 +358,7 @@ select = ["UP004","UP005","UP006",- # "UP007",+ "UP007","UP008","UP009","UP010",@@ -370,15 +370,15 @@ select = ["UP019","UP020","UP021",- # "UP022",+ "UP022","UP023","UP024","UP025","UP026",- # "UP028",+ "UP028","UP029","UP030",- # "UP031",+ "UP031","UP032","UP033","UP034",@@ -387,12 +387,12 @@ select = [# "UP037","UP039","UP040",- # "UP041",+ "UP041","UP043","UP044",- # "UP045",- # "UP046",- # "UP047",+ #"UP045",+ # "UP046", # deferred: fix is PEP 695 class syntax (3.12+), project floor is py3.11+ # "UP047", # deferred: fix is PEP 695 generic-callable syntax (3.12+), project floor is py3.11"UP049","UP050","FURB105",diff --git a/skills/productivity/docx/scripts/docx_common.py b/skills/productivity/docx/scripts/docx_common.pyindex 2745153a374..aa0808008cb 100644--- a/skills/productivity/docx/scripts/docx_common.py+++ b/skills/productivity/docx/scripts/docx_common.py@@ -19,8 +19,7 @@ def iter_all_paragraphs(doc, include_headers_footers: bool = True):def _iter_container(container):- for para in container.paragraphs:- yield para+ yield from container.paragraphsfor table in container.tables:yield from _iter_table(table)@@ -28,8 +27,7 @@ def _iter_container(container):def _iter_table(table):for row in table.rows:for cell in row.cells:- for para in cell.paragraphs:- yield para+ yield from cell.paragraphsfor nested in cell.tables:yield from _iter_table(nested)diff --git a/skills/productivity/docx/scripts/docx_revisions.py b/skills/productivity/docx/scripts/docx_revisions.pyindex 70aff305692..d50e00ae199 100644--- a/skills/productivity/docx/scripts/docx_revisions.py+++ b/skills/productivity/docx/scripts/docx_revisions.py@@ -47,8 +47,7 @@ INS, DEL = q("ins"), q("del")def _iter_revision_elements(doc):"""Yield every w:ins / w:del element across body, headers, footers."""for root in iter_part_roots(doc):- for el in root.iter(INS, DEL):- yield el+ yield from root.iter(INS, DEL)def _rev_text(el) -> str:diff --git a/skills/productivity/powerpoint/scripts/pptx_from_template.py b/skills/productivity/powerpoint/scripts/pptx_from_template.pyindex 024036ae45b..d097510d92c 100644--- a/skills/productivity/powerpoint/scripts/pptx_from_template.py+++ b/skills/productivity/powerpoint/scripts/pptx_from_template.py@@ -23,7 +23,7 @@ def fill_tokens(prs, values):from pptx_edit import replace_text # same scripts/ directorytotal = 0for token, value in values.items():- total += replace_text(prs, "{{%s}}" % token, str(value))+ total += replace_text(prs, f"{{{{{token}}}}}", str(value))return totaldiff --git a/skills/research/grounded-citations/scripts/sources.py b/skills/research/grounded-citations/scripts/sources.pyindex 225367be654..fb7633abe71 100644--- a/skills/research/grounded-citations/scripts/sources.py+++ b/skills/research/grounded-citations/scripts/sources.py@@ -304,8 +304,7 @@ def render_sources(key = f"source{s['id']}"title = s.get("title") or s["url"]lines.append(- "@misc{%s,\n title = {%s},\n howpublished = {\\url{%s}},\n note = {Accessed %s}\n}"- % (key, title, s["url"], s.get("accessed", ""))+ "@misc{{{},\n title = {{{}}},\n howpublished = {{\\url{{{}}}}},\n note = {{Accessed {}}}\n}}".format(key, title, s["url"], s.get("accessed", "")))return "\n".join(lines)if style == "footnotes":diff --git a/tests/acp_adapter/test_ping_suppression.py b/tests/acp_adapter/test_ping_suppression.pyindex 70c10cb5e20..1c96f367d87 100644--- a/tests/acp_adapter/test_ping_suppression.py+++ b/tests/acp_adapter/test_ping_suppression.py@@ -181,7 +181,7 @@ async def test_bare_ping_request_produces_proper_response_and_no_stderr_noise(in_write_file.close()try:await asyncio.wait_for(agent_task, timeout=2.0)- except (asyncio.TimeoutError, Exception):+ except (TimeoutError, Exception):agent_task.cancel()try:await agent_taskdiff --git a/tests/agent/test_auxiliary_auth_rung_fallthrough.py b/tests/agent/test_auxiliary_auth_rung_fallthrough.pyindex 4fcda2a2dac..f24baa11f26 100644--- a/tests/agent/test_auxiliary_auth_rung_fallthrough.py+++ b/tests/agent/test_auxiliary_auth_rung_fallthrough.py@@ -58,15 +58,15 @@ def _auth_error():def _credit_error():return _ApiError(- "Error code: 404 - Model '%s' requires available credits. "- "Your account balance is too low to use paid models." % AUX_MODEL,+ f"Error code: 404 - Model '{AUX_MODEL}' requires available credits. "+ "Your account balance is too low to use paid models.",status_code=404,)class _FakeClient:api_key = "sk-test"- base_url = "https://%s/v1" % NOUS_HOST+ base_url = f"https://{NOUS_HOST}/v1"class _ExplicitProviderClient:@@ -74,7 +74,7 @@ class _ExplicitProviderClient:base_url = "https://vertex.example/v1"-def _ladder(base_info=("https://%s/v1" % NOUS_HOST), resolved_provider="nous"):+def _ladder(base_info=(f"https://{NOUS_HOST}/v1"), resolved_provider="nous"):return aux._aux_recovery_ladder(_auth_error(),client=_FakeClient(),@@ -121,7 +121,7 @@ def test_post_refresh_retry_owns_the_ladder_outcome(if rung == "nous":monkeypatch.setattr(aux, "_refresh_nous_auxiliary_client",lambda **kwargs: (_FakeClient(), AUX_MODEL))- expected_step, expected_base = "call", ("https://%s/v1" % NOUS_HOST)+ expected_step, expected_base = "call", (f"https://{NOUS_HOST}/v1")else:monkeypatch.setattr(aux, "_auth_refresh_provider_for_route",lambda *a, **kw: "codex")@@ -151,8 +151,8 @@ def test_post_refresh_retry_owns_the_ladder_outcome(result = aux._drive_ladder(ladder, perform)except _ApiError as exc:pytest.fail(- "the ladder let %r escape instead of falling through to the configured "- "fallback chain (steps performed: %s)" % (exc, performed)+ f"the ladder let {exc!r} escape instead of falling through to the configured "+ f"fallback chain (steps performed: {performed})")assert performed == [expected_step], "the post-refresh retry is the only request"@@ -273,7 +273,7 @@ def nous_ladder_endpoint(monkeypatch):return resolve_address(host, *args, **kwargs)monkeypatch.setattr(socket, "getaddrinfo", local_nous_address)- monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost,%s" % NOUS_HOST)+ monkeypatch.setenv("NO_PROXY", f"127.0.0.1,localhost,{NOUS_HOST}")class Handler(BaseHTTPRequestHandler):def _send(self, status, payload):@@ -298,8 +298,8 @@ def nous_ladder_endpoint(monkeypatch):self._send(401, {"error": {"message": "Unauthorized", "type": "authentication_error"}})returnself._send(404, {"error": {- "message": "Model '%s' requires available credits. Your account "- "balance is too low to use paid models." % AUX_MODEL,+ "message": f"Model '{AUX_MODEL}' requires available credits. Your account "+ "balance is too low to use paid models.","type": "invalid_request_error","code": "insufficient_credits",}})@@ -326,7 +326,7 @@ def nous_ladder_endpoint(monkeypatch):)thread.start()try:- yield "http://%s:%d" % (NOUS_HOST, server.server_port), requests+ yield f'http://{NOUS_HOST}:{server.server_port:d}', requestsfinally:aux.shutdown_cached_clients()server.shutdown()@@ -338,7 +338,7 @@ def test_auth_refresh_retry_failure_reaches_the_configured_chain_over_http(tmp_path, monkeypatch, nous_ladder_endpoint):"""End to end: the configured chain must serve the retry the refresh could not."""host_url, requests = nous_ladder_endpoint- local_url = "http://127.0.0.1:%s" % host_url.rsplit(":", 1)[1]+ local_url = "http://127.0.0.1:{}".format(host_url.rsplit(":", 1)[1])monkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.setenv("AUX_FB_KEY", "fallback-test-key")config = {@@ -376,8 +376,7 @@ def test_auth_refresh_retry_failure_reaches_the_configured_chain_over_http(body.get("model") for path, body in requests if path == "/v1/chat/completions"]assert seen == [AUX_MODEL, AUX_MODEL, FALLBACK_MODEL], (- "401, then the refreshed retry fails on credits, then the configured chain: %r"- % (seen,)+ f"401, then the refreshed retry fails on credits, then the configured chain: {seen!r}")@@ -400,5 +399,5 @@ def test_exhausted_ladder_raises_the_narrowed_error(monkeypatch, hermetic):aux._drive_ladder(_ladder(), perform)assert raised.value is failure, (- "the ladder must surface the actionable retry failure, got %r" % (raised.value,))+ f"the ladder must surface the actionable retry failure, got {raised.value!r}")assert hermetic == [failure]diff --git a/tests/agent/test_create_openai_client_proxy_env.py b/tests/agent/test_create_openai_client_proxy_env.pyindex 3d158a84f60..1b401b5528f 100644--- a/tests/agent/test_create_openai_client_proxy_env.py+++ b/tests/agent/test_create_openai_client_proxy_env.py@@ -85,7 +85,7 @@ def test_create_openai_client_routes_via_proxy_when_env_set(mock_openai, monkeyphttp_client = _extract_http_client(forwarded)assert isinstance(http_client, httpx.Client), ("Expected _create_openai_client to inject a keepalive-enabled "- "httpx.Client; got %r" % (http_client,)+ f"httpx.Client; got {http_client!r}")# Verify a proxy mount exists. httpx Client(proxy=...) rewrites _mounts so# the proxied pool (HTTPProxy) sits alongside the base transport.@@ -96,7 +96,7 @@ def test_create_openai_client_routes_via_proxy_when_env_set(mock_openai, monkeyp]assert "HTTPProxy" in proxied_pools, ("Expected httpx.Client to route through HTTPProxy when HTTPS_PROXY is "- "set; found pools: %r" % (proxied_pools,)+ f"set; found pools: {proxied_pools!r}")http_client.close()@@ -126,7 +126,7 @@ def test_create_openai_client_no_proxy_when_env_unset(mock_openai, monkeypatch):]assert "HTTPProxy" not in pool_types, ("No proxy env set but httpx.Client still mounted HTTPProxy; "- "pools were %r" % (pool_types,)+ f"pools were {pool_types!r}")http_client.close()diff --git a/tests/agent/test_intent_ack_continuation.py b/tests/agent/test_intent_ack_continuation.pyindex 5340d1c5c48..13eb6a46554 100644--- a/tests/agent/test_intent_ack_continuation.py+++ b/tests/agent/test_intent_ack_continuation.py@@ -21,7 +21,7 @@ from agent.agent_runtime_helpers import (def _agent(- mode: Union[str, bool, list] = "auto",+ mode: str | bool | list = "auto",api_mode="chat_completions",model="anthropic/claude-sonnet-4",):diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.pyindex 90bfc5da8cf..f96d4bc6e07 100644--- a/tests/agent/test_nous_rate_guard.py+++ b/tests/agent/test_nous_rate_guard.py@@ -319,8 +319,7 @@ class TestRateGuardStateEncoding:# which is what this guards against.with open(path, "w", encoding="utf-8") as f:f.write(- '{"reset_at": %d, "provider": "中文", "recorded_at": 0}'- % (int(time.time()) + 3600)+ f'{{"reset_at": {int(time.time()) + 3600:d}, "provider": "中文", "recorded_at": 0}}')real_open = builtins.opendiff --git a/tests/agent/test_provider_id_mint_normalization.py b/tests/agent/test_provider_id_mint_normalization.pyindex 9d4308d565e..8d0a53ec89b 100644--- a/tests/agent/test_provider_id_mint_normalization.py+++ b/tests/agent/test_provider_id_mint_normalization.py@@ -13,7 +13,7 @@ from run_agent import AIAgentdef _tool_call(raw_id, n, **extra):return SimpleNamespace(id=raw_id, type="function",- function=SimpleNamespace(name="read_file", arguments='{"path": "%s"}' % n), **extra,+ function=SimpleNamespace(name="read_file", arguments=f'{{"path": "{n}"}}'), **extra,)diff --git a/tests/e2e/core/chaos/_gateway_harness.py b/tests/e2e/core/chaos/_gateway_harness.pyindex c2bf6525aea..0c9c24383b3 100644--- a/tests/e2e/core/chaos/_gateway_harness.py+++ b/tests/e2e/core/chaos/_gateway_harness.py@@ -123,7 +123,7 @@ class GatewayProc:try:conn, _ = listener.accept()break- except socket.timeout:+ except TimeoutError:if self.proc.poll() is not None:raise AssertionError(f"gateway exited during boot rc={self.proc.returncode}\n{self.log_tail()}")if time.monotonic() >= deadline:diff --git a/tests/e2e/core/security/test_workspace_escape.py b/tests/e2e/core/security/test_workspace_escape.pyindex 4536e55d02f..0c2923eff54 100644--- a/tests/e2e/core/security/test_workspace_escape.py+++ b/tests/e2e/core/security/test_workspace_escape.py@@ -123,7 +123,7 @@ def _confined_steps(lay: Layout) -> list[Step]:lay.link("linkdir", lay.out)lay.link("innerlink.txt", lay.ws / "inner.txt")lay.marks["token"] = token = H.canary("oauth-token")- (lay.hh / "auth.json").write_text('{"providers": {"nous": {"access_token": "%s"' % token, encoding="utf-8")+ (lay.hh / "auth.json").write_text(f'{{"providers": {{"nous": {{"access_token": "{token}"', encoding="utf-8")quarantined = (lay.hh / "auth.json.corrupt", token)return [Step("write_dotdot", "write_file", {"path": "../../outside/new-dotdot.txt", "content": "x"},diff --git a/tests/fakes/fake_llm_provider.py b/tests/fakes/fake_llm_provider.pyindex 8ebbcbc6969..e2483f83508 100644--- a/tests/fakes/fake_llm_provider.py+++ b/tests/fakes/fake_llm_provider.py@@ -112,7 +112,7 @@ class Raw:content_type: str = "application/json"-Response = Union[Text, ToolCall, Error, Hang, DropMidStream, StallMidStream, Raw]+Response = Text | ToolCall | Error | Hang | DropMidStream | StallMidStream | RawResponder = Callable[[dict[str, Any]], Response]diff --git a/tests/fakes/platforms/_standin.py b/tests/fakes/platforms/_standin.pyindex 27c23584901..683bd6b79a2 100644--- a/tests/fakes/platforms/_standin.py+++ b/tests/fakes/platforms/_standin.py@@ -195,4 +195,5 @@ class StandinServer:p = {k: (v[:80] + "…" if isinstance(v, str) and len(v) > 80 else v) for k, v in c.params.items()if k not in ("reply_markup", "blocks", "embeds", "components")}out.append(f" {'!' if c.faulted else ' '}{c.method} {json.dumps(p, default=str)[:240]}")- return "--- stand-in calls (last %d)\n%s" % (len(rows), "\n".join(out))+ return f'''--- stand-in calls (last {len(rows):d})\n{"""+""".join(out)}'''diff --git a/tests/fakes/platforms/telegram_standin.py b/tests/fakes/platforms/telegram_standin.pyindex bb621b2d6a6..8aae1d892ac 100644--- a/tests/fakes/platforms/telegram_standin.py+++ b/tests/fakes/platforms/telegram_standin.py@@ -49,13 +49,13 @@ def mdv2_error(text: str) -> str | None:if text.startswith("```", i):end = text.find("```", i + 3)if end < 0:- return "Can't find end of Pre entity at byte offset %d" % i+ return f"Can't find end of Pre entity at byte offset {i:d}"i = end + 3continueif ch == "`":end = text.find("`", i + 1)if end < 0:- return "Can't find end of Code entity at byte offset %d" % i+ return f"Can't find end of Code entity at byte offset {i:d}"i = end + 1continueif ch == "[":@@ -212,7 +212,7 @@ class TelegramStandin(StandinServer):self._update_event.clear()try:await asyncio.wait_for(self._update_event.wait(), remaining)- except asyncio.TimeoutError:+ except TimeoutError:return []def _push(self, update: dict[str, Any], replay: bool = False) -> None:diff --git a/tests/fakes/providers/anthropic_messages.py b/tests/fakes/providers/anthropic_messages.pyindex fb666f9fdbf..44fbfcebfe1 100644--- a/tests/fakes/providers/anthropic_messages.py+++ b/tests/fakes/providers/anthropic_messages.py@@ -78,7 +78,7 @@ class ToolUse:id: str | None = None-Block = Union[Thinking, Text, ToolUse]+Block = Thinking | Text | ToolUse@dataclass@@ -110,7 +110,7 @@ class DropStream:after_deltas: int = 2-Response = Union[Reply, ApiError, DropStream]+Response = Reply | ApiError | DropStreamResponder = Callable[[dict[str, Any]], Response]_ERROR_MODELS: dict[str, type] = {diff --git a/tests/fakes/providers/bedrock_converse.py b/tests/fakes/providers/bedrock_converse.pyindex 11733028fdd..6ec066eba02 100644--- a/tests/fakes/providers/bedrock_converse.py+++ b/tests/fakes/providers/bedrock_converse.py@@ -89,7 +89,7 @@ class ToolUse:tool_use_id: str = ""-Block = Union[Text, Reasoning, ToolUse]+Block = Text | Reasoning | ToolUse@dataclass@@ -132,7 +132,7 @@ class Drop:clean: bool = False-Reply = Union[Turn, HttpError, StreamException, Drop]+Reply = Turn | HttpError | StreamException | Drop# --------------------------------------------------------------------------------------------------diff --git a/tests/fakes/providers/chat_variants.py b/tests/fakes/providers/chat_variants.pyindex a5e52886cef..20a298f37e4 100644--- a/tests/fakes/providers/chat_variants.py+++ b/tests/fakes/providers/chat_variants.py@@ -86,7 +86,7 @@ class CDropToolCall:partial_args: str = '{"path": "x'-Step = Union[CText, CTools, CError, CStreamError, CDropToolCall]+Step = CText | CTools | CError | CStreamError | CDropToolCallResponder = Callable[[dict[str, Any]], Step]_STREAM_ADAPTER = TypeAdapter(CompletionCreateParamsStreaming)diff --git a/tests/fakes/providers/openai_responses.py b/tests/fakes/providers/openai_responses.pyindex cf9b70bb085..06485b555a3 100644--- a/tests/fakes/providers/openai_responses.py+++ b/tests/fakes/providers/openai_responses.py@@ -82,7 +82,7 @@ class FunctionCall:args: dict[str, Any] | str = field(default_factory=dict)-Item = Union[Reasoning, Message, FunctionCall]+Item = Reasoning | Message | FunctionCall@dataclass@@ -115,7 +115,7 @@ class HttpError:retry_after: float | None = None-Step = Union[Turn, SoftFail, HttpError]+Step = Turn | SoftFail | HttpErrorResponder = Callable[[dict[str, Any]], Step]_REQUEST_ADAPTER = TypeAdapter(ResponseCreateParamsStreaming)diff --git a/tests/fakes/providers/vertex.py b/tests/fakes/providers/vertex.pyindex c3993ee9bea..4326d0ad877 100644--- a/tests/fakes/providers/vertex.py+++ b/tests/fakes/providers/vertex.py@@ -109,7 +109,7 @@ class Drop:after_chars: int = 10-Response = Union[Say, Call, Fail, Drop]+Response = Say | Call | Fail | DropResponder = Callable[[dict[str, Any]], Response]diff --git a/tests/gateway/test_busy_followup_after_session_release.py b/tests/gateway/test_busy_followup_after_session_release.pyindex 61d817b9686..ac7a9e3032e 100644--- a/tests/gateway/test_busy_followup_after_session_release.py+++ b/tests/gateway/test_busy_followup_after_session_release.py@@ -91,14 +91,7 @@ async def test_followup_started_as_fresh_turn_when_session_released_mid_route(bu# Post-fix: the guard was gone when admission resumed, so the event became# a fresh turn instead of queueing behind a task that no longer exists.assert await _wait_until(lambda: bool(turn.dispatched)), (- "follow-up was stranded: dispatched=%r pending=%r debounce=%r active=%r tasks=%r"- % (- turn.dispatched,- dict(adapter._pending_messages),- dict(adapter._text_debounce),- dict(adapter._active_sessions),- {k: t.done() for k, t in adapter._session_tasks.items()},- )+ f"follow-up was stranded: dispatched={turn.dispatched!r} pending={dict(adapter._pending_messages)!r} debounce={dict(adapter._text_debounce)!r} active={dict(adapter._active_sessions)!r} tasks={({k: t.done() for k, t in adapter._session_tasks.items()})!r}")assert turn.dispatched[0] == "did you get that?"assert followup._gateway_accepted is Truediff --git a/tests/gateway/test_buzz_websocket.py b/tests/gateway/test_buzz_websocket.pyindex 56a15e6d58f..742746e29e4 100644--- a/tests/gateway/test_buzz_websocket.py+++ b/tests/gateway/test_buzz_websocket.py@@ -184,7 +184,7 @@ async def test_websocket_loop_reconnects_when_read_goes_silent(monkeypatch, capltask.cancel()try:await asyncio.wait_for(task, 5.0)- except (asyncio.CancelledError, asyncio.TimeoutError):+ except (TimeoutError, asyncio.CancelledError):passassert len(sockets) >= 2, "idle read watchdog did not force a reconnect"@@ -247,7 +247,7 @@ async def test_websocket_loop_reconnects_when_discovery_send_sees_closed_socket(task.cancel()try:await asyncio.wait_for(task, 5.0)- except (asyncio.CancelledError, asyncio.TimeoutError):+ except (TimeoutError, asyncio.CancelledError):passassert len(sockets) >= 2, "a closed socket seen by the discovery sweep did not force a reconnect"@@ -286,7 +286,7 @@ async def test_websocket_loop_backs_off_and_publishes_retrying_on_clean_relay_cltask.cancel()try:await asyncio.wait_for(task, 5.0)- except (asyncio.CancelledError, asyncio.TimeoutError):+ except (TimeoutError, asyncio.CancelledError):passassert len(sockets) == 1, f"clean close must back off before reconnecting, got {len(sockets)} connects in 0.3s"diff --git a/tests/gateway/test_cleanup_off_loop.py b/tests/gateway/test_cleanup_off_loop.pyindex 2dc1b9feda5..eedb7c7f535 100644--- a/tests/gateway/test_cleanup_off_loop.py+++ b/tests/gateway/test_cleanup_off_loop.py@@ -119,7 +119,7 @@ async def test_cleanup_off_loop_times_out_gracefully(caplog):async def _instant_timeout(aw, timeout=None):if asyncio.iscoroutine(aw):aw.close()- raise asyncio.TimeoutError+ raise TimeoutErrorimport gateway.run as _rundiff --git a/tests/gateway/test_dingtalk_reconnect_circuit_breaker.py b/tests/gateway/test_dingtalk_reconnect_circuit_breaker.pyindex b04681a62bd..364c9989106 100644--- a/tests/gateway/test_dingtalk_reconnect_circuit_breaker.py+++ b/tests/gateway/test_dingtalk_reconnect_circuit_breaker.py@@ -69,7 +69,7 @@ async def test_real_sdk_start_with_issue_type_error_is_bounded_and_fatal(caplog)patch("asyncio.sleep", new=fast_sleep):try:await asyncio.wait_for(adapter._run_stream(), timeout=2.0)- except asyncio.TimeoutError:+ except TimeoutError:passsdk = [r for r in caplog.records if r.name == "dingtalk_stream.client"]assert len(sdk) <= 5, len(sdk)diff --git a/tests/gateway/test_discord_connect.py b/tests/gateway/test_discord_connect.pyindex b3e231b6e00..18002e175f0 100644--- a/tests/gateway/test_discord_connect.py+++ b/tests/gateway/test_discord_connect.py@@ -335,7 +335,7 @@ async def test_connect_timeout_cancels_bot_task(monkeypatch):)async def fake_wait_for_ready(ready_event, bot_task, timeout):- raise asyncio.TimeoutError()+ raise TimeoutError()monkeypatch.setattr(discord_platform, "_wait_for_ready_or_bot_exit", fake_wait_for_ready@@ -701,7 +701,7 @@ async def test_post_connect_initialization_retries_fingerprint_after_timeout(tmp"created": 1,"deleted": 0,}- sync = AsyncMock(side_effect=[asyncio.TimeoutError(), summary])+ sync = AsyncMock(side_effect=[TimeoutError(), summary])monkeypatch.setattr(adapter, "_safe_sync_slash_commands", sync)await adapter._run_post_connect_initialization()diff --git a/tests/gateway/test_email.py b/tests/gateway/test_email.pyindex a5011d5fde9..9b272d4fa30 100644--- a/tests/gateway/test_email.py+++ b/tests/gateway/test_email.py@@ -1235,7 +1235,7 @@ class TestConnectSmtp(unittest.TestCase):adapter = self._make_adapter("587")- with patch("smtplib.SMTP", side_effect=_socket.timeout("timed out")), \+ with patch("smtplib.SMTP", side_effect=TimeoutError("timed out")), \patch.object(email_mod, "_IPv4SMTP") as mock_ipv4_smtp:mock_server = MagicMock()mock_ipv4_smtp.return_value = mock_server@@ -1253,7 +1253,7 @@ class TestConnectSmtp(unittest.TestCase):adapter = self._make_adapter("465")- with patch("smtplib.SMTP_SSL", side_effect=_socket.timeout("timed out")), \+ with patch("smtplib.SMTP_SSL", side_effect=TimeoutError("timed out")), \patch.object(email_mod, "_IPv4SMTP_SSL") as mock_ipv4_smtp_ssl:mock_server = MagicMock()mock_ipv4_smtp_ssl.return_value = mock_serverdiff --git a/tests/gateway/test_executor_pool_isolation.py b/tests/gateway/test_executor_pool_isolation.pyindex ef27c72b275..d31afd54eca 100644--- a/tests/gateway/test_executor_pool_isolation.py+++ b/tests/gateway/test_executor_pool_isolation.py@@ -47,7 +47,7 @@ async def _abandon_housekeeping(runner, count, timeout):runner._run_housekeeping_in_executor(runner._cleanup_agent_resources, object()),timeout=timeout,)- except asyncio.TimeoutError:+ except TimeoutError:pass # exactly what the production callers doawait asyncio.gather(*(one() for _ in range(count)))diff --git a/tests/gateway/test_handoff_watcher_resilience.py b/tests/gateway/test_handoff_watcher_resilience.pyindex 4efed0eadd9..6de8a84d887 100644--- a/tests/gateway/test_handoff_watcher_resilience.py+++ b/tests/gateway/test_handoff_watcher_resilience.py@@ -119,7 +119,7 @@ async def test_slow_handoff_does_not_block_later_polls(monkeypatch):# it must finish once the stuck handoff is released.try:await asyncio.wait_for(task, timeout=5)- except asyncio.TimeoutError:+ except TimeoutError:task.cancel()raise AssertionError("watcher did not finish after the handoff was released")diff --git a/tests/gateway/test_history_media_current_turn.py b/tests/gateway/test_history_media_current_turn.pyindex ee28944e299..586786fa880 100644--- a/tests/gateway/test_history_media_current_turn.py+++ b/tests/gateway/test_history_media_current_turn.py@@ -56,8 +56,7 @@ def _tts_tool_row(path: str) -> dict[str, Any]:return {"role": "tool","content": (- '{"success": true, "file_path": "%s", "media_tag": "MEDIA:%s"}'- % (path, path)+ f'{{"success": true, "file_path": "{path}", "media_tag": "MEDIA:{path}"}}'),}diff --git a/tests/gateway/test_irc_adapter.py b/tests/gateway/test_irc_adapter.pyindex 7083cab9aca..a9e643821e7 100644--- a/tests/gateway/test_irc_adapter.py+++ b/tests/gateway/test_irc_adapter.py@@ -377,7 +377,7 @@ class TestIRCStandaloneSend:try:return await coroexcept asyncio.IncompleteReadError:- raise asyncio.TimeoutError()+ raise TimeoutError()monkeypatch.setattr(_irc_mod.asyncio, "wait_for", _fast_timeout)diff --git a/tests/gateway/test_keep_typing_timeout.py b/tests/gateway/test_keep_typing_timeout.pyindex 53b607ea017..48fba92c5dd 100644--- a/tests/gateway/test_keep_typing_timeout.py+++ b/tests/gateway/test_keep_typing_timeout.py@@ -85,7 +85,7 @@ class TestKeepTypingTimeoutPerTick:stop_event.set()try:await asyncio.wait_for(task, timeout=2.0)- except asyncio.TimeoutError:+ except TimeoutError:task.cancel()pytest.fail("_keep_typing did not exit within 2s of stop_event.set() — "diff --git a/tests/gateway/test_loop_liveness_watchdog.py b/tests/gateway/test_loop_liveness_watchdog.pyindex a579c685d0a..90c91a57a33 100644--- a/tests/gateway/test_loop_liveness_watchdog.py+++ b/tests/gateway/test_loop_liveness_watchdog.py@@ -333,6 +333,5 @@ def test_heartbeat_write_does_not_block_the_loop_it_monitors():# Off-loop, the ticker gets roughly block_s / 0.02 ticks. Inline it gets at# most one, because the loop cannot run anything while fsync blocks it.assert ticks >= 5, (- "the loop made only %d tick(s) while the heartbeat was writing — "- "the write is blocking the loop again" % ticks+ f'the loop made only {ticks:d} tick(s) while the heartbeat was writing — the write is blocking the loop again')diff --git a/tests/gateway/test_matrix.py b/tests/gateway/test_matrix.pyindex 601efab20c5..9b875c526ed 100644--- a/tests/gateway/test_matrix.py+++ b/tests/gateway/test_matrix.py@@ -1260,7 +1260,7 @@ class TestMatrixSyncLoop:),# Plain timeout echoing the pagination token, which embeds "401".(- asyncio.TimeoutError(+ TimeoutError("Connection timeout to host https://matrix.example.org/_matrix/""client/v3/sync?timeout=30000&since=s72802_401975_486_12943_11759"),diff --git a/tests/gateway/test_model_command_flat_string_config.py b/tests/gateway/test_model_command_flat_string_config.pyindex 218c8cfcb0d..bfb7b1d69c0 100644--- a/tests/gateway/test_model_command_flat_string_config.py+++ b/tests/gateway/test_model_command_flat_string_config.py@@ -98,7 +98,7 @@ async def test_model_global_persists_when_config_has_flat_string_model(tmp_path,# The persist block must have rewritten config.yaml as a nested dict.written = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))assert isinstance(written["model"], dict), (- "model: should be coerced to a dict, got %r" % (written["model"],)+ "model: should be coerced to a dict, got {!r}".format(written["model"]))assert written["model"]["default"] == "gpt-5.5"assert written["model"]["provider"] == "openrouter"diff --git a/tests/gateway/test_model_picker_persist.py b/tests/gateway/test_model_picker_persist.pyindex 62b7ce8d9b2..b05df8aa34e 100644--- a/tests/gateway/test_model_picker_persist.py+++ b/tests/gateway/test_model_picker_persist.py@@ -192,7 +192,7 @@ async def test_picker_tap_global_flag_persists(tmp_path, monkeypatch, seed_modelassert "gpt-5.5" in confirmationwritten = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))assert isinstance(written["model"], dict), (- "model: should be coerced to a dict, got %r" % (written["model"],)+ "model: should be coerced to a dict, got {!r}".format(written["model"]))assert written["model"]["default"] == "gpt-5.5"assert written["model"]["provider"] == "openrouter"diff --git a/tests/gateway/test_reset_button_deadlock.py b/tests/gateway/test_reset_button_deadlock.pyindex 903acfb4c48..7b1fa6715ee 100644--- a/tests/gateway/test_reset_button_deadlock.py+++ b/tests/gateway/test_reset_button_deadlock.py@@ -185,7 +185,7 @@ async def test_reset_completes_when_cleanup_times_out(caplog):async def _instant_timeout(aw, timeout=None):if asyncio.iscoroutine(aw):aw.close()- raise asyncio.TimeoutError+ raise TimeoutErrorrunner = _make_runner_with_cached_agent(lambda: None)diff --git a/tests/gateway/test_silent_partial_delivery.py b/tests/gateway/test_silent_partial_delivery.pyindex edb4786a436..09009f34104 100644--- a/tests/gateway/test_silent_partial_delivery.py+++ b/tests/gateway/test_silent_partial_delivery.py@@ -422,7 +422,7 @@ class TestDiscordTransportClassification:assert not mod._is_discord_transport_error(RuntimeError("error code: 50013: Missing Permissions"))- assert not mod._is_discord_transport_error(asyncio.TimeoutError())+ assert not mod._is_discord_transport_error(TimeoutError())@pytest.mark.asyncioasync def test_send_without_client_reports_send_path_degraded(self):diff --git a/tests/gateway/test_suppression_contract_matrix.py b/tests/gateway/test_suppression_contract_matrix.pyindex 104e6bcf1c1..a339ced0ebe 100644--- a/tests/gateway/test_suppression_contract_matrix.py+++ b/tests/gateway/test_suppression_contract_matrix.py@@ -157,7 +157,7 @@ async def _drive(adapter, *, interrupt: bool):consumer.finish()try:await asyncio.wait_for(task, timeout=2.0)- except (asyncio.TimeoutError, asyncio.CancelledError):+ except (TimeoutError, asyncio.CancelledError):task.cancel()return consumerdiff --git a/tests/gateway/test_telegram_network_reconnect.py b/tests/gateway/test_telegram_network_reconnect.pyindex b603cdf7977..2203634a308 100644--- a/tests/gateway/test_telegram_network_reconnect.py+++ b/tests/gateway/test_telegram_network_reconnect.py@@ -629,7 +629,7 @@ async def test_heartbeat_loop_skips_reconnect_if_already_in_progress():async def timeout_wait_for(coro, timeout):if asyncio.iscoroutine(coro):coro.close()- raise asyncio.TimeoutError()+ raise TimeoutError()with patch("asyncio.sleep", side_effect=fast_sleep):with patch("plugins.platforms.telegram.adapter.asyncio.wait_for", side_effect=timeout_wait_for):diff --git a/tests/gateway/test_telegram_polling_progress.py b/tests/gateway/test_telegram_polling_progress.pyindex a341b970551..39fd7caf984 100644--- a/tests/gateway/test_telegram_polling_progress.py+++ b/tests/gateway/test_telegram_polling_progress.py@@ -300,7 +300,7 @@ async def test_non_finite_fallback_discovery_timeout_uses_finite_default(monkeypif getattr(getattr(awaitable, "cr_code", None), "co_name", "") == "stuck_discovery":assert timeout == 5.0awaitable.close()- raise asyncio.TimeoutError()+ raise TimeoutError()return await original_deadline(awaitable, timeout, **_kwargs)monkeypatch.setattr(tg_adapter, "discover_fallback_ips", stuck_discovery)diff --git a/tests/gateway/test_webhook_offloop_delivery.py b/tests/gateway/test_webhook_offloop_delivery.pyindex d233986d5d7..8a7d01838bb 100644--- a/tests/gateway/test_webhook_offloop_delivery.py+++ b/tests/gateway/test_webhook_offloop_delivery.py@@ -60,7 +60,7 @@ class TestGithubCommentDeliveryOffLoop:stop = Truetry:await asyncio.wait_for(task, timeout=2)- except asyncio.TimeoutError:+ except TimeoutError:task.cancel()assert result.success is Truediff --git a/tests/gateway/test_wecom_double_send.py b/tests/gateway/test_wecom_double_send.pyindex 842545fdc40..78129ae6b28 100644--- a/tests/gateway/test_wecom_double_send.py+++ b/tests/gateway/test_wecom_double_send.py@@ -88,7 +88,7 @@ async def _gateway_join_and_cancel(stream_task: asyncio.Task, join_timeout: floa"""try:await asyncio.wait_for(stream_task, timeout=join_timeout)- except (asyncio.TimeoutError, asyncio.CancelledError):+ except (TimeoutError, asyncio.CancelledError):stream_task.cancel()try:await stream_taskdiff --git a/tests/gateway/test_whatsapp_bridge_pidfile.py b/tests/gateway/test_whatsapp_bridge_pidfile.pyindex 5e728461f0e..bee0cda9e73 100644--- a/tests/gateway/test_whatsapp_bridge_pidfile.py+++ b/tests/gateway/test_whatsapp_bridge_pidfile.py@@ -103,7 +103,7 @@ class TestKillPortProcess:# A separate process holding a *client* connection to that port.client = subprocess.Popen([sys.executable, "-c",- "import socket,time; c=socket.create_connection(('127.0.0.1',%d)); time.sleep(0.2)" % port,+ f"import socket,time; c=socket.create_connection(('127.0.0.1',{port:d})); time.sleep(0.2)",])try:conn, _ = srv.accept() # establish the client connectiondiff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.pyindex 1412a113136..ef6a7a6d5df 100644--- a/tests/hermes_cli/test_gateway.py+++ b/tests/hermes_cli/test_gateway.py@@ -91,8 +91,7 @@ def _run_native_windows_gateway_start_diag(completed = subprocess.run([sys.executable, "-c", script],stdin=subprocess.DEVNULL,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ capture_output=True,creationflags=windows_detach_flags_without_breakaway(),text=True,encoding="utf-8",@@ -203,8 +202,7 @@ def test_gateway_run_subprocess_preserves_daemon_exit_codes(completed = subprocess.run([sys.executable, "-c", script],stdin=stdin,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ capture_output=True,text=True,env=env,timeout=30,diff --git a/tests/hermes_cli/test_gateway_job_teardown_live.py b/tests/hermes_cli/test_gateway_job_teardown_live.pyindex 555109832e5..d4f7f3b4f19 100644--- a/tests/hermes_cli/test_gateway_job_teardown_live.py+++ b/tests/hermes_cli/test_gateway_job_teardown_live.py@@ -143,15 +143,15 @@ class TestJobObjectMechanismLive:# updater/watcher exiting while its job tears down.return ("import subprocess, sys, pathlib\n"- "sys.path.insert(0, r'%s')\n"+ f"sys.path.insert(0, r'{_REPO_ROOT!s}')\n""from hermes_cli._subprocess_compat import (\n"" windows_detach_flags, windows_detach_flags_without_breakaway)\n"- "flags = %s()\n"- "p = subprocess.Popen([sys.executable, '-c', %r],\n"+ f"flags = {flags_helper}()\n"+ f"p = subprocess.Popen([sys.executable, '-c', {_SLEEPER!r}],\n"" creationflags=flags, stdin=subprocess.DEVNULL,\n"" stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"- "pathlib.Path(r'%s').write_text(str(p.pid), encoding='utf-8')\n"- ) % (str(_REPO_ROOT), flags_helper, _SLEEPER, pid_file)+ f"pathlib.Path(r'{pid_file}').write_text(str(p.pid), encoding='utf-8')\n"+ )def _run_in_job(self, tmp_path: Path, flags_helper: str) -> int:pid_file = tmp_path / f"{flags_helper}.pid"diff --git a/tests/hermes_cli/test_hermes_home_shared_launchers.py b/tests/hermes_cli/test_hermes_home_shared_launchers.pyindex d4e51c0e79e..f992f81f69a 100644--- a/tests/hermes_cli/test_hermes_home_shared_launchers.py+++ b/tests/hermes_cli/test_hermes_home_shared_launchers.py@@ -138,7 +138,7 @@ def test_dead_exe_never_shadows_kept_cmd(tmp_path, monkeypatch):local.mkdir(parents=True)_write_dead_exe(local / "hermes.exe", tmp_path / "gone" / "python.exe")(local / "hermes.cmd").write_text(- '@echo off\r\n"%s" -I -c "eA==" %%*\r\n' % default_python, encoding="utf-8")+ f'@echo off\r\n"{default_python}" -I -c "eA==" %*\r\n', encoding="utf-8")assert _launchers._launcher_python(local / "hermes.exe") == tmp_path / "gone" / "python.exe"_isolate(tmp_path, monkeypatch, temp_home)diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.pyindex b9f228728ae..05c30bd0c2a 100644--- a/tests/hermes_cli/test_pty_session.py+++ b/tests/hermes_cli/test_pty_session.py@@ -373,7 +373,7 @@ async def _two_idle_sessions_first_close_gated(reg):bridges = []for i in range(2):bridge = FakeBridge([b""])- s = PtySession("k%d" % i, bridge, buffer_cap=1024, read_timeout=0.01)+ s = PtySession(f'k{i:d}', bridge, buffer_cap=1024, read_timeout=0.01)await s.start()s.detach(None) # unattached, last_detached_at setreg._sessions[s.key] = sdiff --git a/tests/hermes_cli/test_shared_metrics_send_migration.py b/tests/hermes_cli/test_shared_metrics_send_migration.pyindex 1a17d2f789c..fbf71f430e7 100644--- a/tests/hermes_cli/test_shared_metrics_send_migration.py+++ b/tests/hermes_cli/test_shared_metrics_send_migration.py@@ -136,11 +136,11 @@ class TestUpgradeFromPreSendDatabase:""",(f"pkg-{i}",- "2026-08-2%d" % i,- "2026-08-2%d" % (i + 1),+ f'2026-08-2{i:d}',+ f'2026-08-2{i + 1:d}',json.dumps({"package_id": f"pkg-{i}"}),- "2026-08-2%dT00:00:00Z" % i,- "2026-08-2%dT01:00:00Z" % i,+ f'2026-08-2{i:d}T00:00:00Z',+ f'2026-08-2{i:d}T01:00:00Z',),)connection.commit()diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex 4bc17484d5c..e82375c0299 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -178,13 +178,13 @@ def test_an_adopted_baseline_never_replaces_this_runs_own(tmp_path, monkeypatch)def _orphan(tmp_path: Path, profiles: dict) -> None:"""A record whose owner — a real ``hermes update`` stand-in — was SIGKILLed after writing it."""- owner = _child("""+ owner = _child(f"""import timefrom hermes_cli import update_pause_record as r- r.write(r.stamp_tree({"resume_needed": True, "profiles": %r}), owner=r.identity())+ r.write(r.stamp_tree({{"resume_needed": True, "profiles": {profiles!r}}}), owner=r.identity())print("written", flush=True)time.sleep(120)- """ % profiles, env={"HERMES_HOME": str(tmp_path)})+ """, env={"HERMES_HOME": str(tmp_path)})assert owner.stdout.readline().strip() == "written"owner.send_signal(signal.SIGKILL) # windows-footgun: ok — module skips on Windowsowner.wait(timeout=10)diff --git a/tests/hermes_cli/test_update_posix_pause.py b/tests/hermes_cli/test_update_posix_pause.pyindex d95aa2e6aba..5025a484545 100644--- a/tests/hermes_cli/test_update_posix_pause.py+++ b/tests/hermes_cli/test_update_posix_pause.py@@ -27,14 +27,14 @@ _UNIT = {"kind": "systemd", "scope": "user", "unit": "hermes-gateway-p2probe.serdef test_a_killed_updaters_supervised_units_are_adopted_by_the_next_update(tmp_path):"""The updater stopped a systemd unit and was SIGKILLed: the next ``hermes update`` must ownrestarting that unit (the record's only debt), never drop it."""- owner = _child("""+ owner = _child(f"""import timefrom hermes_cli import update_pause_record as r- r.write(r.stamp_tree({"platform": "posix", "resume_needed": True, "posix_units": [%r]}),+ r.write(r.stamp_tree({{"platform": "posix", "resume_needed": True, "posix_units": [{_UNIT!r}]}}),owner=r.identity())print("written", flush=True)time.sleep(120)- """ % _UNIT, env={"HERMES_HOME": str(tmp_path)})+ """, env={"HERMES_HOME": str(tmp_path)})assert owner.stdout.readline().strip() == "written"owner.send_signal(signal.SIGKILL) # windows-footgun: ok — module skips on Windowsowner.wait(timeout=10)diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.pyindex 0eabb5cd9ee..b29a255f802 100644--- a/tests/hermes_cli/test_update_wedged_gateway.py+++ b/tests/hermes_cli/test_update_wedged_gateway.py@@ -806,7 +806,7 @@ class TestLoopTickTcpWitness:while not stop.is_set():try:conn, _ = srv.accept()- except socket.timeout:+ except TimeoutError:continuetry:conn.sendall(b"1")diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex 4a8e6f876d0..6dd2cd85dca 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -233,7 +233,7 @@ class TestPersistedMergeWitness:rows = _rows(db, "s")assert [r["content"] for r in rows] == ["first, never answered\n\nsecond", "second"]assert rows[0]["message_uid"] == dangling["message_uid"]- assert _absorbed(db, "s") == ['["%s"]' % prompt["message_uid"], None]+ assert _absorbed(db, "s") == ['["{}"]'.format(prompt["message_uid"]), None]restored = db.get_messages_as_conversation("s")assert restored[0]["_absorbed_message_uids"] == [prompt["message_uid"]]assert "_absorbed_message_uids" not in restored[1]diff --git a/tests/hermes_state/test_writer_conn_thread_safety.py b/tests/hermes_state/test_writer_conn_thread_safety.pyindex ec0a266f160..7a1ca3a2ca2 100644--- a/tests/hermes_state/test_writer_conn_thread_safety.py+++ b/tests/hermes_state/test_writer_conn_thread_safety.py@@ -66,10 +66,10 @@ class TestConcurrentReadersDoNotRaceTheWriter:while not stop.is_set():try:db.append_messages_batch(sid, [- {"role": "user", "content": "u%d" % n},- {"role": "assistant", "content": "a%d" % n},- {"role": "tool", "content": "t%d" % n,- "tool_name": "x", "tool_call_id": "c%d" % n},+ {"role": "user", "content": f'u{n:d}'},+ {"role": "assistant", "content": f'a{n:d}'},+ {"role": "tool", "content": f't{n:d}',+ "tool_name": "x", "tool_call_id": f'c{n:d}'},])n += 1except Exception as exc:diff --git a/tests/plugins/test_kanban_events_tail.py b/tests/plugins/test_kanban_events_tail.pyindex 856650a132c..7b9085edd92 100644--- a/tests/plugins/test_kanban_events_tail.py+++ b/tests/plugins/test_kanban_events_tail.py@@ -97,7 +97,7 @@ async def _drive(monkeypatch, mod, ws, conn, polls: int) -> None:waits += 1awaitable.close()if waits <= polls:- raise asyncio.TimeoutError+ raise TimeoutErrorreturn {"type": "websocket.disconnect"}monkeypatch.setattr(mod.asyncio, "wait_for", _wait_for)diff --git a/tests/plugins/test_kanban_ws_idle_disconnect.py b/tests/plugins/test_kanban_ws_idle_disconnect.pyindex d254ac498c0..4d92f06faff 100644--- a/tests/plugins/test_kanban_ws_idle_disconnect.py+++ b/tests/plugins/test_kanban_ws_idle_disconnect.py@@ -160,7 +160,7 @@ async def test_stream_events_reuses_connection_and_closes_after_disconnect(wait_calls += 1awaitable.close()if wait_calls <= 2:- raise asyncio.TimeoutError+ raise TimeoutErrorreturn {"type": "websocket.disconnect"}monkeypatch.setattr(mod.asyncio, "wait_for", _poll_twice_then_disconnect)@@ -215,7 +215,7 @@ async def test_stream_events_closes_connection_when_cancelled(monkeypatch):wait_calls += 1if wait_calls == 1:awaitable.close()- raise asyncio.TimeoutError+ raise TimeoutErrorreturn await awaitablemonkeypatch.setattr(mod.asyncio, "wait_for", _poll_once_then_wait)diff --git a/tests/pm/activation_support.py b/tests/pm/activation_support.pyindex a12dfbf4046..7c9f9bb7247 100644--- a/tests/pm/activation_support.py+++ b/tests/pm/activation_support.py@@ -131,7 +131,7 @@ def fake_store(tmp_path: Path) -> tuple[Path, Path]:interpreter = entry / ("python.exe" if sys.platform.startswith("win") else "bin/python3")interpreter.parent.mkdir(parents=True, exist_ok=True)real = spawnable_python()- wrapper = "#!/bin/sh\nexec '%s' \"$@\"\n" % posix(real)+ wrapper = f"#!/bin/sh\nexec '{posix(real)}' \"$@\"\n"interpreter.write_text(wrapper, encoding="utf-8")interpreter.chmod(0o755)diff --git a/tests/pm/test_progress.py b/tests/pm/test_progress.pyindex a5d5fe41a43..b181ee9067b 100644--- a/tests/pm/test_progress.py+++ b/tests/pm/test_progress.py@@ -20,7 +20,7 @@ def test_ci_streams_and_an_explicit_choice_overrides_it():def test_contained_run_shows_output_only_when_the_child_fails(monkeypatch, fails):monkeypatch.setenv("HERMES_VERBOSE", "0")stream = io.StringIO()- script = "import sys\nfor i in range(200): print('noise', i)\nprint('the real error')\nsys.exit(%d)" % fails+ script = f"import sys\nfor i in range(200): print('noise', i)\nprint('the real error')\nsys.exit({fails:d})"command = [sys.executable, "-c", script]if fails:with pytest.raises(subprocess.CalledProcessError):diff --git a/tests/scripts/test_run_in_hermes_env.py b/tests/scripts/test_run_in_hermes_env.pyindex 552c32b0a29..61a2bfd6da7 100644--- a/tests/scripts/test_run_in_hermes_env.py+++ b/tests/scripts/test_run_in_hermes_env.py@@ -50,7 +50,7 @@ def _shim(path: Path) -> None:"""Quote in posix form: a /bin/sh script treats backslashes in an unquotedword as escapes (same pattern as tests/pm/activation_support.py)."""path.parent.mkdir(parents=True, exist_ok=True)- path.write_text("#!/bin/sh\nexec '%s' \"$@\"\n" % posix(Path(sys.executable)), encoding="utf-8")+ path.write_text(f"#!/bin/sh\nexec '{posix(Path(sys.executable))}' \"$@\"\n", encoding="utf-8")path.chmod(0o755)diff --git a/tests/tools/test_bot_desktop_lease.py b/tests/tools/test_bot_desktop_lease.pyindex 9e5c83aac80..354f519268b 100644--- a/tests/tools/test_bot_desktop_lease.py+++ b/tests/tools/test_bot_desktop_lease.py@@ -72,11 +72,11 @@ def test_lease_authority_is_shared_across_processes(tmp_path):import syslease.acquire("desktop-viewer")- probe = ("import sys; sys.path.insert(0, %r)\n"+ probe = (f"import sys; sys.path.insert(0, {os.getcwd()!r})\n""from tools.bot_desktop import lease\n""try:\n lease.assert_agent_may_act(); print('AGENT')\n""except lease.HumanHasControl:\n print('HUMAN')\n"- "lease.release('desktop-viewer')\n") % os.getcwd()+ "lease.release('desktop-viewer')\n")out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, encoding="utf-8", timeout=30,stdin=subprocess.DEVNULL, env={**os.environ, "HERMES_HOME": os.environ["HERMES_HOME"]})assert out.stdout.strip() == "HUMAN", out.stderr@@ -162,14 +162,14 @@ def test_lease_works_without_fcntl(tmp_path):import subprocessimport sys- probe = ("import sys; sys.modules['fcntl'] = None; sys.path.insert(0, %r)\n"+ probe = (f"import sys; sys.modules['fcntl'] = None; sys.path.insert(0, {os.getcwd()!r})\n""from tools.bot_desktop import lease\n""import tools.computer_use.tool\n""assert lease.get().holder == lease.AGENT\n""assert lease.acquire('v1').holder == lease.HUMAN\n""assert lease.get().holder == lease.HUMAN\n""assert lease.release('v1').holder == lease.AGENT\n"- "print('OK')\n") % os.getcwd()+ "print('OK')\n")out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, encoding="utf-8", timeout=60,stdin=subprocess.DEVNULL, env={**os.environ, "HERMES_HOME": str(tmp_path)})assert out.stdout.strip() == "OK", out.stderrdiff --git a/tests/tools/test_cli_approval_exec_ask_leak.py b/tests/tools/test_cli_approval_exec_ask_leak.pyindex 015546c0bc8..e370cb75f2b 100644--- a/tests/tools/test_cli_approval_exec_ask_leak.py+++ b/tests/tools/test_cli_approval_exec_ask_leak.py@@ -226,15 +226,15 @@ class TestExecuteCodeGuardCliDenialBreakerParity:class TestGatewayRunImportDoesNotSetExecAsk:def test_importing_gateway_run_does_not_set_exec_ask(self, tmp_path):"""Incidental imports must not poison CLI ask-mode process-wide."""- script = r"""+ script = rf"""import os, sysos.environ.pop("HERMES_EXEC_ASK", None)-sys.path.insert(0, %r)+sys.path.insert(0, {str(REPO_ROOT)!r})# Avoid starting the gateway; only import the module for _gateway_runner_ref# style side imports.import gateway.run # noqa: F401print("EXEC_ASK=" + repr(os.environ.get("HERMES_EXEC_ASK")))-""" % (str(REPO_ROOT),)+"""hermes_home = tmp_path / "import-test-home"proc = subprocess.run([sys.executable, "-c", script],diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.pyindex 2a288d169ae..104a94c52c5 100644--- a/tests/tools/test_code_execution.py+++ b/tests/tools/test_code_execution.py@@ -902,7 +902,7 @@ class TestRpcTokenAuthorization(unittest.TestCase):def accept(self):if self._served:- raise socket.timeout()+ raise TimeoutError()self._served = Truereturn self._conn, ("peer", 0)diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex 8bc8147b853..1208745da20 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -1220,7 +1220,7 @@ class TestCuaDriverSessionReconnect:stderr = ""# Daemon returns a path, not inline base64.stdout = ('{"element_count": 7, "tree_markdown": "- [0] AXButton",'- ' "screenshot_file_path": "%s"}' % str(shot))+ f' "screenshot_file_path": "{shot!s}"}}')import subprocess as _sporig_run = _sp.rundiff --git a/tests/tools/test_daemon_pool.py b/tests/tools/test_daemon_pool.pyindex 5a48bc0b45b..0ff7b485bcc 100644--- a/tests/tools/test_daemon_pool.py+++ b/tests/tools/test_daemon_pool.py@@ -65,7 +65,7 @@ def test_wedged_worker_does_not_block_interpreter_exit():exits as soon as the main thread returns."""script = (- "import sys; sys.path.insert(0, %r)\n"+ f"import sys; sys.path.insert(0, {str(_repo_root())!r})\n""from tools.daemon_pool import DaemonThreadPoolExecutor\n""import time\n""pool = DaemonThreadPoolExecutor(max_workers=1)\n"@@ -73,7 +73,7 @@ def test_wedged_worker_does_not_block_interpreter_exit():"time.sleep(0.3)\n""pool.shutdown(wait=False)\n""print('main-done', flush=True)\n"- ) % (str(_repo_root()),)+ )proc = subprocess.run([sys.executable, "-c", script],capture_output=True,diff --git a/tests/tools/test_file_operations_edge_cases.py b/tests/tools/test_file_operations_edge_cases.pyindex 742e4467e90..4b37d87a979 100644--- a/tests/tools/test_file_operations_edge_cases.py+++ b/tests/tools/test_file_operations_edge_cases.py@@ -185,17 +185,17 @@ def test_json_write_refuses_only_introduced_nonstandard_constants(tmp_path, tokeops = ShellFileOperations(LocalEnvironment(cwd=str(tmp_path)), cwd=str(tmp_path))clean = tmp_path / "clean.json"clean.write_text('{"value": 1}\n', encoding="utf-8")- result = ops.write_file(str(clean), '{"value": %s}\n' % token)+ result = ops.write_file(str(clean), f'{{"value": {token}}}\n')assert result.error and token in result.errorassert clean.read_text(encoding="utf-8") == '{"value": 1}\n'- quoted = '{"value": ["%s", 1.5, null]}\n' % token+ quoted = f'{{"value": ["{token}", 1.5, null]}}\n'assert ops.write_file(str(clean), quoted).error is Noneassert clean.read_text(encoding="utf-8") == quotedlegacy = tmp_path / "legacy.json"- legacy.write_text('{"value": %s, "n": 1}\n' % token, encoding="utf-8")- edited = '{"value": %s, "n": 2}\n' % token+ legacy.write_text(f'{{"value": {token}, "n": 1}}\n', encoding="utf-8")+ edited = f'{{"value": {token}, "n": 2}}\n'assert ops.write_file(str(legacy), edited).error is Noneassert legacy.read_text(encoding="utf-8") == editeddiff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 21c2357ea27..ac36fb63478 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -396,7 +396,7 @@ def test_passthrough_accepted_before_an_adapter_owns_the_name_stops_forwarding_ielse:home = child_env / "hermes"home.mkdir(exist_ok=True)- (home / "config.yaml").write_text("terminal:\n env_passthrough: [%s]\n" % ", ".join(names), encoding="utf-8")+ (home / "config.yaml").write_text("terminal:\n env_passthrough: [{}]\n".format(", ".join(names)), encoding="utf-8")builders = [lambda: local._make_run_env({}), lambda: local._sanitize_subprocess_env(dict(os.environ)),lambda: _scrub_child_env(dict(os.environ))]assert [observe_child(b(), names) for b in builders] == [diff --git a/tests/tools/test_mcp_cancelled_error_propagation.py b/tests/tools/test_mcp_cancelled_error_propagation.pyindex 88f232fc254..ad5c2827f73 100644--- a/tests/tools/test_mcp_cancelled_error_propagation.py+++ b/tests/tools/test_mcp_cancelled_error_propagation.py@@ -49,7 +49,7 @@ class TestCancelledErrorPropagation:await asyncio.wait_for(task, timeout=15.0)except asyncio.CancelledError:return "cancelled_cleanly"- except asyncio.TimeoutError:+ except TimeoutError:# If we hit this, the reconnect loop swallowed the cancel# and stayed wedged — the exact #9930 bug.task.cancel()@@ -83,7 +83,7 @@ class TestCancelledErrorPropagation:server._task.cancel()try:await asyncio.wait_for(server._task, timeout=15.0)- except (asyncio.CancelledError, asyncio.TimeoutError):+ except (TimeoutError, asyncio.CancelledError):passreturn server._task.done()diff --git a/tests/tools/test_mcp_capability_gating.py b/tests/tools/test_mcp_capability_gating.pyindex f689298a7cd..936ee1ba352 100644--- a/tests/tools/test_mcp_capability_gating.py+++ b/tests/tools/test_mcp_capability_gating.py@@ -362,7 +362,7 @@ class TestKeepaliveProbeFallback:task = MCPServerTask("test")task.initialize_result = _caps(tools=SimpleNamespace())task.session = SimpleNamespace(- send_ping=AsyncMock(side_effect=asyncio.TimeoutError()),+ send_ping=AsyncMock(side_effect=TimeoutError()),list_tools=AsyncMock(return_value=SimpleNamespace(tools=[])),)@@ -379,8 +379,8 @@ class TestKeepaliveProbeFallback:task = MCPServerTask("test")task.initialize_result = _caps(tools=SimpleNamespace())task.session = SimpleNamespace(- send_ping=AsyncMock(side_effect=asyncio.TimeoutError()),- list_tools=AsyncMock(side_effect=asyncio.TimeoutError()),+ send_ping=AsyncMock(side_effect=TimeoutError()),+ list_tools=AsyncMock(side_effect=TimeoutError()),)with pytest.raises((TimeoutError, asyncio.TimeoutError)):@@ -394,7 +394,7 @@ class TestKeepaliveProbeFallback:task = MCPServerTask("test")task.initialize_result = _caps(prompts=SimpleNamespace()) # no toolstask.session = SimpleNamespace(- send_ping=AsyncMock(side_effect=asyncio.TimeoutError()),+ send_ping=AsyncMock(side_effect=TimeoutError()),list_tools=AsyncMock(),)diff --git a/tests/tools/test_mcp_circuit_breaker.py b/tests/tools/test_mcp_circuit_breaker.pyindex 66f7c9e9588..e626b1e2c8d 100644--- a/tests/tools/test_mcp_circuit_breaker.py+++ b/tests/tools/test_mcp_circuit_breaker.py@@ -487,7 +487,7 @@ def test_run_loop_parks_instead_of_exiting_then_revives(monkeypatch, tmp_path):task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())@@ -567,7 +567,7 @@ def test_initial_connect_budget_parks_instead_of_exiting_then_revives(monkeypatctask._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_client_cert.py b/tests/tools/test_mcp_client_cert.pyindex 6b0ce2af89e..b9d9888ca07 100644--- a/tests/tools/test_mcp_client_cert.py+++ b/tests/tools/test_mcp_client_cert.py@@ -275,7 +275,7 @@ class TestSSEClientCert:}),timeout=2.0,)- except (asyncio.TimeoutError, StopAsyncIteration, Exception):+ except (TimeoutError, StopAsyncIteration, Exception):passasyncio.run(drive())@@ -321,7 +321,7 @@ class TestSSEClientCert:}),timeout=2.0,)- except (asyncio.TimeoutError, StopAsyncIteration, Exception):+ except (TimeoutError, StopAsyncIteration, Exception):passasyncio.run(drive())@@ -372,7 +372,7 @@ class TestSSEClientCert:}),timeout=2.0,)- except (asyncio.TimeoutError, StopAsyncIteration, Exception):+ except (TimeoutError, StopAsyncIteration, Exception):passasyncio.run(drive())diff --git a/tests/tools/test_mcp_failure_classification.py b/tests/tools/test_mcp_failure_classification.pyindex b3d87bc03ad..4231124e8de 100644--- a/tests/tools/test_mcp_failure_classification.py+++ b/tests/tools/test_mcp_failure_classification.py@@ -214,7 +214,7 @@ def test_permanent_failure_parks_without_retry_ladder(monkeypatch, tmp_path, captask._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())@@ -314,7 +314,7 @@ def test_initial_auth_failure_parks_and_revives_after_relogin(task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_oauth_manager.py b/tests/tools/test_mcp_oauth_manager.pyindex 9d0ae5fd69a..4c38bc0b05f 100644--- a/tests/tools/test_mcp_oauth_manager.py+++ b/tests/tools/test_mcp_oauth_manager.py@@ -29,8 +29,7 @@ def test_manager_isolates_same_named_servers_by_profile_home(tmp_path, monkeypatstorage = HermesTokenStorage("shared")storage._tokens_path().parent.mkdir(parents=True, exist_ok=True)storage._tokens_path().write_text(- '{"access_token":"%s","token_type":"Bearer","expires_in":3600}'- % access_token+ f'{{"access_token":"{access_token}","token_type":"Bearer","expires_in":3600}}', encoding="utf-8")finally:reset_hermes_home_override(token)diff --git a/tests/tools/test_mcp_parked_probe_skips_disabled.py b/tests/tools/test_mcp_parked_probe_skips_disabled.pyindex 70e196115f7..47d9911860b 100644--- a/tests/tools/test_mcp_parked_probe_skips_disabled.py+++ b/tests/tools/test_mcp_parked_probe_skips_disabled.py@@ -111,7 +111,7 @@ def test_parked_self_probe_skips_disabled_or_deleted_entry(monkeypatch, tmp_pathtask._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_parked_self_probe.py b/tests/tools/test_mcp_parked_self_probe.pyindex 203a803e63b..87c6ef746c2 100644--- a/tests/tools/test_mcp_parked_self_probe.py+++ b/tests/tools/test_mcp_parked_self_probe.py@@ -136,7 +136,7 @@ def test_parked_server_self_probes_and_revives(monkeypatch, tmp_path):task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_rapid_drop_budget.py b/tests/tools/test_mcp_rapid_drop_budget.pyindex 9fe10dc6aa6..7c2a45fa311 100644--- a/tests/tools/test_mcp_rapid_drop_budget.py+++ b/tests/tools/test_mcp_rapid_drop_budget.py@@ -125,7 +125,7 @@ def test_flapping_transport_reaches_park_within_budget(monkeypatch, tmp_path):task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())@@ -197,7 +197,7 @@ def test_proven_session_does_not_burn_budget(monkeypatch, tmp_path):task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_reconnect_log_hygiene.py b/tests/tools/test_mcp_reconnect_log_hygiene.pyindex 9bbf68a9336..0bfc8a9b0ff 100644--- a/tests/tools/test_mcp_reconnect_log_hygiene.py+++ b/tests/tools/test_mcp_reconnect_log_hygiene.py@@ -78,7 +78,7 @@ def test_retry_attempts_log_debug_transitions_warn(monkeypatch, tmp_path, caplogtask._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())@@ -145,7 +145,7 @@ def test_initial_retry_attempts_log_debug(monkeypatch, tmp_path, caplog):task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_reconnect_retry_reset.py b/tests/tools/test_mcp_reconnect_retry_reset.pyindex d2e1173eb8b..6a9c6e83a15 100644--- a/tests/tools/test_mcp_reconnect_retry_reset.py+++ b/tests/tools/test_mcp_reconnect_retry_reset.py@@ -117,7 +117,7 @@ def test_reconnect_counter_resets_after_successful_session(monkeypatch, tmp_pathtask._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())@@ -186,7 +186,7 @@ def test_reconnect_counter_still_parks_on_consecutive_failures(monkeypatch, tmp_task._reconnect_event.set()try:await asyncio.wait_for(run_task, timeout=15)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception):+ except (TimeoutError, asyncio.CancelledError, Exception):run_task.cancel()asyncio.run(_scenario())diff --git a/tests/tools/test_mcp_sse_fallback.py b/tests/tools/test_mcp_sse_fallback.pyindex cc5433bdb80..9adfe0eb9db 100644--- a/tests/tools/test_mcp_sse_fallback.py+++ b/tests/tools/test_mcp_sse_fallback.py@@ -67,7 +67,7 @@ def test_sse_only_server_connects_via_fallback(monkeypatch, exc):@pytest.mark.parametrize("exc,ever_connected", [(_http_400(), True), # reconnect after a proven session: never mask the 400- (asyncio.TimeoutError(), False), # timeout is not a transport mismatch+ (TimeoutError(), False), # timeout is not a transport mismatch(_http_400(500), False), # 5xx is a broken server, not SSE-only])def test_no_fallback_on_reconnect_timeout_or_server_error(monkeypatch, exc, ever_connected):diff --git a/tests/tools/test_mcp_sse_transport.py b/tests/tools/test_mcp_sse_transport.pyindex aa92eeb5c5c..d1fe6e44a4c 100644--- a/tests/tools/test_mcp_sse_transport.py+++ b/tests/tools/test_mcp_sse_transport.py@@ -97,7 +97,7 @@ class TestSSEReadTimeout:}),timeout=2.0,)- except (asyncio.TimeoutError, StopAsyncIteration, Exception):+ except (TimeoutError, StopAsyncIteration, Exception):passasyncio.run(drive())@@ -134,7 +134,7 @@ class TestSSEOAuthForwarding:}),timeout=2.0,)- except (asyncio.TimeoutError, StopAsyncIteration, Exception):+ except (TimeoutError, StopAsyncIteration, Exception):passasyncio.run(drive())diff --git a/tests/tools/test_profile_gate_env_isolation.py b/tests/tools/test_profile_gate_env_isolation.pyindex e0d5b23f5af..5911dca4e59 100644--- a/tests/tools/test_profile_gate_env_isolation.py+++ b/tests/tools/test_profile_gate_env_isolation.py@@ -23,7 +23,7 @@ _GATES = {"DISCORD_ALLOW_BOTS": "all", "TELEGRAM_GROUP_ALLOWED_CHATS": "-100", "SLACK_ALLOWED_CHANNELS": "C1","WHATSAPP_GROUP_ALLOW_FROM": "+1555", "GATEWAY_ALLOW_ALL_USERS": "true",}-_PROBE = "import json,os;print(json.dumps({k:os.environ.get(k) for k in %r}))" % sorted(_GATES)+_PROBE = f"import json,os;print(json.dumps({{k:os.environ.get(k) for k in {sorted(_GATES)!r}}}))"def _seen_by_child(env: dict) -> set[str]:diff --git a/tests/tools/test_tool_search_multiquery.py b/tests/tools/test_tool_search_multiquery.pyindex bc87290193b..1b401cfc0cc 100644--- a/tests/tools/test_tool_search_multiquery.py+++ b/tests/tools/test_tool_search_multiquery.py@@ -497,7 +497,7 @@ class TestBatchedDescribe:{}, current_tool_defs=issue_defs, config=cfg))assert "error" in json.loads(tool_search.dispatch_tool_describe({"names": []}, current_tool_defs=issue_defs, config=cfg))- over = ["n%d" % i for i in range(3)]+ over = [f'n{i:d}' for i in range(3)]parsed = json.loads(tool_search.dispatch_tool_describe({"names": over}, current_tool_defs=issue_defs, config=cfg))assert "error" in parseddiff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.pyindex 688c7c25873..5d786f0c87b 100644--- a/tests/tools/test_web_providers_ddgs.py+++ b/tests/tools/test_web_providers_ddgs.py@@ -46,8 +46,7 @@ def _install_fake_ddgs(monkeypatch, *, text_results=None, text_raises=None, text_time.sleep(text_sleep)if text_raises is not None:raise text_raises- for hit in (text_results or []):- yield hit+ yield from (text_results or [])fake.DDGS = _FakeDDGSmonkeypatch.setitem(sys.modules, "ddgs", fake)diff --git a/tests/tui_gateway/contracts/test_generated.py b/tests/tui_gateway/contracts/test_generated.pyindex 323cdbd2a5c..263a4a225e1 100644--- a/tests/tui_gateway/contracts/test_generated.py+++ b/tests/tui_gateway/contracts/test_generated.py@@ -36,9 +36,9 @@ def test_generated_files_are_current(gen):# The emitter inventory the old gateway-events.json scan used, kept as the completeness oracle:# names must come from CODE the gateway runs, never from the contract tables themselves._EMIT_HELPERS = ("_emit", "_broadcast_global_event", "_voice_emit", "_pet_emit", "_emit_tool_lifecycle")-_LITERAL_EMIT = re.compile(r"\b(?:%s)\(\s*\"([a-z_][a-z0-9_.]*)\"" % "|".join(_EMIT_HELPERS))+_LITERAL_EMIT = re.compile(r"\b(?:{})\(\s*\"([a-z_][a-z0-9_.]*)\"".format("|".join(_EMIT_HELPERS)))_REQUEST_HELPERS = ("server_requests\\.send", "server_requests\\.send_async", "_ask", "_read_block")-_LITERAL_REQUEST = re.compile(r"\b(?:%s)\(\s*\"([a-z_][a-z0-9_.]*)\"" % "|".join(_REQUEST_HELPERS))+_LITERAL_REQUEST = re.compile(r"\b(?:{})\(\s*\"([a-z_][a-z0-9_.]*)\"".format("|".join(_REQUEST_HELPERS)))_LITERAL_FRAME = re.compile(r"\"method\":\s*\"event\".{0,120}?\"type\":\s*\"([a-z_][a-z0-9_.]*)\"", re.DOTALL)_SIDE_AGENT = re.compile(r"_spawn_side_agent\((?:[^()]|\([^()]*\))*?\"([a-z_][a-z0-9_.]*\.complete)\"", re.DOTALL)_SUBAGENT_RELAY = re.compile(r"\"(subagent\.[a-z_]+)\"")diff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.pyindex ecd9c244873..46a8b58a478 100644--- a/tools/browser_cdp_tool.py+++ b/tools/browser_cdp_tool.py@@ -302,9 +302,9 @@ def browser_cdp(method: str, params: Optional[dict[str, Any]] = None, target_id:safe_timeout = max(1.0, min(safe_timeout, 300.0))try:result = _run_async(_cdp_call(endpoint, method, call_params, target_id, safe_timeout))- except asyncio.TimeoutError as exc:+ except TimeoutError as exc:return tool_error(f"CDP call timed out after {safe_timeout}s: {exc}", method=method)- except (TimeoutError, RuntimeError) as exc:+ except RuntimeError as exc:return tool_error(str(exc), method=method)except WebSocketException as exc:return tool_error(f"WebSocket error talking to CDP at {endpoint}: {exc}. The browser may have "diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 04932970029..6aa4bd0dcb8 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1248,7 +1248,7 @@ def _capture_vision_screenshot(effective_task_id: str, annotate: bool, screenshoreturn result, screenshot_path, None-def browser_vision(question: str, annotate: bool = False, task_id: Optional[str] = None) -> Union[str, dict[str, Any]]:+def browser_vision(question: str, annotate: bool = False, task_id: Optional[str] = None) -> str | dict[str, Any]:"""Screenshot the current page for visual inspection. Native-vision models get the imageattached to the conversation; otherwise the auxiliary vision model returns a textanalysis. The file is kept and its path returned (MEDIA:<path>)."""diff --git a/tools/code_execution_rpc.py b/tools/code_execution_rpc.pyindex de15d75c843..ebbf704ec49 100644--- a/tools/code_execution_rpc.py+++ b/tools/code_execution_rpc.py@@ -153,7 +153,7 @@ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: litry:conn, _ = server_sock.accept()break- except socket.timeout:+ except TimeoutError:continueif conn is None:return@@ -162,7 +162,7 @@ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: liwhile True:try:chunk = conn.recv(65536)- except socket.timeout:+ except TimeoutError:breakif not chunk:break@@ -184,7 +184,7 @@ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: licall_start=call_start, where="sandbox",) if _rpc_token_ok(request, rpc_token) else tool_error("Unauthorized RPC request")conn.sendall((resp + "\n").encode())- except socket.timeout:+ except TimeoutError:logger.debug("RPC listener socket timeout")except OSError as e:logger.debug("RPC listener socket error: %s", e, exc_info=True)diff --git a/tools/computer_use/cua_backend_input.py b/tools/computer_use/cua_backend_input.pyindex 137c96d139e..2b09856a465 100644--- a/tools/computer_use/cua_backend_input.py+++ b/tools/computer_use/cua_backend_input.py@@ -15,7 +15,7 @@ _FOREGROUND_UNSUPPORTED_MSG = ("The connected cua-driver action schema does not"package version describes the live schema.")# (what, extra args) pointer addressing form; ``extra`` is None when the caller did not supply that form and# may be a callable when computing it has side effects (capability probes) that must follow the refusal checks.-_Variant = tuple[str, Union[None, dict[str, Any], Callable[[], dict[str, Any]]]]+_Variant = tuple[str, None | dict[str, Any] | Callable[[], dict[str, Any]]]def _refuse(action: str, message: str, **fields: Any) -> ActionResult:return ActionResult(ok=False, action=action, message=message, **fields)diff --git a/tools/computer_use/doctor.py b/tools/computer_use/doctor.pyindex 6a5c1bc4574..616e0461961 100644--- a/tools/computer_use/doctor.py+++ b/tools/computer_use/doctor.py@@ -47,7 +47,7 @@ def _run_cli(binary: str, *args: str, timeout: float) -> subprocess.CompletedProreturn subprocess.run([binary, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,env=_sanitized_cua_env(), stdin=subprocess.DEVNULL)-def _cli_text(binary: str, *args: str, timeout: float, exc_types: tuple[type, ...] = _IO_EXC) -> Union[subprocess.CompletedProcess, BaseException]:+def _cli_text(binary: str, *args: str, timeout: float, exc_types: tuple[type, ...] = _IO_EXC) -> subprocess.CompletedProcess | BaseException:"""``_run_cli`` that returns (not raises) any exception in *exc_types*."""try:return _run_cli(binary, *args, timeout=timeout)diff --git a/tools/cronjob_job_args.py b/tools/cronjob_job_args.pyindex 57cd7c9108a..046995c2a64 100644--- a/tools/cronjob_job_args.py+++ b/tools/cronjob_job_args.py@@ -20,7 +20,7 @@ _THREAD_HORIZON_MINUTES = 60def _first_fire_within_thread_horizon(- schedule: Union[str, dict[str, Any], None],+ schedule: str | dict[str, Any] | None,) -> bool:"""True when the job's first fire is close enough that the creating conversation is stillalive when it happens. Only near one-shots qualify; recurring jobs and one-shots beyond the@@ -57,7 +57,7 @@ def _first_fire_within_thread_horizon(def _origin_from_env(- schedule: Union[str, dict[str, Any], None] = None,+ schedule: str | dict[str, Any] | None = None,) -> Optional[dict[str, str]]:from gateway.session_context import async_delivery_supported, get_session_envorigin_platform = get_session_env("HERMES_SESSION_PLATFORM")@@ -441,7 +441,7 @@ def _validate_cron_script_path(script: Optional[str]) -> Optional[str]:def _apply_continuity(- context_from: Optional[Union[str, list[str]]],+ context_from: Optional[str | list[str]],continuity: bool) -> Optional[list[str]]:"""continuity=True ensures "self" is in context_from; False removes it; others untouched."""refs = _clean_str_list(context_from)diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex ed08ee141f0..625b7d970bc 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -999,7 +999,7 @@ def cronjob(base_url: Optional[str] = None,reason: Optional[str] = None,script: Optional[str] = None,- context_from: Optional[Union[str, list[str]]] = None,+ context_from: Optional[str | list[str]] = None,continuity: Optional[bool] = None,enabled_toolsets: Optional[list[str]] = None,workdir: Optional[str] = None,@@ -1008,7 +1008,7 @@ def cronjob(monitor_script: Optional[str] = None,monitor_url: Optional[str] = None,reasoning_effort: Optional[str] = None,- failure_deliver: Optional[Union[str, list[str]]] = None,+ failure_deliver: Optional[str | list[str]] = None,task_id: str | None = None,session_id: Optional[str] = None,paused: bool = False,diff --git a/tools/daemon_pool.py b/tools/daemon_pool.pyindex 7fbdc4ea97d..ddc35ed5ca7 100644--- a/tools/daemon_pool.py+++ b/tools/daemon_pool.py@@ -45,7 +45,7 @@ class DaemonThreadPoolExecutor(ThreadPoolExecutor):q.put(None)num_threads = len(self._threads)if num_threads < self._max_workers:- thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)+ thread_name = f'{self._thread_name_prefix or self}_{num_threads:d}'executor_ref = weakref.ref(self, weakref_cb)if hasattr(self, "_create_worker_context"):# Python 3.14 replaced _initializer/_initargs with a factorydiff --git a/tools/fal_common.py b/tools/fal_common.pyindex 5ba02a01ae0..413340981ea 100644--- a/tools/fal_common.py+++ b/tools/fal_common.py@@ -188,7 +188,7 @@ class _ManagedFalSyncClient:def submit(self, application: str, arguments: dict[str, Any], *, path: str = "",hint: Optional[str] = None, webhook_url: Optional[str] = None, priority: Any = None,- headers: Optional[dict[str, str]] = None, start_timeout: Optional[Union[int, float]] = None,+ headers: Optional[dict[str, str]] = None, start_timeout: Optional[int | float] = None,):url = self._queue_url_format + applicationif path:diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 9f1923130d1..556b2f9dbbf 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -45,7 +45,7 @@ async def _preflight_stdio_command(server_name: str, command: str, args: list) -try:malware_error = await asyncio.wait_for(asyncio.to_thread(check_package_for_malware, command, args), timeout=_OSV_MALWARE_CHECK_TIMEOUT_S)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("MCP server '%s': OSV malware preflight timed out after %.0fs ""(network slow/unreachable) — proceeding without the check.",server_name, _OSV_MALWARE_CHECK_TIMEOUT_S)diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.pyindex 8ad0dbf4366..1d74fbb6a99 100644--- a/tools/mcp_tool_sampling.py+++ b/tools/mcp_tool_sampling.py@@ -222,7 +222,7 @@ class SamplingHandler:sync_call = self._build_llm_call(params, resolved_model) # outside the try: its errors propagate, not _failtry:response = await asyncio.wait_for(asyncio.to_thread(sync_call), timeout=self.timeout)- except asyncio.TimeoutError:+ except TimeoutError:return self._fail(f"Sampling LLM call timed out after {self.timeout}s for server '{self.server_name}'")except Exception as exc:return self._fail(f"Sampling LLM call failed: {_sanitize_error(_exc_str(exc))}")@@ -314,7 +314,7 @@ class ElicitationHandler:try: # off-thread: inline, the sync consent flow would freeze the MCP loop and every RPC on itanswer = await asyncio.wait_for(asyncio.to_thread(invoke_consent), timeout=self.timeout + self._OUTER_TIMEOUT_GRACE_SECONDS)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("MCP server '%s' elicitation timed out after %ds", self.server_name, int(self.timeout))return self._result("cancel", "errors")except Exception as exc:diff --git a/tools/mcp_tool_scope.py b/tools/mcp_tool_scope.pyindex dd4ee9313ab..6276c33ebc2 100644--- a/tools/mcp_tool_scope.py+++ b/tools/mcp_tool_scope.py@@ -20,7 +20,7 @@ from typing import Optional, Tuple, Unionfrom tools.mcp_tool_common import _core-ServerKey = Union[str, tuple[str, str]]+ServerKey = str | tuple[str, str]def _server_key(name: str, scope: Optional[str] = None, *, current: bool = True) -> ServerKey:diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 1eada9c37b6..9e74bd9da50 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -546,7 +546,7 @@ class MCPServerRunMixin:if self._task and not self._task.done():try:await asyncio.wait_for(self._task, timeout=10)- except asyncio.TimeoutError:+ except TimeoutError:logger.warning("MCP server '%s' shutdown timed out, cancelling task", self.name)self._task.cancel()try:diff --git a/tools/session_search_tool.py b/tools/session_search_tool.pyindex 409112b63c9..5229e4f97d6 100644--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@ -75,7 +75,7 @@ def _loud(fn, log_msg, error_prefix, *log_args):return None, tool_error(f"{error_prefix}: {e}", success=False)-def _format_timestamp(ts: Union[float, str, None]) -> str:+def _format_timestamp(ts: float | str | None) -> str:"""Unix timestamp -> readable date; ISO strings pass through; "unknown" for None."""if ts is None:return "unknown"diff --git a/tools/skills_hub_github.py b/tools/skills_hub_github.pyindex a6cdda2efc8..b22da1c5866 100644--- a/tools/skills_hub_github.py+++ b/tools/skills_hub_github.py@@ -295,7 +295,7 @@ class GitHubSource(SkillSource):referenced = _referenced_support_paths(skill_md)if referenced is None:return None- files: dict[str, Union[str, bytes]] = {"SKILL.md": skill_md}+ files: dict[str, str | bytes] = {"SKILL.md": skill_md}if tree is not None:complete = self._collect_tree_files(repo, skill_dir, tree[1], pinned_ref, referenced, files)if complete is None:@@ -335,7 +335,7 @@ class GitHubSource(SkillSource):def _collect_tree_files(self, repo: str, skill_path: str, entries: list[dict], ref: Optional[str], referenced: set,- files: dict[str, Union[str, bytes]],+ files: dict[str, str | bytes],) -> Optional[bool]:"""Download the FULL skill directory from the pinned tree into ``files``. Link-driven fetchingsilently dropped support files under non-canonical dirs (``reference/``, ``agents/``, rootdiff --git a/tools/skills_hub_models.py b/tools/skills_hub_models.pyindex 6573849441f..18e66497d12 100644--- a/tools/skills_hub_models.py+++ b/tools/skills_hub_models.py@@ -41,7 +41,7 @@ class SkillMeta:class SkillBundle:"""A downloaded skill ready for quarantine/scanning/installation."""name: str- files: dict[str, Union[str, bytes]] # relative_path -> file content+ files: dict[str, str | bytes] # relative_path -> file contentsource: stridentifier: strtrust_level: strdiff --git a/tools/skills_hub_official.py b/tools/skills_hub_official.pyindex 5ef27edbeee..20f8504af1f 100644--- a/tools/skills_hub_official.py+++ b/tools/skills_hub_official.py@@ -71,7 +71,7 @@ class OptionalSkillSource(SkillSource):return self._meta(rel_dir, rel_dir.rsplit("/", 1)[-1], desc, [])@staticmethod- def _bundle(rel_id: str, files: dict[str, Union[str, bytes]], **kwargs) -> SkillBundle:+ def _bundle(rel_id: str, files: dict[str, str | bytes], **kwargs) -> SkillBundle:return SkillBundle(name=rel_id.rsplit("/", 1)[-1], files=files, source="official",identifier=f"official/{rel_id}", trust_level="builtin", **kwargs)@@ -123,7 +123,7 @@ class OptionalSkillSource(SkillSource):upstream = None if skill_md is None else self._upstream_pointer_from_content(skill_md)if upstream is not None:return self._fetch_from_upstream(upstream, rel_id)- files: dict[str, Union[str, bytes]] = {}+ files: dict[str, str | bytes] = {}for f in skill_dir.rglob("*"):if f.is_file() and not _skip_bundle_file(f.relative_to(skill_dir).as_posix()):try:@@ -174,7 +174,7 @@ class OptionalSkillSource(SkillSource):tree = github._get_repo_tree(self.OFFICIAL_REPO)if tree is None:return None- files: dict[str, Union[str, bytes]] = {}+ files: dict[str, str | bytes] = {}for rel_file, item_path, regular in _tree_members(tree[1], f"{self.OPTIONAL_SKILLS_PREFIX}/{rel}/"):if not regular or _skip_bundle_file(rel_file):continue@@ -216,7 +216,7 @@ class OptionalSkillSource(SkillSource):valid=lambda c: isinstance(c, dict) and bool(c)) or {}return self._remote_dirs- def _upstream_pointer_from_content(self, content: Union[str, bytes]) -> Optional[dict[str, str]]:+ def _upstream_pointer_from_content(self, content: str | bytes) -> Optional[dict[str, str]]:"""Parse ``metadata.hermes.upstream: {repo: owner/name, path: ...}`` out of SKILL.md content(a catalog stub); None for vendored skills."""if isinstance(content, bytes):diff --git a/tools/skills_hub_sources.py b/tools/skills_hub_sources.pyindex 46abc4e6f58..965401792ac 100644--- a/tools/skills_hub_sources.py+++ b/tools/skills_hub_sources.py@@ -215,7 +215,7 @@ class UrlSource(GuardedFetchMixin, SkillSource):referenced = _referenced_support_paths(text)if referenced is None:return None- files: dict[str, Union[str, bytes]] = {"SKILL.md": text}+ files: dict[str, str | bytes] = {"SKILL.md": text}base_url = url.rsplit("/", 1)[0] + "/"for rel_path in sorted(referenced):support_url = urljoin(base_url, quote(rel_path, safe="/"))diff --git a/tools/tool_search_validation.py b/tools/tool_search_validation.pyindex 00cfc527e9a..c2e45e22234 100644--- a/tools/tool_search_validation.py+++ b/tools/tool_search_validation.py@@ -201,7 +201,7 @@ def local_batch_error(entries: list[dict[str, Any]]) -> str:args = json.dumps(first.get("arguments", {}), ensure_ascii=False, separators=(",", ":"))if len(args) > _ECHO_ARGS_MAX_CHARS:args = "{...}" # keep the correction readable; the model still has its own arguments- retry = '{"calls":[{"name":%s,"arguments":%s}]}' % (json.dumps(first["name"], ensure_ascii=False), args)+ retry = '{{"calls":[{{"name":{},"arguments":{}}}]}}'.format(json.dumps(first["name"], ensure_ascii=False), args)remaining = (f" then issue the remaining {len(entries) - 1} call(s) as separate tool_call invocations"if len(entries) > 1 else "")return (diff --git a/tools/tts_streaming.py b/tools/tts_streaming.pyindex 4a2d21cd700..396d3612395 100644--- a/tools/tts_streaming.py+++ b/tools/tts_streaming.py@@ -512,7 +512,7 @@ class XAIStreamer(StreamingTTSProvider):message = await asyncio.wait_for(ws.recv(), timeout=self._RECV_TIMEOUT_S)- except asyncio.TimeoutError:+ except TimeoutError:raise RuntimeError(f"xAI streaming TTS: no audio for {self._RECV_TIMEOUT_S}s")except websockets.exceptions.ConnectionClosedOK:return # clean close, with or without audio.donediff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.pyindex 8df072ff67a..75ec4a895fb 100644--- a/tools/web_tools_extract.py+++ b/tools/web_tools_extract.py@@ -164,7 +164,7 @@ async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[stresults = await asyncio.wait_for(coro, timeout=timeout)else:results = await coro- except asyncio.TimeoutError as exc: # hanging backend — bounded, never a stalled tool call+ except TimeoutError as exc: # hanging backend — bounded, never a stalled tool calllogger.warning("web_extract provider '%s' timed out after %.0fs for %d URL(s)",provider.name, timeout, len(fetch_urls))failed = [_result_entry(u, f"Extract timed out after {timeout:.0f}s via {provider.name}")diff --git a/trajectory_compressor.py b/trajectory_compressor.pyindex 35732a6ec83..9675aa82590 100644--- a/trajectory_compressor.py+++ b/trajectory_compressor.py@@ -599,7 +599,7 @@ Write only the summary, starting with "[CONTEXT SUMMARY]:" prefix."""run.skipped += bool(metrics.skipped_under_target)run.finish()return processed_entry, metrics- except asyncio.TimeoutError:+ except TimeoutError:self.logger.warning("Timeout processing entry from %s:%s (>%ss)", file_path, entry_idx, self.config.per_trajectory_timeout)async with run.lock:self.aggregate_metrics.trajectories_failed += 1diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.pyindex 3f9f7dfbb93..38d8fccea6e 100644--- a/tui_gateway/session_history.py+++ b/tui_gateway/session_history.py@@ -528,8 +528,8 @@ def _turn_failure_detail(error: Any, reason: Any = None, prompt: Any = None) ->message = _strip_prompt_echo(message, prompt)if len(message) > _TURN_FAILURE_DETAIL_LIMIT:message = message[:_TURN_FAILURE_DETAIL_LIMIT] + "\u2026"- out = " failure_reason=%s" % " ".join(reason_text.split()) if reason_text else ""- return out + (" cause=%r" % message if message else "")+ out = " failure_reason={}".format(" ".join(reason_text.split())) if reason_text else ""+ return out + (f" cause={message!r}" if message else "")def register(server) -> None:diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex a0eb76d0568..42dbd6164b8 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -203,7 +203,7 @@ class WSTransport:payload = _sanitize_ws_text(line)try:await asyncio.wait_for(self._ws.send_text(payload), timeout=_WS_SEND_DEADLINE_S)- except asyncio.TimeoutError:+ except TimeoutError:# The loop is responsive (the timer fired) but the socket never drained: unlike the# loop-stall wait in write(), this is a dead peer. Latch under the writer lock so queued# batches bail, and close the socket so handle_ws's read loop ends and its teardowndiff --git a/utils.py b/utils.pyindex b266fa9336f..10c090ef91e 100644--- a/utils.py+++ b/utils.py@@ -165,7 +165,7 @@ def _copy_fallback(tmp_str: str, real_path: str) -> None:os.unlink(tmp_str)-def atomic_replace(tmp_path: Union[str, Path], target: Union[str, Path]) -> str:+def atomic_replace(tmp_path: str | Path, target: str | Path) -> str:"""Atomically move *tmp_path* onto *target*, preserving symlinks.Resolves a symlink first so ``os.replace`` writes the real file in place and the symlink@@ -212,7 +212,7 @@ def _publish_path(target_str: str) -> str:return os.path.realpath(target_str) if os.path.islink(target_str) else target_str-def mkstemp_beside(target: Union[str, Path], **kw: Any) -> tuple[int, str]:+def mkstemp_beside(target: str | Path, **kw: Any) -> tuple[int, str]:"""``tempfile.mkstemp`` in the directory :func:`atomic_replace` will rename into.A temp staged next to a symlink whose target lives on another filesystem turns the publish@@ -232,7 +232,7 @@ def mkstemp_beside(target: Union[str, Path], **kw: Any) -> tuple[int, str]:return tempfile.mkstemp(dir=link_dir, **kw)-def fsync_directory(path: Union[str, Path]) -> None:+def fsync_directory(path: str | Path) -> None:"""Best-effort fsync of a directory entry so a just-renamed file survives power loss.No-op on Windows (directories can't be opened with ``os.open``; the file fsync still applies)@@ -252,7 +252,7 @@ def fsync_directory(path: Union[str, Path]) -> None:os.close(fd)-def rmtree_readonly(path: Union[str, Path], *, ignore_errors: bool = False) -> None:+def rmtree_readonly(path: str | Path, *, ignore_errors: bool = False) -> None:"""``shutil.rmtree`` that can also delete read-only trees.``shutil.rmtree`` stops at the first entry it cannot unlink. Git marks@@ -336,7 +336,7 @@ def _mode_for_write(path: Path, create_mode: "int | None", preserve: bool = Truereturn mode if mode is not None or path.exists() else create_mode-def atomic_write_text(path: Union[str, Path], content: str, *, encoding: str = "utf-8", tmp_prefix: str = ".tmp_",+def 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,fsync_dir: bool = False) -> None:"""Write *content* to *path* via temp file + fsync + atomic rename.@@ -352,7 +352,7 @@ def atomic_write_text(path: Union[str, Path], content: str, *, encoding: str = "preserve_owner=preserve_mode, fsync_dir=fsync_dir)-def atomic_write_bytes(path: Union[str, Path], content: bytes, *, tmp_prefix: str = ".tmp_",+def atomic_write_bytes(path: str | Path, content: bytes, *, tmp_prefix: str = ".tmp_",mode: "int | None" = None, fsync_dir: bool = False) -> None:"""Bytes variant of :func:`atomic_write_text` (encrypted blobs, key material)."""path = Path(path)@@ -378,7 +378,7 @@ def _dump_json(data: Any, f, *, indent: "int | None", ensure_ascii: bool, dump_kdef atomic_json_write(- path: Union[str, Path], data: Any, *, indent: int = 2, mode: int | None = None,+ path: str | Path, data: Any, *, indent: int = 2, mode: int | None = None,ensure_ascii: bool = False, fsync_dir: bool = False, **dump_kwargs: Any,) -> None:"""Write JSON to *path* atomically (temp file + fsync + replace).@@ -394,7 +394,7 @@ def atomic_json_write(fsync_dir=fsync_dir)-def read_json_or_empty(path: Union[str, Path]) -> dict:+def read_json_or_empty(path: str | Path) -> dict:"""The JSON object at *path*, or ``{}`` when the file is missing, unreadable, malformed ornot an object. The read half of every ``read → merge → atomic_json_write`` config store(memory-provider ``save_config``), so a corrupt sidecar degrades to defaults instead of@@ -406,7 +406,7 @@ def read_json_or_empty(path: Union[str, Path]) -> dict:return data if isinstance(data, dict) else {}-def warn_if_credential_file_broadly_readable(path: Union[str, Path], *, label: str = "", log: logging.Logger | None = None) -> bool:+def warn_if_credential_file_broadly_readable(path: str | Path, *, label: str = "", log: logging.Logger | None = None) -> bool:"""Warn when a credential file is group/world-readable; True when a warning was emitted.Hand-made secret files (or ones older Hermes wrote without an explicit mode) commonly end up@@ -426,7 +426,7 @@ def warn_if_credential_file_broadly_readable(path: Union[str, Path], *, label: sreturn True-def atomic_yaml_write(path: Union[str, Path], data: Any, *, default_flow_style: bool = False, sort_keys: bool = False,+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:"""Write YAML to *path* atomically (temp file + fsync + replace)."""path = Path(path)@@ -458,7 +458,7 @@ def _roundtrip_dump(path: Path, yaml_rt, config, *, extra_content: "str | None"_atomic_write(path, _write, prefix=f".{path.stem}_", mode=_preserve_file_mode(path))-def atomic_roundtrip_yaml_update(path: Union[str, Path], key_path: str, value: Any) -> None:+def atomic_roundtrip_yaml_update(path: str | Path, key_path: str, value: Any) -> None:"""Update one dotted YAML key while preserving comments, ordering, quoting and Unicode.Narrower than :func:`atomic_yaml_write` on purpose: for user-edited config files where a@@ -526,7 +526,7 @@ def _rt_value(value: Any) -> Any:return value-def atomic_roundtrip_yaml_save(path: Union[str, Path], new_state: dict, *,+def atomic_roundtrip_yaml_save(path: str | Path, new_state: dict, *,extra_content_on_create: "str | None" = None) -> None:"""Persist a full config-state dict while preserving comments and ordering.@@ -604,7 +604,7 @@ _YAML_FILE_CACHE: dict = {}_YAML_FILE_CACHE_LOCK = threading.Lock()-def load_yaml_file_readonly(path: Union[str, Path]) -> Any:+def load_yaml_file_readonly(path: str | Path) -> Any:"""``fast_safe_load`` of a file, re-parsed only when its :func:`file_signature` changes.Returns the cached object itself — callers must never mutate it. Parse errors propagate and