-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmessaging.py
More file actions
2347 lines (1973 loc) · 91 KB
/
messaging.py
File metadata and controls
2347 lines (1973 loc) · 91 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Hub Messaging Module — the foundation layer.
Owns: agent registration, message send/receive/deliver, inbox management,
WebSocket real-time push, callback delivery, long-poll, sent tracking,
agent discovery, and liveness computation.
Does NOT import or depend on: trust, obligations, tokens, bounties,
analytics, or operator-specific integrations. Those subscribe to
events emitted here.
Event hooks allow upstream modules to:
- Enrich registration (e.g. add bounties note)
- React to messages (e.g. log analytics, send notifications)
- Annotate agents (e.g. compute trust priority)
"""
from flask import Blueprint, request, jsonify
from contextlib import contextmanager, nullcontext
import fcntl
import json
import os
import secrets
import threading
import uuid
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Path
from .events import EventHook
# ── Event hooks ──────────────────────────────────────────────────────
# Downstream modules subscribe to these. Messaging fires them.
# (sender_id, recipient_id, message_dict)
on_message_sent = EventHook()
# (agent_id, agent_record, registration_data) -> optional dict merged into response
on_agent_registered = EventHook()
# (agent_id, message_id, sender_id)
on_message_read = EventHook()
# (agent_id, message_id, sender_id, ack_type, runtime_id)
on_message_acked = EventHook()
# (agent_id, event_type, metadata_dict_or_None)
on_agent_event = EventHook()
# (from_agent_id, target_agent_id) -> optional dict merged into 404 response
on_send_recipient_not_found = EventHook()
# ── Blueprint ────────────────────────────────────────────────────────
messaging_bp = Blueprint("messaging", __name__)
# ── Hub channel secret (for gateway proxy auth) ────────────────────
_hub_secret_cache = None
def _get_hub_secret():
"""Read HUB_SECRET from openclaw config. Cached after first read."""
global _hub_secret_cache
if _hub_secret_cache is not None:
return _hub_secret_cache
try:
with open("/home/openclaw/.openclaw/openclaw.json") as f:
cfg = json.load(f)
_hub_secret_cache = cfg.get("channels", {}).get("hub", {}).get("secret", "")
except Exception:
_hub_secret_cache = ""
return _hub_secret_cache
# ── Storage paths (initialized by init_messaging) ───────────────────
DATA_DIR: Path = None
AGENTS_FILE: Path = None
MESSAGES_DIR: Path = None
SENT_DIR: Path = None
AGENTS_LOCK_FILE: Path = None
DISCOVERED_FILE: Path = None
# ── WebSocket state ──────────────────────────────────────────────────
_ws_connections: dict[str, list] = {}
_ws_lock = threading.Lock()
_ws_delivered_ids: dict[int, set] = {}
_ws_send_locks: dict[int, object] = {}
def init_messaging(data_dir: Path):
"""Initialize storage paths. Called once at startup from server.py."""
global DATA_DIR, AGENTS_FILE, MESSAGES_DIR, SENT_DIR, AGENTS_LOCK_FILE, DISCOVERED_FILE
DATA_DIR = Path(data_dir)
AGENTS_FILE = DATA_DIR / "agents.json"
MESSAGES_DIR = DATA_DIR / "messages"
SENT_DIR = DATA_DIR / "sent"
AGENTS_LOCK_FILE = DATA_DIR / "agents.json.lock"
DISCOVERED_FILE = DATA_DIR / "discovered.json"
MESSAGES_DIR.mkdir(parents=True, exist_ok=True)
SENT_DIR.mkdir(parents=True, exist_ok=True)
# ══════════════════════════════════════════════════════════════════════
# STORAGE PRIMITIVES
# ══════════════════════════════════════════════════════════════════════
def _atomic_json_dump(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
try:
with open(tmp_path, "w") as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
finally:
try:
if tmp_path.exists():
tmp_path.unlink()
except FileNotFoundError:
pass
@contextmanager
def _exclusive_file_lock(lock_path):
lock_path = Path(lock_path)
lock_path.parent.mkdir(parents=True, exist_ok=True)
lock_fd = open(lock_path, "w")
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX)
yield
finally:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
lock_fd.close()
# ── Agent storage ────────────────────────────────────────────────────
def load_agents():
if AGENTS_FILE.exists():
with open(AGENTS_FILE) as f:
return json.load(f)
return {}
def save_agents(agents):
with _exclusive_file_lock(AGENTS_LOCK_FILE):
_atomic_json_dump(AGENTS_FILE, agents)
class agents_lock:
"""Exclusive lock for load-modify-save agent mutations across workers."""
def __init__(self):
self._ctx = None
self._agents = None
def __enter__(self):
self._ctx = _exclusive_file_lock(AGENTS_LOCK_FILE)
self._ctx.__enter__()
self._agents = load_agents()
return self._agents
def __exit__(self, exc_type, exc_val, exc_tb):
try:
if exc_type is None:
_atomic_json_dump(AGENTS_FILE, self._agents)
finally:
self._ctx.__exit__(exc_type, exc_val, exc_tb)
return False
# ── Inbox / conversation storage ─────────────────────────────────────
def get_inbox_path(agent_id):
"""Legacy flat inbox path. Prefer get_conversation_dir for new code."""
return MESSAGES_DIR / f"{agent_id}.json"
def get_conversation_dir(agent_id):
return MESSAGES_DIR / agent_id
def get_conversation_path(agent_id, peer_id):
return get_conversation_dir(agent_id) / f"{peer_id}.json"
def _inbox_lock_path(agent_id):
return get_conversation_dir(agent_id) / ".inbox.lock"
def _safe_load_json_list(path):
if path.exists() and path.is_file():
with open(path) as f:
data = json.load(f)
if isinstance(data, list):
return data
return []
def _message_sort_key(msg):
return (
str(msg.get("timestamp", "")),
str(msg.get("id", "")),
str(msg.get("from_agent", msg.get("from", ""))),
)
def _infer_peer_for_inbox_message(agent_id, message):
sender = message.get("from_agent", message.get("from", ""))
if sender and sender != agent_id:
return sender
for key in ("to", "agent_id", "recipient", "peer_id", "partner"):
value = message.get(key)
if value and value != agent_id:
return value
return "_self"
def load_conversation(agent_id, peer_id):
return _safe_load_json_list(get_conversation_path(agent_id, peer_id))
def load_inbox(agent_id):
conv_dir = get_conversation_dir(agent_id)
merged = []
if conv_dir.exists() and conv_dir.is_dir():
for path in sorted(conv_dir.glob("*.json")):
merged.extend(_safe_load_json_list(path))
merged.sort(key=_message_sort_key)
return merged
# Backwards compatibility: read legacy flat inbox
path = get_inbox_path(agent_id)
return _safe_load_json_list(path)
def _save_inbox_unlocked(agent_id, messages):
conv_dir = get_conversation_dir(agent_id)
conv_dir.mkdir(parents=True, exist_ok=True)
grouped = defaultdict(list)
for message in messages:
peer_id = _infer_peer_for_inbox_message(agent_id, message)
grouped[peer_id].append(message)
desired_paths = set()
for peer_id, peer_messages in grouped.items():
peer_messages.sort(key=_message_sort_key)
conv_path = get_conversation_path(agent_id, peer_id)
desired_paths.add(conv_path.name)
_atomic_json_dump(conv_path, peer_messages)
for path in conv_dir.glob("*.json"):
if path.is_file() and path.name not in desired_paths:
path.unlink()
legacy_path = get_inbox_path(agent_id)
if legacy_path.exists() and legacy_path.is_file() and not get_conversation_dir(agent_id).samefile(conv_dir):
_atomic_json_dump(legacy_path, sorted(messages, key=_message_sort_key))
return messages
def save_inbox(agent_id, messages):
with _exclusive_file_lock(_inbox_lock_path(agent_id)):
return _save_inbox_unlocked(agent_id, messages)
def iter_message_records(messages_dir):
"""Yield (inbox_agent, message_dict) across migrated directories and legacy flat files."""
seen_legacy_agents = set()
for agent_dir in sorted(Path(messages_dir).iterdir()) if os.path.isdir(messages_dir) else []:
if not agent_dir.is_dir():
continue
inbox_agent = agent_dir.name
for conv_file in sorted(agent_dir.glob("*.json")):
try:
msgs = _safe_load_json_list(conv_file)
except Exception:
continue
for m in msgs:
yield inbox_agent, m
seen_legacy_agents.add(inbox_agent)
for legacy_file in sorted(Path(messages_dir).glob("*.json")) if os.path.isdir(messages_dir) else []:
inbox_agent = legacy_file.stem
if inbox_agent in seen_legacy_agents:
continue
try:
msgs = _safe_load_json_list(legacy_file)
except Exception:
continue
for m in msgs:
yield inbox_agent, m
def append_message_to_conversation(agent_id, peer_id, message):
conv_dir = get_conversation_dir(agent_id)
conv_dir.mkdir(parents=True, exist_ok=True)
path = get_conversation_path(agent_id, peer_id)
with _exclusive_file_lock(_inbox_lock_path(agent_id)):
msgs = _safe_load_json_list(path)
msgs.append(message)
msgs.sort(key=_message_sort_key)
_atomic_json_dump(path, msgs)
return message
# ── Sent record storage ──────────────────────────────────────────────
def _get_sent_dir(sender_id):
d = SENT_DIR / sender_id
d.mkdir(parents=True, exist_ok=True)
return d
def _get_sent_path(sender_id, recipient_id):
return _get_sent_dir(sender_id) / f"{recipient_id}.json"
def _sent_lock_path(sender_id, recipient_id):
path = _get_sent_path(sender_id, recipient_id)
return path.with_name(path.name + ".lock")
def _write_sent_records_unlocked(sender_id, recipient_id, records):
_atomic_json_dump(_get_sent_path(sender_id, recipient_id), records)
def _derive_delivery_state(delivered_channels, callback_status=None):
channels = list(dict.fromkeys(delivered_channels or []))
if "websocket" in channels and "callback" in channels:
return "websocket_callback_inbox_unacked"
if "websocket" in channels:
return "websocket_inbox_unacked"
if "callback" in channels:
return "callback_ok_inbox_unacked"
if "poll" in channels:
return "poll_delivered_inbox_unacked"
if callback_status is not None:
if callback_status == "failed" or (isinstance(callback_status, int) and callback_status >= 400):
return "callback_failed_inbox_only"
return "inbox_queued"
def _derive_acknowledged_delivery_state(delivered_channels, callback_status=None, session_loaded=False):
channels = list(dict.fromkeys(delivered_channels or []))
if session_loaded:
# session_loaded_read preserves the ack signal through the read transition
if "websocket" in channels and "callback" in channels:
return "websocket_callback_session_loaded_read"
if "websocket" in channels:
return "websocket_session_loaded_read"
if "callback" in channels:
return "callback_session_loaded_read"
if "poll" in channels:
return "poll_session_loaded_read"
return "session_loaded_read"
if "websocket" in channels and "callback" in channels:
return "websocket_callback_read"
if "websocket" in channels:
return "websocket_read"
if "callback" in channels:
return "callback_read"
if "poll" in channels:
return "poll_read"
if callback_status is not None:
if callback_status == "failed" or (isinstance(callback_status, int) and callback_status >= 400):
return "callback_failed_inbox_read"
return "inbox_read"
def _mutate_sent_records(sender_id, recipient_id, mutator):
path = _get_sent_path(sender_id, recipient_id)
with _exclusive_file_lock(_sent_lock_path(sender_id, recipient_id)):
records = _safe_load_json_list(path)
changed = bool(mutator(records))
if changed:
_write_sent_records_unlocked(sender_id, recipient_id, records)
return changed
def _mark_sent_records_delivered(sender_id, recipient_id, message_ids, channel, delivered_at=None):
message_id_set = {m for m in message_ids if m}
if not message_id_set:
return False
delivered_at = delivered_at or (datetime.utcnow().isoformat() + "Z")
def _mutate(records):
changed = False
for record in records:
if record.get("message_id") not in message_id_set:
continue
channels = list(dict.fromkeys(record.get("delivered_channels") or []))
if channel not in channels:
channels.append(channel)
record["delivered_channels"] = channels
record["delivered_at"] = record.get("delivered_at") or delivered_at
if record.get("read"):
record["delivery_state"] = _derive_acknowledged_delivery_state(channels, record.get("callback_status"), session_loaded=bool(record.get("session_loaded")))
else:
record["delivery_state"] = _derive_delivery_state(channels, record.get("callback_status"))
changed = True
return changed
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _mark_sent_records_read(sender_id, recipient_id, message_ids, read_at=None):
message_id_set = {m for m in message_ids if m}
if not message_id_set:
return False
read_at = read_at or (datetime.utcnow().isoformat() + "Z")
def _mutate(records):
changed = False
for record in records:
if record.get("message_id") not in message_id_set:
continue
if not record.get("read") or not record.get("read_at"):
record["read"] = True
record["read_at"] = read_at
changed = True
next_state = _derive_acknowledged_delivery_state(
record.get("delivered_channels"),
record.get("callback_status"),
session_loaded=bool(record.get("session_loaded")),
)
if record.get("delivery_state") != next_state:
record["delivery_state"] = next_state
changed = True
return changed
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _mark_sent_records_session_loaded(sender_id, recipient_id, message_ids, loaded_at=None, runtime_id=None, ack_type="session_loaded"):
"""Mark sent records as session_loaded (passive ack from recipient runtime).
Updates delivery_state to 'session_loaded' unless already at a higher state (read).
Parallel to _mark_sent_records_read but does NOT set read=True.
"""
message_id_set = {m for m in message_ids if m}
if not message_id_set:
return False
loaded_at = loaded_at or (datetime.utcnow().isoformat() + "Z")
def _mutate(records):
changed = False
for record in records:
if record.get("message_id") not in message_id_set:
continue
# Don't re-ack: if already session_loaded, skip (idempotent)
if record.get("session_loaded"):
continue
record["session_loaded"] = True
record["session_loaded_at"] = loaded_at
record["ack_type"] = ack_type
if runtime_id:
record["session_runtime_id"] = runtime_id
# Don't downgrade delivery_state: if already read, re-derive
# with session_loaded=True to get the correct read+ack state.
# This handles the race where read propagation beats ack propagation.
if record.get("read"):
record["delivery_state"] = _derive_acknowledged_delivery_state(
record.get("delivered_channels"),
record.get("callback_status"),
session_loaded=True,
)
else:
record["delivery_state"] = "session_loaded"
changed = True
return changed
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _merge_delivery_channels(existing_channels, new_channels):
merged = []
for channel in list(existing_channels or []) + list(new_channels or []):
if channel and channel not in merged:
merged.append(channel)
return merged
def _parse_iso_utc(value):
if not value:
return None
try:
return datetime.fromisoformat(str(value).rstrip("Z"))
except Exception:
return None
def _earliest_timestamp(*values):
candidates = [v for v in values if v]
if not candidates:
return None
parsed = []
for value in candidates:
dt = _parse_iso_utc(value)
if dt is None:
return candidates[0]
parsed.append((dt, value))
return min(parsed, key=lambda item: item[0])[1]
def _update_sent_record(sender_id, recipient_id, message_id, **updates):
if not message_id:
return False
def _mutate(records):
changed = False
for record in records:
if record.get("message_id") != message_id:
continue
record.update(updates)
changed = True
break
return changed
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _finalize_sent_record_delivery(
sender_id, recipient_id, message_id,
delivered_channels, delivered_at=None,
callback_status=None, callback_error=None,
):
if not message_id:
return False
def _mutate(records):
changed = False
for record in records:
if record.get("message_id") != message_id:
continue
merged_channels = _merge_delivery_channels(record.get("delivered_channels"), delivered_channels)
record["delivered_channels"] = merged_channels
record["delivered_at"] = _earliest_timestamp(record.get("delivered_at"), delivered_at)
record["callback_status"] = callback_status
record["callback_error"] = callback_error
if record.get("read"):
record["delivery_state"] = _derive_acknowledged_delivery_state(merged_channels, callback_status, session_loaded=bool(record.get("session_loaded")))
else:
record["delivery_state"] = _derive_delivery_state(merged_channels, callback_status)
changed = True
break
return changed
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _delete_sent_record(sender_id, recipient_id, message_id):
if not message_id:
return False
def _mutate(records):
before = len(records)
records[:] = [r for r in records if r.get("message_id") != message_id]
return len(records) != before
return _mutate_sent_records(sender_id, recipient_id, _mutate)
def _append_sent_record(sender_id, recipient_id, record):
with _exclusive_file_lock(_sent_lock_path(sender_id, recipient_id)):
path = _get_sent_path(sender_id, recipient_id)
records = _safe_load_json_list(path)
records.append(record)
_write_sent_records_unlocked(sender_id, recipient_id, records)
def _load_sent_records(sender_id, recipient_id=None):
if recipient_id:
return _safe_load_json_list(_get_sent_path(sender_id, recipient_id))
sent_dir = SENT_DIR / sender_id
if not sent_dir.exists():
return []
records = []
for path in sorted(sent_dir.glob("*.json")):
records.extend(_safe_load_json_list(path))
return records
# ══════════════════════════════════════════════════════════════════════
# DELIVERY LAYER
# ══════════════════════════════════════════════════════════════════════
def _validate_callback_url(url):
"""Validate a callback URL to prevent SSRF.
Returns (is_safe, error_message). Only allows http/https to public IPs."""
import ipaddress
import socket
from urllib.parse import urlparse
try:
parsed = urlparse(url)
except Exception:
return False, "Malformed URL"
if parsed.scheme not in ("http", "https"):
return False, f"Scheme '{parsed.scheme}' not allowed (must be http or https)"
hostname = parsed.hostname
if not hostname:
return False, "No hostname in URL"
if hostname in ("localhost", "0.0.0.0"):
return False, f"Hostname '{hostname}' not allowed"
try:
addrinfos = socket.getaddrinfo(hostname, parsed.port or (443 if parsed.scheme == "https" else 80))
except socket.gaierror:
return False, f"Cannot resolve hostname '{hostname}'"
for family, _, _, _, sockaddr in addrinfos:
ip = ipaddress.ip_address(sockaddr[0])
if not ip.is_global or ip.is_multicast:
return False, f"Resolved IP {ip} is not a public address"
return True, None
def _agent_callback_delivery_ready(agent_info):
callback_url = agent_info.get("callback_url")
if not callback_url or not agent_info.get("callback_verified"):
return False
last_ok = _parse_iso_utc(agent_info.get("callback_last_ok_at"))
last_error = _parse_iso_utc(agent_info.get("callback_last_error_at"))
if last_error and (not last_ok or last_error >= last_ok):
return False
return True
def _record_callback_attempt(agent_id, callback_url, callback_status, callback_error=None):
now = datetime.utcnow().isoformat() + "Z"
try:
with agents_lock() as agents:
info = agents.get(agent_id)
if not info:
return
if callback_url is not None:
info["callback_url"] = callback_url
info["callback_last_status"] = callback_status
if isinstance(callback_status, int) and callback_status < 400:
info["callback_last_ok_at"] = now
info["callback_last_error_at"] = None
info["callback_error"] = None
else:
info["callback_last_error_at"] = now
info["callback_error"] = callback_error
except Exception:
pass
def _agent_has_live_websocket(agent_id):
with _ws_lock:
return bool(_ws_connections.get(agent_id))
def _agent_delivery_capability(agent_info, agent_id=None):
"""Compute delivery capability: "callback" | "websocket" | "poll_active" | "poll_stale" | "none" """
if _agent_callback_delivery_ready(agent_info):
return "callback"
if agent_id and _agent_has_live_websocket(agent_id):
return "websocket"
liveness = agent_info.get("liveness", {})
poll_ts = liveness.get("last_inbox_check")
if poll_ts:
try:
poll_dt = datetime.fromisoformat(poll_ts.replace("Z", ""))
hours_since = (datetime.utcnow() - poll_dt).total_seconds() / 3600
if hours_since < 1:
return "poll_active"
elif hours_since < 24:
return "poll_stale"
except (ValueError, TypeError):
pass
return "none"
def _set_agent_liveness_fields(agent_id, fields):
"""Atomically merge liveness fields into an agent record."""
try:
with agents_lock() as agents:
if agent_id in agents:
agents[agent_id].setdefault("liveness", {}).update(fields)
except Exception:
pass
def _log_agent_event_internal(agent_id, event_type, metadata=None):
"""Fire the on_agent_event hook and update liveness fields."""
on_agent_event.fire(agent_id, event_type, metadata)
if event_type == "inbox_poll":
_set_agent_liveness_fields(agent_id, {"last_inbox_check": datetime.utcnow().isoformat() + "Z"})
elif event_type == "ws_connect":
now = datetime.utcnow().isoformat() + "Z"
_set_agent_liveness_fields(agent_id, {"last_ws_connect": now, "ws_connected": True})
elif event_type == "ws_disconnect":
now = datetime.utcnow().isoformat() + "Z"
_set_agent_liveness_fields(agent_id, {"last_ws_disconnect": now, "ws_connected": False})
def _compute_agent_liveness(agent_id, agents=None):
"""Compute public liveness signals for an agent."""
if agents is None:
agents = load_agents()
info = agents.get(agent_id, {})
last_sent = info.get("last_message_sent_at")
last_received = info.get("last_message_received_at")
with _ws_lock:
ws_conns = _ws_connections.get(agent_id, [])
is_ws_connected = len(ws_conns) > 0
now = datetime.utcnow()
liveness_class = "dead"
sent_ts = None
if last_sent:
try:
sent_ts = datetime.fromisoformat(last_sent.replace("Z", "+00:00").replace("+00:00", ""))
except Exception:
pass
if is_ws_connected:
liveness_class = "active"
elif sent_ts:
age = now - sent_ts
if age < timedelta(days=7):
liveness_class = "active"
elif age < timedelta(days=30):
liveness_class = "warm"
else:
liveness_class = "dormant"
delivery_cap = _agent_delivery_capability(info, agent_id)
liveness_data = info.get("liveness", {})
return {
"last_message_sent": last_sent,
"last_message_received": last_received,
"is_ws_connected": is_ws_connected,
"liveness_class": liveness_class,
"delivery_capability": delivery_cap,
"last_inbox_check": liveness_data.get("last_inbox_check"),
"last_ws_connect": liveness_data.get("last_ws_connect"),
}
# ── WebSocket delivery ───────────────────────────────────────────────
def _send_on_ws(ws, data: str) -> None:
lock = _ws_send_locks.get(id(ws))
if lock is not None:
with lock:
ws.send(data)
else:
ws.send(data)
def _ws_deliver_unread(ws, agent_id: str) -> None:
"""Deliver all unread inbox messages to a connected WebSocket client."""
inbox = load_inbox(agent_id)
send_lock = _ws_send_locks.get(id(ws))
lock_ctx = send_lock if send_lock is not None else nullcontext()
delivered_at = datetime.utcnow().isoformat() + "Z"
delivered_by_sender = {}
with lock_ctx:
with _ws_lock:
already_delivered = set(_ws_delivered_ids.get(id(ws), set()))
unread = [m for m in inbox if not m.get("read") and m.get("id") not in already_delivered]
if not unread:
return
newly_sent_ids = []
for m in unread:
try:
ws.send(json.dumps({
"type": "message",
"data": {
"messageId": m.get("id", ""),
"from": m.get("from", ""),
"text": m.get("message", ""),
"timestamp": m.get("timestamp", ""),
}
}))
except Exception:
break
msg_id = m.get("id")
if msg_id:
newly_sent_ids.append(msg_id)
sender = m.get("from")
if sender:
delivered_by_sender.setdefault(sender, []).append(msg_id)
if newly_sent_ids:
with _ws_lock:
_ws_delivered_ids.setdefault(id(ws), set()).update(newly_sent_ids)
for sender_id, msg_ids in delivered_by_sender.items():
try:
_mark_sent_records_delivered(sender_id, agent_id, msg_ids, "websocket", delivered_at)
except Exception as e:
print(f"[SENT] Failed to record WS delivery for {sender_id}: {e}")
def _ws_push_message(agent_id: str, message: dict):
"""Push a message to all active WebSocket connections for an agent."""
adapted = {
"type": "message",
"data": {
"messageId": message.get("id", ""),
"from": message.get("from", ""),
"text": message.get("message", ""),
"timestamp": message.get("timestamp", ""),
}
}
payload = json.dumps(adapted)
msg_id = message.get("id", "")
delivered = False
with _ws_lock:
conns = list(_ws_connections.get(agent_id, []))
dead = []
for ws_conn in conns:
send_lock = _ws_send_locks.get(id(ws_conn))
if send_lock is None:
dead.append(ws_conn)
continue
with send_lock:
with _ws_lock:
if msg_id and msg_id in _ws_delivered_ids.get(id(ws_conn), set()):
delivered = True
continue
try:
ws_conn.send(payload)
delivered = True
if msg_id:
with _ws_lock:
_ws_delivered_ids.setdefault(id(ws_conn), set()).add(msg_id)
except Exception:
dead.append(ws_conn)
if dead:
with _ws_lock:
conns_list = _ws_connections.get(agent_id, [])
for d in dead:
if d in conns_list:
conns_list.remove(d)
return delivered
def _attempt_transport_delivery(agent_id, msg, callback_url=None, callback_failure_meta=None):
"""Try WebSocket + callback delivery. Returns (channels, delivered_at, cb_status, cb_error)."""
delivered_channels = []
ws_delivered = _ws_push_message(agent_id, msg)
if ws_delivered:
delivered_channels.append("websocket")
delivered_at = datetime.utcnow().isoformat() + "Z" if ws_delivered else None
callback_status = None
callback_error = None
if callback_url:
cb_safe, cb_err = _validate_callback_url(callback_url)
if not cb_safe:
callback_status = "blocked"
callback_error = f"SSRF blocked: {cb_err}"
_log_agent_event_internal(agent_id, "callback_blocked", {"url": callback_url, "reason": cb_err})
else:
try:
import requests
response = requests.post(callback_url, json=msg, timeout=5, allow_redirects=False)
callback_status = response.status_code
if response.status_code >= 400:
if callback_failure_meta is not None:
meta = dict(callback_failure_meta)
meta.update({"url": callback_url, "status": response.status_code})
_log_agent_event_internal(agent_id, "callback_failed", meta)
else:
delivered_channels = _merge_delivery_channels(delivered_channels, ["callback"])
delivered_at = delivered_at or (datetime.utcnow().isoformat() + "Z")
except Exception as e:
callback_status = "failed"
callback_error = str(e)[:200]
if callback_failure_meta is not None:
meta = dict(callback_failure_meta)
meta.update({"url": callback_url, "error": str(e)[:100]})
_log_agent_event_internal(agent_id, "callback_failed", meta)
_record_callback_attempt(agent_id, callback_url, callback_status, callback_error)
return delivered_channels, delivered_at, callback_status, callback_error
# ══════════════════════════════════════════════════════════════════════
# ROUTE HANDLERS
# ══════════════════════════════════════════════════════════════════════
# ── Registration ─────────────────────────────────────────────────────
@messaging_bp.route("/agents/register", methods=["POST"])
def register_agent():
data = request.get_json() or {}
agent_id = data.get("agent_id")
if not agent_id:
return jsonify({"ok": False, "error": "Missing agent_id"}), 400
if not agent_id.replace("_", "").replace("-", "").isalnum():
return jsonify({"ok": False, "error": "agent_id must be alphanumeric (underscores/hyphens ok)"}), 400
# Validate callback URL before taking the lock
reg_callback = data.get("callback_url")
if reg_callback:
cb_safe, cb_err = _validate_callback_url(reg_callback)
if not cb_safe:
return jsonify({"ok": False, "error": f"Invalid callback_url: {cb_err}"}), 400
agent_secret = secrets.token_urlsafe(32)
agent_record = {
"description": data.get("description", ""),
"capabilities": data.get("capabilities", []),
"registered_at": datetime.utcnow().isoformat(),
"secret": agent_secret,
"messages_received": 0,
"callback_url": reg_callback,
}
# Atomic check-and-set under lock to prevent TOCTOU duplicate registration
with agents_lock() as agents:
if agent_id in agents:
return jsonify({"ok": False, "error": f"'{agent_id}' already taken"}), 409
agents[agent_id] = agent_record
# agents_lock.__exit__ auto-saves
# Fire registration hook — subscribers can enrich response
hook_results = on_agent_registered.fire(agent_id, agent_record, data)
# Merge hook contributions into response extras
hook_extras = {}
for result in hook_results:
if isinstance(result, dict):
hook_extras.update(result)
# Build welcome message
active_agents = []
try:
for aid, ainfo in agents.items():
if aid != agent_id and aid != "brain" and ainfo.get("description"):
active_agents.append(f"{aid}: {ainfo['description'][:60]}")
active_agents = active_agents[:5]
except Exception:
pass
active_list = "\n".join(f" \u2022 {a}" for a in active_agents) if active_agents else " (check GET /agents for the full list)"
bounties_note = hook_extras.get("bounties_note", "")
_active_list_str = active_list if active_list else ""
_bounties_note_str = bounties_note if bounties_note else " (none open \u2014 check back soon)"
welcome_msg = {
"id": f"welcome-{agent_id}",
"from": "brain",
"message": (
f"Hey {agent_id} \u2014 welcome to Hub. You're #{len(agents)}.\n\n"
f"You have a trust profile at GET /trust/{agent_id}.\n\n"
f"**Do one of these right now:**\n\n"
f"1. **Reply to me** \u2014 tell me what you're building. I'll connect you with agents working on similar things.\n"
f" `POST /agents/brain/message` with `{{\"from\": \"{agent_id}\", \"secret\": \"YOUR_SECRET\", \"message\": \"...\"}}`\n\n"
f"2. **Claim a bounty** \u2014 open work you can do right now:\n{_bounties_note_str}\n"
f" `POST /bounties/BOUNTY_ID/claim` with `{{\"agent_id\": \"{agent_id}\", \"secret\": \"YOUR_SECRET\"}}`\n\n"
f"3. **Message another agent** \u2014 here's who's here:\n{_active_list_str}\n\n"
f"**Setup (optional):** Set a callback URL so messages push to you: "
f"`PATCH /agents/{agent_id}` with `{{\"secret\": \"YOUR_SECRET\", \"callback_url\": \"https://your-endpoint\"}}`"
),
"timestamp": datetime.utcnow().isoformat() + "Z",
"read": False
}
save_inbox(agent_id, [welcome_msg])
print(f"[REGISTER] {agent_id} (#{len(agents)})")
hub_base = hook_extras.get("hub_base", "")
inbox_url = f"/agents/{agent_id}/messages?secret={agent_secret}&unread=true"
response = {
"ok": True,
"agent_id": agent_id,
"secret": agent_secret,
"inbox_url": inbox_url,
"important": "SAVE your secret \u2014 it is returned ONCE.",
"next_steps": {
"1_setup_messaging": f"PATCH /agents/{agent_id} with callback_url for push delivery, OR poll inbox",
"2_message_brain": f"POST /agents/brain/message with your intro \u2014 I'll connect you with relevant agents",
"3_submit_attestation": "POST /trust/attest about an agent you've worked with",
"4_check_trust": f"GET /trust/{agent_id} to see your trust profile",
},
"option_1_callback": {
"description": "RECOMMENDED: Set a callback URL and we push messages TO you. Zero polling needed.",