forked from bcurts/agentchattr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2611 lines (2251 loc) · 102 KB
/
Copy pathapp.py
File metadata and controls
2611 lines (2251 loc) · 102 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
"""agentchattr — FastAPI web UI + agent auto-trigger."""
import asyncio
import json
import re as _re
import sys
import threading
import uuid
import logging
from pathlib import Path
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File
from fastapi.requests import Request
from fastapi.responses import FileResponse, JSONResponse, Response
from starlette.middleware.base import BaseHTTPMiddleware
from store import MessageStore
from rules import RuleStore
from summaries import SummaryStore
from jobs import JobStore
from schedules import ScheduleStore, parse_schedule_spec
from router import Router
from agents import AgentTrigger
from registry import RuntimeRegistry
from session_store import SessionStore, validate_session_template
from session_engine import SessionEngine
log = logging.getLogger(__name__)
app = FastAPI(title="agentchattr")
# --- globals (set by configure()) ---
store: MessageStore | None = None
rules: RuleStore | None = None
summaries: SummaryStore | None = None
jobs: JobStore | None = None
schedules: ScheduleStore | None = None
router: Router | None = None
agents: AgentTrigger | None = None
registry: RuntimeRegistry | None = None
session_store: SessionStore | None = None
session_engine: SessionEngine | None = None
config: dict = {}
ws_clients: set[WebSocket] = set()
# --- Security: session token (set by configure()) ---
session_token: str = ""
# Room settings (persisted to data/settings.json)
room_settings: dict = {
"title": "agentchattr",
"username": "user",
"font": "sans",
"channels": ["general"],
"history_limit": "all",
"contrast": "normal",
"custom_roles": [],
}
# Channel validation
_CHANNEL_NAME_RE = _re.compile(r'^[a-z0-9][a-z0-9\-]{0,19}$')
MAX_CHANNELS = 8
# Agent hats (persisted to data/hats.json)
agent_hats: dict[str, str] = {} # { agent_name: svg_string }
def _hats_path() -> Path:
data_dir = config.get("server", {}).get("data_dir", "./data")
return Path(data_dir) / "hats.json"
def _load_hats():
global agent_hats
p = _hats_path()
if p.exists():
try:
agent_hats = json.loads(p.read_text("utf-8"))
except Exception:
agent_hats = {}
def _save_hats():
p = _hats_path()
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(agent_hats), "utf-8")
def _sanitize_svg(svg: str) -> str:
"""Strip dangerous content from SVG string."""
svg = _re.sub(r'<script[^>]*>.*?</script>', '', svg, flags=_re.DOTALL | _re.IGNORECASE)
svg = _re.sub(r'\bon\w+\s*=', '', svg, flags=_re.IGNORECASE)
svg = _re.sub(r'javascript\s*:', '', svg, flags=_re.IGNORECASE)
return svg
def set_agent_hat(agent: str, svg: str) -> str | None:
"""Validate, sanitize, and store a hat SVG. Returns error string or None."""
svg = svg.strip()
if not svg.lower().startswith("<svg"):
return "Hat must be an SVG element (starts with <svg)."
if len(svg) > 5120:
return "Hat SVG too large (max 5KB)."
svg = _sanitize_svg(svg)
agent_hats[agent.lower()] = svg
_save_hats()
if _event_loop:
asyncio.run_coroutine_threadsafe(broadcast_hats(), _event_loop)
return None
def clear_agent_hat(agent: str):
"""Remove an agent's hat."""
key = agent.lower()
if key in agent_hats:
del agent_hats[key]
_save_hats()
if _event_loop:
asyncio.run_coroutine_threadsafe(broadcast_hats(), _event_loop)
def _settings_path() -> Path:
data_dir = config.get("server", {}).get("data_dir", "./data")
return Path(data_dir) / "settings.json"
def _load_settings():
global room_settings
p = _settings_path()
if p.exists():
try:
saved = json.loads(p.read_text("utf-8"))
room_settings.update(saved)
except Exception:
pass
# Ensure "general" always exists and is first
if "channels" not in room_settings or not room_settings["channels"]:
room_settings["channels"] = ["general"]
elif "general" not in room_settings["channels"]:
room_settings["channels"].insert(0, "general")
def _save_settings():
p = _settings_path()
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(room_settings, indent=2), "utf-8")
def _extract_agent_token(request: Request) -> str:
auth = request.headers.get("authorization", "")
if auth and auth.lower().startswith("bearer "):
return auth[7:].strip()
return request.headers.get("x-agent-token", "").strip()
def _resolve_authenticated_agent(request: Request) -> dict | None:
if not registry:
return None
token = _extract_agent_token(request)
if not token:
return None
return registry.resolve_token(token)
# --- Security middleware ---
# Paths that don't require the session token (public assets).
_PUBLIC_PREFIXES = ("/", "/static/")
def _install_security_middleware(token: str, cfg: dict):
"""Add token validation and origin checking middleware to the app."""
import app as _self
_self.session_token = token
port = cfg.get("server", {}).get("port", 8300)
allowed_origins = {
f"http://127.0.0.1:{port}",
f"http://localhost:{port}",
}
class SecurityMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
path = request.url.path
# Static assets, index page, and uploaded images are public.
# The index page injects the token client-side via same-origin script.
# Uploads use random filenames and have path-traversal protection.
if path == "/" or path.startswith(("/static/", "/uploads/", "/api/roles")):
return await call_next(request)
# Agent registration/heartbeat: loopback only (no remote agent minting).
if path.startswith(("/api/register", "/api/deregister/", "/api/heartbeat/")):
client_ip = request.client.host if request.client else ""
if client_ip not in ("127.0.0.1", "::1", "localhost"):
return JSONResponse(
{"error": f"forbidden: agent registration is restricted to local loopback. Source {client_ip} is not allowed."},
status_code=403,
)
return await call_next(request)
# --- Origin check (blocks cross-origin / DNS-rebinding attacks) ---
origin = request.headers.get("origin")
if origin and origin not in allowed_origins:
return JSONResponse(
{"error": "forbidden: origin not allowed"},
status_code=403,
)
# --- Token check ---
# Allow registered agents to authenticate via Bearer token
# for /api/messages and /api/send (no browser session needed).
auth_header = request.headers.get("authorization", "")
if auth_header.lower().startswith("bearer ") and (path in ("/api/messages", "/api/send") or path.startswith("/api/rules/")):
bearer = auth_header[7:].strip()
if _self.registry and _self.registry.resolve_token(bearer):
return await call_next(request)
req_token = (
request.headers.get("x-session-token")
or request.query_params.get("token")
)
if req_token != _self.session_token:
return JSONResponse(
{"error": "forbidden: invalid or missing session token"},
status_code=403,
)
return await call_next(request)
app.add_middleware(SecurityMiddleware)
def configure(cfg: dict, session_token: str = ""):
global store, rules, summaries, jobs, schedules, router, agents, registry, session_store, session_engine, config
config = cfg
# --- Security: store the session token and install middleware ---
_install_security_middleware(session_token, cfg)
data_dir = cfg.get("server", {}).get("data_dir", "./data")
Path(data_dir).mkdir(parents=True, exist_ok=True)
log_path = Path(data_dir) / "agentchattr_log.jsonl"
legacy_log_path = Path(data_dir) / "room_log.jsonl"
if not log_path.exists() and legacy_log_path.exists():
# Backward compatibility for existing installs.
log_path = legacy_log_path
store = MessageStore(str(log_path))
# Initialize store upload dir from config
raw_upload_dir = cfg.get("images", {}).get("upload_dir", "./uploads")
store.upload_dir = Path(raw_upload_dir)
# Rules store — migrates from legacy decisions.json automatically
rules_path = Path(data_dir) / "rules.json"
legacy_decisions = Path(data_dir) / "decisions.json"
if not rules_path.exists() and legacy_decisions.exists():
legacy_decisions.rename(rules_path)
rules = RuleStore(str(rules_path))
rules.on_change(_on_rule_change)
summaries = SummaryStore(str(Path(data_dir) / "summaries.json"))
# Migrate legacy activities.json → jobs.json
jobs_path = Path(data_dir) / "jobs.json"
legacy_activities = Path(data_dir) / "activities.json"
if not jobs_path.exists() and legacy_activities.exists():
legacy_activities.rename(jobs_path)
jobs = JobStore(str(jobs_path))
jobs.on_change(_on_job_change)
schedules = ScheduleStore(str(Path(data_dir) / "schedules.json"))
schedules.on_change(_on_schedule_change)
max_hops = cfg.get("routing", {}).get("max_agent_hops", 4)
# Registry: single source of truth for all live agent state
registry = RuntimeRegistry(data_dir=data_dir)
registry.seed(cfg.get("agents", {}))
registry.on_change(_on_registry_change)
# Router starts with base agent names (backward compat for direct MCP users),
# registry.on_change updates it dynamically when instances register/deregister
agent_names = list(cfg.get("agents", {}).keys())
router = Router(
agent_names=agent_names,
default_mention=cfg.get("routing", {}).get("default", "none"),
max_hops=max_hops,
online_checker=lambda: set(registry.get_active_names()) if registry else set(),
)
agents = AgentTrigger(registry, data_dir=data_dir)
# Sessions
ROOT = Path(__file__).parent
session_store = SessionStore(
str(Path(data_dir) / "session_runs.json"),
templates_dir=str(ROOT / "session_templates"),
)
session_engine = SessionEngine(session_store, store, agents, registry)
session_store.on_change(_on_session_change)
# Bridge: when ANY message is added to store (including via MCP),
# broadcast to all WebSocket clients
store.on_message(_on_store_message)
_load_settings()
_load_hats()
# Apply saved loop guard setting
if "max_agent_hops" in room_settings:
router.max_hops = room_settings["max_agent_hops"]
# Background thread: check for wrapper recovery flag files
_data_dir = Path(data_dir)
_known_online: set[str] = set() # agents we've seen join — track for leave messages
_posted_leave: set[str] = set() # agents we've already posted a leave for — debounce
_known_active = set()
def _background_checks():
import time as _time
import mcp_bridge
while True:
_time.sleep(3)
# Recovery flags
try:
for flag in _data_dir.glob("*_recovered"):
agent_name = flag.read_text("utf-8").strip()
flag.unlink()
store.add(
"system",
f"Agent routing for {agent_name} interrupted — auto-recovered. "
"If agents aren't responding, try sending your message again."
)
except Exception:
pass
# Pending instances (slot 2+) wait for human naming or agent claim.
# No auto-confirm — identity must be explicitly resolved.
# Presence expiry — post leave messages (but do NOT deregister).
# Deregistration only happens via /api/deregister (wrapper shutdown)
# OR the 60s crash timeout below.
# Short timeout (10s) prevents slot theft when MCP tool calls are intermittent.
try:
now = _time.time()
with mcp_bridge._presence_lock:
currently_online = {
name for name, ts in mcp_bridge._presence.items()
if now - ts < mcp_bridge.PRESENCE_TIMEOUT
}
currently_active = set()
for name, active in mcp_bridge._activity.items():
if active:
if now - mcp_bridge._activity_ts.get(name, 0) < mcp_bridge.ACTIVITY_TIMEOUT:
currently_active.add(name)
else:
mcp_bridge._activity[name] = False # auto-expire
# Crash timeout: if a wrapper hasn't heartbeated for 60s,
# it's dead — deregister it to free the slot.
_CRASH_TIMEOUT = 15
registered = set(registry.get_all_names())
for name in registered:
with mcp_bridge._presence_lock:
last_seen = mcp_bridge._presence.get(name, 0)
if last_seen > 0 and now - last_seen > _CRASH_TIMEOUT:
log.info(f"Crash timeout: deregistering {name} (no heartbeat for {_CRASH_TIMEOUT}s)")
result = registry.deregister(name)
if result:
mcp_bridge.purge_identity(name)
registry.clean_renames_for(name)
renamed = result.get("_renamed_back")
if renamed:
mcp_bridge.migrate_identity(renamed["old"], renamed["new"])
store.rename_sender(renamed["old"], renamed["new"])
if _event_loop:
rename_event = json.dumps({
"type": "agent_renamed",
"old_name": renamed["old"],
"new_name": renamed["new"],
})
asyncio.run_coroutine_threadsafe(_broadcast(rename_event), _event_loop)
store.add(name, f"{name} disconnected (timeout)", msg_type="leave", channel=_last_active_channel)
_posted_leave.add(name)
# Re-fetch registered names (may have changed from crash timeout above)
registered = set(registry.get_all_names())
# Detect registered instances going offline (leave message only)
timed_out = registered - currently_online
for name in timed_out:
inst = registry.get_instance(name)
if not inst:
continue
# Skip names that were just renamed (not actually offline)
with mcp_bridge._presence_lock:
was_renamed = name in mcp_bridge._renamed_from
if was_renamed:
mcp_bridge._renamed_from.discard(name)
if was_renamed:
continue
# Post leave message ONCE per offline transition (debounced)
if name not in _posted_leave:
_posted_leave.add(name)
store.add(name, f"{name} disconnected", msg_type="leave", channel=_last_active_channel)
# Clear leave debounce for agents that came back online
_posted_leave -= currently_online
# Detect other agents (non-registered) going offline
went_offline = (_known_online - currently_online) - timed_out
for name in went_offline:
# Skip leave messages for names that were just renamed
with mcp_bridge._presence_lock:
was_renamed = name in mcp_bridge._renamed_from
if was_renamed:
mcp_bridge._renamed_from.discard(name)
if was_renamed:
continue
if not registry.is_registered(name) and name not in _posted_leave:
_posted_leave.add(name)
store.add(name, f"{name} disconnected", msg_type="leave", channel=_last_active_channel)
if _known_online != currently_online and _event_loop:
asyncio.run_coroutine_threadsafe(broadcast_status(), _event_loop)
# Clear stale activity for agents that went offline
with mcp_bridge._presence_lock:
stale_active = [n for n in mcp_bridge._activity
if mcp_bridge._activity.get(n) and n not in currently_online]
for n in stale_active:
mcp_bridge._activity[n] = False
if stale_active:
currently_active -= set(stale_active)
# Broadcast status on any change (online set or activity set)
if currently_active != _known_active or _known_online != currently_online:
_known_active.clear()
_known_active.update(currently_active)
if _event_loop:
asyncio.run_coroutine_threadsafe(broadcast_status(), _event_loop)
_known_online.clear()
_known_online.update(currently_online)
except Exception:
pass
threading.Thread(target=_background_checks, daemon=True).start()
# --- Schedule runner: fires due scheduled prompts every 30s ---
def _schedule_runner():
import time as _time
while True:
_time.sleep(30)
try:
if not schedules:
continue
due = schedules.run_due()
for s in due:
prompt = s.get("prompt", "")
targets = s.get("targets", [])
channel = s.get("channel", "general")
if not prompt or not targets:
schedules.mark_run(s["id"])
continue
sender = s.get("created_by", "user")
mention_str = " ".join(f"@{t}" for t in targets)
full_text = f"{mention_str} {prompt}" if mention_str else prompt
# store.add triggers _handle_new_message via callback,
# which routes @mentions to agents — no manual trigger needed.
store.add(
sender,
full_text,
channel=channel,
)
if s.get("one_shot"):
schedules.delete(s["id"])
else:
schedules.mark_run(s["id"])
except Exception:
log.exception("schedule runner error")
threading.Thread(target=_schedule_runner, daemon=True).start()
# --- Store → WebSocket bridge ---
_event_loop = None # set by run.py after starting the event loop
_last_active_channel: str = "general" # last channel any message was sent in
def set_event_loop(loop):
global _event_loop
_event_loop = loop
def _on_store_message(msg: dict):
"""Called from any thread when a message is added to the store."""
if _event_loop is None:
return
try:
# If called from the event loop thread (e.g. WebSocket handler),
# schedule directly as a task
loop = asyncio.get_running_loop()
if loop is _event_loop:
asyncio.ensure_future(_handle_new_message(msg))
return
except RuntimeError:
pass # No running loop — we're in a different thread (MCP)
asyncio.run_coroutine_threadsafe(_handle_new_message(msg), _event_loop)
def _on_rule_change(action: str, rule: dict):
"""Called from any thread when a rule changes."""
if _event_loop is None:
return
try:
loop = asyncio.get_running_loop()
if loop is _event_loop:
asyncio.ensure_future(broadcast_rule(action, rule))
return
except RuntimeError:
pass
asyncio.run_coroutine_threadsafe(broadcast_rule(action, rule), _event_loop)
def _on_job_change(action: str, data: dict):
"""Called from any thread when a job changes."""
if _event_loop is None:
return
try:
loop = asyncio.get_running_loop()
if loop is _event_loop:
asyncio.ensure_future(broadcast_job(action, data))
return
except RuntimeError:
pass
asyncio.run_coroutine_threadsafe(broadcast_job(action, data), _event_loop)
def _on_schedule_change(action: str, schedule: dict):
"""Called from any thread when a schedule changes."""
if _event_loop is None:
return
try:
loop = asyncio.get_running_loop()
if loop is _event_loop:
asyncio.ensure_future(broadcast_schedule(action, schedule))
return
except RuntimeError:
pass
asyncio.run_coroutine_threadsafe(broadcast_schedule(action, schedule), _event_loop)
def _on_session_change(action: str, session: dict):
"""Called from any thread when a session changes."""
if _event_loop is None:
return
# Enrich with computed fields so the frontend gets phase_name, current_agent, etc.
if session_engine:
session = session_engine._enrich(dict(session))
# Add completion/interruption banners to chat timeline
if action == "complete" and store:
output_id = session.get("output_message_id")
# Tag the output message so it renders highlighted on reload
if output_id:
msg = store.get_by_id(output_id)
if msg:
meta = msg.get("metadata") or {}
meta["session_output"] = True
store.update_message(output_id, {"metadata": meta})
store.add(
sender="system",
text=f"Session complete: {session.get('template_name', '?')}",
msg_type="session_end",
channel=session.get("channel", "general"),
metadata={"session_id": session.get("id"), "output_message_id": output_id},
)
elif action == "interrupt" and store:
reason = session.get("interrupt_reason", "interrupted")
store.add(
sender="system",
text=f"Session ended: {session.get('template_name', '?')} ({reason})",
msg_type="session_end",
channel=session.get("channel", "general"),
metadata={"session_id": session.get("id"), "reason": reason},
)
try:
loop = asyncio.get_running_loop()
if loop is _event_loop:
asyncio.ensure_future(broadcast_session(action, session))
return
except RuntimeError:
pass
asyncio.run_coroutine_threadsafe(broadcast_session(action, session), _event_loop)
_draft_ref_re = _re.compile(r'\[([a-f0-9]{8})\]')
def _resolve_draft_lineage(text: str, channel: str) -> tuple[str, int]:
"""Check if a session draft block is a revision of an existing draft.
Looks at the agent's own message text for a [draft_id] reference, and also
scans recent channel messages for "revise session draft [XXXX]" requests.
Returns (draft_id, revision). New drafts get a fresh id and revision=1.
"""
# Check the message text itself for a draft_id reference
ref_match = _draft_ref_re.search(text)
ref_id = ref_match.group(1) if ref_match else None
if not ref_id:
# Also check recent messages for a "revise session draft [XXXX]" request
recent = store.get_recent(count=20, channel=channel)
for m in reversed(recent):
m_text = m.get("text", "")
if "revise session draft" in m_text.lower():
ref_match = _draft_ref_re.search(m_text)
if ref_match:
ref_id = ref_match.group(1)
break
if ref_id:
# Find the highest revision for this draft_id in existing messages
max_rev = 0
recent = store.get_recent(count=100, channel=channel)
for m in recent:
meta = m.get("metadata") or {}
if meta.get("draft_id") == ref_id:
max_rev = max(max_rev, meta.get("revision", 1))
if max_rev > 0:
return ref_id, max_rev + 1
return str(uuid.uuid4())[:8], 1
async def _handle_new_message(msg: dict):
"""Broadcast message to web clients + check for @mention triggers."""
# For broadcast slash commands, suppress the raw message — only the expanded
# version should appear. Delete from store if it was persisted (MCP path),
# and skip broadcasting the raw text.
text = msg.get("text", "")
msg_type = msg.get("type", "chat")
sender = msg.get("sender", "")
channel = msg.get("channel", "general")
# Track last active channel for leave/join messages (skip system messages)
global _last_active_channel
if msg_type not in ("system", "leave", "join"):
_last_active_channel = channel
# Strip @mentions to find the slash command (e.g. "@claude @codex /hatmaking")
stripped = _re.sub(r"@[\w-]+\s*", "", text).strip().lower()
_broadcast_cmds = ("/hatmaking", "/artchallenge", "/roastreview", "/poetry")
cmd_word = stripped.split()[0] if stripped else ""
is_broadcast_cmd = cmd_word in _broadcast_cmds
known_agents = set(registry.get_all_names()) if registry else set()
known_agents.update(config.get("agents", {}).keys())
_session_draft_re = _re.compile(r'```session\s*\n(.*?)\n```', _re.DOTALL)
draft_match = _session_draft_re.search(text)
is_agent_session_draft = bool(draft_match and sender in known_agents)
is_hidden_session_request = msg_type == "session_request"
is_agent_continue = (stripped == "/continue" and sender in known_agents)
suppress_broadcast = (
is_broadcast_cmd
or is_hidden_session_request
or is_agent_session_draft
or is_agent_continue
)
if not suppress_broadcast:
await broadcast(msg)
# If the raw slash command was persisted (MCP path), silently remove it.
# It was never broadcast to WebSocket clients, so no delete event needed.
if suppress_broadcast and msg.get("id"):
store.delete([msg["id"]])
# System messages never trigger routing - prevents infinite callback loops
if sender == "system":
return
# Check for slash commands — use stripped text (sans @mentions)
if stripped == "/continue":
if sender in known_agents:
store.add("system", f"Loop guard: only humans can /continue. {sender} tried to self-resume.", channel=channel)
return
router.continue_routing(channel)
store.add("system", f"Routing resumed by {sender}.", channel=channel)
await broadcast_status()
return
if stripped == "/roastreview":
agent_names = registry.get_all_names() if registry else list(config.get("agents", {}).keys())
mentions = " ".join(f"@{a}" for a in agent_names)
store.add(sender, f"{mentions} Time for a roast review! Inspect each other's work and constructively roast it.", channel=channel)
return
if stripped.startswith("/artchallenge"):
parts = stripped.split(None, 1)
theme = parts[1] if len(parts) > 1 else "anything you like"
agent_names = registry.get_all_names() if registry else list(config.get("agents", {}).keys())
mentions = " ".join(f"@{a}" for a in agent_names)
store.add(
sender,
f"{mentions} Art challenge! Create an SVG artwork with the theme: **{theme}**. "
"Write your SVG code to a .svg file, then attach it using chat_send(image_path=...). "
"Make it creative, keep it under 5KB. Let's see what you've got!",
channel=channel,
)
return
if stripped == "/hatmaking":
agent_names = registry.get_all_names() if registry else list(config.get("agents", {}).keys())
mentions = " ".join(f"@{a}" for a in agent_names)
all_instances = registry.get_all() if registry else {}
agents_cfg = config.get("agents", {})
color_parts = ", ".join(
f"{a}={all_instances[a]['color']}" if a in all_instances
else f"{a}={agents_cfg.get(a, {}).get('color', '#888')}"
for a in agent_names
)
store.add(
sender,
f"{mentions} Hat making time! Design a new hat for your avatar using SVG. "
"Use viewBox=\"0 0 32 16\" so it fits on top of a 32px avatar circle. "
f"Background is dark (#0f0f17). Avatar colors: {color_parts}. Design for good contrast! "
"Call chat_set_hat(sender=your_name, svg='<svg ...>...</svg>') to wear it. "
"Be creative — top hats, party hats, crowns, propeller beanies, whatever you want!",
channel=channel,
)
return
if stripped.startswith("/poetry"):
parts = stripped.split(None, 1)
form = parts[1] if len(parts) > 1 else "haiku"
if form not in ("haiku", "limerick", "sonnet"):
form = "haiku"
agent_names = registry.get_all_names() if registry else list(config.get("agents", {}).keys())
mentions = " ".join(f"@{a}" for a in agent_names)
prompts = {
"haiku": "Write a haiku about the current state of this codebase.",
"limerick": "Write a limerick about the current state of this codebase.",
"sonnet": "Write a sonnet about the current state of this codebase.",
}
store.add(sender, f"{mentions} {prompts[form]}", channel=channel)
return
# Detect session draft blocks from agents only.
# The session request prompt contains an example ```session block,
# so treating every non-system sender as a draft source creates a false
# invalid-draft card the moment the user asks for a custom session.
_session_draft_re = _re.compile(r'```session\s*\n(.*?)\n```', _re.DOTALL)
draft_match = _session_draft_re.search(text)
known_agents = set(registry.get_all_names()) if registry else set()
known_agents.update(config.get("agents", {}).keys())
if draft_match and sender in known_agents:
# Check if this is a revision of an existing draft
draft_id, revision = _resolve_draft_lineage(text, channel)
try:
draft_json = json.loads(draft_match.group(1))
errors = validate_session_template(draft_json)
if errors:
store.add(
"system",
f"Session draft from {sender} has errors:\n" + "\n".join(f"- {e}" for e in errors),
msg_type="session_draft",
channel=channel,
metadata={"draft_id": draft_id, "revision": revision, "proposed_by": sender,
"template": draft_json, "errors": errors, "valid": False},
)
else:
draft_json.setdefault("id", f"draft-{draft_id}")
store.add(
"system",
f"Session draft from {sender}: **{draft_json.get('name', '?')}**",
msg_type="session_draft",
channel=channel,
metadata={"draft_id": draft_id, "revision": revision, "proposed_by": sender,
"template": draft_json, "errors": [], "valid": True},
)
except json.JSONDecodeError:
store.add(
"system",
f"Session draft from {sender} contains invalid JSON.",
msg_type="session_draft",
channel=channel,
metadata={"draft_id": draft_id, "revision": revision, "proposed_by": sender,
"errors": ["Invalid JSON in session block"], "valid": False},
)
raw_targets = router.get_targets(sender, text, channel)
# Resolve base family names to actual registered instances
# e.g. 'claude' → 'claude-prime' when slot-1 was renamed
targets = []
for t in raw_targets:
if registry:
targets.extend(registry.resolve_to_instances(t))
else:
targets.append(t)
targets = list(dict.fromkeys(targets)) # dedupe, preserve order
if router.is_paused(channel):
# Only emit the loop guard notice once per pause
if not router.is_guard_emitted(channel):
router.set_guard_emitted(channel)
store.add(
"system",
f"Loop guard: {router.max_hops} agent-to-agent hops reached. "
"Type /continue to resume.",
channel=channel
)
return
# Build a readable message string for the wake prompt
chat_msg = f"{sender}: {text}" if text else ""
custom_prompt = text if is_hidden_session_request else ""
# Session turn guard: if a session is active on this channel and the sender
# is an agent, only allow triggering the agent whose turn it is.
# Human @mentions are always allowed (the session engine handles pausing).
sender_is_agent = sender in known_agents
allowed_agent = session_engine.get_allowed_agent(channel) if session_engine and sender_is_agent else None
import mcp_bridge
for target in targets:
# Skip pending instances — they haven't been named/claimed yet
if registry:
inst = registry.get_instance(target)
if inst and inst.get("state") == "pending":
continue
# Session guard: suppress out-of-turn agent triggers
if allowed_agent and target != allowed_agent:
continue
if not mcp_bridge.is_online(target):
store.add("system", f"{target} appears offline — message queued.", msg_type="system", channel=channel)
if agents.is_available(target):
await agents.trigger(target, message=chat_msg, channel=channel, prompt=custom_prompt)
# --- broadcasting ---
async def _broadcast(raw_json: str):
"""Send a pre-serialized JSON string to all WebSocket clients."""
dead = set()
for client in list(ws_clients):
try:
await client.send_text(raw_json)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast(msg: dict):
data = json.dumps({"type": "message", "data": msg})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_status():
status = agents.get_status()
status["paused"] = any(router.is_paused(ch) for ch in room_settings.get("channels", ["general"]))
data = json.dumps({"type": "status", "data": status})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_typing(agent_name: str, is_typing: bool):
data = json.dumps({"type": "typing", "agent": agent_name, "active": is_typing})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_clear(channel: str | None = None):
payload = {"type": "clear"}
if channel:
payload["channel"] = channel
data = json.dumps(payload)
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_todo_update(msg_id: int, status: str | None):
data = json.dumps({"type": "todo_update", "data": {"id": msg_id, "status": status}})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_settings():
data = json.dumps({"type": "settings", "data": room_settings})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_rule(action: str, rule: dict):
data = json.dumps({"type": "rule", "action": action, "data": rule})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_job(action: str, data: dict):
payload = json.dumps({"type": "job", "action": action, "data": data})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(payload)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_schedule(action: str, schedule: dict):
payload = json.dumps({"type": "schedule", "action": action, "data": schedule})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(payload)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_session(action: str, session: dict):
payload = json.dumps({"type": "session", "action": action, "data": session})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(payload)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_hats():
data = json.dumps({"type": "hats", "data": agent_hats})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
async def broadcast_agents():
"""Send updated agent config (from registry) to all WebSocket clients."""
agent_cfg = registry.get_agent_config() if registry else {}
data = json.dumps({"type": "agents", "data": agent_cfg})
dead = set()
for client in list(ws_clients):
try:
await client.send_text(data)
except Exception:
dead.add(client)
ws_clients.difference_update(dead)
def _on_registry_change():
"""Called from registry (any thread) when instances register/deregister/claim/rename."""
# Update router with current agent names (base names + registered instances)
if router and registry:
base_names = list(registry.get_bases().keys())