Repository navigation
Expand file tree
/
Copy pathstep12_hooks.py
More file actions
1762 lines (1528 loc) · 68.4 KB
/
Copy pathstep12_hooks.py
File metadata and controls
1762 lines (1528 loc) · 68.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
"""step12_hooks.py — 累积式 Agent:在 step11 MCP 基础上加入 Hooks。"""
from __future__ import annotations
import os
import asyncio
import re
import json
import subprocess
import sys
import threading
import time
import urllib.request
import yaml
import anthropic
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from html.parser import HTMLParser
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic(
api_key=os.environ["ANTHROPIC_API_KEY"],
base_url=os.environ["ANTHROPIC_BASE_URL"],
)
MODEL = os.environ["ANTHROPIC_MODEL"]
PROJECT_ROOT = Path(__file__).resolve().parents[2]
SKILLS_DIR = PROJECT_ROOT / "skills"
MEMORY_DIR = PROJECT_ROOT / "memory"
TEMPLATES_DIR = PROJECT_ROOT / "templates"
MCP_CONFIG_PATH = PROJECT_ROOT / "mcp_servers.json"
AUDIT_FILE = PROJECT_ROOT / ".hooks_audit.jsonl"
TEAM_DIR = Path(__file__).parent / ".team"
INBOX_DIR = TEAM_DIR / "inbox"
VALID_MSG_TYPES = {
"message",
"broadcast",
"shutdown_request",
"shutdown_response",
"plan_approval_response",
}
RUNTIME_STATUSES = {"idle", "working"}
TERMINAL_STATUSES = {"offline", "shutdown"}
class SkillLoader:
def __init__(self, skills_dir: Path):
self.skills_dir = skills_dir
self.skills = {}
self._load_all()
def _load_all(self):
if not self.skills_dir.exists():
return
for f in sorted(self.skills_dir.rglob("SKILL.md")):
text = f.read_text()
meta, body = self._parse_frontmatter(text)
name = meta.get("name", f.parent.name)
self.skills[name] = {"meta": meta, "body": body, "path": str(f)}
def _parse_frontmatter(self, text: str) -> tuple:
match = re.match(r"^---\n(.*?)\n---\n(.*)", text, re.DOTALL)
if not match:
return {}, text
try:
meta = yaml.safe_load(match.group(1)) or {}
except yaml.YAMLError:
meta = {}
return meta, match.group(2).strip()
def get_descriptions(self) -> str:
if not self.skills:
return "(no skills available)"
lines = []
for name, skill in self.skills.items():
desc = skill["meta"].get("description", "No description")
tags = skill["meta"].get("tags", "")
line = f" - {name}: {desc}"
if tags:
line += f" [{tags}]"
lines.append(line)
return "\n".join(lines)
def get_content(self, name: str) -> str:
skill = self.skills.get(name)
if not skill:
return f"Error: Unknown skill '{name}'. Available: {', '.join(self.skills.keys())}"
return f'<skill name="{name}">\n{skill["body"]}\n</skill>'
SKILL_LOADER = SkillLoader(SKILLS_DIR)
class MemoryStore:
def __init__(self, memory_dir: Path, templates_dir: Path):
self.memory_dir = memory_dir
self.memory_file = memory_dir / "MEMORY.md"
self.history_file = memory_dir / "history.jsonl"
self.user_file = templates_dir / "USER.md"
def ensure_files(self):
self.memory_dir.mkdir(parents=True, exist_ok=True)
self.user_file.parent.mkdir(parents=True, exist_ok=True)
if not self.memory_file.exists():
self.memory_file.write_text("# Long-term Memory\n\n", encoding="utf-8")
if not self.user_file.exists():
self.user_file.write_text("# User Profile\n\n", encoding="utf-8")
if not self.history_file.exists():
self.history_file.touch()
def append_history(self, message: dict):
self.ensure_files()
record = {
"ts": datetime.now().isoformat(timespec="seconds"),
"role": message.get("role"),
"content": _json_safe(message.get("content")),
}
with self.history_file.open("a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def read_memory(self) -> str:
self.ensure_files()
return self.memory_file.read_text(encoding="utf-8")
def read_user(self) -> str:
self.ensure_files()
return self.user_file.read_text(encoding="utf-8")
def read_today_episode(self) -> str:
self.ensure_files()
path = self.memory_dir / f"{datetime.now():%Y-%m-%d}.md"
return path.read_text(encoding="utf-8") if path.exists() else ""
MEMORY = MemoryStore(MEMORY_DIR, TEMPLATES_DIR)
def _json_safe(value):
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, list):
return [_json_safe(v) for v in value]
if isinstance(value, dict):
return {k: _json_safe(v) for k, v in value.items()}
if hasattr(value, "model_dump"):
return _json_safe(value.model_dump())
return str(value)
class _TextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self._parts = []
self._skip = False
def handle_starttag(self, tag, attrs):
if tag in ("script", "style"):
self._skip = True
def handle_endtag(self, tag):
if tag in ("script", "style"):
self._skip = False
if tag in ("p", "br", "div", "li", "tr", "h1", "h2", "h3", "h4"):
self._parts.append("\n")
def handle_data(self, data):
if not self._skip:
self._parts.append(data)
def get_text(self):
return re.sub(r"\n{3,}", "\n\n", "".join(self._parts)).strip()
def web_fetch(url: str, extract_mode: str = "text", max_chars: int = 8000) -> str:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read().decode("utf-8", errors="replace")
except Exception as e:
return f"Error fetching {url}: {e}"
if extract_mode == "text":
parser = _TextExtractor()
parser.feed(raw)
text = parser.get_text()
else:
text = raw
return text[:max_chars]
# ============== TodoList 计划与执行(沿用 s08) ==============
TODOS: list[dict] = []
VALID_STATUS = {"pending", "in_progress", "completed"}
STATUS_ICON = {"pending": "[ ]", "in_progress": "[~]", "completed": "[x]"}
def render_todos(todos: list[dict]) -> str:
if not todos:
return "(当前无待办事项)"
lines = []
for t in todos:
icon = STATUS_ICON.get(t.get("status", "pending"), "[?]")
lines.append(f" {icon} {t.get('id')}. {t.get('content', '')}")
return "\n".join(lines)
def update_todos(todos: list[dict]) -> str:
global TODOS
cleaned = []
for i, t in enumerate(todos, start=1):
content = (t.get("content") or "").strip()
if not content:
continue
status = t.get("status", "pending")
if status not in VALID_STATUS:
status = "pending"
cleaned.append({"id": t.get("id", i), "content": content, "status": status})
in_progress = [t for t in cleaned if t["status"] == "in_progress"]
if len(in_progress) > 1:
return "Error: 同一时间只能有一个 in_progress 任务,请重新规划。"
TODOS = cleaned
print("\n[计划已更新]")
print(render_todos(TODOS))
print()
pending = [t for t in TODOS if t["status"] == "pending"]
done = [t for t in TODOS if t["status"] == "completed"]
summary = f"todos updated: total={len(TODOS)}, completed={len(done)}, in_progress={len(in_progress)}, pending={len(pending)}"
return summary + "\n\n当前列表:\n" + render_todos(TODOS)
# ============== 公共工具分发:主循环与子代理共用 ==============
def execute_basic_tool(block, prefix: str = "") -> str:
"""处理基础工具,返回字符串内容。
prefix 用于在终端打印时区分主/子上下文(例如 prefix='子·')。"""
if block.name == "web_fetch":
url = block.input["url"]
mode = block.input.get("extract_mode", "text")
max_chars = block.input.get("max_chars", 8000)
print(f" [{prefix}网页获取]: {url}")
return web_fetch(url, mode, max_chars)
if block.name == "run_command":
command = block.input["command"]
print(f" [{prefix}执行命令]: {command}")
result = subprocess.run(command, shell=True, capture_output=True, text=True)
output = result.stdout or result.stderr
print(f" [{prefix}命令输出]: {output.strip()[:200]}")
return output
if block.name == "load_skill":
skill_name = block.input["skill_name"]
print(f" [{prefix}加载技能]: {skill_name}")
return SKILL_LOADER.get_content(skill_name)
if block.name == "read_file":
path = block.input["path"]
print(f" [{prefix}读取文件]: {path}")
try:
return Path(path).read_text(encoding="utf-8")
except Exception as e:
return f"Error reading {path}: {e}"
if block.name == "write_file":
path = block.input["path"]
content = block.input["content"]
print(f" [{prefix}写入文件]: {path}")
try:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
return f"写入成功: {path}"
except Exception as e:
return f"Error writing {path}: {e}"
if block.name == "glob":
pattern = block.input["pattern"]
print(f" [{prefix}文件搜索]: {pattern}")
matches = sorted(str(p) for p in Path(".").glob(pattern))
return "\n".join(matches) if matches else "(无匹配)"
if block.name == "grep":
pattern = block.input["pattern"]
path = block.input.get("path", ".")
print(f" [{prefix}内容搜索]: {pattern} in {path}")
result = subprocess.run(
["grep", "-r", "--include=*.py", "--include=*.md", "-n", pattern, path],
capture_output=True, text=True
)
return result.stdout or "(无匹配)"
return f"Error: Unknown tool '{block.name}'"
_TOOL_SCHEMAS: dict[str, dict] = {
"run_command": {
"name": "run_command",
"description": "在终端执行一条命令并返回输出。创建或覆盖文件必须调用 write_file。",
"input_schema": {
"type": "object",
"properties": {"command": {"type": "string", "description": "要执行的 shell 命令"}},
"required": ["command"]
}
},
"web_fetch": {
"name": "web_fetch",
"description": "获取指定 URL 的网页内容,支持文本提取模式",
"input_schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "要访问的完整 URL"},
"extract_mode": {"type": "string", "description": "提取模式:text(纯文本,默认)或 raw(原始 HTML)"},
"max_chars": {"type": "integer", "description": "最大返回字符数,默认 8000"}
},
"required": ["url"]
}
},
"load_skill": {
"name": "load_skill",
"description": "加载指定技能的详细知识内容,在回答相关问题前调用",
"input_schema": {
"type": "object",
"properties": {
"skill_name": {"type": "string", "description": "技能名称,必须是系统提示中列出的可用技能之一"}
},
"required": ["skill_name"]
}
},
"read_file": {
"name": "read_file",
"description": "读取本地文件内容",
"input_schema": {
"type": "object",
"properties": {"path": {"type": "string", "description": "文件路径"}},
"required": ["path"]
}
},
"write_file": {
"name": "write_file",
"description": "写入文件内容(覆盖)。创建或覆盖文件必须调用这个工具。",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"}
},
"required": ["path", "content"]
}
},
"glob": {
"name": "glob",
"description": "按 glob 模式搜索工作区文件",
"input_schema": {
"type": "object",
"properties": {"pattern": {"type": "string"}},
"required": ["pattern"]
}
},
"grep": {
"name": "grep",
"description": "在工作区文件中搜索文本内容",
"input_schema": {
"type": "object",
"properties": {
"pattern": {"type": "string"},
"path": {"type": "string"}
},
"required": ["pattern"]
}
},
}
# ============== MCP:外部工具协议(沿用 step10 后新增) ==============
def _mcp_tool_name(server_name: str, mcp_name: str) -> str:
"""把 MCP 原始工具名转换成 Anthropic 可用的 tool name。"""
sanitized = re.sub(r"[^a-zA-Z0-9_-]", "_", mcp_name)
return f"mcp_{server_name}_{sanitized}"
def _result_to_text(result) -> str:
"""把 MCP CallToolResult 压平成普通文本,方便塞回 tool_result。"""
parts = []
for block in result.content:
data = block.model_dump() if hasattr(block, "model_dump") else dict(block)
if data.get("type") == "text":
parts.append(data.get("text", ""))
else:
parts.append(json.dumps(data, ensure_ascii=False))
return "\n".join(parts) if parts else "(empty MCP result)"
class MCPClient:
"""教学版同步 MCP 客户端:每次调用临时启动一次 stdio 会话。"""
def __init__(self, name: str, params: StdioServerParameters):
self.name = name
self.params = params
self._tools: list | None = None
async def _alist_tools(self) -> list:
async with stdio_client(self.params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.list_tools()
return list(result.tools)
async def _acall_tool(self, name: str, arguments: dict[str, Any] | None) -> str:
async with stdio_client(self.params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool(name, arguments or {})
return _result_to_text(result)
def list_tools(self) -> list:
if self._tools is None:
self._tools = asyncio.run(self._alist_tools())
return list(self._tools)
def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> str:
return asyncio.run(self._acall_tool(name, arguments))
def stop(self) -> None:
pass
class MCPConfig:
"""读取项目根目录 mcp_servers.json。"""
def __init__(self, path: Path):
self.path = path
self.servers: dict[str, dict[str, Any]] = {}
if path.exists():
data = json.loads(path.read_text(encoding="utf-8"))
self.servers = data.get("servers", {})
def get_params(self, name: str) -> StdioServerParameters | None:
cfg = self.servers.get(name, {})
if not cfg.get("enabled", True):
return None
command = cfg.get("command")
if not command:
return None
args = cfg.get("args", [])
env = cfg.get("env")
if env:
env = {**os.environ, **env}
return StdioServerParameters(command=command, args=args, env=env)
def load_mcp_clients(registry: dict, config_path: Path) -> dict[str, MCPClient]:
"""根据配置连接 MCP Server,并把外部工具注册进动态工具表。"""
config = MCPConfig(config_path)
clients: dict[str, MCPClient] = {}
for name in sorted(config.servers.keys()):
params = config.get_params(name)
if params is None:
continue
try:
mcp_client = MCPClient(name, params)
tools = mcp_client.list_tools()
for tool in tools:
tool_name = _mcp_tool_name(name, tool.name)
registry[tool_name] = (mcp_client, tool)
clients[name] = mcp_client
print(f"[MCP] 已连接 '{name}',提供 {len(tools)} 个工具")
except Exception as exc:
print(f"[warning] MCP server '{name}' 启动失败:{exc}")
return clients
MCP_CLIENTS: dict[str, MCPClient] = {}
MCP_TOOL_MAP: dict[str, tuple[MCPClient, Any]] = {}
def list_mcp_servers(server: str | None = None) -> str:
names = [server] if server else sorted(MCP_CLIENTS.keys())
if not names:
return "当前没有连接任何 MCP Server。"
lines = []
for name in names:
client = MCP_CLIENTS.get(name)
if client is None:
lines.append(f"## {name}\n未连接。")
continue
try:
tools = client.list_tools()
except Exception as exc:
lines.append(f"## {name}\n拉取工具列表失败:{exc}")
continue
lines.append(f"## {name}")
for tool in tools:
registry_name = _mcp_tool_name(name, tool.name)
desc = getattr(tool, "description", None) or "(no description)"
lines.append(f"- `{registry_name}` ({tool.name}): {desc}")
return "\n".join(lines)
def build_tool_schemas(base_tools: list[dict]) -> list[dict]:
schemas = list(base_tools)
for tool_name, (mcp_client, tool) in MCP_TOOL_MAP.items():
schemas.append({
"name": tool_name,
"description": getattr(tool, "description", f"MCP tool '{tool.name}'") or f"MCP tool '{tool.name}'",
"input_schema": tool.inputSchema or {"type": "object", "properties": {}},
})
return schemas
# ============== 子代理预设身份 ==============
# 身份在 system_prompt 中定义,工具白名单在代码中控制(不放进 prompt)。
# 这里故意使用宫廷内官职位做角色名:既贴合教程人设,也让不同子代理的职责边界更好记。
def build_subagent_prompt(title: str, duty: str, boundary: str) -> str:
return (
f"你是{title},奉总管之命专办一件差事。\n"
f"- 职司:{duty}\n"
f"- 边界:{boundary}\n"
"- 不必使用\"奉天承运皇帝诏曰\"前缀,那是总管对皇上的礼数。\n"
"- 用工具尽快把差事办妥,最后用一段简短中文向总管回禀结果。\n"
"- 只回禀结论与关键信息,不要复述每一步细节。\n"
"- 你不能再派遣其他小太监,所有差事自己跑工具完成。"
)
SUBAGENT_SPECS = {
# 小黄门:宫中通传、跑腿的小内侍。适合短平快的只读探路。
"xiaohuangmen": {
"title": "通传小黄门",
"system_prompt": build_subagent_prompt(
"通传小黄门",
"传话跑腿、快速探路、确认简单事实。",
"只办轻量只读差事;若发现需要大改或长时间探索,回禀总管改派专职内官。",
),
"tools": ["run_command", "read_file", "glob", "grep"],
"max_turns": 8,
},
# 司礼监掌文书机要,这里取“随堂”做文书型子代理。
"sili_suitang": {
"title": "司礼监随堂小太监",
"system_prompt": build_subagent_prompt(
"司礼监随堂小太监",
"查阅文书、阅读代码、整理提纲、归纳结论。",
"只读不写;不得修改文件,只把文书脉络和关键判断回禀总管。",
),
"tools": ["load_skill", "read_file", "glob", "grep"],
"max_turns": 12,
},
# 东厂负责查访缉事,这里用于外部网页、搜索、探索性调查。
"dongchang_tanshi": {
"title": "东厂探事小太监",
"system_prompt": build_subagent_prompt(
"东厂探事小太监",
"外出查访、抓取网页、搜罗线索、比对资料来源。",
"只读不写;运行命令时只许做查询类操作,不得改动本地文件。",
),
"tools": ["run_command", "web_fetch", "load_skill", "read_file", "glob", "grep"],
"max_turns": 15,
},
# 尚宝监掌印信宝册,这里用于盘点、校验、对账。
"shangbao_dianbu": {
"title": "尚宝监典簿小太监",
"system_prompt": build_subagent_prompt(
"尚宝监典簿小太监",
"清点文件、核对清单、校验结果、整理表册。",
"只读不写;重点回禀差异、遗漏、风险点和可复核证据。",
),
"tools": ["run_command", "read_file", "glob", "grep"],
"max_turns": 12,
},
# 内官监掌宫中营造器用,这里用于真正动手改文件、落地实现。
"neiguan_yingzao": {
"title": "内官监营造小太监",
"system_prompt": build_subagent_prompt(
"内官监营造小太监",
"修造工程、改写文件、搭建目录、跑命令验收。",
"可读写可执行;动手前先看清现状,回禀时列出改了什么和验证结果。",
),
"tools": ["run_command", "web_fetch", "load_skill", "read_file", "write_file", "glob", "grep"],
"max_turns": 20,
},
}
SUBAGENT_TYPE_OPTIONS = list(SUBAGENT_SPECS.keys())
def resolve_subagent_type(agent_type: str) -> str:
normalized = (agent_type or "neiguan_yingzao").strip()
if normalized not in SUBAGENT_SPECS:
return "neiguan_yingzao"
return normalized
_SUBAGENT_COUNTER = 0
def run_subagent(task: str, agent_type: str = "neiguan_yingzao",
purpose: str = "", max_turns: int | None = None) -> str:
"""启动一个独立 message loop 的子代理,跑完后只返回最终文本给主 agent。
agent_type: SUBAGENT_SPECS 中的宫廷职位名。
"""
global _SUBAGENT_COUNTER
_SUBAGENT_COUNTER += 1
label = purpose or task[:40]
agent_type = resolve_subagent_type(agent_type)
spec = SUBAGENT_SPECS[agent_type]
turns = max_turns if max_turns is not None else spec["max_turns"]
tools = [_TOOL_SCHEMAS[t] for t in spec["tools"]]
print(f"\n[派遣小太监 #{_SUBAGENT_COUNTER}({spec['title']} / {agent_type})]: {label}")
print(" ┌── subagent context start ──")
messages = [{"role": "user", "content": task}]
for turn in range(turns):
msg = client.messages.create(
model=MODEL,
max_tokens=2000,
system=spec["system_prompt"],
tools=tools,
messages=messages,
)
messages.append({"role": "assistant", "content": msg.content})
if msg.stop_reason != "tool_use":
final = next((b.text for b in msg.content if b.type == "text"), "")
print(f" └── subagent context end (内部 {turn + 1} 轮,回传 {len(final)} 字) ──")
print(f"[小太监回禀]: {final}\n")
return final
results = []
for b in msg.content:
if b.type != "tool_use":
continue
content = execute_basic_tool(b, prefix=f"子({spec['title']})·")
results.append({
"type": "tool_result",
"tool_use_id": b.id,
"content": content
})
messages.append({"role": "user", "content": results})
print(f" └── subagent context end (达到 {turns} 轮上限,未办妥) ──\n")
return "(小太监未能在限定回合内办妥差事)"
# ============== Agent Team:持久队友 + 文件 inbox ==============
class MessageBus:
"""每个队友一个 JSONL inbox。发送=追加一行,读取=读完后清空。"""
def __init__(self, inbox_dir: Path):
self.dir = inbox_dir
self.dir.mkdir(parents=True, exist_ok=True)
def send(self, sender: str, to: str, content: str,
msg_type: str = "message", extra: dict | None = None) -> str:
if msg_type not in VALID_MSG_TYPES:
return f"Error: invalid msg_type '{msg_type}', valid={sorted(VALID_MSG_TYPES)}"
msg = {
"type": msg_type,
"from": sender,
"content": content,
"timestamp": time.time(),
}
if extra:
msg.update(extra)
inbox_path = self.dir / f"{to}.jsonl"
inbox_path.parent.mkdir(parents=True, exist_ok=True)
with inbox_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(msg, ensure_ascii=False) + "\n")
return f"已送达 {to} 的 inbox:{msg_type}"
def read_inbox(self, name: str) -> list[dict]:
inbox_path = self.dir / f"{name}.jsonl"
if not inbox_path.exists():
return []
messages = []
for line in inbox_path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
try:
messages.append(json.loads(line))
except json.JSONDecodeError as e:
messages.append({
"type": "message",
"from": "system",
"content": f"Error: inbox line parse failed: {e}",
"timestamp": time.time(),
})
inbox_path.write_text("", encoding="utf-8")
return messages
def broadcast(self, sender: str, content: str, teammates: list[str]) -> str:
count = 0
for name in teammates:
if name == sender:
continue
self.send(sender, name, content, "broadcast")
count += 1
return f"已广播给 {count} 位队友"
BUS = MessageBus(INBOX_DIR)
class TeammateManager:
"""管理一支持久 agent team:名字、角色、状态和各自的线程。"""
def __init__(self, team_dir: Path):
self.dir = team_dir
self.dir.mkdir(parents=True, exist_ok=True)
self.config_path = self.dir / "config.json"
self.config = self._load_config()
self.threads: dict[str, threading.Thread] = {}
self.lock = threading.Lock()
self._mark_stale_members_offline()
def _load_config(self) -> dict:
if self.config_path.exists():
try:
return json.loads(self.config_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
pass
return {"team_name": "default", "members": []}
def _save_config(self):
self.config_path.write_text(
json.dumps(self.config, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def _mark_stale_members_offline(self):
"""进程重启后,config 还在,但旧线程已经不存在。
所以启动时把上次遗留的 idle/working 改成 offline,避免误导用户。
"""
changed = False
for member in self.config.get("members", []):
if member.get("status") in RUNTIME_STATUSES:
member["status"] = "offline"
changed = True
if changed:
self._save_config()
def _find_member(self, name: str) -> dict | None:
for member in self.config["members"]:
if member["name"] == name:
return member
return None
def _set_status(self, name: str, status: str):
with self.lock:
member = self._find_member(name)
if member:
member["status"] = status
self._save_config()
def spawn(self, name: str, role: str, prompt: str) -> str:
name = name.strip()
role = role.strip() or "teammate"
if not name:
return "Error: name 不能为空"
with self.lock:
member = self._find_member(name)
if member:
running = self.threads.get(name)
if running and running.is_alive():
BUS.send("lead", name, prompt)
member["role"] = role
member["status"] = "working"
self._save_config()
return f"'{name}' 已在队中,已把新差事送入 inbox"
member["role"] = role
member["status"] = "working"
else:
member = {"name": name, "role": role, "status": "working"}
self.config["members"].append(member)
self._save_config()
thread = threading.Thread(
target=self._teammate_loop,
args=(name, role, prompt),
daemon=True,
)
self.threads[name] = thread
thread.start()
return f"已召入/唤回队友 '{name}'(职司:{role}),队友线程已启动"
def _teammate_loop(self, name: str, role: str, prompt: str):
system_prompt = (
f"你是大内团队中的固定队友,名叫{name},职司是{role}。\n"
f"当前目录:{Path.cwd()}。\n"
"你不是一次性小太监,而是 agent team 的持久成员。\n"
"你可以通过 send_message 给 lead 或其他队友发消息,也可以 read_inbox 读取自己的 inbox。\n"
"收到差事后尽快办妥;办完用 send_message 向 lead 回禀简短结果,然后等待下一封 inbox。\n"
"若收到 shutdown_request,可回禀 shutdown_response 后停止。"
)
tools = self._teammate_tools()
messages = [{"role": "user", "content": prompt}]
has_work = True
while True:
inbox = BUS.read_inbox(name)
for msg in inbox:
if msg.get("type") == "shutdown_request":
BUS.send(name, msg.get("from", "lead"), "准许退下,队友线程即将停止。", "shutdown_response")
self._set_status(name, "shutdown")
return
messages.append({
"role": "user",
"content": "<inbox>\n" + json.dumps(msg, ensure_ascii=False, indent=2) + "\n</inbox>",
})
has_work = True
if not has_work:
self._set_status(name, "idle")
time.sleep(1)
continue
self._set_status(name, "working")
for turn in range(20):
try:
msg = client.messages.create(
model=MODEL,
max_tokens=4000,
system=system_prompt,
tools=tools,
messages=messages,
)
except Exception as e:
BUS.send(name, "lead", f"Error: 队友 {name} 调用模型失败:{e}")
self._set_status(name, "idle")
has_work = False
break
messages.append({"role": "assistant", "content": msg.content})
if msg.stop_reason != "tool_use":
final = next((b.text for b in msg.content if b.type == "text"), "")
if final.strip():
BUS.send(name, "lead", final.strip())
print(f"[队友 {name} 空闲]: 本轮 {turn + 1} 次调用后回到 idle")
self._set_status(name, "idle")
has_work = False
break
results = []
for b in msg.content:
if b.type != "tool_use":
continue
output = self._exec(name, b.name, b.input)
print(f" [队友·{name}·{b.name}]: {str(output)[:160]}")
results.append({
"type": "tool_result",
"tool_use_id": b.id,
"content": str(output),
})
messages.append({"role": "user", "content": results})
else:
BUS.send(name, "lead", f"队友 {name} 达到本轮 20 次调用上限,已暂停等待下一步指令。")
self._set_status(name, "idle")
has_work = False
def _exec(self, sender: str, tool_name: str, args: dict) -> str:
if tool_name in _TOOL_SCHEMAS:
block = SimpleNamespace(name=tool_name, input=args)
return execute_basic_tool(block, prefix=f"队友({sender})·")
if tool_name == "send_message":
return BUS.send(sender, args["to"], args["content"], args.get("msg_type", "message"))
if tool_name == "read_inbox":
return json.dumps(BUS.read_inbox(sender), ensure_ascii=False, indent=2)
return f"Error: unknown teammate tool '{tool_name}'"
def _teammate_tools(self) -> list[dict]:
return [
_TOOL_SCHEMAS["run_command"],
_TOOL_SCHEMAS["web_fetch"],
_TOOL_SCHEMAS["load_skill"],
{
"name": "list_mcp_servers",
"description": "列出已连接的 MCP Server 及其提供的工具。",
"input_schema": {
"type": "object",
"properties": {
"server": {"type": "string", "description": "指定 server 名称(可选)"}
}
},
},
_TOOL_SCHEMAS["read_file"],
_TOOL_SCHEMAS["write_file"],
_TOOL_SCHEMAS["glob"],
_TOOL_SCHEMAS["grep"],
{
"name": "send_message",
"description": "给 lead 或其他队友发送 inbox 消息。",
"input_schema": {
"type": "object",
"properties": {
"to": {"type": "string"},
"content": {"type": "string"},
"msg_type": {"type": "string", "enum": list(VALID_MSG_TYPES)},
},
"required": ["to", "content"],
},
},
{
"name": "read_inbox",
"description": "读取并清空自己的 inbox。",
"input_schema": {"type": "object", "properties": {}},
},
]
def list_all(self) -> str:
with self.lock:
if not self.config["members"]:
return "暂无队友。"
lines = [f"Team: {self.config.get('team_name', 'default')}"]
for member in self.config["members"]:
status = member["status"]
note = "(需重新 spawn 才会处理 inbox)" if status == "offline" else ""
lines.append(f" - {member['name']}({member['role']}):{status}{note}")
return "\n".join(lines)
def member_names(self) -> list[str]:
with self.lock:
return [m["name"] for m in self.config["members"]]
TEAM = TeammateManager(TEAM_DIR)
# ============== Hooks:生命周期拦截、注入与审计(沿用 step11 后新增) ==============
# s12 引入四层 Hook 模型:Event(事件)→ Matcher(匹配器)→ Handler(处理器)→ Decision(决策)。
# 该模型与 Claude Code 官方的 Event → Matcher → Handler → Output 结构完全对齐。
# Claude Code 官方支持五种 Handler 类型:command / http / mcp_tool / prompt / agent。
# 教学版统一用 Python 类方法,但保留了相同的四层结构和决策语义。
class HookDecision:
"""Hook 的结构化决策结果。与 Claude Code 的 permissionDecision 概念对齐。
教学版支持四种决策:
- allow:放行(可附带 updated_input 改写工具参数)
- deny:拒绝(工具不执行,reason 会反馈给 Agent)
- ask:请求用户确认(拒绝或非交互环境默认不执行工具)
- block:阻止并给出原因(等同于 Claude Code 的继续处理指令)
"""
def __init__(self, action: str, reason: str = "", updated_input: dict[str, Any] | None = None):
self.action = action # "allow" | "deny" | "ask" | "block"
self.reason = reason # 人类可读原因
self.updated_input = updated_input # 可选:改写工具参数(对应 Claude Code 的 updatedInput)
@property
def is_blocking(self) -> bool:
"""是否阻止当前操作继续执行。"""
return self.action in ("deny", "block")
def to_message(self) -> str:
"""转为 Agent 可读的反馈消息。"""
prefix = {"deny": "拒绝", "block": "阻止", "ask": "需要确认", "allow": "已放行"}
label = prefix.get(self.action, self.action)
msg = f"[HookDecision: {label}] {self.reason}"
if self.updated_input:
msg += f"(参数已改写:{list(self.updated_input.keys())})"
return msg
def confirm_hook_decision(decision: HookDecision) -> bool:
"""处理 ask 决策。
教学版故意保持同步确认:终端里输入 y 才继续;非交互环境默认拒绝。
这更接近权限 Hook 的 fail-closed 行为。
"""
print(f"\n[hook:permission] {decision.reason}")
if not sys.stdin.isatty():
print("[hook:permission] 当前不是交互式终端,默认拒绝执行。\n")
return False
try:
answer = input("[hook:permission] 是否继续执行?输入 y 继续,其余取消: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
return False
return answer in ("y", "yes")
class Hook:
"""Hook 基类:所有事件默认空实现。
四层模型说明(教学版 → Claude Code 官方映射):
- Event(事件):方法名即事件,如 before_turn、before_tool_call、on_stop
- Matcher(匹配器):matcher 属性控制对哪些工具触发,如 "write_file"、"run_command"
- Handler(处理器):子类覆写事件方法实现具体逻辑。Claude Code 支持 command/http/mcp/prompt/agent 五种
- Decision(决策):返回 HookDecision 或字符串来放行/拒绝/确认/阻止
"""