Skip to content

The agent that grows with you

refactor(mattermost,irc,raft): table-driven env seeding/optional-field validation, print_info loops, fold guard chains, compact layout

Tekniuma0ee3c76999a
diff --git a/plugins/platforms/irc/adapter.py b/plugins/platforms/irc/adapter.py
index 6eb46933cc5..f944c036cd5 100644
--- a/plugins/platforms/irc/adapter.py
+++ b/plugins/platforms/irc/adapter.py
@@ -128,7 +128,6 @@ class IRCAdapter(BasePlatformAdapter):
self.allowed_users: list = extra.get("allowed_users", [])
# IRC nicks are case-insensitive — normalise for lookups
self._allowed_users_lower: set = {u.lower() for u in self.allowed_users if isinstance(u, str)}
-
max_msg = extra.get("max_message_length")
if max_msg is None:
with contextlib.suppress(Exception):
@@ -295,14 +294,11 @@ class IRCAdapter(BasePlatformAdapter):
if params:
self._current_nick = params[0] # server may confirm our nick
elif command == "433": # ERR_NICKNAMEINUSE — retry: hermes_, hermes_1, hermes_2...
- base = self.nickname.rstrip("_0123456789")
suffix_match = re.search(r"_(\d+)$", self._current_nick)
if suffix_match:
- self._current_nick = f"{base}_{int(suffix_match.group(1)) + 1}"
- elif self._current_nick == self.nickname:
- self._current_nick = self.nickname + "_"
+ self._current_nick = f"{self.nickname.rstrip('_0123456789')}_{int(suffix_match.group(1)) + 1}"
else:
- self._current_nick = self.nickname + "_1"
+ self._current_nick = self.nickname + ("_" if self._current_nick == self.nickname else "_1")
await self._send_raw(f"NICK {self._current_nick}")
elif command == "PRIVMSG" and len(params) >= 2:
await self._handle_privmsg(_extract_nick(msg["prefix"]), params[0], params[1])
@@ -356,11 +352,9 @@ def validate_config(config) -> bool:
def interactive_setup() -> None:
- """Interactive `hermes gateway setup` flow (lazy-imports hermes_cli so the plugin imports in non-CLI contexts)."""
+ """`hermes gateway setup` flow (lazy hermes_cli imports keep the plugin importable outside the CLI)."""
from hermes_cli.setup import (
- prompt, prompt_yes_no, save_env_value, get_env_value,
- print_header, print_info, print_warning, print_success,
- )
+ prompt, prompt_yes_no, save_env_value, get_env_value, print_header, print_info, print_warning, print_success)
print_header("IRC")
existing_server = get_env_value("IRC_SERVER")
@@ -397,29 +391,28 @@ def interactive_setup() -> None:
elif get_env_value("IRC_PORT"):
save_env_value("IRC_PORT", "") # user cleared the prompt; drop the override
- if not _required("Bot nickname (e.g. hermes-bot)", "IRC_NICKNAME", get_env_value("IRC_NICKNAME") or "", "Nickname"):
- return
- if not _required("Channel to join (e.g. #hermes — comma-separate for multiple)", "IRC_CHANNEL",
- get_env_value("IRC_CHANNEL") or "", "Channel"):
- return
+ for label, env, what in (("Bot nickname (e.g. hermes-bot)", "IRC_NICKNAME", "Nickname"),
+ ("Channel to join (e.g. #hermes — comma-separate for multiple)", "IRC_CHANNEL", "Channel")):
+ if not _required(label, env, get_env_value(env) or "", what):
+ return
print()
print_info("🔑 Optional authentication")
print_info(" Leave blank to skip.")
for question, label, env in (
("Configure a server password (PASS command)?", "Server password", "IRC_SERVER_PASSWORD"),
- ("Identify with NickServ on connect?", "NickServ password", "IRC_NICKSERV_PASSWORD"),
- ):
+ ("Identify with NickServ on connect?", "NickServ password", "IRC_NICKSERV_PASSWORD")):
if prompt_yes_no(question, False):
secret = prompt(label, password=True)
if secret:
save_env_value(env, secret)
print()
- print_info("🔒 Access control: restrict who can message the bot")
- print_info(" IRC nicks are not authenticated — anyone can claim any nick.")
- print_info(" For public channels, pair with NickServ-only mode on your network")
- print_info(" if you want stronger identity guarantees.")
+ for line in ("🔒 Access control: restrict who can message the bot",
+ " IRC nicks are not authenticated — anyone can claim any nick.",
+ " For public channels, pair with NickServ-only mode on your network",
+ " if you want stronger identity guarantees."):
+ print_info(line)
if prompt_yes_no("Allow all users in the channel to talk to the bot?", False):
save_env_value("IRC_ALLOW_ALL_USERS", "true")
save_env_value("IRC_ALLOWED_USERS", "")
@@ -446,23 +439,18 @@ def is_connected(config) -> bool:
def _env_enablement() -> dict | None:
- """Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction.
-
- Returns ``None`` when IRC isn't minimally configured (caller skips auto-enabling).
- The special ``home_channel`` key becomes a ``HomeChannel`` on the PlatformConfig.
- """
+ """Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction; ``None`` when IRC isn't
+ minimally configured (caller skips auto-enabling). ``home_channel`` becomes a ``HomeChannel``."""
server = _get_scoped_secret("IRC_SERVER", "").strip()
channel = _get_scoped_secret("IRC_CHANNEL", "").strip()
if not (server and channel):
return None
seed: dict = {"server": server, "channel": channel}
- if port := _get_scoped_secret("IRC_PORT", "").strip():
- with contextlib.suppress(ValueError):
- seed["port"] = int(port)
- if nickname := _get_scoped_secret("IRC_NICKNAME", "").strip():
- seed["nickname"] = nickname
- if use_tls := _get_scoped_secret("IRC_USE_TLS", "").strip().lower():
- seed["use_tls"] = use_tls in _TRUTHY
+ for env, key, conv in (("IRC_PORT", "port", int), ("IRC_NICKNAME", "nickname", str),
+ ("IRC_USE_TLS", "use_tls", lambda v: v.lower() in _TRUTHY)):
+ if raw := _get_scoped_secret(env, "").strip():
+ with contextlib.suppress(ValueError): # non-numeric IRC_PORT is dropped, not fatal
+ seed[key] = conv(raw)
# Passwords also live in extra for back-compat with config.yaml users; env wins at construct time.
for env, key in (("IRC_SERVER_PASSWORD", "server_password"), ("IRC_NICKSERV_PASSWORD", "nickserv_password")):
if _get_scoped_secret(env):
@@ -488,12 +476,9 @@ def _sa_error(detail: str) -> Dict[str, Any]:
async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Optional[str] = None,
media_files: Optional[List[str]] = None, force_document: bool = False) -> Dict[str, Any]:
- """Open an ephemeral IRC connection, send a PRIVMSG, and quit (out-of-process cron delivery).
-
- Used by ``tools/send_message_tool._send_via_adapter`` when the gateway isn't in this process.
- Uses a distinct ``-cron`` nick so it never collides with the live gateway adapter.
- ``thread_id``/``media_files`` are accepted for signature parity only.
- """
+ """Open an ephemeral IRC connection, send a PRIVMSG, and quit (out-of-process cron delivery via
+ ``send_message_tool``). Uses a distinct ``-cron`` nick so it never collides with the live gateway adapter.
+ ``thread_id``/``media_files`` are accepted for signature parity only."""
extra = getattr(pconfig, "extra", {}) or {}
server, channel = _server_channel(pconfig)
if not server or not channel:
@@ -576,12 +561,10 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
await _raw(f"NICK {standalone_nick}")
await _raw(f"USER {standalone_nick} 0 * :Hermes Agent (cron)")
registered = await _pump(loop.time() + 15.0, _on_registration)
- if registered is None:
- return _sa_error("registration timeout (no RPL_WELCOME)")
- if registered is _EOF:
- return _sa_error("server closed connection during registration")
if registered is not True:
- return registered
+ if registered is None:
+ return _sa_error("registration timeout (no RPL_WELCOME)")
+ return _sa_error("server closed connection during registration") if registered is _EOF else registered
if nickserv_password:
await _raw(f"PRIVMSG NickServ :IDENTIFY {_strip_irc_control_chars(nickserv_password)}")
await asyncio.sleep(2)
@@ -643,6 +626,4 @@ def register(ctx):
"— use plain text only. Messages are limited to ~450 characters per "
"line (long messages are automatically split). In channels, users "
"address you by prefixing your nick. Keep responses concise and "
- "conversational."
- ),
- )
+ "conversational."))
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index c301a353c1f..15fbba039ea 100644
--- a/plugins/platforms/mattermost/adapter.py
+++ b/plugins/platforms/mattermost/adapter.py
@@ -13,9 +13,11 @@ import asyncio
import contextlib
import json
import logging
+import mimetypes
import os
import re
from pathlib import Path
+from urllib.parse import unquote as _unquote
from typing import Any, Dict, List, Optional, Tuple
from gateway.config import Platform, PlatformConfig
@@ -88,12 +90,10 @@ def check_mattermost_requirements() -> bool:
def validate_mattermost_config(config: PlatformConfig) -> bool:
"""Return True when Mattermost has enough config to connect."""
extra = getattr(config, "extra", {}) or {}
- token = (getattr(config, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip()
- url = (extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).strip()
- if not token:
+ if not (getattr(config, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip():
logger.debug("Mattermost: MATTERMOST_TOKEN not set")
return False
- if not url:
+ if not (extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).strip():
logger.warning("Mattermost: MATTERMOST_URL not set")
return False
return True
@@ -117,8 +117,7 @@ class MattermostAdapter(BasePlatformAdapter):
self._closing = False
# Reply mode: "thread" to nest replies, "off" for flat messages.
self._reply_mode: str = (
- config.extra.get("reply_mode", "") or _get_scoped_secret("MATTERMOST_REPLY_MODE", "off")
- ).lower()
+ config.extra.get("reply_mode", "") or _get_scoped_secret("MATTERMOST_REPLY_MODE", "off")).lower()
self._last_post_status: Optional[int] = None
self._last_post_error: str = ""
self._dedup = MessageDeduplicator()
@@ -182,22 +181,15 @@ class MattermostAdapter(BasePlatformAdapter):
return rootish and broken
async def _post_preserving_thread(
- self, chat_id: str, payload: Dict[str, Any], metadata: _Metadata
- ) -> Dict[str, Any]:
+ self, chat_id: str, payload: Dict[str, Any], metadata: _Metadata) -> Dict[str, Any]:
"""Post once, optionally falling back flat for final notify content."""
data = await self._api_post("posts", payload)
- if data or "root_id" not in payload:
- return data
- if not (isinstance(metadata, dict) and metadata.get("notify")):
- return data
- if not self._last_post_failure_is_broken_thread_root():
+ if (data or "root_id" not in payload or not (isinstance(metadata, dict) and metadata.get("notify"))
+ or not self._last_post_failure_is_broken_thread_root()):
return data
- flat_payload = dict(payload)
- flat_payload.pop("root_id", None)
- original = str(flat_payload.get("message") or "")
- flat_payload["message"] = (
- "⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n" + original
- ).strip()
+ flat_payload = {k: v for k, v in payload.items() if k != "root_id"}
+ flat_payload["message"] = ("⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n"
+ + str(flat_payload.get("message") or "")).strip()
logger.warning("Mattermost: falling back to flat channel delivery for notify-worthy post in %s", chat_id)
return await self._api_post("posts", flat_payload)
@@ -266,8 +258,7 @@ class MattermostAdapter(BasePlatformAdapter):
self._bot_user_id = me["id"]
self._bot_username = me.get("username", "")
logger.info(
- "Mattermost: authenticated as @%s (%s) on %s", self._bot_username, self._bot_user_id, self._base_url
- )
+ "Mattermost: authenticated as @%s (%s) on %s", self._bot_username, self._bot_user_id, self._base_url)
self._ws_task = asyncio.create_task(self._ws_loop())
self._mark_connected()
@@ -297,8 +288,7 @@ class MattermostAdapter(BasePlatformAdapter):
return data["root_id"] if data and data.get("root_id") else post_id
async def send(
- self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: _Metadata = None
- ) -> SendResult:
+ self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: _Metadata = None) -> SendResult:
"""Send a message (or multiple chunks) to a channel."""
if not content:
return SendResult(success=True)
@@ -396,10 +386,6 @@ class MattermostAdapter(BasePlatformAdapter):
logger.warning("Mattermost: failed to download %s after %d attempts: %s", url, attempt + 1, exc)
return await fallback()
- if file_data is None:
- logger.warning("Mattermost: download returned no data for %s", url)
- return await fallback()
-
file_id = await self._upload_file(chat_id, file_data, _url_filename(url, f"{kind}.png"), ct)
if not file_id:
return await fallback()
@@ -409,8 +395,6 @@ class MattermostAdapter(BasePlatformAdapter):
self, chat_id: str, file_path: str, caption: Optional[str], reply_to: Optional[str],
file_name: Optional[str] = None, metadata: _Metadata = None) -> SendResult:
"""Upload a local file and attach it to a post."""
- import mimetypes
-
p = Path(file_path)
if not p.exists():
logger.warning("Mattermost: local file not found, skipping: %s", file_path)
@@ -425,9 +409,7 @@ class MattermostAdapter(BasePlatformAdapter):
async def _load_batch_image(self, image_url: str, index: int) -> Optional[Tuple[bytes, str, str]]:
"""Read a file:// or remote image for a batch post → (data, filename, content_type), or None to skip."""
- import mimetypes
import aiohttp
- from urllib.parse import unquote as _unquote
if image_url.startswith("file://"):
local_path = _unquote(image_url[7:])
@@ -505,9 +487,8 @@ class MattermostAdapter(BasePlatformAdapter):
except Exception as exc:
if self._closing:
return
- # Permanent auth/permission failure: escalate via the fatal-error hook (a bare
- # return would leave is_connected() healthy with a dead listener). Type-based
- # only — substring matching on "401" misclassified transient errors.
+ # Permanent auth failure: escalate via the fatal-error hook (a bare return leaves is_connected()
+ # healthy with a dead listener). Type-based: substring "401" matching misclassified transient errors.
import aiohttp
if isinstance(exc, aiohttp.WSServerHandshakeError) and exc.status in {401, 403}:
logger.error("Mattermost WS auth failed (HTTP %d) — stopping reconnect", exc.status)
@@ -598,12 +579,11 @@ class MattermostAdapter(BasePlatformAdapter):
continue
file_data = await resp.read()
if mime.startswith("image/"):
- local_path = cache_image_from_bytes(file_data, ext or ".png")
+ media_urls.append(cache_image_from_bytes(file_data, ext or ".png"))
elif mime.startswith("audio/"):
- local_path = cache_audio_from_bytes(file_data, ext or ".ogg")
+ media_urls.append(cache_audio_from_bytes(file_data, ext or ".ogg"))
else:
- local_path = cache_document_from_bytes(file_data, fname)
- media_urls.append(local_path)
+ media_urls.append(cache_document_from_bytes(file_data, fname))
media_types.append(mime)
except Exception as exc:
logger.warning("Mattermost: error downloading file %s: %s", fid, exc)
@@ -613,11 +593,8 @@ class MattermostAdapter(BasePlatformAdapter):
if event.get("event") != "posted":
return
data = event.get("data", {})
- raw_post_str = data.get("post")
- if not raw_post_str:
- return
try:
- post = json.loads(raw_post_str)
+ post = json.loads(data.get("post") or "")
except (json.JSONDecodeError, TypeError):
return
# Ignore own messages and system posts.
@@ -668,7 +645,6 @@ class MattermostAdapter(BasePlatformAdapter):
# --- Plugin standalone-send (out-of-process cron delivery via Mattermost REST) ---
-
async def _standalone_send(
pconfig, chat_id: str, message: str, *, thread_id: Optional[str] = None,
media_files: Optional[list] = None, force_document: bool = False) -> Dict[str, Any]:
@@ -734,7 +710,6 @@ async def _standalone_send(
# --- Interactive setup wizard ---
-
def interactive_setup() -> None:
"""Guide the user through Mattermost bot setup (URL + token, allowlist, home channel)."""
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
@@ -746,9 +721,9 @@ def interactive_setup() -> None:
if not prompt_yes_no("Reconfigure Mattermost?", False):
return
- print_info("Works with any self-hosted Mattermost instance.")
- print_info(" 1. In Mattermost: Integrations → Bot Accounts → Add Bot Account")
- print_info(" 2. Copy the bot token")
+ for line in ("Works with any self-hosted Mattermost instance.",
+ " 1. In Mattermost: Integrations → Bot Accounts → Add Bot Account", " 2. Copy the bot token"):
+ print_info(line)
print()
mm_url = prompt("Mattermost server URL (e.g. https://mm.example.com)")
if mm_url:
@@ -760,9 +735,9 @@ def interactive_setup() -> None:
print_success("Mattermost token saved")
print()
- print_info("🔒 Security: Restrict who can use your bot")
- print_info(" To find your user ID: click your avatar → Profile")
- print_info(" or use the API: GET /api/v4/users/me")
+ for line in ("🔒 Security: Restrict who can use your bot", " To find your user ID: click your avatar → Profile",
+ " or use the API: GET /api/v4/users/me"):
+ print_info(line)
print()
allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for open access)")
if allowed_users:
@@ -772,9 +747,10 @@ def interactive_setup() -> None:
print_info("⚠️ No allowlist set - anyone who can message the bot can use it!")
print()
- print_info("📬 Home Channel: where Hermes delivers cron job results and notifications.")
- print_info(" To get a channel ID: click channel name → View Info → copy the ID")
- print_info(" You can also set this later by typing /set-home in a Mattermost channel.")
+ for line in ("📬 Home Channel: where Hermes delivers cron job results and notifications.",
+ " To get a channel ID: click channel name → View Info → copy the ID",
+ " You can also set this later by typing /set-home in a Mattermost channel."):
+ print_info(line)
home_channel = prompt("Home channel ID (leave empty to set later with /set-home)").strip()
if home_channel:
save_env_value("MATTERMOST_HOME_CHANNEL", home_channel)
@@ -785,7 +761,6 @@ def interactive_setup() -> None:
# --- YAML → env config bridge (apply_yaml_config_fn) ---
-
def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
"""Translate ``config.yaml`` ``mattermost:`` keys into env vars + ``PlatformConfig.extra``.
@@ -825,7 +800,6 @@ def _is_connected(config) -> bool:
# --- Plugin registration entry point ---
-
def register(ctx) -> None:
"""Plugin entry point — called by the Hermes plugin system."""
ctx.register_platform(
diff --git a/plugins/platforms/raft/adapter.py b/plugins/platforms/raft/adapter.py
index 4ce70af2c62..6cc83d88606 100644
--- a/plugins/platforms/raft/adapter.py
+++ b/plugins/platforms/raft/adapter.py
@@ -58,16 +58,14 @@ _WAKE_ID_KEYS = ("eventId", "attemptId", "messageId", "delivery_id", "wake_id",
_WAKE_PROMPT = (
"Raft wake hint received. New Raft messages may be pending. "
"If you have not read the Raft manual in this session, run "
- "`raft manual get raft-cli-overview` before using Raft commands."
-)
+ "`raft manual get raft-cli-overview` before using Raft commands.")
_CONTENT_FIELD_NAMES = {"body", "content", "message", "messages", "preview", "snippet", "text"}
_SAFE_SCALAR_RE = re.compile(r"^[a-zA-Z0-9._:@/ -]+$")
_MAX_SCALAR_LENGTH = 120
_ACTIVITY_ALLOWED_FIELDS = set(
"schema eventId sessionId hookEventName status occurredAt toolName toolInput toolOutput "
- "toolInputTruncated toolOutputTruncated truncated errorClass durationMs".split()
-)
+ "toolInputTruncated toolOutputTruncated truncated errorClass durationMs".split())
_ACTIVE_ADAPTERS: "weakref.WeakSet[RaftAdapter]" = weakref.WeakSet()
_ACTIVE_ADAPTERS_LOCK = threading.Lock()
_RAFT_CONTEXT_LOCK = threading.Lock()
@@ -82,7 +80,6 @@ def _resolve_raft_profile() -> str:
if _profile_scoped():
try:
from agent.secret_scope import get_secret
-
return (get_secret("RAFT_PROFILE") or "").strip()
except Exception:
return ""
@@ -136,8 +133,7 @@ def _make_activity_event(
"sessionId": _safe_scalar(session_id, "unknown") or "unknown",
"hookEventName": hook_event_name,
"status": "error" if status == "error" else "ok",
- "occurredAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
- }
+ "occurredAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
for key, raw in (("toolName", tool_name), ("errorClass", error_class)):
safe = _safe_scalar(raw)
if safe:
@@ -158,6 +154,13 @@ def _make_activity_event(
return event
+_OPTIONAL_FIELD_RULES = ( # checked in this order; first failure wins
+ (("toolName", "errorClass"), _safe_scalar, "a safe string"),
+ (("durationMs",), lambda v: _duration_ms(v) is not None, "a non-negative number"),
+ (("truncated", "toolInputTruncated", "toolOutputTruncated"), lambda v: isinstance(v, bool), "a boolean"),
+)
+
+
def _validate_activity_event(value: Any) -> Dict[str, Any]:
if not isinstance(value, dict):
raise ValueError("activity event must be an object")
@@ -171,14 +174,10 @@ def _validate_activity_event(value: Any) -> Dict[str, Any]:
raise ValueError(f"activity event {key} must be a safe non-empty string")
if value.get("status") not in {"ok", "error"}:
raise ValueError("activity event status must be ok|error")
- for key in ("toolName", "errorClass"):
- if value.get(key) is not None and not _safe_scalar(value.get(key)):
- raise ValueError(f"activity event {key} must be a safe string")
- if value.get("durationMs") is not None and _duration_ms(value.get("durationMs")) is None:
- raise ValueError("activity event durationMs must be a non-negative number")
- for key in ("truncated", "toolInputTruncated", "toolOutputTruncated"):
- if value.get(key) is not None and not isinstance(value.get(key), bool):
- raise ValueError(f"activity event {key} must be a boolean")
+ for keys, ok, what in _OPTIONAL_FIELD_RULES: # optional fields: None passes, anything else must satisfy ``ok``
+ for key in keys:
+ if value.get(key) is not None and not ok(value.get(key)):
+ raise ValueError(f"activity event {key} must be {what}")
event = dict(value)
if event.get("durationMs") is not None:
event["durationMs"] = _duration_ms(event["durationMs"])
@@ -251,8 +250,7 @@ def _is_raft_context(**kwargs: Any) -> bool:
return True
return bool(
(safe_turn_id and safe_turn_id in _RAFT_TURN_IDS)
- or (safe_session_id and safe_session_id in _RAFT_SESSION_IDS)
- )
+ or (safe_session_id and safe_session_id in _RAFT_SESSION_IDS))
def _emit(hook_event_name: str, kwargs: Dict[str, Any], **fields: Any) -> None:
@@ -271,7 +269,6 @@ def _raft_hook(fn):
def wrapper(**kwargs: Any) -> None:
if _is_raft_context(**kwargs):
fn(**kwargs)
-
return wrapper
@@ -279,7 +276,6 @@ def _raft_hook(fn):
def _on_session_start(**kwargs: Any) -> None:
try:
from tools.env_passthrough import register_env_passthrough
-
register_env_passthrough(["RAFT_PROFILE"])
except Exception:
logger.debug("[raft] failed to register RAFT_PROFILE env passthrough", exc_info=True)
@@ -313,8 +309,7 @@ def _on_post_tool_call(**kwargs: Any) -> None:
tool_input=kwargs.get("args"),
tool_output=kwargs.get("error_message") or kwargs.get("result"),
error_class=kwargs.get("error_type") or ("tool_failure" if status == "error" else None),
- duration_ms=kwargs.get("duration_ms"),
- )
+ duration_ms=kwargs.get("duration_ms"))
@_raft_hook
@@ -417,8 +412,7 @@ class RaftAdapter(BasePlatformAdapter):
endpoint = f"http://{self._host}:{port}{self._path}"
cmd: List[str] = [
raft_bin, "--profile", profile, "agent", "bridge",
- "--wake-adapter", "wake-channel", "--wake-channel-endpoint", endpoint,
- ]
+ "--wake-adapter", "wake-channel", "--wake-channel-endpoint", endpoint]
env = {**os.environ, "RAFT_CHANNEL_TOKEN": self._bridge_token}
try:
self._bridge_process = subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL)
@@ -427,10 +421,9 @@ class RaftAdapter(BasePlatformAdapter):
logger.exception("[raft] Failed to spawn bridge")
def _stop_bridge(self) -> None:
- proc = self._bridge_process
+ proc, self._bridge_process = self._bridge_process, None
if proc is None:
return
- self._bridge_process = None
try:
proc.terminate()
proc.wait(timeout=5)
@@ -453,8 +446,7 @@ class RaftAdapter(BasePlatformAdapter):
async def _handle_health(self, request: "web.Request") -> "web.Response":
activity = {"queueSize": self._activity_queue.size, "endpoint": "/activity", "drainEndpoint": "/activity/drain"}
return web.json_response(
- {"status": "ok", "platform": "raft", "runtimeSession": self._runtime_session, "activity": activity}
- )
+ {"status": "ok", "platform": "raft", "runtimeSession": self._runtime_session, "activity": activity})
def _authorized(self, request: "web.Request") -> bool:
return self._validate_bridge_token(request.headers.get(BRIDGE_TOKEN_HEADER, ""))
@@ -497,16 +489,13 @@ class RaftAdapter(BasePlatformAdapter):
return web.json_response(not_ready, status=503)
delivery_id = str(
next((payload.get(k) for k in _WAKE_ID_KEYS if payload.get(k)), None)
- or f"raft-wake-{int(time.time() * 1000)}"
- )
+ or f"raft-wake-{int(time.time() * 1000)}")
source = self.build_source(
chat_id=self._runtime_session, chat_name="Raft channel", chat_type="dm",
- user_id="raft-bridge", user_name="Raft Bridge",
- )
+ user_id="raft-bridge", user_name="Raft Bridge")
event = MessageEvent(
text=_WAKE_PROMPT, message_type=MessageType.TEXT, source=source, raw_message=payload,
- message_id=delivery_id, internal=True,
- )
+ message_id=delivery_id, internal=True)
try:
await self.handle_message(event)
except Exception:
@@ -549,8 +538,7 @@ class RaftAdapter(BasePlatformAdapter):
event.source,
group_sessions_per_user=self.config.extra.get("group_sessions_per_user", True),
thread_sessions_per_user=self.config.extra.get("thread_sessions_per_user", False),
- profile=self._session_key_profile(event.source),
- )
+ profile=self._session_key_profile(event.source))
if session_key in self._active_sessions:
logger.debug("[raft] Wake queued for busy session %s", session_key)
merge_pending_message_event(self._pending_messages, session_key, event)
@@ -579,7 +567,6 @@ def interactive_setup() -> None:
CLI helpers are lazy-imported so the plugin stays importable in gateway runtime and tests."""
from hermes_cli.cli_output import print_header, print_info, print_success, print_warning, prompt, prompt_yes_no
from hermes_cli.config import get_env_value, save_env_value
-
print_header("Raft")
existing_profile = get_env_value("RAFT_PROFILE")
if existing_profile:
@@ -587,9 +574,9 @@ def interactive_setup() -> None:
if not prompt_yes_no("Reconfigure Raft?", False):
print_info(f"Keeping RAFT_PROFILE={existing_profile}.")
return
- print_info("Connect Hermes to Raft as an external agent.")
- print_info("Create the External Agent in Raft first, then run:")
- print_info(" raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>")
+ for line in ("Connect Hermes to Raft as an external agent.", "Create the External Agent in Raft first, then run:",
+ " raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>"):
+ print_info(line)
print()
profile = prompt("Raft profile slug", default=existing_profile or "")
if not profile:
@@ -621,12 +608,10 @@ def register(ctx) -> None:
"Run `raft --profile {profile} profile show` to confirm which agent profile is active. "
"Run `raft --profile {profile} manual get raft-cli-overview` to learn available Raft commands. "
"Always pass `--profile {profile}` to every raft CLI call."
- ).format(profile=_resolve_raft_profile() or "your-agent-profile"),
- )
+ ).format(profile=_resolve_raft_profile() or "your-agent-profile"))
for hook_name, callback in (
("on_session_start", _on_session_start), ("pre_llm_call", _on_pre_llm_call),
("pre_tool_call", _on_pre_tool_call), ("post_tool_call", _on_post_tool_call),
("post_llm_call", _on_post_llm_call), ("on_session_end", _on_session_end),
- ("on_session_finalize", _on_session_finalize),
- ):
+ ("on_session_finalize", _on_session_finalize)):
ctx.register_hook(hook_name, callback)