foxclaw 0.1.0 → 0.1.2
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.
- package/README.md +54 -29
- package/bin/foxclaw.cjs +51 -0
- package/index.js +11 -10
- package/package.json +46 -38
- package/python/.dockerignore +35 -0
- package/python/.env.example +165 -0
- package/python/.gitattributes +46 -0
- package/python/.github/workflows/ci.yml +122 -0
- package/python/.github/workflows/release.yml +183 -0
- package/python/Dockerfile +64 -0
- package/python/LICENSE +21 -0
- package/python/MANIFEST.in +14 -0
- package/python/README.md +192 -0
- package/python/README_CN.md +324 -0
- package/python/bench/bm25_audit.py +199 -0
- package/python/bench/bm25_regression.py +178 -0
- package/python/bench/bm25_stress.py +159 -0
- package/python/bench/cd_audit.py +238 -0
- package/python/bench/chaos.py +142 -0
- package/python/bench/concurrency.py +103 -0
- package/python/bench/e2e_real_models.py +95 -0
- package/python/bench/llm_retry_test.py +248 -0
- package/python/bench/load_test.py +196 -0
- package/python/bench/vector_ivf_upgrade.py +134 -0
- package/python/docs/CHANNELS.md +195 -0
- package/python/docs/GOVERNANCE.md +164 -0
- package/python/docs/RELEASE.md +109 -0
- package/python/docs/RUN.md +75 -0
- package/python/docs/RUN_CN.md +121 -0
- package/python/docs//351/205/215/347/275/256/346/214/207/345/215/227.md +152 -0
- package/python/evals/__init__.py +0 -0
- package/python/evals/governance/README.md +61 -0
- package/python/evals/governance/__init__.py +0 -0
- package/python/evals/governance/cases.py +152 -0
- package/python/evals/governance/compare_embeddings.py +94 -0
- package/python/evals/governance/convergence.svg +11 -0
- package/python/evals/governance/report.json +371 -0
- package/python/evals/governance/run_evals.py +400 -0
- package/python/examples/governance_middleware_demo.py +77 -0
- package/python/examples/langgraph_governance_demo.py +108 -0
- package/python/examples/sample_itinerary.csv +6 -0
- package/python/examples/sample_knowledge.csv +9 -0
- package/python/examples/sample_transactions.csv +14 -0
- package/python/foxclaw/__init__.py +526 -0
- package/python/foxclaw/agents/__init__.py +12 -0
- package/python/foxclaw/agents/agents.py +35 -0
- package/python/foxclaw/agents/base.py +865 -0
- package/python/foxclaw/agents/impl/__init__.py +1 -0
- package/python/foxclaw/agents/impl/_helpers.py +78 -0
- package/python/foxclaw/agents/impl/finance.py +248 -0
- package/python/foxclaw/agents/impl/office.py +367 -0
- package/python/foxclaw/agents/impl/supervisor.py +659 -0
- package/python/foxclaw/agents/mixins/_context.py +151 -0
- package/python/foxclaw/agents/mixins/augment.py +149 -0
- package/python/foxclaw/agents/mixins/llm.py +66 -0
- package/python/foxclaw/agents/mixins/memory.py +35 -0
- package/python/foxclaw/agents/mixins/preference.py +81 -0
- package/python/foxclaw/agents/mixins/prompt.py +77 -0
- package/python/foxclaw/agents/mixins/skillbox.py +58 -0
- package/python/foxclaw/agents/mixins/tool_exec.py +443 -0
- package/python/foxclaw/api/__init__.py +283 -0
- package/python/foxclaw/api/app.py +123 -0
- package/python/foxclaw/api/middleware.py +317 -0
- package/python/foxclaw/api/routes/ahs.py +417 -0
- package/python/foxclaw/api/routes/attachments.py +117 -0
- package/python/foxclaw/api/routes/browser.py +39 -0
- package/python/foxclaw/api/routes/domain.py +314 -0
- package/python/foxclaw/api/routes/knowledge.py +163 -0
- package/python/foxclaw/api/routes/llm_admin.py +461 -0
- package/python/foxclaw/api/routes/memory.py +89 -0
- package/python/foxclaw/api/routes/orchestration.py +41 -0
- package/python/foxclaw/api/routes/recovery.py +43 -0
- package/python/foxclaw/api/routes/review.py +275 -0
- package/python/foxclaw/api/routes/search.py +37 -0
- package/python/foxclaw/api/routes/system.py +327 -0
- package/python/foxclaw/api/routes/task.py +281 -0
- package/python/foxclaw/api/routes/ws.py +68 -0
- package/python/foxclaw/api/spine.py +55 -0
- package/python/foxclaw/browser/__init__.py +13 -0
- package/python/foxclaw/browser/action/__init__.py +1 -0
- package/python/foxclaw/browser/action/action_executor.py +54 -0
- package/python/foxclaw/browser/action/action_types.py +45 -0
- package/python/foxclaw/browser/action/action_verifier.py +68 -0
- package/python/foxclaw/browser/action/url_policy.py +147 -0
- package/python/foxclaw/browser/adapter/__init__.py +1 -0
- package/python/foxclaw/browser/adapter/base_adapter.py +23 -0
- package/python/foxclaw/browser/adapter/web_adapter.py +46 -0
- package/python/foxclaw/browser/driver/__init__.py +1 -0
- package/python/foxclaw/browser/driver/base_driver.py +61 -0
- package/python/foxclaw/browser/driver/playwright_driver.py +166 -0
- package/python/foxclaw/browser/perception/__init__.py +1 -0
- package/python/foxclaw/browser/perception/dom_extractor.py +43 -0
- package/python/foxclaw/browser/perception/element_indexer.py +57 -0
- package/python/foxclaw/browser/perception/semantic_reducer.py +33 -0
- package/python/foxclaw/browser/perception/snapshot.py +29 -0
- package/python/foxclaw/browser/service.py +148 -0
- package/python/foxclaw/browser/session/__init__.py +1 -0
- package/python/foxclaw/browser/session/session_manager.py +57 -0
- package/python/foxclaw/capability/__init__.py +12 -0
- package/python/foxclaw/capability/embedding_service.py +67 -0
- package/python/foxclaw/channels/__init__.py +140 -0
- package/python/foxclaw/channels/discord.py +184 -0
- package/python/foxclaw/channels/dispatcher.py +204 -0
- package/python/foxclaw/channels/feishu.py +225 -0
- package/python/foxclaw/channels/openclaw_bridge.py +156 -0
- package/python/foxclaw/channels/signing.py +187 -0
- package/python/foxclaw/channels/telegram.py +121 -0
- package/python/foxclaw/channels/weixin.py +225 -0
- package/python/foxclaw/cli.py +154 -0
- package/python/foxclaw/cognitive/__init__.py +4 -0
- package/python/foxclaw/cognitive/reasoner.py +82 -0
- package/python/foxclaw/cognitive/state.py +147 -0
- package/python/foxclaw/core/__init__.py +9 -0
- package/python/foxclaw/core/audit_chain.py +133 -0
- package/python/foxclaw/core/audit_sink.py +100 -0
- package/python/foxclaw/core/compaction.py +283 -0
- package/python/foxclaw/core/config.py +65 -0
- package/python/foxclaw/core/confirm_nonce.py +157 -0
- package/python/foxclaw/core/dispatch.py +27 -0
- package/python/foxclaw/core/envfile.py +48 -0
- package/python/foxclaw/core/failure_policy.py +151 -0
- package/python/foxclaw/core/gateway.py +85 -0
- package/python/foxclaw/core/governance_audit.py +175 -0
- package/python/foxclaw/core/idempotency.py +289 -0
- package/python/foxclaw/core/injection_guard.py +221 -0
- package/python/foxclaw/core/memory_adapter.py +516 -0
- package/python/foxclaw/core/metrics.py +89 -0
- package/python/foxclaw/core/model_router.py +1097 -0
- package/python/foxclaw/core/paths.py +103 -0
- package/python/foxclaw/core/recovery.py +362 -0
- package/python/foxclaw/core/scheduler.py +144 -0
- package/python/foxclaw/core/secrets.py +134 -0
- package/python/foxclaw/core/sessions.py +157 -0
- package/python/foxclaw/core/settings.py +430 -0
- package/python/foxclaw/core/shared_write.py +198 -0
- package/python/foxclaw/core/steering_queue.py +153 -0
- package/python/foxclaw/core/system_bus.py +84 -0
- package/python/foxclaw/core/thought_chain.py +318 -0
- package/python/foxclaw/core/token_meter.py +235 -0
- package/python/foxclaw/core/tools.py +172 -0
- package/python/foxclaw/core/tracing.py +390 -0
- package/python/foxclaw/core/truth_pipeline.py +114 -0
- package/python/foxclaw/core/vec_recall_adapter.py +503 -0
- package/python/foxclaw/core/verify.py +181 -0
- package/python/foxclaw/core/web_search.py +242 -0
- package/python/foxclaw/finance/__init__.py +15 -0
- package/python/foxclaw/finance/evidence.py +153 -0
- package/python/foxclaw/finance/fx.py +100 -0
- package/python/foxclaw/finance/graph.py +188 -0
- package/python/foxclaw/finance/models.py +150 -0
- package/python/foxclaw/finance/nlparse.py +575 -0
- package/python/foxclaw/finance/policy.py +329 -0
- package/python/foxclaw/finance/reasoner.py +129 -0
- package/python/foxclaw/finance/reasoning.py +340 -0
- package/python/foxclaw/finance/reconcile.py +180 -0
- package/python/foxclaw/finance/runtime.py +527 -0
- package/python/foxclaw/governance/__init__.py +24 -0
- package/python/foxclaw/governance/middleware.py +184 -0
- package/python/foxclaw/harness/__init__.py +17 -0
- package/python/foxclaw/harness/_base.py +72 -0
- package/python/foxclaw/harness/_policy.py +359 -0
- package/python/foxclaw/harness/drift.py +89 -0
- package/python/foxclaw/harness/event_bus.py +31 -0
- package/python/foxclaw/harness/harness.py +446 -0
- package/python/foxclaw/harness/loop_detection.py +152 -0
- package/python/foxclaw/itinerary/__init__.py +10 -0
- package/python/foxclaw/itinerary/amap_client.py +117 -0
- package/python/foxclaw/itinerary/models.py +80 -0
- package/python/foxclaw/itinerary/reasoner.py +101 -0
- package/python/foxclaw/itinerary/reasoning.py +174 -0
- package/python/foxclaw/itinerary/runtime.py +148 -0
- package/python/foxclaw/kernel/__init__.py +13 -0
- package/python/foxclaw/kernel/capabilities.py +73 -0
- package/python/foxclaw/kernel/policy_gate.py +114 -0
- package/python/foxclaw/kernel/process_manager.py +205 -0
- package/python/foxclaw/kernel/scheduler.py +131 -0
- package/python/foxclaw/kernel/sentinel.py +453 -0
- package/python/foxclaw/kernel/sentinel_client.py +246 -0
- package/python/foxclaw/kernel/spine.py +97 -0
- package/python/foxclaw/knowledge/__init__.py +376 -0
- package/python/foxclaw/knowledge/truth_crystallizer.py +92 -0
- package/python/foxclaw/learning/__init__.py +12 -0
- package/python/foxclaw/learning/knowledge_graph.py +149 -0
- package/python/foxclaw/learning/models.py +93 -0
- package/python/foxclaw/learning/reasoner.py +70 -0
- package/python/foxclaw/learning/runtime.py +363 -0
- package/python/foxclaw/learning/spaced_repetition.py +96 -0
- package/python/foxclaw/mcp_server.py +189 -0
- package/python/foxclaw/orchestration/__init__.py +184 -0
- package/python/foxclaw/pipeline/__init__.py +23 -0
- package/python/foxclaw/pipeline/cognitive_pipeline.py +481 -0
- package/python/foxclaw/pipeline/supervisor_stages.py +230 -0
- package/python/foxclaw/planning/__init__.py +17 -0
- package/python/foxclaw/planning/llm_planner.py +232 -0
- package/python/foxclaw/planning/planner.py +99 -0
- package/python/foxclaw/search/__init__.py +24 -0
- package/python/foxclaw/search/agent_port.py +194 -0
- package/python/foxclaw/search/evidence.py +113 -0
- package/python/foxclaw/search/external_search.py +50 -0
- package/python/foxclaw/search/hkc_read_port.py +60 -0
- package/python/foxclaw/search/internal_search.py +73 -0
- package/python/foxclaw/search/models.py +129 -0
- package/python/foxclaw/search/planner.py +44 -0
- package/python/foxclaw/search/retriever.py +39 -0
- package/python/foxclaw/search/runtime.py +134 -0
- package/python/foxclaw/search/strategy.py +44 -0
- package/python/foxclaw/skills/__init__.py +613 -0
- package/python/foxclaw/skills/hooks_spec.py +73 -0
- package/python/foxclaw/skills/lifecycle.py +278 -0
- package/python/foxclaw/skills/markdown_skill.py +174 -0
- package/python/foxclaw/skills/markdown_store.py +39 -0
- package/python/foxclaw/skills/mcp_client.py +190 -0
- package/python/foxclaw/skills/mcp_store.py +43 -0
- package/python/foxclaw/skills/permission.py +180 -0
- package/python/foxclaw/skills/pipeline.py +386 -0
- package/python/foxclaw/skills/policy.py +80 -0
- package/python/foxclaw/skills/review.py +72 -0
- package/python/foxclaw/skills/store.py +57 -0
- package/python/frontend/assets/core_bg.jpg +0 -0
- package/python/frontend/deck/auth.js +32 -0
- package/python/frontend/deck/chat_model_picker.js +537 -0
- package/python/frontend/deck/domain.js +296 -0
- package/python/frontend/deck/main.js +1950 -0
- package/python/frontend/deck/markdown.js +48 -0
- package/python/frontend/deck/settings.js +324 -0
- package/python/frontend/deck/state.js +6 -0
- package/python/frontend/deck/util.js +6 -0
- package/python/frontend/deck/visuals.js +212 -0
- package/python/frontend/deck.css +855 -0
- package/python/frontend/deck.html +686 -0
- package/python/frontend/deck_v2.html +341 -0
- package/python/frontend/planet/index.html +266 -0
- package/python/frontend/planet/planet.css +579 -0
- package/python/frontend/planet/planet.js +1637 -0
- package/python/frontend/planet/vendor/three.core.min.js +6 -0
- package/python/frontend/planet/vendor/three.module.min.js +6 -0
- package/python/frontend/v3/assets/index-BD7VPbMV.js +33 -0
- package/python/frontend/v3/assets/index-CAvnYWGH.css +1 -0
- package/python/frontend/v3/index.html +15 -0
- package/python/frontend/widget_runtime.js +295 -0
- package/python/frontend/widgets.js +696 -0
- package/python/frontend_src/index.html +14 -0
- package/python/frontend_src/package-lock.json +1376 -0
- package/python/frontend_src/package.json +19 -0
- package/python/frontend_src/src/App.vue +62 -0
- package/python/frontend_src/src/api.js +89 -0
- package/python/frontend_src/src/components/ChatDock.vue +377 -0
- package/python/frontend_src/src/components/ComposerMenu.vue +75 -0
- package/python/frontend_src/src/components/DocViewer.vue +171 -0
- package/python/frontend_src/src/components/Inspector.vue +241 -0
- package/python/frontend_src/src/components/LeftRail.vue +394 -0
- package/python/frontend_src/src/components/MenuPopover.vue +130 -0
- package/python/frontend_src/src/components/MessageStream.vue +401 -0
- package/python/frontend_src/src/components/ModelPicker.vue +355 -0
- package/python/frontend_src/src/components/QuickIngest.vue +118 -0
- package/python/frontend_src/src/components/Stage.vue +226 -0
- package/python/frontend_src/src/components/ToolMenu.vue +144 -0
- package/python/frontend_src/src/components/TopBar.vue +90 -0
- package/python/frontend_src/src/components/panels/ActivityPanel.vue +84 -0
- package/python/frontend_src/src/components/panels/AgentsPanel.vue +86 -0
- package/python/frontend_src/src/components/panels/KnowledgePanel.vue +441 -0
- package/python/frontend_src/src/components/panels/MemoryPanel.vue +118 -0
- package/python/frontend_src/src/components/panels/PanelBox.vue +51 -0
- package/python/frontend_src/src/components/panels/ReviewPanel.vue +308 -0
- package/python/frontend_src/src/components/panels/SettingsPanel.vue +254 -0
- package/python/frontend_src/src/components/panels/TasksPanel.vue +74 -0
- package/python/frontend_src/src/components/panels/ToolsPanel.vue +640 -0
- package/python/frontend_src/src/components/panels/UsagePanel.vue +105 -0
- package/python/frontend_src/src/lib/fmt.js +48 -0
- package/python/frontend_src/src/lib/md.js +204 -0
- package/python/frontend_src/src/main.js +7 -0
- package/python/frontend_src/src/stores/app.js +106 -0
- package/python/frontend_src/src/stores/chat.js +484 -0
- package/python/frontend_src/src/stores/model.js +104 -0
- package/python/frontend_src/src/stores/panels.js +330 -0
- package/python/frontend_src/src/styles/base.css +138 -0
- package/python/frontend_src/src/styles/panel.css +117 -0
- package/python/frontend_src/src/styles/tokens.css +78 -0
- package/python/frontend_src/vite.config.js +46 -0
- package/python/pyproject.toml +265 -0
- package/python/skills/README.md +123 -0
- package/python/skills/execution-contract/SKILL.md +30 -0
- package/python/skills/general-assistant/SKILL.md +34 -0
- package/python/skills/planner/SKILL.md +33 -0
- package/python/skills/schedule-itinerary/SKILL.md +35 -0
- package/python/skills/skill-composition/SKILL.md +31 -0
- package/python/skills/skill-guard/SKILL.md +67 -0
- package/python/skills/skill-memory/SKILL.md +50 -0
- package/python/skills/skill-router/SKILL.md +35 -0
- package/python/tests/conftest.py +76 -0
- package/python/tests/run_all.py +263 -0
- package/python/tests/test_agent_lifecycle.py +360 -0
- package/python/tests/test_ahs_p2.py +414 -0
- package/python/tests/test_anthropic_tools.py +206 -0
- package/python/tests/test_api.py +87 -0
- package/python/tests/test_api_auth.py +83 -0
- package/python/tests/test_api_host_guard.py +69 -0
- package/python/tests/test_attachments.py +167 -0
- package/python/tests/test_audit_chain.py +121 -0
- package/python/tests/test_audit_sink.py +136 -0
- package/python/tests/test_browser.py +153 -0
- package/python/tests/test_browser_request_guard.py +184 -0
- package/python/tests/test_capabilities.py +158 -0
- package/python/tests/test_channel_signing.py +192 -0
- package/python/tests/test_channel_trust.py +109 -0
- package/python/tests/test_channels.py +184 -0
- package/python/tests/test_cli.py +46 -0
- package/python/tests/test_compaction_toolpair.py +119 -0
- package/python/tests/test_config_layering.py +65 -0
- package/python/tests/test_confirm_nonce.py +197 -0
- package/python/tests/test_context_compaction_wiring.py +130 -0
- package/python/tests/test_dispatch.py +95 -0
- package/python/tests/test_domain_evals.py +403 -0
- package/python/tests/test_domain_import.py +78 -0
- package/python/tests/test_domain_reasoners.py +148 -0
- package/python/tests/test_e2e.py +178 -0
- package/python/tests/test_emb_cache.py +107 -0
- package/python/tests/test_embedding_singleton.py +89 -0
- package/python/tests/test_envfile.py +83 -0
- package/python/tests/test_evals_smoke.py +114 -0
- package/python/tests/test_event_spine.py +182 -0
- package/python/tests/test_evidence_semantic.py +101 -0
- package/python/tests/test_evidence_sse.py +97 -0
- package/python/tests/test_file_ingest.py +146 -0
- package/python/tests/test_finance.py +153 -0
- package/python/tests/test_finance_ledger.py +252 -0
- package/python/tests/test_finance_persist.py +178 -0
- package/python/tests/test_gateway.py +144 -0
- package/python/tests/test_governance.py +468 -0
- package/python/tests/test_governance_audit.py +359 -0
- package/python/tests/test_governance_middleware.py +143 -0
- package/python/tests/test_hkc.py +286 -0
- package/python/tests/test_hkc_index_build_manager.py +339 -0
- package/python/tests/test_hkc_manifest_reuse.py +317 -0
- package/python/tests/test_hkc_search_event_sync.py +533 -0
- package/python/tests/test_import_path_guard.py +161 -0
- package/python/tests/test_injection_guard.py +211 -0
- package/python/tests/test_integration.py +141 -0
- package/python/tests/test_itinerary.py +103 -0
- package/python/tests/test_kee_semantic.py +89 -0
- package/python/tests/test_kernel.py +222 -0
- package/python/tests/test_learning.py +110 -0
- package/python/tests/test_llm_admin.py +160 -0
- package/python/tests/test_llm_planner.py +366 -0
- package/python/tests/test_markdown_skills.py +73 -0
- package/python/tests/test_markdown_skills_openclaw.py +71 -0
- package/python/tests/test_mcp_connectors.py +109 -0
- package/python/tests/test_mcp_guardian_discovery.py +91 -0
- package/python/tests/test_mcp_no_memory.py +43 -0
- package/python/tests/test_mcp_policy_gate.py +77 -0
- package/python/tests/test_mcp_server.py +95 -0
- package/python/tests/test_memory_recall.py +95 -0
- package/python/tests/test_metrics.py +66 -0
- package/python/tests/test_multi_chain.py +102 -0
- package/python/tests/test_multimodal.py +135 -0
- package/python/tests/test_negotiation.py +146 -0
- package/python/tests/test_orchestration.py +119 -0
- package/python/tests/test_orchestration_decoupled.py +109 -0
- package/python/tests/test_p3_p5_hardening.py +338 -0
- package/python/tests/test_parallel_dispatch.py +215 -0
- package/python/tests/test_pipeline.py +533 -0
- package/python/tests/test_plan_visible.py +86 -0
- package/python/tests/test_planner.py +95 -0
- package/python/tests/test_policy_gate.py +109 -0
- package/python/tests/test_reasoner.py +185 -0
- package/python/tests/test_release_check.py +263 -0
- package/python/tests/test_resume_checkpoint.py +156 -0
- package/python/tests/test_routing.py +95 -0
- package/python/tests/test_scheduler.py +141 -0
- package/python/tests/test_search.py +204 -0
- package/python/tests/test_secrets.py +159 -0
- package/python/tests/test_semantic.py +78 -0
- package/python/tests/test_sessions.py +91 -0
- package/python/tests/test_settings.py +281 -0
- package/python/tests/test_shadow_learning.py +330 -0
- package/python/tests/test_shared_write.py +207 -0
- package/python/tests/test_skill_taint_gate.py +154 -0
- package/python/tests/test_skills.py +133 -0
- package/python/tests/test_stats_and_events.py +165 -0
- package/python/tests/test_streaming.py +60 -0
- package/python/tests/test_supervisor_pipeline.py +177 -0
- package/python/tests/test_supervisor_triage.py +108 -0
- package/python/tests/test_taint.py +117 -0
- package/python/tests/test_task_stream.py +85 -0
- package/python/tests/test_thinking_sse.py +67 -0
- package/python/tests/test_thinking_stream.py +76 -0
- package/python/tests/test_tool_center.py +129 -0
- package/python/tests/test_tool_parallel.py +113 -0
- package/python/tests/test_tool_params.py +103 -0
- package/python/tests/test_tool_use.py +242 -0
- package/python/tests/test_toplevel_concurrency.py +117 -0
- package/python/tests/test_tracing.py +290 -0
- package/python/tests/test_truth_crystallizer.py +127 -0
- package/python/tests/test_truth_flow.py +93 -0
- package/python/tests/test_url_policy.py +53 -0
- package/python/tests/test_verify_evidence.py +225 -0
- package/python/tests/test_version_sync.py +71 -0
- package/python/tests/test_web_trigger.py +99 -0
- package/python/tools/check_faiss_type.py +31 -0
- package/python/tools/check_log.ps1 +46 -0
- package/python/tools/ivf_status.py +72 -0
- package/python/tools/mypy_baseline.txt +5 -0
- package/python/tools/mypy_ratchet.py +97 -0
- package/python/tools/pack.py +178 -0
- package/python/tools/release_check.py +349 -0
- package/python/tools/restart_foxclaw.ps1 +74 -0
- package/python/tools/shared_write_audit.py +204 -0
- package/python/tools/size_baseline.txt +28 -0
- package/python/tools/size_check.py +102 -0
- package/python/tools/verify_env.bat +2 -0
- package/python/tools/verify_env.py +25 -0
- package/python/vendor/HMR_LICENSE +37 -0
- package/python/vendor/HMR_README.md +65 -0
- package/python/vendor/hkc/LICENSE +37 -0
- package/python/vendor/hkc/hkc_ace/__init__.py +0 -0
- package/python/vendor/hkc/hkc_ace/ace.py +457 -0
- package/python/vendor/hkc/hkc_ace/skill_taxonomy.json +465 -0
- package/python/vendor/hkc/hkc_api/__init__.py +0 -0
- package/python/vendor/hkc/hkc_api/container.py +416 -0
- package/python/vendor/hkc/hkc_api/ingest_jobs.py +103 -0
- package/python/vendor/hkc/hkc_api/main.py +157 -0
- package/python/vendor/hkc/hkc_api/routes/__init__.py +0 -0
- package/python/vendor/hkc/hkc_api/routes/ability.py +151 -0
- package/python/vendor/hkc/hkc_api/routes/config.py +51 -0
- package/python/vendor/hkc/hkc_api/routes/knowledge.py +630 -0
- package/python/vendor/hkc/hkc_api/routes/search.py +88 -0
- package/python/vendor/hkc/hkc_api/schemas.py +153 -0
- package/python/vendor/hkc/hkc_api/synthesis.py +179 -0
- package/python/vendor/hkc/hkc_core/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/graph/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/graph/base.py +188 -0
- package/python/vendor/hkc/hkc_core/graph/sqlite_store.py +789 -0
- package/python/vendor/hkc/hkc_core/models/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/models/enums.py +65 -0
- package/python/vendor/hkc/hkc_core/models/ku.py +307 -0
- package/python/vendor/hkc/hkc_core/utils/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/utils/id_gen.py +113 -0
- package/python/vendor/hkc/hkc_crystallizer/__init__.py +44 -0
- package/python/vendor/hkc/hkc_crystallizer/adapters.py +94 -0
- package/python/vendor/hkc/hkc_crystallizer/candidate.py +145 -0
- package/python/vendor/hkc/hkc_crystallizer/crystallizer.py +179 -0
- package/python/vendor/hkc/hkc_crystallizer/ingress.py +90 -0
- package/python/vendor/hkc/hkc_kde/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kde/chunker.py +197 -0
- package/python/vendor/hkc/hkc_kde/extractor.py +623 -0
- package/python/vendor/hkc/hkc_kde/kde.py +298 -0
- package/python/vendor/hkc/hkc_kde/loaders/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kde/loaders/ebook_loader.py +153 -0
- package/python/vendor/hkc/hkc_kde/loaders/office_loader.py +194 -0
- package/python/vendor/hkc/hkc_kde/loaders/pdf_loader.py +162 -0
- package/python/vendor/hkc/hkc_kde/loaders/text_loader.py +157 -0
- package/python/vendor/hkc/hkc_kde/loaders/web_loader.py +91 -0
- package/python/vendor/hkc/hkc_kde/models.py +74 -0
- package/python/vendor/hkc/hkc_kde/packager.py +329 -0
- package/python/vendor/hkc/hkc_kde/relation_disc.py +151 -0
- package/python/vendor/hkc/hkc_kee/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kee/dedup.py +227 -0
- package/python/vendor/hkc/hkc_kee/fingerprint.py +106 -0
- package/python/vendor/hkc/hkc_kee/kee.py +541 -0
- package/python/vendor/hkc/hkc_kep/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kep/event_bus.py +205 -0
- package/python/vendor/hkc/hkc_sdk/__init__.py +63 -0
- package/python/vendor/hkc/hkc_sdk/base.py +151 -0
- package/python/vendor/hkc/hkc_sdk/direct_client.py +153 -0
- package/python/vendor/hkc/hkc_sdk/exceptions.py +39 -0
- package/python/vendor/hkc/hkc_sdk/http_client.py +166 -0
- package/python/vendor/hkc/hkc_sdk/models.py +171 -0
- package/python/vendor/hkc/hkc_search/__init__.py +0 -0
- package/python/vendor/hkc/hkc_search/bm25.py +325 -0
- package/python/vendor/hkc/hkc_search/embedding_backends.py +374 -0
- package/python/vendor/hkc/hkc_search/graph_search.py +132 -0
- package/python/vendor/hkc/hkc_search/hybrid.py +331 -0
- package/python/vendor/hkc/hkc_search/index_build_manager.py +378 -0
- package/python/vendor/hkc/hkc_search/vector_search.py +484 -0
- package/python/vendor/hmr/__init__.py +0 -0
- package/python/vendor/hmr/core/__init__.py +0 -0
- package/python/vendor/hmr/core/hmr.py +684 -0
- package/python/vendor/hmr/core/models.py +310 -0
- package/python/vendor/hmr/engines/__init__.py +0 -0
- package/python/vendor/hmr/engines/evolution.py +710 -0
- package/python/vendor/hmr/engines/jit_compiler.py +472 -0
- package/python/vendor/hmr/engines/lifecycle.py +264 -0
- package/python/vendor/hmr/engines/policy.py +625 -0
- package/python/vendor/hmr/engines/recall.py +260 -0
- package/python/vendor/hmr/engines/runtime_state.py +158 -0
- package/python/vendor/hmr/engines/scheduler.py +323 -0
- package/python/vendor/hmr/engines/semantic.py +150 -0
- package/python/vendor/hmr/engines/temporal.py +261 -0
- package/python/vendor/hmr/engines/thought_chain.py +635 -0
- package/python/vendor/hmr/graph/__init__.py +0 -0
- package/python/vendor/hmr/graph/cwg.py +338 -0
- package/python/vendor/hmr/graph/memory_graph.py +530 -0
- package/python/vendor/hmr/storage/__init__.py +0 -0
- package/python/vendor/hmr/storage/memory_fs.py +300 -0
- package/python/vendor/hmr/storage/vector_store.py +520 -0
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Foxclaw 财务子系统 — Finance Runtime
|
|
3
|
+
把 记忆 + 推理 + Policy 串成一个可自治的财务内核。
|
|
4
|
+
执行层只做"建议 + 审批流",真正动钱的操作留接口、不自动执行。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import csv
|
|
8
|
+
import json
|
|
9
|
+
import threading
|
|
10
|
+
from dataclasses import fields
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .models import Transaction, Budget, FinancialEntity
|
|
15
|
+
from .reasoning import FinanceReasoning
|
|
16
|
+
from .policy import FinancePolicyEngine
|
|
17
|
+
from .graph import FinancialDataGraph
|
|
18
|
+
from .fx import FxTable
|
|
19
|
+
from .nlparse import CATEGORY_LABELS, parse as parse_expense_text
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _period_of(txn, default: str = "") -> str:
|
|
23
|
+
"""交易的账期(YYYY-MM)。时间戳坏掉时返回 default,不让一条脏数据炸掉整个汇总。"""
|
|
24
|
+
try:
|
|
25
|
+
return txn.timestamp[:7]
|
|
26
|
+
except Exception:
|
|
27
|
+
return default
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _coerce(cls, d):
|
|
31
|
+
"""按 dataclass 字段过滤后构造;缺必填字段/类型不符 → None。
|
|
32
|
+
|
|
33
|
+
只取认识的字段,是为了让**旧版本写下的文件**照样读得进来(多出的派生字段被忽略),
|
|
34
|
+
而不是一升级就整份数据作废。
|
|
35
|
+
"""
|
|
36
|
+
if not isinstance(d, dict):
|
|
37
|
+
return None
|
|
38
|
+
names = {f.name for f in fields(cls)}
|
|
39
|
+
try:
|
|
40
|
+
return cls(**{k: v for k, v in d.items() if k in names})
|
|
41
|
+
except (TypeError, ValueError):
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class FinanceRuntime:
|
|
46
|
+
"""财务 Agent 的资金行为操作系统内核。"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, policy_path: str = "./finance_policy.yaml", hmr=None,
|
|
49
|
+
data_path: str = None):
|
|
50
|
+
self.transactions: list = []
|
|
51
|
+
self.budgets: list = []
|
|
52
|
+
self.entities: dict = {} # name -> FinancialEntity
|
|
53
|
+
self.account_balances: dict = {} # account -> balance
|
|
54
|
+
self.policy = FinancePolicyEngine(policy_path)
|
|
55
|
+
self.reasoning = FinanceReasoning()
|
|
56
|
+
self.hmr = hmr # 可选:把交易写入 HMR 共享认知
|
|
57
|
+
# 交易/预算/余额/实体的落盘点:默认与 policy 同目录(调用方传的就是 data_dir)。
|
|
58
|
+
# 此前这些只在内存,进程一重启就清零 → 财务分析永远是"0 笔交易"。
|
|
59
|
+
self._data_path = Path(data_path) if data_path else (
|
|
60
|
+
Path(policy_path).resolve().parent / "finance_data.json")
|
|
61
|
+
# 写侧串行:runtime 是单例,请求线程会并发 add/import,analyze 还会触发阈值自校准写盘。
|
|
62
|
+
self._lock = threading.RLock()
|
|
63
|
+
self.load_error: str = ""
|
|
64
|
+
self.save_error: str = ""
|
|
65
|
+
# 多币种:账本按本位币(CNY)算账,汇率表与账本同目录
|
|
66
|
+
self.fx = FxTable(str(self._data_path.parent / "finance_fx.json"))
|
|
67
|
+
self.load()
|
|
68
|
+
|
|
69
|
+
# ── 持久化(原子写 tmp→replace;损坏文件只降级、不阻断启动)──────
|
|
70
|
+
def load(self) -> int:
|
|
71
|
+
"""从落盘点恢复交易/预算/余额/实体,返回恢复的交易条数。
|
|
72
|
+
|
|
73
|
+
容错原则:文件缺失/损坏/单条记录字段不合法一律跳过 —— 财务数据的问题
|
|
74
|
+
不该把整个内核(进而是 Agent 启动)拖下水,大不了退回"0 笔交易"并留下 load_error。
|
|
75
|
+
"""
|
|
76
|
+
self.transactions, self.budgets = [], []
|
|
77
|
+
self.entities, self.account_balances = {}, {}
|
|
78
|
+
self.load_error = ""
|
|
79
|
+
p = self._data_path
|
|
80
|
+
if not p.exists():
|
|
81
|
+
return 0
|
|
82
|
+
try:
|
|
83
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
84
|
+
except Exception as e:
|
|
85
|
+
self.load_error = f"{type(e).__name__}: {e}"
|
|
86
|
+
return 0
|
|
87
|
+
if not isinstance(data, dict):
|
|
88
|
+
self.load_error = "顶层不是 JSON 对象"
|
|
89
|
+
return 0
|
|
90
|
+
|
|
91
|
+
self.transactions = [t for t in (_coerce(Transaction, d)
|
|
92
|
+
for d in (data.get("transactions") or [])) if t]
|
|
93
|
+
self.budgets = [b for b in (_coerce(Budget, d)
|
|
94
|
+
for d in (data.get("budgets") or [])) if b]
|
|
95
|
+
ents = data.get("entities") or {}
|
|
96
|
+
if isinstance(ents, dict):
|
|
97
|
+
for name, d in ents.items():
|
|
98
|
+
ent = _coerce(FinancialEntity, d)
|
|
99
|
+
if ent is not None:
|
|
100
|
+
self.entities[name] = ent
|
|
101
|
+
bals = data.get("account_balances") or {}
|
|
102
|
+
if isinstance(bals, dict):
|
|
103
|
+
for acct, bal in bals.items():
|
|
104
|
+
try:
|
|
105
|
+
self.account_balances[acct] = float(bal)
|
|
106
|
+
except (TypeError, ValueError):
|
|
107
|
+
continue
|
|
108
|
+
if not self.entities and self.transactions:
|
|
109
|
+
self._rebuild_entities() # 实体段缺失(旧格式/被裁)→ 按交易重算
|
|
110
|
+
return len(self.transactions)
|
|
111
|
+
|
|
112
|
+
def save(self) -> bool:
|
|
113
|
+
"""把当前状态原子写盘。失败只记 save_error、返回 False,绝不抛异常。"""
|
|
114
|
+
with self._lock:
|
|
115
|
+
data = {
|
|
116
|
+
"version": 1,
|
|
117
|
+
"saved_at": datetime.now().isoformat(timespec="seconds"),
|
|
118
|
+
"transactions": [t.to_dict() for t in self.transactions],
|
|
119
|
+
"budgets": [b.to_dict() for b in self.budgets],
|
|
120
|
+
"entities": {n: e.to_dict() for n, e in self.entities.items()},
|
|
121
|
+
"account_balances": dict(self.account_balances),
|
|
122
|
+
}
|
|
123
|
+
try:
|
|
124
|
+
self._data_path.parent.mkdir(parents=True, exist_ok=True)
|
|
125
|
+
tmp = self._data_path.with_suffix(".tmp")
|
|
126
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False),
|
|
127
|
+
encoding="utf-8")
|
|
128
|
+
tmp.replace(self._data_path)
|
|
129
|
+
self.save_error = ""
|
|
130
|
+
# 文件已被本进程的完整快照覆盖 → 上一轮"读不进来"的原因作废(自愈)
|
|
131
|
+
self.load_error = ""
|
|
132
|
+
return True
|
|
133
|
+
except Exception as e:
|
|
134
|
+
# 落盘失败不能假装成功:留在内存里 + 暴露错误,让调用方/界面能看到
|
|
135
|
+
self.save_error = f"{type(e).__name__}: {e}"
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
def _rebuild_entities(self):
|
|
139
|
+
"""按已有交易重建实体统计(与 add_transaction 的累加规则一致)。"""
|
|
140
|
+
for txn in self.transactions:
|
|
141
|
+
ent = self.entities.get(txn.entity)
|
|
142
|
+
if not ent:
|
|
143
|
+
etype = "subscription" if txn.is_recurring else "merchant"
|
|
144
|
+
ent = FinancialEntity(name=txn.entity, entity_type=etype)
|
|
145
|
+
self.entities[txn.entity] = ent
|
|
146
|
+
ent.txn_count += 1
|
|
147
|
+
ent.total_amount += txn.amount
|
|
148
|
+
ent.last_seen = txn.timestamp
|
|
149
|
+
if txn.is_recurring:
|
|
150
|
+
ent.recurring_amount = abs(txn.amount)
|
|
151
|
+
|
|
152
|
+
# ── 数据录入 ──────────────────────────────────────────
|
|
153
|
+
def add_transaction(self, txn: Transaction,
|
|
154
|
+
run_gatekeeper: bool = True,
|
|
155
|
+
save: bool = True) -> dict:
|
|
156
|
+
"""录入一笔交易,经过守门人裁决,并落盘(save=False 供批量导入只写一次)。"""
|
|
157
|
+
with self._lock:
|
|
158
|
+
self.transactions.append(txn)
|
|
159
|
+
# 更新实体统计
|
|
160
|
+
ent = self.entities.get(txn.entity)
|
|
161
|
+
if not ent:
|
|
162
|
+
etype = "subscription" if txn.is_recurring else "merchant"
|
|
163
|
+
ent = FinancialEntity(name=txn.entity, entity_type=etype)
|
|
164
|
+
self.entities[txn.entity] = ent
|
|
165
|
+
ent.txn_count += 1
|
|
166
|
+
ent.total_amount += txn.amount
|
|
167
|
+
ent.last_seen = txn.timestamp
|
|
168
|
+
if txn.is_recurring:
|
|
169
|
+
ent.recurring_amount = abs(txn.amount)
|
|
170
|
+
|
|
171
|
+
# 写入 HMR(可选)
|
|
172
|
+
if self.hmr:
|
|
173
|
+
try:
|
|
174
|
+
self.hmr.ingest(
|
|
175
|
+
content=f"交易:{txn.entity} {txn.amount} ({txn.category})",
|
|
176
|
+
type="execution", agent_id="finance",
|
|
177
|
+
title=f"txn_{txn.entity}", tags=["transaction"] + txn.tags,
|
|
178
|
+
)
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
|
|
182
|
+
# 守门人裁决
|
|
183
|
+
verdicts = []
|
|
184
|
+
if run_gatekeeper:
|
|
185
|
+
bal = self.account_balances.get(txn.account)
|
|
186
|
+
verdicts = self.policy.evaluate_transaction(txn, bal)
|
|
187
|
+
result = {
|
|
188
|
+
"transaction": txn.to_dict(),
|
|
189
|
+
"verdicts": [v.to_dict() for v in verdicts],
|
|
190
|
+
"gated": any(v.action in ("veto", "freeze", "require_confirmation")
|
|
191
|
+
for v in verdicts),
|
|
192
|
+
}
|
|
193
|
+
# 写盘放在锁外:避免一次磁盘 IO 把并发进来的读请求全堵住
|
|
194
|
+
if save:
|
|
195
|
+
self.save()
|
|
196
|
+
return result
|
|
197
|
+
|
|
198
|
+
def set_budget(self, category: str, monthly_limit: float):
|
|
199
|
+
with self._lock:
|
|
200
|
+
self.budgets = [b for b in self.budgets if b.category != category]
|
|
201
|
+
self.budgets.append(Budget(category=category, monthly_limit=monthly_limit))
|
|
202
|
+
self.save()
|
|
203
|
+
|
|
204
|
+
def set_balance(self, account: str, balance: float):
|
|
205
|
+
with self._lock:
|
|
206
|
+
self.account_balances[account] = balance
|
|
207
|
+
self.save()
|
|
208
|
+
|
|
209
|
+
# ── 自然语言记账(第一线功能)────────────────────────────
|
|
210
|
+
def record_text(self, text: str, account: str = "default",
|
|
211
|
+
now: datetime = None, dry_run: bool = False) -> dict:
|
|
212
|
+
"""「今天买了一件衣服花了 105 块」→ 落一笔账,返回可读回执。
|
|
213
|
+
|
|
214
|
+
识别(金额/币种/时间/分类)全部走 `nlparse` 的确定性规则,LLM 不参与算钱。
|
|
215
|
+
未来时间(明天/下个月)记成 planned,进账本但不进"本月已花"。
|
|
216
|
+
"""
|
|
217
|
+
parsed = parse_expense_text(text, now=now)
|
|
218
|
+
if not parsed:
|
|
219
|
+
return {"recorded": [], "skipped": [{"text": (text or "").strip(),
|
|
220
|
+
"reason": "没识别出金额"}],
|
|
221
|
+
"dry_run": dry_run, "ack": "这句话里没听出金额,没有记账。"}
|
|
222
|
+
recorded = []
|
|
223
|
+
for p in parsed:
|
|
224
|
+
sign = -1 if p.direction == "expense" else 1
|
|
225
|
+
base, rate = self.fx.to_base(p.amount, p.currency)
|
|
226
|
+
tags = []
|
|
227
|
+
if p.planned:
|
|
228
|
+
tags.append("planned")
|
|
229
|
+
if p.direction == "income":
|
|
230
|
+
tags.append("income")
|
|
231
|
+
txn = Transaction(
|
|
232
|
+
amount=round(sign * base, 2),
|
|
233
|
+
category=p.category,
|
|
234
|
+
entity=p.entity or CATEGORY_LABELS.get(p.category, "未注明"),
|
|
235
|
+
account=account,
|
|
236
|
+
timestamp=p.when.isoformat(timespec="seconds"),
|
|
237
|
+
tags=tags,
|
|
238
|
+
note=p.text,
|
|
239
|
+
currency=p.currency,
|
|
240
|
+
original_amount=round(sign * p.amount, 2),
|
|
241
|
+
fx_rate=rate,
|
|
242
|
+
description=p.description,
|
|
243
|
+
status="planned" if p.planned else "settled",
|
|
244
|
+
source="text",
|
|
245
|
+
)
|
|
246
|
+
item = {**txn.to_dict(), "confidence": p.confidence,
|
|
247
|
+
"warnings": list(p.warnings)}
|
|
248
|
+
if not self.fx.known(p.currency):
|
|
249
|
+
item["warnings"].append(
|
|
250
|
+
f"未配置 {p.currency} 汇率,暂按 1:1 记入,可用 /api/finance/fx 设置")
|
|
251
|
+
if dry_run:
|
|
252
|
+
item["verdicts"] = []
|
|
253
|
+
else:
|
|
254
|
+
res = self.add_transaction(txn, run_gatekeeper=True, save=False)
|
|
255
|
+
item["verdicts"] = res["verdicts"]
|
|
256
|
+
recorded.append(item)
|
|
257
|
+
if recorded and not dry_run:
|
|
258
|
+
self.save()
|
|
259
|
+
result = {"recorded": recorded, "skipped": [], "dry_run": dry_run}
|
|
260
|
+
result["ack"] = self.render_ack(result)
|
|
261
|
+
return result
|
|
262
|
+
|
|
263
|
+
def render_ack(self, rec: dict) -> str:
|
|
264
|
+
"""把记账结果拼成人话。确定性文本 —— 记账回执不该等 LLM,也不该被它改写。"""
|
|
265
|
+
items = rec.get("recorded") or []
|
|
266
|
+
if not items:
|
|
267
|
+
return "这句话里没听出金额,没有记账。"
|
|
268
|
+
head = "预览(未落账)" if rec.get("dry_run") else "已记账"
|
|
269
|
+
lines = [f"{head} {len(items)} 笔:"]
|
|
270
|
+
for it in items:
|
|
271
|
+
cur = it.get("currency") or "CNY"
|
|
272
|
+
orig = it.get("amount_original") or 0.0
|
|
273
|
+
amt = it.get("amount") or 0.0
|
|
274
|
+
label = CATEGORY_LABELS.get(it.get("category"), it.get("category"))
|
|
275
|
+
flag = "(计划)" if it.get("status") == "planned" else ""
|
|
276
|
+
money = (f"{orig:+.2f} {cur}(≈¥{amt:+.2f})" if cur != "CNY"
|
|
277
|
+
else f"{amt:+.2f} 元")
|
|
278
|
+
day = (it.get("timestamp") or "")[:10]
|
|
279
|
+
lines.append(f"· {day} {it.get('description') or it.get('entity') or ''}"
|
|
280
|
+
f" {money} · {label}{flag}")
|
|
281
|
+
|
|
282
|
+
# 汇总期跟着这笔账走:记的是上月 5 号的账,就别报"本月已花"
|
|
283
|
+
period = (items[0].get("timestamp") or "")[:7] or None
|
|
284
|
+
led = self.ledger(period)
|
|
285
|
+
head = "本月" if period == datetime.now().strftime("%Y-%m") else f"{period} "
|
|
286
|
+
lines.append(f"{head}已花 ¥{led['expense']:.2f},共 {led['count']} 笔,"
|
|
287
|
+
f"净额 ¥{led['net']:+.2f}")
|
|
288
|
+
if led["planned"]["count"]:
|
|
289
|
+
lines.append(f"另有 {led['planned']['count']} 笔计划支出共 "
|
|
290
|
+
f"¥{led['planned']['expense']:.2f},发生时才算进已花")
|
|
291
|
+
gates = [v for it in items for v in (it.get("verdicts") or [])
|
|
292
|
+
if v.get("action") in ("veto", "freeze", "require_confirmation")]
|
|
293
|
+
for v in gates:
|
|
294
|
+
lines.append(f"守门人:{v.get('action')} — "
|
|
295
|
+
f"{v.get('message') or v.get('reason') or ''}")
|
|
296
|
+
warns = list(dict.fromkeys(w for it in items for w in (it.get("warnings") or [])))
|
|
297
|
+
if warns:
|
|
298
|
+
lines.append("提示:" + ";".join(warns))
|
|
299
|
+
return "\n".join(lines)
|
|
300
|
+
|
|
301
|
+
def ledger(self, period: str = None) -> dict:
|
|
302
|
+
"""记账本:按月汇总(已发生 vs 计划、按天、按分类、按币种)。"""
|
|
303
|
+
period = period or datetime.now().strftime("%Y-%m")
|
|
304
|
+
with self._lock:
|
|
305
|
+
txns = list(self.transactions)
|
|
306
|
+
settled = [t for t in txns
|
|
307
|
+
if not getattr(t, "is_planned", False) and _period_of(t) == period]
|
|
308
|
+
planned = sorted((t for t in txns if getattr(t, "is_planned", False)),
|
|
309
|
+
key=lambda t: t.timestamp)
|
|
310
|
+
|
|
311
|
+
expense = round(sum(t.amount for t in settled if t.amount < 0), 2)
|
|
312
|
+
income = round(sum(t.amount for t in settled if t.amount > 0), 2)
|
|
313
|
+
|
|
314
|
+
by_day, by_cat, by_cur = {}, {}, {}
|
|
315
|
+
for t in settled:
|
|
316
|
+
day = (t.timestamp or "")[:10]
|
|
317
|
+
d = by_day.setdefault(day, {"date": day, "expense": 0.0, "income": 0.0,
|
|
318
|
+
"count": 0, "items": []})
|
|
319
|
+
d["count"] += 1
|
|
320
|
+
if t.amount < 0:
|
|
321
|
+
d["expense"] = round(d["expense"] + t.amount, 2)
|
|
322
|
+
else:
|
|
323
|
+
d["income"] = round(d["income"] + t.amount, 2)
|
|
324
|
+
if len(d["items"]) < 6:
|
|
325
|
+
d["items"].append(t.description or t.entity)
|
|
326
|
+
|
|
327
|
+
if t.amount < 0:
|
|
328
|
+
c = by_cat.setdefault(t.category, {"category": t.category,
|
|
329
|
+
"label": CATEGORY_LABELS.get(t.category, t.category),
|
|
330
|
+
"total": 0.0, "count": 0})
|
|
331
|
+
c["total"] = round(c["total"] + t.amount, 2)
|
|
332
|
+
c["count"] += 1
|
|
333
|
+
|
|
334
|
+
cur = getattr(t, "currency", "CNY") or "CNY"
|
|
335
|
+
k = by_cur.setdefault(cur, {"currency": cur, "original_total": 0.0,
|
|
336
|
+
"base_total": 0.0, "count": 0})
|
|
337
|
+
k["original_total"] = round(k["original_total"] + t.amount_original, 2)
|
|
338
|
+
k["base_total"] = round(k["base_total"] + t.amount, 2)
|
|
339
|
+
k["count"] += 1
|
|
340
|
+
|
|
341
|
+
cat_total = abs(sum(c["total"] for c in by_cat.values())) or 1.0
|
|
342
|
+
categories = sorted(by_cat.values(), key=lambda c: c["total"])
|
|
343
|
+
for c in categories:
|
|
344
|
+
c["share"] = round(abs(c["total"]) / cat_total, 3)
|
|
345
|
+
c["total"] = round(abs(c["total"]), 2)
|
|
346
|
+
|
|
347
|
+
def _entry(t):
|
|
348
|
+
return {"id": t.id, "date": (t.timestamp or "")[:10],
|
|
349
|
+
"description": t.description or t.entity, "entity": t.entity,
|
|
350
|
+
"category": t.category,
|
|
351
|
+
"category_label": CATEGORY_LABELS.get(t.category, t.category),
|
|
352
|
+
"amount": t.amount, "currency": getattr(t, "currency", "CNY"),
|
|
353
|
+
"amount_original": t.amount_original,
|
|
354
|
+
"status": getattr(t, "status", "settled"),
|
|
355
|
+
"note": t.note}
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
"period": period,
|
|
359
|
+
"base_currency": "CNY",
|
|
360
|
+
"count": len(settled),
|
|
361
|
+
"expense": round(abs(expense), 2),
|
|
362
|
+
"income": round(income, 2),
|
|
363
|
+
"net": round(income + expense, 2),
|
|
364
|
+
"by_day": sorted(by_day.values(), key=lambda d: d["date"], reverse=True),
|
|
365
|
+
"by_category": sorted(categories, key=lambda c: -c["total"]),
|
|
366
|
+
"by_currency": sorted(by_cur.values(), key=lambda c: -abs(c["base_total"])),
|
|
367
|
+
"planned": {
|
|
368
|
+
"count": len(planned),
|
|
369
|
+
"expense": round(abs(sum(t.amount for t in planned if t.amount < 0)), 2),
|
|
370
|
+
"items": [_entry(t) for t in planned],
|
|
371
|
+
},
|
|
372
|
+
"entries": [_entry(t) for t in sorted(settled, key=lambda t: t.timestamp,
|
|
373
|
+
reverse=True)][:300],
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
def import_csv(self, path: str) -> int:
|
|
377
|
+
"""从 CSV 导入交易。列:amount,category,entity,account,timestamp,tags
|
|
378
|
+
真实银行 API 接口可在此处替换/扩展。"""
|
|
379
|
+
path = Path(path)
|
|
380
|
+
count = 0
|
|
381
|
+
with open(path, encoding="utf-8") as f:
|
|
382
|
+
reader = csv.DictReader(f)
|
|
383
|
+
for row in reader:
|
|
384
|
+
tags = [t.strip() for t in (row.get("tags") or "").split("|") if t.strip()]
|
|
385
|
+
# 可选的 currency 列:外币行按当天记账汇率折成本位币再入账,
|
|
386
|
+
# 否则「100 美元」会和「100 元」一起被求和。
|
|
387
|
+
cur = (row.get("currency") or row.get("币种") or "CNY").strip().upper()
|
|
388
|
+
raw = float(row["amount"])
|
|
389
|
+
base, rate = self.fx.to_base(abs(raw), cur)
|
|
390
|
+
txn = Transaction(
|
|
391
|
+
amount=round(-base if raw < 0 else base, 2),
|
|
392
|
+
category=row.get("category", "uncategorized"),
|
|
393
|
+
entity=row.get("entity", "unknown"),
|
|
394
|
+
account=row.get("account", "default"),
|
|
395
|
+
timestamp=row.get("timestamp") or datetime.now().isoformat(),
|
|
396
|
+
tags=tags,
|
|
397
|
+
currency=cur, original_amount=raw, fx_rate=rate,
|
|
398
|
+
description=row.get("description", ""),
|
|
399
|
+
source="csv",
|
|
400
|
+
)
|
|
401
|
+
self.add_transaction(txn, run_gatekeeper=False, save=False)
|
|
402
|
+
count += 1
|
|
403
|
+
if count:
|
|
404
|
+
self.save() # 批量导入只落盘一次,不按每笔交易各做一次磁盘 IO
|
|
405
|
+
return count
|
|
406
|
+
|
|
407
|
+
# ── 综合分析(财务 Agent 的核心输出)──────────────────
|
|
408
|
+
def analyze(self, period: str = None, current_balance: float = None,
|
|
409
|
+
calibrate: bool = True) -> dict:
|
|
410
|
+
"""一次性产出完整财务洞察:预算/风险/预测/守门人裁决。
|
|
411
|
+
|
|
412
|
+
calibrate=True 时先按用户自己的消费分布校准金额类阈值(样本不足则原样不动),
|
|
413
|
+
再裁决 —— 让阈值随消费水平自己长,而不是永远停在出厂拍的经验值上。
|
|
414
|
+
"""
|
|
415
|
+
period = period or datetime.now().strftime("%Y-%m")
|
|
416
|
+
# 快照:分析期间可能有并发录入(持久化后 import 端点就是可并发的写方),
|
|
417
|
+
# 直接遍历 self.transactions 会撞上 "list changed size during iteration"。
|
|
418
|
+
# 计划支出(明天/下个月)必须排除:还没发生的钱不能算进"本月已花",
|
|
419
|
+
# 否则「明天交房租 3000」会立刻把这个月的预算打爆。
|
|
420
|
+
txns = [t for t in self.transactions if not getattr(t, "is_planned", False)]
|
|
421
|
+
budgets = list(self.budgets)
|
|
422
|
+
bal = current_balance
|
|
423
|
+
if bal is None and self.account_balances:
|
|
424
|
+
bal = sum(dict(self.account_balances).values())
|
|
425
|
+
|
|
426
|
+
# 阈值自校准:必须在裁决**之前**,否则这次分析用的还是上一轮的旧阈值
|
|
427
|
+
calibration = (self.policy.apply_calibration(
|
|
428
|
+
self.reasoning.calibrate_thresholds(txns)) if calibrate else [])
|
|
429
|
+
|
|
430
|
+
budget_status = self.reasoning.budget_status(txns, budgets, period)
|
|
431
|
+
anomalies = self.reasoning.detect_anomalies(txns)
|
|
432
|
+
duplicates = self.reasoning.detect_duplicate_charges(txns)
|
|
433
|
+
sub_creep = self.reasoning.detect_subscription_creep(txns)
|
|
434
|
+
burn = self.reasoning.burn_rate(txns)
|
|
435
|
+
cashflow = (self.reasoning.cashflow_projection(txns, bal)
|
|
436
|
+
if bal is not None else None)
|
|
437
|
+
|
|
438
|
+
# 超支预测(对每个有预算的分类)—— 提到裁决之前算,好一并交给守门人
|
|
439
|
+
forecasts = [self.reasoning.overspend_forecast(txns, b, period)
|
|
440
|
+
for b in budgets]
|
|
441
|
+
renewals = self.reasoning.detect_upcoming_renewals(txns)
|
|
442
|
+
pending_refunds = self.reasoning.detect_pending_refunds(txns)
|
|
443
|
+
|
|
444
|
+
# 守门人对整体状态裁决
|
|
445
|
+
# duplicates/forecasts 此前已被算出来、却只进报告不进裁决(检测到了却不吭声);
|
|
446
|
+
# renewals/pending_refunds 为新增信号。现在一并交给守门人。
|
|
447
|
+
state_verdicts = self.policy.evaluate_state(
|
|
448
|
+
subscription_total=sub_creep["monthly_total"], anomalies=anomalies,
|
|
449
|
+
duplicates=duplicates, forecasts=forecasts,
|
|
450
|
+
renewals=renewals, pending_refunds=pending_refunds)
|
|
451
|
+
|
|
452
|
+
# 结构化证据链(可解释决策,可沉淀到 ThoughtChain)
|
|
453
|
+
from .evidence import FinanceExplainer
|
|
454
|
+
evidence_chains = [
|
|
455
|
+
FinanceExplainer.explain_budget_risk(budget_status).to_dict(),
|
|
456
|
+
FinanceExplainer.explain_anomalies(anomalies).to_dict(),
|
|
457
|
+
]
|
|
458
|
+
|
|
459
|
+
return {
|
|
460
|
+
"period": period,
|
|
461
|
+
"transaction_count": len(txns),
|
|
462
|
+
"budget_status": budget_status,
|
|
463
|
+
"overspend_forecast": forecasts,
|
|
464
|
+
"anomalies": anomalies,
|
|
465
|
+
"duplicate_charges": duplicates,
|
|
466
|
+
"subscription_creep": sub_creep,
|
|
467
|
+
"burn_rate": burn,
|
|
468
|
+
"cashflow_projection": cashflow,
|
|
469
|
+
"gatekeeper_verdicts": [v.to_dict() for v in state_verdicts],
|
|
470
|
+
"threshold_calibration": calibration, # 阈值自己变了要让用户看见,不能偷偷改
|
|
471
|
+
"evidence_chains": evidence_chains,
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
# ── 守门人审批流(不自动动钱)─────────────────────────
|
|
475
|
+
def request_action(self, action_type: str, detail: dict) -> dict:
|
|
476
|
+
"""请求一个资金操作(如取消订阅、转账)。
|
|
477
|
+
不自动执行——返回审批请求,标记需用户确认 / 需接真实支付 API。"""
|
|
478
|
+
return {
|
|
479
|
+
"action": action_type,
|
|
480
|
+
"detail": detail,
|
|
481
|
+
"status": "PENDING_USER_APPROVAL",
|
|
482
|
+
"note": "Foxclaw 不自动执行资金操作。请用户确认,或接入真实支付/银行 API 后执行。",
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
def status(self) -> dict:
|
|
486
|
+
return {
|
|
487
|
+
"transactions": len(self.transactions),
|
|
488
|
+
"budgets": len(self.budgets),
|
|
489
|
+
"entities": len(self.entities),
|
|
490
|
+
"accounts": self.account_balances,
|
|
491
|
+
"policy": self.policy.summary(),
|
|
492
|
+
# 落盘状态一并回给界面:否则"数据到底存哪了/为什么重启就没了"只能靠猜
|
|
493
|
+
"persist": {"path": str(self._data_path),
|
|
494
|
+
"exists": self._data_path.exists(),
|
|
495
|
+
"load_error": self.load_error,
|
|
496
|
+
"save_error": self.save_error},
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
def graph(self) -> "FinancialDataGraph":
|
|
500
|
+
"""构建财务数据图(交易/分类/商户/账户/预算关联)。"""
|
|
501
|
+
g = FinancialDataGraph()
|
|
502
|
+
g.build(self.transactions, self.budgets)
|
|
503
|
+
return g
|
|
504
|
+
|
|
505
|
+
def trace_category(self, category: str) -> dict:
|
|
506
|
+
"""关系查询:追溯某分类的消费成因(谁造成的、花在谁身上)。"""
|
|
507
|
+
return self.graph().trace_overspend(category)
|
|
508
|
+
|
|
509
|
+
def reconcile(self, external_records: list, tolerance_days: int = 3) -> dict:
|
|
510
|
+
"""对账:把系统交易与外部流水(银行/支付宝账单)交叉核对。
|
|
511
|
+
|
|
512
|
+
external_records: [ExternalRecord] 或 [dict(amount,entity,date,account,ref)]。
|
|
513
|
+
返回:匹配/差异分类 + 审计日志。
|
|
514
|
+
"""
|
|
515
|
+
from .reconcile import Reconciler, ExternalRecord
|
|
516
|
+
# 容忍 dict 输入,自动转 ExternalRecord
|
|
517
|
+
ext = []
|
|
518
|
+
for r in external_records:
|
|
519
|
+
if isinstance(r, ExternalRecord):
|
|
520
|
+
ext.append(r)
|
|
521
|
+
elif isinstance(r, dict):
|
|
522
|
+
ext.append(ExternalRecord(
|
|
523
|
+
amount=r.get("amount", 0), entity=r.get("entity", ""),
|
|
524
|
+
date=r.get("date", ""), account=r.get("account", ""),
|
|
525
|
+
ref=r.get("ref", "")))
|
|
526
|
+
rec = Reconciler(tolerance_days=tolerance_days)
|
|
527
|
+
return rec.reconcile(self.transactions, ext).to_dict()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Foxclaw Governance Middleware — 框架无关的 Agent 治理中间件(M3)。
|
|
3
|
+
|
|
4
|
+
把 Foxclaw 的护城河(可审计推理链 ThoughtChain + 三维漂移线束 Harness + 循环检测)
|
|
5
|
+
从整套系统里解耦出来,做成**任意 Agent 框架都能挂载的一层护栏**——
|
|
6
|
+
LangGraph / OpenAI Agents SDK / 自研 loop 都能用,无需构造 Foxclaw、
|
|
7
|
+
不依赖 agents / skills / channels / HMR 任何一块。
|
|
8
|
+
|
|
9
|
+
用法(三行接入):
|
|
10
|
+
from foxclaw.governance import GovernanceSession
|
|
11
|
+
with GovernanceSession(goal="分析本月理财", allowed_tools=["read","finance"]) as gov:
|
|
12
|
+
r = gov.observe("准备删库", tool="drop_table") # 越权 → r.blocked=True
|
|
13
|
+
audit = gov.audit() # 可审计推理链
|
|
14
|
+
|
|
15
|
+
见 docs/internal/GOVERNANCE_MIDDLEWARE.md。
|
|
16
|
+
"""
|
|
17
|
+
from .middleware import (
|
|
18
|
+
GovernanceSession,
|
|
19
|
+
GovResult,
|
|
20
|
+
GovernanceBlocked,
|
|
21
|
+
governed,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = ["GovernanceSession", "GovResult", "GovernanceBlocked", "governed"]
|