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,204 @@
1
+ """上下文体积的估算。
2
+
3
+ 压缩系统回答两个问题,都要先知道"现在用了多少 token":
4
+
5
+ 1. **该不该压缩**:``tokens > context_window - reserve_tokens``(:func:`should_compact`);
6
+ 2. **从哪里切**:从尾部向前累计消息体积,到 ``keep_recent_tokens`` 为止
7
+ (:func:`find_cut_point`,在 :mod:`.prepare`)。
8
+
9
+ 两个问题的精度要求不同:触发判断宁可用**真实 usage**(Provider 自报,最准),
10
+ 切点选择只用**字符估算**(chars/4,宁高勿低)。于是这里有两套算法,由
11
+ :func:`estimate_context_tokens` 组合:最后一条带有效 usage 的助手消息之前的
12
+ 历史按 usage 计,之后的尾巴按估算计。
13
+
14
+ 为什么估算用 chars/4:英文平均 4 字符/token,中文约 1.5~2 字符/token,
15
+ 所以对中文内容会**高估**——高估只会让压缩提前触发、多留一些余量,
16
+ 低估却会让请求撞上窗口上限。这是刻意选错方向的"保守"估算。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass
24
+ from typing import Final
25
+
26
+ from braid_ai.types import (
27
+ AssistantMessage,
28
+ ImageContent,
29
+ SystemMessage,
30
+ TextContent,
31
+ ToolCall,
32
+ ToolResultMessage,
33
+ Usage,
34
+ UserMessage,
35
+ )
36
+ from braid_ai.wire import message_to_wire
37
+ from braid_coding_agent.session.entries import (
38
+ BranchSummaryMessage,
39
+ CompactionSummaryMessage,
40
+ CustomMessage,
41
+ )
42
+
43
+ __all__ = [
44
+ "ESTIMATED_IMAGE_CHARS",
45
+ "ContextUsageEstimate",
46
+ "calculate_context_tokens",
47
+ "estimate_context_tokens",
48
+ "estimate_tokens",
49
+ "get_last_assistant_usage",
50
+ "should_compact",
51
+ ]
52
+
53
+ #: 一张图片在估算里折合的字符数。一张中等分辨率的图片按 base64
54
+ #: 送进请求约几千 token,折算成 chars/4 口径就是 4800 字符。
55
+ ESTIMATED_IMAGE_CHARS: Final[int] = 4800
56
+
57
+
58
+ @dataclass(slots=True)
59
+ class ContextUsageEstimate:
60
+ """上下文体积的估算结果,带出处。
61
+
62
+ ``usage_tokens`` 是 Provider 自报的部分,``trailing_tokens`` 是其后的
63
+ 估算尾巴;``last_usage_index`` 是最后一条有效 usage 消息的下标,
64
+ 没有任何 usage 时为 ``None``。
65
+ """
66
+
67
+ tokens: int
68
+ usage_tokens: int
69
+ trailing_tokens: int
70
+ last_usage_index: int | None
71
+
72
+
73
+ def calculate_context_tokens(usage: Usage) -> int:
74
+ """一次调用的上下文占用。优先 Provider 自报的 ``total_tokens``,缺了再自己加。
75
+
76
+ ``total_tokens`` 为 0 视为"没报":部分 Provider 不填这个字段,
77
+ 组件相加(input + output + cache_read + cache_write)是同一件事的另一种报法。
78
+ """
79
+ return usage.total_tokens or usage.input + usage.output + usage.cache_read + usage.cache_write
80
+
81
+
82
+ def _content_chars(content: str | Sequence[TextContent | ImageContent]) -> int:
83
+ """user/custom/toolResult 内容的字符数:text 按长度,image 按固定占位。
84
+
85
+ 块类型由参数类型约束(只有 text 与 image 两种),排除 text 后即是 image。
86
+ """
87
+ if isinstance(content, str):
88
+ return len(content)
89
+ chars = 0
90
+ for block in content:
91
+ if isinstance(block, TextContent):
92
+ chars += len(block.text)
93
+ else:
94
+ chars += ESTIMATED_IMAGE_CHARS
95
+ return chars
96
+
97
+
98
+ def estimate_tokens(message: object) -> int:
99
+ """一条消息的 token 估算:字符数除以 4,向上取整。
100
+
101
+ 覆盖全部七种转录角色(``bashExecution`` 尚无生产者)。
102
+ 各角色的体积构成:
103
+
104
+ - **system**:content + 每个 section + ``tools_added`` 的 JSON 文本。
105
+ 工具声明是请求体的一部分,必须计入;
106
+ - **assistant**:text/thinking 按文本,toolCall 按名字 + 参数 JSON;
107
+ - **user / custom / toolResult**:文本与图片(见 :func:`_content_chars`);
108
+ - **branchSummary / compactionSummary**:摘要文本。
109
+
110
+ 认不出的消息返回 0:未来的自定义角色宁可少算,也不该在这里抛异常
111
+ 把一次压缩打断。
112
+ """
113
+ chars = 0
114
+ match message:
115
+ case SystemMessage():
116
+ chars = _content_chars(message.content)
117
+ if message.sections:
118
+ for section in message.sections.values():
119
+ if section:
120
+ chars += len(section)
121
+ if message.tools_added:
122
+ chars += len(json.dumps(_tools_added_wire(message), ensure_ascii=False))
123
+ case UserMessage() | CustomMessage():
124
+ chars = _content_chars(message.content) # type: ignore[arg-type]
125
+ case AssistantMessage():
126
+ for block in message.content:
127
+ if isinstance(block, TextContent):
128
+ chars += len(block.text)
129
+ elif isinstance(block, ToolCall):
130
+ chars += len(block.name) + len(json.dumps(block.arguments, ensure_ascii=False))
131
+ case ToolResultMessage():
132
+ chars = _content_chars(message.content)
133
+ case BranchSummaryMessage() | CompactionSummaryMessage():
134
+ chars = len(message.summary) # type: ignore[attr-defined]
135
+ case _:
136
+ return 0
137
+ return -(-chars // 4) # ceil(chars / 4),不引入浮点
138
+
139
+
140
+ def _tools_added_wire(message: SystemMessage) -> object:
141
+ """工具声明按 **wire** 形状计数。
142
+
143
+ 不能直接 ``json.dumps(message.tools_added)``:那是 :class:`braid_ai.types.Tool`
144
+ 数据类,不是 JSON(接上带工具声明的会话时会踩到:``TypeError: Object of type
145
+ Tool is not JSON serializable``,而估算路径只在 usage 缺失或错误响应时才走到,
146
+ 测试没暴露它)。走 ``message_to_wire`` 让"算进预算的字节"与
147
+ "真正发给模型的字节"是同一份编码。
148
+ """
149
+ return message_to_wire(message).get("toolsAdded", [])
150
+
151
+
152
+ def get_last_assistant_usage(messages: Sequence[object]) -> tuple[Usage, int] | None:
153
+ """从后往前找最后一条带有效 usage 的助手消息,返回 ``(usage, 下标)``。
154
+
155
+ aborted / error / 全零 usage 的消息不算:取消的请求没有真实账单,
156
+ 错误消息的 usage 也不反映真实上下文体积,拿它们估算会得出错误的触发判断。
157
+ """
158
+ for index in range(len(messages) - 1, -1, -1):
159
+ message = messages[index]
160
+ if not isinstance(message, AssistantMessage):
161
+ continue
162
+ if message.stop_reason in ("aborted", "error"):
163
+ continue
164
+ usage = message.usage
165
+ if calculate_context_tokens(usage) > 0:
166
+ return usage, index
167
+ return None
168
+
169
+
170
+ def estimate_context_tokens(messages: Sequence[object]) -> ContextUsageEstimate:
171
+ """从消息列表估算上下文体积:usage 为主、估算补尾。
172
+
173
+ 混合策略的理由:Provider 的 usage 是服务端真实计数(含提示词模板、
174
+ 工具声明等客户端算不到的开销),最后一条助手消息的 usage 就是"那一刻
175
+ 的全部上下文";之后新进来的消息(工具结果、用户消息)只能估算。
176
+ 两段相加,比纯估算准得多,比逐条拿 usage 简单得多。
177
+ """
178
+ found = get_last_assistant_usage(messages)
179
+ if found is None:
180
+ estimated = sum(estimate_tokens(message) for message in messages)
181
+ return ContextUsageEstimate(
182
+ tokens=estimated, usage_tokens=0, trailing_tokens=estimated, last_usage_index=None
183
+ )
184
+
185
+ usage, index = found
186
+ usage_tokens = calculate_context_tokens(usage)
187
+ trailing_tokens = sum(estimate_tokens(message) for message in messages[index + 1 :])
188
+ return ContextUsageEstimate(
189
+ tokens=usage_tokens + trailing_tokens,
190
+ usage_tokens=usage_tokens,
191
+ trailing_tokens=trailing_tokens,
192
+ last_usage_index=index,
193
+ )
194
+
195
+
196
+ def should_compact(context_tokens: int, context_window: int, settings: object) -> bool:
197
+ """是否达到压缩触发线:``tokens > window - reserve``。
198
+
199
+ ``settings`` 是 :class:`~braid_coding_agent.compaction.prepare.CompactionSettings`;
200
+ 类型在这里放宽是为了避免 tokens → prepare 的反向依赖。
201
+ """
202
+ if not getattr(settings, "enabled", False):
203
+ return False
204
+ return context_tokens > context_window - settings.reserve_tokens # type: ignore[attr-defined]
@@ -0,0 +1,196 @@
1
+ """工具结果清理:在整段摘要之外,提供一层代价最低的上下文控制。
2
+
3
+ 长会话里最占体积的往往不是对话,而是很早以前那些工具输出:`bash` 打印的整份测试
4
+ 日志、`grep` 返回的几百行匹配、`read` 读出的一整个文件。它们在当时有用,过了几轮
5
+ 之后基本只有"做过这件事"的价值。整段摘要的代价是一次模型调用,还会把附近的对话
6
+ 细节一起抹平;这一层只动工具结果,不动任何对话。
7
+
8
+ ## 取舍
9
+
10
+ - **按条替换,不删除**。目标条目追加一条 ``context_edit``,把内容换成一行摘要,
11
+ ``tool_call_id`` 与角色都保留——工具调用与结果的配对关系是协议的硬约束。
12
+ - **保留最近若干条原文**。模型当前正在处理的东西几乎一定在最近几条结果里,
13
+ 更早的才替换。条数由 ``keep_recent`` 决定,每条的单次收益不足以抵消"重新执行
14
+ 一次工具"的代价时不替换(``min_chars``)。
15
+ - **失败结果豁免**。错误输出通常不长,而且正是模型接下来要修的对象。
16
+ - **触发看比例,不看绝对体积**。窗口 8k 的模型和 200k 的模型对"大"的定义不同,
17
+ ``trigger_ratio`` 是投影体积占窗口的比例。
18
+ - **只清一次**。已经清过的条目不再作为目标:重复替换不会更省空间,只会让树上多出
19
+ 一串没有信息量的编辑条目。
20
+
21
+ ## 位置
22
+
23
+ 本模块只做决策(纯函数,输入投影与体积,输出计划),写条目与发事件在
24
+ :mod:`braid_coding_agent.session.agent_session`——压缩系统的分层约定是"包不持有会话对象"。
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Sequence
30
+ from dataclasses import dataclass
31
+ from typing import Final
32
+
33
+ from braid_ai.types import ImageContent, TextContent, ToolResultMessage
34
+ from braid_coding_agent.session.entries import ContextEditEntry, SessionEntry, SessionMessageEntry
35
+ from braid_coding_agent.session.projection import SessionProjection
36
+
37
+ __all__ = [
38
+ "DEFAULT_TOOL_RESULT_CLEANUP",
39
+ "OPENING_CHARS",
40
+ "CleanupTarget",
41
+ "ToolResultCleanupPlan",
42
+ "ToolResultCleanupSettings",
43
+ "plan_tool_result_cleanup",
44
+ ]
45
+
46
+ #: 替换文本里保留的"开头"长度。够模型认出这是什么,又不至于把一行写成一段。
47
+ OPENING_CHARS: Final[int] = 100
48
+
49
+
50
+ @dataclass(slots=True)
51
+ class ToolResultCleanupSettings:
52
+ """工具结果清理的设置。
53
+
54
+ :param enabled: 关掉后完全不检查,也不写条目。
55
+ :param keep_recent: 最近多少条工具结果保留原文。0 表示只要触发就全清。
56
+ :param min_chars: 单条结果的字符数下限;低于它的结果不清理。
57
+ :param trigger_ratio: 投影体积超过窗口的这个比例时开始清理。
58
+ """
59
+
60
+ enabled: bool = True
61
+ keep_recent: int = 8
62
+ min_chars: int = 1_000
63
+ trigger_ratio: float = 0.6
64
+
65
+ def __post_init__(self) -> None:
66
+ if self.keep_recent < 0:
67
+ raise ValueError(f"keep_recent 不能为负,收到 {self.keep_recent}")
68
+ if self.min_chars < 0:
69
+ raise ValueError(f"min_chars 不能为负,收到 {self.min_chars}")
70
+ if not 0 < self.trigger_ratio <= 1:
71
+ raise ValueError(f"trigger_ratio 必须落在 (0, 1],收到 {self.trigger_ratio}")
72
+
73
+
74
+ #: 默认清理设置:窗口占用超过 60% 时,保留最近 8 条、单条 1000 字符以上的结果。
75
+ DEFAULT_TOOL_RESULT_CLEANUP: Final[ToolResultCleanupSettings] = ToolResultCleanupSettings()
76
+
77
+
78
+ @dataclass(slots=True, frozen=True)
79
+ class CleanupTarget:
80
+ """一个待清理的工具结果:换成什么、原来多大。"""
81
+
82
+ entry_id: str
83
+ tool_name: str
84
+ chars: int
85
+ replacement: str
86
+
87
+
88
+ @dataclass(slots=True, frozen=True)
89
+ class ToolResultCleanupPlan:
90
+ """一次清理的完整账目。``targets`` 为空表示这一轮什么都不用做。"""
91
+
92
+ targets: tuple[CleanupTarget, ...] = ()
93
+ #: 被清理条目的原文字符数合计。
94
+ chars_before: int = 0
95
+ #: 替换文本的字符数合计。
96
+ chars_after: int = 0
97
+
98
+
99
+ _EMPTY_PLAN: Final[ToolResultCleanupPlan] = ToolResultCleanupPlan()
100
+
101
+
102
+ def _content_chars(message: ToolResultMessage) -> int:
103
+ """一条结果占多少字符。图片按 base64 长度算,它才是真正吃上下文的部分。"""
104
+ total = 0
105
+ for block in message.content:
106
+ if isinstance(block, TextContent):
107
+ total += len(block.text)
108
+ else:
109
+ total += len(block.data)
110
+ return total
111
+
112
+
113
+ def _opening_line(message: ToolResultMessage) -> str:
114
+ """第一条非空文本行的折叠版本;没有文本时返回空串。"""
115
+ for block in message.content:
116
+ if not isinstance(block, TextContent):
117
+ continue
118
+ for line in block.text.splitlines():
119
+ collapsed = " ".join(line.split())
120
+ if collapsed:
121
+ return collapsed[:OPENING_CHARS]
122
+ return ""
123
+
124
+
125
+ def _replacement_text(message: ToolResultMessage, chars: int) -> str:
126
+ """替换文本:工具名、原体积、开头一行。全部压成一行。"""
127
+ images = sum(1 for block in message.content if isinstance(block, ImageContent))
128
+ parts = [f"[工具结果已清理:{message.tool_name},原文 {chars} 字符"]
129
+ if images:
130
+ parts.append(f",图片 {images} 张")
131
+ parts.append("。")
132
+ opening = _opening_line(message)
133
+ if opening:
134
+ parts.append(f"开头:{opening}。")
135
+ parts.append("需要时重新执行该工具,或读取它落盘的完整输出。]")
136
+ return "".join(parts)
137
+
138
+
139
+ def plan_tool_result_cleanup(
140
+ projection: SessionProjection,
141
+ branch: Sequence[SessionEntry],
142
+ *,
143
+ tokens: int,
144
+ context_window: int,
145
+ settings: ToolResultCleanupSettings,
146
+ ) -> ToolResultCleanupPlan:
147
+ """算出这一轮该清理哪些工具结果。
148
+
149
+ :param projection: 当前请求的投影(``messages`` 已应用既有编辑)。
150
+ :param branch: 活动分支的原始条目,用来确认哪些条目已经被编辑过。
151
+ :param tokens: 投影的当前体积估算。
152
+ :param context_window: 当前模型的上下文窗口;0 表示未声明,此时不清理。
153
+ :param settings: 清理设置。
154
+ """
155
+ if not settings.enabled or context_window <= 0:
156
+ return _EMPTY_PLAN
157
+ if tokens < context_window * settings.trigger_ratio:
158
+ return _EMPTY_PLAN
159
+
160
+ edited = {entry.target_id for entry in branch if isinstance(entry, ContextEditEntry)}
161
+ candidates = [
162
+ item.source_entry
163
+ for item in projection.entries
164
+ if isinstance(item.source_entry, SessionMessageEntry)
165
+ and isinstance(item.source_entry.message, ToolResultMessage)
166
+ # 被省略的条目在投影里没有消息,它们已经不在上下文里了。
167
+ and bool(item.messages)
168
+ and item.source_entry.id not in edited
169
+ ]
170
+
171
+ keep_from = max(len(candidates) - settings.keep_recent, 0)
172
+ targets: list[CleanupTarget] = []
173
+ for entry in candidates[:keep_from]:
174
+ message = entry.message
175
+ assert isinstance(message, ToolResultMessage) # 上面的筛选条件保证了这一点
176
+ if message.is_error:
177
+ continue
178
+ chars = _content_chars(message)
179
+ if chars < settings.min_chars:
180
+ continue
181
+ targets.append(
182
+ CleanupTarget(
183
+ entry_id=entry.id,
184
+ tool_name=message.tool_name,
185
+ chars=chars,
186
+ replacement=_replacement_text(message, chars),
187
+ )
188
+ )
189
+
190
+ if not targets:
191
+ return _EMPTY_PLAN
192
+ return ToolResultCleanupPlan(
193
+ targets=tuple(targets),
194
+ chars_before=sum(target.chars for target in targets),
195
+ chars_after=sum(len(target.replacement) for target in targets),
196
+ )
@@ -0,0 +1,181 @@
1
+ """压缩与分支摘要共用的工具。
2
+
3
+ 三块内容,全是**纯函数**:
4
+
5
+ 1. **文件操作跟踪**:从工具调用里收集 read/write/edit 过哪些路径。摘要末尾
6
+ 附上这两张清单,模型接续工作时才知道"哪些文件的状态是已知的"。
7
+ 跟踪是**累积的**:本次压缩继承上一次压缩的清单(``details`` 里的
8
+ ``readFiles``/``modifiedFiles``),再把新摘要区间里的操作并进去。
9
+ 2. **会话序列化**:把对话压成带 ``[User]:`` / ``[Assistant]:`` 前缀的纯文本,
10
+ 外面包一层 ``<conversation>`` 标签送给摘要请求。目的是让摘要模型把它当
11
+ **材料**读,当对话**续写**——序列化后的文本没有对话轮次结构,模型没法
12
+ 接着编。
13
+ 3. **摘要系统提示词**:与主对话完全无关的一句话人设,禁止续写。
14
+
15
+ 两个刻意的省略:thinking 块不进摘要输入——它常常不在模型的
16
+ 真实上下文里(签名对不上就会被 Provider 丢弃),放进去只会让摘要请求比被
17
+ 摘要的上下文还大;工具结果截到 2000 字符——``read``/``bash`` 的输出是上下文
18
+ 膨胀的主力,但摘要只需要"发生了什么",不需要完整输出。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ from dataclasses import dataclass, field
25
+ from typing import Final
26
+
27
+ from braid_ai.types import (
28
+ AssistantMessage,
29
+ Message,
30
+ TextContent,
31
+ ToolCall,
32
+ ToolResultMessage,
33
+ UserMessage,
34
+ )
35
+ from braid_ai.wire import content_text
36
+ from braid_coding_agent.session.entries import ProjectedMessage
37
+
38
+ __all__ = [
39
+ "SUMMARIZATION_SYSTEM_PROMPT",
40
+ "TOOL_RESULT_MAX_CHARS",
41
+ "FileOperations",
42
+ "compute_file_lists",
43
+ "create_file_ops",
44
+ "extract_file_ops_from_message",
45
+ "format_file_operations",
46
+ "serialize_conversation",
47
+ "truncate_for_summary",
48
+ ]
49
+
50
+ #: 摘要请求的系统提示词。
51
+ SUMMARIZATION_SYSTEM_PROMPT: Final[str] = (
52
+ "You are a context summarization assistant. Your task is to read a conversation "
53
+ "between a user and an AI assistant, then produce a structured summary following "
54
+ "the exact format specified.\n\n"
55
+ "Do NOT continue the conversation. Do NOT respond to any questions in the "
56
+ "conversation. ONLY output the structured summary."
57
+ )
58
+
59
+ #: 序列化时单个工具结果保留的最大字符数。
60
+ TOOL_RESULT_MAX_CHARS: Final[int] = 2000
61
+
62
+
63
+ # ------------------------------------------------------------------ 文件操作跟踪
64
+
65
+
66
+ @dataclass(slots=True)
67
+ class FileOperations:
68
+ """一次压缩覆盖区间内的文件操作集合。
69
+
70
+ ``written``(write 工具)与 ``edited``(edit 工具)分开记,最后合并成
71
+ "修改过";``read`` 减去修改过的才是"只读过"。排序在 :func:`compute_file_lists`
72
+ 统一做,集合本身只负责去重。
73
+ """
74
+
75
+ read: set[str] = field(default_factory=set[str])
76
+ written: set[str] = field(default_factory=set[str])
77
+ edited: set[str] = field(default_factory=set[str])
78
+
79
+
80
+ def create_file_ops() -> FileOperations:
81
+ """空的操作集合,给扩展 API 留的入口。"""
82
+ return FileOperations()
83
+
84
+
85
+ def extract_file_ops_from_message(message: ProjectedMessage, file_ops: FileOperations) -> None:
86
+ """从一条消息里收集文件操作。只认助手消息里的 read/write/edit 工具调用。
87
+
88
+ 其他工具、其他角色直接跳过:路径参数名对不上的工具(比如 grep 的
89
+ ``pattern``)记进来只会污染清单。工具结果里的嵌套调用(codemode 记录)
90
+ 属于"保留但未建模"字段,不参与收集。
91
+ """
92
+ if not isinstance(message, AssistantMessage):
93
+ return
94
+ for block in message.content:
95
+ if not isinstance(block, ToolCall):
96
+ continue
97
+ path = block.arguments.get("path")
98
+ if not isinstance(path, str):
99
+ continue
100
+ if block.name == "read":
101
+ file_ops.read.add(path)
102
+ elif block.name == "write":
103
+ file_ops.written.add(path)
104
+ elif block.name == "edit":
105
+ file_ops.edited.add(path)
106
+
107
+
108
+ def compute_file_lists(file_ops: FileOperations) -> tuple[list[str], list[str]]:
109
+ """归并出 ``(只读过的文件, 修改过的文件)``,各自排序。
110
+
111
+ 一个文件先被 read 后被 edit,应归入"修改过"——读的状态已经被改动覆盖,
112
+ 摘要说它"只读过"会误导接续的模型。
113
+ """
114
+ modified = file_ops.edited | file_ops.written
115
+ read_only = sorted(path for path in file_ops.read if path not in modified)
116
+ return read_only, sorted(modified)
117
+
118
+
119
+ def format_file_operations(read_files: list[str], modified_files: list[str]) -> str:
120
+ """把两张清单格式化成摘要末尾的 XML 段。两张都空时返回空串(不加空标签)。"""
121
+ sections: list[str] = []
122
+ if read_files:
123
+ sections.append("<read-files>\n" + "\n".join(read_files) + "\n</read-files>")
124
+ if modified_files:
125
+ sections.append("<modified-files>\n" + "\n".join(modified_files) + "\n</modified-files>")
126
+ if not sections:
127
+ return ""
128
+ return "\n\n" + "\n\n".join(sections)
129
+
130
+
131
+ # ------------------------------------------------------------------ 会话序列化
132
+
133
+
134
+ def truncate_for_summary(text: str, max_chars: int) -> str:
135
+ """截断到 ``max_chars`` 并注明截掉了多少。保留开头:工具输出的开头通常是
136
+ 命令回显与首屏结果,尾部才是截断提示该出现的地方。"""
137
+ if len(text) <= max_chars:
138
+ return text
139
+ truncated = len(text) - max_chars
140
+ return f"{text[:max_chars]}\n\n[... {truncated} more characters truncated]"
141
+
142
+
143
+ def _json(value: object) -> str:
144
+ """紧凑 JSON(不转义非 ASCII)。"""
145
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
146
+
147
+
148
+ def serialize_conversation(messages: list[Message]) -> str:
149
+ """把 LLM 消息序列化成带角色前缀的纯文本。
150
+
151
+ 入参必须先过 :func:`braid_coding_agent.messages.convert_to_llm`:这里只认四种
152
+ LLM 角色,custom/摘要等自定义角色的展开规则不在本函数。前缀写法以黄金测试为准。
153
+ """
154
+ parts: list[str] = []
155
+ for message in messages:
156
+ match message:
157
+ case UserMessage():
158
+ text = content_text(message.content, "")
159
+ if text:
160
+ parts.append(f"[User]: {text}")
161
+ case AssistantMessage():
162
+ tool_calls: list[str] = []
163
+ for block in message.content:
164
+ if isinstance(block, ToolCall):
165
+ args_text = ", ".join(
166
+ f"{key}={_json(item)}" for key, item in block.arguments.items()
167
+ )
168
+ tool_calls.append(f"{block.name}({args_text})")
169
+ if any(isinstance(block, TextContent) for block in message.content):
170
+ parts.append(f"[Assistant]: {content_text(message.content)}")
171
+ if tool_calls:
172
+ parts.append("[Assistant tool calls]: " + "; ".join(tool_calls))
173
+ case ToolResultMessage():
174
+ text = content_text(message.content, "")
175
+ if text:
176
+ parts.append(
177
+ f"[Tool result]: {truncate_for_summary(text, TOOL_RESULT_MAX_CHARS)}"
178
+ )
179
+ case _:
180
+ continue
181
+ return "\n\n".join(parts)