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.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,191 @@
1
+ """``settings.json`` 的路径、版本检查、模板与旧目录搬迁。
2
+
3
+ 全局配置位于 ``~/.braid/settings.json``,项目配置位于 ``<cwd>/.braid/settings.json``。
4
+ 两份文件使用同一套 JSON 结构,项目文件覆盖全局文件里的同名字段。``config_version``
5
+ 记录文件格式版本,当前只接受版本 1;缺失时按当前版本处理。
6
+
7
+ 早期版本的全局目录是 ``~/.braid/agent/``,后来去掉这一层。``plan_legacy_moves``
8
+ 把旧目录里的条目逐个搬到 ``~/.braid/``,目标已存在的条目记为冲突:两份不同的
9
+ ``settings.json`` 都可能包含用户手写的内容,覆盖任何一份都会丢东西。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import shutil
16
+ from collections.abc import Iterable, Mapping
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import cast
20
+
21
+ from braid_ai.types import JsonValue
22
+
23
+ #: 全局配置文件(相对全局目录)与项目配置目录(相对工作目录)。
24
+ CONFIG_FILE_NAME = "settings.json"
25
+ PROJECT_CONFIG_DIR = ".braid"
26
+
27
+ #: 当前程序能读写的配置版本。
28
+ CURRENT_CONFIG_VERSION = 1
29
+
30
+ #: 旧版全局目录里多出来的那一层,迁移时把它下面的条目搬上来。
31
+ LEGACY_AGENT_SUBDIR = "agent"
32
+
33
+
34
+ class ConfigFileError(ValueError):
35
+ """配置文件版本不可读。消息带文件路径。"""
36
+
37
+
38
+ @dataclass(slots=True, frozen=True)
39
+ class LegacyMove:
40
+ """一条"旧位置 → 新位置"的搬迁。"""
41
+
42
+ source: Path
43
+ target: Path
44
+
45
+
46
+ def _read_json(path: Path) -> JsonValue:
47
+ try:
48
+ text = path.read_bytes().decode("utf-8-sig")
49
+ except OSError as exc:
50
+ raise ConfigFileError(f"{path}: 无法读取配置文件:{exc}") from exc
51
+ except UnicodeDecodeError as exc:
52
+ raise ConfigFileError(f"{path}: 配置文件不是 UTF-8:{exc}") from exc
53
+ try:
54
+ return cast("JsonValue", json.loads(text))
55
+ except ValueError as exc:
56
+ raise ConfigFileError(f"{path}: 不是合法的 JSON:{exc}") from exc
57
+
58
+
59
+ def document_version(document: Mapping[str, object], *, where: str) -> int:
60
+ """读一份已解析配置的版本号。缺失时返回当前版本。"""
61
+ value = document.get("config_version")
62
+ if value is None:
63
+ return CURRENT_CONFIG_VERSION
64
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
65
+ raise ConfigFileError(f"{where}: config_version 必须是正整数,收到 {value!r}")
66
+ if value > CURRENT_CONFIG_VERSION:
67
+ raise ConfigFileError(
68
+ f"{where}: 配置版本 {value} 高于本程序支持的 {CURRENT_CONFIG_VERSION}"
69
+ "(它由更新的 braid 写入);先升级 braid 再读这份配置"
70
+ )
71
+ return value
72
+
73
+
74
+ def file_version(path: Path) -> int | None:
75
+ """磁盘上一份配置的版本号;文件不存在返回 ``None``。"""
76
+ if not path.is_file():
77
+ return None
78
+ parsed = _read_json(path)
79
+ if not isinstance(parsed, dict):
80
+ raise ConfigFileError(f"{path}: 顶层必须是 JSON 对象")
81
+ return document_version(parsed, where=str(path))
82
+
83
+
84
+ # ------------------------------------------------------------------ 旧目录
85
+
86
+
87
+ def plan_legacy_moves(agent_dir: Path) -> tuple[tuple[LegacyMove, ...], tuple[str, ...]]:
88
+ """列出 ``~/.braid/agent/`` 的搬迁计划与冲突。
89
+
90
+ 返回 ``(可搬迁的条目, 冲突说明)``。冲突指目标位置已经有同名条目;调用方应当
91
+ 在有任何冲突时整体停下,不做部分搬迁。
92
+ """
93
+ legacy = agent_dir / LEGACY_AGENT_SUBDIR
94
+ if not legacy.is_dir():
95
+ return (), ()
96
+ moves: list[LegacyMove] = []
97
+ conflicts: list[str] = []
98
+ for entry in sorted(legacy.iterdir()):
99
+ target = agent_dir / entry.name
100
+ if target.exists():
101
+ conflicts.append(f"{target} 已存在(旧位置 {entry})")
102
+ else:
103
+ moves.append(LegacyMove(source=entry, target=target))
104
+ return tuple(moves), tuple(conflicts)
105
+
106
+
107
+ def apply_legacy_moves(moves: Iterable[LegacyMove]) -> tuple[Path, ...]:
108
+ """执行搬迁,返回实际搬动的目标路径。
109
+
110
+ 搬完不删旧目录:迁移只做"把东西放到新位置",删目录留给用户。空目录不占空间,
111
+ 自动删掉一个用户可能还想留着查看的目录,属于不可逆的动作。
112
+ """
113
+ moved: list[Path] = []
114
+ for move in moves:
115
+ shutil.move(str(move.source), str(move.target))
116
+ moved.append(move.target)
117
+ return tuple(moved)
118
+
119
+
120
+ def legacy_dir_has_entries(agent_dir: Path) -> bool:
121
+ """旧布局目录是否还有没搬走的条目。空目录不算。"""
122
+ legacy = agent_dir / LEGACY_AGENT_SUBDIR
123
+ return legacy.is_dir() and any(legacy.iterdir())
124
+
125
+
126
+ # ------------------------------------------------------------------ 模板
127
+
128
+ #: ``braid setup`` 与 ``braid config init`` 写出的内容。
129
+ CONFIG_TEMPLATE = """\
130
+ {
131
+ "config_version": 1,
132
+ "default_thinking": "off",
133
+ "retry": {
134
+ "enabled": true,
135
+ "max_retries": 3,
136
+ "base_delay_ms": 2000,
137
+ "max_agent_delay_ms": 60000
138
+ },
139
+ "compaction": {
140
+ "enabled": true,
141
+ "reserve_tokens": 16384,
142
+ "keep_recent_tokens": 20000
143
+ },
144
+ "statusline": {
145
+ "fields": [
146
+ "model",
147
+ "context-used",
148
+ "cost",
149
+ "tools",
150
+ "permission",
151
+ "plan",
152
+ "background"
153
+ ]
154
+ },
155
+ "permission": {
156
+ "mode": "full"
157
+ },
158
+ "sandbox": {
159
+ "mode": "off"
160
+ },
161
+ "mcp": {
162
+ "loading": "lazy",
163
+ "tool_token_budget": 4000,
164
+ "connect_timeout_s": 15,
165
+ "call_timeout_s": 60,
166
+ "cache": true
167
+ }
168
+ }
169
+ """
170
+
171
+
172
+ def template_text() -> str:
173
+ """默认配置模板。写出的文件必须能被 :func:`braid_coding_agent.config.load_config` 读懂。"""
174
+ return CONFIG_TEMPLATE
175
+
176
+
177
+ __all__ = [
178
+ "CONFIG_FILE_NAME",
179
+ "CONFIG_TEMPLATE",
180
+ "CURRENT_CONFIG_VERSION",
181
+ "LEGACY_AGENT_SUBDIR",
182
+ "PROJECT_CONFIG_DIR",
183
+ "ConfigFileError",
184
+ "LegacyMove",
185
+ "apply_legacy_moves",
186
+ "document_version",
187
+ "file_version",
188
+ "legacy_dir_has_entries",
189
+ "plan_legacy_moves",
190
+ "template_text",
191
+ ]
@@ -0,0 +1,252 @@
1
+ """凭证解析:环境变量 → 系统钥匙串 → 配置里的静态值。
2
+
3
+ ``Models`` 在每次请求前调用 :meth:`Credentials.resolver` 给出的解析器,所以这里
4
+ 不缓存密钥:用户在另一个终端跑完 ``braid auth login``,当前会话的下一次请求就能
5
+ 用上新 Key。
6
+
7
+ 优先级与理由:
8
+
9
+ ```text
10
+ StreamOptions(api_key=...) 显式参数,编程调用方的一次性覆盖(Models 层处理)
11
+ > 环境变量 部署形态的事实标准;CI 与容器只认这个
12
+ > 系统钥匙串 braid auth login 写入;三个桌面平台各有后端
13
+ > 配置里的 api_key 全局 settings.json 可给远端端点;项目文件只给本机端点
14
+ ```
15
+
16
+ **为什么不提供 ``--api-key`` 命令行参数**:它会出现在 ``ps`` 的输出与 shell 历史里。
17
+ 需要一次性覆盖的编程调用方有 ``StreamOptions(api_key=...)``,交互式用户有
18
+ ``braid auth login``,命令行参数这一层没有存在的理由。
19
+
20
+ **钥匙串读不出来时不终止进程**:主机没解锁、容器里没有 Secret Service,都会让
21
+ ``keyring`` 抛错。凭证缺失的表现是"这个 provider 不可用",``/models`` 与
22
+ ``braid auth status`` 会把原因写在旁边;只有 ``braid auth login`` 才把它当失败,
23
+ 因为那是用户明确要求写钥匙串的动作。
24
+
25
+ ## 服务名与账户名
26
+
27
+ 服务名固定 ``braid``,账户名是 provider id(``deepseek``、``openai``…)。
28
+ ``keyring`` 在三个平台上都按 ``(service, username)`` 定位一条记录,所以
29
+ ``braid auth logout deepseek`` 删掉的正是 ``braid auth login deepseek`` 写进去的那条。
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import os
35
+ from collections.abc import Mapping
36
+ from dataclasses import dataclass
37
+ from pathlib import Path
38
+ from typing import Literal, Protocol, runtime_checkable
39
+
40
+ import keyring
41
+ from keyring.backends.fail import Keyring as FailKeyring
42
+ from keyring.errors import KeyringError, PasswordDeleteError
43
+
44
+ from braid_ai.auth import AuthResolver, HasEnvKeys
45
+ from braid_coding_agent.config import AgentConfig, ProviderEntry
46
+
47
+ #: 钥匙串里的服务名。所有 provider 共用,账户名区分它们。
48
+ SERVICE_NAME = "braid"
49
+
50
+ #: 凭证的来源标签。``None`` 表示解析不到。
51
+ type CredentialSource = Literal["env", "keychain", "config", "keyless"]
52
+
53
+
54
+ class KeychainError(RuntimeError):
55
+ """系统钥匙串不可用或读写失败。消息里带后端给的原文。"""
56
+
57
+
58
+ @runtime_checkable
59
+ class Keychain(Protocol):
60
+ """系统钥匙串的最小接口。测试注入内存实现,产品用 :class:`SystemKeychain`。"""
61
+
62
+ @property
63
+ def name(self) -> str: ...
64
+
65
+ @property
66
+ def available(self) -> bool: ...
67
+
68
+ def get(self, provider_id: str) -> str | None: ...
69
+
70
+ def set(self, provider_id: str, secret: str) -> None: ...
71
+
72
+ def delete(self, provider_id: str) -> bool: ...
73
+
74
+
75
+ class SystemKeychain:
76
+ """``keyring`` 包装:macOS Keychain、Windows 凭据管理器、Linux Secret Service。
77
+
78
+ ``keyring`` 在没有可用后端时会选中 ``fail`` 后端,任何读写都抛
79
+ ``NoKeyringError``。把它提前判出来,``/models`` 才能说"这台机器没有钥匙串",
80
+ 而不是每次解析都撞一次异常。
81
+ """
82
+
83
+ def __init__(self, service: str = SERVICE_NAME) -> None:
84
+ self._service = service
85
+
86
+ @property
87
+ def name(self) -> str:
88
+ backend = type(keyring.get_keyring())
89
+ label = backend.__module__.rsplit(".", 1)[-1]
90
+ return f"{label} Keyring"
91
+
92
+ @property
93
+ def available(self) -> bool:
94
+ return not isinstance(keyring.get_keyring(), FailKeyring)
95
+
96
+ def get(self, provider_id: str) -> str | None:
97
+ if not self.available:
98
+ return None
99
+ try:
100
+ return keyring.get_password(self._service, provider_id)
101
+ except KeyringError as exc:
102
+ raise KeychainError(f"{self.name}: {exc}") from exc
103
+
104
+ def set(self, provider_id: str, secret: str) -> None:
105
+ if not self.available:
106
+ raise KeychainError(f"系统钥匙串不可用({self.name})")
107
+ try:
108
+ keyring.set_password(self._service, provider_id, secret)
109
+ except KeyringError as exc:
110
+ raise KeychainError(f"{self.name}: {exc}") from exc
111
+
112
+ def delete(self, provider_id: str) -> bool:
113
+ if not self.available:
114
+ raise KeychainError(f"系统钥匙串不可用({self.name})")
115
+ try:
116
+ keyring.delete_password(self._service, provider_id)
117
+ except PasswordDeleteError:
118
+ return False
119
+ except KeyringError as exc:
120
+ raise KeychainError(f"{self.name}: {exc}") from exc
121
+ return True
122
+
123
+
124
+ @dataclass(slots=True, frozen=True)
125
+ class ProviderCredential:
126
+ """一家 Provider 的凭证状况。
127
+
128
+ ``available`` 为真时 ``detail`` 是来源说明(``环境变量 DEEPSEEK_API_KEY``);
129
+ 为假时是一句可执行的原因(缺哪个变量、钥匙串里有没有、该跑哪条命令)。
130
+ """
131
+
132
+ provider_id: str
133
+ source: CredentialSource | None
134
+ detail: str
135
+
136
+ @property
137
+ def available(self) -> bool:
138
+ return self.source is not None
139
+
140
+
141
+ class Credentials:
142
+ """按优先级为每个 provider 解析密钥,并为界面保留一份来源说明。
143
+
144
+ :param config: 启动时构造的配置对象,提供 provider 表与它们的 ``env_key``。
145
+ :param env: 环境变量表,缺省读 ``os.environ``。
146
+ :param keychain: 钥匙串实现,缺省用 :class:`SystemKeychain`。
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ config: AgentConfig,
152
+ *,
153
+ env: Mapping[str, str] | None = None,
154
+ keychain: Keychain | None = None,
155
+ ) -> None:
156
+ self._config = config
157
+ self._env: Mapping[str, str] = os.environ if env is None else env
158
+ self._keychain: Keychain = keychain if keychain is not None else SystemKeychain()
159
+ # 启动时探一次,`/models` 与 `braid auth status` 直接读;密钥本身每次请求重取。
160
+ self._statuses: dict[str, ProviderCredential] = {
161
+ entry.id: self._probe(entry) for entry in config.providers
162
+ }
163
+
164
+ # ------------------------------------------------------------------ 查询
165
+
166
+ def status(self, provider_id: str) -> ProviderCredential:
167
+ """该 provider 的凭证状况。配置里没有这家时返回"未配置"。"""
168
+ known = self._statuses.get(provider_id)
169
+ if known is not None:
170
+ return known
171
+ return ProviderCredential(
172
+ provider_id=provider_id, source=None, detail=f"未配置:模型目录里没有 {provider_id}"
173
+ )
174
+
175
+ def statuses(self) -> tuple[ProviderCredential, ...]:
176
+ """全部 provider 的凭证状况,顺序与模型目录一致。"""
177
+ return tuple(self._statuses.values())
178
+
179
+ # ------------------------------------------------------------------ 解析
180
+
181
+ def secret(self, provider_id: str) -> str | None:
182
+ """按优先级取一次密钥。给 ``GET /models`` 这类非流式调用用。"""
183
+ entry = self._config.provider(provider_id)
184
+ if entry is None:
185
+ return None
186
+ if entry.env_key:
187
+ value = self._env.get(entry.env_key)
188
+ if value:
189
+ return value
190
+ secret = self._keychain.get(provider_id)
191
+ if secret:
192
+ return secret
193
+ return entry.api_key
194
+
195
+ def resolver(self) -> AuthResolver:
196
+ """给 :class:`~braid_ai.models.Models` 用的解析器,每次请求都重新取值。"""
197
+ return _ResolutionOrder(self)
198
+
199
+ # ------------------------------------------------------------------ 内部
200
+
201
+ def _probe(self, entry: ProviderEntry) -> ProviderCredential:
202
+ """探一次来源,不读完整的密钥值——只判断"有没有"。"""
203
+ if entry.env_key:
204
+ value = self._env.get(entry.env_key)
205
+ if value:
206
+ return ProviderCredential(entry.id, "env", f"环境变量 {entry.env_key}")
207
+
208
+ keychain_note = ""
209
+ if self._keychain.available:
210
+ try:
211
+ if self._keychain.get(entry.id):
212
+ return ProviderCredential(
213
+ entry.id, "keychain", f"{self._keychain.name} {entry.id}"
214
+ )
215
+ except KeychainError as exc:
216
+ keychain_note = f",系统钥匙串不可读({exc})"
217
+ else:
218
+ keychain_note = f",系统钥匙串不可用({self._keychain.name})"
219
+
220
+ if entry.api_key is not None:
221
+ source = Path(entry.api_key_source).name if entry.api_key_source else "配置文件"
222
+ detail = f"{source} 里的 api_key"
223
+ return ProviderCredential(entry.id, "config", detail)
224
+ if not entry.env_key:
225
+ return ProviderCredential(entry.id, "keyless", "免密端点(没有声明 env_key)")
226
+ return ProviderCredential(
227
+ entry.id,
228
+ None,
229
+ f"未配置:环境变量 {entry.env_key} 为空{keychain_note};"
230
+ f"运行 braid auth login {entry.id} 写入系统钥匙串",
231
+ )
232
+
233
+
234
+ class _ResolutionOrder:
235
+ """``Credentials`` 的解析器视图:每次 ``resolve`` 都重新走一遍优先级。"""
236
+
237
+ def __init__(self, credentials: Credentials) -> None:
238
+ self._credentials = credentials
239
+
240
+ def resolve(self, provider: HasEnvKeys) -> str | None:
241
+ return self._credentials.secret(provider.id)
242
+
243
+
244
+ __all__ = [
245
+ "SERVICE_NAME",
246
+ "CredentialSource",
247
+ "Credentials",
248
+ "Keychain",
249
+ "KeychainError",
250
+ "ProviderCredential",
251
+ "SystemKeychain",
252
+ ]