The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(signal): drop core wiring
Tekniumf33b80d717ad
diff --git a/gateway/run.py b/gateway/run.pyindex 8e0baf76c3e..59304603ef0 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -3319,8 +3319,6 @@ def _builtin_adapter_import(module: str, adapter_name: str, requirement: str):# platform -> (module, adapter class, requirements probe, warning on probe failure)._BUILTIN_ADAPTERS: dict[Platform, tuple[str, str, str, str]] = {- Platform.SIGNAL: ("signal", "SignalAdapter", "check_signal_requirements",- "Signal: runtime requirements not met"),Platform.WEIXIN: ("weixin", "WeixinAdapter", "check_weixin_requirements","Weixin: aiohttp/cryptography not installed"),Platform.API_SERVER: ("api_server", "APIServerAdapter", "check_api_server_requirements",@@ -3345,11 +3343,6 @@ def _instantiate_builtin_adapter(platform: Platform, config: Any) -> Optional[Baif not (requirements_ok() if callable(requirements_ok) else requirements_ok):logger.warning(warning)return None- if platform == Platform.SIGNAL:- from gateway.platforms.signal import validate_signal_config- if not validate_signal_config(config):- logger.warning("Signal: SIGNAL_HTTP_URL or SIGNAL_ACCOUNT not configured")- return Nonereturn adapter_cls(config)diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 5a952c3d291..827ac3a887d 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -4663,8 +4663,6 @@ from hermes_cli.gateway_setup_wizard import (_WEIXIN_GROUP_NOTE,_setup_weixin,_setup_qqbot,- _signal_line_input,- _setup_signal,_builtin_setup_fn,_configure_platform,_wizard_offer_service_action,diff --git a/hermes_cli/gateway_setup_wizard.py b/hermes_cli/gateway_setup_wizard.pyindex cf3ed63a9ab..9693010c22a 100644--- a/hermes_cli/gateway_setup_wizard.py+++ b/hermes_cli/gateway_setup_wizard.py@@ -49,7 +49,6 @@ _PLATFORMS = ["help": "off = flat channel messages, thread = replies nest under your message."},],},- {"key": "signal", "label": "Signal", "emoji": "π‘", "token_var": "SIGNAL_HTTP_URL"},{"key": "weixin", "label": "Weixin / WeChat", "emoji": "π¬", "token_var": "WEIXIN_ACCOUNT_ID"},{"key": "qqbot", "label": "QQ Bot", "emoji": "π§", "token_var": "QQ_APP_ID",@@ -142,7 +141,7 @@ def _platform_status(platform: dict) -> str:if not token_var:return "not configured"# Built-ins needing a second credential to count as fully configured.- second_var = {"signal": "SIGNAL_ACCOUNT", "weixin": "WEIXIN_TOKEN"}.get(platform.get("key"))+ second_var = {"weixin": "WEIXIN_TOKEN"}.get(platform.get("key"))present = [bool(_gw().get_env_value(v)) for v in (token_var, second_var) if v]if all(present):return "configured"@@ -564,116 +563,12 @@ def _setup_qqbot():_gw().print_info(f" App ID: {credentials['app_id']}")-def _signal_line_input(prompt_text: str) -> str | None:- """``line_input`` for the Signal wizard; None (after printing the cancel line) on EOF/Ctrl+C."""- try:- return _gw().line_input(prompt_text).strip()- except (EOFError, KeyboardInterrupt):- print("\n Setup cancelled.")- return None---def _setup_signal():- """Interactive setup for Signal messenger."""- _print_setup_header("π‘ Signal")-- existing_url = _gw().get_env_value("SIGNAL_HTTP_URL")- existing_account = _gw().get_env_value("SIGNAL_ACCOUNT")- if not _confirm_reconfigure("Signal", "SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"):- return-- print()- if shutil.which("signal-cli"):- _gw().print_success("signal-cli found on PATH.")- else:- _gw().print_warning("signal-cli not found on PATH.")- _gw()._print_info_lines(- " Signal requires signal-cli running as an HTTP daemon.", " Install options:",- " Linux: download from https://github.com/AsamK/signal-cli/releases",- " macOS: brew install signal-cli", " Docker: bbernhard/signal-cli-rest-api",- )- print()- _gw()._print_info_lines(- " After installing, link your account and start the daemon:",- ' signal-cli link -n "HermesAgent"',- " signal-cli --account +YOURNUMBER daemon --http 127.0.0.1:8080",- )- print()-- print()- _gw().print_info(" Enter the URL where signal-cli HTTP daemon is running.")- default_url = existing_url or "http://127.0.0.1:8080"- url = _signal_line_input(f" HTTP URL [{default_url}]: ")- if url is None:- return- url = url or default_url-- _gw().print_info(" Testing connection...")- try:- import httpx- resp = httpx.get(f"{url.rstrip('/')}/api/v1/check", timeout=10.0)- if resp.status_code == 200:- _gw().print_success(" signal-cli daemon is reachable!")- else:- _gw().print_warning(f" signal-cli responded with status {resp.status_code}.")- if not _gw().prompt_yes_no(" Continue anyway?", False):- return- except Exception as e:- _gw().print_warning(f" Could not reach signal-cli at {url}: {e}")- if not _gw().prompt_yes_no(" Save this URL anyway? (you can start signal-cli later)", True):- return-- _gw().save_env_value("SIGNAL_HTTP_URL", url)-- print()- _gw()._print_info_lines(" Enter your Signal account phone number in E.164 format.", " Example: +15551234567")- default_account = existing_account or ""- account = _signal_line_input(f" Account number{f' [{default_account}]' if default_account else ''}: ")- if account is None:- return- account = account or default_account- if not account:- _gw().print_error(" Account number is required.")- return-- _gw().save_env_value("SIGNAL_ACCOUNT", account)-- print()- _gw()._print_info_lines(- " The gateway DENIES all users by default for security.",- " Enter phone numbers or UUIDs of allowed users (comma-separated).",- )- default_allowed = _gw().get_env_value("SIGNAL_ALLOWED_USERS") or account- allowed = _signal_line_input(f" Allowed users [{default_allowed}]: ")- if allowed is None:- return- _gw().save_env_value("SIGNAL_ALLOWED_USERS", allowed or default_allowed)-- print()- if _gw().prompt_yes_no(" Enable group messaging? (disabled by default for security)", False):- print()- _gw().print_info(" Enter group IDs to allow, or * for all groups.")- existing_groups = _gw().get_env_value("SIGNAL_GROUP_ALLOWED_USERS") or ""- groups = _signal_line_input(f" Group IDs [{existing_groups or '*'}]: ")- if groups is None:- return- _gw().save_env_value("SIGNAL_GROUP_ALLOWED_USERS", groups or existing_groups or "*")-- print()- _gw().print_success("Signal configured!")- _gw()._print_info_lines(- f" URL: {url}", f" Account: {account}", " DM auth: via SIGNAL_ALLOWED_USERS + DM pairing",- f" Groups: {'enabled' if _gw().get_env_value('SIGNAL_GROUP_ALLOWED_USERS') else 'disabled'}",- )--def _builtin_setup_fn(key: str):"""Resolve a built-in platform's setup function; late-bound to dodge the hermes_cli.setup cycle."""from hermes_cli import setup as _sreturn {# telegram/discord/slack/whatsapp/dingtalk/feishu/wecom setup_fns come from their plugins."webhooks": _gw().setup_platforms._setup_webhooks,- "signal": _setup_signal,"weixin": _setup_weixin,"qqbot": _setup_qqbot,}.get(key)diff --git a/tools/send_message_senders.py b/tools/send_message_senders.pyindex 368c93f6c66..17306c18e38 100644--- a/tools/send_message_senders.py+++ b/tools/send_message_senders.py@@ -408,116 +408,6 @@ async def _resolve_slack_user_target(token, chat_id):return None, _error(f"Slack DM resolution failed: {e}")-async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batch_message):- """One Signal batch under the scheduler with rate-limit retries: None on success, False when- retries were exhausted (batch lost), error dict for a non-rate-limit RPC error."""- n, max_attempts = len(att_batch), rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS- for attempt in range(1, max_attempts + 1):- try:- await scheduler.acquire(n)- _rpc_t0 = time.monotonic()- data = await post(att_batch, batch_message)- if "error" not in data:- await scheduler.report_rpc_duration(time.monotonic() - _rpc_t0, n)- return None- err = data["error"]- if not rl._is_signal_rate_limit_error(err):- return _error(f"Signal RPC error on batch {idx + 1}/{n_batches}: {err}")- server_retry_after = rl._extract_retry_after_seconds(err)- scheduler.feedback(server_retry_after, n)- retry_after_label = f"{server_retry_after:.0f}s" if server_retry_after else "unknown"- if attempt >= max_attempts:- logger.error("Signal: rate-limit retries exhausted on batch %d/%d (%d attachments lost, "- "server retry_after=%s)", idx + 1, n_batches, n, retry_after_label)- return False- logger.warning("Signal: rate-limited on batch %d/%d (attempt %d/%d, server retry_after=%s); "- "scheduler will pace the retry",- idx + 1, n_batches, attempt, max_attempts, retry_after_label)- except Exception as e:- if attempt >= max_attempts:- logger.error("Signal: send error on batch %d/%d after %d attempts: %s",- idx + 1, n_batches, attempt, str(e))- return False- logger.warning("Signal: transient error on batch %d/%d (attempt %d/%d): %s; will retry",- idx + 1, n_batches, attempt, max_attempts, str(e))---async def _send_signal(extra, chat_id, message, media_files=None):- """signal-cli JSON-RPC send; attachments go in SIGNAL_MAX_ATTACHMENTS_PER_MSG batches metered- by the process-wide SignalAttachmentScheduler (shared with the gateway adapter's rate-limit state)."""- try:- import httpx- except ImportError:- return {"error": "httpx not installed"}- from gateway.platforms import signal_rate_limit as rl- from gateway.platforms.signal_format import markdown_to_signal- try:- http_url, account = extra.get("http_url", "http://127.0.0.1:8080").rstrip("/"), extra.get("account", "")- if not account:- return {"error": "Signal account not configured"}- valid_media = media_files or []- attachment_paths = []- for media_path, _is_voice in valid_media:- if os.path.exists(media_path):- attachment_paths.append(media_path)- else:- logger.warning("Signal media file not found, skipping: %s", media_path)- # No attachments still means one (text-only) batch; text rides on batch #0 only.- per_batch = rl.SIGNAL_MAX_ATTACHMENTS_PER_MSG- att_batches = [attachment_paths[i:i + per_batch] for i in range(0, len(attachment_paths), per_batch)] or [[]]- n_batches, (plain_text, text_styles) = len(att_batches), markdown_to_signal(message)- recipient = {"groupId": chat_id[6:]} if chat_id.startswith("group:") else {"recipient": [chat_id]}-- async def _rpc_send(text, *, id_prefix, timeout, attachments=None, styled=False):- params = {"account": account, "message": text, **recipient}- if styled and text and text_styles:- params["textStyle" if len(text_styles) == 1 else "textStyles"] = (- text_styles[0] if len(text_styles) == 1 else text_styles)- if attachments:- params["attachments"] = attachments- payload = {"jsonrpc": "2.0", "method": "send", "params": params,- "id": f"{id_prefix}_{int(time.time() * 1000)}"}- async with httpx.AsyncClient(timeout=timeout) as client:- return await client.post(f"{http_url}/api/v1/rpc", json=payload)-- async def _post(batch_attachments, batch_message):- resp = await _rpc_send(batch_message, id_prefix="send", attachments=batch_attachments, styled=True,- timeout=rl._signal_send_timeout(len(batch_attachments)))- resp.raise_for_status()- return resp.json()- scheduler = rl.get_scheduler()- logger.info("send_message Signal: scheduler state=%s, %d attachment(s) in %d batch(es)",- scheduler.state(), len(attachment_paths), n_batches)- failed_batches: list[int] = []- for idx, att_batch in enumerate(att_batches):- n = len(att_batch)- if n > 0 and (estimated := scheduler.estimate_wait(n)) >= rl.SIGNAL_BATCH_PACING_NOTICE_THRESHOLD:- # Best-effort one-shot RPC for a user-facing pacing notice.- try:- await _rpc_send(f"(More images coming β pausing ~{rl._format_wait(estimated)} "- f"for Signal rate limit, batch {idx + 1}/{n_batches}.)", id_prefix="notice", timeout=30.0)- except Exception as _e:- logger.warning("Signal: inline notice failed: %s", _e)- outcome = await _signal_send_batch(_post, scheduler, rl, idx, n_batches, att_batch,- plain_text if idx == 0 else "")- if outcome is False:- failed_batches.append(idx + 1)- elif outcome is not None:- return outcome- warnings = []- if len(attachment_paths) < len(valid_media):- warnings.append("Some media files were skipped (not found on disk)")- if failed_batches:- warnings.append(f"Signal rate-limited {len(failed_batches)} batch(es) "- f"(#{', #'.join(str(b) for b in failed_batches)})")- if failed_batches and len(failed_batches) == n_batches:- return _error(f"Signal: every batch ({n_batches}) hit rate limit; no attachments delivered")- # Result-safe chat identifier for tool transcripts/log consumers.- return _success("signal", "group:***" if str(chat_id).startswith("group:") else chat_id, warnings)- except Exception as e:- return _error(f"Signal send failed: {e}")--# "ephemeral connect (may re-init E2EE per send, see #46310)",async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None, thread_id=None):"""Matrix adapter send (native media preserved). Prefer the live gateway adapter's persistentdiff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex f5f4eb4e035..5f900911fc0 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -18,7 +18,7 @@ from tools.send_message_senders import (_AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _NO_DELIVERABLE, _VIDEO_EXTS, _VOICE_EXTS,_adapter_media_method, _error, _live_adapter, _media_caption_split, _plugin_standalone_sender,_registry_standalone_send, _resolve_slack_user_target, _sanitize_error_text,- _send_matrix_via_adapter, _send_qqbot, _send_signal, _send_telegram, _send_weixin, _send_yuanbao)+ _send_matrix_via_adapter, _send_qqbot, _send_telegram, _send_weixin, _send_yuanbao)from tools.registry import tool_error# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model tool@@ -603,15 +603,7 @@ async def _send_chunks(chunks, send_one):def _platform_max_length(platform):- """Chunking limit: Signal's adapter constant (its raw JSON-RPC path bypasses the adapter's- chunking), the registry's ``max_message_length`` for plugins, else None (no chunking)."""- from gateway.config import Platform- if platform == Platform.SIGNAL:- try:- from gateway.platforms.signal import MAX_MESSAGE_LENGTH- return MAX_MESSAGE_LENGTH- except ImportError:- return 8000+ """Chunking limit: the registry's ``max_message_length`` for plugins, else None (no chunking)."""try:from gateway.platform_registry import platform_registryentry = platform_registry.get(platform.value)@@ -625,7 +617,9 @@ def _platform_max_length(platform):# WhatsApp: Baileys /send-media). platform -> (error label, run discover_plugins first,# caption-capable, media_files sentinel for non-final chunks, forward force_document)_PLUGIN_STANDALONE_MEDIA = {"discord": ("Discord", False, True, [], False), "feishu": ("Feishu", True, False, None, False),- "slack": ("Slack", True, True, [], False), "whatsapp": ("WhatsApp", True, True, None, True)}+ "slack": ("Slack", True, True, [], False), "whatsapp": ("WhatsApp", True, True, None, True),+ # Signal: attachments ride the JSON-RPC param on the final chunk.+ "signal": ("Signal", True, False, [], False)}async def _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files, *, thread_id,@@ -661,14 +655,12 @@ def _via_adapter_route(p, pc, cid, chunk, media, tid, fd):# Native-media chunked routes for built-in platforms; media rides on the final chunk, non-final# chunks get the sentinel. platform -> (media required, sentinel, sender(platform, pconfig,# chat_id, chunk, media, thread_id, force_document)). Matrix: ALL sends use the native adapter-# (E2EE text). Signal: attachments ride the JSON-RPC param. Yuanbao / WeCom: media needs the+# (E2EE text). Yuanbao / WeCom: media needs the# running gateway. Slack text: live adapter (multi-workspace, ignored_channels gates) else the-# plugin's standalone sender. Names resolve at call time so tests can monkeypatch ``_send_signal``.+# plugin's standalone sender. Names resolve at call time so tests can monkeypatch the senders._CHUNKED_ROUTES = {"matrix": (False, [], lambda p, pc, cid, chunk, media, tid, fd: _send_matrix_via_adapter(pc, cid, chunk, media_files=media, thread_id=tid)),- "signal": (True, [], lambda p, pc, cid, chunk, media, tid, fd: _send_signal(- pc.extra, cid, chunk, media_files=media)),"yuanbao": (True, None, lambda p, pc, cid, chunk, media, tid, fd: _send_yuanbao(cid, chunk, media_files=media)),"slack": (False, [], _via_adapter_route),"wecom": (True, None, _via_adapter_route)}@@ -677,8 +669,7 @@ _CHUNKED_ROUTES = {# warning). Signature: (pconfig, chat_id, chunk, thread_id) -> result._TEXT_SENDERS = {**{name: partial(_registry_standalone_send, name)- for name in ("whatsapp", "email", "sms", "dingtalk", "feishu", "wecom")},- "signal": lambda pc, cid, chunk, tid: _send_signal(pc.extra, cid, chunk),+ for name in ("whatsapp", "email", "sms", "dingtalk", "feishu", "wecom", "signal")},"qqbot": lambda pc, cid, chunk, tid: _send_qqbot(pc, cid, chunk),"yuanbao": lambda pc, cid, chunk, tid: _send_yuanbao(cid, chunk)}