Skip to content

The agent that grows with you

refactor(gateway): fold long string literals and dict/call layouts in slash_commands_session/model

Teknium901796093bb5
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.py
index cfee6563884..1a42095bfa9 100644
--- a/gateway/slash_commands_model.py
+++ b/gateway/slash_commands_model.py
@@ -259,20 +259,16 @@ class GatewayModelCommandsMixin:
f"Adjust your self-identification accordingly.]"
)
self._session_model_overrides[ctx.session_key] = {
- "model": result.new_model,
- "provider": result.target_provider,
- "api_key": result.api_key,
- "base_url": result.base_url,
- "api_mode": result.api_mode,
+ "model": result.new_model, "provider": result.target_provider, "api_key": result.api_key,
+ "base_url": result.base_url, "api_mode": result.api_mode,
"request_overrides": dict(result.request_overrides or {}),
"capabilities": dict(result.runtime_capabilities or {}),
}
if one_turn:
if not hasattr(self, "_pending_one_turn_model_restores"):
self._pending_one_turn_model_restores = {}
- self._pending_one_turn_model_restores[ctx.session_key] = (
- ctx.restore_snapshot or {"had_override": False, "override": None}
- )
+ snapshot = ctx.restore_snapshot or {"had_override": False, "override": None}
+ self._pending_one_turn_model_restores[ctx.session_key] = snapshot
elif not picker and hasattr(self, "_pending_one_turn_model_restores"):
self._pending_one_turn_model_restores.pop(ctx.session_key, None)
# Non-secret write-through so the override survives a restart (api_key/api_mode are
@@ -323,14 +319,14 @@ class GatewayModelCommandsMixin:
)
if ctx_len:
lines.append(t("gateway.model.context_label", tokens=f"{ctx_len:,}"))
+ if mi and mi.max_output:
+ lines.append(t("gateway.model.max_output_label", tokens=f"{mi.max_output:,}"))
if mi:
- if mi.max_output:
- lines.append(t("gateway.model.max_output_label", tokens=f"{mi.max_output:,}"))
lines.append(t("gateway.model.capabilities_label", capabilities=mi.format_capabilities()))
- if not picker and (
- (base_url_host_matches(result.base_url or "", "openrouter.ai") and "claude" in result.new_model.lower())
- or result.api_mode == "anthropic_messages"
- ):
+ openrouter_claude = (
+ base_url_host_matches(result.base_url or "", "openrouter.ai") and "claude" in result.new_model.lower()
+ )
+ if not picker and (openrouter_claude or result.api_mode == "anthropic_messages"):
lines.append(t("gateway.model.prompt_caching_enabled"))
if result.warning_message:
lines.append(t("gateway.model.warning_prefix", warning=result.warning_message))
@@ -440,24 +436,17 @@ class GatewayModelCommandsMixin:
async def _on_cost_confirm(choice: str) -> str:
if choice == "cancel":
- return (
- f"🟑 Model switch cancelled. Current model unchanged "
- f"({ctx.current_model or 'unknown'})."
- )
+ return f"🟑 Model switch cancelled. Current model unchanged ({ctx.current_model or 'unknown'})."
# "once" and "always" both proceed β€” selection guards have no persistent opt-out.
return await self._commit_model_switch(result, ctx, source=ctx.source)
_p = self._typed_command_prefix_for(event.source.platform)
+ message = (
+ f"⚠️ **{warning.title}**\n\n{warning.message}\n\n"
+ f"_Text fallback: reply `{_p}approve` to switch or `{_p}cancel` to keep the current model._"
+ )
return True, await self._request_slash_confirm(
- event=event,
- command="model",
- title=warning.title,
- message=(
- f"⚠️ **{warning.title}**\n\n{warning.message}\n\n"
- f"_Text fallback: reply `{_p}approve` to switch or `{_p}cancel` to keep "
- "the current model._"
- ),
- handler=_on_cost_confirm,
+ event=event, command="model", title=warning.title, message=message, handler=_on_cost_confirm,
)
async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index f4690503cc3..7591d3cacdf 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -140,15 +140,13 @@ class GatewaySessionCommandsMixin:
)
except asyncio.TimeoutError:
logger.warning(
- "Agent resource cleanup for session %s exceeded %ss during "
- "/new reset; proceeding with reset (the worker thread is left "
- "to finish on its own). (#35994)",
+ "Agent resource cleanup for session %s exceeded %ss during /new reset; proceeding with "
+ "reset (the worker thread is left to finish on its own). (#35994)",
session_key, _RESET_CLEANUP_TIMEOUT_S,
)
except Exception as cleanup_exc:
logger.warning(
- "Agent resource cleanup for session %s failed during /new "
- "reset: %s (#35994)",
+ "Agent resource cleanup for session %s failed during /new reset: %s (#35994)",
session_key, cleanup_exc,
)
@@ -483,7 +481,7 @@ class GatewaySessionCommandsMixin:
if raw_args:
try:
n = max(1, int(raw_args.split()[0]))
- except (ValueError, IndexError):
+ except ValueError:
return t("gateway.undo.invalid_count", arg=raw_args.split()[0])
session_entry = await self.async_session_store.get_or_create_session(source)
result = await self.async_session_store.rewind_session(session_entry.session_id, n)
@@ -496,10 +494,7 @@ class GatewaySessionCommandsMixin:
logger.debug("undo: cached-agent eviction skipped: %s", e)
target_text = result["target_text"]
preview = target_text[:200] + "..." if len(target_text) > 200 else target_text
- return t(
- "gateway.undo.removed", turns=result["turns_undone"], count=result["rewound_count"],
- preview=preview,
- )
+ return t("gateway.undo.removed", turns=result["turns_undone"], count=result["rewound_count"], preview=preview)
# --------------------------------------------------------------------- /compress
@@ -522,10 +517,9 @@ class GatewaySessionCommandsMixin:
agent = self._cached_agent_for(session_key)
if agent is None or agent is _AGENT_PENDING_SENTINEL or getattr(agent, "_codex_session", None) is None:
return (
- "πŸ—œοΈ Nothing to compact: this session runs on the Codex "
- "app-server runtime, whose context lives in a Codex-owned "
- "thread that only exists while the agent is active. Send a "
- "message first, then /compress β€” or /reset to start fresh."
+ "πŸ—œοΈ Nothing to compact: this session runs on the Codex app-server runtime, whose "
+ "context lives in a Codex-owned thread that only exists while the agent is active. "
+ "Send a message first, then /compress β€” or /reset to start fresh."
)
compressor = getattr(agent, "context_compressor", None)
count_before = getattr(compressor, "compression_count", 0)
@@ -535,14 +529,12 @@ class GatewaySessionCommandsMixin:
return t("gateway.compress.failed", error=exc)
if getattr(compressor, "compression_count", 0) > count_before:
return (
- "πŸ—œοΈ Codex app-server thread compacted (thread/compact). "
- "The transcript mirror is unchanged by design β€” the "
- "app-server now carries the compacted context."
+ "πŸ—œοΈ Codex app-server thread compacted (thread/compact). The transcript mirror is "
+ "unchanged by design β€” the app-server now carries the compacted context."
)
return (
- "⚠️ Codex app-server compaction did not complete β€” the thread "
- "is unchanged. Check the app-server logs, retry /compress, or "
- "/reset for a clean session."
+ "⚠️ Codex app-server compaction did not complete β€” the thread is unchanged. Check the "
+ "app-server logs, retry /compress, or /reset for a clean session."
)
async def _handle_compress_command_inner(self, event: MessageEvent) -> str:
@@ -669,12 +661,9 @@ class GatewaySessionCommandsMixin:
session_row = await get_session(session_id)
except Exception as exc:
logger.warning(
- "Manual compression could not restore the system prompt "
- "for session %s: %s. Preserving an empty prompt so the "
- "live turn rebuilds it with its configured providers.",
- session_id,
- exc,
- exc_info=True,
+ "Manual compression could not restore the system prompt for session %s: %s. "
+ "Preserving an empty prompt so the live turn rebuilds it with its configured "
+ "providers.", session_id, exc, exc_info=True,
)
# compression.checkpoint_required needs the memory provider loaded so _compress_context()
@@ -718,10 +707,8 @@ class GatewaySessionCommandsMixin:
)
elif not getattr(tmp_agent, "_last_compaction_in_place", False):
logger.warning(
- "Manual /compress: session rotation did not occur "
- "(session_id unchanged) and in-place mode is off β€” "
- "preserving original transcript instead of overwriting "
- "it (#44794)."
+ "Manual /compress: session rotation did not occur (session_id unchanged) and in-place "
+ "mode is off β€” preserving original transcript instead of overwriting it (#44794)."
)
await self.async_session_store.update_session(session_entry.session_key, last_prompt_tokens=0)
@@ -1069,10 +1056,7 @@ class GatewaySessionCommandsMixin:
cross_origin = include_all and self._resume_caller_is_admin(source)
scope_notice = None
if include_all and not cross_origin:
- scope_notice = (
- "_Note: `all` (cross-chat listing) requires a configured admin; "
- "showing this chat's sessions only._"
- )
+ scope_notice = "_Note: `all` (cross-chat listing) requires a configured admin; showing this chat's sessions only._"
current_entry = await self.async_session_store.get_or_create_session(source)
rows = await asyncio.to_thread(
query_session_listing,
@@ -1095,9 +1079,7 @@ class GatewaySessionCommandsMixin:
title = f"Sessions matching β€œ{search_query}”"
else:
title = "Sessions" if include_unnamed else "Named Sessions"
- return format_gateway_session_listing(
- rows, include_source=cross_origin, title=title, notice=scope_notice,
- )
+ return format_gateway_session_listing(rows, include_source=cross_origin, title=title, notice=scope_notice)
# ----------------------------------------------------------------------- /branch