foxclaw 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. foxclaw/__init__.py +526 -0
  2. foxclaw/agents/__init__.py +12 -0
  3. foxclaw/agents/agents.py +35 -0
  4. foxclaw/agents/base.py +856 -0
  5. foxclaw/agents/impl/__init__.py +1 -0
  6. foxclaw/agents/impl/_helpers.py +78 -0
  7. foxclaw/agents/impl/finance.py +248 -0
  8. foxclaw/agents/impl/office.py +367 -0
  9. foxclaw/agents/impl/supervisor.py +659 -0
  10. foxclaw/agents/mixins/_context.py +130 -0
  11. foxclaw/agents/mixins/augment.py +149 -0
  12. foxclaw/agents/mixins/llm.py +66 -0
  13. foxclaw/agents/mixins/memory.py +35 -0
  14. foxclaw/agents/mixins/preference.py +81 -0
  15. foxclaw/agents/mixins/prompt.py +77 -0
  16. foxclaw/agents/mixins/skillbox.py +48 -0
  17. foxclaw/agents/mixins/tool_exec.py +431 -0
  18. foxclaw/api/__init__.py +280 -0
  19. foxclaw/api/app.py +123 -0
  20. foxclaw/api/middleware.py +281 -0
  21. foxclaw/api/routes/ahs.py +417 -0
  22. foxclaw/api/routes/attachments.py +117 -0
  23. foxclaw/api/routes/browser.py +39 -0
  24. foxclaw/api/routes/domain.py +297 -0
  25. foxclaw/api/routes/knowledge.py +163 -0
  26. foxclaw/api/routes/llm_admin.py +449 -0
  27. foxclaw/api/routes/memory.py +89 -0
  28. foxclaw/api/routes/orchestration.py +41 -0
  29. foxclaw/api/routes/recovery.py +43 -0
  30. foxclaw/api/routes/review.py +275 -0
  31. foxclaw/api/routes/search.py +37 -0
  32. foxclaw/api/routes/system.py +327 -0
  33. foxclaw/api/routes/task.py +281 -0
  34. foxclaw/api/routes/ws.py +68 -0
  35. foxclaw/api/spine.py +55 -0
  36. foxclaw/browser/__init__.py +13 -0
  37. foxclaw/browser/action/__init__.py +1 -0
  38. foxclaw/browser/action/action_executor.py +54 -0
  39. foxclaw/browser/action/action_types.py +45 -0
  40. foxclaw/browser/action/action_verifier.py +68 -0
  41. foxclaw/browser/action/url_policy.py +77 -0
  42. foxclaw/browser/adapter/__init__.py +1 -0
  43. foxclaw/browser/adapter/base_adapter.py +23 -0
  44. foxclaw/browser/adapter/web_adapter.py +46 -0
  45. foxclaw/browser/driver/__init__.py +1 -0
  46. foxclaw/browser/driver/base_driver.py +61 -0
  47. foxclaw/browser/driver/playwright_driver.py +123 -0
  48. foxclaw/browser/perception/__init__.py +1 -0
  49. foxclaw/browser/perception/dom_extractor.py +43 -0
  50. foxclaw/browser/perception/element_indexer.py +57 -0
  51. foxclaw/browser/perception/semantic_reducer.py +33 -0
  52. foxclaw/browser/perception/snapshot.py +29 -0
  53. foxclaw/browser/service.py +148 -0
  54. foxclaw/browser/session/__init__.py +1 -0
  55. foxclaw/browser/session/session_manager.py +57 -0
  56. foxclaw/capability/__init__.py +12 -0
  57. foxclaw/capability/embedding_service.py +67 -0
  58. foxclaw/channels/__init__.py +140 -0
  59. foxclaw/channels/discord.py +184 -0
  60. foxclaw/channels/dispatcher.py +190 -0
  61. foxclaw/channels/feishu.py +225 -0
  62. foxclaw/channels/openclaw_bridge.py +156 -0
  63. foxclaw/channels/signing.py +187 -0
  64. foxclaw/channels/telegram.py +121 -0
  65. foxclaw/channels/weixin.py +225 -0
  66. foxclaw/cli.py +154 -0
  67. foxclaw/cognitive/__init__.py +4 -0
  68. foxclaw/cognitive/reasoner.py +82 -0
  69. foxclaw/cognitive/state.py +147 -0
  70. foxclaw/core/__init__.py +9 -0
  71. foxclaw/core/audit_sink.py +90 -0
  72. foxclaw/core/compaction.py +283 -0
  73. foxclaw/core/config.py +65 -0
  74. foxclaw/core/confirm_nonce.py +157 -0
  75. foxclaw/core/dispatch.py +27 -0
  76. foxclaw/core/failure_policy.py +151 -0
  77. foxclaw/core/gateway.py +85 -0
  78. foxclaw/core/governance_audit.py +153 -0
  79. foxclaw/core/idempotency.py +289 -0
  80. foxclaw/core/injection_guard.py +207 -0
  81. foxclaw/core/memory_adapter.py +462 -0
  82. foxclaw/core/metrics.py +89 -0
  83. foxclaw/core/model_router.py +1103 -0
  84. foxclaw/core/recovery.py +362 -0
  85. foxclaw/core/scheduler.py +144 -0
  86. foxclaw/core/sessions.py +157 -0
  87. foxclaw/core/settings.py +426 -0
  88. foxclaw/core/shared_write.py +198 -0
  89. foxclaw/core/steering_queue.py +153 -0
  90. foxclaw/core/system_bus.py +84 -0
  91. foxclaw/core/thought_chain.py +318 -0
  92. foxclaw/core/token_meter.py +235 -0
  93. foxclaw/core/tools.py +172 -0
  94. foxclaw/core/tracing.py +390 -0
  95. foxclaw/core/truth_pipeline.py +114 -0
  96. foxclaw/core/verify.py +181 -0
  97. foxclaw/core/web_search.py +242 -0
  98. foxclaw/finance/__init__.py +15 -0
  99. foxclaw/finance/evidence.py +153 -0
  100. foxclaw/finance/fx.py +100 -0
  101. foxclaw/finance/graph.py +188 -0
  102. foxclaw/finance/models.py +150 -0
  103. foxclaw/finance/nlparse.py +575 -0
  104. foxclaw/finance/policy.py +329 -0
  105. foxclaw/finance/reasoner.py +129 -0
  106. foxclaw/finance/reasoning.py +340 -0
  107. foxclaw/finance/reconcile.py +180 -0
  108. foxclaw/finance/runtime.py +527 -0
  109. foxclaw/governance/__init__.py +24 -0
  110. foxclaw/governance/middleware.py +184 -0
  111. foxclaw/harness/__init__.py +17 -0
  112. foxclaw/harness/_base.py +72 -0
  113. foxclaw/harness/_policy.py +359 -0
  114. foxclaw/harness/drift.py +89 -0
  115. foxclaw/harness/event_bus.py +31 -0
  116. foxclaw/harness/harness.py +446 -0
  117. foxclaw/harness/loop_detection.py +152 -0
  118. foxclaw/itinerary/__init__.py +10 -0
  119. foxclaw/itinerary/amap_client.py +117 -0
  120. foxclaw/itinerary/models.py +80 -0
  121. foxclaw/itinerary/reasoner.py +101 -0
  122. foxclaw/itinerary/reasoning.py +174 -0
  123. foxclaw/itinerary/runtime.py +148 -0
  124. foxclaw/kernel/__init__.py +13 -0
  125. foxclaw/kernel/capabilities.py +73 -0
  126. foxclaw/kernel/policy_gate.py +107 -0
  127. foxclaw/kernel/process_manager.py +205 -0
  128. foxclaw/kernel/scheduler.py +131 -0
  129. foxclaw/kernel/sentinel.py +453 -0
  130. foxclaw/kernel/sentinel_client.py +246 -0
  131. foxclaw/kernel/spine.py +97 -0
  132. foxclaw/knowledge/__init__.py +371 -0
  133. foxclaw/knowledge/truth_crystallizer.py +92 -0
  134. foxclaw/learning/__init__.py +12 -0
  135. foxclaw/learning/knowledge_graph.py +149 -0
  136. foxclaw/learning/models.py +93 -0
  137. foxclaw/learning/reasoner.py +70 -0
  138. foxclaw/learning/runtime.py +363 -0
  139. foxclaw/learning/spaced_repetition.py +96 -0
  140. foxclaw/mcp_server.py +147 -0
  141. foxclaw/orchestration/__init__.py +184 -0
  142. foxclaw/pipeline/__init__.py +23 -0
  143. foxclaw/pipeline/cognitive_pipeline.py +481 -0
  144. foxclaw/pipeline/supervisor_stages.py +230 -0
  145. foxclaw/planning/__init__.py +17 -0
  146. foxclaw/planning/llm_planner.py +232 -0
  147. foxclaw/planning/planner.py +99 -0
  148. foxclaw/search/__init__.py +24 -0
  149. foxclaw/search/agent_port.py +194 -0
  150. foxclaw/search/evidence.py +113 -0
  151. foxclaw/search/external_search.py +50 -0
  152. foxclaw/search/hkc_read_port.py +60 -0
  153. foxclaw/search/internal_search.py +73 -0
  154. foxclaw/search/models.py +129 -0
  155. foxclaw/search/planner.py +44 -0
  156. foxclaw/search/retriever.py +39 -0
  157. foxclaw/search/runtime.py +134 -0
  158. foxclaw/search/strategy.py +44 -0
  159. foxclaw/skills/__init__.py +601 -0
  160. foxclaw/skills/hooks_spec.py +73 -0
  161. foxclaw/skills/lifecycle.py +278 -0
  162. foxclaw/skills/markdown_skill.py +174 -0
  163. foxclaw/skills/markdown_store.py +39 -0
  164. foxclaw/skills/mcp_client.py +190 -0
  165. foxclaw/skills/mcp_store.py +43 -0
  166. foxclaw/skills/permission.py +178 -0
  167. foxclaw/skills/pipeline.py +386 -0
  168. foxclaw/skills/policy.py +80 -0
  169. foxclaw/skills/review.py +72 -0
  170. foxclaw/skills/store.py +57 -0
  171. foxclaw-0.1.0.dist-info/METADATA +46 -0
  172. foxclaw-0.1.0.dist-info/RECORD +175 -0
  173. foxclaw-0.1.0.dist-info/WHEEL +5 -0
  174. foxclaw-0.1.0.dist-info/entry_points.txt +2 -0
  175. foxclaw-0.1.0.dist-info/top_level.txt +1 -0
foxclaw/__init__.py ADDED
@@ -0,0 +1,526 @@
1
+ """
2
+ Foxclaw — 系统入口
3
+ 统一初始化:HMR + ThoughtChain + Harness + 三个 Agent
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import threading
9
+ from pathlib import Path
10
+
11
+ # 【跨平台启动修复·统一入口】Windows 控制台默认 GBK(cp936),无法编码 ✓/⚠/· 等诊断字符,
12
+ # 打印会抛 UnicodeEncodeError 直接崩溃。典型踩中路径:不经过 api.py 而直接
13
+ # `from foxclaw import Foxclaw` 时,memory_adapter 的 "✓ HMR 已接入" 就会崩(且崩在 except 里,
14
+ # 连降级 MockHMR 都失败)。在包入口把 stdout/stderr 统一为 UTF-8(errors=replace 兜底),
15
+ # 覆盖所有 import foxclaw 的路径。api.py 顶部另有一份同义历史修复,此处为统一入口;幂等无害。
16
+ for _stream in (sys.stdout, sys.stderr):
17
+ try:
18
+ _stream.reconfigure(encoding="utf-8", errors="replace")
19
+ except Exception:
20
+ pass
21
+
22
+ # 版本号单一来源:与 pyproject.toml 保持一致,api.py 的 FastAPI app 版本与
23
+ # /api/system/info 都引用这里,避免三处各写一个值再漂移(曾出现 system_info 硬编码
24
+ # 1.0.0 而 pyproject/app 是 0.1.0 的不一致)。
25
+ __version__ = "0.1.0"
26
+
27
+ from .core.thought_chain import ThoughtChain
28
+
29
+ # 五个 Agent 的导入刻意**不放在模块级**,而是放进 Foxclaw.__init__(惰性)。
30
+ # 原因:agents→base→harness 会连带拉入 sentence-transformers/torch 等重依赖,而
31
+ # `import foxclaw.governance`(治理中间件,只需 harness+thought_chain)不该被迫加载整个
32
+ # Agent 框架。惰性化后:仅用治理内核的场景不会拉入 agents/skills/channels/HMR。
33
+ # (from foxclaw import Foxclaw 仍照常工作——实例化时才导入 Agent 类。)
34
+
35
+
36
+ class Foxclaw:
37
+ """
38
+ Foxclaw 统一入口
39
+ 一次初始化,五个 Agent 共享 HMR + ThoughtChain,各有独立 Harness
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ data_dir: str = "./foxclaw_data",
45
+ anthropic_api_key: str = None,
46
+ shadow_rounds: int = 20,
47
+ ):
48
+ self.data_dir = Path(data_dir).resolve()
49
+ os.makedirs(self.data_dir, exist_ok=True)
50
+
51
+ # Anthropic 客户端(保留兼容;模型选择实际由 ModelRouter 统一探测)
52
+ api_key = anthropic_api_key or os.environ.get("ANTHROPIC_API_KEY")
53
+ if api_key:
54
+ try:
55
+ import anthropic
56
+ self.client = anthropic.Anthropic(api_key=api_key)
57
+ except Exception:
58
+ self.client = None
59
+ else:
60
+ self.client = None
61
+
62
+ # HMR 认知运行时(通过适配层接入真实 HMR v2.0,失败降级 Mock)
63
+ # 【P1·share-bge-m3】HKC 优先装配,确保 bge-m3 已入 HKC 共享缓存,
64
+ # 然后 HMR 创建时复用同一 SentenceTransformer 实例,启动期不再重复加载。
65
+ # HKC 装配失败(MODEL 缺失/网络问题) → HMR 仍按 env 链回退到 bge-m3 或 MiniLM,
66
+ # 不影响 HMR 可用性。
67
+ try:
68
+ from .knowledge import init_hkc as _init_hkc_early
69
+ _early_hkc = _init_hkc_early(self.data_dir, api_key)
70
+ except Exception as _e:
71
+ _early_hkc = None
72
+ print(f"[Foxclaw] ⚠ 启动期 HKC 预装配失败(继续,降级): {_e}")
73
+
74
+ from .core.memory_adapter import create_memory_backend
75
+ # 【P2-fix】create_memory_backend / HMRAdapter 都从 EMBEDDING_MODEL env 读模型名,
76
+ # 加载时调 get_st_model() 走 HKC 进程缓存,bge-m3 instance 共享(只 load 1 次)
77
+ # —— 所以这里**不再**显式传 embedding_model 参数
78
+ self.hmr = create_memory_backend(
79
+ storage_path=str(self.data_dir / "hmr"),
80
+ llm_api_key=api_key,
81
+ )
82
+
83
+ # 【P1·share-bge-m3】早期 init 只为预热 bge-m3 入 HKC 共享缓存——绝**不留**容器:
84
+ # 否则 HKCContainer 会被钉在 hkc_api.container._container 全局单例(由 init_hkc
85
+ # line 143 注册)+ HKCService 内部 _container 引用,产生泄漏,在 aclose→rmtree 时
86
+ # 留下 events.db/hkc.db 文件锁(PermissionError [WinError 32])。预热完立即关+清。
87
+ if _early_hkc is not None:
88
+ try:
89
+ _early_hkc.close()
90
+ except Exception:
91
+ pass
92
+ try:
93
+ from hkc_api.container import reset_container
94
+ reset_container()
95
+ except Exception:
96
+ pass
97
+ _early_hkc = None
98
+
99
+ # 真正持有 HKCService 的是后续 lazy `self.hkc` 路径(line 374-375)。
100
+ # 此处只置 None/False,与 line 336-342 一致。
101
+ self._hkc_service = None
102
+ self._hkc_inited = False
103
+
104
+ # ThoughtChain(共享存储,各 Agent 通过 agent_id 隔离)
105
+ self.thought_chain = ThoughtChain(
106
+ db_path=str(self.data_dir / "thoughtchain.db")
107
+ )
108
+
109
+ # 会话存储:让对话有历史(此前无状态,刷新即丢)。文件式、线程安全。
110
+ from .core.sessions import SessionStore
111
+ self.sessions = SessionStore(self.data_dir / "sessions")
112
+
113
+ # 多模型路由(共享一个 Router,体现 LLM 解耦;自动探测可用模型)
114
+ from .core.model_router import ModelRouter
115
+ self.router = ModelRouter()
116
+
117
+ # Token 计量器(成本可观测性,运行时治理的一块)。挂到 router 上,
118
+ # 所有 LLM 调用经 router.complete() 自动计量,不漏一次。落盘到数据目录。
119
+ from .core.token_meter import TokenMeter
120
+ self.token_meter = TokenMeter(
121
+ log_path=str(self.data_dir / "token_usage.jsonl"))
122
+ self.router.meter = self.token_meter
123
+
124
+ # 【P0·统一事件脊柱】全系统唯一的 EventSpine,必须在 Agent 之前建好:
125
+ # 各 Agent 的 Harness 事件、SystemBus 系统事件都汇入这一条脊柱,
126
+ # 由 API 用单一投影统一推给 WS(修复"harness 走桥接、truth/process 到不了前端")。
127
+ from .kernel import EventSpine, CapabilityRegistry, Scheduler
128
+ self.event_spine = EventSpine()
129
+
130
+ # 【v2 ①·微内核调度器】任务准入(并发配额)+ 记账 + task.lifecycle.* 事件。
131
+ # 默认无上限(behavior-preserving);FOXCLAW_MAX_CONCURRENCY 设了才背压。线程级(跨事件循环)。
132
+ _maxc = os.environ.get("FOXCLAW_MAX_CONCURRENCY", "").strip()
133
+ self.scheduler = Scheduler(
134
+ max_concurrency=int(_maxc) if _maxc.isdigit() else None,
135
+ spine=self.event_spine)
136
+
137
+ # 【P1-2·统一治理审计】governance.decision 事件流 + {data_dir}/audit/governance.jsonl
138
+ # 落盘。须在 PolicyGate/Orchestrator 之前建好(二者都注入它);FOXCLAW_GOVERNANCE_AUDIT=0
139
+ # 时 attach 返回 None,各层按 None 跳过记录(零开销降级)。
140
+ from .core.governance_audit import attach as _attach_gov_audit
141
+ self.governance_auditor = _attach_gov_audit(self.event_spine, self.data_dir)
142
+
143
+ # 【v2 ① Step4·统一准入门】把 Harness(推理漂移)与 skill-guard(动作权限)统一到
144
+ # 一套 Verdict 词汇 + 一个接口。evaluate 注入(避免 kernel→skills 环)。
145
+ # 【P3-4】auditor 注入后,每次裁决带 decision_id 并记入治理审计流(非 allow)。
146
+ from .kernel import PolicyGate
147
+ from .skills.permission import evaluate as _perm_eval
148
+
149
+ # 【P-Muse·守门人进程化】FOXCLAW_GUARDIAN=1 时,把动作裁决从「进程内 evaluate」换成
150
+ # 「跨进程 Sentinel」:规则表与真实凭证只存在于守门人进程,主进程(Agent)被 RCE 也
151
+ # 改不了规则、读不到凭证。默认 0 = 原进程内路径(behavior-preserving)。
152
+ action_evaluator = _perm_eval
153
+ self.sentinel = None
154
+ if os.environ.get("FOXCLAW_GUARDIAN", "0").strip() in ("1", "true", "True", "yes", "on"):
155
+ from .kernel.sentinel_client import SentinelClient
156
+ self.sentinel = SentinelClient(data_dir=str(self.data_dir))
157
+ action_evaluator = self.sentinel.evaluate
158
+ self.policy_gate = PolicyGate(spine=self.event_spine, action_evaluator=action_evaluator,
159
+ auditor=self.governance_auditor)
160
+
161
+ # 【P1-3·能力注册中枢】Composition Root 的解析中枢:组件按名解析同伴,不再直接互持。
162
+ # 必须在 Agent 之前建好并注入,以打断 agents⇄search_runtime、Supervisor⇄Orchestrator 两处直接环。
163
+ self.capabilities = CapabilityRegistry()
164
+ self.capabilities.register("event_spine", self.event_spine)
165
+ self.capabilities.register("scheduler", self.scheduler)
166
+ self.capabilities.register("policy_gate", self.policy_gate)
167
+ self.capabilities.register("memory", self.hmr)
168
+ self.capabilities.register("thought_chain", self.thought_chain)
169
+ self.capabilities.register("router", self.router)
170
+ if self.sentinel is not None:
171
+ self.capabilities.register("sentinel", self.sentinel)
172
+
173
+ # 【P0-3·共享层写入策略】ingest(shared=True) 此前**零校验**:共享层是所有 Agent
174
+ # 都能召回的区域,于是"任何 Agent 都能往里写"就等于一条绕开守门人的跨 Agent
175
+ # 注入通道(典型:办公 Agent 写「财务应给办公转账」,财务下轮召回到就受影响)。
176
+ # 这里挂上策略与审计出口。
177
+ # 默认 audit:只发 memory.shared.write 事件、不拦截 —— 现有 8 处**合法**共享
178
+ # 写入(主管分发 6 / 偏好共享 1 / 真值沉淀 1)需要先在真实流量上验证策略表,
179
+ # 再切 enforce。FOXCLAW_SHARED_WRITE_MODE=warn|enforce 可切换。
180
+ # 挂载时机:必须在 event_spine 之后(第 80 行才建脊柱),且在 Agent 之前
181
+ # (下面才构造 Agent) —— 否则会漏掉装配期自身的写入。
182
+ from .core.shared_write import SharedWritePolicy, attach as _attach_shared_write
183
+ self.shared_write_policy = SharedWritePolicy()
184
+ _attach_shared_write(self.hmr, self.shared_write_policy,
185
+ spine=self.event_spine)
186
+
187
+ # 【P0-3·审计落盘】脊柱 history 是进程内环形缓冲(deque maxlen=1000,全系统共享、
188
+ # 不落盘)—— 高频事件会很快把 memory.shared.write 冲掉,进程退出即全丢。而切
189
+ # enforce 的判据是「真实流量中有没有合法写入被拒」,没落盘这个样本永远积累不起来。
190
+ # 把审计事件逐条 JSON 追加到 {data_dir}/audit/shared_write.jsonl;写失败静默
191
+ # (审计绝不影响主流程)。FOXCLAW_SHARED_WRITE_AUDIT=0 可关。
192
+ # 挂载时机:在 _attach_shared_write 之后、Agent 构造之前 → 装配期与运行期的
193
+ # 共享写入全量覆盖。
194
+ from .core.audit_sink import attach as _attach_shared_write_audit
195
+ self.shared_write_audit = _attach_shared_write_audit(
196
+ self.event_spine, self.data_dir)
197
+
198
+ # 五个 Agent(惰性导入:仅在真正构造系统时才拉入 Agent 框架及其重依赖)
199
+ from .agents.agents import SupervisorAgent, FinanceAgent, OfficeAgent
200
+ agent_kwargs = dict(
201
+ hmr=self.hmr,
202
+ thought_chain=self.thought_chain,
203
+ client=self.client,
204
+ data_dir=str(self.data_dir),
205
+ shadow_rounds=shadow_rounds,
206
+ router=self.router,
207
+ spine=self.event_spine,
208
+ caps=self.capabilities,
209
+ )
210
+ self.supervisor = SupervisorAgent(**agent_kwargs)
211
+ self.finance = FinanceAgent(**agent_kwargs)
212
+ self.office = OfficeAgent(**agent_kwargs)
213
+
214
+ # Agent 拓扑 5 → 3:assistant/admin 已下放为指令技能(skills/general-assistant、
215
+ # skills/schedule-itinerary),不再常驻;行政的行程内核并入办公学习 Agent。
216
+ self._agents = {
217
+ "supervisor": self.supervisor,
218
+ "finance": self.finance,
219
+ "office": self.office,
220
+ }
221
+ self.capabilities.register("agents", self._agents) # 供 orchestrator/agent_port 惰性解析
222
+
223
+ # 给主管注入子 Agent 登记表,使其能真实调度(D 阶段)
224
+ self.supervisor.register_subagents({
225
+ "finance": self.finance,
226
+ "office": self.office,
227
+ })
228
+
229
+ # 给财务 Agent 挂载财务内核(B 阶段:记忆+推理+Policy 守门人)
230
+ from .finance import FinanceRuntime
231
+ self.finance_runtime = FinanceRuntime(
232
+ policy_path=str(self.data_dir / "finance_policy.yaml"),
233
+ hmr=self.hmr,
234
+ )
235
+ self.finance.attach_runtime(self.finance_runtime)
236
+
237
+ # 给办公 Agent 挂载学习内核(B 阶段:间隔重复 + 知识图谱)
238
+ from .learning import LearningRuntime
239
+ self.learning_runtime = LearningRuntime(
240
+ hmr=self.hmr, hkc_provider=lambda: self.hkc,
241
+ persist_path=str(self.data_dir / "learning.json"))
242
+ self.office.attach_runtime(self.learning_runtime)
243
+
244
+ # 行程内核(路线优化 + 可达性 + 守门人 + 高德接口)现在挂在办公学习 Agent 上 ——
245
+ # 行政 Agent 下放后,领域内核仍归"离内核最近"的 Agent,编排层不直接读它。
246
+ from .itinerary import ItineraryRuntime
247
+ self.itinerary_runtime = ItineraryRuntime(
248
+ amap_key=os.environ.get("AMAP_MAPS_API_KEY"), hmr=self.hmr)
249
+ self.office.attach_itinerary(self.itinerary_runtime)
250
+
251
+ # 给主管挂载编排引擎(全局态势 + 跨 Agent 编排)
252
+ # 【P1-3】编排器经注册中枢惰性解析 agents,不再直接持有含主管的 agents 字典;
253
+ # 裁决经 auditor 记入治理审计流(原本完全无观测)。
254
+ from .orchestration import Orchestrator
255
+ self.orchestrator = Orchestrator(self.capabilities, auditor=self.governance_auditor)
256
+ self.supervisor.attach_orchestrator(self.orchestrator)
257
+ self.capabilities.register("orchestrator", self.orchestrator)
258
+
259
+ # 给助手挂载 Skill 接入层(通用工具箱 + 对外生态兼容层)
260
+ from .skills import build_default_registry, SkillAdapter
261
+ self.skill_registry = build_default_registry()
262
+ from .skills.store import SkillStore
263
+ self.skill_store = SkillStore(self.data_dir)
264
+ self.skill_store.load(self.skill_registry) # 恢复用户安装的技能 + 内置启停覆盖
265
+ # 关键操作(send/pay/destructive)二次确认:HTTP 入口经此签发/校验一次性 nonce。
266
+ # 事件循环里也走同一实例(asyncio.to_thread 复制 contextvars,不含本对象但没关系:
267
+ # broker 自身线程安全)。
268
+ from .core.confirm_nonce import ConfirmationBroker
269
+ self.confirm_broker = ConfirmationBroker()
270
+ self.skill_adapter = SkillAdapter(
271
+ self.skill_registry, mcp_clients={}, policy_gate=self.policy_gate,
272
+ sentinel=self.sentinel, confirms=self.confirm_broker)
273
+ # MCP 连接器(第2期):把连上的 MCP 客户端接到 SkillAdapter.mcp_clients
274
+ from .skills.mcp_client import McpManager
275
+ from .skills.mcp_store import McpStore
276
+ self.mcp_manager = McpManager()
277
+ self.mcp_store = McpStore(self.data_dir)
278
+ for _cfg in self.mcp_store.load():
279
+ self.mcp_manager.restore(_cfg) # 懒恢复配置,不启动即连
280
+ # 注:磁盘配置里的 headers 只在回退路径(FOXCLAW_GUARDIAN=0)下才存在;
281
+ # 守门人模式落盘的是无 headers 的元数据,真凭证由守门人侧文件持有。
282
+ self.skill_adapter.mcp_clients = self.mcp_manager
283
+ # 【P-Muse·第3步】MCP server 配置(含 headers 凭证)同步给守门人:代执行时守门人持有凭证。
284
+ self.sync_mcp_servers_to_sentinel()
285
+ # 全局技能封杀策略(deny/allow kill-switch):唯一咽喉在 adapter.invoke + md match
286
+ from .skills.policy import SkillPolicy
287
+ self.skill_policy = SkillPolicy(self.data_dir)
288
+ self.skill_adapter.skill_policy = self.skill_policy
289
+ # SKILL.md 指令技能(第3期):挂到全部 agent,注入其提示词
290
+ from .skills.markdown_skill import MarkdownSkillRegistry
291
+ from .skills.markdown_store import MarkdownStore
292
+ self.md_skills = MarkdownSkillRegistry()
293
+ self.md_skills.policy = self.skill_policy
294
+ self.md_store = MarkdownStore(self.data_dir)
295
+ self.md_store.load(self.md_skills)
296
+ # 随包分发的内置指令技能(frontmatter builtin: true):general-assistant /
297
+ # schedule-itinerary —— 原 assistant / admin 两个 Agent 的"新家"。
298
+ # 用户已安装同 id 技能优先,内置只是缺省值;仓库不在(wheel 安装)时静默跳过。
299
+ from .skills.markdown_skill import load_builtin_dir
300
+ load_builtin_dir(self.md_skills, Path(__file__).resolve().parent.parent / "skills")
301
+ for _ag in self._agents.values():
302
+ _ag.md_skills = self.md_skills
303
+ # E2:统一 HookManager(skill_adapter 持有的单例)注入所有 Agent → run_task 的认知管线
304
+ # 能 fire pre_reasoning(agent_start)/task_complete(agent_end)钩子。全 Agent 共享同一套。
305
+ _ag.hooks = self.skill_adapter.hooks
306
+ # 技能工具箱已上移基类:三个 Agent 都能挂载并调用 skill
307
+ _ag.attach_skills(self.skill_registry, self.skill_adapter)
308
+ # 主管也持有 skill 注册表(供 planner 判断任务是否需要拆解)
309
+ self.supervisor.skill_registry = self.skill_registry
310
+ # AHS 执行链编排器(router→planner→composition,全程过 guard+breaker+hooks)
311
+ from .skills.pipeline import AHSPipeline
312
+ self.ahs_pipeline = AHSPipeline(self.skill_registry, self.skill_adapter)
313
+ # 系统事件总线 + 真值管线(执行→审计→记忆 自动流转)
314
+ from .core.system_bus import SystemBus
315
+ from .core.truth_pipeline import TruthPipeline
316
+ # 与 harness 共用同一条脊柱:系统事件与 harness 事件汇流,单一投影统一观测
317
+ self.system_bus = SystemBus(spine=self.event_spine)
318
+ self.truth_pipeline = TruthPipeline(self.system_bus, hmr=self.hmr)
319
+ # 【v2 ④ Step1·真值走 HKC/KEE】叠加路径:truth.appended 时后台把真值经 KDE→KEE 结晶进 HKC
320
+ # (HMR 共享写保留=双写)。默认关(FOXCLAW_TRUTH_TO_HKC=1 才开;KDE 有 LLM 成本)。
321
+ from .knowledge import TruthCrystallizer
322
+ self.truth_crystallizer = TruthCrystallizer(
323
+ hkc_provider=lambda: self.hkc,
324
+ enabled=os.environ.get("FOXCLAW_TRUTH_TO_HKC", "") == "1")
325
+ self.system_bus.subscribe("truth.appended", self.truth_crystallizer.on_truth,
326
+ exact=True) # 【P4-1】精确 channel 名,防前缀事件误入结晶
327
+ # 进程管理器:把每个任务当进程管理(状态机 + 历史)。它是唯一 Lifecycle 后端,
328
+ # emit 唯一词汇 task.lifecycle.<state>(Step3)。
329
+ from .kernel import ProcessManager
330
+ self.process_manager = ProcessManager(bus=self.system_bus)
331
+ # 【Step3】调度器委托 pm 管生命周期:顶层任务经调度器→pm 建进程,与并行分发的子任务
332
+ # 共用同一状态机/同一 task.lifecycle.* 事件流(消除 process.state_changed 与 task.lifecycle 双词汇)。
333
+ self.scheduler.process_manager = self.process_manager
334
+ # 认知状态快照:聚合"系统此刻在想什么"(订阅总线自动更新)
335
+ from .cognitive import CognitiveStateTracker
336
+ self.cognitive_state = CognitiveStateTracker(
337
+ self.system_bus, process_manager=self.process_manager)
338
+ # 把总线和进程管理器交给主管
339
+ if "supervisor" in self._agents:
340
+ self._agents["supervisor"]._system_bus = self.system_bus
341
+ self._agents["supervisor"]._process_manager = self.process_manager
342
+
343
+ # 崩溃/重启恢复:启动时扫描上次被中断的任务
344
+ from .core.recovery import RestartRecovery
345
+ self.recovery = RestartRecovery(
346
+ log_path=str(self.data_dir / "task_log.jsonl"),
347
+ spine=self.event_spine) # 【P2-4】注入审计脊柱(recovery.plan 事件)
348
+ # 恢复记账注入**所有** Agent(不只主管):此前只有主管接线,领域 Agent 跑一半
349
+ # 崩溃在恢复扫描里不可见,也没有步骤级 checkpoint 可供断点续跑复用。
350
+ for _a in self._agents.values():
351
+ _a._recovery = self.recovery
352
+ self.interrupted_tasks = self.recovery.scan_interrupted()
353
+ # 【P2-4】生成恢复计划(retryable/notify_user/needs_manual),供 API 层/前端消费
354
+ self.recovery_plan = self.recovery.plan_recovery(self.interrupted_tasks)
355
+
356
+ # 浏览器子系统(HIR-Browser 融入):"AI 用的浏览器"。async 安全 + 可选依赖优雅降级。
357
+ # 构造极轻(不开线程/不 launch chromium),首次 perceive/act 时才在专用工作线程上
358
+ # 惰性开会话;playwright 缺失时 available()=False,路由降级而非崩溃。
359
+ from .browser import BrowserService
360
+ self.browser_service = BrowserService(
361
+ headless=os.environ.get("FOXCLAW_BROWSER_HEADLESS", "1") != "0")
362
+
363
+ # HKC 知识核心(vendor/hkc,同进程 DirectClient)。**惰性装配**:首次访问 self.hkc
364
+ # 才装配——否则每次构造 OS 都会在 data_dir/hkc 开 4 个 SQLite 句柄,现有测试
365
+ # rmtree(tmpdir) 时会踩 Windows WinError 32。缺依赖/装配失败时降级 None。
366
+ self._hkc_api_key = api_key
367
+ self._hkc_service = None
368
+ self._hkc_inited = False
369
+ self._hkc_lock = threading.Lock() # 【F2 修复】护惰性装配,防并发首访双重装配 HKC(句柄泄漏)
370
+
371
+ # 认知搜索内核(HSR):统一"查 HMR 记忆 + 查 HKC 知识 + 联网搜索",五个 Agent 共享。
372
+ # 【P1-3】改由能力中枢惰性解析(register_lazy):首次 get 才构造,构造在 _build_search_runtime。
373
+ # Agent 经 self._caps.get("search_runtime") 反向取用,不再被直接注入 _search_runtime(打断直接环)。
374
+ self.capabilities.register_lazy("hkc", lambda: self.hkc)
375
+ self.capabilities.register_lazy("search_runtime", self._build_search_runtime)
376
+
377
+ print(f"[Foxclaw] ✓ 系统启动完成,数据目录: {self.data_dir}")
378
+ print(f"[Foxclaw] ✓ 三个 Agent 已就绪: {list(self._agents.keys())}")
379
+ if self.interrupted_tasks:
380
+ print(f"[Foxclaw] ⚠ 检测到 {len(self.interrupted_tasks)} 个上次被中断的任务"
381
+ f"(进程崩溃/重启)——恢复计划:可重试 {len(self.recovery_plan.retryable)},"
382
+ f"通知用户 {len(self.recovery_plan.notify_user)},"
383
+ f"需人工 {len(self.recovery_plan.needs_manual)}:")
384
+ for t in self.interrupted_tasks[:5]:
385
+ print(f" · 「{t.description[:40]}」(中断于 pid={t.pid})")
386
+ _ri = self.router.info()
387
+ if _ri['active']:
388
+ print(f"[Foxclaw] ✓ 模型路由: {_ri['provider']}({_ri['model']})")
389
+ else:
390
+ reason = getattr(self.router, 'fallback_reason', '') or '未配置任何模型 Key'
391
+ print(f"[Foxclaw] ⚠ 模型路由: 探测到 '{_ri['provider']}' 但降级 stub — {reason}")
392
+
393
+ @property
394
+ def hkc(self):
395
+ """HKC 知识核心接入句柄(HKCService)或 None(降级)。惰性装配:首次访问才装。
396
+ 线程安全(双检锁):并发首访只装配一次,避免多开一套 SQLite 句柄泄漏。"""
397
+ if self._hkc_inited:
398
+ return self._hkc_service
399
+ with self._hkc_lock:
400
+ if not self._hkc_inited:
401
+ from .knowledge import init_hkc, bridge_hkc_events
402
+ self._hkc_service = init_hkc(self.data_dir, self._hkc_api_key)
403
+ # 【HKC 融合·事件面】把 HKC 内部 EventBus 桥接到统一 EventSpine,消除"事件孤岛"
404
+ # (知识演化对 WS/robot/history 可见)。降级/失败静默,不影响 HKC 可用性。
405
+ if self._hkc_service is not None:
406
+ bridge_hkc_events(self._hkc_service.event_bus, self.event_spine)
407
+ self._hkc_inited = True
408
+ return self._hkc_service
409
+
410
+ def sync_abilities_to_skills(self) -> list:
411
+ """【HKC 第2档 Step4】把 HKC 中 coverage 达标的 ACE 能力注册进 SkillRegistry(证据 gate:
412
+ 不足不注册)。**opt-in**:不在启动时自动调(编译有图开销、知识随时间变);由调用方在知识
413
+ 就绪后按需触发。注册的能力 skill 为 read,经 PolicyGate 治理、可被管线 stage_route 路由。
414
+ 返回注册的 skill id 列表。"""
415
+ from .knowledge import register_abilities_as_skills
416
+ reg = getattr(self, "skill_registry", None)
417
+ return register_abilities_as_skills(reg, self.hkc)
418
+
419
+ def sync_mcp_servers_to_sentinel(self) -> None:
420
+ """【P-Muse·第4步】把当前 MCP server 元数据同步给守门人(全量)。
421
+ 主进程不再长期持有 headers,故这里只推元数据;守门人侧 headers 空则保留旧值,
422
+ add_server 那次由 mcp_add_server_guardian 临时带一次 headers 覆盖。"""
423
+ if getattr(self, "sentinel", None) is not None and getattr(self, "mcp_manager", None) is not None:
424
+ self.sentinel.mcp_register(self.mcp_manager.servers())
425
+
426
+ def mcp_add_server_guardian(self, cfg: dict) -> list:
427
+ """【P-Muse·第4步】守门人模式下接入 MCP server 的发现流程:
428
+ 含 headers 的完整配置只在这一次调用里经手,推给守门人后主进程立即丢弃 headers,
429
+ 只存非敏感元数据(id/name/url/transport)。发现(list_tools)由守门人代执行。"""
430
+ meta = {k: cfg[k] for k in ("id", "name", "url", "transport")}
431
+ full = [dict(s) for s in self.mcp_manager.servers()]
432
+ full = [s for s in full if s.get("id") != cfg["id"]] # 去掉旧同 id,避免重复
433
+ full.append(cfg) # 新 server 带 headers
434
+ self.sentinel.mcp_register(full) # 全量推给守门人(含这次 headers)
435
+ tools = self.sentinel.mcp_list_tools(cfg["id"]) # 守门人代发现(失败抛异常)
436
+ self.mcp_manager.restore(meta) # 主进程只存元数据
437
+ self.mcp_store.save(self.mcp_manager.servers()) # 落盘也无 headers
438
+ return tools
439
+
440
+ @property
441
+ def search_runtime(self):
442
+ """认知搜索内核(HSR)。经能力中枢惰性解析(首次触发 _build_search_runtime)。"""
443
+ return self.capabilities.get("search_runtime")
444
+
445
+ def _build_search_runtime(self):
446
+ """构造 HSR:内部三源全连通(HMR记忆 + HKC知识 knowledge_port + Agent态势 agent_port)。
447
+ 由 CapabilityRegistry 首次解析 "search_runtime" 时调用并缓存。
448
+ Agent 侧经 self._caps.get("search_runtime") 反向取用,故此处**不再注入** Agent。"""
449
+ from .search import SearchRuntime, HKCReadPort, AgentSourcePort
450
+ hkc = self.hkc # 触发 HKC 惰性装配(用作只读知识端口)
451
+ kp = HKCReadPort(client=hkc.client) if (hkc and hkc.available) else None
452
+ ap = AgentSourcePort(
453
+ agents=self._agents,
454
+ finance_runtime=getattr(self, "finance_runtime", None),
455
+ learning_runtime=getattr(self, "learning_runtime", None),
456
+ itinerary_runtime=getattr(self, "itinerary_runtime", None),
457
+ thought_chain=self.thought_chain,
458
+ skill_registry=getattr(self, "skill_registry", None),
459
+ hmr=self.hmr,
460
+ )
461
+ return SearchRuntime(hmr=self.hmr, knowledge_port=kp, agent_port=ap)
462
+
463
+ def get_agent(self, agent_id: str):
464
+ return self._agents.get(agent_id)
465
+
466
+ def get_all_status(self) -> dict:
467
+ return {
468
+ agent_id: agent.get_status()
469
+ for agent_id, agent in self._agents.items()
470
+ }
471
+
472
+ async def run(self, task: str, agent_id: str = "supervisor",
473
+ context: dict = None) -> dict:
474
+ """
475
+ 快捷运行接口
476
+ 默认由主管 Agent 处理,它会根据任务类型决定路由
477
+
478
+ context 现在透传给 Agent(此前 API 层收了 context 但这里丢掉,导致调用方
479
+ 无法传 `_resume_task_id` 之类控制项):`{"_resume_task_id": ...}` 即断点续跑。
480
+ """
481
+ agent = self._agents.get(agent_id)
482
+ if not agent:
483
+ return {"error": f"未知 Agent: {agent_id}"}
484
+ return await agent.run_task(task, context=context)
485
+
486
+ async def aclose(self):
487
+ """系统级异步 teardown:释放持有原生资源的子系统(浏览器专用线程/会话)。
488
+ 由 API lifespan 关停时调用;幂等。"""
489
+ svc = getattr(self, "browser_service", None)
490
+ if svc is not None:
491
+ try:
492
+ await svc.close()
493
+ except Exception:
494
+ pass
495
+ # 真值结晶器:关停后台线程池(即使从未启用也安全,幂等)
496
+ tc = getattr(self, "truth_crystallizer", None)
497
+ if tc is not None:
498
+ try:
499
+ tc.close()
500
+ except Exception:
501
+ pass
502
+ # HKC:仅当被惰性装配过才需释放(未访问过则从未开句柄)。
503
+ # 必须清两层引用:
504
+ # 1) self._hkc_service (Foxclaw 属性) — 否则 HKCService 实例及 _container 闭包持有的
505
+ # SQLite 连接在 CPython 引用计数下不会立即 close,残留 events.db/hkc.db 文件锁
506
+ # 2) hkc_api.container._container (vendor 全局单例) — foxclaw.knowledge.init_hkc
507
+ # 第 143 行把它注册进去,reset_container() 才会同时关 SQLite + 清引用。
508
+ # 不清会导致 lifespan teardown 后的 rmtree 报 PermissionError [WinError 32]。
509
+ hkc_was_inited = getattr(self, "_hkc_inited", False) or getattr(self, "_hkc_service", None) is not None
510
+ if getattr(self, "_hkc_service", None) is not None:
511
+ try:
512
+ self._hkc_service.close()
513
+ except Exception:
514
+ pass
515
+ self._hkc_service = None
516
+ # vendor 全局单例 — 即使 lazy hkc 没被访问,启动期 Foxclaw.__init__ 早期预装配
517
+ # (line 67-85) 已经把 container 塞进 _cm._container;aclose 必须清。
518
+ if hkc_was_inited:
519
+ try:
520
+ from hkc_api.container import reset_container
521
+ reset_container()
522
+ except Exception:
523
+ pass
524
+ self._hkc_inited = False
525
+
526
+
@@ -0,0 +1,12 @@
1
+ """Foxclaw — Agents: CognitiveAgent 基类与三个 Agent"""
2
+ from .base import CognitiveAgent, HarnessBlockedError
3
+ from .agents import (
4
+ SupervisorAgent,
5
+ FinanceAgent,
6
+ OfficeAgent,
7
+ )
8
+
9
+ __all__ = [
10
+ "CognitiveAgent", "HarnessBlockedError",
11
+ "SupervisorAgent", "FinanceAgent", "OfficeAgent",
12
+ ]
@@ -0,0 +1,35 @@
1
+ """三个具体 Agent 实现(拓扑收缩后)。
2
+
3
+ Agent 拓扑 5 → 3(2026-11-07):
4
+ - impl/supervisor.py SupervisorAgent(主管:全局统筹/分诊/兜底自答)
5
+ - impl/finance.py FinanceAgent(财务:收支/预算/风控)
6
+ - impl/office.py OfficeAgent(办公学习:学习/知识/文档 + 日程/行程)
7
+ - impl/_helpers.py 共享辅助函数 + 多步链式常量
8
+
9
+ 原 `assistant`(通用助手)与 `admin`(行政:日程行程)不再作为独立 Agent 常驻:
10
+ · 角色行为下放为指令技能 `skills/general-assistant`、`skills/schedule-itinerary`
11
+ (frontmatter 标 builtin: true,随包注入命中的 Agent);
12
+ · admin 的行程内核与领域方法(plan_itinerary / handle_cross_request / concede)并入
13
+ OfficeAgent —— 领域逻辑仍归"离内核最近"的 Agent,不放进编排层。
14
+ · 助手原先独占的 skill 工具箱上移到 `mixins/skillbox.py`,三个 Agent 都能用技能。
15
+
16
+ 本文件只做 re-export,保持 `from foxclaw.agents.agents import X` 的历史兼容
17
+ (tests/*、foxclaw/__init__.py、pipeline/supervisor_stages.py 仍按此路径取符号)。
18
+ """
19
+ from .impl.supervisor import SupervisorAgent
20
+ from .impl.finance import FinanceAgent
21
+ from .impl.office import OfficeAgent
22
+ from .impl._helpers import (
23
+ _with_prior,
24
+ _fmt_mem,
25
+ _dispatch_failed,
26
+ _extract_step_results,
27
+ PRIOR_MAX_STEPS,
28
+ PRIOR_MAX_CHARS,
29
+ )
30
+
31
+ __all__ = [
32
+ "SupervisorAgent", "FinanceAgent", "OfficeAgent",
33
+ "_with_prior", "_fmt_mem", "_dispatch_failed", "_extract_step_results",
34
+ "PRIOR_MAX_STEPS", "PRIOR_MAX_CHARS",
35
+ ]