Skip to content

The agent that grows with you

refactor(gateway): final compaction of insights/topup/platform/stop/restart bodies

Teknium08c7fb813f38
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index bc3c2f4ce0a..51fb8c71a0f 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -48,10 +48,8 @@ _ROLLBACK_SKIP_LINES = (
# /busy input modes -> (status-card behavior, set-confirmation behavior).
_BUSY_MODE_BEHAVIOR = {
"queue": ("queues for next turn", "Messages will be queued for the next turn while Hermes is busy."),
- "steer": (
- "steers into current run (after next tool call)",
- "Messages will be steered into the current run (after the next tool call).",
- ),
+ "steer": ("steers into current run (after next tool call)",
+ "Messages will be steered into the current run (after the next tool call)."),
"interrupt": ("interrupts current run", "Messages will interrupt the current run while Hermes is busy."),
}
@@ -64,10 +62,8 @@ _DIFF_MODE_BY_ARG = {
# /voice subcommand -> stored mode (None = auto-TTS disabled), confirmation i18n key.
_VOICE_MODE_BY_ARG = {
- "on": ("voice_only", "gateway.voice.enabled_voice_only"),
- "enable": ("voice_only", "gateway.voice.enabled_voice_only"),
- "off": ("off", "gateway.voice.disabled_text"),
- "disable": ("off", "gateway.voice.disabled_text"),
+ **dict.fromkeys(("on", "enable"), ("voice_only", "gateway.voice.enabled_voice_only")),
+ **dict.fromkeys(("off", "disable"), ("off", "gateway.voice.disabled_text")),
"tts": ("all", "gateway.voice.tts_enabled"),
}
@@ -103,12 +99,11 @@ with open(exit_code_path, "w", encoding="utf-8") as f:
def _nested_dict(root: dict, *keys: str) -> dict:
"""Walk/create ``root[k1][k2]...`` as dicts, replacing any non-dict value on the path."""
- current = root
for k in keys:
- if not isinstance(current.get(k), dict):
- current[k] = {}
- current = current[k]
- return current
+ if not isinstance(root.get(k), dict):
+ root[k] = {}
+ root = root[k]
+ return root
def _preview(text: str, limit: int = 60) -> str:
@@ -453,13 +448,11 @@ class GatewaySlashCommandsMixin(
key, source, interrupt_reason=_INTERRUPT_REASON_STOP, invalidation_reason=invalidation_reason,
)
agent = self._running_agents.get(session_key)
- if agent is _AGENT_PENDING_SENTINEL:
- # Force-clean the sentinel so the session is unlocked.
+ if agent is _AGENT_PENDING_SENTINEL: # force-clean the sentinel so the session is unlocked
await _stop(session_key, "stop_command_pending")
logger.info("STOP (pending) for session %s — sentinel cleared", session_key)
return EphemeralReply(t("gateway.stop.stopped_pending"))
- if agent:
- # Force-clean the session lock so a truly hung agent doesn't keep it locked forever.
+ if agent: # force-clean the session lock so a truly hung agent doesn't keep it forever
await _stop(session_key, "stop_command_handler")
return EphemeralReply(t("gateway.stop.stopped"))
@@ -490,9 +483,8 @@ class GatewaySlashCommandsMixin(
async def _handle_platform_command(self, event: MessageEvent) -> str:
"""Handle ``/platform list|pause|resume [name]`` — inspect and manually control failed/paused
adapters (pause stops the reconnect watcher; resume re-queues for retry)."""
- text = (getattr(event, "content", "") or "").strip()
# Strip the leading "/platform" (or "/PLATFORM") token if present
- parts = text.split(maxsplit=2)
+ parts = (getattr(event, "content", "") or "").strip().split(maxsplit=2)
if parts and parts[0].lower().lstrip("/").startswith("platform"):
parts = parts[1:]
action = (parts[0] if parts else "list").lower()
@@ -549,9 +541,7 @@ class GatewaySlashCommandsMixin(
return ""
if self._restart_requested or self._draining:
count = self._running_agent_count()
- if count:
- return t("gateway.draining", count=count)
- return EphemeralReply(t("gateway.restart.in_progress"))
+ return t("gateway.draining", count=count) if count else EphemeralReply(t("gateway.restart.in_progress"))
async def _write_marker(name: str, build, label: str) -> None:
try:
diff --git a/gateway/slash_commands_status.py b/gateway/slash_commands_status.py
index fc43adb352c..1d22f1cb2cd 100644
--- a/gateway/slash_commands_status.py
+++ b/gateway/slash_commands_status.py
@@ -300,14 +300,12 @@ class GatewayStatusCommandsMixin:
source = event.source
session_entry = await self.async_session_store.get_or_create_session(source)
expanded = event.get_command_args().strip().lower() in {"all", "full", "details"}
-
# Running agent first (mid-turn), then cached agent (between turns).
agent = self._resident_agent_for(self._session_key_for_source(source)) or None
ctx = getattr(agent, "context_compressor", None) if agent else None
used, context_length, model_name = await self._resolve_context_figures(
agent, ctx, session_entry, source
)
-
# Gauge path: real current-context figure
if used > 0 and context_length > 0:
pct = _pct(used, context_length)
@@ -322,19 +320,13 @@ class GatewayStatusCommandsMixin:
"",
]
# Full view — compression / throughput need the live agent.
- if ctx is not None:
- lines.extend(_context_compressor_lines(agent, ctx, used))
- else:
- lines.append(t("gateway.context.detail_after_first"))
+ lines += _context_compressor_lines(agent, ctx, used) if ctx is not None else [
+ t("gateway.context.detail_after_first")]
# Per-category estimated breakdown (+ optional expanded listings). Same chars/4 engine
# the desktop popover and /usage use; plain text (monospace isn't guaranteed on
# messaging platforms). Fail-open: rendering errors never break /context.
- if agent:
- breakdown = await asyncio.to_thread(self._context_breakdown_block, agent, source, expanded)
- if breakdown:
- lines += [""] + breakdown
- return "\n".join(lines)
-
+ breakdown = await asyncio.to_thread(self._context_breakdown_block, agent, source, expanded) if agent else []
+ return "\n".join(lines + ([""] + breakdown if breakdown else []))
# Last resort: rough estimate from transcript
history = await self.async_session_store.load_transcript(session_entry.session_id)
if not history:
@@ -434,10 +426,8 @@ class GatewayStatusCommandsMixin:
view = await _quiet(lambda: asyncio.to_thread(build_credits_view, markdown=True))
if view is None or not view.logged_in:
return t("gateway.credits.not_logged_in")
-
# Drop the helper's 📈 header; we print our own.
- lines = ["💳 **Nous balance**"]
- lines += [ln for ln in view.balance_lines if not ln.lstrip().startswith("📈")]
+ lines = ["💳 **Nous balance**"] + [ln for ln in view.balance_lines if not ln.lstrip().startswith("📈")]
if view.identity_line:
lines += ["", view.identity_line]
if view.topup_url:
@@ -572,15 +562,14 @@ class GatewayStatusCommandsMixin:
persisted = await self._session_db.get_session(entry.session_id) or {}
route = await self._session_db.get_dominant_session_model_route(entry.session_id)
return persisted, route if isinstance(route, dict) else {}
- persisted, persisted_route = await _quiet(_rows, ({}, {}))
- row = persisted_route if persisted_route.get("billing_provider") else persisted
+ persisted, dominant = await _quiet(_rows, ({}, {}))
+ row = dominant if dominant.get("billing_provider") else persisted
return row.get("billing_provider"), row.get("billing_base_url")
async def _handle_insights_command(self, event: MessageEvent) -> str:
"""Handle /insights [N | --days N] [--source S] -- usage insights and analytics."""
# Normalize Unicode dashes (Telegram/iOS auto-converts -- to em/en dash)
args = re.sub(r'[\u2012\u2013\u2014\u2015](days|source)', r'--\1', event.get_command_args().strip())
-
days, source = 30, None
parts = args.split()
i = 0
@@ -595,10 +584,8 @@ class GatewayStatusCommandsMixin:
elif flag == "--source" and value is not None:
source, i = value, i + 2
else:
- if flag.isdigit():
- days = int(flag)
+ days = int(flag) if flag.isdigit() else days
i += 1
-
try:
from hermes_state import get_shared_session_db
from agent.insights import InsightsEngine