forked from shareAI-lab/learn-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
2068 lines (1731 loc) · 75.7 KB
/
code.py
File metadata and controls
2068 lines (1731 loc) · 75.7 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
"""
s20: Comprehensive Agent — all teaching components in one loop.
Run: python s20_comprehensive/code.py
Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY
This final chapter intentionally puts the earlier teaching mechanisms back
together: dispatch, permission, hooks, todo, subagent, skills, compaction,
memory, prompt assembly, error recovery, task graph, background tasks, cron,
teams, protocols, autonomous agents, worktrees, and MCP.
"""
import os, subprocess, json, time, random, threading, re
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass, asdict, field
try:
import readline
readline.parse_and_bind('set bind-tty-special-chars off')
READLINE_AVAILABLE = True
except ImportError:
READLINE_AVAILABLE = False
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv(override=True)
if os.getenv("ANTHROPIC_BASE_URL"):
os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
WORKDIR = Path.cwd()
client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
MODEL = os.environ["MODEL_ID"]
PRIMARY_MODEL = MODEL
FALLBACK_MODEL = os.getenv("FALLBACK_MODEL_ID")
SKILLS_DIR = WORKDIR / "skills"
TRANSCRIPT_DIR = WORKDIR / ".transcripts"
TOOL_RESULTS_DIR = WORKDIR / ".task_outputs" / "tool-results"
DEFAULT_MAX_TOKENS = 8000
ESCALATED_MAX_TOKENS = 16000
MAX_RETRIES = 3
MAX_CONSECUTIVE_529 = 2
MAX_RECOVERY_RETRIES = 2
BASE_DELAY_MS = 500
CONTEXT_LIMIT = 50000
KEEP_RECENT_TOOL_RESULTS = 3
PERSIST_THRESHOLD = 30000
CONTINUATION_PROMPT = "Continue from the previous response. Do not repeat completed work."
PROMPT = "\033[36ms20 >> \033[0m"
CLI_ACTIVE = False
def terminal_print(text: str):
if threading.current_thread() is threading.main_thread() or not CLI_ACTIVE:
print(text)
return
line = ""
if READLINE_AVAILABLE:
try:
line = readline.get_line_buffer()
except Exception:
line = ""
print(f"\r\033[K{text}")
print(PROMPT + line, end="", flush=True)
# ── Task System ──
# Tasks are tiny durable records. Later systems add ownership, dependencies,
# worktrees, and teammates on top of this same file-backed state.
TASKS_DIR = WORKDIR / ".tasks"
TASKS_DIR.mkdir(exist_ok=True)
@dataclass
class Task:
id: str
subject: str
description: str
status: str
owner: str | None
blockedBy: list[str]
worktree: str | None = None
def _task_path(task_id: str) -> Path:
return TASKS_DIR / f"{task_id}.json"
def create_task(subject: str, description: str = "",
blockedBy: list[str] | None = None) -> Task:
task = Task(
id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}",
subject=subject, description=description,
status="pending", owner=None,
blockedBy=blockedBy or [],
)
save_task(task)
return task
def save_task(task: Task):
_task_path(task.id).write_text(json.dumps(asdict(task), indent=2))
def load_task(task_id: str) -> Task:
return Task(**json.loads(_task_path(task_id).read_text()))
def list_tasks() -> list[Task]:
return [Task(**json.loads(p.read_text()))
for p in sorted(TASKS_DIR.glob("task_*.json"))]
def get_task_json(task_id: str) -> str:
return json.dumps(asdict(load_task(task_id)), indent=2)
def can_start(task_id: str) -> bool:
# Dependencies are intentionally simple: every blocker must exist and be
# completed before the task can be claimed.
task = load_task(task_id)
for dep_id in task.blockedBy:
if not _task_path(dep_id).exists():
return False
if load_task(dep_id).status != "completed":
return False
return True
def claim_task(task_id: str, owner: str = "agent") -> str:
task = load_task(task_id)
if task.status != "pending":
return f"Task {task_id} is {task.status}, cannot claim"
if task.owner:
return f"Task {task_id} already owned by {task.owner}"
if not can_start(task_id):
deps = [d for d in task.blockedBy
if _task_path(d).exists() and load_task(d).status != "completed"]
missing = [d for d in task.blockedBy if not _task_path(d).exists()]
parts = []
if deps: parts.append(f"blocked by: {deps}")
if missing: parts.append(f"missing deps: {missing}")
return "Cannot start — " + ", ".join(parts)
task.owner = owner
task.status = "in_progress"
save_task(task)
print(f" \033[36m[claim] {task.subject} → in_progress\033[0m")
return f"Claimed {task.id} ({task.subject})"
def complete_task(task_id: str) -> str:
task = load_task(task_id)
if task.status != "in_progress":
return f"Task {task_id} is {task.status}, cannot complete"
task.status = "completed"
save_task(task)
unblocked = [t.subject for t in list_tasks()
if t.status == "pending" and t.blockedBy and can_start(t.id)]
print(f" \033[32m[complete] {task.subject} ✓\033[0m")
msg = f"Completed {task.id} ({task.subject})"
if unblocked:
msg += f"\nUnblocked: {', '.join(unblocked)}"
return msg
# ── Worktree System ──
# Worktree names become filesystem paths, so the teaching version keeps the
# validation rules strict and reuses them for create/remove/keep.
WORKTREES_DIR = WORKDIR / ".worktrees"
WORKTREES_DIR.mkdir(exist_ok=True)
VALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')
def validate_worktree_name(name: str) -> str | None:
if not name:
return "Worktree name cannot be empty"
if name in (".", ".."):
return f"'{name}' is not a valid worktree name"
if not VALID_WT_NAME.match(name):
return (f"Invalid worktree name '{name}': "
"only letters, digits, dots, underscores, dashes (1-64 chars)")
return None
def run_git(args: list[str]) -> tuple[bool, str]:
try:
r = subprocess.run(["git"] + args, cwd=WORKDIR,
capture_output=True, text=True, timeout=30)
out = (r.stdout + r.stderr).strip()
return r.returncode == 0, out[:5000] if out else "(no output)"
except subprocess.TimeoutExpired:
return False, "Error: git timeout"
def log_event(event_type: str, worktree_name: str, task_id: str = ""):
event = {"type": event_type, "worktree": worktree_name,
"task_id": task_id, "ts": time.time()}
events_file = WORKTREES_DIR / "events.jsonl"
with open(events_file, "a") as f:
f.write(json.dumps(event) + "\n")
def create_worktree(name: str, task_id: str = "") -> str:
# Tool-layer validation is part of the safety boundary; do it before git
# sees the name, not only after git happens to reject something.
err = validate_worktree_name(name)
if err:
return f"Error: {err}"
if task_id:
try:
load_task(task_id)
except FileNotFoundError:
return f"Error: task {task_id} not found"
path = WORKTREES_DIR / name
if path.exists():
return f"Worktree '{name}' already exists at {path}"
ok, result = run_git(["worktree", "add", str(path), "-b", f"wt/{name}", "HEAD"])
if not ok:
return f"Git error: {result}"
if task_id:
bind_task_to_worktree(task_id, name)
log_event("create", name, task_id)
print(f" \033[33m[worktree] created: {name} at {path}\033[0m")
return f"Worktree '{name}' created at {path}"
def bind_task_to_worktree(task_id: str, worktree_name: str):
task = load_task(task_id)
task.worktree = worktree_name
save_task(task)
def _count_worktree_changes(path: Path) -> tuple[int, int]:
try:
r1 = subprocess.run(["git", "status", "--porcelain"],
cwd=path, capture_output=True, text=True, timeout=10)
files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])
r2 = subprocess.run(["git", "log", "@{push}..HEAD", "--oneline"],
cwd=path, capture_output=True, text=True, timeout=10)
commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])
return files, commits
except Exception:
return -1, -1
def remove_worktree(name: str, discard_changes: bool = False) -> str:
err = validate_worktree_name(name)
if err:
return err
path = WORKTREES_DIR / name
if not path.exists():
return f"Worktree '{name}' not found"
if not discard_changes:
files, commits = _count_worktree_changes(path)
if files < 0:
return "Cannot verify status. Use discard_changes=true to force."
if files > 0 or commits > 0:
return (f"Worktree '{name}' has {files} file(s), {commits} commit(s). "
"Use discard_changes=true or keep_worktree.")
ok1, _ = run_git(["worktree", "remove", str(path), "--force"])
if not ok1:
return f"Failed to remove worktree '{name}'"
run_git(["branch", "-D", f"wt/{name}"])
log_event("remove", name)
print(f" \033[33m[worktree] removed: {name}\033[0m")
return f"Worktree '{name}' removed"
def keep_worktree(name: str) -> str:
err = validate_worktree_name(name)
if err:
return err
log_event("keep", name)
return f"Worktree '{name}' kept for review (branch: wt/{name})"
# ── Skill Loading ──
SKILL_REGISTRY: dict[str, dict] = {}
def _parse_frontmatter(text: str) -> tuple[dict, str]:
if not text.startswith("---"):
return {}, text
parts = text.split("---", 2)
if len(parts) < 3:
return {}, text
meta = {}
for line in parts[1].strip().splitlines():
if ":" in line:
key, value = line.split(":", 1)
meta[key.strip()] = value.strip().strip('"').strip("'")
return meta, parts[2].strip()
def scan_skills():
SKILL_REGISTRY.clear()
if not SKILLS_DIR.exists():
return
for directory in sorted(SKILLS_DIR.iterdir()):
if not directory.is_dir():
continue
manifest = directory / "SKILL.md"
if not manifest.exists():
continue
raw = manifest.read_text()
meta, _ = _parse_frontmatter(raw)
name = meta.get("name", directory.name)
desc = meta.get("description", raw.split("\n")[0].lstrip("#").strip())
SKILL_REGISTRY[name] = {
"name": name,
"description": desc,
"content": raw,
}
scan_skills()
def list_skills() -> str:
if not SKILL_REGISTRY:
return "(no skills found)"
return "\n".join(
f"- {skill['name']}: {skill['description']}"
for skill in SKILL_REGISTRY.values())
def load_skill(name: str) -> str:
skill = SKILL_REGISTRY.get(name)
if not skill:
available = ", ".join(SKILL_REGISTRY.keys()) or "(none)"
return f"Skill not found: {name}. Available: {available}"
return skill["content"]
# ── Prompt Assembly ──
PROMPT_SECTIONS = {
"identity": "You are a coding agent. Act, don't explain.",
"tools": "Available tools: bash, read_file, write_file, edit_file, glob, "
"todo_write, task, load_skill, compact, "
"create_task, list_tasks, get_task, claim_task, complete_task, "
"schedule_cron, list_crons, cancel_cron, "
"spawn_teammate, send_message, check_inbox, "
"request_shutdown, request_plan, review_plan, "
"create_worktree, remove_worktree, keep_worktree, "
"connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.",
"workspace": f"Working directory: {WORKDIR}",
"memory": "Relevant memories are injected below when available.",
}
def assemble_system_prompt(context: dict) -> str:
# The system prompt is rebuilt each turn from live context. This is where
# memory, skill catalog, MCP state, and active teammates become visible.
sections = [PROMPT_SECTIONS["identity"],
PROMPT_SECTIONS["tools"],
PROMPT_SECTIONS["workspace"]]
sections.append(f"Current time: {datetime.now().isoformat(timespec='seconds')}")
sections.append("Skills catalog:\n" + list_skills() +
"\nUse load_skill(name) when a skill is relevant.")
if context.get("memories"):
sections.append(f"Relevant memories:\n{context['memories']}")
mcp_names = list(mcp_clients.keys())
if mcp_names:
sections.append(f"Connected MCP servers: {', '.join(mcp_names)}")
return "\n\n".join(sections)
# ── Basic Tools ──
def safe_path(p: str, cwd: Path = None) -> Path:
# File tools stay inside the workspace or teammate worktree. Bash remains
# powerful on purpose and is controlled by the permission hook instead.
base = cwd or WORKDIR
path = (base / p).resolve()
if not path.is_relative_to(base):
raise ValueError(f"Path escapes workspace: {p}")
return path
def run_bash(command: str, cwd: Path = None,
run_in_background: bool = False) -> str:
# run_in_background is consumed by the dispatcher; direct execution ignores it.
try:
r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,
capture_output=True, text=True, timeout=120)
out = (r.stdout + r.stderr).strip()
return out[:50000] if out else "(no output)"
except subprocess.TimeoutExpired:
return "Error: Timeout (120s)"
def run_read(path: str, limit: int | None = None,
offset: int = 0, cwd: Path = None) -> str:
try:
lines = safe_path(path, cwd).read_text().splitlines()
offset = max(int(offset or 0), 0)
limit = int(limit) if limit is not None else None
lines = lines[offset:]
if limit is not None and limit < len(lines):
lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
return "\n".join(lines)
except Exception as e:
return f"Error: {e}"
def run_write(path: str, content: str, cwd: Path = None) -> str:
try:
fp = safe_path(path, cwd)
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(content)
return f"Wrote {len(content)} bytes to {path}"
except Exception as e:
return f"Error: {e}"
def run_edit(path: str, old_text: str, new_text: str,
cwd: Path = None) -> str:
try:
fp = safe_path(path, cwd)
text = fp.read_text()
if old_text not in text:
return f"Error: text not found in {path}"
fp.write_text(text.replace(old_text, new_text, 1))
return f"Edited {path}"
except Exception as e:
return f"Error: {e}"
def run_glob(pattern: str, cwd: Path = None) -> str:
import glob as g
try:
base = cwd or WORKDIR
results = []
for match in g.glob(pattern, root_dir=base):
if (base / match).resolve().is_relative_to(base):
results.append(match)
return "\n".join(results) if results else "(no matches)"
except Exception as e:
return f"Error: {e}"
def call_tool_handler(handler, args: dict, name: str) -> str:
if not handler:
return f"Unknown: {name}"
try:
return handler(**(args or {}))
except TypeError as e:
return f"Error: {e}"
def run_todo_write(todos: list) -> str:
for i, todo in enumerate(todos):
if "content" not in todo or "status" not in todo:
return f"Error: todos[{i}] missing 'content' or 'status'"
if todo["status"] not in ("pending", "in_progress", "completed"):
return f"Error: todos[{i}] has invalid status '{todo['status']}'"
path = TASKS_DIR / "current_todos.json"
path.write_text(json.dumps(todos, indent=2, ensure_ascii=False))
print(f" \033[33m[todo] updated {len(todos)} item(s)\033[0m")
return f"Updated {len(todos)} todos"
# ── MessageBus ──
# Team communication is append-only JSONL mailboxes. This keeps the protocol
# inspectable on disk and lets background teammates send messages.
MAILBOX_DIR = WORKDIR / ".mailboxes"
MAILBOX_DIR.mkdir(exist_ok=True)
class MessageBus:
def send(self, from_agent: str, to_agent: str, content: str,
msg_type: str = "message", metadata: dict = None):
msg = {"from": from_agent, "to": to_agent,
"content": content, "type": msg_type,
"ts": time.time(), "metadata": metadata or {}}
inbox = MAILBOX_DIR / f"{to_agent}.jsonl"
with open(inbox, "a") as f:
f.write(json.dumps(msg) + "\n")
terminal_print(f" \033[33m[bus] {from_agent} → {to_agent}: "
f"({msg_type}) {content[:50]}\033[0m")
def read_inbox(self, agent: str) -> list[dict]:
inbox = MAILBOX_DIR / f"{agent}.jsonl"
if not inbox.exists():
return []
msgs = [json.loads(line) for line in inbox.read_text().splitlines()
if line.strip()]
inbox.unlink()
return msgs
BUS = MessageBus()
active_teammates: dict[str, bool] = {}
# ── Protocol State ──
@dataclass
class ProtocolState:
request_id: str
type: str
sender: str
target: str
status: str
payload: str
created_at: float = field(default_factory=time.time)
pending_requests: dict[str, ProtocolState] = {}
def new_request_id() -> str:
return f"req_{random.randint(0, 999999):06d}"
def match_response(response_type: str, request_id: str, approve: bool):
# Responses are matched by request_id so one protocol reply cannot approve
# a different pending request.
state = pending_requests.get(request_id)
if not state:
return
if state.type == "shutdown" and response_type != "shutdown_response":
return
if state.type == "plan_approval" and response_type != "plan_approval_response":
return
state.status = "approved" if approve else "rejected"
def consume_lead_inbox(route_protocol=True) -> list[dict]:
msgs = BUS.read_inbox("lead")
if route_protocol:
for msg in msgs:
meta = msg.get("metadata", {})
req_id = meta.get("request_id", "")
msg_type = msg.get("type", "")
if req_id and msg_type.endswith("_response"):
match_response(msg_type, req_id, meta.get("approve", False))
return msgs
# ── Autonomous Agent ──
IDLE_POLL_INTERVAL = 5
IDLE_TIMEOUT = 60
def scan_unclaimed_tasks() -> list[dict]:
unclaimed = []
for f in sorted(TASKS_DIR.glob("task_*.json")):
task = json.loads(f.read_text())
if (task.get("status") == "pending"
and not task.get("owner")
and can_start(task["id"])):
unclaimed.append(task)
return unclaimed
def idle_poll(agent_name: str, messages: list,
name: str, role: str,
worktree_context: dict | None = None) -> str:
# Autonomous teammates wake up for inbox messages first, then look for
# unclaimed tasks. This keeps direct protocol messages higher priority.
for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):
time.sleep(IDLE_POLL_INTERVAL)
inbox = BUS.read_inbox(agent_name)
if inbox:
for msg in inbox:
if msg.get("type") == "shutdown_request":
req_id = msg.get("metadata", {}).get("request_id", "")
BUS.send(name, "lead", "Shutting down.",
"shutdown_response",
{"request_id": req_id, "approve": True})
return "shutdown"
messages.append({"role": "user",
"content": "<inbox>" + json.dumps(inbox) + "</inbox>"})
return "work"
unclaimed = scan_unclaimed_tasks()
if unclaimed:
task_data = unclaimed[0]
result = claim_task(task_data["id"], agent_name)
if "Claimed" in result:
wt_info = ""
if task_data.get("worktree"):
wt_path = WORKTREES_DIR / task_data["worktree"]
wt_info = f"\nWork directory: {wt_path}"
if worktree_context is not None:
worktree_context["path"] = str(wt_path)
messages.append({"role": "user",
"content": f"<auto-claimed>Task {task_data['id']}: "
f"{task_data['subject']}{wt_info}</auto-claimed>"})
return "work"
return "timeout"
# ── Teammate Thread ──
def spawn_teammate_thread(name: str, role: str, prompt: str) -> str:
if name in active_teammates:
return f"Teammate '{name}' already exists"
# Plan approval is a real gate: after submit_plan, the teammate stops
# taking model/tool steps until lead sends plan_approval_response.
protocol_ctx = {"waiting_plan": None}
system = (f"You are '{name}', a {role}. "
f"Use tools to complete tasks. "
f"If a task has a worktree, work in that directory.")
def handle_inbox_message(name: str, msg: dict, messages: list):
msg_type = msg.get("type", "message")
meta = msg.get("metadata", {})
req_id = meta.get("request_id", "")
if msg_type == "shutdown_request":
BUS.send(name, "lead", "Shutting down.",
"shutdown_response",
{"request_id": req_id, "approve": True})
return True
if msg_type == "plan_approval_response":
approve = meta.get("approve", False)
if req_id == protocol_ctx["waiting_plan"]:
protocol_ctx["waiting_plan"] = None
messages.append({"role": "user",
"content": "[Plan approved]" if approve
else f"[Plan rejected] {msg['content']}"})
return False
def run():
wt_ctx = {"path": None}
def _wt_cwd():
# Once a task with a worktree is claimed, all teammate file tools
# transparently run inside that isolated directory.
p = wt_ctx["path"]
return Path(p) if p else None
def _run_bash(command: str) -> str:
return run_bash(command, cwd=_wt_cwd())
def _run_read(path: str) -> str:
return run_read(path, cwd=_wt_cwd())
def _run_write(path: str, content: str) -> str:
return run_write(path, content, cwd=_wt_cwd())
def _run_list_tasks():
tasks = list_tasks()
if not tasks:
return "No tasks."
return "\n".join(
f" {t.id}: {t.subject} [{t.status}]"
+ (f" (wt:{t.worktree})" if t.worktree else "")
for t in tasks)
def _run_claim_task(task_id: str):
result = claim_task(task_id, owner=name)
if "Claimed" in result:
task = load_task(task_id)
wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree)
if task.worktree else None)
return result
def _run_complete_task(task_id: str):
result = complete_task(task_id)
wt_ctx["path"] = None
return result
messages = [{"role": "user", "content": prompt}]
sub_tools = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"]}},
{"name": "read_file", "description": "Read file.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"limit": {"type": "integer"},
"offset": {"type": "integer"}},
"required": ["path"]}},
{"name": "write_file", "description": "Write file.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"content": {"type": "string"}},
"required": ["path", "content"]}},
{"name": "send_message",
"description": "Send message to another agent.",
"input_schema": {"type": "object",
"properties": {"to": {"type": "string"},
"content": {"type": "string"}},
"required": ["to", "content"]}},
{"name": "submit_plan",
"description": "Submit a plan for Lead approval.",
"input_schema": {"type": "object",
"properties": {"plan": {"type": "string"}},
"required": ["plan"]}},
{"name": "list_tasks",
"description": "List all tasks.",
"input_schema": {"type": "object", "properties": {},
"required": []}},
{"name": "claim_task",
"description": "Claim a pending task.",
"input_schema": {"type": "object",
"properties": {"task_id": {"type": "string"}},
"required": ["task_id"]}},
{"name": "complete_task",
"description": "Mark an in-progress task as completed.",
"input_schema": {"type": "object",
"properties": {"task_id": {"type": "string"}},
"required": ["task_id"]}},
]
sub_handlers = {
"bash": _run_bash, "read_file": _run_read,
"write_file": _run_write,
"send_message": lambda to, content: (BUS.send(name, to, content),
"Sent")[1],
"list_tasks": _run_list_tasks,
"claim_task": _run_claim_task,
"complete_task": _run_complete_task,
}
while True:
if len(messages) <= 3:
messages.insert(0, {"role": "user",
"content": f"<identity>You are '{name}', role: {role}. "
f"Continue your work.</identity>"})
should_shutdown = False
for _ in range(10):
inbox = BUS.read_inbox(name)
for msg in inbox:
stopped = handle_inbox_message(name, msg, messages)
if stopped:
should_shutdown = True
break
if should_shutdown:
break
if protocol_ctx["waiting_plan"]:
# Poll only for protocol replies while the approval gate is
# closed; do not let the model continue with the task.
time.sleep(IDLE_POLL_INTERVAL)
continue
if inbox and not should_shutdown:
non_protocol = [m for m in inbox
if m.get("type") == "message"]
if non_protocol:
messages.append({"role": "user",
"content": "<inbox>" + json.dumps(non_protocol) + "</inbox>"})
try:
response = client.messages.create(
model=MODEL, system=system, messages=messages[-20:],
tools=sub_tools, max_tokens=8000)
except Exception:
break
messages.append({"role": "assistant", "content": response.content})
if not has_tool_use(response.content):
break
results = []
for block in response.content:
if block.type == "tool_use":
if block.name == "submit_plan":
output = _teammate_submit_plan(
name, block.input.get("plan", ""))
match = re.search(r"\((req_\d+)\)", output)
protocol_ctx["waiting_plan"] = (
match.group(1) if match else output)
else:
handler = sub_handlers.get(block.name)
output = call_tool_handler(handler, block.input,
block.name)
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": str(output)})
if protocol_ctx["waiting_plan"]:
# Ignore later tool_use blocks from the same model
# response; they belong after approval, not before.
break
messages.append({"role": "user", "content": results})
if protocol_ctx["waiting_plan"]:
break
if should_shutdown:
break
if protocol_ctx["waiting_plan"]:
continue
idle_result = idle_poll(name, messages, name, role, wt_ctx)
if idle_result in ("shutdown", "timeout"):
break
summary = "Done."
for msg in reversed(messages):
if msg["role"] == "assistant" and isinstance(msg["content"], list):
for b in msg["content"]:
if getattr(b, "type", None) == "text":
summary = b.text
break
else:
continue
break
BUS.send(name, "lead", summary, "result")
active_teammates.pop(name, None)
active_teammates[name] = True
threading.Thread(target=run, daemon=True).start()
return f"Teammate '{name}' spawned as {role}"
def _teammate_submit_plan(from_name: str, plan: str) -> str:
req_id = new_request_id()
pending_requests[req_id] = ProtocolState(
request_id=req_id, type="plan_approval",
sender=from_name, target="lead",
status="pending", payload=plan)
BUS.send(from_name, "lead", plan,
"plan_approval_request",
{"request_id": req_id})
return f"Plan submitted ({req_id})"
# ── Lead Protocol Tools ──
def run_request_shutdown(teammate: str) -> str:
req_id = new_request_id()
pending_requests[req_id] = ProtocolState(
request_id=req_id, type="shutdown",
sender="lead", target=teammate,
status="pending", payload="")
BUS.send("lead", teammate, "Shut down.", "shutdown_request",
{"request_id": req_id})
return f"Shutdown request sent to {teammate}"
def run_request_plan(teammate: str, task: str) -> str:
BUS.send("lead", teammate, f"Submit plan for: {task}", "message")
return f"Asked {teammate} to submit a plan"
def run_review_plan(request_id: str, approve: bool,
feedback: str = "") -> str:
state = pending_requests.get(request_id)
if not state:
return f"Request {request_id} not found"
state.status = "approved" if approve else "rejected"
BUS.send("lead", state.sender,
feedback or ("Approved" if approve else "Rejected"),
"plan_approval_response",
{"request_id": request_id, "approve": approve})
return f"Plan {'approved' if approve else 'rejected'}"
# ── Hooks + Permission Pipeline ──
# Hooks are intentionally outside tool handlers. The loop can add permission,
# logging, and stop behavior without changing each individual tool.
HOOKS = {"UserPromptSubmit": [], "PreToolUse": [],
"PostToolUse": [], "Stop": []}
def register_hook(event: str, callback):
HOOKS[event].append(callback)
def trigger_hooks(event: str, *args):
for callback in HOOKS[event]:
result = callback(*args)
if result is not None:
return result
return None
DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if="]
DESTRUCTIVE = ["rm ", "> /etc/", "chmod 777"]
def permission_hook(block):
# The permission layer sees the raw tool_use before dispatch. It can deny,
# ask the user, or allow execution to continue.
if block.name == "bash":
command = block.input.get("command", "")
for pattern in DENY_LIST:
if pattern in command:
return f"Permission denied: '{pattern}' is on the deny list"
if any(token in command for token in DESTRUCTIVE):
print(f"\n\033[33m[permission] destructive command\033[0m")
print(f" {command}")
choice = input(" Allow? [y/N] ").strip().lower()
if choice not in ("y", "yes"):
return "Permission denied by user"
if block.name in ("write_file", "edit_file"):
path = block.input.get("path", "")
try:
safe_path(path)
except Exception:
return f"Permission denied: path escapes workspace: {path}"
if block.name.startswith("mcp__") and "deploy" in block.name:
print(f"\n\033[33m[permission] MCP destructive-looking tool: {block.name}\033[0m")
choice = input(" Allow? [y/N] ").strip().lower()
if choice not in ("y", "yes"):
return "Permission denied by user"
return None
def log_hook(block):
print(f"\033[90m[HOOK] {block.name}\033[0m")
return None
def large_output_hook(block, output):
if len(str(output)) > 100000:
print(f"\033[33m[HOOK] large output from {block.name}: "
f"{len(str(output))} chars\033[0m")
return None
def user_prompt_hook(query: str):
print(f"\033[90m[HOOK] UserPromptSubmit: {WORKDIR}\033[0m")
return None
def stop_hook(messages: list):
tool_count = 0
for msg in messages:
content = msg.get("content")
if isinstance(content, list):
tool_count += sum(1 for item in content
if isinstance(item, dict)
and item.get("type") == "tool_result")
print(f"\033[90m[HOOK] Stop: {tool_count} tool result(s)\033[0m")
return None
register_hook("UserPromptSubmit", user_prompt_hook)
register_hook("PreToolUse", permission_hook)
register_hook("PreToolUse", log_hook)
register_hook("PostToolUse", large_output_hook)
register_hook("Stop", stop_hook)
# ── Subagent Tool ──
SUB_SYSTEM = (
f"You are a coding subagent at {WORKDIR}. "
"Complete the task, then return a concise final summary. "
"Do not spawn more agents."
)
SUB_TOOLS = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"]}},
{"name": "read_file", "description": "Read file contents.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"limit": {"type": "integer"},
"offset": {"type": "integer"}},
"required": ["path"]}},
{"name": "write_file", "description": "Write content to a file.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"content": {"type": "string"}},
"required": ["path", "content"]}},
{"name": "edit_file", "description": "Replace exact text in a file once.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"old_text": {"type": "string"},
"new_text": {"type": "string"}},
"required": ["path", "old_text", "new_text"]}},
{"name": "glob", "description": "Find files matching a glob pattern.",
"input_schema": {"type": "object",
"properties": {"pattern": {"type": "string"}},
"required": ["pattern"]}},
]
SUB_HANDLERS = {
"bash": run_bash, "read_file": run_read,
"write_file": run_write, "edit_file": run_edit,
"glob": run_glob,
}
def extract_text(content) -> str:
if not isinstance(content, list):
return str(content)
return "\n".join(
getattr(block, "text", "")
for block in content
if getattr(block, "type", None) == "text").strip()
def has_tool_use(content) -> bool:
# Do not rely on stop_reason alone; the concrete tool_use block is the
# continuation signal used by the loop.
return any(getattr(block, "type", None) == "tool_use"