The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: RUF013, RUF015
Maciej Lisiewski4278b6aa24b7
diff --git a/acp_adapter/events.py b/acp_adapter/events.pyindex 47b5c578726..07ccc3492b4 100644--- a/acp_adapter/events.py+++ b/acp_adapter/events.py@@ -130,7 +130,7 @@ def make_tool_progress_cb(``tool.completed`` closes that call with its own result — the step callbackonly fires on the *next* step, which leaves a turn's last tools open."""- def _tool_progress(event_type: str, name: str = None, preview: str = None, args: Any = None, **kwargs) -> None:+ def _tool_progress(event_type: str, name: str | None = None, preview: str | None = None, args: Any = None, **kwargs) -> None:if event_type == "tool.completed" and name:if turn_state is not None:turn_state["saw_completion"] = Truediff --git a/agent/agent_init.py b/agent/agent_init.pyindex 8c7e55c4d45..0371db1feb3 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -2359,40 +2359,40 @@ _CALLBACK_PARAMS = (def init_agent(- agent, base_url: str = None, api_key: str = None, provider: str = None, api_mode: str = None,- acp_command: str = None, acp_args: list[str] | None = None, command: str = None,+ agent, base_url: str | None = None, api_key: str | None = None, provider: str | None = None, api_mode: str | None = None,+ acp_command: str | None = None, acp_args: list[str] | None = None, command: str | None = None,args: list[str] | None = None, model: str = "", max_iterations: int = sys.maxsize,- enabled_toolsets: list[str] = None, disabled_toolsets: list[str] = None,+ enabled_toolsets: list[str] | None = None, disabled_toolsets: list[str] | None = None,save_trajectories: bool = False, verbose_logging: bool = False, quiet_mode: bool = False,- tool_progress_mode: str = "all", ephemeral_system_prompt: str = None,- log_prefix_chars: int = 100, log_prefix: str = "", providers_allowed: list[str] = None,- providers_ignored: list[str] = None, providers_order: list[str] = None,- provider_sort: str = None, provider_require_parameters: bool = False,- provider_data_collection: str = None, openrouter_min_coding_score: Optional[float] = None,- session_id: str = None, tool_progress_callback: callable = None,- tool_start_callback: callable = None, tool_complete_callback: callable = None,- thinking_callback: callable = None, reasoning_callback: callable = None,- clarify_callback: callable = None, read_terminal_callback: callable = None,- read_preview_callback: callable = None, drive_preview_callback: callable = None,- read_window_below_callback: callable = None, connection_callback: callable = None,- tour_callback: callable = None, setup_choose_callback: callable = None, step_callback: callable = None,- stream_delta_callback: callable = None, interim_assistant_callback: callable = None,- tool_gen_callback: callable = None, status_callback: callable = None,- notice_callback: callable = None, notice_clear_callback: callable = None,+ tool_progress_mode: str = "all", ephemeral_system_prompt: str | None = None,+ log_prefix_chars: int = 100, log_prefix: str = "", providers_allowed: list[str] | None = None,+ providers_ignored: list[str] | None = None, providers_order: list[str] | None = None,+ provider_sort: str | None = None, provider_require_parameters: bool = False,+ provider_data_collection: str | None = None, openrouter_min_coding_score: Optional[float] = None,+ session_id: str | None = None, tool_progress_callback: callable | None = None,+ tool_start_callback: callable | None = None, tool_complete_callback: callable | None = None,+ thinking_callback: callable | None = None, reasoning_callback: callable | None = None,+ clarify_callback: callable | None = None, read_terminal_callback: callable | None = None,+ read_preview_callback: callable | None = None, drive_preview_callback: callable | None = None,+ read_window_below_callback: callable | None = None, connection_callback: callable | None = None,+ tour_callback: callable | None = None, setup_choose_callback: callable | None = None, step_callback: callable | None = None,+ stream_delta_callback: callable | None = None, interim_assistant_callback: callable | None = None,+ tool_gen_callback: callable | None = None, status_callback: callable | None = None,+ notice_callback: callable | None = None, notice_clear_callback: callable | None = None,event_callback: Optional[Callable[[str, dict], None]] = None,- reaction_callback: Optional[Callable[[str], None]] = None, max_tokens: int = None,- reasoning_config: dict[str, Any] = None, service_tier: str = None,- request_overrides: dict[str, Any] = None, prefill_messages: list[dict[str, Any]] = None,- platform: str = None, user_id: str = None, user_id_alt: str = None, user_name: str = None,- chat_id: str = None, chat_name: str = None, chat_type: str = None, thread_id: str = None,- gateway_session_key: str = None, skip_context_files: bool = False,+ reaction_callback: Optional[Callable[[str], None]] = None, max_tokens: int | None = None,+ reasoning_config: dict[str, Any] | None = None, service_tier: str | None = None,+ request_overrides: dict[str, Any] | None = None, prefill_messages: list[dict[str, Any]] | None = None,+ platform: str | None = None, user_id: str | None = None, user_id_alt: str | None = None, user_name: str | None = None,+ chat_id: str | None = None, chat_name: str | None = None, chat_type: str | None = None, thread_id: str | None = None,+ gateway_session_key: str | None = None, skip_context_files: bool = False,load_soul_identity: bool = False, skip_memory: bool = False,- skip_background_review: bool = False, session_db=None, parent_session_id: str = None,+ skip_background_review: bool = False, session_db=None, parent_session_id: str | None = None,iteration_budget: "IterationBudget" = None, run_budget_seconds: Optional[float] = None,- fallback_model: dict[str, Any] = None, credential_pool=None, checkpoints_enabled: bool = False,+ fallback_model: dict[str, Any] | None = None, credential_pool=None, checkpoints_enabled: bool = False,checkpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,- requested_provider: str = None, capabilities: Optional[dict[str, bool]] = None, cwd: Optional[str] = None,+ requested_provider: str | None = None, capabilities: Optional[dict[str, bool]] = None, cwd: Optional[str] = None,side_agent: bool = False, memory_manager=None,tool_result_metadata_callback: Optional[Callable[..., dict]] = None,):diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 5d8879bf921..f9a96d2d6fe 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -231,7 +231,7 @@ def _cursor_skip_prefix(messages: list, cursor: Optional[dict]) -> int:def sanitize_tool_call_arguments(- messages: list, *, logger=None, session_id: str = None, cursor: Optional[dict] = None+ messages: list, *, logger=None, session_id: str | None = None, cursor: Optional[dict] = None) -> int:"""Repair corrupted assistant tool-call argument JSON in-place.``cursor["prefix"]`` holds strong refs (not ``id()``: address reuse aliases) to the@@ -2545,7 +2545,7 @@ def _pre_tool_block_message(agent, function_name, function_args, effective_task_def invoke_tool(agent, function_name: str, function_args: dict, effective_task_id: str,- tool_call_id: Optional[str] = None, messages: list = None,+ tool_call_id: Optional[str] = None, messages: list | None = None,pre_tool_block_checked: bool = False,skip_tool_request_middleware: bool = False,tool_request_middleware_trace: Optional[list[dict[str, Any]]] = None,diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex 468312afea9..1f58f7e3c1c 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -387,7 +387,7 @@ def _base_client_kwargs(base_url, timeout) -> tuple[str, dict[str, Any]]:def _build_anthropic_client_with_bearer_hook(- token_provider, base_url: str = None, timeout: float = None, *, drop_context_1m_beta: bool = False+ token_provider, base_url: str | None = None, timeout: float | None = None, *, drop_context_1m_beta: bool = False):"""Anthropic-on-Foundry Entra ID variant of :func:`build_anthropic_client`. The SDK stores``api_key``/``auth_token`` as static strings, so per-request bearer refresh (Microsoft's@@ -414,7 +414,7 @@ def _build_anthropic_client_with_bearer_hook(return _new_sdk_client(sdk, kwargs, headers, route=base_url)-def _new_sdk_client(sdk, kwargs: dict[str, Any], headers: dict[str, str], route: str = None):+def _new_sdk_client(sdk, kwargs: dict[str, Any], headers: dict[str, str], route: str | None = None):"""``sdk.Anthropic(**kwargs)`` with ``headers`` attached, sending exactly ONE credential.``route`` is the caller's un-normalized base_url (the ``/v1`` form ``custom_providers`` entries arekeyed by; ``kwargs["base_url"]`` has it stripped) for the per-provider ``extra_headers`` lookup.@@ -470,7 +470,7 @@ def _auth_style(api_key, base_url, normalized_base_url) -> str:return "api_key"-def build_anthropic_client(api_key, base_url: str = None, timeout: float = None, *, drop_context_1m_beta: bool = False):+def build_anthropic_client(api_key, base_url: str | None = None, timeout: float | None = None, *, drop_context_1m_beta: bool = False):"""Create an Anthropic client, auto-detecting setup-tokens vs API keys. ``api_key`` is a static``str`` or a ``Callable[[], str]`` Entra ID bearer provider (routed through:func:`_build_anthropic_client_with_bearer_hook`). ``timeout`` overrides the 900s read timeoutdiff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 5aac9b9f726..48445451250 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2296,7 +2296,7 @@ def _warn_paid_lane_once(model: str) -> None:)-def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None, model: str = None,+def _try_openrouter(explicit_api_key: Optional[Union[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@@ -2335,7 +2335,7 @@ def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] =), or_model-def _describe_openrouter_unavailable(model: str = None) -> str:+def _describe_openrouter_unavailable(model: str | None = None) -> str:"""Return the policy or credential reason OpenRouter was unavailable."""free_only, cfg_model = _aux_openrouter_settings()or_model = model or cfg_model@@ -4240,7 +4240,7 @@ async def _call_fallback_candidate_async(def _try_payment_fallback(- failed_provider: str, task: str = None, reason: str = "payment error", *,+ failed_provider: str, task: str | None = None, reason: str = "payment error", *,failed_base_url: str = "", failure_scope: Any = None, main_runtime: Optional[dict[str, Any]] = None,) -> tuple[Optional[Any], Optional[str], str]:"""Try the auto-detection chain after a payment/credit or connection error, skipping the failed@@ -4299,7 +4299,7 @@ def _failed_backend_skip(def _try_main_agent_model_fallback(- failed_provider: str, task: str = None, reason: str = "error",+ failed_provider: str, task: str | None = None, reason: str = "error",failed_model: Optional[str] = None, failed_base_url: str = "", failure_scope: Any = None,) -> tuple[Optional[Any], Optional[str], str]:"""Last-resort fallback to the main agent provider + model after the configured chain is exhausted.@@ -5421,9 +5421,9 @@ _EXPLICIT_PROVIDER_BRANCHES: dict[str, Callable[[_ResolveRequest], _ResolveResuldef resolve_provider_client(- provider: str, model: str = None, async_mode: bool = False, raw_codex: bool = False,- explicit_base_url: str = None, explicit_api_key: Optional[Union[str, Callable[[], str]]] = None,- api_mode: str = None, main_runtime: Optional[dict[str, Any]] = None, is_vision: bool = False,+ 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,+ 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]]:"""Central router: return a configured client (auth, base URL, API format) for a provider + optional model.@@ -6013,8 +6013,8 @@ def _compat_model(client: Any, model: Optional[str], cached_default: Optional[stdef _get_cached_client(- provider: str, model: str = None, async_mode: bool = False, base_url: str = None,- api_key: str = None, api_mode: str = None, main_runtime: Optional[dict[str, Any]] = None,+ provider: str, model: str | None = None, async_mode: bool = False, base_url: str | None = None,+ api_key: str | None = 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]]:"""Get or create a cached client for the given provider.@@ -6172,7 +6172,7 @@ def _named_custom_provider_present(name: str) -> bool:def _resolve_task_provider_model(- task: str = None, provider: str = None, model: str = None, base_url: Optional[str] = None,+ task: str | None = None, provider: str | None = None, model: str | None = None, base_url: Optional[str] = None,api_key: Optional[str] = None,) -> tuple[str, Optional[str], Optional[str], Optional[str], Optional[str]]:"""Determine (provider, model, base_url, api_key, api_mode) for a call.@@ -6905,7 +6905,7 @@ def _fail_relay_auxiliary_call(exc: BaseException) -> None:logger.warning("Relay auxiliary failure finalization failed", exc_info=True)-def _unwrap_data_envelope(response: Any, task: str = None) -> Any:+def _unwrap_data_envelope(response: Any, task: str | None = None) -> Any:"""Unwrap gateway envelopes like {"data": {<chat completion>}, "success": true}.Some OpenAI-compatible gateways (e.g. api.cline.bot) wrap non-streaming@@ -8042,12 +8042,12 @@ def _stamp_latency_once(latency_info: Optional[dict[str, int]], key: str, starte@_relay_auxiliary_calldef call_llm(- task: str = None, *, provider: str = None, model: str = None, base_url: str = None,- api_key: str = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,- temperature: Optional[float] = None, max_tokens: int = None, tools: list = None,- timeout: float = None, extra_body: dict = None, reasoning_config: Optional[dict] = None,- extra_headers: Optional[dict[str, str]] = None, api_mode: str = None, stream: bool = False,- stream_options: dict = None, route_info: Optional[dict[str, str]] = None,+ task: str | None = None, *, provider: str | None = None, model: str | None = None, base_url: str | None = None,+ api_key: str | None = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,+ temperature: Optional[float] = None, max_tokens: int | None = None, tools: list | None = None,+ timeout: float | None = None, extra_body: dict | None = None, reasoning_config: Optional[dict] = None,+ extra_headers: Optional[dict[str, str]] = None, api_mode: str | None = None, stream: bool = False,+ stream_options: dict | None = None, route_info: Optional[dict[str, str]] = None,latency_info: Optional[dict[str, int]] = None,) -> Any:"""Run an auxiliary LLM request, applying the configured task limit."""@@ -8177,12 +8177,12 @@ def _start_recovery_ladder(def _call_llm_impl(- task: str = None, *, provider: str = None, model: str = None, base_url: str = None,- api_key: str = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,- temperature: Optional[float] = None, max_tokens: int = None, tools: list = None,- timeout: float = None, extra_body: dict = None, reasoning_config: Optional[dict] = None,- extra_headers: Optional[dict[str, str]] = None, api_mode: str = None, stream: bool = False,- stream_options: dict = None, route_info: Optional[dict[str, str]] = None,+ task: str | None = None, *, provider: str | None = None, model: str | None = None, base_url: str | None = None,+ api_key: str | None = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,+ temperature: Optional[float] = None, max_tokens: int | None = None, tools: list | None = None,+ timeout: float | None = None, extra_body: dict | None = None, reasoning_config: Optional[dict] = None,+ extra_headers: Optional[dict[str, str]] = None, api_mode: str | None = None, stream: bool = False,+ stream_options: dict | None = None, route_info: Optional[dict[str, str]] = None,) -> Any:"""Centralized synchronous LLM call: resolve provider/model, auth, kwargs, fallbacks.task: aux task whose provider:model comes from config (ignored if provider set); api_mode@@ -8339,10 +8339,10 @@ def extract_content_or_reasoning(response, *, max_reasoning_chars: int | None =@_relay_auxiliary_call_asyncasync def async_call_llm(- task: str = None, *, provider: str = None, model: str = None, base_url: str = None,- api_key: str = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,- temperature: Optional[float] = None, max_tokens: int = None, tools: list = None,- timeout: float = None, extra_body: dict = None, reasoning_config: Optional[dict] = None,+ task: str | None = None, *, provider: str | None = None, model: str | None = None, base_url: str | None = None,+ api_key: str | None = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,+ temperature: Optional[float] = None, max_tokens: int | None = None, tools: list | None = None,+ timeout: float | None = None, extra_body: dict | None = None, reasoning_config: Optional[dict] = None,route_info: Optional[dict[str, str]] = None,) -> Any:"""Run an asynchronous auxiliary LLM request under the configured limit."""@@ -8363,10 +8363,10 @@ async def async_call_llm(async def _async_call_llm_impl(- task: str = None, *, provider: str = None, model: str = None, base_url: str = None,- api_key: str = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,- temperature: Optional[float] = None, max_tokens: int = None, tools: list = None,- timeout: float = None, extra_body: dict = None, reasoning_config: Optional[dict] = None,+ task: str | None = None, *, provider: str | None = None, model: str | None = None, base_url: str | None = None,+ api_key: str | None = None, main_runtime: Optional[dict[str, Any]] = None, messages: list,+ temperature: Optional[float] = None, max_tokens: int | None = None, tools: list | None = None,+ timeout: float | None = None, extra_body: dict | None = None, reasoning_config: Optional[dict] = None,route_info: Optional[dict[str, str]] = None,) -> Any:"""Centralized asynchronous LLM call; see call_llm() for full documentation.diff --git a/agent/compression_facade.py b/agent/compression_facade.pyindex 8a5e44bfb0e..35234a90a79 100644--- a/agent/compression_facade.py+++ b/agent/compression_facade.py@@ -219,10 +219,10 @@ class CompressionFacadeMixin:"""``_compress_context`` (see module docstring)."""def _compress_context(- self, messages: list, system_message: str, *, approx_tokens: int = None, task_id: str = "default",- focus_topic: str = None, force: bool = False, bypass_cooldown: bool = False,- defer_context_engine_notification: bool = False, commit_fence=None, verbatim_tail: list = None,- trigger: str = None, snapshot_is_current=None,+ self, messages: list, system_message: str, *, approx_tokens: int | None = None, task_id: str = "default",+ focus_topic: str | None = None, force: bool = False, bypass_cooldown: bool = False,+ defer_context_engine_notification: bool = False, commit_fence=None, verbatim_tail: list | None = None,+ trigger: str | None = None, snapshot_is_current=None,) -> tuple:"""Forwarder — see ``agent.conversation_compression.compress_context``.``force=True`` (manual /compress) bypasses the summary-failure cooldown; ``bypass_cooldown=True``diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 8863e0190cd..191b4e9f359 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -2897,7 +2897,7 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMidef __init__(self, model: str, threshold_percent: float = 0.50, protect_first_n: int = 3, protect_last_n: int = 20,- summary_target_ratio: float = 0.20, quiet_mode: bool = False, summary_model_override: str = None,+ summary_target_ratio: float = 0.20, quiet_mode: bool = False, summary_model_override: str | None = None,base_url: str = "", api_key: str = "", config_context_length: int | None = None, provider: str = "",api_mode: str = "", abort_on_summary_failure: bool = False, max_tokens: int | None = None,model_thresholds: dict[str, float] | None = None, threshold_tokens_cap: Any = None,@@ -3086,11 +3086,11 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMireturn Falsereturn not self._provider_omits_usage- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:"""True when compression should run now (anti-thrash included; see :meth:`should_compress_info` for the reason)."""return self.should_compress_info(prompt_tokens)[0]- def should_compress_info(self, prompt_tokens: int = None) -> "tuple[bool, str | None]":+ def should_compress_info(self, prompt_tokens: int | None = None) -> "tuple[bool, str | None]":"""Return ``(should_compress, reason)``.``reason`` is None unless compression is needed but blocked: ``"cooldown:<seconds>"`` or``"ineffective"``. Callers should surface a warning when it is non-None."""diff --git a/agent/context_engine.py b/agent/context_engine.pyindex b8789e030d6..c9bc6d33001 100644--- a/agent/context_engine.py+++ b/agent/context_engine.py@@ -82,10 +82,10 @@ class ContextEngine(ABC):"""@abstractmethod- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:"""Return True if compaction should fire this turn."""- def should_compress_info(self, prompt_tokens: int = None) -> "tuple[bool, str | None]":+ def should_compress_info(self, prompt_tokens: int | None = None) -> "tuple[bool, str | None]":"""Return ``(should_compress, reason)``.Engines with block reasons (summary-LLM cooldown, anti-thrashing guard) override@@ -119,8 +119,8 @@ class ContextEngine(ABC):return messages, 0def select_context(- self, request_messages: list[dict[str, Any]], *, conversation_messages: list[dict[str, Any]] = None,- incoming_message: dict[str, Any] = None, budget_tokens: int = 0,+ self, request_messages: list[dict[str, Any]], *, conversation_messages: list[dict[str, Any]] | None = None,+ incoming_message: dict[str, Any] | None = None, budget_tokens: int = 0,) -> list[dict[str, Any]]:"""Optionally *select* (replace) the context for THIS request, pre-generation.@@ -140,7 +140,7 @@ class ContextEngine(ABC):"""return None- def on_turn_complete(self, messages: list[dict[str, Any]], usage: dict[str, Any] = None, **kwargs: Any) -> None:+ def on_turn_complete(self, messages: list[dict[str, Any]], usage: dict[str, Any] | None = None, **kwargs: Any) -> None:"""Observe a finished turn (complement of ``select_context()``) to index/updaterouting state for the next request.diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 6404de28b8f..411134b41ae 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1547,9 +1547,9 @@ def _codex_app_server_turn(agent: Any, s: Any) -> Optional[dict[str, Any]]:def _run_conversation_turn(agent,user_message: Any,- system_message: str = None,- conversation_history: list[dict[str, Any]] = None,- task_id: str = None,+ system_message: str | None = None,+ conversation_history: list[dict[str, Any]] | None = None,+ task_id: str | None = None,stream_callback: Optional[callable] = None,persist_user_message: Optional[Any] = None,persist_user_timestamp: Optional[float] = None,@@ -1709,9 +1709,9 @@ def _run_conversation_turn(def run_conversation(agent,user_message: Any,- system_message: str = None,- conversation_history: list[dict[str, Any]] = None,- task_id: str = None,+ system_message: str | None = None,+ conversation_history: list[dict[str, Any]] | None = None,+ task_id: str | None = None,stream_callback: Optional[callable] = None,persist_user_message: Optional[Any] = None,persist_user_timestamp: Optional[float] = None,diff --git a/agent/display.py b/agent/display.pyindex c7cdc19ce36..46bf04a0346 100644--- a/agent/display.py+++ b/agent/display.py@@ -951,7 +951,7 @@ class KawaiiSpinner:redirect_stdout(devnull) because _write targets the stdout captured at creation."""self._write(f"\r{self._clear_line_blanks()}\r {text}" if self.running else f" {text}", flush=True)- def stop(self, final_message: str = None):+ def stop(self, final_message: str | None = None):self.running = Falseif self.thread:self.thread.join(timeout=0.5)diff --git a/agent/insights.py b/agent/insights.pyindex 50b7546c966..f48665c582e 100644--- a/agent/insights.py+++ b/agent/insights.py@@ -170,7 +170,7 @@ class InsightsEngine:sql, params = (getattr(self, base + "_WITH_SOURCE"), (cutoff, source)) if source else (getattr(self, base + "_ALL"), (cutoff,))return self._conn.execute(sql, params).fetchall()- def generate(self, days: int = 30, source: str = None) -> dict[str, Any]:+ def generate(self, days: int = 30, source: str | None = None) -> dict[str, Any]:"""Generate a complete insights report for the last ``days`` days, optionally filtered by source platform."""cutoff = time.time() - (days * 86400)# Drain the SessionDB's async accounting queue so counters are exact@@ -197,7 +197,7 @@ class InsightsEngine:"top_sessions": self._compute_top_sessions(sessions),}- def get_usage_breakdown(self, days: int = 30, source: str = None) -> dict[str, Any]:+ def get_usage_breakdown(self, days: int = 30, source: str | None = None) -> dict[str, Any]:"""Analytics-usage payload (tools + skills) without a full generate(); theinstr()-prefiltered skill query loads only skill_view/skill_manage messages."""cutoff = time.time() - (days * 86400)@@ -206,7 +206,7 @@ class InsightsEngine:# ------------------------------------------------------------------ SQL- def _get_sessions(self, cutoff: float, source: str = None) -> list[dict]:+ def _get_sessions(self, cutoff: float, source: str | None = None) -> list[dict]:# Coerce the two epoch columns once at load: one corrupt/TEXT cell must degrade to "unknown"# for that session, never abort the whole report (#99959).rows = [dict(row) for row in self._query("_GET_SESSIONS", cutoff, source)]@@ -215,7 +215,7 @@ class InsightsEngine:row[col] = coerce_epoch(row.get(col), session_id=row.get("id"), field=col)return rows- def _get_tool_usage(self, cutoff: float, source: str = None) -> list[dict]:+ def _get_tool_usage(self, cutoff: float, source: str | None = None) -> list[dict]:"""Tool call counts from two sources: ``tool_name`` on 'tool' rows (setby the gateway) and ``tool_calls`` JSON on assistant rows (covers CLI,where tool_name is not populated). The two views are reconciled PER@@ -237,7 +237,7 @@ class InsightsEngine:tool_counts[key[1]] += max(by_session_tool.get(key, 0), calls_by_session_tool.get(key, 0))return [{"tool_name": name, "count": count} for name, count in tool_counts.most_common()]- def _get_skill_usage(self, cutoff: float, source: str = None) -> list[dict]:+ def _get_skill_usage(self, cutoff: float, source: str | None = None) -> list[dict]:"""Extract per-skill usage from assistant tool calls."""skill_counts: dict[str, dict[str, Any]] = {}for row in self._query("_GET_SKILL_CALLS", cutoff, source):@@ -255,11 +255,11 @@ class InsightsEngine:entry["last_used_at"] = timestampreturn list(skill_counts.values())- def _get_message_stats(self, cutoff: float, source: str = None) -> dict:+ def _get_message_stats(self, cutoff: float, source: str | None = None) -> dict:rows = self._query("_GET_MESSAGE_STATS", cutoff, source)return dict(rows[0]) if rows else {"total_messages": 0, "user_messages": 0, "assistant_messages": 0, "tool_messages": 0}- def _get_model_usage(self, cutoff: float, source: str = None) -> list[dict]:+ def _get_model_usage(self, cutoff: float, source: str | None = None) -> list[dict]:"""Per-model usage rows; [] when the table is missing (older DB) so the caller falls back to the per-session aggregate."""try:return [dict(row) for row in self._query("_GET_MODEL_USAGE", cutoff, source)]@@ -315,7 +315,7 @@ class InsightsEngine:"included_cost_sessions": status_counts["included"],}- def _compute_model_breakdown(self, sessions: list[dict], cutoff: float, source: str = None) -> list[dict]:+ def _compute_model_breakdown(self, sessions: list[dict], cutoff: float, source: str | None = None) -> list[dict]:"""Tokens/cost per model from session_model_usage, so a session thatswitched models via ``/model`` splits across every model it used.Sessions without per-model rows (pre-table data) fall back to theirdiff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 864fb66e5fb..92a5772a3be 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -432,7 +432,7 @@ class SessionPersistenceMixin:if platform_id is not None: # load-bearing for restart drain-window recovery dedup (has_platform_message_id)msg["platform_message_id"] = platform_id- def _persist_session(self, messages: list[dict], conversation_history: list[dict] = None):+ def _persist_session(self, messages: list[dict], conversation_history: list[dict] | None = None):"""Save to SQLite on any exit path. Trailing empty-response scaffolding is dropped fromthe live list; the persist override is applied to the DB row only.diff --git a/agent/title_generator.py b/agent/title_generator.pyindex a726bed37d4..558e06bdf1d 100644--- a/agent/title_generator.py+++ b/agent/title_generator.py@@ -472,7 +472,7 @@ def generate_title(user_message: str,timeout: Optional[float] = None,failure_callback: Optional[FailureCallback] = None,- main_runtime: dict = None,+ main_runtime: dict | None = None,runtime_validator: Optional[RuntimeValidator] = None,title_preview: str | None = None,) -> Optional[str]:@@ -644,7 +644,7 @@ def auto_title_session(session_id: str,user_message: str,failure_callback: Optional[FailureCallback] = None,- main_runtime: dict = None,+ main_runtime: dict | None = None,title_callback: Optional[TitleCallback] = None,runtime_validator: Optional[RuntimeValidator] = None,title_preview: str | None = None,@@ -739,7 +739,7 @@ def maybe_auto_title(user_message: str,conversation_history: Optional[list] = None,failure_callback: Optional[FailureCallback] = None,- main_runtime: dict = None,+ main_runtime: dict | None = None,title_callback: Optional[TitleCallback] = None,runtime_validator: Optional[RuntimeValidator] = None,title_preview: str | None = None,diff --git a/agent/trajectory.py b/agent/trajectory.pyindex bf5636d82a4..ad0a50b3a49 100644--- a/agent/trajectory.py+++ b/agent/trajectory.py@@ -34,7 +34,7 @@ def _lock_append_handle(f, acquire: bool) -> None:fcntl.flock(f.fileno(), fcntl.LOCK_EX if acquire else fcntl.LOCK_UN)-def save_trajectory(trajectory: list[dict[str, Any]], model: str, completed: bool, filename: str = None):+def save_trajectory(trajectory: list[dict[str, Any]], model: str, completed: bool, filename: str | None = None):"""Append a ShareGPT-format entry to a JSONL file (default trajectory_samples.jsonl / failed_trajectories.jsonl by ``completed``)."""if filename is None:filename = "trajectory_samples.jsonl" if completed else "failed_trajectories.jsonl"diff --git a/agent/turn_facade.py b/agent/turn_facade.pyindex a4839ed4c6d..3830058dce4 100644--- a/agent/turn_facade.py+++ b/agent/turn_facade.py@@ -20,8 +20,8 @@ class TurnFacadeMixin:"""run_conversation()/chat() (see module docstring)."""def run_conversation(- self, user_message: Any, system_message: str=None,- conversation_history: list[dict[str, Any]]=None, task_id: str=None,+ self, user_message: Any, system_message: str | None=None,+ conversation_history: list[dict[str, Any]] | None=None, task_id: str | None=None,stream_callback: Optional[callable]=None, persist_user_message: Optional[Any]=None,persist_user_timestamp: Optional[float]=None, persist_user_display_kind: Optional[str]=None,persist_user_display_metadata: Optional[dict[str, Any]]=None,diff --git a/agent/vision_message_prep.py b/agent/vision_message_prep.pyindex c9dbbeb35d3..c6e6586abe3 100644--- a/agent/vision_message_prep.py+++ b/agent/vision_message_prep.py@@ -174,7 +174,7 @@ class VisionMessagePrepMixin:return f"{prefix}\n\n{suffix}"return prefix or suffix or "[A multimodal message was converted to text for Anthropic compatibility.]"- def _get_transport(self, api_mode: str = None):+ def _get_transport(self, api_mode: str | None = None):"""Return the cached transport for the given (or current) api_mode (lazy; None if unregistered)."""mode = api_mode or self.api_modecache = getattr(self, "_transport_cache", None)diff --git a/batch_runner.py b/batch_runner.pyindex 410855b5e8a..47bbfae64e9 100644--- a/batch_runner.py+++ b/batch_runner.py@@ -429,22 +429,22 @@ class BatchRunner:run_name: str,distribution: str = "default",max_iterations: int = 10,- base_url: str = None,- api_key: str = None,+ base_url: str | None = None,+ api_key: str | None = None,model: str = "claude-opus-4-20250514",num_workers: int = 4,verbose: bool = False,- ephemeral_system_prompt: str = None,+ ephemeral_system_prompt: str | None = None,log_prefix_chars: int = 100,- providers_allowed: list[str] = None,- providers_ignored: list[str] = None,- providers_order: list[str] = None,- provider_sort: str = None,+ providers_allowed: list[str] | None = None,+ providers_ignored: list[str] | None = None,+ providers_order: list[str] | None = None,+ provider_sort: str | None = None,openrouter_min_coding_score: Optional[float] = None,- reasoning_config: dict[str, Any] = None,- prefill_messages: list[dict[str, Any]] = None,- max_samples: int = None,+ reasoning_config: dict[str, Any] | None = None,+ prefill_messages: list[dict[str, Any]] | None = None,+ max_samples: int | None = None,):"""Load the dataset (truncated to *max_samples*), validate *distribution*, create batches.@@ -863,29 +863,29 @@ def _split_csv(value: Optional[str]) -> Optional[list[str]]:def main(- dataset_file: str = None,- batch_size: int = None,- run_name: str = None,+ dataset_file: str | None = None,+ batch_size: int | None = None,+ run_name: str | None = None,distribution: str = "default",model: str = "anthropic/claude-sonnet-4.6",- api_key: str = None,+ api_key: str | None = None,base_url: str = "https://openrouter.ai/api/v1",max_turns: int = 10,num_workers: int = 4,resume: bool = False,verbose: bool = False,list_distributions: bool = False,- ephemeral_system_prompt: str = None,+ ephemeral_system_prompt: str | None = None,log_prefix_chars: int = 100,- providers_allowed: str = None,- providers_ignored: str = None,- providers_order: str = None,- provider_sort: str = None,+ providers_allowed: str | None = None,+ providers_ignored: str | None = None,+ providers_order: str | None = None,+ provider_sort: str | None = None,- reasoning_effort: str = None,+ reasoning_effort: str | None = None,reasoning_disabled: bool = False,- prefill_messages_file: str = None,- max_samples: int = None,+ prefill_messages_file: str | None = None,+ max_samples: int | None = None,):"""Run batch processing of agent prompts from a dataset.diff --git a/cli.py b/cli.pyindex ce818e560e8..78ff9357c58 100644--- a/cli.py+++ b/cli.py@@ -581,7 +581,7 @@ from hermes_cli.worktree_ops import (_active_worktree: Optional[dict[str, str]] = None-def _cleanup_worktree(info: dict[str, str] = None) -> None:+def _cleanup_worktree(info: dict[str, str] | None = None) -> None:"""Remove a clean worktree and its branch on exit; preserve recoverable work."""global _active_worktreeinfo = info or _active_worktree@@ -902,17 +902,17 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,def __init__(self,- model: str = None,- toolsets: list[str] = None,- provider: str = None,- reasoning: str = None,- api_key: str = None,- base_url: str = None,- max_turns: int = None,- run_budget: float = None,+ model: str | None = None,+ toolsets: list[str] | None = None,+ provider: str | None = None,+ reasoning: str | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ max_turns: int | None = None,+ run_budget: float | None = None,verbose: Optional[bool] = None,compact: bool = False,- resume: str = None,+ resume: str | None = None,checkpoints: bool = False,pass_session_id: bool = False,ignore_rules: bool = False,@@ -1648,26 +1648,26 @@ def _start_worktree_setup(list_tools, list_toolsets, worktree, w):def main(- query: str = None,- q: str = None,+ query: str | None = None,+ q: str | None = None,oneshot: bool = False,- image: str = None,- toolsets: str = None,- skills: str | list[str] | tuple[str, ...] = None,- model: str = None,- provider: str = None,- reasoning: str = None,- api_key: str = None,- base_url: str = None,- max_turns: int = None,- run_budget: float = None,+ image: str | None = None,+ toolsets: str | None = None,+ skills: str | list[str] | tuple[str, ...] | None = None,+ model: str | None = None,+ provider: str | None = None,+ reasoning: str | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ max_turns: int | None = None,+ run_budget: float | None = None,verbose: Optional[bool] = None,quiet: bool = False,compact: bool = False,list_tools: bool = False,list_toolsets: bool = False,gateway: bool = False,- resume: str = None,+ resume: str | None = None,worktree: bool = False,w: bool = False,checkpoints: bool = False,diff --git a/gateway/delivery.py b/gateway/delivery.pyindex 6ae9e18694d..b38dfb1433c 100644--- a/gateway/delivery.py+++ b/gateway/delivery.py@@ -164,7 +164,7 @@ async def _ensure_named_dm_topic(adapter: Any, chat_id: str, name: str, *, refreclass DeliveryRouter:"""Resolves delivery targets and dispatches messages to platform adapters."""- def __init__(self, config: GatewayConfig, adapters: dict[Platform, Any] = None,+ def __init__(self, config: GatewayConfig, adapters: dict[Platform, Any] | None = None,dead_targets: Optional[DeadTargetRegistry] = None): # profile-local registry when omittedself.config = configself.adapters = adapters or {}diff --git a/gateway/pairing.py b/gateway/pairing.pyindex cd01cd35179..a66014979be 100644--- a/gateway/pairing.py+++ b/gateway/pairing.py@@ -406,7 +406,7 @@ class PairingStore:with self._lock:return bool(_matching_ids(platform, self._load_approved(platform), user_id))- def list_approved(self, platform: str = None) -> list:+ def list_approved(self, platform: str | None = None) -> list:"""List approved users, optionally filtered by platform."""return [{"platform": p, "user_id": uid, **info}@@ -539,7 +539,7 @@ class PairingStore:return self._finish_approval(platform, pending, entry_id, entry)return None- def list_pending(self, platform: str = None) -> list:+ def list_pending(self, platform: str | None = None) -> list:"""List pending requests (codes are never returned; each exposes a ``request_id``for :meth:`approve_request`; legacy pre-hash entries report an empty id)."""results = []@@ -559,7 +559,7 @@ class PairingStore:})return results- def clear_pending(self, platform: str = None) -> int:+ def clear_pending(self, platform: str | None = None) -> int:"""Clear all pending requests. Returns count removed."""with self._lock:count = 0diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 432ee892542..ab9f4d78b48 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -245,7 +245,7 @@ class ThreadSafeAsyncQueue(asyncio.Queue):"""``asyncio.Queue`` a non-loop thread (run_conversation's executor) can push into via``put_threadsafe``; the SSE consumer's ``await get()`` is woken by ``call_soon_threadsafe``."""- def put_threadsafe(self, item, *, loop: asyncio.AbstractEventLoop = None) -> None:+ def put_threadsafe(self, item, *, loop: asyncio.AbstractEventLoop | None = None) -> None:(loop or self._loop_ref).call_soon_threadsafe(self.put_nowait, item)def __init__(self, *args, **kwargs):@@ -256,7 +256,7 @@ class ThreadSafeAsyncQueue(asyncio.Queue):def _sse_frame(- data: Any, *, event: str = None, ensure_ascii: bool = True, id: Optional[int] = None+ data: Any, *, event: str | None = None, ensure_ascii: bool = True, id: Optional[int] = None) -> bytes:"""Encode one SSE frame (``id:``/``event:`` lines if given, then ``data: <json>\n\n``) forevery SSE writer. ``ensure_ascii=False`` keeps raw non-ASCII on the wire."""@@ -696,7 +696,7 @@ class ResponseStore:"""SQLite-backed LRU store for Responses API state (full conversation history per responsefor ``previous_response_id`` chaining). Persists across restarts; in-memory fallback."""- def __init__(self, max_size: int = MAX_STORED_RESPONSES, db_path: str = None):+ def __init__(self, max_size: int = MAX_STORED_RESPONSES, db_path: str | None = None):self._max_size = max_sizeif db_path is None:db_path = ":memory:"@@ -903,7 +903,7 @@ def _redact_api_error_text(value: Any, *, limit: int | None = None) -> str:return redacted[:limit] if limit is not None else redacted-def _openai_error(message: str, err_type: str = "invalid_request_error", param: str = None, code: str = None) -> dict[str, Any]:+def _openai_error(message: str, err_type: str = "invalid_request_error", param: str | None = None, code: str | None = None) -> dict[str, Any]:"""OpenAI-style error envelope."""return {"error": {"message": _redact_api_error_text(message), "type": err_type, "param": param, "code": code}}@@ -911,7 +911,7 @@ def _openai_error(message: str, err_type: str = "invalid_request_error", param:def _error_response(message: str, status: int, *, err_type: str = "invalid_request_error",- param: str = None, code: str = None, headers: Optional[dict[str, str]] = None,+ param: str | None = None, code: str | None = None, headers: Optional[dict[str, str]] = None,) -> "web.Response":"""``web.json_response(_openai_error(...), status=...)`` in one call."""return web.json_response(_openai_error(message, err_type, param, code), status=status, headers=headers)@@ -3644,7 +3644,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if delta:events.enqueue("assistant.delta", {"message_id": message_id, "delta": delta})- def _tool_progress(event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs) -> None:+ def _tool_progress(event_type: str, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs) -> None:if event_type == "reasoning.available":events.enqueue("tool.progress", {"message_id": message_id, "tool_name": tool_name or "_thinking", "delta": preview or ""})elif event_type in {"tool.started", "tool.completed", "tool.failed"}:diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 0ebac98fad1..33c9a052fca 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -885,8 +885,8 @@ class OpenAICompatRoutesMixin:async def _write_sse_chat_completion(self, request: "web.Request", completion_id: str, model: str,- created: int, stream_q, agent_task, agent_ref=None, session_id: str = None,- gateway_session_key: str = None) -> "web.StreamResponse":+ created: int, stream_q, agent_task, agent_ref=None, session_id: str | None = None,+ gateway_session_key: str | None = None) -> "web.StreamResponse":"""Stream ``chat.completion.chunk`` frames from the agent's delta queue. On clientdisconnect the agent is interrupted (stops LLM calls), then its task wrapper cancelled."""from gateway.platforms.api_server import (diff --git a/gateway/platforms/api_server_run_idempotency.py b/gateway/platforms/api_server_run_idempotency.pyindex f40d91d70c5..74f0b28da13 100644--- a/gateway/platforms/api_server_run_idempotency.py+++ b/gateway/platforms/api_server_run_idempotency.py@@ -62,7 +62,7 @@ class RunIdempotencyStore:def durable(self) -> bool:"""Whether reservations survive this process."""return self._db_path is not None- def __init__(self, db_path: str = None):+ def __init__(self, db_path: str | None = None):if db_path is None:try:from hermes_cli.config import get_hermes_homediff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 7853fdf70ef..9a5b50bb838 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -324,7 +324,7 @@ def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoopwith suppress(Exception):loop.call_soon_threadsafe(q.put_nowait, event)- def _callback(event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs):+ def _callback(event_type: str, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs):# _thinking / subagent.tool / subagent_progress are deliberately dropped (UI noise);# lifecycle boundaries must land so clients can observe delegate_task failures.fields = _FIXED_EVENT_FIELDS.get(event_type)diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.pyindex 58610d374cb..f94fb881be9 100644--- a/gateway/platforms/signal.py+++ b/gateway/platforms/signal.py@@ -594,7 +594,7 @@ class SignalAdapter(BasePlatformAdapter):else cache_audio_from_bytes_async if _is_audio_ext(ext) else cache_document_from_bytes_async)return await cache(raw_data, ext), ext- async def _rpc(self, method: str, params: dict, rpc_id: str = None, *, log_failures: bool = True,+ async def _rpc(self, method: str, params: dict, rpc_id: str | None = None, *, log_failures: bool = True,raise_on_rate_limit: bool = False, timeout: float = 30.0) -> Any:"""Send a JSON-RPC 2.0 request to signal-cli. ``log_failures=False`` logs failures at DEBUG (typingpath: silence NETWORK_FAILURE spam); ``raise_on_rate_limit=True`` raises ``SignalRateLimitError``diff --git a/gateway/platforms/yuanbao_sticker.py b/gateway/platforms/yuanbao_sticker.pyindex 8ff19b6a6da..5d7c85d1b4a 100644--- a/gateway/platforms/yuanbao_sticker.py+++ b/gateway/platforms/yuanbao_sticker.py@@ -105,7 +105,7 @@ def get_sticker_by_name(name: str) -> Optional[dict]:return matches[0] if matches else None-def get_random_sticker(category: str = None) -> dict:+def get_random_sticker(category: str | None = None) -> dict:"""随机贴纸;指定 category 时优先在 description/name 含该词的贴纸中选取。"""candidates = [s for s in STICKER_MAP.values() if category in s["description"] or category in s["name"]] if category else []return random.choice(candidates or list(STICKER_MAP.values()))diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 698e59e0034..eefee0d87f8 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -2752,7 +2752,7 @@ class GatewayTurnMixin:async def _run_agent_via_proxy(self, message: str, context_prompt: str, history: list[dict[str, Any]],- source: "SessionSource", session_id: str, session_key: str = None,+ source: "SessionSource", session_id: str, session_key: str | None = None,run_generation: Optional[int] = None, event_message_id: Optional[str] = None,scheduled_heartbeat: bool = False,) -> dict[str, Any]:@@ -4264,7 +4264,7 @@ class GatewayTurnMixin:async def _run_agent_inner(self, message: str, context_prompt: str, history: list[dict[str, Any]],- source: SessionSource, session_id: str, session_key: str = None,+ source: SessionSource, session_id: str, session_key: str | None = None,run_generation: Optional[int] = None, _interrupt_depth: int = 0,event_message_id: Optional[str] = None, inbound_message_id: Optional[str] = None,channel_prompt: Optional[str] = None, moa_config: Optional[dict] = None,diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 445c9319d54..c822f988455 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -124,7 +124,7 @@ class TurnRunner:# ── progress_callback (agent thread → progress queue) ───────────────────────────────────- def progress_callback(self, event_type: str, tool_name: str = None, preview: str = None, args: dict = None, **kwargs):+ def progress_callback(self, event_type: str, tool_name: str | None = None, preview: str | None = None, args: dict | None = None, **kwargs):"""Callback invoked by agent on tool lifecycle events."""ctx = self._ctx# Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queuediff --git a/gateway/session.py b/gateway/session.pyindex 7b1e37eaa67..3c016b53271 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1064,7 +1064,7 @@ class SessionStore()def update_session(- self, session_key: str, last_prompt_tokens: int = None, touch_activity: bool = True,+ self, session_key: str, last_prompt_tokens: int | None = None, touch_activity: bool = True,) -> None:"""Update lightweight session metadata after an interaction; internal turns pass``touch_activity=False`` so the reset-policy clock does not advance."""diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 62197debc0f..560ad60d4b2 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -172,7 +172,7 @@ def _sync_codex_pool_entries(def _save_codex_tokens(- tokens: dict[str, str], last_refresh: str = None, label: str = None, *,+ tokens: dict[str, str], last_refresh: str | None = None, label: str | None = None, *,set_active: bool = True, write_through: bool = False,) -> None:"""Save Codex OAuth tokens to the auth store the grant was resolved FROM.diff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex c37e5226a65..790807125e3 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -428,7 +428,7 @@ def banner_snapshot_fingerprint() -> Optional[str]:return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()-def load_banner_snapshot(enabled_toolsets: list[str] = None) -> Optional[dict[str, Any]]:+def load_banner_snapshot(enabled_toolsets: list[str] | None = None) -> Optional[dict[str, Any]]:"""Return the stored banner snapshot when its fingerprint is current."""blob = _quiet(lambda: json.loads(_banner_snapshot_path().read_text(encoding="utf-8-sig")))if not isinstance(blob, dict):@@ -467,7 +467,7 @@ def save_banner_snapshot(tools: list[dict], enabled_toolsets: list[str], availab_quiet(_write)-def compute_toolset_availability(enabled_toolsets: list[str] = None) -> dict[str, Any]:+def compute_toolset_availability(enabled_toolsets: list[str] | None = None) -> dict[str, Any]:"""Compute ``{"unavailable_toolsets", "lazy_tools", "disabled_tools"}`` for the banner.Split out so the result can be snapshotted and replayed without importing ``model_tools``.@@ -685,9 +685,9 @@ def _banner_skill_lines(skills_by_category: dict[str, list[str]], skills_enableddef build_welcome_banner(- console: "Console", model: str, cwd: str, tools: list[dict] = None, enabled_toolsets: list[str] = None,- session_id: str = None, get_toolset_for_tool=None, context_length: int = None, provider: str = None,- availability: dict[str, Any] = None, skills_by_category: dict[str, list[str]] = None,+ console: "Console", model: str, cwd: str, tools: list[dict] | None = None, enabled_toolsets: list[str] | None = None,+ session_id: str | None = None, get_toolset_for_tool=None, context_length: int | None = None, provider: str | None = None,+ availability: dict[str, Any] | None = None, skills_by_category: dict[str, list[str]] | None = None,context_pinned: bool = False,):"""Build and print a welcome banner with caduceus on left and info on right.diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex d88884dd5ca..f9a74812d7f 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -622,7 +622,7 @@ class CLIAgentSetupMixin:self._reopen_session()return True- def _init_agent(self, *, model_override: str = None, runtime_override: dict = None, request_overrides: dict | None = None) -> bool:+ def _init_agent(self, *, model_override: str | None = None, runtime_override: dict | None = None, request_overrides: dict | None = None) -> bool:"""Build the agent on first use; when resuming, restore history from SQLite.Returns True on success."""from cli import ChatConsole, _cprint, _prepare_deferred_agent_startup, loggerdiff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.pyindex 15eb5614846..a94395d6b7e 100644--- a/hermes_cli/cli_chat_turn_mixin.py+++ b/hermes_cli/cli_chat_turn_mixin.py@@ -46,7 +46,7 @@ class CLIChatTurnMixin:returnGatewayRunner._apply_fallback_chain_to_agent(agent, self._fallback_model)- def chat(self, message, images: list = None, voice_input: bool = False) -> Optional[str]:+ def chat(self, message, images: list | None = None, voice_input: bool = False) -> Optional[str]:"""Run one user turn; returns the agent's response, or None on error.Input typed while the agent runs goes to ``_interrupt_queue`` (separate fromdiff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.pyindex 427ed65e1c1..cb8efde8925 100644--- a/hermes_cli/cli_stream_mixin.py+++ b/hermes_cli/cli_stream_mixin.py@@ -663,7 +663,7 @@ class CLIStreamMixin:what = bridge_generating_phrase(tool_name) or tool_name_cprint(f" ┊ {t('cli.stream.tool_preparing', emoji=get_tool_emoji(tool_name, default='⚡'), what=what)}")- def _on_tool_progress(self, event_type: str, function_name: str = None, preview: str = None, function_args: dict = None, **kwargs):+ def _on_tool_progress(self, event_type: str, function_name: str | None = None, preview: str | None = None, function_args: dict | None = None, **kwargs):"""Tool lifecycle events (tool.started / tool.completed / reasoning.* / moa.*).Drives the TUI spinner (tool.started stamps the elapsed timer); in "all"/"new"/"verbose"diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 205a3005de9..c4245202d27 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -2058,7 +2058,7 @@ def _resume_status_from_events(conn: sqlite3.Connection, task_id: str) -> str:return "ready"-def recompute_ready(conn: sqlite3.Connection, failure_limit: int = None) -> int:+def recompute_ready(conn: sqlite3.Connection, failure_limit: int | None = None) -> int:"""Promote ``todo``/``blocked`` tasks whose parents are all done/archived;returns the count. Opens its own IMMEDIATE txn — call OUTSIDE any write txn.diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex d41e63a46a9..a770af8e710 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -1348,7 +1348,7 @@ def _record_task_failure(error: str,*,outcome: str,- failure_limit: int = None,+ failure_limit: int | None = None,force_trip: bool = False,release_claim: bool = False,end_run: bool = False,diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 2bd402c2d4f..941ac7a569a 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -835,7 +835,7 @@ def _external_process_match(catalog: list[str], aliases: dict[str, str], typed:def get_authenticated_provider_slugs(- current_provider: str = "", user_providers: dict = None, custom_providers: list | None = None+ current_provider: str = "", user_providers: dict | None = None, custom_providers: list | None = None) -> list[str]:"""Slugs of providers that have credentials (models.dev in-memory cache + disk catalog cache;stale catalogs warm in the background, never in this call)."""@@ -1740,7 +1740,7 @@ def _build_switch_result(st: _Switch) -> ModelSwitchResult:def switch_model(raw_input: str, current_provider: str, current_model: str, current_base_url: str = "",current_api_key: str = "", is_global: bool = False, explicit_provider: str = "",- user_providers: dict = None, custom_providers: list | None = None) -> ModelSwitchResult:+ user_providers: dict | None = None, custom_providers: list | None = None) -> ModelSwitchResult:"""Core model-switching pipeline shared between CLI and gateway.Route (PATH A with ``--provider``, else PATH B) -> credentials -> validation -> result; eachdiff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.pyindex 891b20372a3..413721cf4c9 100644--- a/hermes_cli/model_switch_providers.py+++ b/hermes_cli/model_switch_providers.py@@ -1222,7 +1222,7 @@ def _build_curated_lists(current_provider: str, current_base_url: str, current_mdef list_authenticated_providers(- current_provider: str = "", current_base_url: str = "", user_providers: dict = None,+ current_provider: str = "", current_base_url: str = "", user_providers: dict | None = None,custom_providers: list | None = None, *, force_fresh_nous_tier: bool = False,max_models: int | None = None, current_model: str = "", refresh: bool = False,probe_custom_providers: bool = True, probe_current_custom_provider: bool = False,@@ -1362,7 +1362,7 @@ def _prepend_moa_picker_provider(providers: list[dict], current_provider: str =def list_picker_providers(- current_provider: str = "", current_base_url: str = "", user_providers: dict = None,+ current_provider: str = "", current_base_url: str = "", user_providers: dict | None = None,custom_providers: list | None = None, max_models: int | None = None, current_model: str = "",include_moa: bool = False, excluded_providers: list | None = None,non_blocking_catalogs: bool = False, probe_custom_providers: bool = True,diff --git a/hermes_cli/plugins_cadence.py b/hermes_cli/plugins_cadence.pyindex 88cfec0df48..f6c7259715a 100644--- a/hermes_cli/plugins_cadence.py+++ b/hermes_cli/plugins_cadence.py@@ -37,7 +37,7 @@ def _markers_dir() -> Path:return d-def check_interval_hours(config_get: Callable = None) -> float:+def check_interval_hours(config_get: Callable | None = None) -> float:"""plugins.auto_update_check_hours; 0 disables; default 24."""if config_get is None:config_get = _default_config_get@@ -54,7 +54,7 @@ def check_interval_hours(config_get: Callable = None) -> float:return max(0.0, hours)-def auto_apply_enabled(config_get: Callable = None) -> bool:+def auto_apply_enabled(config_get: Callable | None = None) -> bool:if config_get is None:config_get = _default_config_gettry:@@ -73,7 +73,7 @@ def _default_config_get(section: str, key: str):def check_due(now: Optional[float] = None, interval_hours: Optional[float] = None,- config_get: Callable = None) -> bool:+ config_get: Callable | None = None) -> bool:"""The clock gate: last-run marker vs the interval."""if interval_hours is None:interval_hours = check_interval_hours(config_get)@@ -100,7 +100,7 @@ def run_scheduled_check(plugins_dir: Path,apply_updates_fn: Optional[Callable[[str], None]] = None,log=None,- config_get: Callable = None,+ config_get: Callable | None = None,now: Optional[float] = None,) -> Optional[list]:"""One cadence tick: gate → check → receipt → (opt-in) apply.@@ -136,7 +136,7 @@ def _run_check_locked(plugins_dir: Path,apply_updates_fn: Optional[Callable[[str], None]],log,- config_get: Callable = None,+ config_get: Callable | None = None,) -> list:check_ok = Truewarning = ""diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 9d7cf5e5066..86a02489740 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -103,7 +103,7 @@ def _sanitize_pasted_input(value: str) -> str:return _BRACKETED_PASTE_PATTERN.sub("", value) if isinstance(value, str) and value else value-def prompt(question: str, default: str = None, password: bool = False) -> str:+def prompt(question: str, default: str | None = None, password: bool = False) -> str:"""Prompt for input with optional default."""display = color(f"{question} [{default}]: " if default else f"{question}: ", Colors.YELLOW)try:@@ -311,7 +311,7 @@ def prompt_yes_no(question: str, default: bool = True) -> bool:print_error("Please enter 'y' or 'n'")-def prompt_checklist(title: str, items: list, pre_selected: list = None) -> list:+def prompt_checklist(title: str, items: list, pre_selected: list | None = None) -> list:"""Multi-select checklist; returns the sorted indices of selected items. ``pre_selected``start checked; Space toggles, Enter confirms, cancel keeps the pre-selection."""from hermes_cli.curses_ui import curses_checklistdiff --git a/hermes_cli/setup_summary.py b/hermes_cli/setup_summary.pyindex a60da2a45ce..c3d18fbaf48 100644--- a/hermes_cli/setup_summary.py+++ b/hermes_cli/setup_summary.py@@ -64,7 +64,7 @@ def _voice_provider_status(kind: str, provider: str, rows: dict, default: tuple)return (f"{kind} ({label} — not installed)", False, hint)-def _first_available_plugin_provider(registry: str, skip: str = None):+def _first_available_plugin_provider(registry: str, skip: str | None = None):"""display_name of the first plugin-registered provider in ``agent.<registry>`` that reportsavailable (fail-soft: any error means none), skipping ``skip``."""try:diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.pyindex 2bf2b5101b5..272f1bd9d53 100644--- a/hermes_cli/tools_config.py+++ b/hermes_cli/tools_config.py@@ -772,7 +772,7 @@ def _provider_env_ready(provider: dict) -> bool:def _toolset_has_keys(- ts_key: str, config: dict = None, *, force_fresh: bool = False, features: Optional[NousSubscriptionFeatures] = None,+ ts_key: str, config: dict | None = None, *, force_fresh: bool = False, features: Optional[NousSubscriptionFeatures] = None,) -> bool:"""Check if a toolset's required API keys are configured."""if config is None:@@ -1065,7 +1065,7 @@ def _configure_platforms(config: dict, platform_keys: list[str], *, all_platformreturn True-def tools_command(args=None, first_install: bool = False, config: dict = None):+def tools_command(args=None, first_install: bool = False, config: dict | None = None):"""Entry point for `hermes tools` / `hermes setup tools`. ``first_install`` skips the menu (checklist + keyprompts); a wizard-passed ``config`` receives platform_toolsets so its final save_config() keeps them."""if config is None:diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.pyindex d1f34dd5a5e..650d1c24c78 100644--- a/hermes_cli/web_git.py+++ b/hermes_cli/web_git.py@@ -522,7 +522,7 @@ def _own_pr(key: str, field: dict) -> dict | None:return next((n for n in (field.get("nodes") or []) if n and not n.get("isCrossRepository")), None)-def review_pr_list(cwd: str, branches: list[str], numbers: list[int] = None) -> dict:+def review_pr_list(cwd: str, branches: list[str], numbers: list[int] | None = None) -> dict:"""PRs on the given branches (plus any asked for by number) — queried per branchrather than paging the repo's newest PRs and hoping ours are in the page."""not_ready = {"ghReady": False, "prs": []}diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex 7d3864ac088..ef1bc682bab 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -456,7 +456,7 @@ def get_profiles_sessions(# over-fetches ``limit + offset``.limit: int = Query(20, ge=0, le=500), offset: int = Query(0, ge=0), min_messages: int = 0,archived: str = "exclude", order: str = "recent", profile: str = "all",- source: str = None, sources: str = None, exclude_sources: str = None, full: bool = False):+ source: str | None = None, sources: str | None = None, exclude_sources: str | None = None, full: bool = False):"""Unified, read-only session list aggregated across ALL profiles: opens each profile's``state.db`` directly (no dashboard backend per profile) and tags rows with their owning``profile``. Rows omit ``system_prompt`` / ``model_config`` unless ``full=1`` — same@@ -513,8 +513,8 @@ def get_profiles_sessions(@sessions_router.get("/api/profiles/sessions/sidebar")@_sidebar_singleflight_cachedef get_profiles_sessions_sidebar(- recents_profile: str = "all", recents_limit: int = 20, recents_exclude: str = None,- cron_limit: int = 50, messaging_limit: int = 100, messaging_exclude: str = None):+ recents_profile: str = "all", recents_limit: int = 20, recents_exclude: str | None = None,+ cron_limit: int = 50, messaging_limit: int = 100, messaging_exclude: str | None = None):"""Batched sidebar session slices (recents / cron / messaging) — one profile-DB open perrefresh instead of three ``/api/profiles/sessions`` calls. Same row projection and 300sactive heuristic as the per-slice endpoint; all slices use ``min_messages=1`` /diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex cf2b655ac30..243039f55e8 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -177,8 +177,8 @@ def _resolve_session_id(db, session_id: str) -> Optional[str]:@list_router.get("/api/sessions")def get_sessions(limit: int = Query(20, ge=0, le=100), offset: int = Query(0, ge=0), min_messages: int = 0,- archived: str = "exclude", order: str = "created", source: str = None, sources: str = None,- exclude_sources: str = None, cwd_prefix: str = None, full: bool = False,+ archived: str = "exclude", order: str = "created", source: str | None = None, sources: str | None = None,+ exclude_sources: str | None = None, cwd_prefix: str | None = None, full: bool = False,profile: Optional[str] = None):"""List sessions.@@ -283,8 +283,8 @@ def _is_compression_edge(child: dict, parent: dict) -> bool:@search_router.get("/api/sessions/search")async def search_sessions(- q: str = "", limit: int = 20, profile: Optional[str] = None, source: str = None,- sources: str = None, exclude_sources: str = None):+ q: str = "", limit: int = 20, profile: Optional[str] = None, source: str | None = None,+ sources: str | None = None, exclude_sources: str | None = None):"""Search sessions by ID (first) plus FTS5 message content.Results are deduped by compression lineage, not raw ``session_id``:diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex 864ba74f028..2bf0588bc6a 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -415,7 +415,7 @@ def _worktree_add(repo_root: str, wt_path: Path, branch_name: str, base_ref: strreturn base_ref, base_label-def _setup_worktree(repo_root: str = None, sync_base: bool = True,+def _setup_worktree(repo_root: str | None = None, sync_base: bool = True,name: Optional[str] = None) -> Optional[dict[str, str]]:"""Create an isolated git worktree -> ``{path, branch, repo_root, base}``, or None on failure.diff --git a/hermes_state.py b/hermes_state.pyindex 53b8f06fffd..79db7a4d164 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -577,7 +577,7 @@ class SessionDB(except Exception as exc:logger.warning("%s close failed for %s: %s", label, self.db_path, exc)- def __init__(self, db_path: Path = None, read_only: bool = False):+ def __init__(self, db_path: Path | None = None, read_only: bool = False):self.db_path = db_path or _default_db_path()_ensure_test_isolation(self.db_path) # before any connection/pragma/mkdirself.read_only = read_onlydiff --git a/hermes_state_compression.py b/hermes_state_compression.pyindex 874880377f8..f80b91980c1 100644--- a/hermes_state_compression.py+++ b/hermes_state_compression.py@@ -245,9 +245,9 @@ class SessionCompressionMixin:def publish_compression_child(self, *, parent_session_id: str, child_session_id: str, source: str,- messages: list[dict[str, Any]], model: str = None, model_config: dict[str, Any] = None,- system_prompt: str = None, cwd: str = None, profile_name: str = None,- compression_lock_holder: str = None, require_compression_lease: bool = True,+ messages: list[dict[str, Any]], model: str | None = None, model_config: dict[str, Any] | None = None,+ system_prompt: str | None = None, cwd: str | None = None, profile_name: str | None = None,+ compression_lock_holder: str | None = None, require_compression_lease: bool = True,require_lease_refresh: bool = False, lease_ttl_seconds: float = 300.0,watermark: Optional[int] = None, watermark_ceiling: Optional[int] = None) -> None:"""Atomically close a parent and publish its durable compression child: closure, child row, anddiff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 39e5f1f48f0..cdc69851d69 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -232,10 +232,10 @@ class SessionGatewayMixin:return signalleddef record_gateway_session_peer(- self, session_id: str, *, source: str, user_id: str = None, session_key: str = None,- chat_id: str = None, chat_type: str = None, thread_id: str = None, display_name: str = None,- origin_json: str = None, include_compression_ancestors: bool = False,- transport_profile: str = None) -> None:+ self, session_id: str, *, source: str, user_id: str | None = None, session_key: str | None = None,+ chat_id: str | None = None, chat_type: str | None = None, thread_id: str | None = None, display_name: str | None = None,+ origin_json: str | None = None, include_compression_ancestors: bool = False,+ transport_profile: str | None = None) -> None:"""Persist the gateway routing peer for an existing session row. ``display_name`` / ``origin_json``:``None`` leaves the stored value untouched (consumers read routing data from state.db, notsessions.json). ``include_compression_ancestors`` keeps a compression lineage on one routing peerdiff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 7c505d07171..8d512665a69 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -259,7 +259,7 @@ class SessionMaintenanceMixin:# segment stays, deleting it would cut the start off a chat that is still in use.return f"{where} AND s.id NOT IN ({_continued_ancestors_sql(where)})", [*params, *params]- def list_prune_candidates(self, older_than_days: Optional[float] = None, source: str = None, *,+ def list_prune_candidates(self, older_than_days: Optional[float] = None, source: str | None = None, *,whole_lineages: bool = False, **filters) -> list[dict[str, Any]]:"""Dry-run: sessions a matching prune/archive would touch, oldest first (``older_than_days``= inactivity threshold: freshest of ``last_activity_at`` / latest message / ``started_at``)."""@@ -271,7 +271,7 @@ class SessionMaintenanceMixin:FROM sessions s WHERE {where}ORDER BY last_active ASC, s.started_at ASC""", params)]- def count_prune_matches(self, older_than_days: Optional[float] = None, source: str = None, *,+ def count_prune_matches(self, older_than_days: Optional[float] = None, source: str | None = None, *,pinned_only: bool = False, **filters) -> int:"""Count-only :meth:`list_prune_candidates`; ``pinned_only`` counts rows carrying the pinitself, not the continuations it protects (CLI reports spared pinned sessions)."""@@ -282,7 +282,7 @@ class SessionMaintenanceMixin:where += " AND COALESCE(s.pinned, 0) = 1"return int(self._read_one(f"SELECT COUNT(*) FROM sessions s WHERE {where}", params)[0])- def count_open_prune_matches(self, older_than_days: Optional[float] = None, source: str = None,+ def count_open_prune_matches(self, older_than_days: Optional[float] = None, source: str | None = None,**filters) -> int:"""Count open sessions a matching prune skips (``ended_at`` guard inverted); visibility-only."""where, params = self._prune_where(older_than_days, source, filters)@@ -319,7 +319,7 @@ class SessionMaintenanceMixin:self._auto_archive_lineage(row[0])return len(rows)- def prune_sessions(self, older_than_days: Optional[float] = 90, source: str = None,+ def prune_sessions(self, older_than_days: Optional[float] = 90, source: str | None = None,sessions_dir: Optional[Path] = None, exclude_active_write_guards: bool = False,**filters) -> int:"""Delete ended sessions inactive for ``older_than_days`` (an explicit ``started_before`` /diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 13a2c5f80e2..19908aed180 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -387,10 +387,10 @@ class SessionMessagesMixin:f"UPDATE sessions SET message_count = message_count + {inc} WHERE id = ?", (*params, session_id))def append_message(- self, session_id: str, role: str, content: str = None, tool_name: str = None, tool_calls: Any = None,- tool_call_id: str = None, token_count: int = None, finish_reason: str = None, reasoning: str = None,- reasoning_content: str = None, reasoning_details: Any = None, codex_reasoning_items: Any = None,- codex_message_items: Any = None, platform_message_id: str = None, observed: bool = False,+ self, session_id: str, role: str, content: str | None = None, tool_name: str | None = None, tool_calls: Any = None,+ tool_call_id: str | None = None, token_count: int | None = None, finish_reason: str | None = None, reasoning: str | None = None,+ reasoning_content: str | None = None, reasoning_details: Any = None, codex_reasoning_items: Any = None,+ codex_message_items: Any = None, platform_message_id: str | None = None, observed: bool = False,effect_disposition: Optional[str] = None, _compressed_summary: bool = False, timestamp: Any = None,api_content: Optional[str] = None, display_kind: Optional[str] = None,display_metadata: Optional[dict[str, Any]] = None, compression_lock_holder: Optional[str] = None,@@ -1880,7 +1880,7 @@ class SessionMessagesMixin:"replacement_message_uid": replacement and message_uid_or_none(replacement)}if preserve_compaction_handoff else {})}- def message_count(self, session_id: str = None) -> int:+ def message_count(self, session_id: str | None = None) -> int:"""Count messages, optionally for a specific session."""sql = "SELECT COUNT(*) FROM messages" + (" WHERE session_id = ?" if session_id else "")return self._read_one(sql, (session_id,) if session_id else ())[0]diff --git a/hermes_state_portability.py b/hermes_state_portability.pyindex 76d596973ba..337ae2b0baa 100644--- a/hermes_state_portability.py+++ b/hermes_state_portability.py@@ -315,7 +315,7 @@ class SessionPortabilityMixin:"messages": messages, "timings": _export_timings(messages, session_id),}- def export_all(self, source: str = None, include_compacted: bool = False,+ def export_all(self, source: str | None = None, include_compacted: bool = False,include_inactive: bool = False) -> list[dict[str, Any]]:"""Export all sessions (with messages) as dicts, e.g. for JSONL backup (flags as in:meth:`export_session`; that display read dedupes per session, so it skips the batched read).diff --git a/hermes_state_search.py b/hermes_state_search.pyindex a419c98ed95..ae7660325b5 100644--- a/hermes_state_search.py+++ b/hermes_state_search.py@@ -1061,8 +1061,8 @@ class SessionSearchMixin:# ── search_messages ────────────────────────────────────────────────────def search_messages(- self, query: str, source_filter: list[str] = None, exclude_sources: list[str] = None,- role_filter: list[str] = None, limit: int = 20, offset: int = 0, sort: str = None,+ self, query: str, source_filter: list[str] | None = None, exclude_sources: list[str] | None = None,+ role_filter: list[str] | None = None, limit: int = 20, offset: int = 0, sort: str | None = None,include_inactive: bool = False, fields: Optional[Collection[str]] = None,after_ts: Optional[int] = None, before_ts: Optional[int] = None,) -> list[dict[str, Any]]:@@ -1084,8 +1084,8 @@ class SessionSearchMixin:query[: 200])def _search_messages_impl(- self, query: str, source_filter: list[str] = None, exclude_sources: list[str] = None,- role_filter: list[str] = None, limit: int = 20, offset: int = 0, sort: str = None,+ self, query: str, source_filter: list[str] | None = None, exclude_sources: list[str] | None = None,+ role_filter: list[str] | None = None, limit: int = 20, offset: int = 0, sort: str | None = None,include_inactive: bool = False, fields: Optional[Collection[str]] = None,after_ts: Optional[int] = None, before_ts: Optional[int] = None,) -> list[dict[str, Any]]:@@ -1236,8 +1236,8 @@ class SessionSearchMixin:limit_sql="LIMIT ?")def search_sessions_by_id(- self, query: str, limit: int = 20, include_archived: bool = True, source: str = None,- sources: list[str] = None, exclude_sources: list[str] = None) -> list[dict[str, Any]]:+ self, query: str, limit: int = 20, include_archived: bool = True, source: str | None = None,+ sources: list[str] | None = None, exclude_sources: list[str] | None = None) -> list[dict[str, Any]]:"""Search surfaced sessions by exact/prefix/substring session id. Also matches``_lineage_root_id`` so an old compression root id resolves to the live continuation."""needle = (query or "").strip().lower()diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 38cf19de5df..87afa702895 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -110,8 +110,8 @@ def _where_sql(clauses: list[str], lead: str = "") -> str:def _session_filter_where(- *, exclude_children: bool = False, source: str = None, sources: list[str] = None,- session_key: str = None, exclude_sources: list[str] = None, cwd_prefix: str = None,+ *, exclude_children: bool = False, source: str | None = None, sources: list[str] | None = None,+ session_key: str | None = None, exclude_sources: list[str] | None = None, cwd_prefix: str | None = None,min_message_count: int = 0, archived_only: bool = False, include_archived: bool = False,include_subagents: bool = False,) -> tuple[list[str], list[Any]]:@@ -357,11 +357,11 @@ class SessionSessionsMixin:conn.execute(_INHERIT_PARENT_ROUTING_SQL, (session_id,))def _insert_session_row(- self, session_id: str, source: str, model: str = None, model_config: dict[str, Any] = None,- system_prompt: str = None, user_id: str = None, session_key: Optional[str] = None,- chat_id: str = None, chat_type: str = None, thread_id: str = None,- parent_session_id: str = None, cwd: str = None, profile_name: Optional[str] = None,- git_repo_root: str = None, origin_json: str = None, display_name: str = None,+ self, session_id: str, source: str, model: str | None = None, model_config: dict[str, Any] | None = None,+ system_prompt: str | None = None, user_id: str | None = None, session_key: Optional[str] = None,+ chat_id: str | None = None, chat_type: str | None = None, thread_id: str | None = None,+ parent_session_id: str | None = None, cwd: str | None = None, profile_name: Optional[str] = None,+ git_repo_root: str | None = None, origin_json: str | None = None, display_name: str | None = None,transport_profile: Optional[str] = None,) -> None:"""Upsert a session row, never overwriting what an earlier writer set (the gateway creates a@@ -461,7 +461,7 @@ class SessionSessionsMixin:self._insert_session_row(session_id, source, **kwargs)return session_id- def ensure_session(self, session_id: str, source: str = "unknown", model: str = None, **kwargs) -> str:+ def ensure_session(self, session_id: str, source: str = "unknown", model: str | None = None, **kwargs) -> str:"""Ensure a session row exists (upsert). Accepts optional kwargs."""self._insert_session_row(session_id, source, model=model, **kwargs)return session_id@@ -1165,10 +1165,10 @@ class SessionSessionsMixin:self,*,limit: int = 20,- exclude_sources: list[str] = None,+ exclude_sources: list[str] | None = None,timeout_seconds: float = 3.0,- candidate_limit: int = None,- lineage_limit: int = None,+ candidate_limit: int | None = None,+ lineage_limit: int | None = None,) -> list[dict[str, Any]]:"""Latency-bounded recent-conversation browse (``session_search()``): preselect a small candidate setfrom the indexed durable activity timestamp (fallback ``started_at``), resolve only those across@@ -1346,12 +1346,12 @@ class SessionSessionsMixin:return sdef list_sessions_rich(- self, source: str = None, sources: list[str] = None, exclude_sources: list[str] = None,- cwd_prefix: str = None, limit: int = 20, offset: int = 0, include_children: bool = False,+ self, source: str | None = None, sources: list[str] | None = None, exclude_sources: list[str] | None = None,+ cwd_prefix: str | None = None, limit: int = 20, offset: int = 0, include_children: bool = False,min_message_count: int = 0, project_compression_tips: bool = True,order_by_last_active: bool = False, include_archived: bool = False, archived_only: bool = False,- id_query: str = None, search_query: str = None, compact_rows: bool = False,- include_pinned: bool = False, session_key: str = None, include_hidden: bool = False,+ id_query: str | None = None, search_query: str | None = None, compact_rows: bool = False,+ include_pinned: bool = False, session_key: str | None = None, include_hidden: bool = False,include_subagents: bool = False,) -> list[dict[str, Any]]:"""List sessions with preview and ``last_active`` in one query. ``order_by_last_active`` sorts@@ -1548,7 +1548,7 @@ class SessionSessionsMixin:def search_sessions(self, source: Union[str, Sequence[str], None] = None, limit: int = 20, offset: int = 0,- workspace_key: str = None,+ workspace_key: str | None = None,) -> list[dict[str, Any]]:"""Sessions MRU-first with a computed ``last_active``; ``workspace_key`` scopes to one workspaceso ``hermes -c``/``--resume`` picks its last session. ``source`` may be one label or several."""@@ -1572,9 +1572,9 @@ class SessionSessionsMixin:)]def session_count(- self, source: str = None, sources: list[str] = None, cwd_prefix: str = None,+ self, source: str | None = None, sources: list[str] | None = None, cwd_prefix: str | None = None,min_message_count: int = 0, include_archived: bool = False, archived_only: bool = False,- exclude_children: bool = False, exclude_sources: list[str] = None, include_subagents: bool = False,+ exclude_children: bool = False, exclude_sources: list[str] | None = None, include_subagents: bool = False,) -> int:"""Count sessions with list_sessions_rich's filters so a paired "load more" total matches."""where_clauses, params = _session_filter_where(@@ -1901,7 +1901,7 @@ class SessionSessionsMixin:return countdef archive_sessions(- self, older_than_days: Optional[float] = None, source: str = None, **filters,+ self, older_than_days: Optional[float] = None, source: str | None = None, **filters,) -> int:"""Bulk soft-hide with prune_sessions' filter surface, via set_session_archived so each lineageflips as a unit; idempotent. Returns matches. A lineage is matched through its TIP only: andiff --git a/hermes_state_usage.py b/hermes_state_usage.pyindex e525764e221..8915da6e127 100644--- a/hermes_state_usage.py+++ b/hermes_state_usage.py@@ -271,7 +271,7 @@ class SessionUsageMixin:self._stop_token_writer()def update_token_counts(- self, session_id: str, input_tokens: int=0, output_tokens: int=0, model: str=None, cache_read_tokens: int=0,+ self, session_id: str, input_tokens: int=0, output_tokens: int=0, model: str | None=None, cache_read_tokens: int=0,cache_write_tokens: int=0, reasoning_tokens: int=0, estimated_cost_usd: Optional[float]=None,actual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,diff --git a/mini_swe_runner.py b/mini_swe_runner.pyindex f6583c5dd1b..90e4aa9ceab 100644--- a/mini_swe_runner.py+++ b/mini_swe_runner.py@@ -130,7 +130,7 @@ def _gpt_content(msg: dict[str, Any], content: str) -> str:class MiniSWERunner:"""Tool-calling agent loop over a Hermes execution environment, emitting Hermes trajectories."""- def __init__(self, model: str = "anthropic/claude-sonnet-4.6", base_url: str = None, api_key: str = None,+ def __init__(self, model: str = "anthropic/claude-sonnet-4.6", base_url: str | None = None, api_key: str | None = None,env_type: str = "local", image: str = "python:3.11-slim", cwd: str | None = None,max_iterations: int = 15, command_timeout: int = 60, verbose: bool = False):self.model, self.max_iterations, self.command_timeout, self.verbose = model, max_iterations, command_timeout, verbose@@ -173,7 +173,7 @@ class MiniSWERunner:stop()self.env = None- def _execute_command(self, command: str, timeout: int = None) -> dict[str, Any]:+ def _execute_command(self, command: str, timeout: int | None = None) -> dict[str, Any]:"""Run ``command`` in the environment; returns ``{output, exit_code, error}``."""if self.env is None:self._create_env()@@ -346,12 +346,12 @@ def _load_prompts(prompts_file: str) -> list[str]:def main(- task: str = None,- prompts_file: str = None,+ task: str | None = None,+ prompts_file: str | None = None,output_file: str = "swe-runner-test1.jsonl",model: str = "claude-sonnet-4-20250514",- base_url: str = None,- api_key: str = None,+ base_url: str | None = None,+ api_key: str | None = None,env: str = "local",image: str = "python:3.11-slim",cwd: str | None = None,diff --git a/optional-skills/blockchain/solana/scripts/solana_client.py b/optional-skills/blockchain/solana/scripts/solana_client.pyindex 89966c32edb..17a43a12f50 100644--- a/optional-skills/blockchain/solana/scripts/solana_client.py+++ b/optional-skills/blockchain/solana/scripts/solana_client.py@@ -90,7 +90,7 @@ def _http_get_json(url: str, timeout: int = 10, retries: int = 2) -> Any:return None-def _rpc_call(method: str, params: list = None, retries: int = 2) -> Any:+def _rpc_call(method: str, params: list | None = None, retries: int = 2) -> Any:"""Send a JSON-RPC request with retry on 429 rate-limit."""payload = json.dumps({"jsonrpc": "2.0", "id": 1,diff --git a/optional-skills/finance/polymarket/scripts/polymarket.py b/optional-skills/finance/polymarket/scripts/polymarket.pyindex b76e7aa5f9b..9e9d587ba7f 100644--- a/optional-skills/finance/polymarket/scripts/polymarket.py+++ b/optional-skills/finance/polymarket/scripts/polymarket.py@@ -211,7 +211,7 @@ def cmd_history(condition_id: str, interval: str = "all", fidelity: int = 50):print(f" {ts} {price:>7} {bar}")-def cmd_trades(limit: int = 10, market: str = None):+def cmd_trades(limit: int = 10, market: str | None = None):"""Get recent trades."""url = f"{DATA}/trades?limit={limit}"if market:diff --git a/optional-skills/security/godmode/scripts/auto_jailbreak.py b/optional-skills/security/godmode/scripts/auto_jailbreak.pyindex 00a223209f3..0fe03b702df 100644--- a/optional-skills/security/godmode/scripts/auto_jailbreak.py+++ b/optional-skills/security/godmode/scripts/auto_jailbreak.py@@ -343,7 +343,7 @@ def _get_current_model() -> tuple:return None, None-def _get_api_key(base_url: str = None) -> str:+def _get_api_key(base_url: str | None = None) -> str:"""Get the appropriate API key."""if base_url and "openrouter" in base_url:return os.getenv("OPENROUTER_API_KEY", "")@@ -387,7 +387,7 @@ def _build_messages(system_prompt=None, prefill=None, query=None):return messages-def _write_config(system_prompt: str = None, prefill_file: str = None):+def _write_config(system_prompt: str | None = None, prefill_file: str | None = None):"""Write jailbreak settings to config.yaml (merges, doesn't overwrite)."""cfg = {}if CONFIG_PATH.exists():diff --git a/optional-skills/security/oss-forensics/scripts/evidence-store.py b/optional-skills/security/oss-forensics/scripts/evidence-store.pyindex 2ecfbe25cdd..1ac20efd7ff 100644--- a/optional-skills/security/oss-forensics/scripts/evidence-store.py+++ b/optional-skills/security/oss-forensics/scripts/evidence-store.py@@ -92,12 +92,12 @@ class EvidenceStore:source: str,content: str,evidence_type: str,- actor: str = None,- url: str = None,- timestamp: str = None,- ioc_type: str = None,+ actor: str | None = None,+ url: str | None = None,+ timestamp: str | None = None,+ ioc_type: str | None = None,verification: str = "unverified",- notes: str = None,+ notes: str | None = None,) -> str:evidence_id = self._next_id()entry = {@@ -124,7 +124,7 @@ class EvidenceStore:self._save()return evidence_id- def list_evidence(self, filter_type: str = None, filter_actor: str = None):+ def list_evidence(self, filter_type: str | None = None, filter_actor: str | None = None):results = self.data["evidence"]if filter_type:results = [e for e in results if e.get("type") == filter_type]diff --git a/plugins/memory/byterover/__init__.py b/plugins/memory/byterover/__init__.pyindex a5cfbb2663e..fd09cc25298 100644--- a/plugins/memory/byterover/__init__.py+++ b/plugins/memory/byterover/__init__.py@@ -101,7 +101,7 @@ def _brv_child_env(brv_path: str) -> dict[str, str]:return env-def _run_brv(args: list[str], timeout: int = _QUERY_TIMEOUT, cwd: str = None) -> dict:+def _run_brv(args: list[str], timeout: int = _QUERY_TIMEOUT, cwd: str | None = None) -> dict:"""Run a brv CLI command. Returns {success, output, error}."""global _cached_brv_pathbrv_path = _resolve_brv_path()diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex a9110d8a24a..5697cba40c2 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -710,7 +710,7 @@ class VoiceReceiver:CHANNELS = 2 # Discord sends stereoREKEY_FAILURE_STREAK = 25 # consecutive NaCl failures → re-resolve creds- def __init__(self, voice_client, allowed_user_ids: set = None):+ def __init__(self, voice_client, allowed_user_ids: set | None = None):self._vc = voice_clientself._allowed_user_ids = allowed_user_ids or set()self._running = False@@ -3831,7 +3831,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInmixers = getattr(self, "_voice_mixers", None)return bool(mixers) and mixers.get(guild_id) is not None- async def join_voice_channel(self, channel, *, text_channel_id: int = None, source: dict = None) -> bool:+ async def join_voice_channel(self, channel, *, text_channel_id: int | None = None, source: dict | None = None) -> bool:"""Join a voice channel; returns True on success. ``text_channel_id`` stores thetranscription-routing binding so programmatic joins work without ``/voice join``."""if not self._client or not DISCORD_AVAILABLE:diff --git a/ruff.strict.toml b/ruff.strict.tomlindex 6845bf4e257..d6b88e6a708 100644--- a/ruff.strict.toml+++ b/ruff.strict.toml@@ -417,8 +417,8 @@ select = [# "RUF009","RUF010",# "RUF012",- # "RUF013",- # "RUF015",+ "RUF013",+ "RUF015","RUF016","RUF017","RUF018",diff --git a/run_agent.py b/run_agent.pyindex 8d88a076728..37afd3d85c5 100644--- a/run_agent.py+++ b/run_agent.py@@ -235,44 +235,44 @@ class AIAgent(def __init__(self,- base_url: str = None, api_key: str = None, provider: str = None, api_mode: str = None,- acp_command: str = None, acp_args: list[str] | None = None, command: str = None, args: list[str] | None = None,+ base_url: str | None = None, api_key: str | None = None, provider: str | None = None, api_mode: str | None = None,+ acp_command: str | None = None, acp_args: list[str] | None = None, command: str | None = None, args: list[str] | None = None,model: str = "",max_iterations: int = sys.maxsize, # unlimited tool-calling iterations by default (shared with subagents)- tool_delay: float = None, # deprecated: accepted for compatibility, ignored- enabled_toolsets: list[str] = None, disabled_toolsets: list[str] = None,+ tool_delay: float | None = None, # deprecated: accepted for compatibility, ignored+ enabled_toolsets: list[str] | None = None, disabled_toolsets: list[str] | None = None,save_trajectories: bool = False, verbose_logging: bool = False, quiet_mode: bool = False,- tool_progress_mode: str = "all", ephemeral_system_prompt: str = None,+ tool_progress_mode: str = "all", ephemeral_system_prompt: str | None = None,log_prefix_chars: int = 100, log_prefix: str = "",- providers_allowed: list[str] = None, providers_ignored: list[str] = None, providers_order: list[str] = None,- provider_sort: str = None, provider_require_parameters: bool = False, provider_data_collection: str = None,+ providers_allowed: list[str] | None = None, providers_ignored: list[str] | None = None, providers_order: list[str] | None = None,+ provider_sort: str | None = None, provider_require_parameters: bool = False, provider_data_collection: str | None = None,openrouter_min_coding_score: Optional[float] = None,- session_id: str = None,- tool_progress_callback: callable = None, tool_start_callback: callable = None,- tool_complete_callback: callable = None, thinking_callback: callable = None,- reasoning_callback: callable = None, clarify_callback: callable = None,- read_terminal_callback: callable = None, read_preview_callback: callable = None,- drive_preview_callback: callable = None, read_window_below_callback: callable = None,- connection_callback: callable = None, tour_callback: callable = None,- setup_choose_callback: callable = None, step_callback: callable = None,- stream_delta_callback: callable = None, interim_assistant_callback: callable = None,- tool_gen_callback: callable = None, status_callback: callable = None,- notice_callback: callable = None, notice_clear_callback: callable = None,+ session_id: str | None = None,+ tool_progress_callback: callable | None = None, tool_start_callback: callable | None = None,+ tool_complete_callback: callable | None = None, thinking_callback: callable | None = None,+ reasoning_callback: callable | None = None, clarify_callback: callable | None = None,+ read_terminal_callback: callable | None = None, read_preview_callback: callable | None = None,+ drive_preview_callback: callable | None = None, read_window_below_callback: callable | None = None,+ connection_callback: callable | None = None, tour_callback: callable | None = None,+ setup_choose_callback: callable | None = None, step_callback: callable | None = None,+ stream_delta_callback: callable | None = None, interim_assistant_callback: callable | None = None,+ tool_gen_callback: callable | None = None, status_callback: callable | None = None,+ notice_callback: callable | None = None, notice_clear_callback: callable | None = None,event_callback: Optional[Callable[[str, dict], None]] = None,reaction_callback: Optional[Callable[[str], None]] = None,- max_tokens: int = None, reasoning_config: dict[str, Any] = None, service_tier: str = None,- request_overrides: dict[str, Any] = None, prefill_messages: list[dict[str, Any]] = None,- platform: str = None, user_id: str = None, user_id_alt: str = None, user_name: str = None,- chat_id: str = None, chat_name: str = None, chat_type: str = None, thread_id: str = None,- gateway_session_key: str = None,+ max_tokens: int | None = None, reasoning_config: dict[str, Any] | None = None, service_tier: str | None = None,+ request_overrides: dict[str, Any] | None = None, prefill_messages: list[dict[str, Any]] | None = None,+ platform: str | None = None, user_id: str | None = None, user_id_alt: str | None = None, user_name: str | None = None,+ chat_id: str | None = None, chat_name: str | None = None, chat_type: str | None = None, thread_id: str | None = None,+ gateway_session_key: str | None = None,skip_context_files: bool = False, load_soul_identity: bool = False,skip_memory: bool = False, skip_background_review: bool = False,- session_db=None, parent_session_id: str = None,+ session_db=None, parent_session_id: str | None = None,iteration_budget: "IterationBudget" = None, run_budget_seconds: Optional[float] = None,- fallback_model: dict[str, Any] = None, credential_pool=None,+ fallback_model: dict[str, Any] | None = None, credential_pool=None,checkpoints_enabled: bool = False, checkpoint_max_snapshots: int = 20,checkpoint_max_total_size_mb: int = 500, checkpoint_max_file_size_mb: int = 10,- pass_session_id: bool = False, requested_provider: str = None,+ pass_session_id: bool = False, requested_provider: str | None = None,capabilities: dict[str, bool] | None = None, cwd: str | None = None,side_agent: bool = False, memory_manager=None,tool_result_metadata_callback: Optional[Callable[..., dict]] = None,@@ -517,16 +517,16 @@ class AIAgent(return base_url_hostname(base_url)return getattr(self, "_base_url_hostname", "") or base_url_hostname(getattr(self, "_base_url_lower", ""))- def _is_direct_openai_url(self, base_url: str = None) -> bool:+ def _is_direct_openai_url(self, base_url: str | None = None) -> bool:"""Return True when a base URL targets OpenAI's native API."""return self._hostname_for(base_url) == "api.openai.com"- def _is_azure_openai_url(self, base_url: str = None) -> bool:+ def _is_azure_openai_url(self, base_url: str | None = None) -> bool:"""True when a base URL targets Azure OpenAI (standard client, but NO Responses API support)."""url = str(base_url).lower() if base_url is not None else (getattr(self, "_base_url_lower", "") or "")return base_url_host_matches(url, "openai.azure.com")- def _is_github_copilot_url(self, base_url: str = None) -> bool:+ def _is_github_copilot_url(self, base_url: str | None = None) -> bool:"""Return True when a base URL targets GitHub Copilot's OpenAI-compatible API."""hostname = self._hostname_for(base_url)return bool(hostname) and (hostname == "api.githubcopilot.com" or hostname.endswith(".githubcopilot.com"))@@ -863,7 +863,7 @@ class AIAgent(},)- def shutdown_memory_provider(self, messages: list = None) -> None:+ def shutdown_memory_provider(self, messages: list | None = None) -> None:"""Shut down the memory provider and context engine at session end (idempotent: gateway cleanup and``close()`` may both call it)."""if getattr(self, "_memory_provider_shutdown", False):@@ -877,7 +877,7 @@ class AIAgent(_quietly(lambda: self._memory_manager.shutdown_all())_notify_context_engine_session_end(self, messages)- def commit_memory_session(self, messages: list = None) -> None:+ def commit_memory_session(self, messages: list | None = None) -> None:"""Flush end-of-session extraction on session_id rotation (/new, compression) without tearing providersdown."""if self._memory_manager:@@ -1468,8 +1468,8 @@ def _save_sample_trajectory(agent: "AIAgent", result: dict, user_query: str, moddef main(- query: str = None, model: str = "", api_key: str = None, base_url: str = "", max_turns: int = 10,- enabled_toolsets: str = None, disabled_toolsets: str = None, list_tools: bool = False,+ query: str | None = None, model: str = "", api_key: str | None = None, base_url: str = "", max_turns: int = 10,+ enabled_toolsets: str | None = None, disabled_toolsets: str | None = None, list_tools: bool = False,save_trajectories: bool = False, save_sample: bool = False, verbose: bool = False, log_prefix_chars: int = 20,):"""diff --git a/scripts/sample_and_compress.py b/scripts/sample_and_compress.pyindex 49cfe3b7c1b..ab5b0fe851d 100644--- a/scripts/sample_and_compress.py+++ b/scripts/sample_and_compress.py@@ -314,7 +314,7 @@ def merge_output_to_single_jsonl(input_dir: Path, output_file: Path):def main(total_samples: int = 2500,output_name: str = "compressed_agentic",- datasets: str = None,+ datasets: str | None = None,config: str = "configs/trajectory_compression.yaml",seed: int = 42,batch_size: int = 100,diff --git a/skills/media/youtube-content/scripts/fetch_transcript.py b/skills/media/youtube-content/scripts/fetch_transcript.pyindex efcd3c99384..96c239e92b8 100644--- a/skills/media/youtube-content/scripts/fetch_transcript.py+++ b/skills/media/youtube-content/scripts/fetch_transcript.py@@ -47,7 +47,7 @@ def format_timestamp(seconds: float) -> str:return f"{m}:{s:02d}"-def fetch_transcript(video_id: str, languages: list = None):+def fetch_transcript(video_id: str, languages: list | None = None):"""Fetch transcript segments from YouTube.Returns a list of dicts with 'text', 'start', and 'duration' keys.diff --git a/skills/productivity/xlsx/tests/test_xlsx_skill.py b/skills/productivity/xlsx/tests/test_xlsx_skill.pyindex dd56f2fa172..ad9242dc233 100644--- a/skills/productivity/xlsx/tests/test_xlsx_skill.py+++ b/skills/productivity/xlsx/tests/test_xlsx_skill.py@@ -157,7 +157,7 @@ def test_read_sheets_json_formulas(workbook, tmp_path):assert notes["rows"][0] == ["Zürich", "Фамилия", "12,5%"]formulas = json.loads(run("xlsx_read.py", workbook, "--formulas").stdout)- entry = [f for f in formulas["formulas"] if f["cell"] == "B6"][0]+ entry = next(f for f in formulas["formulas"] if f["cell"] == "B6")assert entry["formula"] == "=SUM(B2:B4)"# openpyxl never computes: cached value absent on a fresh fileassert entry["cached"] is None@@ -350,7 +350,7 @@ def test_restructure_insert_rows_shifts_everything(restructure_book):# validation + conditional format ranges shifteddv = data.data_validations.dataValidation[0]assert str(dv.sqref) == "C2:C6"- cf = list(data.conditional_formatting)[0]+ cf = next(iter(data.conditional_formatting))assert str(cf.sqref) == "B2:B6"# native table expandedassert data.tables["SalesTbl"].ref == "A1:C6"diff --git a/tests/agent/test_anthropic_adapter.py b/tests/agent/test_anthropic_adapter.pyindex 3cd19b2a88f..ee94c93a147 100644--- a/tests/agent/test_anthropic_adapter.py+++ b/tests/agent/test_anthropic_adapter.py@@ -758,7 +758,7 @@ class TestConvertMessages:], native_anthropic=True)_, result = convert_messages_to_anthropic(messages)- assistant_msg = [m for m in result if m["role"] == "assistant"][0]+ assistant_msg = next(m for m in result if m["role"] == "assistant")tool_use = assistant_msg["content"][-1]assert tool_use["type"] == "tool_use"@@ -847,7 +847,7 @@ class TestConvertMessages:], native_anthropic=True)_, result = convert_messages_to_anthropic(messages)- assistant_msg = [m for m in result if m["role"] == "assistant"][0]+ assistant_msg = next(m for m in result if m["role"] == "assistant")thinking, tool_use = assistant_msg["content"]assert thinking["type"] == "thinking"diff --git a/tests/agent/test_anthropic_kimi_signed_thinking_replay.py b/tests/agent/test_anthropic_kimi_signed_thinking_replay.pyindex bd3058c4095..42f9ae47f6d 100644--- a/tests/agent/test_anthropic_kimi_signed_thinking_replay.py+++ b/tests/agent/test_anthropic_kimi_signed_thinking_replay.py@@ -35,7 +35,7 @@ def _thinking_on_replay(base_url, signature=SIG, model="k3"):{"role": "user", "content": "q2"},]_sys, out = convert_messages_to_anthropic(messages, base_url=base_url, model=model)- assistant = [m for m in out if m.get("role") == "assistant"][0]+ assistant = next(m for m in out if m.get("role") == "assistant")return [b for b in assistant["content"] if isinstance(b, dict) and b.get("type") == "thinking"]@@ -96,7 +96,7 @@ def test_orphan_tool_turn_demotes_and_leaks_no_internal_marker():{"role": "user", "content": "continue"},]_sys, out = convert_messages_to_anthropic(messages, base_url=KIMI, model="k3")- assistant = [m for m in out if m.get("role") == "assistant"][0]+ assistant = next(m for m in out if m.get("role") == "assistant")assert "_thinking_signature_invalidated" not in assistant, (f"internal marker leaked into Kimi payload: {assistant.keys()}")diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.pyindex 8e73c65fdf3..67d7aac959f 100644--- a/tests/agent/test_bedrock_adapter.py+++ b/tests/agent/test_bedrock_adapter.py@@ -293,7 +293,7 @@ class TestConvertMessagesToConverse:"toolResult" in b for b in m["content"])]assert len(tool_result_msg) == 1- tr = [b for b in tool_result_msg[0]["content"] if "toolResult" in b][0]+ tr = next(b for b in tool_result_msg[0]["content"] if "toolResult" in b)assert tr["toolResult"]["toolUseId"] == "call_1"assert tr["toolResult"]["content"][0]["text"] == "file contents here"diff --git a/tests/agent/test_codex_multimodal_tool_result.py b/tests/agent/test_codex_multimodal_tool_result.pyindex ac7ffd07d40..29db2e675aa 100644--- a/tests/agent/test_codex_multimodal_tool_result.py+++ b/tests/agent/test_codex_multimodal_tool_result.py@@ -111,7 +111,7 @@ class TestPreflightAcceptsArrayOutput:},]normalized = _preflight_codex_input_items(raw)- out = [it for it in normalized if it.get("type") == "function_call_output"][0]+ out = next(it for it in normalized if it.get("type") == "function_call_output")assert isinstance(out["output"], list)assert len(out["output"]) == 2assert out["output"][1]["type"] == "input_image"@@ -134,7 +134,7 @@ class TestPreflightAcceptsArrayOutput:},]normalized = _preflight_codex_input_items(raw)- out = [it for it in normalized if it.get("type") == "function_call_output"][0]+ out = next(it for it in normalized if it.get("type") == "function_call_output")# The "garbage" part is dropped; valid parts remaintypes = [p.get("type") for p in out["output"]]assert types == ["input_text", "input_image"]diff --git a/tests/agent/test_context_engine.py b/tests/agent/test_context_engine.pyindex e87d45668ed..9e97a244a0a 100644--- a/tests/agent/test_context_engine.py+++ b/tests/agent/test_context_engine.py@@ -36,11 +36,11 @@ class StubEngine(ContextEngine):self.last_completion_tokens = usage.get("completion_tokens", 0)self.last_total_tokens = usage.get("total_tokens", 0)- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:tokens = prompt_tokens if prompt_tokens is not None else self.last_prompt_tokensreturn tokens >= self.threshold_tokens- def compress(self, messages: list[dict[str, Any]], current_tokens: int = None) -> list[dict[str, Any]]:+ def compress(self, messages: list[dict[str, Any]], current_tokens: int | None = None) -> list[dict[str, Any]]:self._compress_called = Trueself.compression_count += 1# Trivial: just return as-isdiff --git a/tests/agent/test_context_engine_on_turn_complete_usage.py b/tests/agent/test_context_engine_on_turn_complete_usage.pyindex b8fb4e51728..fb09e4b5514 100644--- a/tests/agent/test_context_engine_on_turn_complete_usage.py+++ b/tests/agent/test_context_engine_on_turn_complete_usage.py@@ -42,14 +42,14 @@ class _CapturingEngine(ContextEngine):def update_from_response(self, usage: dict[str, Any]) -> None:pass- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:return Falsedef compress(self,messages: list[dict[str, Any]],- current_tokens: int = None,- focus_topic: str = None,+ current_tokens: int | None = None,+ focus_topic: str | None = None,) -> list[dict[str, Any]]:return messagesdiff --git a/tests/agent/test_context_engine_select_context.py b/tests/agent/test_context_engine_select_context.pyindex c9b5076720d..5db2e118cb4 100644--- a/tests/agent/test_context_engine_select_context.py+++ b/tests/agent/test_context_engine_select_context.py@@ -35,14 +35,14 @@ class _MinimalEngine(ContextEngine):def update_from_response(self, usage: dict[str, Any]) -> None:pass- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:return Falsedef compress(self,messages: list[dict[str, Any]],- current_tokens: int = None,- focus_topic: str = None,+ current_tokens: int | None = None,+ focus_topic: str | None = None,) -> list[dict[str, Any]]:return messagesdiff --git a/tests/agent/test_message_sequence_repair.py b/tests/agent/test_message_sequence_repair.pyindex 42c82b5b8f8..1c72aaa5bc1 100644--- a/tests/agent/test_message_sequence_repair.py+++ b/tests/agent/test_message_sequence_repair.py@@ -596,7 +596,7 @@ def test_sanitize_deduplicates_duplicate_assistant_tool_call_ids():{"role": "tool", "tool_call_id": "call_Y", "content": "r"},]out = sanitize_api_messages(list(messages))- assistant = [m for m in out if m.get("role") == "assistant"][0]+ assistant = next(m for m in out if m.get("role") == "assistant")ids = [tc["id"] for tc in assistant["tool_calls"]]assert ids == ["call_Y"] # duplicate collapsed@@ -617,7 +617,7 @@ def test_sanitize_preserves_distinct_tool_call_ids():{"role": "tool", "tool_call_id": "call_B", "content": "rb"},]out = sanitize_api_messages(list(messages))- assistant = [m for m in out if m.get("role") == "assistant"][0]+ assistant = next(m for m in out if m.get("role") == "assistant")assert [tc["id"] for tc in assistant["tool_calls"]] == ["call_A", "call_B"]assert sorted(m["tool_call_id"] for m in out if m.get("role") == "tool") == ["call_A", "call_B"]@@ -785,7 +785,7 @@ def test_sanitize_drops_empty_tool_calls_array():{"role": "assistant", "content": "answer", "tool_calls": []},]out = sanitize_api_messages(list(messages))- assistant = [m for m in out if m.get("role") == "assistant"][0]+ assistant = next(m for m in out if m.get("role") == "assistant")assert "tool_calls" not in assistantassert assistant["content"] == "answer"@@ -1422,7 +1422,7 @@ def test_sanitize_realigns_bridged_tool_result_name_with_call_name():"tool_call_id": "call_1", "content": '{"number": 123}'},]out = sanitize_api_messages(list(messages))- result = [m for m in out if m.get("role") == "tool"][0]+ result = next(m for m in out if m.get("role") == "tool")assert result["name"] == "tool_call"# The internal name stays available for the session DB / UI, and the# caller's own message objects are untouched (per-call copy only).diff --git a/tests/agent/test_plugin_context_references.py b/tests/agent/test_plugin_context_references.pyindex 928f873409d..0c3761d3816 100644--- a/tests/agent/test_plugin_context_references.py+++ b/tests/agent/test_plugin_context_references.py@@ -98,7 +98,7 @@ def test_parse_plugin_reference():kinds = [r.kind for r in refs]assert "test" in kindsassert "file" in kinds- test_ref = [r for r in refs if r.kind == "test"][0]+ test_ref = next(r for r in refs if r.kind == "test")assert test_ref.target == "ENG-123"def test_parse_plugin_reference_ignored_when_not_registered():diff --git a/tests/agent/test_proactive_tool_result_pruning.py b/tests/agent/test_proactive_tool_result_pruning.pyindex 6795ff0329d..873b045deb7 100644--- a/tests/agent/test_proactive_tool_result_pruning.py+++ b/tests/agent/test_proactive_tool_result_pruning.py@@ -69,7 +69,7 @@ def _build(n_pairs, big_indices, big_chars=9000, small="ok"):def _tool_by_id(msgs, cid):- return [m for m in msgs if m.get("role") == "tool" and m.get("tool_call_id") == cid][0]+ return next(m for m in msgs if m.get("role") == "tool" and m.get("tool_call_id") == cid)def test_prunes_below_compression_threshold():diff --git a/tests/agent/test_reasoning_only_stop_persistence.py b/tests/agent/test_reasoning_only_stop_persistence.pyindex 61dc3c725bc..752244f3590 100644--- a/tests/agent/test_reasoning_only_stop_persistence.py+++ b/tests/agent/test_reasoning_only_stop_persistence.py@@ -94,14 +94,14 @@ def test_stall_guard_interim_row_carries_promoted_text_as_sidecar(loop_agent):])assert result["final_response"] == "Here is the file."- interim = [m for m in result["messages"] if m.get("role") == "assistant"][0]+ interim = next(m for m in result["messages"] if m.get("role") == "assistant")assert not interim.get("content")assert interim["reasoning"] == stalledassert interim["api_content"] == stalled# The continuation request carried the promoted text as the interim assistant turn.second_call = loop_agent.client.chat.completions.create.call_args_list[1].kwargs["messages"]- interim_wire = [m for m in second_call if m.get("role") == "assistant"][0]+ interim_wire = next(m for m in second_call if m.get("role") == "assistant")assert interim_wire["content"] == stalledassert "api_content" not in interim_wire@@ -133,7 +133,7 @@ def test_planning_tail_reasoning_only_stop_with_tools_runs_continuation_not_compassert result["api_calls"] == 2assert result["final_response"] == "Ran the checks; all green."- interim = [m for m in result["messages"] if m.get("role") == "assistant"][0]+ interim = next(m for m in result["messages"] if m.get("role") == "assistant")assert not interim.get("content")assert interim["api_content"] == tail # interim row keeps the sidecar shapediff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 104fdb89c47..f13fd388f41 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -2780,7 +2780,7 @@ class TestHandleMaxIterations:# on user/assistant messages.if m.get("role") == "tool":assert "name" not in m, m- assert [m for m in sent_msgs if m.get("role") == "user"][0]["name"] == "sylvain"+ assert next(m for m in sent_msgs if m.get("role") == "user")["name"] == "sylvain"# Internal history is untouched — the path copies each message.assert messages[2]["tool_name"] == "execute_code"assert messages[2]["name"] == "execute_code"diff --git a/tests/cron/test_cron_incidents.py b/tests/cron/test_cron_incidents.pyindex 8352f7dd8eb..2dfa694d90a 100644--- a/tests/cron/test_cron_incidents.py+++ b/tests/cron/test_cron_incidents.py@@ -259,7 +259,7 @@ def test_repeat_failure_alerts_once_then_reminds_after_cooldown(monkeypatch, tmpassert len(deliveries) == 1, "an alerted signature must not re-ping on every run"rows = inc.list_incidents()assert len(rows) == 1 and rows[0]["state"] == "alerted" and rows[0]["alerted_at"]- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ stored = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])assert stored["last_status"] == "error", "the withheld run is still recorded"# Cooldown elapsed: exactly one reminder, then silent again.diff --git a/tests/cron/test_oneshot_dispatch_failure_run_claim.py b/tests/cron/test_oneshot_dispatch_failure_run_claim.pyindex a33532e98a5..bbacc71e3f0 100644--- a/tests/cron/test_oneshot_dispatch_failure_run_claim.py+++ b/tests/cron/test_oneshot_dispatch_failure_run_claim.py@@ -50,7 +50,7 @@ class TestClearRunClaim:def test_clears_claim_on_oneshot(self, cron_store):job = _make_oneshot(claimed=True)assert clear_run_claim(job["id"]) is True- reloaded = [j for j in jobs_mod.load_jobs() if j["id"] == job["id"]][0]+ reloaded = next(j for j in jobs_mod.load_jobs() if j["id"] == job["id"])assert reloaded.get("run_claim") is Nonedef test_noop_when_already_clear(self, cron_store):@@ -65,7 +65,7 @@ class TestClearRunClaim:j["run_claim"] = {"at": "2026-08-17T10:00:00+00:00", "by": "test:1"}jobs_mod.save_jobs(jobs)assert clear_run_claim(job["id"]) is False- reloaded = [j for j in jobs_mod.load_jobs() if j["id"] == job["id"]][0]+ reloaded = next(j for j in jobs_mod.load_jobs() if j["id"] == job["id"])assert reloaded.get("run_claim") is not None # untoucheddef test_unknown_job_id_returns_false(self, cron_store):@@ -85,7 +85,7 @@ class TestDispatchFailurePathsClearClaim:job = _make_oneshot(claimed=True)with patch.object(sched, "_interpreter_shutting_down", return_value=True):self._tick_one(job)- reloaded = [j for j in jobs_mod.load_jobs() if j["id"] == job["id"]][0]+ reloaded = next(j for j in jobs_mod.load_jobs() if j["id"] == job["id"])assert reloaded.get("run_claim") is None, ("shutdown-path dispatch failure must clear run_claim (#86522)")@@ -95,7 +95,7 @@ class TestDispatchFailurePathsClearClaim:job = _make_oneshot(claimed=True)with patch.object(sched, "create_execution", side_effect=RuntimeError("db gone")):self._tick_one(job)- reloaded = [j for j in jobs_mod.load_jobs() if j["id"] == job["id"]][0]+ reloaded = next(j for j in jobs_mod.load_jobs() if j["id"] == job["id"])assert reloaded.get("run_claim") is Noneassert job["id"] not in sched.get_running_job_ids()@@ -110,7 +110,7 @@ class TestDispatchFailurePathsClearClaim:pool = _ExplodingPool()with patch.object(sched, "_get_parallel_pool", return_value=pool):self._tick_one(job)- reloaded = [j for j in jobs_mod.load_jobs() if j["id"] == job["id"]][0]+ reloaded = next(j for j in jobs_mod.load_jobs() if j["id"] == job["id"])assert reloaded.get("run_claim") is Noneassert job["id"] not in sched.get_running_job_ids()diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.pyindex 963d3bebb61..9b27e9aff1d 100644--- a/tests/cron/test_preflight_config.py+++ b/tests/cron/test_preflight_config.py@@ -136,7 +136,7 @@ class TestMissingProviderKeyBlocks:cron_jobs.save_jobs([job])fake_db = MagicMock()for _tick in range(2):- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ fresh = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])with patch("cron.scheduler._hermes_home", tmp_path), \patch("cron.scheduler_delivery._resolve_origin", return_value=None), \patch("hermes_cli.env_loader.load_hermes_dotenv"), \@@ -151,7 +151,7 @@ class TestMissingProviderKeyBlocks:assert ok is Trueassert mock_agent_cls.called is False- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ stored = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])assert stored["last_status"] == "blocked_config"assert len(deliveries) == 1, (@@ -240,14 +240,14 @@ class TestHealthyJobUnaffected:cron_jobs.save_jobs([job])# Tick 1: blocked._run_job_patched(job, tmp_path, resolve=_AuthErrorFactory())- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ stored = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])assert stored.get("preflight_alerted")# Tick 2: key restored → healthy run clears the marker.- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ fresh = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])success, *_rest, agent_constructed = _run_job_patched(fresh, tmp_path)assert success is Trueassert agent_constructed is True- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ stored = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])assert not stored.get("preflight_alerted")@@ -268,7 +268,7 @@ class TestOptOut:cron_jobs.save_jobs([job])fake_db = MagicMock()for _tick in range(2):- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ fresh = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])with patch("cron.scheduler._hermes_home", tmp_path), \patch("cron.scheduler_delivery._resolve_origin", return_value=None), \patch("hermes_cli.env_loader.load_hermes_dotenv"), \@@ -282,7 +282,7 @@ class TestOptOut:sched.run_one_job(fresh)assert mock_agent_cls.called is False- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ stored = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])assert stored["last_status"] == "error"assert len(deliveries) == 2 # old behavior: alert every tickdiff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex fb5091b76db..f0b92f72adc 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -1766,8 +1766,8 @@ class TestParallelTick:assert result == 2# With max_workers=1, second job starts after first ends- end_s1 = [t for action, jid, t in call_times if action == "end" and jid == "s1"][0]- start_s2 = [t for action, jid, t in call_times if action == "start" and jid == "s2"][0]+ end_s1 = next(t for action, jid, t in call_times if action == "end" and jid == "s1")+ start_s2 = next(t for action, jid, t in call_times if action == "start" and jid == "s2")assert start_s2 >= end_s1, "Jobs ran concurrently despite max_parallel=1"class TestDeliverResultTimeoutCancelsFuture:diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.pyindex 2507b326b0e..e9977274d40 100644--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@ -389,7 +389,7 @@ def make_fake_thread(thread_id: int = THREAD_ID, name: str = "test-thread", paredef make_discord_message(*, content: str = "hello", author=None, channel=None, mentions=None,- attachments=None, message_id: int = None,+ attachments=None, message_id: int | None = None,):if message_id is None:message_id = _next_message_id()diff --git a/tests/e2e/core/kanban/test_kanban_worker_sigkill.py b/tests/e2e/core/kanban/test_kanban_worker_sigkill.pyindex ab5e37c7f31..c5e20b7800f 100644--- a/tests/e2e/core/kanban/test_kanban_worker_sigkill.py+++ b/tests/e2e/core/kanban/test_kanban_worker_sigkill.py@@ -158,7 +158,7 @@ def test_sigkilled_worker_is_reclaimed_and_the_retry_completes_once(scenario: Scassert runs[1]["worker_pid"] == sc.w2 and runs[1]["ended_at"], b.diag(sc.tid)task = b.task(sc.tid)assert task["status"] == "done" and task["worker_pid"] is None and task["claim_lock"] is None- assert [r for r in runs if r["outcome"] == "completed"][0]["summary"] == "ATTEMPT_THREE_DONE"+ assert next(r for r in runs if r["outcome"] == "completed")["summary"] == "ATTEMPT_THREE_DONE"# Billing: every attempt paid only for its own turns, nothing ran after the card closed. Attempt 2# is exactly heartbeat + the hung call; attempt 3 opens with kanban_complete, then <= 1 closing turn.billed = sc.director.billeddiff --git a/tests/e2e/core/sqlite/test_compaction_contention.py b/tests/e2e/core/sqlite/test_compaction_contention.pyindex 4b98ce98625..0802b149dbf 100644--- a/tests/e2e/core/sqlite/test_compaction_contention.py+++ b/tests/e2e/core/sqlite/test_compaction_contention.py@@ -239,7 +239,7 @@ def test_compaction_episode(rig, fault):try:_agent(rig, gw, sid=gw_sid, tag="g", turns=5)_agent(rig, tui, sid=tui_sid, tag="t", turns=5, compress_at=3, keep=2, env=rig.tui_env)- micro = [e for e in ch.events(gw) if e.get("event") == "ready"][0]["micro"]+ micro = next(e for e in ch.events(gw) if e.get("event") == "ready")["micro"]assert micro, f"{ctx} gateway agent did not load micro_compact from its config"ch.spawn("writer", plain, tag="p", sessions=[f"{fault}-plain"], source="telegram", pace=0.01)ch.spawn("reader", reader, pace=0.05)diff --git a/tests/gateway/test_compress_plugin_engine.py b/tests/gateway/test_compress_plugin_engine.pyindex 3598d169fca..3c4a9df5a64 100644--- a/tests/gateway/test_compress_plugin_engine.py+++ b/tests/gateway/test_compress_plugin_engine.py@@ -41,14 +41,14 @@ class _FakePluginEngine(ContextEngine):def update_from_response(self, usage: dict[str, Any]) -> None:return None- def should_compress(self, prompt_tokens: int = None) -> bool:+ def should_compress(self, prompt_tokens: int | None = None) -> bool:return Falsedef compress(self,messages: list[dict[str, Any]],- current_tokens: int = None,- focus_topic: str = None,+ current_tokens: int | None = None,+ focus_topic: str | None = None,) -> list[dict[str, Any]]:# Pretend we dropped a middle turn.self.compression_count += 1diff --git a/tests/gateway/test_feishu_approval_buttons.py b/tests/gateway/test_feishu_approval_buttons.pyindex 2a724cef3f5..75b40f7e129 100644--- a/tests/gateway/test_feishu_approval_buttons.py+++ b/tests/gateway/test_feishu_approval_buttons.py@@ -148,7 +148,7 @@ class TestFeishuExecApproval:)assert len(adapter._approval_state) == 1- approval_id = list(adapter._approval_state.keys())[0]+ approval_id = next(iter(adapter._approval_state.keys()))state = adapter._approval_state[approval_id]assert state["session_key"] == "my-session-key"assert state["message_id"] == "msg_002"diff --git a/tests/gateway/test_goal_verdict_send.py b/tests/gateway/test_goal_verdict_send.pyindex 7130f252b5d..ca61719671c 100644--- a/tests/gateway/test_goal_verdict_send.py+++ b/tests/gateway/test_goal_verdict_send.py@@ -70,7 +70,7 @@ class _RecordingAdapter:return _R()-def _make_runner_with_adapter(session_id: str = None):+def _make_runner_with_adapter(session_id: str | None = None):from gateway.run import GatewayRunnerimport uuiddiff --git a/tests/gateway/test_slack_block_kit.py b/tests/gateway/test_slack_block_kit.pyindex 7c0b93fed85..ddc00e5da0a 100644--- a/tests/gateway/test_slack_block_kit.py+++ b/tests/gateway/test_slack_block_kit.py@@ -29,7 +29,7 @@ class TestNestedLists:def test_nested_bullets_produce_increasing_indent(self):md = "- a\n - b\n - c"blocks = render_blocks(md)- rich = [b for b in blocks if b["type"] == "rich_text"][0]+ rich = next(b for b in blocks if b["type"] == "rich_text")indents = [e["indent"] for e in rich["elements"] if e["type"] == "rich_text_list"]# true nesting: indent levels must strictly increase across the runassert indents == sorted(indents)@@ -49,7 +49,7 @@ class TestInlineFormatting:"- <https://example.com/x|GitLab #1> — allow `in_progress`")assert blocks is not None- rich = [b for b in blocks if b["type"] == "rich_text"][0]+ rich = next(b for b in blocks if b["type"] == "rich_text")els = rich["elements"][0]["elements"][0]["elements"]links = [e for e in els if e.get("type") == "link"]assert len(links) == 1@@ -77,7 +77,7 @@ class TestInlineFormatting:"""md = "1. alpha\n\n1. beta\n\n1. gamma"blocks = render_blocks(md)- rich = [b for b in blocks if b["type"] == "rich_text"][0]+ rich = next(b for b in blocks if b["type"] == "rich_text")lists = [e for e in rich["elements"] if e["type"] == "rich_text_list"]# Must be ONE list with 3 items, not 3 separate single-item listsassert len(lists) == 1diff --git a/tests/gateway/test_slack_channel_session_scope.py b/tests/gateway/test_slack_channel_session_scope.pyindex b44ad006780..200212aac59 100644--- a/tests/gateway/test_slack_channel_session_scope.py+++ b/tests/gateway/test_slack_channel_session_scope.py@@ -49,7 +49,7 @@ def _redirect_cache(tmp_path, monkeypatch):)-def _channel_event(text: str, ts: str, thread_ts: str = None) -> dict:+def _channel_event(text: str, ts: str, thread_ts: str | None = None) -> dict:"""Build a minimal ``message`` event for the Slack Events APIresembling what ``handle_message_event`` would pass through."""event = {diff --git a/tests/gateway/test_slack_send_retry.py b/tests/gateway/test_slack_send_retry.pyindex c3f3d676b5d..258dea9166c 100644--- a/tests/gateway/test_slack_send_retry.py+++ b/tests/gateway/test_slack_send_retry.py@@ -64,7 +64,7 @@ def _make_adapter():return a-def _slack_api_error(status_code: int, retry_after: str = None):+def _slack_api_error(status_code: int, retry_after: str | None = None):"""Simulate a SlackApiError with response status and optional Retry-After."""headers = {}if retry_after is not None:diff --git a/tests/gateway/test_wecom.py b/tests/gateway/test_wecom.pyindex f8e23f20d72..206a82e9d16 100644--- a/tests/gateway/test_wecom.py+++ b/tests/gateway/test_wecom.py@@ -976,7 +976,7 @@ class TestSendStreamFrame:assert adapter._send_json.await_count == 1# accumulated_text still updated in StreamTurn despite skip.- turn = list(adapter._stream_turns.values())[0]+ turn = next(iter(adapter._stream_turns.values()))assert turn.accumulated_text == "alpha beta"diff --git a/tests/gateway/test_yuanbao_pipeline.py b/tests/gateway/test_yuanbao_pipeline.pyindex c869a3b2ef6..34c8dc6de5b 100644--- a/tests/gateway/test_yuanbao_pipeline.py+++ b/tests/gateway/test_yuanbao_pipeline.py@@ -1120,7 +1120,7 @@ class TestResolveYbresRefsConcurrency:class TestMediaResolveMiddlewareRouting:"""Branch-routing tests for MediaResolveMiddleware.handle()."""- def _make_resolved_ctx(self, *, chat_type: str, reply_to: str = None,+ def _make_resolved_ctx(self, *, chat_type: str, reply_to: str | None = None,quote_media_refs=None, raw_text: str = "hello"):adapter = make_adapter()ctx = make_ctx(diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 45b44b9ebe6..c9ad00a4773 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -524,9 +524,9 @@ class TestSaveEnvValueSecure:second = (tmp_path / ".env").read_text(encoding="utf-8")assert first == second# One outer wrap layer only (escaped inner quotes, not nested wraps).- line = [+ line = next(ln for ln in first.splitlines() if ln.startswith("TERMINAL_SSH_KEY=")- ][0]+ )assert line.startswith('TERMINAL_SSH_KEY="')assert line.endswith('"')assert line.count('TERMINAL_SSH_KEY="') == 1diff --git a/tests/hermes_cli/test_merge_profile_tree.py b/tests/hermes_cli/test_merge_profile_tree.pyindex 6ec39198eb1..9673a1f90a9 100644--- a/tests/hermes_cli/test_merge_profile_tree.py+++ b/tests/hermes_cli/test_merge_profile_tree.py@@ -38,7 +38,7 @@ class TestMergeProfileTree:assert len(merged) == 1# First writer wins the identity slot.- assert list(merged.values())[0]["id"] == "p_a"+ assert next(iter(merged.values()))["id"] == "p_a"def test_windows_forward_slash_spelling_folds(self):"""``C:/Users/me/Project`` and ``C:\\Users\\me\\Project`` are one folder."""@@ -118,4 +118,4 @@ class TestMergeProfileTree:_merge_profile_tree(merged, [declared], "beta", preview_limit=5)assert len(merged) == 1- assert list(merged.values())[0]["label"] == "My Proj"+ assert next(iter(merged.values()))["label"] == "My Proj"diff --git a/tests/hermes_cli/test_secrets_bitwarden_non_tty.py b/tests/hermes_cli/test_secrets_bitwarden_non_tty.pyindex 1c76d3eb3b7..dfba2410b43 100644--- a/tests/hermes_cli/test_secrets_bitwarden_non_tty.py+++ b/tests/hermes_cli/test_secrets_bitwarden_non_tty.py@@ -47,7 +47,7 @@ class TestCmdSetupNonTtyGuard:assert "--access-token" in captured.out# The usage example contains --server-url and --project-id, so check# the missing line specifically: it should NOT list them as missing- missing_line = [l for l in captured.out.split("\n") if "Missing:" in l][0]+ missing_line = next(l for l in captured.out.split("\n") if "Missing:" in l)assert "--access-token" in missing_lineassert "--server-url" not in missing_lineassert "--project-id" not in missing_linediff --git a/tests/hermes_cli/test_session_recap.py b/tests/hermes_cli/test_session_recap.pyindex bea19f98a56..ea8f0cf4bf2 100644--- a/tests/hermes_cli/test_session_recap.py+++ b/tests/hermes_cli/test_session_recap.py@@ -41,7 +41,7 @@ def _tool_result(content="ok"):def test_tool_preview_length_truncates_long_user_prompt():long = "x " * 500out = build_recap([_user(long)])- ask_line = [l for l in out.splitlines() if "Last ask" in l][0]+ ask_line = next(l for l in out.splitlines() if "Last ask" in l)assert len(ask_line) < 300 # truncated with ellipsisassert "…" in ask_linediff --git a/tests/hermes_cli/test_sessions_held_store_gate.py b/tests/hermes_cli/test_sessions_held_store_gate.pyindex 430428178a5..86fca2e6d46 100644--- a/tests/hermes_cli/test_sessions_held_store_gate.py+++ b/tests/hermes_cli/test_sessions_held_store_gate.py@@ -72,9 +72,9 @@ def _sessions_subparsers():from hermes_cli.subcommands.sessions import build_sessions_parserbuild_sessions_parser(parser.add_subparsers(dest="command"), cmd_sessions=sessions_cmd.cmd_sessions)- subparsers = [a for a in parser._actions if isinstance(a, argparse._SubParsersAction)][0]+ subparsers = next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction))sessions = subparsers.choices["sessions"]- nested = [a for a in sessions._actions if isinstance(a, argparse._SubParsersAction)][0]+ nested = next(a for a in sessions._actions if isinstance(a, argparse._SubParsersAction))return nested.choicesdiff --git a/tests/hermes_cli/test_skin_engine.py b/tests/hermes_cli/test_skin_engine.pyindex b6274f9cb4c..863a044bbad 100644--- a/tests/hermes_cli/test_skin_engine.py+++ b/tests/hermes_cli/test_skin_engine.py@@ -110,7 +110,7 @@ class TestUserSkins:skins = list_skins()names = [s["name"] for s in skins]assert "pirate" in names- pirate = [s for s in skins if s["name"] == "pirate"][0]+ pirate = next(s for s in skins if s["name"] == "pirate")assert pirate["source"] == "user"diff --git a/tests/hermes_cli/test_worktree_gc.py b/tests/hermes_cli/test_worktree_gc.pyindex 7ec95b84643..705d0362170 100644--- a/tests/hermes_cli/test_worktree_gc.py+++ b/tests/hermes_cli/test_worktree_gc.py@@ -357,7 +357,7 @@ class TestExternalTrees:external = worktree_gc.audit_external_trees(str(repo))paths = [record.path for record in external]assert any("elsewhere-tree" in p for p in paths)- record = [r for r in external if "elsewhere-tree" in r.path][0]+ record = next(r for r in external if "elsewhere-tree" in r.path)assert record.branch == "ext/branch"assert not record.missing@@ -380,7 +380,7 @@ class TestExternalTrees:_shutil.rmtree(ext)external = worktree_gc.audit_external_trees(str(repo))- record = [r for r in external if "vanished-tree" in r.path][0]+ record = next(r for r in external if "vanished-tree" in r.path)assert record.missingplanned = worktree_gc.prune_missing_registrations(str(repo), dry_run=True)@@ -421,7 +421,7 @@ class TestCmdWorktreeJson:assert set(payload) == {"repo", "trees", "external_trees", "branches"}names = [t["name"] for t in payload["trees"]]assert "hermes-json" in names- tree = [t for t in payload["trees"] if t["name"] == "hermes-json"][0]+ tree = next(t for t in payload["trees"] if t["name"] == "hermes-json")assert {"verdict", "reason", "age_days", "branch"} <= set(tree)def test_prune_dry_run_json(self, repo, capsys):diff --git a/tests/hermes_state/test_hermes_state_wal_fallback.py b/tests/hermes_state/test_hermes_state_wal_fallback.pyindex 1add6fb0fee..a283d1531e4 100644--- a/tests/hermes_state/test_hermes_state_wal_fallback.py+++ b/tests/hermes_state/test_hermes_state_wal_fallback.py@@ -129,7 +129,7 @@ class TestApplyWalWithFallback:# Post-fallback the DB is still usable for real writesconn.execute("CREATE TABLE t (x INTEGER)")conn.execute("INSERT INTO t VALUES (1)")- assert list(conn.execute("SELECT x FROM t"))[0][0] == 1+ assert next(iter(conn.execute("SELECT x FROM t")))[0] == 1conn.close()def test_falls_back_on_not_authorized(self, tmp_path):@@ -221,7 +221,7 @@ class TestApplyWalWithFallback:# Post-fallback the DB is still usable for real writesconn.execute("CREATE TABLE t (x INTEGER)")conn.execute("INSERT INTO t VALUES (1)")- assert list(conn.execute("SELECT x FROM t"))[0][0] == 1+ assert next(iter(conn.execute("SELECT x FROM t")))[0] == 1conn.close()def test_persistent_disk_io_error_never_downgrades_wal_disk(self, tmp_path):@@ -400,7 +400,7 @@ class TestApplyWalWithFallback:# Connection is still usable for non-journal_mode SQLconn.execute("CREATE TABLE t (x INTEGER)")conn.execute("INSERT INTO t VALUES (1)")- assert list(conn.execute("SELECT x FROM t"))[0][0] == 1+ assert next(iter(conn.execute("SELECT x FROM t")))[0] == 1conn.close()def test_both_pragmas_fail_but_readback_reports_actual_mode(self, tmp_path, caplog):diff --git a/tests/hermes_state/test_orphan_sweep_cross_backend.py b/tests/hermes_state/test_orphan_sweep_cross_backend.pyindex 3ae878e5d95..70e0d600032 100644--- a/tests/hermes_state/test_orphan_sweep_cross_backend.py+++ b/tests/hermes_state/test_orphan_sweep_cross_backend.py@@ -63,7 +63,7 @@ def _make_session(*,source: str,started_at: float,- message_at: float = None,+ message_at: float | None = None,) -> None:db.create_session(session_id, source=source)if message_at is not None:diff --git a/tests/hermes_state/test_sweep_orphaned_sessions.py b/tests/hermes_state/test_sweep_orphaned_sessions.pyindex a82c266d72d..3e5b3d184dc 100644--- a/tests/hermes_state/test_sweep_orphaned_sessions.py+++ b/tests/hermes_state/test_sweep_orphaned_sessions.py@@ -60,7 +60,7 @@ def _make_session(*,source: str,started_at: float,- message_at: float = None,+ message_at: float | None = None,) -> None:db.create_session(session_id, source=source)if message_at is not None:diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.pyindex 2c3afc174f4..0b7a0b30da4 100644--- a/tests/plugins/test_a2a_plugin.py+++ b/tests/plugins/test_a2a_plugin.py@@ -326,7 +326,7 @@ class TestAgentCardV1:"web": ["web_search", "web_extract"],"terminal": ["terminal"],})- web = [s for s in skills if s["name"] == "web"][0]+ web = next(s for s in skills if s["name"] == "web")assert "web_search" in web["tags"]assert "web_extract" in web["tags"]diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.pyindex f6e512a060f..dc513062662 100644--- a/tests/plugins/test_langfuse_plugin.py+++ b/tests/plugins/test_langfuse_plugin.py@@ -1209,7 +1209,7 @@ class TestApiRequestErrorHook:retryable=True,error={"type": "APIError", "message": "secret prompt echo sk-abc"},)- meta = [u["metadata"] for u in gen.updates if "metadata" in u][0]+ meta = next(u["metadata"] for u in gen.updates if "metadata" in u)assert isinstance(meta["error_message"], dict)assert meta["error_message"]["omitted"] is Truediff --git a/tests/plugins/test_telegram_update_admission.py b/tests/plugins/test_telegram_update_admission.pyindex 03b58897e54..8eb02c4f361 100644--- a/tests/plugins/test_telegram_update_admission.py+++ b/tests/plugins/test_telegram_update_admission.py@@ -883,6 +883,6 @@ async def test_slow_update_does_not_block_other_chats(monkeypatch):breakawait asyncio.sleep(0.02)await asyncio.gather(*adapter._pending_text_batch_tasks.values())- assert [e.source.chat_id for e in delivered][0] == "43"+ assert next(e.source.chat_id for e in delivered) == "43"same_chat = "\n".join(e.text for e in delivered if e.source.chat_id == "42")assert same_chat == "hello\nsecond"diff --git a/tests/scripts/test_release_darwin.py b/tests/scripts/test_release_darwin.pyindex f847f287255..746e1b024e0 100644--- a/tests/scripts/test_release_darwin.py+++ b/tests/scripts/test_release_darwin.py@@ -156,7 +156,7 @@ def test_finalize_uses_the_real_signed_transport_and_publishes_last(r2_server):methods = [m for m, _p, _h in r2_server.requests]assert methods.count("PUT") == 1assert "PUT" not in methods[:3]- put_headers = [h for m, _p, h in r2_server.requests if m == "PUT"][0]+ put_headers = next(h for m, _p, h in r2_server.requests if m == "PUT")assert put_headers["If-None-Match"] == "*"assert put_headers["Cache-Control"] == "no-store"assert put_headers["Content-Type"] == "application/yaml"diff --git a/tests/scripts/test_release_r2.py b/tests/scripts/test_release_r2.pyindex e4335164c43..a671637b32b 100644--- a/tests/scripts/test_release_r2.py+++ b/tests/scripts/test_release_r2.py@@ -621,7 +621,7 @@ def test_put_page_object_carries_html_type_and_no_store(r2_server):os.unlink(path)stored, _etag = r2_server.store["releases/stable/index.html"]assert stored == page.encode("utf-8")- headers = [r[2] for r in r2_server.requests if r[0] == "PUT"][0]+ headers = next(r[2] for r in r2_server.requests if r[0] == "PUT")assert headers["Content-Type"] == "text/html; charset=utf-8"assert headers["Cache-Control"] == "no-store"diff --git a/tests/secret_sources/test_secret_source_registry.py b/tests/secret_sources/test_secret_source_registry.pyindex d20ab481e58..0d17b423e4b 100644--- a/tests/secret_sources/test_secret_source_registry.py+++ b/tests/secret_sources/test_secret_source_registry.py@@ -181,7 +181,7 @@ class TestApplyAll:tmp_path, environ=env,)assert env["K"] == "v"- broken = [s for s in report.sources if s.name == "broken"][0]+ broken = next(s for s in report.sources if s.name == "broken")assert broken.result.error_kind is ErrorKind.NETWORKdiff --git a/tests/tools/test_browser_supervisor_capture.py b/tests/tools/test_browser_supervisor_capture.pyindex 0522eb500ef..854e6108656 100644--- a/tests/tools/test_browser_supervisor_capture.py+++ b/tests/tools/test_browser_supervisor_capture.py@@ -33,7 +33,7 @@ class _FakeCDP:async def main():async with serve(self._handle, "127.0.0.1", 0) as server:- self.url = f"ws://127.0.0.1:{list(server.sockets)[0].getsockname()[1]}/devtools/browser/x"+ self.url = f"ws://127.0.0.1:{next(iter(server.sockets)).getsockname()[1]}/devtools/browser/x"ready.set()await asyncio.Event().wait()diff --git a/tests/tools/test_checkpoint_manager.py b/tests/tools/test_checkpoint_manager.pyindex d536914d0ac..0d227ac6bbb 100644--- a/tests/tools/test_checkpoint_manager.py+++ b/tests/tools/test_checkpoint_manager.py@@ -870,7 +870,7 @@ class TestGpgIsolation:# prune_checkpoints + maybe_auto_prune_checkpoints# =========================================================================-def _seed_legacy_repo(base: Path, name: str, workdir: Path, mtime: float = None) -> Path:+def _seed_legacy_repo(base: Path, name: str, workdir: Path, mtime: float | None = None) -> Path:"""Create a minimal pre-v2 shadow repo directly under base."""shadow = base / nameshadow.mkdir(parents=True)diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex fe03a2d9c1a..567b61bb42a 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -1792,7 +1792,7 @@ class TestMcpInvocationResolution:yield@staticmethod- def _fake_run(stdout: str = "", returncode: int = 0, raises: Exception = None):+ def _fake_run(stdout: str = "", returncode: int = 0, raises: Exception | None = None):"""Build a patched subprocess.run that yields the supplied result."""from unittest.mock import MagicMockdef _run(*args, **kwargs):diff --git a/tests/tools/test_file_ops_cwd_tracking.py b/tests/tools/test_file_ops_cwd_tracking.pyindex e2672582dfb..e0d299819e1 100644--- a/tests/tools/test_file_ops_cwd_tracking.py+++ b/tests/tools/test_file_ops_cwd_tracking.py@@ -36,7 +36,7 @@ class _FakeEnv:self.cwd = start_cwdself.calls: list[dict] = []- def execute(self, command: str, cwd: str = None, **kwargs) -> dict:+ def execute(self, command: str, cwd: str | None = None, **kwargs) -> dict:import subprocessself.calls.append({"command": command, "cwd": cwd})# Simulate cd by updating self.cwd (the real env does the samediff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.pyindex ebcae3f037a..25403972fba 100644--- a/tests/tools/test_mcp_npx_cached_bin.py+++ b/tests/tools/test_mcp_npx_cached_bin.py@@ -34,7 +34,7 @@ def _cache(tmp_path, *, package, deps=None, bin_field, make_bin=True, entry="abc)bindir = root / "node_modules" / ".bin"bindir.mkdir(parents=True, exist_ok=True)- name = bin_field if isinstance(bin_field, str) else list(bin_field)[0]+ name = bin_field if isinstance(bin_field, str) else next(iter(bin_field))target = bindir / (os.path.basename(package) if isinstance(bin_field, str) else name)if os.name == "nt":target = target.with_suffix(".cmd")diff --git a/tests/tools/test_skill_ledger.py b/tests/tools/test_skill_ledger.pyindex 4ff89310ac9..4fc03d98a62 100644--- a/tests/tools/test_skill_ledger.py+++ b/tests/tools/test_skill_ledger.py@@ -311,7 +311,7 @@ def test_rollback_fails_closed_when_safety_capture_fails(ledger_env, monkeypatch))assert patched["success"] is True- entry = [r for r in skill_ledger.list_entries("my-skill") if r["action"] == "patch"][0]+ entry = next(r for r in skill_ledger.list_entries("my-skill") if r["action"] == "patch")current = skill_md.read_bytes()monkeypatch.setattr(skill_ledger, "append_entry", lambda *a, **k: None)@@ -338,7 +338,7 @@ def test_rollback_removes_files_created_by_the_mutation(ledger_env):extra = ledger_env["skills"] / "my-skill" / "references" / "extra.md"assert extra.exists()- entry = [r for r in skill_ledger.list_entries("my-skill") if r["action"] == "write_file"][0]+ entry = next(r for r in skill_ledger.list_entries("my-skill") if r["action"] == "write_file")ok, msg = skill_ledger.rollback_entry(entry["id"])assert ok is True, msgassert not extra.exists() # created by the mutation → removed on rollback@@ -469,10 +469,10 @@ def test_delete_after_rehome_ledgers_full_package_from_backup(ledger_env):deleted = json.loads(skill_manage(action="delete", name="my-skill"))assert deleted["success"] is True- delete_entry = [+ delete_entry = next(r for r in skill_ledger.list_entries(skill="my-skill")if r["action"] == "delete"- ][0]+ )before_names = {Path(i["path"]).name for i in delete_entry["before"]}assert "SKILL.md" in before_namesassert "extra.md" in before_names, (@@ -536,10 +536,10 @@ def test_delete_rollback_without_backup_still_works(ledger_env):deleted = json.loads(skill_manage(action="delete", name="my-skill"))assert deleted["success"] is True- delete_entry = [+ delete_entry = next(r for r in skill_ledger.list_entries(skill="my-skill")if r["action"] == "delete"- ][0]+ )assert {Path(i["path"]).name for i in delete_entry["before"]} == {"SKILL.md"}ok, msg = skill_ledger.rollback_entry(delete_entry["id"])diff --git a/tools/browser_camofox.py b/tools/browser_camofox.pyindex 09c8c16c7b4..0aa3ac198ad 100644--- a/tools/browser_camofox.py+++ b/tools/browser_camofox.py@@ -321,16 +321,16 @@ def _post(path: str, body: dict, timeout: Optional[int] = None) -> dict:return _request("post", path, timeout, json=body).json()-def _get(path: str, params: dict = None, timeout: Optional[int] = None) -> dict:+def _get(path: str, params: dict | None = None, timeout: Optional[int] = None) -> dict:return _request("get", path, timeout, params=params).json()-def _get_raw(path: str, params: dict = None, timeout: Optional[int] = None) -> requests.Response:+def _get_raw(path: str, params: dict | None = None, timeout: Optional[int] = None) -> requests.Response:"""GET and return the raw response (for binary data)."""return _request("get", path, timeout, params=params)-def _delete(path: str, body: dict = None, timeout: Optional[int] = None) -> dict:+def _delete(path: str, body: dict | None = None, timeout: Optional[int] = None) -> dict:return _request("delete", path, timeout, json=body).json()diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 3e3636fae1a..9e66bdbd049 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -889,7 +889,7 @@ def _dispatch_browser_command(def _run_browser_command(task_id: str,command: str,- args: list[str] = None,+ args: list[str] | None = None,timeout: Optional[int] = None,_engine_override: Optional[str] = None,) -> dict[str, Any]:diff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.pyindex 1be23cb5d68..50b6e55bbcd 100644--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@ -1117,7 +1117,7 @@ class CheckpointManager:self,working_dir: str,commit_hash: str,- file_path: str = None,+ file_path: str | None = None,safe: bool = False,) -> dict:"""Restore files to a checkpoint state.diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex f88d7a67ae6..bb03874653f 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -874,8 +874,8 @@ _TOOL_DOC_LINES = []-def build_execute_code_schema(enabled_sandbox_tools: set = None,- mode: str = None) -> dict:+def build_execute_code_schema(enabled_sandbox_tools: set | None = None,+ mode: str | None = None) -> dict:"""execute_code schema listing only *enabled_sandbox_tools* — a disabled tool (e.g. web off)must not appear or the model keeps trying it. ``mode`` (None → config) picks the cwd sentence."""if enabled_sandbox_tools is None:diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex d9fc09f40a0..ed08ee141f0 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -1009,7 +1009,7 @@ def cronjob(monitor_url: Optional[str] = None,reasoning_effort: Optional[str] = None,failure_deliver: Optional[Union[str, list[str]]] = None,- task_id: str = None,+ task_id: str | None = None,session_id: Optional[str] = None,paused: bool = False,paused_reason: Optional[str] = None,diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex e8feb25e1eb..a81ca4d34d7 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -326,7 +326,7 @@ class _ChildProgressRelay:kw["tool_count"] = self.tool_countreturn kw- def _relay(self, event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs):+ def _relay(self, event_type: str, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs):if self.parent_cb:# kwargs override identity (e.g. status, duration_seconds).with _quiet("Parent callback failed: %s"):@@ -409,7 +409,7 @@ class _ChildProgressRelay:if len(self.batch) >= self._BATCH_SIZE:self._flush()- def __call__(self, event_type, tool_name: str = None, preview: str = None, args=None, **kwargs):+ def __call__(self, event_type, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs):key = _normalize_event(event_type)method = None if key is None else _EVENT_HANDLERS.get(key, "_on_tool_started")if method is not None:diff --git a/tools/environments/base.py b/tools/environments/base.pyindex 725654c030d..00182c691ee 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -257,7 +257,7 @@ class BaseEnvironment(ABC):"""return "/tmp" # no-tmp: ok — sandbox-side (remote container) temp dir, not the host- def __init__(self, cwd: str, timeout: int, env: dict = None):+ def __init__(self, cwd: str, timeout: int, env: dict | None = None):self.cwd = cwdself.timeout = timeoutself.env = env or {}diff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex aec68cd58a7..1a4545677dc 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -642,14 +642,14 @@ class DockerEnvironment(BaseEnvironment):disk: int = 0,persistent_filesystem: bool = False,task_id: str = "default",- volumes: list = None,+ volumes: list | None = None,forward_env: list[str] | None = None,env: dict | None = None,network: bool = True,host_cwd: Optional[str] = None,auto_mount_cwd: bool = False,run_as_host_user: bool = False,- extra_args: list = None,+ extra_args: list | None = None,persist_across_processes: bool = True,shm_size: str = _DEFAULT_SHM_SIZE,shared_container_key: str = "",diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 2040cb93a8a..7eaa5b7d868 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -987,7 +987,7 @@ class LocalEnvironment(BaseEnvironment):name for name in mergedif isinstance(name, str) and _matches_terminal_first_party_prefix(name)))- def __init__(self, cwd: str = "", timeout: int = 60, env: dict = None):+ def __init__(self, cwd: str = "", timeout: int = 60, env: dict | None = None):super().__init__(cwd=_resolve_local_initial_cwd(cwd), timeout=timeout, env=env)self.init_session()diff --git a/tools/file_operations.py b/tools/file_operations.pyindex 355f135861b..544bc0beb42 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -212,7 +212,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):patches "succeed" with a plausible diff while landing in the wrong directory)."""- def __init__(self, terminal_env, cwd: str = None):+ def __init__(self, terminal_env, cwd: str | None = None):self.env = terminal_env# Never os.getcwd(): that is the HOST path, absent inside container backends.self.cwd = cwd or getattr(terminal_env, 'cwd', None) or \@@ -224,8 +224,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):self._rg_resolution_cache: dict[str, str] = {}self._rg_modified_capability: dict[str, Optional[str]] = {}- def _exec(self, command: str, cwd: str = None, timeout: int = None,- stdin_data: str = None) -> ExecuteResult:+ def _exec(self, command: str, cwd: str | None = None, timeout: int | None = None,+ stdin_data: str | None = None) -> ExecuteResult:"""Run ``command`` on the backend. cwd: explicit arg → live ``env.cwd`` →init-time ``self.cwd``. ``stdin_data`` is piped (bypasses ARG_MAX)."""kwargs = {}@@ -467,7 +467,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):passreturn True- def _is_likely_binary(self, path: str, content_sample: str = None) -> bool:+ def _is_likely_binary(self, path: str, content_sample: str | None = None) -> bool:"""Legacy text-layer binary check: extension, else >30% non-printable chars."""if has_binary_extension(path):return True@@ -714,7 +714,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):return self._escape_shell_arg(sys.executable)return "python3"- def _exec_python_snippet(self, snippet: str, py: str = None) -> ExecuteResult:+ def _exec_python_snippet(self, snippet: str, py: str | None = None) -> ExecuteResult:"""Run a Python ``snippet`` in the terminal backend's interpreter.Base64-encodes the snippet so it survives every shell/quoting layerdiff --git a/tools/file_tools.py b/tools/file_tools.pyindex bab00f7b37e..f334d8b0d3f 100644--- a/tools/file_tools.py+++ b/tools/file_tools.py@@ -376,7 +376,7 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations:return file_ops-def clear_file_ops_cache(task_id: str = None):+def clear_file_ops_cache(task_id: str | None = None):"""Clear file-operation state for a finished task, or all tasks."""with _file_ops_lock:if task_id:@@ -956,8 +956,8 @@ def _collect_v4a_header_paths(patch: str) -> tuple[list[str], list[str], list[streturn paths, content_paths, entry_paths-def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,- new_string: str = None, replace_all: bool = False, patch: str = None,+def patch_tool(mode: str = "replace", path: str | None = None, old_string: str | None = None,+ new_string: str | None = None, replace_all: bool = False, patch: str | None = None,task_id: str = "default", cross_profile: bool = False,session_id: str | None = None) -> str:"""Patch a file using replace mode or V4A patch format.@@ -1051,7 +1051,7 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,def search_tool(pattern: str, target: str = "content", path: str = ".",- file_glob: str = None, limit: int = 50, offset: int = 0,+ file_glob: str | None = None, limit: int = 50, offset: int = 0,output_mode: str = "content", context: int = 0,order: str = "discovery",task_id: str = "default") -> str:diff --git a/tools/file_tools_read_tracking.py b/tools/file_tools_read_tracking.pyindex 31981c9d3a2..1054a42220f 100644--- a/tools/file_tools_read_tracking.py+++ b/tools/file_tools_read_tracking.py@@ -158,7 +158,7 @@ def _bump_consecutive(task_data: dict, key: tuple) -> int:return task_data["consecutive"]-def reset_file_dedup(task_id: str = None):+def reset_file_dedup(task_id: str | None = None):"""Advance the read-dedup generation after context compression (one task, or allwhen ``task_id`` is None). The per-key ``dedup`` metadata map is PRESERVED so unchangedfiles keep returning stubs instead of re-bloating the reclaimed context; thediff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.pyindex b02d308ca8c..883898fbd2c 100644--- a/tools/image_generation_tool.py+++ b/tools/image_generation_tool.py@@ -229,7 +229,7 @@ def _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=Nrequired = {"prompt"}if edit: # a few edit endpoints (Kling Image v3) take a singular `image_url` string instead of the listimage_param = meta.get("edit_image_param") or "image_urls"- payload[image_param] = list(image_urls)[0] if image_param != "image_urls" else list(image_urls)+ payload[image_param] = next(iter(image_urls)) if image_param != "image_urls" else list(image_urls)required.add(image_param)size_key = _SIZE_KEY_BY_STYLE.get(meta["size_style"])if size_key is None and not edit:diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex 5c3aa97c104..b0e4254f15e 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -211,8 +211,8 @@ def _background_delete_gate(store, action, operations, target="memory", content="batch); 'add' is still available.", success=False)-def memory_tool(action: str = None, target: str = "memory", content: str = None, old_text: str = None,- new_text: str = None, operations: Optional[list[dict[str, Any]]] = None,+def memory_tool(action: str | None = None, target: str = "memory", content: str | None = None, old_text: str | None = None,+ new_text: str | None = None, operations: Optional[list[dict[str, Any]]] = None,store: Optional[MemoryStore] = None) -> str:"""Tool entry point; returns a JSON string. Single op (action + content/old_text)or batch (``operations``, atomic against the final budget). ``new_text``diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.pyindex 3051026597a..09753cfe90a 100644--- a/tools/memory_tool_store.py+++ b/tools/memory_tool_store.py@@ -526,7 +526,7 @@ class MemoryStore:it, preserving the prefix cache); None if empty."""return self._system_prompt_snapshot.get(target, "") or None- def _success_response(self, target: str, message: str = None, **extra) -> dict[str, Any]:+ def _success_response(self, target: str, message: str | None = None, **extra) -> dict[str, Any]:"""TERMINAL and WITHOUT the entries list: echoing entries invites the model to"find more to fix" and re-issue the same ops. A successful write resets theper-turn failure budget. ``**extra`` mirrors ``_error``'s convention — e.g. thediff --git a/tools/process_registry.py b/tools/process_registry.pyindex 841f50b2aaf..285984fd472 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -1194,8 +1194,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):return sessiondef spawn_local(- self, command: str, cwd: str = None, task_id: str = "", session_key: str = "",- env_vars: dict = None, use_pty: bool = False, owner_task_id: str = "",+ self, command: str, cwd: str | None = None, task_id: str = "", session_key: str = "",+ env_vars: dict | None = None, use_pty: bool = False, owner_task_id: str = "",persist_on_release: bool = False) -> ProcessSession:"""Spawn a background process locally (TERMINAL_ENV=local; other backends usespawn_via_env()). ``use_pty`` requests a pseudo-terminal via ptyprocess/pywinpty@@ -1287,7 +1287,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):return sessiondef spawn_via_env(- self, env: Any, command: str, cwd: str = None, task_id: str = "", session_key: str = "",+ self, env: Any, command: str, cwd: str | None = None, task_id: str = "", session_key: str = "",timeout: int = 10, owner_task_id: str = "", persist_on_release: bool = False) -> ProcessSession:"""Spawn a background process inside a non-local backend's sandbox.The command is wrapped to capture its in-sandbox PID and redirect output to a@@ -2079,7 +2079,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):self._completion_consumed.add(session_id)return result- def wait(self, session_id: str, timeout: int = None) -> dict:+ def wait(self, session_id: str, timeout: int | None = None) -> dict:"""Block until the process exits, the timeout elapses, the user interrupts, or amid-turn user message (steer/redirect → ``request_yield``) releases the wait.``timeout`` defaults to (and is clamped by) TERMINAL_TIMEOUT. Returns a dict@@ -2389,7 +2389,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):"""O(1) running count for status-bar polling; dict ``len()`` is atomic, no lock."""return len(self._running)- def list_sessions(self, task_id: str = None, session_key: str = None, *, include_retained: bool = False) -> list:+ def list_sessions(self, task_id: str | None = None, session_key: str | None = None, *, include_retained: bool = False) -> list:"""Running and recently-finished processes for ``task_id`` and/or ``session_key``;cross-task entries sharing the gateway session (a forgotten preview serverblocking session reset) are flagged ``"session_scoped": true``.diff --git a/tools/registry.py b/tools/registry.pyindex 1971910612f..30ec01a9f31 100644--- a/tools/registry.py+++ b/tools/registry.py@@ -665,9 +665,9 @@ class ToolRegistry:def register(self, name: str, toolset: str, schema: dict, handler: Callable,- check_fn: Callable = None, requires_env: list = None, is_async: bool = False,+ check_fn: Callable | None = None, requires_env: list | None = None, is_async: bool = False,description: str = "", emoji: str = "", max_result_size_chars: float | None = None,- dynamic_schema_overrides: Callable = None, override: bool = False,+ dynamic_schema_overrides: Callable | None = None, override: bool = False,scope: Optional[str] = None):"""Register a tool (called at import time by each tool file). ``override=True`` is anexplicit opt-in for plugins replacing a built-in implementation (e.g. a headed-Chromediff --git a/tools/session_search_tool.py b/tools/session_search_tool.pyindex a85dfe2cb5d..fd64fcf6eca 100644--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@ -251,7 +251,7 @@ def _shape_message(m: dict[str, Any], anchor_id: Optional[int] = None,return {k: v for k, v in entry.items() if v is not None or k == "content"}-def _session_link(session_id: str, profile: str = None) -> str:+def _session_link(session_id: str, profile: str | None = None) -> str:"""The reference the agent writes for a session — same value the desktop composeremits, so it renders as a titled link. The profile segment is omitted when itcan't be named confidently (a bare id still resolves, just not across profiles)."""@@ -352,7 +352,7 @@ def _hydrate_hit(db, lineage_root: str, match_info: dict[str, Any], result_detaidef _discover(db, query: str, role_filter: Optional[list[str]], limit: int, sort: Optional[str],- detail: str, current_session_id: str = None, link_profile: str = None,+ detail: str, current_session_id: str | None = None, link_profile: str | None = None,after_ts: Optional[int] = None, before_ts: Optional[int] = None,exclude_session_ids: Optional[list[str]] = None) -> str:"""Discovery shape: FTS5 plus adaptive or full result hydration."""@@ -444,7 +444,7 @@ def _resolve_profile_db(profile: str):return SessionDB(db_path=profiles_mod.get_profile_dir(canon) / "state.db", read_only=True)-def _read_session(db, session_id: str, head: int = 20, tail: int = 10, link_profile: str = None) -> str:+def _read_session(db, session_id: str, head: int = 20, tail: int = 10, link_profile: str | None = None) -> str:"""Read shape: whole session, or ``head`` + ``tail`` messages with a scroll pointer."""meta = _get_session_meta(db, session_id)if not meta:@@ -477,7 +477,7 @@ def _read_scoped(db, sid: str, profile: Optional[str]) -> str:"profile, pass profile=<name> (or the @session:<profile>/<id> link).", success=False)-def _list_recent_sessions(db, limit: int, current_session_id: str = None, link_profile: str = None) -> str:+def _list_recent_sessions(db, limit: int, current_session_id: str | None = None, link_profile: str | None = None) -> str:"""Browse shape: metadata for the most recent sessions (no LLM, no FTS5)."""def _browse():# Never use list_sessions_rich(order_by_last_active=True) here: it walks every@@ -529,7 +529,7 @@ def _anchor_in_live_context(db, anchor_state, anchor_sid: str, current_session_idef _scroll(db, session_id: str, around_message_id: int, window: int = 5,- current_session_id: str = None) -> str:+ current_session_id: str | None = None) -> str:"""Scroll shape: a window centered on an anchor (no FTS5, no bookends)."""try:around_message_id = int(around_message_id)@@ -616,10 +616,10 @@ def _dispatch(query, role_filter, limit, db, current_session_id, session_id,exclude_session_ids=_normalize_exclude_session_ids(exclude_session_ids))-def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None,- current_session_id: str = None, session_id: str = None, around_message_id: int = None,- window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive",- after: str = None, before: str = None, exclude_session_ids: Optional[list[str]] = None) -> str:+def session_search(query: str = "", role_filter: str | None = None, limit: int = 3, db=None,+ current_session_id: str | None = None, session_id: str | None = None, around_message_id: int | None = None,+ window: int = 5, sort: str | None = None, profile: str | None = None, detail: str = "adaptive",+ after: str | None = None, before: str | None = None, exclude_session_ids: Optional[list[str]] = None) -> str:"""Run session search, closing DBs opened here. Positional order is frozen for old callers;new parameters are appended after ``detail``."""from hermes_state import format_session_db_unavailablediff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex 0d6a5f1273d..78b72dde0ec 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -216,8 +216,8 @@ def _rollback(snapshots, find_skill, results):_ADVISORY_KEYS = ("lint_warnings", "lint_hint")-def _skill_manage_batch(operations, default_name: str = None, task_id: str = None,- session_id: str = None) -> str:+def _skill_manage_batch(operations, default_name: str | None = None, task_id: str | None = None,+ session_id: str | None = None) -> str:"""Apply operations atomically: every touched skill is snapshotted first and anyfailure rolls ALL of them back (batch-created skills are removed). ``delete`` isonly legal as the SOLE op (its recoverable-archive path doesn't compose withdiff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 221126256aa..eee8c452e46 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -197,7 +197,7 @@ def _description_preview(content: str) -> str:return ""-def _resolve_skill_dir(name: str, category: str = None) -> Path:+def _resolve_skill_dir(name: str, category: str | None = None) -> Path:"""New-skill dir; honors ``skills.create_dir`` (e.g. a shared fleet dir)."""base = _skills_dir()try:@@ -450,7 +450,7 @@ def _clip(text: str, n: int, ellipsis: str) -> str:# --- Core actions --------------------------------------------------------------def _create_skill(name: str, content: str, category: str = None) -> dict[str, Any]:+def _create_skill(name: str, content: str, category: str | None = None) -> dict[str, Any]:if err := (_validate_name(name) or _validate_category(category)or _validate_frontmatter(content, new_skill=True) or _validate_content_size(content)):return _err(err)@@ -505,7 +505,7 @@ def _edit_skill(name: str, content: str) -> dict[str, Any]:return _add_description_prompt_preview(result, content)-def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = None,+def _patch_skill(name: str, old_string: str, new_string: str, file_path: str | None = None,replace_all: bool = False) -> dict[str, Any]:"""Targeted find-and-replace in SKILL.md (default) or a supporting file; unique match unless replace_all."""if not old_string:@@ -763,10 +763,10 @@ def _record_success(action, name, result, *, file_path, absorbed_into, task_id,def skill_manage(- action: str, name: str, content: str = None, category: str = None, file_path: str = None,- file_content: str = None, old_string: str = None, new_string: str = None,- replace_all: bool = False, absorbed_into: str = None, task_id: str = None,- session_id: str = None, operations=None) -> str:+ action: str, name: str, content: str | None = None, category: str | None = None, file_path: str | None = None,+ file_content: str | None = None, old_string: str | None = None, new_string: str | None = None,+ replace_all: bool = False, absorbed_into: str | None = None, task_id: str | None = None,+ session_id: str | None = None, operations=None) -> str:"""Dispatch to the action handler -> JSON string. ``operations`` (atomic batch shape,see _skill_manage_batch) overrides the flat fields."""if operations is not None:diff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 445c98f56b8..9828e4c3f23 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -153,7 +153,7 @@ def _parse_tags(tags_value) -> list[str]:return [t.strip().strip("\"'") for t in tags_value.split(",") if t.strip()]-def _is_skill_disabled(*names: str, platform: str = None) -> bool:+def _is_skill_disabled(*names: str, platform: str | None = None) -> bool:"""Any of *names* disabled in config (one config load)? Platform precedence: explicit arg,``HERMES_PLATFORM``, session ``HERMES_SESSION_PLATFORM``. A globally-disabled skill stays disabled on every platform(keep in sync with agent.skill_utils.get_disabled_skill_names)."""@@ -245,7 +245,7 @@ def _sort_skills(skills: list[dict[str, Any]]) -> list[dict[str, Any]]:return sorted(skills, key=lambda s: (s.get("category") or "", s["name"]))-def skills_list(category: str = None, task_id: str = None) -> str:+def skills_list(category: str | None = None, task_id: str | None = None) -> str:"""Tier 1 listing: name + description (+ category) only; ``task_id`` is handler parity."""try:_skills_dir().mkdir(parents=True, exist_ok=True)@@ -548,7 +548,7 @@ def _log_security_warnings(name: str, skill_md: Path, content: str, all_dirs, acdef skill_view(- name: str, file_path: str = None, task_id: str = None, preprocess: bool = True) -> str:+ name: str, file_path: str | None = None, task_id: str | None = None, preprocess: bool = True) -> str:"""View a skill (SKILL.md) or a file within its directory, as JSON. ``name`` is a skill nameor path ("axolotl", "03-fine-tuning/axolotl"); "plugin:skill" resolves plugin-providedskills. ``preprocess`` applies the configured SKILL.md template / inline shell rendering;diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.pyindex 9cb03bc2c51..eb016f35480 100644--- a/tools/terminal_tool_backends.py+++ b/tools/terminal_tool_backends.py@@ -236,8 +236,8 @@ _ENV_BUILDERS = {"local": _build_local_env, "docker": _build_docker_env, "singuldef _create_environment(env_type: str, image: str, cwd: str, timeout: int,- ssh_config: dict = None, container_config: dict = None,- local_config: dict = None, task_id: str = "default",+ ssh_config: dict | None = None, container_config: dict | None = None,+ local_config: dict | None = None, task_id: str = "default",host_cwd: Optional[str] = None, probe_only: bool = False):"""Create an execution environment (instance with ``execute()``) for *env_type*. ``image`` is ignoredfor local/ssh/vercel; ``container_config`` carries the container_*/docker_* resource keys; ``host_cwd`` isdiff --git a/tools/vision_tools.py b/tools/vision_tools.pyindex 3f93b4a284f..206e453c6db 100644--- a/tools/vision_tools.py+++ b/tools/vision_tools.py@@ -885,7 +885,7 @@ async def _run_analysis(async def vision_analyze_tool(- image_url: str, user_prompt: str, model: str = None,+ image_url: str, user_prompt: str, model: str | None = None,task_id: Optional[str] = None, region: Optional[list] = None) -> str:"""Describe an image (URL, local path, data: URL) with the auxiliary vision LLM. ``user_prompt``is pre-formatted by the caller. Temp images live under $HERMES_HOME/cache/vision/."""@@ -1119,7 +1119,7 @@ async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths:async def video_analyze_tool(- video_url: str, user_prompt: str, model: str = None, task_id: Optional[str] = None) -> str:+ video_url: str, user_prompt: str, model: str | None = None, task_id: Optional[str] = None) -> str:"""Analyze a video via multimodal LLM. Returns JSON {success, analysis}."""async def stage(prompt: str, debug_call_data: dict, temp_paths: list) -> tuple:temp_video_path = await _materialize_video(video_url, task_id, temp_paths)diff --git a/tools/web_tools.py b/tools/web_tools.pyindex aaaf96dcefc..41433df1752 100644--- a/tools/web_tools.py+++ b/tools/web_tools.py@@ -389,7 +389,7 @@ def _memoized_search(provider, query: str, limit: int) -> dict:return slice_search_response(response_data, limit)-async def web_extract_tool(urls: list[Any], format: str = None, char_limit: Optional[int] = None) -> str:+async def web_extract_tool(urls: list[Any], format: str | None = None, char_limit: Optional[int] = None) -> str:"""Extract clean page content (no LLM) from URLs via the configured backend.Pages over ``char_limit`` (default web.extract_char_limit or 15000) are head+tail truncated with a footerdiff --git a/toolsets.py b/toolsets.pyindex 4e1e358bd2c..ad3eb9a9587 100644--- a/toolsets.py+++ b/toolsets.py@@ -370,7 +370,7 @@ def _plugin_platform_bundle(name: str) -> list[str]:return list(tools)-def resolve_toolset(name: str, visited: set[str] = None, *, include_registry: bool = True) -> list[str]:+def resolve_toolset(name: str, visited: set[str] | None = None, *, include_registry: bool = True) -> list[str]:"""Recursively resolve a toolset (and its includes) to a sorted tool-name list.include_registry=False resolves the static TOOLSETS view only.@@ -483,7 +483,7 @@ def validate_toolset(name: str) -> bool:or name in _get_plugin_toolset_names() or name in _get_registry_toolset_aliases())-def create_custom_toolset(name: str, description: str, tools: list[str] = None, includes: list[str] = None) -> None:+def create_custom_toolset(name: str, description: str, tools: list[str] | None = None, includes: list[str] | None = None) -> None:"""Register a runtime toolset in TOOLSETS."""TOOLSETS[name] = _ts(description, tools or [], includes or [])diff --git a/trajectory_compressor.py b/trajectory_compressor.pyindex a45b5a91784..35732a6ec83 100644--- a/trajectory_compressor.py+++ b/trajectory_compressor.py@@ -829,8 +829,8 @@ def _run_dir_mode(input_path: Path, output: Optional[str], compression_config: Cprint("\n✅ Compression complete!")-def main(input: str, output: str = None, config: str = "configs/trajectory_compression.yaml", target_max_tokens: int = None,- tokenizer: str = None, sample_percent: float = None, seed: int = 42, dry_run: bool = False):+def main(input: str, output: str | None = None, config: str = "configs/trajectory_compression.yaml", target_max_tokens: int | None = None,+ tokenizer: str | None = None, sample_percent: float | None = None, seed: int = 42, dry_run: bool = False):"""Compress agent trajectories to fit within a target token budget.