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,381 @@
|
|
|
1
|
+
"""``braid upgrade``:查一次索引,有新版就由用户确认后装。
|
|
2
|
+
|
|
3
|
+
```text
|
|
4
|
+
braid upgrade --check 只查:当前 0.1.0,索引里最新 0.2.0
|
|
5
|
+
braid upgrade 询问"现在升级?",回车确认后执行
|
|
6
|
+
braid upgrade --yes 不询问(脚本与 CI 用)
|
|
7
|
+
braid upgrade --dist dist/ 从本地产物重装(不查索引)
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## 为什么是显式命令
|
|
11
|
+
|
|
12
|
+
启动路径不联网是这个仓库的既定约束(模型目录的缓存同理):每次启动都去索引问一次
|
|
13
|
+
"有没有新版",等于把离线可用性与首屏延迟交给一次外部请求。``braid upgrade`` 是
|
|
14
|
+
用户主动发起的那一刻,它可以联网。
|
|
15
|
+
|
|
16
|
+
## 索引只认 JSON API
|
|
17
|
+
|
|
18
|
+
默认 ``https://pypi.org/pypi``,按 ``<索引>/<包名>/json`` 取 ``info.version`` 与
|
|
19
|
+
``info.requires_python``。``requires_python`` 与本机解释器不匹配时拒绝升级——装一个
|
|
20
|
+
自己解释不了的版本,下一次启动就会在导入阶段失败。
|
|
21
|
+
|
|
22
|
+
## 退出码
|
|
23
|
+
|
|
24
|
+
```text
|
|
25
|
+
0 已是最新版本,或升级成功
|
|
26
|
+
10 有新版本(或本地产物)可用,但没有执行安装:--check、非交互终端、用户拒绝
|
|
27
|
+
1 索引不可达、索引里没有这个包、本机是源码安装、uv 不存在或安装失败
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
``10`` 让脚本能区分"查过了,确实有新版"与"查失败了",而不必去解析人读的输出。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import asyncio
|
|
36
|
+
import platform
|
|
37
|
+
import shutil
|
|
38
|
+
import subprocess
|
|
39
|
+
import sys
|
|
40
|
+
from collections.abc import Mapping, Sequence
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Final, TextIO, cast
|
|
44
|
+
|
|
45
|
+
import httpx
|
|
46
|
+
from packaging.specifiers import InvalidSpecifier, SpecifierSet
|
|
47
|
+
from packaging.version import InvalidVersion, Version
|
|
48
|
+
|
|
49
|
+
from braid_coding_agent import __version__
|
|
50
|
+
from braid_coding_agent.commands import CommandError, take_value
|
|
51
|
+
from braid_coding_agent.commands.doctor import installation_kind
|
|
52
|
+
|
|
53
|
+
USAGE = """braid upgrade [选项]
|
|
54
|
+
检查索引里的最新版本;有新版本时询问后执行升级
|
|
55
|
+
|
|
56
|
+
选项:
|
|
57
|
+
--check 只检查并给出结论,不安装
|
|
58
|
+
--yes 不询问,直接升级(脚本用)
|
|
59
|
+
--dist DIR 从本地产物(含 braid_coding_agent-*.whl 的目录)重装,不查索引
|
|
60
|
+
--index URL 包索引的 JSON API 根地址(默认 https://pypi.org/pypi)
|
|
61
|
+
-h, --help 显示本帮助
|
|
62
|
+
|
|
63
|
+
退出码: 0 已最新或升级成功;10 有新版本但未安装;1 检查或安装失败"""
|
|
64
|
+
|
|
65
|
+
#: 索引的默认 JSON API 根地址。
|
|
66
|
+
DEFAULT_INDEX_URL: Final[str] = "https://pypi.org/pypi"
|
|
67
|
+
#: 发到索引上的包名。
|
|
68
|
+
PACKAGE_NAME: Final[str] = "braid-coding-agent"
|
|
69
|
+
#: "有可用版本但没安装"的退出码。
|
|
70
|
+
UPDATE_PENDING: Final[int] = 10
|
|
71
|
+
#: 查询索引的超时(秒)。
|
|
72
|
+
INDEX_TIMEOUT_SECONDS: Final[float] = 15.0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(slots=True, frozen=True)
|
|
76
|
+
class Release:
|
|
77
|
+
"""索引里的一条版本信息。"""
|
|
78
|
+
|
|
79
|
+
version: Version
|
|
80
|
+
requires_python: str | None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(slots=True, frozen=True)
|
|
84
|
+
class Plan:
|
|
85
|
+
"""一次升级要做的事。``command`` 是最终交给 uv 的 argv。"""
|
|
86
|
+
|
|
87
|
+
current: Version
|
|
88
|
+
target: Version | None
|
|
89
|
+
command: tuple[str, ...]
|
|
90
|
+
dist: Path | None = None
|
|
91
|
+
#: 源码可编辑安装的根目录。非空时拒绝执行:升级工具装不到正在运行的这份代码上。
|
|
92
|
+
source_root: Path | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def index_url_for(base: str) -> str:
|
|
96
|
+
"""``<索引根>/<包名>/json``。"""
|
|
97
|
+
return f"{base.rstrip('/')}/{PACKAGE_NAME}/json"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_release(payload: object, *, where: str) -> Release:
|
|
101
|
+
"""从索引的 JSON 里取版本与 ``requires_python``。"""
|
|
102
|
+
if not isinstance(payload, dict):
|
|
103
|
+
raise CommandError(f"{where}: 索引返回的不是 JSON 对象")
|
|
104
|
+
document = cast("Mapping[str, object]", payload)
|
|
105
|
+
info = document.get("info")
|
|
106
|
+
if not isinstance(info, dict):
|
|
107
|
+
raise CommandError(f"{where}: 索引返回里没有 info 字段")
|
|
108
|
+
fields = cast("Mapping[str, object]", info)
|
|
109
|
+
raw_version = fields.get("version")
|
|
110
|
+
if not isinstance(raw_version, str) or not raw_version.strip():
|
|
111
|
+
raise CommandError(f"{where}: 索引返回里没有 info.version")
|
|
112
|
+
try:
|
|
113
|
+
version = Version(raw_version)
|
|
114
|
+
except InvalidVersion as exc:
|
|
115
|
+
raise CommandError(f"{where}: 索引里的版本 {raw_version!r} 不是合法版本号") from exc
|
|
116
|
+
raw_python = fields.get("requires_python")
|
|
117
|
+
requires = raw_python.strip() if isinstance(raw_python, str) and raw_python.strip() else None
|
|
118
|
+
return Release(version=version, requires_python=requires)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
async def fetch_release(index_url: str, *, client: httpx.AsyncClient | None = None) -> Release:
|
|
122
|
+
"""读索引里的最新版本。404 说明这个包还没有发布到那里。"""
|
|
123
|
+
url = index_url_for(index_url)
|
|
124
|
+
owned = client is None
|
|
125
|
+
http = client if client is not None else httpx.AsyncClient(timeout=INDEX_TIMEOUT_SECONDS)
|
|
126
|
+
try:
|
|
127
|
+
response = await http.get(url, headers={"Accept": "application/json"})
|
|
128
|
+
except httpx.HTTPError as exc:
|
|
129
|
+
raise CommandError(f"访问索引失败:{url}:{exc}") from exc
|
|
130
|
+
finally:
|
|
131
|
+
if owned:
|
|
132
|
+
await http.aclose()
|
|
133
|
+
if response.status_code == 404:
|
|
134
|
+
raise CommandError(
|
|
135
|
+
f"索引里没有 {PACKAGE_NAME}({url} 返回 404):它还没有发布到那里。"
|
|
136
|
+
"用 braid upgrade --dist <含 wheel 的目录> 从本地产物升级"
|
|
137
|
+
)
|
|
138
|
+
if response.status_code != 200:
|
|
139
|
+
raise CommandError(f"索引返回 {response.status_code}:{url}")
|
|
140
|
+
try:
|
|
141
|
+
payload: object = response.json()
|
|
142
|
+
except ValueError as exc:
|
|
143
|
+
raise CommandError(f"索引返回的不是 JSON:{url}") from exc
|
|
144
|
+
return parse_release(payload, where=url)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def check_python_requirement(release: Release, python_version: str) -> None:
|
|
148
|
+
"""索引里的 ``requires_python`` 与本机解释器不兼容时拒绝升级。"""
|
|
149
|
+
if release.requires_python is None:
|
|
150
|
+
return
|
|
151
|
+
try:
|
|
152
|
+
specifier = SpecifierSet(release.requires_python)
|
|
153
|
+
except InvalidSpecifier as exc:
|
|
154
|
+
raise CommandError(
|
|
155
|
+
f"{PACKAGE_NAME} {release.version} 的 requires_python 写法无法解析:"
|
|
156
|
+
f"{release.requires_python}"
|
|
157
|
+
) from exc
|
|
158
|
+
if not specifier.contains(python_version, prereleases=True):
|
|
159
|
+
raise CommandError(
|
|
160
|
+
f"{PACKAGE_NAME} {release.version} 要求 Python {release.requires_python},"
|
|
161
|
+
f"本机是 {python_version};先升级解释器,或留在当前版本 {__version__}"
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def latest_local_version(dist: Path) -> Version:
|
|
166
|
+
"""本地产物目录里 braid 的版本。目录里没有 wheel 时报错。"""
|
|
167
|
+
wheels = sorted(dist.glob("braid_coding_agent-*.whl"))
|
|
168
|
+
if not wheels:
|
|
169
|
+
raise CommandError(f"{dist} 里没有 braid_coding_agent-*.whl;先运行 make dist")
|
|
170
|
+
# 文件名形如 braid_coding_agent-0.1.0-py3-none-any.whl,版本在第二个连字符段。
|
|
171
|
+
stem = wheels[-1].name[: -len(".whl")]
|
|
172
|
+
parts = stem.split("-")
|
|
173
|
+
if len(parts) < 2:
|
|
174
|
+
raise CommandError(f"看不懂的 wheel 文件名:{wheels[-1].name}")
|
|
175
|
+
try:
|
|
176
|
+
return Version(parts[1])
|
|
177
|
+
except InvalidVersion as exc:
|
|
178
|
+
raise CommandError(f"{wheels[-1].name} 里的版本号不合法") from exc
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def build_plan(
|
|
182
|
+
*,
|
|
183
|
+
current: Version,
|
|
184
|
+
release: Release | None = None,
|
|
185
|
+
dist: Path | None = None,
|
|
186
|
+
source_root: Path | None = None,
|
|
187
|
+
uv: str = "uv",
|
|
188
|
+
) -> Plan:
|
|
189
|
+
"""组合出要执行的命令。``release`` 为空表示从本地产物装。"""
|
|
190
|
+
argv: list[str] = [uv, "tool", "install", "--reinstall", "--force"]
|
|
191
|
+
target: str = PACKAGE_NAME
|
|
192
|
+
if dist is not None:
|
|
193
|
+
argv.extend(["--find-links", str(dist)])
|
|
194
|
+
elif release is not None:
|
|
195
|
+
target = f"{PACKAGE_NAME}=={release.version}"
|
|
196
|
+
argv.append(target)
|
|
197
|
+
return Plan(
|
|
198
|
+
current=current,
|
|
199
|
+
target=None if release is None else release.version,
|
|
200
|
+
command=tuple(argv),
|
|
201
|
+
dist=dist,
|
|
202
|
+
source_root=source_root,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def plan_is_actionable(plan: Plan) -> bool:
|
|
207
|
+
"""有没有需要装的版本。本地产物一律视为可执行。"""
|
|
208
|
+
if plan.target is None:
|
|
209
|
+
return True
|
|
210
|
+
return plan.target > plan.current
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def describe(current: Version, latest: Version) -> str:
|
|
214
|
+
"""索引查询的一行结论。本地产物那条路径另有一行说明目录与版本。"""
|
|
215
|
+
if latest > current:
|
|
216
|
+
return f"当前 {current},最新 {latest}"
|
|
217
|
+
return f"已是最新版本({current})"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
async def execute(plan: Plan, *, assume_yes: bool, out: TextIO) -> int:
|
|
221
|
+
"""确认之后执行 ``uv tool install``。
|
|
222
|
+
|
|
223
|
+
源码可编辑安装直接拒绝:``uv tool install`` 装的是另一份代码,正在运行的这份
|
|
224
|
+
不会变,用户会以为升级成功了。
|
|
225
|
+
"""
|
|
226
|
+
if plan.source_root is not None:
|
|
227
|
+
raise CommandError(
|
|
228
|
+
f"当前是源码可编辑安装({plan.source_root}),braid upgrade 不会改变它;"
|
|
229
|
+
"在源码树里用 git pull 后 uv sync,或先 uv tool uninstall braid-coding-agent 再安装"
|
|
230
|
+
)
|
|
231
|
+
command = " ".join(plan.command)
|
|
232
|
+
if not assume_yes:
|
|
233
|
+
if not sys.stdin.isatty():
|
|
234
|
+
print("\n没有终端可以确认。要现在执行,请加 --yes:", file=out)
|
|
235
|
+
print(f" {command}", file=out)
|
|
236
|
+
return UPDATE_PENDING
|
|
237
|
+
print(f"\n将要执行:\n {command}", file=out, flush=True)
|
|
238
|
+
print("继续?[y/N] ", end="", file=out, flush=True)
|
|
239
|
+
answer = sys.stdin.readline().strip().lower()
|
|
240
|
+
if answer not in ("y", "yes"):
|
|
241
|
+
print("已取消,没有改动任何东西", file=out)
|
|
242
|
+
return UPDATE_PENDING
|
|
243
|
+
|
|
244
|
+
uv = plan.command[0]
|
|
245
|
+
if shutil.which(uv) is None:
|
|
246
|
+
raise CommandError(
|
|
247
|
+
f"找不到 {uv}:先安装 uv(curl -LsSf https://astral.sh/uv/install.sh | sh)"
|
|
248
|
+
)
|
|
249
|
+
print(f"执行:{command}", file=out, flush=True)
|
|
250
|
+
process = await asyncio.create_subprocess_exec(*plan.command)
|
|
251
|
+
code = await process.wait()
|
|
252
|
+
if code != 0:
|
|
253
|
+
raise CommandError(f"升级失败:{command} 退出码 {code}")
|
|
254
|
+
print("\n升级完成。新版本:", file=out)
|
|
255
|
+
print(f" {installed_version(uv) or '运行 braid --version 确认'}", file=out)
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def installed_version(uv: str) -> str | None:
|
|
260
|
+
"""``uv tool dir --bin`` 下的 ``braid --version``。读不到就返回 ``None``。"""
|
|
261
|
+
try:
|
|
262
|
+
listing = subprocess.run(
|
|
263
|
+
[uv, "tool", "dir", "--bin"], capture_output=True, text=True, check=False
|
|
264
|
+
)
|
|
265
|
+
except OSError:
|
|
266
|
+
return None
|
|
267
|
+
if listing.returncode != 0:
|
|
268
|
+
return None
|
|
269
|
+
launcher = Path(listing.stdout.strip()) / "braid"
|
|
270
|
+
if not launcher.is_file():
|
|
271
|
+
return None
|
|
272
|
+
probe = subprocess.run(
|
|
273
|
+
[str(launcher), "--version"], capture_output=True, text=True, check=False
|
|
274
|
+
)
|
|
275
|
+
if probe.returncode != 0:
|
|
276
|
+
return None
|
|
277
|
+
return probe.stdout.strip() or None
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ------------------------------------------------------------------ 入口
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass(slots=True)
|
|
284
|
+
class _Options:
|
|
285
|
+
check: bool = False
|
|
286
|
+
yes: bool = False
|
|
287
|
+
dist: Path | None = None
|
|
288
|
+
index: str = DEFAULT_INDEX_URL
|
|
289
|
+
help: bool = False
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _parse(argv: Sequence[str]) -> _Options:
|
|
293
|
+
options = _Options()
|
|
294
|
+
values = list(argv)
|
|
295
|
+
index = 0
|
|
296
|
+
while index < len(values):
|
|
297
|
+
argument = values[index]
|
|
298
|
+
if argument in ("-h", "--help"):
|
|
299
|
+
options.help = True
|
|
300
|
+
elif argument == "--check":
|
|
301
|
+
options.check = True
|
|
302
|
+
elif argument == "--yes":
|
|
303
|
+
options.yes = True
|
|
304
|
+
elif argument == "--dist":
|
|
305
|
+
value, index = take_value(values, index, flag="--dist")
|
|
306
|
+
options.dist = Path(value).expanduser()
|
|
307
|
+
elif argument == "--index":
|
|
308
|
+
value, index = take_value(values, index, flag="--index")
|
|
309
|
+
options.index = value
|
|
310
|
+
else:
|
|
311
|
+
raise CommandError(f"未知参数: {argument}(braid upgrade --help 查看用法)")
|
|
312
|
+
index += 1
|
|
313
|
+
if options.dist is not None and options.index != DEFAULT_INDEX_URL:
|
|
314
|
+
raise CommandError("--dist 与 --index 二选一:一个从本地产物装,一个从索引装")
|
|
315
|
+
if options.dist is not None and not options.dist.is_dir():
|
|
316
|
+
raise CommandError(f"--dist 指向的目录不存在:{options.dist}")
|
|
317
|
+
return options
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
async def run(argv: Sequence[str], *, agent_dir: Path, cwd: str, out: TextIO | None = None) -> int:
|
|
321
|
+
del agent_dir, cwd # 升级与本机配置、工作目录无关;参数只为与其他子命令同形
|
|
322
|
+
options = _parse(argv)
|
|
323
|
+
stream = sys.stdout if out is None else out
|
|
324
|
+
if options.help:
|
|
325
|
+
print(USAGE)
|
|
326
|
+
return 0
|
|
327
|
+
|
|
328
|
+
current = Version(__version__)
|
|
329
|
+
kind, source_root = installation_kind()
|
|
330
|
+
release: Release | None = None
|
|
331
|
+
if options.dist is not None:
|
|
332
|
+
local = latest_local_version(options.dist)
|
|
333
|
+
plan = build_plan(
|
|
334
|
+
current=current,
|
|
335
|
+
dist=options.dist,
|
|
336
|
+
source_root=source_root if kind == "source" else None,
|
|
337
|
+
)
|
|
338
|
+
print(f"本地产物:{options.dist}(版本 {local})", file=stream)
|
|
339
|
+
else:
|
|
340
|
+
release = await fetch_release(options.index)
|
|
341
|
+
check_python_requirement(release, platform.python_version())
|
|
342
|
+
plan = build_plan(
|
|
343
|
+
current=current,
|
|
344
|
+
release=release,
|
|
345
|
+
source_root=source_root if kind == "source" else None,
|
|
346
|
+
)
|
|
347
|
+
print(describe(current, release.version), file=stream)
|
|
348
|
+
|
|
349
|
+
if not plan_is_actionable(plan):
|
|
350
|
+
return 0
|
|
351
|
+
if options.check:
|
|
352
|
+
print("要安装就运行(不带 --check):", file=stream)
|
|
353
|
+
print(f" {' '.join(plan.command)}", file=stream)
|
|
354
|
+
if plan.source_root is not None:
|
|
355
|
+
print(
|
|
356
|
+
"注意:当前是源码可编辑安装,这条命令装的是另一份代码;"
|
|
357
|
+
"在源码树里请用 git pull 后 uv sync",
|
|
358
|
+
file=stream,
|
|
359
|
+
)
|
|
360
|
+
return UPDATE_PENDING
|
|
361
|
+
return await execute(plan, assume_yes=options.yes, out=stream)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
__all__ = [
|
|
365
|
+
"DEFAULT_INDEX_URL",
|
|
366
|
+
"PACKAGE_NAME",
|
|
367
|
+
"UPDATE_PENDING",
|
|
368
|
+
"Plan",
|
|
369
|
+
"Release",
|
|
370
|
+
"build_plan",
|
|
371
|
+
"check_python_requirement",
|
|
372
|
+
"describe",
|
|
373
|
+
"execute",
|
|
374
|
+
"fetch_release",
|
|
375
|
+
"index_url_for",
|
|
376
|
+
"installed_version",
|
|
377
|
+
"latest_local_version",
|
|
378
|
+
"parse_release",
|
|
379
|
+
"plan_is_actionable",
|
|
380
|
+
"run",
|
|
381
|
+
]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""上下文压缩。
|
|
2
|
+
|
|
3
|
+
对外暴露三个使用入口,对应三种触发方式:
|
|
4
|
+
|
|
5
|
+
- **阈值触发**::class:`~braid_coding_agent.session.AgentSession` 传入
|
|
6
|
+
``compaction_settings`` 后,每次请求前与每次 run 结束后检查
|
|
7
|
+
``tokens > window - reserve``,越线自动压缩(``reason="threshold"``);
|
|
8
|
+
- **溢出恢复**:请求撞上上下文上限(显式报错 / 静默溢出 / 截断式 length)时,
|
|
9
|
+
恢复路径自动执行一次"压缩后重试"(``reason="overflow"``);
|
|
10
|
+
- **手动触发**:``AgentSession.compact(custom_instructions)``(``/compact``,
|
|
11
|
+
``reason="manual"``)。
|
|
12
|
+
|
|
13
|
+
模块分层:
|
|
14
|
+
|
|
15
|
+
- :mod:`.tokens` —— 体积估算与触发判断;
|
|
16
|
+
- :mod:`.utils` —— 文件操作跟踪、会话序列化、摘要系统提示词;
|
|
17
|
+
- :mod:`.prepare` —— 切点查找与 ``CompactionPreparation``;
|
|
18
|
+
- :mod:`.summarize` —— 摘要请求、失败判定、:func:`compact` 主流程。
|
|
19
|
+
|
|
20
|
+
压缩的落地(追加 :class:`~braid_coding_agent.session.CompactionEntry`、重建上下文、
|
|
21
|
+
发事件)在 :mod:`braid_coding_agent.session.agent_session`——本包保持纯函数与
|
|
22
|
+
模型调用,不持有会话对象。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import importlib
|
|
28
|
+
from typing import TYPE_CHECKING
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from braid_coding_agent.compaction.prepare import (
|
|
32
|
+
DEFAULT_COMPACTION_SETTINGS,
|
|
33
|
+
CompactionPreparation,
|
|
34
|
+
CompactionSettings,
|
|
35
|
+
CutPointResult,
|
|
36
|
+
estimate_projected_context_tokens,
|
|
37
|
+
extract_file_operations,
|
|
38
|
+
find_cut_point,
|
|
39
|
+
find_turn_start_index,
|
|
40
|
+
prepare_compaction,
|
|
41
|
+
)
|
|
42
|
+
from braid_coding_agent.compaction.summarize import (
|
|
43
|
+
SUMMARIZATION_PROMPT,
|
|
44
|
+
TURN_PREFIX_SUMMARIZATION_PROMPT,
|
|
45
|
+
UPDATE_SUMMARIZATION_PROMPT,
|
|
46
|
+
CompactionResult,
|
|
47
|
+
SummarizationError,
|
|
48
|
+
SummaryWithUsage,
|
|
49
|
+
compact,
|
|
50
|
+
complete_summarization,
|
|
51
|
+
generate_summary,
|
|
52
|
+
generate_summary_with_usage,
|
|
53
|
+
get_summarization_failure,
|
|
54
|
+
)
|
|
55
|
+
from braid_coding_agent.compaction.tokens import (
|
|
56
|
+
ContextUsageEstimate,
|
|
57
|
+
calculate_context_tokens,
|
|
58
|
+
estimate_context_tokens,
|
|
59
|
+
estimate_tokens,
|
|
60
|
+
should_compact,
|
|
61
|
+
)
|
|
62
|
+
from braid_coding_agent.compaction.tool_results import (
|
|
63
|
+
DEFAULT_TOOL_RESULT_CLEANUP,
|
|
64
|
+
CleanupTarget,
|
|
65
|
+
ToolResultCleanupPlan,
|
|
66
|
+
ToolResultCleanupSettings,
|
|
67
|
+
plan_tool_result_cleanup,
|
|
68
|
+
)
|
|
69
|
+
from braid_coding_agent.compaction.utils import (
|
|
70
|
+
SUMMARIZATION_SYSTEM_PROMPT,
|
|
71
|
+
TOOL_RESULT_MAX_CHARS,
|
|
72
|
+
FileOperations,
|
|
73
|
+
compute_file_lists,
|
|
74
|
+
create_file_ops,
|
|
75
|
+
extract_file_ops_from_message,
|
|
76
|
+
format_file_operations,
|
|
77
|
+
serialize_conversation,
|
|
78
|
+
truncate_for_summary,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
_LAZY_EXPORTS: dict[str, str] = {
|
|
82
|
+
"DEFAULT_COMPACTION_SETTINGS": "braid_coding_agent.compaction.prepare",
|
|
83
|
+
"CompactionPreparation": "braid_coding_agent.compaction.prepare",
|
|
84
|
+
"CompactionSettings": "braid_coding_agent.compaction.prepare",
|
|
85
|
+
"CutPointResult": "braid_coding_agent.compaction.prepare",
|
|
86
|
+
"estimate_projected_context_tokens": "braid_coding_agent.compaction.prepare",
|
|
87
|
+
"extract_file_operations": "braid_coding_agent.compaction.prepare",
|
|
88
|
+
"find_cut_point": "braid_coding_agent.compaction.prepare",
|
|
89
|
+
"find_turn_start_index": "braid_coding_agent.compaction.prepare",
|
|
90
|
+
"prepare_compaction": "braid_coding_agent.compaction.prepare",
|
|
91
|
+
"SUMMARIZATION_PROMPT": "braid_coding_agent.compaction.summarize",
|
|
92
|
+
"TURN_PREFIX_SUMMARIZATION_PROMPT": "braid_coding_agent.compaction.summarize",
|
|
93
|
+
"UPDATE_SUMMARIZATION_PROMPT": "braid_coding_agent.compaction.summarize",
|
|
94
|
+
"CompactionResult": "braid_coding_agent.compaction.summarize",
|
|
95
|
+
"SummarizationError": "braid_coding_agent.compaction.summarize",
|
|
96
|
+
"SummaryWithUsage": "braid_coding_agent.compaction.summarize",
|
|
97
|
+
"compact": "braid_coding_agent.compaction.summarize",
|
|
98
|
+
"complete_summarization": "braid_coding_agent.compaction.summarize",
|
|
99
|
+
"generate_summary": "braid_coding_agent.compaction.summarize",
|
|
100
|
+
"generate_summary_with_usage": "braid_coding_agent.compaction.summarize",
|
|
101
|
+
"get_summarization_failure": "braid_coding_agent.compaction.summarize",
|
|
102
|
+
"ContextUsageEstimate": "braid_coding_agent.compaction.tokens",
|
|
103
|
+
"calculate_context_tokens": "braid_coding_agent.compaction.tokens",
|
|
104
|
+
"estimate_context_tokens": "braid_coding_agent.compaction.tokens",
|
|
105
|
+
"estimate_tokens": "braid_coding_agent.compaction.tokens",
|
|
106
|
+
"should_compact": "braid_coding_agent.compaction.tokens",
|
|
107
|
+
"DEFAULT_TOOL_RESULT_CLEANUP": "braid_coding_agent.compaction.tool_results",
|
|
108
|
+
"CleanupTarget": "braid_coding_agent.compaction.tool_results",
|
|
109
|
+
"ToolResultCleanupPlan": "braid_coding_agent.compaction.tool_results",
|
|
110
|
+
"ToolResultCleanupSettings": "braid_coding_agent.compaction.tool_results",
|
|
111
|
+
"plan_tool_result_cleanup": "braid_coding_agent.compaction.tool_results",
|
|
112
|
+
"SUMMARIZATION_SYSTEM_PROMPT": "braid_coding_agent.compaction.utils",
|
|
113
|
+
"TOOL_RESULT_MAX_CHARS": "braid_coding_agent.compaction.utils",
|
|
114
|
+
"FileOperations": "braid_coding_agent.compaction.utils",
|
|
115
|
+
"compute_file_lists": "braid_coding_agent.compaction.utils",
|
|
116
|
+
"create_file_ops": "braid_coding_agent.compaction.utils",
|
|
117
|
+
"extract_file_ops_from_message": "braid_coding_agent.compaction.utils",
|
|
118
|
+
"format_file_operations": "braid_coding_agent.compaction.utils",
|
|
119
|
+
"serialize_conversation": "braid_coding_agent.compaction.utils",
|
|
120
|
+
"truncate_for_summary": "braid_coding_agent.compaction.utils",
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def __getattr__(name: str) -> object:
|
|
125
|
+
"""按需导入导出名。配置层只取 ``CompactionSettings``。"""
|
|
126
|
+
module_name = _LAZY_EXPORTS.get(name)
|
|
127
|
+
if module_name is None:
|
|
128
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
129
|
+
value = getattr(importlib.import_module(module_name), name)
|
|
130
|
+
globals()[name] = value
|
|
131
|
+
return value
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
__all__ = [
|
|
135
|
+
"DEFAULT_COMPACTION_SETTINGS",
|
|
136
|
+
"DEFAULT_TOOL_RESULT_CLEANUP",
|
|
137
|
+
"SUMMARIZATION_PROMPT",
|
|
138
|
+
"SUMMARIZATION_SYSTEM_PROMPT",
|
|
139
|
+
"TOOL_RESULT_MAX_CHARS",
|
|
140
|
+
"TURN_PREFIX_SUMMARIZATION_PROMPT",
|
|
141
|
+
"UPDATE_SUMMARIZATION_PROMPT",
|
|
142
|
+
"CleanupTarget",
|
|
143
|
+
"CompactionPreparation",
|
|
144
|
+
"CompactionResult",
|
|
145
|
+
"CompactionSettings",
|
|
146
|
+
"ContextUsageEstimate",
|
|
147
|
+
"CutPointResult",
|
|
148
|
+
"FileOperations",
|
|
149
|
+
"SummarizationError",
|
|
150
|
+
"SummaryWithUsage",
|
|
151
|
+
"ToolResultCleanupPlan",
|
|
152
|
+
"ToolResultCleanupSettings",
|
|
153
|
+
"calculate_context_tokens",
|
|
154
|
+
"compact",
|
|
155
|
+
"complete_summarization",
|
|
156
|
+
"compute_file_lists",
|
|
157
|
+
"create_file_ops",
|
|
158
|
+
"estimate_context_tokens",
|
|
159
|
+
"estimate_projected_context_tokens",
|
|
160
|
+
"estimate_tokens",
|
|
161
|
+
"extract_file_operations",
|
|
162
|
+
"extract_file_ops_from_message",
|
|
163
|
+
"find_cut_point",
|
|
164
|
+
"find_turn_start_index",
|
|
165
|
+
"format_file_operations",
|
|
166
|
+
"generate_summary",
|
|
167
|
+
"generate_summary_with_usage",
|
|
168
|
+
"get_summarization_failure",
|
|
169
|
+
"plan_tool_result_cleanup",
|
|
170
|
+
"prepare_compaction",
|
|
171
|
+
"serialize_conversation",
|
|
172
|
+
"should_compact",
|
|
173
|
+
"truncate_for_summary",
|
|
174
|
+
]
|