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,542 @@
|
|
|
1
|
+
"""摘要的生成与压缩主流程。
|
|
2
|
+
|
|
3
|
+
压缩 = 准备(:mod:`.prepare`,纯计算)+ 摘要(本模块,一次或两次 LLM 调用)+
|
|
4
|
+
落盘(会话层,:meth:`SessionManager.append_compaction`)。本模块回答三个问题:
|
|
5
|
+
|
|
6
|
+
1. **摘要请求长什么样**:系统提示词禁止续写;用户消息是
|
|
7
|
+
``<conversation>``(序列化的历史)+ 可选 ``<previous-summary>`` + 结构化
|
|
8
|
+
格式要求。格式(Goal / Constraints / Progress / Key Decisions / Next Steps /
|
|
9
|
+
Critical Context)是**模型侧的协议**——下游的消费方是"下一次请求里的模型",
|
|
10
|
+
固定格式让它能可靠地找到"接下来做什么"。
|
|
11
|
+
2. **重复压缩怎么合并**:有 ``previous_summary`` 时换用"增量更新"提示词——
|
|
12
|
+
保留旧信息、并入新进展。两次压缩各自摘要全量历史会让旧信息在两次改写中
|
|
13
|
+
漂移,增量更新只改该改的部分。
|
|
14
|
+
3. **失败怎么界定**:``error`` 与 ``length`` 的响应不能当检查点(前者没有
|
|
15
|
+
内容,后者是半截文本);试图调用工具的响应同样是废品。三者都抛
|
|
16
|
+
:class:`SummarizationError`,由调用方决定放弃——**失败的压缩不写条目,
|
|
17
|
+
会话保持原样**。
|
|
18
|
+
|
|
19
|
+
split turn(切点落在一个回合中间)会发**两次**摘要请求:历史一份、被切断的
|
|
20
|
+
回合前缀一份,格式不同(前缀摘要只回答"用户要什么、做到哪了"),最后用
|
|
21
|
+
固定分隔符合并成一条。
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Final, cast
|
|
29
|
+
|
|
30
|
+
from braid_agent.types import StreamFn
|
|
31
|
+
from braid_ai.cancel import CancelToken
|
|
32
|
+
from braid_ai.retry import RetryCallbacks, RetryPolicy, retry_assistant_call
|
|
33
|
+
from braid_ai.types import (
|
|
34
|
+
AssistantMessage,
|
|
35
|
+
JsonValue,
|
|
36
|
+
Model,
|
|
37
|
+
SimpleStreamOptions,
|
|
38
|
+
SystemMessage,
|
|
39
|
+
TextContent,
|
|
40
|
+
TranscriptContext,
|
|
41
|
+
Usage,
|
|
42
|
+
UserMessage,
|
|
43
|
+
)
|
|
44
|
+
from braid_ai.utils.clock import Clock, SystemClock
|
|
45
|
+
from braid_ai.wire import content_text
|
|
46
|
+
from braid_coding_agent.compaction.prepare import CompactionPreparation
|
|
47
|
+
from braid_coding_agent.compaction.utils import (
|
|
48
|
+
SUMMARIZATION_SYSTEM_PROMPT,
|
|
49
|
+
compute_file_lists,
|
|
50
|
+
format_file_operations,
|
|
51
|
+
serialize_conversation,
|
|
52
|
+
)
|
|
53
|
+
from braid_coding_agent.messages import convert_to_llm
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"SUMMARIZATION_PROMPT",
|
|
57
|
+
"TURN_PREFIX_SUMMARIZATION_PROMPT",
|
|
58
|
+
"UPDATE_SUMMARIZATION_PROMPT",
|
|
59
|
+
"CompactionResult",
|
|
60
|
+
"SummarizationError",
|
|
61
|
+
"SummaryWithUsage",
|
|
62
|
+
"compact",
|
|
63
|
+
"complete_summarization",
|
|
64
|
+
"generate_summary",
|
|
65
|
+
"generate_summary_with_usage",
|
|
66
|
+
"get_summarization_failure",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
#: 首次摘要的用户提示词。
|
|
70
|
+
SUMMARIZATION_PROMPT: Final[
|
|
71
|
+
str
|
|
72
|
+
] = """The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
73
|
+
|
|
74
|
+
Use this EXACT format:
|
|
75
|
+
|
|
76
|
+
## Goal
|
|
77
|
+
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
78
|
+
|
|
79
|
+
## Constraints & Preferences
|
|
80
|
+
- [Any constraints, preferences, or requirements mentioned by user]
|
|
81
|
+
- [Or "(none)" if none were mentioned]
|
|
82
|
+
|
|
83
|
+
## Progress
|
|
84
|
+
### Done
|
|
85
|
+
- [x] [Completed tasks/changes]
|
|
86
|
+
|
|
87
|
+
### In Progress
|
|
88
|
+
- [ ] [Current work]
|
|
89
|
+
|
|
90
|
+
### Blocked
|
|
91
|
+
- [Issues preventing progress, if any]
|
|
92
|
+
|
|
93
|
+
## Key Decisions
|
|
94
|
+
- **[Decision]**: [Brief rationale]
|
|
95
|
+
|
|
96
|
+
## Next Steps
|
|
97
|
+
1. [Ordered list of what should happen next]
|
|
98
|
+
|
|
99
|
+
## Critical Context
|
|
100
|
+
- [Any data, examples, or references needed to continue]
|
|
101
|
+
- [Or "(none)" if not applicable]
|
|
102
|
+
|
|
103
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages."""
|
|
104
|
+
|
|
105
|
+
#: 重复压缩时的更新指令(嵌在 ``UPDATE_SUMMARIZATION_PROMPT`` 里)。
|
|
106
|
+
_UPDATE_SUMMARIZATION_INSTRUCTIONS: Final[
|
|
107
|
+
str
|
|
108
|
+
] = """Update the existing structured summary with new information. RULES:
|
|
109
|
+
- PRESERVE all existing information from the previous summary
|
|
110
|
+
- ADD new progress, decisions, and context from the new messages
|
|
111
|
+
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
112
|
+
- UPDATE "Next Steps" based on what was accomplished
|
|
113
|
+
- PRESERVE exact file paths, function names, and error messages
|
|
114
|
+
- If something is no longer relevant, you may remove it
|
|
115
|
+
|
|
116
|
+
Use this EXACT format:
|
|
117
|
+
|
|
118
|
+
## Goal
|
|
119
|
+
[Preserve existing goals, add new ones if the task expanded]
|
|
120
|
+
|
|
121
|
+
## Constraints & Preferences
|
|
122
|
+
- [Preserve existing, add new ones discovered]
|
|
123
|
+
|
|
124
|
+
## Progress
|
|
125
|
+
### Done
|
|
126
|
+
- [x] [Include previously done items AND newly completed items]
|
|
127
|
+
|
|
128
|
+
### In Progress
|
|
129
|
+
- [ ] [Current work - update based on progress]
|
|
130
|
+
|
|
131
|
+
### Blocked
|
|
132
|
+
- [Current blockers - remove if resolved]
|
|
133
|
+
|
|
134
|
+
## Key Decisions
|
|
135
|
+
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
|
|
136
|
+
|
|
137
|
+
## Next Steps
|
|
138
|
+
1. [Update based on current state]
|
|
139
|
+
|
|
140
|
+
## Critical Context
|
|
141
|
+
- [Preserve important context, add new if needed]
|
|
142
|
+
|
|
143
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages."""
|
|
144
|
+
|
|
145
|
+
#: 重复压缩的用户提示词。
|
|
146
|
+
UPDATE_SUMMARIZATION_PROMPT: Final[str] = (
|
|
147
|
+
"The messages above are NEW conversation messages to incorporate into the existing "
|
|
148
|
+
"summary provided in <previous-summary> tags.\n\n" + _UPDATE_SUMMARIZATION_INSTRUCTIONS
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
#: split turn 时,被切断回合前缀的摘要提示词。
|
|
152
|
+
TURN_PREFIX_SUMMARIZATION_PROMPT: Final[
|
|
153
|
+
str
|
|
154
|
+
] = """The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
|
|
155
|
+
|
|
156
|
+
Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
|
|
157
|
+
|
|
158
|
+
## Original Request
|
|
159
|
+
[What did the user ask for?]
|
|
160
|
+
|
|
161
|
+
## Progress So Far
|
|
162
|
+
- [Key decisions and work completed in these messages]
|
|
163
|
+
|
|
164
|
+
## Context Needed to Continue
|
|
165
|
+
- [Information from these messages needed to understand the later work]
|
|
166
|
+
|
|
167
|
+
Only summarize information explicitly present above. Do not infer or recreate later messages."""
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class SummarizationError(RuntimeError):
|
|
171
|
+
"""摘要响应不可用:error / length / 试图调用工具。压缩流程会就地失败,
|
|
172
|
+
上层保证此时不写任何会话条目。"""
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(slots=True)
|
|
176
|
+
class SummaryWithUsage:
|
|
177
|
+
"""摘要文本 + 生成它的那次调用的用量。用量进压缩条目,会话总账才完整。"""
|
|
178
|
+
|
|
179
|
+
text: str
|
|
180
|
+
usage: Usage
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(slots=True)
|
|
184
|
+
class CompactionResult:
|
|
185
|
+
"""一次压缩的产出,:meth:`SessionManager.append_compaction` 的输入。
|
|
186
|
+
|
|
187
|
+
``details`` 的键是 camelCase(``readFiles``/``modifiedFiles``):它原样
|
|
188
|
+
写进会话文件,键名跟着 wire 约定走。
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
summary: str
|
|
192
|
+
first_kept_entry_id: str
|
|
193
|
+
tokens_before: int
|
|
194
|
+
estimated_tokens_after: int | None = None
|
|
195
|
+
usage: Usage | None = None
|
|
196
|
+
details: JsonValue | None = None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def get_summarization_failure(response: AssistantMessage, label: str) -> str | None:
|
|
200
|
+
"""响应能否作为检查点持久化。不能时返回失败原因,能时返回 ``None``。
|
|
201
|
+
|
|
202
|
+
``length`` 停止的响应带着半截文本,存成检查点会污染后续每一次请求;
|
|
203
|
+
这与主对话的处理不同——主对话里 ``length`` 是一条普通的助手消息,
|
|
204
|
+
这里它是**要被反复重放的摘要**,标准必须更严。
|
|
205
|
+
"""
|
|
206
|
+
if response.stop_reason == "error":
|
|
207
|
+
return f"{label} failed: {response.error_message or 'Unknown error'}"
|
|
208
|
+
if response.stop_reason == "length":
|
|
209
|
+
return f"{label} failed: generation hit the token cap and the summary is incomplete"
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _summarization_options(
|
|
214
|
+
model: Model,
|
|
215
|
+
api_key: str | None,
|
|
216
|
+
headers: dict[str, str] | None,
|
|
217
|
+
signal: CancelToken | None,
|
|
218
|
+
thinking_level: str | None,
|
|
219
|
+
) -> SimpleStreamOptions:
|
|
220
|
+
"""摘要请求的选项。不设 ``max_tokens``:摘要用模型自己的输出上限,
|
|
221
|
+
设小了摘要会被截成废品。
|
|
222
|
+
|
|
223
|
+
``cache_breakpoints=()`` 关掉提示词缓存断点:这是一次性请求,写进缓存只会多付
|
|
224
|
+
一笔缓存写费用,而它写的那段前缀(系统提示词 + 单条摘要指令)以后不会再被读到。
|
|
225
|
+
"""
|
|
226
|
+
options = SimpleStreamOptions(
|
|
227
|
+
signal=signal, api_key=api_key, headers=headers, cache_breakpoints=()
|
|
228
|
+
)
|
|
229
|
+
if model.reasoning and thinking_level and thinking_level != "off":
|
|
230
|
+
options.reasoning = thinking_level # type: ignore[assignment]
|
|
231
|
+
return options
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def complete_summarization(
|
|
235
|
+
model: Model,
|
|
236
|
+
context: TranscriptContext,
|
|
237
|
+
options: SimpleStreamOptions,
|
|
238
|
+
stream_fn: StreamFn,
|
|
239
|
+
*,
|
|
240
|
+
retry: RetryPolicy | None = None,
|
|
241
|
+
signal: CancelToken | None = None,
|
|
242
|
+
callbacks: RetryCallbacks | None = None,
|
|
243
|
+
sleep_fn: object | None = None,
|
|
244
|
+
) -> AssistantMessage:
|
|
245
|
+
"""所有摘要调用的唯一入口:单次 LLM 调用 + 有界重试。
|
|
246
|
+
|
|
247
|
+
流式中断(socket 断开、``terminated``)不该让整次压缩功亏一篑,所以这里
|
|
248
|
+
复用 :func:`braid_ai.retry.retry_assistant_call`;确定性错误与取消立即返回。
|
|
249
|
+
"""
|
|
250
|
+
produce = _produce_response(stream_fn, model, context, options)
|
|
251
|
+
return await retry_assistant_call(
|
|
252
|
+
produce,
|
|
253
|
+
retry,
|
|
254
|
+
signal,
|
|
255
|
+
callbacks,
|
|
256
|
+
sleep_fn=sleep_fn, # type: ignore[arg-type]
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _produce_response(
|
|
261
|
+
stream_fn: StreamFn, model: Model, context: TranscriptContext, options: SimpleStreamOptions
|
|
262
|
+
) -> Callable[[], Awaitable[AssistantMessage]]:
|
|
263
|
+
async def produce() -> AssistantMessage:
|
|
264
|
+
stream = stream_fn(model, context, options)
|
|
265
|
+
return await stream.result()
|
|
266
|
+
|
|
267
|
+
return produce
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _build_summarization_context(prompt_text: str, clock: Clock) -> TranscriptContext:
|
|
271
|
+
"""独立的摘要请求上下文:一条系统提示词 + 一条包裹好的用户消息。
|
|
272
|
+
|
|
273
|
+
与主对话的转录完全无关——摘要模型看到的是一份材料,历史原文(虽然是
|
|
274
|
+
序列化过的)都在这条用户消息里。
|
|
275
|
+
"""
|
|
276
|
+
now = clock.now_ms()
|
|
277
|
+
return TranscriptContext(
|
|
278
|
+
messages=[
|
|
279
|
+
SystemMessage(timestamp=now, content=SUMMARIZATION_SYSTEM_PROMPT),
|
|
280
|
+
UserMessage(timestamp=now, content=[TextContent(text=prompt_text)]),
|
|
281
|
+
]
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
async def generate_summary_with_usage(
|
|
286
|
+
current_messages: Sequence[object],
|
|
287
|
+
model: Model,
|
|
288
|
+
*,
|
|
289
|
+
stream_fn: StreamFn,
|
|
290
|
+
api_key: str | None = None,
|
|
291
|
+
headers: dict[str, str] | None = None,
|
|
292
|
+
signal: CancelToken | None = None,
|
|
293
|
+
custom_instructions: str | None = None,
|
|
294
|
+
previous_summary: str | None = None,
|
|
295
|
+
thinking_level: str | None = None,
|
|
296
|
+
retry: RetryPolicy | None = None,
|
|
297
|
+
callbacks: RetryCallbacks | None = None,
|
|
298
|
+
clock: Clock | None = None,
|
|
299
|
+
sleep_fn: object | None = None,
|
|
300
|
+
) -> SummaryWithUsage:
|
|
301
|
+
"""生成(或增量更新)一份结构化摘要,返回文本与用量。
|
|
302
|
+
|
|
303
|
+
``current_messages`` 是转录消息(可含编码层自定义角色),先过
|
|
304
|
+
:func:`convert_to_llm` 折成 LLM 消息再序列化。
|
|
305
|
+
"""
|
|
306
|
+
resolved_clock: Clock = clock if clock is not None else SystemClock()
|
|
307
|
+
|
|
308
|
+
base_prompt = UPDATE_SUMMARIZATION_PROMPT if previous_summary else SUMMARIZATION_PROMPT
|
|
309
|
+
if custom_instructions:
|
|
310
|
+
base_prompt = f"{base_prompt}\n\nAdditional focus: {custom_instructions}"
|
|
311
|
+
|
|
312
|
+
# 先折角色再序列化:custom / 摘要等编码层角色也要进材料。
|
|
313
|
+
llm_messages = convert_to_llm(current_messages) # type: ignore[arg-type]
|
|
314
|
+
conversation_text = serialize_conversation(llm_messages)
|
|
315
|
+
|
|
316
|
+
prompt_text = f"<conversation>\n{conversation_text}\n</conversation>\n\n"
|
|
317
|
+
if previous_summary:
|
|
318
|
+
prompt_text += f"<previous-summary>\n{previous_summary}\n</previous-summary>\n\n"
|
|
319
|
+
prompt_text += base_prompt
|
|
320
|
+
|
|
321
|
+
options = _summarization_options(model, api_key, headers, signal, thinking_level)
|
|
322
|
+
response = await complete_summarization(
|
|
323
|
+
model,
|
|
324
|
+
_build_summarization_context(prompt_text, resolved_clock),
|
|
325
|
+
options,
|
|
326
|
+
stream_fn,
|
|
327
|
+
retry=retry,
|
|
328
|
+
signal=signal,
|
|
329
|
+
callbacks=callbacks,
|
|
330
|
+
sleep_fn=sleep_fn,
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
failure = get_summarization_failure(response, "Summarization")
|
|
334
|
+
if failure:
|
|
335
|
+
raise SummarizationError(failure)
|
|
336
|
+
if any(block.__class__.__name__ == "ToolCall" for block in response.content):
|
|
337
|
+
raise SummarizationError("Summarization attempted to call a tool")
|
|
338
|
+
|
|
339
|
+
return SummaryWithUsage(text=content_text(response.content), usage=response.usage)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
async def generate_summary(
|
|
343
|
+
current_messages: Sequence[object],
|
|
344
|
+
model: Model,
|
|
345
|
+
*,
|
|
346
|
+
stream_fn: StreamFn,
|
|
347
|
+
api_key: str | None = None,
|
|
348
|
+
headers: dict[str, str] | None = None,
|
|
349
|
+
signal: CancelToken | None = None,
|
|
350
|
+
custom_instructions: str | None = None,
|
|
351
|
+
previous_summary: str | None = None,
|
|
352
|
+
thinking_level: str | None = None,
|
|
353
|
+
retry: RetryPolicy | None = None,
|
|
354
|
+
callbacks: RetryCallbacks | None = None,
|
|
355
|
+
clock: Clock | None = None,
|
|
356
|
+
sleep_fn: object | None = None,
|
|
357
|
+
) -> str:
|
|
358
|
+
""":func:`generate_summary_with_usage` 的只取文本便捷形式。"""
|
|
359
|
+
result = await generate_summary_with_usage(
|
|
360
|
+
current_messages,
|
|
361
|
+
model,
|
|
362
|
+
stream_fn=stream_fn,
|
|
363
|
+
api_key=api_key,
|
|
364
|
+
headers=headers,
|
|
365
|
+
signal=signal,
|
|
366
|
+
custom_instructions=custom_instructions,
|
|
367
|
+
previous_summary=previous_summary,
|
|
368
|
+
thinking_level=thinking_level,
|
|
369
|
+
retry=retry,
|
|
370
|
+
callbacks=callbacks,
|
|
371
|
+
clock=clock,
|
|
372
|
+
sleep_fn=sleep_fn,
|
|
373
|
+
)
|
|
374
|
+
return result.text
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
async def generate_turn_prefix_summary(
|
|
378
|
+
messages: Sequence[object],
|
|
379
|
+
model: Model,
|
|
380
|
+
*,
|
|
381
|
+
stream_fn: StreamFn,
|
|
382
|
+
api_key: str | None = None,
|
|
383
|
+
headers: dict[str, str] | None = None,
|
|
384
|
+
signal: CancelToken | None = None,
|
|
385
|
+
thinking_level: str | None = None,
|
|
386
|
+
retry: RetryPolicy | None = None,
|
|
387
|
+
callbacks: RetryCallbacks | None = None,
|
|
388
|
+
custom_instructions: str | None = None,
|
|
389
|
+
clock: Clock | None = None,
|
|
390
|
+
sleep_fn: object | None = None,
|
|
391
|
+
) -> SummaryWithUsage:
|
|
392
|
+
"""split turn 的回合前缀摘要:只概括"用户要什么、做到哪了"。
|
|
393
|
+
|
|
394
|
+
与历史摘要分开请求、分开提示词:前缀消息**还活着**(后面的保留消息是
|
|
395
|
+
它的延续),摘要只需垫场,无需接管全部历史。
|
|
396
|
+
"""
|
|
397
|
+
resolved_clock: Clock = clock if clock is not None else SystemClock()
|
|
398
|
+
llm_messages = convert_to_llm(messages) # type: ignore[arg-type]
|
|
399
|
+
conversation_text = serialize_conversation(llm_messages)
|
|
400
|
+
prompt_text = (
|
|
401
|
+
f"# Conversation\n{conversation_text}\n\n# Instructions\n{TURN_PREFIX_SUMMARIZATION_PROMPT}"
|
|
402
|
+
)
|
|
403
|
+
if custom_instructions:
|
|
404
|
+
prompt_text = f"{prompt_text}\n\nAdditional focus: {custom_instructions}"
|
|
405
|
+
|
|
406
|
+
options = _summarization_options(model, api_key, headers, signal, thinking_level)
|
|
407
|
+
response = await complete_summarization(
|
|
408
|
+
model,
|
|
409
|
+
_build_summarization_context(prompt_text, resolved_clock),
|
|
410
|
+
options,
|
|
411
|
+
stream_fn,
|
|
412
|
+
retry=retry,
|
|
413
|
+
signal=signal,
|
|
414
|
+
callbacks=callbacks,
|
|
415
|
+
sleep_fn=sleep_fn,
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
failure = get_summarization_failure(response, "Turn prefix summarization")
|
|
419
|
+
if failure:
|
|
420
|
+
raise SummarizationError(failure)
|
|
421
|
+
if any(block.__class__.__name__ == "ToolCall" for block in response.content):
|
|
422
|
+
raise SummarizationError("Turn prefix summarization attempted to call a tool")
|
|
423
|
+
|
|
424
|
+
return SummaryWithUsage(text=content_text(response.content), usage=response.usage)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
async def compact(
|
|
428
|
+
preparation: CompactionPreparation,
|
|
429
|
+
model: Model,
|
|
430
|
+
*,
|
|
431
|
+
stream_fn: StreamFn,
|
|
432
|
+
api_key: str | None = None,
|
|
433
|
+
headers: dict[str, str] | None = None,
|
|
434
|
+
custom_instructions: str | None = None,
|
|
435
|
+
signal: CancelToken | None = None,
|
|
436
|
+
thinking_level: str | None = None,
|
|
437
|
+
retry: RetryPolicy | None = None,
|
|
438
|
+
callbacks: RetryCallbacks | None = None,
|
|
439
|
+
clock: Clock | None = None,
|
|
440
|
+
sleep_fn: object | None = None,
|
|
441
|
+
) -> CompactionResult:
|
|
442
|
+
"""执行一次压缩:按准备结果生成摘要并附上文件清单。
|
|
443
|
+
|
|
444
|
+
这是压缩的**纯计算 + 模型调用**部分,不碰会话文件——落盘由调用方完成,
|
|
445
|
+
这样"摘要成功但落盘失败"只有一种处理方式(放弃本次压缩,会话不变),
|
|
446
|
+
不会出现"条目写了一半"的中间态。
|
|
447
|
+
"""
|
|
448
|
+
read_files, modified_files = compute_file_lists(preparation.file_ops)
|
|
449
|
+
|
|
450
|
+
if preparation.is_split_turn and preparation.turn_prefix_messages:
|
|
451
|
+
history_text = preparation.previous_summary or "No prior history."
|
|
452
|
+
history_usage: Usage | None = None
|
|
453
|
+
if preparation.messages_to_summarize:
|
|
454
|
+
history = await generate_summary_with_usage(
|
|
455
|
+
preparation.messages_to_summarize,
|
|
456
|
+
model,
|
|
457
|
+
stream_fn=stream_fn,
|
|
458
|
+
api_key=api_key,
|
|
459
|
+
headers=headers,
|
|
460
|
+
signal=signal,
|
|
461
|
+
custom_instructions=custom_instructions,
|
|
462
|
+
previous_summary=preparation.previous_summary,
|
|
463
|
+
thinking_level=thinking_level,
|
|
464
|
+
retry=retry,
|
|
465
|
+
callbacks=callbacks,
|
|
466
|
+
clock=clock,
|
|
467
|
+
sleep_fn=sleep_fn,
|
|
468
|
+
)
|
|
469
|
+
history_text = history.text
|
|
470
|
+
history_usage = history.usage
|
|
471
|
+
prefix = await generate_turn_prefix_summary(
|
|
472
|
+
preparation.turn_prefix_messages,
|
|
473
|
+
model,
|
|
474
|
+
stream_fn=stream_fn,
|
|
475
|
+
api_key=api_key,
|
|
476
|
+
headers=headers,
|
|
477
|
+
signal=signal,
|
|
478
|
+
thinking_level=thinking_level,
|
|
479
|
+
retry=retry,
|
|
480
|
+
callbacks=callbacks,
|
|
481
|
+
custom_instructions=custom_instructions,
|
|
482
|
+
clock=clock,
|
|
483
|
+
sleep_fn=sleep_fn,
|
|
484
|
+
)
|
|
485
|
+
summary = f"{history_text}\n\n---\n\n**Turn Context (split turn):**\n\n{prefix.text}"
|
|
486
|
+
summary_usage = (
|
|
487
|
+
prefix.usage if history_usage is None else _combine_usage(history_usage, prefix.usage)
|
|
488
|
+
)
|
|
489
|
+
else:
|
|
490
|
+
result = await generate_summary_with_usage(
|
|
491
|
+
preparation.messages_to_summarize,
|
|
492
|
+
model,
|
|
493
|
+
stream_fn=stream_fn,
|
|
494
|
+
api_key=api_key,
|
|
495
|
+
headers=headers,
|
|
496
|
+
signal=signal,
|
|
497
|
+
custom_instructions=custom_instructions,
|
|
498
|
+
previous_summary=preparation.previous_summary,
|
|
499
|
+
thinking_level=thinking_level,
|
|
500
|
+
retry=retry,
|
|
501
|
+
callbacks=callbacks,
|
|
502
|
+
clock=clock,
|
|
503
|
+
sleep_fn=sleep_fn,
|
|
504
|
+
)
|
|
505
|
+
summary = result.text
|
|
506
|
+
summary_usage = result.usage
|
|
507
|
+
|
|
508
|
+
summary += format_file_operations(read_files, modified_files)
|
|
509
|
+
|
|
510
|
+
if not preparation.first_kept_entry_id:
|
|
511
|
+
raise SummarizationError("First kept entry has no UUID - session may need migration")
|
|
512
|
+
|
|
513
|
+
return CompactionResult(
|
|
514
|
+
summary=summary,
|
|
515
|
+
first_kept_entry_id=preparation.first_kept_entry_id,
|
|
516
|
+
tokens_before=preparation.tokens_before,
|
|
517
|
+
usage=summary_usage,
|
|
518
|
+
# details 是写进会话文件的 JSON 边界:键名用 camelCase。
|
|
519
|
+
details=cast(JsonValue, {"readFiles": read_files, "modifiedFiles": modified_files}),
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _combine_usage(first: Usage, second: Usage) -> Usage:
|
|
524
|
+
"""两次摘要调用的用量合并。split turn 会发
|
|
525
|
+
两次请求,条目里的 usage 是两次之和,总账才不缺斤少两。"""
|
|
526
|
+
return Usage(
|
|
527
|
+
input=first.input + second.input,
|
|
528
|
+
output=first.output + second.output,
|
|
529
|
+
cache_read=first.cache_read + second.cache_read,
|
|
530
|
+
cache_write=first.cache_write + second.cache_write,
|
|
531
|
+
total_tokens=first.total_tokens + second.total_tokens,
|
|
532
|
+
cost=type(first.cost)(
|
|
533
|
+
input=first.cost.input + second.cost.input,
|
|
534
|
+
output=first.cost.output + second.cost.output,
|
|
535
|
+
cache_read=first.cost.cache_read + second.cost.cache_read,
|
|
536
|
+
cache_write=first.cost.cache_write + second.cost.cache_write,
|
|
537
|
+
total=first.cost.total + second.cost.total,
|
|
538
|
+
total_from_provider=(
|
|
539
|
+
first.cost.total_from_provider is True and second.cost.total_from_provider is True
|
|
540
|
+
),
|
|
541
|
+
),
|
|
542
|
+
)
|