foxclaw 0.1.0 → 0.1.3

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 (514) hide show
  1. package/README.md +54 -29
  2. package/bin/foxclaw.cjs +51 -0
  3. package/index.js +4 -10
  4. package/package.json +46 -38
  5. package/python/.dockerignore +35 -0
  6. package/python/.env.example +173 -0
  7. package/python/.gitattributes +46 -0
  8. package/python/.github/workflows/ci.yml +167 -0
  9. package/python/.github/workflows/release.yml +183 -0
  10. package/python/CHANGELOG.md +57 -0
  11. package/python/CHANGELOG_CN.md +57 -0
  12. package/python/Dockerfile +64 -0
  13. package/python/LICENSE +21 -0
  14. package/python/MANIFEST.in +14 -0
  15. package/python/README.md +201 -0
  16. package/python/README_CN.md +336 -0
  17. package/python/bench/bm25_audit.py +186 -0
  18. package/python/bench/bm25_regression.py +177 -0
  19. package/python/bench/bm25_stress.py +155 -0
  20. package/python/bench/cd_audit.py +215 -0
  21. package/python/bench/chaos.py +140 -0
  22. package/python/bench/concurrency.py +103 -0
  23. package/python/bench/e2e_real_models.py +94 -0
  24. package/python/bench/llm_retry_test.py +241 -0
  25. package/python/bench/load_test.py +193 -0
  26. package/python/bench/vector_ivf_upgrade.py +128 -0
  27. package/python/docs/CHANNELS.md +195 -0
  28. package/python/docs/GOVERNANCE.md +164 -0
  29. package/python/docs/RELEASE.md +110 -0
  30. package/python/docs/RUN.md +75 -0
  31. package/python/docs/RUN_CN.md +121 -0
  32. package/python/docs//351/205/215/347/275/256/346/214/207/345/215/227.md +152 -0
  33. package/python/evals/__init__.py +0 -0
  34. package/python/evals/governance/README.md +61 -0
  35. package/python/evals/governance/__init__.py +0 -0
  36. package/python/evals/governance/cases.py +115 -0
  37. package/python/evals/governance/compare_embeddings.py +94 -0
  38. package/python/evals/governance/convergence.svg +11 -0
  39. package/python/evals/governance/report.json +371 -0
  40. package/python/evals/governance/run_evals.py +368 -0
  41. package/python/examples/governance_middleware_demo.py +72 -0
  42. package/python/examples/langgraph_governance_demo.py +104 -0
  43. package/python/examples/sample_itinerary.csv +6 -0
  44. package/python/examples/sample_knowledge.csv +9 -0
  45. package/python/examples/sample_transactions.csv +14 -0
  46. package/python/foxclaw/__init__.py +408 -0
  47. package/python/foxclaw/agents/__init__.py +12 -0
  48. package/python/foxclaw/agents/agents.py +35 -0
  49. package/python/foxclaw/agents/base.py +794 -0
  50. package/python/foxclaw/agents/impl/__init__.py +1 -0
  51. package/python/foxclaw/agents/impl/_helpers.py +70 -0
  52. package/python/foxclaw/agents/impl/finance.py +231 -0
  53. package/python/foxclaw/agents/impl/office.py +350 -0
  54. package/python/foxclaw/agents/impl/supervisor.py +592 -0
  55. package/python/foxclaw/agents/mixins/_context.py +128 -0
  56. package/python/foxclaw/agents/mixins/augment.py +143 -0
  57. package/python/foxclaw/agents/mixins/llm.py +67 -0
  58. package/python/foxclaw/agents/mixins/memory.py +41 -0
  59. package/python/foxclaw/agents/mixins/preference.py +131 -0
  60. package/python/foxclaw/agents/mixins/prompt.py +71 -0
  61. package/python/foxclaw/agents/mixins/skillbox.py +58 -0
  62. package/python/foxclaw/agents/mixins/tool_exec.py +417 -0
  63. package/python/foxclaw/api/__init__.py +224 -0
  64. package/python/foxclaw/api/_state.py +43 -0
  65. package/python/foxclaw/api/bootstrap.py +96 -0
  66. package/python/foxclaw/api/middleware.py +294 -0
  67. package/python/foxclaw/api/routes/ahs.py +404 -0
  68. package/python/foxclaw/api/routes/attachments.py +116 -0
  69. package/python/foxclaw/api/routes/browser.py +35 -0
  70. package/python/foxclaw/api/routes/domain.py +306 -0
  71. package/python/foxclaw/api/routes/knowledge.py +145 -0
  72. package/python/foxclaw/api/routes/llm_admin.py +449 -0
  73. package/python/foxclaw/api/routes/memory.py +105 -0
  74. package/python/foxclaw/api/routes/orchestration.py +39 -0
  75. package/python/foxclaw/api/routes/recovery.py +44 -0
  76. package/python/foxclaw/api/routes/review.py +266 -0
  77. package/python/foxclaw/api/routes/search.py +33 -0
  78. package/python/foxclaw/api/routes/system.py +311 -0
  79. package/python/foxclaw/api/routes/task.py +263 -0
  80. package/python/foxclaw/api/routes/ws.py +64 -0
  81. package/python/foxclaw/api/spine.py +52 -0
  82. package/python/foxclaw/browser/__init__.py +13 -0
  83. package/python/foxclaw/browser/action/__init__.py +1 -0
  84. package/python/foxclaw/browser/action/action_executor.py +50 -0
  85. package/python/foxclaw/browser/action/action_types.py +44 -0
  86. package/python/foxclaw/browser/action/action_verifier.py +68 -0
  87. package/python/foxclaw/browser/action/url_policy.py +143 -0
  88. package/python/foxclaw/browser/adapter/__init__.py +1 -0
  89. package/python/foxclaw/browser/adapter/base_adapter.py +23 -0
  90. package/python/foxclaw/browser/adapter/web_adapter.py +46 -0
  91. package/python/foxclaw/browser/driver/__init__.py +1 -0
  92. package/python/foxclaw/browser/driver/base_driver.py +61 -0
  93. package/python/foxclaw/browser/driver/playwright_driver.py +170 -0
  94. package/python/foxclaw/browser/perception/__init__.py +1 -0
  95. package/python/foxclaw/browser/perception/dom_extractor.py +42 -0
  96. package/python/foxclaw/browser/perception/element_indexer.py +56 -0
  97. package/python/foxclaw/browser/perception/semantic_reducer.py +33 -0
  98. package/python/foxclaw/browser/perception/snapshot.py +29 -0
  99. package/python/foxclaw/browser/service.py +144 -0
  100. package/python/foxclaw/browser/session/__init__.py +1 -0
  101. package/python/foxclaw/browser/session/session_manager.py +57 -0
  102. package/python/foxclaw/capability/__init__.py +12 -0
  103. package/python/foxclaw/capability/embedding_service.py +65 -0
  104. package/python/foxclaw/channels/__init__.py +138 -0
  105. package/python/foxclaw/channels/discord.py +175 -0
  106. package/python/foxclaw/channels/dispatcher.py +179 -0
  107. package/python/foxclaw/channels/feishu.py +215 -0
  108. package/python/foxclaw/channels/openclaw_bridge.py +151 -0
  109. package/python/foxclaw/channels/signing.py +187 -0
  110. package/python/foxclaw/channels/telegram.py +120 -0
  111. package/python/foxclaw/channels/weixin.py +215 -0
  112. package/python/foxclaw/cli.py +183 -0
  113. package/python/foxclaw/cognitive/__init__.py +4 -0
  114. package/python/foxclaw/cognitive/reasoner.py +81 -0
  115. package/python/foxclaw/cognitive/state.py +141 -0
  116. package/python/foxclaw/core/__init__.py +9 -0
  117. package/python/foxclaw/core/audit_chain.py +131 -0
  118. package/python/foxclaw/core/audit_sink.py +100 -0
  119. package/python/foxclaw/core/compaction.py +265 -0
  120. package/python/foxclaw/core/config.py +65 -0
  121. package/python/foxclaw/core/confirm_nonce.py +151 -0
  122. package/python/foxclaw/core/dispatch.py +27 -0
  123. package/python/foxclaw/core/envfile.py +48 -0
  124. package/python/foxclaw/core/failure_policy.py +142 -0
  125. package/python/foxclaw/core/gateway.py +81 -0
  126. package/python/foxclaw/core/governance_audit.py +171 -0
  127. package/python/foxclaw/core/idempotency.py +282 -0
  128. package/python/foxclaw/core/injection_guard.py +202 -0
  129. package/python/foxclaw/core/memory_adapter.py +489 -0
  130. package/python/foxclaw/core/metrics.py +88 -0
  131. package/python/foxclaw/core/model_router.py +985 -0
  132. package/python/foxclaw/core/paths.py +103 -0
  133. package/python/foxclaw/core/recovery.py +349 -0
  134. package/python/foxclaw/core/scheduler.py +141 -0
  135. package/python/foxclaw/core/secrets.py +131 -0
  136. package/python/foxclaw/core/sessions.py +155 -0
  137. package/python/foxclaw/core/settings.py +414 -0
  138. package/python/foxclaw/core/shared_write.py +186 -0
  139. package/python/foxclaw/core/steering_queue.py +154 -0
  140. package/python/foxclaw/core/system_bus.py +84 -0
  141. package/python/foxclaw/core/thought_chain.py +316 -0
  142. package/python/foxclaw/core/token_meter.py +231 -0
  143. package/python/foxclaw/core/tools.py +164 -0
  144. package/python/foxclaw/core/tracing.py +375 -0
  145. package/python/foxclaw/core/truth_pipeline.py +110 -0
  146. package/python/foxclaw/core/update_check.py +149 -0
  147. package/python/foxclaw/core/vec_recall_adapter.py +477 -0
  148. package/python/foxclaw/core/verify.py +173 -0
  149. package/python/foxclaw/core/web_search.py +218 -0
  150. package/python/foxclaw/finance/__init__.py +15 -0
  151. package/python/foxclaw/finance/evidence.py +149 -0
  152. package/python/foxclaw/finance/fx.py +98 -0
  153. package/python/foxclaw/finance/graph.py +179 -0
  154. package/python/foxclaw/finance/models.py +146 -0
  155. package/python/foxclaw/finance/nlparse.py +515 -0
  156. package/python/foxclaw/finance/policy.py +301 -0
  157. package/python/foxclaw/finance/reasoner.py +121 -0
  158. package/python/foxclaw/finance/reasoning.py +319 -0
  159. package/python/foxclaw/finance/reconcile.py +175 -0
  160. package/python/foxclaw/finance/runtime.py +500 -0
  161. package/python/foxclaw/governance/__init__.py +24 -0
  162. package/python/foxclaw/governance/middleware.py +176 -0
  163. package/python/foxclaw/harness/__init__.py +17 -0
  164. package/python/foxclaw/harness/_base.py +66 -0
  165. package/python/foxclaw/harness/_policy.py +340 -0
  166. package/python/foxclaw/harness/drift.py +77 -0
  167. package/python/foxclaw/harness/event_bus.py +28 -0
  168. package/python/foxclaw/harness/harness.py +358 -0
  169. package/python/foxclaw/harness/loop_detection.py +145 -0
  170. package/python/foxclaw/itinerary/__init__.py +10 -0
  171. package/python/foxclaw/itinerary/amap_client.py +114 -0
  172. package/python/foxclaw/itinerary/models.py +80 -0
  173. package/python/foxclaw/itinerary/reasoner.py +96 -0
  174. package/python/foxclaw/itinerary/reasoning.py +168 -0
  175. package/python/foxclaw/itinerary/runtime.py +144 -0
  176. package/python/foxclaw/kernel/__init__.py +13 -0
  177. package/python/foxclaw/kernel/capabilities.py +72 -0
  178. package/python/foxclaw/kernel/policy_gate.py +108 -0
  179. package/python/foxclaw/kernel/process_manager.py +186 -0
  180. package/python/foxclaw/kernel/scheduler.py +125 -0
  181. package/python/foxclaw/kernel/sentinel.py +443 -0
  182. package/python/foxclaw/kernel/sentinel_client.py +243 -0
  183. package/python/foxclaw/kernel/spine.py +97 -0
  184. package/python/foxclaw/knowledge/__init__.py +360 -0
  185. package/python/foxclaw/knowledge/truth_crystallizer.py +89 -0
  186. package/python/foxclaw/learning/__init__.py +12 -0
  187. package/python/foxclaw/learning/knowledge_graph.py +144 -0
  188. package/python/foxclaw/learning/models.py +93 -0
  189. package/python/foxclaw/learning/reasoner.py +67 -0
  190. package/python/foxclaw/learning/runtime.py +351 -0
  191. package/python/foxclaw/learning/spaced_repetition.py +91 -0
  192. package/python/foxclaw/mcp_server.py +188 -0
  193. package/python/foxclaw/orchestration/__init__.py +167 -0
  194. package/python/foxclaw/pipeline/__init__.py +23 -0
  195. package/python/foxclaw/pipeline/cognitive_pipeline.py +429 -0
  196. package/python/foxclaw/pipeline/stage_meta.py +21 -0
  197. package/python/foxclaw/pipeline/supervisor_stages.py +201 -0
  198. package/python/foxclaw/planning/__init__.py +17 -0
  199. package/python/foxclaw/planning/llm_planner.py +232 -0
  200. package/python/foxclaw/planning/planner.py +94 -0
  201. package/python/foxclaw/search/__init__.py +24 -0
  202. package/python/foxclaw/search/agent_port.py +190 -0
  203. package/python/foxclaw/search/evidence.py +109 -0
  204. package/python/foxclaw/search/external_search.py +50 -0
  205. package/python/foxclaw/search/hkc_read_port.py +60 -0
  206. package/python/foxclaw/search/internal_search.py +71 -0
  207. package/python/foxclaw/search/models.py +127 -0
  208. package/python/foxclaw/search/planner.py +44 -0
  209. package/python/foxclaw/search/retriever.py +39 -0
  210. package/python/foxclaw/search/runtime.py +127 -0
  211. package/python/foxclaw/search/strategy.py +44 -0
  212. package/python/foxclaw/skills/__init__.py +559 -0
  213. package/python/foxclaw/skills/archive.py +111 -0
  214. package/python/foxclaw/skills/fetch.py +226 -0
  215. package/python/foxclaw/skills/hooks_spec.py +69 -0
  216. package/python/foxclaw/skills/install_cmd.py +216 -0
  217. package/python/foxclaw/skills/lifecycle.py +252 -0
  218. package/python/foxclaw/skills/markdown_skill.py +175 -0
  219. package/python/foxclaw/skills/markdown_store.py +39 -0
  220. package/python/foxclaw/skills/mcp_client.py +184 -0
  221. package/python/foxclaw/skills/mcp_store.py +40 -0
  222. package/python/foxclaw/skills/permission.py +145 -0
  223. package/python/foxclaw/skills/pipeline.py +354 -0
  224. package/python/foxclaw/skills/policy.py +74 -0
  225. package/python/foxclaw/skills/review.py +72 -0
  226. package/python/foxclaw/skills/store.py +57 -0
  227. package/python/frontend/assets/core_bg.jpg +0 -0
  228. package/python/frontend/deck/auth.js +25 -0
  229. package/python/frontend/deck/chat_model_picker.js +483 -0
  230. package/python/frontend/deck/domain.js +276 -0
  231. package/python/frontend/deck/main.js +1806 -0
  232. package/python/frontend/deck/markdown.js +44 -0
  233. package/python/frontend/deck/settings.js +307 -0
  234. package/python/frontend/deck/state.js +5 -0
  235. package/python/frontend/deck/util.js +4 -0
  236. package/python/frontend/deck/visuals.js +190 -0
  237. package/python/frontend/deck.css +855 -0
  238. package/python/frontend/deck.html +686 -0
  239. package/python/frontend/deck_v2.html +341 -0
  240. package/python/frontend/planet/index.html +266 -0
  241. package/python/frontend/planet/planet.css +579 -0
  242. package/python/frontend/planet/planet.js +1436 -0
  243. package/python/frontend/planet/vendor/three.core.min.js +6 -0
  244. package/python/frontend/planet/vendor/three.module.min.js +6 -0
  245. package/python/frontend/v3/assets/index-CQSBdxk4.js +34 -0
  246. package/python/frontend/v3/assets/index-D5nIsjms.css +1 -0
  247. package/python/frontend/v3/index.html +15 -0
  248. package/python/frontend/widget_runtime.js +252 -0
  249. package/python/frontend/widgets.js +639 -0
  250. package/python/frontend_src/index.html +14 -0
  251. package/python/frontend_src/package-lock.json +1376 -0
  252. package/python/frontend_src/package.json +19 -0
  253. package/python/frontend_src/src/App.vue +58 -0
  254. package/python/frontend_src/src/api.js +82 -0
  255. package/python/frontend_src/src/components/ChatDock.vue +365 -0
  256. package/python/frontend_src/src/components/ComposerMenu.vue +75 -0
  257. package/python/frontend_src/src/components/DocViewer.vue +162 -0
  258. package/python/frontend_src/src/components/Inspector.vue +235 -0
  259. package/python/frontend_src/src/components/LeftRail.vue +415 -0
  260. package/python/frontend_src/src/components/MenuPopover.vue +128 -0
  261. package/python/frontend_src/src/components/MessageStream.vue +389 -0
  262. package/python/frontend_src/src/components/ModelPicker.vue +350 -0
  263. package/python/frontend_src/src/components/QuickIngest.vue +112 -0
  264. package/python/frontend_src/src/components/Stage.vue +272 -0
  265. package/python/frontend_src/src/components/ToolMenu.vue +141 -0
  266. package/python/frontend_src/src/components/TopBar.vue +118 -0
  267. package/python/frontend_src/src/components/panels/ActivityPanel.vue +82 -0
  268. package/python/frontend_src/src/components/panels/AgentsPanel.vue +83 -0
  269. package/python/frontend_src/src/components/panels/KnowledgePanel.vue +425 -0
  270. package/python/frontend_src/src/components/panels/MemoryPanel.vue +117 -0
  271. package/python/frontend_src/src/components/panels/PanelBox.vue +50 -0
  272. package/python/frontend_src/src/components/panels/ReviewPanel.vue +292 -0
  273. package/python/frontend_src/src/components/panels/SettingsPanel.vue +358 -0
  274. package/python/frontend_src/src/components/panels/TasksPanel.vue +73 -0
  275. package/python/frontend_src/src/components/panels/ToolsPanel.vue +746 -0
  276. package/python/frontend_src/src/components/panels/UsagePanel.vue +105 -0
  277. package/python/frontend_src/src/lib/fmt.js +44 -0
  278. package/python/frontend_src/src/lib/i18n.js +53 -0
  279. package/python/frontend_src/src/lib/locales/en.js +173 -0
  280. package/python/frontend_src/src/lib/locales/zh.js +174 -0
  281. package/python/frontend_src/src/lib/md.js +190 -0
  282. package/python/frontend_src/src/main.js +9 -0
  283. package/python/frontend_src/src/stores/app.js +91 -0
  284. package/python/frontend_src/src/stores/chat.js +450 -0
  285. package/python/frontend_src/src/stores/model.js +96 -0
  286. package/python/frontend_src/src/stores/panels.js +289 -0
  287. package/python/frontend_src/src/stores/profile.js +31 -0
  288. package/python/frontend_src/src/stores/system.js +25 -0
  289. package/python/frontend_src/src/styles/base.css +138 -0
  290. package/python/frontend_src/src/styles/panel.css +117 -0
  291. package/python/frontend_src/src/styles/tokens.css +78 -0
  292. package/python/frontend_src/vite.config.js +39 -0
  293. package/python/pyproject.toml +268 -0
  294. package/python/requirements.txt +311 -0
  295. package/python/skills/README.md +123 -0
  296. package/python/skills/execution-contract/SKILL.md +30 -0
  297. package/python/skills/general-assistant/SKILL.md +34 -0
  298. package/python/skills/planner/SKILL.md +33 -0
  299. package/python/skills/schedule-itinerary/SKILL.md +35 -0
  300. package/python/skills/skill-composition/SKILL.md +31 -0
  301. package/python/skills/skill-guard/SKILL.md +67 -0
  302. package/python/skills/skill-memory/SKILL.md +50 -0
  303. package/python/skills/skill-router/SKILL.md +35 -0
  304. package/python/tests/conftest.py +54 -0
  305. package/python/tests/run_all.py +200 -0
  306. package/python/tests/test_agent_lifecycle.py +326 -0
  307. package/python/tests/test_ahs_p2.py +393 -0
  308. package/python/tests/test_anthropic_tools.py +192 -0
  309. package/python/tests/test_api.py +97 -0
  310. package/python/tests/test_api_auth.py +79 -0
  311. package/python/tests/test_api_host_guard.py +69 -0
  312. package/python/tests/test_attachments.py +151 -0
  313. package/python/tests/test_audit_chain.py +116 -0
  314. package/python/tests/test_audit_sink.py +130 -0
  315. package/python/tests/test_browser.py +149 -0
  316. package/python/tests/test_browser_request_guard.py +180 -0
  317. package/python/tests/test_capabilities.py +152 -0
  318. package/python/tests/test_channel_signing.py +185 -0
  319. package/python/tests/test_channel_trust.py +109 -0
  320. package/python/tests/test_channels.py +174 -0
  321. package/python/tests/test_cli.py +46 -0
  322. package/python/tests/test_compaction_toolpair.py +119 -0
  323. package/python/tests/test_config_layering.py +61 -0
  324. package/python/tests/test_confirm_nonce.py +186 -0
  325. package/python/tests/test_context_compaction_wiring.py +124 -0
  326. package/python/tests/test_dispatch.py +89 -0
  327. package/python/tests/test_domain_evals.py +334 -0
  328. package/python/tests/test_domain_import.py +72 -0
  329. package/python/tests/test_domain_reasoners.py +134 -0
  330. package/python/tests/test_e2e.py +161 -0
  331. package/python/tests/test_emb_cache.py +97 -0
  332. package/python/tests/test_embedding_singleton.py +87 -0
  333. package/python/tests/test_envfile.py +83 -0
  334. package/python/tests/test_evals_smoke.py +90 -0
  335. package/python/tests/test_event_spine.py +174 -0
  336. package/python/tests/test_evidence_semantic.py +88 -0
  337. package/python/tests/test_evidence_sse.py +94 -0
  338. package/python/tests/test_file_ingest.py +135 -0
  339. package/python/tests/test_finance.py +144 -0
  340. package/python/tests/test_finance_ledger.py +245 -0
  341. package/python/tests/test_finance_persist.py +174 -0
  342. package/python/tests/test_gateway.py +125 -0
  343. package/python/tests/test_governance.py +421 -0
  344. package/python/tests/test_governance_audit.py +324 -0
  345. package/python/tests/test_governance_middleware.py +137 -0
  346. package/python/tests/test_hkc.py +268 -0
  347. package/python/tests/test_hkc_index_build_manager.py +306 -0
  348. package/python/tests/test_hkc_manifest_reuse.py +294 -0
  349. package/python/tests/test_hkc_search_event_sync.py +482 -0
  350. package/python/tests/test_import_path_guard.py +155 -0
  351. package/python/tests/test_injection_guard.py +193 -0
  352. package/python/tests/test_integration.py +117 -0
  353. package/python/tests/test_itinerary.py +100 -0
  354. package/python/tests/test_kee_semantic.py +84 -0
  355. package/python/tests/test_kernel.py +212 -0
  356. package/python/tests/test_learning.py +101 -0
  357. package/python/tests/test_llm_admin.py +145 -0
  358. package/python/tests/test_llm_planner.py +344 -0
  359. package/python/tests/test_markdown_skills.py +62 -0
  360. package/python/tests/test_markdown_skills_openclaw.py +66 -0
  361. package/python/tests/test_mcp_connectors.py +97 -0
  362. package/python/tests/test_mcp_guardian_discovery.py +87 -0
  363. package/python/tests/test_mcp_no_memory.py +43 -0
  364. package/python/tests/test_mcp_policy_gate.py +76 -0
  365. package/python/tests/test_mcp_server.py +92 -0
  366. package/python/tests/test_memory_recall.py +92 -0
  367. package/python/tests/test_metrics.py +58 -0
  368. package/python/tests/test_multi_chain.py +90 -0
  369. package/python/tests/test_multimodal.py +122 -0
  370. package/python/tests/test_negotiation.py +136 -0
  371. package/python/tests/test_orchestration.py +109 -0
  372. package/python/tests/test_orchestration_decoupled.py +103 -0
  373. package/python/tests/test_p3_p5_hardening.py +324 -0
  374. package/python/tests/test_parallel_dispatch.py +207 -0
  375. package/python/tests/test_pipeline.py +492 -0
  376. package/python/tests/test_plan_visible.py +86 -0
  377. package/python/tests/test_planner.py +88 -0
  378. package/python/tests/test_policy_gate.py +108 -0
  379. package/python/tests/test_profile.py +67 -0
  380. package/python/tests/test_readme_claims.py +163 -0
  381. package/python/tests/test_reasoner.py +170 -0
  382. package/python/tests/test_release_check.py +252 -0
  383. package/python/tests/test_resume_checkpoint.py +148 -0
  384. package/python/tests/test_routing.py +85 -0
  385. package/python/tests/test_scheduler.py +138 -0
  386. package/python/tests/test_search.py +194 -0
  387. package/python/tests/test_secrets.py +153 -0
  388. package/python/tests/test_semantic.py +69 -0
  389. package/python/tests/test_sessions.py +90 -0
  390. package/python/tests/test_settings.py +265 -0
  391. package/python/tests/test_shadow_learning.py +290 -0
  392. package/python/tests/test_shared_write.py +200 -0
  393. package/python/tests/test_skill_taint_gate.py +145 -0
  394. package/python/tests/test_skills.py +117 -0
  395. package/python/tests/test_skills_fetch.py +282 -0
  396. package/python/tests/test_stats_and_events.py +162 -0
  397. package/python/tests/test_streaming.py +55 -0
  398. package/python/tests/test_supervisor_pipeline.py +176 -0
  399. package/python/tests/test_supervisor_triage.py +102 -0
  400. package/python/tests/test_taint.py +112 -0
  401. package/python/tests/test_task_stream.py +74 -0
  402. package/python/tests/test_thinking_sse.py +66 -0
  403. package/python/tests/test_thinking_stream.py +76 -0
  404. package/python/tests/test_tool_center.py +113 -0
  405. package/python/tests/test_tool_parallel.py +113 -0
  406. package/python/tests/test_tool_params.py +99 -0
  407. package/python/tests/test_tool_use.py +229 -0
  408. package/python/tests/test_toplevel_concurrency.py +116 -0
  409. package/python/tests/test_tracing.py +256 -0
  410. package/python/tests/test_truth_crystallizer.py +125 -0
  411. package/python/tests/test_truth_flow.py +88 -0
  412. package/python/tests/test_update_check.py +95 -0
  413. package/python/tests/test_url_policy.py +53 -0
  414. package/python/tests/test_verify_evidence.py +212 -0
  415. package/python/tests/test_version_sync.py +100 -0
  416. package/python/tests/test_web_trigger.py +82 -0
  417. package/python/tools/check_faiss_type.py +30 -0
  418. package/python/tools/check_log.ps1 +38 -0
  419. package/python/tools/ivf_status.py +72 -0
  420. package/python/tools/mypy_baseline.txt +13 -0
  421. package/python/tools/mypy_ratchet.py +143 -0
  422. package/python/tools/pack.py +173 -0
  423. package/python/tools/release_check.py +349 -0
  424. package/python/tools/restart_foxclaw.ps1 +71 -0
  425. package/python/tools/shared_write_audit.py +190 -0
  426. package/python/tools/size_baseline.txt +28 -0
  427. package/python/tools/size_check.py +102 -0
  428. package/python/tools/strip_comments.py +228 -0
  429. package/python/tools/verify_env.bat +2 -0
  430. package/python/tools/verify_env.py +25 -0
  431. package/python/vendor/HMR_LICENSE +37 -0
  432. package/python/vendor/HMR_README.md +65 -0
  433. package/python/vendor/hkc/LICENSE +37 -0
  434. package/python/vendor/hkc/hkc_ace/__init__.py +0 -0
  435. package/python/vendor/hkc/hkc_ace/ace.py +457 -0
  436. package/python/vendor/hkc/hkc_ace/skill_taxonomy.json +465 -0
  437. package/python/vendor/hkc/hkc_api/__init__.py +0 -0
  438. package/python/vendor/hkc/hkc_api/container.py +416 -0
  439. package/python/vendor/hkc/hkc_api/ingest_jobs.py +103 -0
  440. package/python/vendor/hkc/hkc_api/main.py +157 -0
  441. package/python/vendor/hkc/hkc_api/routes/__init__.py +0 -0
  442. package/python/vendor/hkc/hkc_api/routes/ability.py +151 -0
  443. package/python/vendor/hkc/hkc_api/routes/config.py +51 -0
  444. package/python/vendor/hkc/hkc_api/routes/knowledge.py +630 -0
  445. package/python/vendor/hkc/hkc_api/routes/search.py +88 -0
  446. package/python/vendor/hkc/hkc_api/schemas.py +153 -0
  447. package/python/vendor/hkc/hkc_api/synthesis.py +179 -0
  448. package/python/vendor/hkc/hkc_core/__init__.py +0 -0
  449. package/python/vendor/hkc/hkc_core/graph/__init__.py +0 -0
  450. package/python/vendor/hkc/hkc_core/graph/base.py +188 -0
  451. package/python/vendor/hkc/hkc_core/graph/sqlite_store.py +789 -0
  452. package/python/vendor/hkc/hkc_core/models/__init__.py +0 -0
  453. package/python/vendor/hkc/hkc_core/models/enums.py +65 -0
  454. package/python/vendor/hkc/hkc_core/models/ku.py +307 -0
  455. package/python/vendor/hkc/hkc_core/utils/__init__.py +0 -0
  456. package/python/vendor/hkc/hkc_core/utils/id_gen.py +113 -0
  457. package/python/vendor/hkc/hkc_crystallizer/__init__.py +44 -0
  458. package/python/vendor/hkc/hkc_crystallizer/adapters.py +94 -0
  459. package/python/vendor/hkc/hkc_crystallizer/candidate.py +145 -0
  460. package/python/vendor/hkc/hkc_crystallizer/crystallizer.py +179 -0
  461. package/python/vendor/hkc/hkc_crystallizer/ingress.py +90 -0
  462. package/python/vendor/hkc/hkc_kde/__init__.py +0 -0
  463. package/python/vendor/hkc/hkc_kde/chunker.py +197 -0
  464. package/python/vendor/hkc/hkc_kde/extractor.py +623 -0
  465. package/python/vendor/hkc/hkc_kde/kde.py +298 -0
  466. package/python/vendor/hkc/hkc_kde/loaders/__init__.py +0 -0
  467. package/python/vendor/hkc/hkc_kde/loaders/ebook_loader.py +153 -0
  468. package/python/vendor/hkc/hkc_kde/loaders/office_loader.py +194 -0
  469. package/python/vendor/hkc/hkc_kde/loaders/pdf_loader.py +162 -0
  470. package/python/vendor/hkc/hkc_kde/loaders/text_loader.py +157 -0
  471. package/python/vendor/hkc/hkc_kde/loaders/web_loader.py +91 -0
  472. package/python/vendor/hkc/hkc_kde/models.py +74 -0
  473. package/python/vendor/hkc/hkc_kde/packager.py +329 -0
  474. package/python/vendor/hkc/hkc_kde/relation_disc.py +151 -0
  475. package/python/vendor/hkc/hkc_kee/__init__.py +0 -0
  476. package/python/vendor/hkc/hkc_kee/dedup.py +227 -0
  477. package/python/vendor/hkc/hkc_kee/fingerprint.py +106 -0
  478. package/python/vendor/hkc/hkc_kee/kee.py +541 -0
  479. package/python/vendor/hkc/hkc_kep/__init__.py +0 -0
  480. package/python/vendor/hkc/hkc_kep/event_bus.py +205 -0
  481. package/python/vendor/hkc/hkc_sdk/__init__.py +63 -0
  482. package/python/vendor/hkc/hkc_sdk/base.py +151 -0
  483. package/python/vendor/hkc/hkc_sdk/direct_client.py +153 -0
  484. package/python/vendor/hkc/hkc_sdk/exceptions.py +39 -0
  485. package/python/vendor/hkc/hkc_sdk/http_client.py +166 -0
  486. package/python/vendor/hkc/hkc_sdk/models.py +171 -0
  487. package/python/vendor/hkc/hkc_search/__init__.py +0 -0
  488. package/python/vendor/hkc/hkc_search/bm25.py +325 -0
  489. package/python/vendor/hkc/hkc_search/embedding_backends.py +374 -0
  490. package/python/vendor/hkc/hkc_search/graph_search.py +132 -0
  491. package/python/vendor/hkc/hkc_search/hybrid.py +331 -0
  492. package/python/vendor/hkc/hkc_search/index_build_manager.py +378 -0
  493. package/python/vendor/hkc/hkc_search/vector_search.py +484 -0
  494. package/python/vendor/hmr/__init__.py +0 -0
  495. package/python/vendor/hmr/core/__init__.py +0 -0
  496. package/python/vendor/hmr/core/hmr.py +684 -0
  497. package/python/vendor/hmr/core/models.py +310 -0
  498. package/python/vendor/hmr/engines/__init__.py +0 -0
  499. package/python/vendor/hmr/engines/evolution.py +710 -0
  500. package/python/vendor/hmr/engines/jit_compiler.py +472 -0
  501. package/python/vendor/hmr/engines/lifecycle.py +264 -0
  502. package/python/vendor/hmr/engines/policy.py +625 -0
  503. package/python/vendor/hmr/engines/recall.py +260 -0
  504. package/python/vendor/hmr/engines/runtime_state.py +158 -0
  505. package/python/vendor/hmr/engines/scheduler.py +323 -0
  506. package/python/vendor/hmr/engines/semantic.py +150 -0
  507. package/python/vendor/hmr/engines/temporal.py +261 -0
  508. package/python/vendor/hmr/engines/thought_chain.py +635 -0
  509. package/python/vendor/hmr/graph/__init__.py +0 -0
  510. package/python/vendor/hmr/graph/cwg.py +338 -0
  511. package/python/vendor/hmr/graph/memory_graph.py +530 -0
  512. package/python/vendor/hmr/storage/__init__.py +0 -0
  513. package/python/vendor/hmr/storage/memory_fs.py +300 -0
  514. package/python/vendor/hmr/storage/vector_store.py +520 -0
@@ -0,0 +1,218 @@
1
+ """
2
+ 联网搜索工具 —— 给 Agent 提供实时信息检索能力。
3
+
4
+ DeepSeek/OpenAI 等基础 API 不自带联网,本模块对接百度 AI 搜索
5
+ (千帆 ai_search,底层百度搜索 + ERNIE),国内访问稳定、每日有免费额度。
6
+ 百度 AI 搜索是"搜索+生成"一体接口:输入问题,它联网检索后直接产出
7
+ 带引用的实时答案,本模块取其答案作为"联网上下文"注入回 Agent 的模型。
8
+
9
+ 配置(在 .env):
10
+ BAIDU_SEARCH_KEY=bce-v3/ALTAK-xxx/xxx # 千帆 AppBuilder API Key
11
+ BAIDU_SEARCH_MODEL=ernie-4.5-turbo-32k # 可选,默认 ernie-3.5-8k
12
+ BAIDU_SEARCH_BASE=https://qianfan.baidubce.com/v2/ai_search # 可选
13
+
14
+ 降级策略:未配 key / 网络不通 / 失败 → 返回空,不影响主流程,
15
+ Agent 如实告知"暂未查到",不编造。
16
+ """
17
+ from __future__ import annotations
18
+ import os
19
+ import re
20
+ import json
21
+ import urllib.request
22
+ import urllib.error
23
+ from . import settings
24
+
25
+
26
+ TOPIC_TRIGGERS = [
27
+ "版本", "几个版本", "第几", "价格", "多少钱", "汇率", "股价", "新闻",
28
+ "发布", "上线", "更新到", "迭代", "排行", "排名", "天气",
29
+ "模型", "型号", "出了没", "发布没", "更新没", "新版",
30
+ "latest", "news", "version", "price", "models",
31
+ ]
32
+ TIME_WORDS = [
33
+ "最新", "现在", "目前", "今天", "今日", "昨天", "本周", "本月", "今年",
34
+ "最近", "当前", "today", "current", "now",
35
+ ]
36
+ PERSONAL_MARKERS = [
37
+ "支出", "收入", "预算", "交易", "账单", "花了", "消费", "记账", "结余", "余额",
38
+ "行程", "日程", "出行", "复习", "知识点", "学习计划", "记忆",
39
+ ]
40
+
41
+ SEARCH_TRIGGERS = TOPIC_TRIGGERS
42
+
43
+ _CJK_TRIGGERS = [k for k in SEARCH_TRIGGERS if not k.isascii()]
44
+ _ASCII_TRIGGERS = [k.lower() for k in SEARCH_TRIGGERS if k.isascii()]
45
+ _ASCII_RE = (
46
+ re.compile(r"\b(" + "|".join(re.escape(k) for k in _ASCII_TRIGGERS) + r")\b")
47
+ if _ASCII_TRIGGERS else None
48
+ )
49
+
50
+
51
+ def is_personal_query(query: str) -> bool:
52
+ """问的是不是**用户自己的数据**(账本/行程/学习/记忆)。
53
+
54
+ 单一真源:凡是"要不要把这个问题发到外部"的判断都用它 —— 联网增强(needs_search)、
55
+ 技能路由的外部技能闸,都必须走这里。教训:这条保护原先只写在 needs_search 里,
56
+ 结果技能派发默认开启后,「查一下最新的本月支出」照样把私人财务问题发去外部搜索
57
+ —— 同一个 bug 从没设防的旁路回来了。**保护必须放在共同咽喉,不能各写一份。**
58
+ """
59
+ if not query:
60
+ return False
61
+ return any(m in query.lower() for m in PERSONAL_MARKERS)
62
+
63
+
64
+ def needs_search(query: str) -> bool:
65
+ """是否值得为这个问题联网。宁可漏搜也不要错搜:
66
+ 错搜的代价是每次 ~22s + 付费调用(且答案本来就在本地);漏搜只是少一点时效信息。"""
67
+ if not query:
68
+ return False
69
+ q = query.lower()
70
+ if is_personal_query(q):
71
+ return False
72
+ if re.search(r"你[^,。?!]{0,8}模型", q):
73
+ return False
74
+ if any(k in q for k in _CJK_TRIGGERS):
75
+ return True
76
+ return bool(_ASCII_RE and _ASCII_RE.search(q))
77
+
78
+
79
+ def _key() -> str:
80
+ return os.environ.get("BAIDU_SEARCH_KEY", "").strip()
81
+
82
+
83
+ def _model() -> str:
84
+ return os.environ.get("BAIDU_SEARCH_MODEL", "ernie-3.5-8k").strip()
85
+
86
+
87
+ def _base() -> str:
88
+ return os.environ.get(
89
+ "BAIDU_SEARCH_BASE", "https://qianfan.baidubce.com/v2/ai_search"
90
+ ).rstrip("/")
91
+
92
+
93
+ def _timeout() -> int:
94
+ """读取超时(秒)。深度搜索较慢,默认 45s;可经 BAIDU_SEARCH_TIMEOUT 调。"""
95
+ return max(5, int(settings.get_safe("BAIDU_SEARCH_TIMEOUT")))
96
+
97
+
98
+ def _deep() -> bool:
99
+ """是否开启深度搜索(更全但更慢)。默认开;BAIDU_SEARCH_DEEP=0 关掉换速度。"""
100
+ return os.environ.get("BAIDU_SEARCH_DEEP", "1").strip() not in ("0", "false", "False", "")
101
+
102
+
103
+ def search_answer(query: str) -> dict:
104
+ """调用百度 AI 搜索,返回 {answer, references}。
105
+ answer=联网生成的实时答案文本;references=参考资料列表。失败返回空 dict。"""
106
+ key = _key()
107
+ if not key:
108
+ return {}
109
+ from .tracing import span as _span
110
+ with _span("web.search"):
111
+ return _search_answer_inner(query, key)
112
+
113
+
114
+ def _search_answer_inner(query: str, key: str) -> dict:
115
+ try:
116
+ payload = json.dumps({
117
+ "messages": [{"role": "user", "content": query}],
118
+ "stream": False,
119
+ "model": _model(),
120
+ "enable_deep_search": _deep(),
121
+ "enable_corner_markers": False,
122
+ }).encode("utf-8")
123
+ req = urllib.request.Request(
124
+ f"{_base()}/chat/completions",
125
+ data=payload,
126
+ headers={
127
+ "Content-Type": "application/json",
128
+ "Authorization": f"Bearer {key}",
129
+ },
130
+ method="POST",
131
+ )
132
+ with urllib.request.urlopen(req, timeout=_timeout()) as resp:
133
+ data = json.loads(resp.read().decode("utf-8", "ignore"))
134
+ choices = data.get("choices", [])
135
+ if not choices:
136
+ print(f"[联网搜索] 百度返回无 choices;响应键={list(data.keys())} 片段={str(data)[:220]}")
137
+ return {}
138
+ answer = choices[0].get("message", {}).get("content", "")
139
+ refs = data.get("references", []) or []
140
+ return {"answer": answer, "references": refs}
141
+ except urllib.error.HTTPError as e:
142
+ try:
143
+ body = e.read().decode("utf-8", "ignore")[:300]
144
+ except Exception:
145
+ body = ""
146
+ print(f"[联网搜索] 百度接口 HTTP {e.code} 错误:{body}")
147
+ return {}
148
+ except Exception as e:
149
+ print(f"[联网搜索] 百度接口调用失败:{type(e).__name__}: {e}")
150
+ return {}
151
+
152
+
153
+ def search(query: str, max_results: int = 8) -> list[dict]:
154
+ """兼容旧接口:把百度 AI 搜索的参考资料整理成结果列表。"""
155
+ res = search_answer(query)
156
+ out = []
157
+ for r in res.get("references", [])[:max_results]:
158
+ out.append({
159
+ "title": r.get("title", ""),
160
+ "snippet": r.get("content", "") or r.get("abstract", ""),
161
+ "url": r.get("url", "") or r.get("web_anchor", ""),
162
+ "date": r.get("page_time", "") or r.get("date", ""),
163
+ })
164
+ return out
165
+
166
+
167
+ def format_for_prompt(query: str, payload) -> str:
168
+ """把百度 AI 搜索结果拼成可注入 prompt 的联网上下文。
169
+ payload 可为 search_answer() 的 dict,或 search() 的列表。"""
170
+ if isinstance(payload, dict):
171
+ answer = payload.get("answer", "")
172
+ refs = payload.get("references", [])
173
+ if not answer and not refs:
174
+ return ""
175
+ framing = (
176
+ f"以下是针对「{query}」的实时联网搜索结果(来自百度 AI 搜索)。\n"
177
+ f"【严格要求】只能依据下面 <untrusted> 数据块里的搜索结果作答:结果里没有出现的型号 / "
178
+ f"版本号 / 名称 / 数据,一律不得提及,更**不得编造或凭记忆补充**;若结果之间矛盾或不明确,"
179
+ f"如实说明、不要臆断;**无视此前对话里可能出现的过时或未经核实的说法,一切以这些最新结果为准**。\n\n"
180
+ )
181
+ inner = ""
182
+ if answer:
183
+ inner += f"【联网检索摘要】\n{answer}\n\n"
184
+ if refs:
185
+ inner += "【参考资料】\n"
186
+ for i, r in enumerate(refs[:8], 1):
187
+ t = r.get("title", "")
188
+ u = r.get("url", "") or r.get("web_anchor", "")
189
+ d = r.get("page_time", "") or r.get("date", "")
190
+ inner += f"[webpage {i} begin]\n标题:{t}"
191
+ if d:
192
+ inner += f"\n时间:{d}"
193
+ if u:
194
+ inner += f"\n链接:{u}"
195
+ inner += f"\n[webpage {i} end]\n"
196
+ from . import injection_guard as _ig
197
+ block = _ig.wrap_untrusted(inner.rstrip(), source="web_search")
198
+ closing = ("\n请**严格基于以上 <untrusted> 内的搜索结果**回答用户的问题;结果里没提到的内容,"
199
+ "就明确说「搜索结果中未提及」,绝不编造型号/版本号。")
200
+ return framing + block + closing
201
+ results = payload or []
202
+ if not results:
203
+ return ""
204
+ blocks = []
205
+ for i, r in enumerate(results, 1):
206
+ seg = f"[webpage {i} begin]\n标题:{r.get('title','')}"
207
+ if r.get("date"):
208
+ seg += f"\n时间:{r['date']}"
209
+ seg += f"\n内容:{r.get('snippet','')}"
210
+ if r.get("url"):
211
+ seg += f"\n链接:{r['url']}"
212
+ seg += f"\n[webpage {i} end]"
213
+ blocks.append(seg)
214
+ return (
215
+ f"以下是针对「{query}」的实时联网搜索结果(请基于最新信息回答):\n\n"
216
+ + "\n\n".join(blocks)
217
+ + "\n\n请根据以上搜索结果回答用户的问题。"
218
+ )
@@ -0,0 +1,15 @@
1
+ """Foxclaw — Finance: 财务 Agent 的资金行为操作系统内核"""
2
+ from .models import (
3
+ Transaction, Budget, FinancialEntity,
4
+ FinancePolicyRule, PolicyVerdict,
5
+ )
6
+ from .reasoning import FinanceReasoning
7
+ from .policy import FinancePolicyEngine, DEFAULT_RULES
8
+ from .runtime import FinanceRuntime
9
+
10
+ __all__ = [
11
+ "Transaction", "Budget", "FinancialEntity",
12
+ "FinancePolicyRule", "PolicyVerdict",
13
+ "FinanceReasoning", "FinancePolicyEngine", "DEFAULT_RULES",
14
+ "FinanceRuntime",
15
+ ]
@@ -0,0 +1,149 @@
1
+ """
2
+ Foxclaw 财务子系统 — 结构化证据链 (Evidence Chain)
3
+
4
+ 借鉴 2026 年前沿金融 AI 的"可解释性铁律":一个只给原始分数(如 0.87)
5
+ 而无人类可读证据链的决策,被认为比没有 AI 更糟,因为无法被审计员复核。
6
+
7
+ 每个财务风险决策输出结构化的:
8
+ 风险分数 + 风险因子(每个带证据和权重)+ 缓解因素 + 决策理由 + 建议动作 + 置信度
9
+
10
+ 这与 Foxclaw 的 ThoughtChain 审计链天然契合 —— 证据链可直接沉淀为审计节点。
11
+ """
12
+ from __future__ import annotations
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime
15
+
16
+
17
+ @dataclass
18
+ class RiskFactor:
19
+ """单个风险因子:是什么、证据、权重。"""
20
+ factor: str
21
+ evidence: str
22
+ weight: float
23
+
24
+ def to_dict(self) -> dict:
25
+ return {"factor": self.factor, "evidence": self.evidence,
26
+ "weight": round(self.weight, 3)}
27
+
28
+
29
+ @dataclass
30
+ class EvidenceChain:
31
+ """结构化决策证据链 —— 财务决策的可审计输出。"""
32
+ decision_type: str
33
+ risk_score: float = 0.0
34
+ risk_factors: list = field(default_factory=list)
35
+ mitigating_factors: list = field(default_factory=list)
36
+ rationale: str = ""
37
+ recommended_action: str = ""
38
+ confidence: float = 0.0
39
+ additional_checks: list = field(default_factory=list)
40
+ created_at: str = field(default_factory=lambda: datetime.now().isoformat(timespec="seconds"))
41
+
42
+ def add_factor(self, factor: str, evidence: str, weight: float):
43
+ self.risk_factors.append(RiskFactor(factor, evidence, weight))
44
+ return self
45
+
46
+ def compute_risk(self) -> float:
47
+ """综合风险:饱和式聚合(避免多个小因子简单累加成假高危)。
48
+
49
+ 取最大单因子权重为基准 + 其余因子的衰减贡献,再减缓解,裁剪 [0,1]。
50
+ 这样"1个严重"比"3个轻微"风险更高,符合直觉。
51
+ """
52
+ if not self.risk_factors:
53
+ self.risk_score = 0.0
54
+ return 0.0
55
+ weights = sorted((f.weight for f in self.risk_factors), reverse=True)
56
+ score = weights[0]
57
+ for w in weights[1:]:
58
+ score += w * (1 - score) * 0.5
59
+ mitigation = min(0.2, 0.1 * len(self.mitigating_factors))
60
+ self.risk_score = max(0.0, min(1.0, round(score - mitigation, 3)))
61
+ return self.risk_score
62
+
63
+ def level(self) -> str:
64
+ """风险等级(供人快速判断)。"""
65
+ s = self.risk_score
66
+ return "high" if s >= 0.7 else "medium" if s >= 0.4 else "low"
67
+
68
+ def to_dict(self) -> dict:
69
+ return {
70
+ "decision_type": self.decision_type,
71
+ "risk_score": self.risk_score,
72
+ "risk_level": self.level(),
73
+ "risk_factors": [f.to_dict() for f in self.risk_factors],
74
+ "mitigating_factors": list(self.mitigating_factors),
75
+ "rationale": self.rationale,
76
+ "recommended_action": self.recommended_action,
77
+ "confidence": round(self.confidence, 3),
78
+ "additional_checks": list(self.additional_checks),
79
+ "created_at": self.created_at,
80
+ }
81
+
82
+ def to_thought_note(self) -> str:
83
+ """压缩成一句可塞进 ThoughtChain 的审计摘要。"""
84
+ factors = "; ".join(f"{f.factor}({f.weight})" for f in self.risk_factors[:3])
85
+ return (f"[财务决策·{self.decision_type}] 风险={self.risk_score}({self.level()}) "
86
+ f"| 因子: {factors} | 建议: {self.recommended_action}")
87
+
88
+
89
+ class FinanceExplainer:
90
+ """把财务原始判断转成结构化证据链。"""
91
+
92
+ @staticmethod
93
+ def explain_budget_risk(budget_status: list) -> EvidenceChain:
94
+ """预算风险 → 证据链。budget_status 为 budget_status() 的输出。"""
95
+ ec = EvidenceChain(decision_type="budget_risk", confidence=0.9)
96
+ over_budgets = []
97
+ near_budgets = []
98
+ for b in budget_status:
99
+ ratio = b.get("usage_ratio", 0)
100
+ cat = b.get("category", "?")
101
+ if ratio >= 1.0:
102
+ over = b.get("spent", 0) - b.get("monthly_limit", 0)
103
+ w = min(0.8, 0.45 + (ratio - 1.0) * 0.35)
104
+ ec.add_factor("超预算", f"{cat} 已用 {ratio*100:.0f}%,超支 ¥{over:.0f}",
105
+ weight=w)
106
+ over_budgets.append(cat)
107
+ elif ratio >= 0.8:
108
+ ec.add_factor("接近预算上限",
109
+ f"{cat} 已用 {ratio*100:.0f}%,接近上限", weight=0.25)
110
+ near_budgets.append(cat)
111
+ healthy = [b.get("category") for b in budget_status
112
+ if b.get("usage_ratio", 0) < 0.8]
113
+ if healthy:
114
+ ec.mitigating_factors.append(f"{len(healthy)} 个分类预算健康")
115
+ ec.compute_risk()
116
+ if over_budgets:
117
+ ec.rationale = f"{','.join(over_budgets)} 已超预算,需立即关注"
118
+ ec.recommended_action = f"削减 {over_budgets[0]} 支出或调整预算"
119
+ ec.additional_checks.append("检查是否有可取消的重复订阅")
120
+ elif near_budgets:
121
+ ec.rationale = f"{','.join(near_budgets)} 接近上限,建议放缓"
122
+ ec.recommended_action = "本月剩余时间控制相关分类支出"
123
+ else:
124
+ ec.rationale = "所有预算分类处于健康水平"
125
+ ec.recommended_action = "保持当前消费节奏"
126
+ return ec
127
+
128
+ @staticmethod
129
+ def explain_anomalies(anomalies: list) -> EvidenceChain:
130
+ """异常消费 → 证据链。anomalies 为 detect_anomalies() 的输出。"""
131
+ ec = EvidenceChain(decision_type="anomaly", confidence=0.85)
132
+ for a in anomalies[:5]:
133
+ z = a.get("z_score", 0)
134
+ w = min(0.6, 0.15 + z * 0.05)
135
+ ec.add_factor("异常大额支出",
136
+ f"{a.get('entity','?')} ¥{abs(a.get('amount',0)):.0f}"
137
+ f"({a.get('category','?')},偏离度 z={z})", weight=w)
138
+ ec.compute_risk()
139
+ if anomalies:
140
+ ec.rationale = f"检测到 {len(anomalies)} 笔异常支出,偏离历史模式"
141
+ ec.recommended_action = "核对这些交易是否本人操作,排查盗刷/误记"
142
+ ec.additional_checks.append("与银行流水对账确认")
143
+ if len(anomalies) >= 3:
144
+ ec.additional_checks.append("考虑是否近期消费习惯发生变化")
145
+ else:
146
+ ec.rationale = "未发现异常支出,消费模式稳定"
147
+ ec.recommended_action = "无需处理"
148
+ ec.confidence = 0.9
149
+ return ec
@@ -0,0 +1,98 @@
1
+ """本位币折算 —— 多币种记账的汇率表。
2
+
3
+ 为什么需要它:用户会说「花了 105 块」也会说「花了 100 美元」。如果两者都写进
4
+ `Transaction.amount` 再求和,100 美元会被当成 100 元 —— 预算、风控、现金流预测
5
+ 会一起错,而且错得看不出来。所以账本统一用**本位币(CNY)记账**,原币金额与币种
6
+ 另存,汇总时两种都能看。
7
+
8
+ 汇率是**静态参考价,不联网**:宁可给一个用户能改的明确数字,也不假装实时行情。
9
+ 用户可在 `finance_fx.json` 或 `/api/finance/fx` 里改成自己的记账汇率(比如当天
10
+ 刷卡的实际结算价,那才是真实成本)。
11
+ """
12
+
13
+ import json
14
+ from pathlib import Path
15
+
16
+ BASE_CURRENCY = "CNY"
17
+
18
+ DEFAULT_RATES = {
19
+ "CNY": 1.0,
20
+ "USD": 7.2,
21
+ "HKD": 0.92,
22
+ "EUR": 7.8,
23
+ "JPY": 0.048,
24
+ "GBP": 9.1,
25
+ "KRW": 0.0052,
26
+ "SGD": 5.3,
27
+ "AUD": 4.7,
28
+ "CAD": 5.2,
29
+ }
30
+
31
+
32
+ class FxTable:
33
+ """币种 → 本位币折算率,带落盘(原子写)。"""
34
+
35
+ def __init__(self, path: str | None = None):
36
+ self.path = Path(path) if path else None
37
+ self.rates = dict(DEFAULT_RATES)
38
+ self.note = "static"
39
+ self._load()
40
+
41
+ def _load(self):
42
+ if not self.path or not self.path.exists():
43
+ return
44
+ try:
45
+ data = json.loads(self.path.read_text(encoding="utf-8"))
46
+ rates = data.get("rates") if isinstance(data, dict) else None
47
+ if isinstance(rates, dict):
48
+ for k, v in rates.items():
49
+ try:
50
+ self.rates[str(k).upper()] = float(v)
51
+ except (TypeError, ValueError):
52
+ continue
53
+ if data.get("note"):
54
+ self.note = data["note"]
55
+ except Exception:
56
+ pass
57
+
58
+ def save(self) -> bool:
59
+ if not self.path:
60
+ return False
61
+ try:
62
+ self.path.parent.mkdir(parents=True, exist_ok=True)
63
+ tmp = self.path.with_suffix(".tmp")
64
+ tmp.write_text(json.dumps({"base": BASE_CURRENCY, "note": self.note,
65
+ "rates": self.rates},
66
+ ensure_ascii=False, indent=1), encoding="utf-8")
67
+ tmp.replace(self.path)
68
+ return True
69
+ except Exception:
70
+ return False
71
+
72
+ def rate(self, currency: str) -> float:
73
+ """取折算率。未知币种返回 1.0,由调用方标注「按 1:1 暂记」。"""
74
+ if not currency:
75
+ return 1.0
76
+ return float(self.rates.get(str(currency).upper(), 1.0))
77
+
78
+ def known(self, currency: str) -> bool:
79
+ return str(currency or "").upper() in self.rates
80
+
81
+ def to_base(self, amount: float, currency: str = BASE_CURRENCY) -> tuple:
82
+ """原币 → (本位币金额, 折算率)。"""
83
+ r = self.rate(currency)
84
+ return round(float(amount) * r, 2), r
85
+
86
+ def set_rate(self, currency: str, rate: float) -> dict:
87
+ cur = str(currency or "").upper().strip()
88
+ if not cur or rate is None or float(rate) <= 0:
89
+ raise ValueError("币种与汇率都必须有效(汇率 > 0)")
90
+ self.rates[cur] = round(float(rate), 6)
91
+ self.note = "user"
92
+ self.save()
93
+ return self.snapshot()
94
+
95
+ def snapshot(self) -> dict:
96
+ return {"base": BASE_CURRENCY, "note": self.note,
97
+ "rates": dict(sorted(self.rates.items())),
98
+ "path": str(self.path) if self.path else None}
@@ -0,0 +1,179 @@
1
+ """
2
+ Foxclaw 财务子系统 — 财务数据图 (Financial Data Graph)
3
+
4
+ 借鉴 2026 年企业级财务 Agent 的核心设计:不把推理建在孤立记录上,而是先把
5
+ 财务数据连接、归一化成一张可审计的关系图,让推理基于"关系"而非"孤立记录"。
6
+
7
+ 适配 Foxclaw 个人/Agent 级:把交易、分类、商户、账户、预算关联成图,支持
8
+ 关系型查询(这笔超支由谁造成、关联哪些交易、影响哪个账户),与 HMR 关系图呼应。
9
+
10
+ 节点类型:transaction / category / entity(商户) / account / budget
11
+ 边:交易→分类、交易→商户、交易→账户、预算→分类(预算监管该分类)
12
+ """
13
+ from __future__ import annotations
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass, field
16
+
17
+
18
+ @dataclass
19
+ class GraphNode:
20
+ node_id: str
21
+ node_type: str
22
+ label: str
23
+ attrs: dict = field(default_factory=dict)
24
+
25
+ def to_dict(self) -> dict:
26
+ return {"id": self.node_id, "type": self.node_type,
27
+ "label": self.label, "attrs": self.attrs}
28
+
29
+
30
+ @dataclass
31
+ class GraphEdge:
32
+ src: str
33
+ dst: str
34
+ rel: str
35
+ attrs: dict = field(default_factory=dict)
36
+
37
+ def to_dict(self) -> dict:
38
+ return {"src": self.src, "dst": self.dst, "rel": self.rel,
39
+ "attrs": self.attrs}
40
+
41
+
42
+ class FinancialDataGraph:
43
+ """财务数据图:把散落的财务数据关联成可查询的图。"""
44
+
45
+ def __init__(self):
46
+ self.nodes: dict[str, GraphNode] = {}
47
+ self.edges: list[GraphEdge] = []
48
+ self._adj: dict[str, list] = defaultdict(list)
49
+ self._radj: dict[str, list] = defaultdict(list)
50
+
51
+ def _ensure_node(self, node_id: str, node_type: str, label: str, **attrs):
52
+ if node_id not in self.nodes:
53
+ self.nodes[node_id] = GraphNode(node_id, node_type, label, dict(attrs))
54
+ else:
55
+ self.nodes[node_id].attrs.update(attrs)
56
+ return self.nodes[node_id]
57
+
58
+ def _add_edge(self, src: str, dst: str, rel: str, **attrs):
59
+ e = GraphEdge(src, dst, rel, dict(attrs))
60
+ self.edges.append(e)
61
+ self._adj[src].append(e)
62
+ self._radj[dst].append(e)
63
+
64
+ def build(self, transactions: list, budgets: list | None = None):
65
+ """从交易 + 预算构建图。"""
66
+ self.nodes.clear(); self.edges.clear()
67
+ self._adj.clear(); self._radj.clear()
68
+
69
+ for t in transactions:
70
+ tid = f"txn:{t.id}"
71
+ self._ensure_node(tid, "transaction", f"{t.entity} ¥{abs(t.amount):.0f}",
72
+ amount=t.amount, timestamp=t.timestamp,
73
+ is_expense=t.is_expense)
74
+ cat_id = f"cat:{t.category}"
75
+ cnode = self._ensure_node(cat_id, "category", t.category)
76
+ if t.is_expense:
77
+ cnode.attrs["total"] = cnode.attrs.get("total", 0) + abs(t.amount)
78
+ cnode.attrs["count"] = cnode.attrs.get("count", 0) + 1
79
+ else:
80
+ cnode.attrs["income"] = cnode.attrs.get("income", 0) + abs(t.amount)
81
+ self._add_edge(tid, cat_id, "belongs_to")
82
+ ent_id = f"ent:{t.entity}"
83
+ enode = self._ensure_node(ent_id, "entity", t.entity)
84
+ if t.is_expense:
85
+ enode.attrs["total"] = enode.attrs.get("total", 0) + abs(t.amount)
86
+ enode.attrs["count"] = enode.attrs.get("count", 0) + 1
87
+ self._add_edge(tid, ent_id, "paid_to")
88
+ acc_id = f"acc:{t.account}"
89
+ self._ensure_node(acc_id, "account", t.account)
90
+ self._add_edge(tid, acc_id, "charged_on")
91
+
92
+ for b in (budgets or []):
93
+ bid = f"bud:{b.category}"
94
+ self._ensure_node(bid, "budget", f"{b.category}预算",
95
+ monthly_limit=b.monthly_limit, spent=b.spent)
96
+ cat_id = f"cat:{b.category}"
97
+ if cat_id in self.nodes:
98
+ self._add_edge(bid, cat_id, "monitors")
99
+ return self
100
+
101
+ def neighbors(self, node_id: str, rel: str | None = None) -> list:
102
+ """出边邻居(可按关系过滤)。"""
103
+ return [self.nodes[e.dst] for e in self._adj.get(node_id, [])
104
+ if rel is None or e.rel == rel]
105
+
106
+ def transactions_of(self, node_id: str) -> list:
107
+ """某节点(分类/商户/账户)关联的所有交易。"""
108
+ return [self.nodes[e.src] for e in self._radj.get(node_id, [])
109
+ if self.nodes[e.src].node_type == "transaction"]
110
+
111
+ def top_entities_in_category(self, category: str, top: int = 3) -> list:
112
+ """某分类下,按消费额排名的商户 —— 回答'这个分类的钱花在谁身上'。"""
113
+ cat_id = f"cat:{category}"
114
+ txns = self.transactions_of(cat_id)
115
+ by_entity: defaultdict[str, float] = defaultdict(float)
116
+ for t in txns:
117
+ if not t.attrs.get("is_expense"):
118
+ continue
119
+ for e in self._adj.get(t.node_id, []):
120
+ if e.rel == "paid_to":
121
+ by_entity[self.nodes[e.dst].label] += abs(t.attrs.get("amount", 0))
122
+ ranked = sorted(by_entity.items(), key=lambda x: -x[1])[:top]
123
+ return [{"entity": name, "amount": round(amt, 2)} for name, amt in ranked]
124
+
125
+ def trace_overspend(self, category: str) -> dict:
126
+ """追溯某分类超支的成因 —— 图的核心价值:回答'谁造成了超支'。"""
127
+ cat_id = f"cat:{category}"
128
+ bud_id = f"bud:{category}"
129
+ if cat_id not in self.nodes:
130
+ return {"category": category, "found": False}
131
+ cat = self.nodes[cat_id]
132
+ spent = cat.attrs.get("total", 0)
133
+ limit = self.nodes[bud_id].attrs.get("monthly_limit") if bud_id in self.nodes else None
134
+ contributors = self.top_entities_in_category(category, top=3)
135
+ result = {
136
+ "category": category, "found": True,
137
+ "total_spent": round(spent, 2),
138
+ "budget_limit": limit,
139
+ "is_over": (limit is not None and spent > limit),
140
+ "top_contributors": contributors,
141
+ "transaction_count": cat.attrs.get("count", 0),
142
+ }
143
+ if contributors:
144
+ top = contributors[0]
145
+ result["primary_driver"] = (
146
+ f"{top['entity']} 贡献了 ¥{top['amount']:.0f}"
147
+ f"({top['amount']/spent*100:.0f}%)" if spent else top["entity"])
148
+ return result
149
+
150
+ def account_exposure(self) -> list:
151
+ """各账户的支出敞口 —— 回答'钱主要从哪个账户流出'。"""
152
+ out = []
153
+ for nid, node in self.nodes.items():
154
+ if node.node_type != "account":
155
+ continue
156
+ txns = self.transactions_of(nid)
157
+ total = sum(abs(t.attrs.get("amount", 0)) for t in txns
158
+ if t.attrs.get("is_expense"))
159
+ out.append({"account": node.label, "outflow": round(total, 2),
160
+ "transaction_count": len(txns)})
161
+ return sorted(out, key=lambda x: -x["outflow"])
162
+
163
+ def stats(self) -> dict:
164
+ by_type: defaultdict[str, int] = defaultdict(int)
165
+ for n in self.nodes.values():
166
+ by_type[n.node_type] += 1
167
+ return {"nodes": len(self.nodes), "edges": len(self.edges),
168
+ "by_type": dict(by_type)}
169
+
170
+ def to_dict(self, max_nodes: int = 200) -> dict:
171
+ """导出图(供前端可视化或调试)。"""
172
+ nodes = list(self.nodes.values())[:max_nodes]
173
+ node_ids = {n.node_id for n in nodes}
174
+ return {
175
+ "nodes": [n.to_dict() for n in nodes],
176
+ "edges": [e.to_dict() for e in self.edges
177
+ if e.src in node_ids and e.dst in node_ids],
178
+ "stats": self.stats(),
179
+ }