Skip to content

The agent that grows with you

refactor(gateway/platforms): group D layout hug + string-literal joins (AST-neutral)

Teknium7b831c71458b
diff --git a/gateway/platforms/msgraph_webhook.py b/gateway/platforms/msgraph_webhook.py
index d8030d304d3..9d2e94d94df 100644
--- a/gateway/platforms/msgraph_webhook.py
+++ b/gateway/platforms/msgraph_webhook.py
@@ -22,8 +22,7 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
- BasePlatformAdapter, MessageEvent, MessageType, SendResult, is_network_accessible,
-)
+ BasePlatformAdapter, MessageEvent, MessageType, SendResult, is_network_accessible)
logger = logging.getLogger(__name__)
@@ -144,8 +143,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):
"extra.allowed_source_cidrs. Configure the Microsoft Graph "
"source CIDRs or bind to loopback (127.0.0.1/::1) behind a "
"tunnel or reverse proxy.",
- self._host,
- )
+ self._host)
return False
app = web.Application(client_max_size=self._max_body_bytes)
app.router.add_get(self._health_path, self._handle_health)
@@ -169,8 +167,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):
async def send(
self, chat_id: str, content: str, reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:
logger.info("[msgraph_webhook] Response for %s: %s", chat_id, content[:200])
return SendResult(success=True)
@@ -185,8 +182,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):
"platform": self.platform.value,
"webhook_path": self._webhook_path,
"accepted": self._accepted_count,
- "duplicates": self._duplicate_count,
- })
+ "duplicates": self._duplicate_count})
async def _handle_validation(self, request: "web.Request") -> "web.Response":
"""Graph subscription validation handshake: echo ``validationToken`` verbatim
@@ -315,12 +311,10 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):
source = self.build_source(
chat_id=f"msgraph:{notification.get('subscriptionId', 'unknown')}",
chat_name="msgraph/webhook", chat_type="webhook",
- user_id="msgraph", user_name="Microsoft Graph",
- )
+ user_id="msgraph", user_name="Microsoft Graph")
return MessageEvent(
text=self._render_prompt(notification), message_type=MessageType.TEXT, source=source,
- raw_message=notification, message_id=message_id, internal=True,
- )
+ raw_message=notification, message_id=message_id, internal=True)
def _render_prompt(self, notification: Dict[str, Any]) -> str:
template = self.config.extra.get("prompt", "")
@@ -329,8 +323,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):
"notification": notification,
"resource": notification.get("resource", ""),
"change_type": notification.get("changeType", ""),
- "subscription_id": notification.get("subscriptionId", ""),
- })
+ "subscription_id": notification.get("subscriptionId", "")})
rendered = json.dumps(notification, indent=2, sort_keys=True)[:4000]
return f"Microsoft Graph change notification:\n\n```json\n{rendered}\n```"
diff --git a/gateway/platforms/signal_format.py b/gateway/platforms/signal_format.py
index c44d8ab28bc..a10da8f80b3 100644
--- a/gateway/platforms/signal_format.py
+++ b/gateway/platforms/signal_format.py
@@ -16,8 +16,7 @@ _INLINE_PATTERNS = [
(re.compile(r"~~(.+?)~~", re.DOTALL), "STRIKETHROUGH"),
(re.compile(r"`(.+?)`"), "MONOSPACE"),
(re.compile(r"(?<!\*)\*(?!\*| )(.+?)(?<!\*)\*(?!\*)"), "ITALIC"),
- (re.compile(r"(?<!\w)_(?!_)(.+?)(?<!_)_(?!\w)"), "ITALIC"),
-]
+ (re.compile(r"(?<!\w)_(?!_)(.+?)(?<!_)_(?!\w)"), "ITALIC")]
def _utf16_len(s: str) -> int:
@@ -103,8 +102,7 @@ def markdown_to_signal(text: str) -> tuple[str, list[str]]:
adjusted_prior = [
(_adjust(start), _adjust(start + length) - _adjust(start), style)
for start, length, style in styles
- if _adjust(start + length) > _adjust(start)
- ]
+ if _adjust(start + length) > _adjust(start)]
text = result + text[last_end:]
style_strings: list[str] = []
for cp_start, cp_len, style_type in sorted(adjusted_prior + inline_styles):
diff --git a/gateway/platforms/signal_rate_limit.py b/gateway/platforms/signal_rate_limit.py
index b06c1acd317..41511e674a8 100644
--- a/gateway/platforms/signal_rate_limit.py
+++ b/gateway/platforms/signal_rate_limit.py
@@ -62,8 +62,7 @@ def _extract_retry_after_seconds(err: Any) -> Optional[float]:
results = ((err.get("data") or {}).get("response") or {}).get("results") or []
candidates = [
parse_retry_after_seconds(r.get("retryAfterSeconds")) for r in results
- if isinstance(r, dict) and r.get("retryAfterSeconds")
- ]
+ if isinstance(r, dict) and r.get("retryAfterSeconds")]
candidates = [c for c in candidates if c is not None]
if candidates:
return max(candidates)
@@ -84,8 +83,7 @@ def _is_signal_rate_limit_error(err: Any) -> bool:
"[429]" in message
or "ratelimit" in msg_lower
or "retrylaterexception" in msg_lower
- or "retry after" in msg_lower
- )
+ or "retry after" in msg_lower)
def _format_wait(seconds: float) -> str:
@@ -113,8 +111,7 @@ class SignalAttachmentScheduler:
def __init__(
self,
capacity: float = float(SIGNAL_RATE_LIMIT_BUCKET_CAPACITY),
- default_retry_after: float = float(SIGNAL_RATE_LIMIT_DEFAULT_RETRY_AFTER),
- ) -> None:
+ default_retry_after: float = float(SIGNAL_RATE_LIMIT_DEFAULT_RETRY_AFTER)) -> None:
self.capacity = float(capacity)
self.tokens = float(capacity)
self.refill_rate = 1.0 / float(default_retry_after)
@@ -154,8 +151,7 @@ class SignalAttachmentScheduler:
return 0.0
if n > self.capacity:
raise SignalSchedulerError(
- f"Signal scheduler was called requesting {n} tokens (max is {self.capacity})",
- )
+ f"Signal scheduler was called requesting {n} tokens (max is {self.capacity})")
total_slept = 0.0
first_pass = True
while True:
@@ -172,8 +168,7 @@ class SignalAttachmentScheduler:
logger.info(
"Signal scheduler: pausing %.1fs for %d tokens "
"(available=%.1f, deficit=%.1f, refill=%.4f/s ≈ %.1fs/token)",
- wait, n, self.tokens, deficit, self.refill_rate, 1.0 / self.refill_rate,
- )
+ wait, n, self.tokens, deficit, self.refill_rate, 1.0 / self.refill_rate)
first_pass = False
await asyncio.sleep(wait)
total_slept += wait
@@ -196,8 +191,7 @@ class SignalAttachmentScheduler:
logging.INFO if rpc_duration > 10 and n_attachments > 5 else logging.DEBUG,
"Signal scheduler: RPC for %d att took %.1fs — "
"tokens %.1f → %.1f (deducted=%d, no upload refill credited, refill=%.4fs⁻¹)",
- n_attachments, rpc_duration, token_before, self.tokens, n_attachments, self.refill_rate,
- )
+ n_attachments, rpc_duration, token_before, self.tokens, n_attachments, self.refill_rate)
def feedback(self, retry_after: Optional[float], n_attempted: int) -> None:
"""Apply server feedback after a 429: empty the bucket and, when ``retry_after``
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index 73f17c68647..a44d75f3082 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -226,8 +226,7 @@ class WebhookAdapter(BasePlatformAdapter):
self._runner = None
logger.error(
"[webhook] Could not bind %s:%d: %s. "
- "Set a different host or port in config.yaml under "
- "platforms.webhook.extra.",
+ "Set a different host or port in config.yaml under platforms.webhook.extra.",
self._host or "all IPv4+IPv6 interfaces", self._port, exc)
return False
self._mark_connected()
@@ -725,8 +724,7 @@ class WebhookAdapter(BasePlatformAdapter):
if not v2_timestamp:
logger.warning(
"[webhook] Route '%s' sent X-Webhook-Signature-V2 with "
- "no X-Webhook-Timestamp — rejecting rather than "
- "falling back to legacy V1",
+ "no X-Webhook-Timestamp — rejecting rather than falling back to legacy V1",
route_name)
return False
age = _timestamp_age(v2_timestamp)
@@ -745,8 +743,7 @@ class WebhookAdapter(BasePlatformAdapter):
"[webhook] Route '%s' uses legacy body-only HMAC (no "
"timestamp), which is vulnerable to replay attacks. Add "
"an 'X-Webhook-Timestamp' header and switch to "
- "'X-Webhook-Signature-V2' (HMAC-SHA256 of "
- "'<timestamp>.<body>').",
+ "'X-Webhook-Signature-V2' (HMAC-SHA256 of '<timestamp>.<body>').",
route_name)
return _hmac_str_equal(generic_sig, _hex_hmac(secret, body))
logger.debug("[webhook] Secret configured but no signature header found")