Back to Team Protocols
Agent Teams → Team Protocols
s09 (348 LOC) → s10 (419 LOC)
LOC Delta
+71lines
New Tools
3
shutdown_responseplan_approvalshutdown_request
New Classes
0
New Functions
3
handle_shutdown_requesthandle_plan_review_check_shutdown_status
Agent Teams
Teammates + Mailboxes
348 LOC
9 tools: bash, read_file, write_file, edit_file, send_message, read_inbox, spawn_teammate, list_teammates, broadcast
collaborationTeam Protocols
Shared Communication Rules
419 LOC
12 tools: bash, read_file, write_file, edit_file, send_message, read_inbox, shutdown_response, plan_approval, spawn_teammate, list_teammates, broadcast, shutdown_request
collaborationSource Code Diff
s09 (s09_agent_teams.py) -> s10 (s10_team_protocols.py)
| 1 | 1 | #!/usr/bin/env python3 | |
| 2 | - | # Harness: team mailboxes -- multiple models, coordinated through files. | |
| 2 | + | # Harness: protocols -- structured handshakes between models. | |
| 3 | 3 | """ | |
| 4 | - | s09_agent_teams.py - Agent Teams | |
| 4 | + | s10_team_protocols.py - Team Protocols | |
| 5 | 5 | ||
| 6 | - | Persistent named agents with file-based JSONL inboxes. Each teammate runs | |
| 7 | - | its own agent loop in a separate thread. Communication via append-only inboxes. | |
| 6 | + | Shutdown protocol and plan approval protocol, both using the same | |
| 7 | + | request_id correlation pattern. Builds on s09's team messaging. | |
| 8 | 8 | ||
| 9 | - | Subagent (s04): spawn -> execute -> return summary -> destroyed | |
| 10 | - | Teammate (s09): spawn -> work -> idle -> work -> ... -> shutdown | |
| 9 | + | Shutdown FSM: pending -> approved | rejected | |
| 11 | 10 | ||
| 12 | - | .team/config.json .team/inbox/ | |
| 13 | - | +----------------------------+ +------------------+ | |
| 14 | - | | {"team_name": "default", | | alice.jsonl | | |
| 15 | - | | "members": [ | | bob.jsonl | | |
| 16 | - | | {"name":"alice", | | lead.jsonl | | |
| 17 | - | | "role":"coder", | +------------------+ | |
| 18 | - | | "status":"idle"} | | |
| 19 | - | | ]} | send_message("alice", "fix bug"): | |
| 20 | - | +----------------------------+ open("alice.jsonl", "a").write(msg) | |
| 11 | + | Lead Teammate | |
| 12 | + | +---------------------+ +---------------------+ | |
| 13 | + | | shutdown_request | | | | |
| 14 | + | | { | -------> | receives request | | |
| 15 | + | | request_id: abc | | decides: approve? | | |
| 16 | + | | } | | | | |
| 17 | + | +---------------------+ +---------------------+ | |
| 18 | + | | | |
| 19 | + | +---------------------+ +-------v-------------+ | |
| 20 | + | | shutdown_response | <------- | shutdown_response | | |
| 21 | + | | { | | { | | |
| 22 | + | | request_id: abc | | request_id: abc | | |
| 23 | + | | approve: true | | approve: true | | |
| 24 | + | | } | | } | | |
| 25 | + | +---------------------+ +---------------------+ | |
| 26 | + | | | |
| 27 | + | v | |
| 28 | + | status -> "shutdown", thread stops | |
| 21 | 29 | ||
| 22 | - | read_inbox("alice"): | |
| 23 | - | spawn_teammate("alice","coder",...) msgs = [json.loads(l) for l in ...] | |
| 24 | - | | open("alice.jsonl", "w").close() | |
| 25 | - | v return msgs # drain | |
| 26 | - | Thread: alice Thread: bob | |
| 27 | - | +------------------+ +------------------+ | |
| 28 | - | | agent_loop | | agent_loop | | |
| 29 | - | | status: working | | status: idle | | |
| 30 | - | | ... runs tools | | ... waits ... | | |
| 31 | - | | status -> idle | | | | |
| 32 | - | +------------------+ +------------------+ | |
| 30 | + | Plan approval FSM: pending -> approved | rejected | |
| 33 | 31 | ||
| 34 | - | 5 message types (all declared, not all handled here): | |
| 35 | - | +-------------------------+-----------------------------------+ | |
| 36 | - | | message | Normal text message | | |
| 37 | - | | broadcast | Sent to all teammates | | |
| 38 | - | | shutdown_request | Request graceful shutdown (s10) | | |
| 39 | - | | shutdown_response | Approve/reject shutdown (s10) | | |
| 40 | - | | plan_approval_response | Approve/reject plan (s10) | | |
| 41 | - | +-------------------------+-----------------------------------+ | |
| 32 | + | Teammate Lead | |
| 33 | + | +---------------------+ +---------------------+ | |
| 34 | + | | plan_approval | | | | |
| 35 | + | | submit: {plan:"..."}| -------> | reviews plan text | | |
| 36 | + | +---------------------+ | approve/reject? | | |
| 37 | + | +---------------------+ | |
| 38 | + | | | |
| 39 | + | +---------------------+ +-------v-------------+ | |
| 40 | + | | plan_approval_resp | <------- | plan_approval | | |
| 41 | + | | {approve: true} | | review: {req_id, | | |
| 42 | + | +---------------------+ | approve: true} | | |
| 43 | + | +---------------------+ | |
| 42 | 44 | ||
| 43 | - | Key insight: "Teammates that can talk to each other." | |
| 45 | + | Trackers: {request_id: {"target|from": name, "status": "pending|..."}} | |
| 46 | + | ||
| 47 | + | Key insight: "Same request_id correlation pattern, two domains." | |
| 44 | 48 | """ | |
| 45 | 49 | ||
| 46 | 50 | import json | |
| 47 | 51 | import os | |
| 48 | 52 | import subprocess | |
| 49 | 53 | import threading | |
| 50 | 54 | import time | |
| 55 | + | import uuid | |
| 51 | 56 | from pathlib import Path | |
| 52 | 57 | ||
| 53 | 58 | from anthropic import Anthropic | |
| 54 | 59 | from dotenv import load_dotenv | |
| 55 | 60 | ||
| 56 | 61 | load_dotenv(override=True) | |
| 57 | 62 | if os.getenv("ANTHROPIC_BASE_URL"): | |
| 58 | 63 | os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) | |
| 59 | 64 | ||
| 60 | 65 | WORKDIR = Path.cwd() | |
| 61 | 66 | client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) | |
| 62 | 67 | MODEL = os.environ["MODEL_ID"] | |
| 63 | 68 | TEAM_DIR = WORKDIR / ".team" | |
| 64 | 69 | INBOX_DIR = TEAM_DIR / "inbox" | |
| 65 | 70 | ||
| 66 | - | SYSTEM = f"You are a team lead at {WORKDIR}. Spawn teammates and communicate via inboxes." | |
| 71 | + | SYSTEM = f"You are a team lead at {WORKDIR}. Manage teammates with shutdown and plan approval protocols." | |
| 67 | 72 | ||
| 68 | 73 | VALID_MSG_TYPES = { | |
| 69 | 74 | "message", | |
| 70 | 75 | "broadcast", | |
| 71 | 76 | "shutdown_request", | |
| 72 | 77 | "shutdown_response", | |
| 73 | 78 | "plan_approval_response", | |
| 74 | 79 | } | |
| 75 | 80 | ||
| 81 | + | # -- Request trackers: correlate by request_id -- | |
| 82 | + | shutdown_requests = {} | |
| 83 | + | plan_requests = {} | |
| 84 | + | _tracker_lock = threading.Lock() | |
| 76 | 85 | ||
| 86 | + | ||
| 77 | 87 | # -- MessageBus: JSONL inbox per teammate -- | |
| 78 | 88 | class MessageBus: | |
| 79 | 89 | def __init__(self, inbox_dir: Path): | |
| 80 | 90 | self.dir = inbox_dir | |
| 81 | 91 | self.dir.mkdir(parents=True, exist_ok=True) | |
| 82 | 92 | ||
| 83 | 93 | def send(self, sender: str, to: str, content: str, | |
| 84 | 94 | msg_type: str = "message", extra: dict = None) -> str: | |
| 85 | 95 | if msg_type not in VALID_MSG_TYPES: | |
| 86 | 96 | return f"Error: Invalid type '{msg_type}'. Valid: {VALID_MSG_TYPES}" | |
| 87 | 97 | msg = { | |
| 88 | 98 | "type": msg_type, | |
| 89 | 99 | "from": sender, | |
| 90 | 100 | "content": content, | |
| 91 | 101 | "timestamp": time.time(), | |
| 92 | 102 | } | |
| 93 | 103 | if extra: | |
| 94 | 104 | msg.update(extra) | |
| 95 | 105 | inbox_path = self.dir / f"{to}.jsonl" | |
| 96 | 106 | with open(inbox_path, "a") as f: | |
| 97 | 107 | f.write(json.dumps(msg) + "\n") | |
| 98 | 108 | return f"Sent {msg_type} to {to}" | |
| 99 | 109 | ||
| 100 | 110 | def read_inbox(self, name: str) -> list: | |
| 101 | 111 | inbox_path = self.dir / f"{name}.jsonl" | |
| 102 | 112 | if not inbox_path.exists(): | |
| 103 | 113 | return [] | |
| 104 | 114 | messages = [] | |
| 105 | 115 | for line in inbox_path.read_text().strip().splitlines(): | |
| 106 | 116 | if line: | |
| 107 | 117 | messages.append(json.loads(line)) | |
| 108 | 118 | inbox_path.write_text("") | |
| 109 | 119 | return messages | |
| 110 | 120 | ||
| 111 | 121 | def broadcast(self, sender: str, content: str, teammates: list) -> str: | |
| 112 | 122 | count = 0 | |
| 113 | 123 | for name in teammates: | |
| 114 | 124 | if name != sender: | |
| 115 | 125 | self.send(sender, name, content, "broadcast") | |
| 116 | 126 | count += 1 | |
| 117 | 127 | return f"Broadcast to {count} teammates" | |
| 118 | 128 | ||
| 119 | 129 | ||
| 120 | 130 | BUS = MessageBus(INBOX_DIR) | |
| 121 | 131 | ||
| 122 | 132 | ||
| 123 | - | # -- TeammateManager: persistent named agents with config.json -- | |
| 133 | + | # -- TeammateManager with shutdown + plan approval -- | |
| 124 | 134 | class TeammateManager: | |
| 125 | 135 | def __init__(self, team_dir: Path): | |
| 126 | 136 | self.dir = team_dir | |
| 127 | 137 | self.dir.mkdir(exist_ok=True) | |
| 128 | 138 | self.config_path = self.dir / "config.json" | |
| 129 | 139 | self.config = self._load_config() | |
| 130 | 140 | self.threads = {} | |
| 131 | 141 | ||
| 132 | 142 | def _load_config(self) -> dict: | |
| 133 | 143 | if self.config_path.exists(): | |
| 134 | 144 | return json.loads(self.config_path.read_text()) | |
| 135 | 145 | return {"team_name": "default", "members": []} | |
| 136 | 146 | ||
| 137 | 147 | def _save_config(self): | |
| 138 | 148 | self.config_path.write_text(json.dumps(self.config, indent=2)) | |
| 139 | 149 | ||
| 140 | 150 | def _find_member(self, name: str) -> dict: | |
| 141 | 151 | for m in self.config["members"]: | |
| 142 | 152 | if m["name"] == name: | |
| 143 | 153 | return m | |
| 144 | 154 | return None | |
| 145 | 155 | ||
| 146 | 156 | def spawn(self, name: str, role: str, prompt: str) -> str: | |
| 147 | 157 | member = self._find_member(name) | |
| 148 | 158 | if member: | |
| 149 | 159 | if member["status"] not in ("idle", "shutdown"): | |
| 150 | 160 | return f"Error: '{name}' is currently {member['status']}" | |
| 151 | 161 | member["status"] = "working" | |
| 152 | 162 | member["role"] = role | |
| 153 | 163 | else: | |
| 154 | 164 | member = {"name": name, "role": role, "status": "working"} | |
| 155 | 165 | self.config["members"].append(member) | |
| 156 | 166 | self._save_config() | |
| 157 | 167 | thread = threading.Thread( | |
| 158 | 168 | target=self._teammate_loop, | |
| 159 | 169 | args=(name, role, prompt), | |
| 160 | 170 | daemon=True, | |
| 161 | 171 | ) | |
| 162 | 172 | self.threads[name] = thread | |
| 163 | 173 | thread.start() | |
| 164 | 174 | return f"Spawned '{name}' (role: {role})" | |
| 165 | 175 | ||
| 166 | 176 | def _teammate_loop(self, name: str, role: str, prompt: str): | |
| 167 | 177 | sys_prompt = ( | |
| 168 | 178 | f"You are '{name}', role: {role}, at {WORKDIR}. " | |
| 169 | - | f"Use send_message to communicate. Complete your task." | |
| 179 | + | f"Submit plans via plan_approval before major work. " | |
| 180 | + | f"Respond to shutdown_request with shutdown_response." | |
| 170 | 181 | ) | |
| 171 | 182 | messages = [{"role": "user", "content": prompt}] | |
| 172 | 183 | tools = self._teammate_tools() | |
| 184 | + | should_exit = False | |
| 173 | 185 | for _ in range(50): | |
| 174 | 186 | inbox = BUS.read_inbox(name) | |
| 175 | 187 | for msg in inbox: | |
| 176 | 188 | messages.append({"role": "user", "content": json.dumps(msg)}) | |
| 189 | + | if should_exit: | |
| 190 | + | break | |
| 177 | 191 | try: | |
| 178 | 192 | response = client.messages.create( | |
| 179 | 193 | model=MODEL, | |
| 180 | 194 | system=sys_prompt, | |
| 181 | 195 | messages=messages, | |
| 182 | 196 | tools=tools, | |
| 183 | 197 | max_tokens=8000, | |
| 184 | 198 | ) | |
| 185 | 199 | except Exception: | |
| 186 | 200 | break | |
| 187 | 201 | messages.append({"role": "assistant", "content": response.content}) | |
| 188 | 202 | if response.stop_reason != "tool_use": | |
| 189 | 203 | break | |
| 190 | 204 | results = [] | |
| 191 | 205 | for block in response.content: | |
| 192 | 206 | if block.type == "tool_use": | |
| 193 | 207 | output = self._exec(name, block.name, block.input) | |
| 194 | 208 | print(f" [{name}] {block.name}: {str(output)[:120]}") | |
| 195 | 209 | results.append({ | |
| 196 | 210 | "type": "tool_result", | |
| 197 | 211 | "tool_use_id": block.id, | |
| 198 | 212 | "content": str(output), | |
| 199 | 213 | }) | |
| 214 | + | if block.name == "shutdown_response" and block.input.get("approve"): | |
| 215 | + | should_exit = True | |
| 200 | 216 | messages.append({"role": "user", "content": results}) | |
| 201 | 217 | member = self._find_member(name) | |
| 202 | - | if member and member["status"] != "shutdown": | |
| 203 | - | member["status"] = "idle" | |
| 218 | + | if member: | |
| 219 | + | member["status"] = "shutdown" if should_exit else "idle" | |
| 204 | 220 | self._save_config() | |
| 205 | 221 | ||
| 206 | 222 | def _exec(self, sender: str, tool_name: str, args: dict) -> str: | |
| 207 | 223 | # these base tools are unchanged from s02 | |
| 208 | 224 | if tool_name == "bash": | |
| 209 | 225 | return _run_bash(args["command"]) | |
| 210 | 226 | if tool_name == "read_file": | |
| 211 | 227 | return _run_read(args["path"]) | |
| 212 | 228 | if tool_name == "write_file": | |
| 213 | 229 | return _run_write(args["path"], args["content"]) | |
| 214 | 230 | if tool_name == "edit_file": | |
| 215 | 231 | return _run_edit(args["path"], args["old_text"], args["new_text"]) | |
| 216 | 232 | if tool_name == "send_message": | |
| 217 | 233 | return BUS.send(sender, args["to"], args["content"], args.get("msg_type", "message")) | |
| 218 | 234 | if tool_name == "read_inbox": | |
| 219 | 235 | return json.dumps(BUS.read_inbox(sender), indent=2) | |
| 236 | + | if tool_name == "shutdown_response": | |
| 237 | + | req_id = args["request_id"] | |
| 238 | + | approve = args["approve"] | |
| 239 | + | with _tracker_lock: | |
| 240 | + | if req_id in shutdown_requests: | |
| 241 | + | shutdown_requests[req_id]["status"] = "approved" if approve else "rejected" | |
| 242 | + | BUS.send( | |
| 243 | + | sender, "lead", args.get("reason", ""), | |
| 244 | + | "shutdown_response", {"request_id": req_id, "approve": approve}, | |
| 245 | + | ) | |
| 246 | + | return f"Shutdown {'approved' if approve else 'rejected'}" | |
| 247 | + | if tool_name == "plan_approval": | |
| 248 | + | plan_text = args.get("plan", "") | |
| 249 | + | req_id = str(uuid.uuid4())[:8] | |
| 250 | + | with _tracker_lock: | |
| 251 | + | plan_requests[req_id] = {"from": sender, "plan": plan_text, "status": "pending"} | |
| 252 | + | BUS.send( | |
| 253 | + | sender, "lead", plan_text, "plan_approval_response", | |
| 254 | + | {"request_id": req_id, "plan": plan_text}, | |
| 255 | + | ) | |
| 256 | + | return f"Plan submitted (request_id={req_id}). Waiting for lead approval." | |
| 220 | 257 | return f"Unknown tool: {tool_name}" | |
| 221 | 258 | ||
| 222 | 259 | def _teammate_tools(self) -> list: | |
| 223 | 260 | # these base tools are unchanged from s02 | |
| 224 | 261 | return [ | |
| 225 | 262 | {"name": "bash", "description": "Run a shell command.", | |
| 226 | 263 | "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}, | |
| 227 | 264 | {"name": "read_file", "description": "Read file contents.", | |
| 228 | 265 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}, | |
| 229 | 266 | {"name": "write_file", "description": "Write content to file.", | |
| 230 | 267 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}, | |
| 231 | 268 | {"name": "edit_file", "description": "Replace exact text in file.", | |
| 232 | 269 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}}, | |
| 233 | 270 | {"name": "send_message", "description": "Send message to a teammate.", | |
| 234 | 271 | "input_schema": {"type": "object", "properties": {"to": {"type": "string"}, "content": {"type": "string"}, "msg_type": {"type": "string", "enum": list(VALID_MSG_TYPES)}}, "required": ["to", "content"]}}, | |
| 235 | 272 | {"name": "read_inbox", "description": "Read and drain your inbox.", | |
| 236 | 273 | "input_schema": {"type": "object", "properties": {}}}, | |
| 274 | + | {"name": "shutdown_response", "description": "Respond to a shutdown request. Approve to shut down, reject to keep working.", | |
| 275 | + | "input_schema": {"type": "object", "properties": {"request_id": {"type": "string"}, "approve": {"type": "boolean"}, "reason": {"type": "string"}}, "required": ["request_id", "approve"]}}, | |
| 276 | + | {"name": "plan_approval", "description": "Submit a plan for lead approval. Provide plan text.", | |
| 277 | + | "input_schema": {"type": "object", "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, | |
| 237 | 278 | ] | |
| 238 | 279 | ||
| 239 | 280 | def list_all(self) -> str: | |
| 240 | 281 | if not self.config["members"]: | |
| 241 | 282 | return "No teammates." | |
| 242 | 283 | lines = [f"Team: {self.config['team_name']}"] | |
| 243 | 284 | for m in self.config["members"]: | |
| 244 | 285 | lines.append(f" {m['name']} ({m['role']}): {m['status']}") | |
| 245 | 286 | return "\n".join(lines) | |
| 246 | 287 | ||
| 247 | 288 | def member_names(self) -> list: | |
| 248 | 289 | return [m["name"] for m in self.config["members"]] | |
| 249 | 290 | ||
| 250 | 291 | ||
| 251 | 292 | TEAM = TeammateManager(TEAM_DIR) | |
| 252 | 293 | ||
| 253 | 294 | ||
| 254 | 295 | # -- Base tool implementations (these base tools are unchanged from s02) -- | |
| 255 | 296 | def _safe_path(p: str) -> Path: | |
| 256 | 297 | path = (WORKDIR / p).resolve() | |
| 257 | 298 | if not path.is_relative_to(WORKDIR): | |
| 258 | 299 | raise ValueError(f"Path escapes workspace: {p}") | |
| 259 | 300 | return path | |
| 260 | 301 | ||
| 261 | 302 | ||
| 262 | 303 | def _run_bash(command: str) -> str: | |
| 263 | 304 | dangerous = ["rm -rf /", "sudo", "shutdown", "reboot"] | |
| 264 | 305 | if any(d in command for d in dangerous): | |
| 265 | 306 | return "Error: Dangerous command blocked" | |
| 266 | 307 | try: | |
| 267 | 308 | r = subprocess.run( | |
| 268 | 309 | command, shell=True, cwd=WORKDIR, | |
| 269 | 310 | capture_output=True, text=True, timeout=120, | |
| 270 | 311 | ) | |
| 271 | 312 | out = (r.stdout + r.stderr).strip() | |
| 272 | 313 | return out[:50000] if out else "(no output)" | |
| 273 | 314 | except subprocess.TimeoutExpired: | |
| 274 | 315 | return "Error: Timeout (120s)" | |
| 275 | 316 | ||
| 276 | 317 | ||
| 277 | 318 | def _run_read(path: str, limit: int = None) -> str: | |
| 278 | 319 | try: | |
| 279 | 320 | lines = _safe_path(path).read_text().splitlines() | |
| 280 | 321 | if limit and limit < len(lines): | |
| 281 | 322 | lines = lines[:limit] + [f"... ({len(lines) - limit} more)"] | |
| 282 | 323 | return "\n".join(lines)[:50000] | |
| 283 | 324 | except Exception as e: | |
| 284 | 325 | return f"Error: {e}" | |
| 285 | 326 | ||
| 286 | 327 | ||
| 287 | 328 | def _run_write(path: str, content: str) -> str: | |
| 288 | 329 | try: | |
| 289 | 330 | fp = _safe_path(path) | |
| 290 | 331 | fp.parent.mkdir(parents=True, exist_ok=True) | |
| 291 | 332 | fp.write_text(content) | |
| 292 | 333 | return f"Wrote {len(content)} bytes" | |
| 293 | 334 | except Exception as e: | |
| 294 | 335 | return f"Error: {e}" | |
| 295 | 336 | ||
| 296 | 337 | ||
| 297 | 338 | def _run_edit(path: str, old_text: str, new_text: str) -> str: | |
| 298 | 339 | try: | |
| 299 | 340 | fp = _safe_path(path) | |
| 300 | 341 | c = fp.read_text() | |
| 301 | 342 | if old_text not in c: | |
| 302 | 343 | return f"Error: Text not found in {path}" | |
| 303 | 344 | fp.write_text(c.replace(old_text, new_text, 1)) | |
| 304 | 345 | return f"Edited {path}" | |
| 305 | 346 | except Exception as e: | |
| 306 | 347 | return f"Error: {e}" | |
| 307 | 348 | ||
| 308 | 349 | ||
| 309 | - | # -- Lead tool dispatch (9 tools) -- | |
| 350 | + | # -- Lead-specific protocol handlers -- | |
| 351 | + | def handle_shutdown_request(teammate: str) -> str: | |
| 352 | + | req_id = str(uuid.uuid4())[:8] | |
| 353 | + | with _tracker_lock: | |
| 354 | + | shutdown_requests[req_id] = {"target": teammate, "status": "pending"} | |
| 355 | + | BUS.send( | |
| 356 | + | "lead", teammate, "Please shut down gracefully.", | |
| 357 | + | "shutdown_request", {"request_id": req_id}, | |
| 358 | + | ) | |
| 359 | + | return f"Shutdown request {req_id} sent to '{teammate}' (status: pending)" | |
| 360 | + | ||
| 361 | + | ||
| 362 | + | def handle_plan_review(request_id: str, approve: bool, feedback: str = "") -> str: | |
| 363 | + | with _tracker_lock: | |
| 364 | + | req = plan_requests.get(request_id) | |
| 365 | + | if not req: | |
| 366 | + | return f"Error: Unknown plan request_id '{request_id}'" | |
| 367 | + | with _tracker_lock: | |
| 368 | + | req["status"] = "approved" if approve else "rejected" | |
| 369 | + | BUS.send( | |
| 370 | + | "lead", req["from"], feedback, "plan_approval_response", | |
| 371 | + | {"request_id": request_id, "approve": approve, "feedback": feedback}, | |
| 372 | + | ) | |
| 373 | + | return f"Plan {req['status']} for '{req['from']}'" | |
| 374 | + | ||
| 375 | + | ||
| 376 | + | def _check_shutdown_status(request_id: str) -> str: | |
| 377 | + | with _tracker_lock: | |
| 378 | + | return json.dumps(shutdown_requests.get(request_id, {"error": "not found"})) | |
| 379 | + | ||
| 380 | + | ||
| 381 | + | # -- Lead tool dispatch (12 tools) -- | |
| 310 | 382 | TOOL_HANDLERS = { | |
| 311 | - | "bash": lambda **kw: _run_bash(kw["command"]), | |
| 312 | - | "read_file": lambda **kw: _run_read(kw["path"], kw.get("limit")), | |
| 313 | - | "write_file": lambda **kw: _run_write(kw["path"], kw["content"]), | |
| 314 | - | "edit_file": lambda **kw: _run_edit(kw["path"], kw["old_text"], kw["new_text"]), | |
| 315 | - | "spawn_teammate": lambda **kw: TEAM.spawn(kw["name"], kw["role"], kw["prompt"]), | |
| 316 | - | "list_teammates": lambda **kw: TEAM.list_all(), | |
| 317 | - | "send_message": lambda **kw: BUS.send("lead", kw["to"], kw["content"], kw.get("msg_type", "message")), | |
| 318 | - | "read_inbox": lambda **kw: json.dumps(BUS.read_inbox("lead"), indent=2), | |
| 319 | - | "broadcast": lambda **kw: BUS.broadcast("lead", kw["content"], TEAM.member_names()), | |
| 383 | + | "bash": lambda **kw: _run_bash(kw["command"]), | |
| 384 | + | "read_file": lambda **kw: _run_read(kw["path"], kw.get("limit")), | |
| 385 | + | "write_file": lambda **kw: _run_write(kw["path"], kw["content"]), | |
| 386 | + | "edit_file": lambda **kw: _run_edit(kw["path"], kw["old_text"], kw["new_text"]), | |
| 387 | + | "spawn_teammate": lambda **kw: TEAM.spawn(kw["name"], kw["role"], kw["prompt"]), | |
| 388 | + | "list_teammates": lambda **kw: TEAM.list_all(), | |
| 389 | + | "send_message": lambda **kw: BUS.send("lead", kw["to"], kw["content"], kw.get("msg_type", "message")), | |
| 390 | + | "read_inbox": lambda **kw: json.dumps(BUS.read_inbox("lead"), indent=2), | |
| 391 | + | "broadcast": lambda **kw: BUS.broadcast("lead", kw["content"], TEAM.member_names()), | |
| 392 | + | "shutdown_request": lambda **kw: handle_shutdown_request(kw["teammate"]), | |
| 393 | + | "shutdown_response": lambda **kw: _check_shutdown_status(kw.get("request_id", "")), | |
| 394 | + | "plan_approval": lambda **kw: handle_plan_review(kw["request_id"], kw["approve"], kw.get("feedback", "")), | |
| 320 | 395 | } | |
| 321 | 396 | ||
| 322 | 397 | # these base tools are unchanged from s02 | |
| 323 | 398 | TOOLS = [ | |
| 324 | 399 | {"name": "bash", "description": "Run a shell command.", | |
| 325 | 400 | "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}, | |
| 326 | 401 | {"name": "read_file", "description": "Read file contents.", | |
| 327 | 402 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}}, | |
| 328 | 403 | {"name": "write_file", "description": "Write content to file.", | |
| 329 | 404 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}, | |
| 330 | 405 | {"name": "edit_file", "description": "Replace exact text in file.", | |
| 331 | 406 | "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}}, | |
| 332 | - | {"name": "spawn_teammate", "description": "Spawn a persistent teammate that runs in its own thread.", | |
| 407 | + | {"name": "spawn_teammate", "description": "Spawn a persistent teammate.", | |
| 333 | 408 | "input_schema": {"type": "object", "properties": {"name": {"type": "string"}, "role": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["name", "role", "prompt"]}}, | |
| 334 | - | {"name": "list_teammates", "description": "List all teammates with name, role, status.", | |
| 409 | + | {"name": "list_teammates", "description": "List all teammates.", | |
| 335 | 410 | "input_schema": {"type": "object", "properties": {}}}, | |
| 336 | - | {"name": "send_message", "description": "Send a message to a teammate's inbox.", | |
| 411 | + | {"name": "send_message", "description": "Send a message to a teammate.", | |
| 337 | 412 | "input_schema": {"type": "object", "properties": {"to": {"type": "string"}, "content": {"type": "string"}, "msg_type": {"type": "string", "enum": list(VALID_MSG_TYPES)}}, "required": ["to", "content"]}}, | |
| 338 | 413 | {"name": "read_inbox", "description": "Read and drain the lead's inbox.", | |
| 339 | 414 | "input_schema": {"type": "object", "properties": {}}}, | |
| 340 | 415 | {"name": "broadcast", "description": "Send a message to all teammates.", | |
| 341 | 416 | "input_schema": {"type": "object", "properties": {"content": {"type": "string"}}, "required": ["content"]}}, | |
| 417 | + | {"name": "shutdown_request", "description": "Request a teammate to shut down gracefully. Returns a request_id for tracking.", | |
| 418 | + | "input_schema": {"type": "object", "properties": {"teammate": {"type": "string"}}, "required": ["teammate"]}}, | |
| 419 | + | {"name": "shutdown_response", "description": "Check the status of a shutdown request by request_id.", | |
| 420 | + | "input_schema": {"type": "object", "properties": {"request_id": {"type": "string"}}, "required": ["request_id"]}}, | |
| 421 | + | {"name": "plan_approval", "description": "Approve or reject a teammate's plan. Provide request_id + approve + optional feedback.", | |
| 422 | + | "input_schema": {"type": "object", "properties": {"request_id": {"type": "string"}, "approve": {"type": "boolean"}, "feedback": {"type": "string"}}, "required": ["request_id", "approve"]}}, | |
| 342 | 423 | ] | |
| 343 | 424 | ||
| 344 | 425 | ||
| 345 | 426 | def agent_loop(messages: list): | |
| 346 | 427 | while True: | |
| 347 | 428 | inbox = BUS.read_inbox("lead") | |
| 348 | 429 | if inbox: | |
| 349 | 430 | messages.append({ | |
| 350 | 431 | "role": "user", | |
| 351 | 432 | "content": f"<inbox>{json.dumps(inbox, indent=2)}</inbox>", | |
| 352 | 433 | }) | |
| 353 | 434 | messages.append({ | |
| 354 | 435 | "role": "assistant", | |
| 355 | 436 | "content": "Noted inbox messages.", | |
| 356 | 437 | }) | |
| 357 | 438 | response = client.messages.create( | |
| 358 | 439 | model=MODEL, | |
| 359 | 440 | system=SYSTEM, | |
| 360 | 441 | messages=messages, | |
| 361 | 442 | tools=TOOLS, | |
| 362 | 443 | max_tokens=8000, | |
| 363 | 444 | ) | |
| 364 | 445 | messages.append({"role": "assistant", "content": response.content}) | |
| 365 | 446 | if response.stop_reason != "tool_use": | |
| 366 | 447 | return | |
| 367 | 448 | results = [] | |
| 368 | 449 | for block in response.content: | |
| 369 | 450 | if block.type == "tool_use": | |
| 370 | 451 | handler = TOOL_HANDLERS.get(block.name) | |
| 371 | 452 | try: | |
| 372 | 453 | output = handler(**block.input) if handler else f"Unknown tool: {block.name}" | |
| 373 | 454 | except Exception as e: | |
| 374 | 455 | output = f"Error: {e}" | |
| 375 | 456 | print(f"> {block.name}: {str(output)[:200]}") | |
| 376 | 457 | results.append({ | |
| 377 | 458 | "type": "tool_result", | |
| 378 | 459 | "tool_use_id": block.id, | |
| 379 | 460 | "content": str(output), | |
| 380 | 461 | }) | |
| 381 | 462 | messages.append({"role": "user", "content": results}) | |
| 382 | 463 | ||
| 383 | 464 | ||
| 384 | 465 | if __name__ == "__main__": | |
| 385 | 466 | history = [] | |
| 386 | 467 | while True: | |
| 387 | 468 | try: | |
| 388 | - | query = input("\033[36ms09 >> \033[0m") | |
| 469 | + | query = input("\033[36ms10 >> \033[0m") | |
| 389 | 470 | except (EOFError, KeyboardInterrupt): | |
| 390 | 471 | break | |
| 391 | 472 | if query.strip().lower() in ("q", "exit", ""): | |
| 392 | 473 | break | |
| 393 | 474 | if query.strip() == "/team": | |
| 394 | 475 | print(TEAM.list_all()) | |
| 395 | 476 | continue | |
| 396 | 477 | if query.strip() == "/inbox": | |
| 397 | 478 | print(json.dumps(BUS.read_inbox("lead"), indent=2)) | |
| 398 | 479 | continue | |
| 399 | 480 | history.append({"role": "user", "content": query}) | |
| 400 | 481 | agent_loop(history) | |
| 401 | 482 | response_content = history[-1]["content"] | |
| 402 | 483 | if isinstance(response_content, list): | |
| 403 | 484 | for block in response_content: | |
| 404 | 485 | if hasattr(block, "text"): | |
| 405 | 486 | print(block.text) | |
| 406 | 487 | print() |