The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway/platforms): signal.py — walrus guards, inline rpc id, fold calls
Teknium295d09791a8e
diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.pyindex ddd1c01e05e..06f57156a87 100644--- a/gateway/platforms/signal.py+++ b/gateway/platforms/signal.py@@ -303,8 +303,8 @@ class SignalAdapter(BasePlatformAdapter):while self._running:try:logger.debug("Signal SSE: connecting to %s", url)- headers = {"Accept": "text/event-stream"}- async with self.client.stream("GET", url, headers=headers, timeout=None) as response:+ async with self.client.stream("GET", url, headers={"Accept": "text/event-stream"},+ timeout=None) as response:self._sse_response = responsebackoff = SSE_RETRY_DELAY_INITIAL # Reset on successful connectionself._last_sse_activity = time.time()@@ -327,8 +327,7 @@ class SignalAdapter(BasePlatformAdapter):if self._running:logger.warning("Signal SSE: error: %s (reconnecting in %.0fs)", e, backoff)if self._running:- # 20% jitter prevents thundering herd on reconnection- await asyncio.sleep(backoff + backoff * 0.2 * random.random())+ await asyncio.sleep(backoff + backoff * 0.2 * random.random()) # 20% jitter vs thundering herdbackoff = min(backoff * 2, SSE_RETRY_DELAY_MAX)self._sse_response = None@@ -348,8 +347,7 @@ class SignalAdapter(BasePlatformAdapter):logger.warning("Signal: health check error: %s, forcing reconnect", e)self._force_reconnect()continue- if resp.status_code == 200:- # Daemon alive but SSE quiet — reset activity to avoid repeated warnings+ if resp.status_code == 200: # daemon alive but SSE quiet — reset activity to avoid repeated warningsself._last_sse_activity = time.time()logger.debug("Signal: daemon healthy, SSE idle")else:@@ -566,12 +564,10 @@ class SignalAdapter(BasePlatformAdapter):"""Return the preferred Signal recipient identifier for a direct chat."""if not chat_id or chat_id.startswith("group:") or not _looks_like_e164_number(chat_id):return chat_id- cached = self._recipient_uuid_by_number.get(chat_id)- if cached:+ if cached := self._recipient_uuid_by_number.get(chat_id):return cachedasync with self._recipient_cache_lock:- cached = self._recipient_uuid_by_number.get(chat_id)- if cached:+ if cached := self._recipient_uuid_by_number.get(chat_id):return cachedcontacts = await self._rpc("listContacts", {"account": self.account, "allRecipients": True})for contact in contacts if isinstance(contacts, list) else ():@@ -609,18 +605,16 @@ class SignalAdapter(BasePlatformAdapter):else cache_audio_from_bytes if _is_audio_ext(ext) else cache_document_from_bytes)return cache(raw_data, ext), ext- async def _rpc(- self, method: str, params: dict, rpc_id: str = None, *,- log_failures: bool = True, raise_on_rate_limit: bool = False, timeout: float = 30.0) -> Any:- """Send a JSON-RPC 2.0 request to signal-cli. ``log_failures=False`` logs failures at DEBUG- (typing path: silence NETWORK_FAILURE spam); ``raise_on_rate_limit=True`` raises- ``SignalRateLimitError`` on a 429 / RateLimitException instead of swallowing it."""+ async def _rpc(self, method: str, params: dict, rpc_id: str = None, *, log_failures: bool = True,+ raise_on_rate_limit: bool = False, timeout: float = 30.0) -> Any:+ """Send a JSON-RPC 2.0 request to signal-cli. ``log_failures=False`` logs failures at DEBUG (typing+ path: silence NETWORK_FAILURE spam); ``raise_on_rate_limit=True`` raises ``SignalRateLimitError``+ on a 429 / RateLimitException instead of swallowing it."""if not self.client:logger.warning("Signal: RPC called but client not connected")return None- if rpc_id is None:- rpc_id = f"{method}_{int(time.time() * 1000)}"- payload = {"jsonrpc": "2.0", "method": method, "params": params, "id": rpc_id}+ payload = {"jsonrpc": "2.0", "method": method, "params": params,+ "id": rpc_id if rpc_id is not None else f"{method}_{int(time.time() * 1000)}"}fail_level = logging.WARNING if log_failures else logging.DEBUGtry:resp = await self.client.post(f"{self.http_url}/api/v1/rpc", json=payload, timeout=timeout)@@ -637,8 +631,8 @@ class SignalAdapter(BasePlatformAdapter):if isinstance(result, dict) and raise_on_rate_limit:for r in result.get("results") if isinstance(result.get("results"), list) else ():if isinstance(r, dict) and r.get("type") == "RATE_LIMIT_FAILURE":- raise SignalRateLimitError(- "Rate limit exceeded for recipient", retry_after=r.get("retryAfterSeconds"))+ raise SignalRateLimitError("Rate limit exceeded for recipient",+ retry_after=r.get("retryAfterSeconds"))return resultexcept SignalRateLimitError:raise@@ -729,8 +723,7 @@ class SignalAdapter(BasePlatformAdapter):if not content or not content.strip():return SendResult(success=True, message_id=None)base_params = await self._with_target({"account": self.account}, chat_id)- plain_message, message_styles = self._markdown_to_signal(content)- chunks = self._split_signal_formatted_message(plain_message, message_styles, self.MAX_MESSAGE_LENGTH)+ chunks = self._split_signal_formatted_message(*self._markdown_to_signal(content), self.MAX_MESSAGE_LENGTH)last_result = Nonefor idx, (plain_text, text_styles) in enumerate(chunks, start=1):params: Dict[str, Any] = dict(base_params, message=plain_text)@@ -752,8 +745,7 @@ class SignalAdapter(BasePlatformAdapter):if not ts:returnself._remember_sent_message_timestamp(ts)- now = time.monotonic()- recent = self._recent_sent_timestamps+ now, recent = time.monotonic(), self._recent_sent_timestampsrecent.pop(ts, None) # re-insert to mark as most-recently-usedrecent[ts] = now# Drop entries older than TTL first, then enforce the hard cap.@@ -795,21 +787,19 @@ class SignalAdapter(BasePlatformAdapter):return None, "download", eif not file_path or not Path(file_path).exists():return None, "missing", None- file_size = Path(file_path).stat().st_size- if file_size > SIGNAL_MAX_ATTACHMENT_SIZE:+ if (file_size := Path(file_path).stat().st_size) > SIGNAL_MAX_ATTACHMENT_SIZE:return None, "oversize", file_sizereturn file_path, None, None- async def send_multiple_images(- self, chat_id: str, images: List[Tuple[str, str]], metadata: Optional[Dict[str, Any]] = None,- human_delay: float = 0.0) -> None:+ async def send_multiple_images(self, chat_id: str, images: List[Tuple[str, str]],+ metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> None:"""Send a batch of images via chunked Signal RPC calls. Alt texts are dropped (one shared bodyper send); bad images are skipped with a warning; ``human_delay`` is ignored (scheduler paces)."""if not images:returnscheduler = get_scheduler()- logger.info("Signal send_multiple_images: received %d image(s) for %s — scheduler state: %s",- len(images), chat_id[:30], scheduler.state())+ logger.info("Signal send_multiple_images: received %d image(s) for %s — scheduler state: %s", len(images),+ chat_id[:30], scheduler.state())await self._stop_typing_indicator(chat_id)attachments: List[str] = []skipped = {"download": 0, "missing": 0, "oversize": 0}@@ -821,8 +811,8 @@ class SignalAdapter(BasePlatformAdapter):skipped[reason] += 1logger.warning(*_SKIP_IMAGE_LOG[reason](image_url, detail))if not attachments:- logger.error("Signal: no valid images in batch of %d (download=%d missing=%d oversize=%d)",- len(images), skipped["download"], skipped["missing"], skipped["oversize"])+ logger.error("Signal: no valid images in batch of %d (download=%d missing=%d oversize=%d)", len(images),+ skipped["download"], skipped["missing"], skipped["oversize"])returnlogger.info("Signal send_multiple_images: %d/%d images valid, sending in chunks", len(attachments), len(images))base_params = await self._with_target({"account": self.account, "message": ""}, chat_id)@@ -835,8 +825,8 @@ class SignalAdapter(BasePlatformAdapter):logger.debug("Signal batch %d/%d: %d attachments, estimated wait=%.1fs", idx, n_batches, n, estimated)if estimated >= SIGNAL_BATCH_PACING_NOTICE_THRESHOLD:await self._notify_batch_pacing(chat_id, idx, n_batches, estimated)- await self._send_attachment_batch(- scheduler, dict(base_params, attachments=att_batch), n, f"{idx}/{n_batches}")+ await self._send_attachment_batch(scheduler, dict(base_params, attachments=att_batch), n,+ f"{idx}/{n_batches}")async def _send_attachment_batch(self, scheduler, params: Dict[str, Any], n: int, label: str) -> None:"""Send one attachment batch with rate-limit pacing and a single transient retry. Tokens are@@ -862,16 +852,15 @@ class SignalAdapter(BasePlatformAdapter):if success:self._track_sent_timestamp(result)await scheduler.report_rpc_duration(duration, n)- logger.info("Signal batch %s: %d attachments sent in %.1fs (attempt %d/%d)",- label, n, duration, attempt, max_attempts)+ logger.info("Signal batch %s: %d attachments sent in %.1fs (attempt %d/%d)", label, n, duration,+ attempt, max_attempts)returnlogger.error("Signal: RPC send failed for batch %s (%d attachments, attempt %d/%d, rpc_duration=%.1fs)%s",label, n, attempt, max_attempts, duration, f": {err_msg}" if result is not None else "")if attempt >= max_attempts:return- backoff = 2.0 ** attempt- logger.info("Signal: retrying batch %s after %.1fs backoff", label, backoff)- await asyncio.sleep(backoff)+ logger.info("Signal: retrying batch %s after %.1fs backoff", label, 2.0 ** attempt)+ await asyncio.sleep(2.0 ** attempt)async def _notify_batch_pacing(self, chat_id: str, next_batch_idx: int, total_batches: int, wait_s: float) -> None:"""Tell the user about an inter-batch pacing wait over the notice threshold (best-effort)."""