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,1185 @@
1
+ """SessionManager:追加式会话树的持久化、分支与恢复。
2
+
3
+ 核心模型:
4
+
5
+ - 文件是 **JSONL**:第一行 session 头,之后每行一个条目;条目靠 ``id``/``parentId``
6
+ 连成树。文件本身就是事实来源,内存里只多维护一个"当前叶子"指针。
7
+ - **追加只写一行**:新条目是当前叶子的孩子;文件已存在时 append,未创建时
8
+ (还没有 user/assistant 消息)连文件都不落盘——只加了模型/思考级别就关掉的
9
+ 会话不会留下垃圾文件。
10
+ - **崩溃安全**:写坏的最后半行在加载时被忽略并补换行修复;已终止的坏行抛
11
+ :class:`SessionFormatError`——静默跳过等于悄悄丢历史。
12
+ - **分支**::meth:`SessionManager.move_to` 把叶子拨回早前条目,下次追加自然长出新
13
+ 分支;旧分支原样保留。:meth:`SessionManager.fork` / :meth:`SessionManager.clone`
14
+ 把一条路径复制成新文件(返回新对象,原会话不动)。
15
+ - **跨进程独占**:一个会话文件同一时刻只允许一个写入者。锁在
16
+ :meth:`SessionManager.open` 读文件之前、以及第一次真正落盘之前取得,
17
+ ``release_lock()`` 或进程退出时释放;第二个持有者拿到
18
+ :class:`~braid_coding_agent.session.lock.SessionLockedError` 而不是写坏文件。
19
+ - **上下文是投影**:发给模型的消息由 :mod:`braid_coding_agent.session.projection`
20
+ 从树上现算,压缩/编辑都不改原始条目。
21
+
22
+ 可注入项:时钟(:class:`braid_ai.Clock`,条目时间戳)、条目 id 工厂、会话 id 工厂。
23
+ 测试用 ``FakeClock`` 和计数器工厂得到完全确定的时间戳与 id。
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import re
31
+ import uuid
32
+ from collections.abc import Callable, Mapping, Sequence
33
+ from dataclasses import dataclass, field, replace
34
+ from io import TextIOWrapper
35
+ from pathlib import Path
36
+ from typing import Final
37
+
38
+ from braid_ai.transcript import get_current_system_message
39
+ from braid_ai.types import (
40
+ AssistantMessage,
41
+ JsonValue,
42
+ SystemMessage,
43
+ TextContent,
44
+ ToolResultMessage,
45
+ Usage,
46
+ UserMessage,
47
+ )
48
+ from braid_ai.utils.clock import Clock, SystemClock
49
+ from braid_coding_agent.session import projection
50
+ from braid_coding_agent.session.entries import (
51
+ CURRENT_SESSION_VERSION,
52
+ BranchSummaryEntry,
53
+ BranchSummaryMessage,
54
+ CompactionEntry,
55
+ CompactionSummaryMessage,
56
+ ContextEditEntry,
57
+ ContextReplacement,
58
+ CustomEntry,
59
+ CustomMessageEntry,
60
+ FileEntry,
61
+ LabelEntry,
62
+ ModelChangeEntry,
63
+ ProjectedMessage,
64
+ SessionEntry,
65
+ SessionFormatError,
66
+ SessionHeader,
67
+ SessionInfoEntry,
68
+ SessionMessageEntry,
69
+ StorableMessage,
70
+ TextImageContent,
71
+ ThinkingLevelChangeEntry,
72
+ UnknownEntry,
73
+ UsageEntry,
74
+ entry_from_wire,
75
+ entry_to_wire,
76
+ iso_from_ms,
77
+ ms_from_iso,
78
+ )
79
+ from braid_coding_agent.session.lock import SessionFileLock
80
+ from braid_coding_agent.session.projection import (
81
+ UNSET,
82
+ LeafArg,
83
+ SessionContext,
84
+ SessionProjection,
85
+ )
86
+
87
+ _SESSION_ID_PATTERN: Final[re.Pattern[str]] = re.compile(
88
+ r"^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$"
89
+ )
90
+
91
+ #: 8 位短 id 的重试上限;碰撞 100 次后退回完整 uuid。
92
+ _ID_ATTEMPTS: Final[int] = 100
93
+
94
+
95
+ def assert_valid_session_id(session_id: str) -> None:
96
+ """会话 id 用于文件名,只能包含字母、数字与 ``-_.``,且以字母数字开头结尾。"""
97
+ if not _SESSION_ID_PATTERN.fullmatch(session_id):
98
+ raise ValueError(
99
+ f"非法会话 id: {session_id!r};只允许字母、数字、'-'、'_'、'.',且以字母或数字开头结尾"
100
+ )
101
+
102
+
103
+ def default_session_dir(cwd: str, agent_dir: str | None = None) -> str:
104
+ """按 cwd 编码出默认会话目录:``<agent_dir>/sessions/--<safe-path>--``。
105
+
106
+ 去掉前导分隔符,把 ``/``、``\\``、``:`` 都换成 ``-``。
107
+ 目录不存在时顺带创建。
108
+ """
109
+ resolved_cwd = os.path.abspath(cwd)
110
+ base = agent_dir if agent_dir is not None else str(Path.home() / ".braid")
111
+ safe_path = "--" + re.sub(r"[/\\:]", "-", resolved_cwd.lstrip("/\\")) + "--"
112
+ session_dir = os.path.join(os.path.abspath(base), "sessions", safe_path)
113
+ os.makedirs(session_dir, exist_ok=True)
114
+ return session_dir
115
+
116
+
117
+ def _unique_id(existing: set[str], factory: Callable[[], str]) -> str:
118
+ for _ in range(_ID_ATTEMPTS):
119
+ candidate = factory()
120
+ if candidate not in existing:
121
+ return candidate
122
+ return uuid.uuid4().hex
123
+
124
+
125
+ def _is_valid_header(data: Mapping[str, JsonValue]) -> bool:
126
+ return isinstance(data.get("id"), str) and data.get("type") == "session"
127
+
128
+
129
+ def load_entries_from_file(path: str) -> list[dict[str, JsonValue]]:
130
+ """读入 JSONL 会话文件,返回 raw 条目列表(头在首位)。
131
+
132
+ 崩溃语义:
133
+
134
+ - **最后一行 JSON 不完整**(写入中途崩溃,行没有换行符结尾)→ 忽略,并补一个
135
+ 换行符修复文件,让下次追加从新行开始;
136
+ - **已终止的坏行**(有换行符结尾却不是合法 JSON 对象)→ 抛
137
+ :class:`SessionFormatError`:能写完整一行说明不是截断,是真实损坏;
138
+ - 首个条目不是合法 session 头 → 返回空列表,由调用方决定报错还是初始化。
139
+ """
140
+ resolved = os.path.abspath(path)
141
+ if not os.path.exists(resolved):
142
+ return []
143
+ with open(resolved, encoding="utf-8") as handle:
144
+ content = handle.read()
145
+
146
+ entries: list[dict[str, JsonValue]] = []
147
+ lines = content.split("\n")
148
+ ends_with_newline = content.endswith("\n")
149
+ last_index = len(lines) - 1
150
+ needs_repair = False
151
+ for line_number, line in enumerate(lines):
152
+ is_tail = line_number == last_index and not ends_with_newline
153
+ if not line.strip():
154
+ continue
155
+ try:
156
+ parsed: JsonValue = json.loads(line)
157
+ except json.JSONDecodeError:
158
+ if is_tail:
159
+ # 写入中途崩溃留下的半行:忽略内容,稍后补换行修复。
160
+ needs_repair = True
161
+ continue
162
+ raise SessionFormatError(f"{resolved} 第 {line_number + 1} 行不是合法 JSON") from None
163
+ if is_tail and not isinstance(parsed, dict):
164
+ needs_repair = True
165
+ continue
166
+ if not isinstance(parsed, dict):
167
+ raise SessionFormatError(f"{resolved} 第 {line_number + 1} 行不是 JSON 对象")
168
+ entries.append(parsed)
169
+
170
+ if entries and not _is_valid_header(entries[0]):
171
+ return []
172
+ if needs_repair:
173
+ with open(resolved, "a", encoding="utf-8", newline="\n") as handle:
174
+ handle.write("\n")
175
+ return entries
176
+
177
+
178
+ # --------------------------------------------------------------------- 迁移
179
+
180
+
181
+ def migrate_session_entries(entries: list[dict[str, JsonValue]]) -> bool:
182
+ """把 raw 条目迁到当前版本(原地修改)。返回是否发生了迁移。
183
+
184
+ - v1 → v2:给每个条目分配 id/parentId,串成链;compaction 的
185
+ ``firstKeptEntryIndex`` 换算成 ``firstKeptEntryId``;
186
+ - v2 → v3:message 里的 ``hookMessage`` 角色更名为 ``custom``。
187
+ """
188
+ header = next((entry for entry in entries if entry.get("type") == "session"), None)
189
+ raw_version = header.get("version") if header is not None else None
190
+ version = (
191
+ raw_version if isinstance(raw_version, int) and not isinstance(raw_version, bool) else 1
192
+ )
193
+ if version >= CURRENT_SESSION_VERSION:
194
+ return False
195
+ if version < 2:
196
+ _migrate_v1_to_v2(entries)
197
+ if version < 3:
198
+ _migrate_v2_to_v3(entries)
199
+ return True
200
+
201
+
202
+ def _migrate_v1_to_v2(entries: list[dict[str, JsonValue]]) -> None:
203
+ ids: set[str] = set()
204
+ prev_id: str | None = None
205
+ for entry in entries:
206
+ if entry.get("type") == "session":
207
+ entry["version"] = 2
208
+ continue
209
+ entry_id = _unique_id(ids, lambda: uuid.uuid4().hex[:8])
210
+ entry["id"] = entry_id
211
+ entry["parentId"] = prev_id
212
+ prev_id = entry_id
213
+ if entry.get("type") == "compaction":
214
+ index = entry.get("firstKeptEntryIndex")
215
+ if isinstance(index, int) and not isinstance(index, bool):
216
+ target = entries[index] if 0 <= index < len(entries) else None
217
+ if target is not None and target.get("type") != "session":
218
+ target_id = target.get("id")
219
+ if isinstance(target_id, str):
220
+ entry["firstKeptEntryId"] = target_id
221
+ entry.pop("firstKeptEntryIndex", None)
222
+
223
+
224
+ def _migrate_v2_to_v3(entries: list[dict[str, JsonValue]]) -> None:
225
+ for entry in entries:
226
+ if entry.get("type") == "session":
227
+ entry["version"] = 3
228
+ continue
229
+ if entry.get("type") == "message":
230
+ message = entry.get("message")
231
+ if isinstance(message, dict) and message.get("role") == "hookMessage":
232
+ message["role"] = "custom"
233
+
234
+
235
+ # ------------------------------------------------------------------ 树节点
236
+
237
+
238
+ def _empty_children() -> list[SessionTreeNode]:
239
+ """default_factory 的自引用写法:类体内 ``list[SessionTreeNode]`` 会在运行时
240
+ 触发 NameError,而裸 ``list`` 在 strict 模式下推断为 list[Unknown]。"""
241
+ return []
242
+
243
+
244
+ @dataclass(slots=True)
245
+ class SessionTreeNode:
246
+ """getTree() 的节点:条目 + 孩子 + 解析后的 label(防御性副本)。"""
247
+
248
+ entry: SessionEntry
249
+ children: list[SessionTreeNode] = field(default_factory=_empty_children)
250
+ label: str | None = None
251
+ label_timestamp: str | None = None
252
+
253
+
254
+ # --------------------------------------------------------------- SessionManager
255
+
256
+
257
+ class SessionManager:
258
+ """追加式会话树。用 :meth:`create` / :meth:`open` / :meth:`in_memory` 构造。
259
+
260
+ 会话条目有 id/parentId,构成一棵树;"当前叶子"指针标记当前位置,追加在叶子
261
+ 之后长出孩子。分支 = 把叶子拨回早前条目;历史条目永远不被修改或删除。
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ *,
267
+ cwd: str,
268
+ session_dir: str,
269
+ persist: bool,
270
+ session_file: str | None = None,
271
+ preloaded_entries: Sequence[FileEntry | dict[str, JsonValue]] | None = None,
272
+ session_id: str | None = None,
273
+ parent_session: str | None = None,
274
+ clock: Clock | None = None,
275
+ entry_id_factory: Callable[[], str] | None = None,
276
+ session_id_factory: Callable[[], str] | None = None,
277
+ fsync: bool = True,
278
+ lock: SessionFileLock | None = None,
279
+ ) -> None:
280
+ """内部构造器:外部代码请用 :meth:`create` / :meth:`open` / :meth:`in_memory`。
281
+
282
+ ``lock`` 是 :meth:`open` 已经取到的锁(它必须早于读文件),其余路径不传。
283
+ """
284
+ self._cwd = os.path.abspath(cwd)
285
+ self._session_dir = os.path.abspath(session_dir)
286
+ self._persist = persist
287
+ self._fsync = fsync
288
+ self._clock: Clock = clock if clock is not None else SystemClock()
289
+ self._entry_id_factory: Callable[[], str] = entry_id_factory or (
290
+ lambda: uuid.uuid4().hex[:8]
291
+ )
292
+ self._session_id_factory: Callable[[], str] = session_id_factory or (
293
+ lambda: str(uuid.uuid4())
294
+ )
295
+ self._file_entries: list[FileEntry] = []
296
+ self._by_id: dict[str, SessionEntry] = {}
297
+ self._labels: dict[str, str] = {}
298
+ self._label_timestamps: dict[str, str] = {}
299
+ self._leaf_id: str | None = None
300
+ self._flushed = False
301
+ self._session_file: str | None = None
302
+ self._lock: SessionFileLock | None = lock
303
+
304
+ if persist and self._session_dir:
305
+ os.makedirs(self._session_dir, exist_ok=True)
306
+
307
+ if session_file is not None:
308
+ self._set_session_file(session_file, self._raw_entries(preloaded_entries))
309
+ elif preloaded_entries is not None:
310
+ raw = self._raw_entries(preloaded_entries)
311
+ if raw is None: # 不可达:preloaded_entries 非 None 时 _raw_entries 不会返回 None
312
+ raise SessionFormatError("内部错误:preloaded entries 归一化失败")
313
+ self._load_raw_entries(raw, session_id=session_id, parent_session=parent_session)
314
+ else:
315
+ self._new_session(session_id=session_id, parent_session=parent_session)
316
+
317
+ # ------------------------------------------------------------- 构造入口
318
+
319
+ @classmethod
320
+ def create(
321
+ cls,
322
+ cwd: str,
323
+ session_dir: str | None = None,
324
+ *,
325
+ session_id: str | None = None,
326
+ parent_session: str | None = None,
327
+ clock: Clock | None = None,
328
+ entry_id_factory: Callable[[], str] | None = None,
329
+ session_id_factory: Callable[[], str] | None = None,
330
+ fsync: bool = True,
331
+ ) -> SessionManager:
332
+ """新建一个持久化会话。``session_dir`` 省略时用按 cwd 编码的默认目录。"""
333
+ return cls(
334
+ cwd=cwd,
335
+ session_dir=session_dir if session_dir is not None else default_session_dir(cwd),
336
+ persist=True,
337
+ session_id=session_id,
338
+ parent_session=parent_session,
339
+ clock=clock,
340
+ entry_id_factory=entry_id_factory,
341
+ session_id_factory=session_id_factory,
342
+ fsync=fsync,
343
+ )
344
+
345
+ @classmethod
346
+ def open(
347
+ cls,
348
+ path: str,
349
+ session_dir: str | None = None,
350
+ *,
351
+ cwd_override: str | None = None,
352
+ clock: Clock | None = None,
353
+ entry_id_factory: Callable[[], str] | None = None,
354
+ session_id_factory: Callable[[], str] | None = None,
355
+ fsync: bool = True,
356
+ ) -> SessionManager:
357
+ """打开一个会话文件(不存在则之后写到这个路径)。cwd 取头里的值。
358
+
359
+ 锁在读文件**之前**取:读到一半被另一个进程追加的话,"当前叶子"从打开那一刻
360
+ 就是错的,而错在内存里的树比错在磁盘上的文件更难发现。同一个会话文件只能有
361
+ 一个持有者,第二个调用拿到
362
+ :class:`~braid_coding_agent.session.lock.SessionLockedError`。
363
+ """
364
+ resolved = os.path.abspath(path)
365
+ # 锁文件要与会话文件同目录,所以目录得先存在。构造器里对 session_dir 也做
366
+ # 同一件事,取锁提前到读文件之前,这一步就得跟着提前。
367
+ os.makedirs(os.path.dirname(resolved), exist_ok=True)
368
+ lock = SessionFileLock(resolved)
369
+ lock.acquire()
370
+ try:
371
+ raw: list[dict[str, JsonValue]] | None = None
372
+ header_cwd: str | None = None
373
+ if os.path.exists(resolved):
374
+ raw = load_entries_from_file(resolved)
375
+ first = raw[0] if raw else None
376
+ if first is not None and first.get("type") == "session":
377
+ candidate = first.get("cwd")
378
+ if isinstance(candidate, str) and candidate:
379
+ header_cwd = candidate
380
+ cwd = cwd_override or header_cwd or os.getcwd()
381
+ dir_path = session_dir if session_dir is not None else os.path.dirname(resolved)
382
+ return cls(
383
+ cwd=cwd,
384
+ session_dir=dir_path,
385
+ persist=True,
386
+ session_file=resolved,
387
+ preloaded_entries=raw,
388
+ lock=lock,
389
+ clock=clock,
390
+ entry_id_factory=entry_id_factory,
391
+ session_id_factory=session_id_factory,
392
+ fsync=fsync,
393
+ )
394
+ except BaseException:
395
+ # 构造失败时锁要还回去,否则这个进程会一直占着一条它没能打开的会话。
396
+ lock.release()
397
+ raise
398
+
399
+ @classmethod
400
+ def in_memory(
401
+ cls,
402
+ cwd: str | None = None,
403
+ *,
404
+ session_id: str | None = None,
405
+ parent_session: str | None = None,
406
+ entries: Sequence[FileEntry | dict[str, JsonValue]] | None = None,
407
+ clock: Clock | None = None,
408
+ entry_id_factory: Callable[[], str] | None = None,
409
+ session_id_factory: Callable[[], str] | None = None,
410
+ ) -> SessionManager:
411
+ """内存会话:不落盘。``entries`` 可以是别的会话导出的条目(typed 或 raw dict)。"""
412
+ return cls(
413
+ cwd=cwd if cwd is not None else os.getcwd(),
414
+ session_dir="",
415
+ persist=False,
416
+ session_id=session_id,
417
+ parent_session=parent_session,
418
+ preloaded_entries=entries,
419
+ clock=clock,
420
+ entry_id_factory=entry_id_factory,
421
+ session_id_factory=session_id_factory,
422
+ )
423
+
424
+ @classmethod
425
+ def _adopt(
426
+ cls,
427
+ *,
428
+ cwd: str,
429
+ session_dir: str,
430
+ persist: bool,
431
+ session_file: str | None,
432
+ file_entries: list[FileEntry],
433
+ session_id: str,
434
+ clock: Clock,
435
+ entry_id_factory: Callable[[], str],
436
+ fsync: bool,
437
+ ) -> SessionManager:
438
+ """用现成的条目列表直接组装一个管理器(fork/clone 内部用)。"""
439
+ manager = cls(
440
+ cwd=cwd,
441
+ session_dir=session_dir,
442
+ persist=persist,
443
+ clock=clock,
444
+ entry_id_factory=entry_id_factory,
445
+ fsync=fsync,
446
+ )
447
+ manager._session_id = session_id
448
+ manager._session_file = session_file
449
+ manager._file_entries = file_entries
450
+ manager._build_index()
451
+ return manager
452
+
453
+ # ----------------------------------------------------------- 内部装载
454
+
455
+ @staticmethod
456
+ def _raw_entries(
457
+ entries: Sequence[FileEntry | dict[str, JsonValue]] | None,
458
+ ) -> list[dict[str, JsonValue]] | None:
459
+ """typed 条目转回 wire dict,dict 原样保留;``None`` 原样返回。"""
460
+ if entries is None:
461
+ return None
462
+ raw: list[dict[str, JsonValue]] = []
463
+ for item in entries:
464
+ if isinstance(item, dict):
465
+ raw.append(dict(item))
466
+ else:
467
+ raw.append(entry_to_wire(item))
468
+ return raw
469
+
470
+ def _set_session_file(
471
+ self, session_file: str, preloaded: list[dict[str, JsonValue]] | None
472
+ ) -> None:
473
+ self._session_file = os.path.abspath(session_file)
474
+ if os.path.exists(self._session_file):
475
+ # 锁必须在读文件之前就在手:``open()`` 已经在调用本方法之前取好并传进来,
476
+ # 直接构造的情况在这里补取。读到一半被另一个进程追加的话,"当前叶子"
477
+ # 从打开那一刻就是错的,而错在内存里的树比错在磁盘上的文件更难发现。
478
+ self._ensure_lock()
479
+ raw = preloaded if preloaded is not None else load_entries_from_file(self._session_file)
480
+ if not raw:
481
+ # 空文件:初始化成合法会话。非空但读不出头:不是会话文件,拒绝修改。
482
+ if os.path.getsize(self._session_file) > 0:
483
+ raise SessionFormatError(f"不是有效的会话文件: {self._session_file}")
484
+ self._new_session()
485
+ self._session_file = os.path.abspath(session_file)
486
+ self._rewrite_file()
487
+ self._flushed = True
488
+ return
489
+ self._load_raw_entries(raw)
490
+ self._flushed = True
491
+ else:
492
+ self._new_session()
493
+ self._session_file = os.path.abspath(session_file)
494
+ # 这个路径将要由本进程创建:现在占住它,第二个进程在 open 阶段就会失败,
495
+ # 而不是等到第一次追加撞上 O_EXCL。
496
+ self._ensure_lock()
497
+
498
+ def _load_raw_entries(
499
+ self,
500
+ raw_entries: list[dict[str, JsonValue]],
501
+ *,
502
+ session_id: str | None = None,
503
+ parent_session: str | None = None,
504
+ ) -> None:
505
+ header_raw = next((entry for entry in raw_entries if entry.get("type") == "session"), None)
506
+ if header_raw is not None:
507
+ migrated = migrate_session_entries(raw_entries)
508
+ self._file_entries = [entry_from_wire(item) for item in raw_entries]
509
+ header = next(entry for entry in self._file_entries if isinstance(entry, SessionHeader))
510
+ self._session_id = header.id
511
+ if migrated and self._persist and self._session_file is not None:
512
+ self._rewrite_file()
513
+ else:
514
+ # 没有头的条目(如外部导入):先造头,再原样接上。
515
+ self._new_session(session_id=session_id, parent_session=parent_session)
516
+ self._file_entries.extend(entry_from_wire(item) for item in raw_entries)
517
+ self._build_index()
518
+
519
+ def _new_session(
520
+ self, *, session_id: str | None = None, parent_session: str | None = None
521
+ ) -> None:
522
+ if session_id is not None:
523
+ assert_valid_session_id(session_id)
524
+ self._session_id = session_id or self._session_id_factory()
525
+ timestamp = iso_from_ms(self._clock.now_ms())
526
+ self._file_entries = [
527
+ SessionHeader(
528
+ id=self._session_id,
529
+ timestamp=timestamp,
530
+ cwd=self._cwd,
531
+ version=CURRENT_SESSION_VERSION,
532
+ parent_session=parent_session,
533
+ )
534
+ ]
535
+ self._by_id.clear()
536
+ self._labels.clear()
537
+ self._label_timestamps.clear()
538
+ self._leaf_id = None
539
+ self._flushed = False
540
+ if self._persist:
541
+ file_timestamp = re.sub(r"[:.]", "-", timestamp)
542
+ self._session_file = os.path.join(
543
+ self._session_dir, f"{file_timestamp}_{self._session_id}.jsonl"
544
+ )
545
+
546
+ def _build_index(self) -> None:
547
+ self._by_id.clear()
548
+ self._labels.clear()
549
+ self._label_timestamps.clear()
550
+ self._leaf_id = None
551
+ for entry in self._file_entries:
552
+ if isinstance(entry, SessionHeader):
553
+ continue
554
+ self._by_id[entry.id] = entry
555
+ self._leaf_id = entry.id
556
+ if isinstance(entry, LabelEntry):
557
+ if entry.label:
558
+ self._labels[entry.target_id] = entry.label
559
+ self._label_timestamps[entry.target_id] = entry.timestamp
560
+ else:
561
+ self._labels.pop(entry.target_id, None)
562
+ self._label_timestamps.pop(entry.target_id, None)
563
+
564
+ # ------------------------------------------------------------- 持久化
565
+
566
+ def _ensure_lock(self) -> None:
567
+ """取会话文件的独占锁。已持有或不需要落盘时什么都不做。
568
+
569
+ ``open()`` 在读文件之前就把锁取好了(它必须早于读,见 :meth:`open`),这里
570
+ 补的是另外两个写入口:第一次真正落盘之前(:meth:`_persist_entry`)与整份
571
+ 重写之前(:meth:`_rewrite_file`)。首次落盘才取锁让"建了会话但一句话没说"
572
+ 的进程不留下锁文件——那种会话连会话文件本身都还没创建。
573
+
574
+ :raises SessionLockedError: 另一个写入者正持有这个会话文件。
575
+ """
576
+ if not self._persist or self._session_file is None or self._lock is not None:
577
+ return
578
+ lock = SessionFileLock(self._session_file)
579
+ lock.acquire()
580
+ self._lock = lock
581
+
582
+ def release_lock(self) -> None:
583
+ """释放会话文件锁(幂等)。进程退出时内核也会释放。"""
584
+ lock = self._lock
585
+ if lock is None:
586
+ return
587
+ self._lock = None
588
+ lock.release()
589
+
590
+ @property
591
+ def is_locked(self) -> bool:
592
+ """是否持有该会话文件的独占锁。"""
593
+ return self._lock is not None
594
+
595
+ def _has_conversation(self) -> bool:
596
+ """只有出现过 user/assistant 消息才值得落盘:纯设置条目留在内存。"""
597
+ return any(
598
+ isinstance(entry, SessionMessageEntry)
599
+ and isinstance(entry.message, (UserMessage, AssistantMessage))
600
+ for entry in self._file_entries
601
+ )
602
+
603
+ def _persist_entry(self, entry: SessionEntry) -> None:
604
+ if not self._persist or self._session_file is None:
605
+ return
606
+ if not self._flushed:
607
+ if not self._has_conversation():
608
+ return
609
+ self.flush()
610
+ else:
611
+ with open(self._session_file, "a", encoding="utf-8", newline="\n") as handle:
612
+ handle.write(_dumps(entry) + "\n")
613
+ _flush_and_sync(handle, self._fsync)
614
+
615
+ def flush(self) -> None:
616
+ """显式把当前会话树落盘,即使还没有 user/assistant 消息。
617
+
618
+ ``/init`` 这类命令只产生 ``custom`` 条目。首次落盘默认要等一次真实对话,
619
+ 否则用户生成草稿后直接退出,恢复会话时看不到这次生成的结果。
620
+ """
621
+ if not self._persist or self._session_file is None or self._flushed:
622
+ return
623
+ # 首次落盘:先占住文件,再独占创建(O_EXCL 撞车只会发生在没抢到锁的时候)。
624
+ self._ensure_lock()
625
+ descriptor = os.open(self._session_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
626
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
627
+ for item in self._file_entries:
628
+ handle.write(_dumps(item) + "\n")
629
+ _flush_and_sync(handle, self._fsync)
630
+ self._flushed = True
631
+
632
+ def _rewrite_file(self) -> None:
633
+ if not self._persist or self._session_file is None:
634
+ return
635
+ # 整份重写是最危险的一类写:没锁住就写,会把另一个进程刚追加的行抹掉。
636
+ self._ensure_lock()
637
+ with open(self._session_file, "w", encoding="utf-8", newline="\n") as handle:
638
+ for item in self._file_entries:
639
+ handle.write(_dumps(item) + "\n")
640
+ _flush_and_sync(handle, self._fsync)
641
+
642
+ # --------------------------------------------------------------- 追加
643
+
644
+ def _next_entry_id(self) -> str:
645
+ return _unique_id(set(self._by_id), self._entry_id_factory)
646
+
647
+ def _append_entry(self, entry: SessionEntry) -> None:
648
+ self._file_entries.append(entry)
649
+ self._by_id[entry.id] = entry
650
+ self._leaf_id = entry.id
651
+ self._persist_entry(entry)
652
+
653
+ def _now_iso(self) -> str:
654
+ return iso_from_ms(self._clock.now_ms())
655
+
656
+ def append_message(self, message: StorableMessage) -> str:
657
+ """追加一条对话消息(当前叶子的孩子),返回条目 id。
658
+
659
+ ``branchSummary``/``compactionSummary`` 是投影产物,只能通过对应的
660
+ append 方法作为独立条目写入(在运行时强制)。
661
+ """
662
+ if isinstance(message, (BranchSummaryMessage, CompactionSummaryMessage)):
663
+ raise ValueError(
664
+ "branchSummary/compactionSummary 是投影产物,"
665
+ "请用 append_branch_summary / append_compaction 写入"
666
+ )
667
+ entry = SessionMessageEntry(
668
+ id=self._next_entry_id(),
669
+ parent_id=self._leaf_id,
670
+ timestamp=self._now_iso(),
671
+ message=message,
672
+ )
673
+ self._append_entry(entry)
674
+ return entry.id
675
+
676
+ def append_model_change(self, provider: str, model_id: str) -> str:
677
+ entry = ModelChangeEntry(
678
+ id=self._next_entry_id(),
679
+ parent_id=self._leaf_id,
680
+ timestamp=self._now_iso(),
681
+ provider=provider,
682
+ model_id=model_id,
683
+ )
684
+ self._append_entry(entry)
685
+ return entry.id
686
+
687
+ def append_thinking_level_change(self, thinking_level: str) -> str:
688
+ entry = ThinkingLevelChangeEntry(
689
+ id=self._next_entry_id(),
690
+ parent_id=self._leaf_id,
691
+ timestamp=self._now_iso(),
692
+ thinking_level=thinking_level,
693
+ )
694
+ self._append_entry(entry)
695
+ return entry.id
696
+
697
+ def append_usage(
698
+ self,
699
+ kind: str,
700
+ provider: str,
701
+ model: str,
702
+ usage: Usage,
703
+ note: str | None = None,
704
+ ) -> str:
705
+ entry = UsageEntry(
706
+ id=self._next_entry_id(),
707
+ parent_id=self._leaf_id,
708
+ timestamp=self._now_iso(),
709
+ kind=kind,
710
+ provider=provider,
711
+ model=model,
712
+ usage=usage,
713
+ note=note,
714
+ )
715
+ self._append_entry(entry)
716
+ return entry.id
717
+
718
+ def append_compaction(
719
+ self,
720
+ *,
721
+ summary: str,
722
+ tokens_before: int,
723
+ first_kept_entry_id: str | None = None,
724
+ system_message: SystemMessage | None = None,
725
+ usage: Usage | None = None,
726
+ details: JsonValue | None = None,
727
+ from_hook: bool = False,
728
+ ) -> str:
729
+ """追加压缩条目,返回条目 id。
730
+
731
+ ``system_message`` 省略时从当前投影计算检查点。``first_kept_entry_id``
732
+ 为 ``None`` 表示"一条都不保留",条目存自己的 id。
733
+ ``from_hook`` 标记"摘要由扩展提供":恢复与导出时能看出这条摘要不是
734
+ 模型生成的。
735
+ """
736
+ timestamp = self._now_iso()
737
+ entry_id = self._next_entry_id()
738
+ if system_message is None:
739
+ system_message = _current_system_message(self.build_projection().messages)
740
+ entry = CompactionEntry(
741
+ id=entry_id,
742
+ parent_id=self._leaf_id,
743
+ timestamp=timestamp,
744
+ summary=summary,
745
+ first_kept_entry_id=first_kept_entry_id
746
+ if first_kept_entry_id is not None
747
+ else entry_id,
748
+ tokens_before=tokens_before,
749
+ details=details,
750
+ usage=usage,
751
+ from_hook=True if from_hook else None,
752
+ system_message=replace(system_message, timestamp=ms_from_iso(timestamp))
753
+ if system_message is not None
754
+ else None,
755
+ )
756
+ self._append_entry(entry)
757
+ return entry.id
758
+
759
+ def append_custom(self, custom_type: str, data: JsonValue | None = None) -> str:
760
+ entry = CustomEntry(
761
+ id=self._next_entry_id(),
762
+ parent_id=self._leaf_id,
763
+ timestamp=self._now_iso(),
764
+ custom_type=custom_type,
765
+ data=data,
766
+ )
767
+ self._append_entry(entry)
768
+ return entry.id
769
+
770
+ def append_custom_message(
771
+ self,
772
+ custom_type: str,
773
+ content: TextImageContent,
774
+ display: bool,
775
+ details: JsonValue | None = None,
776
+ ) -> str:
777
+ entry = CustomMessageEntry(
778
+ id=self._next_entry_id(),
779
+ parent_id=self._leaf_id,
780
+ timestamp=self._now_iso(),
781
+ custom_type=custom_type,
782
+ content=content,
783
+ display=display,
784
+ details=details,
785
+ )
786
+ self._append_entry(entry)
787
+ return entry.id
788
+
789
+ def append_session_info(self, name: str) -> str:
790
+ sanitized = re.sub(r"[\r\n]+", " ", name).strip()
791
+ entry = SessionInfoEntry(
792
+ id=self._next_entry_id(),
793
+ parent_id=self._leaf_id,
794
+ timestamp=self._now_iso(),
795
+ name=sanitized,
796
+ )
797
+ self._append_entry(entry)
798
+ return entry.id
799
+
800
+ def append_context_edit(self, target_id: str, replacement: ContextReplacement | None) -> str:
801
+ """对活动分支上的早前条目做追加式编辑;原始条目不动,只改此后模型看到的样子。"""
802
+ target = self._by_id.get(target_id)
803
+ if target is None:
804
+ raise ValueError(f"条目 {target_id} 不存在")
805
+ if not any(entry.id == target_id for entry in self.get_branch()):
806
+ raise ValueError(f"条目 {target_id} 不在活动分支上")
807
+ editable = isinstance(target, CustomMessageEntry) or (
808
+ isinstance(target, SessionMessageEntry)
809
+ and isinstance(target.message, (UserMessage, AssistantMessage, ToolResultMessage))
810
+ )
811
+ if not editable:
812
+ raise ValueError(f"条目 {target_id} 不产生可编辑的模型内容")
813
+ normalized = replacement
814
+ if (
815
+ replacement is not None
816
+ and isinstance(target, SessionMessageEntry)
817
+ and isinstance(target.message, (AssistantMessage, ToolResultMessage))
818
+ and isinstance(replacement.content, str)
819
+ ):
820
+ # assistant/toolResult 的内容必须是块数组:字符串替换归一成一个 text 块。
821
+ normalized = ContextReplacement(content=[TextContent(text=replacement.content)])
822
+ entry = ContextEditEntry(
823
+ id=self._next_entry_id(),
824
+ parent_id=self._leaf_id,
825
+ timestamp=self._now_iso(),
826
+ target_id=target_id,
827
+ replacement=normalized,
828
+ )
829
+ self._append_entry(entry)
830
+ return entry.id
831
+
832
+ def append_label(self, target_id: str, label: str | None) -> str:
833
+ """给条目设书签;``label=None`` 清除。"""
834
+ if target_id not in self._by_id:
835
+ raise ValueError(f"条目 {target_id} 不存在")
836
+ entry = LabelEntry(
837
+ id=self._next_entry_id(),
838
+ parent_id=self._leaf_id,
839
+ timestamp=self._now_iso(),
840
+ target_id=target_id,
841
+ label=label,
842
+ )
843
+ self._append_entry(entry)
844
+ if label:
845
+ self._labels[target_id] = label
846
+ self._label_timestamps[target_id] = entry.timestamp
847
+ else:
848
+ self._labels.pop(target_id, None)
849
+ self._label_timestamps.pop(target_id, None)
850
+ return entry.id
851
+
852
+ def append_branch_summary(
853
+ self,
854
+ branch_from_id: str | None,
855
+ summary: str,
856
+ *,
857
+ details: JsonValue | None = None,
858
+ usage: Usage | None = None,
859
+ ) -> str:
860
+ """从 ``branch_from_id`` 开新分支并写入被放弃路径的摘要。``None`` 表示开新根。"""
861
+ if branch_from_id is not None and branch_from_id not in self._by_id:
862
+ raise ValueError(f"条目 {branch_from_id} 不存在")
863
+ from_id = self._leaf_id if self._leaf_id is not None else "root"
864
+ self._leaf_id = branch_from_id
865
+ entry = BranchSummaryEntry(
866
+ id=self._next_entry_id(),
867
+ parent_id=branch_from_id,
868
+ timestamp=self._now_iso(),
869
+ from_id=from_id,
870
+ summary=summary,
871
+ details=details,
872
+ usage=usage,
873
+ )
874
+ self._append_entry(entry)
875
+ return entry.id
876
+
877
+ # ----------------------------------------------------------- 树遍历
878
+
879
+ @property
880
+ def leaf_id(self) -> str | None:
881
+ """当前叶子。``None`` 表示"任何条目之前"。"""
882
+ return self._leaf_id
883
+
884
+ def move_to(self, entry_id: str | None) -> None:
885
+ """把叶子指针拨到指定条目(``None`` 拨回根之前)。历史条目原样保留。"""
886
+ if entry_id is not None and entry_id not in self._by_id:
887
+ raise ValueError(f"条目 {entry_id} 不存在")
888
+ self._leaf_id = entry_id
889
+
890
+ def rewind(self, entry_id: str | None, summary: str) -> str:
891
+ """把活动分支拨回 ``entry_id``,并把被放弃路径的摘要写成新条目。
892
+
893
+ ``entry_id`` 为 ``None`` 表示回到会话开始(第一条消息之前)。返回新条目的 id。
894
+
895
+ 与 :meth:`fork` 的分工:``fork`` 把路径复制到**新文件**,原会话不动,适合
896
+ "我想从这儿另起一条线";``rewind`` 在**同一棵树上**从早前的位置重新长分支,
897
+ 被放弃的条目原样留在文件里,适合"这段不成立,回去重说"。
898
+
899
+ 记录摘要而不是只挪指针:叶子指针在内存里,进程重启后由文件顺序恢复,光挪指针
900
+ 等于什么都没发生。摘要条目是树上真实的一行,重启后路径自然从它继续。
901
+
902
+ :raises ValueError: 目标条目不存在,或不在活动分支上。
903
+ """
904
+ if entry_id is not None:
905
+ if entry_id not in self._by_id:
906
+ raise ValueError(f"条目 {entry_id} 不存在")
907
+ if not any(entry.id == entry_id for entry in self.get_branch()):
908
+ raise ValueError(f"条目 {entry_id} 不在活动分支上,不能作为回退目标")
909
+ return self.append_branch_summary(entry_id, summary)
910
+
911
+ def get_leaf_entry(self) -> SessionEntry | None:
912
+ return self._by_id.get(self._leaf_id) if self._leaf_id is not None else None
913
+
914
+ def get_entry(self, entry_id: str) -> SessionEntry | None:
915
+ return self._by_id.get(entry_id)
916
+
917
+ def get_children(self, parent_id: str) -> list[SessionEntry]:
918
+ return [entry for entry in self._by_id.values() if entry.parent_id == parent_id]
919
+
920
+ def get_label(self, entry_id: str) -> str | None:
921
+ return self._labels.get(entry_id)
922
+
923
+ def get_branch(self, from_id: str | None = None) -> list[SessionEntry]:
924
+ """从指定条目(默认当前叶子)回溯到根,根→叶顺序。"""
925
+ start = from_id if from_id is not None else self._leaf_id
926
+ path: list[SessionEntry] = []
927
+ current = self._by_id.get(start) if start is not None else None
928
+ while current is not None:
929
+ path.append(current)
930
+ current = self._by_id.get(current.parent_id) if current.parent_id is not None else None
931
+ path.reverse()
932
+ return path
933
+
934
+ def get_entries(self) -> list[SessionEntry]:
935
+ """全部树条目(不含头),文件顺序的浅拷贝。会话是追加式的:改内容请走条目级 API。"""
936
+ return [entry for entry in self._file_entries if not isinstance(entry, SessionHeader)]
937
+
938
+ def get_header(self) -> SessionHeader | None:
939
+ return next(
940
+ (entry for entry in self._file_entries if isinstance(entry, SessionHeader)), None
941
+ )
942
+
943
+ def get_entry_count(self) -> int:
944
+ return len(self._by_id)
945
+
946
+ def get_session_name(self) -> str | None:
947
+ """最新的 session_info 名字;空名字视为显式清除。"""
948
+ for entry in reversed(self._file_entries):
949
+ if isinstance(entry, SessionInfoEntry):
950
+ if entry.name and entry.name.strip():
951
+ return entry.name.strip()
952
+ return None
953
+ return None
954
+
955
+ def get_tree(self) -> list[SessionTreeNode]:
956
+ """整棵树(可含多个根:孤儿条目也是根)。孩子按时间戳升序。"""
957
+ nodes: dict[str, SessionTreeNode] = {}
958
+ roots: list[SessionTreeNode] = []
959
+ entries = self.get_entries()
960
+ for entry in entries:
961
+ nodes[entry.id] = SessionTreeNode(
962
+ entry=entry,
963
+ label=self._labels.get(entry.id),
964
+ label_timestamp=self._label_timestamps.get(entry.id),
965
+ )
966
+ for entry in entries:
967
+ node = nodes[entry.id]
968
+ if entry.parent_id is None or entry.parent_id == entry.id:
969
+ roots.append(node)
970
+ continue
971
+ parent = nodes.get(entry.parent_id)
972
+ if parent is not None:
973
+ parent.children.append(node)
974
+ else:
975
+ roots.append(node)
976
+ stack = list(roots)
977
+ while stack:
978
+ node = stack.pop()
979
+ node.children.sort(key=lambda child: ms_from_iso(child.entry.timestamp))
980
+ stack.extend(node.children)
981
+ return roots
982
+
983
+ # ------------------------------------------------------------- 投影
984
+
985
+ def build_context_entries(self, leaf_id: LeafArg = UNSET) -> list[SessionEntry]:
986
+ """压缩感知的活动条目列表。``leaf_id`` 缺省用当前叶子,``None`` 是空路径。"""
987
+ resolved = self._leaf_id if leaf_id is UNSET else leaf_id
988
+ return projection.build_context_entries(self.get_entries(), resolved, self._by_id)
989
+
990
+ def build_projection(self, leaf_id: LeafArg = UNSET) -> SessionProjection:
991
+ """带出处的模型上下文。"""
992
+ resolved = self._leaf_id if leaf_id is UNSET else leaf_id
993
+ return projection.build_session_projection(self.get_entries(), resolved, self._by_id)
994
+
995
+ def build_context(self, leaf_id: LeafArg = UNSET) -> SessionContext:
996
+ """发给 LLM 的最终上下文:消息 + 思考级别 + 当前模型。"""
997
+ resolved = self._leaf_id if leaf_id is UNSET else leaf_id
998
+ return projection.build_session_context(self.get_entries(), resolved, self._by_id)
999
+
1000
+ # ------------------------------------------------------------- 分支
1001
+
1002
+ def fork(self, entry_id: str) -> SessionManager:
1003
+ """从指定条目分叉:新会话文件只含根到该条目的路径,``parentSession`` 指回原文件。
1004
+
1005
+ 返回新对象,当前会话不动。路径上的 label 条目被摘出重挂到链尾,避免孤儿。
1006
+ """
1007
+ branch = self.get_branch(entry_id)
1008
+ if not branch:
1009
+ raise ValueError(f"条目 {entry_id} 不存在")
1010
+ return self._branched_session(branch)
1011
+
1012
+ def clone(self) -> SessionManager:
1013
+ """复制当前活动分支成新会话。"""
1014
+ if self._leaf_id is None:
1015
+ raise ValueError("当前没有活动分支(叶子为空),无法 clone")
1016
+ return self.fork(self._leaf_id)
1017
+
1018
+ def _branched_session(self, branch: list[SessionEntry]) -> SessionManager:
1019
+ path_without_labels: list[SessionEntry] = []
1020
+ replacement_by_label_id: dict[str, str] = {}
1021
+ pending_label_ids: list[str] = []
1022
+ path_parent_id: str | None = None
1023
+ for entry in branch:
1024
+ if isinstance(entry, LabelEntry):
1025
+ pending_label_ids.append(entry.id)
1026
+ continue
1027
+ for label_id in pending_label_ids:
1028
+ replacement_by_label_id[label_id] = entry.id
1029
+ pending_label_ids.clear()
1030
+ if isinstance(entry, CompactionEntry):
1031
+ first_kept = entry.first_kept_entry_id
1032
+ if first_kept != entry.id:
1033
+ first_kept = replacement_by_label_id.get(first_kept, first_kept)
1034
+ entry = replace(entry, parent_id=path_parent_id, first_kept_entry_id=first_kept)
1035
+ else:
1036
+ entry = _reparented(entry, path_parent_id)
1037
+ path_without_labels.append(entry)
1038
+ path_parent_id = entry.id
1039
+
1040
+ path_entry_ids = {entry.id for entry in path_without_labels}
1041
+ labels_to_write = [
1042
+ (target_id, label, self._label_timestamps[target_id])
1043
+ for target_id, label in self._labels.items()
1044
+ if target_id in path_entry_ids
1045
+ ]
1046
+
1047
+ new_session_id = self._session_id_factory()
1048
+ timestamp = self._now_iso()
1049
+ header = SessionHeader(
1050
+ id=new_session_id,
1051
+ timestamp=timestamp,
1052
+ cwd=self._cwd,
1053
+ version=CURRENT_SESSION_VERSION,
1054
+ parent_session=self._session_file if self._persist else None,
1055
+ )
1056
+
1057
+ label_entries: list[LabelEntry] = []
1058
+ parent = path_without_labels[-1].id if path_without_labels else None
1059
+ existing_ids = set(path_entry_ids)
1060
+ for target_id, label, label_timestamp in labels_to_write:
1061
+ label_entry = LabelEntry(
1062
+ id=_unique_id(existing_ids, self._entry_id_factory),
1063
+ parent_id=parent,
1064
+ timestamp=label_timestamp,
1065
+ target_id=target_id,
1066
+ label=label,
1067
+ )
1068
+ existing_ids.add(label_entry.id)
1069
+ label_entries.append(label_entry)
1070
+ parent = label_entry.id
1071
+
1072
+ file_entries: list[FileEntry] = [header, *path_without_labels, *label_entries]
1073
+
1074
+ if self._persist:
1075
+ file_timestamp = re.sub(r"[:.]", "-", timestamp)
1076
+ new_file = os.path.join(self._session_dir, f"{file_timestamp}_{new_session_id}.jsonl")
1077
+ branched = SessionManager._adopt(
1078
+ cwd=self._cwd,
1079
+ session_dir=self._session_dir,
1080
+ persist=True,
1081
+ session_file=new_file,
1082
+ file_entries=file_entries,
1083
+ session_id=new_session_id,
1084
+ clock=self._clock,
1085
+ entry_id_factory=self._entry_id_factory,
1086
+ fsync=self._fsync,
1087
+ )
1088
+ # 与 _persist_entry 同一条规则:有对话立刻写,纯设置条目等出现对话再写。
1089
+ if branched._has_conversation():
1090
+ branched._rewrite_file()
1091
+ branched._flushed = True
1092
+ return branched
1093
+ return SessionManager._adopt(
1094
+ cwd=self._cwd,
1095
+ session_dir="",
1096
+ persist=False,
1097
+ session_file=None,
1098
+ file_entries=file_entries,
1099
+ session_id=new_session_id,
1100
+ clock=self._clock,
1101
+ entry_id_factory=self._entry_id_factory,
1102
+ fsync=self._fsync,
1103
+ )
1104
+
1105
+ # ------------------------------------------------------------- 元信息
1106
+
1107
+ def is_persisted(self) -> bool:
1108
+ return self._persist
1109
+
1110
+ def get_cwd(self) -> str:
1111
+ return self._cwd
1112
+
1113
+ def get_session_dir(self) -> str:
1114
+ return self._session_dir
1115
+
1116
+ def get_session_id(self) -> str:
1117
+ return self._session_id
1118
+
1119
+ def get_session_file(self) -> str | None:
1120
+ return self._session_file
1121
+
1122
+
1123
+ # ------------------------------------------------------------------- 辅助
1124
+
1125
+
1126
+ def _dumps(entry: FileEntry) -> str:
1127
+ """条目 → 单行 JSON。紧凑分隔符与非 ASCII 直出,与 JS ``JSON.stringify`` 同形。"""
1128
+ return json.dumps(entry_to_wire(entry), ensure_ascii=False, separators=(",", ":"))
1129
+
1130
+
1131
+ def _flush_and_sync(handle: TextIOWrapper, fsync: bool) -> None:
1132
+ """写完就刷;``fsync=True`` 时连元数据一起推到磁盘(崩溃后文件仍然成立)。"""
1133
+ handle.flush()
1134
+ if fsync:
1135
+ os.fsync(handle.fileno())
1136
+
1137
+
1138
+ def _reparented(entry: SessionEntry, parent_id: str | None) -> SessionEntry:
1139
+ """复制条目并改写 parent_id。union 上的 dataclasses.replace 需要逐类型收窄。"""
1140
+ match entry:
1141
+ case SessionMessageEntry():
1142
+ return replace(entry, parent_id=parent_id)
1143
+ case ThinkingLevelChangeEntry():
1144
+ return replace(entry, parent_id=parent_id)
1145
+ case ModelChangeEntry():
1146
+ return replace(entry, parent_id=parent_id)
1147
+ case UsageEntry():
1148
+ return replace(entry, parent_id=parent_id)
1149
+ case BranchSummaryEntry():
1150
+ return replace(entry, parent_id=parent_id)
1151
+ case CustomEntry():
1152
+ return replace(entry, parent_id=parent_id)
1153
+ case CustomMessageEntry():
1154
+ return replace(entry, parent_id=parent_id)
1155
+ case ContextEditEntry():
1156
+ return replace(entry, parent_id=parent_id)
1157
+ case LabelEntry():
1158
+ return replace(entry, parent_id=parent_id)
1159
+ case SessionInfoEntry():
1160
+ return replace(entry, parent_id=parent_id)
1161
+ case UnknownEntry():
1162
+ return replace(entry, parent_id=parent_id)
1163
+ case CompactionEntry():
1164
+ raise SessionFormatError("compaction 条目应在上层单独处理")
1165
+
1166
+
1167
+ def _current_system_message(messages: Sequence[ProjectedMessage]) -> SystemMessage | None:
1168
+ """从投影消息里重放出当前系统消息(压缩检查点)。"""
1169
+ llm_messages = [
1170
+ message
1171
+ for message in messages
1172
+ if isinstance(message, (SystemMessage, UserMessage, AssistantMessage, ToolResultMessage))
1173
+ ]
1174
+ return get_current_system_message(llm_messages)
1175
+
1176
+
1177
+ __all__ = [
1178
+ "CURRENT_SESSION_VERSION",
1179
+ "SessionManager",
1180
+ "SessionTreeNode",
1181
+ "assert_valid_session_id",
1182
+ "default_session_dir",
1183
+ "load_entries_from_file",
1184
+ "migrate_session_entries",
1185
+ ]