-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupervisor.py
More file actions
executable file
·1990 lines (1817 loc) · 82.5 KB
/
Copy pathsupervisor.py
File metadata and controls
executable file
·1990 lines (1817 loc) · 82.5 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
#!/usr/bin/env python3
"""
supervisor.py - Own the relay lifecycle, tmux mirrors, runtime state, and
local web UI for clcod.
"""
from __future__ import annotations
import argparse
import asyncio
import copy
import hashlib
import json
import os
import secrets
import shlex
import signal
import socket
import subprocess
import sys
import queue
import threading
import time
from http import HTTPStatus
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlparse
import relay
import dispatcher as dispatcher_mod
from event_store import EventStore, import_transcript_to_event_store
from task_state import TaskStateManager, atomic_write_json
SCRIPT_DIR = Path(__file__).resolve().parent
WEB_DIR = SCRIPT_DIR / "web"
class ReusableHTTPServer(ThreadingHTTPServer):
allow_reuse_address = True
def utc_now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def build_ui_url(config: dict[str, Any]) -> str:
ui = config["ui"]
return f"http://{ui['host']}:{ui['port']}"
USAGE_WINDOW_SECONDS = 5 * 60 * 60 # 5-hour rolling window
DEFAULT_USAGE_LIMIT = 50000 # default token budget per window
ROUTE_HISTORY_LIMIT = 8
def build_usage_window(agent: dict[str, Any]) -> dict[str, Any]:
return {
"window_start": time.time(),
"tokens_used": 0,
"limit": agent.get("usage_limit", DEFAULT_USAGE_LIMIT),
}
def build_agent_state(agent: dict[str, Any]) -> dict[str, Any]:
return {
"state": "starting",
"session_id": None,
"mirror_mode": agent["mirror_mode"],
"mirror_view": "log",
"pane_target": None,
"pane_command": None,
"last_error": None,
"last_reply_at": None,
"selected_model": agent.get("selected_model", "default"),
"selected_effort": agent.get("selected_effort", "default"),
"model_options": agent.get("model_options", []),
"effort_options": agent.get("effort_options", []),
"effort_matrix": agent.get("effort_matrix", {}),
"usage_window": build_usage_window(agent),
}
def build_initial_state(config: dict[str, Any]) -> dict[str, Any]:
session = config["tmux"]["session"]
agents = {
agent["name"]: build_agent_state(agent)
for agent in config["agents"]
if agent["enabled"]
}
return {
"app": {
"phase": "booting",
"sleeping": False,
"ui_url": build_ui_url(config),
"default_sender": config["ui"]["default_sender"],
},
"relay": {
"state": "starting",
"pid": os.getpid(),
"last_error": None,
},
"tmux": {
"session": session,
"state": "starting",
"attach_command": f"tmux attach -t {session}",
},
"agents": agents,
"project": {
"active": None,
"name": None,
"path": str(SCRIPT_DIR),
},
"workspace": {
"repo_path": str(SCRIPT_DIR),
"branch": None,
"dirty": False,
"dirty_files": 0,
"sync_state": "idle",
"last_sync_at": None,
"compact_state": "idle",
"last_compact_at": None,
"last_archive_path": None,
},
"dispatcher": {
"state": "disabled",
"router_model": None,
"routes_total": 0,
"absorbs_total": 0,
"tokens_saved": 0,
"pane_target": None,
},
"routing": {
"active": [],
"recent": [],
"last_route_at": None,
},
"tasks": {
"total": 0,
"pending": 0,
"in_progress": 0,
"done": 0,
"last_created_at": None,
},
"transcript": {
"path": str(config["workspace"]["log_path"]),
"last_speaker": "",
"last_updated_at": None,
"rev": 0,
},
"queue": {
"depth": 0,
"active": 0,
"total_processed": 0,
"total_failed": 0,
"last_job_id": None,
"last_completed_at": None,
},
}
def parse_transcript_entries(text: str, limit: int) -> list[dict[str, str]]:
entries: list[dict[str, str]] = []
tagged_speaker: str | None = None
tagged_lines: list[str] = []
def flush_tagged() -> None:
nonlocal tagged_speaker, tagged_lines
if tagged_speaker and tagged_lines:
entry = {"speaker": tagged_speaker, "text": "\n".join(tagged_lines).strip()}
if entry["text"]:
entries.append(entry)
tagged_speaker = None
tagged_lines = []
for line in text.splitlines():
raw_line = line.rstrip()
line = raw_line.strip()
if not line:
flush_tagged()
continue
if line.startswith("[") and line.endswith("]") and len(line) > 2:
flush_tagged()
tagged_speaker = line[1:-1].strip()
continue
if tagged_speaker:
tagged_lines.append(raw_line)
continue
try:
payload = json.loads(line)
if "speaker" in payload and "text" in payload:
entry = {"speaker": payload["speaker"], "text": payload["text"]}
if payload.get("ts"):
entry["ts"] = payload["ts"]
if payload.get("seq"):
entry["seq"] = payload["seq"]
entries.append(entry)
elif "sender" in payload and "body" in payload:
entry = {"speaker": payload["sender"], "text": payload["body"]}
if payload.get("ts"):
entry["ts"] = payload["ts"]
if payload.get("seq"):
entry["seq"] = payload["seq"]
entries.append(entry)
except json.JSONDecodeError:
continue
flush_tagged()
return entries[-limit:]
def fallback_compact_summary(text: str) -> str:
entries = parse_transcript_entries(text, 8)
if not entries:
return "Conversation compacted. No transcript content was available."
fragments: list[str] = []
for entry in entries[-6:]:
speaker = str(entry.get("speaker") or "UNKNOWN")
body = relay.truncate_text(str(entry.get("text") or ""), 72)
fragments.append(f"{speaker}: {body}")
return relay.truncate_text(
"Conversation compacted. Recent context: " + " | ".join(fragments),
700,
)
def build_log_mirror_command(agent: dict[str, Any]) -> str:
log_path = agent["io_log_path"]
work_dir = agent.get("work_dir") or str(SCRIPT_DIR)
script = (
f"mkdir -p {shlex.quote(str(log_path.parent))} && "
f"touch {shlex.quote(str(log_path))} && "
f"printf '%s\\n\\n' {shlex.quote(f'[{agent['name']}] live log mirror')} && "
f"exec tail -n 120 -F {shlex.quote(str(log_path))}"
)
return f"cd {shlex.quote(work_dir)} && bash -lc {shlex.quote(script)}"
def build_resume_mirror_command(agent: dict[str, Any], session_id: str) -> str:
work_dir = agent.get("work_dir") or str(SCRIPT_DIR)
args = [
item.format_map({"session_id": session_id, "work_dir": work_dir, "script_dir": work_dir})
for item in agent.get("mirror_resume_args", [])
]
cmd = [agent["cmd"], *relay.build_selection_args(agent), *args]
return "cd {} && exec {}".format(
shlex.quote(work_dir),
" ".join(shlex.quote(part) for part in cmd),
)
def desired_mirror_view(agent: dict[str, Any], session_id: str | None) -> str:
if agent["mirror_mode"] == "resume" and session_id and agent.get("mirror_resume_args"):
return "resume"
return "log"
def infer_agent_state(
current_state: str,
relay_state: str,
mirror_view: str,
pane_command: str | None,
) -> str:
if current_state == "error":
return "error"
if not pane_command:
return "starting"
if relay_state != "running":
return "auth"
if mirror_view in {"resume", "log"}:
return "ready"
return "warming"
def sort_routes(routes: list[dict[str, Any]]) -> list[dict[str, Any]]:
return sorted(
routes,
key=lambda item: item.get("updated_at") or item.get("started_at") or "",
reverse=True,
)
class StateStore:
def __init__(self, config: dict[str, Any]) -> None:
self.path: Path = config["workspace"]["state_path"]
self._lock = threading.Lock()
self.state = build_initial_state(config)
self.write()
def _write_locked(self) -> None:
atomic_write_json(self.path, self.state)
def write(self) -> None:
with self._lock:
self._write_locked()
def snapshot(self) -> dict[str, Any]:
with self._lock:
return copy.deepcopy(self.state)
def patch(self, section: str, values: dict[str, Any]) -> None:
with self._lock:
self.state[section].update(values)
self._write_locked()
def patch_agent(self, name: str, values: dict[str, Any]) -> None:
with self._lock:
self.state["agents"][name].update(values)
self._write_locked()
def record_agent_usage(self, name: str, tokens: int) -> None:
"""Increment token usage for an agent, resetting the window if expired."""
with self._lock:
agent = self.state["agents"].get(name)
if not agent:
return
window = agent.setdefault("usage_window", {
"window_start": time.time(),
"tokens_used": 0,
"limit": DEFAULT_USAGE_LIMIT,
})
now = time.time()
if now - window["window_start"] >= USAGE_WINDOW_SECONDS:
window["window_start"] = now
window["tokens_used"] = 0
window["tokens_used"] += tokens
self._write_locked()
def patch_tasks_summary(self, values: dict[str, Any]) -> None:
"""Persist the replayed task summary only.
Task counters are durable/replayed state. Other sections in state.json
remain volatile runtime materialized views owned by the supervisor.
"""
with self._lock:
self.state["tasks"].update(values)
self._write_locked()
def fuel_for_agent(self, name: str) -> dict[str, Any]:
"""Return fuel gauge data for a single agent."""
with self._lock:
agent = self.state["agents"].get(name, {})
window = agent.get("usage_window", {})
window_start = window.get("window_start", time.time())
tokens_used = window.get("tokens_used", 0)
limit = window.get("limit", DEFAULT_USAGE_LIMIT)
now = time.time()
# Auto-reset expired windows
if now - window_start >= USAGE_WINDOW_SECONDS:
tokens_used = 0
window_start = now
remaining = max(0, limit - tokens_used)
pct = round((remaining / limit) * 100, 1) if limit > 0 else 0
return {
"window_start": window_start,
"tokens_used": tokens_used,
"limit": limit,
"remaining": remaining,
"pct_remaining": pct,
}
class RuntimeSupervisor:
def __init__(self, config: dict[str, Any]) -> None:
self.config = config
self.session = config["tmux"]["session"]
self.workspace = config["workspace"]
self.settings_lock = threading.Lock()
self.event_store = EventStore(config["workspace"]["events_db_path"])
self.apply_saved_preferences()
self.state = StateStore(config)
self.task_state = TaskStateManager(
event_store=self.event_store,
tasks_path=config["workspace"]["tasks_path"],
state_store=self.state,
event_callback=self.handle_relay_event,
)
self._sleeping = False
self._sleep_lock = threading.Lock()
self.stop_event = asyncio.Event()
self._password_hash: str = self._hash_password(self.password())
self.auth_tokens: set[str] = set()
self._load_auth_tokens()
self.rebuild_state_from_events()
self.http_server: ThreadingHTTPServer | None = None
self.http_thread: threading.Thread | None = None
self.mirror_keys: dict[str, tuple[str, str | None]] = {}
self.pane_targets: dict[str, str] = {}
self.projects_path: Path = config["workspace"]["projects_path"]
self._sse_clients: list[queue.Queue] = []
self._sse_lock = threading.Lock()
self.max_sse_subscribers: int = config.get("ui", {}).get("max_sse_subscribers", 32)
@property
def _auth_tokens_path(self) -> Path:
return self.workspace["log_path"].parent / "auth_tokens.json"
def _load_auth_tokens(self) -> None:
data = relay.read_json(self._auth_tokens_path, [])
if isinstance(data, list):
self.auth_tokens = set(data)
def _save_auth_tokens(self) -> None:
relay.write_json(self._auth_tokens_path, list(self.auth_tokens))
def rebuild_state_from_events(self) -> None:
"""Replay durable task state into the runtime projections on startup.
Durable/replayed state:
- task board contents
- task counters and last_created_at summary
Volatile/runtime-only state:
- tmux pane data
- queue and routing activity
- live agent process metadata
"""
self.task_state.rebuild_from_events()
def sse_subscribe(self) -> queue.Queue | None:
"""Subscribe to SSE events. Returns None if at capacity."""
q: queue.Queue = queue.Queue(maxsize=64)
with self._sse_lock:
if len(self._sse_clients) >= self.max_sse_subscribers:
return None
self._sse_clients.append(q)
return q
def sse_unsubscribe(self, q: queue.Queue) -> None:
with self._sse_lock:
try:
self._sse_clients.remove(q)
except ValueError:
pass
def sse_client_count(self) -> int:
with self._sse_lock:
return len(self._sse_clients)
def sse_broadcast(self, event_type: str, data: dict[str, Any], event_id: int | None = None) -> None:
payload = {"type": event_type, **data}
with self._sse_lock:
dead: list[queue.Queue] = []
for q in self._sse_clients:
try:
q.put_nowait({"event_id": event_id, "payload": payload})
except queue.Full:
dead.append(q)
for q in dead:
try:
self._sse_clients.remove(q)
except ValueError:
pass
if dead:
print(
f"[supervisor] SSE: dropped {len(dead)} full queues, "
f"{len(self._sse_clients)} clients remain",
file=sys.stderr,
flush=True,
)
def refresh_task_state(self) -> None:
self.state.patch_tasks_summary(self.task_state.summary())
def is_sleeping(self) -> bool:
with self._sleep_lock:
return self._sleeping
def set_sleeping(self, value: bool) -> None:
with self._sleep_lock:
self._sleeping = value
self.state.patch("app", {"sleeping": value})
def password(self) -> str:
env_name = self.config["ui"]["password_env"]
return os.environ.get(env_name) or self.config["ui"]["password"]
@staticmethod
def _hash_password(plaintext: str) -> str:
return hashlib.sha256(plaintext.encode("utf-8")).hexdigest()
def verify_password(self, candidate: str) -> bool:
"""Timing-safe password check. Hashes both sides before comparing."""
return secrets.compare_digest(
self._hash_password(candidate),
self._password_hash,
)
def current_repo_path(self) -> Path:
project_path = self.state.snapshot().get("project", {}).get("path")
if project_path:
return Path(project_path)
return SCRIPT_DIR
def refresh_workspace_state(self) -> None:
repo_path = self.current_repo_path()
branch = None
dirty = False
dirty_files = 0
try:
branch_proc = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=str(repo_path),
text=True,
capture_output=True,
timeout=5,
)
if branch_proc.returncode == 0:
branch = branch_proc.stdout.strip() or None
status_proc = subprocess.run(
["git", "status", "--porcelain"],
cwd=str(repo_path),
text=True,
capture_output=True,
timeout=5,
)
if status_proc.returncode == 0:
dirty_files = len([line for line in status_proc.stdout.splitlines() if line.strip()])
dirty = dirty_files > 0
except Exception:
branch = None
dirty = False
dirty_files = 0
self.state.patch(
"workspace",
{
"repo_path": str(repo_path),
"branch": branch,
"dirty": dirty,
"dirty_files": dirty_files,
},
)
def emit_local_event(self, event: dict[str, Any]) -> dict[str, Any]:
payload = dict(event)
stored = self.event_store.append_event(payload)
payload["event_id"] = stored["id"]
self.handle_relay_event(payload)
return payload
@staticmethod
def sse_event_payload(event: dict[str, Any]) -> dict[str, Any]:
payload = dict(event)
if payload.get("type") == "tasks_bulk_updated":
payload["type"] = "tasks_updated"
return payload
def persist_system_message(
self,
text: str,
*,
sender: str = "SYSTEM",
message_type: str = "system",
) -> dict[str, Any]:
return relay.persist_transcript_message(
self.workspace["log_path"],
sender,
text,
event_callback=self.handle_relay_event,
event_store=self.event_store,
message_type=message_type,
)
def preferences_payload(self) -> dict[str, Any]:
data = relay.read_json(self.workspace["preferences_path"], {"agents": {}})
if not isinstance(data, dict):
return {"agents": {}}
agents = data.get("agents", {})
if not isinstance(agents, dict):
agents = {}
return {"agents": agents}
def save_preferences_payload(self, payload: dict[str, Any]) -> None:
relay.write_json(self.workspace["preferences_path"], payload)
def apply_saved_preferences(self) -> None:
preferences = self.preferences_payload()
agent_preferences = preferences.get("agents", {})
for agent in self.config["agents"]:
if not agent["enabled"]:
continue
saved = agent_preferences.get(agent["name"], {})
if not isinstance(saved, dict):
saved = {}
agent["selected_model"] = relay.resolve_selected_option(
saved.get("selected_model", agent.get("selected_model", "default")),
agent.get("model_options", []),
str(agent.get("selected_model", "default")),
)
if agent.get("effort_options"):
selected_effort = relay.resolve_selected_option(
saved.get("selected_effort", agent.get("selected_effort", "default")),
agent["effort_options"],
str(agent.get("selected_effort", "default")),
)
allowed_efforts = set(self.allowed_efforts_for(agent, agent["selected_model"]))
if allowed_efforts and selected_effort not in allowed_efforts:
selected_effort = "default" if "default" in allowed_efforts else sorted(allowed_efforts)[0]
agent["selected_effort"] = selected_effort
else:
agent["selected_effort"] = "default"
def find_agent(self, name: str) -> dict[str, Any] | None:
target = name.strip().upper()
for agent in self.config["agents"]:
if agent["name"] == target and agent["enabled"]:
return agent
return None
def persist_agent_preferences(self, agent: dict[str, Any]) -> None:
preferences = self.preferences_payload()
preferences.setdefault("agents", {})
preferences["agents"][agent["name"]] = {
"selected_model": agent.get("selected_model", "default"),
"selected_effort": agent.get("selected_effort", "default"),
}
self.save_preferences_payload(preferences)
def allowed_efforts_for(self, agent: dict[str, Any], selected_model: str) -> list[str]:
matrix = agent.get("effort_matrix", {})
if isinstance(matrix, dict):
allowed = matrix.get(selected_model) or matrix.get("default")
if isinstance(allowed, list) and allowed:
return [str(item) for item in allowed]
return [str(item["id"]) for item in agent.get("effort_options", [])]
def restart_agent(self, name: str) -> dict[str, Any]:
"""Kill the process in an agent's pane and respawn its mirror command."""
agent = self.find_agent(name)
if not agent:
raise KeyError(name)
pane_target = self.pane_targets.get(agent["name"])
if not pane_target:
raise RuntimeError(f"no pane target for {name}")
# Force-respawn the mirror (kills whatever is running in the pane)
self.mirror_keys.pop(agent["name"], None)
self.sync_agent_mirrors(force=True)
return self.state.snapshot()["agents"][agent["name"]]
# ── Project management ──────────────────────────────────────────
def list_projects(self) -> dict[str, Any]:
return relay.load_projects(self.projects_path)
def lock_project(self, path: str | None = None, url: str | None = None, name: str | None = None) -> dict[str, Any]:
"""Lock agents to a local path or clone a repo and lock to it."""
projects = relay.load_projects(self.projects_path)
if url:
target_name = name or url.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git")
target_dir = SCRIPT_DIR / "projects" / target_name
if not target_dir.exists():
target_dir.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(
["git", "clone", url, str(target_dir)],
check=True, timeout=120, capture_output=True, text=True,
)
project_path = str(target_dir.resolve())
project_type = "cloned"
elif path:
resolved = Path(path).expanduser().resolve()
if not resolved.is_dir():
raise ValueError(f"path does not exist or is not a directory: {path}")
project_path = str(resolved)
project_type = "local"
target_name = name or resolved.name
else:
raise ValueError("either path or url is required")
project_id = target_name.lower().replace(" ", "-")
projects["projects"][project_id] = {
"name": target_name,
"path": project_path,
"type": project_type,
"locked_at": utc_now(),
"agents_allowed": [a["name"] for a in self.config["agents"] if a["enabled"]],
}
projects["active"] = project_id
relay.save_projects(self.projects_path, projects)
# Inject work_dir into runtime agent configs
for agent in self.config["agents"]:
if agent["enabled"]:
agent["work_dir"] = project_path
self.reset_all_agent_sessions()
self.sync_agent_mirrors(force=True)
lock_body = f"[PROJECT] Locked to: {target_name} ({project_path})"
self.persist_system_message(lock_body, message_type="project")
self.refresh_workspace_state()
return projects
def unlock_project(self) -> dict[str, Any]:
"""Release current project lock, agents return to home repo."""
projects = relay.load_projects(self.projects_path)
projects["active"] = None
relay.save_projects(self.projects_path, projects)
for agent in self.config["agents"]:
agent.pop("work_dir", None)
self.reset_all_agent_sessions()
self.sync_agent_mirrors(force=True)
self.persist_system_message(
f"[PROJECT] Unlocked — agents returned to {SCRIPT_DIR}",
message_type="project",
)
self.refresh_workspace_state()
return projects
def delete_project(self, project_id: str) -> dict[str, Any]:
projects = relay.load_projects(self.projects_path)
if project_id not in projects["projects"]:
raise KeyError(project_id)
if projects["active"] == project_id:
projects["active"] = None
for agent in self.config["agents"]:
agent.pop("work_dir", None)
self.reset_all_agent_sessions()
self.sync_agent_mirrors(force=True)
del projects["projects"][project_id]
relay.save_projects(self.projects_path, projects)
return projects
def reset_agent_session(self, name: str) -> None:
sessions = relay.load_sessions(self.workspace["sessions_path"])
if name in sessions:
del sessions[name]
relay.save_sessions(self.workspace["sessions_path"], sessions)
self.mirror_keys.pop(name, None)
def reset_all_agent_sessions(self) -> None:
relay.save_sessions(self.workspace["sessions_path"], {})
self.mirror_keys.clear()
def update_agent_settings(
self,
name: str,
selected_model: str | None,
selected_effort: str | None,
) -> dict[str, Any]:
agent = self.find_agent(name)
if not agent:
raise KeyError(name)
with self.settings_lock:
next_model = relay.resolve_selected_option(
selected_model or agent.get("selected_model", "default"),
agent.get("model_options", []),
str(agent.get("selected_model", "default")),
)
if agent.get("effort_options"):
next_effort = relay.resolve_selected_option(
selected_effort or agent.get("selected_effort", "default"),
agent["effort_options"],
str(agent.get("selected_effort", "default")),
)
allowed_efforts = set(self.allowed_efforts_for(agent, next_model))
if allowed_efforts and next_effort not in allowed_efforts:
next_effort = "default" if "default" in allowed_efforts else sorted(allowed_efforts)[0]
else:
next_effort = "default"
changed = (
next_model != agent.get("selected_model")
or next_effort != agent.get("selected_effort")
)
agent["selected_model"] = next_model
agent["selected_effort"] = next_effort
self.persist_agent_preferences(agent)
if changed:
self.reset_agent_session(agent["name"])
self.state.patch_agent(
agent["name"],
{
"selected_model": agent["selected_model"],
"selected_effort": agent["selected_effort"],
"session_id": None if changed else self.state.snapshot()["agents"][agent["name"]].get("session_id"),
"mirror_view": "log" if changed else self.state.snapshot()["agents"][agent["name"]].get("mirror_view", "log"),
"model_options": agent.get("model_options", []),
"effort_options": agent.get("effort_options", []),
"effort_matrix": agent.get("effort_matrix", {}),
},
)
if changed:
self.sync_agent_mirrors(force=True)
return self.state.snapshot()["agents"][agent["name"]]
def tmux(self, *args: str, capture: bool = False, check: bool = True) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["tmux", *args],
cwd=str(SCRIPT_DIR),
text=True,
capture_output=capture,
check=check,
)
def tmux_session_exists(self) -> bool:
result = subprocess.run(
["tmux", "has-session", "-t", self.session],
cwd=str(SCRIPT_DIR),
text=True,
capture_output=True,
)
return result.returncode == 0
def prepare_runtime(self) -> None:
for path in (
self.workspace["log_path"],
self.workspace["relay_log_path"],
self.workspace["state_path"],
self.workspace["sessions_path"],
self.workspace["preferences_path"],
self.workspace["projects_path"],
self.workspace["tasks_path"],
self.workspace["events_db_path"],
):
path.parent.mkdir(parents=True, exist_ok=True)
self.workspace["archives_dir"].mkdir(parents=True, exist_ok=True)
self.workspace["log_path"].touch(exist_ok=True)
if not self.workspace["sessions_path"].exists():
relay.save_sessions(self.workspace["sessions_path"], {})
if not self.workspace["preferences_path"].exists():
self.save_preferences_payload({"agents": {}})
for agent in self.config["agents"]:
if agent["enabled"]:
agent["io_log_path"].parent.mkdir(parents=True, exist_ok=True)
agent["io_log_path"].touch(exist_ok=True)
relay.write_text(self.workspace["pid_path"], f"{os.getpid()}\n")
import_transcript_to_event_store(self.event_store, self.workspace["log_path"])
self.refresh_workspace_state()
def ensure_tmux_layout(self) -> None:
if self.tmux_session_exists():
self.tmux("kill-session", "-t", self.session, check=False)
self.tmux("new-session", "-d", "-s", self.session, "-x", "220", "-y", "60")
# Window 0: transcript log watcher
self.tmux("rename-window", "-t", f"{self.session}:0", "log")
self.tmux("set-window-option", "-t", f"{self.session}:0", "remain-on-exit", "on")
self.tmux(
"respawn-pane",
"-k",
"-t",
f"{self.session}:0.0",
f"cd {shlex.quote(str(SCRIPT_DIR))} && exec bash watch-log.sh --config {shlex.quote(str(self.config['config_path']))}",
)
# One dedicated full-screen window per enabled agent
enabled_agents = [agent for agent in self.config["agents"] if agent["enabled"]]
for agent in enabled_agents:
name = agent["name"]
self.tmux("new-window", "-d", "-t", self.session, "-n", name)
pane_target = f"{self.session}:{name}.0"
self.pane_targets[name] = pane_target
self.state.patch_agent(
name,
{
"pane_target": pane_target,
"mirror_mode": agent["mirror_mode"],
"mirror_view": "log",
"selected_model": agent.get("selected_model", "default"),
"selected_effort": agent.get("selected_effort", "default"),
"model_options": agent.get("model_options", []),
"effort_options": agent.get("effort_options", []),
"effort_matrix": agent.get("effort_matrix", {}),
},
)
# Dispatcher monitor window — shows Ollama router status
dispatcher_script = (
"echo '[DISPATCHER] Ollama router monitor'; "
"while true; do "
"echo \"--- $(date) ---\"; "
"curl -s http://localhost:11434/api/tags 2>/dev/null "
"| python3 -c \""
"import json,sys; d=json.load(sys.stdin); "
"[print(' ', m['name']) for m in d.get('models',[])]"
"\" 2>/dev/null || echo ' Ollama not reachable'; "
"sleep 10; "
"done"
)
dispatcher_pane = f"{self.session}:DISPATCHER.0"
self.tmux(
"new-window", "-d", "-t", self.session, "-n", "DISPATCHER",
f"cd {shlex.quote(str(SCRIPT_DIR))} && bash -lc {shlex.quote(dispatcher_script)}",
)
self.pane_targets["DISPATCHER"] = dispatcher_pane
self.state.patch("dispatcher", {"pane_target": dispatcher_pane})
# Runtime log window
self.tmux(
"new-window",
"-d",
"-t",
self.session,
"-n",
"runtime",
f"cd {shlex.quote(str(SCRIPT_DIR))} && touch {shlex.quote(str(self.workspace['relay_log_path']))} && exec tail -n 120 -F {shlex.quote(str(self.workspace['relay_log_path']))}",
)
self.state.patch("tmux", {"state": "running"})
self.sync_agent_mirrors(force=True)
def sync_agent_mirrors(self, force: bool = False) -> None:
sessions = relay.load_sessions(self.workspace["sessions_path"])
for agent in [item for item in self.config["agents"] if item["enabled"]]:
name = agent["name"]
pane_target = self.pane_targets.get(name)
if not pane_target:
continue
session_id = sessions.get(name)
mirror_view = desired_mirror_view(agent, session_id)
mirror_key = (mirror_view, session_id)
if force or self.mirror_keys.get(name) != mirror_key:
if mirror_view == "resume" and session_id:
cmd = build_resume_mirror_command(agent, session_id)
else:
cmd = build_log_mirror_command(agent)
self.tmux("respawn-pane", "-k", "-t", pane_target, cmd)
self.mirror_keys[name] = mirror_key
self.state.patch_agent(
name,
{
"session_id": session_id,
"mirror_view": mirror_view,
"pane_target": pane_target,
"mirror_mode": agent["mirror_mode"],
"selected_model": agent.get("selected_model", "default"),
"selected_effort": agent.get("selected_effort", "default"),
"model_options": agent.get("model_options", []),
"effort_options": agent.get("effort_options", []),
"effort_matrix": agent.get("effort_matrix", {}),
},
)
def collect_pane_commands(self) -> dict[str, str]:
if not self.tmux_session_exists():
return {}
# Query all windows in the session (each agent now has its own window).
# Map both the raw tmux pane id (%7) and window-style targets
# (triagent:CODEX.0) so health checks keep working across layout changes.
result = self.tmux(
"list-panes",
"-s",
"-t",
self.session,
"-F",
"#{pane_id}\t#{session_name}:#{window_name}.#{pane_index}\t#{session_name}:#{window_index}.#{pane_index}\t#{pane_current_command}",
capture=True,
)
pane_commands: dict[str, str] = {}
for raw_line in result.stdout.splitlines():
line = raw_line.strip()
if not line:
continue
parts = line.split("\t", 3)
if len(parts) != 4:
continue
pane_id, named_target, indexed_target, pane_command = parts
normalized_command = pane_command.strip()
for key in (pane_id.strip(), named_target.strip(), indexed_target.strip()):
if key:
pane_commands[key] = normalized_command
return pane_commands
def _send_to_socket(self, message: dict[str, Any]) -> bool:
"""Send a message to the relay socket. Returns True if sent successfully."""
socket_path = self.workspace.get("socket_path")
if not socket_path:
return False
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(str(socket_path))
sock.sendall(json.dumps(message).encode("utf-8"))
return True
finally:
sock.close()
except Exception as e:
print(f"[supervisor] socket error: {e}", file=sys.stderr)
return False
def _pick_compact_agent(self) -> str:
"""Pick the agent with the most remaining fuel capacity. Tie-break: alphabetical."""
best_name = ""
best_remaining = -1
for name in sorted(self.state.snapshot()["agents"]):
fuel = self.state.fuel_for_agent(name)
if fuel["remaining"] > best_remaining:
best_remaining = fuel["remaining"]
best_name = name
return best_name
def compact_context(self) -> dict[str, Any]:
"""Archive transcript context locally and inject a compact summary without dispatching."""
self.state.patch("workspace", {"compact_state": "running"})
cleared: list[str] = []
now = utc_now()
log_path = self.workspace["log_path"]
transcript = relay.read_text(log_path) if log_path.exists() else ""