mainspring 3.3.0__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.
Files changed (69) hide show
  1. mainspring-3.3.0/LICENSE +21 -0
  2. mainspring-3.3.0/PKG-INFO +434 -0
  3. mainspring-3.3.0/README.md +411 -0
  4. mainspring-3.3.0/mainspring/__init__.py +32 -0
  5. mainspring-3.3.0/mainspring/checkpoint/__init__.py +30 -0
  6. mainspring-3.3.0/mainspring/checkpoint/codec.py +40 -0
  7. mainspring-3.3.0/mainspring/checkpoint/postgres.py +89 -0
  8. mainspring-3.3.0/mainspring/checkpoint/redis.py +44 -0
  9. mainspring-3.3.0/mainspring/checkpoint/sqlite.py +93 -0
  10. mainspring-3.3.0/mainspring/context.py +61 -0
  11. mainspring-3.3.0/mainspring/core/__init__.py +29 -0
  12. mainspring-3.3.0/mainspring/core/checkpointer.py +38 -0
  13. mainspring-3.3.0/mainspring/core/nodes/__init__.py +3 -0
  14. mainspring-3.3.0/mainspring/core/nodes/decide.py +102 -0
  15. mainspring-3.3.0/mainspring/core/nodes/execute.py +156 -0
  16. mainspring-3.3.0/mainspring/core/nodes/observe.py +38 -0
  17. mainspring-3.3.0/mainspring/core/nodes/plan.py +63 -0
  18. mainspring-3.3.0/mainspring/core/resilience.py +97 -0
  19. mainspring-3.3.0/mainspring/core/runtime.py +528 -0
  20. mainspring-3.3.0/mainspring/core/state.py +42 -0
  21. mainspring-3.3.0/mainspring/evaluation/__init__.py +9 -0
  22. mainspring-3.3.0/mainspring/evaluation/golden.py +57 -0
  23. mainspring-3.3.0/mainspring/events/__init__.py +19 -0
  24. mainspring-3.3.0/mainspring/events/events.py +83 -0
  25. mainspring-3.3.0/mainspring/knowledge/__init__.py +3 -0
  26. mainspring-3.3.0/mainspring/knowledge/plugin.py +69 -0
  27. mainspring-3.3.0/mainspring/llm/__init__.py +33 -0
  28. mainspring-3.3.0/mainspring/llm/base.py +26 -0
  29. mainspring-3.3.0/mainspring/llm/cost.py +101 -0
  30. mainspring-3.3.0/mainspring/llm/embedder.py +57 -0
  31. mainspring-3.3.0/mainspring/llm/litellm_gateway.py +116 -0
  32. mainspring-3.3.0/mainspring/llm/replay.py +91 -0
  33. mainspring-3.3.0/mainspring/llm/routing.py +115 -0
  34. mainspring-3.3.0/mainspring/llm/stream.py +56 -0
  35. mainspring-3.3.0/mainspring/llm/structured.py +32 -0
  36. mainspring-3.3.0/mainspring/log.py +43 -0
  37. mainspring-3.3.0/mainspring/memory/__init__.py +6 -0
  38. mainspring-3.3.0/mainspring/memory/consolidator.py +84 -0
  39. mainspring-3.3.0/mainspring/memory/manager.py +50 -0
  40. mainspring-3.3.0/mainspring/memory/reflect.py +46 -0
  41. mainspring-3.3.0/mainspring/memory/working.py +36 -0
  42. mainspring-3.3.0/mainspring/observability/__init__.py +11 -0
  43. mainspring-3.3.0/mainspring/observability/metrics.py +44 -0
  44. mainspring-3.3.0/mainspring/observability/trace.py +68 -0
  45. mainspring-3.3.0/mainspring/plugins/__init__.py +4 -0
  46. mainspring-3.3.0/mainspring/plugins/base.py +48 -0
  47. mainspring-3.3.0/mainspring/plugins/manifest.py +32 -0
  48. mainspring-3.3.0/mainspring/plugins/registry.py +90 -0
  49. mainspring-3.3.0/mainspring/ports.py +389 -0
  50. mainspring-3.3.0/mainspring/py.typed +0 -0
  51. mainspring-3.3.0/mainspring/security/__init__.py +64 -0
  52. mainspring-3.3.0/mainspring/skills/__init__.py +3 -0
  53. mainspring-3.3.0/mainspring/skills/agent_skill.py +24 -0
  54. mainspring-3.3.0/mainspring/skills/base.py +64 -0
  55. mainspring-3.3.0/mainspring/skills/flow_skill.py +18 -0
  56. mainspring-3.3.0/mainspring/skills/function_skill.py +100 -0
  57. mainspring-3.3.0/mainspring/skills/manager.py +44 -0
  58. mainspring-3.3.0/mainspring/skills/prompt_skill.py +24 -0
  59. mainspring-3.3.0/mainspring/tools/__init__.py +13 -0
  60. mainspring-3.3.0/mainspring/tools/_http.py +27 -0
  61. mainspring-3.3.0/mainspring/tools/base.py +28 -0
  62. mainspring-3.3.0/mainspring/tools/builtin/__init__.py +4 -0
  63. mainspring-3.3.0/mainspring/tools/builtin/calculator.py +60 -0
  64. mainspring-3.3.0/mainspring/tools/builtin/http.py +28 -0
  65. mainspring-3.3.0/mainspring/tools/decorator.py +78 -0
  66. mainspring-3.3.0/mainspring/tools/http_openapi.py +92 -0
  67. mainspring-3.3.0/mainspring/tools/mcp.py +86 -0
  68. mainspring-3.3.0/mainspring/tools/registry.py +41 -0
  69. mainspring-3.3.0/pyproject.toml +35 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mainspring contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,434 @@
1
+ Metadata-Version: 2.4
2
+ Name: mainspring
3
+ Version: 3.3.0
4
+ Summary: Mainspring: a business-agnostic agent runtime (Plan → Decide → Execute → Observe loop) with plugins, skills, tools, and memory.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: agent,llm,framework,plugins,skills,tools,memory
8
+ Requires-Python: >=3.11,<3.15
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Provides-Extra: observability
16
+ Requires-Dist: httpx (>=0.27)
17
+ Requires-Dist: litellm (>=1.40)
18
+ Requires-Dist: opentelemetry-api (>=1.20) ; extra == "observability"
19
+ Requires-Dist: pydantic (>=2.6)
20
+ Requires-Dist: redis (>=5.0)
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Mainspring
24
+
25
+ 框架设计、版本路线图、使用说明和 UML 文档统一维护在仓库根的 [`documentation/mainspring/`](../../documentation/mainspring/)。
26
+
27
+ 业务无关的 **Agent 框架层**。提供 Agent 运行循环(Plan → Decide → Execute → Observe)、统一插件协议、Skill/Tool 执行、记忆机制与能力端口(Ports)。
28
+
29
+ - **不依赖**业务层的 HTTP / 数据库 / 配置 / 多租户概念,可独立安装使用。
30
+ - 通过 `ports.py` 定义能力端口(`PermissionChecker` / `LongTermMemory` / `WorkingMemory` / `LLMGateway` / `Embedder` / `Plugin` 等),由宿主(业务层)实现并注入。
31
+
32
+ ---
33
+
34
+ ## 特性
35
+
36
+ | 能力 | 说明 |
37
+ |------|------|
38
+ | Agent 运行循环 | 手写状态机:`Decide → Execute → Observe`(Plan 可选开启),带迭代上限防死循环 |
39
+ | 流式输出 | `StreamingLLMGateway` + `message.delta` token 级事件;不支持时自动回退非流式 |
40
+ | 结构化输出 | `chat(schema=PydanticModel)`:`LLMResponse.parsed` 直出模型实例,校验失败抛 `StructuredOutputError` |
41
+ | `@tool` 装饰器 | 类型化函数直出 `BaseTool`:签名自动生成参数 JSON Schema,docstring 即描述 |
42
+ | Checkpointer 后端 | `checkpoint/`:SQLite / Redis / PostgreSQL 官方实现,与 `InMemoryCheckpointer` 行为互换;损坏/版本不符响亮失败 |
43
+ | 上下文治理 | `ContextManager` 端口 + 默认滑窗(`SlidingWindowContext`),长任务不爆窗口 |
44
+ | 统一插件协议 | `Plugin` / `PluginManifest`,Tool / Skill / Knowledge… 统一接入 |
45
+ | 工具执行 | 内置 `calculator`/`http`,支持 MCP 客户端、HTTP(OpenAPI) 适配 |
46
+ | 技能执行 | 四种形态:`prompt` / `function` / `flow` / `agent` |
47
+ | 记忆 | 短期 Working Brain(Redis)+ 会话固化 Consolidator + `LongTermMemory` 端口 |
48
+ | 授权 | 纯逻辑 `check_permission`(admin 绕过 / deny 优先 / 默认拒绝 / 高危审批) |
49
+ | 事件 | 运行时事件模型(非传输层),含 token 级 `message.delta` |
50
+
51
+ ---
52
+
53
+ ## 安装
54
+
55
+ ```bash
56
+ pip install mainspring # 发布后
57
+
58
+ # monorepo 内以 path 依赖(开发态)
59
+ # 宿主工程的 pyproject.toml:
60
+ # [tool.poetry.dependencies]
61
+ # mainspring = { path = "mainspring", develop = true }
62
+ ```
63
+
64
+ 依赖:`python>=3.11`、`litellm`、`pydantic`、`httpx`、`redis`。
65
+
66
+ ---
67
+
68
+ ## 目录结构
69
+
70
+ ```
71
+ mainspring/
72
+ ├── ports.py # 能力端口 + 权限/记忆数据类型(框架与宿主的契约)
73
+ ├── log.py # `mainspring` 命名空间日志(NullHandler,不自行配置)
74
+ ├── context.py # SlidingWindowContext(ContextManager 默认实现)
75
+ ├── core/
76
+ │ ├── runtime.py # AgentRuntime 门面(run/resume + 强类型)
77
+ │ ├── state.py # AgentState(循环内共享状态)
78
+ │ ├── resilience.py # RetryPolicy / CircuitBreaker
79
+ │ ├── checkpointer.py# InMemoryCheckpointer(测试/进程内默认)
80
+ │ └── nodes/ # plan(可选)/ decide / execute / observe
81
+ ├── checkpoint/ # Checkpointer 官方后端(SQLite/Redis/PostgreSQL)+ JSON 信封
82
+ ├── plugins/ # Plugin 协议 + PluginRegistry + ref 解析
83
+ ├── skills/ # prompt/function/flow/agent 四类 Skill
84
+ ├── tools/ # builtin / MCP / HTTP(OpenAPI) 工具
85
+ ├── memory/ # WorkingBrain + Consolidator + MemoryManager 门面
86
+ ├── events/ # 运行时事件模型(run.started/step.completed/…)
87
+ ├── knowledge/ # Knowledge/Retriever 端口插件形态
88
+ ├── evaluation/ # GoldenSet / run_evaluation / HeuristicJudge
89
+ ├── observability/ # Tracer(可选 OTel)+ Metrics
90
+ ├── security/ # 工具结果边界标注 + Redactor 脱敏
91
+ └── llm/ # LLMGateway/Embedder 协议 + LiteLLM 实现 + 成本/路由
92
+ ```
93
+
94
+ ---
95
+
96
+ ## 快速开始
97
+
98
+ ```python
99
+ import asyncio
100
+
101
+ from mainspring import AgentDefinition, AgentRuntime, RunContext, RuntimeDeps
102
+ from mainspring.llm.litellm_gateway import LiteLLMGateway
103
+ from mainspring.plugins.registry import PluginRegistry
104
+ from mainspring.tools.registry import build_default_registry
105
+
106
+
107
+ async def main():
108
+ # 1. 装配插件(内置 calculator / http)
109
+ registry = PluginRegistry()
110
+ for tool in build_default_registry().all():
111
+ registry.register_tool(tool)
112
+
113
+ # 2. 强类型门面:AgentDefinition(装配什么)+ RuntimeDeps(注入哪些端口)
114
+ definition = AgentDefinition(model="deepseek-chat", system_prompt="你是助手", plugins=registry.all())
115
+ deps = RuntimeDeps(llm=LiteLLMGateway(model="deepseek-chat", api_key="sk-..."))
116
+
117
+ # 3. 运行 → RunResult(强类型,不再是裸 dict)
118
+ result = await AgentRuntime().run(
119
+ definition, "计算 3*8 再加 100", RunContext(run_id="demo", session_id="s1"), deps
120
+ )
121
+ print(result.status, result.result) # completed, 3*8+100 = 124
122
+ print(result.steps, result.token_usage)
123
+
124
+
125
+ asyncio.run(main())
126
+ ```
127
+
128
+ `RuntimeDeps` 只要求 `llm`;其余端口(`permission_checker` / `long_term_memory` / `knowledge` / `event_sink` / `checkpointer` / `tracer` / `metrics` …)按需注入,全部契约集中在 `mainspring.ports`。
129
+
130
+ ---
131
+
132
+ ## 核心概念
133
+
134
+ ### AgentState(白板式共享状态)
135
+
136
+ 四个节点不互相传参,而是读写同一份 `AgentState`(`TypedDict`)。节点返回一个 dict,运行时自动 merge 回状态。
137
+
138
+ 关键字段:`task` / `messages` / `plan` / `action` / `action_input` / `last_tool_result` / `iteration` / `max_iterations` / `status` / `result` / `memory_ctx` / `approvals` / `subagent_depth` / `token_usage`。
139
+
140
+ ### 运行循环
141
+
142
+ ```
143
+ (plan ─►) decide ─► execute ─► observe ─┐
144
+ ▲ │ (未完成)
145
+ └──────── decide ◄─────┘
146
+ │ (action=="__finish__" 或 iteration 触顶)
147
+ ▼ END
148
+ ```
149
+
150
+ | 节点 | 职责 |
151
+ |------|------|
152
+ | `plan` | 拆解任务为步骤清单(**默认关闭**,`RuntimeConfig(enable_planning=True)` 开启;失败退化为单步) |
153
+ | `decide` | 带工具 schema 调 LLM,选择插件或收尾给答案;流式时逐 token 发 `message.delta` |
154
+ | `execute` | 权限校验后调用插件,归一化结果为字符串 |
155
+ | `observe` | 回填结果、`iteration+1`、触顶兜底 |
156
+
157
+ Plan 默认关闭的原因:它每次 run 多花一次 LLM 调用,而计划状态从未被跟踪;单循环决策已覆盖大多数任务(与 OpenAI Agents SDK 同一哲学)。
158
+
159
+ ---
160
+
161
+ ## 能力端口(Ports)
162
+
163
+ 框架定义端口、宿主实现。全部在 `ports.py`。
164
+
165
+ ### PermissionChecker
166
+
167
+ ```python
168
+ from mainspring.ports import PermissionChecker, PermissionContext, PermissionDecision, check_permission
169
+
170
+ class MyPermissionChecker(PermissionChecker):
171
+ def check(self, ctx, action, resource_type, resource_id,
172
+ resource_permission="read", requires_approval=False, approved=None):
173
+ return check_permission(ctx, action, resource_type, resource_id,
174
+ resource_permission=resource_permission,
175
+ requires_approval=requires_approval, approved=approved)
176
+ ```
177
+
178
+ `PermissionContext`:`permission_codes: set[str]`、旧版资源级兼容 `grant_keys`、动作级 `grant_actions: set[(resource_type, resource_id, action, effect)]`、`is_admin: bool`。新授权使用 `grant_actions`;宿主迁移旧数据时可用 `grant_keys` 保留旧语义。
179
+
180
+ 判定顺序:**admin 绕过 → 功能权限 `run:execute` → deny 优先 → read 默认放行 → grant 要求 → 高危审批**。
181
+
182
+ ### LongTermMemory / WorkingMemory
183
+
184
+ ```python
185
+ from mainspring.ports import LongTermMemory, MemoryEntry
186
+
187
+ class InMemoryLongTerm(LongTermMemory):
188
+ async def add(self, db, *, tenant_id, user_id, session_id, content,
189
+ importance=0.5, confidence=0.5) -> str: ...
190
+ async def recall(self, db, tenant_id, user_id, query, top_k=5) -> list[MemoryEntry]: ...
191
+ ```
192
+
193
+ > `db` 参数由宿主传入(如 `AsyncSession`),协议不约束其类型。框架自带的 Redis 实现见 `mainspring.memory.working.WorkingBrain`。
194
+
195
+ ### Embedder
196
+
197
+ ```python
198
+ from mainspring.llm.embedder import LiteLLMEmbedder, HashEmbedder
199
+
200
+ embedder = LiteLLMEmbedder("text-embedding-3-small", api_key="sk-...") # 有 key
201
+ embedder = HashEmbedder(1536) # 离线回退(确定性 hash)
202
+ ```
203
+
204
+ ---
205
+
206
+ ## 开发自定义 Tool
207
+
208
+ ```python
209
+ from mainspring.tools.base import BaseTool, ToolResult
210
+
211
+ class WeatherTool(BaseTool):
212
+ name = "weather"
213
+ description = "查询城市天气"
214
+ permission = "read" # read | write | admin
215
+ parameters = {
216
+ "type": "object",
217
+ "properties": {"city": {"type": "string", "description": "城市名"}},
218
+ "required": ["city"],
219
+ }
220
+
221
+ async def run(self, city: str) -> ToolResult:
222
+ return ToolResult(success=True, output=f"{city}:晴 22℃")
223
+
224
+
225
+ registry.register_tool(WeatherTool()) # 内部用 ToolAsPlugin 适配成 Plugin
226
+ ```
227
+
228
+ ---
229
+
230
+ ## 开发自定义 Skill
231
+
232
+ Skill 是 `kind="skill"` 的插件,四种形态,用 `PluginManifest` 声明能力:
233
+
234
+ ```python
235
+ from mainspring.plugins.base import PluginManifest
236
+ from mainspring.plugins.registry import PluginRegistry
237
+ from mainspring.skills.prompt_skill import PromptSkill
238
+ from mainspring.skills.function_skill import FunctionSkill
239
+ from mainspring.skills.agent_skill import AgentSkill
240
+ from mainspring.skills.flow_skill import FlowSkill
241
+
242
+ registry = PluginRegistry()
243
+
244
+ registry.register(PromptSkill( # prompt:模板渲染
245
+ PluginManifest(name="refund_policy", kind="skill"),
246
+ {"template": "退款政策:7 天无理由(上下文:{{memory_ctx}})"},
247
+ ))
248
+
249
+ registry.register(FunctionSkill( # function:执行 Python(非沙箱,仅可信作者)
250
+ PluginManifest(name="add", kind="skill"),
251
+ {"source": "def run(**kw):\n return str(int(kw['a']) + int(kw['b']))"},
252
+ ))
253
+
254
+ registry.register(AgentSkill( # agent:调子 Agent(注入 run_subagent 回调)
255
+ PluginManifest(name="escalate", kind="skill"),
256
+ {"agent_ref": "agent_escalation"},
257
+ run_subagent=my_subagent_runner,
258
+ ))
259
+
260
+ registry.register(FlowSkill( # flow:多步流程(注入 run_flow 回调)
261
+ PluginManifest(name="report", kind="skill"),
262
+ {"graph_spec": {}},
263
+ run_flow=my_flow_runner,
264
+ ))
265
+ ```
266
+
267
+ `PluginManifest` 字段:`name / version / kind / description / parameters(JSON Schema) / permission / requires_approval / dependencies / tags`。
268
+
269
+ ---
270
+
271
+ ## 插件引用与命名
272
+
273
+ ```python
274
+ from mainspring.plugins.manifest import parse_ref, format_ref
275
+
276
+ parse_ref("tool:calculator") # PluginRef(kind="tool", name="calculator")
277
+ parse_ref("skill:refund@1.2.0") # PluginRef(kind="skill", name="refund", version="1.2.0")
278
+ format_ref("skill", "refund", "1.2.0") # "skill:refund@1.2.0"
279
+ ```
280
+
281
+ **`function_name` 命名空间**:`tool` 用裸名(`calculator`),非 `tool` 种类加前缀(`skill_refund_policy`),避免 function-calling 撞名。LLM 返回的 `tool_call.name` 即 `function_name`,可被 `PluginRegistry.get()` 反查。
282
+
283
+ ---
284
+
285
+ ## 事件与流式
286
+
287
+ 经 `RuntimeDeps.event_sink` 注入异步回调,每步产出一个 `RuntimeEvent`(`run.started` / `step.completed` / `run.completed` / …):
288
+
289
+ ```python
290
+ async def sink(event):
291
+ print(event.event, event.data) # 框架只出数据;SSE/WebSocket 序列化由宿主做
292
+
293
+ deps = RuntimeDeps(llm=llm, event_sink=sink)
294
+ ```
295
+
296
+ 事件类型:`run.started` / `message.delta` / `step.completed` / `run.completed` / `run.failed` / `run.awaiting_human` / `run.approved` / `run.rejected`。框架只产出事件数据,传输由宿主负责。
297
+
298
+ **流式(token 级)**:当网关实现 `StreamingLLMGateway`(如 `LiteLLMGateway`)且注入了 `event_sink` 时,Decide 自动走流式并逐 token 发出 `message.delta` 事件,宿主可直接转 SSE 打字机效果:
299
+
300
+ ```python
301
+ async def sink(event):
302
+ if event.event == "message.delta":
303
+ print(event.data["delta"], end="", flush=True)
304
+
305
+ deps = RuntimeDeps(llm=LiteLLMGateway(...), event_sink=sink)
306
+ ```
307
+
308
+ 注意两点:`message.delta` 是**临时性**事件——Decide 重试会从头重新流式,消费方应增量渲染而非持久化;只有折叠后的最终结果才是权威数据。未注入 `event_sink` 或网关不支持 `chat_stream` 时自动回退 `chat()`,零成本。
309
+
310
+ ---
311
+
312
+ ## 上下文治理
313
+
314
+ 长任务的对话历史会无限增长。`ContextManager` 端口(`ports.py`)在每个 Decide 前压缩历史,**被丢弃的轮次永久移除**(这正是控制窗口的机制):
315
+
316
+ ```python
317
+ from mainspring import SlidingWindowContext
318
+
319
+ # 零配置:超过 40 条即滑窗压缩 + 截断超长工具结果
320
+ deps = RuntimeDeps(llm=llm)
321
+ definition = AgentDefinition(model="...", runtime=RuntimeConfig(max_history_messages=40))
322
+
323
+ # 自定义策略(如 LLM 摘要压缩):实现 ContextManager 协议
324
+ deps = RuntimeDeps(llm=llm, context_manager=MySummarizingContext(llm, max_tokens=8000))
325
+ ```
326
+
327
+ 默认实现 `SlidingWindowContext`:保留头部 system 消息 + 最新窗口、切点跳过孤立 tool 消息(避免 API 校验失败)、超长工具结果就地截断。宿主的摘要压缩实现可在构造时自带网关。
328
+
329
+ ---
330
+
331
+ ## 记忆编排
332
+
333
+ ```python
334
+ from mainspring.memory.manager import MemoryManager
335
+ from mainspring.memory.consolidator import Consolidator
336
+ from mainspring.memory.working import WorkingBrain
337
+
338
+ manager = MemoryManager(
339
+ working=WorkingBrain(redis_client),
340
+ vector_store=my_long_term_memory, # 实现 LongTermMemory
341
+ consolidator=Consolidator(my_long_term_memory, similarity_threshold=0.85),
342
+ )
343
+
344
+ await manager.write(session_id, {"role": "user", "content": "..."}) # 短期写入
345
+ history = await manager.get_history(session_id) # 短期读取
346
+ entries = await manager.recall(db, tenant_id, user_id, query, top_k=5) # 长期召回
347
+ await manager.consolidate(db, session_id, tenant_id, user_id) # 短期→长期固化
348
+ ```
349
+
350
+ ---
351
+
352
+ ## 完整示例
353
+
354
+ `example/` 目录下有每个模块的可运行示例(权限/HITL、事件流式、记忆、知识、可靠性、多厂商 fallback、评测等)。典型的高危审批 + 恢复流程:
355
+
356
+ ```python
357
+ result = await runtime.run(definition, "删除账号 u42", context, deps)
358
+ # result.status == "awaiting_human", result.pending_approvals = [...]
359
+
360
+ resumed = await runtime.resume(definition, "run-1", ["delete_account"], deps)
361
+ # resumed.status == "completed"
362
+ ```
363
+
364
+ 详见 `example/permissions_hitl.py`。
365
+
366
+ ---
367
+
368
+ ## API 速查
369
+
370
+ | 符号 | 位置 | 签名 |
371
+ |------|------|------|
372
+ | `AgentRuntime` | `core.runtime` | `run(definition, task, context, deps) -> RunResult` / `resume(...)` |
373
+ | `RuntimeDeps` | `core.runtime` | `llm / permission_checker / long_term_memory / knowledge / event_sink / checkpointer / context_manager / tracer / metrics / retry …` |
374
+ | `RuntimeConfig` | `core.runtime` | `max_iterations / timeout_seconds / max_subagent_depth / max_total_tokens / enable_planning / max_history_messages` |
375
+ | `SlidingWindowContext` | `context` | `ContextManager` 默认实现(滑窗 + 工具结果截断) |
376
+ | `StreamingLLMGateway` / `ChatChunk` | `ports` / `llm.base` | 可选流式协议;`LiteLLMGateway.chat_stream` |
377
+ | `PluginRegistry` | `plugins.registry` | `register / register_tool / get / to_openai_schema / invoke` |
378
+ | `PluginManifest` | `plugins.base` | Pydantic 模型 + `function_name` |
379
+ | `InvokeContext` | `plugins.base` | `tenant_id/user_id/run_id/trace_id/session_id/subagent_depth` |
380
+ | `check_permission` | `ports` | `(ctx, action, resource_type, resource_id, *, resource_permission, requires_approval, approved)` |
381
+ | `Tool` / `BaseTool` / `ToolResult` | `tools.base` | 工具抽象 |
382
+ | `Skill` / `build_skill` | `skills.base` | 四形态技能 |
383
+ | `LiteLLMGateway` | `llm.litellm_gateway` | `(model, api_key, api_base)` |
384
+ | `LiteLLMEmbedder` / `HashEmbedder` | `llm.embedder` | 向量化 |
385
+ | `MemoryManager` / `WorkingBrain` / `Consolidator` | `memory.*` | 记忆编排 |
386
+
387
+ ---
388
+
389
+ ## 运行测试
390
+
391
+ ```bash
392
+ cd mainspring
393
+ poetry install
394
+ poetry run pytest # 168 个单元测试,无外部依赖(Redis/LLM/DB 均用 fake)
395
+ ```
396
+
397
+ ---
398
+
399
+ ## 日志
400
+
401
+ 框架用标准库 `logging` 在 `mainspring` 命名空间下输出日志(`mainspring.core.runtime`、`mainspring.core.nodes.execute` …),**从不自行配置 handler/level**——是否开启由宿主决定。
402
+
403
+ 宿主开启:
404
+
405
+ ```python
406
+ import logging
407
+ from mainspring.log import configure_logging
408
+
409
+ configure_logging(level=logging.INFO) # 或 logging.DEBUG 看更细
410
+ ```
411
+
412
+ 也可直接用宿主自己的 logging 配置(`mainspring` 已挂 `NullHandler`,不会产生 "no handler" 噪音,且会传播到根 logger)。
413
+
414
+ 级别约定:
415
+
416
+ | 级别 | 场景 |
417
+ |------|------|
418
+ | `DEBUG` | 每步节点/耗时、LLM 调用元数据、插件/工具注册 |
419
+ | `INFO` | run 开始/完成、待审批 |
420
+ | `WARNING` | 越权拒绝、未知插件、LLM 失败回退、迭代触顶、工具执行失败 |
421
+ | `ERROR`(含堆栈)| run 失败、插件抛出异常 |
422
+
423
+ > 不记录敏感数据:`api_key`、消息内容、工具入参均不落日志。
424
+
425
+ ---
426
+
427
+ ## 设计原则
428
+
429
+ 1. **依赖倒置**:框架只依赖 `ports.py` 的协议与纯数据,不 import 宿主的存储/HTTP/配置。
430
+ 2. **单一路径执行**:无论 Tool/Skill,`execute` 都走 `registry.get(action) → invoke`。
431
+ 3. **声明与实现分离**:`manifest` 描述「是什么」,`body`/`run` 描述「怎么做」。
432
+ 4. **容错收敛**:LLM 失败退化为单步计划、空输出即收尾、迭代上限兜底,保证不死循环。
433
+ 5. **权限在执行前**:不信任 LLM 的选择,`execute` 前强制校验。
434
+