fusion-core 0.12.1__tar.gz
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.
- fusion_core-0.12.1/LICENSE +201 -0
- fusion_core-0.12.1/PKG-INFO +27 -0
- fusion_core-0.12.1/README.md +228 -0
- fusion_core-0.12.1/fusion_core/__init__.py +227 -0
- fusion_core-0.12.1/fusion_core/config.py +291 -0
- fusion_core-0.12.1/fusion_core/dsl_schema.py +150 -0
- fusion_core-0.12.1/fusion_core/errors.py +51 -0
- fusion_core-0.12.1/fusion_core/guard_client.py +432 -0
- fusion_core-0.12.1/fusion_core/http/__init__.py +5 -0
- fusion_core-0.12.1/fusion_core/http/app.py +245 -0
- fusion_core-0.12.1/fusion_core/http_client.py +391 -0
- fusion_core-0.12.1/fusion_core/logging.py +140 -0
- fusion_core-0.12.1/fusion_core/mcp-server-registry.json +28 -0
- fusion_core-0.12.1/fusion_core/mcp_client.py +112 -0
- fusion_core-0.12.1/fusion_core/mcp_registry.py +237 -0
- fusion_core-0.12.1/fusion_core/mlx_client.py +447 -0
- fusion_core-0.12.1/fusion_core/parse.py +91 -0
- fusion_core-0.12.1/fusion_core/proc.py +15 -0
- fusion_core-0.12.1/fusion_core/prompt.py +72 -0
- fusion_core-0.12.1/fusion_core/prompt_registry.py +206 -0
- fusion_core-0.12.1/fusion_core/tenant/__init__.py +39 -0
- fusion_core-0.12.1/fusion_core/tenant/context.py +56 -0
- fusion_core-0.12.1/fusion_core/tenant/deps.py +22 -0
- fusion_core-0.12.1/fusion_core/tenant/jwt_utils.py +62 -0
- fusion_core-0.12.1/fusion_core/tenant/middleware.py +162 -0
- fusion_core-0.12.1/fusion_core.egg-info/PKG-INFO +27 -0
- fusion_core-0.12.1/fusion_core.egg-info/SOURCES.txt +49 -0
- fusion_core-0.12.1/fusion_core.egg-info/dependency_links.txt +1 -0
- fusion_core-0.12.1/fusion_core.egg-info/requires.txt +23 -0
- fusion_core-0.12.1/fusion_core.egg-info/top_level.txt +1 -0
- fusion_core-0.12.1/pyproject.toml +80 -0
- fusion_core-0.12.1/setup.cfg +4 -0
- fusion_core-0.12.1/tests/test_config.py +247 -0
- fusion_core-0.12.1/tests/test_config_conventions.py +282 -0
- fusion_core-0.12.1/tests/test_dsl_schema.py +204 -0
- fusion_core-0.12.1/tests/test_errors.py +61 -0
- fusion_core-0.12.1/tests/test_guard_client.py +458 -0
- fusion_core-0.12.1/tests/test_http.py +267 -0
- fusion_core-0.12.1/tests/test_http_client.py +325 -0
- fusion_core-0.12.1/tests/test_llm.py +597 -0
- fusion_core-0.12.1/tests/test_llm_integration.py +194 -0
- fusion_core-0.12.1/tests/test_logging.py +185 -0
- fusion_core-0.12.1/tests/test_mcp_client.py +249 -0
- fusion_core-0.12.1/tests/test_mcp_registry.py +277 -0
- fusion_core-0.12.1/tests/test_metrics.py +155 -0
- fusion_core-0.12.1/tests/test_parse.py +129 -0
- fusion_core-0.12.1/tests/test_proc.py +41 -0
- fusion_core-0.12.1/tests/test_prompt.py +89 -0
- fusion_core-0.12.1/tests/test_prompt_registry.py +225 -0
- fusion_core-0.12.1/tests/test_tenant.py +301 -0
- fusion_core-0.12.1/tests/test_version.py +34 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated, in writing by the copyright owner, as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing the Work or
|
|
166
|
+
Derivative Works thereof, You may choose to offer, and charge a
|
|
167
|
+
fee for, acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 dahai80
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
200
|
+
implied. See the License for the specific language governing
|
|
201
|
+
permissions and limitations under the License.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fusion-core
|
|
3
|
+
Version: 0.12.1
|
|
4
|
+
Summary: Fusion-Core — public technical foundation for the Fusion ecosystem (LLM client, JSON parse, config, logging, FastAPI factory)
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: httpx<1.0,>=0.27.0
|
|
9
|
+
Provides-Extra: fastapi
|
|
10
|
+
Requires-Dist: fastapi>=0.110.0; extra == "fastapi"
|
|
11
|
+
Requires-Dist: uvicorn[standard]>=0.29.0; extra == "fastapi"
|
|
12
|
+
Requires-Dist: pydantic>=2.0.0; extra == "fastapi"
|
|
13
|
+
Provides-Extra: schema
|
|
14
|
+
Requires-Dist: jsonschema>=4.18.0; extra == "schema"
|
|
15
|
+
Provides-Extra: proc
|
|
16
|
+
Requires-Dist: setproctitle>=1.3.0; extra == "proc"
|
|
17
|
+
Provides-Extra: test
|
|
18
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
19
|
+
Requires-Dist: pytest-asyncio>=1.0.0; extra == "test"
|
|
20
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == "test"
|
|
21
|
+
Requires-Dist: pytest-mock>=3.14.0; extra == "test"
|
|
22
|
+
Requires-Dist: fastapi>=0.110.0; extra == "test"
|
|
23
|
+
Requires-Dist: httpx>=0.27.0; extra == "test"
|
|
24
|
+
Requires-Dist: jsonschema>=4.18.0; extra == "test"
|
|
25
|
+
Requires-Dist: setproctitle>=1.3.0; extra == "test"
|
|
26
|
+
Requires-Dist: ruff>=0.5.0; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
---
|
|
2
|
+
doc_id: fusion-core/readme
|
|
3
|
+
product: fusion-core
|
|
4
|
+
class: platform
|
|
5
|
+
entry: developer
|
|
6
|
+
doc_type: readme
|
|
7
|
+
title: {zh: "Fusion-Core 公共技术底座", en: "Fusion-Core shared technical foundation"}
|
|
8
|
+
audience: engineer
|
|
9
|
+
status: draft
|
|
10
|
+
version: 0.12.1
|
|
11
|
+
updated: 2026-11-07
|
|
12
|
+
owner: "@dahai"
|
|
13
|
+
source_of_truth:
|
|
14
|
+
- README.md
|
|
15
|
+
- pyproject.toml
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
# fusion-core
|
|
19
|
+
|
|
20
|
+
> Shared technical foundation for the Fusion ecosystem. Pure-tech, zero business logic.
|
|
21
|
+
>
|
|
22
|
+
> [中文文档](README_CN.md)
|
|
23
|
+
|
|
24
|
+
fusion-core is the common technical base shared by the 20+ Python domain projects in the Fusion ecosystem ("一核九端"). It eliminates 7+ duplicate LLM clients and 10+ copies of `_parse_json` by providing one well-tested implementation of each primitive: an LLM client, JSON parsing, config loading, logging, an httpx connection pool with retry, a FastAPI factory, prompt-template management, and a zero-trust guard client.
|
|
25
|
+
|
|
26
|
+
It depends on nothing Fusion-specific. `import fusion_core` triggers no I/O (no env read, no file read, no network connection) — safe to import anywhere.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install fusion-core # from PyPI (published automatically on stable tags, issue #52)
|
|
32
|
+
pip install -e fusion-core # from the monorepo tree — core (httpx only; zero business deps, no pydantic)
|
|
33
|
+
pip install -e "fusion-core[test]" # + test stack (pytest, ruff, fastapi, jsonschema)
|
|
34
|
+
pip install -e "fusion-core[fastapi]" # + fastapi, uvicorn, pydantic
|
|
35
|
+
pip install -e "fusion-core[schema]" # + jsonschema (for dsl_schema validation)
|
|
36
|
+
pip install -e "fusion-core[proc]" # + setproctitle (for set_process_title)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Requirements: Python >=3.12.
|
|
40
|
+
|
|
41
|
+
## 15 modules at a glance
|
|
42
|
+
|
|
43
|
+
| Module | Key symbols | Purpose |
|
|
44
|
+
|--------|-------------|---------|
|
|
45
|
+
| `mlx_client` | `FusionMLXClient`, `create_async_client(*, backend=)`, `LLMResponse`, `EmbeddingResponse`, `ServerStats`, `StreamError` | Unified MLX inference client (chat / embedding / stream). Default base_url `localhost:11434` (resolved at runtime from `FUSION_MLX_URL`; point it at fusion-gateway for multi-node). Retry delegated to `http_client`. `chat(total_deadline=)` is an explicit named param (R5) for the end-to-end budget; `**kwargs` allowlist-passes (`top_p`/`seed` etc.); `stream_chat` raises `StreamError(delivered=, resume_offset=)` for **all** stream-failure paths (mid-stream severed OR retriable-exhausted-no-output) so callers have ONE stream-failure type (H4/R4); non-retriable 4xx still raise the original `HTTPStatusError`; `create_async_client(model=...)` records a default model; `health()` reuses a `probe_client` with 1s throttle (no main-connection leak); `get_server_stats()` returns a `ServerStats` dataclass. Stream chunk parsing tolerates gateway terminator chunks: `{"choices": [null]}` or `delta: null` are skipped, not `AttributeError` (issue #44); `extra_body=` merges engine-specific payload fields verbatim (shallow merge, explicit params win on collision — issue #49) |
|
|
46
|
+
| `parse` | `parse_llm_json` (raises `ParseError`, no fallback), `parse_llm_json_safe` (explicit `default` required, must be dict/list), `parse_llm_json_lenient` (`raw_decode` extracts first object, scan cap 200k), `strip_code_fence` | Parse JSON from LLM output. **Failures are visible, never silent** |
|
|
47
|
+
| `config` | `load_settings` (mtime-invalidated cache), `resolve_api_key`, `load_api_key`, `get_env`, `default_mlx_base_url`, `clear_cache`, `client_key`, `admin_key`, `gateway_admin_key`, `profile`, `gateway_base_url`, `service_port`, `service_data_dir` | Lazy config load + api_key resolution + cache invalidation (settings file mtime change → cache miss). Since v0.7.0 also the **single-point resolution layer** for `architecture/config-conventions.md` (issues #31/#32): `client_key()` resolves `FUSION_CLIENT_KEY` → `FUSION_MLX_API_KEY` → `MLX_API_KEY` (legacy names warn); `admin_key()` reads `FUSION_ADMIN_KEY` (no aliases); `gateway_admin_key()` (issue #35) resolves `FUSION_GATEWAY_API_KEY` → settings.json `shell.gateway_admin_key` — the key the gateway actually accepts; `profile()` reads `FUSION_PROFILE` (dev = warn-once + `""`, prod = 3-part `RuntimeError`); `gateway_base_url()` defaults `http://127.0.0.1:11432`; `service_port(app, default)` / `service_data_dir(app, default)` read `FUSION_<APP>_PORT` / `_DATA_DIR` with the `fusion-` prefix stripped (issues #34/#36 — `"fusion-rag"` and `"rag"` resolve identically) and port-registry hints |
|
|
48
|
+
| `logging` | `setup_logging`, `get_logger` | Idempotent logging init (every `setLevel` applies; `propagate` defaults True so host root still receives logs; package-level `NullHandler` for library mode). Optional JSON format. `extra={}` fields rendered by both formatters (JSON: merged top-level; text: `key=value` suffix — issue #50); `root=True` attaches to the root logger for legacy-pattern migration (idempotent) |
|
|
49
|
+
| `http_client` | `get_async_client` (per-loop connection pool, `OrderedDict` LRU cap 8, evicts only same-loop keys), `gateway_circuit_breaker_ok` (probes gateway `/readyz`, H3/E4), `with_retry` (full jitter; `disable=` + `verify_gateway=` to hand retry off to gateway circuit breaker safely; `total_deadline=` end-to-end budget; exhausted → `RetryExhaustedError` / `RetryTimeoutError`), `close_all`, `close_all_sync`, `set_metrics_callback`, `get_metrics_snapshot`, `reset_metrics` | httpx async client pool + retry. Single source of truth for retry codes/exceptions: `RETRY_STATUS` / `RETRY_EXCEPTIONS` |
|
|
50
|
+
| `http` | `create_app`, `install_auth`, `standard_error_handler` | FastAPI app factory + pure-ASGI middleware (`install_auth` re-orders `user_middleware` so request_id is outermost — 401 carries the same id, H1/E1; SSE not truncated; auth keys encapsulated in the middleware instance, never on `app.state`; 422 and 500 sanitized equally; whitelist paths `rstrip`-normalized). `create_app(readiness_probe=)` mounts `/ready` (readiness, 200 ready / 503 not_ready, unauth) alongside `/health` (liveness) |
|
|
51
|
+
| `prompt` | `PromptManager` | Prompt-template management (engine only, no domain content; missing dir raises `FileNotFoundError`; **mtime-gated cache** — on-disk edits are picked up at runtime (mtime change invalidates the entry), `clear_cache()` forces a full refresh (E3)) |
|
|
52
|
+
| `guard_client` | `FusionGuardClient`, `GuardVerdict`, `GuardRule`, `RedactResult`, `ChainVerification`, `AllChainsVerification`, `GuardError` + 8 typed subclasses | Pure-Python UDS JSON-RPC 2.0 client for **fusion-guard** (the zero-trust action-authorization daemon). Newline-framed (`0x0A`, 1 MiB cap), 2 s default timeout, per-call reconnect-on-drop with one retry. Methods map 1:1 to `guard.ping` / `guard.evaluate` / `guard.rule.list` / `guard.redact` / `guard.reveal` / `guard.confirm` / `guard.tcc.status` / `guard.tcc.events` / `guard.audit.verify`. **Block verdicts are results, not errors** (E5) — `evaluate()` returns `GuardVerdict(action="block")`; RPC error codes map to typed exceptions (`GuardUnauthorizedError` -32001, `GuardRateLimitError` -32002, `StaleEpochError` -32003 carrying `caller_epoch`/`guard_epoch`, `GuardEngineError` -32010). Default socket `/tmp/fusion-guard.sock` resolved lazily at call time from `FUSION_GUARD_SOCK` (import = no I/O). Context-manager lifecycle; native `fg-pyo3` stays an optional fast path |
|
|
53
|
+
| `tenant` | `TenantContext`, `current`, `set_context`, `reset`, `has_scope`, `from_mapping`, `decode_jwt_claims`, `tenant_context_from_token`, `TenantMiddleware`, `install_tenant_middleware`, `get_tenant_dep` | L1 multi-tenant fabric. `TenantContext` (frozen-slots dataclass over `contextvars`) carries `tenant_id`/`user_id`/`role`/`jti`/`scopes` request-scoped; `TenantMiddleware` is a **fail-closed** ASGI middleware — exempt paths skip, missing `X-Tenant-Id` → 401, JWT `tid ≠ X-Tenant-Id` → 401, missing bearer when `require_jwt=True` → 401, binds context for the request then `reset()` in `finally` (no cross-request leak). `jwt_utils` does base64url decode + `exp` check with **no PyJWT dependency, no signature verify** — real signature verification is injected via the `verify_jwt` hook (sync or async; an awaitable return is awaited so a blocking verifier does not stall the event loop — issues #23/#24; lives in fusion-identity). **`authenticated` flag (issue #37)**: `True` only when a verified JWT produced claims — consumers write `if ctx and ctx.authenticated:` instead of reconstructing evidence from optional `role`/`jti`/`scopes` (anonymous contexts no longer mistakable for verified). `_JsonFormatter` auto-injects `tenant_id`/`user_id` from `current()` into log records. Trilingual mirror anchor (Python variant; Rust/Swift variants land in their own repos) |
|
|
54
|
+
| `prompt_registry` | `PromptVersionRegistry`, `PromptVersionRecord`, `compute_version_id`, `is_valid_version_id` | Immutable prompt-template versioning + replay (issue #28). Content-addressed `version_id` (16-hex sha256 of name+text) — edits create new versions, snapshots are write-once, every read re-verifies sha256 (tamper = `SnapshotIntegrityError`). `render(prompt_version, **vars)` re-materializes the exact prompt bytes (same `{{var}}` semantics as `PromptManager`); `replay(prompt_version, client)` re-runs it through an injected `FusionMLXClient` (point at gateway `:11432` for cluster). Storage = plain files: `versions/<id>.txt` + `index.json`, atomic writes. No new deps |
|
|
55
|
+
| `dsl_schema` | `SOCRATIC_DSL_V3_SCHEMA`, `validate_dsl`, `validate_dsl_str` | Canonical JSON Schema (Draft 2020-12) for the **Socratic DSL v3.0** — the shared contract across fusion-k12-teacher (generate), fusion-bench (evaluate), fusion-artifacts-engine (parse), fusion-trainer (sample validation). Enforces `meta` (id/grade/topic/visual_type/fallback_type), `parameters`, `entities`, `pipeline` with step required fields (`step/title/formula/eval/result_unit/visual_state`); `visual_type` enum (8 values: array_grid/tape_diagram/geometry_2d/isometric_3d/track_timeline/bucket_divider/data_chart/flow_card), `fallback_type` enum (2 values: tape_diagram/flow_card). `validate_dsl(dict) -> bool` and `validate_dsl_str(str) -> tuple[bool, str]` (parse + validate, returns error path). jsonschema is a lazy import inside validators — `import fusion_core` stays I/O-free; install `[schema]` extra to enable validation |
|
|
56
|
+
| `mcp_registry` | `load_registry` (mtime-invalidated cache), `resolve_server`, `check_approval`, `McpServerRecord`, `ApprovalVerdict` | MCP server registry — resolution layer for `architecture/mcp-server-registry-1029.md` (issue #40), mirroring how `config` resolves config-conventions. Platform single source of truth for which MCP tool servers are `approved` (status lifecycle proposed → reviewed → approved → deprecated; only approved may be referenced). JSON sidecar `architecture/mcp-server-registry.json` (stdlib json, zero new deps; mirrored as bundled `fusion_core/mcp-server-registry.json` for pip installs / CI — edit all three plus the md table). `check_approval(url, tool_scope)` returns a verdict — **result, not error** (E5 pattern): url-prefix match (same semantics as cowork `Permission.matches` `url:` scopes, trailing slashes normalized), **longest prefix wins**, non-approved status → denied, tool scope exact / `*` / `ns.*` wildcard, no url match → `unknown` (per-URL operator approval decides). Credential mode is declaration only (`identity_issuance` / `env_ref`) — no secrets stored, no network calls, no MCP client, no enforcement defaults (callers decide warn vs block). Malformed registry → `RegistryIntegrityError` (fail visibly). Default path from `FUSION_MCP_REGISTRY`, resolved lazily at call time |
|
|
57
|
+
| `mcp_client` | `McpToolClient`, `McpToolError`, `known_servers` | Thin stdio JSON-RPC client for MCP tool servers (issue #42), paired with `mcp_registry`: registry resolves *which* servers exist and are approved, client *calls* them. Pure move from ai-doc-automation. `known_servers()` returns `name -> McpServerRecord` for `proposed`/`approved` servers declaring a `stdio_command`; `McpToolClient.call_tool(tool, arguments, timeout_s=30)` speaks minimal JSON-RPC over stdio (initialize → `notifications/initialized` → `tools/call`), spawn-per-call, returns `{"ok": bool, "text": str, "raw": result}` — **`isError` is a result, not an error** (E5 pattern); transport/protocol/timeout failures raise `McpToolError`. `stdio_command.env` values with an `env:VAR` prefix resolve from the operator's environment at call time — credentials never stored in the registry. Registry path through `mcp_registry.default_registry_path()` (`FUSION_MCP_REGISTRY` env → monorepo sidecar → bundled copy). stdio only (no HTTP/SSE), no registry writes; import stays I/O-free |
|
|
58
|
+
| `errors` | `FusionError` | Shared error tree base (issue #47). Class-level defaults `code` / `http_status` / `remediation`, overridable per raise; structured `context` copied at construction; `to_http()` returns a sanitized `{status, code, message, remediation, context}` payload for API error handlers. Wrap upstream failures with `raise ... from` so the chain stays intact. Replaces private per-app error trees |
|
|
59
|
+
| `proc` | `set_process_title` | Process-title helper (issue #30). `setproctitle` is the only reliable title mechanism on macOS (Python.app overwrites `argv[0]`); **fail-open** — title is cosmetic, a missing `setproctitle` logs at DEBUG and never blocks service startup. Lazy import inside the function keeps `import fusion_core` I/O-free and `setproctitle` out of `sys.modules`; install `[proc]` extra to enable |
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
### LLM chat + JSON parse
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from fusion_core import create_async_client, parse_llm_json, get_logger
|
|
67
|
+
|
|
68
|
+
log = get_logger(__name__)
|
|
69
|
+
|
|
70
|
+
client = create_async_client(
|
|
71
|
+
base_url="http://localhost:11434",
|
|
72
|
+
api_key="...",
|
|
73
|
+
model="qwen2.5-7b",
|
|
74
|
+
)
|
|
75
|
+
resp = await client.chat(messages=[{"role": "user", "content": "Return JSON"}])
|
|
76
|
+
data = parse_llm_json(resp.content) # invalid JSON raises ParseError, not silent {}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Streaming (with mid-stream recovery envelope)
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
collected = []
|
|
83
|
+
try:
|
|
84
|
+
async for chunk in client.stream_chat(messages=[...]):
|
|
85
|
+
collected.append(chunk)
|
|
86
|
+
except StreamError as e:
|
|
87
|
+
# ALL stream-failure paths raise StreamError (H4/R4): mid-stream severed
|
|
88
|
+
# (e.delivered > 0) OR retriable-exhausted-no-output (e.delivered == 0).
|
|
89
|
+
# Non-retriable 4xx raise HTTPStatusError instead (bad request, not severed).
|
|
90
|
+
log.warning("stream severed after %d chars, resume at %d", e.delivered, e.resume_offset)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### End-to-end deadline
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
# total_deadline caps the whole retry budget, not just one request
|
|
97
|
+
resp = await client.chat(messages=[...], total_deadline=30.0)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Hand retry off to fusion-gateway (avoid double-retry)
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from fusion_core import with_retry
|
|
104
|
+
|
|
105
|
+
# when fusion-gateway's circuit breaker owns retry, disable core's own retry.
|
|
106
|
+
# verify_gateway=True probes gateway /readyz first; if the breaker is open or
|
|
107
|
+
# the gateway is unreachable, core falls back to its own retry (H3/E4 — no
|
|
108
|
+
# capability vacuum).
|
|
109
|
+
resp = await with_retry(fn, disable=True, verify_gateway=True)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### FastAPI factory
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from fusion_core.http import create_app, install_auth
|
|
116
|
+
|
|
117
|
+
# cors_credentials defaults False; "*" with credentials=True raises ValueError
|
|
118
|
+
app = create_app("my-svc", cors_origins=["https://example.com"], cors_credentials=True)
|
|
119
|
+
install_auth(app, api_keys=["secret"]) # request_id is outermost middleware; 401 also carries it
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Zero-trust guard client (fusion-guard)
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from fusion_core import FusionGuardClient
|
|
126
|
+
|
|
127
|
+
# default socket /tmp/fusion-guard.sock; override via FUSION_GUARD_SOCK or ctor.
|
|
128
|
+
with FusionGuardClient() as guard:
|
|
129
|
+
verdict = guard.evaluate("rm -rf /", caller_epoch=guard.ping()["rules_epoch"])
|
|
130
|
+
if verdict.action == "block":
|
|
131
|
+
# a block is a normal verdict, NOT an exception — inspect .action (E5).
|
|
132
|
+
log.warning("blocked: %s (risk %s)", verdict.reason, verdict.risk_level)
|
|
133
|
+
rules, epoch = guard.list_rules()
|
|
134
|
+
redacted = guard.redact("my SSN is 123-45-6789")
|
|
135
|
+
chain = guard.audit_verify() # tamper-evidence across audit/tcc/rules/dead_letter
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Embeddings
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
resp = await client.embed("hello world", model="bge-m3")
|
|
142
|
+
print(resp.vector) # single input → .vector
|
|
143
|
+
batch = await client.embed(["a", "b"], model="bge-m3")
|
|
144
|
+
print(batch.vectors) # batch input → .vectors list
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Design principles
|
|
148
|
+
|
|
149
|
+
- **Pure tech, zero business**: no K12 grading, no finance thresholds, no medical contraindications, no DAG nodes. When a boundary is blurry, it stays out.
|
|
150
|
+
- **Non-invasive, standalone**: `fusion_core` imports on its own, depends on no other fusion-* project.
|
|
151
|
+
- **Fail visibly, no fallbacks**: `parse_llm_json` raises instead of returning `{}`; client failure raises instead of returning empty content; `get_server_stats` failure raises instead of returning `{}`.
|
|
152
|
+
- **Tests are isolatable**: `-m 'not integration'` skips real-engine tests; integration fixtures record `was_running` and only stop engines they started.
|
|
153
|
+
|
|
154
|
+
## Boundary declaration — cluster capabilities belong to fusion-gateway
|
|
155
|
+
|
|
156
|
+
fusion-core is a **single-process, single-engine client library**, not a cluster control plane. The PRD §0.2 four iron rules (pure tech / non-invasive / fail-visible / isolatable tests) draw the boundary. The cluster-level capabilities below are **already implemented and live in fusion-gateway (Go, :11432)** — core does not rebuild them (rebuilding = duplication + violates "pure tech, zero business"). Core only does the minimal "don't conflict with gateway behavior" fixes.
|
|
157
|
+
|
|
158
|
+
| Capability | gateway implementation | core action |
|
|
159
|
+
|------------|------------------------|-------------|
|
|
160
|
+
| Endpoint registry / routing / failover | `discovery` (node register/health/evict) + `router/engine` | `default_mlx_base_url()` reads `FUSION_MLX_URL`; point at gateway for multi-node |
|
|
161
|
+
| Circuit breaker | `router/circuit_breaker.go:CircuitBreaker` | `with_retry(disable=True)` disables core retry, hands to gateway breaker, avoids double-retry |
|
|
162
|
+
| Per-endpoint concurrency gate | `router/engine.go:MaxConcurrent` | core pool adds no concurrency cap |
|
|
163
|
+
| Model registry model→endpoint | `router` routes by model | caller passes model, gateway resolves endpoint; core holds no topology |
|
|
164
|
+
| Metrics (Prometheus) | `observability/metrics` (circuitBreakerState/Trips, routeDecisions, requestDuration, requestTotal) | core does not double-instrument (`http_client` metrics callback kept for single-process use) |
|
|
165
|
+
| Agent scheduling (slots/queue/cancel) | routing-layer concurrency governance | scheduling is business orchestration → fusion-cowork / agent-studio |
|
|
166
|
+
|
|
167
|
+
**Multi-node access**: `export FUSION_MLX_URL=http://<gateway-host>:11432/v1` — core then hits the gateway, which routes to cluster nodes. Core itself is always a single `base_url` view.
|
|
168
|
+
|
|
169
|
+
See `audit/fusion-core-audit-report-0824.md` §六 for the landing state.
|
|
170
|
+
|
|
171
|
+
## Migration guide (self-built client → fusion-core)
|
|
172
|
+
|
|
173
|
+
Projects still on bare `httpx` to MLX (no retry/timeout/metrics): `fusion-health`, `fusion-science`, `fusion-rag`, `fusion-simulation`, `fusion-code-modelization`, `fusion-security`, `fusion-trainer`.
|
|
174
|
+
|
|
175
|
+
Steps (one PR per project, see `architecture/venv-fix-0823.md` §5):
|
|
176
|
+
|
|
177
|
+
1. `httpx.AsyncClient.post(.../chat/completions)` → `create_async_client(...)` + `await client.chat(...)`
|
|
178
|
+
2. Self-built `_parse_json` → `parse_llm_json` (raises on failure, not `return {}`)
|
|
179
|
+
3. No `base_url` → uses core default `localhost:11434/v1` (aligned with fusion-mlx `start.sh`, not the gateway)
|
|
180
|
+
4. Silent degrade `return LLMResult(content="", error=...)` → raise (fixes audit D-H3 silent failure)
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
# Before (health llm_gateway.py silent failure)
|
|
184
|
+
try:
|
|
185
|
+
resp = await client.post(f"{url}/chat/completions", ...)
|
|
186
|
+
return LLMResult(content=resp.json()["choices"][0]["message"]["content"])
|
|
187
|
+
except Exception as e:
|
|
188
|
+
return LLMResult(content="", error=str(e)) # silent! downstream proceeds on empty
|
|
189
|
+
|
|
190
|
+
# After
|
|
191
|
+
from fusion_core import create_async_client
|
|
192
|
+
|
|
193
|
+
self._client = create_async_client(base_url=url, api_key=key, model=model)
|
|
194
|
+
result = await self._client.chat(messages=messages) # raises on failure
|
|
195
|
+
return LLMResult(content=result.content, model=result.model)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## PRD §7.1 acceptance (measured, not declared)
|
|
199
|
+
|
|
200
|
+
| Acceptance item | Status | Evidence |
|
|
201
|
+
|-----------------|--------|----------|
|
|
202
|
+
| `import fusion_core` triggers no I/O (no env/file/conn) | ✅ | `mlx_client` dropped module-level `os.environ.get`; resolves `default_mlx_base_url()` at call time; `tests/test_config.py::TestImportTimeIsolation` guards with env-get spy |
|
|
203
|
+
| grep source has no `or {}` / `or []` / `or ""` silent fallback | ✅ | `resolve_api_key` dropped `or ""`; `get_server_stats` raises, not `return {}` |
|
|
204
|
+
| LLM client holds no retry logic (single responsibility) | ✅ | `mlx_client.chat` routes to `http_client.with_retry`; single source `RETRY_STATUS`/`RETRY_EXCEPTIONS` |
|
|
205
|
+
| Integration tests hit 11434 (PRD §7.1) | ✅ | `DEFAULT_MLX_PORT = 11434`, aligned with fusion-mlx `start.sh`; integration fixture `was_running` doesn't kill user's engine |
|
|
206
|
+
| CORS `*`+credentials rejected | ✅ | `create_app(cors_origins=["*"], cors_credentials=True)` raises `ValueError`; credentials defaults False |
|
|
207
|
+
|
|
208
|
+
## Testing
|
|
209
|
+
|
|
210
|
+
```bash
|
|
211
|
+
pytest tests/ -m "not integration" # unit: 393 passed, 1 skipped (env-only)
|
|
212
|
+
pytest tests/ -m integration # real fusion-mlx engine: 7 passed, 0 skipped
|
|
213
|
+
ruff check . && ruff format --check . # lint clean
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Documentation
|
|
217
|
+
|
|
218
|
+
- [中文文档 (Chinese)](README_CN.md)
|
|
219
|
+
- Module reference: [`docs/`](docs/) — per-module API signatures, params, returns, exceptions, examples
|
|
220
|
+
- Audit: `../audit/fusion-core-audit-report-0824.md` — 28 findings, 21 core fixes + 7 boundary declarations
|
|
221
|
+
- PRD: `../architecture/fusion-core-prd-0823.md`
|
|
222
|
+
|
|
223
|
+
## Related
|
|
224
|
+
|
|
225
|
+
- Fix plan: `../architecture/venv-fix-0823.md` §5 (client rollout)
|
|
226
|
+
- Audit: `../audit/fusion-audit-all-report.md` Chapter 4 Q1
|
|
227
|
+
- Production-readiness audit: `../audit/fusion-core-audit-result-product-0827.md`
|
|
228
|
+
- License: [Apache-2.0](LICENSE)
|