braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,2776 @@
|
|
|
1
|
+
"""配置层级与模型目录:六层来源合成一份 :class:`AgentConfig`。
|
|
2
|
+
|
|
3
|
+
配置在进程启动时读一次,之后所有装配都读同一个对象(``AgentSession.config``)。
|
|
4
|
+
运行中不重读文件:一份中途被改过的配置会让两个回合的压缩阈值、重试次数与模型
|
|
5
|
+
互相矛盾,而用户看到的只是"回答突然变了"。
|
|
6
|
+
|
|
7
|
+
## 文件形状
|
|
8
|
+
|
|
9
|
+
全局配置是 ``~/.braid/settings.json``,项目配置是 ``<cwd>/.braid/settings.json``,
|
|
10
|
+
``--config`` 指向的额外文件也使用同一种 JSON 结构。下面是一份完整示例:
|
|
11
|
+
|
|
12
|
+
```json
|
|
13
|
+
{
|
|
14
|
+
"config_version": 1,
|
|
15
|
+
"default_model": "deepseek/deepseek-flash",
|
|
16
|
+
"default_thinking": "off",
|
|
17
|
+
"instructions": ["CONTRIBUTING.md", "docs/guidelines.md", "packages/*/AGENTS.md"],
|
|
18
|
+
"permission": {
|
|
19
|
+
"default": "ask",
|
|
20
|
+
"mode": "full",
|
|
21
|
+
"approval_timeout_seconds": 60,
|
|
22
|
+
"tools": {
|
|
23
|
+
"read": "allow"
|
|
24
|
+
},
|
|
25
|
+
"bash": {
|
|
26
|
+
"*": "ask",
|
|
27
|
+
"git status*": "allow",
|
|
28
|
+
"rm -rf *": "deny"
|
|
29
|
+
},
|
|
30
|
+
"paths": {
|
|
31
|
+
"~/.ssh/**": "deny",
|
|
32
|
+
"**/.env": "deny"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"sandbox": {
|
|
36
|
+
"mode": "workspace-write",
|
|
37
|
+
"backend": "auto",
|
|
38
|
+
"network": "proxy",
|
|
39
|
+
"read": "all",
|
|
40
|
+
"allow_domains": ["api.deepseek.com"],
|
|
41
|
+
"deny_domains": ["*.internal.example"],
|
|
42
|
+
"writable_paths": ["/tmp/build"],
|
|
43
|
+
"executable": "/opt/homebrew/bin/bwrap"
|
|
44
|
+
},
|
|
45
|
+
"retry": {
|
|
46
|
+
"enabled": true,
|
|
47
|
+
"max_retries": 3,
|
|
48
|
+
"base_delay_ms": 2000,
|
|
49
|
+
"max_agent_delay_ms": 60000
|
|
50
|
+
},
|
|
51
|
+
"compaction": {
|
|
52
|
+
"enabled": true,
|
|
53
|
+
"reserve_tokens": 16384,
|
|
54
|
+
"keep_recent_tokens": 20000,
|
|
55
|
+
"tool_results": {
|
|
56
|
+
"enabled": true,
|
|
57
|
+
"keep_recent": 8,
|
|
58
|
+
"min_chars": 1000,
|
|
59
|
+
"trigger_ratio": 0.6
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"agents": {
|
|
63
|
+
"max_depth": 1,
|
|
64
|
+
"max_background": 2,
|
|
65
|
+
"max_concurrent": 8,
|
|
66
|
+
"timeout_seconds": 300
|
|
67
|
+
},
|
|
68
|
+
"web": {
|
|
69
|
+
"enabled": true,
|
|
70
|
+
"search_provider": "bing",
|
|
71
|
+
"search_max_results": 5,
|
|
72
|
+
"search_endpoint": "",
|
|
73
|
+
"fetch_max_chars": 20000,
|
|
74
|
+
"cache_ttl_seconds": 300,
|
|
75
|
+
"cache_max_entries": 32,
|
|
76
|
+
"timeout_seconds": 20,
|
|
77
|
+
"allow_private_hosts": false
|
|
78
|
+
},
|
|
79
|
+
"lsp": {
|
|
80
|
+
"python": {
|
|
81
|
+
"command": ["pyright-langserver", "--stdio"],
|
|
82
|
+
"extensions": [".py", ".pyi"],
|
|
83
|
+
"language_id": "python",
|
|
84
|
+
"root_markers": ["pyproject.toml", "setup.cfg", ".git"],
|
|
85
|
+
"timeout_seconds": 15,
|
|
86
|
+
"env": {"PYTHONPATH": "src"},
|
|
87
|
+
"initialization_options": {}
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
"verify": {
|
|
91
|
+
"enabled": true,
|
|
92
|
+
"timeout_seconds": 600,
|
|
93
|
+
"fail_fast": false,
|
|
94
|
+
"max_consecutive_failures": 3,
|
|
95
|
+
"commands": [
|
|
96
|
+
{"name": "lint", "command": "uv run ruff check ."},
|
|
97
|
+
{"name": "types", "command": "uv run pyright"},
|
|
98
|
+
{"name": "tests", "command": "uv run pytest -q"}
|
|
99
|
+
]
|
|
100
|
+
},
|
|
101
|
+
"format": {
|
|
102
|
+
"enabled": true,
|
|
103
|
+
"timeout_seconds": 30,
|
|
104
|
+
"commands": {
|
|
105
|
+
".py": ["ruff", "format", "{path}"]
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
"providers": {
|
|
109
|
+
"deepseek": {
|
|
110
|
+
"base_url": "https://api.deepseek.com/v1",
|
|
111
|
+
"env_key": "DEEPSEEK_API_KEY"
|
|
112
|
+
},
|
|
113
|
+
"ollama": {
|
|
114
|
+
"base_url": "http://127.0.0.1:11434/v1",
|
|
115
|
+
"api_key": "ollama"
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
"models": {
|
|
119
|
+
"deepseek/deepseek-flash": {
|
|
120
|
+
"name": "DeepSeek V4.1 Flash",
|
|
121
|
+
"context_window": 1048576,
|
|
122
|
+
"max_tokens": 393216,
|
|
123
|
+
"input": ["text", "image"],
|
|
124
|
+
"reasoning": true,
|
|
125
|
+
"thinking_levels": ["off", "low", "high", "max"],
|
|
126
|
+
"cost_input": 0.15,
|
|
127
|
+
"cost_output": 0.6,
|
|
128
|
+
"cost_cache_read": 0.003
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
``providers.<id>`` 只描述"怎么连上"——地址、凭证、请求字段名、要不要刷新清单。
|
|
135
|
+
``models["<provider>/<id>"]`` 描述"这个模型有多能打"——上下文窗口、输出上限、
|
|
136
|
+
输入模态、思考档位、价格。两张表用 ``provider/id`` 这个键对齐,与 ``--model``
|
|
137
|
+
的写法、``/models`` 的显示、会话里记录的 ``model_change`` 是同一种标识。
|
|
138
|
+
|
|
139
|
+
模型单独成表而不是嵌在 provider 下面,是因为覆盖只发生在模型这一层:项目配置
|
|
140
|
+
想把某个模型的 ``max_tokens`` 调小,不必再抄一遍 ``base_url``;两层文件里同一个
|
|
141
|
+
模型只写各自关心的字段。
|
|
142
|
+
|
|
143
|
+
``permission`` 的三张规则表按**键**合并:全局配置写一条 ``"~/.ssh/**": "deny"``,
|
|
144
|
+
项目配置再写一条 ``"rm -rf *": "deny"``,两条都生效。判定时按规则的具体程度排序,
|
|
145
|
+
最具体的那一组里 deny 优先于 ask、ask 优先于 allow,见
|
|
146
|
+
:mod:`braid_coding_agent.permissions.engine`。
|
|
147
|
+
|
|
148
|
+
运行时规则写在 ``~/.braid/permissions.toml`` 与 ``<cwd>/.braid/permissions.local.toml``;
|
|
149
|
+
项目信任记录在 ``~/.braid/permission_trust.json``。未信任项目的权限配置只保留 deny
|
|
150
|
+
规则,``mode`` 与 ``default`` 沿用全局设置。信任指纹只覆盖项目 ``settings.json``:
|
|
151
|
+
运行时写入 ``permissions.local.toml`` 是用户的显式动作,不该让项目退出信任。
|
|
152
|
+
|
|
153
|
+
``sandbox`` 是另一条轴:权限回答"要不要问用户",沙箱回答"放行之后最多能做到什么"。
|
|
154
|
+
默认 ``mode = "off"``——沙箱要求系统提供可用的后端(macOS 的 ``sandbox-exec``、
|
|
155
|
+
Linux 的 ``bwrap``),"开箱就起不来"不该是默认体验。显式开启后,后端探测失败会让
|
|
156
|
+
进程退出码 1:静默退回无沙箱执行会让用户以为自己在笼子里。字段语义见
|
|
157
|
+
:mod:`braid_coding_agent.sandbox.policy`。
|
|
158
|
+
|
|
159
|
+
``lsp`` / ``verify`` / ``format`` 是三个**可选**的工程能力,各自缺省为空:
|
|
160
|
+
|
|
161
|
+
- 没有任何 ``lsp`` 条目就不装 ``lsp`` 工具,模型看不到一个没有服务器可用的工具;
|
|
162
|
+
- 没有 ``verify.commands`` 就不装 ``verify`` 工具;
|
|
163
|
+
- 没有 ``format.commands`` 就不装 ``format`` 工具。
|
|
164
|
+
|
|
165
|
+
这样"没配置"与"配置了但不启动"是两种可见状态,而不是让模型对着空工具反复尝试。
|
|
166
|
+
三段配置的形状分别在 :mod:`braid_coding_agent.lsp.settings`、
|
|
167
|
+
:mod:`braid_coding_agent.verify.settings` 与 :mod:`braid_coding_agent.formatting.settings`
|
|
168
|
+
里,本模块只负责读取与合并。
|
|
169
|
+
|
|
170
|
+
## 优先级
|
|
171
|
+
|
|
172
|
+
从低到高:
|
|
173
|
+
|
|
174
|
+
1. 内置默认值(``_builtin_providers`` / ``_builtin_models``,只放核对过官方文档的条目)
|
|
175
|
+
2. ``~/.braid/settings.json``(全局)
|
|
176
|
+
3. ``<cwd>/.braid/settings.json``(项目)
|
|
177
|
+
4. ``--config PATH``(可重复,按给出顺序后者覆盖前者)
|
|
178
|
+
5. 环境变量(``BRAID_MODEL``、``BRAID_THINKING``、``BRAID_RETRY_*``、``BRAID_COMPACTION_*``)
|
|
179
|
+
6. 命令行参数(``--model``、``--thinking``、``--no-retry``、``--max-retries``、``--max-tokens``)
|
|
180
|
+
|
|
181
|
+
前四层在 :func:`load_config` 里完成合并,第 5 层同在这里应用,第 6 层由 CLI 在
|
|
182
|
+
装配时压上去——参数只在``run_cli`` 里可见,把它塞进配置对象只会让"这一次的意图"
|
|
183
|
+
变成"这台机器的偏好"。``/models`` 与 ``braid models`` 会把每一层的来源标出来。
|
|
184
|
+
|
|
185
|
+
环境变量优先于文件,是为了让"临时换一个模型跑一次"不必编辑配置;命令行优先于
|
|
186
|
+
环境变量,因为一条命令里的显式参数比 shell 里遗留的导出更接近此刻的意图。
|
|
187
|
+
|
|
188
|
+
## 未知字段一律报错
|
|
189
|
+
|
|
190
|
+
``providers.deepseek`` 里写 ``base_urls``、``models["x/y"]`` 里写 ``max_token``,
|
|
191
|
+
都会在读取时抛 :class:`ConfigError`,消息带文件路径与字段路径。配置错误留在启动
|
|
192
|
+
阶段修,比留到第一次请求变成 400 便宜得多——尤其是那些"看起来生效了"的错字。
|
|
193
|
+
|
|
194
|
+
## 配置版本
|
|
195
|
+
|
|
196
|
+
``config_version`` 缺失按当前版本处理,高于当前版本的文件直接拒绝。``AgentConfig``
|
|
197
|
+
记录文件里读到的版本,状态由 ``braid doctor`` 与 ``braid config path`` 报告——启动
|
|
198
|
+
路径不往 stderr 写这类提示,RPC 与 JSON 通道的诊断输出因此保持干净。
|
|
199
|
+
|
|
200
|
+
模型条目把 ``context_window`` 与 ``max_tokens`` 定为必填。它们分别喂给压缩阈值
|
|
201
|
+
与请求体的输出预算:给个默认值意味着 8K 输出的模型按 16K 发请求,或者压缩按
|
|
202
|
+
128K 算账。前者花钱,后者毁上下文。
|
|
203
|
+
|
|
204
|
+
## 静态密钥只给本机端点
|
|
205
|
+
|
|
206
|
+
``api_key`` 允许写在配置里,但 ``base_url`` 的主机必须是 ``127.0.0.1``、
|
|
207
|
+
``localhost`` 或 ``::1``。远端端点的密钥应当走环境变量或系统钥匙串
|
|
208
|
+
(``braid auth login``):一份带真 Key 的 ``settings.json`` 很容易被提交进仓库。
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
from __future__ import annotations
|
|
212
|
+
|
|
213
|
+
import json
|
|
214
|
+
import os
|
|
215
|
+
from collections.abc import Mapping, Sequence
|
|
216
|
+
from dataclasses import dataclass, field, replace
|
|
217
|
+
from pathlib import Path
|
|
218
|
+
from types import MappingProxyType
|
|
219
|
+
from typing import Literal, cast
|
|
220
|
+
from urllib.parse import urlsplit
|
|
221
|
+
|
|
222
|
+
from braid_ai import (
|
|
223
|
+
Model,
|
|
224
|
+
ModelCost,
|
|
225
|
+
Models,
|
|
226
|
+
)
|
|
227
|
+
from braid_ai.auth import AuthResolver, EnvAuthResolver
|
|
228
|
+
from braid_ai.models import EXTENDED_THINKING_LEVELS
|
|
229
|
+
from braid_ai.types import CACHE_ANCHORS, CacheAnchor, JsonValue, ModelInput, ModelThinkingLevel
|
|
230
|
+
from braid_ai.utils.clock import Clock
|
|
231
|
+
from braid_coding_agent.checkpoint.settings import CheckpointSettings
|
|
232
|
+
from braid_coding_agent.compaction.prepare import CompactionSettings
|
|
233
|
+
from braid_coding_agent.compaction.tool_results import (
|
|
234
|
+
DEFAULT_TOOL_RESULT_CLEANUP,
|
|
235
|
+
ToolResultCleanupSettings,
|
|
236
|
+
)
|
|
237
|
+
from braid_coding_agent.config_files import (
|
|
238
|
+
CONFIG_FILE_NAME,
|
|
239
|
+
CURRENT_CONFIG_VERSION,
|
|
240
|
+
PROJECT_CONFIG_DIR,
|
|
241
|
+
ConfigFileError,
|
|
242
|
+
document_version,
|
|
243
|
+
)
|
|
244
|
+
from braid_coding_agent.formatting.settings import (
|
|
245
|
+
DEFAULT_FORMAT_TIMEOUT_SECONDS,
|
|
246
|
+
PATH_PLACEHOLDER,
|
|
247
|
+
FormatSettings,
|
|
248
|
+
)
|
|
249
|
+
from braid_coding_agent.lsp.settings import (
|
|
250
|
+
DEFAULT_LSP_TIMEOUT_SECONDS,
|
|
251
|
+
LspServerSettings,
|
|
252
|
+
LspSettings,
|
|
253
|
+
merge_extensions,
|
|
254
|
+
normalize_extension,
|
|
255
|
+
)
|
|
256
|
+
from braid_coding_agent.network.settings import (
|
|
257
|
+
MAX_FETCH_CHARS,
|
|
258
|
+
MAX_SEARCH_RESULTS,
|
|
259
|
+
SEARCH_PROVIDERS,
|
|
260
|
+
WebSettings,
|
|
261
|
+
)
|
|
262
|
+
from braid_coding_agent.observability.settings import (
|
|
263
|
+
LOG_FORMATS,
|
|
264
|
+
LOG_LEVELS,
|
|
265
|
+
LogFormat,
|
|
266
|
+
ObservabilitySettings,
|
|
267
|
+
)
|
|
268
|
+
from braid_coding_agent.permissions.engine import (
|
|
269
|
+
PERMISSION_ACTIONS,
|
|
270
|
+
PERMISSION_MODES,
|
|
271
|
+
PermissionAction,
|
|
272
|
+
PermissionMode,
|
|
273
|
+
PermissionSettings,
|
|
274
|
+
)
|
|
275
|
+
from braid_coding_agent.permissions.model import RuleScope, RuleTable, ScopedRule
|
|
276
|
+
from braid_coding_agent.permissions.store import (
|
|
277
|
+
PermissionStore,
|
|
278
|
+
PermissionStoreError,
|
|
279
|
+
RuleFile,
|
|
280
|
+
load_rule_file,
|
|
281
|
+
)
|
|
282
|
+
from braid_coding_agent.sandbox.policy import (
|
|
283
|
+
BACKEND_NAMES,
|
|
284
|
+
NETWORK_MODES,
|
|
285
|
+
READ_SCOPES,
|
|
286
|
+
SANDBOX_MODES,
|
|
287
|
+
BackendName,
|
|
288
|
+
NetworkMode,
|
|
289
|
+
ReadScope,
|
|
290
|
+
SandboxMode,
|
|
291
|
+
SandboxSettings,
|
|
292
|
+
dedupe_domains,
|
|
293
|
+
)
|
|
294
|
+
from braid_coding_agent.settings import (
|
|
295
|
+
McpSettings,
|
|
296
|
+
SettingsError,
|
|
297
|
+
parse_mcp_settings,
|
|
298
|
+
)
|
|
299
|
+
from braid_coding_agent.statusline import DEFAULT_STATUS_FIELDS, STATUS_FIELD_KEYS
|
|
300
|
+
from braid_coding_agent.subagents.settings import MAX_ALLOWED_DEPTH, SubagentSettings
|
|
301
|
+
from braid_coding_agent.verify.settings import (
|
|
302
|
+
DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
303
|
+
DEFAULT_VERIFY_TIMEOUT_SECONDS,
|
|
304
|
+
VerifyCommand,
|
|
305
|
+
VerifySettings,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# 全局配置文件名与项目配置目录由 :mod:`braid_coding_agent.config_files` 定义,
|
|
309
|
+
# 它们与配置模板、版本迁移放在一起。
|
|
310
|
+
#: 兼容旧导入名;配置文件现在统一叫 ``settings.json``。
|
|
311
|
+
SETTINGS_FILE_NAME = CONFIG_FILE_NAME
|
|
312
|
+
#: 本仓库内置的三种协议适配器。``Model.api`` 决定运行时走哪一个。
|
|
313
|
+
MODEL_API = "openai-completions"
|
|
314
|
+
MODEL_API_RESPONSES = "openai-responses"
|
|
315
|
+
MODEL_API_ANTHROPIC = "anthropic-messages"
|
|
316
|
+
#: 默认缓存断点。只有需要显式标记的协议(Anthropic)读它,其余协议忽略。
|
|
317
|
+
#: 三个位置覆盖"工具 + 系统提示词 + 到本轮为止的对话",是增量缓存的自然形态。
|
|
318
|
+
DEFAULT_CACHE_BREAKPOINTS: tuple[CacheAnchor, ...] = ("tools", "system", "messages")
|
|
319
|
+
#: 内置条目的来源标签,出现在错误消息与 ``/models`` 里。
|
|
320
|
+
BUILTIN_SOURCE = "内置默认值"
|
|
321
|
+
#: 本机端点的主机名。写静态 ``api_key`` 时只认这三个。
|
|
322
|
+
LOCAL_ENDPOINT_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
|
|
323
|
+
|
|
324
|
+
#: 产品装配的重试默认值。
|
|
325
|
+
DEFAULT_RETRY_ENABLED = True
|
|
326
|
+
DEFAULT_RETRY_MAX_RETRIES = 3
|
|
327
|
+
DEFAULT_RETRY_BASE_DELAY_MS = 2_000
|
|
328
|
+
DEFAULT_RETRY_MAX_AGENT_DELAY_MS = 60_000
|
|
329
|
+
|
|
330
|
+
#: 简写供应商没有给出窗口与输出上限时的保守值。
|
|
331
|
+
DEFAULT_CUSTOM_CONTEXT_WINDOW = 128_000
|
|
332
|
+
DEFAULT_CUSTOM_MAX_TOKENS = 16_384
|
|
333
|
+
|
|
334
|
+
#: 环境变量:模型与思考级别的默认值。
|
|
335
|
+
ENV_MODEL = "BRAID_MODEL"
|
|
336
|
+
ENV_THINKING = "BRAID_THINKING"
|
|
337
|
+
#: 环境变量:自动重试。
|
|
338
|
+
ENV_RETRY_ENABLED = "BRAID_RETRY_ENABLED"
|
|
339
|
+
ENV_RETRY_MAX_RETRIES = "BRAID_RETRY_MAX_RETRIES"
|
|
340
|
+
ENV_RETRY_BASE_DELAY_MS = "BRAID_RETRY_BASE_DELAY_MS"
|
|
341
|
+
ENV_RETRY_MAX_AGENT_DELAY_MS = "BRAID_RETRY_MAX_AGENT_DELAY_MS"
|
|
342
|
+
#: 环境变量:自动压缩。
|
|
343
|
+
ENV_COMPACTION_ENABLED = "BRAID_COMPACTION_ENABLED"
|
|
344
|
+
ENV_COMPACTION_RESERVE_TOKENS = "BRAID_COMPACTION_RESERVE_TOKENS"
|
|
345
|
+
ENV_COMPACTION_KEEP_RECENT_TOKENS = "BRAID_COMPACTION_KEEP_RECENT_TOKENS"
|
|
346
|
+
|
|
347
|
+
#: 全部会被读取的环境变量,顺序即文档顺序。``braid auth status`` 与 ``/models`` 用它说明来源。
|
|
348
|
+
ENV_VARS: tuple[str, ...] = (
|
|
349
|
+
ENV_MODEL,
|
|
350
|
+
ENV_THINKING,
|
|
351
|
+
ENV_RETRY_ENABLED,
|
|
352
|
+
ENV_RETRY_MAX_RETRIES,
|
|
353
|
+
ENV_RETRY_BASE_DELAY_MS,
|
|
354
|
+
ENV_RETRY_MAX_AGENT_DELAY_MS,
|
|
355
|
+
ENV_COMPACTION_ENABLED,
|
|
356
|
+
ENV_COMPACTION_RESERVE_TOKENS,
|
|
357
|
+
ENV_COMPACTION_KEEP_RECENT_TOKENS,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
type MaxTokensField = Literal["max_tokens", "max_completion_tokens"]
|
|
361
|
+
type ModelApi = Literal["openai-completions", "openai-responses", "anthropic-messages"]
|
|
362
|
+
|
|
363
|
+
#: 字符串到协议字面量的查表。
|
|
364
|
+
_MODEL_API_BY_NAME: Mapping[str, ModelApi] = {
|
|
365
|
+
MODEL_API: MODEL_API,
|
|
366
|
+
MODEL_API_RESPONSES: MODEL_API_RESPONSES,
|
|
367
|
+
MODEL_API_ANTHROPIC: MODEL_API_ANTHROPIC,
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
#: 缓存断点的合法位置,按"请求里出现的先后"排列。
|
|
371
|
+
_ANCHORS: tuple[CacheAnchor, ...] = CACHE_ANCHORS
|
|
372
|
+
_ANCHOR_BY_NAME: Mapping[str, CacheAnchor] = {anchor: anchor for anchor in _ANCHORS}
|
|
373
|
+
|
|
374
|
+
#: 最大输出 token 的请求字段名。OpenAI 的新推理模型只认后一个。
|
|
375
|
+
_MAX_TOKENS_FIELDS: tuple[MaxTokensField, ...] = ("max_tokens", "max_completion_tokens")
|
|
376
|
+
#: 模型可接受的输入模态。
|
|
377
|
+
_INPUT_MODALITIES: tuple[ModelInput, ...] = ("text", "image")
|
|
378
|
+
#: 单价的四个分项,写成 ``cost_<名字>``。
|
|
379
|
+
_COST_PARTS = ("input", "output", "cache_read", "cache_write")
|
|
380
|
+
|
|
381
|
+
#: 字符串到字面量类型的查表。用 ``dict.get`` 查表,不用 ``in`` 加断言:
|
|
382
|
+
#: 返回值的类型直接就是目标字面量联合,不需要类型转换。
|
|
383
|
+
_INPUT_MODALITY_BY_NAME: Mapping[str, ModelInput] = {"text": "text", "image": "image"}
|
|
384
|
+
_MAX_TOKENS_FIELD_BY_NAME: Mapping[str, MaxTokensField] = {
|
|
385
|
+
"max_tokens": "max_tokens",
|
|
386
|
+
"max_completion_tokens": "max_completion_tokens",
|
|
387
|
+
}
|
|
388
|
+
_THINKING_LEVEL_BY_NAME: Mapping[str, ModelThinkingLevel] = {
|
|
389
|
+
level: level for level in EXTENDED_THINKING_LEVELS
|
|
390
|
+
}
|
|
391
|
+
#: 用查表拿回字面量类型,省掉一次 cast。
|
|
392
|
+
_PERMISSION_ACTION_BY_NAME: Mapping[str, PermissionAction] = {
|
|
393
|
+
action: action for action in PERMISSION_ACTIONS
|
|
394
|
+
}
|
|
395
|
+
_PERMISSION_MODE_BY_NAME: Mapping[str, PermissionMode] = {mode: mode for mode in PERMISSION_MODES}
|
|
396
|
+
|
|
397
|
+
_TOP_LEVEL_KEYS = frozenset(
|
|
398
|
+
{
|
|
399
|
+
"$schema",
|
|
400
|
+
"config_version",
|
|
401
|
+
"default_model",
|
|
402
|
+
"default_thinking",
|
|
403
|
+
"instructions",
|
|
404
|
+
"retry",
|
|
405
|
+
"compaction",
|
|
406
|
+
"statusline",
|
|
407
|
+
"providers",
|
|
408
|
+
"models",
|
|
409
|
+
"permission",
|
|
410
|
+
"sandbox",
|
|
411
|
+
"checkpoint",
|
|
412
|
+
"agents",
|
|
413
|
+
"web",
|
|
414
|
+
"lsp",
|
|
415
|
+
"verify",
|
|
416
|
+
"format",
|
|
417
|
+
"observability",
|
|
418
|
+
"mcp",
|
|
419
|
+
}
|
|
420
|
+
)
|
|
421
|
+
_PROVIDER_KEYS = frozenset(
|
|
422
|
+
{
|
|
423
|
+
"base_url",
|
|
424
|
+
"env_key",
|
|
425
|
+
"api_key",
|
|
426
|
+
"apikey",
|
|
427
|
+
"api",
|
|
428
|
+
"max_tokens_field",
|
|
429
|
+
"discover",
|
|
430
|
+
"discover_context_window",
|
|
431
|
+
"discover_max_tokens",
|
|
432
|
+
"cache_breakpoints",
|
|
433
|
+
}
|
|
434
|
+
)
|
|
435
|
+
_MODEL_KEYS = frozenset(
|
|
436
|
+
{
|
|
437
|
+
"name",
|
|
438
|
+
"context_window",
|
|
439
|
+
"max_tokens",
|
|
440
|
+
"input",
|
|
441
|
+
"reasoning",
|
|
442
|
+
"thinking_levels",
|
|
443
|
+
*(f"cost_{part}" for part in _COST_PARTS),
|
|
444
|
+
}
|
|
445
|
+
)
|
|
446
|
+
_RETRY_KEYS = frozenset({"enabled", "max_retries", "base_delay_ms", "max_agent_delay_ms"})
|
|
447
|
+
_COMPACTION_KEYS = frozenset({"enabled", "reserve_tokens", "keep_recent_tokens", "tool_results"})
|
|
448
|
+
_STATUSLINE_KEYS = frozenset({"fields"})
|
|
449
|
+
#: ``compaction.tool_results``:整段摘要之外那一层按条清理的开关与阈值。
|
|
450
|
+
_TOOL_RESULT_KEYS = frozenset({"enabled", "keep_recent", "min_chars", "trigger_ratio"})
|
|
451
|
+
_CHECKPOINT_KEYS = frozenset({"enabled", "max_file_bytes", "exclude"})
|
|
452
|
+
_AGENTS_KEYS = frozenset({"max_depth", "max_background", "max_concurrent", "timeout_seconds"})
|
|
453
|
+
_WEB_KEYS = frozenset(
|
|
454
|
+
{
|
|
455
|
+
"enabled",
|
|
456
|
+
"search_provider",
|
|
457
|
+
"search_max_results",
|
|
458
|
+
"search_endpoint",
|
|
459
|
+
"fetch_max_chars",
|
|
460
|
+
"cache_ttl_seconds",
|
|
461
|
+
"cache_max_entries",
|
|
462
|
+
"timeout_seconds",
|
|
463
|
+
"allow_private_hosts",
|
|
464
|
+
"user_agent",
|
|
465
|
+
}
|
|
466
|
+
)
|
|
467
|
+
_PERMISSION_KEYS = frozenset(
|
|
468
|
+
{"default", "mode", "approval_timeout_seconds", "tools", "bash", "paths", "domains"}
|
|
469
|
+
)
|
|
470
|
+
_PERMISSION_RULE_TABLES: tuple[RuleTable, ...] = ("tools", "bash", "paths", "domains")
|
|
471
|
+
#: ``lsp.<name>`` 的字段。``command`` 与 ``extensions`` 是数组,整体替换。
|
|
472
|
+
_LSP_KEYS = frozenset(
|
|
473
|
+
{
|
|
474
|
+
"command",
|
|
475
|
+
"extensions",
|
|
476
|
+
"language_id",
|
|
477
|
+
"root_markers",
|
|
478
|
+
"initialization_options",
|
|
479
|
+
"env",
|
|
480
|
+
"timeout_seconds",
|
|
481
|
+
"enabled",
|
|
482
|
+
}
|
|
483
|
+
)
|
|
484
|
+
_VERIFY_KEYS = frozenset(
|
|
485
|
+
{"enabled", "timeout_seconds", "fail_fast", "max_consecutive_failures", "commands"}
|
|
486
|
+
)
|
|
487
|
+
_VERIFY_COMMAND_KEYS = frozenset({"name", "command", "timeout_seconds"})
|
|
488
|
+
_FORMAT_KEYS = frozenset({"enabled", "timeout_seconds", "commands"})
|
|
489
|
+
_OBSERVABILITY_KEYS = frozenset(
|
|
490
|
+
{"enabled", "log_level", "log_format", "otel_enabled", "export_jsonl"}
|
|
491
|
+
)
|
|
492
|
+
#: ``sandbox`` 的字段。数组字段整体替换,标量逐字段覆盖。
|
|
493
|
+
_SANDBOX_KEYS = frozenset(
|
|
494
|
+
{
|
|
495
|
+
"mode",
|
|
496
|
+
"backend",
|
|
497
|
+
"network",
|
|
498
|
+
"read",
|
|
499
|
+
"allow_domains",
|
|
500
|
+
"deny_domains",
|
|
501
|
+
"writable_paths",
|
|
502
|
+
"readable_paths",
|
|
503
|
+
"executable",
|
|
504
|
+
}
|
|
505
|
+
)
|
|
506
|
+
_SANDBOX_MODE_BY_NAME: Mapping[str, SandboxMode] = {mode: mode for mode in SANDBOX_MODES}
|
|
507
|
+
_NETWORK_MODE_BY_NAME: Mapping[str, NetworkMode] = {mode: mode for mode in NETWORK_MODES}
|
|
508
|
+
_READ_SCOPE_BY_NAME: Mapping[str, ReadScope] = {scope: scope for scope in READ_SCOPES}
|
|
509
|
+
_BACKEND_BY_NAME: Mapping[str, BackendName] = {name: name for name in BACKEND_NAMES}
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class ConfigError(Exception):
|
|
513
|
+
"""配置文件不可用。CLI 把它翻成 :class:`~braid_coding_agent.cli.CliError`。"""
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# ------------------------------------------------------------------- 数据
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
@dataclass(slots=True, frozen=True)
|
|
520
|
+
class RetrySettings:
|
|
521
|
+
"""产品装配的自动重试设置。字段与 :class:`~braid_ai.retry.RetryPolicy` 一一对应。
|
|
522
|
+
|
|
523
|
+
这里只描述"用户想要什么",不含分类与退避逻辑;CLI 把它翻译成策略后交给会话层。
|
|
524
|
+
"""
|
|
525
|
+
|
|
526
|
+
enabled: bool = DEFAULT_RETRY_ENABLED
|
|
527
|
+
max_retries: int = DEFAULT_RETRY_MAX_RETRIES
|
|
528
|
+
base_delay_ms: int = DEFAULT_RETRY_BASE_DELAY_MS
|
|
529
|
+
max_agent_delay_ms: int = DEFAULT_RETRY_MAX_AGENT_DELAY_MS
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
@dataclass(slots=True, frozen=True)
|
|
533
|
+
class StatuslineSettings:
|
|
534
|
+
"""状态栏显示哪些字段、按什么顺序。项目配置里的 ``fields`` 整体替换全局值。"""
|
|
535
|
+
|
|
536
|
+
fields: tuple[str, ...] = DEFAULT_STATUS_FIELDS
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
@dataclass(slots=True, frozen=True)
|
|
540
|
+
class ProviderEntry:
|
|
541
|
+
"""一家端点的连接方式与它名下的模型。"""
|
|
542
|
+
|
|
543
|
+
id: str
|
|
544
|
+
base_url: str
|
|
545
|
+
#: 凭证环境变量名。``None`` 表示不读环境变量。
|
|
546
|
+
env_key: str | None
|
|
547
|
+
max_tokens_field: MaxTokensField
|
|
548
|
+
models: tuple[Model, ...]
|
|
549
|
+
#: 配置里写的静态密钥。只允许本机端点,见模块文档。
|
|
550
|
+
api_key: str | None = None
|
|
551
|
+
#: 静态密钥来自哪个文件。settings.json 的密钥允许用于远端端点。
|
|
552
|
+
api_key_source: str | None = None
|
|
553
|
+
#: 这个 provider 的模型走哪一套协议。
|
|
554
|
+
api: ModelApi = MODEL_API
|
|
555
|
+
#: 提示词缓存断点。只有 Anthropic 协议读它,其余协议忽略。
|
|
556
|
+
cache_breakpoints: tuple[CacheAnchor, ...] = DEFAULT_CACHE_BREAKPOINTS
|
|
557
|
+
#: 是否允许 ``--refresh-models`` 拉这个端点的 ``GET /models``。
|
|
558
|
+
discover: bool = False
|
|
559
|
+
#: 端点只回 id 清单时用这两个数补齐(端点自己给了元数据就不看它们)。
|
|
560
|
+
discover_context_window: int | None = None
|
|
561
|
+
discover_max_tokens: int | None = None
|
|
562
|
+
|
|
563
|
+
def find(self, model_id: str) -> Model | None:
|
|
564
|
+
for model in self.models:
|
|
565
|
+
if model.id == model_id:
|
|
566
|
+
return model
|
|
567
|
+
return None
|
|
568
|
+
|
|
569
|
+
@property
|
|
570
|
+
def credential_names(self) -> tuple[str, ...]:
|
|
571
|
+
"""该 Provider 认的环境变量名,给 ``AuthResolver`` 用。"""
|
|
572
|
+
return (self.env_key,) if self.env_key else ()
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
@dataclass(slots=True, frozen=True)
|
|
576
|
+
class AgentConfig:
|
|
577
|
+
"""一次进程启动时读到的完整配置:目录、重试、压缩与各层来源。
|
|
578
|
+
|
|
579
|
+
``providers`` 保持声明顺序:``/models`` 与 ``braid models`` 的显示顺序就是它,
|
|
580
|
+
内置条目在前、配置文件追加在后。``default_model_source`` 记录"默认模型是哪个
|
|
581
|
+
文件写的",用来说明"为什么启动时用的是这个模型"。
|
|
582
|
+
"""
|
|
583
|
+
|
|
584
|
+
providers: tuple[ProviderEntry, ...]
|
|
585
|
+
default_model: str | None = None
|
|
586
|
+
default_thinking: ModelThinkingLevel | None = None
|
|
587
|
+
default_model_source: str = BUILTIN_SOURCE
|
|
588
|
+
default_thinking_source: str = BUILTIN_SOURCE
|
|
589
|
+
retry: RetrySettings = field(default_factory=RetrySettings)
|
|
590
|
+
compaction: CompactionSettings = field(default_factory=CompactionSettings)
|
|
591
|
+
statusline: StatuslineSettings = field(default_factory=StatuslineSettings)
|
|
592
|
+
#: 真正读到的配置文件路径,按读取顺序。内置默认值不计入。
|
|
593
|
+
sources: tuple[str, ...] = ()
|
|
594
|
+
#: 由端点刷新得来的 ``provider/id``,用来在 ``/models`` 里标出"这个模型不是手写的"。
|
|
595
|
+
discovered: frozenset[str] = frozenset()
|
|
596
|
+
#: 生效的环境变量名,按 :data:`ENV_VARS` 的顺序。
|
|
597
|
+
env_overrides: tuple[str, ...] = ()
|
|
598
|
+
#: 额外指令文件:相对路径、绝对路径或 glob。排在自动发现的规则文件之后渲染。
|
|
599
|
+
instructions: tuple[str, ...] = ()
|
|
600
|
+
#: 权限判定与运行模式。三张规则表在读取时冻结,运行中不重读文件。
|
|
601
|
+
permission: PermissionSettings = field(default_factory=PermissionSettings)
|
|
602
|
+
#: 操作系统沙箱与网络边界。``mode = "off"``(默认)表示不做任何干预。
|
|
603
|
+
sandbox: SandboxSettings = field(default_factory=SandboxSettings)
|
|
604
|
+
#: 文件检查点:影子仓库快照、``/undo`` 与 ``/redo`` 的依据。
|
|
605
|
+
checkpoint: CheckpointSettings = field(default_factory=CheckpointSettings)
|
|
606
|
+
#: 子代理的嵌套深度、后台并发与单任务超时。
|
|
607
|
+
subagents: SubagentSettings = field(default_factory=SubagentSettings)
|
|
608
|
+
#: 网络工具:搜索来源、抓取上限、缓存与私网开关。
|
|
609
|
+
web: WebSettings = field(default_factory=WebSettings)
|
|
610
|
+
#: 语言服务器:按扩展名路由,懒启动。没有启用的服务器时不装配 ``lsp`` 工具。
|
|
611
|
+
lsp: LspSettings = field(default_factory=LspSettings)
|
|
612
|
+
#: 验证命令:顺序执行、汇总退出码。没有命令时不装配 ``verify`` 工具。
|
|
613
|
+
verify: VerifySettings = field(default_factory=VerifySettings)
|
|
614
|
+
#: 格式化命令:按扩展名分派。没有命令时不装配 ``format`` 工具。
|
|
615
|
+
format: FormatSettings = field(default_factory=FormatSettings)
|
|
616
|
+
#: 可观测性:结构化日志、span、权限审计。OTel 导出默认关闭。
|
|
617
|
+
observability: ObservabilitySettings = field(default_factory=ObservabilitySettings)
|
|
618
|
+
#: MCP 的全局加载方式、超时与缓存开关。服务器定义在 mcp.json。
|
|
619
|
+
mcp: McpSettings = field(default_factory=McpSettings)
|
|
620
|
+
#: 读到的配置格式版本。``config_version`` 缺失的文件按当前版本处理。
|
|
621
|
+
config_version: int = CURRENT_CONFIG_VERSION
|
|
622
|
+
|
|
623
|
+
def provider_ids(self) -> list[str]:
|
|
624
|
+
return [entry.id for entry in self.providers]
|
|
625
|
+
|
|
626
|
+
def provider(self, provider_id: str) -> ProviderEntry | None:
|
|
627
|
+
for entry in self.providers:
|
|
628
|
+
if entry.id == provider_id:
|
|
629
|
+
return entry
|
|
630
|
+
return None
|
|
631
|
+
|
|
632
|
+
def model_specs(self) -> list[str]:
|
|
633
|
+
"""``provider/id`` 清单,顺序即 ``/models`` 的显示顺序。"""
|
|
634
|
+
return [f"{entry.id}/{model.id}" for entry in self.providers for model in entry.models]
|
|
635
|
+
|
|
636
|
+
def models(self) -> list[Model]:
|
|
637
|
+
"""把各家的模型摊平成一个列表,顺序与 :meth:`model_specs` 一致。"""
|
|
638
|
+
return [model for entry in self.providers for model in entry.models]
|
|
639
|
+
|
|
640
|
+
def find(self, provider_id: str, model_id: str) -> Model | None:
|
|
641
|
+
entry = self.provider(provider_id)
|
|
642
|
+
return None if entry is None else entry.find(model_id)
|
|
643
|
+
|
|
644
|
+
def is_discovered(self, provider_id: str, model_id: str) -> bool:
|
|
645
|
+
"""这个模型是端点刷新带进来的,还是目录里写着的。"""
|
|
646
|
+
return f"{provider_id}/{model_id}" in self.discovered
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
# ------------------------------------------------------------- 合并草稿
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
@dataclass(slots=True)
|
|
653
|
+
class _ModelDraft:
|
|
654
|
+
"""合并过程中的一个模型。``None`` 表示"这份文件没写这个字段"。
|
|
655
|
+
|
|
656
|
+
``source`` 记最后写它的那份文件,构建期的"必填项缺失"要指回人真正编辑过的地方。
|
|
657
|
+
"""
|
|
658
|
+
|
|
659
|
+
provider_id: str
|
|
660
|
+
id: str
|
|
661
|
+
source: str
|
|
662
|
+
name: str | None = None
|
|
663
|
+
context_window: int | None = None
|
|
664
|
+
max_tokens: int | None = None
|
|
665
|
+
input: list[ModelInput] | None = None
|
|
666
|
+
reasoning: bool | None = None
|
|
667
|
+
thinking_levels: list[ModelThinkingLevel] | None = None
|
|
668
|
+
cost: dict[str, float] = field(default_factory=dict[str, float])
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
@dataclass(slots=True)
|
|
672
|
+
class _ProviderDraft:
|
|
673
|
+
"""合并过程中的一家端点。必填项在构建期检查。"""
|
|
674
|
+
|
|
675
|
+
source: str
|
|
676
|
+
base_url: str | None = None
|
|
677
|
+
env_key: str | None = None
|
|
678
|
+
api_key: str | None = None
|
|
679
|
+
api_key_source: str | None = None
|
|
680
|
+
#: 静态密钥是否允许用在远端端点。只有全局 ``~/.braid/settings.json`` 打开。
|
|
681
|
+
allow_remote_key: bool = False
|
|
682
|
+
api: ModelApi = MODEL_API
|
|
683
|
+
cache_breakpoints: tuple[CacheAnchor, ...] = DEFAULT_CACHE_BREAKPOINTS
|
|
684
|
+
max_tokens_field: MaxTokensField = "max_tokens"
|
|
685
|
+
discover: bool = False
|
|
686
|
+
discover_context_window: int | None = None
|
|
687
|
+
discover_max_tokens: int | None = None
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
@dataclass(slots=True)
|
|
691
|
+
class _Defaults:
|
|
692
|
+
model: str | None = None
|
|
693
|
+
thinking: ModelThinkingLevel | None = None
|
|
694
|
+
model_source: str = BUILTIN_SOURCE
|
|
695
|
+
thinking_source: str = BUILTIN_SOURCE
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
@dataclass(slots=True)
|
|
699
|
+
class _LspDraft:
|
|
700
|
+
"""合并过程中的一台语言服务器。``None`` 表示"这份文件没写这个字段"。"""
|
|
701
|
+
|
|
702
|
+
name: str
|
|
703
|
+
source: str
|
|
704
|
+
command: tuple[str, ...] | None = None
|
|
705
|
+
extensions: tuple[str, ...] | None = None
|
|
706
|
+
language_id: str | None = None
|
|
707
|
+
root_markers: tuple[str, ...] | None = None
|
|
708
|
+
initialization_options: dict[str, JsonValue] | None = None
|
|
709
|
+
env: dict[str, str] | None = None
|
|
710
|
+
timeout_seconds: float | None = None
|
|
711
|
+
enabled: bool | None = None
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
@dataclass(slots=True)
|
|
715
|
+
class _VerifyDraft:
|
|
716
|
+
"""``verify`` 的合并草稿。``commands`` 整体替换,不做逐条合并。"""
|
|
717
|
+
|
|
718
|
+
enabled: bool = True
|
|
719
|
+
timeout_seconds: float = DEFAULT_VERIFY_TIMEOUT_SECONDS
|
|
720
|
+
fail_fast: bool = False
|
|
721
|
+
max_consecutive_failures: int = DEFAULT_MAX_CONSECUTIVE_FAILURES
|
|
722
|
+
commands: tuple[VerifyCommand, ...] = ()
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
@dataclass(slots=True)
|
|
726
|
+
class _FormatDraft:
|
|
727
|
+
"""``format`` 的合并草稿。``commands`` 按扩展名逐键合并。"""
|
|
728
|
+
|
|
729
|
+
enabled: bool = True
|
|
730
|
+
timeout_seconds: float = DEFAULT_FORMAT_TIMEOUT_SECONDS
|
|
731
|
+
commands: dict[str, tuple[str, ...]] = field(default_factory=dict[str, tuple[str, ...]])
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
# ------------------------------------------------------------- 读取与合并
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def load_config(
|
|
738
|
+
*,
|
|
739
|
+
agent_dir: Path,
|
|
740
|
+
cwd: str,
|
|
741
|
+
extra_files: Sequence[Path] = (),
|
|
742
|
+
env: Mapping[str, str] | None = None,
|
|
743
|
+
trust_project: bool = False,
|
|
744
|
+
) -> AgentConfig:
|
|
745
|
+
"""按"内置默认值 → 全局 → 全局运行时规则 → 项目 → 项目运行时规则 → ``--config``
|
|
746
|
+
→ 环境变量"的顺序合成配置。
|
|
747
|
+
|
|
748
|
+
:param agent_dir: 全局配置目录(通常是 ``~/.braid``)。
|
|
749
|
+
:param cwd: 工作目录,项目配置在它的 ``.braid/`` 下。
|
|
750
|
+
:param extra_files: ``--config`` 给出的文件,按给出顺序读取,后者覆盖前者。
|
|
751
|
+
这些文件是显式指定的,不存在时报错;全局与项目配置不存在属于正常情况。
|
|
752
|
+
:param env: 环境变量表,缺省读 ``os.environ``。测试注入一个普通 dict 即可离线驱动。
|
|
753
|
+
:param trust_project: 本次运行信任当前项目。未信任项目的权限配置只取 deny 规则,
|
|
754
|
+
模式与默认动作沿用全局设置。
|
|
755
|
+
:raises ConfigError: 文件读不出来、不是合法 JSON、字段非法或必填项缺失。
|
|
756
|
+
"""
|
|
757
|
+
store = PermissionStore(agent_dir=agent_dir, cwd=cwd)
|
|
758
|
+
project_trusted = trust_project or store.is_project_trusted()
|
|
759
|
+
providers: dict[str, _ProviderDraft] = _builtin_providers()
|
|
760
|
+
models: dict[tuple[str, str], _ModelDraft] = _builtin_models()
|
|
761
|
+
defaults = _Defaults()
|
|
762
|
+
retry = RetrySettings()
|
|
763
|
+
compaction = CompactionSettings()
|
|
764
|
+
statusline = StatuslineSettings()
|
|
765
|
+
permission = PermissionSettings(project_trusted=project_trusted)
|
|
766
|
+
sandbox = SandboxSettings()
|
|
767
|
+
checkpoint = CheckpointSettings()
|
|
768
|
+
subagents = SubagentSettings()
|
|
769
|
+
web = WebSettings()
|
|
770
|
+
lsp: dict[str, _LspDraft] = {}
|
|
771
|
+
verify = _VerifyDraft()
|
|
772
|
+
formatting = _FormatDraft()
|
|
773
|
+
observability = ObservabilitySettings()
|
|
774
|
+
instructions: list[str] = []
|
|
775
|
+
sources: list[str] = []
|
|
776
|
+
mcp_settings = McpSettings()
|
|
777
|
+
|
|
778
|
+
explicit = {str(path.expanduser()) for path in extra_files}
|
|
779
|
+
global_config = agent_dir / CONFIG_FILE_NAME
|
|
780
|
+
project_config = Path(cwd) / PROJECT_CONFIG_DIR / CONFIG_FILE_NAME
|
|
781
|
+
for legacy in (
|
|
782
|
+
agent_dir / "config.toml",
|
|
783
|
+
Path(cwd) / PROJECT_CONFIG_DIR / "config.toml",
|
|
784
|
+
):
|
|
785
|
+
if legacy.is_file():
|
|
786
|
+
raise ConfigError(
|
|
787
|
+
f"{legacy}: TOML 配置支持已移除;把内容写到同目录的 {CONFIG_FILE_NAME}"
|
|
788
|
+
)
|
|
789
|
+
layers: list[tuple[Path, RuleScope, bool, str]] = [
|
|
790
|
+
(global_config, "global", True, "config"),
|
|
791
|
+
(store.global_path, "global", True, "rules"),
|
|
792
|
+
(project_config, "project", project_trusted, "config"),
|
|
793
|
+
(store.project_path, "project", project_trusted, "rules"),
|
|
794
|
+
]
|
|
795
|
+
layers.extend((path.expanduser(), "global", True, "config") for path in extra_files)
|
|
796
|
+
|
|
797
|
+
for path, scope, trusted, kind in layers:
|
|
798
|
+
if kind == "rules":
|
|
799
|
+
try:
|
|
800
|
+
rule_file = load_rule_file(path, scope=scope, source=str(path), trusted=trusted)
|
|
801
|
+
except PermissionStoreError as exc:
|
|
802
|
+
raise ConfigError(str(exc)) from exc
|
|
803
|
+
if path.is_file():
|
|
804
|
+
sources.append(str(path))
|
|
805
|
+
permission = _merge_rule_file(permission, rule_file)
|
|
806
|
+
continue
|
|
807
|
+
document = _read_document(path, required=str(path) in explicit)
|
|
808
|
+
if document is None:
|
|
809
|
+
continue
|
|
810
|
+
(
|
|
811
|
+
retry,
|
|
812
|
+
compaction,
|
|
813
|
+
permission,
|
|
814
|
+
sandbox,
|
|
815
|
+
checkpoint,
|
|
816
|
+
subagents,
|
|
817
|
+
web,
|
|
818
|
+
observability,
|
|
819
|
+
statusline,
|
|
820
|
+
mcp_settings,
|
|
821
|
+
) = _merge_document(
|
|
822
|
+
document,
|
|
823
|
+
where=str(path),
|
|
824
|
+
providers=providers,
|
|
825
|
+
models=models,
|
|
826
|
+
defaults=defaults,
|
|
827
|
+
retry=retry,
|
|
828
|
+
compaction=compaction,
|
|
829
|
+
permission=permission,
|
|
830
|
+
sandbox=sandbox,
|
|
831
|
+
checkpoint=checkpoint,
|
|
832
|
+
subagents=subagents,
|
|
833
|
+
web=web,
|
|
834
|
+
statusline=statusline,
|
|
835
|
+
lsp=lsp,
|
|
836
|
+
verify=verify,
|
|
837
|
+
formatting=formatting,
|
|
838
|
+
instructions=instructions,
|
|
839
|
+
observability=observability,
|
|
840
|
+
mcp=mcp_settings,
|
|
841
|
+
permission_trusted=trusted,
|
|
842
|
+
permission_scope=scope,
|
|
843
|
+
permission_source=str(path),
|
|
844
|
+
allow_remote_key=path == global_config,
|
|
845
|
+
)
|
|
846
|
+
sources.append(str(path))
|
|
847
|
+
|
|
848
|
+
defaults, retry, compaction, applied = _apply_env(
|
|
849
|
+
os.environ if env is None else env,
|
|
850
|
+
defaults=defaults,
|
|
851
|
+
retry=retry,
|
|
852
|
+
compaction=compaction,
|
|
853
|
+
)
|
|
854
|
+
return _build_config(
|
|
855
|
+
providers=providers,
|
|
856
|
+
models=models,
|
|
857
|
+
defaults=defaults,
|
|
858
|
+
retry=retry,
|
|
859
|
+
compaction=compaction,
|
|
860
|
+
statusline=statusline,
|
|
861
|
+
sources=tuple(sources),
|
|
862
|
+
env_overrides=applied,
|
|
863
|
+
instructions=tuple(instructions),
|
|
864
|
+
permission=permission,
|
|
865
|
+
sandbox=sandbox,
|
|
866
|
+
checkpoint=checkpoint,
|
|
867
|
+
subagents=subagents,
|
|
868
|
+
web=web,
|
|
869
|
+
lsp=lsp,
|
|
870
|
+
verify=verify,
|
|
871
|
+
formatting=formatting,
|
|
872
|
+
observability=observability,
|
|
873
|
+
mcp=mcp_settings,
|
|
874
|
+
)
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
def _builtin_providers() -> dict[str, _ProviderDraft]:
|
|
878
|
+
"""内置目录里的端点。只放核对过官方文档的条目,数字后面注明出处。
|
|
879
|
+
|
|
880
|
+
其余端点由配置文件添加。内置条目可以被配置文件逐字段覆盖,
|
|
881
|
+
所以"内置里没有"从来不构成限制。
|
|
882
|
+
"""
|
|
883
|
+
return {
|
|
884
|
+
# 数值来源:https://api-docs.deepseek.com/zh-cn/quick_start/pricing(2026-11-08 读取)。
|
|
885
|
+
# 两个 id 是端点自己列的(``GET /v1/models``);上下文 1M、最大输出 384K;
|
|
886
|
+
# 思考档位 low/high/max(端点 metadata 的 ``effort.supported_levels``)。
|
|
887
|
+
# 价格按每百万 token 的美元计,取自 models.dev 的 deepseek 条目。
|
|
888
|
+
"deepseek": _ProviderDraft(
|
|
889
|
+
source=BUILTIN_SOURCE,
|
|
890
|
+
base_url="https://api.deepseek.com/v1",
|
|
891
|
+
env_key="DEEPSEEK_API_KEY",
|
|
892
|
+
max_tokens_field="max_tokens",
|
|
893
|
+
# 这个端点会回上下文、输出上限、模态与档位,是发现能力最完整的一家。
|
|
894
|
+
discover=True,
|
|
895
|
+
),
|
|
896
|
+
# 数值来源:models.dev 的 openai 条目(2026-11-08 读取),与
|
|
897
|
+
# https://learn.chatgpt.com/api/docs/models 的模型页一致:上下文 1.05M、
|
|
898
|
+
# 最大输出 128K、推理档位 low…max、输入含图片。``pdf`` 模态本仓库不建模,略过。
|
|
899
|
+
#
|
|
900
|
+
# ``max_tokens_field`` 用 ``max_completion_tokens``:这一代推理模型只认这个字段。
|
|
901
|
+
# ``discover`` 保持关闭——这个端点的 ``/models`` 只回 id 清单,没有上下文与输出
|
|
902
|
+
# 上限,靠它补进来的模型只能套用一组猜测出来的数字。
|
|
903
|
+
"openai": _ProviderDraft(
|
|
904
|
+
source=BUILTIN_SOURCE,
|
|
905
|
+
base_url="https://api.openai.com/v1",
|
|
906
|
+
env_key="OPENAI_API_KEY",
|
|
907
|
+
max_tokens_field="max_completion_tokens",
|
|
908
|
+
),
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _builtin_models() -> dict[tuple[str, str], _ModelDraft]:
|
|
913
|
+
"""内置目录里的模型,键是 ``(provider id, 模型 id)``。"""
|
|
914
|
+
thinking: list[ModelThinkingLevel] = ["off", "low", "high", "max"]
|
|
915
|
+
return {
|
|
916
|
+
("deepseek", "deepseek-flash"): _ModelDraft(
|
|
917
|
+
provider_id="deepseek",
|
|
918
|
+
id="deepseek-flash",
|
|
919
|
+
source=BUILTIN_SOURCE,
|
|
920
|
+
name="DeepSeek V4.1 Flash",
|
|
921
|
+
context_window=1_048_576,
|
|
922
|
+
max_tokens=393_216,
|
|
923
|
+
input=["text", "image"],
|
|
924
|
+
reasoning=True,
|
|
925
|
+
thinking_levels=thinking,
|
|
926
|
+
cost={"input": 0.15, "output": 0.6, "cache_read": 0.003},
|
|
927
|
+
),
|
|
928
|
+
("deepseek", "deepseek-v4-pro"): _ModelDraft(
|
|
929
|
+
provider_id="deepseek",
|
|
930
|
+
id="deepseek-v4-pro",
|
|
931
|
+
source=BUILTIN_SOURCE,
|
|
932
|
+
name="DeepSeek V4 Pro",
|
|
933
|
+
context_window=1_048_576,
|
|
934
|
+
max_tokens=393_216,
|
|
935
|
+
input=["text"],
|
|
936
|
+
reasoning=True,
|
|
937
|
+
thinking_levels=thinking,
|
|
938
|
+
cost={"input": 0.66, "output": 1.98, "cache_read": 0.022},
|
|
939
|
+
),
|
|
940
|
+
("openai", "gpt-6.1-sol"): _ModelDraft(
|
|
941
|
+
provider_id="openai",
|
|
942
|
+
id="gpt-6.1-sol",
|
|
943
|
+
source=BUILTIN_SOURCE,
|
|
944
|
+
name="GPT-6.1 Sol",
|
|
945
|
+
context_window=1_050_000,
|
|
946
|
+
max_tokens=128_000,
|
|
947
|
+
input=["text", "image"],
|
|
948
|
+
reasoning=True,
|
|
949
|
+
thinking_levels=["off", "low", "medium", "high", "xhigh", "max"],
|
|
950
|
+
cost={"input": 2.0, "output": 10.0, "cache_read": 0.1, "cache_write": 2.5},
|
|
951
|
+
),
|
|
952
|
+
("openai", "gpt-6.1-terra"): _ModelDraft(
|
|
953
|
+
provider_id="openai",
|
|
954
|
+
id="gpt-6.1-terra",
|
|
955
|
+
source=BUILTIN_SOURCE,
|
|
956
|
+
name="GPT-6.1 Terra",
|
|
957
|
+
context_window=1_050_000,
|
|
958
|
+
max_tokens=128_000,
|
|
959
|
+
input=["text", "image"],
|
|
960
|
+
reasoning=True,
|
|
961
|
+
thinking_levels=["off", "low", "medium", "high", "xhigh", "max"],
|
|
962
|
+
cost={"input": 1.0, "output": 5.0, "cache_read": 0.05, "cache_write": 1.25},
|
|
963
|
+
),
|
|
964
|
+
("openai", "gpt-6-astra"): _ModelDraft(
|
|
965
|
+
provider_id="openai",
|
|
966
|
+
id="gpt-6-astra",
|
|
967
|
+
source=BUILTIN_SOURCE,
|
|
968
|
+
name="GPT-6 Astra",
|
|
969
|
+
context_window=1_050_000,
|
|
970
|
+
max_tokens=128_000,
|
|
971
|
+
input=["text", "image"],
|
|
972
|
+
reasoning=True,
|
|
973
|
+
thinking_levels=["off", "low", "medium", "high", "xhigh", "max"],
|
|
974
|
+
cost={"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write": 12.5},
|
|
975
|
+
),
|
|
976
|
+
("openai", "gpt-6-sol"): _ModelDraft(
|
|
977
|
+
provider_id="openai",
|
|
978
|
+
id="gpt-6-sol",
|
|
979
|
+
source=BUILTIN_SOURCE,
|
|
980
|
+
name="GPT-6 Sol",
|
|
981
|
+
context_window=1_050_000,
|
|
982
|
+
max_tokens=128_000,
|
|
983
|
+
input=["text", "image"],
|
|
984
|
+
reasoning=True,
|
|
985
|
+
thinking_levels=["off", "low", "medium", "high", "xhigh", "max"],
|
|
986
|
+
cost={"input": 2.0, "output": 10.0, "cache_read": 0.2, "cache_write": 2.5},
|
|
987
|
+
),
|
|
988
|
+
("openai", "gpt-6-luna"): _ModelDraft(
|
|
989
|
+
provider_id="openai",
|
|
990
|
+
id="gpt-6-luna",
|
|
991
|
+
source=BUILTIN_SOURCE,
|
|
992
|
+
name="GPT-6 Luna",
|
|
993
|
+
context_window=1_050_000,
|
|
994
|
+
max_tokens=128_000,
|
|
995
|
+
input=["text", "image"],
|
|
996
|
+
reasoning=True,
|
|
997
|
+
thinking_levels=["off", "low", "medium", "high", "xhigh", "max"],
|
|
998
|
+
cost={"input": 0.1, "output": 0.5, "cache_read": 0.01, "cache_write": 0.125},
|
|
999
|
+
),
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def _read_document(path: Path, *, required: bool) -> dict[str, JsonValue] | None:
|
|
1004
|
+
"""读一份 JSON 配置,文件不存在时按 ``required`` 决定报错或跳过。"""
|
|
1005
|
+
if not path.is_file():
|
|
1006
|
+
if required:
|
|
1007
|
+
raise ConfigError(f"{path}: 配置文件不存在(--config 指向的路径必须可读)")
|
|
1008
|
+
return None
|
|
1009
|
+
if path.suffix == ".toml":
|
|
1010
|
+
raise ConfigError(f"{path}: TOML 配置支持已移除,请改用 {CONFIG_FILE_NAME}")
|
|
1011
|
+
try:
|
|
1012
|
+
text = path.read_bytes().decode("utf-8-sig")
|
|
1013
|
+
except OSError as exc:
|
|
1014
|
+
raise ConfigError(f"{path}: 无法读取配置文件:{exc}") from exc
|
|
1015
|
+
except UnicodeDecodeError as exc:
|
|
1016
|
+
raise ConfigError(f"{path}: 配置文件不是 UTF-8:{exc}") from exc
|
|
1017
|
+
try:
|
|
1018
|
+
parsed = json.loads(text)
|
|
1019
|
+
except ValueError as exc:
|
|
1020
|
+
raise ConfigError(f"{path}: 不是合法的 JSON:{exc}") from exc
|
|
1021
|
+
if not isinstance(parsed, dict):
|
|
1022
|
+
raise ConfigError(f"{path}: 顶层必须是 JSON 对象")
|
|
1023
|
+
document = cast("dict[str, JsonValue]", parsed)
|
|
1024
|
+
try:
|
|
1025
|
+
document_version(document, where=str(path))
|
|
1026
|
+
except ConfigFileError as exc:
|
|
1027
|
+
raise ConfigError(str(exc)) from exc
|
|
1028
|
+
return _normalize_settings(document, where=str(path))
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
_FLAT_PROVIDER_KEYS = frozenset(
|
|
1032
|
+
{
|
|
1033
|
+
"base_url",
|
|
1034
|
+
"apikey",
|
|
1035
|
+
"api_key",
|
|
1036
|
+
"env_key",
|
|
1037
|
+
"api",
|
|
1038
|
+
"max_tokens_field",
|
|
1039
|
+
"cache_breakpoints",
|
|
1040
|
+
}
|
|
1041
|
+
)
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
def _normalize_settings(document: dict[str, JsonValue], *, where: str) -> dict[str, JsonValue]:
|
|
1045
|
+
"""把 settings.json 的简写展开成统一的 providers 与 models 结构。
|
|
1046
|
+
|
|
1047
|
+
同时接受三种写法:顶层扁平供应商、``providers`` 里带 ``models`` 数组的简写、
|
|
1048
|
+
以及完整的 ``providers`` 加 ``models`` 两张表。展开结果只保留最后一种形状,
|
|
1049
|
+
后续合并逻辑因此只有一条路径。
|
|
1050
|
+
"""
|
|
1051
|
+
normalized = dict(document)
|
|
1052
|
+
normalized.pop("$schema", None)
|
|
1053
|
+
|
|
1054
|
+
flat_present = bool(_FLAT_PROVIDER_KEYS & set(normalized)) or "model" in normalized
|
|
1055
|
+
if flat_present and "providers" in normalized:
|
|
1056
|
+
raise ConfigError(f"{where}: 扁平写法与 providers 二选一,不能同时出现")
|
|
1057
|
+
|
|
1058
|
+
raw_models = normalized.get("models", {})
|
|
1059
|
+
if not isinstance(raw_models, dict):
|
|
1060
|
+
raise ConfigError(f'{where}: models 必须是 JSON 对象,键写成 "provider/模型 id"')
|
|
1061
|
+
models: dict[str, JsonValue] = dict(raw_models)
|
|
1062
|
+
|
|
1063
|
+
if flat_present:
|
|
1064
|
+
provider: dict[str, JsonValue] = {"base_url": normalized.pop("base_url", None)}
|
|
1065
|
+
if provider["base_url"] is None:
|
|
1066
|
+
raise ConfigError(f"{where}: base_url 必填")
|
|
1067
|
+
for key in ("apikey", "api_key", "env_key", "api", "max_tokens_field", "cache_breakpoints"):
|
|
1068
|
+
if key in normalized:
|
|
1069
|
+
provider["api_key" if key == "apikey" else key] = normalized.pop(key)
|
|
1070
|
+
if "api_key" not in provider and "env_key" not in provider:
|
|
1071
|
+
raise ConfigError(f"{where}: api_key 或 env_key 至少要有一个")
|
|
1072
|
+
model_id = normalized.pop("model", None)
|
|
1073
|
+
if not isinstance(model_id, str) or not model_id.strip():
|
|
1074
|
+
raise ConfigError(f"{where}: model 必须是模型 id")
|
|
1075
|
+
context_window = normalized.pop("context_window", DEFAULT_CUSTOM_CONTEXT_WINDOW)
|
|
1076
|
+
max_tokens = normalized.pop("max_tokens", DEFAULT_CUSTOM_MAX_TOKENS)
|
|
1077
|
+
model: dict[str, JsonValue] = {}
|
|
1078
|
+
if context_window is not None:
|
|
1079
|
+
model["context_window"] = context_window
|
|
1080
|
+
if max_tokens is not None:
|
|
1081
|
+
model["max_tokens"] = max_tokens
|
|
1082
|
+
normalized["providers"] = {"custom": provider}
|
|
1083
|
+
models[f"custom/{model_id.strip()}"] = model
|
|
1084
|
+
|
|
1085
|
+
raw_providers = normalized.get("providers")
|
|
1086
|
+
if raw_providers is not None:
|
|
1087
|
+
if not isinstance(raw_providers, dict):
|
|
1088
|
+
raise ConfigError(f"{where}: providers 必须是 JSON 对象")
|
|
1089
|
+
providers: dict[str, JsonValue] = {}
|
|
1090
|
+
for provider_id, raw_entry in raw_providers.items():
|
|
1091
|
+
if not isinstance(raw_entry, dict):
|
|
1092
|
+
raise ConfigError(f"{where}: providers.{provider_id} 必须是 JSON 对象")
|
|
1093
|
+
entry = dict(raw_entry)
|
|
1094
|
+
if "apikey" in entry:
|
|
1095
|
+
entry["api_key"] = entry.pop("apikey")
|
|
1096
|
+
if "models" in entry:
|
|
1097
|
+
model_ids = entry.pop("models")
|
|
1098
|
+
if not isinstance(model_ids, list) or not model_ids:
|
|
1099
|
+
raise ConfigError(
|
|
1100
|
+
f"{where}: providers.{provider_id}.models 必须是非空的模型 id 数组"
|
|
1101
|
+
)
|
|
1102
|
+
context_window = entry.pop("context_window", DEFAULT_CUSTOM_CONTEXT_WINDOW)
|
|
1103
|
+
max_tokens = entry.pop("max_tokens", DEFAULT_CUSTOM_MAX_TOKENS)
|
|
1104
|
+
for index, model_id in enumerate(model_ids):
|
|
1105
|
+
if not isinstance(model_id, str) or not model_id.strip():
|
|
1106
|
+
raise ConfigError(
|
|
1107
|
+
f"{where}: providers.{provider_id}.models[{index}] 必须是非空字符串"
|
|
1108
|
+
)
|
|
1109
|
+
model_defaults: dict[str, JsonValue] = {}
|
|
1110
|
+
if context_window is not None:
|
|
1111
|
+
model_defaults["context_window"] = context_window
|
|
1112
|
+
if max_tokens is not None:
|
|
1113
|
+
model_defaults["max_tokens"] = max_tokens
|
|
1114
|
+
spec = f"{provider_id}/{model_id.strip()}"
|
|
1115
|
+
explicit = models.get(spec)
|
|
1116
|
+
if explicit is not None and not isinstance(explicit, dict):
|
|
1117
|
+
raise ConfigError(f"{where}: models.{spec} 必须是 JSON 对象")
|
|
1118
|
+
existing_model = cast("dict[str, JsonValue]", explicit or {})
|
|
1119
|
+
models[spec] = {**model_defaults, **existing_model}
|
|
1120
|
+
if "api_key" not in entry and "env_key" not in entry:
|
|
1121
|
+
raise ConfigError(
|
|
1122
|
+
f"{where}: providers.{provider_id} 的 api_key 或 env_key 至少要有一个"
|
|
1123
|
+
)
|
|
1124
|
+
providers[provider_id] = entry
|
|
1125
|
+
normalized["providers"] = providers
|
|
1126
|
+
|
|
1127
|
+
normalized["models"] = models
|
|
1128
|
+
return normalized
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _merge_document(
|
|
1132
|
+
document: Mapping[str, JsonValue],
|
|
1133
|
+
*,
|
|
1134
|
+
where: str,
|
|
1135
|
+
providers: dict[str, _ProviderDraft],
|
|
1136
|
+
models: dict[tuple[str, str], _ModelDraft],
|
|
1137
|
+
defaults: _Defaults,
|
|
1138
|
+
retry: RetrySettings,
|
|
1139
|
+
compaction: CompactionSettings,
|
|
1140
|
+
statusline: StatuslineSettings,
|
|
1141
|
+
permission: PermissionSettings,
|
|
1142
|
+
sandbox: SandboxSettings,
|
|
1143
|
+
checkpoint: CheckpointSettings,
|
|
1144
|
+
subagents: SubagentSettings,
|
|
1145
|
+
web: WebSettings,
|
|
1146
|
+
lsp: dict[str, _LspDraft],
|
|
1147
|
+
verify: _VerifyDraft,
|
|
1148
|
+
formatting: _FormatDraft,
|
|
1149
|
+
instructions: list[str],
|
|
1150
|
+
observability: ObservabilitySettings,
|
|
1151
|
+
mcp: McpSettings,
|
|
1152
|
+
permission_trusted: bool = True,
|
|
1153
|
+
permission_scope: RuleScope = "global",
|
|
1154
|
+
permission_source: str = "",
|
|
1155
|
+
allow_remote_key: bool = False,
|
|
1156
|
+
) -> tuple[
|
|
1157
|
+
RetrySettings,
|
|
1158
|
+
CompactionSettings,
|
|
1159
|
+
PermissionSettings,
|
|
1160
|
+
SandboxSettings,
|
|
1161
|
+
CheckpointSettings,
|
|
1162
|
+
SubagentSettings,
|
|
1163
|
+
WebSettings,
|
|
1164
|
+
ObservabilitySettings,
|
|
1165
|
+
StatuslineSettings,
|
|
1166
|
+
McpSettings,
|
|
1167
|
+
]:
|
|
1168
|
+
"""把一份文件并进草稿,返回它带来的各项设置。"""
|
|
1169
|
+
unknown = sorted(set(document) - _TOP_LEVEL_KEYS)
|
|
1170
|
+
if unknown:
|
|
1171
|
+
raise ConfigError(
|
|
1172
|
+
f"{where}: 未知的配置项 {', '.join(unknown)}"
|
|
1173
|
+
f"(可用: {', '.join(sorted(_TOP_LEVEL_KEYS))})"
|
|
1174
|
+
)
|
|
1175
|
+
|
|
1176
|
+
raw_providers = document.get("providers")
|
|
1177
|
+
if raw_providers is not None:
|
|
1178
|
+
if not isinstance(raw_providers, dict):
|
|
1179
|
+
raise ConfigError(f"{where}: providers 必须是 JSON 对象")
|
|
1180
|
+
for provider_id, raw in raw_providers.items():
|
|
1181
|
+
_merge_provider(
|
|
1182
|
+
provider_id,
|
|
1183
|
+
raw,
|
|
1184
|
+
where=where,
|
|
1185
|
+
providers=providers,
|
|
1186
|
+
allow_remote_key=allow_remote_key,
|
|
1187
|
+
)
|
|
1188
|
+
|
|
1189
|
+
raw_models = document.get("models")
|
|
1190
|
+
if raw_models is not None:
|
|
1191
|
+
if not isinstance(raw_models, dict):
|
|
1192
|
+
raise ConfigError(
|
|
1193
|
+
f'{where}: models 必须是 JSON 对象,键写成 "provider/模型 id"'
|
|
1194
|
+
'(例如 "deepseek/deepseek-flash": {...})'
|
|
1195
|
+
)
|
|
1196
|
+
for spec, raw in raw_models.items():
|
|
1197
|
+
_merge_model(spec, raw, where=where, models=models)
|
|
1198
|
+
|
|
1199
|
+
if "default_model" in document:
|
|
1200
|
+
defaults.model = _non_empty_text(document["default_model"], where=f"{where}: default_model")
|
|
1201
|
+
defaults.model_source = where
|
|
1202
|
+
if "default_thinking" in document:
|
|
1203
|
+
defaults.thinking = _as_thinking_level(
|
|
1204
|
+
document["default_thinking"], where=f"{where}: default_thinking"
|
|
1205
|
+
)
|
|
1206
|
+
defaults.thinking_source = where
|
|
1207
|
+
|
|
1208
|
+
if "instructions" in document:
|
|
1209
|
+
raw_instructions = document["instructions"]
|
|
1210
|
+
if not isinstance(raw_instructions, list):
|
|
1211
|
+
raise ConfigError(f"{where}: instructions 必须是字符串数组")
|
|
1212
|
+
parsed = [
|
|
1213
|
+
_non_empty_text(value, where=f"{where}: instructions[{index}]")
|
|
1214
|
+
for index, value in enumerate(raw_instructions)
|
|
1215
|
+
]
|
|
1216
|
+
# 数组整体替换:拼两层清单会让"删掉一条规则"写不出来。
|
|
1217
|
+
instructions.clear()
|
|
1218
|
+
instructions.extend(parsed)
|
|
1219
|
+
|
|
1220
|
+
_merge_lsp(document, where=where, lsp=lsp)
|
|
1221
|
+
_merge_verify(document, where=where, verify=verify)
|
|
1222
|
+
_merge_format(document, where=where, formatting=formatting)
|
|
1223
|
+
try:
|
|
1224
|
+
merged_mcp = parse_mcp_settings(document.get("mcp"), where=f"{where}: mcp", base=mcp)
|
|
1225
|
+
except SettingsError as exc:
|
|
1226
|
+
raise ConfigError(str(exc)) from exc
|
|
1227
|
+
|
|
1228
|
+
return (
|
|
1229
|
+
_merge_retry(document, where=where, retry=retry),
|
|
1230
|
+
_merge_compaction(document, where=where, compaction=compaction),
|
|
1231
|
+
_merge_permission(
|
|
1232
|
+
document,
|
|
1233
|
+
where=where,
|
|
1234
|
+
permission=permission,
|
|
1235
|
+
trusted=permission_trusted,
|
|
1236
|
+
scope=permission_scope,
|
|
1237
|
+
source=permission_source,
|
|
1238
|
+
),
|
|
1239
|
+
_merge_sandbox(document, where=where, sandbox=sandbox),
|
|
1240
|
+
_merge_checkpoint(document, where=where, checkpoint=checkpoint),
|
|
1241
|
+
_merge_subagents(document, where=where, subagents=subagents),
|
|
1242
|
+
_merge_web(document, where=where, web=web),
|
|
1243
|
+
_merge_observability(document, where=where, settings=observability),
|
|
1244
|
+
_merge_statusline(document, where=where, settings=statusline),
|
|
1245
|
+
merged_mcp,
|
|
1246
|
+
)
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def _merge_subagents(
|
|
1250
|
+
document: Mapping[str, JsonValue], *, where: str, subagents: SubagentSettings
|
|
1251
|
+
) -> SubagentSettings:
|
|
1252
|
+
"""``agents``:嵌套深度、后台并发与超时。逐字段覆盖,取值越界报错。"""
|
|
1253
|
+
raw = document.get("agents", {})
|
|
1254
|
+
if not isinstance(raw, dict):
|
|
1255
|
+
raise ConfigError(f"{where}: agents 必须是 JSON 对象")
|
|
1256
|
+
unknown = sorted(set(raw) - _AGENTS_KEYS)
|
|
1257
|
+
if unknown:
|
|
1258
|
+
raise ConfigError(
|
|
1259
|
+
f"{where}: agents 里的未知字段 {', '.join(unknown)}"
|
|
1260
|
+
f"(可用: {', '.join(sorted(_AGENTS_KEYS))})"
|
|
1261
|
+
)
|
|
1262
|
+
spot = f"{where}: agents"
|
|
1263
|
+
max_depth = subagents.max_depth
|
|
1264
|
+
max_background = subagents.max_background
|
|
1265
|
+
max_concurrent = subagents.max_concurrent
|
|
1266
|
+
timeout_seconds = subagents.timeout_seconds
|
|
1267
|
+
if "max_depth" in raw:
|
|
1268
|
+
value = raw["max_depth"]
|
|
1269
|
+
if (
|
|
1270
|
+
isinstance(value, bool)
|
|
1271
|
+
or not isinstance(value, int)
|
|
1272
|
+
or not 1 <= value <= MAX_ALLOWED_DEPTH
|
|
1273
|
+
):
|
|
1274
|
+
raise ConfigError(
|
|
1275
|
+
f"{spot}.max_depth: 只能是 1 或 {MAX_ALLOWED_DEPTH}(禁止无限嵌套),收到 {value!r}"
|
|
1276
|
+
)
|
|
1277
|
+
max_depth = value
|
|
1278
|
+
if "max_background" in raw:
|
|
1279
|
+
max_background = _positive_int(raw["max_background"], where=f"{spot}.max_background")
|
|
1280
|
+
if "max_concurrent" in raw:
|
|
1281
|
+
max_concurrent = _positive_int(raw["max_concurrent"], where=f"{spot}.max_concurrent")
|
|
1282
|
+
if "timeout_seconds" in raw:
|
|
1283
|
+
timeout_seconds = _as_positive_float(
|
|
1284
|
+
raw["timeout_seconds"], where=f"{spot}.timeout_seconds"
|
|
1285
|
+
)
|
|
1286
|
+
return SubagentSettings(
|
|
1287
|
+
max_depth=max_depth,
|
|
1288
|
+
max_background=max_background,
|
|
1289
|
+
max_concurrent=max_concurrent,
|
|
1290
|
+
timeout_seconds=timeout_seconds,
|
|
1291
|
+
)
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def _merge_statusline(
|
|
1295
|
+
document: Mapping[str, JsonValue], *, where: str, settings: StatuslineSettings
|
|
1296
|
+
) -> StatuslineSettings:
|
|
1297
|
+
"""``statusline``:字段清单整体替换,未知字段在启动阶段报错。"""
|
|
1298
|
+
raw = document.get("statusline")
|
|
1299
|
+
if raw is None:
|
|
1300
|
+
return settings
|
|
1301
|
+
if not isinstance(raw, dict):
|
|
1302
|
+
raise ConfigError(f"{where}: statusline 必须是 JSON 对象")
|
|
1303
|
+
unknown = sorted(set(raw) - _STATUSLINE_KEYS)
|
|
1304
|
+
if unknown:
|
|
1305
|
+
raise ConfigError(
|
|
1306
|
+
f"{where}: statusline 里的未知字段 {', '.join(unknown)}"
|
|
1307
|
+
f"(可用: {', '.join(sorted(_STATUSLINE_KEYS))})"
|
|
1308
|
+
)
|
|
1309
|
+
fields = raw.get("fields")
|
|
1310
|
+
if fields is None:
|
|
1311
|
+
return settings
|
|
1312
|
+
if not isinstance(fields, list) or any(not isinstance(name, str) for name in fields):
|
|
1313
|
+
raise ConfigError(f"{where}: statusline.fields 必须是字符串数组")
|
|
1314
|
+
raw_names = cast("list[str]", fields)
|
|
1315
|
+
if any(not name for name in raw_names):
|
|
1316
|
+
raise ConfigError(f"{where}: statusline.fields 里的字段名不能为空")
|
|
1317
|
+
names = tuple(raw_names)
|
|
1318
|
+
if not names:
|
|
1319
|
+
raise ConfigError(f"{where}: statusline.fields 至少要有一个字段")
|
|
1320
|
+
unknown_fields = [name for name in names if name not in STATUS_FIELD_KEYS]
|
|
1321
|
+
if unknown_fields:
|
|
1322
|
+
raise ConfigError(
|
|
1323
|
+
f"{where}: 未知的状态栏字段 {', '.join(unknown_fields)}"
|
|
1324
|
+
f"(可用: {', '.join(sorted(STATUS_FIELD_KEYS))})"
|
|
1325
|
+
)
|
|
1326
|
+
duplicates = [name for name in dict.fromkeys(names) if names.count(name) > 1]
|
|
1327
|
+
if duplicates:
|
|
1328
|
+
raise ConfigError(f"{where}: 状态栏字段不能重复:{', '.join(duplicates)}")
|
|
1329
|
+
return StatuslineSettings(fields=names)
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
def _merge_web(document: Mapping[str, JsonValue], *, where: str, web: WebSettings) -> WebSettings:
|
|
1333
|
+
"""``web``:搜索来源、抓取上限、缓存与私网开关。逐字段覆盖。"""
|
|
1334
|
+
raw = document.get("web", {})
|
|
1335
|
+
if not isinstance(raw, dict):
|
|
1336
|
+
raise ConfigError(f"{where}: web 必须是 JSON 对象")
|
|
1337
|
+
unknown = sorted(set(raw) - _WEB_KEYS)
|
|
1338
|
+
if unknown:
|
|
1339
|
+
raise ConfigError(
|
|
1340
|
+
f"{where}: web 里的未知字段 {', '.join(unknown)}"
|
|
1341
|
+
f"(可用: {', '.join(sorted(_WEB_KEYS))})"
|
|
1342
|
+
)
|
|
1343
|
+
spot = f"{where}: web"
|
|
1344
|
+
enabled = web.enabled
|
|
1345
|
+
provider = web.search_provider
|
|
1346
|
+
max_results = web.search_max_results
|
|
1347
|
+
endpoint = web.search_endpoint
|
|
1348
|
+
fetch_max_chars = web.fetch_max_chars
|
|
1349
|
+
ttl = web.cache_ttl_seconds
|
|
1350
|
+
max_entries = web.cache_max_entries
|
|
1351
|
+
timeout = web.timeout_seconds
|
|
1352
|
+
allow_private = web.allow_private_hosts
|
|
1353
|
+
user_agent = web.user_agent
|
|
1354
|
+
|
|
1355
|
+
if "enabled" in raw:
|
|
1356
|
+
enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
1357
|
+
if "search_provider" in raw:
|
|
1358
|
+
value = raw["search_provider"]
|
|
1359
|
+
if not isinstance(value, str) or value not in SEARCH_PROVIDERS:
|
|
1360
|
+
raise ConfigError(
|
|
1361
|
+
f"{spot}.search_provider: 只支持 {', '.join(SEARCH_PROVIDERS)},收到 {value!r}"
|
|
1362
|
+
)
|
|
1363
|
+
provider = value
|
|
1364
|
+
if "search_max_results" in raw:
|
|
1365
|
+
max_results = _positive_int(raw["search_max_results"], where=f"{spot}.search_max_results")
|
|
1366
|
+
if max_results > MAX_SEARCH_RESULTS:
|
|
1367
|
+
raise ConfigError(f"{spot}.search_max_results: 上限是 {MAX_SEARCH_RESULTS}")
|
|
1368
|
+
if "search_endpoint" in raw:
|
|
1369
|
+
value = raw["search_endpoint"]
|
|
1370
|
+
if not isinstance(value, str):
|
|
1371
|
+
raise ConfigError(f"{spot}.search_endpoint: 必须是字符串")
|
|
1372
|
+
endpoint = _non_empty_text(value, where=f"{spot}.search_endpoint")
|
|
1373
|
+
if "fetch_max_chars" in raw:
|
|
1374
|
+
fetch_max_chars = _positive_int(raw["fetch_max_chars"], where=f"{spot}.fetch_max_chars")
|
|
1375
|
+
if fetch_max_chars > MAX_FETCH_CHARS:
|
|
1376
|
+
raise ConfigError(f"{spot}.fetch_max_chars: 上限是 {MAX_FETCH_CHARS}")
|
|
1377
|
+
if "cache_ttl_seconds" in raw:
|
|
1378
|
+
ttl = _as_positive_float(raw["cache_ttl_seconds"], where=f"{spot}.cache_ttl_seconds")
|
|
1379
|
+
if "cache_max_entries" in raw:
|
|
1380
|
+
max_entries = _positive_int(raw["cache_max_entries"], where=f"{spot}.cache_max_entries")
|
|
1381
|
+
if "timeout_seconds" in raw:
|
|
1382
|
+
timeout = _as_positive_float(raw["timeout_seconds"], where=f"{spot}.timeout_seconds")
|
|
1383
|
+
if "allow_private_hosts" in raw:
|
|
1384
|
+
allow_private = _as_bool(raw["allow_private_hosts"], where=f"{spot}.allow_private_hosts")
|
|
1385
|
+
if "user_agent" in raw:
|
|
1386
|
+
user_agent = _non_empty_text(raw["user_agent"], where=f"{spot}.user_agent")
|
|
1387
|
+
|
|
1388
|
+
return WebSettings(
|
|
1389
|
+
enabled=enabled,
|
|
1390
|
+
search_provider=provider,
|
|
1391
|
+
search_max_results=max_results,
|
|
1392
|
+
search_endpoint=endpoint,
|
|
1393
|
+
fetch_max_chars=fetch_max_chars,
|
|
1394
|
+
cache_ttl_seconds=ttl,
|
|
1395
|
+
cache_max_entries=max_entries,
|
|
1396
|
+
timeout_seconds=timeout,
|
|
1397
|
+
allow_private_hosts=allow_private,
|
|
1398
|
+
user_agent=user_agent,
|
|
1399
|
+
)
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
def _merge_lsp(document: Mapping[str, JsonValue], *, where: str, lsp: dict[str, _LspDraft]) -> None:
|
|
1403
|
+
"""``lsp.<name>``:一台语言服务器一段。同名的后写覆盖前写的字段。
|
|
1404
|
+
|
|
1405
|
+
数组字段(``command`` / ``extensions`` / ``root_markers``)整体替换;两张表
|
|
1406
|
+
(``env`` 与 ``initialization_options``)按键合并,这样加一个环境变量不必重抄全部。
|
|
1407
|
+
顺序即路由优先级,所以草稿用插入有序的 dict 存。
|
|
1408
|
+
"""
|
|
1409
|
+
raw = document.get("lsp", {})
|
|
1410
|
+
if not isinstance(raw, dict):
|
|
1411
|
+
raise ConfigError(f'{where}: lsp 必须是 JSON 对象,键是服务器名(例如 "python")')
|
|
1412
|
+
for name, value in raw.items():
|
|
1413
|
+
spot = f"{where}: lsp.{name}"
|
|
1414
|
+
if not name.strip():
|
|
1415
|
+
raise ConfigError(f"{where}: lsp 下的服务器名不能为空")
|
|
1416
|
+
if not isinstance(value, dict):
|
|
1417
|
+
raise ConfigError(f"{spot}: 必须是 JSON 对象")
|
|
1418
|
+
unknown = sorted(set(value) - _LSP_KEYS)
|
|
1419
|
+
if unknown:
|
|
1420
|
+
raise ConfigError(
|
|
1421
|
+
f"{spot}: 未知字段 {', '.join(unknown)}(可用: {', '.join(sorted(_LSP_KEYS))})"
|
|
1422
|
+
)
|
|
1423
|
+
draft = lsp.get(name)
|
|
1424
|
+
if draft is None:
|
|
1425
|
+
draft = _LspDraft(name=name, source=where)
|
|
1426
|
+
lsp[name] = draft
|
|
1427
|
+
else:
|
|
1428
|
+
draft.source = where
|
|
1429
|
+
if "command" in value:
|
|
1430
|
+
draft.command = _as_argv(value["command"], where=f"{spot}.command")
|
|
1431
|
+
if "extensions" in value:
|
|
1432
|
+
draft.extensions = merge_extensions(
|
|
1433
|
+
_as_string_list(value["extensions"], where=f"{spot}.extensions")
|
|
1434
|
+
)
|
|
1435
|
+
if "language_id" in value:
|
|
1436
|
+
draft.language_id = _non_empty_text(value["language_id"], where=f"{spot}.language_id")
|
|
1437
|
+
if "root_markers" in value:
|
|
1438
|
+
draft.root_markers = _as_string_list(
|
|
1439
|
+
value["root_markers"], where=f"{spot}.root_markers"
|
|
1440
|
+
)
|
|
1441
|
+
if "initialization_options" in value:
|
|
1442
|
+
options = _as_mapping(
|
|
1443
|
+
value["initialization_options"], where=f"{spot}.initialization_options"
|
|
1444
|
+
)
|
|
1445
|
+
draft.initialization_options = {**(draft.initialization_options or {}), **options}
|
|
1446
|
+
if "env" in value:
|
|
1447
|
+
env = _as_string_mapping(value["env"], where=f"{spot}.env")
|
|
1448
|
+
draft.env = {**(draft.env or {}), **env}
|
|
1449
|
+
if "timeout_seconds" in value:
|
|
1450
|
+
draft.timeout_seconds = _as_positive_float(
|
|
1451
|
+
value["timeout_seconds"], where=f"{spot}.timeout_seconds"
|
|
1452
|
+
)
|
|
1453
|
+
if "enabled" in value:
|
|
1454
|
+
draft.enabled = _as_bool(value["enabled"], where=f"{spot}.enabled")
|
|
1455
|
+
|
|
1456
|
+
|
|
1457
|
+
def _merge_verify(document: Mapping[str, JsonValue], *, where: str, verify: _VerifyDraft) -> None:
|
|
1458
|
+
"""``verify`` 与 ``verify.commands``。命令数组整体替换。"""
|
|
1459
|
+
raw = document.get("verify", {})
|
|
1460
|
+
if not isinstance(raw, dict):
|
|
1461
|
+
raise ConfigError(f"{where}: verify 必须是 JSON 对象")
|
|
1462
|
+
unknown = sorted(set(raw) - _VERIFY_KEYS)
|
|
1463
|
+
if unknown:
|
|
1464
|
+
raise ConfigError(
|
|
1465
|
+
f"{where}: verify 里的未知字段 {', '.join(unknown)}"
|
|
1466
|
+
f"(可用: {', '.join(sorted(_VERIFY_KEYS))})"
|
|
1467
|
+
)
|
|
1468
|
+
spot = f"{where}: verify"
|
|
1469
|
+
if "enabled" in raw:
|
|
1470
|
+
verify.enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
1471
|
+
if "timeout_seconds" in raw:
|
|
1472
|
+
verify.timeout_seconds = _as_positive_float(
|
|
1473
|
+
raw["timeout_seconds"], where=f"{spot}.timeout_seconds"
|
|
1474
|
+
)
|
|
1475
|
+
if "fail_fast" in raw:
|
|
1476
|
+
verify.fail_fast = _as_bool(raw["fail_fast"], where=f"{spot}.fail_fast")
|
|
1477
|
+
if "max_consecutive_failures" in raw:
|
|
1478
|
+
verify.max_consecutive_failures = _positive_int(
|
|
1479
|
+
raw["max_consecutive_failures"], where=f"{spot}.max_consecutive_failures"
|
|
1480
|
+
)
|
|
1481
|
+
if "commands" in raw:
|
|
1482
|
+
items = raw["commands"]
|
|
1483
|
+
if not isinstance(items, list):
|
|
1484
|
+
raise ConfigError(
|
|
1485
|
+
f"{spot}.commands: 必须是数组,每条是对象(字段 name / command / timeout_seconds)"
|
|
1486
|
+
)
|
|
1487
|
+
commands: list[VerifyCommand] = []
|
|
1488
|
+
for index, item in enumerate(items, start=1):
|
|
1489
|
+
commands.append(
|
|
1490
|
+
_verify_command(item, where=f"{spot}.commands[{index - 1}]", position=index)
|
|
1491
|
+
)
|
|
1492
|
+
names = [command.name for command in commands]
|
|
1493
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
1494
|
+
if duplicates:
|
|
1495
|
+
raise ConfigError(f"{spot}.commands: 命令名重复 {', '.join(duplicates)}")
|
|
1496
|
+
verify.commands = tuple(commands)
|
|
1497
|
+
|
|
1498
|
+
|
|
1499
|
+
def _verify_command(value: JsonValue, *, where: str, position: int) -> VerifyCommand:
|
|
1500
|
+
if not isinstance(value, dict):
|
|
1501
|
+
raise ConfigError(f"{where}: 必须是 JSON 对象")
|
|
1502
|
+
unknown = sorted(set(value) - _VERIFY_COMMAND_KEYS)
|
|
1503
|
+
if unknown:
|
|
1504
|
+
raise ConfigError(
|
|
1505
|
+
f"{where}: 未知字段 {', '.join(unknown)}"
|
|
1506
|
+
f"(可用: {', '.join(sorted(_VERIFY_COMMAND_KEYS))})"
|
|
1507
|
+
)
|
|
1508
|
+
command = _non_empty_text(value.get("command"), where=f"{where}.command")
|
|
1509
|
+
raw_name = value.get("name")
|
|
1510
|
+
# 没写名字时用序号:``step-2`` 比 "第二条命令" 更适合出现在一行摘要里。
|
|
1511
|
+
name = (
|
|
1512
|
+
f"step-{position}" if raw_name is None else _non_empty_text(raw_name, where=f"{where}.name")
|
|
1513
|
+
)
|
|
1514
|
+
timeout = (
|
|
1515
|
+
None
|
|
1516
|
+
if value.get("timeout_seconds") is None
|
|
1517
|
+
else _as_positive_float(value["timeout_seconds"], where=f"{where}.timeout_seconds")
|
|
1518
|
+
)
|
|
1519
|
+
return VerifyCommand(name=name, command=command, timeout_seconds=timeout)
|
|
1520
|
+
|
|
1521
|
+
|
|
1522
|
+
def _merge_format(
|
|
1523
|
+
document: Mapping[str, JsonValue], *, where: str, formatting: _FormatDraft
|
|
1524
|
+
) -> None:
|
|
1525
|
+
"""``format`` 与 ``format.commands``。命令表按扩展名逐键合并。"""
|
|
1526
|
+
raw = document.get("format", {})
|
|
1527
|
+
if not isinstance(raw, dict):
|
|
1528
|
+
raise ConfigError(f"{where}: format 必须是 JSON 对象")
|
|
1529
|
+
unknown = sorted(set(raw) - _FORMAT_KEYS)
|
|
1530
|
+
if unknown:
|
|
1531
|
+
raise ConfigError(
|
|
1532
|
+
f"{where}: format 里的未知字段 {', '.join(unknown)}"
|
|
1533
|
+
f"(可用: {', '.join(sorted(_FORMAT_KEYS))})"
|
|
1534
|
+
)
|
|
1535
|
+
spot = f"{where}: format"
|
|
1536
|
+
if "enabled" in raw:
|
|
1537
|
+
formatting.enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
1538
|
+
if "timeout_seconds" in raw:
|
|
1539
|
+
formatting.timeout_seconds = _as_positive_float(
|
|
1540
|
+
raw["timeout_seconds"], where=f"{spot}.timeout_seconds"
|
|
1541
|
+
)
|
|
1542
|
+
commands = raw.get("commands")
|
|
1543
|
+
if commands is None:
|
|
1544
|
+
return
|
|
1545
|
+
if not isinstance(commands, dict):
|
|
1546
|
+
raise ConfigError(f'{spot}.commands: 必须是 JSON 对象,键是扩展名(例如 ".py": [...])')
|
|
1547
|
+
for extension, value in commands.items():
|
|
1548
|
+
key = normalize_extension(extension)
|
|
1549
|
+
if not key:
|
|
1550
|
+
raise ConfigError(f"{spot}.commands: 扩展名不能为空")
|
|
1551
|
+
argv = _as_argv(value, where=f'{spot}.commands."{extension}"')
|
|
1552
|
+
if not any(PATH_PLACEHOLDER in token for token in argv):
|
|
1553
|
+
raise ConfigError(
|
|
1554
|
+
f'{spot}.commands."{extension}": 命令必须包含 {PATH_PLACEHOLDER} 占位符'
|
|
1555
|
+
'(例如 ["ruff", "format", "{path}"])'
|
|
1556
|
+
)
|
|
1557
|
+
formatting.commands[key] = argv
|
|
1558
|
+
|
|
1559
|
+
|
|
1560
|
+
def _merge_observability(
|
|
1561
|
+
document: Mapping[str, JsonValue], *, where: str, settings: ObservabilitySettings
|
|
1562
|
+
) -> ObservabilitySettings:
|
|
1563
|
+
"""``observability``:开关、日志级别与格式、OTel 导出开关。逐字段覆盖。"""
|
|
1564
|
+
raw = document.get("observability", {})
|
|
1565
|
+
if not isinstance(raw, dict):
|
|
1566
|
+
raise ConfigError(f"{where}: observability 必须是 JSON 对象")
|
|
1567
|
+
unknown = sorted(set(raw) - _OBSERVABILITY_KEYS)
|
|
1568
|
+
if unknown:
|
|
1569
|
+
raise ConfigError(
|
|
1570
|
+
f"{where}: observability 里的未知字段 {', '.join(unknown)}"
|
|
1571
|
+
f"(可用: {', '.join(sorted(_OBSERVABILITY_KEYS))})"
|
|
1572
|
+
)
|
|
1573
|
+
spot = f"{where}: observability"
|
|
1574
|
+
enabled = settings.enabled
|
|
1575
|
+
log_level = settings.log_level
|
|
1576
|
+
log_format = settings.log_format
|
|
1577
|
+
otel_enabled = settings.otel_enabled
|
|
1578
|
+
export_jsonl = settings.export_jsonl
|
|
1579
|
+
if "enabled" in raw:
|
|
1580
|
+
enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
1581
|
+
if "log_level" in raw:
|
|
1582
|
+
level = _non_empty_text(raw["log_level"], where=f"{spot}.log_level").upper()
|
|
1583
|
+
if level not in LOG_LEVELS:
|
|
1584
|
+
raise ConfigError(
|
|
1585
|
+
f"{spot}.log_level: 未知级别 {level}(可用: {', '.join(LOG_LEVELS)})"
|
|
1586
|
+
)
|
|
1587
|
+
log_level = level
|
|
1588
|
+
if "log_format" in raw:
|
|
1589
|
+
fmt = _non_empty_text(raw["log_format"], where=f"{spot}.log_format").lower()
|
|
1590
|
+
if fmt not in LOG_FORMATS:
|
|
1591
|
+
raise ConfigError(
|
|
1592
|
+
f"{spot}.log_format: 未知格式 {fmt}(可用: {', '.join(LOG_FORMATS)})"
|
|
1593
|
+
)
|
|
1594
|
+
log_format = cast("LogFormat", fmt)
|
|
1595
|
+
if "otel_enabled" in raw:
|
|
1596
|
+
otel_enabled = _as_bool(raw["otel_enabled"], where=f"{spot}.otel_enabled")
|
|
1597
|
+
if "export_jsonl" in raw:
|
|
1598
|
+
export_jsonl = _non_empty_text(raw["export_jsonl"], where=f"{spot}.export_jsonl")
|
|
1599
|
+
return ObservabilitySettings(
|
|
1600
|
+
enabled=enabled,
|
|
1601
|
+
log_level=log_level,
|
|
1602
|
+
log_format=log_format,
|
|
1603
|
+
otel_enabled=otel_enabled,
|
|
1604
|
+
export_jsonl=export_jsonl,
|
|
1605
|
+
)
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
def _merge_checkpoint(
|
|
1609
|
+
document: Mapping[str, JsonValue], *, where: str, checkpoint: CheckpointSettings
|
|
1610
|
+
) -> CheckpointSettings:
|
|
1611
|
+
"""``[checkpoint]``:一个开关、一个上限与一张排除表。数组整体替换。"""
|
|
1612
|
+
raw = document.get("checkpoint", {})
|
|
1613
|
+
if not isinstance(raw, dict):
|
|
1614
|
+
raise ConfigError(f"{where}: checkpoint 必须是 JSON 对象")
|
|
1615
|
+
unknown = sorted(set(raw) - _CHECKPOINT_KEYS)
|
|
1616
|
+
if unknown:
|
|
1617
|
+
raise ConfigError(
|
|
1618
|
+
f"{where}: checkpoint 里的未知字段 {', '.join(unknown)}"
|
|
1619
|
+
f"(可用: {', '.join(sorted(_CHECKPOINT_KEYS))})"
|
|
1620
|
+
)
|
|
1621
|
+
spot = f"{where}: checkpoint"
|
|
1622
|
+
enabled = checkpoint.enabled
|
|
1623
|
+
max_file_bytes = checkpoint.max_file_bytes
|
|
1624
|
+
exclude = checkpoint.exclude
|
|
1625
|
+
if "enabled" in raw:
|
|
1626
|
+
enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
1627
|
+
if "max_file_bytes" in raw:
|
|
1628
|
+
max_file_bytes = _positive_int(raw["max_file_bytes"], where=f"{spot}.max_file_bytes")
|
|
1629
|
+
if "exclude" in raw:
|
|
1630
|
+
exclude = _as_string_list(raw["exclude"], where=f"{spot}.exclude")
|
|
1631
|
+
return CheckpointSettings(enabled=enabled, max_file_bytes=max_file_bytes, exclude=exclude)
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
def _merge_sandbox(
|
|
1635
|
+
document: Mapping[str, JsonValue], *, where: str, sandbox: SandboxSettings
|
|
1636
|
+
) -> SandboxSettings:
|
|
1637
|
+
"""``sandbox`` 的标量与四个数组。数组整体替换,标量逐字段覆盖。
|
|
1638
|
+
|
|
1639
|
+
数组为什么整体替换:``allow_domains`` 想「删掉一条」时,拼接语义会让它删不掉;
|
|
1640
|
+
而域名的合并已经在 :meth:`SandboxSettings.network_policy` 里做(模型域名自动并入)。
|
|
1641
|
+
"""
|
|
1642
|
+
raw = document.get("sandbox", {})
|
|
1643
|
+
if not isinstance(raw, dict):
|
|
1644
|
+
raise ConfigError(f"{where}: sandbox 必须是 JSON 对象")
|
|
1645
|
+
unknown = sorted(set(raw) - _SANDBOX_KEYS)
|
|
1646
|
+
if unknown:
|
|
1647
|
+
raise ConfigError(
|
|
1648
|
+
f"{where}: sandbox 里的未知字段 {', '.join(unknown)}"
|
|
1649
|
+
f"(可用: {', '.join(sorted(_SANDBOX_KEYS))})"
|
|
1650
|
+
)
|
|
1651
|
+
spot = f"{where}: sandbox"
|
|
1652
|
+
mode = sandbox.mode
|
|
1653
|
+
backend = sandbox.backend
|
|
1654
|
+
network = sandbox.network
|
|
1655
|
+
read = sandbox.read
|
|
1656
|
+
allow_domains = sandbox.allow_domains
|
|
1657
|
+
deny_domains = sandbox.deny_domains
|
|
1658
|
+
writable_paths = sandbox.writable_paths
|
|
1659
|
+
readable_paths = sandbox.readable_paths
|
|
1660
|
+
executable = sandbox.executable
|
|
1661
|
+
|
|
1662
|
+
if "mode" in raw:
|
|
1663
|
+
mode = _as_sandbox_mode(raw["mode"], where=f"{spot}.mode")
|
|
1664
|
+
if "backend" in raw:
|
|
1665
|
+
backend = _as_backend_name(raw["backend"], where=f"{spot}.backend")
|
|
1666
|
+
if "network" in raw:
|
|
1667
|
+
network = _as_network_mode(raw["network"], where=f"{spot}.network")
|
|
1668
|
+
if "read" in raw:
|
|
1669
|
+
read = _as_read_scope(raw["read"], where=f"{spot}.read")
|
|
1670
|
+
if "allow_domains" in raw:
|
|
1671
|
+
allow_domains = _as_string_list(raw["allow_domains"], where=f"{spot}.allow_domains")
|
|
1672
|
+
if "deny_domains" in raw:
|
|
1673
|
+
deny_domains = _as_string_list(raw["deny_domains"], where=f"{spot}.deny_domains")
|
|
1674
|
+
if "writable_paths" in raw:
|
|
1675
|
+
writable_paths = _as_string_list(raw["writable_paths"], where=f"{spot}.writable_paths")
|
|
1676
|
+
if "readable_paths" in raw:
|
|
1677
|
+
readable_paths = _as_string_list(raw["readable_paths"], where=f"{spot}.readable_paths")
|
|
1678
|
+
if "executable" in raw:
|
|
1679
|
+
executable = _non_empty_text(raw["executable"], where=f"{spot}.executable")
|
|
1680
|
+
|
|
1681
|
+
if mode == "network-only" and network == "allow":
|
|
1682
|
+
raise ConfigError(
|
|
1683
|
+
f'{spot}: mode = "network-only" 必须有网络策略,不能配 network = "allow"'
|
|
1684
|
+
'(那样沙箱什么都不做;要关闭沙箱请写 mode = "off")'
|
|
1685
|
+
)
|
|
1686
|
+
return SandboxSettings(
|
|
1687
|
+
mode=mode,
|
|
1688
|
+
backend=backend,
|
|
1689
|
+
network=network,
|
|
1690
|
+
read=read,
|
|
1691
|
+
allow_domains=allow_domains,
|
|
1692
|
+
deny_domains=deny_domains,
|
|
1693
|
+
writable_paths=writable_paths,
|
|
1694
|
+
readable_paths=readable_paths,
|
|
1695
|
+
executable=executable,
|
|
1696
|
+
)
|
|
1697
|
+
|
|
1698
|
+
|
|
1699
|
+
def _merge_permission(
|
|
1700
|
+
document: Mapping[str, JsonValue],
|
|
1701
|
+
*,
|
|
1702
|
+
where: str,
|
|
1703
|
+
permission: PermissionSettings,
|
|
1704
|
+
trusted: bool = True,
|
|
1705
|
+
scope: RuleScope = "global",
|
|
1706
|
+
source: str = "",
|
|
1707
|
+
) -> PermissionSettings:
|
|
1708
|
+
"""``permission`` 的标量与三张规则表;规则表按键合并,不整体替换。
|
|
1709
|
+
|
|
1710
|
+
``trusted=False`` 时只接受 deny 规则,``default``、``mode`` 与超时沿用已有值:
|
|
1711
|
+
未信任的项目不能放宽权限。
|
|
1712
|
+
"""
|
|
1713
|
+
raw = document.get("permission", {})
|
|
1714
|
+
if not isinstance(raw, dict):
|
|
1715
|
+
raise ConfigError(f"{where}: permission 必须是 JSON 对象")
|
|
1716
|
+
unknown = sorted(set(raw) - _PERMISSION_KEYS)
|
|
1717
|
+
if unknown:
|
|
1718
|
+
raise ConfigError(
|
|
1719
|
+
f"{where}: permission 里的未知字段 {', '.join(unknown)}"
|
|
1720
|
+
f"(可用: {', '.join(sorted(_PERMISSION_KEYS))})"
|
|
1721
|
+
)
|
|
1722
|
+
spot = f"{where}: permission"
|
|
1723
|
+
default = permission.default
|
|
1724
|
+
mode = permission.mode
|
|
1725
|
+
timeout = permission.approval_timeout_seconds
|
|
1726
|
+
if "default" in raw:
|
|
1727
|
+
parsed_default = _as_permission_action(raw["default"], where=f"{spot}.default")
|
|
1728
|
+
if trusted:
|
|
1729
|
+
default = parsed_default
|
|
1730
|
+
if "mode" in raw:
|
|
1731
|
+
parsed_mode = _as_permission_mode(raw["mode"], where=f"{spot}.mode")
|
|
1732
|
+
if trusted:
|
|
1733
|
+
mode = parsed_mode
|
|
1734
|
+
if "approval_timeout_seconds" in raw:
|
|
1735
|
+
parsed_timeout = _as_positive_float(
|
|
1736
|
+
raw["approval_timeout_seconds"], where=f"{spot}.approval_timeout_seconds"
|
|
1737
|
+
)
|
|
1738
|
+
if trusted:
|
|
1739
|
+
timeout = parsed_timeout
|
|
1740
|
+
|
|
1741
|
+
tables: dict[RuleTable, dict[str, PermissionAction]] = {
|
|
1742
|
+
"tools": dict(permission.tools),
|
|
1743
|
+
"bash": dict(permission.bash),
|
|
1744
|
+
"paths": dict(permission.paths),
|
|
1745
|
+
"domains": dict(permission.domains),
|
|
1746
|
+
}
|
|
1747
|
+
new_rules: list[ScopedRule] = []
|
|
1748
|
+
for table in _PERMISSION_RULE_TABLES:
|
|
1749
|
+
value = raw.get(table)
|
|
1750
|
+
if value is None:
|
|
1751
|
+
continue
|
|
1752
|
+
if not isinstance(value, dict):
|
|
1753
|
+
raise ConfigError(f"{spot}.{table} 必须是 JSON 对象")
|
|
1754
|
+
for key, action in value.items():
|
|
1755
|
+
if not key:
|
|
1756
|
+
raise ConfigError(f"{spot}.{table}: 规则的模式不能为空")
|
|
1757
|
+
effect = _as_permission_action(action, where=f"{spot}.{table}.{key}")
|
|
1758
|
+
if not trusted and effect != "deny":
|
|
1759
|
+
continue
|
|
1760
|
+
tables[table][key] = effect
|
|
1761
|
+
new_rules.append(ScopedRule(table, key, effect, scope, source))
|
|
1762
|
+
return PermissionSettings(
|
|
1763
|
+
default=default,
|
|
1764
|
+
mode=mode,
|
|
1765
|
+
approval_timeout_seconds=timeout,
|
|
1766
|
+
tools=MappingProxyType(tables["tools"]),
|
|
1767
|
+
bash=MappingProxyType(tables["bash"]),
|
|
1768
|
+
paths=MappingProxyType(tables["paths"]),
|
|
1769
|
+
domains=MappingProxyType(tables["domains"]),
|
|
1770
|
+
rules=_replace_rules(permission.rules, new_rules),
|
|
1771
|
+
project_trusted=permission.project_trusted,
|
|
1772
|
+
)
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
def _merge_rule_file(settings: PermissionSettings, rule_file: RuleFile) -> PermissionSettings:
|
|
1776
|
+
"""把一份运行时规则文件并进设置。文件没有 ``mode`` 时保留已有模式。"""
|
|
1777
|
+
mode = rule_file.mode if rule_file.mode is not None else settings.mode
|
|
1778
|
+
return replace(
|
|
1779
|
+
settings,
|
|
1780
|
+
mode=mode,
|
|
1781
|
+
rules=_replace_rules(settings.rules, rule_file.rules),
|
|
1782
|
+
)
|
|
1783
|
+
|
|
1784
|
+
|
|
1785
|
+
def _replace_rules(
|
|
1786
|
+
existing: tuple[ScopedRule, ...], incoming: Sequence[ScopedRule]
|
|
1787
|
+
) -> tuple[ScopedRule, ...]:
|
|
1788
|
+
"""同一 ``(table, pattern, scope)`` 只保留最后一条。"""
|
|
1789
|
+
merged = list(existing)
|
|
1790
|
+
for rule in incoming:
|
|
1791
|
+
merged = [
|
|
1792
|
+
item
|
|
1793
|
+
for item in merged
|
|
1794
|
+
if (item.table, item.pattern, item.scope) != (rule.table, rule.pattern, rule.scope)
|
|
1795
|
+
]
|
|
1796
|
+
merged.append(rule)
|
|
1797
|
+
return tuple(merged)
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def _merge_compaction(
|
|
1801
|
+
document: Mapping[str, JsonValue], *, where: str, compaction: CompactionSettings
|
|
1802
|
+
) -> CompactionSettings:
|
|
1803
|
+
"""``compaction`` 逐字段覆盖。"""
|
|
1804
|
+
raw = document.get("compaction", {})
|
|
1805
|
+
if not isinstance(raw, dict):
|
|
1806
|
+
raise ConfigError(f"{where}: compaction 必须是 JSON 对象")
|
|
1807
|
+
unknown = sorted(set(raw) - _COMPACTION_KEYS)
|
|
1808
|
+
if unknown:
|
|
1809
|
+
raise ConfigError(
|
|
1810
|
+
f"{where}: compaction 里的未知字段 {', '.join(unknown)}"
|
|
1811
|
+
f"(可用: {', '.join(sorted(_COMPACTION_KEYS))})"
|
|
1812
|
+
)
|
|
1813
|
+
pool = f"{where}: compaction"
|
|
1814
|
+
enabled = compaction.enabled
|
|
1815
|
+
reserve_tokens = compaction.reserve_tokens
|
|
1816
|
+
keep_recent_tokens = compaction.keep_recent_tokens
|
|
1817
|
+
tool_results = compaction.tool_results
|
|
1818
|
+
if "enabled" in raw:
|
|
1819
|
+
enabled = _as_bool(raw["enabled"], where=f"{pool}.enabled")
|
|
1820
|
+
if "reserve_tokens" in raw:
|
|
1821
|
+
reserve_tokens = _positive_int(raw["reserve_tokens"], where=f"{pool}.reserve_tokens")
|
|
1822
|
+
if "keep_recent_tokens" in raw:
|
|
1823
|
+
keep_recent_tokens = _positive_int(
|
|
1824
|
+
raw["keep_recent_tokens"], where=f"{pool}.keep_recent_tokens"
|
|
1825
|
+
)
|
|
1826
|
+
if "tool_results" in raw:
|
|
1827
|
+
tool_results = _merge_tool_result_cleanup(raw["tool_results"], where=f"{pool}.tool_results")
|
|
1828
|
+
return CompactionSettings(
|
|
1829
|
+
enabled=enabled,
|
|
1830
|
+
reserve_tokens=reserve_tokens,
|
|
1831
|
+
keep_recent_tokens=keep_recent_tokens,
|
|
1832
|
+
tool_results=tool_results,
|
|
1833
|
+
)
|
|
1834
|
+
|
|
1835
|
+
|
|
1836
|
+
def _merge_tool_result_cleanup(raw: JsonValue, *, where: str) -> ToolResultCleanupSettings:
|
|
1837
|
+
"""``compaction.tool_results`` 逐字段覆盖。"""
|
|
1838
|
+
if not isinstance(raw, dict):
|
|
1839
|
+
raise ConfigError(f"{where}: 必须是 JSON 对象")
|
|
1840
|
+
unknown = sorted(set(raw) - _TOOL_RESULT_KEYS)
|
|
1841
|
+
if unknown:
|
|
1842
|
+
raise ConfigError(
|
|
1843
|
+
f"{where}: 未知字段 {', '.join(unknown)}"
|
|
1844
|
+
f"(可用: {', '.join(sorted(_TOOL_RESULT_KEYS))})"
|
|
1845
|
+
)
|
|
1846
|
+
enabled = DEFAULT_TOOL_RESULT_CLEANUP.enabled
|
|
1847
|
+
keep_recent = DEFAULT_TOOL_RESULT_CLEANUP.keep_recent
|
|
1848
|
+
min_chars = DEFAULT_TOOL_RESULT_CLEANUP.min_chars
|
|
1849
|
+
trigger_ratio = DEFAULT_TOOL_RESULT_CLEANUP.trigger_ratio
|
|
1850
|
+
if "enabled" in raw:
|
|
1851
|
+
enabled = _as_bool(raw["enabled"], where=f"{where}.enabled")
|
|
1852
|
+
if "keep_recent" in raw:
|
|
1853
|
+
keep_recent = _non_negative_int(raw["keep_recent"], where=f"{where}.keep_recent")
|
|
1854
|
+
if "min_chars" in raw:
|
|
1855
|
+
min_chars = _non_negative_int(raw["min_chars"], where=f"{where}.min_chars")
|
|
1856
|
+
if "trigger_ratio" in raw:
|
|
1857
|
+
trigger_ratio = _as_ratio(raw["trigger_ratio"], where=f"{where}.trigger_ratio")
|
|
1858
|
+
return ToolResultCleanupSettings(
|
|
1859
|
+
enabled=enabled,
|
|
1860
|
+
keep_recent=keep_recent,
|
|
1861
|
+
min_chars=min_chars,
|
|
1862
|
+
trigger_ratio=trigger_ratio,
|
|
1863
|
+
)
|
|
1864
|
+
|
|
1865
|
+
|
|
1866
|
+
def _merge_provider(
|
|
1867
|
+
provider_id: str,
|
|
1868
|
+
raw: JsonValue,
|
|
1869
|
+
*,
|
|
1870
|
+
where: str,
|
|
1871
|
+
providers: dict[str, _ProviderDraft],
|
|
1872
|
+
allow_remote_key: bool = False,
|
|
1873
|
+
) -> None:
|
|
1874
|
+
spot = f"{where}: providers.{provider_id}"
|
|
1875
|
+
if not provider_id:
|
|
1876
|
+
raise ConfigError(f"{where}: provider 名不能为空")
|
|
1877
|
+
if provider_id == "faux":
|
|
1878
|
+
raise ConfigError(
|
|
1879
|
+
f"{spot}: faux 是测试专用 provider,由 --script 现场注册,不能在配置里声明"
|
|
1880
|
+
)
|
|
1881
|
+
if not isinstance(raw, dict):
|
|
1882
|
+
raise ConfigError(f"{spot}: 必须是 JSON 对象")
|
|
1883
|
+
|
|
1884
|
+
unknown = sorted(set(raw) - _PROVIDER_KEYS)
|
|
1885
|
+
if unknown:
|
|
1886
|
+
hint = ""
|
|
1887
|
+
if "models" in unknown:
|
|
1888
|
+
hint = ';模型现在写在独立的 models["provider/模型 id"] 对象里'
|
|
1889
|
+
raise ConfigError(
|
|
1890
|
+
f"{spot}: 未知字段 {', '.join(unknown)}"
|
|
1891
|
+
f"(可用: {', '.join(sorted(_PROVIDER_KEYS))}){hint}"
|
|
1892
|
+
)
|
|
1893
|
+
|
|
1894
|
+
draft = providers.get(provider_id)
|
|
1895
|
+
if draft is None:
|
|
1896
|
+
draft = _ProviderDraft(source=where)
|
|
1897
|
+
providers[provider_id] = draft
|
|
1898
|
+
elif _PROVIDER_KEYS & set(raw):
|
|
1899
|
+
# 有字段被这份文件改写过,构建期的错误就该指到这里。
|
|
1900
|
+
draft.source = where
|
|
1901
|
+
|
|
1902
|
+
if "base_url" in raw:
|
|
1903
|
+
draft.base_url = _non_empty_text(raw["base_url"], where=f"{spot}.base_url")
|
|
1904
|
+
if "env_key" in raw:
|
|
1905
|
+
draft.env_key = _non_empty_text(raw["env_key"], where=f"{spot}.env_key")
|
|
1906
|
+
if "api_key" in raw:
|
|
1907
|
+
draft.api_key = _non_empty_text(raw["api_key"], where=f"{spot}.api_key")
|
|
1908
|
+
draft.api_key_source = where
|
|
1909
|
+
draft.allow_remote_key = allow_remote_key
|
|
1910
|
+
if "api" in raw:
|
|
1911
|
+
name = _non_empty_text(raw["api"], where=f"{spot}.api")
|
|
1912
|
+
api = _MODEL_API_BY_NAME.get(name)
|
|
1913
|
+
if api is None:
|
|
1914
|
+
raise ConfigError(f"{spot}.api: 只支持 {', '.join(_MODEL_API_BY_NAME)},收到 {name!r}")
|
|
1915
|
+
draft.api = api
|
|
1916
|
+
if "max_tokens_field" in raw:
|
|
1917
|
+
draft.max_tokens_field = _as_max_tokens_field(
|
|
1918
|
+
raw["max_tokens_field"], where=f"{spot}.max_tokens_field"
|
|
1919
|
+
)
|
|
1920
|
+
if "cache_breakpoints" in raw:
|
|
1921
|
+
draft.cache_breakpoints = _as_cache_breakpoints(
|
|
1922
|
+
raw["cache_breakpoints"], where=f"{spot}.cache_breakpoints"
|
|
1923
|
+
)
|
|
1924
|
+
if "discover" in raw:
|
|
1925
|
+
draft.discover = _as_bool(raw["discover"], where=f"{spot}.discover")
|
|
1926
|
+
if "discover_context_window" in raw:
|
|
1927
|
+
draft.discover_context_window = _positive_int(
|
|
1928
|
+
raw["discover_context_window"], where=f"{spot}.discover_context_window"
|
|
1929
|
+
)
|
|
1930
|
+
if "discover_max_tokens" in raw:
|
|
1931
|
+
draft.discover_max_tokens = _positive_int(
|
|
1932
|
+
raw["discover_max_tokens"], where=f"{spot}.discover_max_tokens"
|
|
1933
|
+
)
|
|
1934
|
+
|
|
1935
|
+
|
|
1936
|
+
def _merge_model(
|
|
1937
|
+
spec: str, raw: JsonValue, *, where: str, models: dict[tuple[str, str], _ModelDraft]
|
|
1938
|
+
) -> None:
|
|
1939
|
+
provider_id, separator, model_id = spec.partition("/")
|
|
1940
|
+
if not separator or not provider_id or not model_id:
|
|
1941
|
+
raise ConfigError(
|
|
1942
|
+
f'{where}: 模型键要写成 "provider/模型 id",收到 {spec!r}'
|
|
1943
|
+
'(例如 "deepseek/deepseek-flash": {...})'
|
|
1944
|
+
)
|
|
1945
|
+
spot = f'{where}: models."{spec}"'
|
|
1946
|
+
if not isinstance(raw, dict):
|
|
1947
|
+
raise ConfigError(f"{spot}: 必须是 JSON 对象")
|
|
1948
|
+
unknown = sorted(set(raw) - _MODEL_KEYS)
|
|
1949
|
+
if unknown:
|
|
1950
|
+
raise ConfigError(
|
|
1951
|
+
f"{spot}: 未知字段 {', '.join(unknown)}(可用: {', '.join(sorted(_MODEL_KEYS))})"
|
|
1952
|
+
)
|
|
1953
|
+
|
|
1954
|
+
key = (provider_id, model_id)
|
|
1955
|
+
draft = models.get(key)
|
|
1956
|
+
if draft is None:
|
|
1957
|
+
draft = _ModelDraft(provider_id=provider_id, id=model_id, source=where)
|
|
1958
|
+
models[key] = draft
|
|
1959
|
+
else:
|
|
1960
|
+
draft.source = where
|
|
1961
|
+
|
|
1962
|
+
if "name" in raw:
|
|
1963
|
+
draft.name = _non_empty_text(raw["name"], where=f"{spot}.name")
|
|
1964
|
+
if "context_window" in raw:
|
|
1965
|
+
draft.context_window = _positive_int(raw["context_window"], where=f"{spot}.context_window")
|
|
1966
|
+
if "max_tokens" in raw:
|
|
1967
|
+
draft.max_tokens = _positive_int(raw["max_tokens"], where=f"{spot}.max_tokens")
|
|
1968
|
+
if "input" in raw:
|
|
1969
|
+
draft.input = _as_modalities(raw["input"], where=f"{spot}.input")
|
|
1970
|
+
if "reasoning" in raw:
|
|
1971
|
+
draft.reasoning = _as_bool(raw["reasoning"], where=f"{spot}.reasoning")
|
|
1972
|
+
if "thinking_levels" in raw:
|
|
1973
|
+
draft.thinking_levels = _as_thinking_levels(
|
|
1974
|
+
raw["thinking_levels"], where=f"{spot}.thinking_levels"
|
|
1975
|
+
)
|
|
1976
|
+
for part in _COST_PARTS:
|
|
1977
|
+
field_name = f"cost_{part}"
|
|
1978
|
+
if field_name in raw:
|
|
1979
|
+
draft.cost[part] = _as_cost(raw[field_name], where=f"{spot}.{field_name}")
|
|
1980
|
+
|
|
1981
|
+
|
|
1982
|
+
def _merge_retry(
|
|
1983
|
+
document: Mapping[str, JsonValue], *, where: str, retry: RetrySettings
|
|
1984
|
+
) -> RetrySettings:
|
|
1985
|
+
"""``retry`` 逐字段覆盖。写错的字段在装配之前就报错,不留到第一次请求失败。"""
|
|
1986
|
+
raw = document.get("retry", {})
|
|
1987
|
+
if not isinstance(raw, dict):
|
|
1988
|
+
raise ConfigError(f"{where}: retry 必须是 JSON 对象")
|
|
1989
|
+
unknown = sorted(set(raw) - _RETRY_KEYS)
|
|
1990
|
+
if unknown:
|
|
1991
|
+
raise ConfigError(
|
|
1992
|
+
f"{where}: retry 里的未知字段 {', '.join(unknown)}"
|
|
1993
|
+
f"(可用: {', '.join(sorted(_RETRY_KEYS))})"
|
|
1994
|
+
)
|
|
1995
|
+
spot = f"{where}: retry"
|
|
1996
|
+
enabled = retry.enabled
|
|
1997
|
+
max_retries = retry.max_retries
|
|
1998
|
+
base_delay_ms = retry.base_delay_ms
|
|
1999
|
+
max_agent_delay_ms = retry.max_agent_delay_ms
|
|
2000
|
+
if "enabled" in raw:
|
|
2001
|
+
enabled = _as_bool(raw["enabled"], where=f"{spot}.enabled")
|
|
2002
|
+
if "max_retries" in raw:
|
|
2003
|
+
max_retries = _non_negative_int(raw["max_retries"], where=f"{spot}.max_retries")
|
|
2004
|
+
if "base_delay_ms" in raw:
|
|
2005
|
+
base_delay_ms = _non_negative_int(raw["base_delay_ms"], where=f"{spot}.base_delay_ms")
|
|
2006
|
+
if "max_agent_delay_ms" in raw:
|
|
2007
|
+
max_agent_delay_ms = _positive_int(
|
|
2008
|
+
raw["max_agent_delay_ms"], where=f"{spot}.max_agent_delay_ms"
|
|
2009
|
+
)
|
|
2010
|
+
return RetrySettings(
|
|
2011
|
+
enabled=enabled,
|
|
2012
|
+
max_retries=max_retries,
|
|
2013
|
+
base_delay_ms=base_delay_ms,
|
|
2014
|
+
max_agent_delay_ms=max_agent_delay_ms,
|
|
2015
|
+
)
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
# ----------------------------------------------------------------- 环境变量
|
|
2019
|
+
|
|
2020
|
+
|
|
2021
|
+
def _apply_env(
|
|
2022
|
+
env: Mapping[str, str],
|
|
2023
|
+
*,
|
|
2024
|
+
defaults: _Defaults,
|
|
2025
|
+
retry: RetrySettings,
|
|
2026
|
+
compaction: CompactionSettings,
|
|
2027
|
+
) -> tuple[_Defaults, RetrySettings, CompactionSettings, tuple[str, ...]]:
|
|
2028
|
+
"""把环境变量压到文件之上。返回新值与生效的变量名。
|
|
2029
|
+
|
|
2030
|
+
空字符串视为"没有设置":``BRAID_MODEL=`` 这种写法在 shell 脚本里很常见,
|
|
2031
|
+
它表达的是"这次不覆盖",而不是"默认模型叫空字符串"。
|
|
2032
|
+
"""
|
|
2033
|
+
applied: list[str] = []
|
|
2034
|
+
|
|
2035
|
+
raw_model = _env_text(env, ENV_MODEL)
|
|
2036
|
+
if raw_model is not None:
|
|
2037
|
+
defaults.model = raw_model
|
|
2038
|
+
defaults.model_source = f"环境变量 {ENV_MODEL}"
|
|
2039
|
+
applied.append(ENV_MODEL)
|
|
2040
|
+
|
|
2041
|
+
raw_thinking = _env_text(env, ENV_THINKING)
|
|
2042
|
+
if raw_thinking is not None:
|
|
2043
|
+
defaults.thinking = _as_thinking_level(raw_thinking, where=f"环境变量 {ENV_THINKING}")
|
|
2044
|
+
defaults.thinking_source = f"环境变量 {ENV_THINKING}"
|
|
2045
|
+
applied.append(ENV_THINKING)
|
|
2046
|
+
|
|
2047
|
+
raw_retry_enabled = _env_text(env, ENV_RETRY_ENABLED)
|
|
2048
|
+
if raw_retry_enabled is not None:
|
|
2049
|
+
retry = replace_retry(
|
|
2050
|
+
retry, enabled=_as_env_bool(raw_retry_enabled, where=f"环境变量 {ENV_RETRY_ENABLED}")
|
|
2051
|
+
)
|
|
2052
|
+
applied.append(ENV_RETRY_ENABLED)
|
|
2053
|
+
|
|
2054
|
+
raw_max_retries = _env_text(env, ENV_RETRY_MAX_RETRIES)
|
|
2055
|
+
if raw_max_retries is not None:
|
|
2056
|
+
retry = replace_retry(
|
|
2057
|
+
retry,
|
|
2058
|
+
max_retries=_as_env_int(
|
|
2059
|
+
raw_max_retries, where=f"环境变量 {ENV_RETRY_MAX_RETRIES}", allow_zero=True
|
|
2060
|
+
),
|
|
2061
|
+
)
|
|
2062
|
+
applied.append(ENV_RETRY_MAX_RETRIES)
|
|
2063
|
+
|
|
2064
|
+
raw_base_delay = _env_text(env, ENV_RETRY_BASE_DELAY_MS)
|
|
2065
|
+
if raw_base_delay is not None:
|
|
2066
|
+
retry = replace_retry(
|
|
2067
|
+
retry,
|
|
2068
|
+
base_delay_ms=_as_env_int(
|
|
2069
|
+
raw_base_delay, where=f"环境变量 {ENV_RETRY_BASE_DELAY_MS}", allow_zero=True
|
|
2070
|
+
),
|
|
2071
|
+
)
|
|
2072
|
+
applied.append(ENV_RETRY_BASE_DELAY_MS)
|
|
2073
|
+
|
|
2074
|
+
raw_agent_delay = _env_text(env, ENV_RETRY_MAX_AGENT_DELAY_MS)
|
|
2075
|
+
if raw_agent_delay is not None:
|
|
2076
|
+
retry = replace_retry(
|
|
2077
|
+
retry,
|
|
2078
|
+
max_agent_delay_ms=_as_env_int(
|
|
2079
|
+
raw_agent_delay, where=f"环境变量 {ENV_RETRY_MAX_AGENT_DELAY_MS}", allow_zero=False
|
|
2080
|
+
),
|
|
2081
|
+
)
|
|
2082
|
+
applied.append(ENV_RETRY_MAX_AGENT_DELAY_MS)
|
|
2083
|
+
|
|
2084
|
+
raw_compaction_enabled = _env_text(env, ENV_COMPACTION_ENABLED)
|
|
2085
|
+
if raw_compaction_enabled is not None:
|
|
2086
|
+
compaction = replace_compaction(
|
|
2087
|
+
compaction,
|
|
2088
|
+
enabled=_as_env_bool(
|
|
2089
|
+
raw_compaction_enabled, where=f"环境变量 {ENV_COMPACTION_ENABLED}"
|
|
2090
|
+
),
|
|
2091
|
+
)
|
|
2092
|
+
applied.append(ENV_COMPACTION_ENABLED)
|
|
2093
|
+
|
|
2094
|
+
raw_reserve = _env_text(env, ENV_COMPACTION_RESERVE_TOKENS)
|
|
2095
|
+
if raw_reserve is not None:
|
|
2096
|
+
compaction = replace_compaction(
|
|
2097
|
+
compaction,
|
|
2098
|
+
reserve_tokens=_as_env_int(
|
|
2099
|
+
raw_reserve, where=f"环境变量 {ENV_COMPACTION_RESERVE_TOKENS}", allow_zero=False
|
|
2100
|
+
),
|
|
2101
|
+
)
|
|
2102
|
+
applied.append(ENV_COMPACTION_RESERVE_TOKENS)
|
|
2103
|
+
|
|
2104
|
+
raw_keep_recent = _env_text(env, ENV_COMPACTION_KEEP_RECENT_TOKENS)
|
|
2105
|
+
if raw_keep_recent is not None:
|
|
2106
|
+
compaction = replace_compaction(
|
|
2107
|
+
compaction,
|
|
2108
|
+
keep_recent_tokens=_as_env_int(
|
|
2109
|
+
raw_keep_recent,
|
|
2110
|
+
where=f"环境变量 {ENV_COMPACTION_KEEP_RECENT_TOKENS}",
|
|
2111
|
+
allow_zero=False,
|
|
2112
|
+
),
|
|
2113
|
+
)
|
|
2114
|
+
applied.append(ENV_COMPACTION_KEEP_RECENT_TOKENS)
|
|
2115
|
+
|
|
2116
|
+
return defaults, retry, compaction, tuple(applied)
|
|
2117
|
+
|
|
2118
|
+
|
|
2119
|
+
def replace_retry(
|
|
2120
|
+
settings: RetrySettings,
|
|
2121
|
+
*,
|
|
2122
|
+
enabled: bool | None = None,
|
|
2123
|
+
max_retries: int | None = None,
|
|
2124
|
+
base_delay_ms: int | None = None,
|
|
2125
|
+
max_agent_delay_ms: int | None = None,
|
|
2126
|
+
) -> RetrySettings:
|
|
2127
|
+
"""按字段替换重试设置;``None`` 表示保留原值。"""
|
|
2128
|
+
return RetrySettings(
|
|
2129
|
+
enabled=settings.enabled if enabled is None else enabled,
|
|
2130
|
+
max_retries=settings.max_retries if max_retries is None else max_retries,
|
|
2131
|
+
base_delay_ms=settings.base_delay_ms if base_delay_ms is None else base_delay_ms,
|
|
2132
|
+
max_agent_delay_ms=(
|
|
2133
|
+
settings.max_agent_delay_ms if max_agent_delay_ms is None else max_agent_delay_ms
|
|
2134
|
+
),
|
|
2135
|
+
)
|
|
2136
|
+
|
|
2137
|
+
|
|
2138
|
+
def replace_compaction(
|
|
2139
|
+
settings: CompactionSettings,
|
|
2140
|
+
*,
|
|
2141
|
+
enabled: bool | None = None,
|
|
2142
|
+
reserve_tokens: int | None = None,
|
|
2143
|
+
keep_recent_tokens: int | None = None,
|
|
2144
|
+
tool_results: ToolResultCleanupSettings | None = None,
|
|
2145
|
+
) -> CompactionSettings:
|
|
2146
|
+
"""按字段替换压缩设置;``None`` 表示保留原值。"""
|
|
2147
|
+
return CompactionSettings(
|
|
2148
|
+
enabled=settings.enabled if enabled is None else enabled,
|
|
2149
|
+
reserve_tokens=settings.reserve_tokens if reserve_tokens is None else reserve_tokens,
|
|
2150
|
+
keep_recent_tokens=(
|
|
2151
|
+
settings.keep_recent_tokens if keep_recent_tokens is None else keep_recent_tokens
|
|
2152
|
+
),
|
|
2153
|
+
tool_results=settings.tool_results if tool_results is None else tool_results,
|
|
2154
|
+
)
|
|
2155
|
+
|
|
2156
|
+
|
|
2157
|
+
def replace_permission(
|
|
2158
|
+
settings: PermissionSettings,
|
|
2159
|
+
*,
|
|
2160
|
+
mode: PermissionMode | None = None,
|
|
2161
|
+
project_trusted: bool | None = None,
|
|
2162
|
+
) -> PermissionSettings:
|
|
2163
|
+
"""按字段替换权限设置。``--permission-mode`` 只改模式,规则保持不动。"""
|
|
2164
|
+
return PermissionSettings(
|
|
2165
|
+
default=settings.default,
|
|
2166
|
+
mode=settings.mode if mode is None else mode,
|
|
2167
|
+
approval_timeout_seconds=settings.approval_timeout_seconds,
|
|
2168
|
+
tools=settings.tools,
|
|
2169
|
+
bash=settings.bash,
|
|
2170
|
+
paths=settings.paths,
|
|
2171
|
+
domains=settings.domains,
|
|
2172
|
+
rules=settings.rules,
|
|
2173
|
+
project_trusted=(settings.project_trusted if project_trusted is None else project_trusted),
|
|
2174
|
+
)
|
|
2175
|
+
|
|
2176
|
+
|
|
2177
|
+
def merge_mcp_permissions(
|
|
2178
|
+
settings: PermissionSettings, rules: Mapping[str, PermissionAction]
|
|
2179
|
+
) -> PermissionSettings:
|
|
2180
|
+
"""把 MCP 服务器的调用策略并进权限设置。
|
|
2181
|
+
|
|
2182
|
+
配置里已经写过的同名工具规则优先:服务器条目给的是默认值,用户为某个工具
|
|
2183
|
+
显式写下的 allow / ask / deny 覆盖它。没有现有规则时,先把四张规则表展开成
|
|
2184
|
+
带来源的规则,再加入 MCP 规则;否则 ``rules`` 一旦非空就会让其余三张表失效。
|
|
2185
|
+
"""
|
|
2186
|
+
if not rules:
|
|
2187
|
+
return settings
|
|
2188
|
+
existing = settings.rules or tuple(_rules_from_tables(settings))
|
|
2189
|
+
taken = {(rule.table, rule.pattern, rule.scope) for rule in existing}
|
|
2190
|
+
incoming = [
|
|
2191
|
+
ScopedRule("tools", name, action, "global", "mcp")
|
|
2192
|
+
for name, action in rules.items()
|
|
2193
|
+
if ("tools", name, "global") not in taken
|
|
2194
|
+
]
|
|
2195
|
+
tools = dict(settings.tools)
|
|
2196
|
+
for name, action in rules.items():
|
|
2197
|
+
tools.setdefault(name, action)
|
|
2198
|
+
return replace(
|
|
2199
|
+
settings,
|
|
2200
|
+
tools=MappingProxyType(tools),
|
|
2201
|
+
rules=_replace_rules(existing, incoming),
|
|
2202
|
+
)
|
|
2203
|
+
|
|
2204
|
+
|
|
2205
|
+
def _rules_from_tables(settings: PermissionSettings) -> list[ScopedRule]:
|
|
2206
|
+
"""把四张规则表展开成带来源的规则,来源记为 ``settings``。"""
|
|
2207
|
+
return [
|
|
2208
|
+
*(
|
|
2209
|
+
ScopedRule("tools", pattern, action, "global", "settings")
|
|
2210
|
+
for pattern, action in settings.tools.items()
|
|
2211
|
+
),
|
|
2212
|
+
*(
|
|
2213
|
+
ScopedRule("bash", pattern, action, "global", "settings")
|
|
2214
|
+
for pattern, action in settings.bash.items()
|
|
2215
|
+
),
|
|
2216
|
+
*(
|
|
2217
|
+
ScopedRule("paths", pattern, action, "global", "settings")
|
|
2218
|
+
for pattern, action in settings.paths.items()
|
|
2219
|
+
),
|
|
2220
|
+
*(
|
|
2221
|
+
ScopedRule("domains", pattern, action, "global", "settings")
|
|
2222
|
+
for pattern, action in settings.domains.items()
|
|
2223
|
+
),
|
|
2224
|
+
]
|
|
2225
|
+
|
|
2226
|
+
|
|
2227
|
+
def replace_sandbox(
|
|
2228
|
+
settings: SandboxSettings,
|
|
2229
|
+
*,
|
|
2230
|
+
mode: SandboxMode | None = None,
|
|
2231
|
+
allow_domains: Sequence[str] | None = None,
|
|
2232
|
+
) -> SandboxSettings:
|
|
2233
|
+
"""按字段替换沙箱设置。命令行只覆盖模式与额外放行的域名,其余读配置。"""
|
|
2234
|
+
merged_allow = settings.allow_domains
|
|
2235
|
+
if allow_domains is not None:
|
|
2236
|
+
merged_allow = (
|
|
2237
|
+
*settings.allow_domains,
|
|
2238
|
+
*(domain for domain in dedupe_domains(list(allow_domains))),
|
|
2239
|
+
)
|
|
2240
|
+
return SandboxSettings(
|
|
2241
|
+
mode=settings.mode if mode is None else mode,
|
|
2242
|
+
backend=settings.backend,
|
|
2243
|
+
network=settings.network,
|
|
2244
|
+
read=settings.read,
|
|
2245
|
+
allow_domains=merged_allow,
|
|
2246
|
+
deny_domains=settings.deny_domains,
|
|
2247
|
+
writable_paths=settings.writable_paths,
|
|
2248
|
+
readable_paths=settings.readable_paths,
|
|
2249
|
+
executable=settings.executable,
|
|
2250
|
+
)
|
|
2251
|
+
|
|
2252
|
+
|
|
2253
|
+
def _env_text(env: Mapping[str, str], name: str) -> str | None:
|
|
2254
|
+
value = env.get(name)
|
|
2255
|
+
if value is None or not value.strip():
|
|
2256
|
+
return None
|
|
2257
|
+
return value.strip()
|
|
2258
|
+
|
|
2259
|
+
|
|
2260
|
+
def _as_env_int(raw: str, *, where: str, allow_zero: bool) -> int:
|
|
2261
|
+
try:
|
|
2262
|
+
value = int(raw)
|
|
2263
|
+
except ValueError as exc:
|
|
2264
|
+
raise ConfigError(f"{where}: 必须是整数,收到 {raw!r}") from exc
|
|
2265
|
+
if value < 0 or (value == 0 and not allow_zero):
|
|
2266
|
+
bound = "非负整数" if allow_zero else "正整数"
|
|
2267
|
+
raise ConfigError(f"{where}: 必须是{bound},收到 {raw!r}")
|
|
2268
|
+
return value
|
|
2269
|
+
|
|
2270
|
+
|
|
2271
|
+
# ------------------------------------------------------------------ 值校验
|
|
2272
|
+
|
|
2273
|
+
|
|
2274
|
+
def _non_empty_text(value: JsonValue, *, where: str) -> str:
|
|
2275
|
+
if not isinstance(value, str) or not value.strip():
|
|
2276
|
+
raise ConfigError(f"{where}: 必须是非空字符串")
|
|
2277
|
+
return value
|
|
2278
|
+
|
|
2279
|
+
|
|
2280
|
+
def _positive_int(value: JsonValue, *, where: str) -> int:
|
|
2281
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
2282
|
+
raise ConfigError(f"{where}: 必须是正整数")
|
|
2283
|
+
if value <= 0:
|
|
2284
|
+
raise ConfigError(f"{where}: 必须是正整数")
|
|
2285
|
+
return value
|
|
2286
|
+
|
|
2287
|
+
|
|
2288
|
+
def _non_negative_int(value: JsonValue, *, where: str) -> int:
|
|
2289
|
+
"""重试次数与初始延迟允许 0:分别等于"不重试"与"不退避"。"""
|
|
2290
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
2291
|
+
raise ConfigError(f"{where}: 必须是非负整数")
|
|
2292
|
+
return value
|
|
2293
|
+
|
|
2294
|
+
|
|
2295
|
+
def _as_bool(value: JsonValue, *, where: str) -> bool:
|
|
2296
|
+
"""配置文件里的布尔字段。JSON 有真布尔类型,写成字符串一律报错。"""
|
|
2297
|
+
if not isinstance(value, bool):
|
|
2298
|
+
raise ConfigError(f"{where}: 必须是 true 或 false,收到 {value!r}")
|
|
2299
|
+
return value
|
|
2300
|
+
|
|
2301
|
+
|
|
2302
|
+
def _as_env_bool(raw: str, *, where: str) -> bool:
|
|
2303
|
+
"""环境变量里的布尔字段。它只有字符串形态,所以另外认 1/0、yes/no、on/off。"""
|
|
2304
|
+
lowered = raw.strip().lower()
|
|
2305
|
+
if lowered in ("1", "true", "yes", "on"):
|
|
2306
|
+
return True
|
|
2307
|
+
if lowered in ("0", "false", "no", "off"):
|
|
2308
|
+
return False
|
|
2309
|
+
raise ConfigError(f"{where}: 只接受 true/false(或 1/0、yes/no、on/off),收到 {raw!r}")
|
|
2310
|
+
|
|
2311
|
+
|
|
2312
|
+
def _as_ratio(value: JsonValue, *, where: str) -> float:
|
|
2313
|
+
"""``(0, 1]`` 的比例。布尔值不算数字:``true`` 会被读成 1。"""
|
|
2314
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
2315
|
+
raise ConfigError(f"{where}: 必须是 0 到 1 之间的小数,收到 {value!r}")
|
|
2316
|
+
ratio = float(value)
|
|
2317
|
+
if not 0 < ratio <= 1:
|
|
2318
|
+
raise ConfigError(f"{where}: 必须大于 0 且不超过 1,收到 {value!r}")
|
|
2319
|
+
return ratio
|
|
2320
|
+
|
|
2321
|
+
|
|
2322
|
+
def _as_modalities(value: JsonValue, *, where: str) -> list[ModelInput]:
|
|
2323
|
+
if not isinstance(value, list) or not value:
|
|
2324
|
+
raise ConfigError(f"{where}: 必须是非空数组,取值 {'、'.join(_INPUT_MODALITIES)}")
|
|
2325
|
+
modalities: list[ModelInput] = []
|
|
2326
|
+
for item in value:
|
|
2327
|
+
modality = _INPUT_MODALITY_BY_NAME.get(item) if isinstance(item, str) else None
|
|
2328
|
+
if modality is None:
|
|
2329
|
+
raise ConfigError(f"{where}: 只支持 {'、'.join(_INPUT_MODALITIES)},收到 {item!r}")
|
|
2330
|
+
modalities.append(modality)
|
|
2331
|
+
return modalities
|
|
2332
|
+
|
|
2333
|
+
|
|
2334
|
+
def _as_max_tokens_field(value: JsonValue, *, where: str) -> MaxTokensField:
|
|
2335
|
+
field_name = _MAX_TOKENS_FIELD_BY_NAME.get(value) if isinstance(value, str) else None
|
|
2336
|
+
if field_name is None:
|
|
2337
|
+
raise ConfigError(f"{where}: 只支持 {'、'.join(_MAX_TOKENS_FIELDS)},收到 {value!r}")
|
|
2338
|
+
return field_name
|
|
2339
|
+
|
|
2340
|
+
|
|
2341
|
+
def _as_cache_breakpoints(value: JsonValue, *, where: str) -> tuple[CacheAnchor, ...]:
|
|
2342
|
+
"""缓存断点清单。空数组表示"这次不要断点",比默认值少几个位置就用几个。"""
|
|
2343
|
+
if not isinstance(value, list):
|
|
2344
|
+
raise ConfigError(f'{where}: 必须是数组,例如 ["tools", "system"]')
|
|
2345
|
+
anchors: list[CacheAnchor] = []
|
|
2346
|
+
for item in value:
|
|
2347
|
+
anchor = _ANCHOR_BY_NAME.get(item) if isinstance(item, str) else None
|
|
2348
|
+
if anchor is None:
|
|
2349
|
+
raise ConfigError(f"{where}: 只支持 {'、'.join(_ANCHORS)},收到 {item!r}")
|
|
2350
|
+
if anchor in anchors:
|
|
2351
|
+
raise ConfigError(f"{where}: {anchor} 重复了")
|
|
2352
|
+
anchors.append(anchor)
|
|
2353
|
+
return tuple(anchors)
|
|
2354
|
+
|
|
2355
|
+
|
|
2356
|
+
def _as_thinking_level(value: JsonValue, *, where: str) -> ModelThinkingLevel:
|
|
2357
|
+
level = _THINKING_LEVEL_BY_NAME.get(value) if isinstance(value, str) else None
|
|
2358
|
+
if level is None:
|
|
2359
|
+
raise ConfigError(f"{where}: 只支持 {'、'.join(EXTENDED_THINKING_LEVELS)},收到 {value!r}")
|
|
2360
|
+
return level
|
|
2361
|
+
|
|
2362
|
+
|
|
2363
|
+
def _as_thinking_levels(value: JsonValue, *, where: str) -> list[ModelThinkingLevel]:
|
|
2364
|
+
"""一组思考档位。顺序按写进来的顺序保存——``/models`` 直接展示它。"""
|
|
2365
|
+
if not isinstance(value, list) or not value:
|
|
2366
|
+
raise ConfigError(f"{where}: 必须是非空数组,取值 {'、'.join(EXTENDED_THINKING_LEVELS)}")
|
|
2367
|
+
levels: list[ModelThinkingLevel] = []
|
|
2368
|
+
for item in value:
|
|
2369
|
+
level = _THINKING_LEVEL_BY_NAME.get(item) if isinstance(item, str) else None
|
|
2370
|
+
if level is None:
|
|
2371
|
+
raise ConfigError(
|
|
2372
|
+
f"{where}: 只支持 {'、'.join(EXTENDED_THINKING_LEVELS)},收到 {item!r}"
|
|
2373
|
+
)
|
|
2374
|
+
if level in levels:
|
|
2375
|
+
raise ConfigError(f"{where}: 档位 {level} 重复了")
|
|
2376
|
+
levels.append(level)
|
|
2377
|
+
return levels
|
|
2378
|
+
|
|
2379
|
+
|
|
2380
|
+
def _as_cost(value: JsonValue, *, where: str) -> float:
|
|
2381
|
+
if isinstance(value, bool) or not isinstance(value, int | float):
|
|
2382
|
+
raise ConfigError(f"{where}: 必须是非负数字(美元 / 百万 token)")
|
|
2383
|
+
if value < 0:
|
|
2384
|
+
raise ConfigError(f"{where}: 必须是非负数字(美元 / 百万 token)")
|
|
2385
|
+
return float(value)
|
|
2386
|
+
|
|
2387
|
+
|
|
2388
|
+
def _as_permission_action(value: JsonValue, *, where: str) -> PermissionAction:
|
|
2389
|
+
if isinstance(value, str):
|
|
2390
|
+
action = _PERMISSION_ACTION_BY_NAME.get(value)
|
|
2391
|
+
if action is not None:
|
|
2392
|
+
return action
|
|
2393
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(PERMISSION_ACTIONS)} 之一,收到 {value!r}")
|
|
2394
|
+
|
|
2395
|
+
|
|
2396
|
+
def _as_permission_mode(value: JsonValue, *, where: str) -> PermissionMode:
|
|
2397
|
+
if isinstance(value, str):
|
|
2398
|
+
mode = _PERMISSION_MODE_BY_NAME.get(value)
|
|
2399
|
+
if mode is not None:
|
|
2400
|
+
return mode
|
|
2401
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(PERMISSION_MODES)} 之一,收到 {value!r}")
|
|
2402
|
+
|
|
2403
|
+
|
|
2404
|
+
def _as_sandbox_mode(value: JsonValue, *, where: str) -> SandboxMode:
|
|
2405
|
+
if isinstance(value, str):
|
|
2406
|
+
mode = _SANDBOX_MODE_BY_NAME.get(value)
|
|
2407
|
+
if mode is not None:
|
|
2408
|
+
return mode
|
|
2409
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(SANDBOX_MODES)} 之一,收到 {value!r}")
|
|
2410
|
+
|
|
2411
|
+
|
|
2412
|
+
def _as_network_mode(value: JsonValue, *, where: str) -> NetworkMode:
|
|
2413
|
+
if isinstance(value, str):
|
|
2414
|
+
mode = _NETWORK_MODE_BY_NAME.get(value)
|
|
2415
|
+
if mode is not None:
|
|
2416
|
+
return mode
|
|
2417
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(NETWORK_MODES)} 之一,收到 {value!r}")
|
|
2418
|
+
|
|
2419
|
+
|
|
2420
|
+
def _as_read_scope(value: JsonValue, *, where: str) -> ReadScope:
|
|
2421
|
+
if isinstance(value, str):
|
|
2422
|
+
scope = _READ_SCOPE_BY_NAME.get(value)
|
|
2423
|
+
if scope is not None:
|
|
2424
|
+
return scope
|
|
2425
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(READ_SCOPES)} 之一,收到 {value!r}")
|
|
2426
|
+
|
|
2427
|
+
|
|
2428
|
+
def _as_backend_name(value: JsonValue, *, where: str) -> BackendName:
|
|
2429
|
+
if isinstance(value, str):
|
|
2430
|
+
name = _BACKEND_BY_NAME.get(value)
|
|
2431
|
+
if name is not None:
|
|
2432
|
+
return name
|
|
2433
|
+
raise ConfigError(f"{where}: 必须是 {', '.join(BACKEND_NAMES)} 之一,收到 {value!r}")
|
|
2434
|
+
|
|
2435
|
+
|
|
2436
|
+
def _as_string_list(value: JsonValue, *, where: str) -> tuple[str, ...]:
|
|
2437
|
+
"""字符串数组字段。空数组合法(表示"没有额外项"),空字符串不合法。"""
|
|
2438
|
+
if not isinstance(value, list):
|
|
2439
|
+
raise ConfigError(f"{where}: 必须是字符串数组")
|
|
2440
|
+
items: list[str] = []
|
|
2441
|
+
for index, item in enumerate(value):
|
|
2442
|
+
if not isinstance(item, str) or not item.strip():
|
|
2443
|
+
raise ConfigError(f"{where}[{index}]: 必须是非空字符串")
|
|
2444
|
+
items.append(item)
|
|
2445
|
+
return tuple(items)
|
|
2446
|
+
|
|
2447
|
+
|
|
2448
|
+
def _as_positive_float(value: JsonValue, *, where: str) -> float:
|
|
2449
|
+
if isinstance(value, bool) or not isinstance(value, int | float) or value <= 0:
|
|
2450
|
+
raise ConfigError(f"{where}: 必须是正数(秒),收到 {value!r}")
|
|
2451
|
+
return float(value)
|
|
2452
|
+
|
|
2453
|
+
|
|
2454
|
+
def _as_argv(value: JsonValue, *, where: str) -> tuple[str, ...]:
|
|
2455
|
+
"""argv 数组:非空、每项非空字符串。空字符串会被当成"少传了一个参数"。"""
|
|
2456
|
+
if not isinstance(value, list) or not value:
|
|
2457
|
+
raise ConfigError(
|
|
2458
|
+
f'{where}: 必须是非空字符串数组(例如 ["pyright-langserver", "--stdio"])'
|
|
2459
|
+
)
|
|
2460
|
+
argv: list[str] = []
|
|
2461
|
+
for index, item in enumerate(value):
|
|
2462
|
+
if not isinstance(item, str) or not item.strip():
|
|
2463
|
+
raise ConfigError(f"{where}[{index}]: 必须是非空字符串")
|
|
2464
|
+
argv.append(item)
|
|
2465
|
+
return tuple(argv)
|
|
2466
|
+
|
|
2467
|
+
|
|
2468
|
+
def _as_mapping(value: JsonValue, *, where: str) -> dict[str, JsonValue]:
|
|
2469
|
+
if not isinstance(value, dict):
|
|
2470
|
+
raise ConfigError(f"{where}: 必须是 JSON 对象")
|
|
2471
|
+
return dict(value)
|
|
2472
|
+
|
|
2473
|
+
|
|
2474
|
+
def _as_string_mapping(value: JsonValue, *, where: str) -> dict[str, str]:
|
|
2475
|
+
if not isinstance(value, dict):
|
|
2476
|
+
raise ConfigError(f"{where}: 必须是 JSON 对象,值都是字符串")
|
|
2477
|
+
mapping: dict[str, str] = {}
|
|
2478
|
+
for key, item in value.items():
|
|
2479
|
+
if not isinstance(item, str):
|
|
2480
|
+
raise ConfigError(f"{where}.{key}: 必须是字符串,收到 {item!r}")
|
|
2481
|
+
mapping[key] = item
|
|
2482
|
+
return mapping
|
|
2483
|
+
|
|
2484
|
+
|
|
2485
|
+
# ------------------------------------------------------------------- 构建
|
|
2486
|
+
|
|
2487
|
+
|
|
2488
|
+
def _build_config(
|
|
2489
|
+
*,
|
|
2490
|
+
providers: Mapping[str, _ProviderDraft],
|
|
2491
|
+
models: Mapping[tuple[str, str], _ModelDraft],
|
|
2492
|
+
defaults: _Defaults,
|
|
2493
|
+
retry: RetrySettings,
|
|
2494
|
+
compaction: CompactionSettings,
|
|
2495
|
+
statusline: StatuslineSettings,
|
|
2496
|
+
sources: tuple[str, ...],
|
|
2497
|
+
env_overrides: tuple[str, ...],
|
|
2498
|
+
instructions: tuple[str, ...],
|
|
2499
|
+
permission: PermissionSettings,
|
|
2500
|
+
sandbox: SandboxSettings,
|
|
2501
|
+
checkpoint: CheckpointSettings,
|
|
2502
|
+
subagents: SubagentSettings,
|
|
2503
|
+
web: WebSettings,
|
|
2504
|
+
lsp: Mapping[str, _LspDraft],
|
|
2505
|
+
verify: _VerifyDraft,
|
|
2506
|
+
formatting: _FormatDraft,
|
|
2507
|
+
observability: ObservabilitySettings,
|
|
2508
|
+
mcp: McpSettings,
|
|
2509
|
+
) -> AgentConfig:
|
|
2510
|
+
for (provider_id, model_id), draft in models.items():
|
|
2511
|
+
if provider_id not in providers:
|
|
2512
|
+
raise ConfigError(
|
|
2513
|
+
f'{draft.source}: models."{provider_id}/{model_id}" 的 provider '
|
|
2514
|
+
f"{provider_id} 没有声明(先写 providers.{provider_id})"
|
|
2515
|
+
)
|
|
2516
|
+
|
|
2517
|
+
entries: list[ProviderEntry] = []
|
|
2518
|
+
for provider_id, draft in providers.items():
|
|
2519
|
+
where = f"{draft.source}: providers.{provider_id}"
|
|
2520
|
+
if draft.base_url is None:
|
|
2521
|
+
raise ConfigError(
|
|
2522
|
+
f"{where}.base_url: 必填(端点的根地址,例如 https://api.deepseek.com/v1)"
|
|
2523
|
+
)
|
|
2524
|
+
if (
|
|
2525
|
+
draft.api_key is not None
|
|
2526
|
+
and not draft.allow_remote_key
|
|
2527
|
+
and not is_local_endpoint(draft.base_url)
|
|
2528
|
+
):
|
|
2529
|
+
raise ConfigError(
|
|
2530
|
+
f"{where}.api_key: 静态密钥只允许用于本机端点"
|
|
2531
|
+
f"({', '.join(sorted(LOCAL_ENDPOINT_HOSTS))});远端端点请改用 env_key,"
|
|
2532
|
+
f"运行 `braid auth login {provider_id}` 把密钥写进系统钥匙串,"
|
|
2533
|
+
f"或在全局 ~/.braid/settings.json 里声明 api_key"
|
|
2534
|
+
)
|
|
2535
|
+
provider_models = tuple(
|
|
2536
|
+
_build_model(provider_id, model_draft, draft.api)
|
|
2537
|
+
for (owner, _), model_draft in models.items()
|
|
2538
|
+
if owner == provider_id
|
|
2539
|
+
)
|
|
2540
|
+
if not provider_models:
|
|
2541
|
+
raise ConfigError(f'{where}: 至少要声明一个模型(models["{provider_id}/<模型 id>"])')
|
|
2542
|
+
if draft.discover and draft.api == MODEL_API_ANTHROPIC:
|
|
2543
|
+
raise ConfigError(
|
|
2544
|
+
f"{where}.discover: 模型发现只接 OpenAI 的两种协议;"
|
|
2545
|
+
f'anthropic-messages 的模型请写在 models["{provider_id}/<模型 id>"] 里'
|
|
2546
|
+
)
|
|
2547
|
+
entries.append(
|
|
2548
|
+
ProviderEntry(
|
|
2549
|
+
id=provider_id,
|
|
2550
|
+
base_url=draft.base_url,
|
|
2551
|
+
env_key=draft.env_key,
|
|
2552
|
+
max_tokens_field=draft.max_tokens_field,
|
|
2553
|
+
models=provider_models,
|
|
2554
|
+
api_key=draft.api_key,
|
|
2555
|
+
api_key_source=draft.api_key_source,
|
|
2556
|
+
api=draft.api,
|
|
2557
|
+
cache_breakpoints=draft.cache_breakpoints,
|
|
2558
|
+
discover=draft.discover,
|
|
2559
|
+
discover_context_window=draft.discover_context_window,
|
|
2560
|
+
discover_max_tokens=draft.discover_max_tokens,
|
|
2561
|
+
)
|
|
2562
|
+
)
|
|
2563
|
+
|
|
2564
|
+
config = AgentConfig(
|
|
2565
|
+
providers=tuple(entries),
|
|
2566
|
+
default_model=defaults.model,
|
|
2567
|
+
default_thinking=defaults.thinking,
|
|
2568
|
+
default_model_source=defaults.model_source,
|
|
2569
|
+
default_thinking_source=defaults.thinking_source,
|
|
2570
|
+
retry=retry,
|
|
2571
|
+
compaction=compaction,
|
|
2572
|
+
statusline=statusline,
|
|
2573
|
+
sources=sources,
|
|
2574
|
+
env_overrides=env_overrides,
|
|
2575
|
+
instructions=instructions,
|
|
2576
|
+
permission=permission,
|
|
2577
|
+
sandbox=sandbox,
|
|
2578
|
+
checkpoint=checkpoint,
|
|
2579
|
+
subagents=subagents,
|
|
2580
|
+
web=web,
|
|
2581
|
+
lsp=_build_lsp(lsp),
|
|
2582
|
+
verify=VerifySettings(
|
|
2583
|
+
enabled=verify.enabled,
|
|
2584
|
+
timeout_seconds=verify.timeout_seconds,
|
|
2585
|
+
fail_fast=verify.fail_fast,
|
|
2586
|
+
max_consecutive_failures=verify.max_consecutive_failures,
|
|
2587
|
+
commands=verify.commands,
|
|
2588
|
+
),
|
|
2589
|
+
format=FormatSettings(
|
|
2590
|
+
enabled=formatting.enabled,
|
|
2591
|
+
timeout_seconds=formatting.timeout_seconds,
|
|
2592
|
+
commands=dict(formatting.commands),
|
|
2593
|
+
),
|
|
2594
|
+
observability=observability,
|
|
2595
|
+
mcp=mcp,
|
|
2596
|
+
config_version=CURRENT_CONFIG_VERSION,
|
|
2597
|
+
)
|
|
2598
|
+
_check_default_model(config)
|
|
2599
|
+
return config
|
|
2600
|
+
|
|
2601
|
+
|
|
2602
|
+
def _build_lsp(lsp: Mapping[str, _LspDraft]) -> LspSettings:
|
|
2603
|
+
"""把草稿折成设置。启用的服务器必须能启动,否则启动阶段就失败。"""
|
|
2604
|
+
servers: list[LspServerSettings] = []
|
|
2605
|
+
for draft in lsp.values():
|
|
2606
|
+
where = f"{draft.source}: lsp.{draft.name}"
|
|
2607
|
+
enabled = True if draft.enabled is None else draft.enabled
|
|
2608
|
+
if enabled:
|
|
2609
|
+
if draft.command is None:
|
|
2610
|
+
raise ConfigError(
|
|
2611
|
+
f'{where}.command: 必填(argv 数组,例如 ["pyright-langserver", "--stdio"])'
|
|
2612
|
+
)
|
|
2613
|
+
if not draft.extensions:
|
|
2614
|
+
raise ConfigError(f"{where}.extensions: 必填(这台服务器处理哪些扩展名)")
|
|
2615
|
+
if draft.language_id is None:
|
|
2616
|
+
raise ConfigError(f'{where}.language_id: 必填(例如 "python")')
|
|
2617
|
+
servers.append(
|
|
2618
|
+
LspServerSettings(
|
|
2619
|
+
name=draft.name,
|
|
2620
|
+
command=draft.command or (),
|
|
2621
|
+
extensions=draft.extensions or (),
|
|
2622
|
+
language_id=draft.language_id or "",
|
|
2623
|
+
root_markers=draft.root_markers or (),
|
|
2624
|
+
initialization_options=MappingProxyType(dict(draft.initialization_options or {})),
|
|
2625
|
+
env=MappingProxyType(dict(draft.env or {})),
|
|
2626
|
+
timeout_seconds=(
|
|
2627
|
+
DEFAULT_LSP_TIMEOUT_SECONDS
|
|
2628
|
+
if draft.timeout_seconds is None
|
|
2629
|
+
else draft.timeout_seconds
|
|
2630
|
+
),
|
|
2631
|
+
enabled=enabled,
|
|
2632
|
+
)
|
|
2633
|
+
)
|
|
2634
|
+
return LspSettings(servers=tuple(servers))
|
|
2635
|
+
|
|
2636
|
+
|
|
2637
|
+
def _build_model(provider_id: str, draft: _ModelDraft, api: ModelApi = MODEL_API) -> Model:
|
|
2638
|
+
where = f'{draft.source}: models."{provider_id}/{draft.id}"'
|
|
2639
|
+
if draft.context_window is None:
|
|
2640
|
+
raise ConfigError(f"{where}.context_window: 必填(这个模型能读多少 token)")
|
|
2641
|
+
if draft.max_tokens is None:
|
|
2642
|
+
raise ConfigError(f"{where}.max_tokens: 必填(这个模型一次最多写多少 token)")
|
|
2643
|
+
reasoning = draft.reasoning if draft.reasoning is not None else False
|
|
2644
|
+
levels: tuple[ModelThinkingLevel, ...] = (
|
|
2645
|
+
tuple(draft.thinking_levels) if draft.thinking_levels is not None else ()
|
|
2646
|
+
)
|
|
2647
|
+
if levels and not reasoning:
|
|
2648
|
+
raise ConfigError(f"{where}.thinking_levels: reasoning=false 的模型没有思考档位")
|
|
2649
|
+
return Model(
|
|
2650
|
+
id=draft.id,
|
|
2651
|
+
name=draft.name if draft.name is not None else draft.id,
|
|
2652
|
+
api=api,
|
|
2653
|
+
provider=provider_id,
|
|
2654
|
+
base_url="",
|
|
2655
|
+
reasoning=reasoning,
|
|
2656
|
+
input=list(draft.input) if draft.input is not None else ["text"],
|
|
2657
|
+
cost=ModelCost(
|
|
2658
|
+
input=draft.cost.get("input", 0.0),
|
|
2659
|
+
output=draft.cost.get("output", 0.0),
|
|
2660
|
+
cache_read=draft.cost.get("cache_read", 0.0),
|
|
2661
|
+
cache_write=draft.cost.get("cache_write", 0.0),
|
|
2662
|
+
),
|
|
2663
|
+
context_window=draft.context_window,
|
|
2664
|
+
max_tokens=draft.max_tokens,
|
|
2665
|
+
thinking_levels=levels,
|
|
2666
|
+
)
|
|
2667
|
+
|
|
2668
|
+
|
|
2669
|
+
def _check_default_model(config: AgentConfig) -> None:
|
|
2670
|
+
"""默认模型必须真的在目录里。写错一个字母不该等到第一次提问才发现。"""
|
|
2671
|
+
if config.default_model is None:
|
|
2672
|
+
return
|
|
2673
|
+
provider_id, _, model_id = config.default_model.partition("/")
|
|
2674
|
+
if not model_id:
|
|
2675
|
+
raise ConfigError(
|
|
2676
|
+
f"default_model 要写成 provider/id,收到 {config.default_model!r}"
|
|
2677
|
+
f"(可用: {', '.join(config.model_specs())})"
|
|
2678
|
+
)
|
|
2679
|
+
if config.find(provider_id, model_id) is None:
|
|
2680
|
+
raise ConfigError(
|
|
2681
|
+
f"default_model 里的 {config.default_model} 不在模型目录里"
|
|
2682
|
+
f"(可用: {', '.join(config.model_specs())})"
|
|
2683
|
+
)
|
|
2684
|
+
|
|
2685
|
+
|
|
2686
|
+
def is_local_endpoint(base_url: str) -> bool:
|
|
2687
|
+
"""``base_url`` 是否指向本机。静态密钥的准入判据。"""
|
|
2688
|
+
host = urlsplit(base_url).hostname
|
|
2689
|
+
return host is not None and host in LOCAL_ENDPOINT_HOSTS
|
|
2690
|
+
|
|
2691
|
+
|
|
2692
|
+
# ------------------------------------------------------------------- 运行时
|
|
2693
|
+
|
|
2694
|
+
|
|
2695
|
+
def create_models(config: AgentConfig, *, clock: Clock, auth: AuthResolver | None = None) -> Models:
|
|
2696
|
+
"""把目录变成运行时注册表:按 ``ProviderEntry.api`` 分派适配器。
|
|
2697
|
+
|
|
2698
|
+
``openai-completions`` 打 ``/chat/completions``,``openai-responses`` 打 ``/responses``,
|
|
2699
|
+
``anthropic-messages`` 打 ``/v1/messages``;三者对外吐同一套事件,所以上层装配不需要
|
|
2700
|
+
知道端点说的是哪一种协议。``faux`` 不在这里:它由 CLI 按 ``--script`` 注册,属于测试
|
|
2701
|
+
入口。``auth`` 缺省只读环境变量;产品装配传入
|
|
2702
|
+
:class:`~braid_coding_agent.credentials.Credentials` 的解析链,钥匙串与配置里的静态值
|
|
2703
|
+
才会参与。
|
|
2704
|
+
"""
|
|
2705
|
+
from braid_ai import (
|
|
2706
|
+
AnthropicConfig,
|
|
2707
|
+
AnthropicProvider,
|
|
2708
|
+
OpenAICompatConfig,
|
|
2709
|
+
OpenAICompatProvider,
|
|
2710
|
+
OpenAIResponsesProvider,
|
|
2711
|
+
)
|
|
2712
|
+
|
|
2713
|
+
models = Models(auth=auth if auth is not None else EnvAuthResolver(), clock=clock)
|
|
2714
|
+
for entry in config.providers:
|
|
2715
|
+
provider: OpenAICompatProvider | OpenAIResponsesProvider | AnthropicProvider
|
|
2716
|
+
if entry.api == MODEL_API_ANTHROPIC:
|
|
2717
|
+
provider = AnthropicProvider(
|
|
2718
|
+
AnthropicConfig(base_url=entry.base_url, cache_breakpoints=entry.cache_breakpoints),
|
|
2719
|
+
provider_id=entry.id,
|
|
2720
|
+
env_keys=entry.credential_names or ("ANTHROPIC_API_KEY",),
|
|
2721
|
+
models=entry.models,
|
|
2722
|
+
clock=clock,
|
|
2723
|
+
)
|
|
2724
|
+
elif entry.api == MODEL_API_RESPONSES:
|
|
2725
|
+
provider = OpenAIResponsesProvider(
|
|
2726
|
+
OpenAICompatConfig(
|
|
2727
|
+
base_url=entry.base_url, max_tokens_field=entry.max_tokens_field
|
|
2728
|
+
),
|
|
2729
|
+
provider_id=entry.id,
|
|
2730
|
+
env_keys=entry.credential_names,
|
|
2731
|
+
models=entry.models,
|
|
2732
|
+
clock=clock,
|
|
2733
|
+
)
|
|
2734
|
+
else:
|
|
2735
|
+
provider = OpenAICompatProvider(
|
|
2736
|
+
OpenAICompatConfig(
|
|
2737
|
+
base_url=entry.base_url, max_tokens_field=entry.max_tokens_field
|
|
2738
|
+
),
|
|
2739
|
+
provider_id=entry.id,
|
|
2740
|
+
env_keys=entry.credential_names,
|
|
2741
|
+
models=entry.models,
|
|
2742
|
+
clock=clock,
|
|
2743
|
+
)
|
|
2744
|
+
models.set_provider(provider)
|
|
2745
|
+
return models
|
|
2746
|
+
|
|
2747
|
+
|
|
2748
|
+
__all__ = [
|
|
2749
|
+
"BUILTIN_SOURCE",
|
|
2750
|
+
"CONFIG_FILE_NAME",
|
|
2751
|
+
"DEFAULT_CACHE_BREAKPOINTS",
|
|
2752
|
+
"DEFAULT_RETRY_BASE_DELAY_MS",
|
|
2753
|
+
"DEFAULT_RETRY_ENABLED",
|
|
2754
|
+
"DEFAULT_RETRY_MAX_AGENT_DELAY_MS",
|
|
2755
|
+
"DEFAULT_RETRY_MAX_RETRIES",
|
|
2756
|
+
"ENV_VARS",
|
|
2757
|
+
"LOCAL_ENDPOINT_HOSTS",
|
|
2758
|
+
"MODEL_API",
|
|
2759
|
+
"MODEL_API_ANTHROPIC",
|
|
2760
|
+
"MODEL_API_RESPONSES",
|
|
2761
|
+
"PROJECT_CONFIG_DIR",
|
|
2762
|
+
"SETTINGS_FILE_NAME",
|
|
2763
|
+
"AgentConfig",
|
|
2764
|
+
"ConfigError",
|
|
2765
|
+
"MaxTokensField",
|
|
2766
|
+
"ProviderEntry",
|
|
2767
|
+
"RetrySettings",
|
|
2768
|
+
"create_models",
|
|
2769
|
+
"is_local_endpoint",
|
|
2770
|
+
"load_config",
|
|
2771
|
+
"merge_mcp_permissions",
|
|
2772
|
+
"replace_compaction",
|
|
2773
|
+
"replace_permission",
|
|
2774
|
+
"replace_retry",
|
|
2775
|
+
"replace_sandbox",
|
|
2776
|
+
]
|