hermes-mesh 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hermes_mesh/__init__.py +167 -0
- hermes_mesh/adapter.py +330 -0
- hermes_mesh/float.py +71 -0
- hermes_mesh/identity.py +206 -0
- hermes_mesh/session_relay.py +415 -0
- hermes_mesh-0.1.0.dist-info/METADATA +165 -0
- hermes_mesh-0.1.0.dist-info/RECORD +11 -0
- hermes_mesh-0.1.0.dist-info/WHEEL +5 -0
- hermes_mesh-0.1.0.dist-info/entry_points.txt +2 -0
- hermes_mesh-0.1.0.dist-info/licenses/LICENSE +21 -0
- hermes_mesh-0.1.0.dist-info/top_level.txt +1 -0
hermes_mesh/__init__.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Hermes Mesh — session-aware fleet relay plugin.
|
|
2
|
+
|
|
3
|
+
Registers tools: mesh_list, mesh_register, mesh_send.
|
|
4
|
+
Does NOT re-implement standard A2A — delegates to the upstream
|
|
5
|
+
Hermes A2A platform adapter for discover/call/serve.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
__all__ = ["register"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def check_requirements() -> bool:
|
|
18
|
+
"""Mesh depends on Hermes core — always loadable."""
|
|
19
|
+
return True
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_config(config) -> bool:
|
|
23
|
+
"""No required config — everything is env-var or vault-driven."""
|
|
24
|
+
return True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _serialize_dict_handler(handler):
|
|
28
|
+
"""Wrap a handler that returns a dict so the tool registry sees a JSON string."""
|
|
29
|
+
def wrapper(*args, **kwargs):
|
|
30
|
+
result = handler(*args, **kwargs)
|
|
31
|
+
if isinstance(result, dict):
|
|
32
|
+
return json.dumps(result)
|
|
33
|
+
return result
|
|
34
|
+
return wrapper
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def register(ctx) -> None:
|
|
38
|
+
"""Register the mesh_send tool with Hermes."""
|
|
39
|
+
try:
|
|
40
|
+
from .session_relay import handle_mesh_list, handle_mesh_register, handle_mesh_send
|
|
41
|
+
|
|
42
|
+
ctx.register_tool(
|
|
43
|
+
name="mesh_list",
|
|
44
|
+
toolset="mesh",
|
|
45
|
+
schema={
|
|
46
|
+
"name": "mesh_list",
|
|
47
|
+
"description": "List all agents registered in the fleet mesh vault.",
|
|
48
|
+
"parameters": {
|
|
49
|
+
"type": "object",
|
|
50
|
+
"properties": {},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
handler=_serialize_dict_handler(handle_mesh_list),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
ctx.register_tool(
|
|
57
|
+
name="mesh_register",
|
|
58
|
+
toolset="mesh",
|
|
59
|
+
schema={
|
|
60
|
+
"name": "mesh_register",
|
|
61
|
+
"description": (
|
|
62
|
+
"Register or update an agent identity in the fleet mesh vault. "
|
|
63
|
+
"Requires name, url, and secret."
|
|
64
|
+
),
|
|
65
|
+
"parameters": {
|
|
66
|
+
"type": "object",
|
|
67
|
+
"properties": {
|
|
68
|
+
"name": {
|
|
69
|
+
"type": "string",
|
|
70
|
+
"description": "Agent name (defaults to MESH_AGENT_NAME env var)",
|
|
71
|
+
},
|
|
72
|
+
"url": {
|
|
73
|
+
"type": "string",
|
|
74
|
+
"description": "Hermes webhook URL for this agent",
|
|
75
|
+
},
|
|
76
|
+
"secret": {
|
|
77
|
+
"type": "string",
|
|
78
|
+
"description": "Shared HMAC secret for this agent",
|
|
79
|
+
},
|
|
80
|
+
"role": {
|
|
81
|
+
"type": "string",
|
|
82
|
+
"description": "Role description",
|
|
83
|
+
"default": "agent",
|
|
84
|
+
},
|
|
85
|
+
"description": {
|
|
86
|
+
"type": "string",
|
|
87
|
+
"description": "Human-readable agent description",
|
|
88
|
+
"default": "",
|
|
89
|
+
},
|
|
90
|
+
"overwrite": {
|
|
91
|
+
"type": "boolean",
|
|
92
|
+
"description": "Overwrite existing identity",
|
|
93
|
+
"default": False,
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
"required": ["url", "secret"],
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
handler=_serialize_dict_handler(handle_mesh_register),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
ctx.register_tool(
|
|
103
|
+
name="mesh_send",
|
|
104
|
+
toolset="mesh",
|
|
105
|
+
schema={
|
|
106
|
+
"name": "mesh_send",
|
|
107
|
+
"description": (
|
|
108
|
+
"Send a one-way message through a target Hermes gateway into "
|
|
109
|
+
"its configured platform session context. Auto-pads "
|
|
110
|
+
"[mesh][from:<self>][to:<agent>][id:<uuid>][action:<action>]"
|
|
111
|
+
"[reply:<reply>] header. Returns delivery status."
|
|
112
|
+
),
|
|
113
|
+
"parameters": {
|
|
114
|
+
"type": "object",
|
|
115
|
+
"properties": {
|
|
116
|
+
"message": {
|
|
117
|
+
"type": "string",
|
|
118
|
+
"description": "The message body to send (header is auto-padded)",
|
|
119
|
+
},
|
|
120
|
+
"agent": {
|
|
121
|
+
"type": "string",
|
|
122
|
+
"description": "Name of the target Hermes mesh peer (e.g. daji, yoyo)",
|
|
123
|
+
},
|
|
124
|
+
"action": {
|
|
125
|
+
"type": "string",
|
|
126
|
+
"enum": ["do", "info"],
|
|
127
|
+
"description": "do (recipient should take action) | info (log/acknowledge)",
|
|
128
|
+
"default": "do",
|
|
129
|
+
},
|
|
130
|
+
"reply": {
|
|
131
|
+
"type": "string",
|
|
132
|
+
"enum": ["yes", "no"],
|
|
133
|
+
"description": "yes (sender expects reply) | no (fire-and-forget)",
|
|
134
|
+
"default": "yes",
|
|
135
|
+
},
|
|
136
|
+
"ref": {
|
|
137
|
+
"type": "string",
|
|
138
|
+
"description": "Optional message ID being replied to (for threading)",
|
|
139
|
+
},
|
|
140
|
+
"task_id": {
|
|
141
|
+
"type": "string",
|
|
142
|
+
"description": "Optional task ID override (auto-generated if omitted)",
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
"required": ["message", "agent"],
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
handler=_serialize_dict_handler(handle_mesh_send),
|
|
149
|
+
)
|
|
150
|
+
logger.info("Hermes Mesh: registered mesh tools")
|
|
151
|
+
except Exception:
|
|
152
|
+
logger.warning("Hermes Mesh: failed to register tool", exc_info=True)
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
from .adapter import MeshAdapter, check_mesh_requirements
|
|
156
|
+
|
|
157
|
+
ctx.register_platform(
|
|
158
|
+
name="mesh",
|
|
159
|
+
label="Hermes Mesh",
|
|
160
|
+
adapter_factory=lambda cfg: MeshAdapter(cfg),
|
|
161
|
+
check_fn=check_mesh_requirements,
|
|
162
|
+
validate_config=validate_config,
|
|
163
|
+
emoji="🕸️",
|
|
164
|
+
)
|
|
165
|
+
logger.info("Hermes Mesh: registered mesh platform adapter")
|
|
166
|
+
except Exception:
|
|
167
|
+
logger.warning("Hermes Mesh: failed to register platform adapter", exc_info=True)
|
hermes_mesh/adapter.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Mesh platform adapter — receive HMAC-signed Mesh messages.
|
|
2
|
+
|
|
3
|
+
Runs an aiohttp HTTP server that receives one-way mesh pings from other
|
|
4
|
+
Hermes fleet agents, validates HMAC-SHA256 signatures, parses the mesh
|
|
5
|
+
metadata envelope, and routes the message into the configured platform
|
|
6
|
+
session (e.g. the local agent's Telegram DM).
|
|
7
|
+
"""
|
|
8
|
+
import asyncio
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import errno
|
|
16
|
+
import sys
|
|
17
|
+
from typing import Any, Dict, Optional
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from aiohttp import web
|
|
21
|
+
|
|
22
|
+
AIOHTTP_AVAILABLE = True
|
|
23
|
+
except ImportError:
|
|
24
|
+
AIOHTTP_AVAILABLE = False
|
|
25
|
+
web = None # type: ignore[assignment]
|
|
26
|
+
|
|
27
|
+
from .identity import get_raw_agent_identity
|
|
28
|
+
from gateway.config import Platform, PlatformConfig
|
|
29
|
+
from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _transport(agent_info: dict, name: str) -> dict:
|
|
35
|
+
if not isinstance(agent_info, dict):
|
|
36
|
+
return {}
|
|
37
|
+
transport = agent_info.get("transports", {}).get(name, {})
|
|
38
|
+
return transport if isinstance(transport, dict) else {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _transport_auth_value(transport: dict, key: str) -> str:
|
|
42
|
+
auth = transport.get("auth", {}) if isinstance(transport, dict) else {}
|
|
43
|
+
if not isinstance(auth, dict):
|
|
44
|
+
return ""
|
|
45
|
+
value = auth.get(key, "")
|
|
46
|
+
if value is None:
|
|
47
|
+
return ""
|
|
48
|
+
return str(value)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# Default bind host. ``None`` tells aiohttp/asyncio's ``create_server`` to bind
|
|
52
|
+
# BOTH address families (IPv4 + IPv6) — the portable dual-stack default.
|
|
53
|
+
DEFAULT_HOST = None
|
|
54
|
+
DEFAULT_PORT = 8645
|
|
55
|
+
|
|
56
|
+
_MESH_ENVELOPE_RE = re.compile(
|
|
57
|
+
r'^\s*\[mesh\]\[from:([^\]]+)\]\[to:([^\]]+)\]\[id:([^\]]+)\]'
|
|
58
|
+
r'\[action:([^\]]+)\]\[reply:([^\]]+)\]'
|
|
59
|
+
r'(?:\[ref:([^\]]+)\])?\s*'
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _is_loopback_host(host: Optional[str]) -> bool:
|
|
64
|
+
"""True when `host` binds only to the local machine."""
|
|
65
|
+
if not host:
|
|
66
|
+
return False
|
|
67
|
+
return host.strip().lower() in {"127.0.0.1", "localhost", "::1"}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def check_mesh_requirements() -> bool:
|
|
71
|
+
"""Check if mesh adapter dependencies are available."""
|
|
72
|
+
if not AIOHTTP_AVAILABLE:
|
|
73
|
+
return False
|
|
74
|
+
try:
|
|
75
|
+
import gateway.config
|
|
76
|
+
import gateway.platforms.base
|
|
77
|
+
return True
|
|
78
|
+
except Exception:
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class MeshAdapter(BasePlatformAdapter):
|
|
83
|
+
"""Receive HMAC-signed Mesh messages into a configured platform session."""
|
|
84
|
+
|
|
85
|
+
# Mesh deliveries are event-triggered; never prompt for session restoration.
|
|
86
|
+
interactive_resume: bool = False
|
|
87
|
+
|
|
88
|
+
def __init__(self, config: PlatformConfig):
|
|
89
|
+
super().__init__(config, Platform("mesh"))
|
|
90
|
+
self._background_tasks = getattr(self, "_background_tasks", set())
|
|
91
|
+
_cfg_host = config.extra.get("host", DEFAULT_HOST)
|
|
92
|
+
self._host: Optional[str] = _cfg_host or None
|
|
93
|
+
self._port: int = int(config.extra.get("port", DEFAULT_PORT))
|
|
94
|
+
self._route: str = config.extra.get("route", "receive")
|
|
95
|
+
self._secret: str = config.extra.get("secret", "")
|
|
96
|
+
self._target_session: Optional[str] = config.extra.get("target_session")
|
|
97
|
+
self._agent_name: str = str(
|
|
98
|
+
config.extra.get("agent_name")
|
|
99
|
+
or os.getenv("MESH_AGENT_NAME")
|
|
100
|
+
or os.getenv("A2A_AGENT_NAME", "hermes-agent")
|
|
101
|
+
).strip()
|
|
102
|
+
self._runner = None
|
|
103
|
+
self._seen_message_ids: set[str] = set()
|
|
104
|
+
|
|
105
|
+
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
|
106
|
+
if not AIOHTTP_AVAILABLE:
|
|
107
|
+
logger.error("[mesh] aiohttp is not installed")
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
if not self._secret:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"[mesh] HMAC secret is required. Set platforms.mesh.extra.secret "
|
|
113
|
+
"in config.yaml or use INSECURE_NO_AUTH for local testing."
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
if self._secret == "INSECURE_NO_AUTH" and not _is_loopback_host(self._host):
|
|
117
|
+
raise ValueError(
|
|
118
|
+
f"[mesh] INSECURE_NO_AUTH is only allowed on loopback interfaces, "
|
|
119
|
+
f"not '{self._host}'."
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
app = web.Application(client_max_size=1024 * 1024)
|
|
123
|
+
app.router.add_post(f"/mesh/{self._route}", self._handle_mesh)
|
|
124
|
+
|
|
125
|
+
self._runner = web.AppRunner(app)
|
|
126
|
+
await self._runner.setup()
|
|
127
|
+
site = web.TCPSite(
|
|
128
|
+
self._runner,
|
|
129
|
+
self._host,
|
|
130
|
+
self._port,
|
|
131
|
+
reuse_address=False if sys.platform == "darwin" else None,
|
|
132
|
+
)
|
|
133
|
+
try:
|
|
134
|
+
await site.start()
|
|
135
|
+
except OSError as exc:
|
|
136
|
+
if exc.errno not in {
|
|
137
|
+
errno.EADDRINUSE, errno.EADDRNOTAVAIL, errno.EACCES, errno.EPERM
|
|
138
|
+
}:
|
|
139
|
+
raise
|
|
140
|
+
await self._runner.cleanup()
|
|
141
|
+
self._runner = None
|
|
142
|
+
logger.error(
|
|
143
|
+
"[mesh] Could not bind %s:%d: %s",
|
|
144
|
+
self._host or "all IPv4+IPv6 interfaces",
|
|
145
|
+
self._port,
|
|
146
|
+
exc,
|
|
147
|
+
)
|
|
148
|
+
return False
|
|
149
|
+
|
|
150
|
+
self._mark_connected()
|
|
151
|
+
logger.info(
|
|
152
|
+
"[mesh] Listening on %s:%d — agent '%s'",
|
|
153
|
+
self._host or "* (all interfaces, IPv4+IPv6)",
|
|
154
|
+
self._port,
|
|
155
|
+
self._agent_name,
|
|
156
|
+
)
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
async def disconnect(self) -> None:
|
|
160
|
+
if self._runner:
|
|
161
|
+
await self._runner.cleanup()
|
|
162
|
+
self._runner = None
|
|
163
|
+
self._mark_disconnected()
|
|
164
|
+
logger.info("[mesh] Disconnected")
|
|
165
|
+
|
|
166
|
+
async def _handle_mesh(self, request: "web.Request") -> "web.Response":
|
|
167
|
+
body = await request.read()
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
payload = json.loads(body)
|
|
171
|
+
except json.JSONDecodeError:
|
|
172
|
+
return web.json_response({"status": "invalid json"}, status=400)
|
|
173
|
+
|
|
174
|
+
text = str(payload.get("text", ""))
|
|
175
|
+
from_field = payload.get("from")
|
|
176
|
+
|
|
177
|
+
# C5: per-agent HMAC — verify with the sender's own webhook secret if known
|
|
178
|
+
provided = request.headers.get("X-Hub-Signature-256", "")
|
|
179
|
+
if self._secret != "INSECURE_NO_AUTH":
|
|
180
|
+
verify_secret = self._secret
|
|
181
|
+
if from_field:
|
|
182
|
+
sender_info = get_raw_agent_identity(from_field)
|
|
183
|
+
if sender_info:
|
|
184
|
+
sender_secret = _transport_auth_value(_transport(sender_info, "hermes_webhook"), "secret")
|
|
185
|
+
if sender_secret:
|
|
186
|
+
verify_secret = sender_secret
|
|
187
|
+
expected = "sha256=" + hmac.new(
|
|
188
|
+
verify_secret.encode(), body, hashlib.sha256
|
|
189
|
+
).hexdigest()
|
|
190
|
+
if not hmac.compare_digest(provided.encode(), expected.encode()):
|
|
191
|
+
logger.warning("[mesh] HMAC verification failed")
|
|
192
|
+
return web.json_response({"status": "unauthorized"}, status=401)
|
|
193
|
+
|
|
194
|
+
m = _MESH_ENVELOPE_RE.match(text)
|
|
195
|
+
if not m:
|
|
196
|
+
return web.json_response({"status": "missing mesh envelope"}, status=400)
|
|
197
|
+
|
|
198
|
+
sender, recipient, msg_id, action, reply, ref = m.groups()
|
|
199
|
+
|
|
200
|
+
if msg_id in self._seen_message_ids:
|
|
201
|
+
logger.info("[mesh] Duplicate message_id %s dropped", msg_id)
|
|
202
|
+
return web.json_response({"status": "duplicate"}, status=200)
|
|
203
|
+
self._seen_message_ids.add(msg_id)
|
|
204
|
+
if len(self._seen_message_ids) > 10000:
|
|
205
|
+
self._seen_message_ids.clear()
|
|
206
|
+
|
|
207
|
+
if from_field and sender != from_field:
|
|
208
|
+
logger.warning("[mesh] Envelope sender '%s' does not match body 'from' field '%s'", sender, from_field)
|
|
209
|
+
return web.json_response({"status": "sender mismatch"}, status=401)
|
|
210
|
+
body_text = text[m.end():].lstrip()
|
|
211
|
+
|
|
212
|
+
if recipient != self._agent_name:
|
|
213
|
+
logger.warning(
|
|
214
|
+
"[mesh] Envelope recipient '%s' does not match local agent '%s'",
|
|
215
|
+
recipient,
|
|
216
|
+
self._agent_name,
|
|
217
|
+
)
|
|
218
|
+
return web.json_response(
|
|
219
|
+
{"status": "recipient mismatch", "recipient": recipient},
|
|
220
|
+
status=404,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# Render the message with routing CTA so the agent sees the mesh context.
|
|
224
|
+
cta = ""
|
|
225
|
+
if action and reply:
|
|
226
|
+
cta = f" [Reply via mesh to {sender} — action: {action}, reply: {reply}]"
|
|
227
|
+
display_text = f"⬡ [Mesh from:{sender}] {body_text}{cta}"
|
|
228
|
+
|
|
229
|
+
# Build session source. Prefer target_session routing into an existing
|
|
230
|
+
# platform session (e.g. Telegram DM) so the agent has full context.
|
|
231
|
+
if self._target_session:
|
|
232
|
+
parts = self._target_session.split(":", 2)
|
|
233
|
+
target_platform_str = parts[0]
|
|
234
|
+
target_chat_type = parts[1] if len(parts) > 1 else "dm"
|
|
235
|
+
target_chat_id = parts[2] if len(parts) > 2 else parts[1]
|
|
236
|
+
source = self.build_source(
|
|
237
|
+
chat_id=target_chat_id,
|
|
238
|
+
chat_name=f"mesh/{sender}",
|
|
239
|
+
chat_type=target_chat_type,
|
|
240
|
+
user_id=f"mesh:{sender}",
|
|
241
|
+
user_name=sender,
|
|
242
|
+
_platform=Platform(target_platform_str),
|
|
243
|
+
)
|
|
244
|
+
else:
|
|
245
|
+
source = self.build_source(
|
|
246
|
+
chat_id=f"mesh:{sender}:{msg_id}",
|
|
247
|
+
chat_name=f"mesh/{sender}",
|
|
248
|
+
chat_type="mesh",
|
|
249
|
+
user_id=f"mesh:{sender}",
|
|
250
|
+
user_name=sender,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
event = MessageEvent(
|
|
254
|
+
text=display_text,
|
|
255
|
+
message_type=MessageType.TEXT,
|
|
256
|
+
source=source,
|
|
257
|
+
raw_message=payload,
|
|
258
|
+
message_id=msg_id,
|
|
259
|
+
)
|
|
260
|
+
event.metadata["mesh"] = {
|
|
261
|
+
"sender": sender,
|
|
262
|
+
"recipient": recipient,
|
|
263
|
+
"action": action,
|
|
264
|
+
"reply": reply,
|
|
265
|
+
"ref": ref,
|
|
266
|
+
"message_id": msg_id,
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
logger.info(
|
|
270
|
+
"[mesh] received from=%s to=%s action=%s reply=%s id=%s",
|
|
271
|
+
sender,
|
|
272
|
+
recipient,
|
|
273
|
+
action,
|
|
274
|
+
reply,
|
|
275
|
+
msg_id,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
task = asyncio.create_task(self.handle_message(event))
|
|
279
|
+
self._background_tasks.add(task)
|
|
280
|
+
task.add_done_callback(self._background_tasks.discard)
|
|
281
|
+
|
|
282
|
+
return web.json_response(
|
|
283
|
+
{"status": "accepted", "delivery_id": msg_id},
|
|
284
|
+
status=202,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
|
288
|
+
"""Return minimal chat info for mesh sessions."""
|
|
289
|
+
return {
|
|
290
|
+
"name": f"mesh/{chat_id}",
|
|
291
|
+
"type": "dm",
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async def send(
|
|
295
|
+
self,
|
|
296
|
+
chat_id: str,
|
|
297
|
+
content: str,
|
|
298
|
+
reply_to: Optional[str] = None,
|
|
299
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
300
|
+
) -> SendResult:
|
|
301
|
+
"""Mesh is one-way inbound; log any agent response locally."""
|
|
302
|
+
logger.info("[mesh] Response for %s: %s", chat_id, content[:200])
|
|
303
|
+
return SendResult(success=True)
|
|
304
|
+
|
|
305
|
+
async def on_processing_complete(self, event: MessageEvent, outcome: Any) -> None:
|
|
306
|
+
"""Close isolated mesh sessions; leave real platform sessions open."""
|
|
307
|
+
source_chat_type = getattr(event.source, "chat_type", None)
|
|
308
|
+
if source_chat_type == "dm":
|
|
309
|
+
logger.debug("[mesh] Skipping session close for guest delivery")
|
|
310
|
+
return
|
|
311
|
+
|
|
312
|
+
runner = self.gateway_runner
|
|
313
|
+
if runner is None:
|
|
314
|
+
return
|
|
315
|
+
session_db = getattr(runner, "_session_db", None)
|
|
316
|
+
store = getattr(runner, "session_store", None)
|
|
317
|
+
if session_db is None or store is None:
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
try:
|
|
321
|
+
key_fn = getattr(runner, "_session_key_for_source", None)
|
|
322
|
+
if key_fn is None:
|
|
323
|
+
return
|
|
324
|
+
session_key = key_fn(event.source)
|
|
325
|
+
session_id = store.get(session_key)
|
|
326
|
+
if session_id is None:
|
|
327
|
+
return
|
|
328
|
+
await session_db.end_session(session_id, reason="mesh_complete")
|
|
329
|
+
except Exception as exc:
|
|
330
|
+
logger.warning("[mesh] Failed to end session: %s", exc)
|
hermes_mesh/float.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Telegram float transport for Hermes mesh.
|
|
2
|
+
|
|
3
|
+
Fire-and-forget notification to the sender's Telegram DM. Best-effort —
|
|
4
|
+
failures are logged and swallowed; the tool result is the source of truth.
|
|
5
|
+
|
|
6
|
+
Env var chain: HERMES_TELEGRAM_BOT_TOKEN → A2A_TELEGRAM_BOT_TOKEN → TELEGRAM_BOT_TOKEN
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import html
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _resolve_credentials() -> tuple[str, str]:
|
|
21
|
+
"""Resolve bot_token and chat_id from env vars. Returns ("", "") if absent."""
|
|
22
|
+
bot = (
|
|
23
|
+
os.getenv("HERMES_TELEGRAM_BOT_TOKEN")
|
|
24
|
+
or os.getenv("A2A_TELEGRAM_BOT_TOKEN")
|
|
25
|
+
or os.getenv("TELEGRAM_BOT_TOKEN", "")
|
|
26
|
+
)
|
|
27
|
+
chat = (
|
|
28
|
+
os.getenv("HERMES_TELEGRAM_DEFAULT_CHAT_ID")
|
|
29
|
+
or os.getenv("A2A_TELEGRAM_DEFAULT_CHAT_ID")
|
|
30
|
+
or os.getenv("TELEGRAM_HOME_CHANNEL", "")
|
|
31
|
+
)
|
|
32
|
+
return bot, chat
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def send(text: str, sender_name: str = "hermes-agent") -> None:
|
|
36
|
+
"""Send a float message to the sender's Telegram DM.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
text: The message text to send (already padded with mesh header).
|
|
40
|
+
sender_name: The calling agent's name (for diagnostics, not delivery).
|
|
41
|
+
"""
|
|
42
|
+
bot, chat = _resolve_credentials()
|
|
43
|
+
if not bot or not chat:
|
|
44
|
+
logger.debug("Float skipped: missing Telegram credentials (bot=%s, chat=%s)",
|
|
45
|
+
bool(bot), bool(chat))
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
url = f"https://api.telegram.org/bot{bot}/sendMessage"
|
|
49
|
+
payload = {
|
|
50
|
+
"chat_id": chat,
|
|
51
|
+
"text": html.escape(text),
|
|
52
|
+
"parse_mode": "HTML",
|
|
53
|
+
"disable_web_page_preview": True,
|
|
54
|
+
}
|
|
55
|
+
try:
|
|
56
|
+
data = json.dumps(payload).encode()
|
|
57
|
+
req = urllib.request.Request(
|
|
58
|
+
url,
|
|
59
|
+
data=data,
|
|
60
|
+
headers={"Content-Type": "application/json"},
|
|
61
|
+
method="POST",
|
|
62
|
+
)
|
|
63
|
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
64
|
+
body = resp.read().decode()
|
|
65
|
+
result = json.loads(body)
|
|
66
|
+
if not result.get("ok"):
|
|
67
|
+
logger.warning("Float delivery failed: %s", result.get("description", "unknown"))
|
|
68
|
+
else:
|
|
69
|
+
logger.debug("Float sent to %s: %d chars", chat, len(text))
|
|
70
|
+
except Exception as e:
|
|
71
|
+
logger.error("Float delivery error: %s", e)
|