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,262 @@
1
+ """会话投影:从树上的当前路径算出"模型此刻看到什么"。
2
+
3
+ 三个函数层层叠加:
4
+
5
+ 1. :func:`build_session_path` —— 从叶子回溯到根,得到活动条目序列;
6
+ 2. :func:`build_context_entries` —— 路径上有压缩条目时,用最新的那个替换它之前的
7
+ 区间:压缩条目本身 + ``first_kept_entry_id`` 起的保留区间(去掉系统消息,它们
8
+ 已折进检查点)+ 压缩之后的条目;
9
+ 3. :func:`build_session_projection` —— 对选出的条目应用 context_edit(只改模型
10
+ 可见内容,不动原始条目),并从**完整路径**读出 model/thinking_level 设置。
11
+
12
+ 关键不变量:**上下文是投影,不是存储**。换叶子、切分支、压缩,原始条目一个都不动;
13
+ 模型看到什么由"当前叶子 + 最新压缩 + 最新编辑"三个纯函数决定。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Mapping, Sequence
19
+ from dataclasses import dataclass, replace
20
+ from enum import Enum, auto
21
+ from typing import Final, Literal
22
+
23
+ from braid_ai.types import (
24
+ AssistantMessage,
25
+ SystemMessage,
26
+ TextContent,
27
+ ToolResultMessage,
28
+ UserMessage,
29
+ )
30
+ from braid_coding_agent.session.entries import (
31
+ CompactionEntry,
32
+ ContextEditEntry,
33
+ CustomMessage,
34
+ ModelChangeEntry,
35
+ ProjectedMessage,
36
+ SessionEntry,
37
+ SessionMessageEntry,
38
+ TextImageContent,
39
+ ThinkingLevelChangeEntry,
40
+ session_entry_to_context_messages,
41
+ )
42
+
43
+
44
+ class _Unset(Enum):
45
+ """叶子参数的"未指定"哨兵:与显式 ``None``(空路径)区分。"""
46
+
47
+ TOKEN = auto()
48
+
49
+
50
+ UNSET: Final = _Unset.TOKEN
51
+ #: ``UNSET`` 用最后一个条目;``None`` 是显式的空路径(resetLeaf 之后);字符串按 id 找,
52
+ #: 找不到退回最后一个条目。
53
+ type LeafArg = str | Literal[_Unset.TOKEN] | None
54
+
55
+
56
+ @dataclass(slots=True, frozen=True)
57
+ class ModelRef:
58
+ """当前模型:provider 与模型 id。"""
59
+
60
+ provider: str
61
+ model_id: str
62
+
63
+
64
+ @dataclass(slots=True)
65
+ class ProjectedSessionEntry:
66
+ """投影后的一个条目:来源条目 + 它贡献的模型可见消息。"""
67
+
68
+ source_entry: SessionEntry
69
+ messages: list[ProjectedMessage]
70
+
71
+
72
+ @dataclass(slots=True)
73
+ class SessionProjection:
74
+ """带出处的模型上下文:UI 和调试需要知道每条消息来自哪个条目。"""
75
+
76
+ entries: list[ProjectedSessionEntry]
77
+ messages: list[ProjectedMessage]
78
+ thinking_level: str
79
+ model: ModelRef | None
80
+
81
+
82
+ @dataclass(slots=True)
83
+ class SessionContext:
84
+ """发给 LLM 的最终上下文。"""
85
+
86
+ messages: list[ProjectedMessage]
87
+ thinking_level: str
88
+ model: ModelRef | None
89
+
90
+
91
+ def build_entry_index(entries: Sequence[SessionEntry]) -> dict[str, SessionEntry]:
92
+ """id → 条目。重复 id 后者覆盖。"""
93
+ return {entry.id: entry for entry in entries}
94
+
95
+
96
+ def build_session_path(
97
+ entries: Sequence[SessionEntry],
98
+ leaf_id: LeafArg = UNSET,
99
+ by_id: Mapping[str, SessionEntry] | None = None,
100
+ ) -> list[SessionEntry]:
101
+ """从叶子回溯到根,返回根→叶顺序的路径。"""
102
+ index = by_id if by_id is not None else build_entry_index(entries)
103
+ if leaf_id is UNSET:
104
+ leaf: SessionEntry | None = entries[-1] if entries else None
105
+ elif leaf_id is None:
106
+ return []
107
+ else:
108
+ leaf = index.get(leaf_id)
109
+ if leaf is None:
110
+ leaf = entries[-1] if entries else None
111
+ if leaf is None:
112
+ return []
113
+ path: list[SessionEntry] = []
114
+ current: SessionEntry | None = leaf
115
+ while current is not None:
116
+ path.append(current)
117
+ parent_id = current.parent_id
118
+ current = index.get(parent_id) if parent_id is not None else None
119
+ path.reverse()
120
+ return path
121
+
122
+
123
+ def get_session_context_settings(path: Sequence[SessionEntry]) -> tuple[str, ModelRef | None]:
124
+ """从完整路径读设置:thinking_level 默认 ``off``;model_change 与助手消息后者胜。"""
125
+ thinking_level = "off"
126
+ model: ModelRef | None = None
127
+ for entry in path:
128
+ match entry:
129
+ case ThinkingLevelChangeEntry():
130
+ thinking_level = entry.thinking_level
131
+ case ModelChangeEntry():
132
+ model = ModelRef(provider=entry.provider, model_id=entry.model_id)
133
+ case SessionMessageEntry():
134
+ message = entry.message
135
+ if isinstance(message, AssistantMessage):
136
+ model = ModelRef(provider=message.provider, model_id=message.model)
137
+ case _:
138
+ pass
139
+ return thinking_level, model
140
+
141
+
142
+ def build_context_entries(
143
+ entries: Sequence[SessionEntry],
144
+ leaf_id: LeafArg = UNSET,
145
+ by_id: Mapping[str, SessionEntry] | None = None,
146
+ ) -> list[SessionEntry]:
147
+ """压缩感知的活动条目列表:最新 compaction 替换它之前的被摘要区间。"""
148
+ path = build_session_path(entries, leaf_id, by_id)
149
+ compaction: CompactionEntry | None = None
150
+ for entry in path:
151
+ if isinstance(entry, CompactionEntry):
152
+ compaction = entry
153
+ if compaction is None:
154
+ return path
155
+
156
+ compaction_index = next(index for index, entry in enumerate(path) if entry.id == compaction.id)
157
+ context_entries: list[SessionEntry] = [compaction]
158
+ found_first_kept = False
159
+ for entry in path[:compaction_index]:
160
+ if entry.id == compaction.first_kept_entry_id:
161
+ found_first_kept = True
162
+ # 保留区间里的系统消息不再重放:它们的提示词已经折进压缩检查点。
163
+ if found_first_kept and not (
164
+ isinstance(entry, SessionMessageEntry) and isinstance(entry.message, SystemMessage)
165
+ ):
166
+ context_entries.append(entry)
167
+ context_entries.extend(path[compaction_index + 1 :])
168
+ return context_entries
169
+
170
+
171
+ def project_context_entry(
172
+ entry: SessionEntry, edit: ContextEditEntry | None
173
+ ) -> list[ProjectedMessage]:
174
+ """单条目投影 + 可选的 context_edit 应用。省略型编辑返回空列表。"""
175
+ messages = session_entry_to_context_messages(entry)
176
+ if edit is None:
177
+ return messages
178
+ if edit.replacement is None:
179
+ return []
180
+ content = edit.replacement.content
181
+ return [_replace_content(message, content) for message in messages]
182
+
183
+
184
+ def _replace_content(message: ProjectedMessage, content: TextImageContent) -> ProjectedMessage:
185
+ """把替换内容装进消息。assistant/toolResult 的内容必须是块数组:字符串归一成 text 块。"""
186
+ match message:
187
+ case AssistantMessage():
188
+ if isinstance(content, str):
189
+ return replace(message, content=[TextContent(text=content)])
190
+ # 这里的 cast 只覆盖"数组块类型"的静态差异,运行时块原样保留。
191
+ return replace(message, content=content) # type: ignore[arg-type]
192
+ case ToolResultMessage():
193
+ if isinstance(content, str):
194
+ return replace(message, content=[TextContent(text=content)])
195
+ return replace(message, content=content)
196
+ case UserMessage() | CustomMessage():
197
+ return replace(message, content=content)
198
+ case _:
199
+ # system/branchSummary/compactionSummary 不在可编辑名单里,原样保留。
200
+ return message
201
+
202
+
203
+ def build_session_projection(
204
+ entries: Sequence[SessionEntry],
205
+ leaf_id: LeafArg = UNSET,
206
+ by_id: Mapping[str, SessionEntry] | None = None,
207
+ ) -> SessionProjection:
208
+ """带出处的模型上下文:最新编辑对同一目标生效,编辑只在活动条目里找。"""
209
+ path = build_session_path(entries, leaf_id, by_id)
210
+ thinking_level, model = get_session_context_settings(path)
211
+ context_entries = build_context_entries(entries, leaf_id, by_id)
212
+ edits: dict[str, ContextEditEntry] = {}
213
+ for entry in context_entries:
214
+ if isinstance(entry, ContextEditEntry):
215
+ edits[entry.target_id] = entry
216
+
217
+ projected: list[ProjectedSessionEntry] = []
218
+ for index, source_entry in enumerate(context_entries):
219
+ if isinstance(source_entry, CompactionEntry) and index > 0:
220
+ # buildContextEntries 可能保留更早的压缩条目(它的原始位置落在最新保留
221
+ # 区间里);只有下标 0 的最新压缩才贡献检查点与摘要,更早的只占树位。
222
+ messages: list[ProjectedMessage] = []
223
+ else:
224
+ messages = project_context_entry(source_entry, edits.get(source_entry.id))
225
+ projected.append(ProjectedSessionEntry(source_entry=source_entry, messages=messages))
226
+ return SessionProjection(
227
+ entries=projected,
228
+ messages=[message for item in projected for message in item.messages],
229
+ thinking_level=thinking_level,
230
+ model=model,
231
+ )
232
+
233
+
234
+ def build_session_context(
235
+ entries: Sequence[SessionEntry],
236
+ leaf_id: LeafArg = UNSET,
237
+ by_id: Mapping[str, SessionEntry] | None = None,
238
+ ) -> SessionContext:
239
+ """最终模型上下文(不带出处)。"""
240
+ projection = build_session_projection(entries, leaf_id, by_id)
241
+ return SessionContext(
242
+ messages=projection.messages,
243
+ thinking_level=projection.thinking_level,
244
+ model=projection.model,
245
+ )
246
+
247
+
248
+ __all__ = [
249
+ "UNSET",
250
+ "ModelRef",
251
+ "ProjectedSessionEntry",
252
+ "SessionContext",
253
+ "SessionProjection",
254
+ "build_context_entries",
255
+ "build_entry_index",
256
+ "build_session_context",
257
+ "build_session_path",
258
+ "build_session_projection",
259
+ "get_session_context_settings",
260
+ "project_context_entry",
261
+ "session_entry_to_context_messages",
262
+ ]
@@ -0,0 +1,257 @@
1
+ """会话回退:把对话与工作区一起退到某一轮提问之前。
2
+
3
+ 一次回退要三样东西同时成立:
4
+
5
+ 1. **对话**:活动分支从目标位置重新开始(:meth:`SessionManager.rewind` 追加一条
6
+ branch_summary 条目,被放弃的路径原样留在文件里);
7
+ 2. **转录**:Agent 的内存转录按新路径重算(:meth:`AgentSession.rewind_conversation`);
8
+ 3. **工作区**(可选):恢复成那一轮开始前的文件快照(:meth:`CheckpointStore.restore_to`)。
9
+
10
+ 顺序是"先文件、后对话"。文件恢复要读快照、跑 git,失败机会比追加一行 JSONL 大得多;
11
+ 它失败时对话还没动,用户继续原来的路径就行。反过来做会留下"对话退了、文件没退"的
12
+ 半截状态,而模型看到的历史与磁盘上的文件一旦对不上,后面每一轮都在错的前提上干活。
13
+
14
+ ## 为什么回退单位是"用户提问"而不是任意条目
15
+
16
+ 回退到一条工具结果或一条助手消息之后,模型看到的历史会停在一个不完整的动作中间,
17
+ 下一次请求很容易接着"半句话"往下编。用户提问是这个会话里天然的边界:那句话之前
18
+ 的历史是完整的,后面是这一轮的全部后果。
19
+
20
+ ## 文件那一半为什么可以不要
21
+
22
+ 不是每次都开着检查点(``--no-checkpoint``、没有 git、内存会话)。这时回退只动对话,
23
+ 摘要里会写明"工作区文件保持原状",模型不会以为文件也跟着退了。
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from collections.abc import Sequence
29
+ from dataclasses import dataclass
30
+ from datetime import datetime
31
+ from typing import Final, Literal
32
+
33
+ from braid_ai.types import UserMessage
34
+ from braid_ai.wire import content_text
35
+ from braid_coding_agent.checkpoint import FileChange
36
+ from braid_coding_agent.session.agent_session import AgentSession
37
+ from braid_coding_agent.session.entries import SessionMessageEntry
38
+
39
+ #: 回退清单里预览文本的长度上限。一行里要放下序号、时间、摘要与快照状态。
40
+ PREVIEW_LIMIT: Final[int] = 40
41
+
42
+ #: 回退范围。``conversation`` 只动对话,``files`` 只动文件,``all`` 两者都动。
43
+ type RewindMode = Literal["conversation", "files", "all"]
44
+
45
+ #: 命令行写法 → 回退范围。``--all`` 是显式的"两个都动",与"没给范围"不同。
46
+ MODE_FLAGS: Final[dict[str, RewindMode]] = {
47
+ "--conversation": "conversation",
48
+ "-c": "conversation",
49
+ "--files": "files",
50
+ "-f": "files",
51
+ "--all": "all",
52
+ "-a": "all",
53
+ }
54
+
55
+
56
+ class RewindError(RuntimeError):
57
+ """回退没做成。``message`` 直接给用户看。"""
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class RewindTarget:
62
+ """一个可回退的位置:某一轮用户提问之前。"""
63
+
64
+ #: 1 起的序号,与清单里显示的一致。
65
+ index: int
66
+ #: 这一轮提问的消息条目 id。
67
+ entry_id: str
68
+ #: 回退之后的新叶子(这条提问的父条目;``None`` 表示回到会话开始)。
69
+ parent_id: str | None
70
+ preview: str
71
+ timestamp: str
72
+ #: 这条提问及其之后的消息条数,回退会放弃它们。
73
+ dropped_messages: int
74
+ #: 这一轮开始前的文件快照。``None`` 表示拿不到(没开检查点,或这一轮没绑定)。
75
+ file_tree: str | None
76
+ #: 对应的检查点回合序号,用来截断撤销栈。
77
+ sequence: int | None
78
+
79
+ @property
80
+ def can_restore_files(self) -> bool:
81
+ return self.file_tree is not None
82
+
83
+ def describe(self) -> str:
84
+ """清单里的一行:序号、时间、提问摘要、放弃的消息数、文件快照是否可用。"""
85
+ snapshot = "文件快照可用" if self.can_restore_files else "无文件快照"
86
+ return (
87
+ f"{self._stamp()} · {self.preview} · 之后 {self.dropped_messages} 条消息 · {snapshot}"
88
+ )
89
+
90
+ def menu_label(self) -> str:
91
+ """选择框里的一行:序号、时间、代价、提问摘要。
92
+
93
+ 摘要放在末尾:终端宽度不够时截断的是它,序号与"放弃多少条消息"必须留住。
94
+ """
95
+ snapshot = "快照可用" if self.can_restore_files else "无快照"
96
+ return f"{self._stamp()} · 之后 {self.dropped_messages} 条 · {snapshot} · {self.preview}"
97
+
98
+ def _stamp(self) -> str:
99
+ return f"{self.index}. {_local_minute(self.timestamp)}"
100
+
101
+
102
+ @dataclass(frozen=True, slots=True)
103
+ class RewindOutcome:
104
+ """一次回退的结果。"""
105
+
106
+ target: RewindTarget
107
+ mode: RewindMode
108
+ files: tuple[FileChange, ...]
109
+
110
+ def summary(self) -> str:
111
+ """一行结果:放弃了多少消息,文件动了几个。"""
112
+ if self.mode == "files":
113
+ head = f"已把工作区恢复到第 {self.target.index} 轮提问之前的快照"
114
+ else:
115
+ head = f"已回退到第 {self.target.index} 轮提问之前"
116
+ parts = [f"放弃 {self.target.dropped_messages} 条消息"] if self.mode != "files" else []
117
+ if self.mode != "conversation":
118
+ parts.append(f"文件改动 {len(self.files)} 个{change_breakdown(self.files)}")
119
+ return f"{head}:{';'.join(parts) if parts else '未改动任何东西'}"
120
+
121
+
122
+ async def build_targets(session: AgentSession) -> list[RewindTarget]:
123
+ """列出当前分支上的回退位置,按时间顺序,序号从 1 开始。
124
+
125
+ 检查点先读一遍日志(``ensure_ready``):恢复会话之后刚构造的
126
+ :class:`CheckpointStore` 还没有回合表,不读盘就找不到"这一轮从哪儿开始"。
127
+ """
128
+ checkpoints = session.checkpoints
129
+ if checkpoints is not None:
130
+ await checkpoints.ensure_ready()
131
+ branch = session.session.get_branch()
132
+ targets: list[RewindTarget] = []
133
+ index = 0
134
+ for position, entry in enumerate(branch):
135
+ if not isinstance(entry, SessionMessageEntry) or not isinstance(entry.message, UserMessage):
136
+ continue
137
+ index += 1
138
+ turn = checkpoints.turn_for_message(entry.id) if checkpoints is not None else None
139
+ targets.append(
140
+ RewindTarget(
141
+ index=index,
142
+ entry_id=entry.id,
143
+ parent_id=entry.parent_id,
144
+ preview=_preview(entry.message),
145
+ timestamp=entry.timestamp,
146
+ dropped_messages=sum(
147
+ 1 for item in branch[position:] if isinstance(item, SessionMessageEntry)
148
+ ),
149
+ file_tree=turn.before_tree if turn is not None else None,
150
+ sequence=turn.sequence if turn is not None else None,
151
+ )
152
+ )
153
+ return targets
154
+
155
+
156
+ async def file_preview(session: AgentSession, target: RewindTarget) -> tuple[FileChange, ...]:
157
+ """把这一个位置的文件改动算出来,供确认清单显示。没有快照时返回空。"""
158
+ checkpoints = session.checkpoints
159
+ if checkpoints is None or target.file_tree is None:
160
+ return ()
161
+ return await checkpoints.changes_to(target.file_tree)
162
+
163
+
164
+ async def apply_rewind(
165
+ session: AgentSession, target: RewindTarget, *, mode: RewindMode
166
+ ) -> RewindOutcome:
167
+ """执行一次回退。
168
+
169
+ :raises RewindError: 会话正在运行,或要求恢复文件但这一轮没有快照。
170
+ """
171
+ if session.is_streaming or session.is_compacting:
172
+ raise RewindError("会话正在处理这一轮,等它结束再回退")
173
+ if mode in ("files", "all") and target.file_tree is None:
174
+ raise RewindError(
175
+ f"第 {target.index} 轮没有文件快照(会话没开检查点,或这一轮没走到快照),只能回退对话"
176
+ )
177
+
178
+ files: tuple[FileChange, ...] = ()
179
+ if mode in ("files", "all"):
180
+ checkpoints = session.checkpoints
181
+ if checkpoints is None:
182
+ raise RewindError("本次会话没有启用检查点,无法恢复文件")
183
+ assert target.file_tree is not None
184
+ files = await checkpoints.restore_to(target.file_tree)
185
+ if target.sequence is not None:
186
+ await checkpoints.truncate_from(target.sequence)
187
+
188
+ if mode in ("conversation", "all"):
189
+ session.rewind_conversation(target.parent_id, summary=_summary_text(target, mode, files))
190
+ return RewindOutcome(target=target, mode=mode, files=files)
191
+
192
+
193
+ def parse_mode_flags(flags: Sequence[str]) -> RewindMode | None:
194
+ """把命令行的范围参数翻成 :data:`RewindMode`。空列表返回 ``None``(让调用方去问)。
195
+
196
+ :raises ValueError: 出现不认识的参数,或同时给了两个方向相反的参数。
197
+ """
198
+ if not flags:
199
+ return None
200
+ modes: set[RewindMode] = set()
201
+ for flag in flags:
202
+ mode = MODE_FLAGS.get(flag)
203
+ if mode is None:
204
+ raise ValueError(f"不认识的参数:{flag};可用 --conversation、--files、--all")
205
+ modes.add(mode)
206
+ if len(modes) > 1:
207
+ raise ValueError("回退范围只能选一个:--conversation、--files、--all")
208
+ return modes.pop()
209
+
210
+
211
+ def _summary_text(target: RewindTarget, mode: RewindMode, files: Sequence[FileChange]) -> str:
212
+ """写进 branch_summary 的那段话。模型会把它读成"一条被放弃的分支"。"""
213
+ text = (
214
+ f"用户把会话回退到了第 {target.index} 轮提问之前,"
215
+ f"放弃了那一句「{target.preview}」及其之后的 {target.dropped_messages} 条消息。"
216
+ "被放弃的内容不再属于当前上下文。"
217
+ )
218
+ if mode == "conversation":
219
+ return text + "工作区文件保持回退前的状态,没有恢复。"
220
+ return text + f"工作区文件已恢复到那一轮开始前的快照,共 {len(files)} 个文件有改动。"
221
+
222
+
223
+ def _preview(message: UserMessage) -> str:
224
+ flat = " ".join(content_text(message.content).split())
225
+ if len(flat) <= PREVIEW_LIMIT:
226
+ return flat
227
+ return flat[: PREVIEW_LIMIT - 1] + "…"
228
+
229
+
230
+ def change_breakdown(files: Sequence[FileChange]) -> str:
231
+ """``(新增 1 · 删除 2 · 改写 3)``,没有的那一档不出现。"""
232
+ counts = {"added": 0, "deleted": 0, "modified": 0}
233
+ for change in files:
234
+ counts[change.status] += 1
235
+ labels = {"added": "新增", "deleted": "删除", "modified": "改写"}
236
+ parts = [f"{labels[status]} {counts[status]}" for status in ("added", "deleted", "modified")]
237
+ kept = [part for part in parts if not part.endswith(" 0")]
238
+ return f"({' · '.join(kept)})" if kept else ""
239
+
240
+
241
+ def _local_minute(timestamp: str) -> str:
242
+ return datetime.fromisoformat(timestamp).astimezone().strftime("%H:%M:%S")
243
+
244
+
245
+ __all__ = [
246
+ "MODE_FLAGS",
247
+ "PREVIEW_LIMIT",
248
+ "RewindError",
249
+ "RewindMode",
250
+ "RewindOutcome",
251
+ "RewindTarget",
252
+ "apply_rewind",
253
+ "build_targets",
254
+ "change_breakdown",
255
+ "file_preview",
256
+ "parse_mode_flags",
257
+ ]