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,415 @@
|
|
|
1
|
+
"""从供应商端点拉取模型清单并缓存。
|
|
2
|
+
|
|
3
|
+
协议形状沿用 OpenAI 兼容端点的 ``GET {base_url}/models``:
|
|
4
|
+
|
|
5
|
+
```json
|
|
6
|
+
{"data": [{"id": "deepseek-flash", "name": "DeepSeek-V4.1-Flash",
|
|
7
|
+
"context_window": 1048576, "max_output_tokens": 393216,
|
|
8
|
+
"input_modalities": ["text", "image"],
|
|
9
|
+
"effort": {"supported_levels": ["low", "high", "max"]}}]}
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
``id`` 是唯一必填字段。上下文长度、输出上限、输入模态、思考档位都是**可选**的:
|
|
13
|
+
DeepSeek 全都给,OpenAI 只给 id 与 ``created``。缺什么就按下面的顺序补:
|
|
14
|
+
|
|
15
|
+
1. 端点自己声明的值;
|
|
16
|
+
2. provider 配置里的 ``discover_context_window`` / ``discover_max_tokens``;
|
|
17
|
+
3. 都没有 → 这条模型跳过,摘要里写明原因。
|
|
18
|
+
|
|
19
|
+
第三档是刻意的:一个猜出来的上下文长度会让压缩阈值算错、输出预算算错,而"这条模型没被
|
|
20
|
+
采纳"只是少了一个选项。用一套固定默认值去补齐,在有图形界面引导时还成立,对着一条
|
|
21
|
+
``text-embedding-3-small`` 就是灾难。
|
|
22
|
+
|
|
23
|
+
## 缓存
|
|
24
|
+
|
|
25
|
+
拉到的清单写进 ``<agent dir>/models-cache.json``,下次启动直接读缓存,不联网。缓存是
|
|
26
|
+
派生数据:读不出来、版本不对、字段坏了都当作"没有缓存",下一次 ``--refresh-models``
|
|
27
|
+
会覆盖它。启动路径上不能因为一份缓存挂掉。
|
|
28
|
+
|
|
29
|
+
## 合并顺序
|
|
30
|
+
|
|
31
|
+
目录里写着的模型永远优先。同一个 ``provider/id`` 已经存在时,端点那份被丢掉——用户显式
|
|
32
|
+
写下的数值是他对端点的判断,不该被一次刷新改回去。新 id 追加在该 provider 名下的末尾,
|
|
33
|
+
并登记进 :attr:`~braid_coding_agent.config.AgentConfig.discovered`,``/models`` 据此标出
|
|
34
|
+
"这条是刷出来的"。
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import contextlib
|
|
40
|
+
import json
|
|
41
|
+
import time
|
|
42
|
+
from collections.abc import AsyncGenerator, Mapping, Sequence
|
|
43
|
+
from dataclasses import dataclass, replace
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
|
|
46
|
+
import httpx
|
|
47
|
+
|
|
48
|
+
from braid_ai import Model, ModelCost
|
|
49
|
+
from braid_ai.models import EXTENDED_THINKING_LEVELS
|
|
50
|
+
from braid_ai.types import JsonValue, ModelInput, ModelThinkingLevel
|
|
51
|
+
from braid_coding_agent.config import MODEL_API, AgentConfig, ProviderEntry
|
|
52
|
+
from braid_coding_agent.credentials import Credentials
|
|
53
|
+
|
|
54
|
+
#: 缓存文件(相对 agent dir)。
|
|
55
|
+
CACHE_FILE_NAME = "models-cache.json"
|
|
56
|
+
#: 缓存格式版本。读不懂的版本按"没有缓存"处理。
|
|
57
|
+
CACHE_VERSION = 1
|
|
58
|
+
#: ``GET /models`` 的超时。这是元数据请求,不需要流式那套宽超时。
|
|
59
|
+
REQUEST_TIMEOUT_SECONDS = 10.0
|
|
60
|
+
#: 错误响应体写进摘要前的截断长度。
|
|
61
|
+
_MAX_ERROR_BODY_CHARS = 200
|
|
62
|
+
|
|
63
|
+
_INPUT_MODALITY_BY_NAME: Mapping[str, ModelInput] = {"text": "text", "image": "image"}
|
|
64
|
+
_THINKING_LEVEL_BY_NAME: Mapping[str, ModelThinkingLevel] = {
|
|
65
|
+
level: level for level in EXTENDED_THINKING_LEVELS
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(slots=True, frozen=True)
|
|
70
|
+
class ProviderRefresh:
|
|
71
|
+
"""一家端点的刷新结果。"""
|
|
72
|
+
|
|
73
|
+
provider_id: str
|
|
74
|
+
#: 这次真正被采纳的模型(已经排除目录里已有的 id)。
|
|
75
|
+
added: tuple[Model, ...] = ()
|
|
76
|
+
#: 跳过或失败的说明,逐条一行,给人看。
|
|
77
|
+
notes: tuple[str, ...] = ()
|
|
78
|
+
error: str | None = None
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def ok(self) -> bool:
|
|
82
|
+
return self.error is None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(slots=True, frozen=True)
|
|
86
|
+
class RefreshReport:
|
|
87
|
+
"""一次 ``--refresh-models`` 的汇总。"""
|
|
88
|
+
|
|
89
|
+
providers: tuple[ProviderRefresh, ...]
|
|
90
|
+
cache_path: str
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def added_count(self) -> int:
|
|
94
|
+
return sum(len(item.added) for item in self.providers)
|
|
95
|
+
|
|
96
|
+
def lines(self) -> list[str]:
|
|
97
|
+
"""给 stderr 的几行摘要。顺序与 provider 顺序一致。"""
|
|
98
|
+
lines = [f"模型目录已刷新:新增 {self.added_count} 个模型(缓存 {self.cache_path})"]
|
|
99
|
+
for item in self.providers:
|
|
100
|
+
if item.error is not None:
|
|
101
|
+
lines.append(f" {item.provider_id}:失败 {item.error}")
|
|
102
|
+
continue
|
|
103
|
+
added = "、".join(model.id for model in item.added)
|
|
104
|
+
suffix = f"({added})" if added else ""
|
|
105
|
+
lines.append(f" {item.provider_id}:新增 {len(item.added)} 个{suffix}")
|
|
106
|
+
lines.extend(f" {note}" for note in item.notes)
|
|
107
|
+
return lines
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------- 缓存
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def merge_cached(config: AgentConfig, *, agent_dir: Path) -> AgentConfig:
|
|
114
|
+
"""把缓存里刷出来的模型并进目录。缓存不存在或读不懂时原样返回。"""
|
|
115
|
+
cached = _read_cache(agent_dir / CACHE_FILE_NAME)
|
|
116
|
+
if not cached:
|
|
117
|
+
return config
|
|
118
|
+
return _merge(config, cached)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _read_cache(path: Path) -> dict[str, tuple[Model, ...]]:
|
|
122
|
+
if not path.is_file():
|
|
123
|
+
return {}
|
|
124
|
+
try:
|
|
125
|
+
payload: JsonValue = json.loads(path.read_text(encoding="utf-8"))
|
|
126
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
127
|
+
return {}
|
|
128
|
+
if not isinstance(payload, dict) or payload.get("version") != CACHE_VERSION:
|
|
129
|
+
return {}
|
|
130
|
+
raw_providers = payload.get("providers")
|
|
131
|
+
if not isinstance(raw_providers, dict):
|
|
132
|
+
return {}
|
|
133
|
+
cached: dict[str, tuple[Model, ...]] = {}
|
|
134
|
+
for provider_id, raw in raw_providers.items():
|
|
135
|
+
models = _read_cached_models(provider_id, raw)
|
|
136
|
+
if models:
|
|
137
|
+
cached[provider_id] = tuple(models)
|
|
138
|
+
return cached
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _read_cached_models(provider_id: str, raw: JsonValue) -> list[Model]:
|
|
142
|
+
"""读一家 provider 的缓存条目。坏掉的单条跳过,不影响其余。"""
|
|
143
|
+
if not isinstance(raw, dict):
|
|
144
|
+
return []
|
|
145
|
+
raw_models = raw.get("models")
|
|
146
|
+
if not isinstance(raw_models, list):
|
|
147
|
+
return []
|
|
148
|
+
models: list[Model] = []
|
|
149
|
+
for item in raw_models:
|
|
150
|
+
model = _read_cached_model(provider_id, item)
|
|
151
|
+
if model is not None:
|
|
152
|
+
models.append(model)
|
|
153
|
+
return models
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _read_cached_model(provider_id: str, raw: JsonValue) -> Model | None:
|
|
157
|
+
if not isinstance(raw, dict):
|
|
158
|
+
return None
|
|
159
|
+
model_id = _text(raw.get("id"))
|
|
160
|
+
context_window = _int(raw.get("context_window"))
|
|
161
|
+
max_tokens = _int(raw.get("max_tokens"))
|
|
162
|
+
if model_id is None or context_window is None or max_tokens is None:
|
|
163
|
+
return None
|
|
164
|
+
levels = _levels(raw.get("thinking_levels"))
|
|
165
|
+
return Model(
|
|
166
|
+
id=model_id,
|
|
167
|
+
name=_text(raw.get("name")) or model_id,
|
|
168
|
+
api=MODEL_API,
|
|
169
|
+
provider=provider_id,
|
|
170
|
+
base_url="",
|
|
171
|
+
reasoning=raw.get("reasoning") is True,
|
|
172
|
+
input=_modalities(raw.get("input")) or ["text"],
|
|
173
|
+
cost=ModelCost(),
|
|
174
|
+
context_window=context_window,
|
|
175
|
+
max_tokens=max_tokens,
|
|
176
|
+
thinking_levels=levels,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _write_cache(path: Path, models: Mapping[str, Sequence[Model]], *, fetched_at: int) -> None:
|
|
181
|
+
providers: dict[str, JsonValue] = {}
|
|
182
|
+
for provider_id, entries in models.items():
|
|
183
|
+
providers[provider_id] = {
|
|
184
|
+
"models": [
|
|
185
|
+
{
|
|
186
|
+
"id": model.id,
|
|
187
|
+
"name": model.name,
|
|
188
|
+
"context_window": model.context_window,
|
|
189
|
+
"max_tokens": model.max_tokens,
|
|
190
|
+
"input": list(model.input),
|
|
191
|
+
"reasoning": model.reasoning,
|
|
192
|
+
"thinking_levels": list(model.thinking_levels),
|
|
193
|
+
}
|
|
194
|
+
for model in entries
|
|
195
|
+
]
|
|
196
|
+
}
|
|
197
|
+
payload: JsonValue = {
|
|
198
|
+
"version": CACHE_VERSION,
|
|
199
|
+
"fetched_at": fetched_at,
|
|
200
|
+
"providers": providers,
|
|
201
|
+
}
|
|
202
|
+
if not path.parent.is_dir():
|
|
203
|
+
path.parent.mkdir(parents=True)
|
|
204
|
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ----------------------------------------------------------------- 刷新
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
async def refresh_catalog(
|
|
211
|
+
config: AgentConfig,
|
|
212
|
+
*,
|
|
213
|
+
agent_dir: Path,
|
|
214
|
+
credentials: Credentials,
|
|
215
|
+
client: httpx.AsyncClient | None = None,
|
|
216
|
+
) -> tuple[AgentConfig, RefreshReport]:
|
|
217
|
+
"""拉取每个 ``discover`` 端点的模型清单,写缓存并返回合并后的目录。
|
|
218
|
+
|
|
219
|
+
只处理 ``discover = true`` 的 provider;凭证走 :class:`Credentials` 的同一条链
|
|
220
|
+
(环境变量 → 系统钥匙串 → 配置静态值),取不到就跳过并写明原因。端点错误不影响
|
|
221
|
+
其余 provider,也不中断进程——这是元数据,不是用户正在等的回答。
|
|
222
|
+
"""
|
|
223
|
+
cache_path = agent_dir / CACHE_FILE_NAME
|
|
224
|
+
cached = _read_cache(cache_path)
|
|
225
|
+
fetched_at = int(time.time())
|
|
226
|
+
results: list[ProviderRefresh] = []
|
|
227
|
+
updates: dict[str, tuple[Model, ...]] = dict(cached)
|
|
228
|
+
|
|
229
|
+
async with _client_scope(client) as http:
|
|
230
|
+
for entry in config.providers:
|
|
231
|
+
if not entry.discover:
|
|
232
|
+
continue
|
|
233
|
+
result, models = await _refresh_provider(http, entry, credentials=credentials)
|
|
234
|
+
results.append(result)
|
|
235
|
+
if models is not None:
|
|
236
|
+
updates[entry.id] = tuple(models)
|
|
237
|
+
|
|
238
|
+
_write_cache(cache_path, updates, fetched_at=fetched_at)
|
|
239
|
+
merged = _merge(config, updates)
|
|
240
|
+
return merged, RefreshReport(providers=tuple(results), cache_path=str(cache_path))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@contextlib.asynccontextmanager
|
|
244
|
+
async def _client_scope(client: httpx.AsyncClient | None) -> AsyncGenerator[httpx.AsyncClient]:
|
|
245
|
+
"""注入了客户端就用调用方的,没注入才自己建一个。"""
|
|
246
|
+
if client is not None:
|
|
247
|
+
yield client
|
|
248
|
+
return
|
|
249
|
+
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS) as owned:
|
|
250
|
+
yield owned
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
async def _refresh_provider(
|
|
254
|
+
client: httpx.AsyncClient, entry: ProviderEntry, *, credentials: Credentials
|
|
255
|
+
) -> tuple[ProviderRefresh, list[Model] | None]:
|
|
256
|
+
"""拉一家端点。返回 ``(结果, 端点给的模型清单或 None)``。
|
|
257
|
+
|
|
258
|
+
``None`` 表示"这次没拿到可用清单",缓存里原有的条目保持不动。
|
|
259
|
+
"""
|
|
260
|
+
status = credentials.status(entry.id)
|
|
261
|
+
if not status.available:
|
|
262
|
+
return ProviderRefresh(entry.id, notes=(f"跳过:{status.detail}",)), None
|
|
263
|
+
api_key = credentials.secret(entry.id)
|
|
264
|
+
|
|
265
|
+
url = f"{entry.base_url.rstrip('/')}/models"
|
|
266
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
267
|
+
try:
|
|
268
|
+
response = await client.get(url, headers=headers)
|
|
269
|
+
except httpx.HTTPError as exc:
|
|
270
|
+
return ProviderRefresh(entry.id, error=f"{type(exc).__name__}: {exc}"), None
|
|
271
|
+
if response.status_code >= 400:
|
|
272
|
+
body = " ".join(response.text.split())[:_MAX_ERROR_BODY_CHARS]
|
|
273
|
+
return ProviderRefresh(entry.id, error=f"HTTP {response.status_code}:{body}"), None
|
|
274
|
+
try:
|
|
275
|
+
payload: JsonValue = response.json()
|
|
276
|
+
except ValueError as exc:
|
|
277
|
+
return ProviderRefresh(entry.id, error=f"响应不是 JSON:{exc}"), None
|
|
278
|
+
|
|
279
|
+
models, notes = parse_models_payload(payload, entry=entry)
|
|
280
|
+
added = tuple(model for model in models if entry.find(model.id) is None)
|
|
281
|
+
return ProviderRefresh(entry.id, added=added, notes=tuple(notes)), models
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def parse_models_payload(
|
|
285
|
+
payload: JsonValue, *, entry: ProviderEntry
|
|
286
|
+
) -> tuple[list[Model], list[str]]:
|
|
287
|
+
"""把 ``GET /models`` 的响应解析成模型条目与跳过说明。
|
|
288
|
+
|
|
289
|
+
:param entry: 用来补齐端点没给的上下文长度与输出上限,也用来填 ``provider``。
|
|
290
|
+
"""
|
|
291
|
+
if not isinstance(payload, dict):
|
|
292
|
+
raise ValueError("响应必须是对象")
|
|
293
|
+
raw_models = payload.get("data")
|
|
294
|
+
if not isinstance(raw_models, list):
|
|
295
|
+
raise ValueError("响应里没有 data 数组")
|
|
296
|
+
|
|
297
|
+
models: list[Model] = []
|
|
298
|
+
notes: list[str] = []
|
|
299
|
+
for index, raw in enumerate(raw_models):
|
|
300
|
+
if not isinstance(raw, dict):
|
|
301
|
+
notes.append(f"跳过第 {index} 条:不是对象")
|
|
302
|
+
continue
|
|
303
|
+
model_id = _text(raw.get("id"))
|
|
304
|
+
if model_id is None:
|
|
305
|
+
notes.append(f"跳过第 {index} 条:没有 id")
|
|
306
|
+
continue
|
|
307
|
+
context_window = _int(raw.get("context_window")) or entry.discover_context_window
|
|
308
|
+
max_tokens = (
|
|
309
|
+
_int(raw.get("max_output_tokens"))
|
|
310
|
+
or _int(raw.get("max_tokens"))
|
|
311
|
+
or entry.discover_max_tokens
|
|
312
|
+
)
|
|
313
|
+
if context_window is None or max_tokens is None:
|
|
314
|
+
notes.append(f"跳过 {model_id}:端点没有声明上下文长度或输出上限")
|
|
315
|
+
continue
|
|
316
|
+
models.append(_build_model(entry, raw, model_id, context_window, max_tokens))
|
|
317
|
+
return models, notes
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _build_model(
|
|
321
|
+
entry: ProviderEntry,
|
|
322
|
+
raw: Mapping[str, JsonValue],
|
|
323
|
+
model_id: str,
|
|
324
|
+
context_window: int,
|
|
325
|
+
max_tokens: int,
|
|
326
|
+
) -> Model:
|
|
327
|
+
levels = _levels_from_effort(raw.get("effort"))
|
|
328
|
+
return Model(
|
|
329
|
+
id=model_id,
|
|
330
|
+
name=_text(raw.get("name")) or model_id,
|
|
331
|
+
api=MODEL_API,
|
|
332
|
+
provider=entry.id,
|
|
333
|
+
base_url="",
|
|
334
|
+
# 端点声明了档位就说明它会思考;没有声明时按"不思考"处理,宁可少发一个参数。
|
|
335
|
+
reasoning=bool(levels),
|
|
336
|
+
input=_modalities(raw.get("input_modalities")) or ["text"],
|
|
337
|
+
cost=ModelCost(),
|
|
338
|
+
context_window=context_window,
|
|
339
|
+
max_tokens=max_tokens,
|
|
340
|
+
thinking_levels=levels,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _merge(config: AgentConfig, cached: Mapping[str, Sequence[Model]]) -> AgentConfig:
|
|
345
|
+
"""目录优先,缓存里多出来的 id 追加到对应 provider 末尾。"""
|
|
346
|
+
discovered: set[str] = set(config.discovered)
|
|
347
|
+
providers: list[ProviderEntry] = []
|
|
348
|
+
for entry in config.providers:
|
|
349
|
+
extra = tuple(model for model in cached.get(entry.id, ()) if entry.find(model.id) is None)
|
|
350
|
+
if not extra:
|
|
351
|
+
providers.append(entry)
|
|
352
|
+
continue
|
|
353
|
+
providers.append(replace(entry, models=entry.models + extra))
|
|
354
|
+
discovered.update(f"{entry.id}/{model.id}" for model in extra)
|
|
355
|
+
return replace(config, providers=tuple(providers), discovered=frozenset(discovered))
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# ------------------------------------------------------------------ 取值
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _text(value: JsonValue) -> str | None:
|
|
362
|
+
return value if isinstance(value, str) and value else None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _int(value: JsonValue) -> int | None:
|
|
366
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
367
|
+
return None
|
|
368
|
+
return value if value > 0 else None
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _modalities(value: JsonValue) -> list[ModelInput]:
|
|
372
|
+
if not isinstance(value, list):
|
|
373
|
+
return []
|
|
374
|
+
modalities: list[ModelInput] = []
|
|
375
|
+
for item in value:
|
|
376
|
+
modality = _INPUT_MODALITY_BY_NAME.get(item) if isinstance(item, str) else None
|
|
377
|
+
if modality is not None and modality not in modalities:
|
|
378
|
+
modalities.append(modality)
|
|
379
|
+
return modalities
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _levels(value: JsonValue) -> tuple[ModelThinkingLevel, ...]:
|
|
383
|
+
if not isinstance(value, list):
|
|
384
|
+
return ()
|
|
385
|
+
levels: list[ModelThinkingLevel] = []
|
|
386
|
+
for item in value:
|
|
387
|
+
level = _THINKING_LEVEL_BY_NAME.get(item) if isinstance(item, str) else None
|
|
388
|
+
if level is not None and level not in levels:
|
|
389
|
+
levels.append(level)
|
|
390
|
+
return tuple(levels)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _levels_from_effort(value: JsonValue) -> tuple[ModelThinkingLevel, ...]:
|
|
394
|
+
"""``effort.supported_levels`` → 本仓库的档位。
|
|
395
|
+
|
|
396
|
+
``off`` 一定要在里面:它表示"请求里不带思考参数",对任何端点都成立。
|
|
397
|
+
"""
|
|
398
|
+
if not isinstance(value, dict):
|
|
399
|
+
return ()
|
|
400
|
+
supported = _levels(value.get("supported_levels"))
|
|
401
|
+
if not supported:
|
|
402
|
+
return ()
|
|
403
|
+
return ("off", *supported)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
__all__ = [
|
|
407
|
+
"CACHE_FILE_NAME",
|
|
408
|
+
"CACHE_VERSION",
|
|
409
|
+
"REQUEST_TIMEOUT_SECONDS",
|
|
410
|
+
"ProviderRefresh",
|
|
411
|
+
"RefreshReport",
|
|
412
|
+
"merge_cached",
|
|
413
|
+
"parse_models_payload",
|
|
414
|
+
"refresh_catalog",
|
|
415
|
+
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""扩展机制:注册点、钩子与错误隔离。
|
|
2
|
+
|
|
3
|
+
三个子模块,边界只有一条:
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
api.py —— 扩展作者看到的东西:ExtensionAPI、事件与结果类型、错误类型
|
|
7
|
+
runner.py —— 装载、卸载、按顺序分发、把异常收成 extension_error
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
会话层(:class:`braid_coding_agent.session.AgentSession`)是唯一把两者接到内核上的地方:
|
|
11
|
+
它把 ``before_tool_call`` / ``after_tool_call`` / ``context`` 三个钩子挂到
|
|
12
|
+
:class:`braid_agent.Agent` 上,把 ``before_agent_start`` 接到提示词分节,把
|
|
13
|
+
``session_before_compact`` 接到压缩流程。扩展因此不需要知道内核长什么样。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from braid_agent.types import AfterToolCallResult, BeforeToolCallResult
|
|
19
|
+
from braid_coding_agent.extensions.api import (
|
|
20
|
+
AppendEntryAction,
|
|
21
|
+
BeforeAgentStartEvent,
|
|
22
|
+
BeforeAgentStartPatch,
|
|
23
|
+
BeforeAgentStartResult,
|
|
24
|
+
CommandHandler,
|
|
25
|
+
ContextEvent,
|
|
26
|
+
ContextResult,
|
|
27
|
+
Extension,
|
|
28
|
+
ExtensionAPI,
|
|
29
|
+
ExtensionError,
|
|
30
|
+
ExtensionErrorListener,
|
|
31
|
+
ExtensionEventName,
|
|
32
|
+
ExtensionHandler,
|
|
33
|
+
ExtensionRuntime,
|
|
34
|
+
InlineExtension,
|
|
35
|
+
RegisteredCommand,
|
|
36
|
+
SessionBeforeCompactEvent,
|
|
37
|
+
SessionBeforeCompactResult,
|
|
38
|
+
SessionShutdownEvent,
|
|
39
|
+
ToolCallEvent,
|
|
40
|
+
ToolResultEvent,
|
|
41
|
+
)
|
|
42
|
+
from braid_coding_agent.extensions.runner import (
|
|
43
|
+
ExtensionLoadError,
|
|
44
|
+
ExtensionRunner,
|
|
45
|
+
LoadedExtension,
|
|
46
|
+
render_prompt_sections,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"AfterToolCallResult",
|
|
51
|
+
"AppendEntryAction",
|
|
52
|
+
"BeforeAgentStartEvent",
|
|
53
|
+
"BeforeAgentStartPatch",
|
|
54
|
+
"BeforeAgentStartResult",
|
|
55
|
+
"BeforeToolCallResult",
|
|
56
|
+
"CommandHandler",
|
|
57
|
+
"ContextEvent",
|
|
58
|
+
"ContextResult",
|
|
59
|
+
"Extension",
|
|
60
|
+
"ExtensionAPI",
|
|
61
|
+
"ExtensionError",
|
|
62
|
+
"ExtensionErrorListener",
|
|
63
|
+
"ExtensionEventName",
|
|
64
|
+
"ExtensionHandler",
|
|
65
|
+
"ExtensionLoadError",
|
|
66
|
+
"ExtensionRunner",
|
|
67
|
+
"ExtensionRuntime",
|
|
68
|
+
"InlineExtension",
|
|
69
|
+
"LoadedExtension",
|
|
70
|
+
"RegisteredCommand",
|
|
71
|
+
"SessionBeforeCompactEvent",
|
|
72
|
+
"SessionBeforeCompactResult",
|
|
73
|
+
"SessionShutdownEvent",
|
|
74
|
+
"ToolCallEvent",
|
|
75
|
+
"ToolResultEvent",
|
|
76
|
+
"render_prompt_sections",
|
|
77
|
+
]
|