Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
1892 lines (1624 loc) · 69.4 KB
/
Copy pathcode.py
File metadata and controls
1892 lines (1624 loc) · 69.4 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
"""
s13: Agent Teams - persistent teammates with shared tasks and mailboxes.
Run: python s13_agent_teams/code.py
Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY
+------+ spawn(task_id) +----------+ result +------+
| Lead | ---------------> | WORK | -------> | IDLE |
+--+---+ +----+-----+ +--+---+
^ | |
| team events | tools | wait
| v v
+--+-----------+ +----------+ +----------+
| MessageBus | | Task cwd | <----- | Mailbox |
+--------------+ +----------+ claim +----------+
.tasks/ shared task records and dependencies
.mailboxes/ messages, results, and protocol responses
.worktrees/ optional task-bound working directories
"""
import fcntl
import json
import os
import random
import re
import secrets
import select
import subprocess
import sys
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, asdict, field
from pathlib import Path
try:
import readline
readline.parse_and_bind('set bind-tty-special-chars off')
except ImportError:
pass
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"]
# -- Task System --
TASKS_DIR = WORKDIR / ".tasks"
TASKS_ROOT = TASKS_DIR.resolve()
TASK_ID_PATTERN = re.compile(r"^task_[0-9a-f]{8}$")
task_lock = threading.RLock()
TASK_LOCK_PATH = TASKS_DIR / ".lock"
_task_store_state = threading.local()
# owner -> {"task_id": str, "cwd": Path}. A teammate gets one assignment at
# a time, and every filesystem tool resolves its cwd through this registry.
teammate_assignments: dict[str, dict[str, object]] = {}
assignment_versions: dict[str, int] = {}
@contextmanager
def task_store_lock():
"""Serialize task mutations across threads and host processes."""
with task_lock:
depth = getattr(_task_store_state, "depth", 0)
if depth == 0:
TASKS_DIR.mkdir(parents=True, exist_ok=True)
handle = TASK_LOCK_PATH.open("a+", encoding="utf-8")
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
_task_store_state.handle = handle
_task_store_state.depth = depth + 1
try:
yield
finally:
_task_store_state.depth -= 1
if _task_store_state.depth == 0:
handle = _task_store_state.handle
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
handle.close()
del _task_store_state.handle
def advance_assignment_version(owner: str):
"""Invalidate old approvals without clearing an explicit plan requirement."""
with task_lock:
assignment_versions[owner] = assignment_versions.get(owner, 0) + 1
gates = globals().get("plan_gates")
request_ids = globals().get("plan_request_ids")
team = globals().get("team_lock")
if team is not None:
team.acquire()
try:
if (isinstance(gates, dict) and owner in gates
and gates[owner] != "not_required"):
gates[owner] = "required"
if isinstance(request_ids, dict):
request_ids.pop(owner, None)
finally:
if team is not None:
team.release()
@dataclass
class Task:
id: str
subject: str
description: str
status: str # pending | in_progress | completed
owner: str | None
blockedBy: list[str]
worktree: str | None = None
def _task_path(task_id: str) -> Path:
if not isinstance(task_id, str) or not TASK_ID_PATTERN.fullmatch(task_id):
raise ValueError(f"Invalid task ID: {task_id!r}")
path = (TASKS_DIR / f"{task_id}.json").resolve()
if (not TASKS_ROOT.is_relative_to(WORKDIR.resolve())
or not path.is_relative_to(TASKS_ROOT)):
raise ValueError(f"Invalid task ID: {task_id!r}")
return path
def create_task(subject: str, description: str = "") -> Task:
subject = subject.strip()
if not subject:
raise ValueError("Task subject cannot be empty")
with task_store_lock():
for _ in range(100):
task = Task(
id=f"task_{secrets.token_hex(4)}",
subject=subject,
description=description,
status="pending",
owner=None,
blockedBy=[],
)
try:
with _task_path(task.id).open("x", encoding="utf-8") as handle:
json.dump(asdict(task), handle, indent=2)
return task
except FileExistsError:
continue
raise RuntimeError("Could not allocate a unique task ID")
def _task_depends_on(task_id: str, target_id: str) -> bool:
"""Return whether task_id transitively depends on target_id."""
pending = [task_id]
visited = set()
while pending:
current = pending.pop()
if current == target_id:
return True
if current in visited:
continue
visited.add(current)
pending.extend(load_task(current).blockedBy)
return False
def update_task(task_id: str, addBlockedBy: list[str]) -> Task:
"""Add dependency edges after create_task has returned real task IDs."""
if not isinstance(addBlockedBy, list):
raise ValueError("addBlockedBy must be a list of task IDs")
with task_store_lock():
task = load_task(task_id)
if task.status != "pending" or task.owner is not None:
raise ValueError(
f"Task {task_id} dependencies can only be updated while "
"pending and unowned"
)
dependencies = list(dict.fromkeys(addBlockedBy))
for dependency in dependencies:
if dependency == task_id:
raise ValueError("Task cannot depend on itself")
if not _task_path(dependency).is_file():
raise ValueError(f"Dependency not found: {dependency}")
if dependency not in task.blockedBy and _task_depends_on(
dependency, task_id
):
raise ValueError(
f"Dependency cycle detected: {task_id} -> {dependency}"
)
task.blockedBy.extend(
dependency for dependency in dependencies
if dependency not in task.blockedBy
)
save_task(task)
return task
def save_task(task: Task):
with task_store_lock():
path = _task_path(task.id)
temporary = path.with_name(
f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp"
)
try:
temporary.write_text(
json.dumps(asdict(task), indent=2), encoding="utf-8"
)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def load_task(task_id: str) -> Task:
with task_lock:
data = json.loads(_task_path(task_id).read_text(encoding="utf-8"))
task = Task(**data)
if task.id != task_id:
raise ValueError(f"Task file ID does not match {task_id}")
if task.status not in {"pending", "in_progress", "completed"}:
raise ValueError(f"Invalid task status: {task.status}")
return task
def list_tasks() -> list[Task]:
with task_lock:
if not TASKS_DIR.exists():
return []
if not TASKS_ROOT.is_relative_to(WORKDIR.resolve()):
raise ValueError("Tasks directory escapes workspace")
return [load_task(path.stem)
for path in sorted(TASKS_DIR.glob("task_*.json"))]
def get_task(task_id: str) -> str:
"""Return full task details as JSON."""
task = load_task(task_id)
return json.dumps(asdict(task), indent=2)
def can_start(task_id: str) -> bool:
"""Check if all blockedBy dependencies are completed.
Missing dependencies are treated as blocked."""
task = load_task(task_id)
for dep_id in task.blockedBy:
try:
dep_path = _task_path(dep_id)
except ValueError:
return False
if not dep_path.exists():
return False
if load_task(dep_id).status != "completed":
return False
return True
def _owner_in_progress(owner: str) -> Task | None:
return next((task for task in list_tasks()
if task.status == "in_progress" and task.owner == owner), None)
def _incomplete_dependencies(task: Task) -> list[str]:
incomplete = []
for dep_id in task.blockedBy:
try:
dep_path = _task_path(dep_id)
except ValueError:
incomplete.append(dep_id)
continue
if not dep_path.exists() or load_task(dep_id).status != "completed":
incomplete.append(dep_id)
return incomplete
def claim_task(task_id: str, owner: str = "agent") -> str:
"""Atomically claim one task and bind the owner's filesystem cwd."""
with task_store_lock():
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} is already owned by {task.owner}"
assignment = teammate_assignments.get(owner)
if assignment:
return (f"Owner {owner} must finish the current work turn for "
f"{assignment['task_id']} before claiming another task")
current = _owner_in_progress(owner)
if current:
return (f"Owner {owner} must complete {current.id} before "
"claiming another task")
if not can_start(task_id):
return f"Blocked by: {_incomplete_dependencies(task)}"
cwd, error = task_worktree_cwd(task)
if error:
return f"Cannot claim {task_id}: {error}"
task.owner = owner
task.status = "in_progress"
save_task(task)
teammate_assignments[owner] = {"task_id": task.id, "cwd": cwd}
advance_assignment_version(owner)
print(f" [claim] {task.subject} -> in_progress (owner: {owner})")
return f"Claimed {task.id} ({task.subject})"
def complete_task(task_id: str, owner: str = "agent") -> str:
"""Complete an assignment only when the caller owns it."""
with task_store_lock():
task = load_task(task_id)
if task.status != "in_progress":
return f"Task {task_id} is {task.status}, cannot complete"
if task.owner != owner:
return (f"Task {task_id} is owned by {task.owner}, "
f"not {owner}; cannot complete")
gate = globals().get("plan_gates", {}).get(owner, "not_required")
if gate in {"required", "pending", "rejected"}:
return f"Task {task_id} cannot complete while plan status is {gate}"
assignment = teammate_assignments.get(owner)
if not assignment or assignment.get("task_id") != task.id:
cwd, error = task_worktree_cwd(task)
if error:
return f"Task {task_id} cannot complete: {error}"
teammate_assignments[owner] = {"task_id": task.id, "cwd": cwd}
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" [complete] {task.subject}")
msg = f"Completed {task.id} ({task.subject})"
if unblocked:
msg += f"\nUnblocked: {', '.join(unblocked)}"
print(f" [unblocked] {', '.join(unblocked)}")
return msg
# -- Task-bound Worktrees --
WORKTREES_DIR = WORKDIR / ".worktrees"
WORKTREES_ROOT = WORKTREES_DIR.resolve()
VALID_WORKTREE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
def validate_worktree_name(name: str) -> str | None:
if not isinstance(name, str) or not VALID_WORKTREE_NAME.fullmatch(name):
return ("worktree name must be 1-64 letters, digits, dots, "
"underscores, or dashes, and start with a letter or digit")
if name in {".", ".."} or ".." in name:
return "worktree name cannot contain '..'"
return None
def _worktree_path(name: str) -> Path:
path = (WORKTREES_DIR / name).resolve()
if (not WORKTREES_ROOT.is_relative_to(WORKDIR.resolve())
or not path.is_relative_to(WORKTREES_ROOT)
or path == WORKTREES_ROOT):
raise ValueError(f"Worktree path escapes directory: {name!r}")
return path
def _worktree_branch(name: str) -> str:
return f"wt/{name}"
def _run_git(args: list[str], cwd: Path | None = None) -> tuple[bool, str]:
"""Run Git without shell interpolation and preserve machine output."""
try:
result = subprocess.run(
["git", *args], cwd=cwd or WORKDIR,
capture_output=True, text=True, errors="replace", timeout=30,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return False, f"{type(exc).__name__}: {exc}"
output = (result.stdout + result.stderr).strip()
return result.returncode == 0, output or "(no output)"
def run_git(args: list[str], cwd: Path | None = None) -> tuple[bool, str]:
"""Run Git and bound only the text returned to the model."""
ok, output = _run_git(args, cwd)
return ok, output[:5000]
def _registered_worktrees() -> tuple[dict[Path, dict[str, str]], str | None]:
ok, output = _run_git(["worktree", "list", "--porcelain"])
if not ok:
return {}, f"cannot read Git worktree registry: {output}"
entries: dict[Path, dict[str, str]] = {}
current: dict[str, str] = {}
for line in output.splitlines() + [""]:
if not line:
raw_path = current.get("worktree")
if raw_path:
entries[Path(raw_path).resolve()] = current
current = {}
continue
key, _, value = line.partition(" ")
current[key] = value
return entries, None
def _registered_worktree(name: str) -> tuple[Path | None, str | None]:
try:
path = _worktree_path(name)
except ValueError as exc:
return None, str(exc)
entries, error = _registered_worktrees()
if error:
return None, error
if path not in entries:
return None, f"worktree '{name}' is not registered with Git"
if not path.is_dir():
return None, f"worktree '{name}' is missing at {path}"
expected_branch = f"refs/heads/{_worktree_branch(name)}"
if entries[path].get("branch") != expected_branch:
return None, (f"worktree '{name}' is not registered on expected "
f"branch '{_worktree_branch(name)}'")
return path, None
def task_worktree_cwd(task: Task) -> tuple[Path, str | None]:
"""Resolve a task cwd, failing closed for broken worktree bindings."""
if not task.worktree:
return WORKDIR, None
path, error = _registered_worktree(task.worktree)
return (path or WORKDIR), error
def assignment_cwd(owner: str) -> Path:
with task_lock:
assignment = teammate_assignments.get(owner)
task = _owner_in_progress(owner)
if task and (not assignment or assignment.get("task_id") != task.id):
cwd, error = task_worktree_cwd(task)
if error:
raise ValueError(error)
assignment = {"task_id": task.id, "cwd": cwd}
teammate_assignments[owner] = assignment
elif not assignment:
return WORKDIR
task = load_task(str(assignment["task_id"]))
if task.status not in {"in_progress", "completed"} or task.owner != owner:
raise ValueError(f"Assignment for {owner} is no longer active")
cwd, error = task_worktree_cwd(task)
if error:
raise ValueError(error)
if cwd.resolve() != Path(assignment["cwd"]).resolve():
raise ValueError(f"Assignment cwd changed for task {task.id}")
return cwd
def release_completed_assignment(owner: str) -> bool:
"""Release a completed cwd lease only at a model turn boundary."""
with task_lock:
assignment = teammate_assignments.get(owner)
if not assignment:
return False
task = load_task(str(assignment["task_id"]))
if task.status != "completed" or task.owner != owner:
return False
teammate_assignments.pop(owner, None)
advance_assignment_version(owner)
if owner in globals().get("plan_gates", {}):
globals()["plan_gates"][owner] = "not_required"
return True
def release_teammate_assignment(owner: str):
"""Return abandoned teammate work to the task board on thread exit."""
with task_lock:
try:
task = _owner_in_progress(owner)
if task:
task.status = "pending"
task.owner = None
save_task(task)
finally:
teammate_assignments.pop(owner, None)
advance_assignment_version(owner)
if owner in globals().get("plan_gates", {}):
globals()["plan_gates"][owner] = "not_required"
def create_worktree(name: str, task_id: str) -> str:
"""Create and bind a dedicated worktree after all inputs validate."""
error = validate_worktree_name(name)
if error:
return f"Error: {error}"
try:
path = _worktree_path(name)
task_path = _task_path(task_id)
except ValueError as exc:
return f"Error: {exc}"
branch = _worktree_branch(name)
with task_lock:
if not task_path.exists():
return f"Error: Task {task_id} not found"
task = load_task(task_id)
if task.status != "pending" or task.owner is not None:
return f"Error: Task {task_id} must be pending and unowned"
if task.worktree:
return f"Error: Task {task_id} already uses worktree '{task.worktree}'"
if any(t.worktree == name for t in list_tasks() if t.id != task_id):
return f"Error: Worktree '{name}' is already bound to another task"
if path.exists():
return f"Error: Worktree path already exists: {path}"
ok, root = run_git(["rev-parse", "--show-toplevel"])
if not ok or Path(root).resolve() != WORKDIR.resolve():
return "Error: Working directory must be the root of a Git repository"
ok, branch_check = run_git(["check-ref-format", "--branch", branch])
if not ok:
return f"Error: Invalid worktree branch '{branch}': {branch_check}"
exists, _ = run_git(["show-ref", "--verify", "--quiet",
f"refs/heads/{branch}"])
if exists:
return f"Error: Branch '{branch}' already exists"
entries, registry_error = _registered_worktrees()
if registry_error:
return f"Error: {registry_error}"
if path in entries:
return f"Error: Worktree path is already registered: {path}"
WORKTREES_DIR.mkdir(parents=True, exist_ok=True)
ok, result = run_git(["worktree", "add", "-b", branch,
str(path), "HEAD"])
if not ok:
entries, registry_error = _registered_worktrees()
branch_exists, _ = run_git(
["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"]
)
artifacts = []
if path.exists():
artifacts.append(f"checkout path '{path}'")
if registry_error is None and path in entries:
artifacts.append("registered Git worktree")
if branch_exists:
artifacts.append(f"branch '{branch}'")
if artifacts:
return (
"Partial operation: git worktree add reported an error "
f"after leaving {', '.join(artifacts)}. Task {task_id} "
"remains unbound and no Git data was deleted. Run "
f"`git worktree list`, inspect '{path}' and '{branch}', "
"then keep or remove those artifacts manually after "
f"preserving any work. Git error: {result}"
)
return f"Git error: {result}"
try:
task.worktree = name
save_task(task)
except Exception as exc:
return (f"Partial success: Worktree '{name}' was created at "
f"{path} on branch '{branch}', but task binding failed: "
f"{exc}. Git data was retained for manual recovery.")
print(f" \033[33m[worktree] created: {name} at {path}\033[0m")
return f"Worktree '{name}' created at {path} for task {task_id}"
def remove_worktree(name: str, discard_changes: bool = False) -> str:
"""Remove a registered checkout while always retaining its branch."""
error = validate_worktree_name(name)
if error:
return f"Error: {error}"
with task_lock:
path, error = _registered_worktree(name)
if error:
return f"Error: {error}"
bound = [task for task in list_tasks() if task.worktree == name]
if not bound:
return f"Error: Worktree '{name}' is not bound to a task"
active = [task for task in bound if task.status != "completed"]
if active:
return (f"Error: Worktree '{name}' is bound to active task "
f"{active[0].id}; complete it before removal")
leased = [owner for owner, assignment in teammate_assignments.items()
if Path(assignment["cwd"]).resolve() == path.resolve()]
if leased:
return (f"Error: Worktree '{name}' is still in use by "
f"{', '.join(sorted(leased))}; wait for the turn to end")
ok, status = run_git(
["status", "--porcelain", "--ignored"], cwd=path
)
if not ok:
return f"Error: Cannot verify worktree '{name}' status: {status}"
if status != "(no output)" and not discard_changes:
changed = len([line for line in status.splitlines() if line.strip()])
return (f"Error: Worktree '{name}' has {changed} uncommitted "
"change(s); preserve or discard them manually")
args = ["worktree", "remove"]
if discard_changes:
args.append("--force")
args.append(str(path))
ok, result = run_git(args)
if not ok:
return f"Git error: {result}"
try:
for task in bound:
task.worktree = None
save_task(task)
except Exception as exc:
return (f"Partial success: Worktree '{name}' was removed and "
f"branch '{_worktree_branch(name)}' retained, but task "
f"unbinding failed: {exc}. Manual recovery is required.")
print(f" [worktree] removed: {name}; branch retained")
return f"Worktree '{name}' removed; branch '{_worktree_branch(name)}' retained"
# -- System Prompt --
PROMPT_SECTIONS = {
"identity": "You are a coding agent. Act, don't explain.",
"tools": "Available tools: bash, read_file, write_file, edit_file, glob, "
"create_task, update_task, list_tasks, get_task, claim_task, "
"complete_task, "
"spawn_teammate, list_teammates, send_message, request_shutdown, "
"request_plan, review_plan, create_worktree.",
"tasks": (
"Create all task nodes first. Only after create_task returns "
"runtime-generated IDs, use update_task with those exact IDs to add "
"dependencies. Only the Lead changes task dependencies."
),
"teams": (
"When parallel work would help, first propose a small team with clear "
"responsibilities and wait for the user's confirmation. Do not call "
"spawn_teammate before the user confirms. After confirmation, delegate "
"independent work by creating a Task for each parallel change. Pass "
"task_id to spawn_teammate when assigning ready work, then "
"create a task-bound worktree only when a separate working directory "
"would prevent conflicting edits. A teammate must complete its current "
"Task before claiming another. A worktree changes tool default cwd "
"only; it is not a sandbox. Worktree removal stays with the host or "
"user. After spawning a teammate, end the current turn instead of "
"polling its status; the runtime will deliver team events and wake the "
"Lead. React to those events, and shut teammates down when "
"coordination is complete."
),
"workspace": f"Working directory: {WORKDIR}",
}
SYSTEM = "\n\n".join(PROMPT_SECTIONS.values())
# -- Base Tools --
def safe_path(p: str, cwd: Path | None = None) -> Path:
base = (cwd or WORKDIR).resolve()
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 = None) -> str:
try:
result = subprocess.run(
command,
shell=True,
cwd=cwd or WORKDIR,
capture_output=True,
text=True, errors="replace",
timeout=120,
)
output = (result.stdout + result.stderr).strip()
output = output[:50000] if output else "(no output)"
if result.returncode:
return f"Error: command exited with status {result.returncode}\n{output}"
return output
except subprocess.TimeoutExpired:
return "Error: Timeout (120s)"
except OSError as exc:
return f"Error: {type(exc).__name__}: {exc}"
def run_read(path: str, limit: int | None = None,
cwd: Path | None = None) -> str:
try:
lines = safe_path(path, cwd).read_text(encoding="utf-8").splitlines()
if limit 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 = None) -> str:
try:
fp = safe_path(path, cwd)
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(content, encoding="utf-8")
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 = None) -> str:
try:
target = safe_path(path, cwd)
content = target.read_text(encoding="utf-8")
count = content.count(old_text)
if count != 1:
return f"Error: Expected 1 occurrence, found {count}"
target.write_text(content.replace(old_text, new_text), encoding="utf-8")
return f"Edited {path}"
except Exception as exc:
return f"Error: {exc}"
def run_glob(pattern: str, cwd: Path | None = None) -> str:
try:
base = (cwd or WORKDIR).resolve()
matches = [
str(path.relative_to(base))
for path in sorted(base.glob(pattern))
if path.resolve().is_relative_to(base)
]
shown = matches[:200]
if len(matches) > 200:
shown.append("... (more matches omitted; narrow the pattern)")
return "\n".join(shown) or "No files found"
except Exception as exc:
return f"Error: {exc}"
def _agent_cwd() -> tuple[Path | None, str | None]:
try:
return assignment_cwd("agent"), None
except (FileNotFoundError, ValueError) as exc:
return None, f"Error: Invalid task assignment: {exc}"
def run_agent_bash(command: str) -> str:
cwd, error = _agent_cwd()
return error or run_bash(command, cwd)
def run_agent_read(path: str, limit: int | None = None) -> str:
cwd, error = _agent_cwd()
return error or run_read(path, limit, cwd)
def run_agent_write(path: str, content: str) -> str:
cwd, error = _agent_cwd()
return error or run_write(path, content, cwd)
def run_agent_edit(path: str, old_text: str, new_text: str) -> str:
cwd, error = _agent_cwd()
return error or run_edit(path, old_text, new_text, cwd)
def run_agent_glob(pattern: str) -> str:
cwd, error = _agent_cwd()
return error or run_glob(pattern, cwd)
# -- Task Tools --
def run_create_task(subject: str, description: str = "") -> str:
task = create_task(subject, description)
print(f" \033[34m[create] {task.subject}\033[0m")
return f"Created {task.id}: {task.subject}"
def run_update_task(task_id: str, addBlockedBy: list[str]) -> str:
try:
task = update_task(task_id, addBlockedBy)
except ValueError as exc:
return f"Error: {exc}"
except FileNotFoundError:
return f"Error: Task {task_id} not found"
dependencies = ", ".join(task.blockedBy) or "(none)"
print(f" \033[34m[update] {task.subject} blockedBy: {dependencies}\033[0m")
return f"Updated {task.id} blockedBy: {dependencies}"
def run_list_tasks() -> str:
tasks = list_tasks()
if not tasks:
return "No tasks. Use create_task to add some."
lines = []
for t in tasks:
icon = {"pending": "[ ]", "in_progress": "[~]",
"completed": "[x]"}.get(t.status, "[?]")
deps = f" (blockedBy: {', '.join(t.blockedBy)})" if t.blockedBy else ""
owner = f" [{t.owner}]" if t.owner else ""
worktree = f" (worktree: {t.worktree})" if t.worktree else ""
lines.append(f" {icon} {t.id}: {t.subject} "
f"[{t.status}]{owner}{deps}{worktree}")
return "\n".join(lines)
def run_get_task(task_id: str) -> str:
try:
return get_task(task_id)
except ValueError as exc:
return f"Error: {exc}"
except FileNotFoundError:
return f"Error: Task {task_id} not found"
def run_claim_task(task_id: str) -> str:
try:
return claim_task(task_id, owner="agent")
except ValueError as exc:
return f"Error: {exc}"
except FileNotFoundError:
return f"Error: Task {task_id} not found"
def run_complete_task(task_id: str) -> str:
try:
return complete_task(task_id, owner="agent")
except ValueError as exc:
return f"Error: {exc}"
except FileNotFoundError:
return f"Error: Task {task_id} not found"
# -- MessageBus and Team Protocols --
MAILBOX_DIR = WORKDIR / ".mailboxes"
MAILBOX_ROOT = MAILBOX_DIR.resolve()
VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
RESERVED_TEAMMATE_NAMES = {"lead", "agent"}
def is_valid_agent_name(name: str) -> bool:
return bool(VALID_AGENT_NAME.fullmatch(name))
class MessageBus:
"""Thread-safe file mailboxes with destructive reads."""
def __init__(self):
self._lock = threading.RLock()
self._changed = threading.Condition(self._lock)
def _path(self, agent: str) -> Path:
if not is_valid_agent_name(agent):
raise ValueError(f"Invalid mailbox recipient: {agent!r}")
path = (MAILBOX_DIR / f"{agent}.jsonl").resolve()
if not path.is_relative_to(MAILBOX_ROOT):
raise ValueError(f"Mailbox path escapes directory: {agent!r}")
return path
def _read_unlocked(self, agent: str) -> list[dict]:
inbox = self._path(agent)
if not inbox.exists():
return []
msgs = [json.loads(line) for line in inbox.read_text(encoding="utf-8").splitlines()
if line.strip()]
inbox.unlink()
return msgs
def send(self, from_agent: str, to_agent: str, content: str,
msg_type: str = "message", metadata: dict | None = None):
msg = {"from": from_agent, "to": to_agent,
"content": content, "type": msg_type,
"ts": time.time(), "metadata": metadata or {}}
with self._changed:
MAILBOX_DIR.mkdir(parents=True, exist_ok=True)
with self._path(to_agent).open("a", encoding="utf-8") as handle:
handle.write(json.dumps(msg, ensure_ascii=True) + "\n")
self._changed.notify_all()
print(f" [bus] {from_agent} -> {to_agent}: "
f"({msg_type}) {content[:50]}")
def read_inbox(self, agent: str) -> list[dict]:
with self._lock:
return self._read_unlocked(agent)
def peek(self, agent: str) -> bool:
with self._lock:
inbox = self._path(agent)
return inbox.exists() and inbox.stat().st_size > 0
def wait_for_messages(self, agent: str,
timeout: float | None = None) -> list[dict]:
"""Block until the agent has messages or timeout expires."""
deadline = None if timeout is None else time.monotonic() + timeout
with self._changed:
while not self.peek(agent):
remaining = (None if deadline is None
else deadline - time.monotonic())
if remaining is not None and remaining <= 0:
return []
self._changed.wait(remaining)
return self._read_unlocked(agent)
BUS = MessageBus()
# working | waiting_approval | idle | stopping
active_teammates: dict[str, str] = {}
plan_gates: dict[str, str] = {}
plan_request_ids: dict[str, str] = {}
team_lock = threading.RLock()
@dataclass
class ProtocolState:
request_id: str
type: str
sender: str
target: str
status: str
payload: str
work_version: int | None = None
task_id: str | None = None
created_at: float = field(default_factory=time.time)
pending_requests: dict[str, ProtocolState] = {}
def new_request_id() -> str:
while True:
request_id = f"req_{random.randint(0, 999999):06d}"
if request_id not in pending_requests:
return request_id
def match_response(response_type: str, request_id: str, approve: bool,
from_agent: str, to_agent: str) -> bool:
"""Match one protocol response to one pending request."""
with team_lock:
state = pending_requests.get(request_id)
if not state:
print(f" [protocol] unknown request_id: {request_id}")
return False
expected = {
"shutdown": "shutdown_response",
"plan_approval": "plan_approval_response",
}[state.type]
if response_type != expected:
print(f" [protocol] expected {expected}, got {response_type}")
return False
if from_agent != state.target or to_agent != state.sender:
print(f" [protocol] {request_id} responder mismatch")
return False
if state.status != "pending":
print(f" [protocol] {request_id} already {state.status}")
return False
state.status = "approved" if approve else "rejected"
print(f" [protocol] {request_id} -> {state.status}")
return True
def consume_lead_inbox() -> list[dict]:
"""Consume Lead events and update protocol state before model delivery."""
msgs = BUS.read_inbox("lead")
for msg in msgs:
metadata = msg.get("metadata", {})
request_id = metadata.get("request_id", "")
if request_id and msg.get("type", "").endswith("_response"):
match_response(msg["type"], request_id,
metadata.get("approve", False),
msg.get("from", ""), msg.get("to", ""))
return msgs
def format_team_events(msgs: list[dict]) -> str:
lines = []
for msg in msgs:
metadata = msg.get("metadata", {})
request_id = metadata.get("request_id")
suffix = f" request_id={request_id}" if request_id else ""
lines.append(
f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}"
)
return "[Team events]\n" + "\n".join(lines)
def _last_assistant_text(content) -> str:
for block in content:
if getattr(block, "type", None) == "text":
return block.text.strip()
if isinstance(block, dict) and block.get("type") == "text":
return str(block.get("text", "")).strip()
return ""
def current_work_identity(owner: str) -> tuple[int, str | None]:
with task_lock:
assignment = teammate_assignments.get(owner)