hermes-bot / scripts /patch_weixin_cross_loop.py
Z User
feat: add DuckDuckGo free fallback for web_search (no API key needed)
4036608
#!/usr/bin/env python3
"""Patch hermes-agent WeixinAdapter to fix cross-event-loop session reuse.
ROOT CAUSE: send_weixin_direct() in weixin.py reuses the live adapter's
aiohttp.ClientSession (created in the gateway's event loop) when called
from _run_async() (which creates a new event loop in a worker thread).
aiohttp 3.13+ uses asyncio.timeout() internally, which raises
"Timeout context manager should be used inside a task" when the session's
event loop doesn't match the caller's loop.
FIX: In send_weixin_direct(), skip the live_adapter reuse path entirely
and always create a fresh aiohttp session + adapter. This function is only
called from send_message_tool._send_weixin() via _run_async() (a different
event loop), so reusing the gateway's session is always wrong here.
"""
import sys
import os
import glob
def patch_file(filepath: str):
with open(filepath, 'r') as f:
content = f.read()
# The problematic block: reuses live_adapter._send_session across event loops
old = ''' live_adapter = _LIVE_ADAPTERS.get(resolved_token)
send_session = getattr(live_adapter, '_send_session', None)
if live_adapter is not None and send_session is not None and not send_session.closed:
last_result: Optional[SendResult] = None
cleaned = live_adapter.format_message(message)
if cleaned:
last_result = await live_adapter.send(chat_id, cleaned)
if not last_result.success:
return {"error": f"Weixin send failed: {last_result.error}"}
for media_path, _is_voice in media_files or []:
ext = Path(media_path).suffix.lower()
if ext in {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}:
last_result = await live_adapter.send_image_file(chat_id, media_path)
else:
last_result = await live_adapter.send_document(chat_id, media_path)
if not last_result.success:
return {"error": f"Weixin media send failed: {last_result.error}"}
return {
"success": True,
"platform": "weixin",
"chat_id": chat_id,
"message_id": last_result.message_id if last_result else None,
"context_token_used": bool(context_token),
}'''
new = ''' # NOTE: Do NOT reuse live_adapter._send_session here.
# send_weixin_direct() is called from _run_async() (model_tools.py) which
# creates a new event loop in a worker thread. The live adapter\'s
# aiohttp.ClientSession was created in the gateway\'s event loop, and
# aiohttp 3.13+ raises "Timeout context manager should be used inside a
# task" when the session\'s loop doesn\'t match the caller\'s loop.
# Always fall through to the fresh-session path below.'''
if old not in content:
print(f"WARNING: Could not find live_adapter reuse block in {filepath}", file=sys.stderr)
print("The upstream code may have changed. Skipping this patch.", file=sys.stderr)
sys.exit(0)
content = content.replace(old, new, 1)
with open(filepath, 'w') as f:
f.write(content)
print(f"Patched {filepath}: removed cross-event-loop session reuse in send_weixin_direct()")
if __name__ == "__main__":
candidates = [
"/app/hermes-agent/gateway/platforms/weixin.py",
]
candidates.extend(glob.glob("/app/venv/lib/**/gateway/platforms/weixin.py", recursive=True))
filepath = None
for c in candidates:
if os.path.isfile(c):
filepath = c
break
if not filepath:
print("WARNING: weixin.py not found in any candidate location", file=sys.stderr)
print(f"Checked: {candidates}", file=sys.stderr)
print("Skipping patch_weixin_cross_loop.", file=sys.stderr)
sys.exit(0)
patch_file(filepath)