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,809 @@
1
+ """会话条目:JSONL 会话文件里的一行,以及编码层自己的消息角色。
2
+
3
+ 分三块:
4
+
5
+ - **条目**(:data:`SessionEntry` 联合):树节点,``id``/``parent_id``/``timestamp``
6
+ 是公共骨架,``type`` 判别具体条目。未知类型保成 :class:`UnknownEntry`——新版本
7
+ 写出的条目在旧代码里仍是合法树节点,只是不贡献上下文。
8
+ - **编码层消息**(:class:`CustomMessage` 等):只存在于 coding-agent 的转录角色,
9
+ ``braid_ai`` 不认识它们;哪些能进模型由 ``convert_to_llm`` 决定。
10
+ - **双向 wire 映射**::func:`entry_to_wire` / :func:`entry_from_wire`。四种 LLM 角色
11
+ 的嵌套消息直接复用 :mod:`braid_ai.wire`,本模块只负责条目外壳。
12
+
13
+ 时间纪律:**条目**时间戳是 ISO 8601 UTC 字符串(带毫秒),
14
+ **消息内**时间戳是毫秒整数。:func:`iso_from_ms` / :func:`ms_from_iso` 是两个方向
15
+ 的唯一出入口。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Mapping
21
+ from dataclasses import dataclass, field
22
+ from datetime import UTC, datetime, timedelta
23
+ from typing import ClassVar, Final, Literal
24
+
25
+ from braid_ai.types import (
26
+ ImageContent,
27
+ JsonValue,
28
+ Message,
29
+ SystemMessage,
30
+ TextContent,
31
+ Usage,
32
+ )
33
+ from braid_ai.wire import (
34
+ WireError,
35
+ content_to_wire,
36
+ usage_from_wire,
37
+ usage_to_wire,
38
+ user_content_from_wire,
39
+ )
40
+ from braid_ai.wire import (
41
+ message_from_wire as _llm_message_from_wire,
42
+ )
43
+ from braid_ai.wire import (
44
+ message_to_wire as _llm_message_to_wire,
45
+ )
46
+
47
+ #: 当前会话文件版本。v1 线性 → v2 树 → v3 hookMessage 更名 custom。
48
+ CURRENT_SESSION_VERSION: Final[int] = 3
49
+
50
+
51
+ class SessionFormatError(ValueError):
52
+ """会话文件内容不符合格式。
53
+
54
+ 与 :class:`braid_ai.wire.WireError` 的分工:WireError 管"消息形状",
55
+ SessionFormatError 管"文件结构"——坏行、缺头、条目缺 id、message 条目里
56
+ 出现投影角色等。
57
+ """
58
+
59
+
60
+ # ------------------------------------------------------------------ 时间换算
61
+
62
+ _EPOCH: Final[datetime] = datetime(1970, 1, 1, tzinfo=UTC)
63
+
64
+
65
+ def iso_from_ms(ms: int) -> str:
66
+ """毫秒整数 → ISO 8601 UTC(带毫秒、``Z`` 结尾),与 ``Date.toISOString()`` 同形。
67
+
68
+ 用 ``timedelta`` 做整数加法,绕开浮点秒换算的舍入误差。
69
+ """
70
+ moment = _EPOCH + timedelta(milliseconds=ms)
71
+ return (
72
+ f"{moment.year:04d}-{moment.month:02d}-{moment.day:02d}"
73
+ f"T{moment.hour:02d}:{moment.minute:02d}:{moment.second:02d}"
74
+ f".{moment.microsecond // 1000:03d}Z"
75
+ )
76
+
77
+
78
+ def ms_from_iso(value: str) -> int:
79
+ """ISO 8601 → 毫秒整数。naive 值按 UTC 处理。"""
80
+ try:
81
+ moment = datetime.fromisoformat(value)
82
+ except ValueError as exc:
83
+ raise SessionFormatError(f"非法的条目时间戳: {value!r}") from exc
84
+ if moment.tzinfo is None:
85
+ moment = moment.replace(tzinfo=UTC)
86
+ delta = moment - _EPOCH
87
+ return delta.days * 86_400_000 + delta.seconds * 1000 + delta.microseconds // 1000
88
+
89
+
90
+ # ------------------------------------------------------------- 编码层消息角色
91
+
92
+ #: ``str`` 或 ``TextContent | ImageContent`` 数组,user/custom 消息共用的内容形状。
93
+ type TextImageContent = str | list[TextContent | ImageContent]
94
+
95
+
96
+ @dataclass(slots=True, kw_only=True)
97
+ class CustomMessage:
98
+ """扩展注入、参与模型上下文的消息(``role="custom"``)。
99
+
100
+ ``content`` 是模型可见内容;
101
+ ``display`` 只控制 UI 渲染;``details`` 只给扩展自己。从 wire 读入时
102
+ ``customType`` 缺失按空串处理——v2 的 ``hookMessage`` 迁移后可能没有这个字段。
103
+ """
104
+
105
+ custom_type: str
106
+ timestamp: int
107
+ content: TextImageContent = ""
108
+ display: bool = False
109
+ details: JsonValue | None = None
110
+
111
+ role: ClassVar[Literal["custom"]] = "custom"
112
+
113
+
114
+ @dataclass(slots=True, kw_only=True)
115
+ class BranchSummaryMessage:
116
+ """分支摘要消息(``role="branchSummary"``):离开一条分支时对被放弃路径的概括。"""
117
+
118
+ summary: str
119
+ from_id: str | None
120
+ timestamp: int
121
+
122
+ role: ClassVar[Literal["branchSummary"]] = "branchSummary"
123
+
124
+
125
+ @dataclass(slots=True, kw_only=True)
126
+ class CompactionSummaryMessage:
127
+ """压缩摘要消息(``role="compactionSummary"``):代替被压缩区间进入模型上下文。"""
128
+
129
+ summary: str
130
+ tokens_before: int
131
+ timestamp: int
132
+
133
+ role: ClassVar[Literal["compactionSummary"]] = "compactionSummary"
134
+
135
+
136
+ #: 能写进 ``message`` 条目的消息:四种 LLM 角色加 custom。
137
+ type StorableMessage = Message | CustomMessage
138
+
139
+ #: 投影(:func:`session_entry_to_context_messages`)能产出的消息。
140
+ type ProjectedMessage = Message | CustomMessage | BranchSummaryMessage | CompactionSummaryMessage
141
+
142
+
143
+ def agent_message_to_wire(message: StorableMessage) -> dict[str, JsonValue]:
144
+ """转录消息 → wire。四种 LLM 角色交给 :mod:`braid_ai.wire`,custom 在这里处理。"""
145
+ if isinstance(message, CustomMessage):
146
+ wire: dict[str, JsonValue] = {
147
+ "role": "custom",
148
+ "customType": message.custom_type,
149
+ "content": content_to_wire(message.content),
150
+ "display": message.display,
151
+ "timestamp": message.timestamp,
152
+ }
153
+ if message.details is not None:
154
+ wire["details"] = message.details
155
+ return wire
156
+ return _llm_message_to_wire(message)
157
+
158
+
159
+ def agent_message_from_wire(data: Mapping[str, JsonValue]) -> StorableMessage:
160
+ """wire → 转录消息。未知 role 抛 :class:`SessionFormatError`,静默跳过等于改上下文。"""
161
+ if not isinstance(data, dict):
162
+ raise SessionFormatError(f"message 必须是 JSON 对象,实际是 {type(data).__name__}")
163
+ role = data.get("role")
164
+ if role == "custom":
165
+ raw_type = data.get("customType")
166
+ raw_ts = data.get("timestamp")
167
+ if raw_ts is None or isinstance(raw_ts, bool) or not isinstance(raw_ts, int):
168
+ raise SessionFormatError(f"custom 消息缺少毫秒整数 timestamp: {raw_ts!r}")
169
+ content = user_content_from_wire(data.get("content", ""), "custom.content")
170
+ details = data.get("details")
171
+ return CustomMessage(
172
+ custom_type=raw_type if isinstance(raw_type, str) else "",
173
+ timestamp=raw_ts,
174
+ content=content,
175
+ display=data.get("display") is True,
176
+ details=details,
177
+ )
178
+ if role in ("branchSummary", "compactionSummary"):
179
+ raise SessionFormatError(
180
+ f"role={role!r} 是投影产生的消息,只能由对应条目生成,不能存进 message 条目"
181
+ )
182
+ try:
183
+ return _llm_message_from_wire(data)
184
+ except WireError as exc:
185
+ raise SessionFormatError(f"message 条目无法读取: {exc}") from exc
186
+
187
+
188
+ # ---------------------------------------------------------------------- 条目
189
+
190
+
191
+ @dataclass(slots=True, kw_only=True)
192
+ class SessionHeader:
193
+ """文件第一行:元数据,不在树上(没有 id/parentId)。"""
194
+
195
+ id: str
196
+ timestamp: str
197
+ cwd: str
198
+ #: v1 文件没有 version;其余固定为 :data:`CURRENT_SESSION_VERSION`。
199
+ version: int | None = CURRENT_SESSION_VERSION
200
+ parent_session: str | None = None
201
+ extra: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
202
+
203
+ type: ClassVar[Literal["session"]] = "session"
204
+
205
+
206
+ @dataclass(slots=True, kw_only=True)
207
+ class SessionEntryBase:
208
+ """除头之外所有条目的公共骨架。"""
209
+
210
+ id: str
211
+ parent_id: str | None
212
+ timestamp: str
213
+ #: 未来版本写入的未知字段,写回时原样合并(显式字段优先)。
214
+ extra: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
215
+
216
+
217
+ @dataclass(slots=True, kw_only=True)
218
+ class SessionMessageEntry(SessionEntryBase):
219
+ """对话消息。``message`` 是 :data:`StorableMessage`。"""
220
+
221
+ message: StorableMessage
222
+
223
+ type: ClassVar[Literal["message"]] = "message"
224
+
225
+
226
+ @dataclass(slots=True, kw_only=True)
227
+ class ThinkingLevelChangeEntry(SessionEntryBase):
228
+ """思考强度切换。"""
229
+
230
+ thinking_level: str
231
+
232
+ type: ClassVar[Literal["thinking_level_change"]] = "thinking_level_change"
233
+
234
+
235
+ @dataclass(slots=True, kw_only=True)
236
+ class ModelChangeEntry(SessionEntryBase):
237
+ """模型切换。最新一条决定当前模型;助手消息会再覆盖它(见 projection)。"""
238
+
239
+ provider: str
240
+ model_id: str
241
+
242
+ type: ClassVar[Literal["model_change"]] = "model_change"
243
+
244
+
245
+ @dataclass(slots=True, kw_only=True)
246
+ class UsageEntry(SessionEntryBase):
247
+ """不进上下文的模型用量(如缓存预热),计入会话总量。"""
248
+
249
+ kind: str
250
+ provider: str
251
+ model: str
252
+ usage: Usage
253
+ note: str | None = None
254
+
255
+ type: ClassVar[Literal["usage"]] = "usage"
256
+
257
+
258
+ @dataclass(slots=True, kw_only=True)
259
+ class CompactionEntry(SessionEntryBase):
260
+ """压缩条目:摘要 + 保留边界 + 当时的完整系统消息检查点。
261
+
262
+ ``first_kept_entry_id`` 指向压缩后仍保留的第一条;保留none的压缩存自己的 id。
263
+ """
264
+
265
+ summary: str
266
+ first_kept_entry_id: str
267
+ tokens_before: int
268
+ details: JsonValue | None = None
269
+ usage: Usage | None = None
270
+ from_hook: bool | None = None
271
+ system_message: SystemMessage | None = None
272
+
273
+ type: ClassVar[Literal["compaction"]] = "compaction"
274
+
275
+
276
+ @dataclass(slots=True, kw_only=True)
277
+ class BranchSummaryEntry(SessionEntryBase):
278
+ """分支摘要条目。``parent_id`` 是新分支的起点,``from_id`` 是被放弃路径的叶子。"""
279
+
280
+ from_id: str
281
+ summary: str
282
+ details: JsonValue | None = None
283
+ usage: Usage | None = None
284
+ from_hook: bool | None = None
285
+
286
+ type: ClassVar[Literal["branch_summary"]] = "branch_summary"
287
+
288
+
289
+ @dataclass(slots=True, kw_only=True)
290
+ class CustomEntry(SessionEntryBase):
291
+ """扩展状态条目。不进模型上下文。"""
292
+
293
+ custom_type: str
294
+ data: JsonValue | None = None
295
+
296
+ type: ClassVar[Literal["custom"]] = "custom"
297
+
298
+
299
+ @dataclass(slots=True, kw_only=True)
300
+ class CustomMessageEntry(SessionEntryBase):
301
+ """扩展注入消息条目。参与模型上下文(投影成 :class:`CustomMessage`)。"""
302
+
303
+ custom_type: str
304
+ content: TextImageContent = ""
305
+ display: bool = False
306
+ details: JsonValue | None = None
307
+
308
+ type: ClassVar[Literal["custom_message"]] = "custom_message"
309
+
310
+
311
+ @dataclass(slots=True, kw_only=True)
312
+ class ContextReplacement:
313
+ """context_edit 的替换内容。``content`` 只换内容,角色与元数据保留。"""
314
+
315
+ content: TextImageContent
316
+
317
+
318
+ @dataclass(slots=True, kw_only=True)
319
+ class ContextEditEntry(SessionEntryBase):
320
+ """对早前条目的追加式编辑:只改此后模型上下文里的样子,不动原始条目。
321
+
322
+ ``replacement`` 为 ``None`` 表示从上下文里省略目标。
323
+ """
324
+
325
+ target_id: str
326
+ replacement: ContextReplacement | None
327
+
328
+ type: ClassVar[Literal["context_edit"]] = "context_edit"
329
+
330
+
331
+ @dataclass(slots=True, kw_only=True)
332
+ class LabelEntry(SessionEntryBase):
333
+ """用户书签。``label`` 为 ``None`` 表示清除(wire 里省略该键)。"""
334
+
335
+ target_id: str
336
+ label: str | None = None
337
+
338
+ type: ClassVar[Literal["label"]] = "label"
339
+
340
+
341
+ @dataclass(slots=True, kw_only=True)
342
+ class SessionInfoEntry(SessionEntryBase):
343
+ """会话元数据(如显示名)。"""
344
+
345
+ name: str | None = None
346
+
347
+ type: ClassVar[Literal["session_info"]] = "session_info"
348
+
349
+
350
+ @dataclass(slots=True, kw_only=True)
351
+ class UnknownEntry(SessionEntryBase):
352
+ """未知类型的条目。
353
+
354
+ 未来版本写出的新条目在旧代码里仍是合法树节点,只是不贡献上下文;显式建模才能
355
+ 保住树结构。``raw`` 保留原始 wire,写回时原样输出。``type`` 是实例字段——
356
+ 每个 UnknownEntry 的判别值不同。
357
+ """
358
+
359
+ type: str
360
+ raw: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
361
+
362
+
363
+ #: 树上的条目联合。
364
+ type SessionEntry = (
365
+ SessionMessageEntry
366
+ | ThinkingLevelChangeEntry
367
+ | ModelChangeEntry
368
+ | UsageEntry
369
+ | CompactionEntry
370
+ | BranchSummaryEntry
371
+ | CustomEntry
372
+ | CustomMessageEntry
373
+ | ContextEditEntry
374
+ | LabelEntry
375
+ | SessionInfoEntry
376
+ | UnknownEntry
377
+ )
378
+
379
+ #: 文件条目 = 头 + 树条目。
380
+ type FileEntry = SessionHeader | SessionEntry
381
+
382
+
383
+ #: 各条目类型的已知 wire 键。不在表里的键进 ``extra``,写回时合并。
384
+ _ENTRY_BASE_KEYS: Final[frozenset[str]] = frozenset({"type", "id", "parentId", "timestamp"})
385
+ _HEADER_KEYS: Final[frozenset[str]] = frozenset(
386
+ {"type", "version", "id", "timestamp", "cwd", "parentSession"}
387
+ )
388
+ _KNOWN_ENTRY_KEYS: Final[dict[str, frozenset[str]]] = {
389
+ "message": _ENTRY_BASE_KEYS | {"message"},
390
+ "thinking_level_change": _ENTRY_BASE_KEYS | {"thinkingLevel"},
391
+ "model_change": _ENTRY_BASE_KEYS | {"provider", "modelId"},
392
+ "usage": _ENTRY_BASE_KEYS | {"kind", "provider", "model", "usage", "note"},
393
+ "compaction": _ENTRY_BASE_KEYS
394
+ | {
395
+ "summary",
396
+ "firstKeptEntryId",
397
+ "tokensBefore",
398
+ "details",
399
+ "usage",
400
+ "fromHook",
401
+ "systemMessage",
402
+ },
403
+ "branch_summary": _ENTRY_BASE_KEYS | {"fromId", "summary", "details", "usage", "fromHook"},
404
+ "custom": _ENTRY_BASE_KEYS | {"customType", "data"},
405
+ "custom_message": _ENTRY_BASE_KEYS | {"customType", "content", "display", "details"},
406
+ "context_edit": _ENTRY_BASE_KEYS | {"targetId", "replacement"},
407
+ "label": _ENTRY_BASE_KEYS | {"targetId", "label"},
408
+ "session_info": _ENTRY_BASE_KEYS | {"name"},
409
+ }
410
+
411
+
412
+ # ------------------------------------------------------------------ wire 映射
413
+
414
+
415
+ def entry_to_wire(entry: FileEntry) -> dict[str, JsonValue]:
416
+ """条目 → wire JSON。``None`` 字段省略(``replacement`` 除外:null 是显式语义)。"""
417
+ if isinstance(entry, SessionHeader):
418
+ wire: dict[str, JsonValue] = {
419
+ "type": "session",
420
+ "id": entry.id,
421
+ "timestamp": entry.timestamp,
422
+ "cwd": entry.cwd,
423
+ }
424
+ if entry.version is not None:
425
+ wire["version"] = entry.version
426
+ if entry.parent_session is not None:
427
+ wire["parentSession"] = entry.parent_session
428
+ _merge_extra(wire, entry.extra)
429
+ return wire
430
+ if isinstance(entry, UnknownEntry):
431
+ return dict(entry.raw)
432
+
433
+ data: dict[str, JsonValue] = {
434
+ "type": entry.type,
435
+ "id": entry.id,
436
+ "parentId": entry.parent_id,
437
+ "timestamp": entry.timestamp,
438
+ }
439
+ match entry:
440
+ case SessionMessageEntry():
441
+ data["message"] = agent_message_to_wire(entry.message)
442
+ case ThinkingLevelChangeEntry():
443
+ data["thinkingLevel"] = entry.thinking_level
444
+ case ModelChangeEntry():
445
+ data["provider"] = entry.provider
446
+ data["modelId"] = entry.model_id
447
+ case UsageEntry():
448
+ data["kind"] = entry.kind
449
+ data["provider"] = entry.provider
450
+ data["model"] = entry.model
451
+ data["usage"] = usage_to_wire(entry.usage)
452
+ if entry.note is not None:
453
+ data["note"] = entry.note
454
+ case CompactionEntry():
455
+ data["summary"] = entry.summary
456
+ data["firstKeptEntryId"] = entry.first_kept_entry_id
457
+ data["tokensBefore"] = entry.tokens_before
458
+ if entry.details is not None:
459
+ data["details"] = entry.details
460
+ if entry.usage is not None:
461
+ data["usage"] = usage_to_wire(entry.usage)
462
+ if entry.from_hook is not None:
463
+ data["fromHook"] = entry.from_hook
464
+ if entry.system_message is not None:
465
+ data["systemMessage"] = _llm_message_to_wire(entry.system_message)
466
+ case BranchSummaryEntry():
467
+ data["fromId"] = entry.from_id
468
+ data["summary"] = entry.summary
469
+ if entry.details is not None:
470
+ data["details"] = entry.details
471
+ if entry.usage is not None:
472
+ data["usage"] = usage_to_wire(entry.usage)
473
+ if entry.from_hook is not None:
474
+ data["fromHook"] = entry.from_hook
475
+ case CustomEntry():
476
+ data["customType"] = entry.custom_type
477
+ if entry.data is not None:
478
+ data["data"] = entry.data
479
+ case CustomMessageEntry():
480
+ data["customType"] = entry.custom_type
481
+ data["content"] = content_to_wire(entry.content)
482
+ data["display"] = entry.display
483
+ if entry.details is not None:
484
+ data["details"] = entry.details
485
+ case ContextEditEntry():
486
+ data["targetId"] = entry.target_id
487
+ # 显式写 null 表示"省略目标",与键缺失不同。
488
+ data["replacement"] = (
489
+ None
490
+ if entry.replacement is None
491
+ else {"content": content_to_wire(entry.replacement.content)}
492
+ )
493
+ case LabelEntry():
494
+ data["targetId"] = entry.target_id
495
+ if entry.label is not None:
496
+ data["label"] = entry.label
497
+ case SessionInfoEntry():
498
+ if entry.name is not None:
499
+ data["name"] = entry.name
500
+ _merge_extra(data, entry.extra)
501
+ return data
502
+
503
+
504
+ def entry_from_wire(data: Mapping[str, JsonValue]) -> FileEntry:
505
+ """wire JSON → 条目。读严格:缺 id/时间戳、非法字段都抛 :class:`SessionFormatError`。"""
506
+ if not isinstance(data, dict):
507
+ raise SessionFormatError(f"条目必须是 JSON 对象,实际是 {type(data).__name__}")
508
+ entry_type = data.get("type")
509
+ if not isinstance(entry_type, str):
510
+ raise SessionFormatError(f"条目缺少 type 字段: {data!r}")
511
+
512
+ if entry_type == "session":
513
+ return _header_from_wire(data)
514
+
515
+ if entry_type not in _KNOWN_ENTRY_KEYS:
516
+ # 未知条目类型:保留为树节点,不贡献上下文。
517
+ return UnknownEntry(
518
+ id=_req_str(data, "id", entry_type),
519
+ parent_id=_opt_parent(data, entry_type),
520
+ timestamp=_req_str(data, "timestamp", entry_type),
521
+ type=entry_type,
522
+ raw=dict(data),
523
+ )
524
+
525
+ entry_id = _req_str(data, "id", entry_type)
526
+ parent_id = _opt_parent(data, entry_type)
527
+ timestamp = _req_str(data, "timestamp", entry_type)
528
+ extra = {key: value for key, value in data.items() if key not in _KNOWN_ENTRY_KEYS[entry_type]}
529
+
530
+ match entry_type:
531
+ case "message":
532
+ raw_message = data.get("message")
533
+ if not isinstance(raw_message, dict):
534
+ raise SessionFormatError("message 条目缺少 message 对象")
535
+ return SessionMessageEntry(
536
+ id=entry_id,
537
+ parent_id=parent_id,
538
+ timestamp=timestamp,
539
+ extra=extra,
540
+ message=agent_message_from_wire(raw_message),
541
+ )
542
+ case "thinking_level_change":
543
+ return ThinkingLevelChangeEntry(
544
+ id=entry_id,
545
+ parent_id=parent_id,
546
+ timestamp=timestamp,
547
+ extra=extra,
548
+ thinking_level=_req_str(data, "thinkingLevel", entry_type),
549
+ )
550
+ case "model_change":
551
+ return ModelChangeEntry(
552
+ id=entry_id,
553
+ parent_id=parent_id,
554
+ timestamp=timestamp,
555
+ extra=extra,
556
+ provider=_req_str(data, "provider", entry_type),
557
+ model_id=_req_str(data, "modelId", entry_type),
558
+ )
559
+ case "usage":
560
+ raw_note = data.get("note")
561
+ return UsageEntry(
562
+ id=entry_id,
563
+ parent_id=parent_id,
564
+ timestamp=timestamp,
565
+ extra=extra,
566
+ kind=_req_str(data, "kind", entry_type),
567
+ provider=_req_str(data, "provider", entry_type),
568
+ model=_req_str(data, "model", entry_type),
569
+ usage=usage_from_wire(data["usage"]) if data.get("usage") is not None else Usage(),
570
+ note=raw_note if isinstance(raw_note, str) else None,
571
+ )
572
+ case "compaction":
573
+ raw_system = data.get("systemMessage")
574
+ system_message: SystemMessage | None = None
575
+ if isinstance(raw_system, dict):
576
+ parsed_system = _llm_message_from_wire(raw_system)
577
+ if not isinstance(parsed_system, SystemMessage):
578
+ raise SessionFormatError("compaction.systemMessage 必须是 system 角色消息")
579
+ system_message = parsed_system
580
+ raw_hook = data.get("fromHook")
581
+ return CompactionEntry(
582
+ id=entry_id,
583
+ parent_id=parent_id,
584
+ timestamp=timestamp,
585
+ extra=extra,
586
+ summary=_req_str(data, "summary", entry_type),
587
+ first_kept_entry_id=_req_str(data, "firstKeptEntryId", entry_type),
588
+ tokens_before=_req_int(data, "tokensBefore", entry_type),
589
+ details=data.get("details"),
590
+ usage=usage_from_wire(data["usage"]) if data.get("usage") is not None else None,
591
+ from_hook=raw_hook if isinstance(raw_hook, bool) else None,
592
+ system_message=system_message,
593
+ )
594
+ case "branch_summary":
595
+ raw_from = data.get("fromId")
596
+ raw_hook = data.get("fromHook")
597
+ return BranchSummaryEntry(
598
+ id=entry_id,
599
+ parent_id=parent_id,
600
+ timestamp=timestamp,
601
+ extra=extra,
602
+ from_id=raw_from if isinstance(raw_from, str) else "",
603
+ summary=_req_str(data, "summary", entry_type),
604
+ details=data.get("details"),
605
+ usage=usage_from_wire(data["usage"]) if data.get("usage") is not None else None,
606
+ from_hook=raw_hook if isinstance(raw_hook, bool) else None,
607
+ )
608
+ case "custom":
609
+ return CustomEntry(
610
+ id=entry_id,
611
+ parent_id=parent_id,
612
+ timestamp=timestamp,
613
+ extra=extra,
614
+ custom_type=_req_str(data, "customType", entry_type),
615
+ data=data.get("data"),
616
+ )
617
+ case "custom_message":
618
+ return CustomMessageEntry(
619
+ id=entry_id,
620
+ parent_id=parent_id,
621
+ timestamp=timestamp,
622
+ extra=extra,
623
+ custom_type=_req_str(data, "customType", entry_type),
624
+ content=user_content_from_wire(data.get("content", ""), "custom_message.content"),
625
+ display=data.get("display") is True,
626
+ details=data.get("details"),
627
+ )
628
+ case "context_edit":
629
+ raw_replacement = data.get("replacement")
630
+ replacement: ContextReplacement | None
631
+ if raw_replacement is None:
632
+ replacement = None
633
+ elif isinstance(raw_replacement, dict):
634
+ replacement = ContextReplacement(
635
+ content=user_content_from_wire(
636
+ raw_replacement.get("content"), "context_edit.replacement.content"
637
+ )
638
+ )
639
+ else:
640
+ raise SessionFormatError("context_edit.replacement 必须是 null 或 {content}")
641
+ return ContextEditEntry(
642
+ id=entry_id,
643
+ parent_id=parent_id,
644
+ timestamp=timestamp,
645
+ extra=extra,
646
+ target_id=_req_str(data, "targetId", entry_type),
647
+ replacement=replacement,
648
+ )
649
+ case "label":
650
+ raw_label = data.get("label")
651
+ return LabelEntry(
652
+ id=entry_id,
653
+ parent_id=parent_id,
654
+ timestamp=timestamp,
655
+ extra=extra,
656
+ target_id=_req_str(data, "targetId", entry_type),
657
+ label=raw_label if isinstance(raw_label, str) else None,
658
+ )
659
+ case "session_info":
660
+ raw_name = data.get("name")
661
+ return SessionInfoEntry(
662
+ id=entry_id,
663
+ parent_id=parent_id,
664
+ timestamp=timestamp,
665
+ extra=extra,
666
+ name=raw_name if isinstance(raw_name, str) else None,
667
+ )
668
+ case _:
669
+ raise SessionFormatError(f"不可到达的条目类型: {entry_type!r}")
670
+
671
+
672
+ def _header_from_wire(data: Mapping[str, JsonValue]) -> SessionHeader:
673
+ session_id = data.get("id")
674
+ if not isinstance(session_id, str) or not session_id:
675
+ raise SessionFormatError(f"session 头缺少 id: {data!r}")
676
+ timestamp = data.get("timestamp")
677
+ if not isinstance(timestamp, str):
678
+ raise SessionFormatError("session 头缺少 ISO timestamp")
679
+ cwd = data.get("cwd", "")
680
+ if not isinstance(cwd, str):
681
+ raise SessionFormatError("session 头的 cwd 必须是字符串")
682
+ raw_version = data.get("version")
683
+ version: int | None
684
+ if raw_version is None:
685
+ version = None
686
+ elif isinstance(raw_version, int) and not isinstance(raw_version, bool):
687
+ version = raw_version
688
+ else:
689
+ raise SessionFormatError(f"session 头 version 非法: {raw_version!r}")
690
+ parent = data.get("parentSession")
691
+ return SessionHeader(
692
+ id=session_id,
693
+ timestamp=timestamp,
694
+ cwd=cwd,
695
+ version=version,
696
+ parent_session=parent if isinstance(parent, str) else None,
697
+ extra={key: value for key, value in data.items() if key not in _HEADER_KEYS},
698
+ )
699
+
700
+
701
+ def _req_str(data: Mapping[str, JsonValue], key: str, entry_type: str) -> str:
702
+ value = data.get(key)
703
+ if not isinstance(value, str):
704
+ raise SessionFormatError(f"{entry_type}.{key} 必须是字符串,实际是 {value!r}")
705
+ return value
706
+
707
+
708
+ def _req_int(data: Mapping[str, JsonValue], key: str, entry_type: str) -> int:
709
+ value = data.get(key)
710
+ if isinstance(value, bool) or not isinstance(value, int):
711
+ raise SessionFormatError(f"{entry_type}.{key} 必须是整数,实际是 {value!r}")
712
+ return value
713
+
714
+
715
+ def _opt_parent(data: Mapping[str, JsonValue], entry_type: str) -> str | None:
716
+ value = data.get("parentId")
717
+ if value is None:
718
+ return None
719
+ if not isinstance(value, str):
720
+ raise SessionFormatError(f"{entry_type}.parentId 必须是字符串或 null,实际是 {value!r}")
721
+ return value
722
+
723
+
724
+ def _merge_extra(wire: dict[str, JsonValue], extra: Mapping[str, JsonValue]) -> None:
725
+ """合并未知字段。显式字段优先——即使 extra 里被塞了同名键也不覆盖。"""
726
+ for key, value in extra.items():
727
+ if key not in wire:
728
+ wire[key] = value
729
+
730
+
731
+ # -------------------------------------------------------------------- 投影
732
+
733
+
734
+ def session_entry_to_context_messages(entry: SessionEntry) -> list[ProjectedMessage]:
735
+ """单个条目 → 投影消息。
736
+
737
+ 未知条目与状态条目(custom/label/usage/context_edit/session_info)不贡献消息。
738
+ wire 映射读入时已给缺省形状,这里不再处理 null。
739
+ """
740
+ match entry:
741
+ case SessionMessageEntry():
742
+ return [entry.message]
743
+ case CustomMessageEntry():
744
+ return [
745
+ CustomMessage(
746
+ custom_type=entry.custom_type,
747
+ timestamp=ms_from_iso(entry.timestamp),
748
+ content=entry.content,
749
+ display=entry.display,
750
+ details=entry.details,
751
+ )
752
+ ]
753
+ case BranchSummaryEntry():
754
+ if not entry.summary:
755
+ return []
756
+ return [
757
+ BranchSummaryMessage(
758
+ summary=entry.summary,
759
+ from_id=entry.from_id,
760
+ timestamp=ms_from_iso(entry.timestamp),
761
+ )
762
+ ]
763
+ case CompactionEntry():
764
+ summary = CompactionSummaryMessage(
765
+ summary=entry.summary,
766
+ tokens_before=entry.tokens_before,
767
+ timestamp=ms_from_iso(entry.timestamp),
768
+ )
769
+ if entry.system_message is not None:
770
+ return [entry.system_message, summary]
771
+ return [summary]
772
+ case _:
773
+ return []
774
+
775
+
776
+ __all__ = [
777
+ "CURRENT_SESSION_VERSION",
778
+ "BranchSummaryEntry",
779
+ "BranchSummaryMessage",
780
+ "CompactionEntry",
781
+ "CompactionSummaryMessage",
782
+ "ContextEditEntry",
783
+ "ContextReplacement",
784
+ "CustomEntry",
785
+ "CustomMessage",
786
+ "CustomMessageEntry",
787
+ "FileEntry",
788
+ "LabelEntry",
789
+ "ModelChangeEntry",
790
+ "ProjectedMessage",
791
+ "SessionEntry",
792
+ "SessionEntryBase",
793
+ "SessionFormatError",
794
+ "SessionHeader",
795
+ "SessionInfoEntry",
796
+ "SessionMessageEntry",
797
+ "StorableMessage",
798
+ "TextImageContent",
799
+ "ThinkingLevelChangeEntry",
800
+ "UnknownEntry",
801
+ "UsageEntry",
802
+ "agent_message_from_wire",
803
+ "agent_message_to_wire",
804
+ "entry_from_wire",
805
+ "entry_to_wire",
806
+ "iso_from_ms",
807
+ "ms_from_iso",
808
+ "session_entry_to_context_messages",
809
+ ]