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,430 @@
|
|
|
1
|
+
"""压缩的准备阶段:算出"从哪里切、摘要哪些、保留哪些"。
|
|
2
|
+
|
|
3
|
+
这是整个压缩系统里最讲究的部分——**切错位置的代价是模型
|
|
4
|
+
看到一段无法解释的上下文**:
|
|
5
|
+
|
|
6
|
+
- 切在 toolResult 后面:结果和它的工具调用分了家,Provider 直接拒绝请求;
|
|
7
|
+
- 切进一个 user 消息引领的区间中间(split turn):那一轮工作还没做完就被
|
|
8
|
+
摘掉了,必须额外生成一段"回合前缀摘要"垫在被保留的消息前面;
|
|
9
|
+
- 切点后面跟着一串被省略的失败尝试:它们虽然不可见,
|
|
10
|
+
但作为"恢复痕迹"应该跟着被摘要区间一起划走。
|
|
11
|
+
|
|
12
|
+
所有判断都在**投影**(:func:`~braid_coding_agent.session.projection.build_session_projection`)
|
|
13
|
+
上做,不在原始条目上做:被 context_edit 省略的条目在投影里贡献零条消息,
|
|
14
|
+
切点与体积估算自然跳过它们——"模型看不到的东西不参与压缩决策"。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Final
|
|
21
|
+
|
|
22
|
+
from braid_ai.transcript import get_current_system_message
|
|
23
|
+
from braid_ai.types import AssistantMessage, SystemMessage, ToolResultMessage, UserMessage
|
|
24
|
+
from braid_coding_agent.compaction.tokens import (
|
|
25
|
+
ContextUsageEstimate,
|
|
26
|
+
estimate_context_tokens,
|
|
27
|
+
estimate_tokens,
|
|
28
|
+
)
|
|
29
|
+
from braid_coding_agent.compaction.tool_results import ToolResultCleanupSettings
|
|
30
|
+
from braid_coding_agent.compaction.utils import (
|
|
31
|
+
FileOperations,
|
|
32
|
+
create_file_ops,
|
|
33
|
+
extract_file_ops_from_message,
|
|
34
|
+
)
|
|
35
|
+
from braid_coding_agent.session.entries import (
|
|
36
|
+
BranchSummaryMessage,
|
|
37
|
+
CompactionEntry,
|
|
38
|
+
CompactionSummaryMessage,
|
|
39
|
+
ContextEditEntry,
|
|
40
|
+
CustomMessage,
|
|
41
|
+
ProjectedMessage,
|
|
42
|
+
SessionEntry,
|
|
43
|
+
SessionMessageEntry,
|
|
44
|
+
session_entry_to_context_messages,
|
|
45
|
+
)
|
|
46
|
+
from braid_coding_agent.session.projection import (
|
|
47
|
+
ProjectedSessionEntry,
|
|
48
|
+
SessionProjection,
|
|
49
|
+
build_session_projection,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"DEFAULT_COMPACTION_SETTINGS",
|
|
54
|
+
"CompactionPreparation",
|
|
55
|
+
"CompactionSettings",
|
|
56
|
+
"CutPointResult",
|
|
57
|
+
"estimate_projected_context_tokens",
|
|
58
|
+
"extract_file_operations",
|
|
59
|
+
"find_cut_point",
|
|
60
|
+
"find_turn_start_index",
|
|
61
|
+
"prepare_compaction",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(slots=True)
|
|
66
|
+
class CompactionSettings:
|
|
67
|
+
"""压缩设置。
|
|
68
|
+
|
|
69
|
+
``enabled`` 关掉整个自动上下文处理:阈值检查、溢出恢复与工具结果清理。手动
|
|
70
|
+
``/compact`` 不受它约束——用户明确要求压缩时,"配置里关了自动压缩"不构成拒绝理由。
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
enabled: bool = True
|
|
74
|
+
#: 给生成预留的空闲 token。触发线是 ``window - reserve_tokens``。
|
|
75
|
+
reserve_tokens: int = 16_384
|
|
76
|
+
#: 压缩时从尾部保留的最近 token 数。
|
|
77
|
+
keep_recent_tokens: int = 20_000
|
|
78
|
+
#: 工具结果清理:替换更早的大块结果,不动对话。见 :mod:`.tool_results`。
|
|
79
|
+
tool_results: ToolResultCleanupSettings = field(default_factory=ToolResultCleanupSettings)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
#: 默认压缩设置:
|
|
83
|
+
#: 保留 16384 token 的生成余量,压缩时从尾部保留最近 20000 token。
|
|
84
|
+
DEFAULT_COMPACTION_SETTINGS: Final[CompactionSettings] = CompactionSettings()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------------ 角色判定
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _is_cut_point_message(message: ProjectedMessage) -> bool:
|
|
91
|
+
"""能否切在这条消息前面。toolResult 永远不行(必须跟着它的工具调用),
|
|
92
|
+
system 也不行(提示词状态不是对话轮次);其余角色都可以。"""
|
|
93
|
+
return not isinstance(message, (SystemMessage, ToolResultMessage))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _is_turn_start_message(message: ProjectedMessage) -> bool:
|
|
97
|
+
"""是否开启一个新回合:user、custom、两类摘要都可以;assistant 与
|
|
98
|
+
toolResult 都是上一回合的延续。"""
|
|
99
|
+
return isinstance(
|
|
100
|
+
message, (UserMessage, CustomMessage, BranchSummaryMessage, CompactionSummaryMessage)
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _is_turn_start_entry(item: ProjectedSessionEntry) -> bool:
|
|
105
|
+
"""一个投影条目是否开启回合。压缩条目本身不算:它代表"被概括的历史",
|
|
106
|
+
切在它前面等于把摘要也摘要一遍。"""
|
|
107
|
+
if isinstance(item.source_entry, CompactionEntry):
|
|
108
|
+
return False
|
|
109
|
+
return any(_is_turn_start_message(message) for message in item.messages)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def find_turn_start_index(
|
|
113
|
+
entries: list[ProjectedSessionEntry], entry_index: int, start_index: int
|
|
114
|
+
) -> int:
|
|
115
|
+
"""从 ``entry_index`` 往回找开启所在回合的条目;找不到返回 -1。"""
|
|
116
|
+
for index in range(entry_index, start_index - 1, -1):
|
|
117
|
+
if _is_turn_start_entry(entries[index]):
|
|
118
|
+
return index
|
|
119
|
+
return -1
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(slots=True)
|
|
123
|
+
class CutPointResult:
|
|
124
|
+
"""切点查找结果。
|
|
125
|
+
|
|
126
|
+
``first_kept_entry_index`` 是保留区间的第一条;``turn_start_index`` 只在
|
|
127
|
+
split turn 时有效(被切断回合的起点);``is_split_turn`` 表示切点落在了
|
|
128
|
+
一个回合中间。
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
first_kept_entry_index: int
|
|
132
|
+
turn_start_index: int
|
|
133
|
+
is_split_turn: bool
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def find_cut_point(
|
|
137
|
+
entries: list[ProjectedSessionEntry],
|
|
138
|
+
start_index: int,
|
|
139
|
+
end_index: int,
|
|
140
|
+
keep_recent_tokens: int,
|
|
141
|
+
) -> CutPointResult:
|
|
142
|
+
"""在投影条目的 ``[start_index, end_index)`` 区间里找保留边界。
|
|
143
|
+
|
|
144
|
+
算法:从最新往回累计每条的消息体积,累计到 ``keep_recent_tokens`` 时停下,
|
|
145
|
+
切在"该条目或其后最近的合法切点"上。三个细节都有真实场景撑着:
|
|
146
|
+
|
|
147
|
+
- **默认切在第一个合法切点**(而不是区间开头):累计完还没超预算说明整个
|
|
148
|
+
区间都该保留,但"第一个切点"之前的头部(通常是系统消息)仍然会被摘要——
|
|
149
|
+
实际上摘要输入过滤掉 system 后为空,:func:`prepare_compaction` 会因此
|
|
150
|
+
判定"没什么可压缩"返回 ``None``;
|
|
151
|
+
- **尾部全是被省略的失败尝试时前移一格**(recovery omission suffix):
|
|
152
|
+
省略掉的重试残留不该被划进保留区;
|
|
153
|
+
- **切点前的一串零贡献条目(label、usage 等元数据)一并划入保留区**:
|
|
154
|
+
它们不影响上下文,跟哪边都不产生语义差别,跟保留区走少动切点。
|
|
155
|
+
"""
|
|
156
|
+
cut_points = [
|
|
157
|
+
index
|
|
158
|
+
for index in range(start_index, end_index)
|
|
159
|
+
if not isinstance(entries[index].source_entry, CompactionEntry)
|
|
160
|
+
and any(_is_cut_point_message(message) for message in entries[index].messages)
|
|
161
|
+
]
|
|
162
|
+
if not cut_points:
|
|
163
|
+
return CutPointResult(
|
|
164
|
+
first_kept_entry_index=start_index, turn_start_index=-1, is_split_turn=False
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
accumulated = 0
|
|
168
|
+
exceeded_budget = False
|
|
169
|
+
cut_index = cut_points[0]
|
|
170
|
+
for index in range(end_index - 1, start_index - 1, -1):
|
|
171
|
+
message_tokens = sum(estimate_tokens(message) for message in entries[index].messages)
|
|
172
|
+
if message_tokens == 0:
|
|
173
|
+
continue
|
|
174
|
+
accumulated += message_tokens
|
|
175
|
+
if accumulated >= keep_recent_tokens:
|
|
176
|
+
exceeded_budget = True
|
|
177
|
+
# 该条目本身可能不是合法切点(比如尾部 toolResult 单独超预算):
|
|
178
|
+
# 取它或其后最近的切点,实在没有就取最后一个切点。
|
|
179
|
+
cut_index = next(
|
|
180
|
+
(candidate for candidate in cut_points if candidate >= index), cut_points[-1]
|
|
181
|
+
)
|
|
182
|
+
break
|
|
183
|
+
|
|
184
|
+
# 恢复省略的尾缀整体前移:省略的失败尝试 + 它们的 omission 编辑一起划走。
|
|
185
|
+
suffix = entries[cut_index + 1 : end_index]
|
|
186
|
+
|
|
187
|
+
def _intrinsically_visible(item: ProjectedSessionEntry) -> bool:
|
|
188
|
+
return not isinstance(item.source_entry, ContextEditEntry) and bool(
|
|
189
|
+
session_entry_to_context_messages(item.source_entry)
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
def _omitted(item: ProjectedSessionEntry) -> bool:
|
|
193
|
+
return _intrinsically_visible(item) and not item.messages
|
|
194
|
+
|
|
195
|
+
omitted_ids = {item.source_entry.id for item in suffix if _omitted(item)}
|
|
196
|
+
has_external_replacement = any(
|
|
197
|
+
isinstance(item.source_entry, ContextEditEntry)
|
|
198
|
+
and item.source_entry.replacement is not None
|
|
199
|
+
and item.source_entry.target_id not in omitted_ids
|
|
200
|
+
for item in suffix
|
|
201
|
+
)
|
|
202
|
+
is_recovery_omission_suffix = (
|
|
203
|
+
exceeded_budget
|
|
204
|
+
and not has_external_replacement
|
|
205
|
+
and any(
|
|
206
|
+
isinstance(item.source_entry, SessionMessageEntry)
|
|
207
|
+
and isinstance(item.source_entry.message, AssistantMessage)
|
|
208
|
+
and _omitted(item)
|
|
209
|
+
for item in suffix
|
|
210
|
+
)
|
|
211
|
+
and all(
|
|
212
|
+
not isinstance(item.source_entry, CompactionEntry)
|
|
213
|
+
and (not _intrinsically_visible(item) or _omitted(item))
|
|
214
|
+
for item in suffix
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
if is_recovery_omission_suffix:
|
|
218
|
+
cut_index += 1
|
|
219
|
+
|
|
220
|
+
# 切点前的零贡献元数据条目归入保留区,切点保持贴着可见内容。
|
|
221
|
+
while cut_index > start_index:
|
|
222
|
+
previous = entries[cut_index - 1]
|
|
223
|
+
if isinstance(previous.source_entry, CompactionEntry) or previous.messages:
|
|
224
|
+
break
|
|
225
|
+
cut_index -= 1
|
|
226
|
+
|
|
227
|
+
starts_turn = _is_turn_start_entry(entries[cut_index])
|
|
228
|
+
turn_start_index = -1 if starts_turn else find_turn_start_index(entries, cut_index, start_index)
|
|
229
|
+
return CutPointResult(
|
|
230
|
+
first_kept_entry_index=cut_index,
|
|
231
|
+
turn_start_index=turn_start_index,
|
|
232
|
+
is_split_turn=not starts_turn and turn_start_index != -1,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ------------------------------------------------------------------ 投影体积
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def estimate_projected_context_tokens(
|
|
240
|
+
projection: SessionProjection, branch_entries: list[SessionEntry]
|
|
241
|
+
) -> ContextUsageEstimate:
|
|
242
|
+
"""带投影校正的上下文体积估算。
|
|
243
|
+
|
|
244
|
+
普通估算信任最后一条助手消息的 usage;但那之后的 context_edit / 压缩
|
|
245
|
+
改变了上下文,旧 usage 描述的是"编辑前"的世界,继续信它会得出错误的
|
|
246
|
+
触发判断(比如刚压缩完立刻又触发一次)。所以:usage 来源条目比最近一次
|
|
247
|
+
失效性条目(context_edit/compaction)旧时,退回纯字符估算。
|
|
248
|
+
"""
|
|
249
|
+
estimate = estimate_context_tokens(projection.messages)
|
|
250
|
+
if estimate.last_usage_index is not None:
|
|
251
|
+
projected_message_index = 0
|
|
252
|
+
usage_entry_id: str | None = None
|
|
253
|
+
for item in projection.entries:
|
|
254
|
+
next_index = projected_message_index + len(item.messages)
|
|
255
|
+
if estimate.last_usage_index < next_index:
|
|
256
|
+
usage_entry_id = item.source_entry.id
|
|
257
|
+
break
|
|
258
|
+
projected_message_index = next_index
|
|
259
|
+
|
|
260
|
+
usage_entry_index = -1
|
|
261
|
+
if usage_entry_id is not None:
|
|
262
|
+
for index, entry in enumerate(branch_entries):
|
|
263
|
+
if entry.id == usage_entry_id:
|
|
264
|
+
usage_entry_index = index
|
|
265
|
+
break
|
|
266
|
+
latest_invalidating = -1
|
|
267
|
+
for index in range(len(branch_entries) - 1, -1, -1):
|
|
268
|
+
if isinstance(branch_entries[index], (ContextEditEntry, CompactionEntry)):
|
|
269
|
+
latest_invalidating = index
|
|
270
|
+
break
|
|
271
|
+
if usage_entry_index > latest_invalidating:
|
|
272
|
+
return estimate
|
|
273
|
+
|
|
274
|
+
current_system = get_current_system_message(projection.messages) # type: ignore[arg-type]
|
|
275
|
+
tokens = estimate_tokens(current_system) if current_system is not None else 0
|
|
276
|
+
for message in projection.messages:
|
|
277
|
+
if not isinstance(message, SystemMessage):
|
|
278
|
+
tokens += estimate_tokens(message)
|
|
279
|
+
return ContextUsageEstimate(
|
|
280
|
+
tokens=tokens, usage_tokens=0, trailing_tokens=tokens, last_usage_index=None
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# ------------------------------------------------------------------ 准备结果
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _messages_for_compaction(item: ProjectedSessionEntry) -> list[ProjectedMessage]:
|
|
288
|
+
"""一个投影条目对摘要输入的贡献。压缩条目贡献零条(它的摘要已经在
|
|
289
|
+
``previous_summary`` 里),系统消息剔除(提示词状态不进摘要)。"""
|
|
290
|
+
if isinstance(item.source_entry, CompactionEntry):
|
|
291
|
+
return []
|
|
292
|
+
return [message for message in item.messages if not isinstance(message, SystemMessage)]
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def extract_file_operations(
|
|
296
|
+
messages: list[ProjectedMessage], entries: list[SessionEntry], prev_compaction_index: int
|
|
297
|
+
) -> FileOperations:
|
|
298
|
+
"""收集摘要区间的文件操作:继承上一次压缩的清单,再并入本次区间的新操作。
|
|
299
|
+
|
|
300
|
+
只有内建压缩(``from_hook`` 为假)才继承:扩展写的 ``details``
|
|
301
|
+
是它自己的格式,乱读会把扩展数据当文件路径。
|
|
302
|
+
"""
|
|
303
|
+
file_ops = create_file_ops()
|
|
304
|
+
if 0 <= prev_compaction_index < len(entries):
|
|
305
|
+
previous = entries[prev_compaction_index]
|
|
306
|
+
if (
|
|
307
|
+
isinstance(previous, CompactionEntry)
|
|
308
|
+
and not previous.from_hook
|
|
309
|
+
and isinstance(previous.details, dict)
|
|
310
|
+
):
|
|
311
|
+
read_files = previous.details.get("readFiles")
|
|
312
|
+
modified_files = previous.details.get("modifiedFiles")
|
|
313
|
+
if isinstance(read_files, list):
|
|
314
|
+
file_ops.read.update(path for path in read_files if isinstance(path, str))
|
|
315
|
+
if isinstance(modified_files, list):
|
|
316
|
+
file_ops.edited.update(path for path in modified_files if isinstance(path, str))
|
|
317
|
+
for message in messages:
|
|
318
|
+
extract_file_ops_from_message(message, file_ops)
|
|
319
|
+
return file_ops
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@dataclass(slots=True)
|
|
323
|
+
class CompactionPreparation:
|
|
324
|
+
"""一次压缩的全部输入:摘要什么、保留什么、从哪继续。
|
|
325
|
+
|
|
326
|
+
这是压缩的**唯一**决策产物:纯数据、可序列化、可以被扩展检查或覆盖
|
|
327
|
+
(``session_before_compact`` 钩子拿到的就是它)。
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
#: 保留区间的第一条条目 id。会话里找不到时退回"压缩条目的下一条"。
|
|
331
|
+
first_kept_entry_id: str
|
|
332
|
+
#: 要被摘要并离开上下文的消息。
|
|
333
|
+
messages_to_summarize: list[ProjectedMessage]
|
|
334
|
+
#: split turn 时,被切断回合的前缀消息(单独摘要后垫在保留消息前面)。
|
|
335
|
+
turn_prefix_messages: list[ProjectedMessage]
|
|
336
|
+
#: 切点是否落在一个回合中间。
|
|
337
|
+
is_split_turn: bool
|
|
338
|
+
#: 压缩前的上下文体积估算。
|
|
339
|
+
tokens_before: int
|
|
340
|
+
#: 上一次压缩的摘要。存在时走"增量更新"摘要提示词。
|
|
341
|
+
previous_summary: str | None = None
|
|
342
|
+
#: 区间内累积的文件操作。
|
|
343
|
+
file_ops: FileOperations = field(default_factory=FileOperations)
|
|
344
|
+
#: 本次压缩生效的设置(模型覆盖解析之后的最终值)。
|
|
345
|
+
settings: CompactionSettings = field(default_factory=CompactionSettings)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def prepare_compaction(
|
|
349
|
+
path_entries: list[SessionEntry], settings: CompactionSettings
|
|
350
|
+
) -> CompactionPreparation | None:
|
|
351
|
+
"""为当前分支准备一次压缩。没什么可压缩时返回 ``None``。
|
|
352
|
+
|
|
353
|
+
返回 ``None`` 的三种情形(上层据此区分报错文案):
|
|
354
|
+
|
|
355
|
+
- 最后一条已经是压缩条目("Already compacted");
|
|
356
|
+
- 投影里没有任何切点(空会话 / 只有系统消息);
|
|
357
|
+
- 摘要输入与回合前缀都为空("session too small")。
|
|
358
|
+
"""
|
|
359
|
+
if path_entries and isinstance(path_entries[-1], CompactionEntry):
|
|
360
|
+
return None
|
|
361
|
+
|
|
362
|
+
projection = build_session_projection(path_entries)
|
|
363
|
+
projected = projection.entries
|
|
364
|
+
source_entries = [item.source_entry for item in projected]
|
|
365
|
+
# 最新压缩在投影里排第一;更早的压缩条目即使还留在保留区间里,投影贡献也是零。
|
|
366
|
+
prev_compaction_index = next(
|
|
367
|
+
(
|
|
368
|
+
index
|
|
369
|
+
for index, item in enumerate(projected)
|
|
370
|
+
if isinstance(item.source_entry, CompactionEntry) and item.messages
|
|
371
|
+
),
|
|
372
|
+
-1,
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
previous_summary: str | None = None
|
|
376
|
+
boundary_start = 0
|
|
377
|
+
if prev_compaction_index >= 0:
|
|
378
|
+
source = projected[prev_compaction_index].source_entry
|
|
379
|
+
assert isinstance(source, CompactionEntry) # 上面的筛选条件保证了这一点
|
|
380
|
+
previous_summary = source.summary
|
|
381
|
+
# 投影已经替我们选好了上次压缩保留的尾部:摘要从它的下一条开始,
|
|
382
|
+
# 上次幸存的消息会再次进入这次摘要——摘要因此是累积的。
|
|
383
|
+
boundary_start = prev_compaction_index + 1
|
|
384
|
+
boundary_end = len(projected)
|
|
385
|
+
|
|
386
|
+
tokens_before = estimate_projected_context_tokens(projection, path_entries).tokens
|
|
387
|
+
cut_point = find_cut_point(projected, boundary_start, boundary_end, settings.keep_recent_tokens)
|
|
388
|
+
|
|
389
|
+
if cut_point.first_kept_entry_index >= len(projected):
|
|
390
|
+
return None
|
|
391
|
+
first_kept_entry = projected[cut_point.first_kept_entry_index].source_entry
|
|
392
|
+
if not first_kept_entry.id:
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
history_end = (
|
|
396
|
+
cut_point.turn_start_index if cut_point.is_split_turn else cut_point.first_kept_entry_index
|
|
397
|
+
)
|
|
398
|
+
messages_to_summarize = [
|
|
399
|
+
message
|
|
400
|
+
for item in projected[boundary_start:history_end]
|
|
401
|
+
for message in _messages_for_compaction(item)
|
|
402
|
+
]
|
|
403
|
+
turn_prefix_messages = (
|
|
404
|
+
[
|
|
405
|
+
message
|
|
406
|
+
for item in projected[cut_point.turn_start_index : cut_point.first_kept_entry_index]
|
|
407
|
+
for message in _messages_for_compaction(item)
|
|
408
|
+
]
|
|
409
|
+
if cut_point.is_split_turn
|
|
410
|
+
else []
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
if not messages_to_summarize and not turn_prefix_messages:
|
|
414
|
+
return None
|
|
415
|
+
|
|
416
|
+
file_ops = extract_file_operations(messages_to_summarize, source_entries, prev_compaction_index)
|
|
417
|
+
if cut_point.is_split_turn:
|
|
418
|
+
for message in turn_prefix_messages:
|
|
419
|
+
extract_file_ops_from_message(message, file_ops)
|
|
420
|
+
|
|
421
|
+
return CompactionPreparation(
|
|
422
|
+
first_kept_entry_id=first_kept_entry.id,
|
|
423
|
+
messages_to_summarize=messages_to_summarize,
|
|
424
|
+
turn_prefix_messages=turn_prefix_messages,
|
|
425
|
+
is_split_turn=cut_point.is_split_turn,
|
|
426
|
+
tokens_before=tokens_before,
|
|
427
|
+
previous_summary=previous_summary,
|
|
428
|
+
file_ops=file_ops,
|
|
429
|
+
settings=settings,
|
|
430
|
+
)
|