Skip to content

The agent that grows with you

ci: UP007, UP022, UP028, UP031, UP041 linter fixes

Maciej Lisiewskiaff64c3eebe9
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 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: bool
raw_codex: bool
explicit_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], _ResolveResul
def 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.py
index 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):
pass
try:
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)
return
if 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 False
return True
diff --git a/agent/pet/render.py b/agent/pet/render.py
index 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 scale
r, 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 CR
out.append("-") # next band
return "".join(out) + "\x1b\\"
diff --git a/agent/plugin_llm.py b/agent/plugin_llm.py
index 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.py
index 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 exc
except OSError as exc:
raise ConnectError(str(exc)) from exc
diff --git a/agent/rate_limit_credits.py b/agent/rate_limit_credits.py
index 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.py
index 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 = True
elif 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 THIS
caller won (``CronScheduler.fire_due``: exactly one of N replicas runs a job). Under the
fence + file lock: reject missing/terminal/paused jobs unless ``force`` (explicit manual
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 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 active
cron 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.py
index 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 lock
diff --git a/evals/core_tool_deferral/worker.py b/evals/core_tool_deferral/worker.py
index 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_home
os.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.py
index 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):
pass
except Exception:
logger.debug("Control socket connection handler error", exc_info=True)
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 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")
continue
if item is None:
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index 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.py
index 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) -> "w
try:
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")
continue
if event is _RUN_STREAM_SUBSCRIBER_OVERFLOW:
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 4466b5a1ad2..770f96267e8 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2713,7 +2713,7 @@ class BasePlatformAdapter(ABC):
return None
try:
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 None
except 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.py
index 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 None
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index 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.py
index 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:
break
logger.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 False
logger.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 += 1
logger.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 None
biz_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.py
index 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 SendResult
when 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):
pass
self._revocation_monitor = None
if self._transport is not None:
@@ -1511,7 +1511,7 @@ class RelayAdapter(BasePlatformAdapter):
self._auto_thread_waiters[key] = waiter
try:
await asyncio.wait_for(waiter.wait(), timeout)
- except asyncio.TimeoutError:
+ except TimeoutError:
return None
finally:
# Only the waiter we installed, and only if no later call replaced it; a
diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.py
index 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 = True
return 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 = False
diff --git a/gateway/run.py b/gateway/run.py
index 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.py
index 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 when
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 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_text
output = 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.py
index 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.py
index 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.py
index 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.py
index 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:
pass
if 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.py
index eefee0d87f8..593078cafe4 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -819,7 +819,7 @@ class GatewayTurnMixin:
fence = attempt.commit_fence
while 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_task
diff --git a/gateway/run_watchers.py b/gateway/run_watchers.py
index 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.py
index 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 thread
never 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 is
persisted 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.py
index 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.source
session_key = self._session_key_for_source(source)
diff --git a/gateway/stream_events.py b/gateway/stream_events.py
index 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.py
index 008ecb59f8d..2046f1b198d 100644
--- a/gateway/turn_lease.py
+++ b/gateway/turn_lease.py
@@ -120,7 +120,7 @@ class SessionTurnLeaseRegistry:
lease.pending_acquires += 1
try:
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.py
index 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: str
await 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 = exc
logger.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.py
index 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.py
index 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.py
index 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, Union
from 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.py
index 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[in
failed.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.py
index 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"] = url
owner, 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.py
index 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) -> li
return ["-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 axis
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.py
index 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"] = False
try:
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.py
index b905d335de7..42150596f8f 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -888,7 +888,7 @@ class PluginContext:
return count
def 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 handle
def 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). The
loader calls this for plugins declaring ``provides_locales``; ``metadata`` maps ids to
@@ -955,7 +955,7 @@ class PluginContext:
return handle
def 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 a
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index 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: str
max_chars: int
plugin: 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 directive
results.append({"action": "block", "message": _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE})
diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.py
index 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 LoadedPlugin
if 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 with
identity-conditional inverses. Returns ``True`` when anything was found."""
diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.py
index 36f97b0a728..1b5c1b950ab 100644
--- a/hermes_cli/plugins_loader.py
+++ b/hermes_cli/plugins_loader.py
@@ -732,7 +732,7 @@ class PluginLoaderMixin:
raise
return 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.py
index 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.py
index 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, cre
await 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"), None
except Exception:
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 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 False
finally:
try:
diff --git a/hermes_cli/update_cmd_validation.py b/hermes_cli/update_cmd_validation.py
index 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.py
index 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] = None
skills: Optional[list[str]] = None
model: Optional[str] = None
provider: Optional[str] = None
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 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 = None
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 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.py
index 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.py
index 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 False
except 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:
pass
except 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.py
index 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 workspace
diff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.py
index 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.py
index 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 2
if 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.py
index 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 DB
cursor, events = await tail.poll(cursor)
if events:
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.py
index 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 None
stdout, 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 = None
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index 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 = None
for task in list(self._bg_tasks):
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 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 TimeoutError
if 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, DiscordVoiceIn
if not self._ready_event.is_set():
try:
await asyncio.wait_for(self._ready_event.wait(), timeout=30.0)
- except asyncio.TimeoutError:
+ except TimeoutError:
pass
admitted, role_authorized = self._discord_message_admission(message, claim=True)
if not admitted:
@@ -2101,9 +2101,9 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn
try:
done, _pending = await asyncio.wait({close_task}, timeout=1.0)
if close_task not in done:
- raise asyncio.TimeoutError
+ raise TimeoutError
await 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, DiscordVoiceIn
asyncio.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, DiscordVoiceIn
self.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, DiscordVoiceIn
vc.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 True
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.py
index 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):
raise
return _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.py
index 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.py
index 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.py
index 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 None
except asyncio.IncompleteReadError:
return _EOF
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 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_f
for 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 result
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index 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.py
index 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.py
index 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_count
if 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))
return
delay = 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):
return
try:
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 signal
pending = 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 = True
if _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.py
index 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``, anything
else (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 None
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index a5e1277671f..d893ea38439 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -610,7 +610,7 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAcc
if 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, OwnAcc
return 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.py
index 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.py
index 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.py
index 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, None
try:
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 arrive
except Exception:
return True, None
@@ -485,7 +485,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
return True
stale_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 it
except Exception:
pass # Bridge not running, start a new one
diff --git a/plugins/web/firecrawl/provider.py b/plugins/web/firecrawl/provider.py
index 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.toml
index 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.py
index 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.paragraphs
for 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.paragraphs
for 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.py
index 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.py
index 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/ directory
total = 0
for token, value in values.items():
- total += replace_text(prs, "{{%s}}" % token, str(value))
+ total += replace_text(prs, f"{{{{{token}}}}}", str(value))
return total
diff --git a/skills/research/grounded-citations/scripts/sources.py b/skills/research/grounded-citations/scripts/sources.py
index 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.py
index 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_task
diff --git a/tests/agent/test_auxiliary_auth_rung_fallthrough.py b/tests/agent/test_auxiliary_auth_rung_fallthrough.py
index 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"}})
return
self._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}', requests
finally:
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.py
index 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, monkeyp
http_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.py
index 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.py
index 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.open
diff --git a/tests/agent/test_provider_id_mint_normalization.py b/tests/agent/test_provider_id_mint_normalization.py
index 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 AIAgent
def _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.py
index 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.py
index 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.py
index 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 | Raw
Responder = Callable[[dict[str, Any]], Response]
diff --git a/tests/fakes/platforms/_standin.py b/tests/fakes/platforms/_standin.py
index 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.py
index 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 + 3
continue
if 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 + 1
continue
if 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.py
index 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 | DropStream
Responder = 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.py
index 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.py
index 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 | CDropToolCall
Responder = Callable[[dict[str, Any]], Step]
_STREAM_ADAPTER = TypeAdapter(CompletionCreateParamsStreaming)
diff --git a/tests/fakes/providers/openai_responses.py b/tests/fakes/providers/openai_responses.py
index 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 | HttpError
Responder = Callable[[dict[str, Any]], Step]
_REQUEST_ADAPTER = TypeAdapter(ResponseCreateParamsStreaming)
diff --git a/tests/fakes/providers/vertex.py b/tests/fakes/providers/vertex.py
index 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 | Drop
Responder = 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.py
index 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 True
diff --git a/tests/gateway/test_buzz_websocket.py b/tests/gateway/test_buzz_websocket.py
index 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, capl
task.cancel()
try:
await asyncio.wait_for(task, 5.0)
- except (asyncio.CancelledError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.CancelledError):
pass
assert 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):
pass
assert 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_cl
task.cancel()
try:
await asyncio.wait_for(task, 5.0)
- except (asyncio.CancelledError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.CancelledError):
pass
assert 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.py
index 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 TimeoutError
import gateway.run as _run
diff --git a/tests/gateway/test_dingtalk_reconnect_circuit_breaker.py b/tests/gateway/test_dingtalk_reconnect_circuit_breaker.py
index 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:
pass
sdk = [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.py
index 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.py
index 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_server
diff --git a/tests/gateway/test_executor_pool_isolation.py b/tests/gateway/test_executor_pool_isolation.py
index 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 do
await asyncio.gather(*(one() for _ in range(count)))
diff --git a/tests/gateway/test_handoff_watcher_resilience.py b/tests/gateway/test_handoff_watcher_resilience.py
index 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.py
index 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.py
index 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 coro
except 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.py
index 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.py
index 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.py
index 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.py
index 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.py
index 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_model
assert "gpt-5.5" in confirmation
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_reset_button_deadlock.py b/tests/gateway/test_reset_button_deadlock.py
index 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 TimeoutError
runner = _make_runner_with_cached_agent(lambda: None)
diff --git a/tests/gateway/test_silent_partial_delivery.py b/tests/gateway/test_silent_partial_delivery.py
index 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.asyncio
async 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.py
index 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 consumer
diff --git a/tests/gateway/test_telegram_network_reconnect.py b/tests/gateway/test_telegram_network_reconnect.py
index 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.py
index 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(monkeyp
if getattr(getattr(awaitable, "cr_code", None), "co_name", "") == "stuck_discovery":
assert timeout == 5.0
awaitable.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.py
index 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 = True
try:
await asyncio.wait_for(task, timeout=2)
- except asyncio.TimeoutError:
+ except TimeoutError:
task.cancel()
assert result.success is True
diff --git a/tests/gateway/test_wecom_double_send.py b/tests/gateway/test_wecom_double_send.py
index 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_task
diff --git a/tests/gateway/test_whatsapp_bridge_pidfile.py b/tests/gateway/test_whatsapp_bridge_pidfile.py
index 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 connection
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index 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.py
index 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.py
index 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.py
index 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 set
reg._sessions[s.key] = s
diff --git a/tests/hermes_cli/test_shared_metrics_send_migration.py b/tests/hermes_cli/test_shared_metrics_send_migration.py
index 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.py
index 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 time
from 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 Windows
owner.wait(timeout=10)
diff --git a/tests/hermes_cli/test_update_posix_pause.py b/tests/hermes_cli/test_update_posix_pause.py
index 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.ser
def 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 own
restarting that unit (the record's only debt), never drop it."""
- owner = _child("""
+ owner = _child(f"""
import time
from 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 Windows
owner.wait(timeout=10)
diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.py
index 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:
continue
try:
conn.sendall(b"1")
diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.py
index 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.py
index 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 += 1
except Exception as exc:
diff --git a/tests/plugins/test_kanban_events_tail.py b/tests/plugins/test_kanban_events_tail.py
index 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 += 1
awaitable.close()
if waits <= polls:
- raise asyncio.TimeoutError
+ raise TimeoutError
return {"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.py
index 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 += 1
awaitable.close()
if wait_calls <= 2:
- raise asyncio.TimeoutError
+ raise TimeoutError
return {"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 += 1
if wait_calls == 1:
awaitable.close()
- raise asyncio.TimeoutError
+ raise TimeoutError
return await awaitable
monkeypatch.setattr(mod.asyncio, "wait_for", _poll_once_then_wait)
diff --git a/tests/pm/activation_support.py b/tests/pm/activation_support.py
index 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.py
index 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.py
index 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 unquoted
word 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.py
index 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 sys
lease.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 subprocess
import 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.stderr
diff --git a/tests/tools/test_cli_approval_exec_ask_leak.py b/tests/tools/test_cli_approval_exec_ask_leak.py
index 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, sys
os.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: F401
print("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.py
index 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 = True
return self._conn, ("peer", 0)
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 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 _sp
orig_run = _sp.run
diff --git a/tests/tools/test_daemon_pool.py b/tests/tools/test_daemon_pool.py
index 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.py
index 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, toke
ops = 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.error
assert 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 None
assert clean.read_text(encoding="utf-8") == quoted
legacy = 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 None
assert legacy.read_text(encoding="utf-8") == edited
diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.py
index 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_i
else:
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.py
index 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):
pass
return server._task.done()
diff --git a/tests/tools/test_mcp_capability_gating.py b/tests/tools/test_mcp_capability_gating.py
index 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 tools
task.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.py
index 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(monkeypatc
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_client_cert.py b/tests/tools/test_mcp_client_cert.py
index 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):
pass
asyncio.run(drive())
@@ -321,7 +321,7 @@ class TestSSEClientCert:
}),
timeout=2.0,
)
- except (asyncio.TimeoutError, StopAsyncIteration, Exception):
+ except (TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
@@ -372,7 +372,7 @@ class TestSSEClientCert:
}),
timeout=2.0,
)
- except (asyncio.TimeoutError, StopAsyncIteration, Exception):
+ except (TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
diff --git a/tests/tools/test_mcp_failure_classification.py b/tests/tools/test_mcp_failure_classification.py
index 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, cap
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())
@@ -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.py
index 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, monkeypat
storage = 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.py
index 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_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_parked_self_probe.py b/tests/tools/test_mcp_parked_self_probe.py
index 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.py
index 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.py
index 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, 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())
@@ -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.py
index 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_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())
@@ -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.py
index 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.py
index 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):
pass
asyncio.run(drive())
@@ -134,7 +134,7 @@ class TestSSEOAuthForwarding:
}),
timeout=2.0,
)
- except (asyncio.TimeoutError, StopAsyncIteration, Exception):
+ except (TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
diff --git a/tests/tools/test_profile_gate_env_isolation.py b/tests/tools/test_profile_gate_env_isolation.py
index 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.py
index 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 parsed
diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.py
index 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 = _FakeDDGS
monkeypatch.setitem(sys.modules, "ddgs", fake)
diff --git a/tests/tui_gateway/contracts/test_generated.py b/tests/tui_gateway/contracts/test_generated.py
index 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.py
index 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.py
index 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, screensho
return 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 image
attached to the conversation; otherwise the auxiliary vision model returns a text
analysis. The file is kept and its path returned (MEDIA:<path>)."""
diff --git a/tools/code_execution_rpc.py b/tools/code_execution_rpc.py
index 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: li
try:
conn, _ = server_sock.accept()
break
- except socket.timeout:
+ except TimeoutError:
continue
if conn is None:
return
@@ -162,7 +162,7 @@ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: li
while True:
try:
chunk = conn.recv(65536)
- except socket.timeout:
+ except TimeoutError:
break
if not chunk:
break
@@ -184,7 +184,7 @@ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: li
call_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.py
index 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.py
index 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.CompletedPro
return 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.py
index 57cd7c9108a..046995c2a64 100644
--- a/tools/cronjob_job_args.py
+++ b/tools/cronjob_job_args.py
@@ -20,7 +20,7 @@ _THREAD_HORIZON_MINUTES = 60
def _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 still
alive 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_env
origin_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.py
index 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.py
index 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 factory
diff --git a/tools/fal_common.py b/tools/fal_common.py
index 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 + application
if path:
diff --git a/tools/mcp_tool.py b/tools/mcp_tool.py
index 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.py
index 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 _fail
try:
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 it
answer = 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.py
index dd4ee9313ab..6276c33ebc2 100644
--- a/tools/mcp_tool_scope.py
+++ b/tools/mcp_tool_scope.py
@@ -20,7 +20,7 @@ from typing import Optional, Tuple, Union
from 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.py
index 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.py
index 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.py
index 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 fetching
silently dropped support files under non-canonical dirs (``reference/``, ``agents/``, root
diff --git a/tools/skills_hub_models.py b/tools/skills_hub_models.py
index 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 content
source: str
identifier: str
trust_level: str
diff --git a/tools/skills_hub_official.py b/tools/skills_hub_official.py
index 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.py
index 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.py
index 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.py
index 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.done
diff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.py
index 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[st
results = 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 call
logger.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.py
index 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 += 1
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index 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.py
index 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 teardown
diff --git a/utils.py b/utils.py
index 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 = True
return 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_k
def 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 or
not 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: s
return 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