-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdaniel.py
More file actions
executable file
·1356 lines (1209 loc) · 50.3 KB
/
Copy pathdaniel.py
File metadata and controls
executable file
·1356 lines (1209 loc) · 50.3 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
"""Multi-agent terminal orchestrator with CLI wrapping and next-man-up failover."""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
import urllib.parse
from getpass import getpass
from pathlib import Path
from datetime import datetime, timedelta, timezone
AGENTS = ("claude", "codex", "gemini")
GEMINI_CLI_TIMEOUT_SECS = 300 # 5 minutes (was 120 — too short for complex prompts)
DEFAULTS = {
"name": "agent",
"tasks_root": str(Path.home() / "tasks"),
"kb_port": "3838",
"claude_mode": "cli",
"codex_mode": "cli",
"gemini_mode": "cli",
"codex_cli_permission_mode": "full-host-unattended",
"gemini_cli_permission_mode": "full-host-unattended",
"models": {
"claude": "claude-sonnet-4-5",
"codex": "gpt-5",
"codex_orchestrator": "gpt-5",
"gemini": "gemini-2.5-pro",
},
"chains": {
"orchestrator": ["claude", "codex", "gemini"],
"implementation": ["codex", "claude", "gemini"],
"uidocs": ["gemini", "codex", "claude"],
"review": ["claude", "codex", "gemini"],
},
"keys": {
"openai": "",
"anthropic": "",
"gemini": "",
},
"service_overrides": {
"claude": {"manual_disabled": False, "disabled_until": ""},
"codex": {"manual_disabled": False, "disabled_until": ""},
"gemini": {"manual_disabled": False, "disabled_until": ""},
},
"allowed_dirs": [str(Path.home())],
}
CONFIG_DIR = Path.home() / ".config" / "agent-orchestrator"
CONFIG_PATH = CONFIG_DIR / "config.json"
# Backward compat: check old location
_OLD_CONFIG = Path.home() / ".config" / "daniel" / "config.json"
# --- Terminal colors (disabled if not a TTY) ---
_COLORS = sys.stdout.isatty()
def _c(code: str, text: str) -> str:
return f"\033[{code}m{text}\033[0m" if _COLORS else text
AGENT_COLORS = {"claude": "35", "codex": "32", "gemini": "34"} # magenta, green, blue
def _read(path: Path) -> str:
if not path.exists():
return ""
return path.read_text(encoding="utf-8")
def _write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
def _load_config() -> dict:
# Check old config location for backward compat
path = CONFIG_PATH
if not path.exists() and _OLD_CONFIG.exists():
path = _OLD_CONFIG
if not path.exists():
return json.loads(json.dumps(DEFAULTS))
raw = json.loads(_read(path))
cfg = json.loads(json.dumps(DEFAULTS))
for top in (
"name",
"tasks_root",
"kb_port",
"claude_mode",
"codex_mode",
"gemini_mode",
"codex_cli_permission_mode",
"gemini_cli_permission_mode",
"models",
"chains",
"keys",
"service_overrides",
"allowed_dirs",
):
if top not in raw:
continue
if isinstance(cfg[top], dict):
cfg[top].update(raw[top])
else:
cfg[top] = raw[top]
for agent in AGENTS:
cfg["service_overrides"].setdefault(agent, {"manual_disabled": False, "disabled_until": ""})
ov = cfg["service_overrides"][agent]
if not isinstance(ov, dict):
cfg["service_overrides"][agent] = {"manual_disabled": False, "disabled_until": ""}
continue
ov.setdefault("manual_disabled", False)
ov.setdefault("disabled_until", "")
if not isinstance(cfg.get("allowed_dirs"), list):
cfg["allowed_dirs"] = [str(Path.home())]
cfg["allowed_dirs"] = [str(Path(p).expanduser()) for p in cfg["allowed_dirs"] if str(p).strip()]
return cfg
def _save_config(cfg: dict) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
os.chmod(CONFIG_PATH, 0o600)
def _try_save_config(cfg: dict) -> tuple[bool, str]:
try:
_save_config(cfg)
return True, ""
except Exception as exc:
return False, str(exc)
CLI_PERMISSION_MODES = ("full-host-unattended", "sandboxed-auto")
def _cli_permissions_payload(cfg: dict) -> dict:
return {
"codex": {
"mode": cfg.get("codex_mode", "api"),
"permission_mode": cfg.get("codex_cli_permission_mode", "full-host-unattended"),
"model": cfg["models"]["codex"],
"orchestrator_model": cfg["models"]["codex_orchestrator"],
},
"gemini": {
"mode": cfg.get("gemini_mode", "api"),
"permission_mode": cfg.get("gemini_cli_permission_mode", "full-host-unattended"),
"model": cfg["models"]["gemini"],
},
}
def _set_cli_permission_mode(cfg: dict, agent: str, permission_mode: str) -> tuple[bool, str]:
if agent not in ("codex", "gemini"):
return False, "Only codex and gemini support runtime CLI permission mode changes."
if permission_mode not in CLI_PERMISSION_MODES:
return False, f"Permission mode must be one of: {', '.join(CLI_PERMISSION_MODES)}"
key = f"{agent}_cli_permission_mode"
cfg[key] = permission_mode
ok, err = _try_save_config(cfg)
if not ok:
return False, f"warning: updated in memory but could not persist config: {err}"
return True, f"{agent} permission mode set to {permission_mode}"
def _parse_chain(raw: str, default: list[str]) -> list[str]:
raw = raw.strip()
if not raw:
return list(default)
out: list[str] = []
for part in raw.replace(" ", "").split(","):
if part in AGENTS and part not in out:
out.append(part)
return out or list(default)
def _agent_prompt_identity(agent: str) -> str:
if agent == "codex":
return "You are Codex, the implementation-heavy engineering agent."
if agent == "gemini":
return "You are Gemini, the UI/docs and second-opinion agent."
if agent == "claude":
return "You are Claude, the orchestrator/review agent."
return f"You are {agent.title()}, a pragmatic software assistant."
def _default_role_for_direct_agent(agent: str) -> str:
if agent == "codex":
return "implementation"
if agent == "gemini":
return "uidocs"
if agent == "claude":
return "review"
return "orchestrator"
def _key_for(agent: str, cfg: dict) -> str:
mapping = {
"codex": cfg["keys"]["openai"] if cfg.get("codex_mode", "api") == "api" else "cli",
"claude": cfg["keys"]["anthropic"] if cfg.get("claude_mode", "cli") == "api" else "cli",
"gemini": cfg["keys"]["gemini"] if cfg.get("gemini_mode", "api") == "api" else "cli",
}
return mapping[agent].strip()
def _available(agent: str, cfg: dict) -> bool:
if agent == "codex":
mode = cfg.get("codex_mode", "api")
if mode == "api":
return bool(cfg["keys"]["openai"].strip())
if mode == "cli":
return shutil.which("codex") is not None
return False
if agent == "claude":
mode = cfg.get("claude_mode", "cli")
if mode == "api":
return bool(cfg["keys"]["anthropic"].strip())
if mode == "cli":
return shutil.which("claude") is not None
return False
if agent == "gemini":
mode = cfg.get("gemini_mode", "api")
if mode == "api":
return bool(cfg["keys"]["gemini"].strip())
if mode == "cli":
return shutil.which("gemini") is not None
return False
return bool(_key_for(agent, cfg))
def _parse_iso_utc(value: str) -> datetime | None:
raw = (value or "").strip()
if not raw:
return None
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(raw)
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _format_iso_utc(dt: datetime) -> str:
return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _service_disabled_reason(agent: str, cfg: dict, now: datetime | None = None) -> str | None:
now = now or datetime.now(timezone.utc)
override = cfg.get("service_overrides", {}).get(agent, {})
if override.get("manual_disabled", False):
return "manually disabled"
until = _parse_iso_utc(str(override.get("disabled_until", "")))
if until is None:
return None
if now < until:
return f"disabled until { _format_iso_utc(until) }"
override["disabled_until"] = ""
return None
def _service_status(agent: str, cfg: dict) -> str:
if not _available(agent, cfg):
return "unavailable (missing key/cli)"
reason = _service_disabled_reason(agent, cfg)
if reason:
return f"down ({reason})"
return "up"
def _parse_claude_reset_utc(error_text: str) -> datetime | None:
m = re.search(r"resets\s+([A-Za-z]{3}\s+\d{1,2},\s+\d{1,2}(?::\d{2})?(?:am|pm)\s+\(UTC\))", error_text, re.IGNORECASE)
if not m:
return None
raw = m.group(1)
now = datetime.now(timezone.utc)
for fmt in ("%b %d, %I:%M%p (UTC)", "%b %d, %I%p (UTC)"):
try:
parsed = datetime.strptime(raw, fmt)
candidate = parsed.replace(year=now.year, tzinfo=timezone.utc)
if candidate < now - timedelta(hours=1):
candidate = candidate.replace(year=now.year + 1)
return candidate
except ValueError:
continue
return None
def _apply_auto_downtime(agent: str, error_text: str, cfg: dict) -> str | None:
text = (error_text or "").strip()
if not text:
return None
override = cfg["service_overrides"][agent]
if agent == "claude" and "out of extra usage" in text.lower():
reset_at = _parse_claude_reset_utc(text)
if reset_at is not None:
override["manual_disabled"] = False
override["disabled_until"] = _format_iso_utc(reset_at)
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} until {override['disabled_until']}{suffix}"
if agent == "gemini":
lower = text.lower()
if "modelnot found" in lower or "requested entity was not found" in lower or "model not found" in lower:
override["manual_disabled"] = True
override["disabled_until"] = ""
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} manual (model not found). Fix model then run /service up {agent}.{suffix}"
if "resource_exhausted" in lower or "quota" in lower or "rate limit" in lower:
override["disabled_until"] = _format_iso_utc(datetime.now(timezone.utc) + timedelta(minutes=5))
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} rate limited, retry in 5min{suffix}"
if "permission_denied" in lower or "api_key_invalid" in lower or "unauthorized" in lower:
override["manual_disabled"] = True
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} auth failed. Check API key then /service up {agent}.{suffix}"
if agent == "codex":
lower = text.lower()
if "rate limit" in lower or "429" in lower or "resource exhausted" in lower:
override["disabled_until"] = _format_iso_utc(datetime.now(timezone.utc) + timedelta(minutes=5))
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} rate limited, retry in 5min{suffix}"
if "authentication" in lower or "401" in lower or "invalid api key" in lower:
override["manual_disabled"] = True
ok, err = _try_save_config(cfg)
suffix = "" if ok else f" (warning: could not persist config: {err})"
return f"auto-down: {agent} auth failed. Check API key then /service up {agent}.{suffix}"
return None
def _role_chain(role: str, cfg: dict) -> list[str]:
configured = list(cfg["chains"].get(role, []))
filtered = [a for a in configured if _available(a, cfg) and not _service_disabled_reason(a, cfg)]
if filtered:
return filtered
defaults = [a for a in DEFAULTS["chains"][role] if _available(a, cfg) and not _service_disabled_reason(a, cfg)]
if defaults:
return defaults
return [a for a in AGENTS if _available(a, cfg) and not _service_disabled_reason(a, cfg)]
def _extract_openai_text(resp: object) -> str:
output_text = getattr(resp, "output_text", None)
if isinstance(output_text, str) and output_text.strip():
return output_text
try:
output = getattr(resp, "output", None) or []
chunks: list[str] = []
for item in output:
content = getattr(item, "content", None) or []
for c in content:
text = getattr(c, "text", None)
if isinstance(text, str):
chunks.append(text)
return "\n".join(chunks).strip()
except Exception:
return str(resp)
def _call_codex_api(prompt: str, cfg: dict, role: str) -> str:
from openai import OpenAI # type: ignore
model = cfg["models"]["codex_orchestrator"] if role == "orchestrator" else cfg["models"]["codex"]
client = OpenAI(api_key=cfg["keys"]["openai"])
resp = client.responses.create(model=model, input=prompt)
out = _extract_openai_text(resp)
return out or "<empty response>"
def _codex_cli_model(cfg: dict, role: str) -> str:
return cfg["models"]["codex_orchestrator"] if role == "orchestrator" else cfg["models"]["codex"]
def _call_codex_cli(prompt: str, cfg: dict, role: str) -> str:
if shutil.which("codex") is None:
raise RuntimeError("Codex CLI not found on PATH")
cli_cwd = _cli_workdir(cfg)
allowed = _allowed_dirs(cfg)
with tempfile.NamedTemporaryFile(prefix="daniel-codex-", suffix=".txt", delete=False) as tmp:
out_path = tmp.name
permission_mode = cfg.get("codex_cli_permission_mode", "full-host-unattended")
cmd = [
"codex",
"exec",
"--model",
_codex_cli_model(cfg, role),
"--cd",
cli_cwd or str(Path.home()),
"--skip-git-repo-check",
"--color",
"never",
"-o",
out_path,
]
if permission_mode == "full-host-unattended":
cmd.append("--dangerously-bypass-approvals-and-sandbox")
else:
cmd.extend(["--full-auto", "--sandbox", "workspace-write"])
for d in allowed:
cmd.extend(["--add-dir", d])
cmd.append(prompt)
proc = subprocess.run(
cmd,
cwd=cli_cwd,
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=1800,
)
if proc.returncode != 0:
err = (proc.stderr or "").strip() or (proc.stdout or "").strip() or f"exit {proc.returncode}"
try:
os.remove(out_path)
except OSError:
pass
raise RuntimeError(f"codex CLI failed: {err}")
out = _read(Path(out_path)).strip()
try:
os.remove(out_path)
except OSError:
pass
return out or "<empty response>"
def _call_codex(prompt: str, cfg: dict, role: str) -> str:
mode = cfg.get("codex_mode", "api")
if mode == "api":
return _call_codex_api(prompt, cfg, role)
if mode == "cli":
return _call_codex_cli(prompt, cfg, role)
raise RuntimeError(f"Unsupported codex_mode: {mode}")
def _call_claude_api(prompt: str, cfg: dict) -> str:
from anthropic import Anthropic # type: ignore
client = Anthropic(api_key=cfg["keys"]["anthropic"])
resp = client.messages.create(
model=cfg["models"]["claude"],
max_tokens=2200,
temperature=0,
messages=[{"role": "user", "content": prompt}],
)
chunks: list[str] = []
for block in getattr(resp, "content", []):
text = getattr(block, "text", None)
if isinstance(text, str):
chunks.append(text)
return "\n".join(chunks).strip() or "<empty response>"
def _call_claude_cli(prompt: str, cfg: dict) -> str:
if shutil.which("claude") is None:
raise RuntimeError("Claude CLI not found on PATH")
cli_cwd = _cli_workdir(cfg)
allowed = _allowed_dirs(cfg)
cmd = [
"claude",
"-p",
"--output-format",
"text",
"--allow-dangerously-skip-permissions",
"--dangerously-skip-permissions",
"--permission-mode",
"bypassPermissions",
"--add-dir",
*(allowed or [cli_cwd or str(Path.home())]),
"--model",
cfg["models"]["claude"],
prompt,
]
env = os.environ.copy()
env.pop("CLAUDECODE", None)
proc = subprocess.run(
cmd,
cwd=cli_cwd,
capture_output=True,
text=True,
timeout=1800,
env=env,
)
if proc.returncode != 0:
err = (proc.stderr or "").strip() or (proc.stdout or "").strip() or f"exit {proc.returncode}"
raise RuntimeError(f"claude CLI failed: {err}")
out = (proc.stdout or "").strip()
return out or "<empty response>"
def _call_claude(prompt: str, cfg: dict) -> str:
mode = cfg.get("claude_mode", "cli")
if mode == "api":
return _call_claude_api(prompt, cfg)
if mode == "cli":
return _call_claude_cli(prompt, cfg)
raise RuntimeError(f"Unsupported claude_mode: {mode}")
def _call_gemini_api(prompt: str, cfg: dict) -> str:
from google import genai # type: ignore
client = genai.Client(api_key=cfg["keys"]["gemini"])
resp = client.models.generate_content(model=cfg["models"]["gemini"], contents=prompt)
text = getattr(resp, "text", None)
if isinstance(text, str) and text.strip():
return text.strip()
return str(resp)
def _call_gemini_cli(prompt: str, cfg: dict) -> str:
if shutil.which("gemini") is None:
raise RuntimeError("Gemini CLI not found on PATH")
cli_cwd = _cli_workdir(cfg)
permission_mode = cfg.get("gemini_cli_permission_mode", "full-host-unattended")
# Pass prompt via -p flag (Gemini CLI headless mode)
# Force text output for reliability — JSON parsing was fragile.
cmd = [
"gemini",
"-p", prompt,
"--model", cfg["models"]["gemini"],
"--output-format", "text",
]
if permission_mode == "full-host-unattended":
cmd.extend(["--approval-mode", "yolo", "--sandbox=false"])
else:
cmd.extend(["--approval-mode", "yolo"])
try:
proc = subprocess.run(
cmd,
cwd=cli_cwd,
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=GEMINI_CLI_TIMEOUT_SECS,
)
except subprocess.TimeoutExpired:
raise RuntimeError(f"gemini CLI timed out after {GEMINI_CLI_TIMEOUT_SECS}s")
if proc.returncode != 0:
err = (proc.stderr or "").strip() or (proc.stdout or "").strip() or f"exit {proc.returncode}"
raise RuntimeError(f"gemini CLI failed: {err}")
raw = (proc.stdout or "").strip()
if not raw:
# Check stderr for clues
stderr = (proc.stderr or "").strip()
if stderr:
raise RuntimeError(f"gemini CLI empty output, stderr: {stderr}")
return "<empty response>"
# Try to extract text from JSON if Gemini returns structured output
try:
parsed = json.loads(raw)
# Gemini CLI JSON format: candidates[0].content.parts[0].text
if isinstance(parsed, dict):
candidates = parsed.get("candidates", [])
if candidates and isinstance(candidates, list):
parts = candidates[0].get("content", {}).get("parts", [])
if parts and isinstance(parts, list):
text = parts[0].get("text", "")
if text.strip():
return text.strip()
# Fallback: try flat keys
for key in ("text", "content", "response"):
val = parsed.get(key)
if isinstance(val, str) and val.strip():
return val.strip()
except (json.JSONDecodeError, IndexError, KeyError, TypeError):
pass
return raw
def _call_gemini(prompt: str, cfg: dict) -> str:
mode = cfg.get("gemini_mode", "api")
if mode == "api":
return _call_gemini_api(prompt, cfg)
if mode == "cli":
return _call_gemini_cli(prompt, cfg)
raise RuntimeError(f"Unsupported gemini_mode: {mode}")
def _call_agent(agent: str, prompt: str, cfg: dict, role: str) -> str:
if agent == "codex":
return _call_codex(prompt, cfg, role)
if agent == "claude":
return _call_claude(prompt, cfg)
if agent == "gemini":
return _call_gemini(prompt, cfg)
raise RuntimeError(f"Unknown agent: {agent}")
def _known_tasks(tasks_root: Path) -> list[str]:
if not tasks_root.exists():
return []
names: list[str] = []
for p in sorted(tasks_root.iterdir()):
if not p.is_dir() or p.name.startswith("."):
continue
if (p / "TASK.md").exists():
names.append(p.name)
return names
def _truncate(text: str, max_chars: int = 4000) -> str:
if len(text) <= max_chars:
return text
return text[: max_chars - 40].rstrip() + "\n...[truncated]"
def _normalize_dir(raw: str) -> str:
return str(Path(raw).expanduser().resolve())
def _allowed_dirs(cfg: dict) -> list[str]:
dirs = cfg.get("allowed_dirs", [])
out: list[str] = []
for d in dirs:
try:
n = _normalize_dir(str(d))
except Exception:
continue
if n not in out:
out.append(n)
return out
def _is_allowed_dir(path: Path, cfg: dict) -> bool:
target = path.resolve()
for base_raw in _allowed_dirs(cfg):
base = Path(base_raw)
try:
target.relative_to(base)
return True
except ValueError:
continue
return False
def _cli_workdir(cfg: dict) -> str | None:
tasks_root = Path(cfg["tasks_root"]).expanduser()
if tasks_root.exists() and _is_allowed_dir(tasks_root, cfg):
return str(tasks_root)
for d in _allowed_dirs(cfg):
p = Path(d)
if p.exists() and p.is_dir():
return str(p)
return str(tasks_root) if tasks_root.exists() else None
def _kb_search(query: str, cfg: dict, limit: int = 5) -> str:
"""Search the knowledge base server if running. Returns empty string if KB unavailable."""
port = cfg.get("kb_port", "3838")
url = f"http://localhost:{port}/api/v1/search?q={urllib.parse.quote(query)}&limit={limit}"
try:
headers = {"Accept": "application/json"}
# Use API key if configured
kb_key = cfg.get("keys", {}).get("kb", "") or os.environ.get("KB_API_KEY", "")
if kb_key:
headers["X-API-Key"] = kb_key
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=5) as resp:
raw = json.loads(resp.read())
# v1 API wraps results: {"results": [...]}
data = raw.get("results", raw) if isinstance(raw, dict) else raw
if not data or not isinstance(data, list):
return ""
results = []
for doc in data[:limit]:
title = doc.get("title", "Untitled")
snippet = doc.get("snippet", "")[:200].replace("<mark>", "").replace("</mark>", "")
results.append(f"- {title}: {snippet}")
return "\n".join(results)
except Exception:
return "" # KB not running — silently skip
def _shared_context(tasks_root: Path, task_id: str | None, cfg: dict | None = None) -> str:
sections: list[str] = []
global_files = [
("Global Guardrails", tasks_root / "GUARDRAILS.md"),
("Global Todo", tasks_root / "TODO_GLOBAL.md"),
("Global MCP", tasks_root / "MCP_SERVERS.md"),
("Shared Knowledge", tasks_root / "SHARED_KNOWLEDGE.md"),
]
for label, path in global_files:
raw = _read(path).strip()
if raw:
sections.append(f"## {label}\n{_truncate(raw, 5000)}")
if task_id:
task_dir = tasks_root / task_id
for label, name in [
("Task", "TASK.md"),
("Task Plan", "PLAN.md"),
("Task Decision", "DECISION.md"),
("Task Todo", "TODO.md"),
("Task Guardrails", "GUARDRAILS.md"),
("Task MCP", "MCP_SERVERS.md"),
]:
raw = _read(task_dir / name).strip()
if raw:
sections.append(f"## {label}\n{_truncate(raw, 5000)}")
tasks = _known_tasks(tasks_root)
if tasks:
sections.append("## Known Tasks\n" + "\n".join(f"- {t}" for t in tasks[:200]))
# Inject KB context if server is running
if cfg and task_id:
kb_results = _kb_search(task_id, cfg, limit=5)
if kb_results:
sections.append(f"## Knowledge Base Context\n{kb_results}")
return "\n\n".join(sections)
def _build_prompt(
role: str,
user_text: str,
history: list[dict],
shared: str,
name: str = "agent",
agent: str | None = None,
direct_address: bool = False,
) -> str:
hist = history[-8:]
hist_text = "\n".join(f"{m['role']}: {m['text']}" for m in hist)
identity = _agent_prompt_identity(agent or name.lower())
direct_note = "This message was directly addressed to you, so answer as that specific agent.\n" if direct_address else ""
return (
f"{identity}\n"
f"You are operating inside {name.title()}, a pragmatic multi-agent software assistant.\n"
f"Current role: {role}.\n"
"Use concise, actionable outputs.\n"
"Keep your answer in your own perspective and do not pretend to be a different agent.\n"
f"{direct_note}"
"Respect guardrails and todo/context.\n\n"
"SHARED CONTEXT:\n"
f"{shared}\n\n"
"RECENT CHAT:\n"
f"{hist_text}\n\n"
"USER:\n"
f"{user_text}\n"
)
def _render_response_block(agent: str, role: str, text: str) -> str:
ts = datetime.now(timezone.utc).replace(microsecond=0).strftime("%H:%M:%S")
color = AGENT_COLORS.get(agent, "37")
header = _c(color, f" [{agent}]") + _c("90", f" {role} @ {ts}")
separator = _c("90", " " + "-" * 60)
body = text.rstrip() or "<empty response>"
return f"\n{header}\n{separator}\n{body}\n"
def _call_agent_with_spinner(agent: str, prompt: str, cfg: dict, role: str) -> str:
if not sys.stdout.isatty():
return _call_agent(agent, prompt, cfg, role)
done = threading.Event()
def _spin() -> None:
frames = (".", "..", "...", "....", ".....")
i = 0
while not done.is_set():
color = AGENT_COLORS.get(agent, "37")
msg = _c(color, f" [{agent}]") + _c("90", f" thinking{frames[i % len(frames)]}")
sys.stdout.write(f"\r{msg}" + " " * 20)
sys.stdout.flush()
time.sleep(0.3)
i += 1
sys.stdout.write("\r" + " " * 72 + "\r")
sys.stdout.flush()
t = threading.Thread(target=_spin, daemon=True)
t.start()
try:
return _call_agent(agent, prompt, cfg, role)
finally:
done.set()
t.join(timeout=1)
def _route_message(raw: str) -> tuple[str, str, str | None]:
role = "orchestrator"
direct_agent: str | None = None
user_text = raw.strip()
if user_text.lower().startswith("impl:"):
return "implementation", user_text[5:].strip(), None
if user_text.lower().startswith("ui:"):
return "uidocs", user_text[3:].strip(), None
lowered = user_text.lower()
for agent_name in AGENTS:
prefix = f"@{agent_name} "
if lowered.startswith(prefix):
direct_agent = agent_name
user_text = user_text[len(prefix):].strip()
role = _default_role_for_direct_agent(agent_name)
break
return role, user_text, direct_agent
def _run_once(cfg: dict, message: str, task_id: str | None) -> int:
history: list[dict] = []
role, user_text, direct_agent = _route_message(message)
history.append({"role": "user", "text": user_text})
try:
agent, out, failures = _chat_once(role, user_text, cfg, history, task_id, direct_agent=direct_agent)
sys.stdout.write(_render_response_block(agent, role, out))
if failures:
for f in failures:
sys.stdout.write(_c("33", f" [fallback] {f}") + "\n")
return 0
except Exception as exc:
sys.stderr.write(f"error: {exc}\n")
return 1
def _smoke_test(cfg: dict, task_id: str | None) -> int:
prompt = "Reply with exactly: smoke-ok"
role = "orchestrator"
history: list[dict] = [{"role": "user", "text": prompt}]
shared = _shared_context(Path(cfg["tasks_root"]).expanduser(), task_id, cfg)
built = _build_prompt(role, prompt, history, shared, cfg.get("name", "agent"))
print("Smoke test start")
rc = 0
for agent in AGENTS:
status = _service_status(agent, cfg)
if status.startswith("down") or status.startswith("unavailable"):
print(f"- {agent}: skipped ({status})")
continue
try:
out = _call_agent_with_spinner(agent, built, cfg, role)
first = (out or "").strip().splitlines()
sample = first[0] if first else "<empty response>"
print(f"- {agent}: ok -> {sample[:120]}")
except Exception as exc:
rc = 1
print(f"- {agent}: failed -> {exc}")
print("Smoke test done")
return rc
def _write_tasks_env(cfg: dict) -> None:
tasks_root = Path(cfg["tasks_root"]).expanduser()
env_path = tasks_root / ".env"
lines = [
f"OPENAI_API_KEY={cfg['keys']['openai']}",
f"ANTHROPIC_API_KEY={cfg['keys']['anthropic']}",
f"GEMINI_API_KEY={cfg['keys']['gemini']}",
"",
f"OPENAI_MODEL_CODEX={cfg['models']['codex']}",
f"OPENAI_MODEL_ORCHESTRATOR_FALLBACK={cfg['models']['codex_orchestrator']}",
f"ANTHROPIC_MODEL_ORCHESTRATOR={cfg['models']['claude']}",
f"GEMINI_MODEL_UI_DOCS={cfg['models']['gemini']}",
"",
f"ORCHESTRATOR_CHAIN={','.join(cfg['chains']['orchestrator'])}",
f"IMPLEMENTATION_CHAIN={','.join(cfg['chains']['implementation'])}",
f"UIDOCS_CHAIN={','.join(cfg['chains']['uidocs'])}",
f"REVIEW_CHAIN={','.join(cfg['chains']['review'])}",
"SHARED_CONTEXT_MAX_SECTION_CHARS=6000",
]
_write(env_path, "\n".join(lines) + "\n")
os.chmod(env_path, 0o600)
def _run_init_shared(tasks_root: Path) -> None:
script = tasks_root / "orchestrator.py"
if not script.exists():
return
subprocess.run([sys.executable, str(script), "init-shared"], check=False)
def _prompt(label: str, default: str = "") -> str:
suffix = f" [{default}]" if default else ""
val = input(f"{label}{suffix}: ").strip()
return val if val else default
def setup_wizard(cfg: dict, force: bool = False) -> dict:
name = cfg.get("name", "agent")
print(f"\n{name.title()} setup wizard")
print("Configure API and/or CLI providers. At least one usable provider is required.\n")
name = _prompt("Orchestrator name", name).lower().strip() or "agent"
cfg["name"] = name
tasks_root = Path(_prompt("Tasks root", cfg["tasks_root"]))
cfg["tasks_root"] = str(tasks_root)
claude_mode = _prompt("Claude mode (cli/api)", cfg.get("claude_mode", "cli")).lower()
if claude_mode not in ("cli", "api"):
claude_mode = "cli"
cfg["claude_mode"] = claude_mode
codex_mode = _prompt("Codex mode (api/cli)", cfg.get("codex_mode", "api")).lower()
if codex_mode not in ("api", "cli"):
codex_mode = "api"
cfg["codex_mode"] = codex_mode
if cfg["codex_mode"] == "cli":
codex_perm = _prompt(
"Codex CLI permission mode (full-host-unattended/sandboxed-auto)",
cfg.get("codex_cli_permission_mode", "full-host-unattended"),
).lower()
if codex_perm not in ("full-host-unattended", "sandboxed-auto"):
codex_perm = "full-host-unattended"
cfg["codex_cli_permission_mode"] = codex_perm
gemini_mode = _prompt("Gemini mode (api/cli)", cfg.get("gemini_mode", "api")).lower()
if gemini_mode not in ("api", "cli"):
gemini_mode = "api"
cfg["gemini_mode"] = gemini_mode
if cfg["gemini_mode"] == "cli":
gemini_perm = _prompt(
"Gemini CLI permission mode (full-host-unattended/sandboxed-auto)",
cfg.get("gemini_cli_permission_mode", "full-host-unattended"),
).lower()
if gemini_perm not in ("full-host-unattended", "sandboxed-auto"):
gemini_perm = "full-host-unattended"
cfg["gemini_cli_permission_mode"] = gemini_perm
existing_openai = cfg["keys"]["openai"] if cfg["keys"]["openai"] and not force else ""
existing_anthropic = cfg["keys"]["anthropic"] if cfg["keys"]["anthropic"] and not force else ""
existing_gemini = cfg["keys"]["gemini"] if cfg["keys"]["gemini"] and not force else ""
oai_label = "OpenAI API key"
if cfg["codex_mode"] == "cli":
oai_label += " (optional in cli mode)"
oai = getpass(f"{oai_label}{' [press Enter to keep existing]' if existing_openai else ''}: ").strip()
ant_label = "Anthropic API key"
if cfg["claude_mode"] == "cli":
ant_label += " (optional in cli mode)"
ant = getpass(f"{ant_label}{' [press Enter to keep existing]' if existing_anthropic else ''}: ").strip()
gem_label = "Gemini API key"
if cfg["gemini_mode"] == "cli":
gem_label += " (optional in cli mode)"
gem = getpass(f"{gem_label}{' [press Enter to keep existing]' if existing_gemini else ''}: ").strip()
cfg["keys"]["openai"] = oai or existing_openai
cfg["keys"]["anthropic"] = ant or existing_anthropic
cfg["keys"]["gemini"] = gem or existing_gemini
has_provider = any(v.strip() for v in cfg["keys"].values())
if cfg["claude_mode"] == "cli" and shutil.which("claude"):
has_provider = True
if cfg["codex_mode"] == "cli" and shutil.which("codex"):
has_provider = True
if cfg["gemini_mode"] == "cli" and shutil.which("gemini"):
has_provider = True
if not has_provider:
raise RuntimeError(
"No usable provider configured. Add at least one API key, or use Claude/Codex/Gemini in cli mode with their CLIs installed."
)
print("\nModel IDs (use exact account IDs if custom):")
cfg["models"]["claude"] = _prompt("Claude model", cfg["models"]["claude"])
cfg["models"]["codex"] = _prompt("Codex model", cfg["models"]["codex"])
cfg["models"]["codex_orchestrator"] = _prompt(
"Codex fallback orchestrator model", cfg["models"]["codex_orchestrator"]
)
cfg["models"]["gemini"] = _prompt("Gemini model", cfg["models"]["gemini"])
print("\nRole fallback chains (comma separated, values: claude,codex,gemini):")
cfg["chains"]["orchestrator"] = _parse_chain(
_prompt("ORCHESTRATOR_CHAIN", ",".join(cfg["chains"]["orchestrator"])),
DEFAULTS["chains"]["orchestrator"],
)
cfg["chains"]["implementation"] = _parse_chain(
_prompt("IMPLEMENTATION_CHAIN", ",".join(cfg["chains"]["implementation"])),
DEFAULTS["chains"]["implementation"],
)
cfg["chains"]["uidocs"] = _parse_chain(
_prompt("UIDOCS_CHAIN", ",".join(cfg["chains"]["uidocs"])),
DEFAULTS["chains"]["uidocs"],
)
cfg["chains"]["review"] = _parse_chain(
_prompt("REVIEW_CHAIN", ",".join(cfg["chains"]["review"])),
DEFAULTS["chains"]["review"],
)
_save_config(cfg)
_write_tasks_env(cfg)
_run_init_shared(tasks_root)
print(f"\nSaved: {CONFIG_PATH}")
print(f"Synced env: {tasks_root / '.env'}\n")
return cfg
def _run_orchestrator(task_id: str, cfg: dict) -> int:
tasks_root = Path(cfg["tasks_root"]).expanduser()
script = tasks_root / "orchestrator.py"
if not script.exists():
print(f"orchestrator.py not found at {script}")