Skip to content

The agent that grows with you

refactor(signal): move Signal adapter into bundled platform plugin

Teknium527695851123
diff --git a/plugins/platforms/signal/__init__.py b/plugins/platforms/signal/__init__.py
new file mode 100644
index 00000000000..d4f1d7bf0e3
--- /dev/null
+++ b/plugins/platforms/signal/__init__.py
@@ -0,0 +1,3 @@
+from .adapter import register
+
+__all__ = ["register"]
diff --git a/gateway/platforms/signal.py b/plugins/platforms/signal/adapter.py
similarity index 96%
rename from gateway/platforms/signal.py
rename to plugins/platforms/signal/adapter.py
index 20673fbdc2d..1dca244483a 100644
--- a/gateway/platforms/signal.py
+++ b/plugins/platforms/signal/adapter.py
@@ -34,8 +34,8 @@ from gateway.platforms.helpers import redact_phone
from gateway.platforms.helpers import cancel_task
from gateway.platforms.media_cache import mime_for_ext
from tools.audio_container import CONTAINER_TO_EXT, sniff_container
-from gateway.platforms.signal_format import markdown_to_signal
-from gateway.platforms.signal_rate_limit import (
+from plugins.platforms.signal.signal_format import markdown_to_signal
+from plugins.platforms.signal.signal_rate_limit import (
SIGNAL_BATCH_PACING_NOTICE_THRESHOLD, SIGNAL_MAX_ATTACHMENTS_PER_MSG, SIGNAL_RATE_LIMIT_MAX_ATTEMPTS,
SignalRateLimitError, _extract_retry_after_seconds, _format_wait, _is_signal_rate_limit_error,
_signal_send_timeout, get_scheduler)
@@ -980,3 +980,37 @@ class SignalAdapter(BasePlatformAdapter):
result = await self._rpc("getContact", {"account": self.account, "contactAddress": chat_id})
name = (result.get("name") or result.get("profileName")) if isinstance(result, dict) else None
return {"name": name or chat_id, "type": "dm", "chat_id": chat_id}
+
+
+def _validate_config(config: PlatformConfig) -> bool:
+ """``validate_config``: same warning the core instantiation path logged before the move."""
+ if validate_signal_config(config):
+ return True
+ logger.warning("Signal: SIGNAL_HTTP_URL or SIGNAL_ACCOUNT not configured")
+ return False
+
+
+async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
+ from plugins.platforms.signal.standalone import standalone_send
+ return await standalone_send(pconfig, chat_id, message, thread_id=thread_id, media_files=media_files,
+ force_document=force_document)
+
+
+def _interactive_setup() -> None:
+ from plugins.platforms.signal.setup import interactive_setup
+ interactive_setup()
+
+
+def register(ctx) -> None:
+ """Plugin entry point — called by the Hermes plugin system."""
+ ctx.register_platform(
+ name="signal", label="Signal", adapter_factory=SignalAdapter,
+ check_fn=check_signal_requirements, validate_config=_validate_config,
+ is_connected=validate_signal_config, required_env=["SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"],
+ install_hint="Signal: runtime requirements not met", setup_fn=_interactive_setup,
+ allowed_users_env="SIGNAL_ALLOWED_USERS", allow_all_env="SIGNAL_ALLOW_ALL_USERS",
+ cron_deliver_env_var="SIGNAL_HOME_CHANNEL",
+ # Out-of-process sends speak raw JSON-RPC and bypass SignalAdapter.send()'s chunking, so
+ # send_message splits at the adapter's limit through this field.
+ standalone_sender_fn=_standalone_send, max_message_length=MAX_MESSAGE_LENGTH,
+ emoji="📡", pii_safe=True, allow_update_command=True)
diff --git a/plugins/platforms/signal/plugin.yaml b/plugins/platforms/signal/plugin.yaml
new file mode 100644
index 00000000000..019696f727e
--- /dev/null
+++ b/plugins/platforms/signal/plugin.yaml
@@ -0,0 +1,51 @@
+name: signal-platform
+label: Signal
+kind: platform
+version: 1.0.0
+description: >
+ Signal gateway adapter for Hermes Agent via a signal-cli daemon in HTTP
+ mode (SSE inbound, JSON-RPC 2.0 outbound). Supports DMs, allowlisted
+ groups, attachments, reactions and home-channel cron delivery. Phone
+ numbers are treated as PII in logs.
+author: NousResearch
+# ``requires_env`` / ``optional_env`` entries are surfaced in the ``hermes config`` UI via the
+# platform-plugin env var injector in ``hermes_cli/config.py``.
+requires_env:
+ - name: SIGNAL_HTTP_URL
+ description: "signal-cli HTTP daemon URL (e.g. http://127.0.0.1:8080)"
+ prompt: "signal-cli HTTP URL"
+ url: "https://github.com/AsamK/signal-cli"
+ password: false
+ - name: SIGNAL_ACCOUNT
+ description: "Signal account phone number in E.164 format (e.g. +15551234567)"
+ prompt: "Signal account number"
+ password: false
+optional_env:
+ - name: SIGNAL_ALLOWED_USERS
+ description: "Comma-separated phone numbers or UUIDs allowed to DM the bot"
+ prompt: "Allowed users (comma-separated)"
+ password: false
+ - name: SIGNAL_ALLOW_ALL_USERS
+ description: "Allow any Signal user to talk to the bot (dev only)"
+ prompt: "Allow all users? (true/false)"
+ password: false
+ - name: SIGNAL_GROUP_ALLOWED_USERS
+ description: "Comma-separated group IDs allowed to talk to the bot (* for all groups)"
+ prompt: "Allowed group IDs"
+ password: false
+ - name: SIGNAL_REQUIRE_MENTION
+ description: "Only answer group messages that mention the bot (true/false, default: false)"
+ prompt: "Require mention in groups? (true/false)"
+ password: false
+ - name: SIGNAL_IGNORE_STORIES
+ description: "Ignore Signal stories (true/false, default: true)"
+ prompt: "Ignore stories? (true/false)"
+ password: false
+ - name: SIGNAL_HOME_CHANNEL
+ description: "Default chat (phone number or group:<id>) for cron / notification delivery"
+ prompt: "Home channel"
+ password: false
+ - name: SIGNAL_HOME_CHANNEL_NAME
+ description: "Display name for the Signal home channel"
+ prompt: "Home channel name"
+ password: false
diff --git a/plugins/platforms/signal/setup.py b/plugins/platforms/signal/setup.py
new file mode 100644
index 00000000000..03146cc5ea4
--- /dev/null
+++ b/plugins/platforms/signal/setup.py
@@ -0,0 +1,113 @@
+"""Interactive ``hermes gateway setup`` wizard for Signal. Helpers resolve late through the
+``hermes_cli.gateway`` facade so the plugin stays importable outside the CLI and the seams tests
+patch there keep intercepting."""
+
+import shutil
+
+
+def _gw():
+ from hermes_cli import gateway # late: CLI-only dependency
+ return gateway
+
+
+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 interactive_setup() -> None:
+ """``hermes gateway setup`` flow for Signal (registered as the plugin's ``setup_fn``)."""
+ _gw()._print_setup_header("📡 Signal")
+
+ existing_url = _gw().get_env_value("SIGNAL_HTTP_URL")
+ existing_account = _gw().get_env_value("SIGNAL_ACCOUNT")
+ if not _gw()._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'}",
+ )
diff --git a/gateway/platforms/signal_format.py b/plugins/platforms/signal/signal_format.py
similarity index 100%
rename from gateway/platforms/signal_format.py
rename to plugins/platforms/signal/signal_format.py
diff --git a/gateway/platforms/signal_rate_limit.py b/plugins/platforms/signal/signal_rate_limit.py
similarity index 100%
rename from gateway/platforms/signal_rate_limit.py
rename to plugins/platforms/signal/signal_rate_limit.py
diff --git a/plugins/platforms/signal/standalone.py b/plugins/platforms/signal/standalone.py
new file mode 100644
index 00000000000..018b56bfdfc
--- /dev/null
+++ b/plugins/platforms/signal/standalone.py
@@ -0,0 +1,127 @@
+"""Out-of-process Signal send (cron / ``hermes send`` / send_message without a live gateway): raw
+signal-cli JSON-RPC with Signal formatting, attachment batching and the process-wide rate-limit
+scheduler shared with the gateway adapter. Wired as the plugin's ``standalone_sender_fn``."""
+
+import logging
+import os
+import time
+
+from plugins.platforms.signal import signal_rate_limit as rl
+from plugins.platforms.signal.signal_format import markdown_to_signal
+from tools.send_message_senders import _error, _success
+
+logger = logging.getLogger(__name__)
+
+
+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"}
+ 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}")
+
+
+async def standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
+ """``standalone_sender_fn``: attachments ride the JSON-RPC ``attachments`` param (thread_id and
+ force_document have no Signal equivalent)."""
+ return await _send_signal(getattr(pconfig, "extra", None) or {}, chat_id, message, media_files=media_files)
diff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.json
index 1b19ec5f8d6..6212baa0d15 100644
--- a/tests/fixtures/resolution_allowlist.json
+++ b/tests/fixtures/resolution_allowlist.json
@@ -84,11 +84,6 @@
"symbol": "transcode_to_ogg_opus",
"kind": "bare_which"
},
- {
- "path": "gateway/platforms/signal.py",
- "symbol": "_remux_aac_to_m4a",
- "kind": "bare_which"
- },
{
"path": "gateway/run.py",
"symbol": "_resolve_hermes_bin",
@@ -207,11 +202,6 @@
"symbol": "supports_systemd_services",
"kind": "bare_which"
},
- {
- "path": "hermes_cli/gateway_setup_wizard.py",
- "symbol": "_setup_signal",
- "kind": "bare_which"
- },
{
"path": "hermes_cli/gateway_windows.py",
"symbol": "_exec_schtasks",
diff --git a/tests/gateway/test_adapter_settings_profile_parity.py b/tests/gateway/test_adapter_settings_profile_parity.py
index 099260a59b3..88a273a9479 100644
--- a/tests/gateway/test_adapter_settings_profile_parity.py
+++ b/tests/gateway/test_adapter_settings_profile_parity.py
@@ -72,7 +72,7 @@ _SETTINGS = [
lambda m: m.FeishuAdapter._load_settings({}).connection_mode),
("plugins.platforms.bluebubbles.adapter", "BLUEBUBBLES_WEBHOOK_PORT", "18010", "18110",
lambda m: m._extra_or_secret({}, "webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", "0")),
- ("gateway.platforms.signal", "SIGNAL_REACTIONS", "true", "false",
+ ("plugins.platforms.signal.adapter", "SIGNAL_REACTIONS", "true", "false",
lambda m: _signal_reactions(m)),
("plugins.platforms.line.adapter", "LINE_PORT", "18015", "18115",
lambda m: (m._env_enablement() or {}).get("port")),
@@ -123,7 +123,7 @@ def test_served_secondary_resolves_its_own_setting(monkeypatch, module, var, def
def test_signal_startup_gate_reads_the_profile_env(monkeypatch):
"""A secondary whose SIGNAL_HTTP_URL/SIGNAL_ACCOUNT live only in its own .env must pass the startup
gate served exactly as it does standalone; a secondary WITHOUT them must not borrow the default's."""
- from gateway.platforms import signal as sig
+ from plugins.platforms.signal import adapter as sig
for k in ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"):
monkeypatch.delenv(k, raising=False)
ss.set_multiplex_active(True)
diff --git a/tests/gateway/test_native_producer_owner_matrix.py b/tests/gateway/test_native_producer_owner_matrix.py
index 395f0c8e715..d245732739a 100644
--- a/tests/gateway/test_native_producer_owner_matrix.py
+++ b/tests/gateway/test_native_producer_owner_matrix.py
@@ -80,7 +80,7 @@ async def test_slack_upload_failure_owner_scope_keeps_caption_and_result(owners,
@pytest.mark.asyncio
async def test_signal_pacing_owner_scope_keeps_acquisition_and_upload(owners, tmp_path, monkeypatch):
- import gateway.platforms.signal as module
+ import plugins.platforms.signal.adapter as module
root, suppressed = owners
adapter = module.SignalAdapter(PlatformConfig())
adapter.gateway_runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
diff --git a/tests/gateway/test_platform_authz_scope.py b/tests/gateway/test_platform_authz_scope.py
index 73d54d4499f..6e340c74bb9 100644
--- a/tests/gateway/test_platform_authz_scope.py
+++ b/tests/gateway/test_platform_authz_scope.py
@@ -57,7 +57,7 @@ def profile_scope():
[
("gateway.platforms.weixin", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
("gateway.platforms.yuanbao", "_yb_secret", "YUANBAO_DM_POLICY"),
- ("gateway.platforms.signal", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
+ ("plugins.platforms.signal.adapter", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret", "WECOM_ALLOWED_USERS"),
],
)
@@ -88,7 +88,7 @@ def multiplex_on(monkeypatch):
[
("gateway.platforms.weixin", "_wx_secret"),
("gateway.platforms.yuanbao", "_yb_secret"),
- ("gateway.platforms.signal", "_sig_secret"),
+ ("plugins.platforms.signal.adapter", "_sig_secret"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret"),
],
)
@@ -123,7 +123,7 @@ def test_helper_does_not_leak_default_env_into_scoped_miss(
[
("gateway.platforms.weixin", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
("gateway.platforms.yuanbao", "_yb_secret", "YUANBAO_DM_POLICY"),
- ("gateway.platforms.signal", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
+ ("plugins.platforms.signal.adapter", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret", "WECOM_ALLOWED_USERS"),
],
)
diff --git a/tests/gateway/test_signal.py b/tests/gateway/test_signal.py
index f9e9ccab7d8..fe2589dfa94 100644
--- a/tests/gateway/test_signal.py
+++ b/tests/gateway/test_signal.py
@@ -13,7 +13,7 @@ from gateway.config import Platform, PlatformConfig
def _reset_signal_scheduler():
"""The attachment scheduler is process-wide; drop it between tests
so a fresh token bucket greets each case."""
- from gateway.platforms.signal_rate_limit import _reset_scheduler
+ from plugins.platforms.signal.signal_rate_limit import _reset_scheduler
_reset_scheduler()
yield
_reset_scheduler()
@@ -26,7 +26,7 @@ def _reset_signal_scheduler():
def _make_signal_adapter(monkeypatch, account="+15551234567", **extra):
"""Create a SignalAdapter with sensible test defaults."""
monkeypatch.setenv("SIGNAL_GROUP_ALLOWED_USERS", extra.pop("group_allowed", ""))
- from gateway.platforms.signal import SignalAdapter
+ from plugins.platforms.signal.adapter import SignalAdapter
config = PlatformConfig()
config.enabled = True
config.extra = {
@@ -91,7 +91,7 @@ class TestSignalConnectCleanup:
mock_client.get = AsyncMock(return_value=MagicMock(status_code=503))
mock_client.aclose = AsyncMock()
- with patch("gateway.platforms.signal.httpx.AsyncClient", return_value=mock_client), \
+ with patch("plugins.platforms.signal.adapter.httpx.AsyncClient", return_value=mock_client), \
patch("gateway.status.acquire_scoped_lock", return_value=(True, None)), \
patch("gateway.status.release_scoped_lock") as mock_release:
result = await adapter.connect()
@@ -111,7 +111,7 @@ class TestSignalHelpers:
def test_parse_comma_list(self):
- from gateway.platforms.signal import _parse_comma_list
+ from plugins.platforms.signal.adapter import _parse_comma_list
assert _parse_comma_list("+1234, +5678 , +9012") == ["+1234", "+5678", "+9012"]
assert _parse_comma_list("") == []
assert _parse_comma_list(" , , ") == []
@@ -124,7 +124,7 @@ class TestSignalHelpers:
``_guess_extension`` never produced ``.wav`` for raw bytes, so the
attachment was treated as a document and STT never received it.
"""
- from gateway.platforms.signal import _is_audio_ext, _guess_extension
+ from plugins.platforms.signal.adapter import _is_audio_ext, _guess_extension
wav = b"RIFF\x24\x08\x00\x00WAVEfmt " + b"\x00" * 100
ext = _guess_extension(wav)
assert ext == ".wav"
@@ -138,7 +138,7 @@ class TestSignalHelpers:
STT reject the upload ("Invalid file format") even though the bytes
were valid audio. Audio brands must resolve to ``.m4a``.
"""
- from gateway.platforms.signal import _guess_extension, _is_audio_ext
+ from plugins.platforms.signal.adapter import _guess_extension, _is_audio_ext
for brand in (b"M4A ", b"M4B ", b"m4a "):
data = b"\x00\x00\x00\x1cftyp" + brand + b"\x00" * 100
assert _guess_extension(data) == ".m4a", brand
@@ -156,7 +156,7 @@ class TestSignalHelpers:
import shutil
import subprocess
import tempfile
- from gateway.platforms.signal import _remux_aac_to_m4a
+ from plugins.platforms.signal.adapter import _remux_aac_to_m4a
ffmpeg = shutil.which("ffmpeg")
if not ffmpeg:
@@ -200,13 +200,13 @@ class TestSignalHelpers:
def test_check_requirements(self, monkeypatch):
- from gateway.platforms.signal import check_signal_requirements
+ from plugins.platforms.signal.adapter import check_signal_requirements
monkeypatch.setenv("SIGNAL_HTTP_URL", "http://localhost:8080")
monkeypatch.setenv("SIGNAL_ACCOUNT", "+15551234567")
assert check_signal_requirements() is True
def test_render_mentions(self):
- from gateway.platforms.signal import _render_mentions
+ from plugins.platforms.signal.adapter import _render_mentions
text = "Hello \uFFFC, how are you?"
mentions = [{"start": 6, "length": 1, "number": "+15559999999"}]
result = _render_mentions(text, mentions)
@@ -217,7 +217,7 @@ class TestSignalHelpers:
def test_validate_signal_config_accepts_platform_values(self, monkeypatch):
monkeypatch.delenv("SIGNAL_HTTP_URL", raising=False)
monkeypatch.delenv("SIGNAL_ACCOUNT", raising=False)
- from gateway.platforms.signal import validate_signal_config
+ from plugins.platforms.signal.adapter import validate_signal_config
config = PlatformConfig(
enabled=True,
@@ -260,7 +260,7 @@ class TestSignalAttachmentFetch:
adapter._rpc, captured = _stub_rpc({"data": b64_data})
with patch(
- "gateway.platforms.signal.cache_image_from_bytes_async",
+ "plugins.platforms.signal.adapter.cache_image_from_bytes_async",
new=AsyncMock(return_value="/tmp/test.png"),
):
await adapter._fetch_attachment("attachment-123")
@@ -992,7 +992,7 @@ class TestSignalRpcRateLimit:
"""signal-cli ≥ v0.14.3 surfaces server Retry-After under
``error.data.response.results[*].retryAfterSeconds`` — _rpc
carries that value through SignalRateLimitError.retry_after."""
- from gateway.platforms.signal_rate_limit import (
+ from plugins.platforms.signal.signal_rate_limit import (
SignalRateLimitError, SIGNAL_RPC_ERROR_RATELIMIT,
)
@@ -1073,10 +1073,10 @@ def _patch_scheduler_sleep(monkeypatch, capture: list):
await _real_sleep(0)
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.asyncio.sleep", fake_sleep
+ "plugins.platforms.signal.signal_rate_limit.asyncio.sleep", fake_sleep
)
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.time.monotonic", lambda: offset[0]
+ "plugins.platforms.signal.signal_rate_limit.time.monotonic", lambda: offset[0]
)
@@ -1135,7 +1135,7 @@ class TestSignalSendMultipleImages:
"""signal-cli < v0.14.3 doesn't surface Retry-After. The
scheduler keeps its default refill rate (1 token / 4s), so a
retry of n=3 waits 12s."""
- from gateway.platforms.signal_rate_limit import (
+ from plugins.platforms.signal.signal_rate_limit import (
SIGNAL_RATE_LIMIT_DEFAULT_RETRY_AFTER,
SignalRateLimitError,
)
@@ -1167,7 +1167,7 @@ class TestSignalRateLimitDetection:
def test_extract_retry_after_from_results(self):
- from gateway.platforms.signal import _extract_retry_after_seconds
+ from plugins.platforms.signal.adapter import _extract_retry_after_seconds
err = {
"code": -5,
"message": "Failed to send message due to rate limiting",
@@ -1188,7 +1188,7 @@ class TestSignalRateLimitDetection:
"""libsignal-net's RetryLaterException leaks through as
AttachmentInvalidException → UnexpectedErrorException when the
rate-limit fires inside attachment upload. Detect it by substring."""
- from gateway.platforms.signal import _is_signal_rate_limit_error
+ from plugins.platforms.signal.adapter import _is_signal_rate_limit_error
err = {
"code": -32603,
"message": (
@@ -1255,7 +1255,7 @@ class TestSignalContentlessEnvelope:
adapter._rpc, _ = _stub_rpc({"data": b64_data})
with patch(
- "gateway.platforms.signal.cache_image_from_bytes_async",
+ "plugins.platforms.signal.adapter.cache_image_from_bytes_async",
new=AsyncMock(return_value="/tmp/img.png"),
):
await adapter._handle_envelope({
@@ -1372,7 +1372,7 @@ class TestRecentSentTimestampRing:
adapter._recent_sent_ttl_seconds = 100.0
# Drive time.monotonic deterministically.
- import gateway.platforms.signal as sig_mod
+ import plugins.platforms.signal.adapter as sig_mod
fake_now = [1000.0]
monkeypatch.setattr(sig_mod.time, "monotonic", lambda: fake_now[0])
diff --git a/tests/gateway/test_signal_format.py b/tests/gateway/test_signal_format.py
index 3a6f1c11532..3e63d8b7ddb 100644
--- a/tests/gateway/test_signal_format.py
+++ b/tests/gateway/test_signal_format.py
@@ -5,7 +5,7 @@ strikethrough, monospace, code blocks, headings, and — critically — the
false-positive regressions that caused spurious italics in production.
"""
-from gateway.platforms.signal_format import markdown_to_signal
+from plugins.platforms.signal.signal_format import markdown_to_signal
# ---------------------------------------------------------------------------
# Helper
diff --git a/tests/gateway/test_signal_plugin.py b/tests/gateway/test_signal_plugin.py
new file mode 100644
index 00000000000..d0e9a63c606
--- /dev/null
+++ b/tests/gateway/test_signal_plugin.py
@@ -0,0 +1,27 @@
+"""Signal ships as a bundled platform plugin: the registry entry carries what core used to hard-wire
+(requirements probe, config gate, out-of-process sender, chunking cap, setup wizard)."""
+
+from types import SimpleNamespace
+
+from gateway.config import PlatformConfig
+
+
+def test_register_declares_the_former_core_wiring(monkeypatch):
+ from plugins.platforms.signal import adapter
+
+ captured = {}
+ adapter.register(SimpleNamespace(register_platform=lambda **kw: captured.update(kw)))
+
+ assert captured["name"] == "signal" and captured["label"] == "Signal" and captured["emoji"] == "📡"
+ assert captured["adapter_factory"] is adapter.SignalAdapter
+ assert captured["max_message_length"] == adapter.MAX_MESSAGE_LENGTH == 8000
+ assert captured["allowed_users_env"] == "SIGNAL_ALLOWED_USERS"
+ assert captured["allow_all_env"] == "SIGNAL_ALLOW_ALL_USERS"
+ assert captured["cron_deliver_env_var"] == "SIGNAL_HOME_CHANNEL"
+ assert captured["pii_safe"] is True and captured["allow_update_command"] is True
+ assert callable(captured["standalone_sender_fn"]) and callable(captured["setup_fn"])
+ for k in ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"):
+ monkeypatch.delenv(k, raising=False)
+ validate = captured["validate_config"]
+ assert validate(PlatformConfig(enabled=True)) is False
+ assert validate(PlatformConfig(enabled=True, extra={"http_url": "http://127.0.0.1:1", "account": "+15550001"}))
diff --git a/tests/gateway/test_signal_rate_limit.py b/tests/gateway/test_signal_rate_limit.py
index cf09676a865..642a6ed18f9 100644
--- a/tests/gateway/test_signal_rate_limit.py
+++ b/tests/gateway/test_signal_rate_limit.py
@@ -3,7 +3,7 @@ import asyncio
import pytest
-from gateway.platforms.signal_rate_limit import (
+from plugins.platforms.signal.signal_rate_limit import (
SignalAttachmentScheduler,
_reset_scheduler,
)
@@ -26,10 +26,10 @@ def _patch_sleep_and_time(monkeypatch, capture: list):
offset += seconds
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.asyncio.sleep", _fake_sleep
+ "plugins.platforms.signal.signal_rate_limit.asyncio.sleep", _fake_sleep
)
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.time.monotonic", lambda: offset
+ "plugins.platforms.signal.signal_rate_limit.time.monotonic", lambda: offset
)
class TestEstimateWait:
@@ -40,7 +40,7 @@ class TestEstimateWait:
s.tokens = 0.0
frozen = s.last_refill
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.time.monotonic", lambda: frozen
+ "plugins.platforms.signal.signal_rate_limit.time.monotonic", lambda: frozen
)
# 32 tokens at 0.25 tokens/sec = 128s
assert s.estimate_wait(32) == pytest.approx(32 / s.refill_rate)
@@ -93,7 +93,7 @@ class TestRefillClamping:
s.tokens = 0.0
# Pretend a year passed.
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.time.monotonic",
+ "plugins.platforms.signal.signal_rate_limit.time.monotonic",
lambda: s.last_refill + 365 * 24 * 3600,
)
s._refill()
diff --git a/tests/gateway/test_warning_delivery_real_producers.py b/tests/gateway/test_warning_delivery_real_producers.py
index 7029fad83f5..7463f6eea97 100644
--- a/tests/gateway/test_warning_delivery_real_producers.py
+++ b/tests/gateway/test_warning_delivery_real_producers.py
@@ -21,7 +21,7 @@ def policy(request, monkeypatch, tmp_path):
@pytest.mark.asyncio
async def test_signal_pacing_producer_keeps_actual_image_delivery(policy, monkeypatch, tmp_path):
- import gateway.platforms.signal as module
+ import plugins.platforms.signal.adapter as module
adapter = module.SignalAdapter(PlatformConfig())
scheduler = SimpleNamespace(state=dict, estimate_wait=lambda n: 120,
acquire=AsyncMock(), report_rpc_duration=AsyncMock())
diff --git a/tests/tools/test_audio_container.py b/tests/tools/test_audio_container.py
index 274dd0e3b8b..1011abb38f5 100644
--- a/tests/tools/test_audio_container.py
+++ b/tests/tools/test_audio_container.py
@@ -152,6 +152,6 @@ class TestSignalDelegatesToCentralSniffer:
"""signal._guess_extension audio branches delegate to the shared module."""
def test_signal_uses_shared_sniffer(self):
- from gateway.platforms import signal as signal_mod
+ from plugins.platforms.signal import adapter as signal_mod
assert signal_mod._guess_extension(M4A) == ".m4a"
diff --git a/tests/tools/test_send_message_tool.py b/tests/tools/test_send_message_tool.py
index 0e77282eea7..0bd1cf95f98 100644
--- a/tests/tools/test_send_message_tool.py
+++ b/tests/tools/test_send_message_tool.py
@@ -20,7 +20,7 @@ _HAS_TELEGRAM = pytest.importorskip("telegram", reason="python-telegram-bot not
def _reset_signal_scheduler():
"""Drop the process-wide attachment scheduler so each test gets a
fresh token bucket."""
- from gateway.platforms.signal_rate_limit import _reset_scheduler
+ from plugins.platforms.signal.signal_rate_limit import _reset_scheduler
_reset_scheduler()
yield
_reset_scheduler()
@@ -29,12 +29,12 @@ from gateway.config import Platform
from tools.send_message_tool import (
_resolve_slack_user_target,
_send_matrix_via_adapter,
- _send_signal,
_send_telegram,
_send_to_platform,
send_message_tool,
)
from tools.send_message_targets import _parse_target_ref
+from plugins.platforms.signal.standalone import _send_signal
# Discord helpers moved to the plugin in #24325. Import from the new path
# and provide a thin ``_send_discord(token, ...)`` shim that mirrors the
# pre-migration signature so the existing test bodies keep working.
@@ -533,16 +533,19 @@ class TestSendToPlatformChunking:
truncate_message() pass in _send_to_platform must know Signal's limit
(regression for #67279 / #57929 — long sends were rejected whole).
"""
- from gateway.platforms.signal import MAX_MESSAGE_LENGTH as SIGNAL_MAX
- import tools.send_message_tool as smt
+ from plugins.platforms.signal.adapter import MAX_MESSAGE_LENGTH as SIGNAL_MAX
+ from hermes_cli.plugins import discover_plugins
+ from gateway.platform_registry import platform_registry
sent = []
- async def fake_send_signal(extra, chat_id, chunk, media_files=None):
+ async def fake_send_signal(pconfig, chat_id, chunk, *, thread_id=None, media_files=None,
+ force_document=False):
sent.append(chunk)
return {"success": True, "platform": "signal", "chat_id": chat_id}
- monkeypatch.setattr(smt, "_send_signal", fake_send_signal)
+ discover_plugins()
+ monkeypatch.setattr(platform_registry.get("signal"), "standalone_sender_fn", fake_send_signal)
long_msg = "word " * ((SIGNAL_MAX // 5) + 500) # comfortably over limit
result = asyncio.run(
@@ -1425,10 +1428,10 @@ def _patch_sendmsg_sleep_and_time(monkeypatch, capture: list):
await _real_sleep(0)
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.asyncio.sleep", fake_sleep
+ "plugins.platforms.signal.signal_rate_limit.asyncio.sleep", fake_sleep
)
monkeypatch.setattr(
- "gateway.platforms.signal_rate_limit.time.monotonic", lambda: offset[0]
+ "plugins.platforms.signal.signal_rate_limit.time.monotonic", lambda: offset[0]
)
diff --git a/tests/tools/test_signal_media.py b/tests/tools/test_signal_media.py
index 6136db726aa..d0988b92d3d 100644
--- a/tests/tools/test_signal_media.py
+++ b/tests/tools/test_signal_media.py
@@ -50,7 +50,7 @@ class TestSendSignalMediaFiles:
def test_send_signal_with_missing_media_file(self):
"""Missing media files should generate warnings but not fail."""
- from tools.send_message_tool import _send_signal
+ from plugins.platforms.signal.standalone import _send_signal
extra = {"http_url": "http://localhost:8080", "account": "+155****4567"}
diff --git a/tools/audio_container.py b/tools/audio_container.py
index 910b7b41967..8d1f9af5670 100644
--- a/tools/audio_container.py
+++ b/tools/audio_container.py
@@ -3,7 +3,7 @@
Outbound (``tools/tts_tool.py``): TTS backends silently ignore the requested
format (Edge emits MP3, Piper WAV), so the file is sniffed and its ``.ogg``
extension repaired. Inbound (``gateway/platforms/base.py`` cache_audio_*,
-``gateway/platforms/signal.py``): adapters pass wrong/guessed voice-note
+``plugins/platforms/signal/adapter.py``): adapters pass wrong/guessed voice-note
extensions (Telegram ``.oga``, iOS M4A-branded MP4), so the cache sniffs the
real container for STT and players. Only audio/AV containers are claimed:
RIFF/WEBP and other images return ``None`` so callers check images first.
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 45072fe95c4..d505e147d42 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -562,13 +562,13 @@ plugins/platforms/ # plugin-packaged adapters (one dir each)
├── wecom/adapter.py # WeCom (WeChat Work) callback
├── line/adapter.py # LINE Messaging API
├── teams/adapter.py # Microsoft Teams
+├── signal/adapter.py # Signal via signal-cli HTTP daemon (SSE + JSON-RPC)
├── irc/adapter.py # IRC (canonical scoped-lock example)
├── bluebubbles/adapter.py # Apple iMessage via BlueBubbles macOS server
└── … # google_chat, ntfy, photon, raft, simplex, …
gateway/platforms/ # core base + legacy direct adapters
├── base.py # BasePlatformAdapter — shared logic for all platforms
-├── signal.py # Signal via signal-cli REST API
├── weixin.py # Weixin (personal WeChat) via iLink Bot API
├── qqbot/ # QQ Bot (Tencent QQ) via Official API v2 (sub-package)
├── yuanbao.py # Yuanbao (Tencent) DM/group adapter
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
index 8afbd4f4021..dbca8416799 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
@@ -162,13 +162,13 @@ plugins/platforms/ # 插件打包的适配器(每个一个目
├── wecom/adapter.py # 企业微信(WeCom)回调
├── line/adapter.py # LINE Messaging API
├── teams/adapter.py # Microsoft Teams
+├── signal/adapter.py # Signal(通过 signal-cli HTTP 守护进程,SSE + JSON-RPC)
├── irc/adapter.py # IRC(作用域锁的标准示例)
├── bluebubbles/adapter.py # Apple iMessage(通过 BlueBubbles macOS 服务端)
└── … # google_chat、ntfy、photon、raft、simplex 等
gateway/platforms/ # 核心 base 与旧的直接适配器
├── base.py # BasePlatformAdapter — 所有平台的共享逻辑
-├── signal.py # Signal(通过 signal-cli REST API)
├── weixin.py # 微信(个人版,通过 iLink Bot API)
├── qqbot/ # QQ Bot(腾讯 QQ,通过官方 API v2,子包)
├── yuanbao.py # 元宝(腾讯)私信/群组适配器