File size: 3,834 Bytes
2a76983
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/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)